Skip to content

chore: add tests for read operations #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/tools/mongodb/read/aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { z } from "zod";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { DbOperationArgs, MongoDBToolBase } from "../mongodbTool.js";
import { ToolArgs, OperationType } from "../../tool.js";
import { EJSON } from "bson";

export const AggregateArgs = {
pipeline: z.array(z.object({}).passthrough()).describe("An array of aggregation stages to execute"),
limit: z.number().optional().default(10).describe("The maximum number of documents to return"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit worried about this, we should run the MCP against a very very large collection and ask for all documents: #108

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That wasn't previously used, so figured it's better to remove it rather than lie to the model. Agree that we should investigate mechanisms to mitigate that risk post initial release.

};

export class AggregateTool extends MongoDBToolBase {
Expand All @@ -27,12 +27,12 @@ export class AggregateTool extends MongoDBToolBase {

const content: Array<{ text: string; type: "text" }> = [
{
text: `Found ${documents.length} documents in the collection \`${collection}\`:`,
text: `Found ${documents.length} documents in the collection "${collection}":`,
type: "text",
},
...documents.map((doc) => {
return {
text: JSON.stringify(doc),
text: EJSON.stringify(doc),
type: "text",
} as { text: string; type: "text" };
}),
Expand Down
34 changes: 29 additions & 5 deletions src/tools/mongodb/read/collectionIndexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,36 @@ export class CollectionIndexesTool extends MongoDBToolBase {
const indexes = await provider.getIndexes(database, collection);

return {
content: indexes.map((indexDefinition) => {
return {
text: `Field: ${indexDefinition.name}: ${JSON.stringify(indexDefinition.key)}`,
content: [
{
text: `Found ${indexes.length} indexes in the collection "${collection}":`,
type: "text",
};
}),
},
...(indexes.map((indexDefinition) => {
return {
text: `Name "${indexDefinition.name}", definition: ${JSON.stringify(indexDefinition.key)}`,
type: "text",
};
}) as { text: string; type: "text" }[]),
],
};
}

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 indexes for "${args.database}.${args.collection}" cannot be determined because the collection does not exist.`,
type: "text",
},
],
};
}

return super.handleError(error, args);
}
}
5 changes: 3 additions & 2 deletions src/tools/mongodb/read/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { DbOperationArgs, MongoDBToolBase } from "../mongodbTool.js";
import { ToolArgs, OperationType } from "../../tool.js";
import { SortDirection } from "mongodb";
import { EJSON } from "bson";

export const FindArgs = {
filter: z
Expand Down Expand Up @@ -44,12 +45,12 @@ export class FindTool extends MongoDBToolBase {

const content: Array<{ text: string; type: "text" }> = [
{
text: `Found ${documents.length} documents in the collection \`${collection}\`:`,
text: `Found ${documents.length} documents in the collection "${collection}":`,
type: "text",
},
...documents.map((doc) => {
return {
text: JSON.stringify(doc),
text: EJSON.stringify(doc),
type: "text",
} as { text: string; type: "text" };
}),
Expand Down
98 changes: 98 additions & 0 deletions tests/integration/tools/mongodb/read/aggregate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
databaseCollectionParameters,
validateToolMetadata,
validateThrowsForInvalidArguments,
getResponseElements,
} from "../../../helpers.js";
import { describeWithMongoDB, validateAutoConnectBehavior } from "../mongodbHelpers.js";

describeWithMongoDB("aggregate tool", (integration) => {
validateToolMetadata(integration, "aggregate", "Run an aggregation against a MongoDB collection", [
...databaseCollectionParameters,
{
name: "pipeline",
description: "An array of aggregation stages to execute",
type: "array",
required: true,
},
]);

validateThrowsForInvalidArguments(integration, "aggregate", [
{},
{ database: "test", collection: "foo" },
{ database: test, pipeline: [] },
{ database: "test", collection: "foo", pipeline: {} },
{ database: "test", collection: "foo", pipeline: [], extra: "extra" },
{ database: "test", collection: [], pipeline: [] },
{ database: 123, collection: "foo", pipeline: [] },
]);

it("can run aggragation on non-existent database", async () => {
await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "aggregate",
arguments: { database: "non-existent", collection: "people", pipeline: [{ $match: { name: "Peter" } }] },
});

const elements = getResponseElements(response.content);
expect(elements).toHaveLength(1);
expect(elements[0].text).toEqual('Found 0 documents in the collection "people":');
});

it("can run aggragation on an empty collection", async () => {
await integration.mongoClient().db(integration.randomDbName()).createCollection("people");

await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "aggregate",
arguments: {
database: integration.randomDbName(),
collection: "people",
pipeline: [{ $match: { name: "Peter" } }],
},
});

const elements = getResponseElements(response.content);
expect(elements).toHaveLength(1);
expect(elements[0].text).toEqual('Found 0 documents in the collection "people":');
});

