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

mongodb-js / mongodb-mcp-server / 23295186729

19 Mar 2026 12:38PM UTC coverage: 84.695% (-0.3%) from 84.953%
23295186729

push

github

web-flow
chore: skip coverage if tests fail (#989)

2084 of 2702 branches covered (77.13%)

Branch coverage included in aggregate %.

9902 of 11450 relevant lines covered (86.48%)

110.22 hits per line

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

84.94
/src/common/session.ts
1
import { ObjectId } from "bson";
3✔
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";
3✔
6
import EventEmitter from "events";
3✔
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";
3✔
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";
3✔
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> {
3✔
43
    private readonly userConfig: UserConfig;
44
    readonly sessionId: string = new ObjectId().toString();
3✔
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({
3✔
61
        userConfig,
203✔
62
        logger,
203✔
63
        connectionManager,
203✔
64
        exportsManager,
203✔
65
        keychain,
203✔
66
        atlasLocalClient,
203✔
67
        connectionErrorHandler,
203✔
68
        apiClient,
203✔
69
    }: SessionOptions<UserConfig>) {
203✔
70
        super();
203✔
71

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

86
    setMcpClient(mcpClient: Implementation | undefined): void {
3✔
87
        if (!mcpClient) {
162!
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 = {
162✔
97
            name: mcpClient?.name || "unknown",
162!
98
            version: mcpClient?.version || "unknown",
162!
99
            title: mcpClient?.title || "unknown",
162✔
100
        };
162✔
101

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

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

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

111
        if (atlasCluster?.username && atlasCluster?.projectId && this.apiClient) {
899!
112
            void this.apiClient
3✔
113
                .deleteDatabaseUser({
3✔
114
                    params: {
3✔
115
                        path: {
3✔
116
                            groupId: atlasCluster.projectId,
3✔
117
                            username: atlasCluster.username,
3✔
118
                            databaseName: "admin",
3✔
119
                        },
3✔
120
                    },
3✔
121
                })
3✔
122
                .catch((err: unknown) => {
3✔
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
                });
3✔
130
        }
3✔
131
    }
899✔
132

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

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

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

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

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

162
        return false;
1✔
163
    }
204✔
164

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

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

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

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

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