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

mongodb-js / mongodb-mcp-server / 16779406063

06 Aug 2025 02:11PM UTC coverage: 81.424% (-0.4%) from 81.781%
16779406063

Pull #420

github

web-flow
Merge cc01ac54e into a35d18dd6
Pull Request #420: chore: allow logging unredacted messages MCP-103

679 of 874 branches covered (77.69%)

Branch coverage included in aggregate %.

161 of 291 new or added lines in 16 files covered. (55.33%)

7 existing lines in 4 files now uncovered.

3485 of 4240 relevant lines covered (82.19%)

63.42 hits per line

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

77.44
/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> {
48✔
14
    return new Promise((resolve) => setTimeout(resolve, ms));
48✔
15
}
48✔
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,
32✔
28
        clusterName: string
32✔
29
    ): "connected" | "disconnected" | "connecting" | "connected-to-other-cluster" | "unknown" {
32✔
30
        if (!this.session.connectedAtlasCluster) {
32✔
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;
30✔
38
        if (
30✔
39
            this.session.connectedAtlasCluster.projectId !== projectId ||
30✔
40
            this.session.connectedAtlasCluster.clusterName !== clusterName
30✔
41
        ) {
32!
42
            return "connected-to-other-cluster";
×
43
        }
✔
44

45
        switch (currentConectionState.tag) {
30✔
46
            case "connecting":
32!
47
            case "disconnected": // we might still be calling Atlas APIs and not attempted yet to connect to MongoDB, but we are still "connecting"
32!
48
                return "connecting";
×
49
            case "connected":
32✔
50
                return "connected";
1✔
51
            case "errored":
32✔
52
                logger.debug({
29✔
53
                    id: LogId.atlasConnectFailure,
29✔
54
                    context: "atlas-connect-cluster",
29✔
55
                    message: `error querying cluster: ${currentConectionState.errorReason}`,
29✔
56
                });
29✔
57
                return "unknown";
29✔
58
        }
32✔
59
    }
32✔
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
            id: LogId.atlasConnectAttempt,
2✔
132
            context: "atlas-connect-cluster",
2✔
133
            message: `attempting to connect to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,
2✔
134
            noRedaction: true,
2✔
135
        });
2✔
136

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

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

147
                lastError = error;
17✔
148

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

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

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

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

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

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

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

241
            await sleep(500);
31✔
242
        }
31✔
243

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