-
Notifications
You must be signed in to change notification settings - Fork 96
chore: refactor connections to use the new ConnectionManager to isolate long running processes like OIDC connections MCP-81 #423
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 14 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
3977aa7
chore: refactor to include the new ConnectionManager
kmruiz 7a1e217
chore: add tests to connection manager
kmruiz ece4d6c
chore: fix typo
kmruiz 06a7ea8
chore: js prefers strict equality
kmruiz 806382f
chore: fix linter errors
kmruiz 4c357f9
chore: connection requested is not necessary at the end
kmruiz 3f52815
chore: add test to connection-requested
kmruiz 28d8b69
chore: add tests for the actual connection status
kmruiz f7ec158
chore: Fix typing issues and few PR suggestions
kmruiz f49e2b0
chore: style changes, use a getter for isConnectedToMongoDB
kmruiz e03b7a6
chore: move AtlasConnectionInfo to the connection manager
kmruiz 43b54a0
chore: fixed linting issues
kmruiz 89ba76d
chore: emit the close event
kmruiz 61d7b1e
chore: add resource subscriptions and improve the resource prompt
kmruiz a33abb3
chore: Do not use anonymous tuples
kmruiz cc92766
chore: change the break to a return to make it easier to follow
kmruiz 0a77b97
chore: small refactor
kmruiz 6b5f49b
chore: minor clean up of redundant params
kmruiz 6cbb1ab
Merge branch 'main' into chore/mcp-81
kmruiz 1122e09
chore: ensure that we return connecting when not connected yet
kmruiz da872b4
chore: allow having the atlas cluster info independently of the conne…
kmruiz fe16acd
chore: simplify query connection logic
kmruiz 17494ac
chore: This is clearer on how the behavior should look like
kmruiz 693c755
chore: finish the refactor and clean up
kmruiz a6efc47
chore: propagate connected atlas cluster when disconnecting
kmruiz 71dbf56
chore: fix linter issues and some status mismatch
kmruiz 76e8ab5
chore: clean up atlas resource handling
kmruiz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,183 @@ | ||
import { ConnectOptions } from "./config.js"; | ||
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver"; | ||
import EventEmitter from "events"; | ||
import { setAppNameParamIfMissing } from "../helpers/connectionOptions.js"; | ||
import { packageInfo } from "./packageInfo.js"; | ||
import ConnectionString from "mongodb-connection-string-url"; | ||
import { MongoClientOptions } from "mongodb"; | ||
import { ErrorCodes, MongoDBError } from "./errors.js"; | ||
|
||
export interface AtlasClusterConnectionInfo { | ||
username: string; | ||
projectId: string; | ||
clusterName: string; | ||
expiryDate: Date; | ||
} | ||
|
||
export interface ConnectionSettings extends ConnectOptions { | ||
connectionString: string; | ||
atlas?: AtlasClusterConnectionInfo; | ||
} | ||
|
||
type ConnectionTag = "connected" | "connecting" | "disconnected" | "errored"; | ||
type OIDCConnectionAuthType = "oidc-auth-flow" | "oidc-device-flow"; | ||
export type ConnectionStringAuthType = "scram" | "ldap" | "kerberos" | OIDCConnectionAuthType | "x.509"; | ||
|
||
export interface ConnectionState { | ||
tag: ConnectionTag; | ||
connectionStringAuthType?: ConnectionStringAuthType; | ||
} | ||
|
||
export interface ConnectionStateConnected extends ConnectionState { | ||
tag: "connected"; | ||
serviceProvider: NodeDriverServiceProvider; | ||
connectedAtlasCluster?: AtlasClusterConnectionInfo; | ||
} | ||
|
||
export interface ConnectionStateConnecting extends ConnectionState { | ||
nirinchev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tag: "connecting"; | ||
serviceProvider: NodeDriverServiceProvider; | ||
oidcConnectionType: OIDCConnectionAuthType; | ||
oidcLoginUrl?: string; | ||
oidcUserCode?: string; | ||
} | ||
|
||
export interface ConnectionStateDisconnected extends ConnectionState { | ||
tag: "disconnected"; | ||
} | ||
|
||
export interface ConnectionStateErrored extends ConnectionState { | ||
tag: "errored"; | ||
errorReason: string; | ||
} | ||
|
||
export type AnyConnectionState = | ||
| ConnectionStateConnected | ||
| ConnectionStateConnecting | ||
| ConnectionStateDisconnected | ||
| ConnectionStateErrored; | ||
|
||
export interface ConnectionManagerEvents { | ||
"connection-requested": [AnyConnectionState]; | ||
"connection-succeeded": [ConnectionStateConnected]; | ||
"connection-timed-out": [ConnectionStateErrored]; | ||
"connection-closed": [ConnectionStateDisconnected]; | ||
"connection-errored": [ConnectionStateErrored]; | ||
} | ||
|
||
export class ConnectionManager extends EventEmitter<ConnectionManagerEvents> { | ||
private state: AnyConnectionState; | ||
|
||
constructor() { | ||
super(); | ||
this.state = { tag: "disconnected" }; | ||
} | ||
|
||
async connect(settings: ConnectionSettings): Promise<AnyConnectionState> { | ||
this.emit("connection-requested", this.state); | ||
|
||
if (this.state.tag === "connected" || this.state.tag === "connecting") { | ||
await this.disconnect(); | ||
} | ||
|
||
let serviceProvider: NodeDriverServiceProvider; | ||
try { | ||
settings = { ...settings }; | ||
settings.connectionString = setAppNameParamIfMissing({ | ||
connectionString: settings.connectionString, | ||
defaultAppName: `${packageInfo.mcpServerName} ${packageInfo.version}`, | ||
}); | ||
|
||
serviceProvider = await NodeDriverServiceProvider.connect(settings.connectionString, { | ||
productDocsLink: "https://github.com/mongodb-js/mongodb-mcp-server/", | ||
productName: "MongoDB MCP", | ||
readConcern: { | ||
level: settings.readConcern, | ||
}, | ||
readPreference: settings.readPreference, | ||
writeConcern: { | ||
w: settings.writeConcern, | ||
}, | ||
timeoutMS: settings.timeoutMS, | ||
proxy: { useEnvironmentVariableProxies: true }, | ||
applyProxyToOIDC: true, | ||
}); | ||
} catch (error: unknown) { | ||
const errorReason = error instanceof Error ? error.message : `${error as string}`; | ||
kmruiz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
this.changeState("connection-errored", { tag: "errored", errorReason }); | ||
throw new MongoDBError(ErrorCodes.MisconfiguredConnectionString, errorReason); | ||
kmruiz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
try { | ||
await serviceProvider?.runCommand?.("admin", { hello: 1 }); | ||
|
||
return this.changeState("connection-succeeded", { | ||
tag: "connected", | ||
connectedAtlasCluster: settings.atlas, | ||
serviceProvider, | ||
connectionStringAuthType: ConnectionManager.inferConnectionTypeFromSettings(settings), | ||
}); | ||
} catch (error: unknown) { | ||
const errorReason = error instanceof Error ? error.message : `${error as string}`; | ||
this.changeState("connection-errored", { tag: "errored", errorReason }); | ||
throw new MongoDBError(ErrorCodes.NotConnectedToMongoDB, errorReason); | ||
} | ||
} | ||
|
||
async disconnect(): Promise<ConnectionStateDisconnected | ConnectionStateErrored> { | ||
if (this.state.tag === "disconnected" || this.state.tag === "errored") { | ||
return this.state; | ||
} | ||
|
||
if (this.state.tag === "connected" || this.state.tag === "connecting") { | ||
try { | ||
await this.state.serviceProvider?.close(true); | ||
} finally { | ||
this.changeState("connection-closed", { tag: "disconnected" }); | ||
} | ||
} | ||
|
||
return { tag: "disconnected" }; | ||
} | ||
|
||
get currentConnectionState(): AnyConnectionState { | ||
return this.state; | ||
} | ||
|
||
changeState<Event extends keyof ConnectionManagerEvents, State extends ConnectionManagerEvents[Event][0]>( | ||
event: Event, | ||
newState: State | ||
): State { | ||
this.state = newState; | ||
// TypeScript doesn't seem to be happy with the spread operator and generics | ||
// eslint-disable-next-line | ||
this.emit(event, ...([newState] as any)); | ||
return newState; | ||
} | ||
|
||
static inferConnectionTypeFromSettings(settings: ConnectionSettings): ConnectionStringAuthType { | ||
const connString = new ConnectionString(settings.connectionString); | ||
const searchParams = connString.typedSearchParams<MongoClientOptions>(); | ||
|
||
switch (searchParams.get("authMechanism")) { | ||
case "MONGODB-OIDC": { | ||
return "oidc-auth-flow"; // TODO: depending on if we don't have a --browser later it can be oidc-device-flow | ||
} | ||
case "MONGODB-X509": | ||
return "x.509"; | ||
case "GSSAPI": | ||
return "kerberos"; | ||
case "PLAIN": | ||
if (searchParams.get("authSource") === "$external") { | ||
return "ldap"; | ||
} | ||
break; | ||
kmruiz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// default should catch also null, but eslint complains | ||
// about it. | ||
case null: | ||
default: | ||
return "scram"; | ||
} | ||
return "scram"; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.