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

mongodb-js / mongodb-mcp-server / 16296888938

15 Jul 2025 03:00PM UTC coverage: 77.39% (-0.2%) from 77.581%
16296888938

Pull #375

github

web-flow
Merge b7eee8130 into 48bce63a0
Pull Request #375: chore(tests): use the newer `@vitest/eslint-plugin` package

499 of 688 branches covered (72.53%)

Branch coverage included in aggregate %.

0 of 1 new or added line in 1 file covered. (0.0%)

8 existing lines in 1 file now uncovered.

2828 of 3611 relevant lines covered (78.32%)

57.02 hits per line

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

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

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

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

15
export class ConnectClusterTool extends AtlasToolBase {
4✔
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"),
68✔
21
        clusterName: z.string().describe("Atlas cluster name"),
68✔
22
    };
68✔
23

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

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

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

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

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

63
    private async prepareClusterConnection(projectId: string, clusterName: string): Promise<string> {
4✔
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 =
2✔
76
            this.config.readOnly ||
2✔
77
            (this.config.disabledTools?.includes("create") &&
2!
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: {
2✔
87
                path: {
2✔
88
                    groupId: projectId,
2✔
89
                },
2✔
90
            },
2✔
91
            body: {
2✔
92
                databaseName: "admin",
2✔
93
                groupId: projectId,
2✔
94
                roles: [
2✔
95
                    {
2✔
96
                        roleName,
2✔
97
                        databaseName: "admin",
2✔
98
                    },
2✔
99
                ],
2✔
100
                scopes: [{ type: "CLUSTER", name: clusterName }],
2✔
101
                username,
2✔
102
                password,
2✔
103
                awsIAMType: "NONE",
2✔
104
                ldapAuthType: "NONE",
2✔
105
                oidcAuthType: "NONE",
2✔
106
                x509Type: "NONE",
2✔
107
                deleteAfterDate: expiryDate.toISOString(),
2✔
108
            },
2✔
109
        });
2✔
110

111
        this.session.connectedAtlasCluster = {
2✔
112
            username,
2✔
113
            projectId,
2✔
114
            clusterName,
2✔
115
            expiryDate,
2✔
116
        };
2✔
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
    }
2✔
124

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

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

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

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

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

152
                lastError = error;
×
153

154
                logger.debug(
×
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
×
161
            }
×
162
        }
2✔
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,
2✔
195
            "atlas-connect-cluster",
2✔
196
            `connected to cluster: ${this.session.connectedAtlasCluster?.clusterName}`
2✔
197
        );
2✔
198
    }
2✔
199

200
    protected async execute({ projectId, clusterName }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
4✔
201
        for (let i = 0; i < 60; i++) {
2✔
202
            const state = await this.queryConnection(projectId, clusterName);
12✔
203
            switch (state) {
12✔
204
                case "connected": {
12✔
205
                    return {
2✔
206
                        content: [
2✔
207
                            {
2✔
208
                                type: "text",
2✔
209
                                text: `Connected to cluster "${clusterName}".`,
2✔
210
                            },
2✔
211
                        ],
2✔
212
                    };
2✔
213
                }
2✔
214
                case "connecting":
12✔
215
                case "unknown": {
12✔
216
                    break;
8✔
217
                }
8✔
218
                case "connected-to-other-cluster":
12!
219
                case "disconnected":
12✔
220
                default: {
12✔
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
                    });
2✔
233
                    break;
2✔
234
                }
2✔
235
            }
12✔
236

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

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