Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/common/mongodb/connect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
import { State } from "../../state.js";
import config from "../../config.js";

export async function connectToMongoDB(connectionString: string, state: State): Promise<void> {
const provider = await NodeDriverServiceProvider.connect(connectionString, {
productDocsLink: "https://docs.mongodb.com/todo-mcp",
productName: "MongoDB MCP",
readConcern: config.connectOptions.readConcern,
readPreference: config.connectOptions.readPreference,
writeConcern: {
w: config.connectOptions.writeConcern,
},
timeoutMS: config.connectOptions.timeoutMS,
});

state.serviceProvider = provider;
state.credentials.connectionString = connectionString;
await state.persistCredentials();
}
61 changes: 52 additions & 9 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,34 @@ import argv from "yargs-parser";

import packageJson from "../package.json" with { type: "json" };
import fs from "fs";
import { ReadConcernLevel, ReadPreferenceMode, W } from "mongodb";
const { localDataPath, configPath } = getLocalDataPath();

// If we decide to support non-string config options, we'll need to extend the mechanism for parsing
// env variables.
interface UserConfig extends Record<string, string | undefined> {
interface UserConfig extends Record<string, unknown> {
apiBaseUrl: string;
clientId: string;
stateFile: string;
connectionString?: string;
connectOptions: {
readConcern: ReadConcernLevel;
readPreference: ReadPreferenceMode;
writeConcern: W;
timeoutMS: number;
};
}

const defaults: UserConfig = {
apiBaseUrl: "https://cloud.mongodb.com/",
clientId: "0oabtxactgS3gHIR0297",
stateFile: path.join(localDataPath, "state.json"),
connectOptions: {
readConcern: "local",
readPreference: "secondaryPreferred",
writeConcern: "majority",
timeoutMS: 30_000,
},
};

const mergedUserConfig = {
Expand Down Expand Up @@ -66,21 +79,51 @@ function getLocalDataPath(): { localDataPath: string; configPath: string } {
// are prefixed with `MDB_MCP_` and the keys match the UserConfig keys, but are converted
// to SNAKE_UPPER_CASE.
function getEnvConfig(): Partial<UserConfig> {
const camelCaseToSNAKE_UPPER_CASE = (str: string): string => {
return str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
};
function setValue(obj: Record<string, unknown>, path: string[], value: string): void {
const currentField = path.shift()!;
if (path.length === 0) {
const numberValue = Number(value);
if (!isNaN(numberValue)) {
obj[currentField] = numberValue;
return;
}

const booleanValue = value.toLocaleLowerCase();
if (booleanValue === "true" || booleanValue === "false") {
obj[currentField] = booleanValue === "true";
return;
}

obj[currentField] = value;
return;
}

const result: Partial<UserConfig> = {};
for (const key of Object.keys(defaults)) {
const envVarName = `MDB_MCP_${camelCaseToSNAKE_UPPER_CASE(key)}`;
if (process.env[envVarName]) {
result[key] = process.env[envVarName];
if (!obj[currentField]) {
obj[currentField] = {};
}

setValue(obj[currentField] as Record<string, unknown>, path, value);
}

const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(process.env).filter(
([key, value]) => value !== undefined && key.startsWith("MDB_MCP_")
)) {
const fieldPath = key
.replace("MDB_MCP_", "")
.split(".")
.map((part) => SNAKE_CASE_toCamelCase(part));

setValue(result, fieldPath, value!);
}

return result;
}

function SNAKE_CASE_toCamelCase(str: string): string {
return str.toLowerCase().replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace("_", ""));
}

// Gets the config supplied by the user as a JSON file. The file is expected to be located in the local data path
// and named `config.json`.
function getFileConfig(): Partial<UserConfig> {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/collectionIndexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class CollectionIndexesTool extends MongoDBToolBase {
protected operationType: DbOperationType = "read";

protected async execute({ database, collection }: ToolArgs<typeof DbOperationArgs>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const indexes = await provider.getIndexes(database, collection);

return {
Expand Down
15 changes: 2 additions & 13 deletions src/tools/mongodb/connect.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { z } from "zod";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
import { DbOperationType, MongoDBToolBase } from "./mongodbTool.js";
import { ToolArgs } from "../tool.js";
import { ErrorCodes, MongoDBError } from "../../errors.js";
import config from "../../config.js";
import { connectToMongoDB } from "../../common/mongodb/connect.js";

export class ConnectTool extends MongoDBToolBase {
protected name = "connect";
Expand Down Expand Up @@ -58,21 +58,10 @@ export class ConnectTool extends MongoDBToolBase {
throw new MongoDBError(ErrorCodes.InvalidParams, "Invalid connection options");
}

await this.connect(connectionString);
await connectToMongoDB(connectionString, this.state);

return {
content: [{ type: "text", text: `Successfully connected to ${connectionString}.` }],
};
}

private async connect(connectionString: string): Promise<void> {
const provider = await NodeDriverServiceProvider.connect(connectionString, {
productDocsLink: "https://docs.mongodb.com/todo-mcp",
productName: "MongoDB MCP",
});

this.state.serviceProvider = provider;
this.state.credentials.connectionString = connectionString;
await this.state.persistCredentials();
}
}
2 changes: 1 addition & 1 deletion src/tools/mongodb/create/insertMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class InsertManyTool extends MongoDBToolBase {
collection,
documents,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.insertMany(database, collection, documents);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/create/insertOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class InsertOneTool extends MongoDBToolBase {
collection,
document,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.insertOne(database, collection, document);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/createIndex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class CreateIndexTool extends MongoDBToolBase {
protected operationType: DbOperationType = "create";

protected async execute({ database, collection, keys }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const indexes = await provider.createIndexes(database, collection, [
{
key: keys,
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/delete/deleteMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class DeleteManyTool extends MongoDBToolBase {
collection,
filter,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.deleteMany(database, collection, filter);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/delete/deleteOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class DeleteOneTool extends MongoDBToolBase {
collection,
filter,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.deleteOne(database, collection, filter);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/delete/dropCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class DropCollectionTool extends MongoDBToolBase {
protected operationType: DbOperationType = "delete";

protected async execute({ database, collection }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.dropCollection(database, collection);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/delete/dropDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class DropDatabaseTool extends MongoDBToolBase {
protected operationType: DbOperationType = "delete";

protected async execute({ database }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.dropDatabase(database);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/metadata/collectionSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class CollectionSchemaTool extends MongoDBToolBase {
protected operationType: DbOperationType = "metadata";

protected async execute({ database, collection }: ToolArgs<typeof DbOperationArgs>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const documents = await provider.find(database, collection, {}, { limit: 5 }).toArray();
const schema = await parseSchema(documents);

Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/metadata/collectionStorageSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class CollectionStorageSizeTool extends MongoDBToolBase {
protected operationType: DbOperationType = "metadata";

protected async execute({ database, collection }: ToolArgs<typeof DbOperationArgs>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const [{ value }] = await provider
.aggregate(database, collection, [
{ $collStats: { storageStats: {} } },
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/metadata/dbStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class DbStatsTool extends MongoDBToolBase {
protected operationType: DbOperationType = "metadata";

protected async execute({ database }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.runCommandWithCheck(database, {
dbStats: 1,
scale: 1,
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/metadata/listCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class ListCollectionsTool extends MongoDBToolBase {
protected operationType: DbOperationType = "metadata";

protected async execute({ database }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const collections = await provider.listCollections(database);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/metadata/listDatabases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class ListDatabasesTool extends MongoDBToolBase {
protected operationType: DbOperationType = "metadata";

protected async execute(): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const dbs = (await provider.listDatabases("")).databases as { name: string; sizeOnDisk: bson.Long }[];

return {
Expand Down
8 changes: 7 additions & 1 deletion src/tools/mongodb/mongodbTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { State } from "../../state.js";
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { ErrorCodes, MongoDBError } from "../../errors.js";
import config from "../../config.js";
import { connectToMongoDB } from "../../common/mongodb/connect.js";

export const DbOperationArgs = {
database: z.string().describe("Database name"),
Expand All @@ -19,8 +21,12 @@ export abstract class MongoDBToolBase extends ToolBase {

protected abstract operationType: DbOperationType;

protected ensureConnected(): NodeDriverServiceProvider {
protected async ensureConnected(): Promise<NodeDriverServiceProvider> {
const provider = this.state.serviceProvider;
if (!provider && config.connectionString) {
await connectToMongoDB(config.connectionString, this.state);
}

if (!provider) {
throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, "Not connected to MongoDB");
}
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/read/aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class AggregateTool extends MongoDBToolBase {
collection,
pipeline,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const documents = await provider.aggregate(database, collection, pipeline).toArray();

const content: Array<{ text: string; type: "text" }> = [
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/read/count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class CountTool extends MongoDBToolBase {
protected operationType: DbOperationType = "metadata";

protected async execute({ database, collection, query }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const count = await provider.count(database, collection, query);

return {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/read/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class FindTool extends MongoDBToolBase {
limit,
sort,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const documents = await provider.find(database, collection, filter, { projection, limit, sort }).toArray();

const content: Array<{ text: string; type: "text" }> = [
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/update/renameCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class RenameCollectionTool extends MongoDBToolBase {
newName,
dropTarget,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.renameCollection(database, collection, newName, {
dropTarget,
});
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/update/updateMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class UpdateManyTool extends MongoDBToolBase {
update,
upsert,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.updateMany(database, collection, filter, update, {
upsert,
});
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mongodb/update/updateOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class UpdateOneTool extends MongoDBToolBase {
update,
upsert,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = this.ensureConnected();
const provider = await this.ensureConnected();
const result = await provider.updateOne(database, collection, filter, update, {
upsert,
});
Expand Down