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

mongodb-js / mongodb-mcp-server / 17330103427

29 Aug 2025 05:17PM UTC coverage: 80.912% (-1.1%) from 82.036%
17330103427

push

github

web-flow
ci: add ipAccessList after creating project (#496)

889 of 1182 branches covered (75.21%)

Branch coverage included in aggregate %.

4520 of 5503 relevant lines covered (82.14%)

39.79 hits per line

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

77.73
/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

24
export interface ServerOptions {
25
    session: Session;
26
    userConfig: UserConfig;
27
    mcpServer: McpServer;
28
    telemetry: Telemetry;
29
}
30

31
export class Server {
2✔
32
    public readonly session: Session;
33
    public readonly mcpServer: McpServer;
34
    private readonly telemetry: Telemetry;
35
    public readonly userConfig: UserConfig;
36
    public readonly tools: ToolBase[] = [];
2✔
37

38
    private _mcpLogLevel: LogLevel = "debug";
2✔
39

40
    public get mcpLogLevel(): LogLevel {
2✔
41
        return this._mcpLogLevel;
2✔
42
    }
2✔
43

44
    private readonly startTime: number;
45
    private readonly subscriptions = new Set<string>();
2✔
46

47
    constructor({ session, mcpServer, userConfig, telemetry }: ServerOptions) {
2✔
48
        this.startTime = Date.now();
48✔
49
        this.session = session;
48✔
50
        this.telemetry = telemetry;
48✔
51
        this.mcpServer = mcpServer;
48✔
52
        this.userConfig = userConfig;
48✔
53
    }
48✔
54

55
    async connect(transport: Transport): Promise<void> {
2✔
56
        // Resources are now reactive, so we register them ASAP so they can listen to events like
57
        // connection events.
58
        this.registerResources();
48✔
59
        await this.validateConfig();
48✔
60

61
        this.mcpServer.server.registerCapabilities({ logging: {}, resources: { listChanged: true, subscribe: true } });
48✔
62

63
        // TODO: Eventually we might want to make tools reactive too instead of relying on custom logic.
64
        this.registerTools();
48✔
65

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

79
        assert(existingHandler, "No existing handler found for CallToolRequestSchema");
48✔
80

81
        this.mcpServer.server.setRequestHandler(CallToolRequestSchema, (request, extra): Promise<CallToolResult> => {
48✔
82
            if (!request.params.arguments) {
456✔
83
                request.params.arguments = {};
1✔
84
            }
1✔
85

86
            return existingHandler(request, extra);
456✔
87
        });
48✔
88

89
        this.mcpServer.server.setRequestHandler(SubscribeRequestSchema, ({ params }) => {
48✔
90
            this.subscriptions.add(params.uri);
20✔
91
            this.session.logger.debug({
20✔
92
                id: LogId.serverInitialized,
20✔
93
                context: "resources",
20✔
94
                message: `Client subscribed to resource: ${params.uri}`,
20✔
95
            });
20✔
96
            return {};
20✔
97
        });
48✔
98

99
        this.mcpServer.server.setRequestHandler(UnsubscribeRequestSchema, ({ params }) => {
48✔
100
            this.subscriptions.delete(params.uri);
×
101
            this.session.logger.debug({
×
102
                id: LogId.serverInitialized,
×
103
                context: "resources",
×
104
                message: `Client unsubscribed from resource: ${params.uri}`,
×
105
            });
×
106
            return {};
×
107
        });
48✔
108

109
        this.mcpServer.server.setRequestHandler(SetLevelRequestSchema, ({ params }) => {
48✔
110
            if (!McpLogger.LOG_LEVELS.includes(params.level)) {
×
111
                throw new Error(`Invalid log level: ${params.level}`);
×
112
            }
×
113

114
            this._mcpLogLevel = params.level;
×
115
            return {};
×
116
        });
48✔
117

118
        this.mcpServer.server.oninitialized = (): void => {
48✔
119
            this.session.setMcpClient(this.mcpServer.server.getClientVersion());
48✔
120
            // Placed here to start the connection to the config connection string as soon as the server is initialized.
121
            void this.connectToConfigConnectionString();
48✔
122

123
            this.session.logger.info({
48✔
124
                id: LogId.serverInitialized,
48✔
125
                context: "server",
48✔
126
                message: `Server started with transport ${transport.constructor.name} and agent runner ${this.session.mcpClient?.name}`,
48✔
127
            });
48✔
128

129
            this.emitServerEvent("start", Date.now() - this.startTime);
48✔
130
        };
48✔
131

132
        this.mcpServer.server.onclose = (): void => {
48✔
133
            const closeTime = Date.now();
48✔
134
            this.emitServerEvent("stop", Date.now() - closeTime);
48✔
135
        };
48✔
136

137
        this.mcpServer.server.onerror = (error: Error): void => {
48✔
138
            const closeTime = Date.now();
×
139
            this.emitServerEvent("stop", Date.now() - closeTime, error);
×
140
        };
×
141

142
        await this.mcpServer.connect(transport);
48✔
143
    }
48✔
144

145
    async close(): Promise<void> {
2✔
146
        await this.telemetry.close();
48✔
147
        await this.session.close();
48✔
148
        await this.mcpServer.close();
48✔
149
    }
48✔
150

151
    public sendResourceListChanged(): void {
2✔
152
        this.mcpServer.sendResourceListChanged();
509✔
153
    }
509✔
154

155
    public sendResourceUpdated(uri: string): void {
2✔
156
        if (this.subscriptions.has(uri)) {
509!
157
            void this.mcpServer.server.sendResourceUpdated({ uri });
20✔
158
        }
20✔
159
    }
509✔
160

161
    /**
162
     * Emits a server event
163
     * @param command - The server command (e.g., "start", "stop", "register", "deregister")
164
     * @param additionalProperties - Additional properties specific to the event
165
     */
166
    private emitServerEvent(command: ServerCommand, commandDuration: number, error?: Error): void {
2✔
167
        const event: ServerEvent = {
96✔
168
            timestamp: new Date().toISOString(),
96✔
169
            source: "mdbmcp",
96✔
170
            properties: {
96✔
171
                result: "success",
96✔
172
                duration_ms: commandDuration,
96✔
173
                component: "server",
96✔
174
                category: "other",
96✔
175
                command: command,
96✔
176
            },
96✔
177
        };
96✔
178

179
        if (command === "start") {
96✔
180
            event.properties.startup_time_ms = commandDuration;
48✔
181
            event.properties.read_only_mode = this.userConfig.readOnly || false;
48✔
182
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
48!
183
        }
48✔
184
        if (command === "stop") {
96✔
185
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
48✔
186
            if (error) {
48!
187
                event.properties.result = "failure";
×
188
                event.properties.reason = error.message;
×
189
            }
×
190
        }
48✔
191

192
        this.telemetry.emitEvents([event]).catch(() => {});
96✔
193
    }
96✔
194

195
    private registerTools(): void {
2✔
196
        for (const toolConstructor of [...AtlasTools, ...MongoDbTools]) {
48✔
197
            const tool = new toolConstructor(this.session, this.userConfig, this.telemetry);
1,584✔
198
            if (tool.register(this)) {
1,584✔
199
                this.tools.push(tool);
1,089✔
200
            }
1,089✔
201
        }
1,584✔
202
    }
48✔
203

204
    private registerResources(): void {
2✔
205
        for (const resourceConstructor of Resources) {
48✔
206
            const resource = new resourceConstructor(this.session, this.userConfig, this.telemetry);
144✔
207
            resource.register(this);
144✔
208
        }
144✔
209
    }
48✔
210

211
    private async validateConfig(): Promise<void> {
2✔
212
        // Validate connection string
213
        if (this.userConfig.connectionString) {
48!
214
            try {
1✔
215
                validateConnectionString(this.userConfig.connectionString, false);
1✔
216
            } catch (error) {
1!
217
                console.error("Connection string validation failed with error: ", error);
×
218
                throw new Error(
×
219
                    "Connection string validation failed with error: " +
×
220
                        (error instanceof Error ? error.message : String(error))
×
221
                );
×
222
            }
×
223
        }
1✔
224

225
        // Validate API client credentials
226
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
48✔
227
            try {
8✔
228
                await this.session.apiClient.validateAccessToken();
8✔
229
            } catch (error) {
8!
230
                if (this.userConfig.connectionString === undefined) {
×
231
                    console.error("Failed to validate MongoDB Atlas the credentials from the config: ", error);
×
232

233
                    throw new Error(
×
234
                        "Failed to connect to MongoDB Atlas instance using the credentials from the config"
×
235
                    );
×
236
                }
×
237
                console.error(
×
238
                    "Failed to validate MongoDB Atlas the credentials from the config, but validated the connection string."
×
239
                );
×
240
            }
×
241
        }
8✔
242
    }
48✔
243

244
    private async connectToConfigConnectionString(): Promise<void> {
2✔
245
        if (this.userConfig.connectionString) {
48!
246
            try {
1✔
247
                await this.session.connectToMongoDB({
1✔
248
                    connectionString: this.userConfig.connectionString,
1✔
249
                });
1✔
250
            } catch (error) {
1!
251
                console.error(
×
252
                    "Failed to connect to MongoDB instance using the connection string from the config: ",
×
253
                    error
×
254
                );
×
255
                throw new Error("Failed to connect to MongoDB instance using the connection string from the config");
×
256
            }
×
257
        }
1✔
258
    }
48✔
259
}
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