-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathconnectCluster.ts
More file actions
321 lines (282 loc) · 12.8 KB
/
connectCluster.ts
File metadata and controls
321 lines (282 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { type OperationType, type ToolArgs } from "../../tool.js";
import { AtlasToolBase } from "../atlasTool.js";
import { generateSecurePassword } from "../../../helpers/generatePassword.js";
import { LogId } from "../../../common/logger.js";
import { getConnectionString, inspectCluster } from "../../../common/atlas/cluster.js";
import { ensureCurrentIpInAccessList } from "../../../common/atlas/accessListUtils.js";
import type { AtlasClusterConnectionInfo } from "../../../common/connectionManager.js";
import { getDefaultRoleFromConfig } from "../../../common/atlas/roles.js";
import { AtlasArgs } from "../../args.js";
import type { ConnectionMetadata } from "../../../telemetry/types.js";
import type { ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
const addedIpAccessListMessage =
"Note: Your current IP address has been added to the Atlas project's IP access list to enable secure connection.";
const createdUserMessage =
"Note: A temporary user has been created to enable secure connection to the cluster. For more information, see https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations\n\nNote to LLM Agent: it is important to include the following link in your response to the user in case they want to get more information about the temporary user created: https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations";
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export const ConnectClusterArgs = {
projectId: AtlasArgs.projectId().describe("Atlas project ID"),
clusterName: AtlasArgs.clusterName().describe("Atlas cluster name"),
connectionType: AtlasArgs.connectionType().describe(
"Type of connection (standard, private, or privateEndpoint) to an Atlas cluster"
),
};
export class ConnectClusterTool extends AtlasToolBase {
public name = "atlas-connect-cluster";
protected description = "Connect to MongoDB Atlas cluster";
public operationType: OperationType = "connect";
protected argsShape = {
...ConnectClusterArgs,
};
private queryConnection(
projectId: string,
clusterName: string
): "connected" | "disconnected" | "connecting" | "connected-to-other-cluster" | "unknown" {
if (!this.session.connectedAtlasCluster) {
if (this.session.isConnectedToMongoDB) {
return "connected-to-other-cluster";
}
return "disconnected";
}
const currentConectionState = this.session.connectionManager.currentConnectionState;
if (
this.session.connectedAtlasCluster.projectId !== projectId ||
this.session.connectedAtlasCluster.clusterName !== clusterName
) {
return "connected-to-other-cluster";
}
switch (currentConectionState.tag) {
case "connecting":
case "disconnected": // we might still be calling Atlas APIs and not attempted yet to connect to MongoDB, but we are still "connecting"
return "connecting";
case "connected":
return "connected";
case "errored":
this.session.logger.debug({
id: LogId.atlasConnectFailure,
context: "atlas-connect-cluster",
message: `error querying cluster: ${currentConectionState.errorReason}`,
});
return "unknown";
}
}
private async prepareClusterConnection(
projectId: string,
clusterName: string,
connectionType: "standard" | "private" | "privateEndpoint" | undefined = "standard"
): Promise<{ connectionString: string; atlas: AtlasClusterConnectionInfo }> {
const cluster = await inspectCluster(this.session.apiClient, projectId, clusterName);
if (cluster.connectionStrings === undefined) {
throw new Error("Connection strings not available");
}
const connectionString = getConnectionString(cluster.connectionStrings, connectionType);
if (connectionString === undefined) {
throw new Error(
`Connection string for connection type "${connectionType}" is not available. Please ensure this connection type is set up in Atlas. See https://www.mongodb.com/docs/atlas/connect-to-database-deployment/#connect-to-an-atlas-cluster.`
);
}
const username = `mcpUser${Math.floor(Math.random() * 100000)}`;
const password = await generateSecurePassword();
const expiryDate = new Date(Date.now() + this.config.atlasTemporaryDatabaseUserLifetimeMs);
const role = getDefaultRoleFromConfig(this.config);
await this.session.apiClient.createDatabaseUser({
params: {
path: {
groupId: projectId,
},
},
body: {
databaseName: "admin",
groupId: projectId,
roles: [role],
scopes: [{ type: "CLUSTER", name: clusterName }],
username,
password,
awsIAMType: "NONE",
ldapAuthType: "NONE",
oidcAuthType: "NONE",
x509Type: "NONE",
deleteAfterDate: expiryDate.toISOString(),
description:
"MDB MCP Temporary user, see https://dochub.mongodb.org/core/mongodb-mcp-server-tools-considerations",
},
});
const connectedAtlasCluster = {
username,
projectId,
clusterName,
expiryDate,
};
const cn = new URL(connectionString);
cn.username = username;
cn.password = password;
cn.searchParams.set("authSource", "admin");
this.session.keychain.register(username, "user");
this.session.keychain.register(password, "password");
return { connectionString: cn.toString(), atlas: connectedAtlasCluster };
}
private async connectToCluster(connectionString: string, atlas: AtlasClusterConnectionInfo): Promise<void> {
let lastError: Error | undefined = undefined;
this.session.logger.debug({
id: LogId.atlasConnectAttempt,
context: "atlas-connect-cluster",
message: `attempting to connect to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,
noRedaction: true,
});
// try to connect for about 5 minutes
for (let i = 0; i < 600; i++) {
try {
lastError = undefined;
await this.session.connectToMongoDB({ connectionString, atlas });
break;
} catch (err: unknown) {
const error = err instanceof Error ? err : new Error(String(err));
lastError = error;
this.session.logger.debug({
id: LogId.atlasConnectFailure,
context: "atlas-connect-cluster",
message: `error connecting to cluster: ${error.message}`,
});
await sleep(500); // wait for 500ms before retrying
}
if (
!this.session.connectedAtlasCluster ||
this.session.connectedAtlasCluster.projectId !== atlas.projectId ||
this.session.connectedAtlasCluster.clusterName !== atlas.clusterName
) {
throw new Error("Cluster connection aborted");
}
}
if (lastError) {
if (
this.session.connectedAtlasCluster?.projectId === atlas.projectId &&
this.session.connectedAtlasCluster?.clusterName === atlas.clusterName &&
this.session.connectedAtlasCluster?.username
) {
void this.session.apiClient
.deleteDatabaseUser({
params: {
path: {
groupId: this.session.connectedAtlasCluster.projectId,
username: this.session.connectedAtlasCluster.username,
databaseName: "admin",
},
},
})
.catch((err: unknown) => {
const error = err instanceof Error ? err : new Error(String(err));
this.session.logger.debug({
id: LogId.atlasConnectFailure,
context: "atlas-connect-cluster",
message: `error deleting database user: ${error.message}`,
});
});
}
throw lastError;
}
this.session.logger.debug({
id: LogId.atlasConnectSucceeded,
context: "atlas-connect-cluster",
message: `connected to cluster: ${this.session.connectedAtlasCluster?.clusterName}`,
noRedaction: true,
});
}
protected async execute({
projectId,
clusterName,
connectionType,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const ipAccessListUpdated = await ensureCurrentIpInAccessList(this.session.apiClient, projectId);
let createdUser = false;
for (let i = 0; i < 60; i++) {
const state = this.queryConnection(projectId, clusterName);
switch (state) {
case "connected": {
const content: CallToolResult["content"] = [
{
type: "text",
text: `Connected to cluster "${clusterName}".`,
},
];
if (ipAccessListUpdated) {
content.push({
type: "text",
text: addedIpAccessListMessage,
});
}
if (createdUser) {
content.push({
type: "text",
text: createdUserMessage,
});
}
return { content };
}
case "connecting":
case "unknown": {
break;
}
case "connected-to-other-cluster":
case "disconnected":
default: {
await this.session.disconnect();
const { connectionString, atlas } = await this.prepareClusterConnection(
projectId,
clusterName,
connectionType
);
createdUser = true;
// try to connect for about 5 minutes asynchronously
void this.connectToCluster(connectionString, atlas).catch((err: unknown) => {
const error = err instanceof Error ? err : new Error(String(err));
this.session.logger.error({
id: LogId.atlasConnectFailure,
context: "atlas-connect-cluster",
message: `error connecting to cluster: ${error.message}`,
});
});
break;
}
}
await sleep(500);
}
const content: CallToolResult["content"] = [
{
type: "text" as const,
text: `Attempting to connect to cluster "${clusterName}"...`,
},
{
type: "text" as const,
text: `Warning: Provisioning a user and connecting to the cluster may take more time, please check again in a few seconds.`,
},
];
if (ipAccessListUpdated) {
content.push({
type: "text" as const,
text: addedIpAccessListMessage,
});
}
if (createdUser) {
content.push({
type: "text" as const,
text: createdUserMessage,
});
}
return { content };
}
protected override resolveTelemetryMetadata(
result: CallToolResult,
...args: Parameters<ToolCallback<typeof this.argsShape>>
): ConnectionMetadata {
const parentMetadata = super.resolveTelemetryMetadata(result, ...args);
const connectionMetadata = this.getConnectionInfoMetadata();
if (connectionMetadata && connectionMetadata.project_id !== undefined) {
// delete the project_id from the parent metadata to avoid duplication
delete parentMetadata.project_id;
}
return { ...parentMetadata, ...connectionMetadata };
}
}