getCollections
Lists all available collections in the connected MongoDB database to help users identify data sources for querying and management operations.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- src/index.ts:26-46 (handler)The handler function for the 'getCollections' tool. It ensures a connection to the MongoDB database, lists all collections using db.listCollections(), maps them to names, joins with commas, and returns as text content. Handles connection and errors.this.mcpServer.tool("getCollections", async () => { try { let db = mongodbConnection.getDb(); if (!db) { await mongodbConnection.connect(this.MONGODB_URI); db = mongodbConnection.getDb(); if (!db) throw new Error("Failed to connect to database"); } const collections = await db.listCollections().toArray(); return { content: [ { type: "text", text: collections.map((c) => c.name).join(", ") }, ], }; } catch (error) { console.error(error); return { content: [{ type: "text", text: "Error: " + error }], }; } });
- src/mongodb/index.ts:3-32 (helper)The MongoDBConnection helper class used by the getCollections handler for database connection management, providing getDb() and connect() methods.export class MongoDBConnection { private client: MongoClient | null = null; private db: Db | null = null; async connect(databaseUrl: string) { try { this.client = new MongoClient(databaseUrl); await this.client.connect(); this.db = this.client.db(); return this.db; } catch (error) { console.error("MongoDB connection error:", error); throw error; } } async close() { await this.client?.close(); } getClient(): MongoClient | null { return this.client; } getDb(): Db | null { return this.db; } } export const mongodbConnection = new MongoDBConnection();
- src/index.ts:26-26 (registration)Registration of the 'getCollections' tool using mcpServer.tool() with the inline handler function.this.mcpServer.tool("getCollections", async () => {