Skip to content

feat: update the connect tool based on connectivity status #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export enum ErrorCodes {
NotConnectedToMongoDB = 1_000_000,
InvalidParams = 1_000_001,
MisconfiguredConnectionString = 1_000_001,
}

export class MongoDBError extends Error {
Expand Down
5 changes: 2 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#!/usr/bin/env node

import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import logger from "./logger.js";
import { mongoLogId } from "mongodb-log-writer";
import logger, { LogId } from "./logger.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { config } from "./config.js";
import { Session } from "./session.js";
Expand All @@ -29,6 +28,6 @@ try {

await server.connect(transport);
} catch (error: unknown) {
logger.emergency(mongoLogId(1_000_004), "server", `Fatal error running server: ${error as string}`);
logger.emergency(LogId.serverStartFailure, "server", `Fatal error running server: ${error as string}`);
process.exit(1);
}
20 changes: 19 additions & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
import fs from "fs/promises";
import { MongoLogId, MongoLogManager, MongoLogWriter } from "mongodb-log-writer";
import { mongoLogId, MongoLogId, MongoLogManager, MongoLogWriter } from "mongodb-log-writer";
import redact from "mongodb-redact";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { LoggingMessageNotification } from "@modelcontextprotocol/sdk/types.js";

export type LogLevel = LoggingMessageNotification["params"]["level"];

export const LogId = {
serverStartFailure: mongoLogId(1_000_001),
serverInitialized: mongoLogId(1_000_002),

atlasCheckCredentials: mongoLogId(1_001_001),

telemetryDisabled: mongoLogId(1_002_001),
telemetryEmitFailure: mongoLogId(1_002_002),
telemetryEmitStart: mongoLogId(1_002_003),
telemetryEmitSuccess: mongoLogId(1_002_004),

toolExecute: mongoLogId(1_003_001),
toolExecuteFailure: mongoLogId(1_003_002),
toolDisabled: mongoLogId(1_003_003),

mongodbConnectFailure: mongoLogId(1_004_001),
} as const;

abstract class LoggerBase {
abstract log(level: LogLevel, id: MongoLogId, context: string, message: string): void;

Expand Down
33 changes: 29 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import { Session } from "./session.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { AtlasTools } from "./tools/atlas/tools.js";
import { MongoDbTools } from "./tools/mongodb/tools.js";
import logger, { initializeLogger } from "./logger.js";
import { mongoLogId } from "mongodb-log-writer";
import logger, { initializeLogger, LogId } from "./logger.js";
import { ObjectId } from "mongodb";
import { Telemetry } from "./telemetry/telemetry.js";
import { UserConfig } from "./config.js";
Expand All @@ -23,7 +22,7 @@ export class Server {
public readonly session: Session;
private readonly mcpServer: McpServer;
private readonly telemetry: Telemetry;
private readonly userConfig: UserConfig;
public readonly userConfig: UserConfig;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still not super happy with where we are at wrt configs, but this was a stopgap - there were a bunch of places in the tests where we were updating fields in the global config expecting this to be reflected in the server config, which only worked by accident.

private readonly startTime: number;

constructor({ session, mcpServer, userConfig }: ServerOptions) {
Expand Down Expand Up @@ -71,7 +70,7 @@ export class Server {
this.session.sessionId = new ObjectId().toString();

logger.info(
mongoLogId(1_000_004),
LogId.serverInitialized,
"server",
`Server started with transport ${transport.constructor.name} and agent runner ${this.session.agentRunner?.name}`
);
Expand Down Expand Up @@ -135,6 +134,32 @@ export class Server {
}

private registerResources() {
this.mcpServer.resource(
"config",
"config://config",
{
description:
"Server configuration, supplied by the user either as environment variables or as startup arguments",
},
(uri) => {
const result = {
telemetry: this.userConfig.telemetry,
logPath: this.userConfig.logPath,
connectionString: this.userConfig.connectionString
? "set; no explicit connect needed, use switch-connection tool to connect to a different connection if necessary"
: "not set; before using any mongodb tool, you need to call the connect tool with a connection string",
connectOptions: this.userConfig.connectOptions,
Comment on lines +146 to +151
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are the config options we're exposing as a resource

};
return {
contents: [
{
text: JSON.stringify(result),
uri: uri.href,
},
],
};
}
);
if (this.userConfig.connectionString) {
this.mcpServer.resource(
"connection-string",
Expand Down
9 changes: 8 additions & 1 deletion src/session.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
import { ApiClient, ApiClientCredentials } from "./common/atlas/apiClient.js";
import { Implementation } from "@modelcontextprotocol/sdk/types.js";
import EventEmitter from "events";

export interface SessionOptions {
apiBaseUrl?: string;
apiClientId?: string;
apiClientSecret?: string;
}

export class Session {
export class Session extends EventEmitter<{
close: [];
}> {
sessionId?: string;
serviceProvider?: NodeDriverServiceProvider;
apiClient: ApiClient;
Expand All @@ -18,6 +21,8 @@ export class Session {
};

constructor({ apiBaseUrl, apiClientId, apiClientSecret }: SessionOptions = {}) {
super();

const credentials: ApiClientCredentials | undefined =
apiClientId && apiClientSecret
? {
Expand Down Expand Up @@ -49,6 +54,8 @@ export class Session {
console.error("Error closing service provider:", error);
}
this.serviceProvider = undefined;

this.emit("close");
}
}
}
13 changes: 6 additions & 7 deletions src/telemetry/telemetry.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Session } from "../session.js";
import { BaseEvent, CommonProperties } from "./types.js";
import { config } from "../config.js";
import logger from "../logger.js";
import { mongoLogId } from "mongodb-log-writer";
import logger, { LogId } from "../logger.js";
import { ApiClient } from "../common/atlas/apiClient.js";
import { MACHINE_METADATA } from "./constants.js";
import { EventCache } from "./eventCache.js";
Expand Down Expand Up @@ -61,7 +60,7 @@ export class Telemetry {

await this.emit(events);
} catch {
logger.debug(mongoLogId(1_000_002), "telemetry", `Error emitting telemetry events.`);
logger.debug(LogId.telemetryEmitFailure, "telemetry", `Error emitting telemetry events.`);
}
}

Expand Down Expand Up @@ -89,20 +88,20 @@ export class Telemetry {
const allEvents = [...cachedEvents, ...events];

logger.debug(
mongoLogId(1_000_003),
LogId.telemetryEmitStart,
"telemetry",
`Attempting to send ${allEvents.length} events (${cachedEvents.length} cached)`
);

const result = await this.sendEvents(this.session.apiClient, allEvents);
if (result.success) {
this.eventCache.clearEvents();
logger.debug(mongoLogId(1_000_004), "telemetry", `Sent ${allEvents.length} events successfully`);
logger.debug(LogId.telemetryEmitSuccess, "telemetry", `Sent ${allEvents.length} events successfully`);
return;
}

logger.warning(
mongoLogId(1_000_005),
logger.debug(
LogId.telemetryEmitFailure,
"telemetry",
`Error sending event to client: ${result.error instanceof Error ? result.error.message : String(result.error)}`
);
Expand Down
153 changes: 78 additions & 75 deletions src/tools/mongodb/metadata/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,92 +2,95 @@ import { z } from "zod";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { MongoDBToolBase } from "../mongodbTool.js";
import { ToolArgs, OperationType } from "../../tool.js";
import { MongoError as DriverError } from "mongodb";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import assert from "assert";
import { UserConfig } from "../../../config.js";
import { Telemetry } from "../../../telemetry/telemetry.js";
import { Session } from "../../../session.js";

const disconnectedSchema = z
.object({
connectionString: z.string().describe("MongoDB connection string (in the mongodb:// or mongodb+srv:// format)"),
})
.describe("Options for connecting to MongoDB.");

const connectedSchema = z
.object({
connectionString: z
.string()
.optional()
.describe("MongoDB connection string to switch to (in the mongodb:// or mongodb+srv:// format)"),
})
.describe(
"Options for switching the current MongoDB connection. If a connection string is not provided, the connection string from the config will be used."
);

const connectedName = "switch-connection" as const;
const disconnectedName = "connect" as const;

const connectedDescription =
"Switch to a different MongoDB connection. If the user has configured a connection string or has previously called the connect tool, a connection is already established and there's no need to call this tool unless the user has explicitly requested to switch to a new instance.";
const disconnectedDescription = "Connect to a MongoDB instance";

export class ConnectTool extends MongoDBToolBase {
protected name = "connect";
protected description = "Connect to a MongoDB instance";
protected name: typeof connectedName | typeof disconnectedName = disconnectedName;
protected description: typeof connectedDescription | typeof disconnectedDescription = disconnectedDescription;

// Here the default is empty just to trigger registration, but we're going to override it with the correct
// schema in the register method.
protected argsShape = {
options: z
.array(
z
.union([
z.object({
connectionString: z
.string()
.describe("MongoDB connection string (in the mongodb:// or mongodb+srv:// format)"),
}),
z.object({
clusterName: z.string().describe("MongoDB cluster name"),
}),
])
.optional()
)
.optional()
.describe(
"Options for connecting to MongoDB. If not provided, the connection string from the config://connection-string resource will be used. If the user hasn't specified Atlas cluster name or a connection string explicitly and the `config://connection-string` resource is present, always invoke this with no arguments."
),
connectionString: z.string().optional(),
};

protected operationType: OperationType = "metadata";

protected async execute({ options: optionsArr }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const options = optionsArr?.[0];
let connectionString: string;
if (!options && !this.config.connectionString) {
return {
content: [
{ type: "text", text: "No connection details provided." },
{ type: "text", text: "Please provide either a connection string or a cluster name" },
],
};
}
constructor(session: Session, config: UserConfig, telemetry: Telemetry) {
super(session, config, telemetry);
session.on("close", () => {
this.updateMetadata();
});
}

if (!options) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
connectionString = this.config.connectionString!;
} else if ("connectionString" in options) {
connectionString = options.connectionString;
} else {
// TODO: https://github.com/mongodb-js/mongodb-mcp-server/issues/19
// We don't support connecting via cluster name since we'd need to obtain the user credentials
// and fill in the connection string.
return {
content: [
{
type: "text",
text: `Connecting via cluster name not supported yet. Please provide a connection string.`,
},
],
};
protected async execute({ connectionString }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
switch (this.name) {
case disconnectedName:
assert(connectionString, "Connection string is required");
break;
case connectedName:
connectionString ??= this.config.connectionString;
assert(
connectionString,
"Cannot switch to a new connection because no connection string was provided and no default connection string is configured."
);
break;
}

try {
await this.connectToMongoDB(connectionString);
return {
content: [{ type: "text", text: `Successfully connected to ${connectionString}.` }],
};
} catch (error) {
// Sometimes the model will supply an incorrect connection string. If the user has configured
// a different one as environment variable or a cli argument, suggest using that one instead.
if (
this.config.connectionString &&
error instanceof DriverError &&
this.config.connectionString !== connectionString
) {
return {
content: [
{
type: "text",
text:
`Failed to connect to MongoDB at '${connectionString}' due to error: '${error.message}.` +
`Your config lists a different connection string: '${this.config.connectionString}' - do you want to try connecting to it instead?`,
},
],
};
}
await this.connectToMongoDB(connectionString);
this.updateMetadata();
return {
content: [{ type: "text", text: "Successfully connected to MongoDB." }],
};
}

public register(server: McpServer): void {
super.register(server);

throw error;
this.updateMetadata();
}

private updateMetadata(): void {
if (this.config.connectionString || this.session.serviceProvider) {
this.update?.({
name: connectedName,
description: connectedDescription,
inputSchema: connectedSchema,
});
} else {
this.update?.({
name: disconnectedName,
description: disconnectedDescription,
inputSchema: disconnectedSchema,
});
}
}
}
Loading