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

mongodb-js / mongodb-mcp-server / 16269895831

14 Jul 2025 02:39PM UTC coverage: 70.041%. First build
16269895831

Pull #359

github

web-flow
Merge 85d70efa8 into b10990b77
Pull Request #359: feat: add streamable http

343 of 602 branches covered (56.98%)

Branch coverage included in aggregate %.

22 of 28 new or added lines in 2 files covered. (78.57%)

847 of 1097 relevant lines covered (77.21%)

56.5 hits per line

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

75.36
/src/server.ts
1
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
import { Session } from "./common/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, { LogId, LoggerBase, McpLogger, DiskLogger, ConsoleLogger } from "./common/logger.js";
7
import { ObjectId } from "mongodb";
8
import { Telemetry } from "./telemetry/telemetry.js";
9
import { UserConfig } from "./common/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
import { ToolBase } from "./tools/tool.js";
15

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

23
export class Server {
24
    public readonly session: Session;
25
    public readonly mcpServer: McpServer;
26
    private readonly telemetry: Telemetry;
27
    public readonly userConfig: UserConfig;
28
    public readonly tools: ToolBase[] = [];
34✔
29
    private readonly startTime: number;
30

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

39
    async connect(transport: Transport): Promise<void> {
40
        await this.validateConfig();
34✔
41

42
        this.mcpServer.server.registerCapabilities({ logging: {} });
34✔
43

44
        this.registerTools();
34✔
45
        this.registerResources();
34✔
46

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

60
        assert(existingHandler, "No existing handler found for CallToolRequestSchema");
34✔
61

62
        this.mcpServer.server.setRequestHandler(CallToolRequestSchema, (request, extra): Promise<CallToolResult> => {
34✔
63
            if (!request.params.arguments) {
370✔
64
                request.params.arguments = {};
1✔
65
            }
66

67
            return existingHandler(request, extra);
370✔
68
        });
69

70
        const loggers: LoggerBase[] = [];
34✔
71
        if (this.userConfig.loggers.includes("mcp")) {
34✔
72
            loggers.push(new McpLogger(this.mcpServer));
2✔
73
        }
74
        if (this.userConfig.loggers.includes("disk")) {
34✔
75
            loggers.push(await DiskLogger.fromPath(this.userConfig.logPath));
2✔
76
        }
77
        if (this.userConfig.loggers.includes("stderr")) {
34✔
78
            loggers.push(new ConsoleLogger());
32✔
79
        }
80
        logger.setLoggers(...loggers);
34✔
81
        
82
        this.mcpServer.server.oninitialized = () => {
34✔
83
            this.session.setAgentRunner(this.mcpServer.server.getClientVersion());
34✔
84
            this.session.sessionId = new ObjectId().toString();
34✔
85

86
            logger.info(
34✔
87
                LogId.serverInitialized,
88
                "server",
89
                `Server started with transport ${transport.constructor.name} and agent runner ${this.session.agentRunner?.name}`
90
            );
91

92
            this.emitServerEvent("start", Date.now() - this.startTime);
34✔
93
        };
94

95
        this.mcpServer.server.onclose = () => {
34✔
96
            const closeTime = Date.now();
34✔
97
            this.emitServerEvent("stop", Date.now() - closeTime);
34✔
98
        };
99

100
        this.mcpServer.server.onerror = (error: Error) => {
34✔
101
            const closeTime = Date.now();
×
102
            this.emitServerEvent("stop", Date.now() - closeTime, error);
×
103
        };
104

105
        await this.mcpServer.connect(transport);
34✔
106
    }
107

108
    async close(): Promise<void> {
109
        await this.telemetry.close();
34✔
110
        await this.session.close();
34✔
111
        await this.mcpServer.close();
34✔
112
    }
113

114
    /**
115
     * Emits a server event
116
     * @param command - The server command (e.g., "start", "stop", "register", "deregister")
117
     * @param additionalProperties - Additional properties specific to the event
118
     */
119
    private emitServerEvent(command: ServerCommand, commandDuration: number, error?: Error) {
120
        const event: ServerEvent = {
68✔
121
            timestamp: new Date().toISOString(),
122
            source: "mdbmcp",
123
            properties: {
124
                result: "success",
125
                duration_ms: commandDuration,
126
                component: "server",
127
                category: "other",
128
                command: command,
129
            },
130
        };
131

132
        if (command === "start") {
68✔
133
            event.properties.startup_time_ms = commandDuration;
34✔
134
            event.properties.read_only_mode = this.userConfig.readOnly || false;
34✔
135
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
34!
136
        }
137
        if (command === "stop") {
68✔
138
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
34✔
139
            if (error) {
34!
140
                event.properties.result = "failure";
×
141
                event.properties.reason = error.message;
×
142
            }
143
        }
144

145
        this.telemetry.emitEvents([event]).catch(() => {});
68✔
146
    }
147

148
    private registerTools() {
149
        for (const toolConstructor of [...AtlasTools, ...MongoDbTools]) {
34✔
150
            const tool = new toolConstructor(this.session, this.userConfig, this.telemetry);
1,088✔
151
            if (tool.register(this)) {
1,088✔
152
                this.tools.push(tool);
761✔
153
            }
154
        }
155
    }
156

157
    private registerResources() {
158
        this.mcpServer.resource(
34✔
159
            "config",
160
            "config://config",
161
            {
162
                description:
163
                    "Server configuration, supplied by the user either as environment variables or as startup arguments",
164
            },
165
            (uri) => {
166
                const result = {
×
167
                    telemetry: this.userConfig.telemetry,
168
                    logPath: this.userConfig.logPath,
169
                    connectionString: this.userConfig.connectionString
×
170
                        ? "set; access to MongoDB tools are currently available to use"
171
                        : "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'.",
172
                    connectOptions: this.userConfig.connectOptions,
173
                    atlas:
174
                        this.userConfig.apiClientId && this.userConfig.apiClientSecret
×
175
                            ? "set; MongoDB Atlas tools are currently available to use"
176
                            : "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'.",
177
                };
178
                return {
×
179
                    contents: [
180
                        {
181
                            text: JSON.stringify(result),
182
                            mimeType: "application/json",
183
                            uri: uri.href,
184
                        },
185
                    ],
186
                };
187
            }
188
        );
189
    }
190

191
    private async validateConfig(): Promise<void> {
192
        if (this.userConfig.transport !== "http" && this.userConfig.transport !== "stdio") {
34!
NEW
193
            throw new Error(`Invalid transport: ${this.userConfig.transport}`);
×
194
        }
195

196
        if (this.userConfig.telemetry !== "enabled" && this.userConfig.telemetry !== "disabled") {
34!
NEW
197
            throw new Error(`Invalid telemetry: ${this.userConfig.telemetry}`);
×
198
        }
199

200
        if (this.userConfig.httpPort < 1 || this.userConfig.httpPort > 65535) {
34!
NEW
201
            throw new Error(`Invalid httpPort: ${this.userConfig.httpPort}`);
×
202
        }
203

204
        if (this.userConfig.loggers.length === 0) {
34!
NEW
205
            throw new Error("No loggers found in config");
×
206
        }
207

208
        const loggerTypes = new Set(this.userConfig.loggers);
34✔
209
        if (loggerTypes.size !== this.userConfig.loggers.length) {
34!
NEW
210
            throw new Error("Duplicate loggers found in config");
×
211
        }
212

213
        for (const loggerType of this.userConfig.loggers) {
34✔
214
            if (loggerType !== "mcp" && loggerType !== "disk" && loggerType !== "stderr") {
36!
NEW
215
                throw new Error(`Invalid logger: ${loggerType}`);
×
216
            }
217
        }
218

219
        if (this.userConfig.connectionString) {
34✔
220
            try {
1✔
221
                await this.session.connectToMongoDB(this.userConfig.connectionString, this.userConfig.connectOptions);
1✔
222
            } catch (error) {
223
                console.error(
×
224
                    "Failed to connect to MongoDB instance using the connection string from the config: ",
225
                    error
226
                );
227
                throw new Error("Failed to connect to MongoDB instance using the connection string from the config");
×
228
            }
229
        }
230

231
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
34✔
232
            try {
8✔
233
                await this.session.apiClient.validateAccessToken();
8✔
234
            } catch (error) {
235
                if (this.userConfig.connectionString === undefined) {
×
236
                    console.error("Failed to validate MongoDB Atlas the credentials from the config: ", error);
×
237

238
                    throw new Error(
×
239
                        "Failed to connect to MongoDB Atlas instance using the credentials from the config"
240
                    );
241
                }
242
                console.error(
×
243
                    "Failed to validate MongoDB Atlas the credentials from the config, but validated the connection string."
244
                );
245
            }
246
        }
247
    }
248
}
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

© 2025 Coveralls, Inc