it("can run aggragation on an existing collection", async () => {
const mongoClient = integration.mongoClient();
await mongoClient
.db(integration.randomDbName())
.collection("people")
.insertMany([
{ name: "Peter", age: 5 },
{ name: "Laura", age: 10 },
{ name: "Søren", age: 15 },
]);

await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "aggregate",
arguments: {
database: integration.randomDbName(),
collection: "people",
pipeline: [{ $match: { age: { $gt: 8 } } }, { $sort: { name: -1 } }],
},
});

const elements = getResponseElements(response.content);
expect(elements).toHaveLength(3);
expect(elements[0].text).toEqual('Found 2 documents in the collection "people":');
expect(JSON.parse(elements[1].text)).toEqual({ _id: expect.any(Object), name: "Søren", age: 15 });
expect(JSON.parse(elements[2].text)).toEqual({ _id: expect.any(Object), name: "Laura", age: 10 });
});

validateAutoConnectBehavior(integration, "aggregate", () => {
return {
args: {
database: integration.randomDbName(),
collection: "coll1",
pipeline: [{ $match: { name: "Liva" } }],
},
expectedResponse: 'Found 0 documents in the collection "coll1"',
};
});
});
98 changes: 98 additions & 0 deletions tests/integration/tools/mongodb/read/collectionIndexes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { IndexDirection } from "mongodb";
import {
databaseCollectionParameters,
validateToolMetadata,
validateThrowsForInvalidArguments,
getResponseElements,
databaseCollectionInvalidArgs,
} from "../../../helpers.js";
import { describeWithMongoDB, validateAutoConnectBehavior } from "../mongodbHelpers.js";

describeWithMongoDB("collectionIndexes tool", (integration) => {
validateToolMetadata(
integration,
"collection-indexes",
"Describe the indexes for a collection",
databaseCollectionParameters
);

validateThrowsForInvalidArguments(integration, "collection-indexes", databaseCollectionInvalidArgs);

it("can inspect indexes on non-existent database", async () => {
await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "collection-indexes",
arguments: { database: "non-existent", collection: "people" },
});

const elements = getResponseElements(response.content);
expect(elements).toHaveLength(1);
expect(elements[0].text).toEqual(
'The indexes for "non-existent.people" cannot be determined because the collection does not exist.'
);
});

it("returns the _id index for a new collection", async () => {
await integration.mongoClient().db(integration.randomDbName()).createCollection("people");

await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "collection-indexes",
arguments: {
database: integration.randomDbName(),
collection: "people",
},
});

const elements = getResponseElements(response.content);
expect(elements).toHaveLength(2);
expect(elements[0].text).toEqual('Found 1 indexes in the collection "people":');
expect(elements[1].text).toEqual('Name "_id_", definition: {"_id":1}');
});

it("returns all indexes for a collection", async () => {
await integration.mongoClient().db(integration.randomDbName()).createCollection("people");

const indexTypes: IndexDirection[] = [-1, 1, "2d", "2dsphere", "text", "hashed"];
for (const indexType of indexTypes) {
await integration
.mongoClient()
.db(integration.randomDbName())
.collection("people")
.createIndex({ [`prop_${indexType}`]: indexType });
}

await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "collection-indexes",
arguments: {
database: integration.randomDbName(),
collection: "people",
},
});

const elements = getResponseElements(response.content);
expect(elements).toHaveLength(indexTypes.length + 2);
expect(elements[0].text).toEqual(`Found ${indexTypes.length + 1} indexes in the collection "people":`);
expect(elements[1].text).toEqual('Name "_id_", definition: {"_id":1}');

for (const indexType of indexTypes) {
const index = elements.find((element) => element.text.includes(`prop_${indexType}`));
expect(index).toBeDefined();

let expectedDefinition = JSON.stringify({ [`prop_${indexType}`]: indexType });
if (indexType === "text") {
expectedDefinition = '{"_fts":"text"';
}

expect(index!.text).toContain(`definition: ${expectedDefinition}`);
}
});

validateAutoConnectBehavior(integration, "collection-indexes", () => {
return {
args: { database: integration.randomDbName(), collection: "coll1" },
expectedResponse: `The indexes for "${integration.randomDbName()}.coll1" cannot be determined because the collection does not exist.`,
};
});
});
Loading
Loading