mongo-list-collections
Retrieve all collections from a MongoDB database to view available data structures and manage database organization.
Instructions
List all collections in a MongoDB database
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| database | Yes | Database name |
Implementation Reference
- src/index.ts:293-318 (registration)Registration of the 'mongo-list-collections' tool using server.tool(), including name, description, input schema, and inline handler function.server.tool( "mongo-list-collections", "List all collections in a MongoDB database", { database: z.string().describe("Database name"), }, async ({ database: dbName }) => { try { const db = await ensureConnection(dbName); const collections = await db.listCollections().toArray(); const collectionNames = collections.map(col => col.name); return { content: [ { type: "text", text: `Collections in database '${dbName}':\n${collectionNames.join('\n')}`, }, ], }; } catch (error) { throw new Error(`Failed to list collections: ${error instanceof Error ? error.message : 'Unknown error'}`); } } );
- src/index.ts:299-317 (handler)The core handler function that ensures a connection to the specified database, lists collections using db.listCollections(), extracts names, and returns formatted text output.async ({ database: dbName }) => { try { const db = await ensureConnection(dbName); const collections = await db.listCollections().toArray(); const collectionNames = collections.map(col => col.name); return { content: [ { type: "text", text: `Collections in database '${dbName}':\n${collectionNames.join('\n')}`, }, ], }; } catch (error) { throw new Error(`Failed to list collections: ${error instanceof Error ? error.message : 'Unknown error'}`); } }
- src/index.ts:296-298 (schema)Input schema using Zod, requiring a 'database' string parameter.{ database: z.string().describe("Database name"), },
- src/index.ts:88-100 (helper)Helper function to establish and cache MongoDB connection and database instance, called by the handler.async function ensureConnection(dbName: string): Promise<Db> { if (!mongoClient) { const uri = getMongoUri(); mongoClient = new MongoClient(uri); await mongoClient.connect(); } if (!databases.has(dbName)) { databases.set(dbName, mongoClient.db(dbName)); } return databases.get(dbName)!; }