Skip to main content
Glama
mongodb-js

MongoDB MCP Server

Official
by mongodb-js

collection-storage-size

Read-only

Retrieve storage size for a MongoDB collection to monitor database capacity and optimize resource allocation.

Instructions

Gets the size of the collection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name

Implementation Reference

  • Executes an aggregation pipeline using $collStats to compute the total storage size of the specified collection, scales the value to human-readable units, and returns a formatted text response.
    protected async execute({ database, collection }: ToolArgs<typeof DbOperationArgs>): Promise<CallToolResult> {
        const provider = await this.ensureConnected();
        const [{ value }] = (await provider
            .aggregate(database, collection, [
                { $collStats: { storageStats: {} } },
                { $group: { _id: null, value: { $sum: "$storageStats.size" } } },
            ])
            .toArray()) as [{ value: number }];
    
        const { units, value: scaledValue } = CollectionStorageSizeTool.getStats(value);
    
        return {
            content: [
                {
                    text: `The size of "${database}.${collection}" is \`${scaledValue.toFixed(2)} ${units}\``,
                    type: "text",
                },
            ],
        };
    }
  • Zod schema defining the required input arguments for the tool: database and collection names.
    export const DbOperationArgs = {
        database: z.string().describe("Database name"),
        collection: z.string().describe("Collection name"),
    };
  • The tool class definition with the 'name' property set to 'collection-storage-size', which identifies and registers the tool.
    export class CollectionStorageSizeTool extends MongoDBToolBase {
        public name = "collection-storage-size";
  • Custom error handling for cases where the collection does not exist (NamespaceNotFound), providing a user-friendly message.
    protected handleError(
        error: unknown,
        args: ToolArgs<typeof this.argsShape>
    ): Promise<CallToolResult> | CallToolResult {
        if (error instanceof Error && "codeName" in error && error.codeName === "NamespaceNotFound") {
            return {
                content: [
                    {
                        text: `The size of "${args.database}.${args.collection}" cannot be determined because the collection does not exist.`,
                        type: "text",
                    },
                ],
                isError: true,
            };
        }
    
        return super.handleError(error, args);
    }
  • Utility function to convert raw storage size in bytes to a scaled human-readable value with appropriate units (bytes, KB, MB, GB).
    private static getStats(value: number): { value: number; units: string } {
        const kb = 1024;
        const mb = kb * 1024;
        const gb = mb * 1024;
    
        if (value > gb) {
            return { value: value / gb, units: "GB" };
        }
    
        if (value > mb) {
            return { value: value / mb, units: "MB" };
        }
        if (value > kb) {
            return { value: value / kb, units: "KB" };
        }
        return { value, units: "bytes" };
    }
Behavior3/5

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

Annotations already indicate readOnlyHint=true and destructiveHint=false, so the agent knows this is a safe read operation. The description adds no behavioral context beyond this, such as performance implications, rate limits, or what the size measurement includes (e.g., storage vs. document count). With annotations covering safety, a baseline score is appropriate, but more detail would enhance transparency.

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 with a single, direct sentence that front-loads the core purpose. There's no wasted language or redundancy, making it efficient for quick understanding, though this conciseness comes at the cost of omitted details like usage guidelines.

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 low complexity (2 required parameters, no output schema) and rich annotations (readOnlyHint, destructiveHint), the description is minimally adequate. However, it lacks context on return values (e.g., size units, format) and doesn't leverage the absence of an output schema to explain what the tool returns, leaving gaps in completeness for agent invocation.

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%, with clear documentation for both 'database' and 'collection' parameters. The description doesn't add any semantic details beyond what the schema provides, such as examples or constraints on valid names. Since the schema handles parameter documentation adequately, the baseline score reflects no additional value from the description.

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 with a specific verb ('Gets') and resource ('size of the collection'), making it immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'db-stats' or 'collection-schema', which might also provide size-related information, leaving some ambiguity about uniqueness.

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, such as needing an existing database and collection, or compare it to sibling tools like 'db-stats' for broader database statistics, leaving the agent to infer usage context independently.

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