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

mongodb-js / mongodb-mcp-server / 17076257943

19 Aug 2025 04:49PM UTC coverage: 82.007% (-0.1%) from 82.111%
17076257943

push

github

web-flow
docs: add gateways and proxies section to README (#438)

Co-authored-by: Kevin Mas Ruiz <kevin.mas@hey.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

805 of 1008 branches covered (79.86%)

Branch coverage included in aggregate %.

4236 of 5139 relevant lines covered (82.43%)

68.46 hits per line

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

85.71
/src/common/session.ts
1
import { ObjectId } from "bson";
2✔
2
import { ApiClient, ApiClientCredentials } from "./atlas/apiClient.js";
2✔
3
import { Implementation } from "@modelcontextprotocol/sdk/types.js";
4
import { CompositeLogger, LogId } from "./logger.js";
2✔
5
import EventEmitter from "events";
2✔
6
import {
7
    AtlasClusterConnectionInfo,
8
    ConnectionManager,
9
    ConnectionSettings,
10
    ConnectionStateConnected,
11
} from "./connectionManager.js";
12
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
13
import { ErrorCodes, MongoDBError } from "./errors.js";
2✔
14
import { ExportsManager } from "./exportsManager.js";
15

16
export interface SessionOptions {
17
    apiBaseUrl: string;
18
    apiClientId?: string;
19
    apiClientSecret?: string;
20
    logger: CompositeLogger;
21
    exportsManager: ExportsManager;
22
    connectionManager: ConnectionManager;
23
}
24

25
export type SessionEvents = {
26
    connect: [];
27
    close: [];
28
    disconnect: [];
29
    "connection-error": [string];
30
};
31

32
export class Session extends EventEmitter<SessionEvents> {
2✔
33
    readonly sessionId: string = new ObjectId().toString();
2✔
34
    readonly exportsManager: ExportsManager;
35
    readonly connectionManager: ConnectionManager;
36
    readonly apiClient: ApiClient;
37
    agentRunner?: {
38
        name: string;
39
        version: string;
40
    };
41

42
    public logger: CompositeLogger;
43

44
    constructor({
2✔
45
        apiBaseUrl,
92✔
46
        apiClientId,
92✔
47
        apiClientSecret,
92✔
48
        logger,
92✔
49
        connectionManager,
92✔
50
        exportsManager,
92✔
51
    }: SessionOptions) {
92✔
52
        super();
92✔
53

54
        this.logger = logger;
92✔
55
        const credentials: ApiClientCredentials | undefined =
92✔
56
            apiClientId && apiClientSecret
92✔
57
                ? {
44✔
58
                      clientId: apiClientId,
44✔
59
                      clientSecret: apiClientSecret,
44✔
60
                  }
44✔
61
                : undefined;
48✔
62

63
        this.apiClient = new ApiClient({ baseUrl: apiBaseUrl, credentials }, logger);
92✔
64
        this.exportsManager = exportsManager;
92✔
65
        this.connectionManager = connectionManager;
92✔
66
        this.connectionManager.on("connection-succeeded", () => this.emit("connect"));
92✔
67
        this.connectionManager.on("connection-timed-out", (error) => this.emit("connection-error", error.errorReason));
92✔
68
        this.connectionManager.on("connection-closed", () => this.emit("disconnect"));
92✔
69
        this.connectionManager.on("connection-errored", (error) => this.emit("connection-error", error.errorReason));
92✔
70
    }
92✔
71

72
    setAgentRunner(agentRunner: Implementation | undefined): void {
2✔
73
        if (agentRunner?.name && agentRunner?.version) {
80✔
74
            this.agentRunner = {
80✔
75
                name: agentRunner.name,
80✔
76
                version: agentRunner.version,
80✔
77
            };
80✔
78
        }
80✔
79
    }
80✔
80

81
    async disconnect(): Promise<void> {
2✔
82
        const atlasCluster = this.connectedAtlasCluster;
784✔
83

84
        try {
784✔
85
            await this.connectionManager.disconnect();
784✔
86
        } catch (err: unknown) {
784!
87
            const error = err instanceof Error ? err : new Error(String(err));
×
88
            this.logger.error({
×
89
                id: LogId.mongodbDisconnectFailure,
×
90
                context: "session",
×
91
                message: `Error closing service provider: ${error.message}`,
×
92
            });
×
93
        }
×
94

95
        if (atlasCluster?.username && atlasCluster?.projectId) {
784✔
96
            void this.apiClient
1✔
97
                .deleteDatabaseUser({
1✔
98
                    params: {
1✔
99
                        path: {
1✔
100
                            groupId: atlasCluster.projectId,
1✔
101
                            username: atlasCluster.username,
1✔
102
                            databaseName: "admin",
1✔
103
                        },
1✔
104
                    },
1✔
105
                })
1✔
106
                .catch((err: unknown) => {
1✔
107
                    const error = err instanceof Error ? err : new Error(String(err));
×
108
                    this.logger.error({
×
109
                        id: LogId.atlasDeleteDatabaseUserFailure,
×
110
                        context: "session",
×
111
                        message: `Error deleting previous database user: ${error.message}`,
×
112
                    });
×
113
                });
1✔
114
        }
1✔
115
    }
784✔
116

117
    async close(): Promise<void> {
2✔
118
        await this.disconnect();
80✔
119
        await this.apiClient.close();
80✔
120
        await this.exportsManager.close();
79✔
121
        this.emit("close");
79✔
122
    }
80✔
123

124
    async connectToMongoDB(settings: ConnectionSettings): Promise<void> {
2✔
125
        try {
378✔
126
            await this.connectionManager.connect({ ...settings });
378✔
127
        } catch (error: unknown) {
378✔
128
            const message = error instanceof Error ? error.message : (error as string);
14!
129
            this.emit("connection-error", message);
14✔
130
            throw error;
14✔
131
        }
14✔
132
    }
378✔
133

134
    get isConnectedToMongoDB(): boolean {
2✔
135
        return this.connectionManager.currentConnectionState.tag === "connected";
2,151✔
136
    }
2,151✔
137

138
    get serviceProvider(): NodeDriverServiceProvider {
2✔
139
        if (this.isConnectedToMongoDB) {
298✔
140
            const state = this.connectionManager.currentConnectionState as ConnectionStateConnected;
298✔
141
            return state.serviceProvider;
298✔
142
        }
298!
143

144
        throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, "Not connected to MongoDB");
×
145
    }
298✔
146

147
    get connectedAtlasCluster(): AtlasClusterConnectionInfo | undefined {
2✔
148
        return this.connectionManager.currentConnectionState.connectedAtlasCluster;
958✔
149
    }
958✔
150
}
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

© 2026 Coveralls, Inc