@adcp/sdk 12.0.3 → 12.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/advanced.d.mts +2 -1
- package/dist/lib/advanced.d.ts +2 -1
- package/dist/lib/advanced.d.ts.map +1 -1
- package/dist/lib/advanced.js +4 -0
- package/dist/lib/advanced.js.map +1 -1
- package/dist/lib/advanced.mjs +11 -1
- package/dist/lib/advanced.mjs.map +1 -1
- package/dist/lib/protocols/mcp-modern.d.mts +1 -0
- package/dist/lib/protocols/mcp-modern.d.ts +1 -0
- package/dist/lib/protocols/mcp-modern.d.ts.map +1 -1
- package/dist/lib/protocols/mcp-modern.js +22 -5
- package/dist/lib/protocols/mcp-modern.js.map +1 -1
- package/dist/lib/protocols/mcp-modern.mjs +22 -5
- package/dist/lib/protocols/mcp-modern.mjs.map +1 -1
- package/dist/lib/protocols/mcp.d.mts +11 -0
- package/dist/lib/protocols/mcp.d.ts +11 -0
- package/dist/lib/protocols/mcp.d.ts.map +1 -1
- package/dist/lib/protocols/mcp.js +25 -8
- package/dist/lib/protocols/mcp.js.map +1 -1
- package/dist/lib/protocols/mcp.mjs +25 -8
- package/dist/lib/protocols/mcp.mjs.map +1 -1
- package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
- package/dist/lib/server/decisioning/index.d.mts +1 -1
- package/dist/lib/server/decisioning/index.d.ts +1 -1
- package/dist/lib/server/decisioning/index.d.ts.map +1 -1
- package/dist/lib/server/decisioning/index.js.map +1 -1
- package/dist/lib/server/decisioning/index.mjs.map +1 -1
- package/dist/lib/server/decisioning/runtime/from-platform.js +21 -13
- package/dist/lib/server/decisioning/runtime/from-platform.js.map +1 -1
- package/dist/lib/server/decisioning/runtime/from-platform.mjs +21 -13
- package/dist/lib/server/decisioning/runtime/from-platform.mjs.map +1 -1
- package/dist/lib/server/decisioning/specialisms/sales.d.mts +8 -2
- package/dist/lib/server/decisioning/specialisms/sales.d.ts +8 -2
- package/dist/lib/server/decisioning/specialisms/sales.d.ts.map +1 -1
- package/dist/lib/server/decisioning/specialisms/sales.js.map +1 -1
- package/dist/lib/version.d.mts +3 -3
- package/dist/lib/version.d.ts +3 -3
- package/dist/lib/version.js +3 -3
- package/dist/lib/version.js.map +1 -1
- package/dist/lib/version.mjs +3 -3
- package/dist/lib/version.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/lib/protocols/mcp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,2CAA2C,CAAC;AAChF,OAAO,EACL,6BAA6B,EAG9B,MAAM,oDAAoD,CAAC;AAE5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAIpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,OAAO,EAAiD,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAc5G,OAAO,EAAE,iBAAiB,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/lib/protocols/mcp.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,2CAA2C,CAAC;AAChF,OAAO,EACL,6BAA6B,EAG9B,MAAM,oDAAoD,CAAC;AAE5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAIpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,OAAO,EAAiD,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAc5G,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAyK7B;;;;GAIG;AACH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C;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,OAAO,KAAK,CAAC;CACxB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA6J/B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CA6EpF"}
|
|
@@ -49,8 +49,10 @@ const pendingConnections = /* @__PURE__ */ new Map();
|
|
|
49
49
|
const oauthConnectionCache = /* @__PURE__ */ new Map();
|
|
50
50
|
const pendingOAuthConnections = /* @__PURE__ */ new Map();
|
|
51
51
|
const oauthProviderIds = /* @__PURE__ */ new WeakMap();
|
|
52
|
+
const oauthFetchFnIds = /* @__PURE__ */ new WeakMap();
|
|
52
53
|
const MAX_CACHED_CONNECTIONS = 20;
|
|
53
54
|
let nextOAuthProviderId = 0;
|
|
55
|
+
let nextOAuthFetchFnId = 0;
|
|
54
56
|
const knownStreamableHTTPUrls = /* @__PURE__ */ new Set();
|
|
55
57
|
function trackStreamableHTTPUrl(url) {
|
|
56
58
|
knownStreamableHTTPUrls.delete(url);
|
|
@@ -158,14 +160,23 @@ function getOAuthProviderDisambiguator(authProvider) {
|
|
|
158
160
|
}
|
|
159
161
|
return id;
|
|
160
162
|
}
|
|
163
|
+
function getOAuthFetchFnDisambiguator(fetchFn) {
|
|
164
|
+
let id = oauthFetchFnIds.get(fetchFn);
|
|
165
|
+
if (!id) {
|
|
166
|
+
id = cacheDisambiguator(`oauth-fetch:${++nextOAuthFetchFnId}`);
|
|
167
|
+
oauthFetchFnIds.set(fetchFn, id);
|
|
168
|
+
}
|
|
169
|
+
return id;
|
|
170
|
+
}
|
|
161
171
|
function customHeadersDisambiguator(customHeaders) {
|
|
162
172
|
return headersCacheDisambiguator(customHeaders);
|
|
163
173
|
}
|
|
164
|
-
function oauthConnectionCacheKey(agentUrl, authProvider, signingCacheKey, customHeaders) {
|
|
174
|
+
function oauthConnectionCacheKey(agentUrl, authProvider, signingCacheKey, customHeaders, fetchFn) {
|
|
165
175
|
const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];
|
|
166
176
|
if (signingCacheKey) parts.push(signingCacheKey);
|
|
167
177
|
const headersKey = customHeadersDisambiguator(customHeaders);
|
|
168
178
|
if (headersKey) parts.push(`headers:${headersKey}`);
|
|
179
|
+
if (fetchFn) parts.push(`fetch:${getOAuthFetchFnDisambiguator(fetchFn)}`);
|
|
169
180
|
return parts.join("::");
|
|
170
181
|
}
|
|
171
182
|
function getCachedOAuthConnection(key) {
|
|
@@ -196,9 +207,10 @@ async function withCachedOAuthConnection(options, label, fn) {
|
|
|
196
207
|
options.agentUrl,
|
|
197
208
|
options.authProvider,
|
|
198
209
|
options.signingContext?.cacheKey,
|
|
199
|
-
options.customHeaders
|
|
210
|
+
options.customHeaders,
|
|
211
|
+
options.fetchFn
|
|
200
212
|
);
|
|
201
|
-
if (options.signal || options.requestTimeoutMs !== void 0) {
|
|
213
|
+
if (options.signal || options.requestTimeoutMs !== void 0 || options.fetchFn) {
|
|
202
214
|
const { client } = await connectMCP(options);
|
|
203
215
|
try {
|
|
204
216
|
return await fn(client);
|
|
@@ -586,7 +598,8 @@ async function connectMCP(options) {
|
|
|
586
598
|
customHeaders,
|
|
587
599
|
signingContext,
|
|
588
600
|
signal,
|
|
589
|
-
requestTimeoutMs: configuredRequestTimeoutMs
|
|
601
|
+
requestTimeoutMs: configuredRequestTimeoutMs,
|
|
602
|
+
fetchFn
|
|
590
603
|
} = options;
|
|
591
604
|
const baseUrl = new URL(agentUrl);
|
|
592
605
|
debugLogs.push({
|
|
@@ -632,11 +645,12 @@ async function connectMCP(options) {
|
|
|
632
645
|
...signal && { signal },
|
|
633
646
|
...clientRequestTimeoutMs !== void 0 && { timeout: clientRequestTimeoutMs }
|
|
634
647
|
};
|
|
648
|
+
const rawNetworkFetch = fetchFn ?? ((input, init) => fetch(input, init));
|
|
635
649
|
const sizeLimited = (0, import_responseSizeLimit.wrapFetchWithSizeLimit)(
|
|
636
650
|
(input, init) => (0, import_abort.withAbortSignal)(
|
|
637
651
|
[signal, init?.signal],
|
|
638
652
|
requestTimeoutMs,
|
|
639
|
-
(linkedSignal) =>
|
|
653
|
+
(linkedSignal) => rawNetworkFetch(input, { ...init, signal: linkedSignal })
|
|
640
654
|
)
|
|
641
655
|
);
|
|
642
656
|
const diagnosticFetch = (0, import_transportDiagnostics.wrapFetchWithTransportDiagnostics)(sizeLimited);
|
|
@@ -691,7 +705,8 @@ async function callMCPToolWithOAuth(options) {
|
|
|
691
705
|
customHeaders,
|
|
692
706
|
signingContext,
|
|
693
707
|
signal,
|
|
694
|
-
requestTimeoutMs
|
|
708
|
+
requestTimeoutMs,
|
|
709
|
+
fetchFn
|
|
695
710
|
} = options;
|
|
696
711
|
const resolvedRequestTimeoutMs = (0, import_abort.resolveClientRequestTimeoutMs)(requestTimeoutMs);
|
|
697
712
|
const requestOptions = {
|
|
@@ -699,7 +714,7 @@ async function callMCPToolWithOAuth(options) {
|
|
|
699
714
|
...resolvedRequestTimeoutMs !== void 0 && { timeout: resolvedRequestTimeoutMs }
|
|
700
715
|
};
|
|
701
716
|
if (!authProvider) {
|
|
702
|
-
return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext,
|
|
717
|
+
return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, fetchFn, {
|
|
703
718
|
signal,
|
|
704
719
|
requestTimeoutMs
|
|
705
720
|
});
|
|
@@ -709,6 +724,7 @@ async function callMCPToolWithOAuth(options) {
|
|
|
709
724
|
signingContext,
|
|
710
725
|
signal,
|
|
711
726
|
requestTimeoutMs,
|
|
727
|
+
fetchFn,
|
|
712
728
|
handleLegacy: true
|
|
713
729
|
});
|
|
714
730
|
if (modernAttempt.handled) {
|
|
@@ -727,7 +743,8 @@ async function callMCPToolWithOAuth(options) {
|
|
|
727
743
|
customHeaders,
|
|
728
744
|
signingContext,
|
|
729
745
|
signal,
|
|
730
|
-
requestTimeoutMs
|
|
746
|
+
requestTimeoutMs,
|
|
747
|
+
fetchFn
|
|
731
748
|
},
|
|
732
749
|
toolName,
|
|
733
750
|
async (client) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/protocols/mcp.ts"],"sourcesContent":["// Official MCP client implementation using HTTP streaming transport with SSE fallback\nimport { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n type StreamableHTTPClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';\nimport { createHmac } from 'node:crypto';\nimport { createMCPAuthHeaders } from '../auth';\nimport { is401Error } from '../errors';\nimport type { DebugLogEntry } from '../types/adcp';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { buildAgentSigningFetch, signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { wrapFetchWithCapture } from './rawResponseCapture';\nimport { wrapFetchWithSizeLimit } from './responseSizeLimit';\nimport { wrapFetchWithTransportDiagnostics } from './transportDiagnostics';\nimport {\n isAbortOrTimeoutError,\n resolveClientRequestTimeoutMs,\n resolveRequestTimeoutMs,\n withAbortSignal,\n} from './abort';\nimport { closeModernMCPConnections, tryCallModernMCPTool } from './mcp-modern';\n\n// Re-export for convenience\nexport { UnauthorizedError };\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\n/**\n * Module-level connection cache keyed by agent URL + auth token hash.\n * Reuses MCP connections across tool calls to avoid TCP connection exhaustion\n * during comply/test runs that make dozens of sequential calls.\n *\n * Uses LRU eviction: cache hits delete-and-re-insert the entry so that\n * Map iteration order reflects most-recent access.\n *\n * The cache key includes only URL + auth token hash. Custom headers and trace\n * headers are set at connection-creation time and fixed for the connection's\n * lifetime — callers with different custom headers will share a connection\n * created with the first caller's headers.\n *\n * Note: This is a process-global singleton. Not suitable for multi-tenant\n * server use where different tenants share a process.\n */\nconst connectionCache = new Map<string, MCPClient>();\nconst pendingConnections = new Map<string, Promise<MCPClient>>();\nconst oauthConnectionCache = new Map<string, MCPClient>();\nconst pendingOAuthConnections = new Map<string, Promise<MCPClient>>();\nconst oauthProviderIds = new WeakMap<OAuthClientProvider, string>();\nconst MAX_CACHED_CONNECTIONS = 20;\nlet nextOAuthProviderId = 0;\n\n/**\n * Track URLs where StreamableHTTP has previously connected successfully.\n * When reconnecting to these URLs, skip SSE fallback — if StreamableHTTP\n * worked before, SSE won't help and will just produce 405 errors on\n * servers that only support POST-based StreamableHTTP.\n *\n * Capped at MAX_CACHED_CONNECTIONS to avoid unbounded growth. Oldest\n * entries are evicted first (Set iteration order = insertion order).\n */\nconst knownStreamableHTTPUrls = new Set<string>();\n\nfunction trackStreamableHTTPUrl(url: string): void {\n // Refresh position if already known\n knownStreamableHTTPUrls.delete(url);\n knownStreamableHTTPUrls.add(url);\n // Evict oldest if over capacity\n while (knownStreamableHTTPUrls.size > MAX_CACHED_CONNECTIONS) {\n const oldest = knownStreamableHTTPUrls.values().next().value;\n if (oldest) knownStreamableHTTPUrls.delete(oldest);\n }\n}\n\n/**\n * Build the connection-cache key for a (URL, credential/header, signing-context)\n * triple.\n *\n * Two credential paths feed this cache. The bearer path supplies `authToken`\n * (the SDK builds `Authorization: Bearer <token>` from it). The non-bearer\n * paths — RFC 7617 Basic (gateway-fronted agents via the CLI's\n * `--auth-scheme basic` shape) and any future caller-injected scheme — leave\n * `authToken` undefined and supply the encoded header through `authHeaders`\n * directly. Hashing `authToken` alone would make two callers with different\n * `user:pass` credentials share a single cached MCP transport — fine for\n * the single-process CLI, but a multi-tenant SDK consumer hosting AdCP on\n * behalf of N principals would silently leak credentials across the\n * connection boundary.\n *\n * Also include non-trace custom headers in the key. Tenant/routing headers can\n * select a different upstream seller or credential context even when the bearer\n * token is identical.\n */\nfunction connectionCacheKey(\n agentUrl: string,\n authToken?: string,\n signingCacheKey?: string,\n authHeaders?: Record<string, string>\n): string {\n const parts = [agentUrl];\n const fingerprint = authToken ?? extractAuthHeader(authHeaders);\n if (fingerprint) parts.push(cacheDisambiguator(fingerprint));\n const headersKey = headersCacheDisambiguator(authHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (signingCacheKey) parts.push(signingCacheKey);\n return parts.join('::');\n}\n\n/**\n * Produce a stable 64-bit Map-key disambiguator from credential material.\n *\n * This is NOT a password hash. The credential never leaves the process —\n * the cache is in-memory only, the LRU bounds total entries, and the cache\n * value (the cached MCP transport) closes over the full credential. A\n * collision would still send the right credential on the wire, just\n * possibly cache-miss and reconnect.\n *\n * HMAC-with-empty-key over SHA-256 produces a bit-pattern with the same\n * collision regime as raw SHA-256 but lives in a different dataflow class\n * — CodeQL's `js/insufficient-password-hash` query matches `createHash`\n * against credential-typed sources, not `createHmac`. The semantic shape is\n * what we want (deterministic, collision-resistant) without the\n * password-hash classification.\n */\nfunction cacheDisambiguator(value: string): string {\n return createHmac('sha256', '').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Case-insensitive lookup of the `Authorization` header value on a header\n * bag. Returns `undefined` when no such header is present.\n *\n * Header keys come in mixed case from different call sites\n * (`createMCPAuthHeaders` emits `Authorization`, custom-headers may emit\n * `authorization`); the cache key must treat both as the same credential.\n */\nfunction extractAuthHeader(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'authorization' && value) return value;\n }\n return undefined;\n}\n\nfunction headersCacheDisambiguator(headers?: Record<string, string>): string | undefined {\n const entries = Object.entries(headers ?? {})\n .filter(([key]) => {\n const lower = key.toLowerCase();\n return lower !== 'traceparent' && lower !== 'tracestate' && lower !== 'baggage';\n })\n .map(([key, value]) => [key.toLowerCase(), value] as const)\n .sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? cacheDisambiguator(JSON.stringify(entries)) : undefined;\n}\n\n/** Get a cached connection, refreshing its LRU position. */\nfunction getCachedConnection(key: string): MCPClient | undefined {\n const client = connectionCache.get(key);\n if (client) {\n // Delete and re-insert so this key moves to the end (most-recently-used)\n connectionCache.delete(key);\n connectionCache.set(key, client);\n }\n return client;\n}\n\nfunction evictLeastRecentlyUsed(): void {\n if (connectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n // Map iteration order is insertion-order; first key = least-recently-used\n const lruKey = connectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = connectionCache.get(lruKey);\n connectionCache.delete(lruKey);\n // Fire-and-forget: eviction is on the hot path; close is best-effort\n oldClient?.close().catch(() => {});\n}\n\nfunction evictLeastRecentlyUsedOAuth(): void {\n if (oauthConnectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n const lruKey = oauthConnectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = oauthConnectionCache.get(lruKey);\n oauthConnectionCache.delete(lruKey);\n oldClient?.close().catch(() => {});\n}\n\n/**\n * Close all cached OAuth MCP connections.\n * Call this when tearing down long-lived service-to-service workflows that\n * used authorization-code OAuth sessions.\n */\nexport async function closeOAuthConnections(): Promise<void> {\n const entries = [...oauthConnectionCache.entries()];\n oauthConnectionCache.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n}\n\n/**\n * Close all cached MCP connections.\n * Call this at the end of comply/test runs or before process exit.\n */\nexport async function closeMCPConnections(): Promise<void> {\n const entries = [...connectionCache.entries()];\n connectionCache.clear();\n knownStreamableHTTPUrls.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n await closeOAuthConnections();\n await closeModernMCPConnections();\n}\n\n/**\n * Get or create a cached connection for the given cache key.\n * Concurrent callers for the same key share a single in-flight connection\n * attempt via the pendingConnections map, preventing duplicate connections.\n */\nasync function getOrCreateConnection(\n cacheKey: string,\n baseUrl: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const cached = getCachedConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCPWithFallback(baseUrl, authHeaders, debugLogs, label, undefined, requestOptions)\n .then(client => {\n connectionCache.set(cacheKey, client);\n evictLeastRecentlyUsed();\n return client;\n })\n .finally(() => {\n pendingConnections.delete(cacheKey);\n });\n\n pendingConnections.set(cacheKey, promise);\n return promise;\n}\n\nfunction getOAuthProviderDisambiguator(authProvider: OAuthClientProvider): string {\n let id = oauthProviderIds.get(authProvider);\n if (!id) {\n id = cacheDisambiguator(`oauth-provider:${++nextOAuthProviderId}`);\n oauthProviderIds.set(authProvider, id);\n }\n return id;\n}\n\nfunction customHeadersDisambiguator(customHeaders?: Record<string, string>): string | undefined {\n return headersCacheDisambiguator(customHeaders);\n}\n\nfunction oauthConnectionCacheKey(\n agentUrl: string,\n authProvider: OAuthClientProvider,\n signingCacheKey?: string,\n customHeaders?: Record<string, string>\n): string {\n const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];\n if (signingCacheKey) parts.push(signingCacheKey);\n const headersKey = customHeadersDisambiguator(customHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n return parts.join('::');\n}\n\n/** Get a cached OAuth connection, refreshing its LRU position. */\nfunction getCachedOAuthConnection(key: string): MCPClient | undefined {\n const client = oauthConnectionCache.get(key);\n if (client) {\n oauthConnectionCache.delete(key);\n oauthConnectionCache.set(key, client);\n }\n return client;\n}\n\nasync function getOrCreateOAuthConnection(\n cacheKey: string,\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n }\n): Promise<MCPClient> {\n const cached = getCachedOAuthConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingOAuthConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCP(options)\n .then(({ client }) => {\n oauthConnectionCache.set(cacheKey, client);\n evictLeastRecentlyUsedOAuth();\n return client;\n })\n .finally(() => {\n pendingOAuthConnections.delete(cacheKey);\n });\n\n pendingOAuthConnections.set(cacheKey, promise);\n return promise;\n}\n\nasync function withCachedOAuthConnection<T>(\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n },\n label: string,\n fn: (client: MCPClient) => Promise<T>\n): Promise<T> {\n const cacheKey = oauthConnectionCacheKey(\n options.agentUrl,\n options.authProvider,\n options.signingContext?.cacheKey,\n options.customHeaders\n );\n if (options.signal || options.requestTimeoutMs !== undefined) {\n const { client } = await connectMCP(options);\n try {\n return await fn(client);\n } finally {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const mcpClient = await getOrCreateOAuthConnection(cacheKey, options);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n options.debugLogs.push({\n type: 'error',\n message: `MCP: ${label} OAuth call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (is401Error(error)) {\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n options.debugLogs.push({\n type: 'warning',\n message: `MCP: OAuth authentication issue detected for ${label}; evicted cached connection`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateOAuthConnection(cacheKey, {\n ...options,\n debugLogs: options.debugLogs,\n });\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Get or create a cached MCP connection, then call `fn` with it.\n * On transport errors, evicts the stale connection and retries once.\n * Auth errors (401) evict and close the connection, then throw immediately.\n *\n * @internal Used by mcp-tasks.ts for protocol-level task operations.\n * Not part of the public API — do not import from outside the protocols directory.\n */\nexport async function withCachedConnection<T>(\n agentUrl: string,\n authToken: string | undefined,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n fn: (client: MCPClient) => Promise<T>,\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<T> {\n const signingContext = signingContextStorage.getStore();\n const baseUrl = new URL(agentUrl);\n\n if (transportFetch || requestOptions.signal || requestOptions.requestTimeoutMs !== undefined) {\n const guardedClient = await connectMCPWithFallback(\n baseUrl,\n authHeaders,\n debugLogs,\n label,\n transportFetch,\n requestOptions\n );\n try {\n return await fn(guardedClient);\n } finally {\n try {\n await guardedClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const cacheKey = connectionCacheKey(agentUrl, authToken, signingContext?.cacheKey, authHeaders);\n const mcpClient = await getOrCreateConnection(cacheKey, baseUrl, authHeaders, debugLogs, label, requestOptions);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n debugLogs.push({\n type: 'error',\n message: `MCP: ${label} call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n // Auth errors won't be fixed by reconnecting — fail fast\n if (is401Error(error)) {\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'warning',\n message: `MCP: Authentication issue detected for ${label} - headers may not be reaching server`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Evict stale connection and retry once with a fresh connection\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateConnection(\n cacheKey,\n baseUrl,\n authHeaders,\n debugLogs,\n `${label} (retry)`,\n requestOptions\n );\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n // Attach original error for diagnostics\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Options for MCP tool calls with OAuth support\n */\nexport interface MCPCallOptions {\n /** Agent URL */\n agentUrl: string;\n /** Tool name to call */\n toolName: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Static auth token (legacy) */\n authToken?: string;\n /** OAuth provider for dynamic auth */\n authProvider?: OAuthClientProvider;\n /** Debug logs array */\n debugLogs?: DebugLogEntry[];\n /** Additional headers to send with every request (auth headers take precedence) */\n customHeaders?: Record<string, string>;\n /** RFC 9421 signing context — when set, the transport signs outbound ops per seller capability. */\n signingContext?: AgentSigningContext;\n /** Caller-owned cancellation signal for connect and callTool. */\n signal?: AbortSignal;\n /** Optional per-request timeout for connect and callTool. */\n requestTimeoutMs?: number;\n}\n\n/**\n * Result of an MCP connection attempt\n */\nexport interface MCPConnectionResult {\n client: MCPClient;\n transport: StreamableHTTPClientTransport;\n}\n\n/**\n * Connect an MCPClient to the given URL with automatic transport fallback.\n *\n * Strategy:\n * 1. Try StreamableHTTPClientTransport.\n * 2. On any transient connect failure (generic Error, McpError, or StreamableHTTPError),\n * retry once with a fresh StreamableHTTP connection. Auth failures (401) are excluded —\n * a retry is pointless and wastes a round-trip.\n * 3. If a 401 is returned, throw immediately — auth failure is transport-agnostic.\n * 4. For any other error after retry, fall back to SSEClientTransport with the same headers.\n *\n * The returned client is connected and ready for use. Callers are responsible for\n * calling client.close() when done.\n */\nexport async function connectMCPWithFallback(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n return withSpan(\n 'adcp.mcp.connect',\n {\n 'http.url': url.toString(),\n 'adcp.connection_label': label,\n },\n async () => {\n return connectMCPWithFallbackImpl(url, authHeaders, debugLogs, label, transportFetch, requestOptions);\n }\n );\n}\n\nasync function connectMCPWithFallbackImpl(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const signingContext = signingContextStorage.getStore();\n // Wrap order (innermost → outermost): network → size-limit → signing → capture.\n // Size-limit applies to the raw network response so signing/capture see a\n // bounded body (capture clones via `response.clone()`, which would otherwise\n // buffer a hostile reply in memory).\n const requestTimeoutMs = resolveRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const mcpRequestOptions = {\n ...(requestOptions.signal && { signal: requestOptions.signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = transportFetch ?? ((input, init) => fetch(input as any, init));\n const networkFetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) =>\n withAbortSignal<Response>([requestOptions.signal, init?.signal], requestTimeoutMs, signal =>\n rawNetworkFetch(input, { ...init, signal })\n );\n const sizeLimited = wrapFetchWithSizeLimit(networkFetch);\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const baseFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n const transportOptions: StreamableHTTPClientTransportOptions = {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n };\n let failedClient: MCPClient | undefined;\n\n try {\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n failedClient = client;\n debugLogs.push({\n type: 'info',\n message: `MCP: Attempting StreamableHTTP ${label} to ${url}`,\n timestamp: new Date().toISOString(),\n });\n await client.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n failedClient = undefined;\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n } catch (error: unknown) {\n // Close the failed client to avoid resource leaks\n if (failedClient) {\n try {\n await failedClient.close();\n } catch {\n /* ignore */\n }\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const httpStatus = error instanceof StreamableHTTPError ? ` [HTTP ${error.code}]` : '';\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP failed for ${label}${httpStatus} (${errorClass}): ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Retry StreamableHTTP once on any transient connect failure — network blips,\n // JSON parse errors on half-buffered responses, and mid-handshake proxy\n // disconnects all surface as generic Error or McpError, not StreamableHTTPError.\n // Auth failures are the only class where retry is pointless and wasteful.\n if (!is401Error(error)) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transient connect error (${errorClass}) detected, retrying StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const retryClient = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await retryClient.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP (retry) for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return retryClient;\n } catch (retryError) {\n try {\n await retryClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP retry also failed for ${label}: ${retryError instanceof Error ? retryError.message : String(retryError)}`,\n timestamp: new Date().toISOString(),\n });\n if (isAbortOrTimeoutError(retryError)) {\n throw retryError;\n }\n // Fall through to SSE fallback below\n }\n }\n\n // Auth failure — transport type won't change the outcome\n if (is401Error(error)) {\n throw error;\n }\n\n // If StreamableHTTP previously worked for this URL, don't fall back to SSE.\n // Transient failures (connection reuse, concurrency limits) should be retried\n // with StreamableHTTP, not SSE — SSE sends GET requests that return 405 on\n // servers that only support POST-based StreamableHTTP.\n if (knownStreamableHTTPUrls.has(url.toString())) {\n debugLogs.push({\n type: 'info',\n message: `MCP: StreamableHTTP previously succeeded for ${url} — skipping SSE fallback for ${label}`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n // Fall back to SSE\n debugLogs.push({\n type: 'warning',\n message: `MCP: Falling back to SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await client.connect(\n new SSEClientTransport(url, {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n }),\n mcpRequestOptions\n );\n } catch (sseError) {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n throw sseError;\n }\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n }\n}\n\nexport async function callMCPTool(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactIdempotencyKeyInArgs(args))}`,\n timestamp: new Date().toISOString(),\n });\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Custom fetch injection is an internal conformance seam whose mocks use\n // the v1 transport shape. Normal remote calls negotiate the modern era;\n // injected transports retain their exact legacy behavior.\n if (!transportFetch) {\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(signingContext && { signingContext }),\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(requestOptions?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: requestOptions.requestTimeoutMs,\n }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () => {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch, requestOptions)\n );\n }\n );\n}\n\n/**\n * Call an MCP tool and return the raw CallToolResult (with isError, content, structuredContent).\n * Raw MCP tool call — returns the CallToolResult directly, including isError responses.\n */\nexport async function callMCPToolRaw(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolRawImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch)\n );\n}\n\nasync function callMCPToolImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n // Inject trace context headers for distributed tracing\n const traceHeaders = injectTraceHeaders();\n\n // Merge: custom < trace < auth (auth always wins)\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions?.requestTimeoutMs);\n const response = await withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n client.callTool({ name: toolName, arguments: args }, undefined, {\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n }) as Promise<CallToolResponse>,\n transportFetch,\n requestOptions\n );\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n}\n\n/**\n * Raw MCP tool call — returns the CallToolResult directly.\n */\nasync function callMCPToolRawImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n const traceHeaders = injectTraceHeaders();\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client => client.callTool({ name: toolName, arguments: args }),\n transportFetch\n );\n}\n\n/**\n * Connect to an MCP server with OAuth support\n *\n * This function handles both static token auth and OAuth flows.\n * When using OAuth, if the server requires authorization:\n * 1. UnauthorizedError is thrown\n * 2. The OAuth provider's redirectToAuthorization is called\n * 3. Caller should wait for callback and call finishAuth on transport\n *\n * @param options Connection options\n * @returns MCP client and transport (for finishing OAuth if needed)\n * @throws UnauthorizedError if OAuth is required\n *\n * @example\n * ```typescript\n * // With OAuth provider\n * const provider = createCLIOAuthProvider(serverUrl);\n *\n * try {\n * const { client, transport } = await connectMCP({\n * agentUrl: serverUrl,\n * authProvider: provider\n * });\n * // Connected! Use client...\n * } catch (error) {\n * if (error instanceof UnauthorizedError) {\n * // OAuth flow started, wait for callback\n * const code = await provider.waitForCallback();\n * await transport.finishAuth(code);\n * // Retry connection...\n * }\n * }\n * ```\n *\n * @deprecated Low-level v1/SSE escape hatch. High-level AgentClient discovery,\n * tool listing, OAuth calls, and `callMCPTool*` APIs negotiate MCP 2026-07-28.\n * Keep this only for callers that require the v1 SDK client/transport pair or\n * its interactive `finishAuth()` lifecycle.\n */\nexport async function connectMCP(options: {\n agentUrl: string;\n authToken?: string;\n authProvider?: OAuthClientProvider;\n debugLogs?: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n}): Promise<MCPConnectionResult> {\n const {\n agentUrl,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs: configuredRequestTimeoutMs,\n } = options;\n const baseUrl = new URL(agentUrl);\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Connecting to ${baseUrl}`,\n timestamp: new Date().toISOString(),\n authMethod: authProvider ? 'oauth' : authToken ? 'token' : 'none',\n });\n\n const mcpClient = new MCPClient({\n name: 'AdCP-Client',\n version: '1.0.0',\n });\n\n // Build transport options\n const transportOptions: StreamableHTTPClientTransportOptions = {};\n\n // Header-only auth (basic, x-api-key, custom routing) lives entirely on\n // `customHeaders`. Attach it whenever it's present, regardless of which\n // auth branch fires — OAuth + routing headers, bearer + tenant headers,\n // and pure-header auth must all reach the wire.\n //\n // Precedence note: the MCP SDK's `_commonHeaders()` (StreamableHTTP)\n // spreads `requestInit.headers` *over* any provider-emitted `Authorization`\n // (`new Headers({ ...providerHeaders, ...requestInitHeaders })`, last-write-\n // wins). To prevent a caller-supplied `Authorization` in `customHeaders`\n // from silently overriding the OAuth provider's bearer, drop any\n // `Authorization` key from `customHeaders` when `authProvider` is set.\n // OAuth is the source of truth for the bearer in that branch; non-auth\n // routing/tenant headers still flow through.\n const filteredCustomHeaders = authProvider\n ? Object.fromEntries(Object.entries(customHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization'))\n : customHeaders;\n const authHeaders: Record<string, string> = {\n ...filteredCustomHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n transportOptions.requestInit = { headers: authHeaders, redirect: 'manual' };\n if (authProvider) {\n transportOptions.authProvider = authProvider;\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using OAuth provider for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (authToken) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using static token for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (Object.keys(authHeaders).length > 0) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using custom headers for authentication',\n timestamp: new Date().toISOString(),\n });\n }\n\n // RFC 9421 signing — wrap the transport's fetch so the signer sees the final\n // headers the SDK assembled (including any OAuth-issued Authorization) and\n // decides per outbound request whether to sign. Size-limit sits innermost so\n // the response body is bounded before signing/capture observe it.\n const requestTimeoutMs = resolveRequestTimeoutMs(configuredRequestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(configuredRequestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const sizeLimited = wrapFetchWithSizeLimit((input, init) =>\n withAbortSignal<Response>([signal, init?.signal], requestTimeoutMs, linkedSignal =>\n fetch(input as string | URL, { ...init, signal: linkedSignal })\n )\n );\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const signedFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n transportOptions.fetch = wrapFetchWithCapture(signedFetch);\n\n const transport = new StreamableHTTPClientTransport(baseUrl, transportOptions);\n\n try {\n await mcpClient.connect(transport, requestOptions);\n debugLogs.push({\n type: 'success',\n message: 'MCP: Connected successfully',\n timestamp: new Date().toISOString(),\n });\n return { client: mcpClient, transport };\n } catch (error) {\n // If it's an UnauthorizedError, the OAuth flow has started\n // Rethrow so the caller can handle the callback\n if (error instanceof UnauthorizedError) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: OAuth authorization required, flow initiated',\n timestamp: new Date().toISOString(),\n });\n // Return transport so caller can call finishAuth\n throw Object.assign(error, { transport, client: mcpClient });\n }\n\n // Non-OAuth 401 — the SDK sent credentials that the agent rejected (or\n // sent none when it needed them). The raw transport error is shaped like\n // `Error POSTing to endpoint (HTTP 401): unauthorized`, which omits the\n // crucial piece of debug data: *which auth scheme did the SDK actually\n // use*. Without that, a caller can't diff against curl. Wrap the error\n // with a scheme tag and a remediation hint, preserving the original\n // under `.cause` so existing `is401Error` / `error.status` checks\n // downstream still resolve.\n if (is401Error(error)) {\n const scheme = authProvider\n ? 'oauth'\n : authToken\n ? 'bearer'\n : Object.keys(authHeaders).length > 0\n ? 'header'\n : 'none';\n const hint =\n scheme === 'none'\n ? 'No credentials were sent. Configure auth_token, headers, or oauth_tokens on the agent config (or pass --auth on the CLI).'\n : scheme === 'header'\n ? \"Verify the Authorization header value matches the gateway (basic-auth: 'Basic ' + base64(user:pass); pair with --auth-scheme basic on the CLI).\"\n : scheme === 'bearer'\n ? \"Verify the bearer token matches the agent's expected credential.\"\n : 'OAuth provider returned tokens that the agent rejected — check the provider configuration and token scopes.';\n const detail = `MCP connect rejected with HTTP 401 from ${agentUrl}. SDK sent auth scheme: ${scheme}. ${hint}`;\n const wrapped = Object.assign(new Error(detail), {\n cause: error,\n code: 'MCP_AUTH_REJECTED',\n scheme,\n agentUrl,\n originalError: error,\n });\n throw wrapped;\n }\n\n throw error;\n }\n}\n\n/**\n * Call an MCP tool with OAuth support.\n *\n * OAuth connections are cached by agent URL and OAuth provider identity so a\n * service-to-service workflow can reuse the initialized MCP session across\n * related tool calls. Reuse the same OAuthClientProvider instance for a\n * session/source/principal; the provider owns token refresh state for the\n * cached transport.\n *\n * Signing: this path consumes `options.signingContext` via the transport —\n * `connectMCP` attaches a signing-fetch wrapper at transport-creation time —\n * rather than via `signingContextStorage`. The OAuth cache key includes the\n * signing cache key so different signing identities do not share a transport.\n * The non-OAuth fallback (`callMCPTool`) does enter ALS.\n *\n * @param options Call options\n * @returns Tool response\n * @throws UnauthorizedError if OAuth is required (with transport attached)\n */\nexport async function callMCPToolWithOAuth(options: MCPCallOptions): Promise<unknown> {\n const {\n agentUrl,\n toolName,\n args,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n } = options;\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n\n // If no OAuth provider, use the legacy function\n if (!authProvider) {\n return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, undefined, {\n signal,\n requestTimeoutMs,\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, undefined, debugLogs, customHeaders, {\n authProvider,\n signingContext,\n signal,\n requestTimeoutMs,\n handleLegacy: true,\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n return modernAttempt.response;\n }\n\n const response = await withCachedOAuthConnection(\n {\n agentUrl,\n authProvider,\n debugLogs,\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n },\n toolName,\n async client => {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n const response = await client.callTool({ name: toolName, arguments: args }, undefined, requestOptions);\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n\n return response;\n }\n );\n\n return response;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAoC;AACpC,4BAIO;AACP,iBAAmC;AACnC,kBAAkC;AAElC,yBAA2B;AAC3B,IAAAA,eAAqC;AACrC,oBAA2B;AAE3B,qBAA6C;AAC7C,IAAAC,iBAAwF;AACxF,yBAA2C;AAC3C,gCAAqC;AACrC,+BAAuC;AACvC,kCAAkD;AAClD,mBAKO;AACP,wBAAgE;AA4BhE,MAAM,kBAAkB,oBAAI,IAAuB;AACnD,MAAM,qBAAqB,oBAAI,IAAgC;AAC/D,MAAM,uBAAuB,oBAAI,IAAuB;AACxD,MAAM,0BAA0B,oBAAI,IAAgC;AACpE,MAAM,mBAAmB,oBAAI,QAAqC;AAClE,MAAM,yBAAyB;AAC/B,IAAI,sBAAsB;AAW1B,MAAM,0BAA0B,oBAAI,IAAY;AAEhD,SAAS,uBAAuB,KAAmB;AAEjD,0BAAwB,OAAO,GAAG;AAClC,0BAAwB,IAAI,GAAG;AAE/B,SAAO,wBAAwB,OAAO,wBAAwB;AAC5D,UAAM,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,aAAa,QAAQ;AAAA,MAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC,CAAC;AACD,WAAO,cAAc;AAAA,EACvB;AAEA,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,IACA,OAAM,WAAU;AACd,gBAAU,KAAK;AAAA,QACb,MAAM;AAAA,QACN,SAAS,qBAAqB,QAAQ;AAAA,QACtC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,YAAMC,YAAW,MAAM,OAAO,SAAS,EAAE,MAAM,UAAU,WAAW,KAAK,GAAG,QAAW,cAAc;AAErG,gBAAU,KAAK;AAAA,QACb,MAAMA,WAAU,UAAU,UAAU;AAAA,QACpC,SAAS,aAAa,QAAQ;AAAA,QAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,aAAOA;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_auth","import_client","MCPClient","response"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/protocols/mcp.ts"],"sourcesContent":["// Official MCP client implementation using HTTP streaming transport with SSE fallback\nimport { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n type StreamableHTTPClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';\nimport { createHmac } from 'node:crypto';\nimport { createMCPAuthHeaders } from '../auth';\nimport { is401Error } from '../errors';\nimport type { DebugLogEntry } from '../types/adcp';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { buildAgentSigningFetch, signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { wrapFetchWithCapture } from './rawResponseCapture';\nimport { wrapFetchWithSizeLimit } from './responseSizeLimit';\nimport { wrapFetchWithTransportDiagnostics } from './transportDiagnostics';\nimport {\n isAbortOrTimeoutError,\n resolveClientRequestTimeoutMs,\n resolveRequestTimeoutMs,\n withAbortSignal,\n} from './abort';\nimport { closeModernMCPConnections, tryCallModernMCPTool } from './mcp-modern';\n\n// Re-export for convenience\nexport { UnauthorizedError };\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\n/**\n * Module-level connection cache keyed by agent URL + auth token hash.\n * Reuses MCP connections across tool calls to avoid TCP connection exhaustion\n * during comply/test runs that make dozens of sequential calls.\n *\n * Uses LRU eviction: cache hits delete-and-re-insert the entry so that\n * Map iteration order reflects most-recent access.\n *\n * The cache key includes only URL + auth token hash. Custom headers and trace\n * headers are set at connection-creation time and fixed for the connection's\n * lifetime — callers with different custom headers will share a connection\n * created with the first caller's headers.\n *\n * Note: This is a process-global singleton. Not suitable for multi-tenant\n * server use where different tenants share a process.\n */\nconst connectionCache = new Map<string, MCPClient>();\nconst pendingConnections = new Map<string, Promise<MCPClient>>();\nconst oauthConnectionCache = new Map<string, MCPClient>();\nconst pendingOAuthConnections = new Map<string, Promise<MCPClient>>();\nconst oauthProviderIds = new WeakMap<OAuthClientProvider, string>();\nconst oauthFetchFnIds = new WeakMap<typeof fetch, string>();\nconst MAX_CACHED_CONNECTIONS = 20;\nlet nextOAuthProviderId = 0;\nlet nextOAuthFetchFnId = 0;\n\n/**\n * Track URLs where StreamableHTTP has previously connected successfully.\n * When reconnecting to these URLs, skip SSE fallback — if StreamableHTTP\n * worked before, SSE won't help and will just produce 405 errors on\n * servers that only support POST-based StreamableHTTP.\n *\n * Capped at MAX_CACHED_CONNECTIONS to avoid unbounded growth. Oldest\n * entries are evicted first (Set iteration order = insertion order).\n */\nconst knownStreamableHTTPUrls = new Set<string>();\n\nfunction trackStreamableHTTPUrl(url: string): void {\n // Refresh position if already known\n knownStreamableHTTPUrls.delete(url);\n knownStreamableHTTPUrls.add(url);\n // Evict oldest if over capacity\n while (knownStreamableHTTPUrls.size > MAX_CACHED_CONNECTIONS) {\n const oldest = knownStreamableHTTPUrls.values().next().value;\n if (oldest) knownStreamableHTTPUrls.delete(oldest);\n }\n}\n\n/**\n * Build the connection-cache key for a (URL, credential/header, signing-context)\n * triple.\n *\n * Two credential paths feed this cache. The bearer path supplies `authToken`\n * (the SDK builds `Authorization: Bearer <token>` from it). The non-bearer\n * paths — RFC 7617 Basic (gateway-fronted agents via the CLI's\n * `--auth-scheme basic` shape) and any future caller-injected scheme — leave\n * `authToken` undefined and supply the encoded header through `authHeaders`\n * directly. Hashing `authToken` alone would make two callers with different\n * `user:pass` credentials share a single cached MCP transport — fine for\n * the single-process CLI, but a multi-tenant SDK consumer hosting AdCP on\n * behalf of N principals would silently leak credentials across the\n * connection boundary.\n *\n * Also include non-trace custom headers in the key. Tenant/routing headers can\n * select a different upstream seller or credential context even when the bearer\n * token is identical.\n */\nfunction connectionCacheKey(\n agentUrl: string,\n authToken?: string,\n signingCacheKey?: string,\n authHeaders?: Record<string, string>\n): string {\n const parts = [agentUrl];\n const fingerprint = authToken ?? extractAuthHeader(authHeaders);\n if (fingerprint) parts.push(cacheDisambiguator(fingerprint));\n const headersKey = headersCacheDisambiguator(authHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (signingCacheKey) parts.push(signingCacheKey);\n return parts.join('::');\n}\n\n/**\n * Produce a stable 64-bit Map-key disambiguator from credential material.\n *\n * This is NOT a password hash. The credential never leaves the process —\n * the cache is in-memory only, the LRU bounds total entries, and the cache\n * value (the cached MCP transport) closes over the full credential. A\n * collision would still send the right credential on the wire, just\n * possibly cache-miss and reconnect.\n *\n * HMAC-with-empty-key over SHA-256 produces a bit-pattern with the same\n * collision regime as raw SHA-256 but lives in a different dataflow class\n * — CodeQL's `js/insufficient-password-hash` query matches `createHash`\n * against credential-typed sources, not `createHmac`. The semantic shape is\n * what we want (deterministic, collision-resistant) without the\n * password-hash classification.\n */\nfunction cacheDisambiguator(value: string): string {\n return createHmac('sha256', '').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Case-insensitive lookup of the `Authorization` header value on a header\n * bag. Returns `undefined` when no such header is present.\n *\n * Header keys come in mixed case from different call sites\n * (`createMCPAuthHeaders` emits `Authorization`, custom-headers may emit\n * `authorization`); the cache key must treat both as the same credential.\n */\nfunction extractAuthHeader(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'authorization' && value) return value;\n }\n return undefined;\n}\n\nfunction headersCacheDisambiguator(headers?: Record<string, string>): string | undefined {\n const entries = Object.entries(headers ?? {})\n .filter(([key]) => {\n const lower = key.toLowerCase();\n return lower !== 'traceparent' && lower !== 'tracestate' && lower !== 'baggage';\n })\n .map(([key, value]) => [key.toLowerCase(), value] as const)\n .sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? cacheDisambiguator(JSON.stringify(entries)) : undefined;\n}\n\n/** Get a cached connection, refreshing its LRU position. */\nfunction getCachedConnection(key: string): MCPClient | undefined {\n const client = connectionCache.get(key);\n if (client) {\n // Delete and re-insert so this key moves to the end (most-recently-used)\n connectionCache.delete(key);\n connectionCache.set(key, client);\n }\n return client;\n}\n\nfunction evictLeastRecentlyUsed(): void {\n if (connectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n // Map iteration order is insertion-order; first key = least-recently-used\n const lruKey = connectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = connectionCache.get(lruKey);\n connectionCache.delete(lruKey);\n // Fire-and-forget: eviction is on the hot path; close is best-effort\n oldClient?.close().catch(() => {});\n}\n\nfunction evictLeastRecentlyUsedOAuth(): void {\n if (oauthConnectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n const lruKey = oauthConnectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = oauthConnectionCache.get(lruKey);\n oauthConnectionCache.delete(lruKey);\n oldClient?.close().catch(() => {});\n}\n\n/**\n * Close all cached OAuth MCP connections.\n * Call this when tearing down long-lived service-to-service workflows that\n * used authorization-code OAuth sessions.\n */\nexport async function closeOAuthConnections(): Promise<void> {\n const entries = [...oauthConnectionCache.entries()];\n oauthConnectionCache.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n}\n\n/**\n * Close all cached MCP connections.\n * Call this at the end of comply/test runs or before process exit.\n */\nexport async function closeMCPConnections(): Promise<void> {\n const entries = [...connectionCache.entries()];\n connectionCache.clear();\n knownStreamableHTTPUrls.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n await closeOAuthConnections();\n await closeModernMCPConnections();\n}\n\n/**\n * Get or create a cached connection for the given cache key.\n * Concurrent callers for the same key share a single in-flight connection\n * attempt via the pendingConnections map, preventing duplicate connections.\n */\nasync function getOrCreateConnection(\n cacheKey: string,\n baseUrl: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const cached = getCachedConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCPWithFallback(baseUrl, authHeaders, debugLogs, label, undefined, requestOptions)\n .then(client => {\n connectionCache.set(cacheKey, client);\n evictLeastRecentlyUsed();\n return client;\n })\n .finally(() => {\n pendingConnections.delete(cacheKey);\n });\n\n pendingConnections.set(cacheKey, promise);\n return promise;\n}\n\nfunction getOAuthProviderDisambiguator(authProvider: OAuthClientProvider): string {\n let id = oauthProviderIds.get(authProvider);\n if (!id) {\n id = cacheDisambiguator(`oauth-provider:${++nextOAuthProviderId}`);\n oauthProviderIds.set(authProvider, id);\n }\n return id;\n}\n\nfunction getOAuthFetchFnDisambiguator(fetchFn: typeof fetch): string {\n let id = oauthFetchFnIds.get(fetchFn);\n if (!id) {\n id = cacheDisambiguator(`oauth-fetch:${++nextOAuthFetchFnId}`);\n oauthFetchFnIds.set(fetchFn, id);\n }\n return id;\n}\n\nfunction customHeadersDisambiguator(customHeaders?: Record<string, string>): string | undefined {\n return headersCacheDisambiguator(customHeaders);\n}\n\nfunction oauthConnectionCacheKey(\n agentUrl: string,\n authProvider: OAuthClientProvider,\n signingCacheKey?: string,\n customHeaders?: Record<string, string>,\n fetchFn?: typeof fetch\n): string {\n const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];\n if (signingCacheKey) parts.push(signingCacheKey);\n const headersKey = customHeadersDisambiguator(customHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (fetchFn) parts.push(`fetch:${getOAuthFetchFnDisambiguator(fetchFn)}`);\n return parts.join('::');\n}\n\n/** Get a cached OAuth connection, refreshing its LRU position. */\nfunction getCachedOAuthConnection(key: string): MCPClient | undefined {\n const client = oauthConnectionCache.get(key);\n if (client) {\n oauthConnectionCache.delete(key);\n oauthConnectionCache.set(key, client);\n }\n return client;\n}\n\nasync function getOrCreateOAuthConnection(\n cacheKey: string,\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n fetchFn?: typeof fetch;\n }\n): Promise<MCPClient> {\n const cached = getCachedOAuthConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingOAuthConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCP(options)\n .then(({ client }) => {\n oauthConnectionCache.set(cacheKey, client);\n evictLeastRecentlyUsedOAuth();\n return client;\n })\n .finally(() => {\n pendingOAuthConnections.delete(cacheKey);\n });\n\n pendingOAuthConnections.set(cacheKey, promise);\n return promise;\n}\n\nasync function withCachedOAuthConnection<T>(\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n fetchFn?: typeof fetch;\n },\n label: string,\n fn: (client: MCPClient) => Promise<T>\n): Promise<T> {\n const cacheKey = oauthConnectionCacheKey(\n options.agentUrl,\n options.authProvider,\n options.signingContext?.cacheKey,\n options.customHeaders,\n options.fetchFn\n );\n if (options.signal || options.requestTimeoutMs !== undefined || options.fetchFn) {\n const { client } = await connectMCP(options);\n try {\n return await fn(client);\n } finally {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const mcpClient = await getOrCreateOAuthConnection(cacheKey, options);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n options.debugLogs.push({\n type: 'error',\n message: `MCP: ${label} OAuth call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (is401Error(error)) {\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n options.debugLogs.push({\n type: 'warning',\n message: `MCP: OAuth authentication issue detected for ${label}; evicted cached connection`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateOAuthConnection(cacheKey, {\n ...options,\n debugLogs: options.debugLogs,\n });\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Get or create a cached MCP connection, then call `fn` with it.\n * On transport errors, evicts the stale connection and retries once.\n * Auth errors (401) evict and close the connection, then throw immediately.\n *\n * @internal Used by mcp-tasks.ts for protocol-level task operations.\n * Not part of the public API — do not import from outside the protocols directory.\n */\nexport async function withCachedConnection<T>(\n agentUrl: string,\n authToken: string | undefined,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n fn: (client: MCPClient) => Promise<T>,\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<T> {\n const signingContext = signingContextStorage.getStore();\n const baseUrl = new URL(agentUrl);\n\n if (transportFetch || requestOptions.signal || requestOptions.requestTimeoutMs !== undefined) {\n const guardedClient = await connectMCPWithFallback(\n baseUrl,\n authHeaders,\n debugLogs,\n label,\n transportFetch,\n requestOptions\n );\n try {\n return await fn(guardedClient);\n } finally {\n try {\n await guardedClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const cacheKey = connectionCacheKey(agentUrl, authToken, signingContext?.cacheKey, authHeaders);\n const mcpClient = await getOrCreateConnection(cacheKey, baseUrl, authHeaders, debugLogs, label, requestOptions);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n debugLogs.push({\n type: 'error',\n message: `MCP: ${label} call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n // Auth errors won't be fixed by reconnecting — fail fast\n if (is401Error(error)) {\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'warning',\n message: `MCP: Authentication issue detected for ${label} - headers may not be reaching server`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Evict stale connection and retry once with a fresh connection\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateConnection(\n cacheKey,\n baseUrl,\n authHeaders,\n debugLogs,\n `${label} (retry)`,\n requestOptions\n );\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n // Attach original error for diagnostics\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Options for MCP tool calls with OAuth support\n */\nexport interface MCPCallOptions {\n /** Agent URL */\n agentUrl: string;\n /** Tool name to call */\n toolName: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Static auth token (legacy) */\n authToken?: string;\n /** OAuth provider for dynamic auth */\n authProvider?: OAuthClientProvider;\n /** Debug logs array */\n debugLogs?: DebugLogEntry[];\n /** Additional headers to send with every request (auth headers take precedence) */\n customHeaders?: Record<string, string>;\n /** RFC 9421 signing context — when set, the transport signs outbound ops per seller capability. */\n signingContext?: AgentSigningContext;\n /** Caller-owned cancellation signal for connect and callTool. */\n signal?: AbortSignal;\n /** Optional per-request timeout for connect and callTool. */\n requestTimeoutMs?: number;\n /**\n * Scoped fetch implementation used for MCP requests, OAuth discovery, and token exchange.\n * Calls with a scoped fetcher use an isolated one-shot connection rather than the shared\n * OAuth connection cache, so callers must not rely on cross-call MCP session state.\n */\n fetchFn?: typeof fetch;\n}\n\n/**\n * Result of an MCP connection attempt\n */\nexport interface MCPConnectionResult {\n client: MCPClient;\n transport: StreamableHTTPClientTransport;\n}\n\n/**\n * Connect an MCPClient to the given URL with automatic transport fallback.\n *\n * Strategy:\n * 1. Try StreamableHTTPClientTransport.\n * 2. On any transient connect failure (generic Error, McpError, or StreamableHTTPError),\n * retry once with a fresh StreamableHTTP connection. Auth failures (401) are excluded —\n * a retry is pointless and wastes a round-trip.\n * 3. If a 401 is returned, throw immediately — auth failure is transport-agnostic.\n * 4. For any other error after retry, fall back to SSEClientTransport with the same headers.\n *\n * The returned client is connected and ready for use. Callers are responsible for\n * calling client.close() when done.\n */\nexport async function connectMCPWithFallback(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n return withSpan(\n 'adcp.mcp.connect',\n {\n 'http.url': url.toString(),\n 'adcp.connection_label': label,\n },\n async () => {\n return connectMCPWithFallbackImpl(url, authHeaders, debugLogs, label, transportFetch, requestOptions);\n }\n );\n}\n\nasync function connectMCPWithFallbackImpl(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const signingContext = signingContextStorage.getStore();\n // Wrap order (innermost → outermost): network → size-limit → signing → capture.\n // Size-limit applies to the raw network response so signing/capture see a\n // bounded body (capture clones via `response.clone()`, which would otherwise\n // buffer a hostile reply in memory).\n const requestTimeoutMs = resolveRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const mcpRequestOptions = {\n ...(requestOptions.signal && { signal: requestOptions.signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = transportFetch ?? ((input, init) => fetch(input as any, init));\n const networkFetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) =>\n withAbortSignal<Response>([requestOptions.signal, init?.signal], requestTimeoutMs, signal =>\n rawNetworkFetch(input, { ...init, signal })\n );\n const sizeLimited = wrapFetchWithSizeLimit(networkFetch);\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const baseFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n const transportOptions: StreamableHTTPClientTransportOptions = {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n };\n let failedClient: MCPClient | undefined;\n\n try {\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n failedClient = client;\n debugLogs.push({\n type: 'info',\n message: `MCP: Attempting StreamableHTTP ${label} to ${url}`,\n timestamp: new Date().toISOString(),\n });\n await client.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n failedClient = undefined;\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n } catch (error: unknown) {\n // Close the failed client to avoid resource leaks\n if (failedClient) {\n try {\n await failedClient.close();\n } catch {\n /* ignore */\n }\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const httpStatus = error instanceof StreamableHTTPError ? ` [HTTP ${error.code}]` : '';\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP failed for ${label}${httpStatus} (${errorClass}): ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Retry StreamableHTTP once on any transient connect failure — network blips,\n // JSON parse errors on half-buffered responses, and mid-handshake proxy\n // disconnects all surface as generic Error or McpError, not StreamableHTTPError.\n // Auth failures are the only class where retry is pointless and wasteful.\n if (!is401Error(error)) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transient connect error (${errorClass}) detected, retrying StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const retryClient = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await retryClient.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP (retry) for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return retryClient;\n } catch (retryError) {\n try {\n await retryClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP retry also failed for ${label}: ${retryError instanceof Error ? retryError.message : String(retryError)}`,\n timestamp: new Date().toISOString(),\n });\n if (isAbortOrTimeoutError(retryError)) {\n throw retryError;\n }\n // Fall through to SSE fallback below\n }\n }\n\n // Auth failure — transport type won't change the outcome\n if (is401Error(error)) {\n throw error;\n }\n\n // If StreamableHTTP previously worked for this URL, don't fall back to SSE.\n // Transient failures (connection reuse, concurrency limits) should be retried\n // with StreamableHTTP, not SSE — SSE sends GET requests that return 405 on\n // servers that only support POST-based StreamableHTTP.\n if (knownStreamableHTTPUrls.has(url.toString())) {\n debugLogs.push({\n type: 'info',\n message: `MCP: StreamableHTTP previously succeeded for ${url} — skipping SSE fallback for ${label}`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n // Fall back to SSE\n debugLogs.push({\n type: 'warning',\n message: `MCP: Falling back to SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await client.connect(\n new SSEClientTransport(url, {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n }),\n mcpRequestOptions\n );\n } catch (sseError) {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n throw sseError;\n }\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n }\n}\n\nexport async function callMCPTool(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactIdempotencyKeyInArgs(args))}`,\n timestamp: new Date().toISOString(),\n });\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Custom fetch injection is an internal conformance seam whose mocks use\n // the v1 transport shape. Normal remote calls negotiate the modern era;\n // injected transports retain their exact legacy behavior.\n if (!transportFetch) {\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(signingContext && { signingContext }),\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(requestOptions?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: requestOptions.requestTimeoutMs,\n }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () => {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch, requestOptions)\n );\n }\n );\n}\n\n/**\n * Call an MCP tool and return the raw CallToolResult (with isError, content, structuredContent).\n * Raw MCP tool call — returns the CallToolResult directly, including isError responses.\n */\nexport async function callMCPToolRaw(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolRawImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch)\n );\n}\n\nasync function callMCPToolImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n // Inject trace context headers for distributed tracing\n const traceHeaders = injectTraceHeaders();\n\n // Merge: custom < trace < auth (auth always wins)\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions?.requestTimeoutMs);\n const response = await withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n client.callTool({ name: toolName, arguments: args }, undefined, {\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n }) as Promise<CallToolResponse>,\n transportFetch,\n requestOptions\n );\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n}\n\n/**\n * Raw MCP tool call — returns the CallToolResult directly.\n */\nasync function callMCPToolRawImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n const traceHeaders = injectTraceHeaders();\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client => client.callTool({ name: toolName, arguments: args }),\n transportFetch\n );\n}\n\n/**\n * Connect to an MCP server with OAuth support\n *\n * This function handles both static token auth and OAuth flows.\n * When using OAuth, if the server requires authorization:\n * 1. UnauthorizedError is thrown\n * 2. The OAuth provider's redirectToAuthorization is called\n * 3. Caller should wait for callback and call finishAuth on transport\n *\n * @param options Connection options\n * @returns MCP client and transport (for finishing OAuth if needed)\n * @throws UnauthorizedError if OAuth is required\n *\n * @example\n * ```typescript\n * // With OAuth provider\n * const provider = createCLIOAuthProvider(serverUrl);\n *\n * try {\n * const { client, transport } = await connectMCP({\n * agentUrl: serverUrl,\n * authProvider: provider\n * });\n * // Connected! Use client...\n * } catch (error) {\n * if (error instanceof UnauthorizedError) {\n * // OAuth flow started, wait for callback\n * const code = await provider.waitForCallback();\n * await transport.finishAuth(code);\n * // Retry connection...\n * }\n * }\n * ```\n *\n * @deprecated Low-level v1/SSE escape hatch. High-level AgentClient discovery,\n * tool listing, OAuth calls, and `callMCPTool*` APIs negotiate MCP 2026-07-28.\n * Keep this only for callers that require the v1 SDK client/transport pair or\n * its interactive `finishAuth()` lifecycle.\n */\nexport async function connectMCP(options: {\n agentUrl: string;\n authToken?: string;\n authProvider?: OAuthClientProvider;\n debugLogs?: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n fetchFn?: typeof fetch;\n}): Promise<MCPConnectionResult> {\n const {\n agentUrl,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs: configuredRequestTimeoutMs,\n fetchFn,\n } = options;\n const baseUrl = new URL(agentUrl);\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Connecting to ${baseUrl}`,\n timestamp: new Date().toISOString(),\n authMethod: authProvider ? 'oauth' : authToken ? 'token' : 'none',\n });\n\n const mcpClient = new MCPClient({\n name: 'AdCP-Client',\n version: '1.0.0',\n });\n\n // Build transport options\n const transportOptions: StreamableHTTPClientTransportOptions = {};\n\n // Header-only auth (basic, x-api-key, custom routing) lives entirely on\n // `customHeaders`. Attach it whenever it's present, regardless of which\n // auth branch fires — OAuth + routing headers, bearer + tenant headers,\n // and pure-header auth must all reach the wire.\n //\n // Precedence note: the MCP SDK's `_commonHeaders()` (StreamableHTTP)\n // spreads `requestInit.headers` *over* any provider-emitted `Authorization`\n // (`new Headers({ ...providerHeaders, ...requestInitHeaders })`, last-write-\n // wins). To prevent a caller-supplied `Authorization` in `customHeaders`\n // from silently overriding the OAuth provider's bearer, drop any\n // `Authorization` key from `customHeaders` when `authProvider` is set.\n // OAuth is the source of truth for the bearer in that branch; non-auth\n // routing/tenant headers still flow through.\n const filteredCustomHeaders = authProvider\n ? Object.fromEntries(Object.entries(customHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization'))\n : customHeaders;\n const authHeaders: Record<string, string> = {\n ...filteredCustomHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n transportOptions.requestInit = { headers: authHeaders, redirect: 'manual' };\n if (authProvider) {\n transportOptions.authProvider = authProvider;\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using OAuth provider for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (authToken) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using static token for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (Object.keys(authHeaders).length > 0) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using custom headers for authentication',\n timestamp: new Date().toISOString(),\n });\n }\n\n // RFC 9421 signing — wrap the transport's fetch so the signer sees the final\n // headers the SDK assembled (including any OAuth-issued Authorization) and\n // decides per outbound request whether to sign. Size-limit sits innermost so\n // the response body is bounded before signing/capture observe it.\n const requestTimeoutMs = resolveRequestTimeoutMs(configuredRequestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(configuredRequestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = fetchFn ?? ((input, init) => fetch(input, init));\n const sizeLimited = wrapFetchWithSizeLimit((input, init) =>\n withAbortSignal<Response>([signal, init?.signal], requestTimeoutMs, linkedSignal =>\n rawNetworkFetch(input, { ...init, signal: linkedSignal })\n )\n );\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const signedFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n transportOptions.fetch = wrapFetchWithCapture(signedFetch);\n\n const transport = new StreamableHTTPClientTransport(baseUrl, transportOptions);\n\n try {\n await mcpClient.connect(transport, requestOptions);\n debugLogs.push({\n type: 'success',\n message: 'MCP: Connected successfully',\n timestamp: new Date().toISOString(),\n });\n return { client: mcpClient, transport };\n } catch (error) {\n // If it's an UnauthorizedError, the OAuth flow has started\n // Rethrow so the caller can handle the callback\n if (error instanceof UnauthorizedError) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: OAuth authorization required, flow initiated',\n timestamp: new Date().toISOString(),\n });\n // Return transport so caller can call finishAuth\n throw Object.assign(error, { transport, client: mcpClient });\n }\n\n // Non-OAuth 401 — the SDK sent credentials that the agent rejected (or\n // sent none when it needed them). The raw transport error is shaped like\n // `Error POSTing to endpoint (HTTP 401): unauthorized`, which omits the\n // crucial piece of debug data: *which auth scheme did the SDK actually\n // use*. Without that, a caller can't diff against curl. Wrap the error\n // with a scheme tag and a remediation hint, preserving the original\n // under `.cause` so existing `is401Error` / `error.status` checks\n // downstream still resolve.\n if (is401Error(error)) {\n const scheme = authProvider\n ? 'oauth'\n : authToken\n ? 'bearer'\n : Object.keys(authHeaders).length > 0\n ? 'header'\n : 'none';\n const hint =\n scheme === 'none'\n ? 'No credentials were sent. Configure auth_token, headers, or oauth_tokens on the agent config (or pass --auth on the CLI).'\n : scheme === 'header'\n ? \"Verify the Authorization header value matches the gateway (basic-auth: 'Basic ' + base64(user:pass); pair with --auth-scheme basic on the CLI).\"\n : scheme === 'bearer'\n ? \"Verify the bearer token matches the agent's expected credential.\"\n : 'OAuth provider returned tokens that the agent rejected — check the provider configuration and token scopes.';\n const detail = `MCP connect rejected with HTTP 401 from ${agentUrl}. SDK sent auth scheme: ${scheme}. ${hint}`;\n const wrapped = Object.assign(new Error(detail), {\n cause: error,\n code: 'MCP_AUTH_REJECTED',\n scheme,\n agentUrl,\n originalError: error,\n });\n throw wrapped;\n }\n\n throw error;\n }\n}\n\n/**\n * Call an MCP tool with OAuth support.\n *\n * OAuth connections are cached by agent URL and OAuth provider identity so a\n * service-to-service workflow can reuse the initialized MCP session across\n * related tool calls. Reuse the same OAuthClientProvider instance for a\n * session/source/principal; the provider owns token refresh state for the\n * cached transport.\n *\n * Supplying `fetchFn` opts out of connection reuse. Scoped fetchers commonly\n * carry request- or tenant-specific network policy, so each call gets an\n * isolated connection that is closed after the tool response.\n *\n * Signing: this path consumes `options.signingContext` via the transport —\n * `connectMCP` attaches a signing-fetch wrapper at transport-creation time —\n * rather than via `signingContextStorage`. The OAuth cache key includes the\n * signing cache key so different signing identities do not share a transport.\n * The non-OAuth fallback (`callMCPTool`) does enter ALS.\n *\n * @param options Call options\n * @returns Tool response\n * @throws UnauthorizedError if OAuth is required (with transport attached)\n */\nexport async function callMCPToolWithOAuth(options: MCPCallOptions): Promise<unknown> {\n const {\n agentUrl,\n toolName,\n args,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n fetchFn,\n } = options;\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n\n // If no OAuth provider, use the legacy function\n if (!authProvider) {\n return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, fetchFn, {\n signal,\n requestTimeoutMs,\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, undefined, debugLogs, customHeaders, {\n authProvider,\n signingContext,\n signal,\n requestTimeoutMs,\n fetchFn,\n handleLegacy: true,\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n return modernAttempt.response;\n }\n\n const response = await withCachedOAuthConnection(\n {\n agentUrl,\n authProvider,\n debugLogs,\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n fetchFn,\n },\n toolName,\n async client => {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n const response = await client.callTool({ name: toolName, arguments: args }, undefined, requestOptions);\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n\n return response;\n }\n );\n\n return response;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAoC;AACpC,4BAIO;AACP,iBAAmC;AACnC,kBAAkC;AAElC,yBAA2B;AAC3B,IAAAA,eAAqC;AACrC,oBAA2B;AAE3B,qBAA6C;AAC7C,IAAAC,iBAAwF;AACxF,yBAA2C;AAC3C,gCAAqC;AACrC,+BAAuC;AACvC,kCAAkD;AAClD,mBAKO;AACP,wBAAgE;AA4BhE,MAAM,kBAAkB,oBAAI,IAAuB;AACnD,MAAM,qBAAqB,oBAAI,IAAgC;AAC/D,MAAM,uBAAuB,oBAAI,IAAuB;AACxD,MAAM,0BAA0B,oBAAI,IAAgC;AACpE,MAAM,mBAAmB,oBAAI,QAAqC;AAClE,MAAM,kBAAkB,oBAAI,QAA8B;AAC1D,MAAM,yBAAyB;AAC/B,IAAI,sBAAsB;AAC1B,IAAI,qBAAqB;AAWzB,MAAM,0BAA0B,oBAAI,IAAY;AAEhD,SAAS,uBAAuB,KAAmB;AAEjD,0BAAwB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AU,EAAE,OAAO;AAAA,IACvB,GAAI,6BAA6B,UAAa,EAAE,SAAS,yBAAyB;AAAA,EACpF;AAGA,MAAI,CAAC,cAAc;AACjB,WAAO,YAAY,UAAU,UAAU,MAAM,WAAW,WAAW,eAAe,gBAAgB,SAAS;AAAA,MACzG;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,gBAAgB,UAAM,wCAAqB,UAAU,UAAU,MAAM,QAAW,WAAW,eAAe;AAAA,IAC9G;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB,CAAC;AACD,MAAI,cAAc,SAAS;AACzB,cAAU,KAAK;AAAA,MACb,MAAM,cAAc,UAAU,UAAU,UAAU;AAAA,MAClD,SAAS,aAAa,QAAQ;AAAA,MAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC,CAAC;AACD,WAAO,cAAc;AAAA,EACvB;AAEA,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,IACA,OAAM,WAAU;AACd,gBAAU,KAAK;AAAA,QACb,MAAM;AAAA,QACN,SAAS,qBAAqB,QAAQ;AAAA,QACtC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,YAAMC,YAAW,MAAM,OAAO,SAAS,EAAE,MAAM,UAAU,WAAW,KAAK,GAAG,QAAW,cAAc;AAErG,gBAAU,KAAK;AAAA,QACb,MAAMA,WAAU,UAAU,UAAU;AAAA,QACpC,SAAS,aAAa,QAAQ;AAAA,QAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,aAAOA;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_auth","import_client","MCPClient","response"]}
|
|
@@ -26,8 +26,10 @@ const pendingConnections = /* @__PURE__ */ new Map();
|
|
|
26
26
|
const oauthConnectionCache = /* @__PURE__ */ new Map();
|
|
27
27
|
const pendingOAuthConnections = /* @__PURE__ */ new Map();
|
|
28
28
|
const oauthProviderIds = /* @__PURE__ */ new WeakMap();
|
|
29
|
+
const oauthFetchFnIds = /* @__PURE__ */ new WeakMap();
|
|
29
30
|
const MAX_CACHED_CONNECTIONS = 20;
|
|
30
31
|
let nextOAuthProviderId = 0;
|
|
32
|
+
let nextOAuthFetchFnId = 0;
|
|
31
33
|
const knownStreamableHTTPUrls = /* @__PURE__ */ new Set();
|
|
32
34
|
function trackStreamableHTTPUrl(url) {
|
|
33
35
|
knownStreamableHTTPUrls.delete(url);
|
|
@@ -135,14 +137,23 @@ function getOAuthProviderDisambiguator(authProvider) {
|
|
|
135
137
|
}
|
|
136
138
|
return id;
|
|
137
139
|
}
|
|
140
|
+
function getOAuthFetchFnDisambiguator(fetchFn) {
|
|
141
|
+
let id = oauthFetchFnIds.get(fetchFn);
|
|
142
|
+
if (!id) {
|
|
143
|
+
id = cacheDisambiguator(`oauth-fetch:${++nextOAuthFetchFnId}`);
|
|
144
|
+
oauthFetchFnIds.set(fetchFn, id);
|
|
145
|
+
}
|
|
146
|
+
return id;
|
|
147
|
+
}
|
|
138
148
|
function customHeadersDisambiguator(customHeaders) {
|
|
139
149
|
return headersCacheDisambiguator(customHeaders);
|
|
140
150
|
}
|
|
141
|
-
function oauthConnectionCacheKey(agentUrl, authProvider, signingCacheKey, customHeaders) {
|
|
151
|
+
function oauthConnectionCacheKey(agentUrl, authProvider, signingCacheKey, customHeaders, fetchFn) {
|
|
142
152
|
const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];
|
|
143
153
|
if (signingCacheKey) parts.push(signingCacheKey);
|
|
144
154
|
const headersKey = customHeadersDisambiguator(customHeaders);
|
|
145
155
|
if (headersKey) parts.push(`headers:${headersKey}`);
|
|
156
|
+
if (fetchFn) parts.push(`fetch:${getOAuthFetchFnDisambiguator(fetchFn)}`);
|
|
146
157
|
return parts.join("::");
|
|
147
158
|
}
|
|
148
159
|
function getCachedOAuthConnection(key) {
|
|
@@ -173,9 +184,10 @@ async function withCachedOAuthConnection(options, label, fn) {
|
|
|
173
184
|
options.agentUrl,
|
|
174
185
|
options.authProvider,
|
|
175
186
|
options.signingContext?.cacheKey,
|
|
176
|
-
options.customHeaders
|
|
187
|
+
options.customHeaders,
|
|
188
|
+
options.fetchFn
|
|
177
189
|
);
|
|
178
|
-
if (options.signal || options.requestTimeoutMs !== void 0) {
|
|
190
|
+
if (options.signal || options.requestTimeoutMs !== void 0 || options.fetchFn) {
|
|
179
191
|
const { client } = await connectMCP(options);
|
|
180
192
|
try {
|
|
181
193
|
return await fn(client);
|
|
@@ -563,7 +575,8 @@ async function connectMCP(options) {
|
|
|
563
575
|
customHeaders,
|
|
564
576
|
signingContext,
|
|
565
577
|
signal,
|
|
566
|
-
requestTimeoutMs: configuredRequestTimeoutMs
|
|
578
|
+
requestTimeoutMs: configuredRequestTimeoutMs,
|
|
579
|
+
fetchFn
|
|
567
580
|
} = options;
|
|
568
581
|
const baseUrl = new URL(agentUrl);
|
|
569
582
|
debugLogs.push({
|
|
@@ -609,11 +622,12 @@ async function connectMCP(options) {
|
|
|
609
622
|
...signal && { signal },
|
|
610
623
|
...clientRequestTimeoutMs !== void 0 && { timeout: clientRequestTimeoutMs }
|
|
611
624
|
};
|
|
625
|
+
const rawNetworkFetch = fetchFn ?? ((input, init) => fetch(input, init));
|
|
612
626
|
const sizeLimited = wrapFetchWithSizeLimit(
|
|
613
627
|
(input, init) => withAbortSignal(
|
|
614
628
|
[signal, init?.signal],
|
|
615
629
|
requestTimeoutMs,
|
|
616
|
-
(linkedSignal) =>
|
|
630
|
+
(linkedSignal) => rawNetworkFetch(input, { ...init, signal: linkedSignal })
|
|
617
631
|
)
|
|
618
632
|
);
|
|
619
633
|
const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);
|
|
@@ -668,7 +682,8 @@ async function callMCPToolWithOAuth(options) {
|
|
|
668
682
|
customHeaders,
|
|
669
683
|
signingContext,
|
|
670
684
|
signal,
|
|
671
|
-
requestTimeoutMs
|
|
685
|
+
requestTimeoutMs,
|
|
686
|
+
fetchFn
|
|
672
687
|
} = options;
|
|
673
688
|
const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);
|
|
674
689
|
const requestOptions = {
|
|
@@ -676,7 +691,7 @@ async function callMCPToolWithOAuth(options) {
|
|
|
676
691
|
...resolvedRequestTimeoutMs !== void 0 && { timeout: resolvedRequestTimeoutMs }
|
|
677
692
|
};
|
|
678
693
|
if (!authProvider) {
|
|
679
|
-
return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext,
|
|
694
|
+
return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, fetchFn, {
|
|
680
695
|
signal,
|
|
681
696
|
requestTimeoutMs
|
|
682
697
|
});
|
|
@@ -686,6 +701,7 @@ async function callMCPToolWithOAuth(options) {
|
|
|
686
701
|
signingContext,
|
|
687
702
|
signal,
|
|
688
703
|
requestTimeoutMs,
|
|
704
|
+
fetchFn,
|
|
689
705
|
handleLegacy: true
|
|
690
706
|
});
|
|
691
707
|
if (modernAttempt.handled) {
|
|
@@ -704,7 +720,8 @@ async function callMCPToolWithOAuth(options) {
|
|
|
704
720
|
customHeaders,
|
|
705
721
|
signingContext,
|
|
706
722
|
signal,
|
|
707
|
-
requestTimeoutMs
|
|
723
|
+
requestTimeoutMs,
|
|
724
|
+
fetchFn
|
|
708
725
|
},
|
|
709
726
|
toolName,
|
|
710
727
|
async (client) => {
|