• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mongodb-js / mongodb-mcp-server / 21630713045

03 Feb 2026 12:44PM UTC coverage: 82.301% (-0.01%) from 82.311%
21630713045

push

github

web-flow
fix: warn on insecure apiBaseUrl (#893)

1641 of 2107 branches covered (77.88%)

Branch coverage included in aggregate %.

12 of 18 new or added lines in 2 files covered. (66.67%)

2 existing lines in 1 file now uncovered.

7501 of 9001 relevant lines covered (83.34%)

118.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.05
/src/server.ts
1
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
import type { Session } from "./common/session.js";
3
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
4
import { Resources } from "./resources/resources.js";
3✔
5
import type { LogLevel } from "./common/logger.js";
6
import { LogId, McpLogger } from "./common/logger.js";
3✔
7
import type { Telemetry } from "./telemetry/telemetry.js";
8
import type { UserConfig } from "./common/config/userConfig.js";
9
import { type ServerEvent } from "./telemetry/types.js";
10
import { type ServerCommand } from "./telemetry/types.js";
11
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
12
import {
3✔
13
    CallToolRequestSchema,
14
    SetLevelRequestSchema,
15
    SubscribeRequestSchema,
16
    UnsubscribeRequestSchema,
17
} from "@modelcontextprotocol/sdk/types.js";
18
import type { ToolBase, ToolCategory, ToolClass } from "./tools/tool.js";
19
import { validateConnectionString } from "./helpers/connectionOptions.js";
3✔
20
import { packageInfo } from "./common/packageInfo.js";
3✔
21
import { type ConnectionErrorHandler } from "./common/connectionErrorHandler.js";
22
import type { Elicitation } from "./elicitation.js";
23
import { AllTools } from "./tools/index.js";
3✔
24
import type { UIRegistry } from "./ui/registry/index.js";
25

26
export interface ServerOptions {
27
    session: Session;
28
    userConfig: UserConfig;
29
    mcpServer: McpServer;
30
    telemetry: Telemetry;
31
    elicitation: Elicitation;
32
    connectionErrorHandler: ConnectionErrorHandler;
33
    uiRegistry?: UIRegistry;
34
    /**
35
     * Custom tool constructors to register with the server.
36
     * This will override any default tools. You can use both existing and custom tools by using the `mongodb-mcp-server/tools` export.
37
     *
38
     * ```ts
39
     * import { AllTools, ToolBase, type ToolCategory, type OperationType } from "mongodb-mcp-server/tools";
40
     * class CustomTool extends ToolBase {
41
     *     override name = "custom_tool";
42
     *     static category: ToolCategory = "mongodb";
43
     *     static operationType: OperationType = "read";
44
     *     public description = "Custom tool description";
45
     *     public argsShape = {};
46
     *     protected async execute() {
47
     *         return { content: [{ type: "text", text: "Result" }] };
48
     *     }
49
     *     protected resolveTelemetryMetadata() {
50
     *         return {};
51
     *     }
52
     * }
53
     * const server = new Server({
54
     *     session: mySession,
55
     *     userConfig: myUserConfig,
56
     *     mcpServer: myMcpServer,
57
     *     telemetry: myTelemetry,
58
     *     elicitation: myElicitation,
59
     *     connectionErrorHandler: myConnectionErrorHandler,
60
     *     tools: [...AllTools, CustomTool],
61
     * });
62
     * ```
63
     */
64
    tools?: ToolClass[];
65
}
66

67
export class Server {
3✔
68
    public readonly session: Session;
69
    public readonly mcpServer: McpServer;
70
    private readonly telemetry: Telemetry;
71
    public readonly userConfig: UserConfig;
72
    public readonly elicitation: Elicitation;
73
    private readonly toolConstructors: ToolClass[];
74
    public readonly tools: ToolBase[] = [];
3✔
75
    public readonly connectionErrorHandler: ConnectionErrorHandler;
76
    public readonly uiRegistry?: UIRegistry;
77

78
    private _mcpLogLevel: LogLevel = "debug";
3✔
79

80
    public get mcpLogLevel(): LogLevel {
3✔
81
        return this._mcpLogLevel;
3✔
82
    }
3✔
83

84
    private readonly startTime: number;
85
    private readonly subscriptions = new Set<string>();
3✔
86

87
    constructor({
3✔
88
        session,
175✔
89
        mcpServer,
175✔
90
        userConfig,
175✔
91
        telemetry,
175✔
92
        connectionErrorHandler,
175✔
93
        elicitation,
175✔
94
        tools,
175✔
95
        uiRegistry,
175✔
96
    }: ServerOptions) {
175✔
97
        this.startTime = Date.now();
175✔
98
        this.session = session;
175✔
99
        this.telemetry = telemetry;
175✔
100
        this.mcpServer = mcpServer;
175✔
101
        this.userConfig = userConfig;
175✔
102
        this.elicitation = elicitation;
175✔
103
        this.connectionErrorHandler = connectionErrorHandler;
175✔
104
        this.toolConstructors = tools ?? AllTools;
175✔
105
        this.uiRegistry = uiRegistry;
175✔
106
    }
175✔
107

108
    async connect(transport: Transport): Promise<void> {
3✔
109
        await this.validateConfig();
166✔
110
        // Register resources after the server is initialized so they can listen to events like
111
        // connection events.
112
        this.registerResources();
166✔
113
        this.mcpServer.server.registerCapabilities({
166✔
114
            logging: {},
166✔
115
            resources: { listChanged: true, subscribe: true },
166✔
116
        });
166✔
117

118
        // TODO: Eventually we might want to make tools reactive too instead of relying on custom logic.
119
        this.registerTools();
166✔
120

121
        // This is a workaround for an issue we've seen with some models, where they'll see that everything in the `arguments`
122
        // object is optional, and then not pass it at all. However, the MCP server expects the `arguments` object to be if
123
        // the tool accepts any arguments, even if they're all optional.
124
        //
125
        // see: https://github.com/modelcontextprotocol/typescript-sdk/blob/131776764536b5fdca642df51230a3746fb4ade0/src/server/mcp.ts#L705
126
        // Since paramsSchema here is not undefined, the server will create a non-optional z.object from it.
127
        const existingHandler = (
166✔
128
            this.mcpServer.server["_requestHandlers"] as Map<
166✔
129
                string,
130
                (request: unknown, extra: unknown) => Promise<CallToolResult>
131
            >
132
        ).get(CallToolRequestSchema.shape.method.value);
166✔
133

134
        if (!existingHandler) {
166!
135
            throw new Error("No existing handler found for CallToolRequestSchema");
×
136
        }
✔
137

138
        this.mcpServer.server.setRequestHandler(CallToolRequestSchema, (request, extra): Promise<CallToolResult> => {
165✔
139
            if (!request.params.arguments) {
945!
140
                request.params.arguments = {};
1✔
141
            }
1✔
142

143
            return existingHandler(request, extra);
945✔
144
        });
165✔
145

146
        this.mcpServer.server.setRequestHandler(SubscribeRequestSchema, ({ params }) => {
165✔
147
            this.subscriptions.add(params.uri);
20✔
148
            this.session.logger.debug({
20✔
149
                id: LogId.serverInitialized,
20✔
150
                context: "resources",
20✔
151
                message: `Client subscribed to resource: ${params.uri}`,
20✔
152
            });
20✔
153
            return {};
20✔
154
        });
165✔
155

156
        this.mcpServer.server.setRequestHandler(UnsubscribeRequestSchema, ({ params }) => {
165✔
157
            this.subscriptions.delete(params.uri);
×
158
            this.session.logger.debug({
×
159
                id: LogId.serverInitialized,
×
160
                context: "resources",
×
161
                message: `Client unsubscribed from resource: ${params.uri}`,
×
162
            });
×
163
            return {};
×
164
        });
165✔
165

166
        this.mcpServer.server.setRequestHandler(SetLevelRequestSchema, ({ params }) => {
165✔
167
            if (!McpLogger.LOG_LEVELS.includes(params.level)) {
×
168
                throw new Error(`Invalid log level: ${params.level}`);
×
169
            }
×
170

171
            this._mcpLogLevel = params.level;
×
172
            return {};
×
173
        });
165✔
174

175
        this.mcpServer.server.oninitialized = (): void => {
165✔
176
            this.session.setMcpClient(this.mcpServer.server.getClientVersion());
145✔
177
            // Placed here to start the connection to the config connection string as soon as the server is initialized.
178
            void this.connectToConfigConnectionString();
145✔
179
            this.session.logger.info({
145✔
180
                id: LogId.serverInitialized,
145✔
181
                context: "server",
145✔
182
                message: `Server with version ${packageInfo.version} started with transport ${transport.constructor.name} and agent runner ${JSON.stringify(this.session.mcpClient)}`,
145✔
183
            });
145✔
184

185
            this.emitServerTelemetryEvent("start", Date.now() - this.startTime);
145✔
186
        };
145✔
187

188
        this.mcpServer.server.onclose = (): void => {
165✔
189
            const closeTime = Date.now();
161✔
190
            this.emitServerTelemetryEvent("stop", Date.now() - closeTime);
161✔
191
        };
161✔
192

193
        this.mcpServer.server.onerror = (error: Error): void => {
165✔
194
            const closeTime = Date.now();
×
195
            this.emitServerTelemetryEvent("stop", Date.now() - closeTime, error);
×
196
        };
×
197

198
        await this.mcpServer.connect(transport);
165✔
199
    }
166✔
200

201
    async close(): Promise<void> {
3✔
202
        await this.telemetry.close();
167✔
203
        await this.session.close();
167✔
204
        await this.mcpServer.close();
167✔
205
    }
167✔
206

207
    public sendResourceListChanged(): void {
3✔
208
        this.mcpServer.sendResourceListChanged();
1,052✔
209
    }
1,052✔
210

211
    public isToolCategoryAvailable(name: ToolCategory): boolean {
3✔
212
        return !!this.tools.filter((t) => t.category === name).length;
2✔
213
    }
2✔
214

215
    public sendResourceUpdated(uri: string): void {
3✔
216
        this.session.logger.info({
1,052✔
217
            id: LogId.resourceUpdateFailure,
1,052✔
218
            context: "resources",
1,052✔
219
            message: `Resource updated: ${uri}`,
1,052✔
220
        });
1,052✔
221

222
        if (this.subscriptions.has(uri)) {
1,052!
223
            void this.mcpServer.server.sendResourceUpdated({ uri });
20✔
224
        }
20✔
225
    }
1,052✔
226

227
    private emitServerTelemetryEvent(command: ServerCommand, commandDuration: number, error?: Error): void {
3✔
228
        const event: ServerEvent = {
306✔
229
            timestamp: new Date().toISOString(),
306✔
230
            source: "mdbmcp",
306✔
231
            properties: {
306✔
232
                result: "success",
306✔
233
                duration_ms: commandDuration,
306✔
234
                component: "server",
306✔
235
                category: "other",
306✔
236
                command: command,
306✔
237
            },
306✔
238
        };
306✔
239

240
        if (command === "start") {
306✔
241
            event.properties.startup_time_ms = commandDuration;
145✔
242
            event.properties.read_only_mode = this.userConfig.readOnly ? "true" : "false";
145!
243
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
145!
244
            event.properties.confirmation_required_tools = this.userConfig.confirmationRequiredTools || [];
145!
245
            event.properties.previewFeatures = this.userConfig.previewFeatures;
145✔
246
            event.properties.embeddingProviderConfigured = !!this.userConfig.voyageApiKey;
145✔
247
        }
145✔
248
        if (command === "stop") {
306✔
249
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
161✔
250
            if (error) {
161!
251
                event.properties.result = "failure";
×
252
                event.properties.reason = error.message;
×
253
            }
×
254
        }
161✔
255

256
        this.telemetry.emitEvents([event]);
306✔
257
    }
306✔
258

259
    public registerTools(): void {
3✔
260
        for (const toolConstructor of this.toolConstructors) {
166✔
261
            const tool = new toolConstructor({
6,160✔
262
                category: toolConstructor.category,
6,160✔
263
                operationType: toolConstructor.operationType,
6,160✔
264
                session: this.session,
6,160✔
265
                config: this.userConfig,
6,160✔
266
                telemetry: this.telemetry,
6,160✔
267
                elicitation: this.elicitation,
6,160✔
268
                uiRegistry: this.uiRegistry,
6,160✔
269
            });
6,160✔
270
            if (tool.register(this)) {
6,160✔
271
                this.tools.push(tool);
4,379✔
272
            }
4,379✔
273
        }
6,160✔
274
    }
166✔
275

276
    public registerResources(): void {
3✔
277
        for (const resourceConstructor of Resources) {
166✔
278
            const resource = new resourceConstructor(this.session, this.userConfig, this.telemetry);
498✔
279
            resource.register(this);
498✔
280
        }
498✔
281
    }
166✔
282

283
    private async validateConfig(): Promise<void> {
3✔
284
        // Validate connection string
285
        if (this.userConfig.connectionString) {
166!
286
            try {
8✔
287
                validateConnectionString(this.userConfig.connectionString, false);
8✔
288
            } catch (error) {
8!
289
                throw new Error(
×
290
                    "Connection string validation failed with error: " +
×
291
                        (error instanceof Error ? error.message : String(error))
×
292
                );
×
293
            }
×
294
        }
8✔
295

296
        // Validate API client credentials
297
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
166!
298
            try {
14✔
299
                if (!this.session.apiClient) {
14!
300
                    throw new Error("API client is not available.");
×
301
                }
×
302

303
                try {
14✔
304
                    const apiBaseUrl = new URL(this.userConfig.apiBaseUrl);
14✔
305
                    if (apiBaseUrl.protocol !== "https:") {
14!
306
                        // Log a warning, but don't error out. This is to allow for testing against local or non-HTTPS endpoints.
307
                        const message = `apiBaseUrl is configured to use ${apiBaseUrl.protocol}, which is not secure. It is strongly recommended to use HTTPS for secure communication.`;
1✔
308
                        this.session.logger.warning({
1✔
309
                            id: LogId.atlasApiBaseUrlInsecure,
1✔
310
                            context: "server",
1✔
311
                            message,
1✔
312
                        });
1✔
313
                    }
1✔
314
                } catch (error) {
14!
NEW
315
                    throw new Error(`Invalid apiBaseUrl: ${error instanceof Error ? error.message : String(error)}`);
×
UNCOV
316
                }
×
317

318
                await this.session.apiClient.validateAuthConfig();
14✔
319
            } catch (error) {
14!
320
                if (this.userConfig.connectionString === undefined) {
×
321
                    throw new Error(
×
322
                        `Failed to connect to MongoDB Atlas instance using the credentials from the config: ${error instanceof Error ? error.message : String(error)}`
×
323
                    );
×
324
                }
×
325

NEW
326
                this.session.logger.warning({
×
NEW
327
                    id: LogId.atlasCheckCredentials,
×
NEW
328
                    context: "server",
×
NEW
329
                    message: `Failed to validate MongoDB Atlas API client credentials from the config: ${error instanceof Error ? error.message : String(error)}. Continuing since a connection string is also provided.`,
×
NEW
330
                });
×
UNCOV
331
            }
×
332
        }
14✔
333
    }
166✔
334

335
    private async connectToConfigConnectionString(): Promise<void> {
3✔
336
        if (this.userConfig.connectionString) {
145!
337
            try {
8✔
338
                this.session.logger.info({
8✔
339
                    id: LogId.mongodbConnectTry,
8✔
340
                    context: "server",
8✔
341
                    message: `Detected a MongoDB connection string in the configuration, trying to connect...`,
8✔
342
                });
8✔
343
                await this.session.connectToConfiguredConnection();
8✔
344
            } catch (error) {
8✔
345
                // We don't throw an error here because we want to allow the server to start even if the connection string is invalid.
346
                this.session.logger.error({
2✔
347
                    id: LogId.mongodbConnectFailure,
2✔
348
                    context: "server",
2✔
349
                    message: `Failed to connect to MongoDB instance using the connection string from the config: ${error instanceof Error ? error.message : String(error)}`,
2!
350
                });
2✔
351
            }
2✔
352
        }
8✔
353
    }
145✔
354
}
3✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc