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

mongodb-js / mongodb-mcp-server / 20852798965

09 Jan 2026 01:03PM UTC coverage: 79.538% (-0.1%) from 79.647%
20852798965

Pull #837

github

web-flow
Merge 9b3bafc92 into 7043c219d
Pull Request #837: chore: minimize node-specific API usage

1509 of 1967 branches covered (76.72%)

Branch coverage included in aggregate %.

13 of 25 new or added lines in 5 files covered. (52.0%)

19 existing lines in 2 files now uncovered.

6899 of 8604 relevant lines covered (80.18%)

89.32 hits per line

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

78.88
/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 assert from "assert";
19
import type { ToolBase, ToolCategory, ToolClass } from "./tools/tool.js";
20
import { validateConnectionString } from "./helpers/connectionOptions.js";
3✔
21
import { packageInfo } from "./common/packageInfo.js";
3✔
22
import { type ConnectionErrorHandler } from "./common/connectionErrorHandler.js";
23
import type { Elicitation } from "./elicitation.js";
24
import { AllTools } from "./tools/index.js";
3✔
25
import { UIRegistry } from "./ui/registry/index.js";
3✔
26

27
export interface ServerOptions {
28
    session: Session;
29
    userConfig: UserConfig;
30
    mcpServer: McpServer;
31
    telemetry: Telemetry;
32
    elicitation: Elicitation;
33
    connectionErrorHandler: ConnectionErrorHandler;
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
     * Custom UIs for tools. Function that returns HTML strings for tool names.
67
     * Use this to add UIs to tools or replace the default bundled UIs.
68
     * The function is called lazily when a UI is requested, allowing you to
69
     * defer loading large HTML files until needed.
70
     *
71
     * ```ts
72
     * import { readFileSync } from 'fs';
73
     * const server = new Server({
74
     *     // ... other options
75
     *     customUIs: (toolName) => {
76
     *         if (toolName === 'list-databases') {
77
     *             return readFileSync('./my-custom-ui.html', 'utf-8');
78
     *         }
79
     *         return null;
80
     *     }
81
     * });
82
     * ```
83
     */
84
    customUIs?: (toolName: string) => string | null | Promise<string | null>;
85
}
86

