Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8370208

Browse files
Merge branch 'main' into MCP-158
2 parents e6b0d15 + 1f68c3e commit 8370208

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+4034
-2060
lines changed

‎package-lock.json

Lines changed: 2813 additions & 1668 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,15 +101,15 @@
101101
"@mongodb-js/devtools-connect": "^3.9.3",
102102
"@mongodb-js/devtools-proxy-support": "^0.5.2",
103103
"@mongosh/arg-parser": "^3.14.0",
104-
"@mongosh/service-provider-node-driver": "^3.12.0",
104+
"@mongosh/service-provider-node-driver": "~3.12.0",
105105
"@vitest/eslint-plugin": "^1.3.4",
106106
"bson": "^6.10.4",
107107
"express": "^5.1.0",
108108
"lru-cache": "^11.1.0",
109109
"mongodb": "^6.19.0",
110110
"mongodb-connection-string-url": "^3.0.2",
111111
"mongodb-log-writer": "^2.4.1",
112-
"mongodb-redact": "^1.1.8",
112+
"mongodb-redact": "^1.2.0",
113113
"mongodb-schema": "^12.6.2",
114114
"node-fetch": "^3.3.2",
115115
"node-machine-id": "1.1.12",

‎src/common/atlas/accessListUtils.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ export async function makeCurrentIpAccessListEntry(
2222
* If the IP is already present, this is a no-op.
2323
* @param apiClient The Atlas API client instance
2424
* @param projectId The Atlas project ID
25+
* @returns Promise<boolean> - true if a new IP access list entry was created, false if it already existed
2526
*/
26-
export async function ensureCurrentIpInAccessList(apiClient: ApiClient, projectId: string): Promise<void> {
27+
export async function ensureCurrentIpInAccessList(apiClient: ApiClient, projectId: string): Promise<boolean> {
2728
const entry = await makeCurrentIpAccessListEntry(apiClient, projectId, DEFAULT_ACCESS_LIST_COMMENT);
2829
try {
2930
await apiClient.createProjectIpAccessList({
@@ -35,6 +36,7 @@ export async function ensureCurrentIpInAccessList(apiClient: ApiClient, projectI
3536
context: "accessListUtils",
3637
message: `IP access list created: ${JSON.stringify(entry)}`,
3738
});
39+
return true;
3840
} catch (err) {
3941
if (err instanceof ApiClientError && err.response?.status === 409) {
4042
// 409 Conflict: entry already exists, log info
@@ -43,12 +45,13 @@ export async function ensureCurrentIpInAccessList(apiClient: ApiClient, projectI
4345
context: "accessListUtils",
4446
message: `IP address ${entry.ipAddress} is already present in the access list for project ${projectId}.`,
4547
});
46-
return;
48+
returnfalse;
4749
}
4850
apiClient.logger.warning({
4951
id: LogId.atlasIpAccessListAddFailure,
5052
context: "accessListUtils",
5153
message: `Error adding IP access list: ${err instanceof Error ? err.message : String(err)}`,
5254
});
5355
}
56+
return false;
5457
}

‎src/common/config.ts

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import os from "os";
33
import argv from "yargs-parser";
44
import type { CliOptions, ConnectionInfo } from "@mongosh/arg-parser";
55
import { generateConnectionInfoFromCliArgs } from "@mongosh/arg-parser";
6+
import { Keychain } from "./keychain.js";
7+
import type { Secret } from "./keychain.js";
68

79
// From: https://github.com/mongodb-js/mongosh/blob/main/packages/cli-repl/src/arg-parser.ts
810
const OPTIONS = {
@@ -87,7 +89,7 @@ const OPTIONS = {
8789
"greedy-arrays": true,
8890
"short-option-groups": false,
8991
},
90-
};
92+
}asconst;
9193

9294
function isConnectionSpecifier(arg: string | undefined): boolean {
9395
return (
@@ -185,12 +187,19 @@ function getExportsPath(): string {
185187
// are prefixed with `MDB_MCP_` and the keys match the UserConfig keys, but are converted
186188
// to SNAKE_UPPER_CASE.
187189
function parseEnvConfig(env: Record<string, unknown>): Partial<UserConfig> {
190+
const CONFIG_WITH_URLS: Set<string> = new Set<(typeof OPTIONS)["string"][number]>(["connectionString"]);
191+
188192
function setValue(obj: Record<string, unknown>, path: string[], value: string): void {
189193
const currentField = path.shift();
190194
if (!currentField) {
191195
return;
192196
}
193197
if (path.length === 0) {
198+
if (CONFIG_WITH_URLS.has(currentField)) {
199+
obj[currentField] = value;
200+
return;
201+
}
202+
194203
const numberValue = Number(value);
195204
if (!isNaN(numberValue)) {
196205
obj[currentField] = numberValue;
@@ -247,12 +256,19 @@ function SNAKE_CASE_toCamelCase(str: string): string {
247256
// whatever is in mongosh.
248257
function parseCliConfig(args: string[]): CliOptions {
249258
const programArgs = args.slice(2);
250-
const parsed = argv(programArgs, OPTIONS) as unknown as CliOptions &
259+
const parsed = argv(programArgs, OPTIONSasunknownasargv.Options) as unknown as CliOptions &
251260
UserConfig & {
252261
_?: string[];
253262
};
254263

255264
const positionalArguments = parsed._ ?? [];
265+
266+
// we use console.warn here because we still don't have our logging system configured
267+
// so we don't have a logger. For stdio, the warning will be received as a string in
268+
// the client and IDEs like VSCode do show the message in the log window. For HTTP,
269+
// it will be in the stdout of the process.
270+
warnAboutDeprecatedCliArgs({ ...parsed, _: positionalArguments }, console.warn);
271+
256272
// if we have a positional argument that matches a connection string
257273
// store it as the connection specifier and remove it from the argument
258274
// list, so it doesn't get misunderstood by the mongosh args-parser
@@ -264,6 +280,28 @@ function parseCliConfig(args: string[]): CliOptions {
264280
return parsed;
265281
}
266282

283+
export function warnAboutDeprecatedCliArgs(
284+
args: CliOptions &
285+
UserConfig & {
286+
_?: string[];
287+
},
288+
warn: (msg: string) => void
289+
): void {
290+
let usedDeprecatedArgument = false;
291+
// the first position argument should be used
292+
// instead of --connectionString, as it's how the mongosh works.
293+
if (args.connectionString) {
294+
usedDeprecatedArgument = true;
295+
warn(
296+
"The --connectionString argument is deprecated. Prefer using the first positional argument for the connection string or the MDB_MCP_CONNECTION_STRING environment variable."
297+
);
298+
}
299+
300+
if (usedDeprecatedArgument) {
301+
warn("Refer to https://www.mongodb.com/docs/mcp-server/get-started/ for setting up the MCP Server.");
302+
}
303+
}
304+
267305
function commaSeparatedToArray<T extends string[]>(str: string | string[] | undefined): T {
268306
if (str === undefined) {
269307
return [] as unknown as T;
@@ -287,6 +325,29 @@ function commaSeparatedToArray<T extends string[]>(str: string | string[] | unde
287325
return str as T;
288326
}
289327

328+
export function registerKnownSecretsInRootKeychain(userConfig: Partial<UserConfig>): void {
329+
const keychain = Keychain.root;
330+
331+
const maybeRegister = (value: string | undefined, kind: Secret["kind"]): void => {
332+
if (value) {
333+
keychain.register(value, kind);
334+
}
335+
};
336+
337+
maybeRegister(userConfig.apiClientId, "user");
338+
maybeRegister(userConfig.apiClientSecret, "password");
339+
maybeRegister(userConfig.awsAccessKeyId, "password");
340+
maybeRegister(userConfig.awsIamSessionToken, "password");
341+
maybeRegister(userConfig.awsSecretAccessKey, "password");
342+
maybeRegister(userConfig.awsSessionToken, "password");
343+
maybeRegister(userConfig.password, "password");
344+
maybeRegister(userConfig.tlsCAFile, "url");
345+
maybeRegister(userConfig.tlsCRLFile, "url");
346+
maybeRegister(userConfig.tlsCertificateKeyFile, "url");
347+
maybeRegister(userConfig.tlsCertificateKeyFilePassword, "password");
348+
maybeRegister(userConfig.username, "user");
349+
}
350+
290351
export function setupUserConfig({
291352
cli,
292353
env,
@@ -340,6 +401,7 @@ export function setupUserConfig({
340401
}
341402
}
342403

404+
registerKnownSecretsInRootKeychain(userConfig);
343405
return userConfig;
344406
}
345407

‎src/common/connectionErrorHandler.ts

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2+
import { ErrorCodes, type MongoDBError } from "./errors.js";
3+
import type { AnyConnectionState } from "./connectionManager.js";
4+
import type { ToolBase } from "../tools/tool.js";
5+
6+
export type ConnectionErrorHandler = (
7+
error: MongoDBError<ErrorCodes.NotConnectedToMongoDB | ErrorCodes.MisconfiguredConnectionString>,
8+
additionalContext: ConnectionErrorHandlerContext
9+
) => ConnectionErrorUnhandled | ConnectionErrorHandled;
10+
11+
export type ConnectionErrorHandlerContext = { availableTools: ToolBase[]; connectionState: AnyConnectionState };
12+
export type ConnectionErrorUnhandled = { errorHandled: false };
13+
export type ConnectionErrorHandled = { errorHandled: true; result: CallToolResult };
14+
15+
export const connectionErrorHandler: ConnectionErrorHandler = (error, { availableTools, connectionState }) => {
16+
const connectTools = availableTools
17+
.filter((t) => t.operationType === "connect")
18+
.sort((a, b) => a.category.localeCompare(b.category)); // Sort Atlas tools before MongoDB tools
19+
20+
// Find the first Atlas connect tool if available and suggest to the LLM to use it.
21+
// Note: if we ever have multiple Atlas connect tools, we may want to refine this logic to select the most appropriate one.
22+
const atlasConnectTool = connectTools?.find((t) => t.category === "atlas");
23+
const llmConnectHint = atlasConnectTool
24+
? `Note to LLM: prefer using the "${atlasConnectTool.name}" tool to connect to an Atlas cluster over using a connection string. Make sure to ask the user to specify a cluster name they want to connect to or ask them if they want to use the "list-clusters" tool to list all their clusters. Do not invent cluster names or connection strings unless the user has explicitly specified them. If they've previously connected to MongoDB using MCP, you can ask them if they want to reconnect using the same cluster/connection.`
25+
: "Note to LLM: do not invent connection strings and explicitly ask the user to provide one. If they have previously connected to MongoDB using MCP, you can ask them if they want to reconnect using the same connection string.";
26+
27+
const connectToolsNames = connectTools?.map((t) => `"${t.name}"`).join(", ");
28+
const additionalPromptForConnectivity: { type: "text"; text: string }[] = [];
29+
30+
if (connectionState.tag === "connecting" && connectionState.oidcConnectionType) {
31+
additionalPromptForConnectivity.push({
32+
type: "text",
33+
text: `The user needs to finish their OIDC connection by opening '${connectionState.oidcLoginUrl}' in the browser and use the following user code: '${connectionState.oidcUserCode}'`,
34+
});
35+
} else {
36+
additionalPromptForConnectivity.push({
37+
type: "text",
38+
text: connectToolsNames
39+
? `Please use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance or update the MCP server configuration to include a connection string. ${llmConnectHint}`
40+
: "There are no tools available to connect. Please update the configuration to include a connection string and restart the server.",
41+
});
42+
}
43+
44+
switch (error.code) {
45+
case ErrorCodes.NotConnectedToMongoDB:
46+
return {
47+
errorHandled: true,
48+
result: {
49+
content: [
50+
{
51+
type: "text",
52+
text: "You need to connect to a MongoDB instance before you can access its data.",
53+
},
54+
...additionalPromptForConnectivity,
55+
],
56+
isError: true,
57+
},
58+
};
59+
case ErrorCodes.MisconfiguredConnectionString:
60+
return {
61+
errorHandled: true,
62+
result: {
63+
content: [
64+
{
65+
type: "text",
66+
text: "The configured connection string is not valid. Please check the connection string and confirm it points to a valid MongoDB instance.",
67+
},
68+
{
69+
type: "text",
70+
text: connectTools
71+
? `Alternatively, you can use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance. ${llmConnectHint}`
72+
: "Please update the configuration to use a valid connection string and restart the server.",
73+
},
74+
],
75+
isError: true,
76+
},
77+
};
78+
79+
default:
80+
return { errorHandled: false };
81+
}
82+
};

‎src/common/connectionManager.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { EventEmitter } from "events";
22
import type { MongoClientOptions } from "mongodb";
3-
import ConnectionString from "mongodb-connection-string-url";
3+
import {ConnectionString} from "mongodb-connection-string-url";
44
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
55
import { type ConnectionInfo, generateConnectionInfoFromCliArgs } from "@mongosh/arg-parser";
66
import type { DeviceId } from "../helpers/deviceId.js";
@@ -199,19 +199,15 @@ export class MCPConnectionManager extends ConnectionManager {
199199
}
200200

201201
try {
202-
const connectionType = MCPConnectionManager.inferConnectionTypeFromSettings(
203-
this.userConfig,
204-
connectionInfo
205-
);
206-
if (connectionType.startsWith("oidc")) {
202+
if (connectionStringAuthType.startsWith("oidc")) {
207203
void this.pingAndForget(serviceProvider);
208204

209205
return this.changeState("connection-request", {
210206
tag: "connecting",
211207
connectedAtlasCluster: settings.atlas,
212208
serviceProvider,
213-
connectionStringAuthType: connectionType,
214-
oidcConnectionType: connectionType as OIDCConnectionAuthType,
209+
connectionStringAuthType,
210+
oidcConnectionType: connectionStringAuthType as OIDCConnectionAuthType,
215211
});
216212
}
217213

@@ -221,7 +217,7 @@ export class MCPConnectionManager extends ConnectionManager {
221217
tag: "connected",
222218
connectedAtlasCluster: settings.atlas,
223219
serviceProvider,
224-
connectionStringAuthType: connectionType,
220+
connectionStringAuthType,
225221
});
226222
} catch (error: unknown) {
227223
const errorReason = error instanceof Error ? error.message : `${error as string}`;

‎src/common/errors.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ export enum ErrorCodes {
44
ForbiddenCollscan = 1_000_002,
55
}
66

7-
export class MongoDBError extends Error {
7+
export class MongoDBError<ErrorCodeextendsErrorCodes=ErrorCodes> extends Error {
88
constructor(
9-
public code: ErrorCodes,
9+
public code: ErrorCode,
1010
message: string
1111
) {
1212
super(message);

‎src/common/exportsManager.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ type StoredExport = ReadyExport | InProgressExport;
5656
*
5757
* Ref Cursor: https://forum.cursor.com/t/cursor-mcp-resource-feature-support/50987
5858
* JIRA: https://jira.mongodb.org/browse/MCP-104 */
59-
type AvailableExport = Pick<StoredExport, "exportName" | "exportTitle" | "exportURI" | "exportPath">;
59+
exporttype AvailableExport = Pick<StoredExport, "exportName" | "exportTitle" | "exportURI" | "exportPath">;
6060

6161
export type ExportsManagerConfig = Pick<UserConfig, "exportsPath" | "exportTimeoutMs" | "exportCleanupIntervalMs">;
6262

‎src/common/keychain.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import type { Secret } from "mongodb-redact";
2+
export type { Secret } from "mongodb-redact";
3+
4+
/**
5+
* This class holds the secrets of a single server. Ideally, we might want to have a keychain
6+
* per session, but right now the loggers are set up by server and are not aware of the concept
7+
* of session and this would require a bigger refactor.
8+
*
9+
* Whenever we identify or create a secret (for example, Atlas login, CLI arguments...) we
10+
* should register them in the root Keychain (`Keychain.root.register`) or preferably
11+
* on the session keychain if available `this.session.keychain`.
12+
**/
13+
export class Keychain {
14+
private secrets: Secret[];
15+
private static rootKeychain: Keychain = new Keychain();
16+
17+
constructor() {
18+
this.secrets = [];
19+
}
20+
21+
static get root(): Keychain {
22+
return Keychain.rootKeychain;
23+
}
24+
25+
register(value: Secret["value"], kind: Secret["kind"]): void {
26+
this.secrets.push({ value, kind });
27+
}
28+
29+
clearAllSecrets(): void {
30+
this.secrets = [];
31+
}
32+
33+
get allSecrets(): Secret[] {
34+
return [...this.secrets];
35+
}
36+
}
37+
38+
export function registerGlobalSecretToRedact(value: Secret["value"], kind: Secret["kind"]): void {
39+
Keychain.root.register(value, kind);
40+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /