Skip to main content
Glama
mongodb-js

MongoDB MCP Server

Official
by mongodb-js

collection-schema

Read-only

Analyze MongoDB collection structure to identify field types, patterns, and data formats for schema documentation and validation.

Instructions

Describe the schema for a collection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name
sampleSizeNoNumber of documents to sample for schema inference
responseBytesLimitNoThe maximum number of bytes to return in the response. This value is capped by the server's configured maxBytesPerQuery and cannot be exceeded.

Implementation Reference

  • The main handler function that connects to MongoDB, samples documents from the specified collection, infers the schema using getSimplifiedSchema, and returns a formatted response with the schema or an error message if empty.
    protected async execute(
        { database, collection, sampleSize, responseBytesLimit }: ToolArgs<typeof this.argsShape>,
        { signal }: ToolExecutionContext
    ): Promise<CallToolResult> {
        const provider = await this.ensureConnected();
        const cursor = provider.aggregate(database, collection, [
            { $sample: { size: Math.min(sampleSize, MAXIMUM_SAMPLE_SIZE_HARD_LIMIT) } },
        ]);
        const { cappedBy, documents } = await collectCursorUntilMaxBytesLimit({
            cursor,
            configuredMaxBytesPerQuery: this.config.maxBytesPerQuery,
            toolResponseBytesLimit: responseBytesLimit,
            abortSignal: signal,
        });
        const schema = await getSimplifiedSchema(documents);
    
        if (isObjectEmpty(schema)) {
            return {
                content: [
                    {
                        text: `Could not deduce the schema for "${database}.${collection}". This may be because it doesn't exist or is empty.`,
                        type: "text",
                    },
                ],
            };
        }
    
        const fieldsCount = Object.keys(schema).length;
        const header = `Found ${fieldsCount} fields in the schema for "${database}.${collection}"`;
        const cappedWarning =
            cappedBy !== undefined
                ? `\nThe schema was inferred from a subset of documents due to the response size limit. (${cappedBy})`
                : "";
    
        return {
            content: formatUntrustedData(`${header}${cappedWarning}`, JSON.stringify(schema)),
        };
    }
  • Input schema definition using Zod, extending DbOperationArgs with sampleSize and responseBytesLimit parameters.
    protected argsShape = {
        ...DbOperationArgs,
        sampleSize: z.number().optional().default(50).describe("Number of documents to sample for schema inference"),
        responseBytesLimit: z
            .number()
            .optional()
            .default(ONE_MB)
            .describe(
                `The maximum number of bytes to return in the response. This value is capped by the server's configured maxBytesPerQuery and cannot be exceeded.`
            ),
    };
  • Registers the CollectionSchemaTool (via MongoDbTools) by including it in the AllTools array of all available tool classes.
    import * as AtlasTools from "./atlas/tools.js";
    import * as AtlasLocalTools from "./atlasLocal/tools.js";
    import * as MongoDbTools from "./mongodb/tools.js";
    import type { ToolClass } from "./tool.js";
    
    // Export the collection of tools for easier reference
    export const AllTools: ToolClass[] = Object.values({
        ...MongoDbTools,
        ...AtlasTools,
        ...AtlasLocalTools,
    });
  • Re-exports the CollectionSchemaTool to make it available in the MongoDB tools namespace used by the main tools index.
    export { CollectionSchemaTool } from "./metadata/collectionSchema.js";
Behavior3/5

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

Annotations indicate readOnlyHint=true and destructiveHint=false, so the agent knows this is a safe read operation. The description adds context about schema inference (sampling documents), which isn't covered by annotations. However, it doesn't disclose behavioral traits like rate limits, authentication needs, or what happens if the collection doesn't exist. With annotations covering safety, a 3 is appropriate—some added value but limited behavioral detail.

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 a single, efficient sentence: 'Describe the schema for a collection.' It's front-loaded with the core purpose, has zero wasted words, and is appropriately sized for a tool with clear annotations and schema. Every word earns its place.

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?

Given the tool's complexity (schema inference with sampling), annotations cover safety, and schema coverage is 100%, the description is minimally adequate. However, with no output schema, it doesn't explain what the schema description includes (e.g., field types, nested structures) or potential limitations (e.g., inference accuracy). For a read-only tool with good schema support, it meets basic needs but lacks depth.

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 fully documents all four parameters (database, collection, sampleSize, responseBytesLimit). The description doesn't add any parameter-specific semantics beyond what the schema provides (e.g., it doesn't explain how sampleSize affects accuracy or what responseBytesLimit entails). Baseline 3 is correct 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.

Purpose4/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: 'Describe the schema for a collection' specifies the verb ('describe') and resource ('schema for a collection'). It distinguishes from siblings like 'collection-indexes' or 'collection-storage-size' by focusing on schema inference rather than indexes or storage metrics. However, it doesn't explicitly differentiate from 'list-collections' or 'find', which might also involve schema-related operations.

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. It doesn't mention prerequisites (e.g., needing database/collection names), exclusions, or compare to siblings like 'find' (which might return data samples) or 'list-collections' (which lists collections without schema details). Usage is implied but not explicitly stated.

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

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