Skip to main content
Glama
jonfreeland

MongoDB MCP Server

by jonfreeland

get_schema

Analyze sample documents to infer the structure of a MongoDB collection, helping understand data organization before querying.

Instructions

Infer schema from a collection by analyzing sample documents.

Best Practice: Use this before querying to understand collection structure.

Example: use_mcp_tool with server_name: "mongodb", tool_name: "get_schema", arguments: { "collection": "users", "sampleSize": 100 }

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNoDatabase name (optional if default database is configured)
collectionYesCollection name
sampleSizeNoNumber of documents to sample (default: 100)

Implementation Reference

  • Main handler for the 'get_schema' tool. Samples up to 1000 documents from the specified collection, infers the schema using the inferSchema helper, and returns the schema as JSON.
    case 'get_schema': {
      const { database, collection, sampleSize = 100 } = request.params.arguments as {
        database?: string;
        collection: string;
        sampleSize?: number;
      };
      const dbName = database || this.defaultDatabase;
      if (!dbName) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'Database name is required when no default database is configured'
        );
      }
      const db = client.db(dbName);
      const docs = await db
        .collection(collection)
        .find()
        .limit(sampleSize)
        .toArray();
      
      if (docs.length === 0) {
        return {
          content: [
            {
              type: 'text',
              text: 'No documents found in collection',
            },
          ],
        };
      }
    
      const schema = await this.inferSchema(docs);
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(schema, null, 2),
          },
        ],
      };
    }
  • src/index.ts:336-369 (registration)
    Registration of the 'get_schema' tool in the ListTools response, including name, detailed description, and input schema definition.
              name: 'get_schema',
              description: `Infer schema from a collection by analyzing sample documents.
            
    Best Practice: Use this before querying to understand collection structure.
    
    Example:
    use_mcp_tool with
      server_name: "mongodb",
      tool_name: "get_schema",
      arguments: {
        "collection": "users",
        "sampleSize": 100
      }`,
              inputSchema: {
                type: 'object',
                properties: {
                  database: {
                    type: 'string',
                    description: 'Database name (optional if default database is configured)',
                  },
                  collection: {
                    type: 'string',
                    description: 'Collection name',
                  },
                  sampleSize: {
                    type: 'number',
                    description: 'Number of documents to sample (default: 100)',
                    minimum: 1,
                    maximum: 1000,
                  },
                },
                required: ['collection'],
              },
            },
  • Input schema definition for the 'get_schema' tool, specifying parameters: database (optional), collection (required), sampleSize (1-1000).
    inputSchema: {
      type: 'object',
      properties: {
        database: {
          type: 'string',
          description: 'Database name (optional if default database is configured)',
        },
        collection: {
          type: 'string',
          description: 'Collection name',
        },
        sampleSize: {
          type: 'number',
          description: 'Number of documents to sample (default: 100)',
          minimum: 1,
          maximum: 1000,
        },
      },
      required: ['collection'],
    },
  • Helper method inferSchema that recursively analyzes sample documents to infer the data schema, handling nested objects, arrays, primitives, and providing types, examples, and nullability.
    private async inferSchema(documents: any[], path = '', schema: any = {}) {
      for (const doc of documents) {
        Object.entries(doc).forEach(([key, value]) => {
          const fullPath = path ? `${path}.${key}` : key;
          
          if (Array.isArray(value)) {
            if (!schema[fullPath]) {
              schema[fullPath] = { type: 'array' };
            }
            
            // Handle empty arrays
            if (value.length === 0) {
              schema[fullPath].items = { type: 'unknown' };
            } 
            // Handle arrays of primitives
            else if (typeof value[0] !== 'object' || value[0] === null) {
              schema[fullPath].items = { type: typeof value[0] };
            }
            // Handle arrays of objects
            else {
              schema[fullPath].items = { type: 'object', properties: {} };
              this.inferSchema(value, `${fullPath}.items.properties`, schema);
            }
          } else if (value && typeof value === 'object') {
            if (!schema[fullPath]) {
              schema[fullPath] = { type: 'object', properties: {} };
            }
            this.inferSchema([value], `${fullPath}.properties`, schema);
          } else {
            if (!schema[fullPath]) {
              schema[fullPath] = { 
                type: typeof value,
                example: value, // Add example value for better understanding
                nullable: value === null
              };
            }
          }
        });
      }
      return schema;
    }
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It explains the core behavior (inferring schema by analyzing samples) and mentions a best practice, but doesn't disclose important behavioral aspects like whether this is a read-only operation, potential performance impact of sampling, error conditions, or what the output format looks like. The description adds some context but leaves significant gaps.

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

Conciseness4/5

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

The description is well-structured with purpose statement, best practice guidance, and an example. It's appropriately sized and front-loaded with the core functionality. The example could be slightly more concise, but overall the description earns its place with useful information.

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

Completeness3/5

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

For a schema inference tool with 3 parameters and no output schema, the description provides good purpose and usage guidance but lacks details about the output format, error handling, and behavioral constraints. The absence of annotations means the description should do more to explain what kind of schema is returned and any limitations of the inference process.

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 the schema already documents all three parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema descriptions. The example shows parameter usage but doesn't provide additional semantic context. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the tool's purpose with specific verb ('Infer schema') and resource ('from a collection'), and distinguishes it from siblings by focusing on schema analysis rather than querying or data retrieval. It explicitly mentions analyzing sample documents, which differentiates it from tools like get_indexes or get_collection_stats.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool ('Use this before querying to understand collection structure'), which clearly positions it as a preparatory step for other operations like querying. This distinguishes it from siblings such as query, sample_data, or find_by_ids that perform actual data operations.

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/jonfreeland/mongodb-mcp'

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