@adcp/sdk 12.0.3 → 12.0.4

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.
@@ -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":"AACA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAElC,SAAS,kBAAkB;AAC3B,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAE3B,SAAS,UAAU,0BAA0B;AAC7C,SAAS,wBAAwB,6BAAuD;AACxF,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,4BAA4B;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,wBA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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,YAAMA,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":["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":"AACA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAElC,SAAS,kBAAkB;AAC3B,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAE3B,SAAS,UAAU,0BAA0B;AAC7C,SAAS,wBAAwB,6BAAuD;AACxF,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,4BAA4B;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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arball_sha256": "580656d6466ef9f0d1119985e6726c2efea718dc671e2ad30957fcb2fd54af0f",
6
6
  "upstream_adcp_version": "2.5.3",
7
- "synced_at": "2026-07-19T01:37:04.433Z"
7
+ "synced_at": "2026-07-21T22:49:01.295Z"
8
8
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * AdCP SDK library version
3
3
  */
4
- export declare const LIBRARY_VERSION = "12.0.3";
4
+ export declare const LIBRARY_VERSION = "12.0.4";
5
5
  /**
6
6
  * AdCP specification version this library is built for
7
7
  */
@@ -33,10 +33,10 @@ export type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number];
33
33
  * Full version information
34
34
  */
35
35
  export declare const VERSION_INFO: {
36
- readonly library: "12.0.3";
36
+ readonly library: "12.0.4";
37
37
  readonly adcp: "3.1.2";
38
38
  readonly compatibleVersions: readonly ["v2.5", "v2.6", "v3", "3.0.0-beta.1", "3.0-beta.1", "3.0-beta", "3.0.0-beta.3", "3.0-beta.3", "3.0.0", "3.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.0.7", "3.0.8", "3.0.9", "3.0.10", "3.0.11", "3.0.12", "3.1.0", "3.1", "3.1.1", "3.1.2"];
39
- readonly generatedAt: "2026-07-19T01:26:47.776Z";
39
+ readonly generatedAt: "2026-07-21T22:42:42.739Z";
40
40
  };
41
41
  /**
42
42
  * Get the AdCP specification version this library is built for
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * AdCP SDK library version
3
3
  */
4
- export declare const LIBRARY_VERSION = "12.0.3";
4
+ export declare const LIBRARY_VERSION = "12.0.4";
5
5
  /**
6
6
  * AdCP specification version this library is built for
7
7
  */
@@ -33,10 +33,10 @@ export type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number];
33
33
  * Full version information
34
34
  */
35
35
  export declare const VERSION_INFO: {
36
- readonly library: "12.0.3";
36
+ readonly library: "12.0.4";
37
37
  readonly adcp: "3.1.2";
38
38
  readonly compatibleVersions: readonly ["v2.5", "v2.6", "v3", "3.0.0-beta.1", "3.0-beta.1", "3.0-beta", "3.0.0-beta.3", "3.0-beta.3", "3.0.0", "3.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.0.7", "3.0.8", "3.0.9", "3.0.10", "3.0.11", "3.0.12", "3.1.0", "3.1", "3.1.1", "3.1.2"];
39
- readonly generatedAt: "2026-07-19T01:26:47.776Z";
39
+ readonly generatedAt: "2026-07-21T22:42:42.739Z";
40
40
  };
