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

mongodb-js / mongodb-mcp-server / 16271253098

14 Jul 2025 03:37PM UTC coverage: 75.779%. First build
16271253098

Pull #359

github

web-flow
Merge f0a83b00b into b10990b77
Pull Request #359: feat: add streamable http [MCP-55]

388 of 602 branches covered (64.45%)

Branch coverage included in aggregate %.

24 of 30 new or added lines in 2 files covered. (80.0%)

901 of 1099 relevant lines covered (81.98%)

114.56 hits per line

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

66.09
/src/tools/atlas/connect/connectCluster.ts
1
import { z } from "zod";
2
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3
import { AtlasToolBase } from "../atlasTool.js";
4
import { ToolArgs, OperationType } from "../../tool.js";
5
import { generateSecurePassword } from "../../../helpers/generatePassword.js";
6
import logger, { LogId } from "../../../common/logger.js";
7
import { inspectCluster } from "../../../common/atlas/cluster.js";
8

9
const EXPIRY_MS = 1000 * 60 * 60 * 12; // 12 hours
68✔
10

11
function sleep(ms: number): Promise<void> {
12
    return new Promise((resolve) => setTimeout(resolve, ms));
60✔
13
}
14

15
export class ConnectClusterTool extends AtlasToolBase {
16
    public name = "atlas-connect-cluster";
68✔
17
    protected description = "Connect to MongoDB Atlas cluster";
68✔
18
    public operationType: OperationType = "connect";
68✔
19
    protected argsShape = {
68✔
20
        projectId: z.string().describe("Atlas project ID"),
21
        clusterName: z.string().describe("Atlas cluster name"),
22
    };
23

24
    private async queryConnection(
25
        projectId: string,
26
        clusterName: string
27
    ): Promise<"connected" | "disconnected" | "connecting" | "connected-to-other-cluster" | "unknown"> {
28
        if (!this.session.connectedAtlasCluster) {
42✔
29
            if (this.session.serviceProvider) {
2!
30
                return "connected-to-other-cluster";
×
31
            }
32
            return "disconnected";
2✔
33
        }
34

35
        if (
40!
36
            this.session.connectedAtlasCluster.projectId !== projectId ||
80✔
37
            this.session.connectedAtlasCluster.clusterName !== clusterName
38
        ) {
39
            return "connected-to-other-cluster";
×
40
        }
41

42
        if (!this.session.serviceProvider) {
40✔
43
            return "connecting";
38✔
44
        }
45

46
        try {
2✔
47
            await this.session.serviceProvider.runCommand("admin", {
2✔
48
                ping: 1,
49
            });
50

51
            return "connected";
2✔
52
        } catch (err: unknown) {
53
            const error = err instanceof Error ? err : new Error(String(err));
×
54
            logger.debug(
×
55
                LogId.atlasConnectFailure,
56
                "atlas-connect-cluster",
57
                `error querying cluster: ${error.message}`
58
            );
59
            return "unknown";
×
60
        }
61
    }
62

63
    private async prepareClusterConnection(projectId: string, clusterName: string): Promise<string> {
64
        const cluster = await inspectCluster(this.session.apiClient, projectId, clusterName);
2✔
65

66
        if (!cluster.connectionString) {
2!
67
            throw new Error("Connection string not available");
×
68
        }
69

70
        const username = `mcpUser${Math.floor(Math.random() * 100000)}`;
2✔
71
        const password = await generateSecurePassword();
2✔
72

73
        const expiryDate = new Date(Date.now() + EXPIRY_MS);
2✔
74

75
        const readOnly =
76
            this.config.readOnly ||
2!
77
            (this.config.disabledTools?.includes("create") &&
78
                this.config.disabledTools?.includes("update") &&
79
                this.config.disabledTools?.includes("delete") &&
80
                !this.config.disabledTools?.includes("read") &&
81
                !this.config.disabledTools?.includes("metadata"));
82

83
        const roleName = readOnly ? "readAnyDatabase" : "readWriteAnyDatabase";
2!
84

85
        await this.session.apiClient.createDatabaseUser({
2✔
86
            params: {
87
                path: {
88
                    groupId: projectId,
89
                },
90
            },
91
            body: {
92
                databaseName: "admin",
93
                groupId: projectId,
94
                roles: [
95
                    {
96
                        roleName,
97
                        databaseName: "admin",
98
                    },
99
                ],
100
                scopes: [{ type: "CLUSTER", name: clusterName }],
101
                username,
102
                password,
103
                awsIAMType: "NONE",
104
                ldapAuthType: "NONE",
105
                oidcAuthType: "NONE",
106
                x509Type: "NONE",
107
                deleteAfterDate: expiryDate.toISOString(),
108
            },
109
        });
110

111
        this.session.connectedAtlasCluster = {
2✔
112
            username,
113
            projectId,
114
            clusterName,
115
            expiryDate,
116
        };
117

118
        const cn = new URL(cluster.connectionString);
2✔
119
        cn.username = username;
2✔
120
        cn.password = password;
2✔
121
        cn.searchParams.set("authSource", "admin");
2✔
122
        return cn.toString();
2✔
123
    }
124

125
    private async connectToCluster(projectId: string, clusterName: string, connectionString: string): Promise<void> {
126
        let lastError: Error | undefined = undefined;
2✔
127

128
        logger.debug(
2✔
129
            LogId.atlasConnectAttempt,
130
            "atlas-connect-cluster",
131
            `attempting to connect to cluster: ${this.session.connectedAtlasCluster?.clusterName}`
132
        );
133

134
        // try to connect for about 5 minutes
135
        for (let i = 0; i < 600; i++) {
2✔
136
            if (
22!
137
                !this.session.connectedAtlasCluster ||
66✔
138
                this.session.connectedAtlasCluster.projectId != projectId ||
139
                this.session.connectedAtlasCluster.clusterName != clusterName
140
            ) {
141
                throw new Error("Cluster connection aborted");
×
142
            }
143

144
            try {
22✔
145
                lastError = undefined;
22✔
146

147
                await this.session.connectToMongoDB(connectionString, this.config.connectOptions);
22✔
148
                break;
2✔
149
            } catch (err: unknown) {
150
                const error = err instanceof Error ? err : new Error(String(err));
20!
151

152
                lastError = error;
20✔
153

154
                logger.debug(
20✔
155
                    LogId.atlasConnectFailure,
156
                    "atlas-connect-cluster",
157
                    `error connecting to cluster: ${error.message}`
158
                );
159

160
                await sleep(500); // wait for 500ms before retrying
20✔
161
            }
162
        }
163

164
        if (lastError) {
2!
165
            if (
×
166
                this.session.connectedAtlasCluster?.projectId == projectId &&
×
167
                this.session.connectedAtlasCluster?.clusterName == clusterName &&
168
                this.session.connectedAtlasCluster?.username
169
            ) {
170
                void this.session.apiClient
×
171
                    .deleteDatabaseUser({
172
                        params: {
173
                            path: {
174
                                groupId: this.session.connectedAtlasCluster.projectId,
175
                                username: this.session.connectedAtlasCluster.username,
176
                                databaseName: "admin",
177
                            },
178
                        },
179
                    })
180
                    .catch((err: unknown) => {
181
                        const error = err instanceof Error ? err : new Error(String(err));
×
182
                        logger.debug(
×
183
                            LogId.atlasConnectFailure,
184
                            "atlas-connect-cluster",
185
                            `error deleting database user: ${error.message}`
186
                        );
187
                    });
188
            }
189
            this.session.connectedAtlasCluster = undefined;
×
190
            throw lastError;
×
191
        }
192

193
        logger.debug(
2✔
194
            LogId.atlasConnectSucceeded,
195
            "atlas-connect-cluster",
196
            `connected to cluster: ${this.session.connectedAtlasCluster?.clusterName}`
197
        );
198
    }
199

200
    protected async execute({ projectId, clusterName }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
201
        for (let i = 0; i < 60; i++) {
2✔
202
            const state = await this.queryConnection(projectId, clusterName);
42✔
203
            switch (state) {
42!
204
                case "connected": {
205
                    return {
2✔
206
                        content: [
207
                            {
208
                                type: "text",
209
                                text: `Connected to cluster "${clusterName}".`,
210
                            },
211
                        ],
212
                    };
213
                }
214
                case "connecting": {
215
                    break;
38✔
216
                }
217
                case "connected-to-other-cluster":
218
                case "disconnected":
219
                case "unknown":
220
                default: {
221
                    await this.session.disconnect();
2✔
222
                    const connectionString = await this.prepareClusterConnection(projectId, clusterName);
2✔
223

224
                    // try to connect for about 5 minutes asynchronously
225
                    void this.connectToCluster(projectId, clusterName, connectionString).catch((err: unknown) => {
2✔
226
                        const error = err instanceof Error ? err : new Error(String(err));
×
227
                        logger.error(
×
228
                            LogId.atlasConnectFailure,
229
                            "atlas-connect-cluster",
230
                            `error connecting to cluster: ${error.message}`
231
                        );
232
                    });
233
                    break;
2✔
234
                }
235
            }
236

237
            await sleep(500);
40✔
238
        }
239

240
        return {
×
241
            content: [
242
                {
243
                    type: "text" as const,
244
                    text: `Attempting to connect to cluster "${clusterName}"...`,
245
                },
246
                {
247
                    type: "text" as const,
248
                    text: `Warning: Provisioning a user and connecting to the cluster may take more time, please check again in a few seconds.`,
249
                },
250
                {
251
                    type: "text" as const,
252
                    text: `Warning: Make sure your IP address was enabled in the allow list setting of the Atlas cluster.`,
253
                },
254
            ],
255
        };
256
    }
257
}
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