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

mongodb-js / mongodb-mcp-server / 16269631846

14 Jul 2025 02:28PM UTC coverage: 68.405%. First build
16269631846

Pull #359

github

web-flow
Merge a4530488b into 184841400
Pull Request #359: feat: add streamable http

326 of 587 branches covered (55.54%)

Branch coverage included in aggregate %.

9 of 12 new or added lines in 2 files covered. (75.0%)

815 of 1081 relevant lines covered (75.39%)

56.82 hits per line

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

73.83
/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 } 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
        this.mcpServer.server.oninitialized = () => {
34✔
71
            this.session.setAgentRunner(this.mcpServer.server.getClientVersion());
34✔
72
            this.session.sessionId = new ObjectId().toString();
34✔
73

74
            logger.info(
34✔
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);
34✔
81
        };
82

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

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

93
        await this.mcpServer.connect(transport);
34✔
94
    }
95

96
    async close(): Promise<void> {
97
        await this.telemetry.close();
34✔
98
        await this.session.close();
34✔
99
        await this.mcpServer.close();
34✔
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 = {
68✔
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") {
68✔
121
            event.properties.startup_time_ms = commandDuration;
34✔
122
            event.properties.read_only_mode = this.userConfig.readOnly || false;
34✔
123
            event.properties.disabled_tools = this.userConfig.disabledTools || [];
34!
124
        }
125
        if (command === "stop") {
68✔
126
            event.properties.runtime_duration_ms = Date.now() - this.startTime;
34✔
127
            if (error) {
34!
128
                event.properties.result = "failure";
×
129
                event.properties.reason = error.message;
×
130
            }
131
        }
132

133
        this.telemetry.emitEvents([event]).catch(() => {});
68✔
134
    }
135

136
    private registerTools() {
137
        for (const toolConstructor of [...AtlasTools, ...MongoDbTools]) {
34✔
138
            const tool = new toolConstructor(this.session, this.userConfig, this.telemetry);
1,088✔
139
            if (tool.register(this)) {
1,088✔
140
                this.tools.push(tool);
761✔
141
            }
142
        }
143
    }
144

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

179
    private async validateConfig(): Promise<void> {
180
        if (this.userConfig.transport !== "http" && this.userConfig.transport !== "stdio") {
34!
NEW
181
            throw new Error(`Invalid transport: ${this.userConfig.transport}`);
×
182
        }
183

184
        if (this.userConfig.telemetry !== "enabled" && this.userConfig.telemetry !== "disabled") {
34!
NEW
185
            throw new Error(`Invalid telemetry: ${this.userConfig.telemetry}`);
×
186
        }
187

188
        if (this.userConfig.httpPort < 1 || this.userConfig.httpPort > 65535) {
34!
NEW
189
            throw new Error(`Invalid httpPort: ${this.userConfig.httpPort}`);
×
190
        }
191

192
        if (this.userConfig.connectionString) {
34✔
193
            try {
1✔
194
                await this.session.connectToMongoDB(this.userConfig.connectionString, this.userConfig.connectOptions);
1✔
195
            } catch (error) {
196
                console.error(
×
197
                    "Failed to connect to MongoDB instance using the connection string from the config: ",
198
                    error
199
                );
200
                throw new Error("Failed to connect to MongoDB instance using the connection string from the config");
×
201
            }
202
        }
203

204
        if (this.userConfig.apiClientId && this.userConfig.apiClientSecret) {
34✔
205
            try {
8✔
206
                await this.session.apiClient.validateAccessToken();
8✔
207
            } catch (error) {
208
                if (this.userConfig.connectionString === undefined) {
×
209
                    console.error("Failed to validate MongoDB Atlas the credentials from the config: ", error);
×
210

211
                    throw new Error(
×
212
                        "Failed to connect to MongoDB Atlas instance using the credentials from the config"
213
                    );
214
                }
215
                console.error(
×
216
                    "Failed to validate MongoDB Atlas the credentials from the config, but validated the connection string."
217
                );
218
            }
219
        }
220
    }
221
}
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