Skip to content

feat: add logs tool #114

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 2 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
55 changes: 55 additions & 0 deletions src/tools/mongodb/metadata/logs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { MongoDBToolBase } from "../mongodbTool.js";
import { ToolArgs, OperationType } from "../../tool.js";
import { z } from "zod";

export class LogsTool extends MongoDBToolBase {
protected name = "mongodb-logs";
protected description = "Returns the most recent logged mongod events";
protected argsShape = {
type: z
.enum(["global", "startupWarnings"])
.optional()
.default("global")
.describe(
"The type of logs to return. Global returns all recent log entries, while startupWarnings returns only warnings and errors from when the process started."
),
limit: z
.number()
.int()
.max(1024)
.min(1)
.optional()
.default(50)
.describe("The maximum number of log entries to return."),
};

protected operationType: OperationType = "metadata";

protected async execute({ type, limit }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = await this.ensureConnected();

const result = await provider.runCommandWithCheck("admin", {
getLog: type,
});

const logs = (result.log as string[]).slice(0, limit);

return {
content: [
{
text: `Found: ${result.totalLinesWritten} messages`,
type: "text",
},

...logs.map(
(log) =>
({
text: log,
type: "text",
}) as const
),
],
};
}
}
2 changes: 2 additions & 0 deletions src/tools/mongodb/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { DropDatabaseTool } from "./delete/dropDatabase.js";
import { DropCollectionTool } from "./delete/dropCollection.js";
import { ExplainTool } from "./metadata/explain.js";
import { CreateCollectionTool } from "./create/createCollection.js";
import { LogsTool } from "./metadata/logs.js";

export const MongoDbTools = [
ConnectTool,
Expand All @@ -38,4 +39,5 @@ export const MongoDbTools = [
DropCollectionTool,
ExplainTool,
CreateCollectionTool,
LogsTool,
];
8 changes: 6 additions & 2 deletions tests/integration/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,17 @@ export function setupIntegrationTest(userConfig: UserConfig = config): Integrati
};
}

export function getResponseContent(content: unknown): string {
export function getResponseContent(content: unknown | { content: unknown }): string {
return getResponseElements(content)
.map((item) => item.text)
.join("\n");
}

export function getResponseElements(content: unknown): { type: string; text: string }[] {
export function getResponseElements(content: unknown | { content: unknown }): { type: string; text: string }[] {
if (typeof content === "object" && content !== null && "content" in content) {
content = (content as { content: unknown }).content;
}

expect(Array.isArray(content)).toBe(true);

const response = content as { type: string; text: string }[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describeWithMongoDB("dropDatabase tool", (integration) => {
it("can drop non-existing database", async () => {
let { databases } = await integration.mongoClient().db("").admin().listDatabases();

const preDropLength = databases.length;
expect(databases.find((db) => db.name === integration.randomDbName())).toBeUndefined();

await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
Expand All @@ -36,7 +36,6 @@ describeWithMongoDB("dropDatabase tool", (integration) => {

({ databases } = await integration.mongoClient().db("").admin().listDatabases());

expect(databases).toHaveLength(preDropLength);
expect(databases.find((db) => db.name === integration.randomDbName())).toBeUndefined();
});

Expand Down
18 changes: 8 additions & 10 deletions tests/integration/tools/mongodb/metadata/dbStats.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,13 @@ describeWithMongoDB("dbStats tool", (integration) => {
}
});

describe("when not connected", () => {
validateAutoConnectBehavior(integration, "db-stats", () => {
return {
args: {
database: integration.randomDbName(),
collection: "foo",
},
expectedResponse: `Statistics for database ${integration.randomDbName()}`,
};
});
validateAutoConnectBehavior(integration, "db-stats", () => {
return {
args: {
database: integration.randomDbName(),
collection: "foo",
},
expectedResponse: `Statistics for database ${integration.randomDbName()}`,
};
});
});
83 changes: 83 additions & 0 deletions tests/integration/tools/mongodb/metadata/logs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { validateToolMetadata, validateThrowsForInvalidArguments, getResponseElements } from "../../../helpers.js";
import { describeWithMongoDB, validateAutoConnectBehavior } from "../mongodbHelpers.js";

describeWithMongoDB("logs tool", (integration) => {
validateToolMetadata(integration, "mongodb-logs", "Returns the most recent logged mongod events", [
{
type: "string",
name: "type",
description:
"The type of logs to return. Global returns all recent log entries, while startupWarnings returns only warnings and errors from when the process started.",
required: false,
},
{
type: "integer",
name: "limit",
description: "The maximum number of log entries to return.",
required: false,
},
]);

validateThrowsForInvalidArguments(integration, "mongodb-logs", [
{ extra: true },
{ type: 123 },
{ type: "something" },
{ limit: 0 },
{ limit: true },
{ limit: 1025 },
]);

it("should return global logs", async () => {
await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "mongodb-logs",
arguments: {},
});

const elements = getResponseElements(response);

// Default limit is 50
expect(elements.length).toBeLessThanOrEqual(51);
expect(elements[0].text).toMatch(/Found: \d+ messages/);

for (let i = 1; i < elements.length; i++) {
const log = JSON.parse(elements[i].text);
expect(log).toHaveProperty("t");
expect(log).toHaveProperty("msg");
}
});

it("should return startupWarnings logs", async () => {
await integration.connectMcpClient();
const response = await integration.mcpClient().callTool({
name: "mongodb-logs",
arguments: {
type: "startupWarnings",
},
});

const elements = getResponseElements(response);
expect(elements.length).toBeLessThanOrEqual(51);
for (let i = 1; i < elements.length; i++) {
const log = JSON.parse(elements[i].text);
expect(log).toHaveProperty("t");
expect(log).toHaveProperty("msg");
expect(log).toHaveProperty("tags");
expect(log.tags).toContain("startupWarnings");
}
});

validateAutoConnectBehavior(integration, "mongodb-logs", () => {
return {
args: {
database: integration.randomDbName(),
collection: "foo",
},
validate: (content) => {
const elements = getResponseElements(content);
expect(elements.length).toBeLessThanOrEqual(51);
expect(elements[0].text).toMatch(/Found: \d+ messages/);
},
};
});
});
Loading