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

mongodb-js / mongodb-mcp-server / 17759877157

16 Sep 2025 08:35AM UTC coverage: 82.063% (+0.5%) from 81.531%
17759877157

push

github

web-flow
fix: incorrect number of clusters found (#561)

1018 of 1352 branches covered (75.3%)

Branch coverage included in aggregate %.

7 of 7 new or added lines in 1 file covered. (100.0%)

70 existing lines in 5 files now uncovered.

5021 of 6007 relevant lines covered (83.59%)

54.28 hits per line

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

80.97
/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 { AtlasTools } from "./tools/atlas/tools.js";
2✔
5
import { MongoDbTools } from "./tools/mongodb/tools.js";
2✔
6
import { Resources } from "./resources/resources.js";
2✔
7
import type { LogLevel } from "./common/logger.js";
8
import { LogId, McpLogger } from "./common/logger.js";
2✔
9
import type { Telemetry } from "./telemetry/telemetry.js";
10
import type { UserConfig } from "./common/config.js";
11
import { type ServerEvent } from "./telemetry/types.js";
12
import { type ServerCommand } from "./telemetry/types.js";
13
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
14
import {
2✔
15
    CallToolRequestSchema,
16
    SetLevelRequestSchema,
17
    SubscribeRequestSchema,
18
    UnsubscribeRequestSchema,
19
} from "@modelcontextprotocol/sdk/types.js";
20
import assert from "assert";
2✔
21
import type { ToolBase } from "./tools/tool.js";
22
import { validateConnectionString } from "./helpers/connectionOptions.js";
2✔
23
import { packageInfo } from "./common/packageInfo.js";
2✔
24
import { type ConnectionErrorHandler } from "./common/connectionErrorHandler.js";
25
import type { Elicitation } from "./elicitation.js";
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

36
export class Server {
2✔
37
    public readonly session: Session;
38
    public readonly mcpServer: McpServer;
39
    private readonly telemetry: Telemetry;
40
    public readonly userConfig: UserConfig;
41
    public readonly elicitation: Elicitation;
42
    public readonly tools: ToolBase[] = [];
2✔
43
    public readonly connectionErrorHandler: ConnectionErrorHandler;
44

45
    private _mcpLogLevel: LogLevel = "debug";
2✔
46

47
    public get mcpLogLevel(): LogLevel {
2✔
48
        return this._mcpLogLevel;
2✔
49
    }
2✔
50

51
    private readonly startTime: number;
52
    private readonly subscriptions = new Set<string>();
2✔
53

54
    constructor({ session, mcpServer, userConfig, telemetry, connectionErrorHandler, elicitation }: ServerOptions) {
2✔
55
        this.startTime = Date.now();
67✔
56
        this.session = session;
67✔
57
        this.telemetry = telemetry;
67✔
58
        this.mcpServer = mcpServer;
67✔
59
        this.userConfig = userConfig;
67✔
60
        this.elicitation = elicitation;
67✔
61
        this.connectionErrorHandler = connectionErrorHandler;
67✔
62
    }
67✔
63

64
    async connect(transport: Transport): Promise<void> {
2✔
65
        // Resources are now reactive, so we register them ASAP so they can listen to events like
66
        // connection events.
67
        this.registerResources();
66✔
68
        await this.validateConfig();
66✔
69

70
        this.mcpServer.server.registerCapabilities({ logging: {}, resources: { listChanged: true, subscribe: true } });
66✔
71

72
        // TODO: Eventually we might want to make tools reactive too instead of relying on custom logic.
73
        this.registerTools();
66✔
74

75
        // This is a workaround for an issue we've seen with some models, where they'll see that everything in the `arguments`
76
        // object is optional, and then not pass it at all. However, the MCP server expects the `arguments` object to be if
77
        // the tool accepts any arguments, even if they're all optional.
78
        //
79
        // see: https://github.com/modelcontextprotocol/typescript-sdk/blob/131776764536b5fdca642df51230a3746fb4ade0/src/server/mcp.ts#L705
80
        // Since paramsSchema here is not undefined, the server will create a non-optional z.object from it.
81
        const existingHandler = (
66✔
82
            this.mcpServer.server["_requestHandlers"] as Map<
66✔
83
                string,
84
                (request: unknown, extra: unknown) => Promise<CallToolResult>
85
            >
86
        ).get(CallToolRequestSchema.shape.method.value);
66✔
87

88
        assert(existingHandler, "No existing handler found for CallToolRequestSchema");
66✔
89

90
        this.mcpServer.server.setRequestHandler(CallToolRequestSchema, (request, extra): Promise<CallToolResult> => {
66✔
91
            if (!request.params.arguments) {
492✔
92
                request.params.arguments = {};
1✔
93
            }
1✔
94

95
            return existingHandler(request, extra);
492✔
96
        });
66✔
97

98
        this.mcpServer.server.setRequestHandler(SubscribeRequestSchema, ({ params }) => {
66✔
99
            this.subscriptions.add(params.uri);
20✔
100
            this.session.logger.debug({
20✔
101
                id: LogId.serverInitialized,
20✔
102
                context: "resources",
20✔
103
                message: `Client subscribed to resource: ${params.uri}`,
20✔
104
            });
20✔
105
            return {};
20✔
106
        });
66✔
107

108
        this.mcpServer.server.setRequestHandler(UnsubscribeRequestSchema, ({ params }) => {
66✔
109
            this.subscriptions.delete(params.uri);
×
110
            this.session.logger.debug({
×
111
                id: LogId.serverInitialized,
×
UNCOV
112
                context: "resources",
×
UNCOV
113
                message: `Client unsubscribed from resource: ${params.uri}`,
×
UNCOV
114
            });
×
115
            return {};
×
116
        });
66✔
117

118
        this.mcpServer.server.setRequestHandler(SetLevelRequestSchema, ({ params }) => {
66✔
119
            if (!McpLogger.LOG_LEVELS.includes(params.level)) {
×
120
                throw new Error(`Invalid log level: ${params.level}`);
×
UNCOV
121
            }
×
122

UNCOV
123
            this._mcpLogLevel = params.level;
×
UNCOV
124
            return {};
×
125
        });
66✔
126

127
        this.mcpServer.server.oninitialized = (): void => {
66✔
128
            this.session.setMcpClient(this.mcpServer.server.getClientVersion());
66✔
129
            // Placed here to start the connection to the config connection string as soon as the server is initialized.
130
            void this.connectToConfigConnectionString();
66✔
131
            this.session.logger.info({
66✔
132
                id: LogId.serverInitialized,
66✔
133
                context: "server",
66✔
134
                message: `Server with version ${packageInfo.version} started with transport ${transport.constructor.name} and agent runner ${JSON.stringify(this.session.mcpClient)}`,
66✔
135
            });
66✔
136

137
            this.emitServerEvent("start", Date.now() - this.startTime);
66✔
138
        };
66✔
139

140
        this.mcpServer.server.onclose = (): void => {
66✔
141
            const closeTime = Date.now();
66✔
142
            this.emitServerEvent("stop", Date.now() - closeTime);
66✔
143
        };
66✔
144

145
        this.mcpServer.server.onerror = (error: Error): void => {
66✔
UNCOV
146
            const closeTime = Date.now();
×
UNCOV
147
            this.emitServerEvent("stop", Date.now() - closeTime, error);
×
UNCOV
148
        };
×
149

150
        await this.mcpServer.connect(transport);
66✔
151
    }
66✔
152

153
    async close(): Promise<void> {
2✔
154
        await this.telemetry.close();
66✔
155
        await this.session.close();
66✔
156
        await this.mcpServer.close();
66✔
157
    }
66✔
158

159
    public sendResourceListChanged(): void {
2✔
160
        this.mcpServer.sendResourceListChanged();
546✔
161
    }
546✔
162

163
    public sendResourceUpdated(uri: string): void {
2✔
164
        if (this.subscriptions.has(uri)) {
546!
165
            void this.mcpServer.server.sendResourceUpdated({ uri });
20✔
166
        }
20✔
167
    }
546✔
168

169
    /**
170
     * Emits a server event
171
     * @param command - The server command (e.g., "start", "stop", "register", "deregister")
172
     * @param additionalProperties - Additional properties specific to the event
173
     */
174
    private emitServerEvent(command: ServerCommand, commandDuration: number, error?: Error): void {
2✔
175
        const event: ServerEvent = {
132✔
176
            timestamp: new Date().toISOString(),
132✔
177
            source: "mdbmcp",
132✔
178
            properties: {
132✔
179
                result: "success",
132✔
180
                duration_ms: commandDuration,
132✔
181
                component: "server",
132✔
182
                category: "other",
132✔
183
                command: command,
132✔
184
            },
132✔
185
        };
132✔
186

187
        if (command === "start") {
132✔
188
            event.properties.startup_time_ms = commandDuration;
66✔
189
            event.properties.read_only_mode = this.userConfig.readOnly || false;
66✔
190
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
66!
191
            event.properties.confirmation_required_tools = this.userConfig.confirmationRequiredTools || [];
66!
192
        }
66✔
193
        if (command === "stop") {
132✔
194
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
66✔
195
            if (error) {
66!
UNCOV
196
                event.properties.result = "failure";
×
UNCOV
197
                event.properties.reason = error.message;
×
UNCOV
198
            }
×
199
        }
66✔
200

201
        this.telemetry.emitEvents([event]);
132✔
202
    }
132✔
203

204
    private registerTools(): void {
2✔
205
        for (const toolConstructor of [...AtlasTools, ...MongoDbTools]) {
66✔
206
            const tool = new toolConstructor({
2,178✔
207
                session: this.session,
2,178✔
208
                config: this.userConfig,
2,178✔
209
                telemetry: this.telemetry,
2,178✔
210
                elicitation: this.elicitation,
2,178✔
211
            });
2,178✔
212
            if (tool.register(this)) {
2,178✔
213
                this.tools.push(tool);
1,529✔
214
            }
1,529✔
215
        }
2,178✔
216
    }
66✔
217

218
    private registerResources(): void {
2✔
219
        for (const resourceConstructor of Resources) {
66✔
220
            const resource = new resourceConstructor(this.session, this.userConfig, this.telemetry);
198✔
221
            resource.register(this);
198✔
222
        }
198✔
223
    }
66✔
224

225
    private async validateConfig(): Promise<void> {
2✔
226
        // Validate connection string
227
        if (this.userConfig.connectionString) {
66!
228
            try {
5✔
229
                validateConnectionString(this.userConfig.connectionString, false);
5✔
230
            } catch (error) {
5!
UNCOV
231
                console.error("Connection string validation failed with error: ", error);
×
UNCOV
232
                throw new Error(
×
UNCOV
233
                    "Connection string validation failed with error: " +
×
234
                        (error instanceof Error ? error.message : String(error))
×
235
                );
×
UNCOV
236
            }
×
237
        }
5✔
238

239
        // Validate API client credentials
240
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
66✔
241
            try {
13✔
242
                await this.session.apiClient.validateAccessToken();
13✔
243
            } catch (error) {
13!
244
                if (this.userConfig.connectionString === undefined) {
×
UNCOV
245
                    console.error("Failed to validate MongoDB Atlas the credentials from the config: ", error);
×
246

UNCOV
247
                    throw new Error(
×
UNCOV
248
                        "Failed to connect to MongoDB Atlas instance using the credentials from the config"
×
UNCOV
249
                    );
×
UNCOV
250
                }
×
UNCOV
251
                console.error(
×
UNCOV
252
                    "Failed to validate MongoDB Atlas the credentials from the config, but validated the connection string."
×
UNCOV
253
                );
×
UNCOV
254
            }
×
255
        }
13✔
256
    }
66✔
257

258
    private async connectToConfigConnectionString(): Promise<void> {
2✔
259
        if (this.userConfig.connectionString) {
66!
260
            try {
5✔
261
                this.session.logger.info({
5✔
262
                    id: LogId.mongodbConnectTry,
5✔
263
                    context: "server",
5✔
264
                    message: `Detected a MongoDB connection string in the configuration, trying to connect...`,
5✔
265
                });
5✔
266
                await this.session.connectToMongoDB({
5✔
267
                    connectionString: this.userConfig.connectionString,
5✔
268
                });
5✔
269
            } catch (error) {
3✔
270
                // We don't throw an error here because we want to allow the server to start even if the connection string is invalid.
271
                this.session.logger.error({
2✔
272
                    id: LogId.mongodbConnectFailure,
2✔
273
                    context: "server",
2✔
274
                    message: `Failed to connect to MongoDB instance using the connection string from the config: ${error instanceof Error ? error.message : String(error)}`,
2!
275
                });
2✔
276
            }
2✔
277
        }
5✔
278
    }
66✔
279
}
2✔
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