Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
97 changes: 97 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.17.4",
"@mongodb-js-preview/atlas-local": "^0.0.0-preview.1",
"@mongodb-js/device-id": "^0.3.1",
"@mongodb-js/devtools-connect": "^3.9.3",
"@mongodb-js/devtools-proxy-support": "^0.5.2",
Expand Down
9 changes: 5 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { Session } from "./common/session.js";
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { AtlasTools } from "./tools/atlas/tools.js";
import { AtlasLocalTools } from "./tools/atlasLocal/tools.js";
import { BuildAtlasLocalTools } from "./tools/atlasLocal/tools.js";
import { MongoDbTools } from "./tools/mongodb/tools.js";
import { Resources } from "./resources/resources.js";
import type { LogLevel } from "./common/logger.js";
Expand Down Expand Up @@ -62,7 +62,7 @@ export class Server {
this.mcpServer.server.registerCapabilities({ logging: {}, resources: { listChanged: true, subscribe: true } });

// TODO: Eventually we might want to make tools reactive too instead of relying on custom logic.
this.registerTools();
await this.registerTools();

// This is a workaround for an issue we've seen with some models, where they'll see that everything in the `arguments`
// object is optional, and then not pass it at all. However, the MCP server expects the `arguments` object to be if
Expand Down Expand Up @@ -193,8 +193,9 @@ export class Server {
this.telemetry.emitEvents([event]).catch(() => {});
}

private registerTools(): void {
for (const toolConstructor of [...AtlasTools, ...AtlasLocalTools, ...MongoDbTools]) {
private async registerTools(): Promise<void> {
const atlasLocalTools = await BuildAtlasLocalTools();
for (const toolConstructor of [...AtlasTools, ...atlasLocalTools, ...MongoDbTools]) {
const tool = new toolConstructor(this.session, this.userConfig, this.telemetry);
if (tool.register(this)) {
this.tools.push(tool);
Expand Down
18 changes: 17 additions & 1 deletion src/tools/atlasLocal/atlasLocalTool.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import type { ToolArgs, ToolCategory } from "../tool.js";
import type { TelemetryToolMetadata, ToolArgs, ToolCategory } from "../tool.js";
import { ToolBase } from "../tool.js";
import type { ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
import type AtlasLocal from "@mongodb-js-preview/atlas-local";

export abstract class AtlasLocalToolBase extends ToolBase {
public category: ToolCategory = "atlas-local";
// Will be injected by BuildAtlasLocalTools() in atlasLocal/tools.ts
public client?: AtlasLocal.Client;

protected verifyAllowed(): boolean {
return this.client !== undefined && super.verifyAllowed();
}

protected handleError(
error: unknown,
Expand All @@ -14,4 +22,12 @@ export abstract class AtlasLocalToolBase extends ToolBase {
// For other types of errors, use the default error handling from the base class
return super.handleError(error, args);
}

protected resolveTelemetryMetadata(
...args: Parameters<ToolCallback<typeof this.argsShape>>
): TelemetryToolMetadata {
// TODO: include deployment id in the metadata where possible
void args; // this shuts up the eslint rule until we implement the TODO above
return {};
}
}
55 changes: 55 additions & 0 deletions src/tools/atlasLocal/read/listDeployments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { AtlasLocalToolBase } from "../atlasLocalTool.js";
import type { OperationType } from "../../tool.js";
import { formatUntrustedData } from "../../tool.js";
import type { Deployment } from "@mongodb-js-preview/atlas-local";

export class ListDeploymentsTool extends AtlasLocalToolBase {
public name = "atlas-local-list-deployments";
protected description = "List MongoDB Atlas local deployments";
public operationType: OperationType = "read";
protected argsShape = {};

protected async execute(): Promise<CallToolResult> {
// Get the client
const client = this.client;

// If the client is not found, throw an error
// This should never happen, because the tool should have been disabled.
// verifyAllowed in the base class returns false if the client is not found
if (!client) {
throw new Error("Atlas Local client not found, tool should have been disabled.");
}

// List the deployments
const deployments = await client.listDeployments();

// Format the deployments
return this.formatDeploymentsTable(deployments);
}

private formatDeploymentsTable(deployments: Deployment[]): CallToolResult {
// Check if deployments are absent
if (!deployments?.length) {
return {
content: [{ type: "text", text: "No deployments found." }],
};
}

// Turn the deployments into a markdown table
const rows = deployments
.map((deployment) => {
return `${deployment.name || "Unknown"} | ${deployment.state} | ${deployment.mongodbVersion}`;
})
.join("\n");

return {
content: formatUntrustedData(
`Found ${deployments.length} deployments:`,
`Deployment Name | State | MongoDB Version
----------------|----------------|----------------
${rows}`
),
};
}
}
34 changes: 33 additions & 1 deletion src/tools/atlasLocal/tools.ts
Original file line number Diff line number Diff line change
@@ -1 +1,33 @@
export const AtlasLocalTools = [];
import { ListDeploymentsTool } from "./read/listDeployments.js";
import type AtlasLocal from "@mongodb-js-preview/atlas-local";

// Don't use this directly, use BuildAtlasLocalTools instead
const atlasLocalTools = [ListDeploymentsTool];

// Build the Atlas Local tools
export const BuildAtlasLocalTools = async (): Promise<typeof atlasLocalTools> => {
// Initialize the Atlas Local client
const client = await GetAtlasLocalClient();

// If the client is found, set it on the tools
// On unsupported platforms, the client will be undefined
if (client) {
// Set the client on the tools
atlasLocalTools.forEach((tool) => {
tool.prototype.client = client;
});
}

return atlasLocalTools;
};

export const GetAtlasLocalClient = async (): Promise<AtlasLocal.Client | undefined> => {
try {
const { Client: AtlasLocalClient } = await import("@mongodb-js-preview/atlas-local");
return AtlasLocalClient.connect();
} catch (error) {
// We only get here if the user is running atlas-local on a unsupported platform
console.warn("Atlas Local native binding not available:", error);
return undefined;
}
};
4 changes: 3 additions & 1 deletion tests/integration/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ describe("Server integration test", () => {
expectDefined(tools);
expect(tools.tools.length).toBeGreaterThan(0);

const atlasTools = tools.tools.filter((tool) => tool.name.startsWith("atlas-"));
const atlasTools = tools.tools.filter(
(tool) => tool.name.startsWith("atlas-") && !tool.name.startsWith("atlas-local-")
);
expect(atlasTools.length).toBeLessThanOrEqual(0);
});
},
Expand Down
61 changes: 61 additions & 0 deletions tests/integration/tools/atlas-local/listDeployments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {
defaultDriverOptions,
defaultTestConfig,
expectDefined,
getResponseElements,
setupIntegrationTest,
} from "../../helpers.js";
import { describe, expect, it } from "vitest";

const isMacOSInGitHubActions = process.platform === "darwin" && process.env.GITHUB_ACTIONS === "true";

describe("atlas-local-list-deployments", () => {
const integration = setupIntegrationTest(
() => defaultTestConfig,
() => defaultDriverOptions
);

it.skipIf(isMacOSInGitHubActions)("should have the atlas-local-list-deployments tool", async () => {
const { tools } = await integration.mcpClient().listTools();
const listDeployments = tools.find((tool) => tool.name === "atlas-local-list-deployments");
expectDefined(listDeployments);
});

it.skipIf(!isMacOSInGitHubActions)(
"[MacOS in GitHub Actions] should not have the atlas-local-list-deployments tool",
async () => {
const { tools } = await integration.mcpClient().listTools();
const listDeployments = tools.find((tool) => tool.name === "atlas-local-list-deployments");
expect(listDeployments).toBeUndefined();
}
);

it.skipIf(isMacOSInGitHubActions)("should have correct metadata", async () => {
const { tools } = await integration.mcpClient().listTools();
const listDeployments = tools.find((tool) => tool.name === "atlas-local-list-deployments");
expectDefined(listDeployments);
expect(listDeployments.inputSchema.type).toBe("object");
expectDefined(listDeployments.inputSchema.properties);
expect(listDeployments.inputSchema.properties).toEqual({});
});

it.skipIf(isMacOSInGitHubActions)("should not crash when calling the tool", async () => {
const response = await integration.mcpClient().callTool({
name: "atlas-local-list-deployments",
arguments: {},
});
const elements = getResponseElements(response.content);
expect(elements.length).toBeGreaterThanOrEqual(1);

if (elements.length === 1) {
expect(elements[0]?.text).toContain("No deployments found.");
}

if (elements.length > 1) {
expect(elements[0]?.text).toMatch(/Found \d+ deployments/);
expect(elements[1]?.text).toContain(
"Deployment Name | State | MongoDB Version\n----------------|----------------|----------------\n"
);
}
});
});
2 changes: 1 addition & 1 deletion tests/integration/transports/stdio.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describeWithMongoDB("StdioRunner", (integration) => {
beforeAll(async () => {
transport = new StdioClientTransport({
command: "node",
args: ["dist/index.js"],
args: ["dist/index.js", "--disabledTools", "atlas-local"],
env: {
MDB_MCP_TRANSPORT: "stdio",
MDB_MCP_CONNECTION_STRING: integration.connectionString(),
Expand Down
Loading