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

mongodb-js / mongodb-mcp-server / 16790782045

06 Aug 2025 11:09PM UTC coverage: 81.233% (-0.07%) from 81.298%
16790782045

Pull #425

github

web-flow
Merge 7712da066 into 53ac631ea
Pull Request #425: fix: remove global logger MCP-103

681 of 881 branches covered (77.3%)

Branch coverage included in aggregate %.

158 of 207 new or added lines in 17 files covered. (76.33%)

6 existing lines in 2 files now uncovered.

3522 of 4293 relevant lines covered (82.04%)

58.12 hits per line

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

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

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

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

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

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

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

45
        return this.session.serviceProvider;
250✔
46
    }
291✔
47

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

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

62
            // Find the first Atlas connect tool if available and suggest to the LLM to use it.
63
            // Note: if we ever have multiple Atlas connect tools, we may want to refine this logic to select the most appropriate one.
64
            const atlasConnectTool = connectTools?.find((t) => t.category === "atlas");
55✔
65
            const llmConnectHint = atlasConnectTool
55✔
66
                ? `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.`
27✔
67
                : "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.";
28✔
68

69
            const connectToolsNames = connectTools?.map((t) => `"${t.name}"`).join(", ");
55✔
70
            switch (error.code) {
55✔
71
                case ErrorCodes.NotConnectedToMongoDB:
55✔
72
                    return {
41✔
73
                        content: [
41✔
74
                            {
41✔
75
                                type: "text",
41✔
76
                                text: "You need to connect to a MongoDB instance before you can access its data.",
41✔
77
                            },
41✔
78
                            {
41✔
79
                                type: "text",
41✔
80
                                text: connectToolsNames
41✔
81
                                    ? `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}`
39✔
82
                                    : "There are no tools available to connect. Please update the configuration to include a connection string and restart the server.",
2✔
83
                            },
41✔
84
                        ],
41✔
85
                        isError: true,
41✔
86
                    };
41✔
87
                case ErrorCodes.MisconfiguredConnectionString:
55✔
88
                    return {
4✔
89
                        content: [
4✔
90
                            {
4✔
91
                                type: "text",
4✔
92
                                text: "The configured connection string is not valid. Please check the connection string and confirm it points to a valid MongoDB instance.",
4✔
93
                            },
4✔
94
                            {
4✔
95
                                type: "text",
4✔
96
                                text: connectTools
4✔
97
                                    ? `Alternatively, you can use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance. ${llmConnectHint}`
4!
98
                                    : "Please update the configuration to use a valid connection string and restart the server.",
×
99
                            },
4✔
100
                        ],
4✔
101
                        isError: true,
4✔
102
                    };
4✔
103
                case ErrorCodes.ForbiddenCollscan:
55✔
104
                    return {
10✔
105
                        content: [
10✔
106
                            {
10✔
107
                                type: "text",
10✔
108
                                text: error.message,
10✔
109
                            },
10✔
110
                        ],
10✔
111
                        isError: true,
10✔
112
                    };
10✔
113
            }
55✔
114
        }
55✔
115

116
        return super.handleError(error, args);
4✔
117
    }
59✔
118

119
    protected connectToMongoDB(connectionString: string): Promise<void> {
2✔
120
        return this.session.connectToMongoDB({ connectionString, ...this.config.connectOptions });
254✔
121
    }
254✔
122

123
    protected resolveTelemetryMetadata(
2✔
124
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
125
        args: ToolArgs<typeof this.argsShape>
×
126
    ): TelemetryToolMetadata {
×
127
        const metadata: TelemetryToolMetadata = {};
×
128

129
        // Add projectId to the metadata if running a MongoDB operation to an Atlas cluster
130
        if (this.session.connectedAtlasCluster?.projectId) {
×
131
            metadata.projectId = this.session.connectedAtlasCluster.projectId;
×
132
        }
×
133

134
        return metadata;
×
135
    }
×
136
}
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