fix(mcp): add direct Redis command execution

This commit is contained in:
t8y2
2026-06-26 22:27:31 +08:00
parent 76e2d33cd3
commit 23b44cc2b9
15 changed files with 774 additions and 26 deletions
+4 -1
View File
@@ -1,7 +1,8 @@
import { addConnection as desktopAddConnection, findConnection as desktopFindConnection, loadConnections as desktopLoadConnections, removeConnection as desktopRemoveConnection } from "./connections.js";
import { closeDatabaseResources as desktopCloseDatabaseResources, describeTable as desktopDescribeTable, executeQuery as desktopExecuteQuery, listTables as desktopListTables } from "./database.js";
import { closeDatabaseResources as desktopCloseDatabaseResources, describeTable as desktopDescribeTable, executeQuery as desktopExecuteQuery, executeRedisCommand as desktopExecuteRedisCommand, listTables as desktopListTables } from "./database.js";
import type { ConnectionConfig } from "./connections.js";
import type { ColumnInfo, QueryOptions, QueryResult, TableInfo } from "./database.js";
import type { RedisCommandOptions, RedisCommandResult } from "./redis-command.js";
export interface Backend {
loadConnections(): Promise<ConnectionConfig[]>;
@@ -11,6 +12,7 @@ export interface Backend {
listTables(config: ConnectionConfig, schema?: string): Promise<TableInfo[]>;
describeTable(config: ConnectionConfig, table: string, schema?: string): Promise<ColumnInfo[]>;
executeQuery(config: ConnectionConfig, sql: string, options?: QueryOptions): Promise<QueryResult>;
executeRedisCommand?(config: ConnectionConfig, db: number, command: string, options?: RedisCommandOptions): Promise<RedisCommandResult>;
close?(): Promise<void>;
}
@@ -27,6 +29,7 @@ export async function createBackend(env: NodeJS.ProcessEnv = process.env): Promi
listTables: desktopListTables,
describeTable: desktopDescribeTable,
executeQuery: desktopExecuteQuery,
executeRedisCommand: desktopExecuteRedisCommand,
close: desktopCloseDatabaseResources,
};
}
+4 -1
View File
@@ -19,13 +19,16 @@ export interface ConnectionConfig {
keepalive_interval_secs?: number;
ssl: boolean;
ca_cert_path?: string;
client_cert_path?: string;
client_key_path?: string;
oracle_connection_type?: "service_name" | "sid";
redis_connection_mode?: "standalone" | "sentinel";
redis_connection_mode?: "standalone" | "sentinel" | "cluster";
redis_sentinel_master?: string;
redis_sentinel_nodes?: string;
redis_sentinel_username?: string;
redis_sentinel_password?: string;
redis_sentinel_tls?: boolean;
redis_cluster_nodes?: string;
redis_key_separator?: string;
read_only?: boolean;
}
+100
View File
@@ -7,6 +7,7 @@ import Database from "better-sqlite3";
import { sqlSafetyFromEnv } from "./sql-safety.js";
import { isDirectQueryType } from "./diagnostics.js";
import { bridgePortFilePath } from "./paths.js";
import { parseRedisCommandArgv, classifyRedisCommand, type RedisCommandOptions, type RedisCommandResult, type RedisCommandSafety } from "./redis-command.js";
export interface TableInfo {
name: string;
@@ -169,6 +170,11 @@ function firstProxyLayer(config: ConnectionConfig): ProxyLayer | undefined {
return config.transport_layers?.find((layer): layer is ProxyLayer => layer.type === "proxy" && layer.enabled !== false && !!layer.host);
}
function hasDirectRedisSupport(config: ConnectionConfig): boolean {
const mode = config.redis_connection_mode || "standalone";
return config.db_type === "redis" && mode === "standalone" && !hasActiveSshLayer(config);
}
async function connectionEndpoint(config: ConnectionConfig): Promise<{ host: string; port: number }> {
const proxy = firstProxyLayer(config);
if (!proxy) return { host: config.host, port: config.port };
@@ -293,6 +299,10 @@ function decodeUrlParamPart(value: string): string {
}
}
function urlParams(config: ConnectionConfig): URLSearchParams {
return new URLSearchParams((config.url_params || "").trim().replace(/^\?/, ""));
}
function connectViaProxy(config: ConnectionConfig, proxy: ProxyLayer): Promise<Socket> {
return new Promise((resolve, reject) => {
const socket = netConnect(proxy.port || 1080, proxy.host || "127.0.0.1");
@@ -659,6 +669,96 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
return convertBridgeQueryResult(result, options);
}
export async function executeRedisCommand(config: ConnectionConfig, db: number, command: string, options?: RedisCommandOptions): Promise<RedisCommandResult> {
if (config.db_type !== "redis") {
throw new Error("Connection is not Redis.");
}
if (hasDirectRedisSupport(config)) {
return executeRedisCommandDirect(config, db, command, options);
}
return withTimeout(
bridgeDataRequest<RedisCommandResult>("/data/redis/execute-command", {
connection_name: config.name,
db,
command,
skip_safety_check: options?.skipSafetyCheck ?? false,
}),
resolveTimeoutMs(options),
);
}
async function executeRedisCommandDirect(config: ConnectionConfig, db: number, commandText: string, options?: RedisCommandOptions): Promise<RedisCommandResult> {
const argv = parseRedisCommandArgv(commandText);
const command = argv[0].toUpperCase();
const safety = classifyRedisCommand(command) as RedisCommandSafety;
if (!options?.skipSafetyCheck && safety === "blocked") {
throw new Error(`Redis command is blocked for safety: ${command}`);
}
const { Redis } = await import("ioredis");
const endpoint = await connectionEndpoint(config);
const tls = await redisTlsOptions(config);
const client = new Redis({
host: endpoint.host,
port: endpoint.port,
username: config.username || undefined,
password: config.password || undefined,
db,
tls,
lazyConnect: true,
enableReadyCheck: false,
maxRetriesPerRequest: 0,
enableOfflineQueue: false,
connectTimeout: Math.min(resolveTimeoutMs(options), 10_000),
commandTimeout: resolveTimeoutMs(options),
});
try {
await client.connect();
const value = await client.call(command, ...argv.slice(1));
return { command, safety, value: redisValueToJson(value) };
} finally {
client.disconnect();
}
}
async function redisTlsOptions(config: ConnectionConfig): Promise<import("node:tls").ConnectionOptions | undefined> {
if (!config.ssl) return undefined;
const params = urlParams(config);
const tls: import("node:tls").ConnectionOptions = {
servername: config.host,
};
if ((params.get("insecure") || "").toLowerCase() === "true") {
tls.rejectUnauthorized = false;
}
if (config.ca_cert_path) tls.ca = await readFile(config.ca_cert_path);
if (config.client_cert_path) tls.cert = await readFile(config.client_cert_path);
if (config.client_key_path) tls.key = await readFile(config.client_key_path);
return tls;
}
function redisValueToJson(value: unknown): unknown {
if (Buffer.isBuffer(value)) return redisTextToJson(value.toString("utf8"));
if (Array.isArray(value)) return value.map(redisValueToJson);
if (value && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redisValueToJson(item)]));
}
if (typeof value === "string") return redisTextToJson(value);
return value;
}
function redisTextToJson(value: string): unknown {
const trimmed = value.trim();
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
return JSON.parse(trimmed);
} catch {
return value;
}
}
return value;
}
export async function listTables(config: ConnectionConfig, schema?: string): Promise<TableInfo[]> {
if (config.db_type === "mongodb") {
const collections = await bridgeDataRequest<CollectionListEntry[]>("/data/mongo/list-collections", {
+1
View File
@@ -6,5 +6,6 @@ export * from "./diagnostics.js";
export * from "./entrypoint.js";
export * from "./format.js";
export * from "./paths.js";
export * from "./redis-command.js";
export * from "./schema-context.js";
export * from "./sql-safety.js";
+172
View File
@@ -0,0 +1,172 @@
import type { SqlSafetyOptions } from "./sql-safety.js";
export type RedisCommandSafety = "allowed" | "confirm" | "blocked";
export interface RedisCommandResult {
command: string;
safety: RedisCommandSafety;
value: unknown;
}
export interface RedisCommandOptions {
skipSafetyCheck?: boolean;
timeoutMs?: number;
}
export interface RedisCommandSafetyDecision {
allowed: boolean;
command?: string;
safety?: RedisCommandSafety;
reason?: string;
skipSafetyCheck?: boolean;
}
const BLOCKED_REDIS_COMMANDS = new Set([
"KEYS",
"FLUSHALL",
"SHUTDOWN",
"CONFIG",
"SAVE",
"BGSAVE",
"SLAVEOF",
"REPLICAOF",
"MIGRATE",
"MODULE",
"SCRIPT",
"EVAL",
"EVALSHA",
]);
const CONFIRM_REDIS_COMMANDS = new Set([
"DEL",
"UNLINK",
"EXPIRE",
"EXPIREAT",
"PEXPIRE",
"PEXPIREAT",
"PERSIST",
"RENAME",
"RENAMENX",
"SET",
"SETEX",
"PSETEX",
"SETNX",
"MSET",
"MSETNX",
"HSET",
"HDEL",
"LPUSH",
"RPUSH",
"LPOP",
"RPOP",
"LSET",
"LREM",
"SADD",
"SREM",
"ZADD",
"ZREM",
"XADD",
"XDEL",
"FLUSHDB",
]);
export function firstRedisCommandToken(commandText: string): string | undefined {
try {
return parseRedisCommandArgv(commandText)[0]?.toUpperCase();
} catch {
const token = commandText.trim().match(/^\S+/)?.[0]?.toUpperCase();
return token || undefined;
}
}
export function classifyRedisCommand(commandText: string): RedisCommandSafety {
const command = firstRedisCommandToken(commandText);
if (!command) return "blocked";
if (BLOCKED_REDIS_COMMANDS.has(command)) return "blocked";
if (CONFIRM_REDIS_COMMANDS.has(command)) return "confirm";
return "allowed";
}
export function evaluateRedisCommandSafety(commandText: string, options: SqlSafetyOptions = {}): RedisCommandSafetyDecision {
const command = firstRedisCommandToken(commandText);
if (!command) {
return { allowed: false, reason: "Redis command is empty." };
}
const safety = classifyRedisCommand(command);
if (safety === "blocked" && !options.allowDangerous) {
return {
allowed: false,
command,
safety,
reason: `Dangerous Redis command "${command}" is blocked. Set DBX_MCP_ALLOW_DANGEROUS_SQL=1 to allow it.`,
};
}
if (safety !== "allowed" && !options.allowWrites) {
return {
allowed: false,
command,
safety,
reason: "MCP Redis command execution is read-only for this session. Set DBX_MCP_ALLOW_WRITES=1 to allow write or dangerous commands.",
};
}
return {
allowed: true,
command,
safety,
skipSafetyCheck: safety === "blocked" && options.allowDangerous === true,
};
}
export function parseRedisCommandArgv(commandText: string): string[] {
const trimmed = commandText.trimEnd().replace(/;+$/, "");
const argv: string[] = [];
let current = "";
let quote: "\"" | "'" | undefined;
let escaping = false;
for (const ch of trimmed) {
if (escaping) {
if (ch === "n") current += "\n";
else if (ch === "r") current += "\r";
else if (ch === "t") current += "\t";
else current += ch;
escaping = false;
continue;
}
if (ch === "\\") {
escaping = true;
continue;
}
if (quote) {
if (ch === quote) quote = undefined;
else current += ch;
continue;
}
if (ch === "\"" || ch === "'") {
quote = ch;
continue;
}
if (/\s/.test(ch)) {
if (current) {
argv.push(current);
current = "";
}
continue;
}
current += ch;
}
if (escaping) current += "\\";
if (quote) throw new Error("Redis command has an unterminated quote");
if (current) argv.push(current);
if (argv.length === 0) throw new Error("Redis command is empty");
return argv;
}
+18
View File
@@ -1,6 +1,7 @@
import type { ConnectionConfig } from "./connections.js";
import type { TableInfo, ColumnInfo, QueryOptions, QueryResult } from "./database.js";
import { collectionListToTableInfos, evaluateMongoAggregateSafety, evaluateMongoWriteSafety, inferMongoColumns, mongoDocumentsToQueryResult, parseMongoAggregateCommand, parseMongoCountDocumentsCommand, parseMongoFindCommand, parseMongoGetIndexesCommand, parseMongoWriteCommand, type CollectionInfo, type MongoWriteCommand } from "./database.js";
import type { RedisCommandOptions, RedisCommandResult } from "./redis-command.js";
import { sqlSafetyFromEnv } from "./sql-safety.js";
const baseUrl = process.env.DBX_WEB_URL!.replace(/\/+$/, "");
@@ -222,6 +223,23 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
return { columns: data.columns, rows: limitedRows, row_count: limitedRows.length };
}
export async function executeRedisCommand(config: ConnectionConfig, db: number, command: string, options?: RedisCommandOptions): Promise<RedisCommandResult> {
if (config.db_type !== "redis") {
throw new Error("Connection is not Redis.");
}
await ensureConnected(config);
const res = await apiFetch("/api/redis/execute-command", {
method: "POST",
body: JSON.stringify({
connectionId: config.id,
db,
command,
skipSafetyCheck: options?.skipSafetyCheck ?? false,
}),
});
return (await res.json()) as RedisCommandResult;
}
async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCommand): Promise<number> {
if (command.kind === "insert") {
const res = await apiFetch("/api/mongo/insert-documents", {