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

mongodb-js / mongodb-mcp-server / 16778685993

06 Aug 2025 01:43PM UTC coverage: 81.981% (+0.7%) from 81.319%
16778685993

Pull #423

github

web-flow
Merge 76e8ab544 into a91618672
Pull Request #423: chore: refactor connections to use the new ConnectionManager to isolate long running processes like OIDC connections MCP-81

663 of 855 branches covered (77.54%)

Branch coverage included in aggregate %.

192 of 200 new or added lines in 7 files covered. (96.0%)

7 existing lines in 2 files now uncovered.

3418 of 4123 relevant lines covered (82.9%)

61.03 hits per line

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

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

11
const EXPIRY_MS = 1000 * 60 * 60 * 12; // 12 hours
2✔
12

13
function sleep(ms: number): Promise<void> {
53✔
14
    return new Promise((resolve) => setTimeout(resolve, ms));
53✔
15
}
53✔
16

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

26
    private queryConnection(
2✔
27
        projectId: string,
37✔
28
        clusterName: string
37✔
29
    ): "connected" | "disconnected" | "connecting" | "connected-to-other-cluster" | "unknown" {
37✔
30
        if (!this.session.connectedAtlasCluster) {
37✔
31
            if (this.session.isConnectedToMongoDB) {
2!
32
                return "connected-to-other-cluster";
×
33
            }
×
34
            return "disconnected";
2✔
35
        }
2✔
36

37
        const currentConectionState = this.session.connectionManager.currentConnectionState;
35✔
38
        if (
35✔
39
            this.session.connectedAtlasCluster.projectId !== projectId ||
35✔
40
            this.session.connectedAtlasCluster.clusterName !== clusterName
35✔
41
        ) {
37!
42
            return "connected-to-other-cluster";
×
43
        }
✔
44

45
        switch (currentConectionState.tag) {
35✔
46
            case "connecting":
37!
47
            case "disconnected": // we might still be calling Atlas APIs and not attempted yet to connect to MongoDB, but we are still "connecting"
37!
NEW
48
                return "connecting";
×
49
            case "connected":
37✔
50
                return "connected";
1✔
51
            case "errored":
37✔
52
                logger.debug(
34✔
53
                    LogId.atlasConnectFailure,
34✔
54
                    "atlas-connect-cluster",
34✔
55
                    `error querying cluster: ${currentConectionState.errorReason}`
34✔
56
                );
34✔
57
                return "unknown";
34✔
58
        }
37✔
59
    }
37✔
60

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

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

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

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

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

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

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

112
        const connectedAtlasCluster = {
2✔
113
            username,
2✔
114
            projectId,
2✔
115
            clusterName,
2✔
116
            expiryDate,
2✔
117
        };
2✔
118

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

124
        return { connectionString: cn.toString(), atlas: connectedAtlasCluster };
2✔
125
    }
2✔
126

127
    private async connectToCluster(connectionString: string, atlas: AtlasClusterConnectionInfo): Promise<void> {
2✔
128
        let lastError: Error | undefined = undefined;
2✔
129

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

136
        // try to connect for about 5 minutes
137
        for (let i = 0; i < 600; i++) {
2✔
138
            try {
19✔
139
                lastError = undefined;
19✔
140

141
                await this.session.connectToMongoDB({ connectionString, ...this.config.connectOptions, atlas });
19✔
142
                break;
2✔
143
            } catch (err: unknown) {
19✔
144
                const error = err instanceof Error ? err : new Error(String(err));
17!
145

146
                lastError = error;
17✔
147

148
                logger.debug(
17✔
149
                    LogId.atlasConnectFailure,
17✔
150
                    "atlas-connect-cluster",
17✔
151
                    `error connecting to cluster: ${error.message}`
17✔
152
                );
17✔
153

154
                await sleep(500); // wait for 500ms before retrying
17✔
155
            }
17✔
156

157
            if (
17✔
158
                !this.session.connectedAtlasCluster ||
17✔
159
                this.session.connectedAtlasCluster.projectId !== atlas.projectId ||
17✔
160
                this.session.connectedAtlasCluster.clusterName !== atlas.clusterName
17✔
161
            ) {
19!
NEW
162
                throw new Error("Cluster connection aborted");
×
NEW
163
            }
×
164
        }
19✔
165

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

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

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

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

239
            await sleep(500);
36✔
240
        }
36✔
241

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

© 2025 Coveralls, Inc