• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mongodb-js / mongodb-mcp-server / 17161333946

22 Aug 2025 05:03PM UTC coverage: 81.909% (-0.1%) from 82.022%
17161333946

Pull #471

github

web-flow
Merge 903825dd4 into 49707be70
Pull Request #471: fix: atlas connectCluster defaults to readOnly DB roles - MCP-125

874 of 1092 branches covered (80.04%)

Branch coverage included in aggregate %.

25 of 25 new or added lines in 2 files covered. (100.0%)

49 existing lines in 10 files now uncovered.

4360 of 5298 relevant lines covered (82.3%)

70.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.85
/src/tools/mongodb/mongodbTool.ts
1
import { z } from "zod";
2✔
2
import type { ToolArgs, ToolCategory, TelemetryToolMetadata } from "../tool.js";
3
import { ToolBase } from "../tool.js";
2✔
4
import type { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
5
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
6
import { ErrorCodes, MongoDBError } from "../../common/errors.js";
2✔
7
import { LogId } from "../../common/logger.js";
2✔
8
import type { Server } from "../../server.js";
9

10
export const DbOperationArgs = {
2✔
11
    database: z.string().describe("Database name"),
2✔
12
    collection: z.string().describe("Collection name"),
2✔
13
};
2✔
14

15
export abstract class MongoDBToolBase extends ToolBase {
2✔
16
    private server?: Server;
17
    public category: ToolCategory = "mongodb";
1,680✔
18

19
    protected async ensureConnected(): Promise<NodeDriverServiceProvider> {
2✔
20
        if (!this.session.isConnectedToMongoDB) {
337✔
21
            if (this.session.connectedAtlasCluster) {
81!
UNCOV
22
                throw new MongoDBError(
×
23
                    ErrorCodes.NotConnectedToMongoDB,
×
24
                    `Attempting to connect to Atlas cluster "${this.session.connectedAtlasCluster.clusterName}", try again in a few seconds.`
×
25
                );
×
26
            }
×
27

28
            if (this.config.connectionString) {
81✔
29
                try {
38✔
30
                    await this.connectToMongoDB(this.config.connectionString);
38✔
31
                } catch (error) {
38!
UNCOV
32
                    this.session.logger.error({
×
33
                        id: LogId.mongodbConnectFailure,
×
34
                        context: "mongodbTool",
×
35
                        message: `Failed to connect to MongoDB instance using the connection string from the config: ${error as string}`,
×
36
                    });
×
37
                    throw new MongoDBError(ErrorCodes.MisconfiguredConnectionString, "Not connected to MongoDB.");
×
38
                }
×
39
            }
38✔
40
        }
81✔
41

42
        if (!this.session.isConnectedToMongoDB) {
337✔
43
            throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, "Not connected to MongoDB");
43✔
44
        }
43✔
45

46
        return this.session.serviceProvider;
294✔
47
    }
337✔
48

49
    public register(server: Server): boolean {
2✔
50
        this.server = server;
1,680✔
51
        return super.register(server);
1,680✔
52
    }
1,680✔
53

54
    protected handleError(
2✔
55
        error: unknown,
61✔
56
        args: ToolArgs<typeof this.argsShape>
61✔
57
    ): Promise<CallToolResult> | CallToolResult {
61✔
58
        if (error instanceof MongoDBError) {
61✔
59
            const connectTools = this.server?.tools
57✔
60
                .filter((t) => t.operationType === "connect")
57✔
61
                .sort((a, b) => a.category.localeCompare(b.category)); // Sort Altas tools before MongoDB tools
57✔
62

63
            // Find the first Atlas connect tool if available and suggest to the LLM to use it.
64
            // Note: if we ever have multiple Atlas connect tools, we may want to refine this logic to select the most appropriate one.
65
            const atlasConnectTool = connectTools?.find((t) => t.category === "atlas");
57✔
66
            const llmConnectHint = atlasConnectTool
57✔
67
                ? `Note to LLM: prefer using the "${atlasConnectTool.name}" tool to connect to an Atlas cluster over using a connection string. Make sure to ask the user to specify a cluster name they want to connect to or ask them if they want to use the "list-clusters" tool to list all their clusters. Do not invent cluster names or connection strings unless the user has explicitly specified them. If they've previously connected to MongoDB using MCP, you can ask them if they want to reconnect using the same cluster/connection.`
28✔
68
                : "Note to LLM: do not invent connection strings and explicitly ask the user to provide one. If they have previously connected to MongoDB using MCP, you can ask them if they want to reconnect using the same connection string.";
29✔
69

70
            const connectToolsNames = connectTools?.map((t) => `"${t.name}"`).join(", ");
57✔
71
            const connectionStatus = this.session.connectionManager.currentConnectionState;
57✔
72
            const additionalPromptForConnectivity: { type: "text"; text: string }[] = [];
57✔
73

74
            if (connectionStatus.tag === "connecting" && connectionStatus.oidcConnectionType) {
57✔
75
                additionalPromptForConnectivity.push({
2✔
76
                    type: "text",
2✔
77
                    text: `The user needs to finish their OIDC connection by opening '${connectionStatus.oidcLoginUrl}' in the browser and use the following user code: '${connectionStatus.oidcUserCode}'`,
2✔
78
                });
2✔
79
            } else {
57✔
80
                additionalPromptForConnectivity.push({
55✔
81
                    type: "text",
55✔
82
                    text: connectToolsNames
55✔
83
                        ? `Please use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance or update the MCP server configuration to include a connection string. ${llmConnectHint}`
53✔
84
                        : "There are no tools available to connect. Please update the configuration to include a connection string and restart the server.",
2✔
85
                });
55✔
86
            }
55✔
87

88
            switch (error.code) {
57✔
89
                case ErrorCodes.NotConnectedToMongoDB:
57✔
90
                    return {
43✔
91
                        content: [
43✔
92
                            {
43✔
93
                                type: "text",
43✔
94
                                text: "You need to connect to a MongoDB instance before you can access its data.",
43✔
95
                            },
43✔
96
                            ...additionalPromptForConnectivity,
43✔
97
                        ],
43✔
98
                        isError: true,
43✔
99
                    };
43✔
100
                case ErrorCodes.MisconfiguredConnectionString:
57✔
101
                    return {
4✔
102
                        content: [
4✔
103
                            {
4✔
104
                                type: "text",
4✔
105
                                text: "The configured connection string is not valid. Please check the connection string and confirm it points to a valid MongoDB instance.",
4✔
106
                            },
4✔
107
                            {
4✔
108
                                type: "text",
4✔
109
                                text: connectTools
4✔
110
                                    ? `Alternatively, you can use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance. ${llmConnectHint}`
4!
UNCOV
111
                                    : "Please update the configuration to use a valid connection string and restart the server.",
×
112
                            },
4✔
113
                        ],
4✔
114
                        isError: true,
4✔
115
                    };
4✔
116
                case ErrorCodes.ForbiddenCollscan:
57✔
117
                    return {
10✔
118
                        content: [
10✔
119
                            {
10✔
120
                                type: "text",
10✔
121
                                text: error.message,
10✔
122
                            },
10✔
123
                        ],
10✔
124
                        isError: true,
10✔
125
                    };
10✔
126
            }
57✔
127
        }
57✔
128

129
        return super.handleError(error, args);
4✔
130
    }
61✔
131

132
    protected connectToMongoDB(connectionString: string): Promise<void> {
2✔
133
        return this.session.connectToMongoDB({ connectionString });
346✔
134
    }
346✔
135

136
    protected resolveTelemetryMetadata(
2✔
137
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
UNCOV
138
        args: ToolArgs<typeof this.argsShape>
×
139
    ): TelemetryToolMetadata {
×
140
        const metadata: TelemetryToolMetadata = {};
×
141

142
        // Add projectId to the metadata if running a MongoDB operation to an Atlas cluster
UNCOV
143
        if (this.session.connectedAtlasCluster?.projectId) {
×
144
            metadata.projectId = this.session.connectedAtlasCluster.projectId;
×
145
        }
×
146

UNCOV
147
        return metadata;
×
148
    }
×
149
}
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc