* Initialize connection to MCP server. * If an `onToolsChanged` callback was provided, registers a notification handler * for `notifications/tools/list_changed` after connecting.
(options: McpClientConnectOptions = {})
| 90 | * for `notifications/tools/list_changed` after connecting. |
| 91 | */ |
| 92 | async connect(options: McpClientConnectOptions = {}): Promise<void> { |
| 93 | logger.info(`Connecting to MCP server: ${this.config.name} (${this.config.transport})`) |
| 94 | |
| 95 | try { |
| 96 | await this.client.connect(this.transport) |
| 97 | if (options.isCancelled?.()) { |
| 98 | await this.client.close().catch((error) => { |
| 99 | logger.warn(`Error closing cancelled connection to ${this.config.name}:`, error) |
| 100 | }) |
| 101 | throw new McpConnectionError('Connection attempt cancelled', this.config.name) |
| 102 | } |
| 103 | |
| 104 | this.isConnected = true |
| 105 | this.connectionStatus.connected = true |
| 106 | this.connectionStatus.lastConnected = new Date() |
| 107 | |
| 108 | if (this.onToolsChanged) { |
| 109 | this.client.setNotificationHandler(ToolListChangedNotificationSchema, async () => { |
| 110 | if (!this.isConnected) return |
| 111 | logger.info(`[${this.config.name}] Received tools/list_changed notification`) |
| 112 | this.onToolsChanged?.(this.config.id) |
| 113 | }) |
| 114 | logger.info(`[${this.config.name}] Registered tools/list_changed notification handler`) |
| 115 | } |
| 116 | |
| 117 | const serverVersion = this.client.getServerVersion() |
| 118 | logger.info(`Successfully connected to MCP server: ${this.config.name}`, { |
| 119 | protocolVersion: serverVersion, |
| 120 | }) |
| 121 | } catch (error) { |
| 122 | this.isConnected = false |
| 123 | if (error instanceof McpOauthRedirectRequired || error instanceof UnauthorizedError) { |
| 124 | this.connectionStatus.lastError = undefined |
| 125 | throw error |
| 126 | } |
| 127 | const errorMessage = getErrorMessage(error, 'Unknown error') |
| 128 | this.connectionStatus.lastError = errorMessage |
| 129 | logger.error(`Failed to connect to MCP server ${this.config.name}:`, error) |
| 130 | throw new McpConnectionError(errorMessage, this.config.name) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | async disconnect(): Promise<void> { |
| 135 | logger.info(`Disconnecting from MCP server: ${this.config.name}`) |
no test coverage detected