87
export class Server {
3✔
88
    public readonly session: Session;
89
    public readonly mcpServer: McpServer;
90
    private readonly telemetry: Telemetry;
91
    public readonly userConfig: UserConfig;
92
    public readonly elicitation: Elicitation;
93
    private readonly toolConstructors: ToolClass[];
94
    public readonly tools: ToolBase[] = [];
3✔
95
    public readonly connectionErrorHandler: ConnectionErrorHandler;
96
    public readonly uiRegistry: UIRegistry;
97

98
    private _mcpLogLevel: LogLevel = "debug";
3✔
99

100
    public get mcpLogLevel(): LogLevel {
3✔
101
        return this._mcpLogLevel;
3✔
102
    }
3✔
103

104
    private readonly startTime: number;
105
    private readonly subscriptions = new Set<string>();
3✔
106

107
    constructor({
3✔
108
        session,
133✔
109
        mcpServer,
133✔
110
        userConfig,
133✔
111
        telemetry,
133✔
112
        connectionErrorHandler,
133✔
113
        elicitation,
133✔
114
        tools,
133✔
115
        customUIs,
133✔
116
    }: ServerOptions) {
133✔
117
        this.startTime = Date.now();
133✔
118
        this.session = session;
133✔
119
        this.telemetry = telemetry;
133✔
120
        this.mcpServer = mcpServer;
133✔
121
        this.userConfig = userConfig;
133✔
122
        this.elicitation = elicitation;
133✔
123
        this.connectionErrorHandler = connectionErrorHandler;
133✔
124
        this.toolConstructors = tools ?? AllTools;
133✔
125
        this.uiRegistry = new UIRegistry({ customUIs });
133✔
126
    }
133✔
127

128
    async connect(transport: Transport): Promise<void> {
3✔
129
        await this.validateConfig();
129✔
130
        // Register resources after the server is initialized so they can listen to events like
131
        // connection events.
132
        this.registerResources();
129✔
133
        this.mcpServer.server.registerCapabilities({
129✔
134
            logging: {},
129✔
135
            resources: { listChanged: true, subscribe: true },
129✔
136
        });
129✔
137

138
        // TODO: Eventually we might want to make tools reactive too instead of relying on custom logic.
139
        this.registerTools();
129✔
140

141
        // This is a workaround for an issue we've seen with some models, where they'll see that everything in the `arguments`
142
        // object is optional, and then not pass it at all. However, the MCP server expects the `arguments` object to be if
143
        // the tool accepts any arguments, even if they're all optional.
144
        //
145
        // see: https://github.com/modelcontextprotocol/typescript-sdk/blob/131776764536b5fdca642df51230a3746fb4ade0/src/server/mcp.ts#L705
146
        // Since paramsSchema here is not undefined, the server will create a non-optional z.object from it.
147
        const existingHandler = (
129✔
148
            this.mcpServer.server["_requestHandlers"] as Map<
129✔
149
                string,
150
                (request: unknown, extra: unknown) => Promise<CallToolResult>
151
            >
152
        ).get(CallToolRequestSchema.shape.method.value);
129✔
153

154
        if (!existingHandler) {
129!
NEW
155
            throw new Error("No existing handler found for CallToolRequestSchema");
×
UNCOV
156
        }
✔
157

158
        this.mcpServer.server.setRequestHandler(CallToolRequestSchema, (request, extra): Promise<CallToolResult> => {
128✔
159
            if (!request.params.arguments) {
751!
160
                request.params.arguments = {};
1✔
161
            }
1✔
162

163
            return existingHandler(request, extra);
751✔
164
        });
128✔
165

166
        this.mcpServer.server.setRequestHandler(SubscribeRequestSchema, ({ params }) => {
128✔
167
            this.subscriptions.add(params.uri);
20✔
168
            this.session.logger.debug({
20✔
169
                id: LogId.serverInitialized,
20✔
170
                context: "resources",
20✔
171
                message: `Client subscribed to resource: ${params.uri}`,
20✔
172
            });
20✔
173
            return {};
20✔
174
        });
128✔
175

176
        this.mcpServer.server.setRequestHandler(UnsubscribeRequestSchema, ({ params }) => {
128✔
177
            this.subscriptions.delete(params.uri);
×
178
            this.session.logger.debug({
×
179
                id: LogId.serverInitialized,
×
180
                context: "resources",
×
181
                message: `Client unsubscribed from resource: ${params.uri}`,
×
182
            });
×
UNCOV
183
            return {};
×
184
        });
128✔
185

186
        this.mcpServer.server.setRequestHandler(SetLevelRequestSchema, ({ params }) => {
128✔
187
            if (!McpLogger.LOG_LEVELS.includes(params.level)) {
×
188
                throw new Error(`Invalid log level: ${params.level}`);
×
UNCOV
189
            }
×
190

191
            this._mcpLogLevel = params.level;
×
UNCOV
192
            return {};
×
193
        });
128✔
194

195
        this.mcpServer.server.oninitialized = (): void => {
128✔
196
            this.session.setMcpClient(this.mcpServer.server.getClientVersion());
122✔
197
            // Placed here to start the connection to the config connection string as soon as the server is initialized.
198
            void this.connectToConfigConnectionString();
122✔
199
            this.session.logger.info({
122✔
200
                id: LogId.serverInitialized,
122✔
201
                context: "server",
122✔
202
                message: `Server with version ${packageInfo.version} started with transport ${transport.constructor.name} and agent runner ${JSON.stringify(this.session.mcpClient)}`,
122✔
203
            });
122✔
204

205
            this.emitServerTelemetryEvent("start", Date.now() - this.startTime);
122✔
206
        };
122✔
207

208
        this.mcpServer.server.onclose = (): void => {
128✔
209
            const closeTime = Date.now();
124✔
210
            this.emitServerTelemetryEvent("stop", Date.now() - closeTime);
124✔
211
        };
124✔
212

213
        this.mcpServer.server.onerror = (error: Error): void => {
128✔
214
            const closeTime = Date.now();
×
215
            this.emitServerTelemetryEvent("stop", Date.now() - closeTime, error);
×
UNCOV
216
        };
×
217

218
        await this.mcpServer.connect(transport);
128✔
219
    }
129✔
220

221
    async close(): Promise<void> {
3✔
222
        await this.telemetry.close();
123✔
223
        await this.session.close();
120✔
224
        await this.mcpServer.close();
120✔
225
    }
123✔
226

227
    public sendResourceListChanged(): void {
3✔
228
        this.mcpServer.sendResourceListChanged();
810✔
229
    }
810✔
230

231
    public isToolCategoryAvailable(name: ToolCategory): boolean {
3✔
232
        return !!this.tools.filter((t) => t.category === name).length;
2✔
233
    }
2✔
234

235
    public sendResourceUpdated(uri: string): void {
3✔
236
        this.session.logger.info({
810✔
237
            id: LogId.resourceUpdateFailure,
810✔
238
            context: "resources",
810✔
239
            message: `Resource updated: ${uri}`,
810✔
240
        });
810✔
241

242
        if (this.subscriptions.has(uri)) {
810!
243
            void this.mcpServer.server.sendResourceUpdated({ uri });
20✔
244
        }
20✔
245
    }
810✔
246

247
    private emitServerTelemetryEvent(command: ServerCommand, commandDuration: number, error?: Error): void {
3✔
248
        const event: ServerEvent = {
246✔
249
            timestamp: new Date().toISOString(),
246✔
250
            source: "mdbmcp",
246✔
251
            properties: {
246✔
252
                result: "success",
246✔
253
                duration_ms: commandDuration,
246✔
254
                component: "server",
246✔
255
                category: "other",
246✔
256
                command: command,
246✔
257
            },
246✔
258
        };
246✔
259

260
        if (command === "start") {
246✔
261
            event.properties.startup_time_ms = commandDuration;
122✔
262
            event.properties.read_only_mode = this.userConfig.readOnly ? "true" : "false";
122!
263
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
122!
264
            event.properties.confirmation_required_tools = this.userConfig.confirmationRequiredTools || [];
122!
265
            event.properties.previewFeatures = this.userConfig.previewFeatures;
122✔
266
            event.properties.embeddingProviderConfigured = !!this.userConfig.voyageApiKey;
122✔
267
        }
122✔
268
        if (command === "stop") {
246✔
269
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
124✔
270
            if (error) {
124!
271
                event.properties.result = "failure";
×
272
                event.properties.reason = error.message;
×
UNCOV
273
            }
×
274
        }
124✔
275

276
        this.telemetry.emitEvents([event]);
246✔
277
    }
246✔
278

279
    public registerTools(): void {
3✔
280
        for (const toolConstructor of this.toolConstructors) {
129✔
281
            const tool = new toolConstructor({
4,719✔
282
                category: toolConstructor.category,
4,719✔
283
                operationType: toolConstructor.operationType,
4,719✔
284
                session: this.session,
4,719✔
285
                config: this.userConfig,
4,719✔
286
                telemetry: this.telemetry,
4,719✔
287
                elicitation: this.elicitation,
4,719✔
288
                uiRegistry: this.uiRegistry,
4,719✔
289
            });
4,719✔
290
            if (tool.register(this)) {
4,719✔
291
                this.tools.push(tool);
3,406✔
292
            }
3,406✔
293
        }
4,719✔
294
    }
129✔
295

296
    public registerResources(): void {
3✔
297
        for (const resourceConstructor of Resources) {
129✔
298
            const resource = new resourceConstructor(this.session, this.userConfig, this.telemetry);
387✔
299
            resource.register(this);
387✔
300
        }
387✔
301
    }
129✔
302

303
    private async validateConfig(): Promise<void> {
3✔
304
        // Validate connection string
305
        if (this.userConfig.connectionString) {
129!
306
            try {
8✔
307
                validateConnectionString(this.userConfig.connectionString, false);
8✔
308
            } catch (error) {
8!
309
                console.error("Connection string validation failed with error: ", error);
×
310
                throw new Error(
×
311
                    "Connection string validation failed with error: " +
×
312
                        (error instanceof Error ? error.message : String(error))
×
313
                );
×
UNCOV
314
            }
×
315
        }
8✔
316

317
        // Validate API client credentials
318
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
129!
319
            try {
13✔
320
                if (!this.userConfig.apiBaseUrl.startsWith("https://")) {
13!
321
                    const message =
×
322
                        "Failed to validate MongoDB Atlas the credentials from config: apiBaseUrl must start with https://";
×
323
                    console.error(message);
×
324
                    throw new Error(message);
×
UNCOV
325
                }
×
326

327
                await this.session.apiClient.validateAccessToken();
13✔
328
            } catch (error) {
13!
329
                if (this.userConfig.connectionString === undefined) {
×
UNCOV
330
                    console.error("Failed to validate MongoDB Atlas the credentials from the config: ", error);
×
331

332
                    throw new Error(
×
333
                        "Failed to connect to MongoDB Atlas instance using the credentials from the config"
×
334
                    );
×
335
                }
×
336
                console.error(
×
337
                    "Failed to validate MongoDB Atlas the credentials from the config, but validated the connection string."
×
338
                );
×
UNCOV
339
            }
×
340
        }
13✔
341
    }
129✔
342

343
    private async connectToConfigConnectionString(): Promise<void> {
3✔
344
        if (this.userConfig.connectionString) {
122!
345
            try {
8✔
346
                this.session.logger.info({
8✔
347
                    id: LogId.mongodbConnectTry,
8✔
348
                    context: "server",
8✔
349
                    message: `Detected a MongoDB connection string in the configuration, trying to connect...`,
8✔
350
                });
8✔
351
                await this.session.connectToConfiguredConnection();
8✔
352
            } catch (error) {
8✔
353
                // We don't throw an error here because we want to allow the server to start even if the connection string is invalid.
354
                this.session.logger.error({
2✔
355
                    id: LogId.mongodbConnectFailure,
2✔
356
                    context: "server",
2✔
357
                    message: `Failed to connect to MongoDB instance using the connection string from the config: ${error instanceof Error ? error.message : String(error)}`,
2!
358
                });
2✔
359
            }
2✔
360
        }
8✔
361
    }
122✔
362
}
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