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

mongodb-js / mongodb-mcp-server / 15979268264

30 Jun 2025 05:11PM UTC coverage: 74.965% (+2.5%) from 72.437%
15979268264

push

github

web-flow
fix: index tests (#331)

239 of 404 branches covered (59.16%)

Branch coverage included in aggregate %.

830 of 1022 relevant lines covered (81.21%)

58.42 hits per line

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

73.08
/src/server.ts
1
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
import { Session } from "./session.js";
3
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
4
import { AtlasTools } from "./tools/atlas/tools.js";
5
import { MongoDbTools } from "./tools/mongodb/tools.js";
6
import logger, { initializeLogger, LogId } from "./logger.js";
7
import { ObjectId } from "mongodb";
8
import { Telemetry } from "./telemetry/telemetry.js";
9
import { UserConfig } from "./config.js";
10
import { type ServerEvent } from "./telemetry/types.js";
11
import { type ServerCommand } from "./telemetry/types.js";
12
import { CallToolRequestSchema, CallToolResult } from "@modelcontextprotocol/sdk/types.js";
13
import assert from "assert";
14

15
export interface ServerOptions {
16
    session: Session;
17
    userConfig: UserConfig;
18
    mcpServer: McpServer;
19
    telemetry: Telemetry;
20
}
21

22
export class Server {
23
    public readonly session: Session;
24
    private readonly mcpServer: McpServer;
25
    private readonly telemetry: Telemetry;
26
    public readonly userConfig: UserConfig;
27
    private readonly startTime: number;
28

29
    constructor({ session, mcpServer, userConfig, telemetry }: ServerOptions) {
30
        this.startTime = Date.now();
33✔
31
        this.session = session;
33✔
32
        this.telemetry = telemetry;
33✔
33
        this.mcpServer = mcpServer;
33✔
34
        this.userConfig = userConfig;
33✔
35
    }
36

37
    async connect(transport: Transport): Promise<void> {
38
        this.mcpServer.server.registerCapabilities({ logging: {} });
33✔
39

40
        this.registerTools();
33✔
41
        this.registerResources();
33✔
42

43
        // This is a workaround for an issue we've seen with some models, where they'll see that everything in the `arguments`
44
        // object is optional, and then not pass it at all. However, the MCP server expects the `arguments` object to be if
45
        // the tool accepts any arguments, even if they're all optional.
46
        //
47
        // see: https://github.com/modelcontextprotocol/typescript-sdk/blob/131776764536b5fdca642df51230a3746fb4ade0/src/server/mcp.ts#L705
48
        // Since paramsSchema here is not undefined, the server will create a non-optional z.object from it.
49
        const existingHandler = (
50
            this.mcpServer.server["_requestHandlers"] as Map<
33✔
51
                string,
52
                (request: unknown, extra: unknown) => Promise<CallToolResult>
53
            >
54
        ).get(CallToolRequestSchema.shape.method.value);
55

56
        assert(existingHandler, "No existing handler found for CallToolRequestSchema");
33✔
57

58
        this.mcpServer.server.setRequestHandler(CallToolRequestSchema, (request, extra): Promise<CallToolResult> => {
33✔
59
            if (!request.params.arguments) {
370✔
60
                request.params.arguments = {};
1✔
61
            }
62

63
            return existingHandler(request, extra);
370✔
64
        });
65

66
        await initializeLogger(this.mcpServer, this.userConfig.logPath);
33✔
67

68
        await this.mcpServer.connect(transport);
33✔
69

70
        this.mcpServer.server.oninitialized = () => {
33✔
71
            this.session.setAgentRunner(this.mcpServer.server.getClientVersion());
33✔
72
            this.session.sessionId = new ObjectId().toString();
33✔
73

74
            logger.info(
33✔
75
                LogId.serverInitialized,
76
                "server",
77
                `Server started with transport ${transport.constructor.name} and agent runner ${this.session.agentRunner?.name}`
78
            );
79

80
            this.emitServerEvent("start", Date.now() - this.startTime);
33✔
81
        };
82

83
        this.mcpServer.server.onclose = () => {
33✔
84
            const closeTime = Date.now();
33✔
85
            this.emitServerEvent("stop", Date.now() - closeTime);
33✔
86
        };
87

88
        this.mcpServer.server.onerror = (error: Error) => {
33✔
89
            const closeTime = Date.now();
×
90
            this.emitServerEvent("stop", Date.now() - closeTime, error);
×
91
        };
92

93
        await this.validateConfig();
33✔
94
    }
95

96
    async close(): Promise<void> {
97
        await this.telemetry.close();
33✔
98
        await this.session.close();
33✔
99
        await this.mcpServer.close();
33✔
100
    }
101

102
    /**
103
     * Emits a server event
104
     * @param command - The server command (e.g., "start", "stop", "register", "deregister")
105
     * @param additionalProperties - Additional properties specific to the event
106
     */
107
    private emitServerEvent(command: ServerCommand, commandDuration: number, error?: Error) {
108
        const event: ServerEvent = {
66✔
109
            timestamp: new Date().toISOString(),
110
            source: "mdbmcp",
111
            properties: {
112
                result: "success",
113
                duration_ms: commandDuration,
114
                component: "server",
115
                category: "other",
116
                command: command,
117
            },
118
        };
119

120
        if (command === "start") {
66✔
121
            event.properties.startup_time_ms = commandDuration;
33✔
122
            event.properties.read_only_mode = this.userConfig.readOnly || false;
33✔
123
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
33!
124
        }
125
        if (command === "stop") {
66✔
126
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
33✔
127
            if (error) {
33!
128
                event.properties.result = "failure";
×
129
                event.properties.reason = error.message;
×
130
            }
131
        }
132

133
        this.telemetry.emitEvents([event]);
66✔
134
    }
135

136
    private registerTools() {
137
        for (const tool of [...AtlasTools, ...MongoDbTools]) {
33✔
138
            new tool(this.session, this.userConfig, this.telemetry).register(this.mcpServer);
1,056✔
139
        }
140
    }
141

142
    private registerResources() {
143
        this.mcpServer.resource(
33✔
144
            "config",
145
            "config://config",
146
            {
147
                description:
148
                    "Server configuration, supplied by the user either as environment variables or as startup arguments",
149
            },
150
            (uri) => {
151
                const result = {
×
152
                    telemetry: this.userConfig.telemetry,
153
                    logPath: this.userConfig.logPath,
154
                    connectionString: this.userConfig.connectionString
×
155
                        ? "set; access to MongoDB tools are currently available to use"
156
                        : "not set; before using any MongoDB tool, you need to configure a connection string, alternatively you can setup MongoDB Atlas access, more info at 'https://github.com/mongodb-js/mongodb-mcp-server'.",
157
                    connectOptions: this.userConfig.connectOptions,
158
                    atlas:
159
                        this.userConfig.apiClientId && this.userConfig.apiClientSecret
×
160
                            ? "set; MongoDB Atlas tools are currently available to use"
161
                            : "not set; MongoDB Atlas tools are currently unavailable, to have access to MongoDB Atlas tools like creating clusters or connecting to clusters make sure to setup credentials, more info at 'https://github.com/mongodb-js/mongodb-mcp-server'.",
162
                };
163
                return {
×
164
                    contents: [
165
                        {
166
                            text: JSON.stringify(result),
167
                            mimeType: "application/json",
168
                            uri: uri.href,
169
                        },
170
                    ],
171
                };
172
            }
173
        );
174
    }
175

176
    private async validateConfig(): Promise<void> {
177
        if (this.userConfig.connectionString) {
33✔
178
            try {
1✔
179
                await this.session.connectToMongoDB(this.userConfig.connectionString, this.userConfig.connectOptions);
1✔
180
            } catch (error) {
181
                console.error(
×
182
                    "Failed to connect to MongoDB instance using the connection string from the config: ",
183
                    error
184
                );
185
                throw new Error("Failed to connect to MongoDB instance using the connection string from the config");
×
186
            }
187
        }
188

189
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
33✔
190
            try {
8✔
191
                await this.session.apiClient.validateAccessToken();
8✔
192
            } catch (error) {
193
                if (this.userConfig.connectionString === undefined) {
×
194
                    console.error("Failed to validate MongoDB Atlas the credentials from the config: ", error);
×
195

196
                    throw new Error(
×
197
                        "Failed to connect to MongoDB Atlas instance using the credentials from the config"
198
                    );
199
                }
200
                console.error(
×
201
                    "Failed to validate MongoDB Atlas the credentials from the config, but validated the connection string."
202
                );
203
            }
204
        }
205
    }
206
}
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