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

mongodb-js / mongodb-mcp-server / 24667400508

20 Apr 2026 12:48PM UTC coverage: 81.647% (-0.3%) from 81.921%
24667400508

push

github

web-flow
chore: improve error message for api extractor (#1077)

1595 of 2180 branches covered (73.17%)

Branch coverage included in aggregate %.

3054 of 3514 relevant lines covered (86.91%)

166.57 hits per line

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

82.61
/src/common/session.ts
1
import { ObjectId } from "bson";
2
import type { ApiClient } from "./atlas/apiClient.js";
3
import type { Implementation } from "@modelcontextprotocol/sdk/types.js";
4
import type { CompositeLogger } from "./logging/index.js";
5
import { LogId } from "./logging/index.js";
6
import EventEmitter from "events";
7
import type {
8
    AtlasClusterConnectionInfo,
9
    ConnectionManager,
10
    ConnectionSettings,
11
    ConnectionStateConnected,
12
    ConnectionStateErrored,
13
} from "./connectionManager.js";
14
import type { ConnectionStringInfo } from "./connectionInfo.js";
15
import type { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
16
import { ErrorCodes, MongoDBError } from "./errors.js";
17
import type { ExportsManager } from "./exportsManager.js";
18
import type { Client } from "@mongodb-js/atlas-local";
19
import type { Keychain } from "./keychain.js";
20
import { generateConnectionInfoFromCliArgs } from "@mongosh/arg-parser";
21
import { type UserConfig } from "../common/config/userConfig.js";
22
import { type ConnectionErrorHandler } from "./connectionErrorHandler.js";
23

24
export interface SessionOptions<TUserConfig extends UserConfig = UserConfig> {
25
    userConfig: TUserConfig;
26
    logger: CompositeLogger;
27
    exportsManager: ExportsManager;
28
    connectionManager: ConnectionManager;
29
    keychain: Keychain;
30
    atlasLocalClient?: Client;
31
    connectionErrorHandler: ConnectionErrorHandler;
32
    apiClient?: ApiClient;
33
}
34

35
export type SessionEvents = {
36
    connect: [];
37
    close: [];
38
    disconnect: [];
39
    "connection-error": [ConnectionStateErrored];
40
};
41

42
export class Session extends EventEmitter<SessionEvents> {
43
    private readonly userConfig: UserConfig;
44
    readonly sessionId: string = new ObjectId().toString();
238✔
45
    readonly exportsManager: ExportsManager;
46
    readonly connectionManager: ConnectionManager;
47
    readonly apiClient?: ApiClient;
48
    readonly atlasLocalClient?: Client;
49
    readonly keychain: Keychain;
50
    readonly connectionErrorHandler: ConnectionErrorHandler;
51

52
    mcpClient?: {
53
        name?: string;
54
        version?: string;
55
        title?: string;
56
    };
57

58
    public logger: CompositeLogger;
59

60
    constructor({
61
        userConfig,
62
        logger,
63
        connectionManager,
64
        exportsManager,
65
        keychain,
66
        atlasLocalClient,
67
        connectionErrorHandler,
68
        apiClient,
69
    }: SessionOptions<UserConfig>) {
70
        super();
238✔
71

72
        this.userConfig = userConfig;
238✔
73
        this.keychain = keychain;
238✔
74
        this.logger = logger;
238✔
75
        this.apiClient = apiClient;
238✔
76
        this.atlasLocalClient = atlasLocalClient;
238✔
77
        this.exportsManager = exportsManager;
238✔
78
        this.connectionManager = connectionManager;
238✔
79
        this.connectionErrorHandler = connectionErrorHandler;
238✔
80
        this.connectionManager.events.on("connection-success", () => this.emit("connect"));
403✔
81
        this.connectionManager.events.on("connection-time-out", (error) => this.emit("connection-error", error));
238✔
82
        this.connectionManager.events.on("connection-close", () => this.emit("disconnect"));
410✔
83
        this.connectionManager.events.on("connection-error", (error) => this.emit("connection-error", error));
255✔
84
    }
85

86
    setMcpClient(mcpClient: Implementation | undefined): void {
87
        if (!mcpClient) {
179!
88
            this.connectionManager.setClientName("unknown");
×
89
            this.logger.debug({
×
90
                id: LogId.serverMcpClientSet,
91
                context: "session",
92
                message: "MCP client info not found",
93
            });
94
        }
95

96
        this.mcpClient = {
179✔
97
            name: mcpClient?.name || "unknown",
179!
98
            version: mcpClient?.version || "unknown",
179!
99
            title: mcpClient?.title || "unknown",
358✔
100
        };
101

102
        // Set the client name on the connection manager for appName generation
103
        this.connectionManager.setClientName(this.mcpClient.name || "unknown");
179!
104
    }
105

106
    async disconnect(): Promise<void> {
107
        const atlasCluster = this.connectedAtlasCluster;
950✔
108

109
        await this.connectionManager.close();
950✔
110

111
        if (atlasCluster?.username && atlasCluster?.projectId && this.apiClient) {
950✔
112
            void this.apiClient
3✔
113
                .deleteDatabaseUser({
114
                    params: {
115
                        path: {
116
                            groupId: atlasCluster.projectId,
117
                            username: atlasCluster.username,
118
                            databaseName: "admin",
119
                        },
120
                    },
121
                })
122
                .catch((err: unknown) => {
123
                    const error = err instanceof Error ? err : new Error(String(err));
×
124
                    this.logger.error({
×
125
                        id: LogId.atlasDeleteDatabaseUserFailure,
126
                        context: "session",
127
                        message: `Error deleting previous database user: ${error.message}`,
128
                    });
129
                });
130
        }
131
    }
132

133
    async close(): Promise<void> {
134
        await this.disconnect();
212✔
135
        await this.apiClient?.close();
212✔
136
        await this.exportsManager.close();
212✔
137
        this.emit("close");
209✔
138
    }
139

140
    async connectToConfiguredConnection(): Promise<void> {
141
        const connectionInfo = generateConnectionInfoFromCliArgs({
36✔
142
            ...this.userConfig,
143
            connectionSpecifier: this.userConfig.connectionString,
144
        });
145
        await this.connectToMongoDB(connectionInfo);
36✔
146
    }
147

148
    async connectToMongoDB(settings: ConnectionSettings): Promise<void> {
149
        await this.connectionManager.connect({ ...settings });
408✔
150
    }
151

152
    get isConnectedToMongoDB(): boolean {
153
        return this.connectionManager.currentConnectionState.tag === "connected";
1,560✔
154
    }
155

156
    async isSearchSupported(): Promise<boolean> {
157
        const state = this.connectionManager.currentConnectionState;
200✔
158
        if (state.tag === "connected") {
200✔
159
            return await state.isSearchSupported();
199✔
160
        }
161

162
        return false;
1✔
163
    }
164

165
    async assertSearchSupported(): Promise<void> {
166
        const isSearchSupported = await this.isSearchSupported();
26✔
167
        if (!isSearchSupported) {
26✔
168
            throw new MongoDBError(
3✔
169
                ErrorCodes.AtlasSearchNotSupported,
170
                "Atlas Search is not supported in the current cluster."
171
            );
172
        }
173
    }
174

175
    get serviceProvider(): NodeDriverServiceProvider {
176
        if (this.isConnectedToMongoDB) {
370!
177
            const state = this.connectionManager.currentConnectionState as ConnectionStateConnected;
370✔
178
            return state.serviceProvider;
370✔
179
        }
180

181
        throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, "Not connected to MongoDB");
×
182
    }
183

184
    get connectedAtlasCluster(): AtlasClusterConnectionInfo | undefined {
185
        return this.connectionManager.currentConnectionState.connectedAtlasCluster;
1,283✔
186
    }
187

188
    get connectionStringInfo(): ConnectionStringInfo | undefined {
189
        return this.connectionManager.currentConnectionState.connectionStringInfo;
66✔
190
    }
191
}
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

© 2026 Coveralls, Inc