MongoDB MCP Server

repository·main·Indexed 21 days ago

https://github.com/mongodb-js/mongodb-mcp-server

A Model Context Protocol (MCP) server that enables AI models to interact with MongoDB Databases and MongoDB Atlas. It provides tools for database management, Atlas administration, and assistant-based interactions. Supports deployment via AWS Bedrock AgentCore, Azure Container Apps, Docker, and npx, with support for both stdio and HTTP transport.

Tokens
59.9K
Snippets
170
Records
227
Agent score
75%

What's inside mongodb-mcp-server

  1. Configure vectorSearch in CreateIndexTool

    main

    When using CreateIndexTool with type: "vectorSearch", you can define fields with the following options:

    • filter: A path to a field used for filtering.
    • vector: Defines a vector field. Requires:
      • path: The field path.
      • numDimensions: Number of dimensions.
      • similarity: One of cosine, euclidean, or dotProduct.
      • quantization: One of binary, none, or scalar.
    • autoEmbed: Uses automated embedding. Requires:
      • path: The field path.
      • model: One of voyage-4, voyage-4-large, voyage-4-lite, or voyage-code-3.
      • modality: Currently supports text.
  2. Understand the ToolBase class and lifecycle

    main

    The ToolBase is the abstract foundation for all tools in the MCP server. It manages the lifecycle, configuration, and execution of a tool.

    Core Lifecycle and Methods

    • invoke(args, context): The primary method to trigger tool execution.
    • enable() / disable(): Methods to control the availability of the tool.
    • requiresConfirmation(): Indicates if the tool requires user approval before execution.
    • normalizeRawArgs(args): Used to clean and prepare incoming raw arguments.
    • execute(args, context): The internal method implemented by subclasses to perform the actual logic.

    Key Properties

    • name: The unique identifier for the tool.
    • category: The ToolCategory this tool belongs to (mongodb, atlas, atlas-local, or assistant).
    • operationType: The type of operation the tool performs.
    • outputSchema: A Zod schema defining the structure of the tool's return value.
  3. Reuse an existing Azure Container Apps Environment

    main

    Instead of letting the Bicep template create a new managed environment, you can deploy the MongoDB MCP server into an existing Azure Container Apps environment.

    1. Set containerAppEnvironmentName in your parameter file to the name of your existing environment.
    2. Verification: Before deploying, ensure the existing environment is in a Succeeded provisioning state by running:
    az containerapp env show \
       --resource-group <RESOURCE_GROUP> \
       --name <CONTAINER_APP_ENVIRONMENT_NAME> \
       --query properties.provisioningState -o tsv
    az containerapp env show \
       --resource-group <RESOURCE_GROUP> \
       --name <CONTAINER_APP_ENVIRONMENT_NAME> \
       --query properties.provisioningState -o tsv
  4. How to implement custom connection management

    main

    MongoDB connections are managed in an app-level MCPConnectionStore. You can extend connection management in two ways:

    1. Custom dialing, default bookkeeping: Construct your own MCPConnectionStore with a custom createConnectionManager. This is ideal if you want to use your own connection logic while keeping standard handle semantics (IDs, connection limits). You provide a view of this store to sessions via sessionOptions.connectionRegistry by overriding createServerForRequest in a StreamableHttpRunner.

    2. Full ownership: Implement the ConnectionRegistry interface yourself and supply it per session via sessionOptions.connectionRegistry. This is used for multi-tenant scoping or backing connections with durable storage. The server calls registry.close() when a session ends; you decide if that should release resources or be a no-op.

    import {
      MCPConnectionStore,
      StreamableHttpRunner,
      UserConfigSchema,
    } from "mongodb-mcp-server";
    import type { Server, TransportRequestContext } from "mongodb-mcp-server";
    
    // Extend StreamableHttpRunner and override createServerForRequest to serve
    // sessions from a store you own.
    class CustomStreamableHttpRunner extends StreamableHttpRunner {
      private readonly connectionStore = new MCPConnectionStore({
        userConfig: this.userConfig,
        logger: this.logger,
        deviceId: this.deviceId,
        createConnectionManager: () => new MyConnectionManager(),
      });
    
      protected override async createServerForRequest({
        request,
      }: {
        request: TransportRequestContext;
      }): Promise<Server> {
        return this.createServer({
          userConfig: this.userConfig,
          sessionOptions: {
            connectionRegistry: this.connectionStore.view(),
          },
        });
      }
    
      override async close(): Promise<void> {
        await super.close();
        await this.connectionStore.closeAll();
      }
    }
    
    const runner = new CustomStreamableHttpRunner({
      userConfig: UserConfigSchema.parse({}),
    });
    
    await runner.start();
  5. Configure proxy support for the MCP Server

    main

    The MCP Server supports standard proxy environment variables for outbound connections (Atlas API, OIDC, MongoDB cluster, and MongoDB Assistant). This behavior is consistent with mongosh.

    Proxy Environment Variables:

    • HTTPS_PROXY: Proxy for HTTPS requests (Atlas API, OIDC, Assistant).
    • HTTP_PROXY: Proxy for plain HTTP requests.
    • ALL_PROXY: Fallback proxy for all protocols.
    • NO_PROXY: Comma-separated list of hosts/domains to bypass the proxy.

    Example (bash/zsh):

    export HTTPS_PROXY="http://proxy.example.com:8080"
    export NO_PROXY="localhost,127.0.0.1,*.internal.example.com"

    Proxy in MongoDB Connection String: For cluster connections specifically, you can define a SOCKS5 proxy directly in the connection string using these parameters:

    • proxyHost
    • proxyPort
    • proxyUsername
    • proxyPassword

    Example Connection String:

    mongodb+srv://<host>/?proxyHost=127.0.0.1&proxyPort=1080&proxyUsername=user&proxyPassword=pass

    Certificate Authorities: The server trusts the operating system's certificate store in addition to bundled CAs, meaning corporate root certificates installed at the OS level are automatically recognized.

  6. Understand OperationType values

    main

    The OperationType type defines the classification of a tool's action. It is used to categorize what a tool does within the MCP ecosystem.

    Supported values:

    • metadata: Operations that retrieve information about the system or resources.
    • read: Operations that fetch data.
    • create: Operations that create new resources or data.
    • delete: Operations that remove resources or data.
    • update: Operations that modify existing resources or data.
    • connect: Operations related to establishing connections.
    export type OperationType = "metadata" | "read" | "create" | "delete" | "update" | "connect";
  7. Use environment variables for sensitive configuration

    main

    When configuring the MongoDB MCP Server, use the following environment variables to securely provide credentials and connection details. This prevents sensitive data from appearing in process lists.

    Sensitive Environment Variables:

    • MDB_MCP_API_CLIENT_ID: Your API Client ID.
    • MDB_MCP_API_CLIENT_SECRET: Your API Client Secret.
    • MDB_MCP_CONNECTION_STRING: Your MongoDB connection string.
  8. Implement Per-Session Configuration by extending StreamableHttpRunner

    main

    To provide user-specific permissions or dynamic settings (like different connection strings based on an environment header), extend StreamableHttpRunner and override the createServerForRequest method. This is the recommended pattern for per-session customization.

    Inside createServerForRequest, you can access the RequestContext to inspect headers (e.g., x-user-id or x-environment), fetch user permissions, and then call this.createServer({ userConfig: sessionConfig }) to return a server instance tailored to that specific request.

    import { UserConfigSchema, StreamableHttpRunner } from "mongodb-mcp-server";
    import type { Server, UserConfig } from "mongodb-mcp-server";
    import type { RequestContext } from "mongodb-mcp-server";
    
    class CustomStreamableHttpRunner extends StreamableHttpRunner {
      protected override async createServerForRequest({
        request,
      }: { 
        request: RequestContext; 
      }): Promise<Server> {
        const userId = request?.headers?.["x-user-id"];
        // ... logic to fetch permissions and build sessionConfig ...
        const sessionConfig: UserConfig = {
          ...this.userConfig,
          readOnly: true,
        };
    
        return this.createServer({
          userConfig: sessionConfig,
        });
      }
    }
  9. Manage Atlas Local deployments

    main

    The following tools are used for managing local MongoDB deployments (Atlas Local):

    • CreateDeploymentTool: Creates a new local deployment. Supports optional loadSampleData and imageTag configuration.
    • ConnectDeploymentTool: Connects to an existing local deployment using its deploymentName.
    // CreateDeploymentTool args:
    // {
    //   deploymentName?: string;
    //   loadSampleData?: boolean;
    //   imageTag?: string;
    // }
    //
    // ConnectDeploymentTool args:
    // {
    //   deploymentName: string;
    // }
  10. Assign appropriate MongoDB Atlas roles

    main

    When configuring access for the MongoDB MCP Server, use the principle of least privilege. Assign roles based on the specific tasks required:

    • List orgs/projects: Use Org Member or Org Read Only (at the Organization level).
    • Create new projects: Use Org Project Creator (at the Organization level).
    • View clusters/databases in a project: Use Project Read Only (at the Project level).
    • Create/manage clusters in a project: Use Project Cluster Manager (at the Project level).
    • Manage project access lists: Use Project IP Access List Admin (at the Project level).
    • Manage database users: Use Project Database Access Admin (at the Project level).
    • Manage stream processing resources: Use Project Stream Processing Owner (at the Project level).

    Best Practices:

    • Prefer project-level roles to limit scope.
    • Avoid using Organization Owner unless full administrative control over all projects is strictly necessary.
  11. How to customize MongoDB MCP Server behavior

    main

    You can customize the server using two primary approaches depending on whether you need static or dynamic configuration:

    1. Static Customization: Use the start({ serverOptions, sessionOptions }) method. This is ideal for configurations that apply globally to all sessions (e.g., setting up tools, error handlers, or the UI registry).
    2. Dynamic/Per-Session Customization: When using HTTP transport, extend StreamableHttpRunner and override the createServerForRequest method. This allows you to inspect incoming request headers, query parameters, or authentication context to configure the server uniquely for every individual request.
  12. Understand Connection States and Tags

    main

    Connections in the system transition through several states, identified by the ConnectionTag type. Common tags include:

    • connected: The connection is active and ready.
    • connecting: The connection is in progress (e.g., performing OIDC flows).
    • disconnected: The connection is not active.
    • errored: The connection encountered a failure.
    export type ConnectionTag = "connected" | "connecting" | "disconnected" | "errored";