|
| 1 | +import { ConnectOptions } from "./config.js"; |
| 2 | +import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver"; |
| 3 | +import EventEmitter from "events"; |
| 4 | +import { setAppNameParamIfMissing } from "../helpers/connectionOptions.js"; |
| 5 | +import { packageInfo } from "./packageInfo.js"; |
| 6 | +import ConnectionString from "mongodb-connection-string-url"; |
| 7 | +import { MongoClientOptions } from "mongodb"; |
| 8 | +import { ErrorCodes, MongoDBError } from "./errors.js"; |
| 9 | + |
| 10 | +export interface AtlasClusterConnectionInfo { |
| 11 | + username: string; |
| 12 | + projectId: string; |
| 13 | + clusterName: string; |
| 14 | + expiryDate: Date; |
| 15 | +} |
| 16 | + |
| 17 | +export interface ConnectionSettings extends ConnectOptions { |
| 18 | + connectionString: string; |
| 19 | + atlas?: AtlasClusterConnectionInfo; |
| 20 | +} |
| 21 | + |
| 22 | +type ConnectionTag = "connected" | "connecting" | "disconnected" | "errored"; |
| 23 | +type OIDCConnectionAuthType = "oidc-auth-flow" | "oidc-device-flow"; |
| 24 | +type ConnectionStringAuthType = "scram" | "ldap" | "kerberos" | OIDCConnectionAuthType | "x.509"; |
| 25 | + |
| 26 | +export interface ConnectionState { |
| 27 | + tag: ConnectionTag; |
| 28 | + connectionStringAuthType?: ConnectionStringAuthType; |
| 29 | +} |
| 30 | + |
| 31 | +export interface ConnectionStateConnected extends ConnectionState { |
| 32 | + tag: "connected"; |
| 33 | + serviceProvider: NodeDriverServiceProvider; |
| 34 | + connectedAtlasCluster?: AtlasClusterConnectionInfo; |
| 35 | +} |
| 36 | + |
| 37 | +export interface ConnectionStateConnecting extends ConnectionState { |
| 38 | + tag: "connecting"; |
| 39 | + serviceProvider: NodeDriverServiceProvider; |
| 40 | + oidcConnectionType: OIDCConnectionAuthType; |
| 41 | + oidcLoginUrl?: string; |
| 42 | + oidcUserCode?: string; |
| 43 | +} |
| 44 | + |
| 45 | +export interface ConnectionStateDisconnected extends ConnectionState { |
| 46 | + tag: "disconnected"; |
| 47 | +} |
| 48 | + |
| 49 | +export interface ConnectionStateErrored extends ConnectionState { |
| 50 | + tag: "errored"; |
| 51 | + errorReason: string; |
| 52 | +} |
| 53 | + |
| 54 | +export type AnyConnectionState = |
| 55 | + | ConnectionState |
| 56 | + | ConnectionStateConnected |
| 57 | + | ConnectionStateConnecting |
| 58 | + | ConnectionStateDisconnected |
| 59 | + | ConnectionStateErrored; |
| 60 | + |
| 61 | +export interface ConnectionManagerEvents { |
| 62 | + "connection-requested": [AnyConnectionState]; |
| 63 | + "connection-succeeded": [ConnectionStateConnected]; |
| 64 | + "connection-timed-out": [ConnectionStateErrored]; |
| 65 | + "connection-closed": [ConnectionStateDisconnected]; |
| 66 | + "connection-errored": [ConnectionStateErrored]; |
| 67 | +} |
| 68 | + |
| 69 | +export class ConnectionManager extends EventEmitter<ConnectionManagerEvents> { |
| 70 | + private state: AnyConnectionState; |
| 71 | + |
| 72 | + constructor() { |
| 73 | + super(); |
| 74 | + this.state = { tag: "disconnected" }; |
| 75 | + } |
| 76 | + |
| 77 | + async connect(settings: ConnectionSettings): Promise<AnyConnectionState> { |
| 78 | + if (this.state.tag == "connected" || this.state.tag == "connecting") { |
| 79 | + await this.disconnect(); |
| 80 | + } |
| 81 | + |
| 82 | + let serviceProvider: NodeDriverServiceProvider; |
| 83 | + try { |
| 84 | + settings = { ...settings }; |
| 85 | + settings.connectionString = setAppNameParamIfMissing({ |
| 86 | + connectionString: settings.connectionString, |
| 87 | + defaultAppName: `${packageInfo.mcpServerName} ${packageInfo.version}`, |
| 88 | + }); |
| 89 | + |
| 90 | + serviceProvider = await NodeDriverServiceProvider.connect(settings.connectionString, { |
| 91 | + productDocsLink: "https://github.com/mongodb-js/mongodb-mcp-server/", |
| 92 | + productName: "MongoDB MCP", |
| 93 | + readConcern: { |
| 94 | + level: settings.readConcern, |
| 95 | + }, |
| 96 | + readPreference: settings.readPreference, |
| 97 | + writeConcern: { |
| 98 | + w: settings.writeConcern, |
| 99 | + }, |
| 100 | + timeoutMS: settings.timeoutMS, |
| 101 | + proxy: { useEnvironmentVariableProxies: true }, |
| 102 | + applyProxyToOIDC: true, |
| 103 | + }); |
| 104 | + } catch (error: unknown) { |
| 105 | + const errorReason = error instanceof Error ? error.message : `${error as string}`; |
| 106 | + this.changeState("connection-errored", { tag: "errored", errorReason }); |
| 107 | + throw new MongoDBError(ErrorCodes.MisconfiguredConnectionString, errorReason); |
| 108 | + } |
| 109 | + |
| 110 | + try { |
| 111 | + await serviceProvider?.runCommand?.("admin", { hello: 1 }); |
| 112 | + |
| 113 | + return this.changeState("connection-succeeded", { |
| 114 | + tag: "connected", |
| 115 | + connectedAtlasCluster: settings.atlas, |
| 116 | + serviceProvider, |
| 117 | + connectionStringAuthType: this.inferConnectionTypeFromSettings(settings), |
| 118 | + }); |
| 119 | + } catch (error: unknown) { |
| 120 | + const errorReason = error instanceof Error ? error.message : `${error as string}`; |
| 121 | + this.changeState("connection-errored", { tag: "errored", errorReason }); |
| 122 | + throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, errorReason); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + async disconnect(): Promise<ConnectionStateDisconnected | ConnectionStateErrored> { |
| 127 | + if (this.state.tag == "disconnected") { |
| 128 | + return this.state as ConnectionStateDisconnected; |
| 129 | + } |
| 130 | + |
| 131 | + if (this.state.tag == "errored") { |
| 132 | + return this.state as ConnectionStateErrored; |
| 133 | + } |
| 134 | + |
| 135 | + if (this.state.tag == "connected" || this.state.tag == "connecting") { |
| 136 | + const state = this.state as ConnectionStateConnecting | ConnectionStateConnected; |
| 137 | + try { |
| 138 | + await state.serviceProvider?.close(true); |
| 139 | + } finally { |
| 140 | + this.changeState("connection-closed", { tag: "disconnected" }); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + return { tag: "disconnected" }; |
| 145 | + } |
| 146 | + |
| 147 | + get currentConnectionState(): AnyConnectionState { |
| 148 | + return this.state; |
| 149 | + } |
| 150 | + |
| 151 | + changeState<State extends AnyConnectionState>(event: keyof ConnectionManagerEvents, newState: State): State { |
| 152 | + this.state = newState; |
| 153 | + this.emit(event, newState); |
| 154 | + return newState; |
| 155 | + } |
| 156 | + |
| 157 | + private inferConnectionTypeFromSettings(settings: ConnectionSettings): ConnectionStringAuthType { |
| 158 | + const connString = new ConnectionString(settings.connectionString); |
| 159 | + const searchParams = connString.typedSearchParams<MongoClientOptions>(); |
| 160 | + |
| 161 | + switch (searchParams.get("authMechanism")) { |
| 162 | + case "MONGODB-OIDC": { |
| 163 | + return "oidc-auth-flow"; // TODO: depending on if we don't have a --browser later it can be oidc-device-flow |
| 164 | + } |
| 165 | + case "MONGODB-X509": |
| 166 | + return "x.509"; |
| 167 | + case "GSSAPI": |
| 168 | + return "kerberos"; |
| 169 | + case "PLAIN": |
| 170 | + if (searchParams.get("authSource") == "$external") { |
| 171 | + return "ldap"; |
| 172 | + } |
| 173 | + break; |
| 174 | + default: |
| 175 | + return "scram"; |
| 176 | + } |
| 177 | + return "scram"; |
| 178 | + } |
| 179 | +} |
0 commit comments