forked from Gitlawb/openclaude
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
3411 lines (3147 loc) · 119 KB
/
client.ts
File metadata and controls
3411 lines (3147 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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,
ElicitRequestSchema,
type ElicitRequestURLParams,
type ElicitResult,
ErrorCode,
type JSONRPCMessage,
type ListPromptsResult,
ListPromptsResultSchema,
ListResourcesResultSchema,
ListRootsRequestSchema,
type ListToolsResult,
ListToolsResultSchema,
McpError,
type PromptMessage,
type ResourceLink,
} from '@modelcontextprotocol/sdk/types.js'
import mapValues from 'lodash-es/mapValues.js'
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 { 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 { getPublicBuildVersion } from '../../utils/userAgent.js'
import {
getBinaryBlobSavedMessage,
getFormatDescription,
getLargeOutputInstructions,
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 { 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 { AssistantMessage } from 'src/types/message.js'
/* eslint-enable @typescript-eslint/no-require-imports */
import { classifyMcpToolForCollapse } from '../../tools/MCPTool/classifyForCollapse.js'
import { clearKeychainCache } from '../../utils/secureStorage/macOsKeychainHelpers.js'
import { sleep } from '../../utils/sleep.js'
import {
ClaudeAuthProvider,
hasMcpDiscoveryButNoToken,
wrapFetchWithStepUpDetection,
} from './auth.js'
import { markClaudeAiMcpConnected } from './claudeai.js'
import { getAllMcpConfigs, isMcpServerDisabled } from './config.js'
import { getMcpServerHeaders } from './headersHelper.js'
import { SdkControlClientTransport } from './SdkControlTransport.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<string, unknown> },
) {
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
/**
* 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'
const MCP_AUTH_CACHE_TTL_MS = 15 * 60 * 1000 // 15 min
type McpAuthCacheData = Record<string, { timestamp: number }>
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<McpAuthCacheData> | null = null
function getMcpAuthCache(): Promise<McpAuthCacheData> {
if (!authCachePromise) {
authCachePromise = readFile(getMcpAuthCachePath(), 'utf-8')
.then(data => jsonParse(data) as McpAuthCacheData)
.catch(() => ({}))
}
return authCachePromise
}
async function isMcpAuthCached(serverId: string): Promise<boolean> {
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<typeof transportType, string> = {
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<string, unknown>,
): Promise<WsClientLike> {
const wsModule = await import('ws')
const WS = wsModule.default as unknown as new (
url: string,
protocols: string[],
options: Record<string, unknown>,
) => 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'
/**
* Wraps a fetch function to apply a fresh timeout signal to each request.
* This avoids the bug where a single AbortSignal.timeout() created at connection
* time becomes stale after 60 seconds, causing all subsequent requests to fail
* immediately with "The operation timed out." Uses a 60-second timeout.
*
* Also ensures the Accept header required by the MCP Streamable HTTP spec is
* present on POSTs. The MCP SDK sets this inside StreamableHTTPClientTransport.send(),
* but it is attached to a Headers instance that passes through an object spread here,
* and some runtimes/agents have been observed dropping it before it reaches the wire.
* See https://github.com/anthropics/claude-agent-sdk-typescript/issues/202.
* Normalizing here (the last wrapper before fetch()) guarantees it is sent.
*
* GET requests are excluded from the timeout since, for MCP transports, they are
* long-lived SSE streams meant to stay open indefinitely. (Auth-related GETs use
* a separate fetch wrapper with its own timeout in auth.ts.)
*
* @param baseFetch - The fetch function to wrap
*/
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,
})
cleanup()
return response
} catch (error) {
cleanup()
throw error
}
}
}
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<void>
close(): Promise<void>
}
export async function cleanupFailedConnection(
transport: Pick<Transport, 'close'>,
inProcessServer?: Pick<InProcessMcpServer, 'close'>,
): Promise<void> {
if (inProcessServer) {
await inProcessServer.close().catch(() => {})
}
await transport.close().catch(() => {})
}
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)}`
}
/**
* 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)
*/
export const connectToServer = memoize(
async (
name: string,
serverRef: ScopedMcpServerConfig,
serverStats?: {
totalServers: number
stdioCount: number
sseCount: number
httpCount: number
sseIdeCount: number
wsIdeCount: number
},
): Promise<MCPServerConnection> => {
const connectStartTime = Date.now()
let inProcessServer: InProcessMcpServer | undefined
try {
let transport
// 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)
// 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),
),
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.
transportOptions.eventSourceInit = {
fetch: async (url: string | URL, init?: RequestInit) => {
// Get auth headers from the auth provider
const authHeaders: Record<string, string> = {}
const tokens = await authProvider.tokens()
if (tokens) {
authHeaders.Authorization = `Bearer ${tokens.access_token}`
}
const proxyOptions = getProxyFetchOptions()
// eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
return fetch(url, {
...init,
...proxyOptions,
headers: {
'User-Agent': getMCPUserAgent(),
...authHeaders,
...init?.headers,
...combinedHeaders,
Accept: 'text/event-stream',
},
})
},
}
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 = mapValues(wsHeaders, (value, key) =>
key.toLowerCase() === 'authorization' ? '[REDACTED]' : value,
)
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())
// Use the auth provider with StreamableHTTPClientTransport
const proxyOptions = getProxyFetchOptions()
logMCPDebug(
name,
`Proxy options: ${proxyOptions.dispatcher ? 'custom dispatcher' : 'default'}`,
)
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: wrapFetchWithTimeout(
wrapFetchWithStepUpDetection(createFetchWithInit(), authProvider),
),
requestInit: {
...proxyOptions,
headers: {
'User-Agent': getMCPUserAgent(),
...(sessionIngressToken &&
!hasOAuthTokens && {
Authorization: `Bearer ${sessionIngressToken}`,
}),
...combinedHeaders,
},
},
}
// Redact sensitive headers before logging
const headersForLogging = transportOptions.requestInit?.headers
? mapValues(
transportOptions.requestInit.headers as Record<string, string>,
(value, key) =>
key.toLowerCase() === 'authorization' ? '[REDACTED]' : value,
)
: 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,
)
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 transportOptions: StreamableHTTPClientTransportOptions = {
// Wrap fetchWithAuth with fresh timeout per request
fetch: wrapFetchWithTimeout(fetchWithAuth),
requestInit: {
...proxyOptions,
headers: {
'User-Agent': getMCPUserAgent(),
'X-Mcp-Client-Session-Id': getSessionId(),
},
},
}
transport = new StreamableHTTPClientTransport(
new URL(proxyUrl),
transportOptions,
)
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) {
const finalCommand =
process.env.CLAUDE_CODE_SHELL_PREFIX || serverRef.command
const finalArgs = process.env.CLAUDE_CODE_SHELL_PREFIX
? [[serverRef.command, ...serverRef.args].join(' ')]
: serverRef.args
transport = new StdioClientTransport({
command: finalCommand,
args: finalArgs,
env: {
...subprocessEnv(),
...serverRef.env,
} as Record<string, string>,
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) => {
// Cap stderr accumulation to prevent unbounded memory growth
if (stderrOutput.length < 64 * 1024 * 1024) {
try {
stderrOutput += data.toString()
} catch {
// Ignore errors from exceeding max string length
}
}
}
stdioTransport.stderr.on('data', stderrHandler)