import { feature } from 'bun:bundle' import type { Base64ImageSource, ContentBlockParam, MessageParam, } from '@anthropic-ai/sdk/resources/index.mjs' import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { SSEClientTransport, type SSEClientTransportOptions, } from '@modelcontextprotocol/sdk/client/sse.js' import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js' import { StreamableHTTPClientTransport, type StreamableHTTPClientTransportOptions, } from '@modelcontextprotocol/sdk/client/streamableHttp.js' import { createFetchWithInit, type FetchLike, type Transport, } from '@modelcontextprotocol/sdk/shared/transport.js' import { CallToolResultSchema, CreateTaskResultSchema, ElicitRequestSchema, type ElicitRequestURLParams, type ElicitResult, ErrorCode, type JSONRPCMessage, type ListPromptsResult, ListPromptsResultSchema, ListRootsRequestSchema, type ListToolsResult, ListToolsResultSchema, McpError, type PromptMessage, type ResourceLink, type Task as McpTask, TaskStatusNotificationSchema, } from '@modelcontextprotocol/sdk/types.js' import { z } from 'zod' import memoize from 'lodash-es/memoize.js' import zipObject from 'lodash-es/zipObject.js' import pMap from 'p-map' import { getOriginalCwd, getSessionId } from '../../bootstrap/state.js' import type { Command } from '../../commands.js' import { getOauthConfig } from '../../constants/oauth.js' import { PRODUCT_URL } from '../../constants/product.js' import type { AppState } from '../../state/AppState.js' import { type Tool, type ToolCallProgress, toolMatchesName, } from '../../Tool.js' import { ListMcpResourcesTool } from '../../tools/ListMcpResourcesTool/ListMcpResourcesTool.js' import { type MCPProgress, MCPTool } from '../../tools/MCPTool/MCPTool.js' import { createMcpAuthTool } from '../../tools/McpAuthTool/McpAuthTool.js' import { ReadMcpResourceTool } from '../../tools/ReadMcpResourceTool/ReadMcpResourceTool.js' import { createAbortController } from '../../utils/abortController.js' import { createCombinedAbortSignal } from '../../utils/combinedAbortSignal.js' import { AbortError, isAbortError } from '../../utils/errors.js' import { count } from '../../utils/array.js' import { checkAndRefreshOAuthTokenIfNeeded, getClaudeAIOAuthTokens, handleOAuth401Error, } from '../../utils/auth.js' import { registerCleanup } from '../../utils/cleanupRegistry.js' import { detectCodeIndexingFromMcpServerName } from '../../utils/codeIndexing.js' import { logForDebugging } from '../../utils/debug.js' import { isEnvDefinedFalsy, isEnvTruthy } from '../../utils/envUtils.js' import { errorMessage, TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, } from '../../utils/errors.js' import { getMCPUserAgent } from '../../utils/http.js' import { maybeNotifyIDEConnected } from '../../utils/ide.js' import { maybeResizeAndDownsampleImageBuffer } from '../../utils/imageResizer.js' import { logMCPDebug, logMCPError } from '../../utils/log.js' import { getBinaryBlobSavedMessage, getFormatDescription, getLargeOutputInstructions, getLargeOutputPersistenceFailureInstructions, persistBinaryContent, } from '../../utils/mcpOutputStorage.js' import { getContentSizeEstimate, type MCPToolResult, mcpContentNeedsTruncation, truncateMcpContentIfNeeded, } from '../../utils/mcpValidation.js' import { WebSocketTransport } from '../../utils/mcpWebSocketTransport.js' import { memoizeWithLRU } from '../../utils/memoize.js' import { getWebSocketTLSOptions } from '../../utils/mtls.js' import { getProxyFetchOptions, getWebSocketProxyAgent, getWebSocketProxyUrl, } from '../../utils/proxy.js' import { recursivelySanitizeUnicode } from '../../utils/sanitization.js' import { getSessionIngressAuthToken } from '../../utils/sessionIngressAuth.js' import { subprocessEnv } from '../../utils/subprocessEnv.js' import { isPersistError, persistToolResult, } from '../../utils/toolResultStorage.js' import { type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, logEvent, } from '../analytics/index.js' import { type ElicitationWaitingState, runElicitationHooks, runElicitationResultHooks, } from './elicitationHandler.js' import { buildMcpToolName } from './mcpStringUtils.js' import { normalizeNameForMCP } from './normalization.js' import { listAllMcpResources, paginateMcpList } from './pagination.js' import { createMcpStdioClientTransport } from './stdioTransport.js' import { getLoggingSafeMcpBaseUrl } from './utils.js' /* eslint-disable @typescript-eslint/no-require-imports */ const fetchMcpSkillsForClient = feature('MCP_SKILLS') ? ( require('../../skills/mcpSkills.js') as typeof import('../../skills/mcpSkills.js') ).fetchMcpSkillsForClient : null import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js' import type { AgentId } from 'src/types/ids.js' import type { AssistantMessage } from 'src/types/message.js' /* eslint-enable @typescript-eslint/no-require-imports */ import { classifyMcpToolForCollapse } from '../../tools/MCPTool/classifyForCollapse.js' import { raceAbort } from '../../utils/boundedAsync.js' import { clearKeychainCache } from '../../utils/secureStorage/macOsKeychainHelpers.js' import { sleep } from '../../utils/sleep.js' import { AuthenticationCancelledError, ClaudeAuthProvider, hasMcpDiscoveryButNoToken, wrapFetchWithStepUpDetection, } from './auth.js' import { markClaudeAiMcpConnected } from './claudeai.js' import { getAllMcpConfigs, isMcpServerDisabled } from './config.js' import { type CredentialScope, resumeIn } from './credentialScope.js' import { getMcpServerHeaders } from './headersHelper.js' import { SdkControlClientTransport } from './SdkControlTransport.js' import { failMcpServerTasksForServer, handleMcpTaskStatusNotification, isMcpTaskBackgroundingDisabled, clearMcpToolTaskSupport, isMcpToolTaskSupportUnknown, mcpServerAdvertisesTaskTools, mcpTaskSupportForTool, recordMcpToolTaskSupport, trackMcpServerTask, } from './tasks.js' import type { ConnectedMCPServer, MCPServerConnection, McpSdkServerConfig, ScopedMcpServerConfig, ServerResource, } from './types.js' /** * Custom error class to indicate that an MCP tool call failed due to * authentication issues (e.g., expired OAuth token returning 401). * This error should be caught at the tool execution layer to update * the client's status to 'needs-auth'. */ export class McpAuthError extends Error { serverName: string constructor(serverName: string, message: string) { super(message) this.name = 'McpAuthError' this.serverName = serverName } } /** * Thrown when an MCP session has expired and the connection cache has been cleared. * The caller should get a fresh client via ensureConnectedClient and retry. */ class McpSessionExpiredError extends Error { constructor(serverName: string) { super(`MCP server "${serverName}" session expired`) this.name = 'McpSessionExpiredError' } } /** * Thrown when an MCP tool returns `isError: true`. Carries the result's `_meta` * so SDK consumers can still receive it — per the MCP spec, `_meta` is on the * base Result type and is valid on error results. */ export class McpToolCallError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS extends TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS { constructor( message: string, telemetryMessage: string, readonly mcpMeta?: { _meta?: Record }, ) { super(message, telemetryMessage) this.name = 'McpToolCallError' } } /** * Detects whether an error is an MCP "Session not found" error (HTTP 404 + JSON-RPC code -32001). * Per the MCP spec, servers return 404 when a session ID is no longer valid. * We check both signals to avoid false positives from generic 404s (wrong URL, server gone, etc.). */ export function isMcpSessionExpiredError(error: Error): boolean { const httpStatus = 'code' in error ? (error as Error & { code?: number }).code : undefined if (httpStatus !== 404) { return false } // The SDK embeds the response body text in the error message. // MCP servers return: {"error":{"code":-32001,"message":"Session not found"},...} // Check for the JSON-RPC error code to distinguish from generic web server 404s. return ( error.message.includes('"code":-32001') || error.message.includes('"code": -32001') ) } /** * Default timeout for MCP tool calls (5 minutes — reasonable for most tools). * Use MCP_TOOL_TIMEOUT env var to override per-server. * The previous default of ~27.8 hours effectively meant no timeout, causing * tools to hang indefinitely on unresponsive servers. */ const DEFAULT_MCP_TOOL_TIMEOUT_MS = 300_000 const MCP_TOOL_ACTIVITY_INTERVAL_MS = 30_000 /** * Cap on MCP tool descriptions and server instructions sent to the model. * OpenAPI-generated MCP servers have been observed dumping 15-60KB of endpoint * docs into tool.description; this caps the p95 tail without losing the intent. */ const MAX_MCP_DESCRIPTION_LENGTH = 2048 /** * Gets the timeout for MCP tool calls in milliseconds. * Uses MCP_TOOL_TIMEOUT environment variable if set, otherwise defaults to ~27.8 hours. */ function getMcpToolTimeoutMs(): number { return ( parseInt(process.env.MCP_TOOL_TIMEOUT || '', 10) || DEFAULT_MCP_TOOL_TIMEOUT_MS ) } import { isClaudeInChromeMCPServer } from '../../utils/claudeInChrome/common.js' // Lazy: toolRendering.tsx pulls React/ink; only needed when Claude-in-Chrome MCP server is connected /* eslint-disable @typescript-eslint/no-require-imports */ const claudeInChromeToolRendering = (): typeof import('../../utils/claudeInChrome/toolRendering.js') => require('../../utils/claudeInChrome/toolRendering.js') // Lazy: wrapper.tsx → hostAdapter.ts → executor.ts pulls both native modules // (@ant/computer-use-input + @ant/computer-use-swift). Runtime-gated by // GrowthBook tengu_malort_pedway (see gates.ts). const computerUseWrapper = feature('CHICAGO_MCP') ? (): typeof import('../../utils/computerUse/wrapper.js') => require('../../utils/computerUse/wrapper.js') : undefined const isComputerUseMCPServer = feature('CHICAGO_MCP') ? ( require('../../utils/computerUse/common.js') as typeof import('../../utils/computerUse/common.js') ).isComputerUseMCPServer : undefined import { mkdir, readFile, unlink, writeFile } from 'fs/promises' import { dirname, join } from 'path' import { getClaudeConfigHomeDir } from '../../utils/envUtils.js' /* eslint-enable @typescript-eslint/no-require-imports */ import { jsonParse, jsonStringify } from '../../utils/slowOperations.js' import { jsonRedactor } from '../../utils/redaction.js' const MCP_AUTH_CACHE_TTL_MS = 15 * 60 * 1000 // 15 min type McpAuthCacheData = Record function getMcpAuthCachePath(): string { return join(getClaudeConfigHomeDir(), 'mcp-needs-auth-cache.json') } // Memoized so N concurrent isMcpAuthCached() calls during batched connection // share a single file read instead of N reads of the same file. Invalidated // on write (setMcpAuthCacheEntry) and clear (clearMcpAuthCache). Not using // lodash memoize because we need to null out the cache, not delete by key. let authCachePromise: Promise | null = null function getMcpAuthCache(): Promise { if (!authCachePromise) { authCachePromise = readFile(getMcpAuthCachePath(), 'utf-8') .then(data => jsonParse(data) as McpAuthCacheData) .catch(() => ({})) } return authCachePromise } async function isMcpAuthCached(serverId: string): Promise { const cache = await getMcpAuthCache() const entry = cache[serverId] if (!entry) { return false } return Date.now() - entry.timestamp < MCP_AUTH_CACHE_TTL_MS } // Serialize cache writes through a promise chain to prevent concurrent // read-modify-write races when multiple servers return 401 in the same batch let writeChain = Promise.resolve() function setMcpAuthCacheEntry(serverId: string): void { writeChain = writeChain .then(async () => { const cache = await getMcpAuthCache() cache[serverId] = { timestamp: Date.now() } const cachePath = getMcpAuthCachePath() await mkdir(dirname(cachePath), { recursive: true }) await writeFile(cachePath, jsonStringify(cache)) // Invalidate the read cache so subsequent reads see the new entry. // Safe because writeChain serializes writes: the next write's // getMcpAuthCache() call will re-read the file with this entry present. authCachePromise = null }) .catch(() => { // Best-effort cache write }) } export function clearMcpAuthCache(): void { authCachePromise = null void unlink(getMcpAuthCachePath()).catch(() => { // Cache file may not exist }) } /** * Spread-ready analytics field for the server's base URL. Calls * getLoggingSafeMcpBaseUrl once (not twice like the inline ternary it replaces). * Typed as AnalyticsMetadata since the URL is query-stripped and safe to log. */ function mcpBaseUrlAnalytics(serverRef: ScopedMcpServerConfig): { mcpServerBaseUrl?: AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS } { const url = getLoggingSafeMcpBaseUrl(serverRef) return url ? { mcpServerBaseUrl: url as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, } : {} } /** * Shared handler for sse/http/claudeai-proxy auth failures during connect: * emits tengu_mcp_server_needs_auth, caches the needs-auth entry, and returns * the needs-auth connection result. */ function handleRemoteAuthFailure( name: string, serverRef: ScopedMcpServerConfig, transportType: 'sse' | 'http' | 'claudeai-proxy', ): MCPServerConnection { logEvent('tengu_mcp_server_needs_auth', { transportType: transportType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, ...mcpBaseUrlAnalytics(serverRef), }) const label: Record = { sse: 'SSE', http: 'HTTP', 'claudeai-proxy': 'claude.ai proxy', } logMCPDebug( name, `Authentication required for ${label[transportType]} server`, ) setMcpAuthCacheEntry(name) return { name, type: 'needs-auth', config: serverRef } } /** * Fetch wrapper for claude.ai proxy connections. Attaches the OAuth bearer * token and retries once on 401 via handleOAuth401Error (force-refresh). * * The Anthropic API path has this retry (withRetry.ts, grove.ts) to handle * memoize-cache staleness and clock drift. Without the same here, a single * stale token mass-401s every claude.ai connector and sticks them all in the * 15-min needs-auth cache. */ export function createClaudeAiProxyFetch(innerFetch: FetchLike): FetchLike { return async (url, init) => { const doRequest = async () => { await checkAndRefreshOAuthTokenIfNeeded() const currentTokens = getClaudeAIOAuthTokens() if (!currentTokens) { throw new Error('No claude.ai OAuth token available') } // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins const headers = new Headers(init?.headers) headers.set('Authorization', `Bearer ${currentTokens.accessToken}`) const response = await innerFetch(url, { ...init, headers }) // Return the exact token that was sent. Reading getClaudeAIOAuthTokens() // again after the request is wrong under concurrent 401s: another // connector's handleOAuth401Error clears the memoize cache, so we'd read // the NEW token from keychain, pass it to handleOAuth401Error, which // finds same-as-keychain → returns false → skips retry. Same pattern as // bridgeApi.ts withOAuthRetry (token passed as fn param). return { response, sentToken: currentTokens.accessToken } } const { response, sentToken } = await doRequest() if (response.status !== 401) { return response } // handleOAuth401Error returns true only if the token actually changed // (keychain had a newer one, or force-refresh succeeded). Gate retry on // that — otherwise we double round-trip time for every connector whose // downstream service genuinely needs auth (the common case: 30+ servers // with "MCP server requires authentication but no OAuth token configured"). const tokenChanged = await handleOAuth401Error(sentToken).catch(() => false) logEvent('tengu_mcp_claudeai_proxy_401', { tokenChanged: tokenChanged as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, }) if (!tokenChanged) { // ELOCKED contention: another connector may have won the lockfile and refreshed — check if token changed underneath us const now = getClaudeAIOAuthTokens()?.accessToken if (!now || now === sentToken) { return response } } try { return (await doRequest()).response } catch { // Retry itself failed (network error). Return the original 401 so the // outer handler can classify it. return response } } } // Minimal interface for WebSocket instances passed to mcpWebSocketTransport type WsClientLike = { readonly readyState: number close(): void send(data: string): void } /** * Create a ws.WebSocket client with the MCP protocol. * Bun's ws shim types lack the 3-arg constructor (url, protocols, options) * that the real ws package supports, so we cast the constructor here. */ async function createNodeWsClient( url: string, options: Record, ): Promise { const wsModule = await import('ws') const WS = wsModule.default as unknown as new ( url: string, protocols: string[], options: Record, ) => WsClientLike return new WS(url, ['mcp'], options) } const IMAGE_MIME_TYPES = new Set([ 'image/jpeg', 'image/png', 'image/gif', 'image/webp', ]) function getConnectionTimeoutMs(): number { return parseInt(process.env.MCP_TIMEOUT || '', 10) || 30000 } /** * Default timeout for individual MCP requests (auth, tool calls, etc.) */ const MCP_REQUEST_TIMEOUT_MS = 60000 /** * MCP Streamable HTTP spec requires clients to advertise acceptance of both * JSON and SSE on every POST. Servers that enforce this strictly reject * requests without it (HTTP 406). * https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#sending-messages-to-the-server */ const MCP_STREAMABLE_HTTP_ACCEPT = 'application/json, text/event-stream' /** * Keep fetch timeout and cancellation resources alive until a streaming * response is consumed or cancelled, not merely until response headers arrive. */ function wrapResponseBodyWithCleanup( response: Response, cleanup: () => void, signal?: AbortSignal, ): Response { if (!response.body) { cleanup() return response } const reader = response.body.getReader() let isCleanedUp = false const finish = () => { if (isCleanedUp) return isCleanedUp = true signal?.removeEventListener('abort', cancelReader) cleanup() } const cancelReader = () => { void reader.cancel(signal?.reason).catch(() => {}) finish() } signal?.addEventListener('abort', cancelReader, { once: true }) if (signal?.aborted) { cancelReader() } const body = new ReadableStream({ async pull(controller) { try { const { done, value } = await reader.read() if (done) { controller.close() finish() } else { controller.enqueue(value) } } catch (error) { controller.error(error) finish() } }, async cancel(reason) { try { await reader.cancel(reason) } finally { finish() } }, }) return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers, }) } /** * Wrap a fetch function with a fresh request timeout and an MCP-compatible * Accept header. The request timeout and parent abort listener stay active * until a streaming response is consumed or cancelled. * * GET requests are excluded because MCP GET streams may stay open indefinitely. */ export function wrapFetchWithTimeout(baseFetch: FetchLike): FetchLike { return async (url: string | URL, init?: RequestInit) => { const method = (init?.method ?? 'GET').toUpperCase() // Skip timeout for GET requests - in MCP transports, these are long-lived SSE streams. // (OAuth discovery GETs in auth.ts use a separate createAuthFetch() with its own timeout.) if (method === 'GET') { return baseFetch(url, init) } // Normalize headers and guarantee the Streamable-HTTP Accept value. new Headers() // accepts HeadersInit | undefined and copies from plain objects, tuple arrays, // and existing Headers instances — so whatever shape the SDK handed us, the // Accept value survives the spread below as an own property of a concrete object. // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins const headers = new Headers(init?.headers) if (!headers.has('accept')) { headers.set('accept', MCP_STREAMABLE_HTTP_ACCEPT) } // Use setTimeout instead of AbortSignal.timeout() so we can clearTimeout on // completion. AbortSignal.timeout's internal timer is only released when the // signal is GC'd, which in Bun is lazy — ~2.4KB of native memory per request // lingers for the full 60s even when the request completes in milliseconds. const controller = new AbortController() const timer = setTimeout( c => c.abort(new DOMException('The operation timed out.', 'TimeoutError')), MCP_REQUEST_TIMEOUT_MS, controller, ) timer.unref?.() const parentSignal = init?.signal const abort = () => controller.abort(parentSignal?.reason) parentSignal?.addEventListener('abort', abort) if (parentSignal?.aborted) { controller.abort(parentSignal.reason) } const cleanup = () => { clearTimeout(timer) parentSignal?.removeEventListener('abort', abort) } try { const response = await baseFetch(url, { ...init, headers, signal: controller.signal, }) clearTimeout(timer) return wrapResponseBodyWithCleanup(response, cleanup, controller.signal) } catch (error) { cleanup() throw error } } } type McpRequestId = string | number /** * Associate Streamable HTTP POST response bodies with MCP request IDs so * notifications/cancelled can interrupt a response stream after headers arrive. */ export function wrapFetchWithRequestCancellation( baseFetch: FetchLike, activeRequests: Map, ): FetchLike { return async (url, init) => { let requestId: McpRequestId | undefined if ( (init?.method ?? 'GET').toUpperCase() === 'POST' && typeof init?.body === 'string' ) { try { const request: unknown = JSON.parse(init.body) if ( request !== null && typeof request === 'object' && 'id' in request && (typeof request.id === 'string' || typeof request.id === 'number') ) { requestId = request.id } } catch { // Leave malformed/non-JSON requests to the underlying fetch unchanged. } } if (requestId === undefined) { return baseFetch(url, init) } const requestController = createAbortController() activeRequests.set(requestId, requestController) const { signal, cleanup } = createCombinedAbortSignal( init?.signal ?? undefined, { signalB: requestController.signal, trace: { subsystem: 'mcp_http_request', controllerRole: 'mcp_http_request', }, }, ) const finish = () => { cleanup() if (activeRequests.get(requestId!) === requestController) { activeRequests.delete(requestId!) } } try { const response = await baseFetch(url, { ...init, signal }) return wrapResponseBodyWithCleanup(response, finish, signal) } catch (error) { finish() throw error } } } /** * Abort the matching HTTP request body when the MCP SDK emits cancellation. */ export function attachMcpRequestCancellationHandler( transport: Transport, activeRequests: Map, ): void { const send = transport.send.bind(transport) transport.send = async (message, options) => { if ( 'method' in message && message.method === 'notifications/cancelled' && 'params' in message && message.params !== undefined && typeof message.params === 'object' && 'requestId' in message.params ) { const requestId = message.params.requestId if (typeof requestId === 'string' || typeof requestId === 'number') { activeRequests.get(requestId)?.abort( new DOMException('MCP request cancelled.', 'AbortError'), ) } } return send(message, options) } } export function getMcpServerConnectionBatchSize(): number { return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE || '', 10) || 3 } function getRemoteMcpServerConnectionBatchSize(): number { return ( parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE || '', 10) || 20 ) } type InProcessMcpServer = { connect(t: Transport): Promise close(): Promise } const MAX_MCP_STDERR_CHARS = 256 * 1024 const MCP_STDERR_TRUNCATED_MARKER = '\n...[stderr truncated]' export function buildMcpSseEventSourceHeaders( initHeaders: HeadersInit | undefined, ): Headers { const headers = new Headers(initHeaders) if (!headers.has('User-Agent')) { headers.set('User-Agent', getMCPUserAgent()) } headers.set('Accept', 'text/event-stream') return headers } export function buildMcpSseRequestHeaders( initHeaders: HeadersInit | undefined, combinedHeaders: Record, ): Headers { const headers = new Headers(initHeaders) new Headers(combinedHeaders).forEach((value, key) => { headers.set(key, value) }) return headers } export function appendBoundedMcpStderr( current: string, chunk: Buffer | string, ): string { if (current.includes(MCP_STDERR_TRUNCATED_MARKER)) { return current } const text = typeof chunk === 'string' ? chunk : chunk.toString() const next = current + text if (next.length <= MAX_MCP_STDERR_CHARS) { return next } return ( next.slice(0, MAX_MCP_STDERR_CHARS - MCP_STDERR_TRUNCATED_MARKER.length) + MCP_STDERR_TRUNCATED_MARKER ) } export async function cleanupFailedConnection( transport: Pick, inProcessServer?: Pick, ): Promise { if (inProcessServer) { await inProcessServer.close().catch(() => {}) } await transport.close().catch(() => {}) } export function logMcpServerStderr( name: string, stderrOutput: string, connectedSuccessfully: boolean, ): void { if (!stderrOutput) return const message = `Server stderr: ${stderrOutput}` if (connectedSuccessfully) { logMCPDebug(name, message) } else { logMCPError(name, message) } } function isLocalMcpServer(config: ScopedMcpServerConfig): boolean { return !config.type || config.type === 'stdio' || config.type === 'sdk' } // For the IDE MCP servers, we only include specific tools const ALLOWED_IDE_TOOLS = ['mcp__ide__executeCode', 'mcp__ide__getDiagnostics'] function isIncludedMcpTool(tool: Tool): boolean { return ( !tool.name.startsWith('mcp__ide__') || ALLOWED_IDE_TOOLS.includes(tool.name) ) } /** * Generates the cache key for a server connection * @param name Server name * @param serverRef Server configuration * @returns Cache key string */ export function getServerCacheKey( name: string, serverRef: ScopedMcpServerConfig, ): string { return `${name}-${jsonStringify(serverRef)}` } /** * One discovery generation per transport, keyed by the client object * that owns it: a reconnect creates a new client object, so the * replacement gets its own entry instead of reading — or invalidating — * the entry the transport it replaces wrote. Callers sharing one * transport share one client object, so they still share one entry. * Assigned lazily per object, so a client that never discovers anything * takes no id (CodeRabbit #2493 review 5957362782). */ const discoveryGenerations = new WeakMap() let discoveryGenerationCounter = 0 /** * Discovery cache key for a connection. The display name alone does not * identify a connection — two sessions can run the same server name at * different endpoints — so the discovery memos are keyed by the same * connection key the connect cache uses. A fetch keyed by name alone * lets a same-named peer's tools answer a host's reconnect. The key is * further scoped to the transport generation that owns the client, so a * replacement transport never reads entries written by the transport it * replaces. */ export function getDiscoveryCacheKey(client: MCPServerConnection): string { let generation = discoveryGenerations.get(client) if (generation === undefined) { generation = `gen${++discoveryGenerationCounter}` discoveryGenerations.set(client, generation) } return `${getServerCacheKey(client.name, client.config)}#${generation}` } /** * Callers awaiting a connect, keyed by the connect's own promise — not * the cache key: a cache clear replaces the entry for a key while an * older generation is still pending, and re-keying by the string would * drop the older generation's waiters (or count a newer generation's). * A generation's waiter count is its own. */ const connectWaiters = new Map< Promise, { count: number } >() /** * Clients another caller adopted from the shared connect cache: a * reconnect that created one must not close it on cancellation, or it * would fail the session that adopted it. A client is adopted when a * caller reuses a connect it did not start — joining one in flight, or a * settled cached one. Adoption is counted per caller, not a single flag: * a join that aborts before it receives the client withdraws its own * claim, and only when the last claim goes is the client unadopted again. * A plain set cannot tell one adopter leaving from the last one leaving. * Once a caller receives the client, its provisional claim is replaced * by the single permanent marker below, so repeated joins keep one claim * per client instead of one per call. */ const adoptedMcpClients = new WeakMap>() /** * The claim shared by every received adoption of a client. Provisional * claims stay per-caller until receipt — an abort before receipt * withdraws only its own — and consolidate into this marker on receipt. * A caller that passes an owner consolidates into the owner instead: * setup joins adopt under their session, so abandoning one session's * setup withdraws only that session's claim (CodeRabbit #2493 review * 5964014825) instead of stripping every adopter's. */ const permanentAdoptionClaim = {} function adoptMcpClient(client: MCPServerConnection, claim: object): void { let claims = adoptedMcpClients.get(client) if (!claims) { claims = new Set() adoptedMcpClients.set(client, claims) } claims.add(claim) } /** * Withdraws one caller's adoption claim. Returns true when the client has * no claims left. Withdrawing alone does not clean the client up — the * caller re-runs a release the claim had blocked (see * blockedUnownedReleases), since no other step re-runs it. */ function withdrawMcpClientAdoption(client: MCPServerConnection, claim: object): boolean { const claims = adoptedMcpClients.get(client) if (!claims) return true claims.delete(claim) if (claims.size === 0) { adoptedMcpClients.delete(client) return true } return false } /** * Clients a release declined to clean up because a caller had adopted * them. When the last claim is withdrawn, the withdrawing call re-runs * the release — otherwise an abandoned join leaves the transport open * and cached with no owner, and nobody ever cleans it up. */ const blockedUnownedReleases = new WeakSet() /** * The client each connect promise settled to, once it has settled. * Recorded by a `.then` the wrapper attaches when the promise is created, * so it is in place before any caller can await the promise — and therefore * before any release can run. A join of an already-settled connect adopts * synchronously from this map (below): recording adoption in a `.then` on * the cached promise instead leaves a microtask gap a release can win, no * matter how many ticks the release waits. A WeakMap, so a settled entry * never keeps a client — or its transport — alive past its promise. */ const settledConnectClients = new WeakMap< Promise, MCPServerConnection >() /** Whether another caller adopted this client from the shared connect. */ export function isMcpClientAdopted(client: MCPServerConnection): boolean { return (adoptedMcpClients.get(client)?.size ?? 0) > 0 } /** * Whether the connection cache no longer holds this client as its * settled generation — a replacement took over the entry, or one is in * flight. No entry means the client never went through the connect * cache (in-process SDK servers), so it is not retired. Used where a * stale generation must not act on the current one: a retired * transport's list-changed update, and its onclose clear/reconnect * (CodeRabbit #2493 review 5957362782). One microtask tick tells * whether the entry already settled: a .then callback on a settled * promise runs before the continuation of the await below; on a pending * one it never runs. (The same probe lives in releaseUnownedMcpClient * and isClientCached.) */ export async function isMcpClientRetired( name: string, serverRef: ScopedMcpServerConfig, client: MCPServerConnection, ): Promise { const key = getServerCacheKey(name, serverRef) const cached = connectToServer.cache.get(key) as | Promise | undefined if (cached === undefined) return false let settledValue: MCPServerConnection | undefined let isSettled = false void cached.then( value => { isSettled = true settledValue = value }, () => {}, ) await Promise.resolve() // A pending entry is a newer connect in flight: this generation no // longer owns the entry, and the replacement's completion applies its // own discovery. if (!isSettled) return true return settledValue !== client } /** * Sessions that installed a client as their current client record, by * owner token (the session instance). Adoption alone cannot tell session * ownership from cache reuse: every tool call through * ensureConnectedClient joins the cached connect and consolidates into * the same permanent adoption marker, so a session that reuses the cache * for one completed call looks like a permanent owner forever. The * install record is the ownership: a session notes the install when it * puts the client in its record and the uninstall when it replaces or * drops that record, so a client with no installers left has no real * session owner — only completed cache reuse — and may be released. A * WeakMap, so an install record never keeps a client — or its transport * — alive past the client itself (CodeRabbit #2493 review 5957362782). */ const installedMcpClients = new WeakMap>() /** Notes that a session installed this client as its current record. */ export function noteMcpClientInstalled( client: MCPServerConnection, owner: object, ): void { let owners = installedMcpClients.get(client) if (!owners) { owners = new Set() installedMcpClients.set(client, owners) } owners.add(owner) // Installing converts the owner's setup reservation into ownership: // the reservation held the client alive while the session was still // setting up, and the install record holds it from here on. The record // goes in first, so a blocked release the reservation's release re-runs // sees this session as an owner and stands down. releaseMcpClientSetupReservation(client, owner) } /** * Notes that a session dropped this client from its record — replaced by * a reconnected client, or cleaned up on close. Idempotent: dropping a * record the session never installed is a no-op. */ export function noteMcpClientUninstalled( client: MCPServerConnection, owner: object, ): void { const owners = installedMcpClients.get(client) if (!owners) return owners.delete(owner) if (owners.size === 0) installedMcpClients.delete(client) } /** Whether any session still has this client as its current record. */ export function isMcpClientInstalled(client: MCPServerConnection): boolean { return (installedMcpClients.get(client)?.size ?? 0) > 0 } /** * Sessions that received a client and are still setting it up, by owner * token. Adoption alone cannot cover that window: connectSdkMcpServers * waits for every server before the caller installs any of them, so a * session that received a client has no install record yet — and the * single permanent adoption marker can be withdrawn by another session's * reauthentication while this one is still setting up, closing the * transport under it. A reservation is per owner, from receipt through * installation: installing converts it (see noteMcpClientInstalled), and * setup failure or cancellation releases it. A WeakMap, so a reservation * never keeps a client — or its transport — alive past the client itself * (CodeRabbit #2493 review 5961865068). */ const setupMcpClientReservations = new WeakMap< MCPServerConnection, Set >() /** Reserves a received client for one owner's setup, until it installs. */ export function reserveMcpClientForSetup( client: MCPServerConnection, owner: object, ): void { let owners = setupMcpClientReservations.get(client) if (!owners) { owners = new Set() setupMcpClientReservations.set(client, owners) } owners.add(owner) } /** Whether any session is still setting this client up. */ export function hasMcpClientSetupReservation( client: MCPServerConnection, ): boolean { return (setupMcpClientReservations.get(client)?.size ?? 0) > 0 } /** * Releases one owner's setup reservation. When the last reservation goes * and a release was blocked on it, the release is re-run — otherwise a * client whose setup failed keeps a transport open with no owner, and * nobody ever cleans it up. The client carries its own name and config, * so the re-run needs no caller-supplied key. */ export function releaseMcpClientSetupReservation( client: MCPServerConnection, owner: object, ): void { const owners = setupMcpClientReservations.get(client) if (!owners) return owners.delete(owner) // The reservation goes with the owner's adoption claim: a session that // received this client for setup adopted it from the shared connect // under its owner token, and no install record ever followed. The // claim must go here, not only when the last reservation goes — with // another owner still holding a reservation, a claim left behind would // survive that owner's later release too, and the retry would decline // on it forever (CodeRabbit #2493 review 5964014825). Only the // abandoning owner's claim goes — the shared marker belongs to joins // that passed no owner (a tool call through ensureConnectedClient, a // second session's join), and withdrawing it would close a transport // a live caller still holds. A joiner still awaiting receipt keeps // the client alive either way: its provisional claim is still in the // set, so the retry declines and re-blocks. withdrawMcpClientAdoption(client, owner) if (owners.size === 0) { setupMcpClientReservations.delete(client) // A session that installed the client in the meantime owns it now: // leave the blocked release for its own uninstall path instead of // closing a transport under a live owner. if ( blockedUnownedReleases.has(client) && !isMcpClientInstalled(client) ) { blockedUnownedReleases.delete(client) void releaseUnownedMcpClient(client.name, client.config, client) } } } /** Setup-reservation count for a client, for tests only. */ export function getMcpClientSetupReservationCountForTesting( client: MCPServerConnection, ): number { return setupMcpClientReservations.get(client)?.size ?? 0 } /** * Releases a client a session adopted and then stopped owning: withdraws * the permanent adoption claim the session's cache reuse left behind, * and re-runs a release the claim had blocked. Only the permanent marker * goes — provisional claims belong to joiners still awaiting receipt, * and withdrawing them would break the abort-before-receipt path; a * joiner whose receipt lands afterwards re-adds the marker, and its own * install record keeps the client alive until that session drops it. * A caller that knows the adopting owner passes it so that owner's claim * goes too; a session that adopted under its owner token leaves no claim * behind otherwise. Callers must have uninstalled the client first and * checked no other session still has it installed. */ export async function releaseAdoptedMcpClient( name: string, serverRef: ScopedMcpServerConfig, client: MCPServerConnection, owner?: object, ): Promise { if (client.type !== 'connected') return withdrawMcpClientAdoption(client, permanentAdoptionClaim) if (owner !== undefined) withdrawMcpClientAdoption(client, owner) if ( !isMcpClientAdopted(client) && blockedUnownedReleases.has(client) ) { blockedUnownedReleases.delete(client) await releaseUnownedMcpClient(name, serverRef, client) } } /** * Adoption claim count for a client, for tests only: repeated joins must * consolidate to one claim per adopting caller — the single permanent * marker for joins that passed no owner, the owner object for joins * that did — instead of retaining one claim object per call. */ export function getMcpClientAdoptionClaimCountForTesting( client: MCPServerConnection, ): number { return adoptedMcpClients.get(client)?.size ?? 0 } /** * Clients whose transport an installed-release already closed. A session * close runs more than once in practice (engine close, then query close), * and cleanup on an already-closed transport must not run twice. */ const releasedInstalledMcpClients = new WeakSet() /** * The one ownership-aware release for a session-owned client, shared by * the query and v2 session close paths: drops this owner's install * record, and only when no other session still has the client installed * does it withdraw the adoption claims — the permanent marker and this * owner's own claim — and release the client — * evicting that generation from the connect cache before cleanup, so a * caller joining afterwards dials fresh instead of receiving a client * that is closing. A client another owner still uses stays open; a * client a joiner is still setting up under a reservation stays open * too (releaseUnownedMcpClient re-checks both). Fire-and-forget from * synchronous close() paths (CodeRabbit #2493 review 5961865068). */ export async function releaseInstalledMcpClient( name: string, serverRef: ScopedMcpServerConfig, client: MCPServerConnection, owner: object, ): Promise { if (client.type !== 'connected') return noteMcpClientUninstalled(client, owner) if (isMcpClientInstalled(client)) return if (releasedInstalledMcpClients.has(client)) return // This session's install is gone: the permanent adoption claim its // cache reuse left behind goes with it — and so does this session's // own claim, if it adopted under its owner token — and the release // this claim may have blocked is the one this call performs: clear // the claims first so the release below does not have to wait for a // second withdrawing call that may never come. withdrawMcpClientAdoption(client, permanentAdoptionClaim) withdrawMcpClientAdoption(client, owner) blockedUnownedReleases.delete(client) await releaseUnownedMcpClient(name, serverRef, client) // Only a release that actually ran may mark the client done: a release // declined for a live adopter or a setup reservation leaves the flag // set, and the next withdrawing call re-runs it. if (!blockedUnownedReleases.has(client)) { releasedInstalledMcpClients.add(client) } } /** * Releases a connected client no session adopted, and evicts it from the * connect cache so a later connection dials fresh instead of reusing a * closed client. A client another caller adopted from the shared connect * stays cached: closing it would fail that session's in-flight MCP calls. * Cache membership alone is not adoption — the cache holds a client its * creator made whether or not anyone adopted it. */ export async function releaseUnownedMcpClient( name: string, serverRef: ScopedMcpServerConfig, client: MCPServerConnection, ): Promise { if (client.type !== 'connected') return if (isMcpClientAdopted(client) || isMcpClientInstalled(client)) { // A caller holds this client — adopted from the shared connect, or // installed as a session's current record; remember the declined // release so the withdrawing call can re-run it when the last // holder goes. blockedUnownedReleases.add(client) return } if (hasMcpClientSetupReservation(client)) { // A session received this client and is still setting it up: it has // no install record yet, so the check above cannot see it. Its // reservation holds the transport until setup installs or releases // it (CodeRabbit #2493 review 5961865068). blockedUnownedReleases.add(client) return } // Evict the cache entry only when it still holds this client — and // decide that BEFORE cleanup: cleanup fires the close callback, which // evicts by key, so a newer generation that replaced the entry while // this one was being released would be dropped before any comparison // here could save it. A newer connection for the same key replaces the // entry while this one is being released, so only a value that has // already settled is compared — one microtask tick tells whether the // entry settled to this client: a .then callback on a settled promise // runs before the continuation of the await below, and on a pending // one it never runs. Awaiting the entry instead would hang on its // pending initialize. const key = getServerCacheKey(name, serverRef) const cached = connectToServerMemoized.cache.get(key) as | Promise | undefined let settledToThisClient = false if (cached !== undefined) { let settledValue: MCPServerConnection | undefined let isSettled = false void cached.then( value => { isSettled = true settledValue = value }, () => {}, ) await Promise.resolve() settledToThisClient = isSettled && settledValue === client } // A join that ran while the probe yielded records its adoption in a // `.then` on the cached promise, queued behind the probe's continuation. // One more tick lets a join whose trigger was queued behind that // continuation run its call before the decision below: the call adopts // synchronously in connectToServer (see settledConnectClients), so the // decision sees it without a third tick — a fixed tick count alone can // always be beaten by a join scheduled one tick later. Decide ownership // here, before cleanup starts — a recheck after cleanup would be too // late, the joiner would already hold a closing client. The probe's // first tick above still stands: it lets the adoption callback of a // caller that joined while the connect was still pending land — that // callback was attached at join time, ahead of the probe's continuation. await Promise.resolve() if ( isMcpClientAdopted(client) || isMcpClientInstalled(client) || hasMcpClientSetupReservation(client) ) { // As above: a join that landed during the probe holds this client, // and so does a session that installed it — or reserved it for // setup — while the probe yielded. blockedUnownedReleases.add(client) return } // Evict the entry before cleanup starts, so a caller that joins after // this decision dials a fresh connect instead of receiving this client // while its transport closes. Only the entry the probe saw goes: a // newer generation that replaced it while this one was being released // stays cached, and the close callback is generation-guarded the same way. if ( settledToThisClient && connectToServerMemoized.cache.get(key) === cached ) { connectToServerMemoized.cache.delete(key) } await client.cleanup().catch(() => {}) } /** * Closes a stalled connect's transport once its last waiter cancels. The * memoize body's abort listener watches only the creator's signal, so a * waiter that is not the creator cannot close it; the wrapper closes it * through here instead, keyed by the connect's promise so a newer * generation for the same key cannot close this one. Dropped when the * connect settles or the transport is closed. */ const connectTransportClosers = new Map< Promise, () => void >() /** * Whether no caller is still awaiting the connect this promise belongs * to. Tracked by the originating promise, not the current cache * entry: a cache clear removes the mapping but not the waiter, and * cancelling the creator must not close a transport another waiter * still needs. The creator leaves the count when it cancels, so a count * of one after that is a live joiner, not the creator alone — only an * absent entry (the wrapper deletes it when the last waiter leaves) * means nobody remains. A promise the wrapper has not supplied yet (the * synchronous stdio path) has no waiters by construction: no other code * can have joined before the body yields. */ function hasNoConnectWaiters( promise: Promise | undefined, ): boolean { if (!promise) return true return connectWaiters.get(promise) === undefined } /** * TODO (ollie): The memoization here increases complexity by a lot, and im not sure it really improves performance * Attempts to connect to a single MCP server * @param name Server name * @param serverRef Scoped server configuration * @returns A wrapped client (either connected or failed) */ const connectToServerMemoized = memoize( async ( name: string, serverRef: ScopedMcpServerConfig, serverStats?: { totalServers: number stdioCount: number sseCount: number httpCount: number sseIdeCount: number wsIdeCount: number }, /** * Aborts this connect attempt: closing the transport rejects a stalled * initialize instead of waiting out the connection timeout. Only the * caller that created this connect passes one — the memoize body runs * once per key, so an adopter of the cached promise attaches nothing * and cannot close a connect it did not start. The listener is removed * once the connect settles, so a later abort cannot close the live, * shared client. Not part of the memo key (getServerCacheKey ignores * it), so sharing is unchanged. */ signal?: AbortSignal, /** * Holds this connect's own promise, set by the wrapper once memoize * returns it: the body cannot read its promise back from the cache, * which is set only after the body returns and may hold a newer * generation by then. The waiter counts use this originating * promise, not whichever entry is current; the transport closer is * registered by the wrapper against it, not by the body below. * Also carries the closer the wrapper registers for this connect: * the body leaves it here because it cannot register the closer * itself — on the synchronous stdio path it reaches the connect * before the wrapper has supplied the promise, so reading it here * yields undefined and no closer would ever be registered. Not part * of the memo key (getServerCacheKey ignores it). */ generation?: { promise?: Promise closeStalledTransport?: () => void }, ): Promise => { const connectStartTime = Date.now() let inProcessServer: InProcessMcpServer | undefined // Set once the connect settles, so a waiter that cancels in the same // window cannot close a transport that just connected. let connectSettled = false try { let transport // Closing the transport rejects the stalled initialize below. The // transport is assigned later, so the handler closes whatever it is // by then; an abort before assignment closes it as soon as it exists. let onConnectAbort: (() => void) | undefined if (signal) { onConnectAbort = () => { // Cancelling the creator of a shared reconnect must not close // the transport while other waiters remain: they would keep // the failed result and skip MCP setup on later turns. Only // the last waiter closes it — the creator still cancels, once // the shared connect settles and the attempt check runs. The // creator leaves the count when it cancels, so "no waiter // remains" is an absent entry, not a count of one: after the // creator leaves, one is the live joiner alone. if (hasNoConnectWaiters(generation?.promise)) { transport?.close().catch(() => {}) } } if (signal.aborted) { onConnectAbort() } else { signal.addEventListener('abort', onConnectAbort, { once: true }) } } const stopConnectAbort = () => { if (signal && onConnectAbort) { signal.removeEventListener('abort', onConnectAbort) } } // Leave the stalled-transport closer on the generation holder for // the wrapper to register, keyed by the originating promise. This // runs before the first await on every path, so the wrapper sees // it even on the synchronous stdio path, where the body reaches // the connect before the wrapper has supplied the promise. The // closure reads the transport lazily: it may not exist yet when // the wrapper registers it. The connectSettled guard keeps a // waiter that cancels in the same window from closing a transport // that just connected. if (generation) { generation.closeStalledTransport = () => { if (!connectSettled) { transport?.close().catch(() => {}) } } } // If we have the session ingress JWT, we will connect via the session ingress rather than // to remote MCP's directly. const sessionIngressToken = getSessionIngressAuthToken() if (serverRef.type === 'sse') { // Create an auth provider for this server const authProvider = new ClaudeAuthProvider(name, serverRef) // Get combined headers (static + dynamic) const combinedHeaders = await getMcpServerHeaders(name, serverRef) const allowUnauthorizedRefresh = !new Headers(combinedHeaders).has( 'Authorization', ) // Use the auth provider with SSEClientTransport const transportOptions: SSEClientTransportOptions = { authProvider, // Use fresh timeout per request to avoid stale AbortSignal bug. // Step-up detection wraps innermost so the 403 is seen before the // SDK's handler calls auth() → tokens(). fetch: wrapFetchWithTimeout( wrapFetchWithStepUpDetection(createFetchWithInit(), authProvider, { allowUnauthorizedRefresh, resourceUrl: serverRef.url, providerOwnsAuthorization: allowUnauthorizedRefresh, }), ), requestInit: { headers: { 'User-Agent': getMCPUserAgent(), ...combinedHeaders, }, }, } // IMPORTANT: Always set eventSourceInit with a fetch that does NOT use the // timeout wrapper. The EventSource connection is long-lived (stays open indefinitely // to receive server-sent events), so applying a 60-second timeout would kill it. // The timeout is only meant for individual API requests (POST, auth refresh), not // the persistent SSE stream. const eventSourceFetch = wrapFetchWithStepUpDetection( async (url: string | URL, init?: RequestInit) => { const proxyOptions = getProxyFetchOptions() // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins return fetch(url, { ...init, ...proxyOptions, headers: buildMcpSseEventSourceHeaders(init?.headers), }) }, authProvider, { allowUnauthorizedRefresh, resourceUrl: serverRef.url, providerOwnsAuthorization: allowUnauthorizedRefresh, }, ) transportOptions.eventSourceInit = { fetch: async (url: string | URL, init?: RequestInit) => { return eventSourceFetch(url, { ...init, headers: buildMcpSseRequestHeaders(init?.headers, combinedHeaders), }) }, } transport = new SSEClientTransport( new URL(serverRef.url), transportOptions, ) logMCPDebug(name, `SSE transport initialized, awaiting connection`) } else if (serverRef.type === 'sse-ide') { logMCPDebug(name, `Setting up SSE-IDE transport to ${serverRef.url}`) // IDE servers don't need authentication // TODO: Use the auth token provided in the lockfile const proxyOptions = getProxyFetchOptions() const transportOptions: SSEClientTransportOptions = proxyOptions.dispatcher ? { eventSourceInit: { fetch: async (url: string | URL, init?: RequestInit) => { // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins return fetch(url, { ...init, ...proxyOptions, headers: { 'User-Agent': getMCPUserAgent(), ...init?.headers, }, }) }, }, } : {} transport = new SSEClientTransport( new URL(serverRef.url), Object.keys(transportOptions).length > 0 ? transportOptions : undefined, ) } else if (serverRef.type === 'ws-ide') { const tlsOptions = getWebSocketTLSOptions() const wsHeaders = { 'User-Agent': getMCPUserAgent(), ...(serverRef.authToken && { 'X-Claude-Code-Ide-Authorization': serverRef.authToken, }), } let wsClient: WsClientLike if (typeof Bun !== 'undefined') { // Bun's WebSocket supports headers/proxy/tls options but the DOM typings don't // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins wsClient = new globalThis.WebSocket(serverRef.url, { protocols: ['mcp'], headers: wsHeaders, proxy: getWebSocketProxyUrl(serverRef.url), tls: tlsOptions || undefined, } as unknown as string[]) } else { wsClient = await createNodeWsClient(serverRef.url, { headers: wsHeaders, agent: getWebSocketProxyAgent(serverRef.url), ...(tlsOptions || {}), }) } transport = new WebSocketTransport(wsClient) } else if (serverRef.type === 'ws') { logMCPDebug( name, `Initializing WebSocket transport to ${serverRef.url}`, ) const combinedHeaders = await getMcpServerHeaders(name, serverRef) const tlsOptions = getWebSocketTLSOptions() const wsHeaders = { 'User-Agent': getMCPUserAgent(), ...(sessionIngressToken && { Authorization: `Bearer ${sessionIngressToken}`, }), ...combinedHeaders, } // Redact sensitive headers before logging const wsHeadersForLogging = JSON.parse( JSON.stringify(wsHeaders, jsonRedactor), ) logMCPDebug( name, `WebSocket transport options: ${jsonStringify({ url: serverRef.url, headers: wsHeadersForLogging, hasSessionAuth: !!sessionIngressToken, })}`, ) let wsClient: WsClientLike if (typeof Bun !== 'undefined') { // Bun's WebSocket supports headers/proxy/tls options but the DOM typings don't // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins wsClient = new globalThis.WebSocket(serverRef.url, { protocols: ['mcp'], headers: wsHeaders, proxy: getWebSocketProxyUrl(serverRef.url), tls: tlsOptions || undefined, } as unknown as string[]) } else { wsClient = await createNodeWsClient(serverRef.url, { headers: wsHeaders, agent: getWebSocketProxyAgent(serverRef.url), ...(tlsOptions || {}), }) } transport = new WebSocketTransport(wsClient) } else if (serverRef.type === 'http') { logMCPDebug(name, `Initializing HTTP transport to ${serverRef.url}`) logMCPDebug( name, `Node version: ${process.version}, Platform: ${process.platform}`, ) logMCPDebug( name, `Environment: ${jsonStringify({ NODE_OPTIONS: process.env.NODE_OPTIONS || 'not set', UV_THREADPOOL_SIZE: process.env.UV_THREADPOOL_SIZE || 'default', HTTP_PROXY: process.env.HTTP_PROXY || 'not set', HTTPS_PROXY: process.env.HTTPS_PROXY || 'not set', NO_PROXY: process.env.NO_PROXY || 'not set', })}`, ) // Create an auth provider for this server const authProvider = new ClaudeAuthProvider(name, serverRef) // Get combined headers (static + dynamic) const combinedHeaders = await getMcpServerHeaders(name, serverRef) // Check if this server has stored OAuth tokens. If so, the SDK's // authProvider will set Authorization — don't override with the // session ingress token (SDK merges requestInit AFTER authProvider). // CCR proxy URLs (ccr_shttp_mcp) have no stored OAuth, so they still // get the ingress token. See PR #24454 discussion. const hasOAuthTokens = !!(await authProvider.tokens()) const hasExplicitAuthorization = new Headers(combinedHeaders).has('Authorization') || Boolean(sessionIngressToken && !hasOAuthTokens) const allowUnauthorizedRefresh = !hasExplicitAuthorization // Use the auth provider with StreamableHTTPClientTransport const proxyOptions = getProxyFetchOptions() logMCPDebug( name, `Proxy options: ${proxyOptions.dispatcher ? 'custom dispatcher' : 'default'}`, ) const activeHttpRequests = new Map() const transportOptions: StreamableHTTPClientTransportOptions = { authProvider, // Use fresh timeout per request to avoid stale AbortSignal bug. // Step-up detection wraps innermost so the 403 is seen before the // SDK's handler calls auth() → tokens(). fetch: wrapFetchWithRequestCancellation( wrapFetchWithTimeout( wrapFetchWithStepUpDetection(createFetchWithInit(), authProvider, { allowUnauthorizedRefresh, resourceUrl: serverRef.url, providerOwnsAuthorization: allowUnauthorizedRefresh, }), ), activeHttpRequests, ), requestInit: { ...proxyOptions, headers: { 'User-Agent': getMCPUserAgent(), ...(sessionIngressToken && !hasOAuthTokens && { Authorization: `Bearer ${sessionIngressToken}`, }), ...combinedHeaders, }, }, } // Redact sensitive headers before logging const headersForLogging = transportOptions.requestInit?.headers ? JSON.parse( JSON.stringify( transportOptions.requestInit.headers as Record, jsonRedactor, ), ) : undefined logMCPDebug( name, `HTTP transport options: ${jsonStringify({ url: serverRef.url, headers: headersForLogging, hasAuthProvider: !!authProvider, timeoutMs: MCP_REQUEST_TIMEOUT_MS, })}`, ) transport = new StreamableHTTPClientTransport( new URL(serverRef.url), transportOptions, ) attachMcpRequestCancellationHandler(transport, activeHttpRequests) logMCPDebug(name, `HTTP transport created successfully`) } else if (serverRef.type === 'sdk') { throw new Error('SDK servers should be handled in print.ts') } else if (serverRef.type === 'claudeai-proxy') { logMCPDebug( name, `Initializing claude.ai proxy transport for server ${serverRef.id}`, ) const tokens = getClaudeAIOAuthTokens() if (!tokens) { throw new Error('No claude.ai OAuth token found') } const oauthConfig = getOauthConfig() const proxyUrl = `${oauthConfig.MCP_PROXY_URL}${oauthConfig.MCP_PROXY_PATH.replace('{server_id}', serverRef.id)}` logMCPDebug(name, `Using claude.ai proxy at ${proxyUrl}`) // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins const fetchWithAuth = createClaudeAiProxyFetch(globalThis.fetch) const proxyOptions = getProxyFetchOptions() const activeProxyRequests = new Map() const transportOptions: StreamableHTTPClientTransportOptions = { // Wrap fetchWithAuth with fresh timeout per request fetch: wrapFetchWithRequestCancellation( wrapFetchWithTimeout(fetchWithAuth), activeProxyRequests, ), requestInit: { ...proxyOptions, headers: { 'User-Agent': getMCPUserAgent(), 'X-Mcp-Client-Session-Id': getSessionId(), }, }, } transport = new StreamableHTTPClientTransport( new URL(proxyUrl), transportOptions, ) attachMcpRequestCancellationHandler(transport, activeProxyRequests) logMCPDebug(name, `claude.ai proxy transport created successfully`) } else if ( (serverRef.type === 'stdio' || !serverRef.type) && isClaudeInChromeMCPServer(name) ) { // Run the Chrome MCP server in-process to avoid spawning a ~325 MB subprocess const { createChromeContext } = await import( '../../utils/claudeInChrome/mcpServer.js' ) const { createClaudeForChromeMcpServer } = await import( '@ant/claude-for-chrome-mcp' ) const { createLinkedTransportPair } = await import( './InProcessTransport.js' ) const context = createChromeContext(serverRef.env) inProcessServer = createClaudeForChromeMcpServer(context) const [clientTransport, serverTransport] = createLinkedTransportPair() await inProcessServer.connect(serverTransport) transport = clientTransport logMCPDebug(name, `In-process Chrome MCP server started`) } else if ( feature('CHICAGO_MCP') && (serverRef.type === 'stdio' || !serverRef.type) && isComputerUseMCPServer!(name) ) { // Run the Computer Use MCP server in-process — same rationale as // Chrome above. The package's CallTool handler is a stub; real // dispatch goes through wrapper.tsx's .call() override. const { createComputerUseMcpServerForCli } = await import( '../../utils/computerUse/mcpServer.js' ) const { createLinkedTransportPair } = await import( './InProcessTransport.js' ) inProcessServer = await createComputerUseMcpServerForCli() const [clientTransport, serverTransport] = createLinkedTransportPair() await inProcessServer.connect(serverTransport) transport = clientTransport logMCPDebug(name, `In-process Computer Use MCP server started`) } else if (serverRef.type === 'stdio' || !serverRef.type) { // Split the prefix into separate args so we hand a real array to the // MCP SDK's stdio transport. Joining the server command + its args // into one string and putting that single string inside a one-element // array causes the SDK to shell-invoke the whole blob, letting shell // metacharacters in serverRef.args run arbitrary commands before the // target binary even starts. const { command: finalCommand, args: finalArgs } = buildMcpStdioCommand( serverRef.command, serverRef.args ?? [], process.env.CLAUDE_CODE_SHELL_PREFIX, ) transport = createMcpStdioClientTransport({ command: finalCommand, args: finalArgs, env: { ...subprocessEnv(), ...serverRef.env, } as Record, stderr: 'pipe', // prevents error output from the MCP server from printing to the UI }) } else { throw new Error(`Unsupported server type: ${serverRef.type}`) } // Set up stderr logging for stdio transport before connecting in case there are any stderr // outputs emitted during the connection start (this can be useful for debugging failed connections). // Store handler reference for cleanup to prevent memory leaks let stderrHandler: ((data: Buffer) => void) | undefined let stderrOutput = '' if (serverRef.type === 'stdio' || !serverRef.type) { const stdioTransport = transport as StdioClientTransport if (stdioTransport.stderr) { stderrHandler = (data: Buffer) => { stderrOutput = appendBoundedMcpStderr(stderrOutput, data) } stdioTransport.stderr.on('data', stderrHandler) } } const client = new Client( { // name stays 'claude-code' for compatibility with MCP servers that // gate features on the upstream client identifier. name: 'claude-code', title: 'OpenClaude', version: MACRO.VERSION ?? 'unknown', description: 'OpenClaude — coding-agent CLI for any LLM provider', websiteUrl: PRODUCT_URL, }, { capabilities: { roots: {}, // Empty object declares the capability. Sending {form:{},url:{}} // breaks Java MCP SDK servers (Spring AI) whose Elicitation class // has zero fields and fails on unknown properties. elicitation: {}, // Client task capability (SEP-1686 wire shape): the server may // run tools/call as a durable task and we poll tasks/get. Only // the bare key is declared: list and cancel advertise handlers // for requests a server sends to the client, and none exist. // The requests key is omitted; taskified server-initiated // requests (sampling/elicitation) are not supported here. ...(isMcpTaskBackgroundingDisabled() ? {} : { tasks: {} }), }, }, ) // Add debug logging for client events if available if (serverRef.type === 'http') { logMCPDebug(name, `Client created, setting up request handler`) } client.setRequestHandler(ListRootsRequestSchema, async () => { logMCPDebug(name, `Received ListRoots request from server`) return { roots: [ { uri: `file://${getOriginalCwd()}`, }, ], } }) if (!isMcpTaskBackgroundingDisabled()) { // Eager status pushes for server-initiated tasks. Polling stays the // reliable path; notifications only shorten the latency. client.setNotificationHandler( TaskStatusNotificationSchema, notification => { handleMcpTaskStatusNotification(name, notification.params) }, ) } // Add a timeout to connection attempts to prevent tests from hanging indefinitely logMCPDebug( name, `Starting connection with timeout of ${getConnectionTimeoutMs()}ms`, ) // For HTTP transport, try a basic connectivity test first if (serverRef.type === 'http') { logMCPDebug(name, `Testing basic HTTP connectivity to ${serverRef.url}`) try { const testUrl = new URL(serverRef.url) logMCPDebug( name, `Parsed URL: host=${testUrl.hostname}, port=${testUrl.port || 'default'}, protocol=${testUrl.protocol}`, ) // Log DNS resolution attempt if ( testUrl.hostname === '127.0.0.1' || testUrl.hostname === 'localhost' ) { logMCPDebug(name, `Using loopback address: ${testUrl.hostname}`) } } catch (urlError) { logMCPDebug(name, `Failed to parse URL: ${urlError}`) } } const connectPromise = client.connect(transport) // The closer for this connect is registered by the wrapper (see // connectToServer below), keyed by this connect's own promise: the // wrapper supplies the promise only after this body returns, so // reading generation.promise here yields undefined on the // synchronous stdio path and no closer would be registered. // An abort that landed before the transport existed still cancels // the connect: the listener above could not close what did not exist. // Shared like the listener: another waiter keeps the transport. The // creator leaves the count when it cancels, so a count of one here // is a live joiner — only an absent entry means nobody remains. if ( signal?.aborted && hasNoConnectWaiters(generation?.promise) ) { transport.close().catch(() => {}) } const timeoutPromise = new Promise((_, reject) => { const timeoutId = setTimeout(() => { const elapsed = Date.now() - connectStartTime logMCPDebug( name, `Connection timeout triggered after ${elapsed}ms (limit: ${getConnectionTimeoutMs()}ms)`, ) if (inProcessServer) { inProcessServer.close().catch(() => { }) } transport.close().catch(() => { }) reject( new TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( `MCP server "${name}" connection timed out after ${getConnectionTimeoutMs()}ms`, 'MCP connection timeout', ), ) }, getConnectionTimeoutMs()) // Clean up timeout if connect resolves or rejects connectPromise.then( () => { connectSettled = true clearTimeout(timeoutId) stopConnectAbort() }, _error => { connectSettled = true clearTimeout(timeoutId) stopConnectAbort() }, ) }) try { await Promise.race([connectPromise, timeoutPromise]) if (stderrOutput) { logMcpServerStderr(name, stderrOutput, true) stderrOutput = '' // Release accumulated string to prevent memory growth } const elapsed = Date.now() - connectStartTime logMCPDebug( name, `Successfully connected (transport: ${serverRef.type || 'stdio'}) in ${elapsed}ms`, ) } catch (error) { const elapsed = Date.now() - connectStartTime // SSE-specific error logging if (serverRef.type === 'sse' && error instanceof Error) { logMCPDebug( name, `SSE Connection failed after ${elapsed}ms: ${jsonStringify({ url: serverRef.url, error: error.message, errorType: error.constructor.name, stack: error.stack, })}`, ) logMCPError(name, error) if (error instanceof UnauthorizedError) { return handleRemoteAuthFailure(name, serverRef, 'sse') } } else if (serverRef.type === 'http' && error instanceof Error) { const errorObj = error as Error & { cause?: unknown code?: string errno?: string | number syscall?: string } logMCPDebug( name, `HTTP Connection failed after ${elapsed}ms: ${error.message} (code: ${errorObj.code || 'none'}, errno: ${errorObj.errno || 'none'})`, ) logMCPError(name, error) if (error instanceof UnauthorizedError) { return handleRemoteAuthFailure(name, serverRef, 'http') } } else if ( serverRef.type === 'claudeai-proxy' && error instanceof Error ) { logMCPDebug( name, `claude.ai proxy connection failed after ${elapsed}ms: ${error.message}`, ) logMCPError(name, error) // StreamableHTTPError has a `code` property with the HTTP status const errorCode = (error as Error & { code?: number }).code if (errorCode === 401) { return handleRemoteAuthFailure(name, serverRef, 'claudeai-proxy') } } else if ( serverRef.type === 'sse-ide' || serverRef.type === 'ws-ide' ) { logEvent('tengu_mcp_ide_server_connection_failed', { connectionDurationMs: elapsed, }) } if (inProcessServer) { await cleanupFailedConnection(transport, inProcessServer) } else { await cleanupFailedConnection(transport) } if (stderrOutput) { logMcpServerStderr(name, stderrOutput, false) } throw error } const capabilities = client.getServerCapabilities() const serverVersion = client.getServerVersion() const rawInstructions = client.getInstructions() let instructions = rawInstructions if ( rawInstructions && rawInstructions.length > MAX_MCP_DESCRIPTION_LENGTH ) { instructions = rawInstructions.slice(0, MAX_MCP_DESCRIPTION_LENGTH) + '… [truncated]' logMCPDebug( name, `Server instructions truncated from ${rawInstructions.length} to ${MAX_MCP_DESCRIPTION_LENGTH} chars`, ) } // Log successful connection details logMCPDebug( name, `Connection established with capabilities: ${jsonStringify({ hasTools: !!capabilities?.tools, hasPrompts: !!capabilities?.prompts, hasResources: !!capabilities?.resources, hasResourceSubscribe: !!capabilities?.resources?.subscribe, serverVersion: serverVersion || 'unknown', })}`, ) logForDebugging( `[MCP] Server "${name}" connected with subscribe=${!!capabilities?.resources?.subscribe}`, ) // Register default elicitation handler that returns cancel during the // window before registerElicitationHandler overwrites it in // onConnectionAttempt (useManageMCPConnections). client.setRequestHandler(ElicitRequestSchema, async request => { logMCPDebug( name, `Elicitation request received during initialization: ${jsonStringify(request)}`, ) return { action: 'cancel' as const } }) if (serverRef.type === 'sse-ide' || serverRef.type === 'ws-ide') { const ideConnectionDurationMs = Date.now() - connectStartTime logEvent('tengu_mcp_ide_server_connection_succeeded', { connectionDurationMs: ideConnectionDurationMs, serverVersion: serverVersion as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, }) try { void maybeNotifyIDEConnected(client) } catch (error) { logMCPError( name, `Failed to send ide_connected notification: ${error}`, ) } } // Enhanced connection drop detection and logging for all transport types const connectionStartTime = Date.now() let hasErrorOccurred = false // Store original handlers const originalOnerror = client.onerror const originalOnclose = client.onclose // The SDK's transport calls onerror on connection failures but doesn't call onclose, // which CC uses to trigger reconnection. We bridge this gap by tracking consecutive // terminal errors and manually closing after MAX_ERRORS_BEFORE_RECONNECT failures. let consecutiveConnectionErrors = 0 const MAX_ERRORS_BEFORE_RECONNECT = 3 // Guard against re-entry: close() aborts in-flight streams which may fire // onerror again before the close chain completes. let hasTriggeredClose = false // client.close() → transport.close() → transport.onclose → SDK's _onclose(): // rejects all pending request handlers (so hung callTool() promises fail with // McpError -32000 "Connection closed") and then invokes our client.onclose // handler below (which clears the memo cache so the next call reconnects). // Calling client.onclose?.() directly would only clear the cache — pending // tool calls would stay hung. const closeTransportAndRejectPending = (reason: string) => { if (hasTriggeredClose) return hasTriggeredClose = true logMCPDebug(name, `Closing transport (${reason})`) void client.close().catch(e => { logMCPDebug(name, `Error during close: ${errorMessage(e)}`) }) } const isTerminalConnectionError = (msg: string): boolean => { return ( msg.includes('ECONNRESET') || msg.includes('ETIMEDOUT') || msg.includes('EPIPE') || msg.includes('EHOSTUNREACH') || msg.includes('ECONNREFUSED') || msg.includes('Body Timeout Error') || msg.includes('terminated') || // SDK SSE reconnection intermediate errors — may be wrapped around the // actual network error, so the substrings above won't match msg.includes('SSE stream disconnected') || msg.includes('Failed to reconnect SSE stream') ) } // Enhanced error handler with detailed logging client.onerror = (error: Error) => { const uptime = Date.now() - connectionStartTime hasErrorOccurred = true const transportType = serverRef.type || 'stdio' // Log the connection drop with context logMCPDebug( name, `${transportType.toUpperCase()} connection dropped after ${Math.floor(uptime / 1000)}s uptime`, ) // Log specific error details for debugging if (error.message) { if (error.message.includes('ECONNRESET')) { logMCPDebug( name, `Connection reset - server may have crashed or restarted`, ) } else if (error.message.includes('ETIMEDOUT')) { logMCPDebug( name, `Connection timeout - network issue or server unresponsive`, ) } else if (error.message.includes('ECONNREFUSED')) { logMCPDebug(name, `Connection refused - server may be down`) } else if (error.message.includes('EPIPE')) { logMCPDebug( name, `Broken pipe - server closed connection unexpectedly`, ) } else if (error.message.includes('EHOSTUNREACH')) { logMCPDebug(name, `Host unreachable - network connectivity issue`) } else if (error.message.includes('ESRCH')) { logMCPDebug( name, `Process not found - stdio server process terminated`, ) } else if (error.message.includes('spawn')) { logMCPDebug( name, `Failed to spawn process - check command and permissions`, ) } else { logMCPDebug(name, `Connection error: ${error.message}`) } } // For HTTP transports, detect session expiry (404 + JSON-RPC -32001) // and close the transport so pending tool calls reject and the next // call reconnects with a fresh session ID. if ( (transportType === 'http' || transportType === 'claudeai-proxy') && isMcpSessionExpiredError(error) ) { logMCPDebug( name, `MCP session expired (server returned 404 with session-not-found), triggering reconnection`, ) closeTransportAndRejectPending('session expired') if (originalOnerror) { originalOnerror(error) } return } // For remote transports (SSE/HTTP), track terminal connection errors // and trigger reconnection via close if we see repeated failures. if ( transportType === 'sse' || transportType === 'http' || transportType === 'claudeai-proxy' ) { // The SDK's StreamableHTTP transport fires this after exhausting its // own SSE reconnect attempts (default maxRetries: 2) — but it never // calls onclose, so pending callTool() promises hang indefinitely. // This is the definitive "transport gave up" signal. if (error.message.includes('Maximum reconnection attempts')) { closeTransportAndRejectPending('SSE reconnection exhausted') if (originalOnerror) { originalOnerror(error) } return } if (isTerminalConnectionError(error.message)) { consecutiveConnectionErrors++ logMCPDebug( name, `Terminal connection error ${consecutiveConnectionErrors}/${MAX_ERRORS_BEFORE_RECONNECT}`, ) if (consecutiveConnectionErrors >= MAX_ERRORS_BEFORE_RECONNECT) { consecutiveConnectionErrors = 0 closeTransportAndRejectPending('max consecutive terminal errors') } } else { // Non-terminal error (e.g., transient issue), reset counter consecutiveConnectionErrors = 0 } } // Call original handler if (originalOnerror) { originalOnerror(error) } } // Enhanced close handler with connection drop context client.onclose = () => { const uptime = Date.now() - connectionStartTime const transportType = serverRef.type ?? 'unknown' logMCPDebug( name, `${transportType.toUpperCase()} connection closed after ${Math.floor(uptime / 1000)}s (${hasErrorOccurred ? 'with errors' : 'cleanly'})`, ) // Clear the memoization cache so next operation reconnects const key = getServerCacheKey(name, serverRef) // Evict the connect entry only when this generation still owns // it. A newer generation for the same key replaces it while this // one is being released, and an unconditional delete would drop // the newer's entry with it. A generation the wrapper never // supplied a promise for (the synchronous stdio path) owns no // entry by construction, so it still clears. The discovery // caches go under the same condition: a retired transport's close // must not drop the replacement's freshly fetched tools — the // clear is keyed by connection, not by display name, so a // same-named peer's discovery survives this close either way // (CodeRabbit #2493 review 5957362782). const current = connectToServer.cache.get(key) as | Promise | undefined if (generation?.promise === undefined || current === generation.promise) { connectToServer.cache.delete(key) // Also clear fetch caches (keyed by connection). Reconnection // creates a new connection object; without clearing, the next // fetch would return stale tools/resources from the old connection. // This covers the same caches upstream clears by name (tools, // resources, commands, MCP skills), scoped to this connection // so a same-named peer's discovery survives the close. clearFetchCaches(name, serverRef) // Fail this connection's server tasks under the same guard // (upstream #2541): the fail call is keyed by server name, so // a retired generation's close must not fail the replacement // connection's live tasks. failMcpServerTasksForServer( name, `MCP server "${name}" disconnected before the task completed`, ) } logMCPDebug(name, `Cleared connection cache for reconnection`) if (originalOnclose) { originalOnclose() } } const cleanup = async () => { // In-process servers (e.g. Chrome MCP) don't have child processes or stderr if (inProcessServer) { try { await inProcessServer.close() } catch (error) { logMCPDebug(name, `Error closing in-process server: ${error}`) } try { await client.close() } catch (error) { logMCPDebug(name, `Error closing client: ${error}`) } return } // Remove stderr event listener to prevent memory leaks if (stderrHandler && (serverRef.type === 'stdio' || !serverRef.type)) { const stdioTransport = transport as StdioClientTransport stdioTransport.stderr?.off('data', stderrHandler) } // For stdio transports, explicitly terminate the child process with proper signals // NOTE: StdioClientTransport.close() only sends an abort signal, but many MCP servers // (especially Docker containers) need explicit SIGINT/SIGTERM signals to trigger graceful shutdown if (serverRef.type === 'stdio') { try { const stdioTransport = transport as StdioClientTransport const childPid = stdioTransport.pid if (childPid) { logMCPDebug(name, 'Sending SIGINT to MCP server process') // First try SIGINT (like Ctrl+C) try { process.kill(childPid, 'SIGINT') } catch (error) { logMCPDebug(name, `Error sending SIGINT: ${error}`) return } // Wait for graceful shutdown with rapid escalation (total 500ms to keep CLI responsive) await new Promise(async resolve => { let resolved = false // Set up a timer to check if process still exists const checkInterval = setInterval(() => { try { // process.kill(pid, 0) checks if process exists without killing it process.kill(childPid, 0) } catch { // Process no longer exists if (!resolved) { resolved = true clearInterval(checkInterval) clearTimeout(failsafeTimeout) logMCPDebug(name, 'MCP server process exited cleanly') resolve() } } }, 50) // Absolute failsafe: clear interval after 600ms no matter what const failsafeTimeout = setTimeout(() => { if (!resolved) { resolved = true clearInterval(checkInterval) logMCPDebug( name, 'Cleanup timeout reached, stopping process monitoring', ) resolve() } }, 600) try { // Wait 100ms for SIGINT to work (usually much faster) await sleep(100) if (!resolved) { // Check if process still exists try { process.kill(childPid, 0) // Process still exists, SIGINT failed, try SIGTERM logMCPDebug( name, 'SIGINT failed, sending SIGTERM to MCP server process', ) try { process.kill(childPid, 'SIGTERM') } catch (termError) { logMCPDebug(name, `Error sending SIGTERM: ${termError}`) resolved = true clearInterval(checkInterval) clearTimeout(failsafeTimeout) resolve() return } } catch { // Process already exited resolved = true clearInterval(checkInterval) clearTimeout(failsafeTimeout) resolve() return } // Wait 400ms for SIGTERM to work (slower than SIGINT, often used for cleanup) await sleep(400) if (!resolved) { // Check if process still exists try { process.kill(childPid, 0) // Process still exists, SIGTERM failed, force kill with SIGKILL logMCPDebug( name, 'SIGTERM failed, sending SIGKILL to MCP server process', ) try { process.kill(childPid, 'SIGKILL') } catch (killError) { logMCPDebug( name, `Error sending SIGKILL: ${killError}`, ) } } catch { // Process already exited resolved = true clearInterval(checkInterval) clearTimeout(failsafeTimeout) resolve() } } } // Final timeout - always resolve after 500ms max (total cleanup time) if (!resolved) { resolved = true clearInterval(checkInterval) clearTimeout(failsafeTimeout) resolve() } } catch { // Handle any errors in the escalation sequence if (!resolved) { resolved = true clearInterval(checkInterval) clearTimeout(failsafeTimeout) resolve() } } }) } } catch (processError) { logMCPDebug(name, `Error terminating process: ${processError}`) } } // Close the client connection (which also closes the transport) try { await client.close() } catch (error) { logMCPDebug(name, `Error closing client: ${error}`) } } // Register cleanup for all transport types - even network transports might need cleanup // This ensures all MCP servers get properly terminated, not just stdio ones const cleanupUnregister = registerCleanup(cleanup) // Create the wrapped cleanup that includes unregistering const wrappedCleanup = async () => { cleanupUnregister?.() await cleanup() } const connectionDurationMs = Date.now() - connectStartTime logEvent('tengu_mcp_server_connection_succeeded', { connectionDurationMs, transportType: (serverRef.type ?? 'stdio') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, totalServers: serverStats?.totalServers, stdioCount: serverStats?.stdioCount, sseCount: serverStats?.sseCount, httpCount: serverStats?.httpCount, sseIdeCount: serverStats?.sseIdeCount, wsIdeCount: serverStats?.wsIdeCount, ...mcpBaseUrlAnalytics(serverRef), }) return { name, client, type: 'connected' as const, capabilities: capabilities ?? {}, serverInfo: serverVersion, instructions, config: serverRef, cleanup: wrappedCleanup, } } catch (error) { const connectionDurationMs = Date.now() - connectStartTime logEvent('tengu_mcp_server_connection_failed', { connectionDurationMs, totalServers: serverStats?.totalServers || 1, stdioCount: serverStats?.stdioCount || (serverRef.type === 'stdio' ? 1 : 0), sseCount: serverStats?.sseCount || (serverRef.type === 'sse' ? 1 : 0), httpCount: serverStats?.httpCount || (serverRef.type === 'http' ? 1 : 0), sseIdeCount: serverStats?.sseIdeCount || (serverRef.type === 'sse-ide' ? 1 : 0), wsIdeCount: serverStats?.wsIdeCount || (serverRef.type === 'ws-ide' ? 1 : 0), transportType: (serverRef.type ?? 'stdio') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, ...mcpBaseUrlAnalytics(serverRef), }) logMCPDebug( name, `Connection failed after ${connectionDurationMs}ms: ${errorMessage(error)}`, ) logMCPError(name, `Connection failed: ${errorMessage(error)}`) if (inProcessServer) { inProcessServer.close().catch(() => { }) } return { name, type: 'failed' as const, config: serverRef, error: errorMessage(error), } } }, getServerCacheKey, ) /** * Attempts to connect to a single MCP server, sharing one memoized * connect per server key. Counts the callers awaiting each connect so * the creator's abort can tell a solo connect from a shared one, and * releases a caller's waiter when its signal aborts — a session that * closed while joining a reconnect must not keep the creator's abort * from closing the stalled transport. When the last waiter cancels, the * transport closes through the closer the connect registered, so the * connect rejects instead of holding its callers until the timeout. The * memoize cache is shared with the inner function, so existing * `connectToServer.cache.get/delete` uses keep working. A caller that * reuses a connect it did not start adopts its client: a later * cancellation must not close a client another session holds. */ export const connectToServer = Object.assign( ( name: string, serverRef: ScopedMcpServerConfig, serverStats?: { totalServers: number stdioCount: number sseCount: number httpCount: number sseIdeCount: number wsIdeCount: number }, signal?: AbortSignal, // A setup caller passes its session so its adoption is its own claim // (see the permanentAdoptionClaim comment). Callers that omit it keep // the shared marker, as before. owner?: object, ): Promise => { const key = getServerCacheKey(name, serverRef) // A cache hit reuses a connect another caller started; that caller // adopts the client it resolves to — unless it was cancelled before // or during the wait, in which case its adoption would keep a // transport alive the creator's abort should close. const hadCached = connectToServerMemoized.cache.get(key) !== undefined const generation: { promise?: Promise closeStalledTransport?: () => void } = {} const promise = connectToServerMemoized(name, serverRef, serverStats, signal, generation) generation.promise = promise // Remember what this connect settles to, synchronously readable // afterwards: a later join of the settled connect and a later release // both need the value without yielding. Attached here, before the // promise reaches any caller, so it runs before any await continuation // that could release the client. void promise.then( client => { if (client.type === 'connected') settledConnectClients.set(promise, client) }, () => {}, ) // Register this connect's stalled-transport closer, keyed by the // originating promise. The body leaves it on the generation holder: // on the synchronous stdio path it runs before this promise exists // and so cannot register it itself. A cache hit reuses the creator's // registration — this generation holds none. A waiter that is not // the creator cannot close a stalled transport through the creator's // abort listener, so the wrapper invokes the closer when the last // waiter cancels, and the connect rejects instead of holding its // callers until the connection timeout. The closer is inert once // the connect settles; drop it then. if (generation.closeStalledTransport) { connectTransportClosers.set(promise, generation.closeStalledTransport) const dropCloser = () => { connectTransportClosers.delete(promise) } void promise.then(dropCloser, dropCloser) } // One claim per caller, shared by the synchronous add and the `.then` // below: a second adopter never un-adopts the first. `adoptedClient` // is the client this call claimed, if any; `adoptionReceived` turns // true once the caller's continuation has resumed with it — the marker // runs two ticks out, after that continuation — so an abort before // then means the caller never received the client. const adoptionClaim = {} let adoptedClient: MCPServerConnection | undefined let adoptionReceived = false if (hadCached) { // A settled connect adopts synchronously: the `.then` below records // adoption a microtask later, and a release deciding ownership in // that gap would clean up a client this caller is about to receive. // The map is filled when the connect settles, before any caller can // hold the client, so a hit after settle always finds it. The `.then` // stays for the pending case, where the client is not known yet. const settled = settledConnectClients.get(promise) if (settled?.type === 'connected' && !signal?.aborted) { adoptMcpClient(settled, adoptionClaim) adoptedClient = settled } void promise.then( client => { if (client.type === 'connected' && !signal?.aborted) { adoptMcpClient(client, adoptionClaim) adoptedClient = client } }, () => {}, ) void promise.then( () => Promise.resolve(), () => {}, ).then( () => { adoptionReceived = true // The caller holds the client now: consolidate this call's // provisional claim into the single permanent marker, so // repeated joins — one per tool call through // ensureConnectedClient — do not retain one claim object // each for the client's lifetime (CodeRabbit #2493 review // 5955577457). A join that passed an owner consolidates into // the owner instead, so one claim object per adopting session // and the abandoning session's setup release can withdraw // only its own claim. A later abort cannot withdraw the // claim, so the listener can go. if (adoptedClient !== undefined) { const client = adoptedClient withdrawMcpClientAdoption(client, adoptionClaim) adoptMcpClient(client, owner ?? permanentAdoptionClaim) } if (signal && releaseOnAbort) signal.removeEventListener('abort', releaseOnAbort) }, () => {}, ) } const entry = connectWaiters.get(promise) if (entry) { entry.count++ } else { connectWaiters.set(promise, { count: 1 }) } let released = false let releaseOnAbort: (() => void) | undefined // Withdraws this call's adoption claim when the caller aborts before // receiving the client. Runs on abort even after the settle path // already did the waiter bookkeeping — that bookkeeping is guarded // by `released` below, this is not, and the abort listener stays // attached until receipt for exactly this reason. A release the claim // had blocked is re-run here — withdrawal alone leaves nobody to run // it — and the re-run re-checks adoption, so a second live adopter // still keeps the client open. const withdrawIfUnreceived = () => { if (adoptedClient === undefined || adoptionReceived) return const client = adoptedClient adoptedClient = undefined if (signal && releaseOnAbort) signal.removeEventListener('abort', releaseOnAbort) if ( withdrawMcpClientAdoption(client, adoptionClaim) && blockedUnownedReleases.has(client) ) { blockedUnownedReleases.delete(client) void releaseUnownedMcpClient(name, serverRef, client) } } const release = (onAbort: boolean) => { if (released) return released = true if (signal && releaseOnAbort) { // Keep the abort listener while this call's adoption claim is // live and unreceived: the settle path already did the waiter // bookkeeping, but an abort before receipt must still withdraw // the claim. if (adoptedClient === undefined || adoptionReceived) { signal.removeEventListener('abort', releaseOnAbort) } } const current = connectWaiters.get(promise) if (current) { if (current.count <= 1) { connectWaiters.delete(promise) // Only an abort leaves the transport stalled: on settle the // client is live and its callers hold it. if (onAbort) { connectTransportClosers.get(promise)?.() connectTransportClosers.delete(promise) } } else { current.count-- } } } releaseOnAbort = () => { withdrawIfUnreceived() release(true) } void promise.then( () => release(false), () => release(false), ) if (signal) { // A caller whose signal is already aborted never waits: it leaves // at once instead of holding the creator's abort off. if (signal.aborted) releaseOnAbort() else signal.addEventListener('abort', releaseOnAbort, { once: true }) } return promise }, { cache: connectToServerMemoized.cache }, ) /** * Drops the per-connection discovery caches so a reconnect fetches fresh * tools/resources/commands instead of stale ones. Keyed by connection, * not by display name, so clearing one endpoint never drops another * same-named connection's discovery. Entries are scoped by transport * generation, so the clear drops every generation for this connection: * the `#gen` suffix keeps one server's generations from matching another * server whose name extends it, since the full config JSON is part of * the prefix. */ function clearFetchCaches(name: string, serverRef: ScopedMcpServerConfig): void { const prefix = `${getServerCacheKey(name, serverRef)}#` const caches = [ fetchToolsForClient.cache, fetchResourcesForClient.cache, fetchCommandsForClient.cache, ...(feature('MCP_SKILLS') ? [fetchMcpSkillsForClient!.cache] : []), ] for (const cache of caches) { for (const key of cache.keys()) { if (key.startsWith(prefix)) cache.delete(key) } } } /** * Clears the memoize cache for a specific server * @param name Server name * @param serverRef Server configuration * @param signal Aborts the wait for a pending connect: a caller that is * cancelled while another connect is in flight does not wait it out. * Only the reconnect path passes one. * @param options.keepAdoptedClient When true, a client another caller * adopted from the shared connect is detached, not closed: closing it * would fail that caller's in-flight calls. Only the reconnect path * passes this — a caller replacing the connection, not ending it. * Other callers (disable, session expiry) close the client outright. * @param options.expectedClient When set, only the client this caller * actually failed or saw close is cleared: if the cache already holds a * different generation — a reauthentication swapped in a replacement * while the old transport's tool call was still in flight — the entry * is left intact for the retry to use, and neither the replacement nor * its discovery caches are touched (CodeRabbit #2493 review 5961865068). */ export async function clearServerCache( name: string, serverRef: ScopedMcpServerConfig, signal?: AbortSignal, options?: { keepAdoptedClient?: boolean; expectedClient?: MCPServerConnection }, ): Promise { const key = getServerCacheKey(name, serverRef) // A cached connect is the only thing to clean up. Calling // connectToServer here used to dial a fresh connection just to clear // it, so clearing an idle server opened one. const cached = connectToServer.cache.get(key) as | Promise | undefined if (cached === undefined) { clearFetchCaches(name, serverRef) return } if (options?.expectedClient !== undefined) { // Decide which generation the entry holds before touching it: one // microtask tick tells whether it already settled, and to what. A // pending entry is a newer connect in flight — the expected client // is not current, and awaiting it here would wait out that connect // only to clear the wrong generation. A settled entry holding a // different client is the replacement: leave it, and the retry uses // it. Only an entry settled to the expected client is cleared. const expected = options.expectedClient let settledValue: MCPServerConnection | undefined let isSettled = false void cached.then( value => { isSettled = true settledValue = value }, () => {}, ) await Promise.resolve() if (!isSettled || settledValue !== expected) return } try { const wrappedClient = await raceAbort(cached, signal) if (wrappedClient.type === 'connected') { if ( options?.keepAdoptedClient && (isMcpClientAdopted(wrappedClient) || hasMcpClientSetupReservation(wrappedClient) || isMcpClientInstalled(wrappedClient)) ) { // Another caller adopted this client from the shared connect, // or is still setting it up under a reservation: detach the // cache entry below without closing its transport, so the // reconnect dials fresh while the adopter's in-flight calls // finish on the client it holds. The declined release is // recorded, so the withdrawing call re-runs it when the last // claim goes; a received adoption stays until its owning // session closes the client it installed (Copilot #2493 review // 5955514041). blockedUnownedReleases.add(wrappedClient) } else { await wrappedClient.cleanup() } } } catch { // A cancelled wait is not a failed connect: the caller is gone, so // the clear is abandoned rather than reported as a connect failure. // Any other error means the connect itself failed, which the old // code also ignored — there is nothing to clean up either way. if (signal?.aborted) { throw new AuthenticationCancelledError() } } // Clear from cache (both connection and fetch caches so reconnect // fetches fresh tools/resources/commands instead of stale ones) — // but only when this generation still owns the entry. A newer // connect can replace the entry while cleanup runs: the close // callback evicts the old one, and a concurrent connect stores its // replacement in that gap. An unconditional delete would drop the // replacement, leaving it connected with no cache entry, so a later // clear never releases it — and its discovery caches with it // (CodeRabbit #2493 review 5956557301). const current = connectToServer.cache.get(key) if (current === undefined || current === cached) { connectToServer.cache.delete(key) clearFetchCaches(name, serverRef) } } /** * Ensures a valid connected client for an MCP server. * For most server types, uses the memoization cache if available, or reconnects * if the cache was cleared (e.g., after onclose). This ensures tool/resource * calls always use a valid connection. * * SDK MCP servers run in-process and are handled separately via setupSdkMcpClients, * so they are returned as-is without going through connectToServer. * * @param client The connected MCP server client * @returns Connected MCP server client (same or reconnected) * @throws Error if server cannot be connected */ export async function ensureConnectedClient( client: ConnectedMCPServer, ): Promise { // SDK MCP servers run in-process and are handled separately via setupSdkMcpClients if (client.config.type === 'sdk') { return client } const connectedClient = await connectToServer(client.name, client.config) if (connectedClient.type !== 'connected') { throw new TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( `MCP server "${client.name}" is not connected`, 'MCP server not connected', ) } return connectedClient } /** * Compares two MCP server configurations to determine if they are equivalent. * Used to detect when a server needs to be reconnected due to config changes. */ export function areMcpConfigsEqual( a: ScopedMcpServerConfig, b: ScopedMcpServerConfig, ): boolean { // Quick type check first if (a.type !== b.type) return false // Compare by serializing - this handles all config variations // We exclude 'scope' from comparison since it's metadata, not connection config const { scope: _scopeA, ...configA } = a const { scope: _scopeB, ...configB } = b return jsonStringify(configA) === jsonStringify(configB) } // Max cache size for fetch* caches. Keyed by server name (stable across // reconnects), bounded to prevent unbounded growth with many MCP servers. const MCP_FETCH_CACHE_SIZE = 20 export const MCP_TOOLS_LIST_RETRY_BUDGET_MS = 3_000 /** * Encode MCP tool input for the auto-mode security classifier. * Exported so the auto-mode eval scripts can mirror production encoding * for `mcp__*` tool stubs without duplicating this logic. */ export function mcpToolInputToAutoClassifierInput( input: Record, toolName: string, ): string { const keys = Object.keys(input) return keys.length > 0 ? keys.map(k => `${k}=${String(input[k])}`).join(' ') : toolName } export const fetchToolsForClient = memoizeWithLRU( async ( client: MCPServerConnection, options?: { signal?: AbortSignal }, ): Promise => { if (client.type !== 'connected') return [] try { if (!client.capabilities?.tools) { return [] } const retryDeadline = performance.now() + MCP_TOOLS_LIST_RETRY_BUDGET_MS const tools = await paginateMcpList({ method: 'tools/list', resultSchema: ListToolsResultSchema, // Preserve the existing three-attempt 1s/2s policy for each page while // one traversal-wide deadline has retry budget remaining. A page-two // retry must not replay the successful first page. requestPage: async (request, resultSchema) => { let result: ListToolsResult | undefined let lastError: unknown for (let attempt = 0; attempt < 3; attempt++) { try { result = (await client.client.request( request, resultSchema, { signal: options?.signal }, )) as ListToolsResult break } catch (err) { lastError = err // A cancelled request is not a failure to retry: the // attempt is over, and the next request would abort again // at once after waiting out the backoff. if (options?.signal?.aborted || isAbortError(err)) { break } if (attempt < 2) { const remainingRetryBudget = retryDeadline - performance.now() if (remainingRetryBudget <= 0) { break } logMCPDebug( client.name, `tools/list failed (attempt ${attempt + 1}/3): ${errorMessage(err)}. Retrying...`, ) await sleep( Math.min(1000 * (attempt + 1), remainingRetryBudget), options?.signal, ) // A cancelled backoff must not issue another request: the // attempt is over, and a request with an aborted signal // would fail at once after waiting out the timer. if (options?.signal?.aborted) { break } // A timer can wake after its scheduled deadline when the event // loop is busy. Do not turn that overdue wake-up into another // request; a wake exactly at the deadline preserves the legacy // third attempt after the full 1s/2s backoff. if (performance.now() > retryDeadline) { break } } } } if (!result) { throw lastError ?? new Error('tools/list failed after 3 attempts') } return result }, getItems: result => result.tools, getNextCursor: result => result.nextCursor, }) // Sanitize tool data from MCP server after the complete list succeeds. const toolsToProcess = recursivelySanitizeUnicode(tools) // execution.taskSupport decides which tools/call requests get task // augmentation; the SDK's own cache is private, so keep ours. recordMcpToolTaskSupport(client, toolsToProcess) // Check if we should skip the mcp__ prefix for SDK MCP servers const skipPrefix = client.config.type === 'sdk' && isEnvTruthy(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX) // Convert MCP tools to our Tool format return toolsToProcess .map((tool): Tool => { const fullyQualifiedName = buildMcpToolName(client.name, tool.name) return { ...MCPTool, // In skip-prefix mode, use the original name for model invocation so MCP tools // can override builtins by name. mcpInfo is used for permission checking. name: skipPrefix ? tool.name : fullyQualifiedName, mcpInfo: { serverName: client.name, toolName: tool.name }, isMcp: true, // Collapse whitespace: _meta is open to external MCP servers, and // a newline here would inject orphan lines into the deferred-tool // list (formatDeferredToolLine joins on '\n'). searchHint: typeof tool._meta?.['anthropic/searchHint'] === 'string' ? tool._meta['anthropic/searchHint'] .replace(/\s+/g, ' ') .trim() || undefined : undefined, alwaysLoad: tool._meta?.['anthropic/alwaysLoad'] === true, async description() { return tool.description ?? '' }, async prompt() { const desc = tool.description ?? '' return desc.length > MAX_MCP_DESCRIPTION_LENGTH ? desc.slice(0, MAX_MCP_DESCRIPTION_LENGTH) + '… [truncated]' : desc }, isConcurrencySafe() { return tool.annotations?.readOnlyHint ?? false }, isReadOnly() { return tool.annotations?.readOnlyHint ?? false }, toAutoClassifierInput(input) { return mcpToolInputToAutoClassifierInput(input, tool.name) }, isDestructive() { return tool.annotations?.destructiveHint ?? false }, isOpenWorld() { return tool.annotations?.openWorldHint ?? false }, isSearchOrReadCommand() { return classifyMcpToolForCollapse(client.name, tool.name) }, inputJSONSchema: tool.inputSchema as Tool['inputJSONSchema'], async checkPermissions() { return { behavior: 'passthrough' as const, message: 'MCPTool requires permission.', suggestions: [ { type: 'addRules' as const, rules: [ { toolName: fullyQualifiedName, ruleContent: undefined, }, ], behavior: 'allow' as const, destination: 'localSettings' as const, }, ], } }, async call( args: Record, context, _canUseTool, parentMessage, onProgress?: ToolCallProgress, ) { const toolUseId = extractToolUseId(parentMessage) const meta = toolUseId ? { 'claudecode/toolUseId': toolUseId } : {} // Emit progress when tool starts if (onProgress && toolUseId) { try { onProgress({ toolUseID: toolUseId, data: { type: 'mcp_progress', status: 'started', serverName: client.name, toolName: tool.name, }, }) } catch (error) { // A throwing progress consumer must not prevent the MCP // request from starting. logMCPError(client.name, error) } } const startTime = Date.now() // Cover connection setup, retries, and elicitation waits, not only // the individual protocol request inside callMCPTool. let latestServerProgress: | { progress: number total?: number progressMessage?: string } | undefined let activityInterval = onProgress && toolUseId ? setInterval(() => { try { onProgress({ toolUseID: toolUseId, data: { type: 'mcp_progress', status: 'progress', serverName: client.name, toolName: tool.name, ...latestServerProgress, elapsedTimeMs: Date.now() - startTime, }, }) } catch (error) { // Timer callbacks escape the surrounding try/finally; // an uncaught throw here would crash the process. logMCPError(client.name, error) } }, MCP_TOOL_ACTIVITY_INTERVAL_MS) : undefined const stopActivityHeartbeat = () => { if (activityInterval !== undefined) { clearInterval(activityInterval) activityInterval = undefined } } // A taskified call returns a handle while the work continues on // the server, so it must not report 'completed' below. let taskified = false const MAX_SESSION_RETRIES = 1 for (let attempt = 0; ; attempt++) { try { const connectedClient = await ensureConnectedClient(client) const mcpResult = await callMCPToolWithUrlElicitationRetry({ client: connectedClient, clientConnection: client, tool: tool.name, args, meta, signal: context.abortController.signal, setAppState: context.setAppState, // Async subagents get a no-op setAppState; task // registration must still reach the root store. setTaskAppState: context.setAppStateForTasks ?? context.setAppState, // The scheduler's id names this tool use; the first // block of parentMessage can belong to a sibling call. toolUseId: context.toolUseId ?? toolUseId, agentId: context.agentId, onUrlElicitationRequired: () => { // The protocol attempt has ended before elicitation // handling begins, so its cached progress is stale. latestServerProgress = undefined }, onProgress: onProgress && toolUseId ? progressData => { let dataToEmit = progressData if ( progressData.status === 'progress' && typeof progressData.progress === 'number' ) { // Merge partial updates so a notification carrying // only progress does not drop the previously // reported total/progressMessage. latestServerProgress = { ...latestServerProgress, progress: progressData.progress, ...(progressData.total !== undefined && { total: progressData.total, }), ...(progressData.progressMessage !== undefined && { progressMessage: progressData.progressMessage, }), } dataToEmit = { ...progressData, ...latestServerProgress, } } try { onProgress({ toolUseID: toolUseId, data: dataToEmit, }) } catch (error) { // A throwing consumer must not propagate into // the MCP SDK's notification handler. logMCPError(client.name, error) } } : undefined, handleElicitation: context.handleElicitation, onServerTaskStarted: () => { taskified = true }, }) stopActivityHeartbeat() // Emit progress when tool completes successfully if (onProgress && toolUseId && !taskified) { try { onProgress({ toolUseID: toolUseId, data: { type: 'mcp_progress', status: 'completed', serverName: client.name, toolName: tool.name, elapsedTimeMs: Date.now() - startTime, }, }) } catch (error) { // A throwing progress consumer must not turn a // completed tool call into a failure. logMCPError(client.name, error) } } return { data: mcpResult.content, ...((mcpResult._meta || mcpResult.structuredContent) && { mcpMeta: { ...(mcpResult._meta && { _meta: mcpResult._meta, }), ...(mcpResult.structuredContent && { structuredContent: mcpResult.structuredContent, }), }, }), } } catch (error) { // Session expired — the connection cache has been // cleared, so retry with a fresh client. if ( error instanceof McpSessionExpiredError && attempt < MAX_SESSION_RETRIES ) { logMCPDebug( client.name, `Retrying tool '${tool.name}' after session recovery`, ) // The retried call starts over, so cached progress from // the previous attempt is no longer truthful. latestServerProgress = undefined continue } stopActivityHeartbeat() // Emit progress when tool fails if (onProgress && toolUseId) { try { onProgress({ toolUseID: toolUseId, data: { type: 'mcp_progress', status: 'failed', serverName: client.name, toolName: tool.name, elapsedTimeMs: Date.now() - startTime, }, }) } catch (progressError) { // Preserve the original tool error; the progress // consumer failure is only logged. logMCPError(client.name, progressError) } } // Wrap MCP SDK errors so telemetry gets useful context // instead of just "Error" or "McpError" (the constructor // name). MCP SDK errors are protocol-level messages and // don't contain user file paths or code. if ( error instanceof Error && !( error instanceof TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS ) ) { const name = error.constructor.name if (name === 'Error') { throw new TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( error.message, error.message.slice(0, 200), ) } // McpError has a numeric `code` with the JSON-RPC error // code (e.g. -32000 ConnectionClosed, -32001 RequestTimeout) if ( name === 'McpError' && 'code' in error && typeof error.code === 'number' ) { throw new TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( error.message, `McpError ${error.code}`, ) } } throw error } } }, userFacingName() { // Prefer title annotation if available, otherwise use tool name const displayName = tool.annotations?.title || tool.name return `${client.name} - ${displayName} (MCP)` }, ...(isClaudeInChromeMCPServer(client.name) && (client.config.type === 'stdio' || !client.config.type) ? claudeInChromeToolRendering().getClaudeInChromeMCPToolOverrides( tool.name, ) : {}), ...(feature('CHICAGO_MCP') && (client.config.type === 'stdio' || !client.config.type) && isComputerUseMCPServer!(client.name) ? computerUseWrapper!().getComputerUseMCPToolOverrides(tool.name) : {}), } }) .filter(isIncludedMcpTool) } catch (error) { // A cancelled fetch must not poison the cache: the next fetch for // this server re-lists instead of reusing the aborted empty result. if (options?.signal?.aborted || isAbortError(error)) { fetchToolsForClient.cache.delete(getDiscoveryCacheKey(client)) return [] } logMCPError(client.name, `Failed to fetch tools: ${errorMessage(error)}`) // Discovery did not record support for this connection. Support is // keyed by the connection's SDK client, so this only ever clears this // connection's own entry. clearMcpToolTaskSupport(client) return [] } }, // The cache key ignores the options: a fetch for one connection is one // entry, whatever signal it carries. The second parameter only keeps // the memoized function's arity honest. The key is the connection, not // the display name: two sessions can run the same name at different // endpoints, and a name-keyed entry lets a peer's tools answer a // host's reconnect. (client: MCPServerConnection, _options?: { signal?: AbortSignal }) => getDiscoveryCacheKey(client), MCP_FETCH_CACHE_SIZE, ) export const fetchResourcesForClient = memoizeWithLRU( async ( client: MCPServerConnection, options?: { signal?: AbortSignal }, ): Promise => { if (client.type !== 'connected') return [] try { if (!client.capabilities?.resources) { return [] } return await listAllMcpResources(client, options) } catch (error) { // Same cache-poisoning guard as fetchToolsForClient above. if (options?.signal?.aborted || isAbortError(error)) { fetchResourcesForClient.cache.delete(getDiscoveryCacheKey(client)) return [] } logMCPError( client.name, `Failed to fetch resources: ${errorMessage(error)}`, ) return [] } }, (client: MCPServerConnection, _options?: { signal?: AbortSignal }) => getDiscoveryCacheKey(client), MCP_FETCH_CACHE_SIZE, ) export const fetchCommandsForClient = memoizeWithLRU( async ( client: MCPServerConnection, options?: { signal?: AbortSignal }, ): Promise => { if (client.type !== 'connected') return [] try { if (!client.capabilities?.prompts) { return [] } const prompts = await paginateMcpList({ method: 'prompts/list', resultSchema: ListPromptsResultSchema, requestPage: async (request, resultSchema) => (await client.client.request(request, resultSchema, { signal: options?.signal, })) as ListPromptsResult, getItems: result => result.prompts, getNextCursor: result => result.nextCursor, }) // Sanitize prompt data from MCP server after the complete list succeeds. const promptsToProcess = recursivelySanitizeUnicode(prompts) // Convert MCP prompts to our Command format return promptsToProcess.map(prompt => { const argNames = Object.values(prompt.arguments ?? {}).map(k => k.name) return { type: 'prompt' as const, name: 'mcp__' + normalizeNameForMCP(client.name) + '__' + prompt.name, description: prompt.description ?? '', hasUserSpecifiedDescription: !!prompt.description, contentLength: 0, // Dynamic MCP content isEnabled: () => true, isHidden: false, isMcp: true, progressMessage: 'running', userFacingName() { // Use prompt.name (programmatic identifier) not prompt.title (display name) // to avoid spaces breaking slash command parsing return `${client.name}:${prompt.name} (MCP)` }, argNames, source: 'mcp', async getPromptForCommand(args: string) { const argsArray = args.split(' ') try { const connectedClient = await ensureConnectedClient(client) const result = await connectedClient.client.getPrompt({ name: prompt.name, arguments: zipObject(argNames, argsArray), }) const transformed = await Promise.all( result.messages.map(message => transformResultContent(message.content, connectedClient.name), ), ) return transformed.flat() } catch (error) { logMCPError( client.name, `Error running command '${prompt.name}': ${errorMessage(error)}`, ) throw error } }, } }) } catch (error) { // Same cache-poisoning guard as fetchToolsForClient above. if (options?.signal?.aborted || isAbortError(error)) { fetchCommandsForClient.cache.delete(getDiscoveryCacheKey(client)) return [] } logMCPError( client.name, `Failed to fetch commands: ${errorMessage(error)}`, ) return [] } }, (client: MCPServerConnection, _options?: { signal?: AbortSignal }) => getDiscoveryCacheKey(client), MCP_FETCH_CACHE_SIZE, ) /** * Call an IDE tool directly as an RPC * @param toolName The name of the tool to call * @param args The arguments to pass to the tool * @param client The IDE client to use for the RPC call * @returns The result of the tool call */ export async function callIdeRpc( toolName: string, args: Record, client: ConnectedMCPServer, ): Promise { const result = await callMCPTool({ client, tool: toolName, args, signal: createAbortController().signal, }) return result.content } /** * Note: This should not be called by UI components directly, they should use the reconnectMcpServer * function from useManageMcpConnections. * @param name Server name * @param config Server configuration * @returns Object containing the client connection and its resources */ export async function reconnectMcpServerImpl( name: string, config: ScopedMcpServerConfig, /** * Aborts the reconnect's connect attempt: a caller that is cancelled * while the reconnect is stalled does not wait out the connection * timeout, and the scope it ran in is released with it. Only the * caller that started this reconnect passes one. */ signal?: AbortSignal, /** * Where a discovery that outlives this caller finishes: another caller * may have adopted the shared client, so its remaining credential * operations — a later tools/list page, a skill read — run inside the * namespace the reconnect began in. It carries no signal: the * cancelled attempt must not fail the re-entry that keeps it there. * Only the host-facing caller passes one. */ survivingDiscoveryScope?: CredentialScope, /** * The session reconnecting: the received client is reserved for it * from receipt through installation, so another session's close cannot * withdraw the adoption claim and close the transport while this * session is still discovering (its prompts/list may still be pending * after tools/list completes). The caller converts the reservation * into the install record on success (noteMcpClientInstalled); the * catch below releases it on every other exit. Only the host-facing * caller passes one (CodeRabbit #2493 review 5964014825). */ owner?: object, ): Promise<{ client: MCPServerConnection tools: Tool[] commands: Command[] resources?: ServerResource[] }> { // The connected client, for the catch: a cancelled discovery leaves one // no session adopted, and only the catch sees it — the race below turns // the cancellation into a failed result before the caller does. let connected: MCPServerConnection | undefined // A client this session received but has not installed yet: reserved // for it from receipt through installation, so another session's // close cannot withdraw the adoption claim and close the transport // while discovery is still running (see the owner parameter above). let reservedClient: MCPServerConnection | undefined try { // Invalidate the keychain cache so we read fresh credentials from disk. // This is necessary when another process (e.g. the VS Code extension host) // has modified stored tokens (cleared auth, saved new OAuth tokens) and then // asks the CLI subprocess to reconnect. Without this, the subprocess would // use stale cached data and never notice the tokens were removed. clearKeychainCache() // A reconnect replaces the connection, it does not end it: a client // another session adopted from the shared connect keeps its // transport while the reconnect dials fresh (Copilot #2493 review // 5955514041). await clearServerCache(name, config, signal, { keepAdoptedClient: true }) const client = await connectToServer(name, config, undefined, signal) connected = client if (client.type !== 'connected') { return { client, tools: [], commands: [], } } if (owner !== undefined) { reserveMcpClientForSetup(client, owner) reservedClient = client } if (config.type === 'claudeai-proxy') { markClaudeAiMcpConnected(name) } const supportsResources = !!client.capabilities?.resources // Discovery is shared by client name across callers, so the attempt // signal must not drive the shared fetch: one caller's abort would // cancel another caller's result and leave it with a connected server // but no tools. The fetchers run without a signal and their results // stay cached for the other waiter; the race below rejects this caller // promptly on abort instead, and the attempt check in // authenticateMcpServer turns that into the cancellation error. // The list stays a tuple so Promise.all keeps each fetcher's type // (tools, commands, skills, resources) instead of widening to a union. const discoveryPartsList: [ Promise, Promise, Promise, Promise, ] = [ fetchToolsForClient(client), fetchCommandsForClient(client), feature('MCP_SKILLS') && supportsResources ? fetchMcpSkillsForClient!(client) : Promise.resolve([]), supportsResources ? fetchResourcesForClient(client) : Promise.resolve([]), ] // A cancelled discovery can outlive this caller: another caller may // have adopted the shared client, so the fetchers keep running for // it. The surviving entry re-enters the namespace the reconnect // began in for the parts' remaining credential operations. It queues // with precedence over regular waiters, so when this caller's scope // releases it is picked before a session that queued earlier — a // plain FIFO queue would hand the mutex to that session first, and // the remaining pages would read its environment instead. The entry // holds the mutex until the parts settle, so no other session's // environment can apply while they run. The entry is not awaited and // is not attached to the cancelled signal, so it cannot strip the // adopter's tools the way a shared signal would. Promise.all below // rejects on the first failure and would drop the stragglers, so the // surviving entry awaits the parts themselves. if (survivingDiscoveryScope !== undefined) { const parts = discoveryPartsList void resumeIn(survivingDiscoveryScope, () => Promise.allSettled(parts), ).catch(() => {}) } const discovery = Promise.all(discoveryPartsList) const [tools, mcpCommands, mcpSkills, resources] = await raceAbort( discovery, signal, ) const commands = [...mcpCommands, ...mcpSkills] // Check if we need to add resource tools const resourceTools: Tool[] = [] if (supportsResources) { // Only add resource tools if no other server has them const hasResourceTools = [ListMcpResourcesTool, ReadMcpResourceTool].some( tool => tools.some(t => toolMatchesName(t, tool.name)), ) if (!hasResourceTools) { resourceTools.push(ListMcpResourcesTool, ReadMcpResourceTool) } } return { client, tools: [...tools, ...resourceTools], commands, resources: resources.length > 0 ? resources : undefined, } } catch (error) { // Handle errors gracefully - connection might have closed during fetch. // A cancelled reconnect is not an error to report: the caller already // knows it aborted. if (!signal?.aborted && !isAbortError(error)) { logMCPError(name, `Error during reconnection: ${errorMessage(error)}`) } // A cancelled discovery leaves a connected client no session adopted: // release it, or its transport stays open in the cache until the next // reconnect clears it. A failure that is not a cancellation keeps the // client cached for the next connection. if ( (signal?.aborted || isAbortError(error)) && connected !== undefined ) { // The release is attempted before the reservation goes: while the // reservation is held it declines and records the block, and the // reservation's release below re-runs it exactly once — the other // order would race two releases through the probe. await releaseUnownedMcpClient(name, config, connected) } // A setup reservation outlives every exit except installation: the // caller converts it on success, so any exit here releases it, or // the transport stays reserved with no owner. A blocked release the // reservation held back is re-run by the release itself. if (reservedClient !== undefined && owner !== undefined) { releaseMcpClientSetupReservation(reservedClient, owner) } // Return with failed status return { client: { name, type: 'failed' as const, config }, tools: [], commands: [], } } } // Replaced 2026-03: previous implementation ran fixed-size sequential batches // (await batch 1 fully, then start batch 2). That meant one slow server in // batch N held up ALL servers in batch N+1, even if the other 19 slots were // idle. pMap frees each slot as soon as its server completes, so a single // slow server only occupies one slot instead of blocking an entire batch // boundary. Same concurrency ceiling, same results, better scheduling. async function processBatched( items: T[], concurrency: number, processor: (item: T) => Promise, ): Promise { await pMap(items, processor, { concurrency }) } export async function getMcpToolsCommandsAndResources( onConnectionAttempt: (params: { client: MCPServerConnection tools: Tool[] commands: Command[] resources?: ServerResource[] }) => void, mcpConfigs?: Record, ): Promise { let resourceToolsAdded = false const allConfigEntries = Object.entries( mcpConfigs ?? (await getAllMcpConfigs()).servers, ) // Partition into disabled and active entries — disabled servers should // never generate HTTP connections or flow through batch processing const configEntries: typeof allConfigEntries = [] for (const entry of allConfigEntries) { if (isMcpServerDisabled(entry[0])) { onConnectionAttempt({ client: { name: entry[0], type: 'disabled', config: entry[1] }, tools: [], commands: [], }) } else { configEntries.push(entry) } } // Calculate transport counts for logging const totalServers = configEntries.length const stdioCount = count(configEntries, ([_, c]) => c.type === 'stdio') const sseCount = count(configEntries, ([_, c]) => c.type === 'sse') const httpCount = count(configEntries, ([_, c]) => c.type === 'http') const sseIdeCount = count(configEntries, ([_, c]) => c.type === 'sse-ide') const wsIdeCount = count(configEntries, ([_, c]) => c.type === 'ws-ide') // Split servers by type: local (stdio/sdk) need lower concurrency due to // process spawning, remote servers can connect with higher concurrency const localServers = configEntries.filter(([_, config]) => isLocalMcpServer(config), ) const remoteServers = configEntries.filter( ([_, config]) => !isLocalMcpServer(config), ) const serverStats = { totalServers, stdioCount, sseCount, httpCount, sseIdeCount, wsIdeCount, } const processServer = async ([name, config]: [ string, ScopedMcpServerConfig, ]): Promise => { try { // Check if server is disabled - if so, just add it to state without connecting if (isMcpServerDisabled(name)) { onConnectionAttempt({ client: { name, type: 'disabled', config, }, tools: [], commands: [], }) return } // Skip connection for servers that recently returned 401 (15min TTL), // or that we have probed before but hold no token for. The second // check closes the gap the TTL leaves open: without it, every 15min // we re-probe servers that cannot succeed until the user runs /mcp. // Each probe is a network round-trip for connect-401 plus OAuth // discovery, and print mode awaits the whole batch (main.tsx:3503). if ( (config.type === 'claudeai-proxy' || config.type === 'http' || config.type === 'sse') && ((await isMcpAuthCached(name)) || ((config.type === 'http' || config.type === 'sse') && hasMcpDiscoveryButNoToken(name, config))) ) { logMCPDebug(name, `Skipping connection (cached needs-auth)`) onConnectionAttempt({ client: { name, type: 'needs-auth' as const, config }, tools: [createMcpAuthTool(name, config)], commands: [], }) return } const client = await connectToServer(name, config, serverStats) if (client.type !== 'connected') { onConnectionAttempt({ client, tools: client.type === 'needs-auth' ? [createMcpAuthTool(name, config)] : [], commands: [], }) return } if (config.type === 'claudeai-proxy') { markClaudeAiMcpConnected(name) } const supportsResources = !!client.capabilities?.resources const [tools, mcpCommands, mcpSkills, resources] = await Promise.all([ fetchToolsForClient(client), fetchCommandsForClient(client), // Discover skills from skill:// resources feature('MCP_SKILLS') && supportsResources ? fetchMcpSkillsForClient!(client) : Promise.resolve([]), // Fetch resources if supported supportsResources ? fetchResourcesForClient(client) : Promise.resolve([]), ]) const commands = [...mcpCommands, ...mcpSkills] // If this server resources and we haven't added resource tools yet, // include our resource tools with this client's tools const resourceTools: Tool[] = [] if (supportsResources && !resourceToolsAdded) { resourceToolsAdded = true resourceTools.push(ListMcpResourcesTool, ReadMcpResourceTool) } onConnectionAttempt({ client, tools: [...tools, ...resourceTools], commands, resources: resources.length > 0 ? resources : undefined, }) } catch (error) { // Handle errors gracefully - connection might have closed during fetch logMCPError( name, `Error fetching tools/commands/resources: ${errorMessage(error)}`, ) // Still update with the client but no tools/commands onConnectionAttempt({ client: { name, type: 'failed' as const, config }, tools: [], commands: [], }) } } // Process both groups concurrently, each with their own concurrency limits: // - Local servers (stdio/sdk): lower concurrency to avoid process spawning resource contention // - Remote servers: higher concurrency since they're just network connections await Promise.all([ processBatched( localServers, getMcpServerConnectionBatchSize(), processServer, ), processBatched( remoteServers, getRemoteMcpServerConnectionBatchSize(), processServer, ), ]) } // Not memoized: called only 2-3 times at startup/reconfig. The inner work // (connectToServer, fetch*ForClient) is already cached. Memoizing here by // mcpConfigs object ref leaked — main.tsx creates fresh config objects each call. export function prefetchAllMcpResources( mcpConfigs: Record, ): Promise<{ clients: MCPServerConnection[] tools: Tool[] commands: Command[] }> { return new Promise(resolve => { let pendingCount = 0 let completedCount = 0 pendingCount = Object.keys(mcpConfigs).length if (pendingCount === 0) { void resolve({ clients: [], tools: [], commands: [], }) return } const clients: MCPServerConnection[] = [] const tools: Tool[] = [] const commands: Command[] = [] getMcpToolsCommandsAndResources(result => { clients.push(result.client) tools.push(...result.tools) commands.push(...result.commands) completedCount++ if (completedCount >= pendingCount) { const commandsMetadataLength = commands.reduce((sum, command) => { const commandMetadataLength = command.name.length + (command.description ?? '').length + (command.argumentHint ?? '').length return sum + commandMetadataLength }, 0) logEvent('tengu_mcp_tools_commands_loaded', { tools_count: tools.length, commands_count: commands.length, commands_metadata_length: commandsMetadataLength, }) void resolve({ clients, tools, commands, }) } }, mcpConfigs).catch(error => { logMCPError( 'prefetchAllMcpResources', `Failed to get MCP resources: ${errorMessage(error)}`, ) // Still resolve with empty results void resolve({ clients: [], tools: [], commands: [], }) }) }) } /** * Transform result content from an MCP tool or MCP prompt into message blocks */ export async function transformResultContent( resultContent: PromptMessage['content'], serverName: string, ): Promise> { switch (resultContent.type) { case 'text': return [ { type: 'text', text: recursivelySanitizeUnicode(resultContent.text) as string, }, ] case 'audio': { const audioData = resultContent as { type: 'audio' data: string mimeType?: string } return await persistBlobToTextBlock( Buffer.from(audioData.data, 'base64'), audioData.mimeType, serverName, `[Audio from ${serverName}] `, ) } case 'image': { // Resize and compress image data, enforcing API dimension limits const imageBuffer = Buffer.from(String(resultContent.data), 'base64') const ext = resultContent.mimeType?.split('/')[1] || 'png' const resized = await maybeResizeAndDownsampleImageBuffer( imageBuffer, imageBuffer.length, ext, ) return [ { type: 'image', source: { data: resized.buffer.toString('base64'), media_type: `image/${resized.mediaType}` as Base64ImageSource['media_type'], type: 'base64', }, }, ] } case 'resource': { const resource = resultContent.resource const prefix = `[Resource from ${serverName} at ${resource.uri}] ` if ('text' in resource) { return [ { type: 'text', text: recursivelySanitizeUnicode( `${prefix}${resource.text}`, ) as string, }, ] } else if ('blob' in resource) { const isImage = IMAGE_MIME_TYPES.has(resource.mimeType ?? '') if (isImage) { // Resize and compress image blob, enforcing API dimension limits const imageBuffer = Buffer.from(resource.blob, 'base64') const ext = resource.mimeType?.split('/')[1] || 'png' const resized = await maybeResizeAndDownsampleImageBuffer( imageBuffer, imageBuffer.length, ext, ) const content: MessageParam['content'] = [] if (prefix) { content.push({ type: 'text', text: prefix, }) } content.push({ type: 'image', source: { data: resized.buffer.toString('base64'), media_type: `image/${resized.mediaType}` as Base64ImageSource['media_type'], type: 'base64', }, }) return content } else { return await persistBlobToTextBlock( Buffer.from(resource.blob, 'base64'), resource.mimeType, serverName, prefix, ) } } return [] } case 'resource_link': { const resourceLink = resultContent as ResourceLink let text = `[Resource link: ${resourceLink.name}] ${resourceLink.uri}` if (resourceLink.description) { text += ` (${resourceLink.description})` } return [ { type: 'text', text, }, ] } default: return [] } } /** * Decode base64 binary content, write it to disk with the proper extension, * and return a small text block with the file path. Replaces the old behavior * of dumping raw base64 into the context. */ async function persistBlobToTextBlock( bytes: Buffer, mimeType: string | undefined, serverName: string, sourceDescription: string, ): Promise> { const persistId = `mcp-${normalizeNameForMCP(serverName)}-blob-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` const result = await persistBinaryContent(bytes, mimeType, persistId) if ('error' in result) { return [ { type: 'text', text: `${sourceDescription}Binary content (${mimeType || 'unknown type'}, ${bytes.length} bytes) could not be saved to disk: ${result.error}`, }, ] } return [ { type: 'text', text: getBinaryBlobSavedMessage( result.filepath, mimeType, result.size, sourceDescription, ), }, ] } /** * Processes MCP tool result into a normalized format. */ export type MCPResultType = 'toolResult' | 'structuredContent' | 'contentArray' export type TransformedMCPResult = { content: MCPToolResult type: MCPResultType schema?: string } /** * Generates a compact, jq-friendly type signature for a value. * e.g. "{title: string, items: [{id: number, name: string}]}" */ export function inferCompactSchema(value: unknown, depth = 2): string { if (value === null) return 'null' if (Array.isArray(value)) { if (value.length === 0) return '[]' return `[${inferCompactSchema(value[0], depth - 1)}]` } if (typeof value === 'object') { if (depth <= 0) return '{...}' const entries = Object.entries(value).slice(0, 10) const props = entries.map( ([k, v]) => `${k}: ${inferCompactSchema(v, depth - 1)}`, ) const suffix = Object.keys(value).length > 10 ? ', ...' : '' return `{${props.join(', ')}${suffix}}` } return typeof value } export async function transformMCPResult( result: unknown, tool: string, // Tool name for validation (e.g., "search") name: string, // Server name for transformation (e.g., "slack") ): Promise { if (result && typeof result === 'object') { if ('toolResult' in result) { return { content: String(result.toolResult), type: 'toolResult', } } if ( 'structuredContent' in result && result.structuredContent !== undefined ) { return { content: jsonStringify(result.structuredContent), type: 'structuredContent', schema: inferCompactSchema(result.structuredContent), } } if ('content' in result && Array.isArray(result.content)) { const transformedContent = ( await Promise.all( result.content.map(item => transformResultContent(item, name)), ) ).flat() return { content: transformedContent, type: 'contentArray', schema: inferCompactSchema(transformedContent), } } } const errorMessage = `MCP server "${name}" tool "${tool}": unexpected response format` logMCPError(name, errorMessage) throw new TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( errorMessage, 'MCP tool unexpected response format', ) } /** * Check if MCP content contains any image blocks. * Used to decide whether to persist to file (images should use truncation instead * to preserve image compression and viewability). */ function contentContainsImages(content: MCPToolResult): boolean { if (!content || typeof content === 'string') { return false } return content.some(block => block.type === 'image') } export async function processMCPResult( result: unknown, tool: string, // Tool name for validation (e.g., "search") name: string, // Server name for IDE check and transformation (e.g., "slack") ): Promise { const { content, type, schema } = await transformMCPResult(result, tool, name) // IDE tools are not going to the model directly, so we don't need to // handle large output. if (name === 'ide') { return content } // Check if content needs truncation (i.e., is too large) if (!(await mcpContentNeedsTruncation(content))) { return content } const sizeEstimateTokens = getContentSizeEstimate(content) // If large output files feature is disabled, fall back to old truncation behavior if (isEnvDefinedFalsy(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES)) { logEvent('tengu_mcp_large_result_handled', { outcome: 'truncated', reason: 'env_disabled', sizeEstimateTokens, } as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS) return await truncateMcpContentIfNeeded(content) } // Save large output to file and return instructions for reading it // Content is guaranteed to exist at this point (we checked mcpContentNeedsTruncation) if (!content) { return content } // If content contains images, fall back to truncation - persisting images as JSON // defeats the image compression logic and makes them non-viewable if (contentContainsImages(content)) { logEvent('tengu_mcp_large_result_handled', { outcome: 'truncated', reason: 'contains_images', sizeEstimateTokens, } as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS) return await truncateMcpContentIfNeeded(content) } // Generate a unique ID for the persisted file (server__tool-timestamp) const timestamp = Date.now() const persistId = `mcp-${normalizeNameForMCP(name)}-${normalizeNameForMCP(tool)}-${timestamp}` // Convert to string for persistence (persistToolResult expects string or specific block types) const contentStr = typeof content === 'string' ? content : jsonStringify(content, null, 2) const persistResult = await persistToolResult(contentStr, persistId) if (isPersistError(persistResult)) { // If file save failed, fall back to returning truncated content info logEvent('tengu_mcp_large_result_handled', { outcome: 'truncated', reason: 'persist_failed', sizeEstimateTokens, } as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS) return getLargeOutputPersistenceFailureInstructions( contentStr, persistResult.error, ) } logEvent('tengu_mcp_large_result_handled', { outcome: 'persisted', reason: 'file_saved', sizeEstimateTokens, persistedSizeBytes: persistResult.originalSize, } as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS) const formatDescription = getFormatDescription(type, schema) return getLargeOutputInstructions( persistResult.filepath, persistResult.originalSize, formatDescription, ) } /** * Call an MCP tool, handling UrlElicitationRequiredError (-32042) by * displaying the URL elicitation to the user, waiting for the completion * notification, and retrying the tool call. */ /** * tools/call augmented with task creation params can answer with either a * normal tool result or a CreateTaskResult when the server taskifies it. */ const TaskAugmentedCallToolResultSchema = z.union([ CreateTaskResultSchema, CallToolResultSchema, ]) type MCPToolCallResult = { content: MCPToolResult _meta?: Record structuredContent?: Record } /** @internal Exported for testing. */ export async function callMCPToolWithUrlElicitationRetry({ client: connectedClient, clientConnection, tool, args, meta, signal, setAppState, setTaskAppState = setAppState, onProgress, toolUseId, agentId, callToolFn = callMCPTool, handleElicitation, onUrlElicitationRequired, onServerTaskStarted, }: { client: ConnectedMCPServer clientConnection: MCPServerConnection tool: string args: Record meta?: Record signal: AbortSignal setAppState: (f: (prev: AppState) => AppState) => void /** Task registration channel (setAppStateForTasks); defaults to setAppState. */ setTaskAppState?: (f: (prev: AppState) => AppState) => void onProgress?: (data: MCPProgress) => void /** Caller context for the background task notification. */ toolUseId?: string agentId?: AgentId /** Injectable for testing. Defaults to callMCPTool. */ callToolFn?: (opts: { client: ConnectedMCPServer tool: string args: Record meta?: Record signal: AbortSignal onProgress?: (data: MCPProgress) => void onServerTaskCreated?: (task: McpTask) => MCPToolCallResult }) => Promise /** Handler for URL elicitations when no hook handles them. * In print/SDK mode, delegates to structuredIO. In REPL, falls back to queue. */ handleElicitation?: ( serverName: string, params: ElicitRequestURLParams, signal: AbortSignal, ) => Promise /** Called after validating a URL-elicitation error, before awaiting handling. */ onUrlElicitationRequired?: () => void /** Called when the server accepted taskification and the call returned a background handle. */ onServerTaskStarted?: () => void }): Promise { const MAX_URL_ELICITATION_RETRIES = 3 for (let attempt = 0; ; attempt++) { // Check abort signal before each attempt — without this, a cancelled // elicitation retry loop continues spinning until MAX retries if (signal.aborted) { throw new AbortError('Tool call aborted during URL elicitation') } try { return await callToolFn({ client: connectedClient, tool, args, meta, signal, onProgress, onServerTaskCreated: mcpTask => { onServerTaskStarted?.() const description = `${connectedClient.name}: ${tool}` const taskId = trackMcpServerTask({ connection: connectedClient, task: mcpTask, toolName: tool, description, toolUseId, agentId, setAppState: setTaskAppState, }) return { content: `MCP server "${connectedClient.name}" started "${tool}" as background task ${taskId}. The task runs on the server; you will be notified when it completes. Do not retry or poll for the result.`, } }, }) } catch (error) { // The MCP SDK's Protocol creates plain McpError (not UrlElicitationRequiredError) // for error responses, so we check the error code instead of instanceof. if ( !(error instanceof McpError) || error.code !== ErrorCode.UrlElicitationRequired ) { throw error } // Limit the number of URL elicitation retries if (attempt >= MAX_URL_ELICITATION_RETRIES) { throw error } const errorData = error.data const rawElicitations = errorData != null && typeof errorData === 'object' && 'elicitations' in errorData && Array.isArray(errorData.elicitations) ? (errorData.elicitations as unknown[]) : [] // Validate each element has the required fields for ElicitRequestURLParams const elicitations = rawElicitations.filter( (e): e is ElicitRequestURLParams => { if (e == null || typeof e !== 'object') return false const obj = e as Record return ( obj.mode === 'url' && typeof obj.url === 'string' && typeof obj.elicitationId === 'string' && typeof obj.message === 'string' ) }, ) const serverName = clientConnection.type === 'connected' ? clientConnection.name : 'unknown' if (elicitations.length === 0) { logMCPDebug( serverName, `Tool '${tool}' returned -32042 but no valid elicitations in error data`, ) throw error } onUrlElicitationRequired?.() logMCPDebug( serverName, `Tool '${tool}' requires URL elicitation (error -32042, attempt ${attempt + 1}), processing ${elicitations.length} elicitation(s)`, ) // Process each URL elicitation from the error. // The completion notification handler (in registerElicitationHandler) sets // `completed: true` on the matching queue event; the dialog reacts to this flag. for (const elicitation of elicitations) { const { elicitationId } = elicitation // Run elicitation hooks — they can resolve URL elicitations programmatically const hookResponse = await runElicitationHooks( serverName, elicitation, signal, ) if (hookResponse) { logMCPDebug( serverName, `URL elicitation ${elicitationId} resolved by hook: ${jsonStringify(hookResponse)}`, ) if (hookResponse.action !== 'accept') { return { content: `URL elicitation was ${hookResponse.action === 'decline' ? 'declined' : hookResponse.action + 'ed'} by a hook. The tool "${tool}" could not complete because it requires the user to open a URL.`, } } // Hook accepted — skip the UI and proceed to retry continue } // Resolve the URL elicitation via callback (print/SDK mode) or queue (REPL mode). let userResult: ElicitResult if (handleElicitation) { // Print/SDK mode: delegate to structuredIO which sends a control request userResult = await handleElicitation(serverName, elicitation, signal) } else { // REPL mode: queue for ElicitationDialog with two-phase consent/waiting flow const waitingState: ElicitationWaitingState = { actionLabel: 'Retry now', showCancel: true, } userResult = await new Promise(resolve => { const onAbort = () => { void resolve({ action: 'cancel' }) } if (signal.aborted) { onAbort() return } signal.addEventListener('abort', onAbort, { once: true }) setAppState(prev => ({ ...prev, elicitation: { queue: [ ...prev.elicitation.queue, { serverName, requestId: `error-elicit-${elicitationId}`, params: elicitation, signal, waitingState, respond: result => { // Phase 1 consent: accept is a no-op (doesn't resolve retry Promise) if (result.action === 'accept') { return } // Decline or cancel: resolve the retry Promise signal.removeEventListener('abort', onAbort) void resolve(result) }, onWaitingDismiss: action => { signal.removeEventListener('abort', onAbort) if (action === 'retry') { void resolve({ action: 'accept' }) } else { void resolve({ action: 'cancel' }) } }, }, ], }, })) }) } // Run ElicitationResult hooks — they can modify or block the response const finalResult = await runElicitationResultHooks( serverName, userResult, signal, 'url', elicitationId, ) if (finalResult.action !== 'accept') { logMCPDebug( serverName, `User ${finalResult.action === 'decline' ? 'declined' : finalResult.action + 'ed'} URL elicitation ${elicitationId}`, ) return { content: `URL elicitation was ${finalResult.action === 'decline' ? 'declined' : finalResult.action + 'ed'} by the user. The tool "${tool}" could not complete because it requires the user to open a URL.`, } } logMCPDebug( serverName, `Elicitation ${elicitationId} completed, retrying tool call`, ) } // Loop back to retry the tool call } } } async function callMCPTool({ client: connection, tool, args, meta, signal, onProgress, onServerTaskCreated, }: { client: ConnectedMCPServer tool: string args: Record meta?: Record signal: AbortSignal onProgress?: (data: MCPProgress) => void /** * Called when the server taskifies the call (CreateTaskResult instead of a * tool result). Returns the tool result the model should see immediately. */ onServerTaskCreated?: (task: McpTask) => MCPToolCallResult }): Promise<{ content: MCPToolResult _meta?: Record structuredContent?: Record }> { const { client, name, config } = connection const toolStartTime = Date.now() let progressInterval: NodeJS.Timeout | undefined try { logMCPDebug(name, `Calling MCP tool: ${tool}`) // Set up progress logging for long-running tools (every 30 seconds) progressInterval = setInterval( (startTime, name, tool) => { const elapsed = Date.now() - startTime const elapsedSeconds = Math.floor(elapsed / 1000) const duration = `${elapsedSeconds}s` logMCPDebug(name, `Tool '${tool}' still running (${duration} elapsed)`) }, 30000, // Log every 30 seconds toolStartTime, name, tool, ) // Use our own timeout to handle cases where SDK's internal timeout // doesn't work (e.g., SSE stream breaks mid-request). Abort the protocol // request too; merely racing a timeout leaves the server call running in // the background and can keep its transport occupied after we return. const timeoutMs = getMcpToolTimeoutMs() const timeoutController = createAbortController() const { signal: requestSignal, cleanup: cleanupRequestSignal, } = createCombinedAbortSignal(signal, { signalB: timeoutController.signal, trace: { subsystem: 'mcp_tool_call', controllerRole: 'mcp_tool_call' }, }) let timeoutId: NodeJS.Timeout | undefined const timeoutPromise = new Promise((_, reject) => { timeoutId = setTimeout(() => { timeoutController.abort( new DOMException('The operation timed out.', 'TimeoutError'), ) reject( new TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( `MCP server "${name}" tool "${tool}" timed out after ${Math.floor(timeoutMs / 1000)}s`, 'MCP tool timeout', ), ) }, timeoutMs) }) const requestOptions = { signal: requestSignal, timeout: timeoutMs, onprogress: onProgress ? sdkProgress => { onProgress({ type: 'mcp_progress', status: 'progress', serverName: name, toolName: tool, progress: sdkProgress.progress, total: sdkProgress.total, progressMessage: sdkProgress.message, }) } : undefined, } // A server that advertises tasks.requests.tools.call may run task-marked // tools as durable tasks. Augment the request so it can answer with a // CreateTaskResult; the task then moves to the background task list. // A reconnect clears the recorded support, so ensure tools/list has run // on this connection first: a task-required tool sent as a plain // tools/call is rejected by the server. // Discovery runs inside the timed race and the caller's abort also ends // the wait, so a slow tools/list counts against MCP_TOOL_TIMEOUT and Esc // interrupts it. Dispatch stays one `.then` after discovery, the same // depth as a plain await. let removeCallerAbortListener: (() => void) | undefined const callerAbortPromise = new Promise((_, reject) => { const onCallerAbort = () => reject(new AbortError()) if (signal.aborted) { onCallerAbort() return } signal.addEventListener('abort', onCallerAbort, { once: true }) removeCallerAbortListener = () => signal.removeEventListener('abort', onCallerAbort) }) // A caller without onServerTaskCreated (the IDE RPC path) cannot register // or fetch a server task, so it must get the plain call and its result. const canTrackServerTask = onServerTaskCreated !== undefined const dispatch = async () => { // Discovery can outlive the timeout or the caller's abort; do not send // a request that has already been given up on. if (requestSignal.aborted) { throw requestSignal.reason ?? new AbortError() } // Discovery failed on this connection, so support is unknown, and the // failed run's empty result is memoized. Drop it so a later call // rediscovers instead of staying on the plain path until reconnect. // Discovery memos are keyed by connection (getDiscoveryCacheKey), // not by display name: a bare-name delete would miss the entry and // the failed run would pin the plain path (merge with upstream #2541). if (canTrackServerTask && isMcpToolTaskSupportUnknown(connection)) { fetchToolsForClient.cache.delete(getDiscoveryCacheKey(connection)) } const taskSupport = canTrackServerTask ? mcpTaskSupportForTool(connection, tool) : undefined return taskSupport ? client.request( { method: 'tools/call' as const, params: { name: tool, arguments: args, _meta: meta, }, }, TaskAugmentedCallToolResultSchema, // The SDK keeps the progress handler until the connection closes // on the task path, so a background task would leave one behind. // Progress stays on the synchronous path only. { ...requestOptions, onprogress: undefined, task: {} }, ) : client.callTool( { name: tool, arguments: args, _meta: meta, }, CallToolResultSchema, requestOptions, ) } const result = await Promise.race([ // Discovery only decides plain vs task-augmented, so skip it when the // server cannot background anything or the env opt-out is set: a slow // tools/list must not delay the plain call in those cases. (canTrackServerTask && mcpServerAdvertisesTaskTools(connection) ? fetchToolsForClient(connection) : Promise.resolve([]) ).then(dispatch), callerAbortPromise, timeoutPromise, ]).finally(() => { if (timeoutId) { clearTimeout(timeoutId) } removeCallerAbortListener?.() cleanupRequestSignal() }) if ('task' in result && result.task) { // The server accepted taskification. Register the remote task as a // background task and let the model continue; the real result arrives // as a task notification on completion. clearInterval(progressInterval) const task = result.task as McpTask logMCPDebug( name, `Tool '${tool}' taskified by server as task ${task.taskId} (status ${task.status})`, ) return ( onServerTaskCreated?.(task) ?? { content: `MCP server "${name}" started tool "${tool}" as background task ${task.taskId}.`, } ) } if ('isError' in result && result.isError) { let errorDetails = 'Unknown error' if ( 'content' in result && Array.isArray(result.content) && result.content.length > 0 ) { const firstContent = result.content[0] if ( firstContent && typeof firstContent === 'object' && 'text' in firstContent ) { errorDetails = firstContent.text } } else if ('error' in result) { // Fallback for legacy error format errorDetails = String(result.error) } logMCPError(name, errorDetails) // Include server and tool name in telemetry for debugging, but keep // the human-readable message unchanged to avoid breaking error consumers // that parse the message string. throw new McpToolCallError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS( errorDetails, `MCP tool [${name}] ${tool}: ${errorDetails}`, '_meta' in result && result._meta ? { _meta: result._meta } : undefined, ) } const elapsed = Date.now() - toolStartTime const duration = elapsed < 1000 ? `${elapsed}ms` : elapsed < 60000 ? `${Math.floor(elapsed / 1000)}s` : `${Math.floor(elapsed / 60000)}m ${Math.floor((elapsed % 60000) / 1000)}s` logMCPDebug(name, `Tool '${tool}' completed successfully in ${duration}`) // Log code indexing tool usage const codeIndexingTool = detectCodeIndexingFromMcpServerName(name) if (codeIndexingTool) { logEvent('tengu_code_indexing_tool_used', { tool: codeIndexingTool as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, source: 'mcp' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, success: true, }) } const content = await processMCPResult(result, tool, name) return { content, _meta: result._meta as Record | undefined, structuredContent: result.structuredContent as | Record | undefined, } } catch (e) { // Clear intervals on error if (progressInterval !== undefined) { clearInterval(progressInterval) } const elapsed = Date.now() - toolStartTime if (e instanceof Error && e.name !== 'AbortError') { logMCPDebug( name, `Tool '${tool}' failed after ${Math.floor(elapsed / 1000)}s: ${e.message}`, ) } // Check for 401 errors indicating expired/invalid OAuth tokens // The MCP SDK's StreamableHTTPError has a `code` property with the HTTP status if (e instanceof Error) { const errorCode = 'code' in e ? (e.code as number | undefined) : undefined if (errorCode === 401 || e instanceof UnauthorizedError) { logMCPDebug( name, `Tool call returned 401 Unauthorized - token may have expired`, ) logEvent('tengu_mcp_tool_call_auth_error', {}) throw new McpAuthError( name, `MCP server "${name}" requires re-authorization (token expired)`, ) } // Check for session expiry — two error shapes can surface here: // 1. Direct 404 + JSON-RPC -32001 from the server (StreamableHTTPError) // 2. -32000 "Connection closed" (McpError) — the SDK closes the transport // after the onerror handler fires, so the pending callTool() rejects // with this derived error instead of the original 404. // In both cases, clear the connection cache so the next tool call // creates a fresh session — but only the transport this call // actually failed on. A reauthentication may have swapped in a // replacement while this call was in flight; clearing by name and // config would close the replacement instead and interrupt the // requests already running on it. When the cache already holds a // different generation, the clear leaves it intact and the retry // uses it (CodeRabbit #2493 review 5961865068). const isSessionExpired = isMcpSessionExpiredError(e) const isConnectionClosedOnHttp = 'code' in e && (e as Error & { code?: number }).code === -32000 && e.message.includes('Connection closed') && (config.type === 'http' || config.type === 'claudeai-proxy') // Dispatch-time discovery swallows its own session-loss error and // returns []; the closed SDK client then rejects the call itself with // a plain "Not connected" that has no code to match above. const isNotConnectedOnHttp = e.message === 'Not connected' && (config.type === 'http' || config.type === 'claudeai-proxy') if (isSessionExpired || isConnectionClosedOnHttp || isNotConnectedOnHttp) { logMCPDebug( name, `MCP session expired during tool call (${isSessionExpired ? '404/-32001' : 'connection closed'}), clearing connection cache for re-initialization`, ) logEvent('tengu_mcp_session_expired', {}) await clearServerCache(name, config, undefined, { expectedClient: connection, }) throw new McpSessionExpiredError(name) } } // When the user hits esc, convert to our AbortError class so the tool // execution framework handles it properly (skips logging, creates // is_error: true result with [Request interrupted by user for tool use]). // Previously this returned { content: undefined }, which masked the // cancellation and caused mapToolResultToToolResultBlockParam to send // empty/undefined content to the API as if it were a successful result. if (isAbortError(e)) { throw new AbortError( e instanceof Error ? e.message : 'Tool execution cancelled', ) } throw e } finally { // Always clear intervals if (progressInterval !== undefined) { clearInterval(progressInterval) } } } function extractToolUseId(message: AssistantMessage): string | undefined { if (message.message.content[0]?.type !== 'tool_use') { return undefined } return message.message.content[0].id } /** * Build the command and args for a stdio MCP transport, applying the * CLAUDE_CODE_SHELL_PREFIX split into separate argv entries. This * ensures the MCP SDK receives a proper command + args[] instead of * a shell-joined string, preventing shell metacharacter injection * from serverRef.args. * * When a prefix is set, prefixParts[0] becomes the command and * prefixParts[1..] + original command + original args become the * argv array. */ export function buildMcpStdioCommand( command: string, args: string[], shellPrefix?: string, ): { command: string; args: string[] } { if (!shellPrefix) { return { command, args } } let finalCommand: string let prefixArgs: string[] // Split on the last " -c" to preserve spaced executable path // (e.g. "C:\Program Files\Git\bin\bash.exe -c"). When no " -c" is // present, fall back to plain whitespace split. const cIndex = shellPrefix.lastIndexOf(' -c') if (cIndex > 0) { finalCommand = shellPrefix.substring(0, cIndex) prefixArgs = ['-c', ...shellPrefix.substring(cIndex + 3).split(/\s+/).filter(Boolean)] } else { const parts = shellPrefix.split(/\s+/).filter(Boolean) if (parts.length === 0) return { command, args } finalCommand = parts[0] prefixArgs = parts.slice(1) } // Shell -c prefix (e.g. sh -c, bash -c): everything after -c is a single // shell command string, not individual argv entries. Without this join, // sh -c runs only the first word as the command string and treats the // remaining entries as shell positional parameters ($0, $1, ...), so the // MCP server never receives its configured arguments. // // Each original command/arg is single-quote-escaped to prevent shell // injection via MCP server args (e.g. --path=/tmp; rm -rf / would // otherwise execute the semicolon as a command separator). if (prefixArgs.includes('-c')) { const cmdStr = [command, ...args].map(a => `'${a.replace(/'/g, "'\\''")}'`).join(' ') return { command: finalCommand, args: [...prefixArgs, cmdStr], } } return { command: finalCommand, args: [...prefixArgs, command, ...args], } } /** * Sets up SDK MCP clients by creating transports and connecting them. * This is used for SDK MCP servers that run in the same process as the SDK. * * @param sdkMcpConfigs - The SDK MCP server configurations * @param sendMcpMessage - Callback to send MCP messages through the control channel * @returns Connected clients, their tools, and transport map for message routing */ export async function setupSdkMcpClients( sdkMcpConfigs: Record, sendMcpMessage: ( serverName: string, message: JSONRPCMessage, ) => Promise, ): Promise<{ clients: MCPServerConnection[] tools: Tool[] }> { const clients: MCPServerConnection[] = [] const tools: Tool[] = [] // Connect to all servers in parallel const results = await Promise.allSettled( Object.entries(sdkMcpConfigs).map(async ([name, config]) => { const transport = new SdkControlClientTransport(name, sendMcpMessage) const client = new Client( { // name stays 'claude-code' for compatibility with MCP servers that // gate features on the upstream client identifier. name: 'claude-code', title: 'OpenClaude', version: MACRO.VERSION ?? 'unknown', description: 'OpenClaude — coding-agent CLI for any LLM provider', websiteUrl: PRODUCT_URL, }, { capabilities: {}, }, ) try { // Connect the client await client.connect(transport) // Get capabilities from the server const capabilities = client.getServerCapabilities() // Create the connected client object const connectedClient: MCPServerConnection = { type: 'connected', name, capabilities: capabilities || {}, client, config: { ...config, scope: 'dynamic' as const }, cleanup: async () => { await client.close() }, } // Fetch tools if the server has them const serverTools: Tool[] = [] if (capabilities?.tools) { const sdkTools = await fetchToolsForClient(connectedClient) serverTools.push(...sdkTools) } return { client: connectedClient, tools: serverTools, } } catch (error) { // If connection fails, return failed server logMCPError(name, `Failed to connect SDK MCP server: ${error}`) return { client: { type: 'failed' as const, name, config: { ...config, scope: 'user' as const }, }, tools: [], } } }), ) // Process results and collect clients and tools for (const result of results) { if (result.status === 'fulfilled') { clients.push(result.value.client) tools.push(...result.value.tools) } // If rejected (unexpected), the error was already logged inside the promise } return { clients, tools } }