Skip to main content
Glama
yaoxiaolinglong

MCP-MongoDB-MySQL-Server

connect_mongodb

Establish a connection to a MongoDB database using a connection URL or configuration parameters to enable database operations through the MCP server.

Instructions

Connect to MongoDB database using URL or config

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlNoMongoDB URL (mongodb://user:pass@host:port/db)
workspaceNoProject workspace path
databaseNoMongoDB database name

Implementation Reference

  • The main handler function for the connect_mongodb tool. Processes input arguments to establish a MongoDB connection, supporting URL, workspace .env, or env vars. Closes prior connections and uses MongoClient.
    private async handleConnectMongoDB(args: any) {
      let config: MongoDBConfig | null = null;
    
      // 优先使用URL
      if (args.url) {
        config = this.parseMongoConnectionUrl(args.url);
      }
      // 其次使用工作区配置
      else if (args.workspace) {
        this.currentWorkspace = args.workspace;
        config = await this.loadMongoWorkspaceConfig(args.workspace);
      }
      // 最后使用单独的参数
      else if (args.database) {
        config = {
          uri: process.env.MONGODB_URI || 'mongodb://localhost:27017',
          database: args.database
        };
      }
    
      if (!config) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'No valid MongoDB configuration provided. Please provide either a URL, workspace path, or database name.'
        );
      }
    
      // 关闭现有连接
      if (this.mongoClient) {
        await this.mongoClient.close();
        this.mongoClient = null;
        this.mongoDB = null;
      }
    
      this.mongoConfig = config;
    
      try {
        await this.ensureMongoConnection();
        return {
          content: [
            {
              type: 'text',
              text: `Successfully connected to MongoDB database ${config.database}`
            }
          ]
        };
      } catch (error) {
        throw new McpError(
          ErrorCode.InternalError,
          `Failed to connect to MongoDB: ${getErrorMessage(error)}`
        );
      }
    }
  • src/index.ts:234-258 (registration)
    Registers the connect_mongodb tool in the server's tool list for ListTools requests, defining its name, description, and input schema.
    {
      name: 'connect_mongodb',
      description: 'Connect to MongoDB database using URL or config',
      inputSchema: {
        type: 'object',
        properties: {
          url: {
            type: 'string',
            description: 'MongoDB URL (mongodb://user:pass@host:port/db)',
            optional: true
          },
          workspace: {
            type: 'string',
            description: 'Project workspace path',
            optional: true
          },
          database: { 
            type: 'string', 
            description: 'MongoDB database name',
            optional: true 
          }
        },
        // No required fields - will try different connection methods
      },
    },
  • src/index.ts:552-553 (registration)
    Dispatcher switch case that routes connect_mongodb tool calls to the handleConnectMongoDB handler.
    case 'connect_mongodb':
      return await this.handleConnectMongoDB(request.params.arguments);
  • TypeScript interface defining the MongoDB configuration structure used by the connect_mongodb tool.
    interface MongoDBConfig {
      uri: string;
      database: string;
      options?: any;
    }
  • Helper function to parse a MongoDB connection URL into a MongoDBConfig object.
    private parseMongoConnectionUrl(url: string): MongoDBConfig {
      try {
        const parsed = parseUrl(url);
        if (!parsed.hostname) {
          throw new McpError(
            ErrorCode.InvalidParams,
            'Invalid MongoDB connection URL'
          );
        }
    
        const database = parsed.pathname?.slice(1);
        if (!database) {
          throw new McpError(
            ErrorCode.InvalidParams,
            'Database name must be specified in MongoDB URL'
          );
        }
    
        return {
          uri: url,
          database: database
        };
      } catch (error) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `Invalid MongoDB connection URL: ${getErrorMessage(error)}`
        );
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool establishes a connection but doesn't describe what that connection enables, whether it's persistent, what authentication is needed, error handling, or what happens if connection fails. For a connection tool with zero annotation coverage, this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single sentence that states the core purpose without any unnecessary words. It's front-loaded with the main action and doesn't waste space on redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a connection tool with no annotations and no output schema, the description is inadequate. It doesn't explain what successful connection enables, what the tool returns, error conditions, or how this fits with sibling MongoDB tools. The agent would struggle to use this effectively without additional context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so all parameters are documented in the schema. The description mentions 'URL or config' which aligns with the 'url' parameter but doesn't explain the relationship between parameters or when to use which. It adds minimal value beyond what's already in the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Connect to MongoDB database') and the method ('using URL or config'), which is specific and unambiguous. However, it doesn't explicitly distinguish this from sibling tools like 'connect_db' or other MongoDB tools, leaving some ambiguity about when to choose this specific connection method.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'connect_db' or other MongoDB operations. There's no mention of prerequisites, when this connection is needed, or what happens after connection. This leaves the agent without context for tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/yaoxiaolinglong/mcp-mongodb-mysql-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server