41
41
  /**
42
42
  * Get the AdCP specification version this library is built for
@@ -31,7 +31,7 @@ __export(version_exports, {
31
31
  toReleasePrecisionVersion: () => toReleasePrecisionVersion
32
32
  });
33
33
  module.exports = __toCommonJS(version_exports);
34
- const LIBRARY_VERSION = "12.0.3";
34
+ const LIBRARY_VERSION = "12.0.4";
35
35
  const ADCP_VERSION = "3.1.2";
36
36
  const ADCP_MAJOR_VERSION = 3;
37
37
  const COMPATIBLE_ADCP_VERSIONS = [
@@ -63,10 +63,10 @@ const COMPATIBLE_ADCP_VERSIONS = [
63
63
  "3.1.2"
64
64
  ];
65
65
  const VERSION_INFO = {
66
- library: "12.0.3",
66
+ library: "12.0.4",
67
67
  adcp: "3.1.2",
68
68
  compatibleVersions: COMPATIBLE_ADCP_VERSIONS,
69
- generatedAt: "2026-07-19T01:26:47.776Z"
69
+ generatedAt: "2026-07-21T22:42:42.739Z"
70
70
  };
71
71
  function getAdcpVersion() {
72
72
  return ADCP_VERSION;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/version.ts"],"sourcesContent":["// Generated version information\n// This file is auto-generated by sync-version.ts\n\n/**\n * AdCP SDK library version\n */\nexport const LIBRARY_VERSION = '12.0.3';\n\n/**\n * AdCP specification version this library is built for\n */\nexport const ADCP_VERSION = '3.1.2';\n\n/**\n * AdCP major version sent with every request (adcp_major_version field).\n * Sellers validate this against their supported versions and return\n * VERSION_UNSUPPORTED if the version is not in range.\n */\nexport const ADCP_MAJOR_VERSION = 3;\n\n/**\n * AdCP versions this library maintains backward compatibility with.\n *\n * Auto-derived from `ADCP_VERSION` by scripts/sync-version.ts. Do not edit\n * this list by hand; bumping the AdCP pin via `npm run sync-version`\n * extends it.\n */\nexport const COMPATIBLE_ADCP_VERSIONS = [\n 'v2.5',\n 'v2.6',\n 'v3',\n '3.0.0-beta.1',\n '3.0-beta.1',\n '3.0-beta',\n '3.0.0-beta.3',\n '3.0-beta.3',\n '3.0.0',\n '3.0',\n '3.0.1',\n '3.0.2',\n '3.0.3',\n '3.0.4',\n '3.0.5',\n '3.0.6',\n '3.0.7',\n '3.0.8',\n '3.0.9',\n '3.0.10',\n '3.0.11',\n '3.0.12',\n '3.1.0',\n '3.1',\n '3.1.1',\n '3.1.2',\n] as const;\n\n/**\n * String literal union of every AdCP version the SDK formally supports.\n *\n * Used by the per-instance `adcpVersion` constructor option to give callers\n * autocomplete in editors. The intersection with `(string & {})` in the\n * config type preserves the escape hatch — any string is still accepted at\n * the type level — while the literal union surfaces canonical values first.\n */\nexport type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number];\n\n/**\n * Full version information\n */\nexport const VERSION_INFO = {\n library: '12.0.3',\n adcp: '3.1.2',\n compatibleVersions: COMPATIBLE_ADCP_VERSIONS,\n generatedAt: '2026-07-19T01:26:47.776Z',\n} as const;\n\n/**\n * Get the AdCP specification version this library is built for\n */\nexport function getAdcpVersion(): string {\n return ADCP_VERSION;\n}\n\n/**\n * Get the library version\n */\nexport function getLibraryVersion(): string {\n return LIBRARY_VERSION;\n}\n\n/**\n * Check if this library version is compatible with a given AdCP version\n */\nexport function isCompatibleWith(adcpVersion: string): boolean {\n return (COMPATIBLE_ADCP_VERSIONS as readonly string[]).includes(adcpVersion);\n}\n\n/**\n * Get all AdCP versions this library is compatible with\n */\nexport function getCompatibleVersions(): readonly string[] {\n return COMPATIBLE_ADCP_VERSIONS;\n}\n\n/**\n * Extract the major version number from an AdCP version string.\n *\n * Accepts:\n * - Semver: '3.0.0', '3.0.1', '3.1.0-beta.1' → 3\n * - Legacy aliases: 'v3' → 3, 'v2.5' / 'v2.6' → 2\n *\n * Returns NaN for unrecognized strings — callers should validate before passing.\n */\nexport function parseAdcpMajorVersion(version: string): number {\n const trimmed = version.trim();\n const semverLike = trimmed.startsWith('v') ? trimmed.slice(1) : trimmed;\n const major = parseInt(semverLike.split('.')[0] ?? '', 10);\n return Number.isFinite(major) ? major : NaN;\n}\n\n/**\n * Normalize a full-semver AdCP version (`MAJOR.MINOR.PATCH[-prerelease]`) to\n * the release-precision form that AdCP 3.1+ requires on the wire:\n * `MAJOR.MINOR[-prerelease]` — the patch digit is dropped.\n *\n * Per the spec note on `adcp_version`: \"SDKs that read full-semver values\n * from bundle metadata (e.g. `ComplianceIndex.published_version =\n * \"3.1.0-beta.1\"`) MUST normalize to release-precision (`\"3.1-beta.1\"`)\n * before emitting on the wire — meta-field values are NOT valid wire\n * values.\" The wire regex (`^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`) rejects strings\n * with a patch digit.\n *\n * Behavior:\n * - `\"3.1.0-beta.7\"` → `\"3.1-beta.7\"`\n * - `\"3.1.0\"` → `\"3.1\"`\n * - `\"3.0.12\"` → `\"3.0\"`\n * - Already-release-precision input (`\"3.1\"`, `\"3.1-beta.7\"`) passes through\n * - Legacy aliases (`\"v2.5\"`, `\"v3\"`) pass through unchanged — the wire\n * regex doesn't accept them anyway; the v2.5 path uses\n * `adcp_major_version` instead of `adcp_version` for transport.\n * - Unrecognized strings pass through unchanged so callers can detect drift\n * via the wire validator rather than have it masked by this helper.\n */\nexport function toReleasePrecisionVersion(version: string): string {\n const trimmed = version.trim();\n // Pre-release form `MAJOR.MINOR.PATCH-prerelease` → `MAJOR.MINOR-prerelease`\n const semverMatch = trimmed.match(/^(\\d+)\\.(\\d+)\\.\\d+(-[A-Za-z0-9.-]+)?$/);\n if (semverMatch) {\n const [, major, minor, pre = ''] = semverMatch;\n return `${major}.${minor}${pre}`;\n }\n // Already release-precision (no patch digit). Includes `3.1`, `3.1-beta.7`.\n if (/^\\d+\\.\\d+(-[A-Za-z0-9.-]+)?$/.test(trimmed)) return trimmed;\n // Legacy aliases (`v3`, `v2.5`, `v2.6`) and anything we don't recognize —\n // pass through so the wire validator can flag genuine drift.\n return version;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,MAAM,kBAAkB;AAKxB,MAAM,eAAe;AAOrB,MAAM,qBAAqB;AAS3B,MAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAeO,MAAM,eAAe;AAAA,EAC1B,SAAS;AAAA,EACT,MAAM;AAAA,EACN,oBAAoB;AAAA,EACpB,aAAa;AACf;AAKO,SAAS,iBAAyB;AACvC,SAAO;AACT;AAKO,SAAS,oBAA4B;AAC1C,SAAO;AACT;AAKO,SAAS,iBAAiB,aAA8B;AAC7D,SAAQ,yBAA+C,SAAS,WAAW;AAC7E;AAKO,SAAS,wBAA2C;AACzD,SAAO;AACT;AAWO,SAAS,sBAAsB,SAAyB;AAC7D,QAAM,UAAU,QAAQ,KAAK;AAC7B,QAAM,aAAa,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAChE,QAAM,QAAQ,SAAS,WAAW,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AACzD,SAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;AAyBO,SAAS,0BAA0B,SAAyB;AACjE,QAAM,UAAU,QAAQ,KAAK;AAE7B,QAAM,cAAc,QAAQ,MAAM,uCAAuC;AACzE,MAAI,aAAa;AACf,UAAM,CAAC,EAAE,OAAO,OAAO,MAAM,EAAE,IAAI;AACnC,WAAO,GAAG,KAAK,IAAI,KAAK,GAAG,GAAG;AAAA,EAChC;AAEA,MAAI,+BAA+B,KAAK,OAAO,EAAG,QAAO;AAGzD,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/lib/version.ts"],"sourcesContent":["// Generated version information\n// This file is auto-generated by sync-version.ts\n\n/**\n * AdCP SDK library version\n */\nexport const LIBRARY_VERSION = '12.0.4';\n\n/**\n * AdCP specification version this library is built for\n */\nexport const ADCP_VERSION = '3.1.2';\n\n/**\n * AdCP major version sent with every request (adcp_major_version field).\n * Sellers validate this against their supported versions and return\n * VERSION_UNSUPPORTED if the version is not in range.\n */\nexport const ADCP_MAJOR_VERSION = 3;\n\n/**\n * AdCP versions this library maintains backward compatibility with.\n *\n * Auto-derived from `ADCP_VERSION` by scripts/sync-version.ts. Do not edit\n * this list by hand; bumping the AdCP pin via `npm run sync-version`\n * extends it.\n */\nexport const COMPATIBLE_ADCP_VERSIONS = [\n 'v2.5',\n 'v2.6',\n 'v3',\n '3.0.0-beta.1',\n '3.0-beta.1',\n '3.0-beta',\n '3.0.0-beta.3',\n '3.0-beta.3',\n '3.0.0',\n '3.0',\n '3.0.1',\n '3.0.2',\n '3.0.3',\n '3.0.4',\n '3.0.5',\n '3.0.6',\n '3.0.7',\n '3.0.8',\n '3.0.9',\n '3.0.10',\n '3.0.11',\n '3.0.12',\n '3.1.0',\n '3.1',\n '3.1.1',\n '3.1.2',\n] as const;\n\n/**\n * String literal union of every AdCP version the SDK formally supports.\n *\n * Used by the per-instance `adcpVersion` constructor option to give callers\n * autocomplete in editors. The intersection with `(string & {})` in the\n * config type preserves the escape hatch — any string is still accepted at\n * the type level — while the literal union surfaces canonical values first.\n */\nexport type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number];\n\n/**\n * Full version information\n */\nexport const VERSION_INFO = {\n library: '12.0.4',\n adcp: '3.1.2',\n compatibleVersions: COMPATIBLE_ADCP_VERSIONS,\n generatedAt: '2026-07-21T22:42:42.739Z',\n} as const;\n\n/**\n * Get the AdCP specification version this library is built for\n */\nexport function getAdcpVersion(): string {\n return ADCP_VERSION;\n}\n\n/**\n * Get the library version\n */\nexport function getLibraryVersion(): string {\n return LIBRARY_VERSION;\n}\n\n/**\n * Check if this library version is compatible with a given AdCP version\n */\nexport function isCompatibleWith(adcpVersion: string): boolean {\n return (COMPATIBLE_ADCP_VERSIONS as readonly string[]).includes(adcpVersion);\n}\n\n/**\n * Get all AdCP versions this library is compatible with\n */\nexport function getCompatibleVersions(): readonly string[] {\n return COMPATIBLE_ADCP_VERSIONS;\n}\n\n/**\n * Extract the major version number from an AdCP version string.\n *\n * Accepts:\n * - Semver: '3.0.0', '3.0.1', '3.1.0-beta.1' → 3\n * - Legacy aliases: 'v3' → 3, 'v2.5' / 'v2.6' → 2\n *\n * Returns NaN for unrecognized strings — callers should validate before passing.\n */\nexport function parseAdcpMajorVersion(version: string): number {\n const trimmed = version.trim();\n const semverLike = trimmed.startsWith('v') ? trimmed.slice(1) : trimmed;\n const major = parseInt(semverLike.split('.')[0] ?? '', 10);\n return Number.isFinite(major) ? major : NaN;\n}\n\n/**\n * Normalize a full-semver AdCP version (`MAJOR.MINOR.PATCH[-prerelease]`) to\n * the release-precision form that AdCP 3.1+ requires on the wire:\n * `MAJOR.MINOR[-prerelease]` — the patch digit is dropped.\n *\n * Per the spec note on `adcp_version`: \"SDKs that read full-semver values\n * from bundle metadata (e.g. `ComplianceIndex.published_version =\n * \"3.1.0-beta.1\"`) MUST normalize to release-precision (`\"3.1-beta.1\"`)\n * before emitting on the wire — meta-field values are NOT valid wire\n * values.\" The wire regex (`^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`) rejects strings\n * with a patch digit.\n *\n * Behavior:\n * - `\"3.1.0-beta.7\"` → `\"3.1-beta.7\"`\n * - `\"3.1.0\"` → `\"3.1\"`\n * - `\"3.0.12\"` → `\"3.0\"`\n * - Already-release-precision input (`\"3.1\"`, `\"3.1-beta.7\"`) passes through\n * - Legacy aliases (`\"v2.5\"`, `\"v3\"`) pass through unchanged — the wire\n * regex doesn't accept them anyway; the v2.5 path uses\n * `adcp_major_version` instead of `adcp_version` for transport.\n * - Unrecognized strings pass through unchanged so callers can detect drift\n * via the wire validator rather than have it masked by this helper.\n */\nexport function toReleasePrecisionVersion(version: string): string {\n const trimmed = version.trim();\n // Pre-release form `MAJOR.MINOR.PATCH-prerelease` → `MAJOR.MINOR-prerelease`\n const semverMatch = trimmed.match(/^(\\d+)\\.(\\d+)\\.\\d+(-[A-Za-z0-9.-]+)?$/);\n if (semverMatch) {\n const [, major, minor, pre = ''] = semverMatch;\n return `${major}.${minor}${pre}`;\n }\n // Already release-precision (no patch digit). Includes `3.1`, `3.1-beta.7`.\n if (/^\\d+\\.\\d+(-[A-Za-z0-9.-]+)?$/.test(trimmed)) return trimmed;\n // Legacy aliases (`v3`, `v2.5`, `v2.6`) and anything we don't recognize —\n // pass through so the wire validator can flag genuine drift.\n return version;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,MAAM,kBAAkB;AAKxB,MAAM,eAAe;AAOrB,MAAM,qBAAqB;AAS3B,MAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAeO,MAAM,eAAe;AAAA,EAC1B,SAAS;AAAA,EACT,MAAM;AAAA,EACN,oBAAoB;AAAA,EACpB,aAAa;AACf;AAKO,SAAS,iBAAyB;AACvC,SAAO;AACT;AAKO,SAAS,oBAA4B;AAC1C,SAAO;AACT;AAKO,SAAS,iBAAiB,aAA8B;AAC7D,SAAQ,yBAA+C,SAAS,WAAW;AAC7E;AAKO,SAAS,wBAA2C;AACzD,SAAO;AACT;AAWO,SAAS,sBAAsB,SAAyB;AAC7D,QAAM,UAAU,QAAQ,KAAK;AAC7B,QAAM,aAAa,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAChE,QAAM,QAAQ,SAAS,WAAW,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AACzD,SAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;AAyBO,SAAS,0BAA0B,SAAyB;AACjE,QAAM,UAAU,QAAQ,KAAK;AAE7B,QAAM,cAAc,QAAQ,MAAM,uCAAuC;AACzE,MAAI,aAAa;AACf,UAAM,CAAC,EAAE,OAAO,OAAO,MAAM,EAAE,IAAI;AACnC,WAAO,GAAG,KAAK,IAAI,KAAK,GAAG,GAAG;AAAA,EAChC;AAEA,MAAI,+BAA+B,KAAK,OAAO,EAAG,QAAO;AAGzD,SAAO;AACT;","names":[]}
@@ -1,4 +1,4 @@
1
- const LIBRARY_VERSION = "12.0.3";
1
+ const LIBRARY_VERSION = "12.0.4";
2
2
  const ADCP_VERSION = "3.1.2";
3
3
  const ADCP_MAJOR_VERSION = 3;
4
4
  const COMPATIBLE_ADCP_VERSIONS = [
@@ -30,10 +30,10 @@ const COMPATIBLE_ADCP_VERSIONS = [
30
30
  "3.1.2"
31
31
  ];
32
32
  const VERSION_INFO = {
33
- library: "12.0.3",
33
+ library: "12.0.4",
34
34
  adcp: "3.1.2",
35
35
  compatibleVersions: COMPATIBLE_ADCP_VERSIONS,
36
- generatedAt: "2026-07-19T01:26:47.776Z"
36
+ generatedAt: "2026-07-21T22:42:42.739Z"
37
37
  };
38
38
  function getAdcpVersion() {
39
39
  return ADCP_VERSION;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/version.ts"],"sourcesContent":["// Generated version information\n// This file is auto-generated by sync-version.ts\n\n/**\n * AdCP SDK library version\n */\nexport const LIBRARY_VERSION = '12.0.3';\n\n/**\n * AdCP specification version this library is built for\n */\nexport const ADCP_VERSION = '3.1.2';\n\n/**\n * AdCP major version sent with every request (adcp_major_version field).\n * Sellers validate this against their supported versions and return\n * VERSION_UNSUPPORTED if the version is not in range.\n */\nexport const ADCP_MAJOR_VERSION = 3;\n\n/**\n * AdCP versions this library maintains backward compatibility with.\n *\n * Auto-derived from `ADCP_VERSION` by scripts/sync-version.ts. Do not edit\n * this list by hand; bumping the AdCP pin via `npm run sync-version`\n * extends it.\n */\nexport const COMPATIBLE_ADCP_VERSIONS = [\n 'v2.5',\n 'v2.6',\n 'v3',\n '3.0.0-beta.1',\n '3.0-beta.1',\n '3.0-beta',\n '3.0.0-beta.3',\n '3.0-beta.3',\n '3.0.0',\n '3.0',\n '3.0.1',\n '3.0.2',\n '3.0.3',\n '3.0.4',\n '3.0.5',\n '3.0.6',\n '3.0.7',\n '3.0.8',\n '3.0.9',\n '3.0.10',\n '3.0.11',\n '3.0.12',\n '3.1.0',\n '3.1',\n '3.1.1',\n '3.1.2',\n] as const;\n\n/**\n * String literal union of every AdCP version the SDK formally supports.\n *\n * Used by the per-instance `adcpVersion` constructor option to give callers\n * autocomplete in editors. The intersection with `(string & {})` in the\n * config type preserves the escape hatch — any string is still accepted at\n * the type level — while the literal union surfaces canonical values first.\n */\nexport type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number];\n\n/**\n * Full version information\n */\nexport const VERSION_INFO = {\n library: '12.0.3',\n adcp: '3.1.2',\n compatibleVersions: COMPATIBLE_ADCP_VERSIONS,\n generatedAt: '2026-07-19T01:26:47.776Z',\n} as const;\n\n/**\n * Get the AdCP specification version this library is built for\n */\nexport function getAdcpVersion(): string {\n return ADCP_VERSION;\n}\n\n/**\n * Get the library version\n */\nexport function getLibraryVersion(): string {\n return LIBRARY_VERSION;\n}\n\n/**\n * Check if this library version is compatible with a given AdCP version\n */\nexport function isCompatibleWith(adcpVersion: string): boolean {\n return (COMPATIBLE_ADCP_VERSIONS as readonly string[]).includes(adcpVersion);\n}\n\n/**\n * Get all AdCP versions this library is compatible with\n */\nexport function getCompatibleVersions(): readonly string[] {\n return COMPATIBLE_ADCP_VERSIONS;\n}\n\n/**\n * Extract the major version number from an AdCP version string.\n *\n * Accepts:\n * - Semver: '3.0.0', '3.0.1', '3.1.0-beta.1' → 3\n * - Legacy aliases: 'v3' → 3, 'v2.5' / 'v2.6' → 2\n *\n * Returns NaN for unrecognized strings — callers should validate before passing.\n */\nexport function parseAdcpMajorVersion(version: string): number {\n const trimmed = version.trim();\n const semverLike = trimmed.startsWith('v') ? trimmed.slice(1) : trimmed;\n const major = parseInt(semverLike.split('.')[0] ?? '', 10);\n return Number.isFinite(major) ? major : NaN;\n}\n\n/**\n * Normalize a full-semver AdCP version (`MAJOR.MINOR.PATCH[-prerelease]`) to\n * the release-precision form that AdCP 3.1+ requires on the wire:\n * `MAJOR.MINOR[-prerelease]` — the patch digit is dropped.\n *\n * Per the spec note on `adcp_version`: \"SDKs that read full-semver values\n * from bundle metadata (e.g. `ComplianceIndex.published_version =\n * \"3.1.0-beta.1\"`) MUST normalize to release-precision (`\"3.1-beta.1\"`)\n * before emitting on the wire — meta-field values are NOT valid wire\n * values.\" The wire regex (`^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`) rejects strings\n * with a patch digit.\n *\n * Behavior:\n * - `\"3.1.0-beta.7\"` → `\"3.1-beta.7\"`\n * - `\"3.1.0\"` → `\"3.1\"`\n * - `\"3.0.12\"` → `\"3.0\"`\n * - Already-release-precision input (`\"3.1\"`, `\"3.1-beta.7\"`) passes through\n * - Legacy aliases (`\"v2.5\"`, `\"v3\"`) pass through unchanged — the wire\n * regex doesn't accept them anyway; the v2.5 path uses\n * `adcp_major_version` instead of `adcp_version` for transport.\n * - Unrecognized strings pass through unchanged so callers can detect drift\n * via the wire validator rather than have it masked by this helper.\n */\nexport function toReleasePrecisionVersion(version: string): string {\n const trimmed = version.trim();\n // Pre-release form `MAJOR.MINOR.PATCH-prerelease` → `MAJOR.MINOR-prerelease`\n const semverMatch = trimmed.match(/^(\\d+)\\.(\\d+)\\.\\d+(-[A-Za-z0-9.-]+)?$/);\n if (semverMatch) {\n const [, major, minor, pre = ''] = semverMatch;\n return `${major}.${minor}${pre}`;\n }\n // Already release-precision (no patch digit). Includes `3.1`, `3.1-beta.7`.\n if (/^\\d+\\.\\d+(-[A-Za-z0-9.-]+)?$/.test(trimmed)) return trimmed;\n // Legacy aliases (`v3`, `v2.5`, `v2.6`) and anything we don't recognize —\n // pass through so the wire validator can flag genuine drift.\n return version;\n}\n"],"mappings":"AAMO,MAAM,kBAAkB;AAKxB,MAAM,eAAe;AAOrB,MAAM,qBAAqB;AAS3B,MAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAeO,MAAM,eAAe;AAAA,EAC1B,SAAS;AAAA,EACT,MAAM;AAAA,EACN,oBAAoB;AAAA,EACpB,aAAa;AACf;AAKO,SAAS,iBAAyB;AACvC,SAAO;AACT;AAKO,SAAS,oBAA4B;AAC1C,SAAO;AACT;AAKO,SAAS,iBAAiB,aAA8B;AAC7D,SAAQ,yBAA+C,SAAS,WAAW;AAC7E;AAKO,SAAS,wBAA2C;AACzD,SAAO;AACT;AAWO,SAAS,sBAAsB,SAAyB;AAC7D,QAAM,UAAU,QAAQ,KAAK;AAC7B,QAAM,aAAa,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAChE,QAAM,QAAQ,SAAS,WAAW,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AACzD,SAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;AAyBO,SAAS,0BAA0B,SAAyB;AACjE,QAAM,UAAU,QAAQ,KAAK;AAE7B,QAAM,cAAc,QAAQ,MAAM,uCAAuC;AACzE,MAAI,aAAa;AACf,UAAM,CAAC,EAAE,OAAO,OAAO,MAAM,EAAE,IAAI;AACnC,WAAO,GAAG,KAAK,IAAI,KAAK,GAAG,GAAG;AAAA,EAChC;AAEA,MAAI,+BAA+B,KAAK,OAAO,EAAG,QAAO;AAGzD,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/lib/version.ts"],"sourcesContent":["// Generated version information\n// This file is auto-generated by sync-version.ts\n\n/**\n * AdCP SDK library version\n */\nexport const LIBRARY_VERSION = '12.0.4';\n\n/**\n * AdCP specification version this library is built for\n */\nexport const ADCP_VERSION = '3.1.2';\n\n/**\n * AdCP major version sent with every request (adcp_major_version field).\n * Sellers validate this against their supported versions and return\n * VERSION_UNSUPPORTED if the version is not in range.\n */\nexport const ADCP_MAJOR_VERSION = 3;\n\n/**\n * AdCP versions this library maintains backward compatibility with.\n *\n * Auto-derived from `ADCP_VERSION` by scripts/sync-version.ts. Do not edit\n * this list by hand; bumping the AdCP pin via `npm run sync-version`\n * extends it.\n */\nexport const COMPATIBLE_ADCP_VERSIONS = [\n 'v2.5',\n 'v2.6',\n 'v3',\n '3.0.0-beta.1',\n '3.0-beta.1',\n '3.0-beta',\n '3.0.0-beta.3',\n '3.0-beta.3',\n '3.0.0',\n '3.0',\n '3.0.1',\n '3.0.2',\n '3.0.3',\n '3.0.4',\n '3.0.5',\n '3.0.6',\n '3.0.7',\n '3.0.8',\n '3.0.9',\n '3.0.10',\n '3.0.11',\n '3.0.12',\n '3.1.0',\n '3.1',\n '3.1.1',\n '3.1.2',\n] as const;\n\n/**\n * String literal union of every AdCP version the SDK formally supports.\n *\n * Used by the per-instance `adcpVersion` constructor option to give callers\n * autocomplete in editors. The intersection with `(string & {})` in the\n * config type preserves the escape hatch — any string is still accepted at\n * the type level — while the literal union surfaces canonical values first.\n */\nexport type AdcpVersion = (typeof COMPATIBLE_ADCP_VERSIONS)[number];\n\n/**\n * Full version information\n */\nexport const VERSION_INFO = {\n library: '12.0.4',\n adcp: '3.1.2',\n compatibleVersions: COMPATIBLE_ADCP_VERSIONS,\n generatedAt: '2026-07-21T22:42:42.739Z',\n} as const;\n\n/**\n * Get the AdCP specification version this library is built for\n */\nexport function getAdcpVersion(): string {\n return ADCP_VERSION;\n}\n\n/**\n * Get the library version\n */\nexport function getLibraryVersion(): string {\n return LIBRARY_VERSION;\n}\n\n/**\n * Check if this library version is compatible with a given AdCP version\n */\nexport function isCompatibleWith(adcpVersion: string): boolean {\n return (COMPATIBLE_ADCP_VERSIONS as readonly string[]).includes(adcpVersion);\n}\n\n/**\n * Get all AdCP versions this library is compatible with\n */\nexport function getCompatibleVersions(): readonly string[] {\n return COMPATIBLE_ADCP_VERSIONS;\n}\n\n/**\n * Extract the major version number from an AdCP version string.\n *\n * Accepts:\n * - Semver: '3.0.0', '3.0.1', '3.1.0-beta.1' → 3\n * - Legacy aliases: 'v3' → 3, 'v2.5' / 'v2.6' → 2\n *\n * Returns NaN for unrecognized strings — callers should validate before passing.\n */\nexport function parseAdcpMajorVersion(version: string): number {\n const trimmed = version.trim();\n const semverLike = trimmed.startsWith('v') ? trimmed.slice(1) : trimmed;\n const major = parseInt(semverLike.split('.')[0] ?? '', 10);\n return Number.isFinite(major) ? major : NaN;\n}\n\n/**\n * Normalize a full-semver AdCP version (`MAJOR.MINOR.PATCH[-prerelease]`) to\n * the release-precision form that AdCP 3.1+ requires on the wire:\n * `MAJOR.MINOR[-prerelease]` — the patch digit is dropped.\n *\n * Per the spec note on `adcp_version`: \"SDKs that read full-semver values\n * from bundle metadata (e.g. `ComplianceIndex.published_version =\n * \"3.1.0-beta.1\"`) MUST normalize to release-precision (`\"3.1-beta.1\"`)\n * before emitting on the wire — meta-field values are NOT valid wire\n * values.\" The wire regex (`^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`) rejects strings\n * with a patch digit.\n *\n * Behavior:\n * - `\"3.1.0-beta.7\"` → `\"3.1-beta.7\"`\n * - `\"3.1.0\"` → `\"3.1\"`\n * - `\"3.0.12\"` → `\"3.0\"`\n * - Already-release-precision input (`\"3.1\"`, `\"3.1-beta.7\"`) passes through\n * - Legacy aliases (`\"v2.5\"`, `\"v3\"`) pass through unchanged — the wire\n * regex doesn't accept them anyway; the v2.5 path uses\n * `adcp_major_version` instead of `adcp_version` for transport.\n * - Unrecognized strings pass through unchanged so callers can detect drift\n * via the wire validator rather than have it masked by this helper.\n */\nexport function toReleasePrecisionVersion(version: string): string {\n const trimmed = version.trim();\n // Pre-release form `MAJOR.MINOR.PATCH-prerelease` → `MAJOR.MINOR-prerelease`\n const semverMatch = trimmed.match(/^(\\d+)\\.(\\d+)\\.\\d+(-[A-Za-z0-9.-]+)?$/);\n if (semverMatch) {\n const [, major, minor, pre = ''] = semverMatch;\n return `${major}.${minor}${pre}`;\n }\n // Already release-precision (no patch digit). Includes `3.1`, `3.1-beta.7`.\n if (/^\\d+\\.\\d+(-[A-Za-z0-9.-]+)?$/.test(trimmed)) return trimmed;\n // Legacy aliases (`v3`, `v2.5`, `v2.6`) and anything we don't recognize —\n // pass through so the wire validator can flag genuine drift.\n return version;\n}\n"],"mappings":"AAMO,MAAM,kBAAkB;AAKxB,MAAM,eAAe;AAOrB,MAAM,qBAAqB;AAS3B,MAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAeO,MAAM,eAAe;AAAA,EAC1B,SAAS;AAAA,EACT,MAAM;AAAA,EACN,oBAAoB;AAAA,EACpB,aAAa;AACf;AAKO,SAAS,iBAAyB;AACvC,SAAO;AACT;AAKO,SAAS,oBAA4B;AAC1C,SAAO;AACT;AAKO,SAAS,iBAAiB,aAA8B;AAC7D,SAAQ,yBAA+C,SAAS,WAAW;AAC7E;AAKO,SAAS,wBAA2C;AACzD,SAAO;AACT;AAWO,SAAS,sBAAsB,SAAyB;AAC7D,QAAM,UAAU,QAAQ,KAAK;AAC7B,QAAM,aAAa,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAChE,QAAM,QAAQ,SAAS,WAAW,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AACzD,SAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;AAyBO,SAAS,0BAA0B,SAAyB;AACjE,QAAM,UAAU,QAAQ,KAAK;AAE7B,QAAM,cAAc,QAAQ,MAAM,uCAAuC;AACzE,MAAI,aAAa;AACf,UAAM,CAAC,EAAE,OAAO,OAAO,MAAM,EAAE,IAAI;AACnC,WAAO,GAAG,KAAK,IAAI,KAAK,GAAG,GAAG;AAAA,EAChC;AAEA,MAAI,+BAA+B,KAAK,OAAO,EAAG,QAAO;AAGzD,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adcp/sdk",
3
- "version": "12.0.3",
3
+ "version": "12.0.4",
4
4
  "description": "AdCP SDK — client, server, and compliance harnesses for the AdContext Protocol (MCP + A2A)",
5
5
  "workspaces": [
6
6
  ".",