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

mongodb-js / mongodb-mcp-server / 20853900721

09 Jan 2026 01:45PM UTC coverage: 79.931% (+0.3%) from 79.647%
20853900721

Pull #836

github

web-flow
Merge 97195e48d into 7043c219d
Pull Request #836: [DRAFT] Add configurable api / auth client support

1536 of 1988 branches covered (77.26%)

Branch coverage included in aggregate %.

206 of 209 new or added lines in 6 files covered. (98.56%)

66 existing lines in 2 files now uncovered.

6979 of 8665 relevant lines covered (80.54%)

88.9 hits per line

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

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

25
export interface SessionOptions {
26
    userConfig: UserConfig;
27
    logger: CompositeLogger;
28
    exportsManager: ExportsManager;
29
    connectionManager: ConnectionManager;
30
    keychain: Keychain;
31
    atlasLocalClient?: Client;
32
    vectorSearchEmbeddingsManager: VectorSearchEmbeddingsManager;
33
    apiClient?: ApiClient;
34
}
35

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

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

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

59
    public logger: CompositeLogger;
60

61
    constructor({
3✔
62
        userConfig,
145✔
63
        logger,
145✔
64
        connectionManager,
145✔
65
        exportsManager,
145✔
66
        keychain,
145✔
67
        atlasLocalClient,
145✔
68
        vectorSearchEmbeddingsManager,
145✔
69
        apiClient,
145✔
70
    }: SessionOptions) {
145✔
71
        super();
145✔
72

73
        this.userConfig = userConfig;
145✔
74
        this.keychain = keychain;
145✔
75
        this.logger = logger;
145✔
76

77
        this.apiClient =
145✔
78
            apiClient ??
145✔
79
            createAtlasApiClient(
121✔
80
                {
121✔
81
                    baseUrl: userConfig.apiBaseUrl,
121✔
82
                    credentials: {
121✔
83
                        clientId: userConfig.apiClientId,
121✔
84
                        clientSecret: userConfig.apiClientSecret,
121✔
85
                    },
121✔
86
                },
121✔
87
                logger
121✔
88
            );
121✔
89
        this.atlasLocalClient = atlasLocalClient;
145✔
90
        this.exportsManager = exportsManager;
145✔
91
        this.connectionManager = connectionManager;
145✔
92
        this.vectorSearchEmbeddingsManager = vectorSearchEmbeddingsManager;
145✔
93
        this.connectionManager.events.on("connection-success", () => this.emit("connect"));
145✔
94
        this.connectionManager.events.on("connection-time-out", (error) => this.emit("connection-error", error));
145✔
95
        this.connectionManager.events.on("connection-close", () => this.emit("disconnect"));
145✔
96
        this.connectionManager.events.on("connection-error", (error) => this.emit("connection-error", error));
145✔
97
    }
145✔
98

99
    setMcpClient(mcpClient: Implementation | undefined): void {
3✔
100
        if (!mcpClient) {
123!
UNCOV
101
            this.connectionManager.setClientName("unknown");
×
UNCOV
102
            this.logger.debug({
×
103
                id: LogId.serverMcpClientSet,
×
104
                context: "session",
×
105
                message: "MCP client info not found",
×
106
            });
×
107
        }
×
108

109
        this.mcpClient = {
123✔
110
            name: mcpClient?.name || "unknown",
123!
111
            version: mcpClient?.version || "unknown",
123!
112
            title: mcpClient?.title || "unknown",
123✔
113
        };
123✔
114

115
        // Set the client name on the connection manager for appName generation
116
        this.connectionManager.setClientName(this.mcpClient.name || "unknown");
123!
117
    }
123✔
118

119
    async disconnect(): Promise<void> {
3✔
120
        const atlasCluster = this.connectedAtlasCluster;
758✔
121

122
        await this.connectionManager.close();
758✔
123

124
        if (atlasCluster?.username && atlasCluster?.projectId) {
758!
125
            void this.apiClient
3✔
126
                .deleteDatabaseUser({
3✔
127
                    params: {
3✔
128
                        path: {
3✔
129
                            groupId: atlasCluster.projectId,
3✔
130
                            username: atlasCluster.username,
3✔
131
                            databaseName: "admin",
3✔
132
                        },
3✔
133
                    },
3✔
134
                })
3✔
135
                .catch((err: unknown) => {
3✔
UNCOV
136
                    const error = err instanceof Error ? err : new Error(String(err));
×
UNCOV
137
                    this.logger.error({
×
138
                        id: LogId.atlasDeleteDatabaseUserFailure,
×
139
                        context: "session",
×
140
                        message: `Error deleting previous database user: ${error.message}`,
×
141
                    });
×
142
                });
3✔
143
        }
3✔
144
    }
758✔
145

146
    async close(): Promise<void> {
3✔
147
        await this.disconnect();
121✔
148
        await this.apiClient.close();
121✔
149
        await this.exportsManager.close();
121✔
150
        this.emit("close");
120✔
151
    }
121✔
152

153
    async connectToConfiguredConnection(): Promise<void> {
3✔
154
        const connectionInfo = generateConnectionInfoFromCliArgs({
35✔
155
            ...this.userConfig,
35✔
156
            connectionSpecifier: this.userConfig.connectionString,
35✔
157
        });
35✔
158
        await this.connectToMongoDB(connectionInfo);
35✔
159
    }
35✔
160

161
    async connectToMongoDB(settings: ConnectionSettings): Promise<void> {
3✔
162
        await this.connectionManager.connect({ ...settings });
318✔
163
    }
318✔
164

165
    get isConnectedToMongoDB(): boolean {
3✔
166
        return this.connectionManager.currentConnectionState.tag === "connected";
1,117✔
167
    }
1,117✔
168

169
    async isSearchSupported(): Promise<boolean> {
3✔
170
        const state = this.connectionManager.currentConnectionState;
76✔
171
        if (state.tag === "connected") {
76✔
172
            return await state.isSearchSupported();
75✔
173
        }
75✔
174

175
        return false;
1✔
176
    }
76✔
177

178
    async assertSearchSupported(): Promise<void> {
3✔
179
        const isSearchSupported = await this.isSearchSupported();
23✔
180
        if (!isSearchSupported) {
23✔
181
            throw new MongoDBError(
3✔
182
                ErrorCodes.AtlasSearchNotSupported,
3✔
183
                "Atlas Search is not supported in the current cluster."
3✔
184
            );
3✔
185
        }
3✔
186
    }
23✔
187

188
    get serviceProvider(): NodeDriverServiceProvider {
3✔
189
        if (this.isConnectedToMongoDB) {
258✔
190
            const state = this.connectionManager.currentConnectionState as ConnectionStateConnected;
258✔
191
            return state.serviceProvider;
258✔
192
        }
258!
193

UNCOV
194
        throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, "Not connected to MongoDB");
×
195
    }
258✔
196

197
    get connectedAtlasCluster(): AtlasClusterConnectionInfo | undefined {
3✔
198
        return this.connectionManager.currentConnectionState.connectedAtlasCluster;
1,022✔
199
    }
1,022✔
200

201
    get connectionStringAuthType(): ConnectionStringAuthType | undefined {
3✔
202
        return this.connectionManager.currentConnectionState.connectionStringAuthType;
24✔
203
    }
24✔
204
}
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