fix(mcp): disambiguate same-name connections
This commit is contained in:
1 parent
3b1a9cb98b
commit
0674433eea
7 files changed
+483
-90
No files matched your search
@@ -40,6 +40,14 @@ function withDatabase(config: ConnectionConfig, database?: string): ConnectionCo
|
|||||||
return database === undefined ? config : { ...config, database };
|
return database === undefined ? config : { ...config, database };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function connectionIdentity(config: ConnectionConfig): string {
|
||||||
|
return `${config.name} (${config.id}) [${config.db_type} @ ${config.host}:${config.port}]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function labeledText(config: ConnectionConfig, body: string): ReturnType<typeof text> {
|
||||||
|
return text(`[${connectionIdentity(config)}]\n${body}`);
|
||||||
|
}
|
||||||
|
|
||||||
function formatQueryToolResult(result: QueryResult, title?: string) {
|
function formatQueryToolResult(result: QueryResult, title?: string) {
|
||||||
const prefix = title ? `${title}\n` : "";
|
const prefix = title ? `${title}\n` : "";
|
||||||
if (result.columns.length === 0) return text(`${prefix}Query executed. ${result.row_count} row(s) affected.`);
|
if (result.columns.length === 0) return text(`${prefix}Query executed. ${result.row_count} row(s) affected.`);
|
||||||
@@ -104,11 +112,39 @@ async function loadScopedConnections(backend: Backend, scope: McpScope): Promise
|
|||||||
return connections.filter((config) => connectionMatchesScope(config, scope));
|
return connections.filter((config) => connectionMatchesScope(config, scope));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolveConnection(backend: Backend, scope: McpScope, requestedName?: string): Promise<{ config?: ConnectionConfig; error?: ReturnType<typeof toolError> }> {
|
async function resolveConnection(
|
||||||
|
backend: Backend,
|
||||||
|
scope: McpScope,
|
||||||
|
requestedId?: string,
|
||||||
|
requestedName?: string,
|
||||||
|
): Promise<{ config?: ConnectionConfig; error?: ReturnType<typeof toolError> }> {
|
||||||
|
// connection_id takes priority over connection_name when both are provided.
|
||||||
|
if (requestedId?.trim()) {
|
||||||
|
const connections = await backend.loadConnections();
|
||||||
|
const config = connections.find((c) => c.id === requestedId.trim());
|
||||||
|
if (!config) return { error: toolError("CONNECTION_NOT_FOUND", `Connection with id "${requestedId}" not found.`) };
|
||||||
|
// In scoped mode, verify the resolved connection is within the scope.
|
||||||
|
if (scopeEnabled(scope) && !connectionMatchesScope(config, scope)) {
|
||||||
|
return { error: toolError("CONNECTION_OUT_OF_SCOPE", `Connection "${requestedId}" is outside this DBX AI session scope.`) };
|
||||||
|
}
|
||||||
|
return { config };
|
||||||
|
}
|
||||||
|
|
||||||
if (!scopeEnabled(scope)) {
|
if (!scopeEnabled(scope)) {
|
||||||
if (!requestedName?.trim()) return { error: toolError("CONNECTION_NOT_FOUND", "Connection name is required.") };
|
if (!requestedName?.trim()) return { error: toolError("CONNECTION_NOT_FOUND", "Connection name is required.") };
|
||||||
const config = await backend.findConnection(requestedName);
|
const connections = await backend.loadConnections();
|
||||||
return config ? { config } : { error: toolError("CONNECTION_NOT_FOUND", `Connection "${requestedName}" not found.`) };
|
const matching = connections.filter((c) => c.name.toLowerCase() === requestedName.trim().toLowerCase());
|
||||||
|
if (matching.length === 0) return { error: toolError("CONNECTION_NOT_FOUND", `Connection "${requestedName}" not found.`) };
|
||||||
|
if (matching.length > 1) {
|
||||||
|
const lines = matching.map((c) => `- ${c.id}: ${c.db_type} @ ${c.host}:${c.port}`);
|
||||||
|
return {
|
||||||
|
error: toolError(
|
||||||
|
"AMBIGUOUS_CONNECTION",
|
||||||
|
`Multiple connections found with name "${requestedName}". Please specify connection_id:\n${lines.join("\n")}`,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { config: matching[0] };
|
||||||
}
|
}
|
||||||
|
|
||||||
const [scopedConfig] = await loadScopedConnections(backend, scope);
|
const [scopedConfig] = await loadScopedConnections(backend, scope);
|
||||||
@@ -131,25 +167,27 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
server.tool("dbx_list_connections", "List all database connections configured in DBX", {}, async () => {
|
server.tool("dbx_list_connections", "List all database connections configured in DBX", {}, async () => {
|
||||||
const connections = await loadScopedConnections(backend, scope);
|
const connections = await loadScopedConnections(backend, scope);
|
||||||
if (connections.length === 0) return text("No connections configured in DBX.");
|
if (connections.length === 0) return text("No connections configured in DBX.");
|
||||||
const rows = connections.map((c) => [c.name, c.db_type, c.host, String(c.port), c.database || ""]);
|
const rows = connections.map((c) => [c.id, c.name, c.db_type, c.host, String(c.port), c.database || ""]);
|
||||||
return text(mdTable(["Name", "Type", "Host", "Port", "Database"], rows));
|
return text(mdTable(["ID", "Name", "Type", "Host", "Port", "Database"], rows));
|
||||||
});
|
});
|
||||||
|
|
||||||
server.tool(
|
server.tool(
|
||||||
"dbx_list_tables",
|
"dbx_list_tables",
|
||||||
"List tables and views for a database connection",
|
"List tables and views for a database connection",
|
||||||
{
|
{
|
||||||
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
||||||
database: z.string().optional().describe("Database name"),
|
database: z.string().optional().describe("Database name"),
|
||||||
schema: z.string().optional().describe("Schema name (default: public for PostgreSQL)"),
|
schema: z.string().optional().describe("Schema name (default: public for PostgreSQL)"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, database, schema }) => {
|
async ({ connection_id, connection_name, database, schema }) => {
|
||||||
const { config, error } = await resolveConnection(backend, scope, connection_name);
|
const { config, error } = await resolveConnection(backend, scope, connection_id, connection_name);
|
||||||
if (error) return error;
|
if (error) return error;
|
||||||
const tables = await backend.listTables(withDatabase(config!, database ?? scope.database), schema);
|
const resolvedConfig = config!;
|
||||||
|
const tables = await backend.listTables(withDatabase(resolvedConfig, database ?? scope.database), schema);
|
||||||
if (tables.length === 0) return text("No tables found.");
|
if (tables.length === 0) return text("No tables found.");
|
||||||
const rows = tables.map((t) => [t.name, t.type]);
|
const rows = tables.map((t) => [t.name, t.type]);
|
||||||
return text(mdTable(["Table", "Type"], rows));
|
return labeledText(resolvedConfig, mdTable(["Table", "Type"], rows));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -157,18 +195,20 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"dbx_describe_table",
|
"dbx_describe_table",
|
||||||
"Get column definitions for a table",
|
"Get column definitions for a table",
|
||||||
{
|
{
|
||||||
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
||||||
table: z.string().describe("Table name"),
|
table: z.string().describe("Table name"),
|
||||||
database: z.string().optional().describe("Database name"),
|
database: z.string().optional().describe("Database name"),
|
||||||
schema: z.string().optional().describe("Schema name (default: public for PostgreSQL)"),
|
schema: z.string().optional().describe("Schema name (default: public for PostgreSQL)"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, table, database, schema }) => {
|
async ({ connection_id, connection_name, table, database, schema }) => {
|
||||||
const { config, error } = await resolveConnection(backend, scope, connection_name);
|
const { config, error } = await resolveConnection(backend, scope, connection_id, connection_name);
|
||||||
if (error) return error;
|
if (error) return error;
|
||||||
const columns = await backend.describeTable(withDatabase(config!, database ?? scope.database), table, schema);
|
const resolvedConfig = config!;
|
||||||
|
const columns = await backend.describeTable(withDatabase(resolvedConfig, database ?? scope.database), table, schema);
|
||||||
if (columns.length === 0) return text("No columns found.");
|
if (columns.length === 0) return text("No columns found.");
|
||||||
const rows = columns.map((c) => [c.is_primary_key ? `${c.name} (PK)` : c.name, c.data_type, c.is_nullable ? "YES" : "NO", c.column_default ?? "", c.comment ?? ""]);
|
const rows = columns.map((c) => [c.is_primary_key ? `${c.name} (PK)` : c.name, c.data_type, c.is_nullable ? "YES" : "NO", c.column_default ?? "", c.comment ?? ""]);
|
||||||
return text(mdTable(["Column", "Type", "Nullable", "Default", "Comment"], rows));
|
return labeledText(resolvedConfig, mdTable(["Column", "Type", "Nullable", "Default", "Comment"], rows));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -176,12 +216,13 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"dbx_execute_query",
|
"dbx_execute_query",
|
||||||
"Execute a SQL query on a database connection (max 100 rows returned)",
|
"Execute a SQL query on a database connection (max 100 rows returned)",
|
||||||
{
|
{
|
||||||
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
||||||
database: z.string().optional().describe("Database name"),
|
database: z.string().optional().describe("Database name"),
|
||||||
sql: z.string().describe("SQL query to execute"),
|
sql: z.string().describe("SQL query to execute"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, database, sql }) => {
|
async ({ connection_id, connection_name, database, sql }) => {
|
||||||
const { config, error } = await resolveConnection(backend, scope, connection_name);
|
const { config, error } = await resolveConnection(backend, scope, connection_id, connection_name);
|
||||||
if (error) return error;
|
if (error) return error;
|
||||||
const scopedConfig = config!;
|
const scopedConfig = config!;
|
||||||
if (scopedConfig.db_type === "redis") {
|
if (scopedConfig.db_type === "redis") {
|
||||||
@@ -199,8 +240,8 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
for (const statement of statements) {
|
for (const statement of statements) {
|
||||||
results.push(await backend.executeQuery(withDatabase(scopedConfig, database ?? scope.database), statement));
|
results.push(await backend.executeQuery(withDatabase(scopedConfig, database ?? scope.database), statement));
|
||||||
}
|
}
|
||||||
if (results.length === 1) return formatQueryToolResult(results[0]);
|
if (results.length === 1) return labeledText(scopedConfig, formatQueryToolResult(results[0]).content[0].text);
|
||||||
return text(results.map((result, index) => formatQueryToolResult(result, `Statement ${index + 1}`).content[0].text).join("\n\n"));
|
return labeledText(scopedConfig, results.map((result, index) => formatQueryToolResult(result, `Statement ${index + 1}`).content[0].text).join("\n\n"));
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const msg = e instanceof Error ? e.message : String(e);
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
return toolError("QUERY_ERROR", msg);
|
return toolError("QUERY_ERROR", msg);
|
||||||
@@ -212,12 +253,13 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"dbx_execute_redis_command",
|
"dbx_execute_redis_command",
|
||||||
"Execute a Redis command on a Redis connection",
|
"Execute a Redis command on a Redis connection",
|
||||||
{
|
{
|
||||||
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
connection_name: z.string().optional().describe("Name of the DBX Redis connection"),
|
connection_name: z.string().optional().describe("Name of the DBX Redis connection"),
|
||||||
db: z.number().int().min(0).optional().describe("Redis logical database number (default: scoped/default database or 0)"),
|
db: z.number().int().min(0).optional().describe("Redis logical database number (default: scoped/default database or 0)"),
|
||||||
command: z.string().describe("Redis command to execute, for example: GET mykey, INFO, or DBSIZE"),
|
command: z.string().describe("Redis command to execute, for example: GET mykey, INFO, or DBSIZE"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, db, command }) => {
|
async ({ connection_id, connection_name, db, command }) => {
|
||||||
const { config, error } = await resolveConnection(backend, scope, connection_name);
|
const { config, error } = await resolveConnection(backend, scope, connection_id, connection_name);
|
||||||
if (error) return error;
|
if (error) return error;
|
||||||
const scopedConfig = config!;
|
const scopedConfig = config!;
|
||||||
if (scopedConfig.db_type !== "redis") {
|
if (scopedConfig.db_type !== "redis") {
|
||||||
@@ -232,7 +274,7 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
const result = await backend.executeRedisCommand(scopedConfig, defaultRedisDb(scopedConfig, scope, db), command, {
|
const result = await backend.executeRedisCommand(scopedConfig, defaultRedisDb(scopedConfig, scope, db), command, {
|
||||||
skipSafetyCheck: safety.skipSafetyCheck,
|
skipSafetyCheck: safety.skipSafetyCheck,
|
||||||
});
|
});
|
||||||
return formatRedisCommandToolResult(result);
|
return labeledText(scopedConfig, formatRedisCommandToolResult(result).content[0].text);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const msg = e instanceof Error ? e.message : String(e);
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
return toolError("REDIS_COMMAND_ERROR", msg);
|
return toolError("REDIS_COMMAND_ERROR", msg);
|
||||||
@@ -244,22 +286,24 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"dbx_get_schema_context",
|
"dbx_get_schema_context",
|
||||||
"Get compact table and column context for writing SQL",
|
"Get compact table and column context for writing SQL",
|
||||||
{
|
{
|
||||||
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
||||||
database: z.string().optional().describe("Database name"),
|
database: z.string().optional().describe("Database name"),
|
||||||
schema: z.string().optional().describe("Schema name (default: public for PostgreSQL)"),
|
schema: z.string().optional().describe("Schema name (default: public for PostgreSQL)"),
|
||||||
tables: z.array(z.string()).optional().describe("Specific table names to include"),
|
tables: z.array(z.string()).optional().describe("Specific table names to include"),
|
||||||
max_tables: z.number().int().min(1).max(20).default(8).describe("Maximum number of tables to include"),
|
max_tables: z.number().int().min(1).max(20).default(8).describe("Maximum number of tables to include"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, database, schema, tables, max_tables }) => {
|
async ({ connection_id, connection_name, database, schema, tables, max_tables }) => {
|
||||||
const { config, error } = await resolveConnection(backend, scope, connection_name);
|
const { config, error } = await resolveConnection(backend, scope, connection_id, connection_name);
|
||||||
if (error) return error;
|
if (error) return error;
|
||||||
const context = await buildSchemaContext(backend, withDatabase(config!, database ?? scope.database), {
|
const resolvedConfig = config!;
|
||||||
|
const context = await buildSchemaContext(backend, withDatabase(resolvedConfig, database ?? scope.database), {
|
||||||
schema,
|
schema,
|
||||||
tables,
|
tables,
|
||||||
maxTables: max_tables,
|
maxTables: max_tables,
|
||||||
});
|
});
|
||||||
if (context.tables.length === 0) return text("No matching tables found.");
|
if (context.tables.length === 0) return text("No matching tables found.");
|
||||||
return text(formatSchemaContext(context));
|
return labeledText(resolvedConfig, formatSchemaContext(context));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -313,8 +357,32 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"Remove a database connection from DBX",
|
"Remove a database connection from DBX",
|
||||||
{
|
{
|
||||||
connection_name: z.string().describe("Name of the connection to remove"),
|
connection_name: z.string().describe("Name of the connection to remove"),
|
||||||
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to remove by id instead of name)"),
|
||||||
},
|
},
|
||||||
async ({ connection_name }) => {
|
async ({ connection_name, connection_id }) => {
|
||||||
|
if (connection_id?.trim()) {
|
||||||
|
if (backend.removeConnectionById) {
|
||||||
|
const removed = await backend.removeConnectionById(connection_id.trim());
|
||||||
|
if (!removed) return toolError("CONNECTION_NOT_FOUND", `Connection with id "${connection_id}" not found.`);
|
||||||
|
await notifyReload();
|
||||||
|
return text(`Connection with id "${connection_id}" removed.`);
|
||||||
|
}
|
||||||
|
// Fallback: resolve by id then remove by name
|
||||||
|
const connections = await backend.loadConnections();
|
||||||
|
const config = connections.find((c) => c.id === connection_id.trim());
|
||||||
|
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection with id "${connection_id}" not found.`);
|
||||||
|
const removed = await backend.removeConnection(config.name);
|
||||||
|
if (!removed) return toolError("CONNECTION_NOT_FOUND", `Connection "${config.name}" could not be removed.`);
|
||||||
|
await notifyReload();
|
||||||
|
return text(`Connection "${config.name}" (id: ${config.id}) removed.`);
|
||||||
|
}
|
||||||
|
const allConnections = await backend.loadConnections();
|
||||||
|
const matching = allConnections.filter((c) => c.name.toLowerCase() === connection_name.toLowerCase());
|
||||||
|
if (matching.length === 0) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
||||||
|
if (matching.length > 1) {
|
||||||
|
const lines = matching.map((c) => `- ${c.id}: ${c.db_type} @ ${c.host}:${c.port}`);
|
||||||
|
return toolError("AMBIGUOUS_CONNECTION", `Multiple connections found with name "${connection_name}". Please specify connection_id:\n${lines.join("\n")}`);
|
||||||
|
}
|
||||||
const removed = await backend.removeConnection(connection_name);
|
const removed = await backend.removeConnection(connection_name);
|
||||||
if (!removed) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
if (!removed) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
||||||
await notifyReload();
|
await notifyReload();
|
||||||
@@ -329,15 +397,31 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"dbx_open_table",
|
"dbx_open_table",
|
||||||
"Open a table in DBX desktop app UI. Requires DBX to be running.",
|
"Open a table in DBX desktop app UI. Requires DBX to be running.",
|
||||||
{
|
{
|
||||||
connection_name: z.string().describe("Name of the DBX connection"),
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
|
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
||||||
table: z.string().describe("Table name to open"),
|
table: z.string().describe("Table name to open"),
|
||||||
database: z.string().optional().describe("Database name"),
|
database: z.string().optional().describe("Database name"),
|
||||||
schema: z.string().optional().describe("Schema name"),
|
schema: z.string().optional().describe("Schema name"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, table, database, schema }) => {
|
async ({ connection_id, connection_name, table, database, schema }) => {
|
||||||
const config = await backend.findConnection(connection_name);
|
let config: ConnectionConfig | undefined;
|
||||||
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
if (connection_id?.trim()) {
|
||||||
return bridgeRequest("/open-table", { connection_name, table, database, schema }, `Opened ${table} in DBX`);
|
const connections = await backend.loadConnections();
|
||||||
|
config = connections.find((c) => c.id === connection_id.trim());
|
||||||
|
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection with id "${connection_id}" not found.`);
|
||||||
|
} else if (connection_name?.trim()) {
|
||||||
|
const connections = await backend.loadConnections();
|
||||||
|
const matching = connections.filter((c) => c.name.toLowerCase() === connection_name.toLowerCase());
|
||||||
|
if (matching.length === 0) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
||||||
|
if (matching.length > 1) {
|
||||||
|
const lines = matching.map((c) => `- ${c.id}: ${c.db_type} @ ${c.host}:${c.port}`);
|
||||||
|
return toolError("AMBIGUOUS_CONNECTION", `Multiple connections found with name "${connection_name}". Please specify connection_id:\n${lines.join("\n")}`);
|
||||||
|
}
|
||||||
|
config = matching[0];
|
||||||
|
} else {
|
||||||
|
return toolError("CONNECTION_NOT_FOUND", "Either connection_id or connection_name is required.");
|
||||||
|
}
|
||||||
|
return bridgeRequest("/open-table", { connection_id: config.id, connection_name: config.name, table, database, schema }, `Opened ${table} in DBX`);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -345,13 +429,29 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
"dbx_execute_and_show",
|
"dbx_execute_and_show",
|
||||||
"Execute a SQL query in DBX desktop app UI and show results there. Requires DBX to be running.",
|
"Execute a SQL query in DBX desktop app UI and show results there. Requires DBX to be running.",
|
||||||
{
|
{
|
||||||
connection_name: z.string().describe("Name of the DBX connection"),
|
connection_id: z.string().optional().describe("Unique ID of the DBX connection (use this to disambiguate when multiple connections share the same name)"),
|
||||||
|
connection_name: z.string().optional().describe("Name of the DBX connection"),
|
||||||
sql: z.string().describe("SQL query to execute"),
|
sql: z.string().describe("SQL query to execute"),
|
||||||
database: z.string().optional().describe("Database name"),
|
database: z.string().optional().describe("Database name"),
|
||||||
},
|
},
|
||||||
async ({ connection_name, sql, database }) => {
|
async ({ connection_id, connection_name, sql, database }) => {
|
||||||
const config = await backend.findConnection(connection_name);
|
let config: ConnectionConfig | undefined;
|
||||||
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
if (connection_id?.trim()) {
|
||||||
|
const connections = await backend.loadConnections();
|
||||||
|
config = connections.find((c) => c.id === connection_id.trim());
|
||||||
|
if (!config) return toolError("CONNECTION_NOT_FOUND", `Connection with id "${connection_id}" not found.`);
|
||||||
|
} else if (connection_name?.trim()) {
|
||||||
|
const connections = await backend.loadConnections();
|
||||||
|
const matching = connections.filter((c) => c.name.toLowerCase() === connection_name.toLowerCase());
|
||||||
|
if (matching.length === 0) return toolError("CONNECTION_NOT_FOUND", `Connection "${connection_name}" not found.`);
|
||||||
|
if (matching.length > 1) {
|
||||||
|
const lines = matching.map((c) => `- ${c.id}: ${c.db_type} @ ${c.host}:${c.port}`);
|
||||||
|
return toolError("AMBIGUOUS_CONNECTION", `Multiple connections found with name "${connection_name}". Please specify connection_id:\n${lines.join("\n")}`);
|
||||||
|
}
|
||||||
|
config = matching[0];
|
||||||
|
} else {
|
||||||
|
return toolError("CONNECTION_NOT_FOUND", "Either connection_id or connection_name is required.");
|
||||||
|
}
|
||||||
const safetyOptions = sqlSafetyFromEnv();
|
const safetyOptions = sqlSafetyFromEnv();
|
||||||
if (config?.db_type === "mongodb") {
|
if (config?.db_type === "mongodb") {
|
||||||
const aggregate = parseMongoAggregateCommand(sql);
|
const aggregate = parseMongoAggregateCommand(sql);
|
||||||
@@ -368,7 +468,8 @@ export function createDbxMcpServer(backend: Backend, options: { isWebMode?: bool
|
|||||||
return bridgeRequest(
|
return bridgeRequest(
|
||||||
"/execute-query",
|
"/execute-query",
|
||||||
{
|
{
|
||||||
connection_name,
|
connection_id: config!.id,
|
||||||
|
connection_name: config!.name,
|
||||||
sql,
|
sql,
|
||||||
database,
|
database,
|
||||||
allow_writes: safetyOptions.allowWrites,
|
allow_writes: safetyOptions.allowWrites,
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ test("redis execute query points callers to the redis command tool", async () =>
|
|||||||
const redisConnection: ConnectionConfig = { ...connection, db_type: "redis", database: "0" };
|
const redisConnection: ConnectionConfig = { ...connection, db_type: "redis", database: "0" };
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => redisConnection,
|
loadConnections: async () => [redisConnection],
|
||||||
};
|
};
|
||||||
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
@@ -216,7 +216,7 @@ test("redis command tool executes redis commands on the selected database", asyn
|
|||||||
let usedCommand = "";
|
let usedCommand = "";
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => redisConnection,
|
loadConnections: async () => [redisConnection],
|
||||||
executeRedisCommand: async (_config, db, command) => {
|
executeRedisCommand: async (_config, db, command) => {
|
||||||
usedDb = db;
|
usedDb = db;
|
||||||
usedCommand = command;
|
usedCommand = command;
|
||||||
@@ -242,7 +242,7 @@ test("redis command tool blocks write commands in read-only MCP sessions", async
|
|||||||
const redisConnection: ConnectionConfig = { ...connection, db_type: "redis" };
|
const redisConnection: ConnectionConfig = { ...connection, db_type: "redis" };
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => redisConnection,
|
loadConnections: async () => [redisConnection],
|
||||||
executeRedisCommand: async () => {
|
executeRedisCommand: async () => {
|
||||||
executed = true;
|
executed = true;
|
||||||
return { command: "SET", safety: "write", value: "OK" };
|
return { command: "SET", safety: "write", value: "OK" };
|
||||||
@@ -267,7 +267,7 @@ test("redis command tool allows dangerous redis commands only when explicitly en
|
|||||||
let skipSafetyCheck = false;
|
let skipSafetyCheck = false;
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => redisConnection,
|
loadConnections: async () => [redisConnection],
|
||||||
executeRedisCommand: async (_config, _db, _command, options) => {
|
executeRedisCommand: async (_config, _db, _command, options) => {
|
||||||
skipSafetyCheck = options?.skipSafetyCheck ?? false;
|
skipSafetyCheck = options?.skipSafetyCheck ?? false;
|
||||||
return { command: "KEYS", safety: "blocked", value: ["session:1"] };
|
return { command: "KEYS", safety: "blocked", value: ["session:1"] };
|
||||||
@@ -301,7 +301,7 @@ test("mongodb list tables returns collections from the selected database", async
|
|||||||
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb", database: "admin" };
|
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb", database: "admin" };
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => mongoConnection,
|
loadConnections: async () => [mongoConnection],
|
||||||
listTables: async (config) => {
|
listTables: async (config) => {
|
||||||
usedDatabase = config.database || "";
|
usedDatabase = config.database || "";
|
||||||
return [{ name: "projects", type: "COLLECTION" }];
|
return [{ name: "projects", type: "COLLECTION" }];
|
||||||
@@ -323,7 +323,7 @@ test("mongodb describe table returns inferred document fields", async () => {
|
|||||||
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb" };
|
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb" };
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => mongoConnection,
|
loadConnections: async () => [mongoConnection],
|
||||||
describeTable: async () => [
|
describeTable: async () => [
|
||||||
{
|
{
|
||||||
name: "_id",
|
name: "_id",
|
||||||
@@ -359,7 +359,7 @@ test("mongodb execute query formats shell-style find results", async () => {
|
|||||||
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb" };
|
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb" };
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => mongoConnection,
|
loadConnections: async () => [mongoConnection],
|
||||||
executeQuery: async () => ({
|
executeQuery: async () => ({
|
||||||
columns: ["_id", "meta", "missing"],
|
columns: ["_id", "meta", "missing"],
|
||||||
rows: [{ _id: "1", meta: { name: "demo" }, missing: null }],
|
rows: [{ _id: "1", meta: { name: "demo" }, missing: null }],
|
||||||
@@ -395,7 +395,6 @@ test("add connection accepts H2 file paths without a port", async () => {
|
|||||||
let added: Omit<ConnectionConfig, "id"> | undefined;
|
let added: Omit<ConnectionConfig, "id"> | undefined;
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => undefined,
|
|
||||||
addConnection: async (config) => {
|
addConnection: async (config) => {
|
||||||
added = config;
|
added = config;
|
||||||
return { id: "h2-file", ...config };
|
return { id: "h2-file", ...config };
|
||||||
@@ -449,23 +448,23 @@ test("query exceptions include a stable MCP error code", async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("desktop bridge failures include a stable MCP error code", async () => {
|
test("desktop bridge failures include a stable MCP error code", async () => {
|
||||||
const oldHome = process.env.HOME;
|
|
||||||
const dir = await mkdtemp(join(tmpdir(), "dbx-mcp-home-"));
|
const dir = await mkdtemp(join(tmpdir(), "dbx-mcp-home-"));
|
||||||
process.env.HOME = dir;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const server = createDbxMcpServer(backend, { isWebMode: false });
|
// Use DBX_DATA_DIR (honoured cross-platform) to point bridgePortFilePath()
|
||||||
const result = await (server as any)._registeredTools.dbx_open_table.handler({
|
// at an empty temp directory so no real bridge is reachable.
|
||||||
connection_name: "local",
|
await withScopedEnv({ DBX_DATA_DIR: dir }, async () => {
|
||||||
table: "users",
|
const server = createDbxMcpServer(backend, { isWebMode: false });
|
||||||
});
|
const result = await (server as any)._registeredTools.dbx_open_table.handler({
|
||||||
|
connection_name: "local",
|
||||||
|
table: "users",
|
||||||
|
});
|
||||||
|
|
||||||
assert.equal(result.isError, true);
|
assert.equal(result.isError, true);
|
||||||
assert.match(result.content[0].text, /DBX_NOT_RUNNING:/);
|
assert.match(result.content[0].text, /DBX_NOT_RUNNING:/);
|
||||||
assert.match(result.content[0].text, /DBX is not running/);
|
assert.match(result.content[0].text, /DBX is not running/);
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
if (oldHome === undefined) delete process.env.HOME;
|
|
||||||
else process.env.HOME = oldHome;
|
|
||||||
await rm(dir, { recursive: true, force: true });
|
await rm(dir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -478,7 +477,7 @@ test("mongodb execute-and-show blocks aggregate write stages before desktop brid
|
|||||||
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb" };
|
const mongoConnection: ConnectionConfig = { ...connection, db_type: "mongodb" };
|
||||||
const scopedBackend: Backend = {
|
const scopedBackend: Backend = {
|
||||||
...backend,
|
...backend,
|
||||||
findConnection: async () => mongoConnection,
|
loadConnections: async () => [mongoConnection],
|
||||||
};
|
};
|
||||||
const server = createDbxMcpServer(scopedBackend, { isWebMode: false });
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: false });
|
||||||
|
|
||||||
@@ -498,3 +497,242 @@ test("mongodb execute-and-show blocks aggregate write stages before desktop brid
|
|||||||
else process.env.DBX_MCP_ALLOW_DANGEROUS_SQL = oldAllowDangerous;
|
else process.env.DBX_MCP_ALLOW_DANGEROUS_SQL = oldAllowDangerous;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("connection_id parameter resolves correctly", async () => {
|
||||||
|
const connA: ConnectionConfig = { ...connection, id: "a1b2c3", name: "shared-name", db_type: "postgres" };
|
||||||
|
const connB: ConnectionConfig = { ...connection, id: "d4e5f6", name: "shared-name", db_type: "redis", host: "redis.local", port: 6379 };
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connA, connB],
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
// Resolve by connection_id should return the correct connection
|
||||||
|
const result = await (server as any)._registeredTools.dbx_list_tables.handler({
|
||||||
|
connection_id: "d4e5f6",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.match(result.content[0].text, /users/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("duplicate connection names return AMBIGUOUS_CONNECTION error", async () => {
|
||||||
|
const connA: ConnectionConfig = { ...connection, id: "a1b2c3", name: "shared-name", db_type: "postgres", host: "pg.local", port: 5432 };
|
||||||
|
const connB: ConnectionConfig = { ...connection, id: "d4e5f6", name: "shared-name", db_type: "redis", host: "redis.local", port: 6379 };
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connA, connB],
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
// Using connection_name with duplicates should return AMBIGUOUS_CONNECTION
|
||||||
|
const result = await (server as any)._registeredTools.dbx_list_tables.handler({
|
||||||
|
connection_name: "shared-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.isError, true);
|
||||||
|
assert.match(result.content[0].text, /AMBIGUOUS_CONNECTION:/);
|
||||||
|
assert.match(result.content[0].text, /a1b2c3:/);
|
||||||
|
assert.match(result.content[0].text, /d4e5f6:/);
|
||||||
|
assert.match(result.content[0].text, /postgres @ pg.local:5432/);
|
||||||
|
assert.match(result.content[0].text, /redis @ redis.local:6379/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("connection_id takes priority over connection_name", async () => {
|
||||||
|
const connA: ConnectionConfig = { ...connection, id: "a1b2c3", name: "shared-name", db_type: "postgres" };
|
||||||
|
const connB: ConnectionConfig = { ...connection, id: "d4e5f6", name: "shared-name", db_type: "mysql", host: "mysql.local", port: 3306 };
|
||||||
|
let usedConfig: ConnectionConfig | undefined;
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connA, connB],
|
||||||
|
listTables: async (config) => {
|
||||||
|
usedConfig = config;
|
||||||
|
return [{ name: "users", type: "BASE TABLE" }];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
// Provide both connection_id and connection_name; connection_id should win
|
||||||
|
await (server as any)._registeredTools.dbx_list_tables.handler({
|
||||||
|
connection_id: "d4e5f6",
|
||||||
|
connection_name: "shared-name",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(usedConfig?.id, "d4e5f6");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dbx_list_connections includes ID column", async () => {
|
||||||
|
const server = createDbxMcpServer(backend, { isWebMode: true });
|
||||||
|
const result = await (server as any)._registeredTools.dbx_list_connections.handler({});
|
||||||
|
|
||||||
|
// The table header should include the ID column
|
||||||
|
assert.match(result.content[0].text, /ID.*Name.*Type.*Host.*Port.*Database/);
|
||||||
|
// The connection's ID value "1" should appear in the table
|
||||||
|
assert.match(result.content[0].text, /1\s+\|\s+local/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("same name and db_type with different host/port returns AMBIGUOUS_CONNECTION", async () => {
|
||||||
|
const connA: ConnectionConfig = {
|
||||||
|
...connection,
|
||||||
|
id: "pg-prod-us",
|
||||||
|
name: "my-db",
|
||||||
|
db_type: "postgres",
|
||||||
|
host: "10.0.1.100",
|
||||||
|
port: 5432,
|
||||||
|
database: "app",
|
||||||
|
};
|
||||||
|
const connB: ConnectionConfig = {
|
||||||
|
...connection,
|
||||||
|
id: "pg-prod-eu",
|
||||||
|
name: "my-db",
|
||||||
|
db_type: "postgres",
|
||||||
|
host: "10.0.2.200",
|
||||||
|
port: 5432,
|
||||||
|
database: "app",
|
||||||
|
};
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connA, connB],
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
// Using connection_name with duplicates (same db_type) should still return AMBIGUOUS_CONNECTION
|
||||||
|
const result = await (server as any)._registeredTools.dbx_list_tables.handler({
|
||||||
|
connection_name: "my-db",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.isError, true);
|
||||||
|
assert.match(result.content[0].text, /AMBIGUOUS_CONNECTION:/);
|
||||||
|
assert.match(result.content[0].text, /pg-prod-us: postgres @ 10\.0\.1\.100:5432/);
|
||||||
|
assert.match(result.content[0].text, /pg-prod-eu: postgres @ 10\.0\.2\.200:5432/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("connection_id routes to correct host among same-name same-type connections", async () => {
|
||||||
|
const connA: ConnectionConfig = {
|
||||||
|
...connection,
|
||||||
|
id: "pg-prod-us",
|
||||||
|
name: "my-db",
|
||||||
|
db_type: "postgres",
|
||||||
|
host: "10.0.1.100",
|
||||||
|
port: 5432,
|
||||||
|
database: "app",
|
||||||
|
};
|
||||||
|
const connB: ConnectionConfig = {
|
||||||
|
...connection,
|
||||||
|
id: "pg-prod-eu",
|
||||||
|
name: "my-db",
|
||||||
|
db_type: "postgres",
|
||||||
|
host: "10.0.2.200",
|
||||||
|
port: 5432,
|
||||||
|
database: "app",
|
||||||
|
};
|
||||||
|
const usedConfigs: ConnectionConfig[] = [];
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connA, connB],
|
||||||
|
listTables: async (config) => {
|
||||||
|
usedConfigs.push(config);
|
||||||
|
return [{ name: "orders", type: "BASE TABLE" }];
|
||||||
|
},
|
||||||
|
executeQuery: async (config, _sql) => {
|
||||||
|
usedConfigs.push(config);
|
||||||
|
return { columns: ["cnt"], rows: [{ cnt: 42 }], row_count: 1 };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
// Route to US instance via connection_id
|
||||||
|
const listResult = await (server as any)._registeredTools.dbx_list_tables.handler({
|
||||||
|
connection_id: "pg-prod-us",
|
||||||
|
});
|
||||||
|
assert.match(listResult.content[0].text, /orders/);
|
||||||
|
assert.equal(usedConfigs[0].id, "pg-prod-us");
|
||||||
|
assert.equal(usedConfigs[0].host, "10.0.1.100");
|
||||||
|
|
||||||
|
// Route to EU instance via connection_id
|
||||||
|
const queryResult = await (server as any)._registeredTools.dbx_execute_query.handler({
|
||||||
|
connection_id: "pg-prod-eu",
|
||||||
|
database: "app",
|
||||||
|
sql: "select count(*) as cnt from orders",
|
||||||
|
});
|
||||||
|
assert.match(queryResult.content[0].text, /42/);
|
||||||
|
assert.equal(usedConfigs[1].id, "pg-prod-eu");
|
||||||
|
assert.equal(usedConfigs[1].host, "10.0.2.200");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tool responses are prefixed with connection identity label", async () => {
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [{ ...connection, id: "conn-xyz", name: "orders-db", db_type: "postgres", host: "10.5.5.5", port: 5432 }],
|
||||||
|
listTables: async () => [{ name: "orders", type: "BASE TABLE" }],
|
||||||
|
executeQuery: async () => ({ columns: ["cnt"], rows: [{ cnt: 7 }], row_count: 1 }),
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
const listResult = await (server as any)._registeredTools.dbx_list_tables.handler({ connection_id: "conn-xyz" });
|
||||||
|
assert.match(listResult.content[0].text, /^\[orders-db \(conn-xyz\) \[postgres @ 10\.5\.5\.5:5432\]\]/);
|
||||||
|
|
||||||
|
const queryResult = await (server as any)._registeredTools.dbx_execute_query.handler({ connection_id: "conn-xyz", sql: "select count(*) as cnt from orders" });
|
||||||
|
assert.match(queryResult.content[0].text, /^\[orders-db \(conn-xyz\) \[postgres @ 10\.5\.5\.5:5432\]\]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dbx_remove_connection with duplicate names returns AMBIGUOUS_CONNECTION", async () => {
|
||||||
|
const connA: ConnectionConfig = { ...connection, id: "db-a", name: "staging", db_type: "postgres", host: "pg-a.local" };
|
||||||
|
const connB: ConnectionConfig = { ...connection, id: "db-b", name: "staging", db_type: "mysql", host: "mysql-b.local", port: 3306 };
|
||||||
|
let removedName: string | undefined;
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connA, connB],
|
||||||
|
removeConnection: async (name) => {
|
||||||
|
removedName = name;
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
const result = await (server as any)._registeredTools.dbx_remove_connection.handler({
|
||||||
|
connection_name: "staging",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.isError, true);
|
||||||
|
assert.match(result.content[0].text, /AMBIGUOUS_CONNECTION:/);
|
||||||
|
assert.match(result.content[0].text, /db-a: postgres @ pg-a\.local/);
|
||||||
|
assert.match(result.content[0].text, /db-b: mysql @ mysql-b\.local/);
|
||||||
|
// removeConnection must NOT have been called — no silent deletion
|
||||||
|
assert.equal(removedName, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("dbx_execute_query with connection_id routes correctly on bridge-backed (SSH) connections", async () => {
|
||||||
|
const connDirect: ConnectionConfig = { ...connection, id: "pg-direct", name: "shared", db_type: "postgres", host: "direct.local", ssh_enabled: false };
|
||||||
|
const connSsh: ConnectionConfig = { ...connection, id: "pg-ssh", name: "shared", db_type: "postgres", host: "private.local", ssh_enabled: true };
|
||||||
|
const usedConfigs: ConnectionConfig[] = [];
|
||||||
|
const scopedBackend: Backend = {
|
||||||
|
...backend,
|
||||||
|
loadConnections: async () => [connDirect, connSsh],
|
||||||
|
executeQuery: async (config, _sql) => {
|
||||||
|
usedConfigs.push(config);
|
||||||
|
return { columns: ["result"], rows: [{ result: "ok" }], row_count: 1 };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const server = createDbxMcpServer(scopedBackend, { isWebMode: true });
|
||||||
|
|
||||||
|
// connection_name with two same-name connections (one SSH-backed) → AMBIGUOUS_CONNECTION
|
||||||
|
const ambigResult = await (server as any)._registeredTools.dbx_execute_query.handler({
|
||||||
|
connection_name: "shared",
|
||||||
|
sql: "select 1",
|
||||||
|
});
|
||||||
|
assert.equal(ambigResult.isError, true);
|
||||||
|
assert.match(ambigResult.content[0].text, /AMBIGUOUS_CONNECTION:/);
|
||||||
|
assert.match(ambigResult.content[0].text, /pg-direct/);
|
||||||
|
assert.match(ambigResult.content[0].text, /pg-ssh/);
|
||||||
|
|
||||||
|
// connection_id routes to the SSH-backed instance and passes its config through
|
||||||
|
const result = await (server as any)._registeredTools.dbx_execute_query.handler({
|
||||||
|
connection_id: "pg-ssh",
|
||||||
|
sql: "select 1",
|
||||||
|
});
|
||||||
|
assert.equal(result.isError, undefined);
|
||||||
|
assert.equal(usedConfigs.length, 1);
|
||||||
|
assert.equal(usedConfigs[0].id, "pg-ssh");
|
||||||
|
assert.equal(usedConfigs[0].host, "private.local");
|
||||||
|
assert.equal(usedConfigs[0].ssh_enabled, true);
|
||||||
|
});
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { addConnection as desktopAddConnection, findConnection as desktopFindConnection, loadConnections as desktopLoadConnections, removeConnection as desktopRemoveConnection } from "./connections.js";
|
import { addConnection as desktopAddConnection, findConnection as desktopFindConnection, loadConnections as desktopLoadConnections, removeConnection as desktopRemoveConnection, removeConnectionById as desktopRemoveConnectionById } from "./connections.js";
|
||||||
import { closeDatabaseResources as desktopCloseDatabaseResources, describeTable as desktopDescribeTable, executeQuery as desktopExecuteQuery, executeRedisCommand as desktopExecuteRedisCommand, 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 { ConnectionConfig } from "./connections.js";
|
||||||
import type { ColumnInfo, QueryOptions, QueryResult, TableInfo } from "./database.js";
|
import type { ColumnInfo, QueryOptions, QueryResult, TableInfo } from "./database.js";
|
||||||
@@ -9,6 +9,7 @@ export interface Backend {
|
|||||||
findConnection(name: string): Promise<ConnectionConfig | undefined>;
|
findConnection(name: string): Promise<ConnectionConfig | undefined>;
|
||||||
addConnection(config: Omit<ConnectionConfig, "id">): Promise<ConnectionConfig>;
|
addConnection(config: Omit<ConnectionConfig, "id">): Promise<ConnectionConfig>;
|
||||||
removeConnection(name: string): Promise<boolean>;
|
removeConnection(name: string): Promise<boolean>;
|
||||||
|
removeConnectionById?(id: string): Promise<boolean>;
|
||||||
listTables(config: ConnectionConfig, schema?: string): Promise<TableInfo[]>;
|
listTables(config: ConnectionConfig, schema?: string): Promise<TableInfo[]>;
|
||||||
describeTable(config: ConnectionConfig, table: string, schema?: string): Promise<ColumnInfo[]>;
|
describeTable(config: ConnectionConfig, table: string, schema?: string): Promise<ColumnInfo[]>;
|
||||||
executeQuery(config: ConnectionConfig, sql: string, options?: QueryOptions): Promise<QueryResult>;
|
executeQuery(config: ConnectionConfig, sql: string, options?: QueryOptions): Promise<QueryResult>;
|
||||||
@@ -26,6 +27,7 @@ export async function createBackend(env: NodeJS.ProcessEnv = process.env): Promi
|
|||||||
findConnection: desktopFindConnection,
|
findConnection: desktopFindConnection,
|
||||||
addConnection: desktopAddConnection,
|
addConnection: desktopAddConnection,
|
||||||
removeConnection: desktopRemoveConnection,
|
removeConnection: desktopRemoveConnection,
|
||||||
|
removeConnectionById: desktopRemoveConnectionById,
|
||||||
listTables: desktopListTables,
|
listTables: desktopListTables,
|
||||||
describeTable: desktopDescribeTable,
|
describeTable: desktopDescribeTable,
|
||||||
executeQuery: desktopExecuteQuery,
|
executeQuery: desktopExecuteQuery,
|
||||||
|
|||||||
@@ -279,6 +279,11 @@ export async function findConnection(name: string): Promise<ConnectionConfig | u
|
|||||||
return connections.find((c) => c.name.toLowerCase() === name.toLowerCase());
|
return connections.find((c) => c.name.toLowerCase() === name.toLowerCase());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function findConnectionById(id: string): Promise<ConnectionConfig | undefined> {
|
||||||
|
const connections = await loadConnections();
|
||||||
|
return connections.find((c) => c.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
export async function addConnection(config: Omit<ConnectionConfig, "id">): Promise<ConnectionConfig> {
|
export async function addConnection(config: Omit<ConnectionConfig, "id">): Promise<ConnectionConfig> {
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const db = openDb();
|
const db = openDb();
|
||||||
@@ -355,3 +360,15 @@ export async function removeConnection(name: string): Promise<boolean> {
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function removeConnectionById(id: string): Promise<boolean> {
|
||||||
|
const db = openDb();
|
||||||
|
const remove = db.transaction(() => {
|
||||||
|
const result = db.prepare("DELETE FROM connections WHERE id = ?").run(id);
|
||||||
|
db.prepare("DELETE FROM connection_secrets WHERE connection_id = ?").run(id);
|
||||||
|
return result.changes > 0;
|
||||||
|
});
|
||||||
|
const deleted = remove();
|
||||||
|
db.close();
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
@@ -856,6 +856,7 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
|
|||||||
if (hasActiveSshLayer(config)) {
|
if (hasActiveSshLayer(config)) {
|
||||||
const result = await withTimeout(
|
const result = await withTimeout(
|
||||||
bridgeDataRequest<BridgeQueryResult>("/data/execute-query", {
|
bridgeDataRequest<BridgeQueryResult>("/data/execute-query", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
sql,
|
sql,
|
||||||
@@ -927,6 +928,7 @@ export async function executeQuery(config: ConnectionConfig, sql: string, option
|
|||||||
}
|
}
|
||||||
const result = await withTimeout(
|
const result = await withTimeout(
|
||||||
bridgeDataRequest<BridgeQueryResult>("/data/execute-query", {
|
bridgeDataRequest<BridgeQueryResult>("/data/execute-query", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
sql,
|
sql,
|
||||||
@@ -945,6 +947,7 @@ export async function executeRedisCommand(config: ConnectionConfig, db: number,
|
|||||||
}
|
}
|
||||||
return withTimeout(
|
return withTimeout(
|
||||||
bridgeDataRequest<RedisCommandResult>("/data/redis/execute-command", {
|
bridgeDataRequest<RedisCommandResult>("/data/redis/execute-command", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
db,
|
db,
|
||||||
command,
|
command,
|
||||||
@@ -1029,6 +1032,7 @@ function redisTextToJson(value: string): unknown {
|
|||||||
export async function listTables(config: ConnectionConfig, schema?: string): Promise<TableInfo[]> {
|
export async function listTables(config: ConnectionConfig, schema?: string): Promise<TableInfo[]> {
|
||||||
if (config.db_type === "mongodb") {
|
if (config.db_type === "mongodb") {
|
||||||
const collections = await bridgeDataRequest<CollectionListEntry[]>("/data/mongo/list-collections", {
|
const collections = await bridgeDataRequest<CollectionListEntry[]>("/data/mongo/list-collections", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
schema: schema || "",
|
schema: schema || "",
|
||||||
@@ -1041,6 +1045,7 @@ export async function listTables(config: ConnectionConfig, schema?: string): Pro
|
|||||||
}
|
}
|
||||||
if (hasActiveSshLayer(config) || !isDirectQueryType(config.db_type)) {
|
if (hasActiveSshLayer(config) || !isDirectQueryType(config.db_type)) {
|
||||||
const tables = await bridgeDataRequest<BridgeTableInfo[]>("/data/list-tables", {
|
const tables = await bridgeDataRequest<BridgeTableInfo[]>("/data/list-tables", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
schema: schema || "",
|
schema: schema || "",
|
||||||
@@ -1074,6 +1079,7 @@ export async function describeTable(config: ConnectionConfig, table: string, sch
|
|||||||
}
|
}
|
||||||
if (hasActiveSshLayer(config) || !isDirectQueryType(config.db_type)) {
|
if (hasActiveSshLayer(config) || !isDirectQueryType(config.db_type)) {
|
||||||
const columns = await bridgeDataRequest<BridgeColumnInfo[]>("/data/describe-table", {
|
const columns = await bridgeDataRequest<BridgeColumnInfo[]>("/data/describe-table", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
schema: schema || "",
|
schema: schema || "",
|
||||||
@@ -1099,6 +1105,7 @@ export async function describeTable(config: ConnectionConfig, table: string, sch
|
|||||||
|
|
||||||
async function mongoFindDocuments(config: ConnectionConfig, collection: string, skip: number, limit: number, filter: string, projection?: string, sort?: string): Promise<MongoDocumentResult> {
|
async function mongoFindDocuments(config: ConnectionConfig, collection: string, skip: number, limit: number, filter: string, projection?: string, sort?: string): Promise<MongoDocumentResult> {
|
||||||
return bridgeDataRequest<MongoDocumentResult>("/data/mongo/find-documents", {
|
return bridgeDataRequest<MongoDocumentResult>("/data/mongo/find-documents", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection,
|
collection,
|
||||||
@@ -1112,6 +1119,7 @@ async function mongoFindDocuments(config: ConnectionConfig, collection: string,
|
|||||||
|
|
||||||
async function mongoServerVersion(config: ConnectionConfig): Promise<string> {
|
async function mongoServerVersion(config: ConnectionConfig): Promise<string> {
|
||||||
return bridgeDataRequest<string>("/data/mongo/server-version", {
|
return bridgeDataRequest<string>("/data/mongo/server-version", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
});
|
});
|
||||||
@@ -1119,6 +1127,7 @@ async function mongoServerVersion(config: ConnectionConfig): Promise<string> {
|
|||||||
|
|
||||||
async function mongoCollectionStats(config: ConnectionConfig, collection: string, scale?: number): Promise<Record<string, unknown>> {
|
async function mongoCollectionStats(config: ConnectionConfig, collection: string, scale?: number): Promise<Record<string, unknown>> {
|
||||||
return bridgeDataRequest<Record<string, unknown>>("/data/mongo/collection-stats", {
|
return bridgeDataRequest<Record<string, unknown>>("/data/mongo/collection-stats", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection,
|
collection,
|
||||||
@@ -1129,6 +1138,7 @@ async function mongoCollectionStats(config: ConnectionConfig, collection: string
|
|||||||
async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCommand): Promise<{ affectedRows: number; indexName?: string; droppedNames?: string[] }> {
|
async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCommand): Promise<{ affectedRows: number; indexName?: string; droppedNames?: string[] }> {
|
||||||
if (command.kind === "insert") {
|
if (command.kind === "insert") {
|
||||||
const result = await bridgeDataRequest<{ affected_rows: number }>("/data/mongo/insert-documents", {
|
const result = await bridgeDataRequest<{ affected_rows: number }>("/data/mongo/insert-documents", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection: command.collection,
|
collection: command.collection,
|
||||||
@@ -1138,6 +1148,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
|
|||||||
}
|
}
|
||||||
if (command.kind === "update") {
|
if (command.kind === "update") {
|
||||||
const result = await bridgeDataRequest<{ affected_rows: number }>("/data/mongo/update-documents", {
|
const result = await bridgeDataRequest<{ affected_rows: number }>("/data/mongo/update-documents", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection: command.collection,
|
collection: command.collection,
|
||||||
@@ -1149,6 +1160,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
|
|||||||
}
|
}
|
||||||
if (command.kind === "createIndex") {
|
if (command.kind === "createIndex") {
|
||||||
const result = await bridgeDataRequest<{ name: string }>("/data/mongo/create-index", {
|
const result = await bridgeDataRequest<{ name: string }>("/data/mongo/create-index", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection: command.collection,
|
collection: command.collection,
|
||||||
@@ -1159,6 +1171,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
|
|||||||
}
|
}
|
||||||
if (command.kind === "dropIndex" || command.kind === "dropIndexes") {
|
if (command.kind === "dropIndex" || command.kind === "dropIndexes") {
|
||||||
const result = await bridgeDataRequest<{ dropped_names: string[]; affected_rows: number }>("/data/mongo/drop-indexes", {
|
const result = await bridgeDataRequest<{ dropped_names: string[]; affected_rows: number }>("/data/mongo/drop-indexes", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection: command.collection,
|
collection: command.collection,
|
||||||
@@ -1169,6 +1182,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
|
|||||||
}
|
}
|
||||||
if (command.kind === "dropCollection") {
|
if (command.kind === "dropCollection") {
|
||||||
await bridgeDataRequest<{ ok: boolean }>("/data/mongo/drop-collection", {
|
await bridgeDataRequest<{ ok: boolean }>("/data/mongo/drop-collection", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection: command.collection,
|
collection: command.collection,
|
||||||
@@ -1176,6 +1190,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
|
|||||||
return { affectedRows: 1 };
|
return { affectedRows: 1 };
|
||||||
}
|
}
|
||||||
const result = await bridgeDataRequest<{ affected_rows: number }>("/data/mongo/delete-documents", {
|
const result = await bridgeDataRequest<{ affected_rows: number }>("/data/mongo/delete-documents", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection: command.collection,
|
collection: command.collection,
|
||||||
@@ -1187,6 +1202,7 @@ async function executeMongoWrite(config: ConnectionConfig, command: MongoWriteCo
|
|||||||
|
|
||||||
async function mongoAggregateDocuments(config: ConnectionConfig, collection: string, pipelineJson: string, maxRows: number): Promise<MongoDocumentResult> {
|
async function mongoAggregateDocuments(config: ConnectionConfig, collection: string, pipelineJson: string, maxRows: number): Promise<MongoDocumentResult> {
|
||||||
return bridgeDataRequest<MongoDocumentResult>("/data/mongo/aggregate-documents", {
|
return bridgeDataRequest<MongoDocumentResult>("/data/mongo/aggregate-documents", {
|
||||||
|
connection_id: config.id,
|
||||||
connection_name: config.name,
|
connection_name: config.name,
|
||||||
database: config.database || "",
|
database: config.database || "",
|
||||||
collection,
|
collection,
|
||||||
|
|||||||
@@ -150,6 +150,13 @@ export async function removeConnection(name: string): Promise<boolean> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function removeConnectionById(id: string): Promise<boolean> {
|
||||||
|
const connection = await loadConnections().then((cs) => cs.find((c) => c.id === id));
|
||||||
|
if (!connection) return false;
|
||||||
|
await apiFetch(`/api/connection/delete?id=${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
async function ensureConnected(config: ConnectionConfig): Promise<void> {
|
async function ensureConnected(config: ConnectionConfig): Promise<void> {
|
||||||
await apiFetch("/api/connection/connect", {
|
await apiFetch("/api/connection/connect", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const MCP_BRIDGE_PORT_FILE: &str = "mcp-bridge-port";
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct OpenTableRequest {
|
struct OpenTableRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
schema: Option<String>,
|
schema: Option<String>,
|
||||||
table: String,
|
table: String,
|
||||||
@@ -23,6 +24,7 @@ struct OpenTableRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct ExecuteQueryRequest {
|
struct ExecuteQueryRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
sql: String,
|
sql: String,
|
||||||
schema: Option<String>,
|
schema: Option<String>,
|
||||||
@@ -33,6 +35,7 @@ struct ExecuteQueryRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct ListTablesRequest {
|
struct ListTablesRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
schema: Option<String>,
|
schema: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -40,6 +43,7 @@ struct ListTablesRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct DescribeTableRequest {
|
struct DescribeTableRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
schema: Option<String>,
|
schema: Option<String>,
|
||||||
table: String,
|
table: String,
|
||||||
@@ -48,6 +52,7 @@ struct DescribeTableRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoFindDocumentsRequest {
|
struct MongoFindDocumentsRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
skip: Option<u64>,
|
skip: Option<u64>,
|
||||||
@@ -60,12 +65,14 @@ struct MongoFindDocumentsRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoServerVersionRequest {
|
struct MongoServerVersionRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoCollectionStatsRequest {
|
struct MongoCollectionStatsRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
scale: Option<serde_json::Number>,
|
scale: Option<serde_json::Number>,
|
||||||
@@ -74,6 +81,7 @@ struct MongoCollectionStatsRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoAggregateDocumentsRequest {
|
struct MongoAggregateDocumentsRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
pipeline_json: String,
|
pipeline_json: String,
|
||||||
@@ -83,6 +91,7 @@ struct MongoAggregateDocumentsRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoCreateIndexRequest {
|
struct MongoCreateIndexRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
keys_json: String,
|
keys_json: String,
|
||||||
@@ -92,6 +101,7 @@ struct MongoCreateIndexRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoDropIndexesRequest {
|
struct MongoDropIndexesRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
indexes_json: Option<String>,
|
indexes_json: Option<String>,
|
||||||
@@ -101,6 +111,7 @@ struct MongoDropIndexesRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoDropCollectionRequest {
|
struct MongoDropCollectionRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
}
|
}
|
||||||
@@ -108,6 +119,7 @@ struct MongoDropCollectionRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoInsertDocumentsRequest {
|
struct MongoInsertDocumentsRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
docs_json: String,
|
docs_json: String,
|
||||||
@@ -116,6 +128,7 @@ struct MongoInsertDocumentsRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoUpdateDocumentsRequest {
|
struct MongoUpdateDocumentsRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
filter_json: String,
|
filter_json: String,
|
||||||
@@ -126,6 +139,7 @@ struct MongoUpdateDocumentsRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct MongoDeleteDocumentsRequest {
|
struct MongoDeleteDocumentsRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
collection: String,
|
collection: String,
|
||||||
filter_json: String,
|
filter_json: String,
|
||||||
@@ -135,6 +149,7 @@ struct MongoDeleteDocumentsRequest {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct RedisCommandRequest {
|
struct RedisCommandRequest {
|
||||||
connection_name: String,
|
connection_name: String,
|
||||||
|
connection_id: Option<String>,
|
||||||
db: u32,
|
db: u32,
|
||||||
command: String,
|
command: String,
|
||||||
skip_safety_check: Option<bool>,
|
skip_safety_check: Option<bool>,
|
||||||
@@ -295,17 +310,21 @@ async fn respond_error(stream: &mut tokio::net::TcpStream, status: &str, message
|
|||||||
|
|
||||||
async fn resolve_connection(
|
async fn resolve_connection(
|
||||||
state: &Arc<AppState>,
|
state: &Arc<AppState>,
|
||||||
|
connection_id: Option<&str>,
|
||||||
connection_name: &str,
|
connection_name: &str,
|
||||||
) -> Result<crate::models::connection::ConnectionConfig, String> {
|
) -> Result<crate::models::connection::ConnectionConfig, String> {
|
||||||
let configs = state.storage.load_connections().await.map_err(|e| e.to_string())?;
|
let configs = state.storage.load_connections().await.map_err(|e| e.to_string())?;
|
||||||
let config =
|
let config = if let Some(id) = connection_id.filter(|s| !s.is_empty()) {
|
||||||
find_config_by_name(&configs, connection_name).ok_or_else(|| "Connection not found".to_string())?.clone();
|
configs.iter().find(|c| c.id == id).ok_or_else(|| format!("Connection with id '{}' not found", id))?
|
||||||
|
} else {
|
||||||
|
find_config_by_name(&configs, connection_name).ok_or_else(|| "Connection not found".to_string())?
|
||||||
|
};
|
||||||
let mut state_configs = state.configs.write().await;
|
let mut state_configs = state.configs.write().await;
|
||||||
if !state_configs.contains_key(&config.id) {
|
if !state_configs.contains_key(&config.id) {
|
||||||
state_configs.insert(config.id.clone(), config.clone());
|
state_configs.insert(config.id.clone(), config.clone());
|
||||||
}
|
}
|
||||||
drop(state_configs);
|
drop(state_configs);
|
||||||
Ok(config)
|
Ok(config.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_visible_database(config: &crate::models::connection::ConnectionConfig, database: &str) -> Result<(), String> {
|
fn check_visible_database(config: &crate::models::connection::ConnectionConfig, database: &str) -> Result<(), String> {
|
||||||
@@ -319,11 +338,12 @@ fn check_visible_database(config: &crate::models::connection::ConnectionConfig,
|
|||||||
|
|
||||||
async fn resolve_mongo_pool_key(
|
async fn resolve_mongo_pool_key(
|
||||||
state: &Arc<AppState>,
|
state: &Arc<AppState>,
|
||||||
|
connection_id: Option<&str>,
|
||||||
connection_name: &str,
|
connection_name: &str,
|
||||||
database: Option<String>,
|
database: Option<String>,
|
||||||
stream: &mut tokio::net::TcpStream,
|
stream: &mut tokio::net::TcpStream,
|
||||||
) -> Option<(String, String, String)> {
|
) -> Option<(String, String, String)> {
|
||||||
let config = match resolve_connection(state, connection_name).await {
|
let config = match resolve_connection(state, connection_id, connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
respond_error(stream, "404 Not Found", &e).await;
|
respond_error(stream, "404 Not Found", &e).await;
|
||||||
@@ -350,17 +370,13 @@ async fn handle_open_table(app: &AppHandle, state: &Arc<AppState>, body: &str, s
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let configs = match state.storage.load_connections().await {
|
let config = match resolve_connection(state, req.connection_id.as_deref(), &req.connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(_) => {
|
Err(e) => {
|
||||||
respond(stream, "500 Internal Server Error", "").await;
|
respond(stream, "404 Not Found", &e).await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some(config) = find_config_by_name(&configs, &req.connection_name) else {
|
|
||||||
respond(stream, "404 Not Found", "Connection not found").await;
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let event = McpOpenTableEvent {
|
let event = McpOpenTableEvent {
|
||||||
connection_id: config.id.clone(),
|
connection_id: config.id.clone(),
|
||||||
database: req.database.unwrap_or_else(|| config.database.clone().unwrap_or_default()),
|
database: req.database.unwrap_or_else(|| config.database.clone().unwrap_or_default()),
|
||||||
@@ -379,17 +395,13 @@ async fn handle_execute_query(app: &AppHandle, state: &Arc<AppState>, body: &str
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let configs = match state.storage.load_connections().await {
|
let config = match resolve_connection(state, req.connection_id.as_deref(), &req.connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(_) => {
|
Err(e) => {
|
||||||
respond(stream, "500 Internal Server Error", "").await;
|
respond(stream, "404 Not Found", &e).await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some(config) = find_config_by_name(&configs, &req.connection_name) else {
|
|
||||||
respond(stream, "404 Not Found", "Connection not found").await;
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let event = McpExecuteQueryEvent {
|
let event = McpExecuteQueryEvent {
|
||||||
connection_id: config.id.clone(),
|
connection_id: config.id.clone(),
|
||||||
database: req.database.unwrap_or_else(|| config.database.clone().unwrap_or_default()),
|
database: req.database.unwrap_or_else(|| config.database.clone().unwrap_or_default()),
|
||||||
@@ -409,7 +421,7 @@ async fn handle_list_tables_data(state: &Arc<AppState>, body: &str, stream: &mut
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let config = match resolve_connection(state, &req.connection_name).await {
|
let config = match resolve_connection(state, req.connection_id.as_deref(), &req.connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
respond_error(stream, "404 Not Found", &e).await;
|
respond_error(stream, "404 Not Found", &e).await;
|
||||||
@@ -436,7 +448,7 @@ async fn handle_describe_table_data(state: &Arc<AppState>, body: &str, stream: &
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let config = match resolve_connection(state, &req.connection_name).await {
|
let config = match resolve_connection(state, req.connection_id.as_deref(), &req.connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
respond_error(stream, "404 Not Found", &e).await;
|
respond_error(stream, "404 Not Found", &e).await;
|
||||||
@@ -464,7 +476,7 @@ async fn handle_mongo_list_collections_data(state: &Arc<AppState>, body: &str, s
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, _connection_id)) =
|
let Some((pool_key, database, _connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -483,7 +495,7 @@ async fn handle_mongo_find_documents_data(state: &Arc<AppState>, body: &str, str
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, _connection_id)) =
|
let Some((pool_key, database, _connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -514,7 +526,7 @@ async fn handle_mongo_server_version_data(state: &Arc<AppState>, body: &str, str
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, _connection_id)) =
|
let Some((pool_key, database, _connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -533,7 +545,7 @@ async fn handle_mongo_collection_stats_data(state: &Arc<AppState>, body: &str, s
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, _connection_id)) =
|
let Some((pool_key, database, _connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -554,7 +566,7 @@ async fn handle_mongo_aggregate_documents_data(state: &Arc<AppState>, body: &str
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, _connection_id)) =
|
let Some((pool_key, database, _connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -582,7 +594,7 @@ async fn handle_mongo_create_index_data(state: &Arc<AppState>, body: &str, strea
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, connection_id)) =
|
let Some((pool_key, database, connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -614,7 +626,7 @@ async fn handle_mongo_drop_indexes_data(state: &Arc<AppState>, body: &str, strea
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, connection_id)) =
|
let Some((pool_key, database, connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -646,7 +658,7 @@ async fn handle_mongo_drop_collection_data(state: &Arc<AppState>, body: &str, st
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, connection_id)) =
|
let Some((pool_key, database, connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -669,7 +681,7 @@ async fn handle_mongo_insert_documents_data(state: &Arc<AppState>, body: &str, s
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, connection_id)) =
|
let Some((pool_key, database, connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -694,7 +706,7 @@ async fn handle_mongo_update_documents_data(state: &Arc<AppState>, body: &str, s
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, connection_id)) =
|
let Some((pool_key, database, connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -727,7 +739,7 @@ async fn handle_mongo_delete_documents_data(state: &Arc<AppState>, body: &str, s
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some((pool_key, database, connection_id)) =
|
let Some((pool_key, database, connection_id)) =
|
||||||
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
|
resolve_mongo_pool_key(state, req.connection_id.as_deref(), &req.connection_name, req.database, stream).await
|
||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
@@ -758,7 +770,7 @@ async fn handle_redis_execute_command_data(state: &Arc<AppState>, body: &str, st
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let config = match resolve_connection(state, &req.connection_name).await {
|
let config = match resolve_connection(state, req.connection_id.as_deref(), &req.connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
respond_error(stream, "404 Not Found", &e).await;
|
respond_error(stream, "404 Not Found", &e).await;
|
||||||
@@ -809,7 +821,7 @@ async fn handle_execute_query_data(state: &Arc<AppState>, body: &str, stream: &m
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let config = match resolve_connection(state, &req.connection_name).await {
|
let config = match resolve_connection(state, req.connection_id.as_deref(), &req.connection_name).await {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
respond_error(stream, "404 Not Found", &e).await;
|
respond_error(stream, "404 Not Found", &e).await;
|
||||||
|
|||||||
Reference in new issue
Block a user