@adcp/sdk 13.0.0-rc.4 → 13.0.0-rc.6

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.
Files changed (175) hide show
  1. package/README.md +7 -1
  2. package/bin/adcp.js +7 -1
  3. package/dist/lib/adapters/property-list-adapter.d.mts +5 -1
  4. package/dist/lib/adapters/property-list-adapter.d.ts +5 -1
  5. package/dist/lib/adapters/property-list-adapter.d.ts.map +1 -1
  6. package/dist/lib/adapters/property-list-adapter.js +7 -7
  7. package/dist/lib/adapters/property-list-adapter.js.map +1 -1
  8. package/dist/lib/adapters/property-list-adapter.mjs +7 -7
  9. package/dist/lib/adapters/property-list-adapter.mjs.map +1 -1
  10. package/dist/lib/auth/oauth/CLIFlowHandler.d.mts +10 -3
  11. package/dist/lib/auth/oauth/CLIFlowHandler.d.ts +10 -3
  12. package/dist/lib/auth/oauth/CLIFlowHandler.d.ts.map +1 -1
  13. package/dist/lib/auth/oauth/CLIFlowHandler.js +40 -4
  14. package/dist/lib/auth/oauth/CLIFlowHandler.js.map +1 -1
  15. package/dist/lib/auth/oauth/CLIFlowHandler.mjs +40 -4
  16. package/dist/lib/auth/oauth/CLIFlowHandler.mjs.map +1 -1
  17. package/dist/lib/auth/oauth/index.d.mts +1 -1
  18. package/dist/lib/auth/oauth/index.d.ts +1 -1
  19. package/dist/lib/auth/oauth/index.d.ts.map +1 -1
  20. package/dist/lib/auth/oauth/index.js +2 -0
  21. package/dist/lib/auth/oauth/index.js.map +1 -1
  22. package/dist/lib/auth/oauth/index.mjs +2 -0
  23. package/dist/lib/auth/oauth/index.mjs.map +1 -1
  24. package/dist/lib/auth/oauth/web-flow.d.mts +12 -0
  25. package/dist/lib/auth/oauth/web-flow.d.ts +12 -0
  26. package/dist/lib/auth/oauth/web-flow.d.ts.map +1 -1
  27. package/dist/lib/auth/oauth/web-flow.js +20 -2
  28. package/dist/lib/auth/oauth/web-flow.js.map +1 -1
  29. package/dist/lib/auth/oauth/web-flow.mjs +19 -2
  30. package/dist/lib/auth/oauth/web-flow.mjs.map +1 -1
  31. package/dist/lib/core/AgentClient.d.ts.map +1 -1
  32. package/dist/lib/core/SingleAgentClient.d.mts +27 -1
  33. package/dist/lib/core/SingleAgentClient.d.ts +27 -1
  34. package/dist/lib/core/SingleAgentClient.d.ts.map +1 -1
  35. package/dist/lib/core/SingleAgentClient.js +46 -18
  36. package/dist/lib/core/SingleAgentClient.js.map +1 -1
  37. package/dist/lib/core/SingleAgentClient.mjs +46 -18
  38. package/dist/lib/core/SingleAgentClient.mjs.map +1 -1
  39. package/dist/lib/net/address-guards.d.ts.map +1 -1
  40. package/dist/lib/net/address-guards.js +4 -0
  41. package/dist/lib/net/address-guards.js.map +1 -1
  42. package/dist/lib/net/address-guards.mjs +4 -0
  43. package/dist/lib/net/address-guards.mjs.map +1 -1
  44. package/dist/lib/protocols/a2a.js +2 -2
  45. package/dist/lib/protocols/a2a.js.map +1 -1
  46. package/dist/lib/protocols/a2a.mjs +2 -2
  47. package/dist/lib/protocols/a2a.mjs.map +1 -1
  48. package/dist/lib/protocols/index.d.ts.map +1 -1
  49. package/dist/lib/protocols/index.js +28 -7
  50. package/dist/lib/protocols/index.js.map +1 -1
  51. package/dist/lib/protocols/index.mjs +28 -7
  52. package/dist/lib/protocols/index.mjs.map +1 -1
  53. package/dist/lib/protocols/mcp-modern.d.ts.map +1 -1
  54. package/dist/lib/protocols/mcp-modern.js +18 -5
  55. package/dist/lib/protocols/mcp-modern.js.map +1 -1
  56. package/dist/lib/protocols/mcp-modern.mjs +18 -5
  57. package/dist/lib/protocols/mcp-modern.mjs.map +1 -1
  58. package/dist/lib/protocols/mcp-tasks.d.ts.map +1 -1
  59. package/dist/lib/protocols/mcp-tasks.js +2 -12
  60. package/dist/lib/protocols/mcp-tasks.js.map +1 -1
  61. package/dist/lib/protocols/mcp-tasks.mjs +2 -12
  62. package/dist/lib/protocols/mcp-tasks.mjs.map +1 -1
  63. package/dist/lib/protocols/mcp.js +2 -2
  64. package/dist/lib/protocols/mcp.js.map +1 -1
  65. package/dist/lib/protocols/mcp.mjs +2 -2
  66. package/dist/lib/protocols/mcp.mjs.map +1 -1
  67. package/dist/lib/registry/types.generated.d.mts +554 -15
  68. package/dist/lib/registry/types.generated.d.ts +554 -15
  69. package/dist/lib/registry/types.generated.d.ts.map +1 -1
  70. package/dist/lib/registry/types.generated.js.map +1 -1
  71. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  72. package/dist/lib/server/decisioning/account.d.mts +6 -4
  73. package/dist/lib/server/decisioning/account.d.ts +6 -4
  74. package/dist/lib/server/decisioning/account.d.ts.map +1 -1
  75. package/dist/lib/server/decisioning/account.js.map +1 -1
  76. package/dist/lib/server/decisioning/account.mjs.map +1 -1
  77. package/dist/lib/server/decisioning/manifest-helpers.d.mts +6 -5
  78. package/dist/lib/server/decisioning/manifest-helpers.d.ts +6 -5
  79. package/dist/lib/server/decisioning/manifest-helpers.d.ts.map +1 -1
  80. package/dist/lib/server/decisioning/manifest-helpers.js.map +1 -1
  81. package/dist/lib/server/decisioning/manifest-helpers.mjs.map +1 -1
  82. package/dist/lib/server/decisioning/runtime/from-platform.js +4 -2
  83. package/dist/lib/server/decisioning/runtime/from-platform.js.map +1 -1
  84. package/dist/lib/server/decisioning/runtime/from-platform.mjs +4 -2
  85. package/dist/lib/server/decisioning/runtime/from-platform.mjs.map +1 -1
  86. package/dist/lib/server/decisioning/tenant-store.d.mts +26 -14
  87. package/dist/lib/server/decisioning/tenant-store.d.ts +26 -14
  88. package/dist/lib/server/decisioning/tenant-store.d.ts.map +1 -1
  89. package/dist/lib/server/decisioning/tenant-store.js +6 -1
  90. package/dist/lib/server/decisioning/tenant-store.js.map +1 -1
  91. package/dist/lib/server/decisioning/tenant-store.mjs +6 -1
  92. package/dist/lib/server/decisioning/tenant-store.mjs.map +1 -1
  93. package/dist/lib/server/pin-and-bind-fetch.d.mts +2 -0
  94. package/dist/lib/server/pin-and-bind-fetch.d.ts +2 -0
  95. package/dist/lib/server/pin-and-bind-fetch.d.ts.map +1 -1
  96. package/dist/lib/server/pin-and-bind-fetch.js +2 -0
  97. package/dist/lib/server/pin-and-bind-fetch.js.map +1 -1
  98. package/dist/lib/server/pin-and-bind-fetch.mjs +2 -0
  99. package/dist/lib/server/pin-and-bind-fetch.mjs.map +1 -1
  100. package/dist/lib/server/structured-serialize.d.ts.map +1 -1
  101. package/dist/lib/server/structured-serialize.js +10 -2
  102. package/dist/lib/server/structured-serialize.js.map +1 -1
  103. package/dist/lib/server/structured-serialize.mjs +10 -2
  104. package/dist/lib/server/structured-serialize.mjs.map +1 -1
  105. package/dist/lib/server/webhook-emitter.d.ts.map +1 -1
  106. package/dist/lib/server/webhook-emitter.js +4 -2
  107. package/dist/lib/server/webhook-emitter.js.map +1 -1
  108. package/dist/lib/server/webhook-emitter.mjs +4 -2
  109. package/dist/lib/server/webhook-emitter.mjs.map +1 -1
  110. package/dist/lib/signing/middleware.d.mts +2 -1
  111. package/dist/lib/signing/middleware.d.ts +2 -1
  112. package/dist/lib/signing/middleware.d.ts.map +1 -1
  113. package/dist/lib/signing/middleware.js +26 -4
  114. package/dist/lib/signing/middleware.js.map +1 -1
  115. package/dist/lib/signing/middleware.mjs +26 -4
  116. package/dist/lib/signing/middleware.mjs.map +1 -1
  117. package/dist/lib/signing/webhook-verifier.d.ts.map +1 -1
  118. package/dist/lib/signing/webhook-verifier.js +4 -2
  119. package/dist/lib/signing/webhook-verifier.js.map +1 -1
  120. package/dist/lib/signing/webhook-verifier.mjs +4 -2
  121. package/dist/lib/signing/webhook-verifier.mjs.map +1 -1
  122. package/dist/lib/testing/agent-tester.d.ts.map +1 -1
  123. package/dist/lib/testing/agent-tester.js +46 -1
  124. package/dist/lib/testing/agent-tester.js.map +1 -1
  125. package/dist/lib/testing/agent-tester.mjs +46 -1
  126. package/dist/lib/testing/agent-tester.mjs.map +1 -1
  127. package/dist/lib/types/asset-instances.d.mts +8 -6
  128. package/dist/lib/types/asset-instances.d.ts +8 -6
  129. package/dist/lib/types/asset-instances.d.ts.map +1 -1
  130. package/dist/lib/types/asset-instances.js.map +1 -1
  131. package/dist/lib/types/index.d.ts.map +1 -1
  132. package/dist/lib/types/index.js.map +1 -1
  133. package/dist/lib/types/index.mjs.map +1 -1
  134. package/dist/lib/utils/capabilities.d.mts +2 -0
  135. package/dist/lib/utils/capabilities.d.ts +2 -0
  136. package/dist/lib/utils/capabilities.d.ts.map +1 -1
  137. package/dist/lib/utils/capabilities.js +2 -1
  138. package/dist/lib/utils/capabilities.js.map +1 -1
  139. package/dist/lib/utils/capabilities.mjs +2 -1
  140. package/dist/lib/utils/capabilities.mjs.map +1 -1
  141. package/dist/lib/utils/probe-policy.d.mts +0 -16
  142. package/dist/lib/utils/probe-policy.d.ts +0 -16
  143. package/dist/lib/utils/probe-policy.d.ts.map +1 -1
  144. package/dist/lib/utils/probe-policy.js +15 -1
  145. package/dist/lib/utils/probe-policy.js.map +1 -1
  146. package/dist/lib/utils/probe-policy.mjs +15 -1
  147. package/dist/lib/utils/probe-policy.mjs.map +1 -1
  148. package/dist/lib/utils/redact-args.d.mts +36 -0
  149. package/dist/lib/utils/redact-args.d.ts +37 -0
  150. package/dist/lib/utils/redact-args.d.ts.map +1 -0
  151. package/dist/lib/utils/redact-args.js +46 -0
  152. package/dist/lib/utils/redact-args.js.map +1 -0
  153. package/dist/lib/utils/redact-args.mjs +22 -0
  154. package/dist/lib/utils/redact-args.mjs.map +1 -0
  155. package/dist/lib/v2/projection/creative-delivery.js +1 -5
  156. package/dist/lib/v2/projection/creative-delivery.js.map +1 -1
  157. package/dist/lib/v2/projection/creative-delivery.mjs +1 -5
  158. package/dist/lib/v2/projection/creative-delivery.mjs.map +1 -1
  159. package/dist/lib/validation/index.d.mts +15 -1
  160. package/dist/lib/validation/index.d.ts +15 -1
  161. package/dist/lib/validation/index.d.ts.map +1 -1
  162. package/dist/lib/validation/index.js +4 -8
  163. package/dist/lib/validation/index.js.map +1 -1
  164. package/dist/lib/validation/index.mjs +4 -8
  165. package/dist/lib/validation/index.mjs.map +1 -1
  166. package/dist/lib/version.d.mts +3 -3
  167. package/dist/lib/version.d.ts +3 -3
  168. package/dist/lib/version.js +3 -3
  169. package/dist/lib/version.js.map +1 -1
  170. package/dist/lib/version.mjs +3 -3
  171. package/dist/lib/version.mjs.map +1 -1
  172. package/examples/hello_seller_adapter_multi_tenant.ts +7 -0
  173. package/package.json +3 -2
  174. package/skills/build-holdco-agent/SKILL.md +19 -0
  175. package/skills/cross-cutting.md +3 -1
@@ -106,6 +106,14 @@ function buildVersionEnvelope(adcpVersion, serverVersion) {
106
106
  (0, import_schema_loader.validateAdcpVersionWire)(wireValue);
107
107
  return { adcp_major_version: wireMajor, adcp_version: wireValue };
108
108
  }
109
+ let hasWarnedAboutV2PushNotificationSecret = false;
110
+ function warnV2PushNotificationNeedsSecret() {
111
+ if (hasWarnedAboutV2PushNotificationSecret) return;
112
+ hasWarnedAboutV2PushNotificationSecret = true;
113
+ console.warn(
114
+ "[adcp] Suppressing push_notification_config for a v2 seller: AdCP 2.5 requires an `authentication` block and no `webhookSecret` is configured. Set `webhookSecret` to register async task-status webhooks with this agent, or move the agent to an AdCP 3.x pin, where the RFC 9421 webhook profile needs no shared secret."
115
+ );
116
+ }
109
117
  function buildVersionEnvelopeForMode(mode, adcpVersion, serverVersion) {
110
118
  if (mode === "none" || serverVersion === "v2") return {};
111
119
  if (mode === "major-only") return { adcp_major_version: resolveWireMajor(adcpVersion) };
@@ -201,14 +209,27 @@ class ProtocolClient {
201
209
  );
202
210
  }
203
211
  const argsWithVersion = applyVersionEnvelope(args, versionEnvelope);
204
- const pushNotificationConfig = webhookUrl ? {
205
- url: webhookUrl,
206
- ...webhookToken && { token: webhookToken },
207
- authentication: {
208
- schemes: ["HMAC-SHA256"],
209
- credentials: webhookSecret || "placeholder_secret_min_32_characters_required"
212
+ const pushNotificationConfig = (() => {
213
+ if (!webhookUrl) return void 0;
214
+ if (webhookSecret) {
215
+ return {
216
+ url: webhookUrl,
217
+ ...webhookToken && { token: webhookToken },
218
+ authentication: {
219
+ schemes: ["HMAC-SHA256"],
220
+ credentials: webhookSecret
221
+ }
222
+ };
223
+ }
224
+ if (serverVersion === "v2") {
225
+ warnV2PushNotificationNeedsSecret();
226
+ return void 0;
210
227
  }
211
- } : void 0;
228
+ return {
229
+ url: webhookUrl,
230
+ ...webhookToken && { token: webhookToken }
231
+ };
232
+ })();
212
233
  if (agent.protocol === "mcp") {
213
234
  const argsWithWebhook = pushNotificationConfig ? { ...argsWithVersion, push_notification_config: pushNotificationConfig } : argsWithVersion;
214
235
  if (agent.oauth_tokens && !agent.oauth_client_credentials) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/index.ts"],"sourcesContent":["// Unified Protocol Interface for AdCP\nexport {\n callMCPTool,\n callMCPToolWithOAuth,\n connectMCP,\n closeMCPConnections,\n closeOAuthConnections,\n UnauthorizedError,\n} from './mcp';\n\nimport { closeMCPConnections } from './mcp';\nimport { closeA2AConnections } from './a2a';\n\n/**\n * Close protocol connections for the given protocol.\n * MCP closes persistent HTTP transports; A2A clears the agent-card client cache.\n */\nexport async function closeConnections(protocol: 'mcp' | 'a2a' = 'mcp'): Promise<void> {\n if (protocol === 'mcp') {\n await closeMCPConnections();\n } else {\n closeA2AConnections();\n }\n}\nexport type { MCPCallOptions, MCPConnectionResult } from './mcp';\nexport { callA2ATool } from './a2a';\nexport { DEFAULT_REQUEST_TIMEOUT_MS } from './abort';\nexport {\n callMCPToolWithTasks,\n getMCPTaskStatus,\n getMCPTaskResult,\n listMCPTasks,\n cancelMCPTask,\n mapMCPTaskStatus,\n serverSupportsTasks,\n} from './mcp-tasks';\n\nimport { callMCPToolWithTasks, callMCPToolWithClient } from './mcp-tasks';\nimport { callMCPToolWithOAuth } from './mcp';\nimport { callA2ATool } from './a2a';\nimport type { AgentConfig, DebugLogEntry } from '../types';\nimport type { PushNotificationConfig } from '../types/tools.generated';\nimport { getAuthToken } from '../auth';\nimport {\n discoverAuthorizationRequirements,\n NeedsAuthorizationError,\n getAgentStorage,\n ensureClientCredentialsTokens,\n} from '../auth/oauth';\nimport { getNonInteractiveOAuthProvider } from '../auth/oauth/provider-cache';\nimport { is401Error } from '../errors';\nimport { isLikelyPrivateUrl } from '../net';\nimport { validateAgentUrl } from '../validation';\nimport { withSpan } from '../observability/tracing';\nimport { ADCP_MAJOR_VERSION, ADCP_VERSION, parseAdcpMajorVersion } from '../version';\nimport { ConfigurationError } from '../errors';\nimport { resolveBundleKey, toReleasePrecisionWire, validateAdcpVersionWire } from '../validation/schema-loader';\nimport { buildAgentSigningContext, CAPABILITY_OP, ensureCapabilityLoaded } from '../signing/client';\nimport { withResponseSizeLimit } from './responseSizeLimit';\nimport {\n withTransportDiagnostics,\n type TransportActivityHandler as TransportActivityHandlerFn,\n} from './transportDiagnostics';\n\nexport {\n sanitizeTransportHeaders,\n sanitizeTransportUrl,\n withTransportDiagnostics,\n wrapFetchWithTransportDiagnostics,\n} from './transportDiagnostics';\nexport type { TransportActivity, TransportActivityContext, TransportActivityHandler } from './transportDiagnostics';\n\nexport type VersionEnvelopeMode = 'auto' | 'none' | 'major-only';\n\n/**\n * Derive the wire-level `adcp_major_version` integer from a caller-supplied\n * pin. Returns the SDK default when no pin is provided; throws on a pin\n * that doesn't parse so misuse surfaces at the factory boundary instead\n * of silently emitting the SDK's major.\n *\n * Throws `ConfigurationError` (not a plain `Error`) so a typo'd pin\n * surfaces with the same error class as the construction-time gate in\n * `resolveAdcpVersion` — one shape for all pin-misuse paths.\n */\nfunction resolveWireMajor(adcpVersion: string | undefined): number {\n if (adcpVersion === undefined) return ADCP_MAJOR_VERSION;\n const parsed = parseAdcpMajorVersion(adcpVersion);\n if (!Number.isFinite(parsed)) {\n throw new ConfigurationError(\n `adcpVersion ${JSON.stringify(adcpVersion)} is not a valid AdCP version. ` +\n `Expected a semver string (e.g. '3.0.1', '3.1.0-beta.1') or a legacy alias (e.g. 'v3').`,\n 'adcpVersion'\n );\n }\n return parsed;\n}\n\n/**\n * Returns true when the AdCP release that `bundleKey` identifies declares the\n * top-level `adcp_version` envelope field. The field landed in AdCP 3.1 per\n * spec PR `adcontextprotocol/adcp#3493` — 3.0 (any patch / prerelease) does\n * not carry it; 3.1+ does. Used to gate dual-emit on the wire so a 3.0-pinned\n * client doesn't emit a field its target schema doesn't define.\n */\nexport function bundleSupportsAdcpVersionField(bundleKey: string): boolean {\n const major = parseAdcpMajorVersion(bundleKey);\n if (!Number.isFinite(major)) return false;\n if (major < 3) return false;\n if (major > 3) return true;\n // Major 3 — only 3.1+ has the field. Bundle key shape is normalized by\n // `resolveBundleKey`: `'3.0'` / `'3.1'` for stable; `'3.0.0-beta.1'` /\n // `'3.1.0-beta.1'` for prereleases. Match the minor.\n const minorMatch = bundleKey.match(/^\\d+\\.(\\d+)/);\n if (!minorMatch) return false;\n return parseInt(minorMatch[1]!, 10) >= 1;\n}\n\n/**\n * Build the wire-level version envelope to merge into outgoing request args.\n *\n * Per AdCP 3.1 (spec PR `adcontextprotocol/adcp#3493`), 3.1+ requests carry\n * BOTH the integer `adcp_major_version` (deprecated through 3.x, removed in\n * 4.0) AND the release-precision string `adcp_version`. 3.0 schemas don't\n * define the string field, so a 3.0-pinned client emits the integer only —\n * matches the 3.0 spec exactly.\n *\n * Wire string is release-precision (MAJOR.MINOR with optional prerelease tag),\n * per `core/version-envelope.json`'s pattern `^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`.\n * Full-semver bundle keys (`'3.1.0-beta.1'`) are collapsed via\n * `toReleasePrecisionWire` to `'3.1-beta.1'` before emit — meta-field shapes\n * are explicitly NOT valid wire values per the envelope schema's own\n * normalization rule.\n *\n * Returns `{}` for v2 callers (predates the major-version field entirely).\n */\nfunction buildVersionEnvelope(\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (serverVersion === 'v2') return {};\n const wireMajor = resolveWireMajor(adcpVersion);\n const bundleKey = resolveBundleKey(adcpVersion ?? ADCP_VERSION);\n if (!bundleSupportsAdcpVersionField(bundleKey)) {\n return { adcp_major_version: wireMajor };\n }\n const wireValue = toReleasePrecisionWire(bundleKey);\n // Defensive postcondition — should never throw in well-formed code, but\n // if a future refactor breaks the normalization the error message tells\n // the developer to call `toReleasePrecisionWire` instead of silently\n // emitting a non-spec wire string.\n validateAdcpVersionWire(wireValue);\n return { adcp_major_version: wireMajor, adcp_version: wireValue };\n}\n\nfunction buildVersionEnvelopeForMode(\n mode: VersionEnvelopeMode,\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (mode === 'none' || serverVersion === 'v2') return {};\n if (mode === 'major-only') return { adcp_major_version: resolveWireMajor(adcpVersion) };\n return buildVersionEnvelope(adcpVersion, serverVersion);\n}\n\n/**\n * Merge the wire-level version envelope into a caller-supplied args object.\n * Caller args win: an explicit `adcp_major_version` / `adcp_version` in\n * `args` (e.g. a conformance harness probing `VERSION_UNSUPPORTED`) passes\n * through unchanged. The envelope only fills fields the caller didn't set.\n *\n * Single chokepoint for all four wire-injection sites so a future refactor\n * can't silently flip the spread order on one branch and leave the others\n * intact. Stale dual-field drift is caught at the server boundary by\n * `createAdcpServer`'s field-disagreement check (spec PR\n * `adcontextprotocol/adcp#3493`).\n *\n * @internal\n */\nexport function applyVersionEnvelope(\n args: Record<string, unknown>,\n envelope: Record<string, unknown>\n): Record<string, unknown> {\n return { ...envelope, ...args };\n}\n\n/**\n * Transport-level safeguards applied to a call.\n *\n * Wired into the SDK's internal fetch chain via AsyncLocalStorage, so the\n * cap takes effect even when the underlying transport's connection cache\n * reuses a fetch that was created on an earlier call with different limits.\n */\nexport interface TransportOptions {\n /**\n * Maximum response body size (in octets) the SDK will read before aborting\n * with `ResponseTooLargeError`. When unset, the SDK does not impose a cap —\n * matches the underlying MCP / A2A transport defaults.\n *\n * Set this when crawling **untrusted** agents (registries, federated\n * discovery layers, monitoring tools) to prevent a hostile vendor from\n * buffering a large reply before any application-layer schema validation\n * runs. Counted across response chunks; pre-cancels when `Content-Length`\n * exceeds the cap. Applies to A2A agent-card discovery\n * (`/.well-known/agent.json`) on the same call as well.\n *\n * Per-call override (`TaskOptions.transport.maxResponseBytes`) beats the\n * value set on the client constructor (`SingleAgentClientConfig.transport`).\n *\n * @remarks\n * **Safe to set on all calls.** SSE responses (`text/event-stream`) are\n * passed through unchanged — a single tool call legitimately emits N status\n * frames + a final result, bounded by protocol-level framing rather than\n * cumulative byte counts. The cap applies to one-shot JSON responses\n * (`get_adcp_capabilities`, agent-card lookup, tool result payloads on\n * non-streaming transports) where the body is bounded by definition.\n *\n * @remarks\n * **Hostile-peer note:** A peer can opt itself out of this cap by responding\n * with `Content-Type: text/event-stream`. SSE is bypassed because cumulative\n * event-frame bytes are unbounded by spec — MCP and A2A both stream tool\n * responses this way. The MCP/A2A SDKs consume SSE incrementally and frame\n * termination bounds memory in practice, so this is not a memory-bomb risk\n * for well-formed transports. Adopters relying on `maxResponseBytes` as a\n * hostile-server defense should treat it as best-effort for non-SSE\n * responses only.\n *\n * @remarks\n * Future hardening knobs (DNS-rebind defense, scheme allow-list, request\n * timeout overrides) will land here as additional fields. When `fetchFn`\n * is supplied, the SDK composes it inside its signing, capture, size-limit,\n * timeout, and diagnostics wrappers so callers do not have to reproduce\n * that non-obvious ordering themselves.\n */\n maxResponseBytes?: number;\n /**\n * Scoped fetch implementation for all outbound HTTP performed on behalf of\n * this client or call, including endpoint/card discovery, tool listing,\n * OAuth discovery and token refresh, and MCP/A2A tool requests.\n *\n * The function is runtime-only configuration and is never serialized into\n * agent records, storyboard artifacts, or compliance output. When unset,\n * the SDK uses the global `fetch` implementation.\n *\n * For SSRF-sensitive metadata probes, supplying this function makes it the\n * trusted network boundary: the SDK still validates schemes and resolved\n * addresses, but a custom fetch API cannot accept the SDK's pinned undici\n * dispatcher. The implementation must therefore prevent DNS rebinding (for\n * example with an egress proxy or its own DNS pinning).\n */\n fetchFn?: typeof fetch;\n /**\n * Timeout in milliseconds for bounded one-shot transport requests such as\n * A2A agent-card discovery and MCP read-path probes. Defaults to 60 seconds\n * for A2A discovery so an unresponsive card endpoint cannot hang forever.\n * Set to `0` to disable the SDK-imposed discovery timeout.\n */\n requestTimeoutMs?: number;\n}\n\n/**\n * Options for {@link ProtocolClient.callTool}. All fields are optional.\n *\n * `webhookUrl` / `webhookSecret` / `webhookToken` are for ASYNC TASK STATUS\n * notifications (push_notification_config). For reporting webhooks\n * (reporting_webhook), include them directly in `args` — they stay in skill\n * parameters and are sent verbatim to the agent.\n */\nexport interface CallToolOptions {\n /** Debug log array. Mutated in place by the protocol layer. */\n debugLogs?: DebugLogEntry[];\n /** URL for async task status notifications. */\n webhookUrl?: string;\n /** HMAC-SHA256 secret for push_notification_config authentication. */\n webhookSecret?: string;\n /** Bearer token for push_notification_config validation. */\n webhookToken?: string;\n /** Pinned protocol generation when the agent advertises both v2 and v3. */\n serverVersion?: 'v2' | 'v3';\n /** A2A session continuity (contextId carries conversation, taskId resumes a task). */\n session?: { contextId?: string; taskId?: string };\n /**\n * AdCP version pin from the calling client/server instance. Sets the\n * wire-level `adcp_major_version` field per-call instead of from the\n * SDK-pinned `ADCP_MAJOR_VERSION` constant. Default falls back to the\n * constant so call sites that don't plumb a per-instance version keep\n * their existing behavior. An explicit `adcp_major_version` /\n * `adcp_version` in `args` overrides this — conformance harnesses use\n * that path to probe seller version negotiation.\n */\n adcpVersion?: string;\n /**\n * Optional wire-only version override. Schema selection and client\n * construction can remain pinned to `adcpVersion`; the request envelope is\n * emitted for this release-precision line.\n */\n wireAdcpVersion?: string;\n /**\n * Controls whether the SDK injects AdCP version envelope fields into the\n * outgoing request. Defaults to `auto`. 3.0 pins emit only the legacy\n * `adcp_major_version`; 3.1+ pins emit both the legacy major and exact\n * `adcp_version` marker. `major-only` forces the legacy integer marker\n * without the 3.1 string marker for strict pre-3.1 peers discovered at\n * runtime.\n */\n versionEnvelope?: VersionEnvelopeMode;\n /**\n * Transport-level safeguards (size caps, etc.). Per-call override of any\n * matching field on the client constructor's `transport` option.\n */\n transport?: TransportOptions;\n /** Caller-owned cancellation signal for the in-flight protocol call. */\n signal?: AbortSignal;\n /** Transport-level diagnostics callback for outbound HTTP requests. */\n onTransportActivity?: TransportActivityHandlerFn;\n /**\n * Correlation metadata attached to transport diagnostics events emitted\n * while this protocol call is active.\n */\n transportActivityContext?: {\n operationId?: string;\n taskId?: string;\n contextId?: string;\n idempotencyKey?: string;\n };\n}\n\n/**\n * Universal protocol client - automatically routes to the correct protocol implementation\n */\nexport class ProtocolClient {\n /**\n * Call a tool on an agent using the appropriate protocol.\n *\n * @param agent - Agent configuration\n * @param toolName - Name of the tool/skill to call\n * @param args - Tool arguments (includes reporting_webhook if needed - NOT removed)\n * @param options - Optional call-level configuration. See {@link CallToolOptions}.\n */\n static async callTool(\n agent: AgentConfig,\n toolName: string,\n args: Record<string, unknown>,\n options: CallToolOptions = {}\n ): Promise<unknown> {\n const {\n debugLogs = [],\n webhookUrl,\n webhookSecret,\n webhookToken,\n serverVersion,\n session,\n adcpVersion,\n wireAdcpVersion,\n versionEnvelope: versionEnvelopeMode = 'auto',\n transport,\n signal,\n onTransportActivity,\n transportActivityContext,\n } = options;\n // Per-instance version envelope. Throws on unparseable pins via\n // `resolveWireMajor`; construction-time `resolveAdcpVersion` is the\n // primary gate but this is the failsafe for callers reaching\n // `ProtocolClient.callTool` directly (test harnesses, the in-process\n // MCP path). Returns `{ adcp_major_version }` for 3.0 pins and\n // `{ adcp_major_version, adcp_version }` for 3.1+ pins.\n const versionEnvelope = buildVersionEnvelopeForMode(\n versionEnvelopeMode,\n wireAdcpVersion ?? adcpVersion,\n serverVersion\n );\n // Enter the response-size-limit ALS slot once for this call. The slot is\n // read by `wrapFetchWithSizeLimit` in both protocol transports, so the\n // cap applies regardless of which path (MCP / A2A / OAuth refresh) the\n // call ends up taking. No-op when the cap is unset or non-positive.\n return withResponseSizeLimit(transport?.maxResponseBytes, () =>\n withTransportDiagnostics(\n {\n agentId: agent.id,\n protocol: agent.protocol,\n tool: toolName,\n taskType: toolName,\n ...transportActivityContext,\n onTransportActivity,\n },\n () =>\n withSpan(\n `adcp.${agent.protocol}.call_tool`,\n {\n 'adcp.agent_id': agent.id,\n 'adcp.protocol': agent.protocol,\n 'adcp.tool': toolName,\n 'http.url': agent.agent_uri,\n },\n async () => {\n // In-process MCP path: pre-connected client, no HTTP transport.\n // Idempotency injection, schema validation, and governance middleware all\n // still apply (they run in SingleAgentClient above this call). We skip\n // URL validation, OAuth refresh, and signing — none apply in-process.\n if (agent.protocol === 'mcp' && agent._inProcessMcpClient) {\n const inProcArgs = applyVersionEnvelope(args, versionEnvelope);\n return callMCPToolWithClient(agent._inProcessMcpClient, toolName, inProcArgs, debugLogs, {\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n });\n }\n\n validateAgentUrl(agent.agent_uri);\n\n // OAuth 2.0 client credentials (RFC 6749 §4.4): re-exchange the\n // secret for a fresh access token whenever the cached one is within\n // its expiration skew. Runs before every call so mid-session expiry\n // can't leave the caller with a stale bearer. No-op if the agent\n // doesn't declare client credentials. Cheap on warm cache (single\n // `Date.now()` compare); a single POST to the token endpoint on miss.\n //\n // `allowPrivateIp` inherits the trust the caller already placed in\n // `agent.agent_uri` — if they're making a call to a private-IP agent,\n // they've authorized this process to talk to private-IP hosts, so\n // the token endpoint on the same network is reachable too. Public\n // agent URLs with private-IP token endpoints still require an\n // explicit opt-in via the library API.\n if (agent.oauth_client_credentials) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n }\n\n const authToken = getAuthToken(agent);\n\n // RFC 9421 signing context. Built once per call and passed through\n // to each protocol-layer entry (`callMCPToolWithTasks`, `callA2ATool`,\n // `callMCPToolWithOAuth`) — those entries seed `signingContextStorage`\n // (AsyncLocalStorage) so the internal transport helpers read it\n // without an explicit parameter. Keep the explicit arg here: it's the\n // ALS seed, not incidental plumbing. `get_adcp_capabilities` is\n // exempt from signing (it's the discovery call itself) and also\n // triggers cache priming for any other op on agents with\n // `request_signing` configured.\n const signingContext = buildAgentSigningContext(agent);\n if (signingContext && toolName !== CAPABILITY_OP) {\n await ensureCapabilityLoaded(agent, signingContext, primeArgs =>\n ProtocolClient.callTool(agent, CAPABILITY_OP, primeArgs, {\n debugLogs,\n serverVersion,\n adcpVersion,\n ...(versionEnvelopeMode !== 'auto' && { versionEnvelope: versionEnvelopeMode }),\n transport,\n signal,\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n onTransportActivity,\n transportActivityContext,\n })\n );\n }\n\n // Inject the version envelope on every request so sellers can validate\n // compatibility. Skip for v2 servers — they don't recognise the\n // version fields and strict-schema agents reject them. The envelope\n // shape is per-pin: 3.0 pins get the integer `adcp_major_version`\n // alone; 3.1+ pins get both that and the release-precision string\n // `adcp_version` (`'3.1'` / `'3.1.0-beta.1'`) per spec PR\n // `adcontextprotocol/adcp#3493`.\n const argsWithVersion = applyVersionEnvelope(args, versionEnvelope);\n\n // Build push_notification_config for ASYNC TASK STATUS notifications\n // (NOT for reporting_webhook - that stays in args)\n // Schema: https://adcontextprotocol.org/schemas/v1/core/push-notification-config.json\n const pushNotificationConfig: PushNotificationConfig | undefined = webhookUrl\n ? {\n url: webhookUrl,\n ...(webhookToken && { token: webhookToken }),\n authentication: {\n schemes: ['HMAC-SHA256'],\n credentials: webhookSecret || 'placeholder_secret_min_32_characters_required',\n },\n }\n : undefined;\n\n if (agent.protocol === 'mcp') {\n // For MCP, include push_notification_config in tool arguments (MCP spec)\n const argsWithWebhook = pushNotificationConfig\n ? { ...argsWithVersion, push_notification_config: pushNotificationConfig }\n : argsWithVersion;\n\n // If the agent config carries authorization-code OAuth tokens,\n // route through the OAuth provider path so the MCP SDK can refresh\n // on 401 instead of hard-failing. Excludes client-credentials\n // agents: they have a cached access token but no refresh_token,\n // and their refresh path is a secret re-exchange (handled above),\n // not the SDK's refresh_token grant.\n if (agent.oauth_tokens && !agent.oauth_client_credentials) {\n const authProvider = getNonInteractiveOAuthProvider(agent, {\n agentHint: agent.id,\n storage: getAgentStorage(agent),\n allowHttp: isLikelyPrivateUrl(agent.agent_uri),\n });\n try {\n return await callMCPToolWithOAuth({\n agentUrl: agent.agent_uri,\n toolName,\n args: argsWithWebhook,\n authProvider,\n debugLogs,\n customHeaders: agent.headers,\n signingContext,\n signal,\n requestTimeoutMs: transport?.requestTimeoutMs,\n fetchFn: transport?.fetchFn,\n });\n } catch (err) {\n // Refresh failed or server rejected the refreshed token — walk the\n // discovery chain so the caller can distinguish \"re-auth needed\"\n // from other failure modes.\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n }\n\n // Use callMCPToolWithTasks which auto-detects server tasks capability\n // and falls back to standard callTool when tasks are not supported\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n authToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (err) {\n // Client-credentials agents: on 401, the AS may have rotated\n // something out-of-band. Force a fresh exchange and retry once\n // before surfacing the error. Bounded (single retry) so we don't\n // loop if the credentials are genuinely wrong.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n retryAuthToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else if (agent.protocol === 'a2a') {\n // For A2A, pass pushNotificationConfig separately (not in skill parameters)\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n authToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (err) {\n // Same single-retry-on-401 for client-credentials agents as the\n // MCP path above. Kept symmetric so A2A CC agents aren't a\n // second-class experience — including the NeedsAuthorizationError\n // rewrap on a retry that still 401s.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n retryAuthToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else {\n throw new Error(`Unsupported protocol: ${agent.protocol}`);\n }\n }\n )\n )\n );\n }\n}\n\n/**\n * If `err` looks like a 401 from the MCP transport, probe the agent for a\n * Bearer challenge and throw a {@link NeedsAuthorizationError} carrying\n * walked discovery metadata. If the error isn't a 401 or we can't build a\n * requirements record, return silently so the caller re-throws the original.\n *\n * Keeping this off the hot path: we only probe on error, and the probe is\n * a single unauthenticated `tools/list` POST — no retries, no DNS rebind.\n */\nasync function rethrowAsNeedsAuthorization(err: unknown, agentUrl: string, fetchFn?: typeof fetch): Promise<void> {\n if (err instanceof NeedsAuthorizationError) throw err;\n if (!is401Error(err)) return;\n\n // If the caller has already connected to the agent URL, they've implicitly\n // trusted it — inherit that trust for the discovery probe so loopback /\n // private-IP development agents work the same way as public ones.\n const allowPrivateIp = isLikelyPrivateUrl(agentUrl);\n\n // discoverAuthorizationRequirements internally catches network failures and\n // returns null rather than throwing — anything that escapes is a genuine\n // bug we want to surface rather than mask the 401 with.\n const requirements = await discoverAuthorizationRequirements(agentUrl, { allowPrivateIp, fetchFn });\n if (requirements) {\n throw new NeedsAuthorizationError(requirements);\n }\n // No requirements walked; let the caller re-throw the original error.\n}\n\n/**\n * Simple factory functions for protocol-specific clients.\n *\n * Both factories accept a `transport` argument that flows through to the\n * size-cap surface so callers reaching the factory exports honor the same\n * `maxResponseBytes` contract as `ProtocolClient.callTool`. Without it,\n * the factories would silently bypass the cap, which the public API\n * (`TransportOptions`) implies they honor.\n */\nexport const createMCPClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n // Validate the pin at factory time so a typo surfaces here rather than at\n // first call. `buildVersionEnvelope` throws via `resolveWireMajor` on bad\n // input — call it once to surface, then close over the envelope.\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, args: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callMCPToolWithTasks(\n agentUrl,\n toolName,\n applyVersionEnvelope(args, versionEnvelope),\n authToken,\n debugLogs,\n headers,\n {\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n )\n ),\n };\n};\n\nexport const createA2AClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, parameters: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callA2ATool(\n agentUrl,\n toolName,\n applyVersionEnvelope(parameters, versionEnvelope),\n authToken,\n debugLogs,\n undefined,\n headers,\n undefined,\n undefined,\n undefined,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n )\n ),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,iBAOO;AAEP,IAAAA,cAAoC;AACpC,iBAAoC;AAcpC,IAAAC,cAA4B;AAC5B,mBAA2C;AAC3C,uBAQO;AAEP,IAAAC,oBAA4D;AAC5D,IAAAF,cAAqC;AACrC,IAAAC,cAA4B;AAG5B,kBAA6B;AAC7B,mBAKO;AACP,4BAA+C;AAC/C,oBAA2B;AAC3B,iBAAmC;AACnC,wBAAiC;AACjC,qBAAyB;AACzB,qBAAwE;AACxE,IAAAE,iBA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AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,WAAW;AAAA,QACX,WAAW;AAAA,MACb;AAAA,IACF;AAAA,EACJ;AACF;","names":["import_mcp","import_a2a","import_mcp_tasks","import_errors","import_transportDiagnostics"]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/index.ts"],"sourcesContent":["// Unified Protocol Interface for AdCP\nexport {\n callMCPTool,\n callMCPToolWithOAuth,\n connectMCP,\n closeMCPConnections,\n closeOAuthConnections,\n UnauthorizedError,\n} from './mcp';\n\nimport { closeMCPConnections } from './mcp';\nimport { closeA2AConnections } from './a2a';\n\n/**\n * Close protocol connections for the given protocol.\n * MCP closes persistent HTTP transports; A2A clears the agent-card client cache.\n */\nexport async function closeConnections(protocol: 'mcp' | 'a2a' = 'mcp'): Promise<void> {\n if (protocol === 'mcp') {\n await closeMCPConnections();\n } else {\n closeA2AConnections();\n }\n}\nexport type { MCPCallOptions, MCPConnectionResult } from './mcp';\nexport { callA2ATool } from './a2a';\nexport { DEFAULT_REQUEST_TIMEOUT_MS } from './abort';\nexport {\n callMCPToolWithTasks,\n getMCPTaskStatus,\n getMCPTaskResult,\n listMCPTasks,\n cancelMCPTask,\n mapMCPTaskStatus,\n serverSupportsTasks,\n} from './mcp-tasks';\n\nimport { callMCPToolWithTasks, callMCPToolWithClient } from './mcp-tasks';\nimport { callMCPToolWithOAuth } from './mcp';\nimport { callA2ATool } from './a2a';\nimport type { AgentConfig, DebugLogEntry } from '../types';\nimport type { PushNotificationConfig } from '../types/tools.generated';\nimport { getAuthToken } from '../auth';\nimport {\n discoverAuthorizationRequirements,\n NeedsAuthorizationError,\n getAgentStorage,\n ensureClientCredentialsTokens,\n} from '../auth/oauth';\nimport { getNonInteractiveOAuthProvider } from '../auth/oauth/provider-cache';\nimport { is401Error } from '../errors';\nimport { isLikelyPrivateUrl } from '../net';\nimport { validateAgentUrl } from '../validation';\nimport { withSpan } from '../observability/tracing';\nimport { ADCP_MAJOR_VERSION, ADCP_VERSION, parseAdcpMajorVersion } from '../version';\nimport { ConfigurationError } from '../errors';\nimport { resolveBundleKey, toReleasePrecisionWire, validateAdcpVersionWire } from '../validation/schema-loader';\nimport { buildAgentSigningContext, CAPABILITY_OP, ensureCapabilityLoaded } from '../signing/client';\nimport { withResponseSizeLimit } from './responseSizeLimit';\nimport {\n withTransportDiagnostics,\n type TransportActivityHandler as TransportActivityHandlerFn,\n} from './transportDiagnostics';\n\nexport {\n sanitizeTransportHeaders,\n sanitizeTransportUrl,\n withTransportDiagnostics,\n wrapFetchWithTransportDiagnostics,\n} from './transportDiagnostics';\nexport type { TransportActivity, TransportActivityContext, TransportActivityHandler } from './transportDiagnostics';\n\nexport type VersionEnvelopeMode = 'auto' | 'none' | 'major-only';\n\n/**\n * Derive the wire-level `adcp_major_version` integer from a caller-supplied\n * pin. Returns the SDK default when no pin is provided; throws on a pin\n * that doesn't parse so misuse surfaces at the factory boundary instead\n * of silently emitting the SDK's major.\n *\n * Throws `ConfigurationError` (not a plain `Error`) so a typo'd pin\n * surfaces with the same error class as the construction-time gate in\n * `resolveAdcpVersion` — one shape for all pin-misuse paths.\n */\nfunction resolveWireMajor(adcpVersion: string | undefined): number {\n if (adcpVersion === undefined) return ADCP_MAJOR_VERSION;\n const parsed = parseAdcpMajorVersion(adcpVersion);\n if (!Number.isFinite(parsed)) {\n throw new ConfigurationError(\n `adcpVersion ${JSON.stringify(adcpVersion)} is not a valid AdCP version. ` +\n `Expected a semver string (e.g. '3.0.1', '3.1.0-beta.1') or a legacy alias (e.g. 'v3').`,\n 'adcpVersion'\n );\n }\n return parsed;\n}\n\n/**\n * Returns true when the AdCP release that `bundleKey` identifies declares the\n * top-level `adcp_version` envelope field. The field landed in AdCP 3.1 per\n * spec PR `adcontextprotocol/adcp#3493` — 3.0 (any patch / prerelease) does\n * not carry it; 3.1+ does. Used to gate dual-emit on the wire so a 3.0-pinned\n * client doesn't emit a field its target schema doesn't define.\n */\nexport function bundleSupportsAdcpVersionField(bundleKey: string): boolean {\n const major = parseAdcpMajorVersion(bundleKey);\n if (!Number.isFinite(major)) return false;\n if (major < 3) return false;\n if (major > 3) return true;\n // Major 3 — only 3.1+ has the field. Bundle key shape is normalized by\n // `resolveBundleKey`: `'3.0'` / `'3.1'` for stable; `'3.0.0-beta.1'` /\n // `'3.1.0-beta.1'` for prereleases. Match the minor.\n const minorMatch = bundleKey.match(/^\\d+\\.(\\d+)/);\n if (!minorMatch) return false;\n return parseInt(minorMatch[1]!, 10) >= 1;\n}\n\n/**\n * Build the wire-level version envelope to merge into outgoing request args.\n *\n * Per AdCP 3.1 (spec PR `adcontextprotocol/adcp#3493`), 3.1+ requests carry\n * BOTH the integer `adcp_major_version` (deprecated through 3.x, removed in\n * 4.0) AND the release-precision string `adcp_version`. 3.0 schemas don't\n * define the string field, so a 3.0-pinned client emits the integer only —\n * matches the 3.0 spec exactly.\n *\n * Wire string is release-precision (MAJOR.MINOR with optional prerelease tag),\n * per `core/version-envelope.json`'s pattern `^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`.\n * Full-semver bundle keys (`'3.1.0-beta.1'`) are collapsed via\n * `toReleasePrecisionWire` to `'3.1-beta.1'` before emit — meta-field shapes\n * are explicitly NOT valid wire values per the envelope schema's own\n * normalization rule.\n *\n * Returns `{}` for v2 callers (predates the major-version field entirely).\n */\nfunction buildVersionEnvelope(\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (serverVersion === 'v2') return {};\n const wireMajor = resolveWireMajor(adcpVersion);\n const bundleKey = resolveBundleKey(adcpVersion ?? ADCP_VERSION);\n if (!bundleSupportsAdcpVersionField(bundleKey)) {\n return { adcp_major_version: wireMajor };\n }\n const wireValue = toReleasePrecisionWire(bundleKey);\n // Defensive postcondition — should never throw in well-formed code, but\n // if a future refactor breaks the normalization the error message tells\n // the developer to call `toReleasePrecisionWire` instead of silently\n // emitting a non-spec wire string.\n validateAdcpVersionWire(wireValue);\n return { adcp_major_version: wireMajor, adcp_version: wireValue };\n}\n\nlet hasWarnedAboutV2PushNotificationSecret = false;\n\n/**\n * Warn once when an async webhook registration is suppressed for a v2 seller.\n *\n * v2.5's `push-notification-config.json` requires `authentication`, and unlike\n * 3.x it has no RFC 9421 selector semantics — so omitting the block produces a\n * schema-invalid request rather than choosing a signing mode. Without a\n * configured secret there is no honest value to send, and the previous\n * behaviour (a hardcoded placeholder credential) told the seller the channel\n * was authenticated by a constant published in this package.\n */\nfunction warnV2PushNotificationNeedsSecret(): void {\n if (hasWarnedAboutV2PushNotificationSecret) return;\n hasWarnedAboutV2PushNotificationSecret = true;\n console.warn(\n '[adcp] Suppressing push_notification_config for a v2 seller: AdCP 2.5 requires an ' +\n '`authentication` block and no `webhookSecret` is configured. Set `webhookSecret` to register ' +\n 'async task-status webhooks with this agent, or move the agent to an AdCP 3.x pin, where the ' +\n 'RFC 9421 webhook profile needs no shared secret.'\n );\n}\n\nfunction buildVersionEnvelopeForMode(\n mode: VersionEnvelopeMode,\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (mode === 'none' || serverVersion === 'v2') return {};\n if (mode === 'major-only') return { adcp_major_version: resolveWireMajor(adcpVersion) };\n return buildVersionEnvelope(adcpVersion, serverVersion);\n}\n\n/**\n * Merge the wire-level version envelope into a caller-supplied args object.\n * Caller args win: an explicit `adcp_major_version` / `adcp_version` in\n * `args` (e.g. a conformance harness probing `VERSION_UNSUPPORTED`) passes\n * through unchanged. The envelope only fills fields the caller didn't set.\n *\n * Single chokepoint for all four wire-injection sites so a future refactor\n * can't silently flip the spread order on one branch and leave the others\n * intact. Stale dual-field drift is caught at the server boundary by\n * `createAdcpServer`'s field-disagreement check (spec PR\n * `adcontextprotocol/adcp#3493`).\n *\n * @internal\n */\nexport function applyVersionEnvelope(\n args: Record<string, unknown>,\n envelope: Record<string, unknown>\n): Record<string, unknown> {\n return { ...envelope, ...args };\n}\n\n/**\n * Transport-level safeguards applied to a call.\n *\n * Wired into the SDK's internal fetch chain via AsyncLocalStorage, so the\n * cap takes effect even when the underlying transport's connection cache\n * reuses a fetch that was created on an earlier call with different limits.\n */\nexport interface TransportOptions {\n /**\n * Maximum response body size (in octets) the SDK will read before aborting\n * with `ResponseTooLargeError`. When unset, the SDK does not impose a cap —\n * matches the underlying MCP / A2A transport defaults.\n *\n * Set this when crawling **untrusted** agents (registries, federated\n * discovery layers, monitoring tools) to prevent a hostile vendor from\n * buffering a large reply before any application-layer schema validation\n * runs. Counted across response chunks; pre-cancels when `Content-Length`\n * exceeds the cap. Applies to A2A agent-card discovery\n * (`/.well-known/agent.json`) on the same call as well.\n *\n * Per-call override (`TaskOptions.transport.maxResponseBytes`) beats the\n * value set on the client constructor (`SingleAgentClientConfig.transport`).\n *\n * @remarks\n * **Safe to set on all calls.** SSE responses (`text/event-stream`) are\n * passed through unchanged — a single tool call legitimately emits N status\n * frames + a final result, bounded by protocol-level framing rather than\n * cumulative byte counts. The cap applies to one-shot JSON responses\n * (`get_adcp_capabilities`, agent-card lookup, tool result payloads on\n * non-streaming transports) where the body is bounded by definition.\n *\n * @remarks\n * **Hostile-peer note:** A peer can opt itself out of this cap by responding\n * with `Content-Type: text/event-stream`. SSE is bypassed because cumulative\n * event-frame bytes are unbounded by spec — MCP and A2A both stream tool\n * responses this way. The MCP/A2A SDKs consume SSE incrementally and frame\n * termination bounds memory in practice, so this is not a memory-bomb risk\n * for well-formed transports. Adopters relying on `maxResponseBytes` as a\n * hostile-server defense should treat it as best-effort for non-SSE\n * responses only.\n *\n * @remarks\n * Future hardening knobs (DNS-rebind defense, scheme allow-list, request\n * timeout overrides) will land here as additional fields. When `fetchFn`\n * is supplied, the SDK composes it inside its signing, capture, size-limit,\n * timeout, and diagnostics wrappers so callers do not have to reproduce\n * that non-obvious ordering themselves.\n */\n maxResponseBytes?: number;\n /**\n * Scoped fetch implementation for all outbound HTTP performed on behalf of\n * this client or call, including endpoint/card discovery, tool listing,\n * OAuth discovery and token refresh, and MCP/A2A tool requests.\n *\n * The function is runtime-only configuration and is never serialized into\n * agent records, storyboard artifacts, or compliance output. When unset,\n * the SDK uses the global `fetch` implementation.\n *\n * For SSRF-sensitive metadata probes, supplying this function makes it the\n * trusted network boundary: the SDK still validates schemes and resolved\n * addresses, but a custom fetch API cannot accept the SDK's pinned undici\n * dispatcher. The implementation must therefore prevent DNS rebinding (for\n * example with an egress proxy or its own DNS pinning).\n */\n fetchFn?: typeof fetch;\n /**\n * Timeout in milliseconds for bounded one-shot transport requests such as\n * A2A agent-card discovery and MCP read-path probes. Defaults to 60 seconds\n * for A2A discovery so an unresponsive card endpoint cannot hang forever.\n * Set to `0` to disable the SDK-imposed discovery timeout.\n */\n requestTimeoutMs?: number;\n}\n\n/**\n * Options for {@link ProtocolClient.callTool}. All fields are optional.\n *\n * `webhookUrl` / `webhookSecret` / `webhookToken` are for ASYNC TASK STATUS\n * notifications (push_notification_config). For reporting webhooks\n * (reporting_webhook), include them directly in `args` — they stay in skill\n * parameters and are sent verbatim to the agent.\n */\nexport interface CallToolOptions {\n /** Debug log array. Mutated in place by the protocol layer. */\n debugLogs?: DebugLogEntry[];\n /** URL for async task status notifications. */\n webhookUrl?: string;\n /** HMAC-SHA256 secret for push_notification_config authentication. */\n webhookSecret?: string;\n /** Bearer token for push_notification_config validation. */\n webhookToken?: string;\n /** Pinned protocol generation when the agent advertises both v2 and v3. */\n serverVersion?: 'v2' | 'v3';\n /** A2A session continuity (contextId carries conversation, taskId resumes a task). */\n session?: { contextId?: string; taskId?: string };\n /**\n * AdCP version pin from the calling client/server instance. Sets the\n * wire-level `adcp_major_version` field per-call instead of from the\n * SDK-pinned `ADCP_MAJOR_VERSION` constant. Default falls back to the\n * constant so call sites that don't plumb a per-instance version keep\n * their existing behavior. An explicit `adcp_major_version` /\n * `adcp_version` in `args` overrides this — conformance harnesses use\n * that path to probe seller version negotiation.\n */\n adcpVersion?: string;\n /**\n * Optional wire-only version override. Schema selection and client\n * construction can remain pinned to `adcpVersion`; the request envelope is\n * emitted for this release-precision line.\n */\n wireAdcpVersion?: string;\n /**\n * Controls whether the SDK injects AdCP version envelope fields into the\n * outgoing request. Defaults to `auto`. 3.0 pins emit only the legacy\n * `adcp_major_version`; 3.1+ pins emit both the legacy major and exact\n * `adcp_version` marker. `major-only` forces the legacy integer marker\n * without the 3.1 string marker for strict pre-3.1 peers discovered at\n * runtime.\n */\n versionEnvelope?: VersionEnvelopeMode;\n /**\n * Transport-level safeguards (size caps, etc.). Per-call override of any\n * matching field on the client constructor's `transport` option.\n */\n transport?: TransportOptions;\n /** Caller-owned cancellation signal for the in-flight protocol call. */\n signal?: AbortSignal;\n /** Transport-level diagnostics callback for outbound HTTP requests. */\n onTransportActivity?: TransportActivityHandlerFn;\n /**\n * Correlation metadata attached to transport diagnostics events emitted\n * while this protocol call is active.\n */\n transportActivityContext?: {\n operationId?: string;\n taskId?: string;\n contextId?: string;\n idempotencyKey?: string;\n };\n}\n\n/**\n * Universal protocol client - automatically routes to the correct protocol implementation\n */\nexport class ProtocolClient {\n /**\n * Call a tool on an agent using the appropriate protocol.\n *\n * @param agent - Agent configuration\n * @param toolName - Name of the tool/skill to call\n * @param args - Tool arguments (includes reporting_webhook if needed - NOT removed)\n * @param options - Optional call-level configuration. See {@link CallToolOptions}.\n */\n static async callTool(\n agent: AgentConfig,\n toolName: string,\n args: Record<string, unknown>,\n options: CallToolOptions = {}\n ): Promise<unknown> {\n const {\n debugLogs = [],\n webhookUrl,\n webhookSecret,\n webhookToken,\n serverVersion,\n session,\n adcpVersion,\n wireAdcpVersion,\n versionEnvelope: versionEnvelopeMode = 'auto',\n transport,\n signal,\n onTransportActivity,\n transportActivityContext,\n } = options;\n // Per-instance version envelope. Throws on unparseable pins via\n // `resolveWireMajor`; construction-time `resolveAdcpVersion` is the\n // primary gate but this is the failsafe for callers reaching\n // `ProtocolClient.callTool` directly (test harnesses, the in-process\n // MCP path). Returns `{ adcp_major_version }` for 3.0 pins and\n // `{ adcp_major_version, adcp_version }` for 3.1+ pins.\n const versionEnvelope = buildVersionEnvelopeForMode(\n versionEnvelopeMode,\n wireAdcpVersion ?? adcpVersion,\n serverVersion\n );\n // Enter the response-size-limit ALS slot once for this call. The slot is\n // read by `wrapFetchWithSizeLimit` in both protocol transports, so the\n // cap applies regardless of which path (MCP / A2A / OAuth refresh) the\n // call ends up taking. No-op when the cap is unset or non-positive.\n return withResponseSizeLimit(transport?.maxResponseBytes, () =>\n withTransportDiagnostics(\n {\n agentId: agent.id,\n protocol: agent.protocol,\n tool: toolName,\n taskType: toolName,\n ...transportActivityContext,\n onTransportActivity,\n },\n () =>\n withSpan(\n `adcp.${agent.protocol}.call_tool`,\n {\n 'adcp.agent_id': agent.id,\n 'adcp.protocol': agent.protocol,\n 'adcp.tool': toolName,\n 'http.url': agent.agent_uri,\n },\n async () => {\n // In-process MCP path: pre-connected client, no HTTP transport.\n // Idempotency injection, schema validation, and governance middleware all\n // still apply (they run in SingleAgentClient above this call). We skip\n // URL validation, OAuth refresh, and signing — none apply in-process.\n if (agent.protocol === 'mcp' && agent._inProcessMcpClient) {\n const inProcArgs = applyVersionEnvelope(args, versionEnvelope);\n return callMCPToolWithClient(agent._inProcessMcpClient, toolName, inProcArgs, debugLogs, {\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n });\n }\n\n validateAgentUrl(agent.agent_uri);\n\n // OAuth 2.0 client credentials (RFC 6749 §4.4): re-exchange the\n // secret for a fresh access token whenever the cached one is within\n // its expiration skew. Runs before every call so mid-session expiry\n // can't leave the caller with a stale bearer. No-op if the agent\n // doesn't declare client credentials. Cheap on warm cache (single\n // `Date.now()` compare); a single POST to the token endpoint on miss.\n //\n // `allowPrivateIp` inherits the trust the caller already placed in\n // `agent.agent_uri` — if they're making a call to a private-IP agent,\n // they've authorized this process to talk to private-IP hosts, so\n // the token endpoint on the same network is reachable too. Public\n // agent URLs with private-IP token endpoints still require an\n // explicit opt-in via the library API.\n if (agent.oauth_client_credentials) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n }\n\n const authToken = getAuthToken(agent);\n\n // RFC 9421 signing context. Built once per call and passed through\n // to each protocol-layer entry (`callMCPToolWithTasks`, `callA2ATool`,\n // `callMCPToolWithOAuth`) — those entries seed `signingContextStorage`\n // (AsyncLocalStorage) so the internal transport helpers read it\n // without an explicit parameter. Keep the explicit arg here: it's the\n // ALS seed, not incidental plumbing. `get_adcp_capabilities` is\n // exempt from signing (it's the discovery call itself) and also\n // triggers cache priming for any other op on agents with\n // `request_signing` configured.\n const signingContext = buildAgentSigningContext(agent);\n if (signingContext && toolName !== CAPABILITY_OP) {\n await ensureCapabilityLoaded(agent, signingContext, primeArgs =>\n ProtocolClient.callTool(agent, CAPABILITY_OP, primeArgs, {\n debugLogs,\n serverVersion,\n adcpVersion,\n ...(versionEnvelopeMode !== 'auto' && { versionEnvelope: versionEnvelopeMode }),\n transport,\n signal,\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n onTransportActivity,\n transportActivityContext,\n })\n );\n }\n\n // Inject the version envelope on every request so sellers can validate\n // compatibility. Skip for v2 servers — they don't recognise the\n // version fields and strict-schema agents reject them. The envelope\n // shape is per-pin: 3.0 pins get the integer `adcp_major_version`\n // alone; 3.1+ pins get both that and the release-precision string\n // `adcp_version` (`'3.1'` / `'3.1.0-beta.1'`) per spec PR\n // `adcontextprotocol/adcp#3493`.\n const argsWithVersion = applyVersionEnvelope(args, versionEnvelope);\n\n // Build push_notification_config for ASYNC TASK STATUS notifications\n // (NOT for reporting_webhook - that stays in args)\n // Schema: https://adcontextprotocol.org/schemas/v1/core/push-notification-config.json\n // `authentication` is a scheme SELECTOR, not a fallback: from AdCP\n // 3.0 on, push-notification-config.json makes its presence opt the\n // seller into legacy HMAC-SHA256 and its absence select the RFC\n // 9421 webhook profile, with `required: [\"url\"]` only. Emitting it\n // with a placeholder credential would therefore downgrade every\n // webhook to legacy HMAC keyed by a constant that ships in this\n // file, so the block is omitted unless a real secret backs it.\n //\n // v2.5 predates the selector: there `required` is\n // `[\"url\", \"authentication\"]` and there is no 9421 path, so an\n // omitted block is schema-invalid rather than a mode selection.\n // With no secret there is nothing honest to send a v2 seller, so\n // suppress the registration instead of fabricating a credential.\n const pushNotificationConfig: PushNotificationConfig | undefined = (():\n | PushNotificationConfig\n | undefined => {\n if (!webhookUrl) return undefined;\n if (webhookSecret) {\n return {\n url: webhookUrl,\n ...(webhookToken && { token: webhookToken }),\n authentication: {\n schemes: ['HMAC-SHA256' as const],\n credentials: webhookSecret,\n },\n };\n }\n if (serverVersion === 'v2') {\n warnV2PushNotificationNeedsSecret();\n return undefined;\n }\n return {\n url: webhookUrl,\n ...(webhookToken && { token: webhookToken }),\n };\n })();\n\n if (agent.protocol === 'mcp') {\n // For MCP, include push_notification_config in tool arguments (MCP spec)\n const argsWithWebhook = pushNotificationConfig\n ? { ...argsWithVersion, push_notification_config: pushNotificationConfig }\n : argsWithVersion;\n\n // If the agent config carries authorization-code OAuth tokens,\n // route through the OAuth provider path so the MCP SDK can refresh\n // on 401 instead of hard-failing. Excludes client-credentials\n // agents: they have a cached access token but no refresh_token,\n // and their refresh path is a secret re-exchange (handled above),\n // not the SDK's refresh_token grant.\n if (agent.oauth_tokens && !agent.oauth_client_credentials) {\n const authProvider = getNonInteractiveOAuthProvider(agent, {\n agentHint: agent.id,\n storage: getAgentStorage(agent),\n allowHttp: isLikelyPrivateUrl(agent.agent_uri),\n });\n try {\n return await callMCPToolWithOAuth({\n agentUrl: agent.agent_uri,\n toolName,\n args: argsWithWebhook,\n authProvider,\n debugLogs,\n customHeaders: agent.headers,\n signingContext,\n signal,\n requestTimeoutMs: transport?.requestTimeoutMs,\n fetchFn: transport?.fetchFn,\n });\n } catch (err) {\n // Refresh failed or server rejected the refreshed token — walk the\n // discovery chain so the caller can distinguish \"re-auth needed\"\n // from other failure modes.\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n }\n\n // Use callMCPToolWithTasks which auto-detects server tasks capability\n // and falls back to standard callTool when tasks are not supported\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n authToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (err) {\n // Client-credentials agents: on 401, the AS may have rotated\n // something out-of-band. Force a fresh exchange and retry once\n // before surfacing the error. Bounded (single retry) so we don't\n // loop if the credentials are genuinely wrong.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n retryAuthToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else if (agent.protocol === 'a2a') {\n // For A2A, pass pushNotificationConfig separately (not in skill parameters)\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n authToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (err) {\n // Same single-retry-on-401 for client-credentials agents as the\n // MCP path above. Kept symmetric so A2A CC agents aren't a\n // second-class experience — including the NeedsAuthorizationError\n // rewrap on a retry that still 401s.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n retryAuthToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else {\n throw new Error(`Unsupported protocol: ${agent.protocol}`);\n }\n }\n )\n )\n );\n }\n}\n\n/**\n * If `err` looks like a 401 from the MCP transport, probe the agent for a\n * Bearer challenge and throw a {@link NeedsAuthorizationError} carrying\n * walked discovery metadata. If the error isn't a 401 or we can't build a\n * requirements record, return silently so the caller re-throws the original.\n *\n * Keeping this off the hot path: we only probe on error, and the probe is\n * a single unauthenticated `tools/list` POST — no retries, no DNS rebind.\n */\nasync function rethrowAsNeedsAuthorization(err: unknown, agentUrl: string, fetchFn?: typeof fetch): Promise<void> {\n if (err instanceof NeedsAuthorizationError) throw err;\n if (!is401Error(err)) return;\n\n // If the caller has already connected to the agent URL, they've implicitly\n // trusted it — inherit that trust for the discovery probe so loopback /\n // private-IP development agents work the same way as public ones.\n const allowPrivateIp = isLikelyPrivateUrl(agentUrl);\n\n // discoverAuthorizationRequirements internally catches network failures and\n // returns null rather than throwing — anything that escapes is a genuine\n // bug we want to surface rather than mask the 401 with.\n const requirements = await discoverAuthorizationRequirements(agentUrl, { allowPrivateIp, fetchFn });\n if (requirements) {\n throw new NeedsAuthorizationError(requirements);\n }\n // No requirements walked; let the caller re-throw the original error.\n}\n\n/**\n * Simple factory functions for protocol-specific clients.\n *\n * Both factories accept a `transport` argument that flows through to the\n * size-cap surface so callers reaching the factory exports honor the same\n * `maxResponseBytes` contract as `ProtocolClient.callTool`. Without it,\n * the factories would silently bypass the cap, which the public API\n * (`TransportOptions`) implies they honor.\n */\nexport const createMCPClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n // Validate the pin at factory time so a typo surfaces here rather than at\n // first call. `buildVersionEnvelope` throws via `resolveWireMajor` on bad\n // input — call it once to surface, then close over the envelope.\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, args: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callMCPToolWithTasks(\n agentUrl,\n toolName,\n applyVersionEnvelope(args, versionEnvelope),\n authToken,\n debugLogs,\n headers,\n {\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n )\n ),\n };\n};\n\nexport const createA2AClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, parameters: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callA2ATool(\n agentUrl,\n toolName,\n applyVersionEnvelope(parameters, versionEnvelope),\n authToken,\n debugLogs,\n undefined,\n headers,\n undefined,\n undefined,\n undefined,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n )\n ),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,iBAOO;AAEP,IAAAA,cAAoC;AACpC,iBAAoC;AAcpC,IAAAC,cAA4B;AAC5B,mBAA2C;AAC3C,uBAQO;AAEP,IAAAC,oBAA4D;AAC5D,IAAAF,cAAqC;AACrC,IAAAC,cAA4B;AAG5B,kBAA6B;AAC7B,mBAKO;AACP,4BAA+C;AAC/C,oBAA2B;AAC3B,iBAAmC;AACnC,wBAAiC;AACjC,qBAAyB;AACzB,qBAAwE;AACxE,IAAAE,iBAAmC;AACnC,2BAAkF;AAClF,oBAAgF;AAChF,+BAAsC;AACtC,kCAGO;AAEP,IAAAC,+BAKO;AApDP,eAAsB,iBAAiB,WAA0B,OAAsB;AACrF,MAAI,aAAa,OAAO;AACtB,cAAM,iCAAoB;AAAA,EAC5B,OAAO;AACL,wCAAoB;AAAA,EACtB;AACF;AA6DA,SAAS,iBAAiB,aAAyC;AACjE,MAAI,gBAAgB,OAAW,QAAO;AACtC,QAAM,aAAS,sCAAsB,WAAW;AAChD,MAAI,CAAC,OAAO,SAAS,MAAM,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR,eAAe,KAAK,UAAU,WAAW,CAAC;AAAA,MAE1C;AAAA,IACF;AAAA,EACF;AAC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AAA,IACF;AAAA,EACJ;AACF;","names":["import_mcp","import_a2a","import_mcp_tasks","import_errors","import_transportDiagnostics"]}
@@ -91,6 +91,14 @@ function buildVersionEnvelope(adcpVersion, serverVersion) {
91
91
  validateAdcpVersionWire(wireValue);
92
92
  return { adcp_major_version: wireMajor, adcp_version: wireValue };
93
93
  }
94
+ let hasWarnedAboutV2PushNotificationSecret = false;
95
+ function warnV2PushNotificationNeedsSecret() {
96
+ if (hasWarnedAboutV2PushNotificationSecret) return;
97
+ hasWarnedAboutV2PushNotificationSecret = true;
98
+ console.warn(
99
+ "[adcp] Suppressing push_notification_config for a v2 seller: AdCP 2.5 requires an `authentication` block and no `webhookSecret` is configured. Set `webhookSecret` to register async task-status webhooks with this agent, or move the agent to an AdCP 3.x pin, where the RFC 9421 webhook profile needs no shared secret."
100
+ );
101
+ }
94
102
  function buildVersionEnvelopeForMode(mode, adcpVersion, serverVersion) {
95
103
  if (mode === "none" || serverVersion === "v2") return {};
96
104
  if (mode === "major-only") return { adcp_major_version: resolveWireMajor(adcpVersion) };
@@ -186,14 +194,27 @@ class ProtocolClient {
186
194
  );
187
195
  }
188
196
  const argsWithVersion = applyVersionEnvelope(args, versionEnvelope);
189
- const pushNotificationConfig = webhookUrl ? {
190
- url: webhookUrl,
191
- ...webhookToken && { token: webhookToken },
192
- authentication: {
193
- schemes: ["HMAC-SHA256"],
194
- credentials: webhookSecret || "placeholder_secret_min_32_characters_required"
197
+ const pushNotificationConfig = (() => {
198
+ if (!webhookUrl) return void 0;
199
+ if (webhookSecret) {
200
+ return {
201
+ url: webhookUrl,
202
+ ...webhookToken && { token: webhookToken },
203
+ authentication: {
204
+ schemes: ["HMAC-SHA256"],
205
+ credentials: webhookSecret
206
+ }
207
+ };
208
+ }
209
+ if (serverVersion === "v2") {
210
+ warnV2PushNotificationNeedsSecret();
211
+ return void 0;
195
212
  }
196
- } : void 0;
213
+ return {
214
+ url: webhookUrl,
215
+ ...webhookToken && { token: webhookToken }
216
+ };
217
+ })();
197
218
  if (agent.protocol === "mcp") {
198
219
  const argsWithWebhook = pushNotificationConfig ? { ...argsWithVersion, push_notification_config: pushNotificationConfig } : argsWithVersion;
199
220
  if (agent.oauth_tokens && !agent.oauth_client_credentials) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/index.ts"],"sourcesContent":["import { fileURLToPath as __adcpFileURLToPath } from 'node:url';\nimport { dirname as __adcpDirname } from 'node:path';\nimport { createRequire as __adcpCreateRequire } from 'node:module';\nconst __dirname = __adcpDirname(__adcpFileURLToPath(import.meta.url));\nconst require = __adcpCreateRequire(import.meta.url);\n// Unified Protocol Interface for AdCP\nexport {\n callMCPTool,\n callMCPToolWithOAuth,\n connectMCP,\n closeMCPConnections,\n closeOAuthConnections,\n UnauthorizedError,\n} from './mcp';\n\nimport { closeMCPConnections } from './mcp';\nimport { closeA2AConnections } from './a2a';\n\n/**\n * Close protocol connections for the given protocol.\n * MCP closes persistent HTTP transports; A2A clears the agent-card client cache.\n */\nexport async function closeConnections(protocol: 'mcp' | 'a2a' = 'mcp'): Promise<void> {\n if (protocol === 'mcp') {\n await closeMCPConnections();\n } else {\n closeA2AConnections();\n }\n}\nexport type { MCPCallOptions, MCPConnectionResult } from './mcp';\nexport { callA2ATool } from './a2a';\nexport { DEFAULT_REQUEST_TIMEOUT_MS } from './abort';\nexport {\n callMCPToolWithTasks,\n getMCPTaskStatus,\n getMCPTaskResult,\n listMCPTasks,\n cancelMCPTask,\n mapMCPTaskStatus,\n serverSupportsTasks,\n} from './mcp-tasks';\n\nimport { callMCPToolWithTasks, callMCPToolWithClient } from './mcp-tasks';\nimport { callMCPToolWithOAuth } from './mcp';\nimport { callA2ATool } from './a2a';\nimport type { AgentConfig, DebugLogEntry } from '../types';\nimport type { PushNotificationConfig } from '../types/tools.generated';\nimport { getAuthToken } from '../auth';\nimport {\n discoverAuthorizationRequirements,\n NeedsAuthorizationError,\n getAgentStorage,\n ensureClientCredentialsTokens,\n} from '../auth/oauth';\nimport { getNonInteractiveOAuthProvider } from '../auth/oauth/provider-cache';\nimport { is401Error } from '../errors';\nimport { isLikelyPrivateUrl } from '../net';\nimport { validateAgentUrl } from '../validation';\nimport { withSpan } from '../observability/tracing';\nimport { ADCP_MAJOR_VERSION, ADCP_VERSION, parseAdcpMajorVersion } from '../version';\nimport { ConfigurationError } from '../errors';\nimport { resolveBundleKey, toReleasePrecisionWire, validateAdcpVersionWire } from '../validation/schema-loader';\nimport { buildAgentSigningContext, CAPABILITY_OP, ensureCapabilityLoaded } from '../signing/client';\nimport { withResponseSizeLimit } from './responseSizeLimit';\nimport {\n withTransportDiagnostics,\n type TransportActivityHandler as TransportActivityHandlerFn,\n} from './transportDiagnostics';\n\nexport {\n sanitizeTransportHeaders,\n sanitizeTransportUrl,\n withTransportDiagnostics,\n wrapFetchWithTransportDiagnostics,\n} from './transportDiagnostics';\nexport type { TransportActivity, TransportActivityContext, TransportActivityHandler } from './transportDiagnostics';\n\nexport type VersionEnvelopeMode = 'auto' | 'none' | 'major-only';\n\n/**\n * Derive the wire-level `adcp_major_version` integer from a caller-supplied\n * pin. Returns the SDK default when no pin is provided; throws on a pin\n * that doesn't parse so misuse surfaces at the factory boundary instead\n * of silently emitting the SDK's major.\n *\n * Throws `ConfigurationError` (not a plain `Error`) so a typo'd pin\n * surfaces with the same error class as the construction-time gate in\n * `resolveAdcpVersion` — one shape for all pin-misuse paths.\n */\nfunction resolveWireMajor(adcpVersion: string | undefined): number {\n if (adcpVersion === undefined) return ADCP_MAJOR_VERSION;\n const parsed = parseAdcpMajorVersion(adcpVersion);\n if (!Number.isFinite(parsed)) {\n throw new ConfigurationError(\n `adcpVersion ${JSON.stringify(adcpVersion)} is not a valid AdCP version. ` +\n `Expected a semver string (e.g. '3.0.1', '3.1.0-beta.1') or a legacy alias (e.g. 'v3').`,\n 'adcpVersion'\n );\n }\n return parsed;\n}\n\n/**\n * Returns true when the AdCP release that `bundleKey` identifies declares the\n * top-level `adcp_version` envelope field. The field landed in AdCP 3.1 per\n * spec PR `adcontextprotocol/adcp#3493` — 3.0 (any patch / prerelease) does\n * not carry it; 3.1+ does. Used to gate dual-emit on the wire so a 3.0-pinned\n * client doesn't emit a field its target schema doesn't define.\n */\nexport function bundleSupportsAdcpVersionField(bundleKey: string): boolean {\n const major = parseAdcpMajorVersion(bundleKey);\n if (!Number.isFinite(major)) return false;\n if (major < 3) return false;\n if (major > 3) return true;\n // Major 3 — only 3.1+ has the field. Bundle key shape is normalized by\n // `resolveBundleKey`: `'3.0'` / `'3.1'` for stable; `'3.0.0-beta.1'` /\n // `'3.1.0-beta.1'` for prereleases. Match the minor.\n const minorMatch = bundleKey.match(/^\\d+\\.(\\d+)/);\n if (!minorMatch) return false;\n return parseInt(minorMatch[1]!, 10) >= 1;\n}\n\n/**\n * Build the wire-level version envelope to merge into outgoing request args.\n *\n * Per AdCP 3.1 (spec PR `adcontextprotocol/adcp#3493`), 3.1+ requests carry\n * BOTH the integer `adcp_major_version` (deprecated through 3.x, removed in\n * 4.0) AND the release-precision string `adcp_version`. 3.0 schemas don't\n * define the string field, so a 3.0-pinned client emits the integer only —\n * matches the 3.0 spec exactly.\n *\n * Wire string is release-precision (MAJOR.MINOR with optional prerelease tag),\n * per `core/version-envelope.json`'s pattern `^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`.\n * Full-semver bundle keys (`'3.1.0-beta.1'`) are collapsed via\n * `toReleasePrecisionWire` to `'3.1-beta.1'` before emit — meta-field shapes\n * are explicitly NOT valid wire values per the envelope schema's own\n * normalization rule.\n *\n * Returns `{}` for v2 callers (predates the major-version field entirely).\n */\nfunction buildVersionEnvelope(\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (serverVersion === 'v2') return {};\n const wireMajor = resolveWireMajor(adcpVersion);\n const bundleKey = resolveBundleKey(adcpVersion ?? ADCP_VERSION);\n if (!bundleSupportsAdcpVersionField(bundleKey)) {\n return { adcp_major_version: wireMajor };\n }\n const wireValue = toReleasePrecisionWire(bundleKey);\n // Defensive postcondition — should never throw in well-formed code, but\n // if a future refactor breaks the normalization the error message tells\n // the developer to call `toReleasePrecisionWire` instead of silently\n // emitting a non-spec wire string.\n validateAdcpVersionWire(wireValue);\n return { adcp_major_version: wireMajor, adcp_version: wireValue };\n}\n\nfunction buildVersionEnvelopeForMode(\n mode: VersionEnvelopeMode,\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (mode === 'none' || serverVersion === 'v2') return {};\n if (mode === 'major-only') return { adcp_major_version: resolveWireMajor(adcpVersion) };\n return buildVersionEnvelope(adcpVersion, serverVersion);\n}\n\n/**\n * Merge the wire-level version envelope into a caller-supplied args object.\n * Caller args win: an explicit `adcp_major_version` / `adcp_version` in\n * `args` (e.g. a conformance harness probing `VERSION_UNSUPPORTED`) passes\n * through unchanged. The envelope only fills fields the caller didn't set.\n *\n * Single chokepoint for all four wire-injection sites so a future refactor\n * can't silently flip the spread order on one branch and leave the others\n * intact. Stale dual-field drift is caught at the server boundary by\n * `createAdcpServer`'s field-disagreement check (spec PR\n * `adcontextprotocol/adcp#3493`).\n *\n * @internal\n */\nexport function applyVersionEnvelope(\n args: Record<string, unknown>,\n envelope: Record<string, unknown>\n): Record<string, unknown> {\n return { ...envelope, ...args };\n}\n\n/**\n * Transport-level safeguards applied to a call.\n *\n * Wired into the SDK's internal fetch chain via AsyncLocalStorage, so the\n * cap takes effect even when the underlying transport's connection cache\n * reuses a fetch that was created on an earlier call with different limits.\n */\nexport interface TransportOptions {\n /**\n * Maximum response body size (in octets) the SDK will read before aborting\n * with `ResponseTooLargeError`. When unset, the SDK does not impose a cap —\n * matches the underlying MCP / A2A transport defaults.\n *\n * Set this when crawling **untrusted** agents (registries, federated\n * discovery layers, monitoring tools) to prevent a hostile vendor from\n * buffering a large reply before any application-layer schema validation\n * runs. Counted across response chunks; pre-cancels when `Content-Length`\n * exceeds the cap. Applies to A2A agent-card discovery\n * (`/.well-known/agent.json`) on the same call as well.\n *\n * Per-call override (`TaskOptions.transport.maxResponseBytes`) beats the\n * value set on the client constructor (`SingleAgentClientConfig.transport`).\n *\n * @remarks\n * **Safe to set on all calls.** SSE responses (`text/event-stream`) are\n * passed through unchanged — a single tool call legitimately emits N status\n * frames + a final result, bounded by protocol-level framing rather than\n * cumulative byte counts. The cap applies to one-shot JSON responses\n * (`get_adcp_capabilities`, agent-card lookup, tool result payloads on\n * non-streaming transports) where the body is bounded by definition.\n *\n * @remarks\n * **Hostile-peer note:** A peer can opt itself out of this cap by responding\n * with `Content-Type: text/event-stream`. SSE is bypassed because cumulative\n * event-frame bytes are unbounded by spec — MCP and A2A both stream tool\n * responses this way. The MCP/A2A SDKs consume SSE incrementally and frame\n * termination bounds memory in practice, so this is not a memory-bomb risk\n * for well-formed transports. Adopters relying on `maxResponseBytes` as a\n * hostile-server defense should treat it as best-effort for non-SSE\n * responses only.\n *\n * @remarks\n * Future hardening knobs (DNS-rebind defense, scheme allow-list, request\n * timeout overrides) will land here as additional fields. When `fetchFn`\n * is supplied, the SDK composes it inside its signing, capture, size-limit,\n * timeout, and diagnostics wrappers so callers do not have to reproduce\n * that non-obvious ordering themselves.\n */\n maxResponseBytes?: number;\n /**\n * Scoped fetch implementation for all outbound HTTP performed on behalf of\n * this client or call, including endpoint/card discovery, tool listing,\n * OAuth discovery and token refresh, and MCP/A2A tool requests.\n *\n * The function is runtime-only configuration and is never serialized into\n * agent records, storyboard artifacts, or compliance output. When unset,\n * the SDK uses the global `fetch` implementation.\n *\n * For SSRF-sensitive metadata probes, supplying this function makes it the\n * trusted network boundary: the SDK still validates schemes and resolved\n * addresses, but a custom fetch API cannot accept the SDK's pinned undici\n * dispatcher. The implementation must therefore prevent DNS rebinding (for\n * example with an egress proxy or its own DNS pinning).\n */\n fetchFn?: typeof fetch;\n /**\n * Timeout in milliseconds for bounded one-shot transport requests such as\n * A2A agent-card discovery and MCP read-path probes. Defaults to 60 seconds\n * for A2A discovery so an unresponsive card endpoint cannot hang forever.\n * Set to `0` to disable the SDK-imposed discovery timeout.\n */\n requestTimeoutMs?: number;\n}\n\n/**\n * Options for {@link ProtocolClient.callTool}. All fields are optional.\n *\n * `webhookUrl` / `webhookSecret` / `webhookToken` are for ASYNC TASK STATUS\n * notifications (push_notification_config). For reporting webhooks\n * (reporting_webhook), include them directly in `args` — they stay in skill\n * parameters and are sent verbatim to the agent.\n */\nexport interface CallToolOptions {\n /** Debug log array. Mutated in place by the protocol layer. */\n debugLogs?: DebugLogEntry[];\n /** URL for async task status notifications. */\n webhookUrl?: string;\n /** HMAC-SHA256 secret for push_notification_config authentication. */\n webhookSecret?: string;\n /** Bearer token for push_notification_config validation. */\n webhookToken?: string;\n /** Pinned protocol generation when the agent advertises both v2 and v3. */\n serverVersion?: 'v2' | 'v3';\n /** A2A session continuity (contextId carries conversation, taskId resumes a task). */\n session?: { contextId?: string; taskId?: string };\n /**\n * AdCP version pin from the calling client/server instance. Sets the\n * wire-level `adcp_major_version` field per-call instead of from the\n * SDK-pinned `ADCP_MAJOR_VERSION` constant. Default falls back to the\n * constant so call sites that don't plumb a per-instance version keep\n * their existing behavior. An explicit `adcp_major_version` /\n * `adcp_version` in `args` overrides this — conformance harnesses use\n * that path to probe seller version negotiation.\n */\n adcpVersion?: string;\n /**\n * Optional wire-only version override. Schema selection and client\n * construction can remain pinned to `adcpVersion`; the request envelope is\n * emitted for this release-precision line.\n */\n wireAdcpVersion?: string;\n /**\n * Controls whether the SDK injects AdCP version envelope fields into the\n * outgoing request. Defaults to `auto`. 3.0 pins emit only the legacy\n * `adcp_major_version`; 3.1+ pins emit both the legacy major and exact\n * `adcp_version` marker. `major-only` forces the legacy integer marker\n * without the 3.1 string marker for strict pre-3.1 peers discovered at\n * runtime.\n */\n versionEnvelope?: VersionEnvelopeMode;\n /**\n * Transport-level safeguards (size caps, etc.). Per-call override of any\n * matching field on the client constructor's `transport` option.\n */\n transport?: TransportOptions;\n /** Caller-owned cancellation signal for the in-flight protocol call. */\n signal?: AbortSignal;\n /** Transport-level diagnostics callback for outbound HTTP requests. */\n onTransportActivity?: TransportActivityHandlerFn;\n /**\n * Correlation metadata attached to transport diagnostics events emitted\n * while this protocol call is active.\n */\n transportActivityContext?: {\n operationId?: string;\n taskId?: string;\n contextId?: string;\n idempotencyKey?: string;\n };\n}\n\n/**\n * Universal protocol client - automatically routes to the correct protocol implementation\n */\nexport class ProtocolClient {\n /**\n * Call a tool on an agent using the appropriate protocol.\n *\n * @param agent - Agent configuration\n * @param toolName - Name of the tool/skill to call\n * @param args - Tool arguments (includes reporting_webhook if needed - NOT removed)\n * @param options - Optional call-level configuration. See {@link CallToolOptions}.\n */\n static async callTool(\n agent: AgentConfig,\n toolName: string,\n args: Record<string, unknown>,\n options: CallToolOptions = {}\n ): Promise<unknown> {\n const {\n debugLogs = [],\n webhookUrl,\n webhookSecret,\n webhookToken,\n serverVersion,\n session,\n adcpVersion,\n wireAdcpVersion,\n versionEnvelope: versionEnvelopeMode = 'auto',\n transport,\n signal,\n onTransportActivity,\n transportActivityContext,\n } = options;\n // Per-instance version envelope. Throws on unparseable pins via\n // `resolveWireMajor`; construction-time `resolveAdcpVersion` is the\n // primary gate but this is the failsafe for callers reaching\n // `ProtocolClient.callTool` directly (test harnesses, the in-process\n // MCP path). Returns `{ adcp_major_version }` for 3.0 pins and\n // `{ adcp_major_version, adcp_version }` for 3.1+ pins.\n const versionEnvelope = buildVersionEnvelopeForMode(\n versionEnvelopeMode,\n wireAdcpVersion ?? adcpVersion,\n serverVersion\n );\n // Enter the response-size-limit ALS slot once for this call. The slot is\n // read by `wrapFetchWithSizeLimit` in both protocol transports, so the\n // cap applies regardless of which path (MCP / A2A / OAuth refresh) the\n // call ends up taking. No-op when the cap is unset or non-positive.\n return withResponseSizeLimit(transport?.maxResponseBytes, () =>\n withTransportDiagnostics(\n {\n agentId: agent.id,\n protocol: agent.protocol,\n tool: toolName,\n taskType: toolName,\n ...transportActivityContext,\n onTransportActivity,\n },\n () =>\n withSpan(\n `adcp.${agent.protocol}.call_tool`,\n {\n 'adcp.agent_id': agent.id,\n 'adcp.protocol': agent.protocol,\n 'adcp.tool': toolName,\n 'http.url': agent.agent_uri,\n },\n async () => {\n // In-process MCP path: pre-connected client, no HTTP transport.\n // Idempotency injection, schema validation, and governance middleware all\n // still apply (they run in SingleAgentClient above this call). We skip\n // URL validation, OAuth refresh, and signing — none apply in-process.\n if (agent.protocol === 'mcp' && agent._inProcessMcpClient) {\n const inProcArgs = applyVersionEnvelope(args, versionEnvelope);\n return callMCPToolWithClient(agent._inProcessMcpClient, toolName, inProcArgs, debugLogs, {\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n });\n }\n\n validateAgentUrl(agent.agent_uri);\n\n // OAuth 2.0 client credentials (RFC 6749 §4.4): re-exchange the\n // secret for a fresh access token whenever the cached one is within\n // its expiration skew. Runs before every call so mid-session expiry\n // can't leave the caller with a stale bearer. No-op if the agent\n // doesn't declare client credentials. Cheap on warm cache (single\n // `Date.now()` compare); a single POST to the token endpoint on miss.\n //\n // `allowPrivateIp` inherits the trust the caller already placed in\n // `agent.agent_uri` — if they're making a call to a private-IP agent,\n // they've authorized this process to talk to private-IP hosts, so\n // the token endpoint on the same network is reachable too. Public\n // agent URLs with private-IP token endpoints still require an\n // explicit opt-in via the library API.\n if (agent.oauth_client_credentials) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n }\n\n const authToken = getAuthToken(agent);\n\n // RFC 9421 signing context. Built once per call and passed through\n // to each protocol-layer entry (`callMCPToolWithTasks`, `callA2ATool`,\n // `callMCPToolWithOAuth`) — those entries seed `signingContextStorage`\n // (AsyncLocalStorage) so the internal transport helpers read it\n // without an explicit parameter. Keep the explicit arg here: it's the\n // ALS seed, not incidental plumbing. `get_adcp_capabilities` is\n // exempt from signing (it's the discovery call itself) and also\n // triggers cache priming for any other op on agents with\n // `request_signing` configured.\n const signingContext = buildAgentSigningContext(agent);\n if (signingContext && toolName !== CAPABILITY_OP) {\n await ensureCapabilityLoaded(agent, signingContext, primeArgs =>\n ProtocolClient.callTool(agent, CAPABILITY_OP, primeArgs, {\n debugLogs,\n serverVersion,\n adcpVersion,\n ...(versionEnvelopeMode !== 'auto' && { versionEnvelope: versionEnvelopeMode }),\n transport,\n signal,\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n onTransportActivity,\n transportActivityContext,\n })\n );\n }\n\n // Inject the version envelope on every request so sellers can validate\n // compatibility. Skip for v2 servers — they don't recognise the\n // version fields and strict-schema agents reject them. The envelope\n // shape is per-pin: 3.0 pins get the integer `adcp_major_version`\n // alone; 3.1+ pins get both that and the release-precision string\n // `adcp_version` (`'3.1'` / `'3.1.0-beta.1'`) per spec PR\n // `adcontextprotocol/adcp#3493`.\n const argsWithVersion = applyVersionEnvelope(args, versionEnvelope);\n\n // Build push_notification_config for ASYNC TASK STATUS notifications\n // (NOT for reporting_webhook - that stays in args)\n // Schema: https://adcontextprotocol.org/schemas/v1/core/push-notification-config.json\n const pushNotificationConfig: PushNotificationConfig | undefined = webhookUrl\n ? {\n url: webhookUrl,\n ...(webhookToken && { token: webhookToken }),\n authentication: {\n schemes: ['HMAC-SHA256'],\n credentials: webhookSecret || 'placeholder_secret_min_32_characters_required',\n },\n }\n : undefined;\n\n if (agent.protocol === 'mcp') {\n // For MCP, include push_notification_config in tool arguments (MCP spec)\n const argsWithWebhook = pushNotificationConfig\n ? { ...argsWithVersion, push_notification_config: pushNotificationConfig }\n : argsWithVersion;\n\n // If the agent config carries authorization-code OAuth tokens,\n // route through the OAuth provider path so the MCP SDK can refresh\n // on 401 instead of hard-failing. Excludes client-credentials\n // agents: they have a cached access token but no refresh_token,\n // and their refresh path is a secret re-exchange (handled above),\n // not the SDK's refresh_token grant.\n if (agent.oauth_tokens && !agent.oauth_client_credentials) {\n const authProvider = getNonInteractiveOAuthProvider(agent, {\n agentHint: agent.id,\n storage: getAgentStorage(agent),\n allowHttp: isLikelyPrivateUrl(agent.agent_uri),\n });\n try {\n return await callMCPToolWithOAuth({\n agentUrl: agent.agent_uri,\n toolName,\n args: argsWithWebhook,\n authProvider,\n debugLogs,\n customHeaders: agent.headers,\n signingContext,\n signal,\n requestTimeoutMs: transport?.requestTimeoutMs,\n fetchFn: transport?.fetchFn,\n });\n } catch (err) {\n // Refresh failed or server rejected the refreshed token — walk the\n // discovery chain so the caller can distinguish \"re-auth needed\"\n // from other failure modes.\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n }\n\n // Use callMCPToolWithTasks which auto-detects server tasks capability\n // and falls back to standard callTool when tasks are not supported\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n authToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (err) {\n // Client-credentials agents: on 401, the AS may have rotated\n // something out-of-band. Force a fresh exchange and retry once\n // before surfacing the error. Bounded (single retry) so we don't\n // loop if the credentials are genuinely wrong.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n retryAuthToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else if (agent.protocol === 'a2a') {\n // For A2A, pass pushNotificationConfig separately (not in skill parameters)\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n authToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (err) {\n // Same single-retry-on-401 for client-credentials agents as the\n // MCP path above. Kept symmetric so A2A CC agents aren't a\n // second-class experience — including the NeedsAuthorizationError\n // rewrap on a retry that still 401s.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n retryAuthToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else {\n throw new Error(`Unsupported protocol: ${agent.protocol}`);\n }\n }\n )\n )\n );\n }\n}\n\n/**\n * If `err` looks like a 401 from the MCP transport, probe the agent for a\n * Bearer challenge and throw a {@link NeedsAuthorizationError} carrying\n * walked discovery metadata. If the error isn't a 401 or we can't build a\n * requirements record, return silently so the caller re-throws the original.\n *\n * Keeping this off the hot path: we only probe on error, and the probe is\n * a single unauthenticated `tools/list` POST — no retries, no DNS rebind.\n */\nasync function rethrowAsNeedsAuthorization(err: unknown, agentUrl: string, fetchFn?: typeof fetch): Promise<void> {\n if (err instanceof NeedsAuthorizationError) throw err;\n if (!is401Error(err)) return;\n\n // If the caller has already connected to the agent URL, they've implicitly\n // trusted it — inherit that trust for the discovery probe so loopback /\n // private-IP development agents work the same way as public ones.\n const allowPrivateIp = isLikelyPrivateUrl(agentUrl);\n\n // discoverAuthorizationRequirements internally catches network failures and\n // returns null rather than throwing — anything that escapes is a genuine\n // bug we want to surface rather than mask the 401 with.\n const requirements = await discoverAuthorizationRequirements(agentUrl, { allowPrivateIp, fetchFn });\n if (requirements) {\n throw new NeedsAuthorizationError(requirements);\n }\n // No requirements walked; let the caller re-throw the original error.\n}\n\n/**\n * Simple factory functions for protocol-specific clients.\n *\n * Both factories accept a `transport` argument that flows through to the\n * size-cap surface so callers reaching the factory exports honor the same\n * `maxResponseBytes` contract as `ProtocolClient.callTool`. Without it,\n * the factories would silently bypass the cap, which the public API\n * (`TransportOptions`) implies they honor.\n */\nexport const createMCPClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n // Validate the pin at factory time so a typo surfaces here rather than at\n // first call. `buildVersionEnvelope` throws via `resolveWireMajor` on bad\n // input — call it once to surface, then close over the envelope.\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, args: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callMCPToolWithTasks(\n agentUrl,\n toolName,\n applyVersionEnvelope(args, versionEnvelope),\n authToken,\n debugLogs,\n headers,\n {\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n )\n ),\n };\n};\n\nexport const createA2AClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, parameters: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callA2ATool(\n agentUrl,\n toolName,\n applyVersionEnvelope(parameters, versionEnvelope),\n authToken,\n debugLogs,\n undefined,\n headers,\n undefined,\n undefined,\n undefined,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n )\n ),\n };\n};\n"],"mappings":"AAAA,SAAS,iBAAiB,2BAA2B;AACrD,SAAS,WAAW,qBAAqB;AACzC,SAAS,iBAAiB,2BAA2B;AACrD,MAAM,YAAY,cAAc,oBAAoB,YAAY,GAAG,CAAC;AACpE,MAAMA,WAAU,oBAAoB,YAAY,GAAG;AAEnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,uBAAAC,4BAA2B;AACpC,SAAS,2BAA2B;AAMpC,eAAsB,iBAAiB,WAA0B,OAAsB;AACrF,MAAI,aAAa,OAAO;AACtB,UAAMA,qBAAoB;AAAA,EAC5B,OAAO;AACL,wBAAoB;AAAA,EACtB;AACF;AAEA,SAAS,mBAAmB;AAC5B,SAAS,kCAAkC;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,wBAAA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kB,CAC7B,UACA,WACA,SACA,eACA,aACA,WACA,sBAA2C,WACxC;AACH,QAAM,kBAAkB,4BAA4B,qBAAqB,aAAa,aAAa;AACnG,SAAO;AAAA,IACL,UAAU,CAAC,UAAkB,YAAqC,cAChE;AAAA,MAAsB,WAAW;AAAA,MAAkB,MACjDE;AAAA,QACE;AAAA,QACA;AAAA,QACA,qBAAqB,YAAY,eAAe;AAAA,QAChD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,WAAW;AAAA,QACX,WAAW;AAAA,MACb;AAAA,IACF;AAAA,EACJ;AACF;","names":["require","closeMCPConnections","callMCPToolWithTasks","callMCPToolWithOAuth","callA2ATool","withTransportDiagnostics"]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/index.ts"],"sourcesContent":["import { fileURLToPath as __adcpFileURLToPath } from 'node:url';\nimport { dirname as __adcpDirname } from 'node:path';\nimport { createRequire as __adcpCreateRequire } from 'node:module';\nconst __dirname = __adcpDirname(__adcpFileURLToPath(import.meta.url));\nconst require = __adcpCreateRequire(import.meta.url);\n// Unified Protocol Interface for AdCP\nexport {\n callMCPTool,\n callMCPToolWithOAuth,\n connectMCP,\n closeMCPConnections,\n closeOAuthConnections,\n UnauthorizedError,\n} from './mcp';\n\nimport { closeMCPConnections } from './mcp';\nimport { closeA2AConnections } from './a2a';\n\n/**\n * Close protocol connections for the given protocol.\n * MCP closes persistent HTTP transports; A2A clears the agent-card client cache.\n */\nexport async function closeConnections(protocol: 'mcp' | 'a2a' = 'mcp'): Promise<void> {\n if (protocol === 'mcp') {\n await closeMCPConnections();\n } else {\n closeA2AConnections();\n }\n}\nexport type { MCPCallOptions, MCPConnectionResult } from './mcp';\nexport { callA2ATool } from './a2a';\nexport { DEFAULT_REQUEST_TIMEOUT_MS } from './abort';\nexport {\n callMCPToolWithTasks,\n getMCPTaskStatus,\n getMCPTaskResult,\n listMCPTasks,\n cancelMCPTask,\n mapMCPTaskStatus,\n serverSupportsTasks,\n} from './mcp-tasks';\n\nimport { callMCPToolWithTasks, callMCPToolWithClient } from './mcp-tasks';\nimport { callMCPToolWithOAuth } from './mcp';\nimport { callA2ATool } from './a2a';\nimport type { AgentConfig, DebugLogEntry } from '../types';\nimport type { PushNotificationConfig } from '../types/tools.generated';\nimport { getAuthToken } from '../auth';\nimport {\n discoverAuthorizationRequirements,\n NeedsAuthorizationError,\n getAgentStorage,\n ensureClientCredentialsTokens,\n} from '../auth/oauth';\nimport { getNonInteractiveOAuthProvider } from '../auth/oauth/provider-cache';\nimport { is401Error } from '../errors';\nimport { isLikelyPrivateUrl } from '../net';\nimport { validateAgentUrl } from '../validation';\nimport { withSpan } from '../observability/tracing';\nimport { ADCP_MAJOR_VERSION, ADCP_VERSION, parseAdcpMajorVersion } from '../version';\nimport { ConfigurationError } from '../errors';\nimport { resolveBundleKey, toReleasePrecisionWire, validateAdcpVersionWire } from '../validation/schema-loader';\nimport { buildAgentSigningContext, CAPABILITY_OP, ensureCapabilityLoaded } from '../signing/client';\nimport { withResponseSizeLimit } from './responseSizeLimit';\nimport {\n withTransportDiagnostics,\n type TransportActivityHandler as TransportActivityHandlerFn,\n} from './transportDiagnostics';\n\nexport {\n sanitizeTransportHeaders,\n sanitizeTransportUrl,\n withTransportDiagnostics,\n wrapFetchWithTransportDiagnostics,\n} from './transportDiagnostics';\nexport type { TransportActivity, TransportActivityContext, TransportActivityHandler } from './transportDiagnostics';\n\nexport type VersionEnvelopeMode = 'auto' | 'none' | 'major-only';\n\n/**\n * Derive the wire-level `adcp_major_version` integer from a caller-supplied\n * pin. Returns the SDK default when no pin is provided; throws on a pin\n * that doesn't parse so misuse surfaces at the factory boundary instead\n * of silently emitting the SDK's major.\n *\n * Throws `ConfigurationError` (not a plain `Error`) so a typo'd pin\n * surfaces with the same error class as the construction-time gate in\n * `resolveAdcpVersion` — one shape for all pin-misuse paths.\n */\nfunction resolveWireMajor(adcpVersion: string | undefined): number {\n if (adcpVersion === undefined) return ADCP_MAJOR_VERSION;\n const parsed = parseAdcpMajorVersion(adcpVersion);\n if (!Number.isFinite(parsed)) {\n throw new ConfigurationError(\n `adcpVersion ${JSON.stringify(adcpVersion)} is not a valid AdCP version. ` +\n `Expected a semver string (e.g. '3.0.1', '3.1.0-beta.1') or a legacy alias (e.g. 'v3').`,\n 'adcpVersion'\n );\n }\n return parsed;\n}\n\n/**\n * Returns true when the AdCP release that `bundleKey` identifies declares the\n * top-level `adcp_version` envelope field. The field landed in AdCP 3.1 per\n * spec PR `adcontextprotocol/adcp#3493` — 3.0 (any patch / prerelease) does\n * not carry it; 3.1+ does. Used to gate dual-emit on the wire so a 3.0-pinned\n * client doesn't emit a field its target schema doesn't define.\n */\nexport function bundleSupportsAdcpVersionField(bundleKey: string): boolean {\n const major = parseAdcpMajorVersion(bundleKey);\n if (!Number.isFinite(major)) return false;\n if (major < 3) return false;\n if (major > 3) return true;\n // Major 3 — only 3.1+ has the field. Bundle key shape is normalized by\n // `resolveBundleKey`: `'3.0'` / `'3.1'` for stable; `'3.0.0-beta.1'` /\n // `'3.1.0-beta.1'` for prereleases. Match the minor.\n const minorMatch = bundleKey.match(/^\\d+\\.(\\d+)/);\n if (!minorMatch) return false;\n return parseInt(minorMatch[1]!, 10) >= 1;\n}\n\n/**\n * Build the wire-level version envelope to merge into outgoing request args.\n *\n * Per AdCP 3.1 (spec PR `adcontextprotocol/adcp#3493`), 3.1+ requests carry\n * BOTH the integer `adcp_major_version` (deprecated through 3.x, removed in\n * 4.0) AND the release-precision string `adcp_version`. 3.0 schemas don't\n * define the string field, so a 3.0-pinned client emits the integer only —\n * matches the 3.0 spec exactly.\n *\n * Wire string is release-precision (MAJOR.MINOR with optional prerelease tag),\n * per `core/version-envelope.json`'s pattern `^\\d+\\.\\d+(-[a-zA-Z0-9.-]+)?$`.\n * Full-semver bundle keys (`'3.1.0-beta.1'`) are collapsed via\n * `toReleasePrecisionWire` to `'3.1-beta.1'` before emit — meta-field shapes\n * are explicitly NOT valid wire values per the envelope schema's own\n * normalization rule.\n *\n * Returns `{}` for v2 callers (predates the major-version field entirely).\n */\nfunction buildVersionEnvelope(\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (serverVersion === 'v2') return {};\n const wireMajor = resolveWireMajor(adcpVersion);\n const bundleKey = resolveBundleKey(adcpVersion ?? ADCP_VERSION);\n if (!bundleSupportsAdcpVersionField(bundleKey)) {\n return { adcp_major_version: wireMajor };\n }\n const wireValue = toReleasePrecisionWire(bundleKey);\n // Defensive postcondition — should never throw in well-formed code, but\n // if a future refactor breaks the normalization the error message tells\n // the developer to call `toReleasePrecisionWire` instead of silently\n // emitting a non-spec wire string.\n validateAdcpVersionWire(wireValue);\n return { adcp_major_version: wireMajor, adcp_version: wireValue };\n}\n\nlet hasWarnedAboutV2PushNotificationSecret = false;\n\n/**\n * Warn once when an async webhook registration is suppressed for a v2 seller.\n *\n * v2.5's `push-notification-config.json` requires `authentication`, and unlike\n * 3.x it has no RFC 9421 selector semantics — so omitting the block produces a\n * schema-invalid request rather than choosing a signing mode. Without a\n * configured secret there is no honest value to send, and the previous\n * behaviour (a hardcoded placeholder credential) told the seller the channel\n * was authenticated by a constant published in this package.\n */\nfunction warnV2PushNotificationNeedsSecret(): void {\n if (hasWarnedAboutV2PushNotificationSecret) return;\n hasWarnedAboutV2PushNotificationSecret = true;\n console.warn(\n '[adcp] Suppressing push_notification_config for a v2 seller: AdCP 2.5 requires an ' +\n '`authentication` block and no `webhookSecret` is configured. Set `webhookSecret` to register ' +\n 'async task-status webhooks with this agent, or move the agent to an AdCP 3.x pin, where the ' +\n 'RFC 9421 webhook profile needs no shared secret.'\n );\n}\n\nfunction buildVersionEnvelopeForMode(\n mode: VersionEnvelopeMode,\n adcpVersion: string | undefined,\n serverVersion: 'v2' | 'v3' | undefined\n): Record<string, unknown> {\n if (mode === 'none' || serverVersion === 'v2') return {};\n if (mode === 'major-only') return { adcp_major_version: resolveWireMajor(adcpVersion) };\n return buildVersionEnvelope(adcpVersion, serverVersion);\n}\n\n/**\n * Merge the wire-level version envelope into a caller-supplied args object.\n * Caller args win: an explicit `adcp_major_version` / `adcp_version` in\n * `args` (e.g. a conformance harness probing `VERSION_UNSUPPORTED`) passes\n * through unchanged. The envelope only fills fields the caller didn't set.\n *\n * Single chokepoint for all four wire-injection sites so a future refactor\n * can't silently flip the spread order on one branch and leave the others\n * intact. Stale dual-field drift is caught at the server boundary by\n * `createAdcpServer`'s field-disagreement check (spec PR\n * `adcontextprotocol/adcp#3493`).\n *\n * @internal\n */\nexport function applyVersionEnvelope(\n args: Record<string, unknown>,\n envelope: Record<string, unknown>\n): Record<string, unknown> {\n return { ...envelope, ...args };\n}\n\n/**\n * Transport-level safeguards applied to a call.\n *\n * Wired into the SDK's internal fetch chain via AsyncLocalStorage, so the\n * cap takes effect even when the underlying transport's connection cache\n * reuses a fetch that was created on an earlier call with different limits.\n */\nexport interface TransportOptions {\n /**\n * Maximum response body size (in octets) the SDK will read before aborting\n * with `ResponseTooLargeError`. When unset, the SDK does not impose a cap —\n * matches the underlying MCP / A2A transport defaults.\n *\n * Set this when crawling **untrusted** agents (registries, federated\n * discovery layers, monitoring tools) to prevent a hostile vendor from\n * buffering a large reply before any application-layer schema validation\n * runs. Counted across response chunks; pre-cancels when `Content-Length`\n * exceeds the cap. Applies to A2A agent-card discovery\n * (`/.well-known/agent.json`) on the same call as well.\n *\n * Per-call override (`TaskOptions.transport.maxResponseBytes`) beats the\n * value set on the client constructor (`SingleAgentClientConfig.transport`).\n *\n * @remarks\n * **Safe to set on all calls.** SSE responses (`text/event-stream`) are\n * passed through unchanged — a single tool call legitimately emits N status\n * frames + a final result, bounded by protocol-level framing rather than\n * cumulative byte counts. The cap applies to one-shot JSON responses\n * (`get_adcp_capabilities`, agent-card lookup, tool result payloads on\n * non-streaming transports) where the body is bounded by definition.\n *\n * @remarks\n * **Hostile-peer note:** A peer can opt itself out of this cap by responding\n * with `Content-Type: text/event-stream`. SSE is bypassed because cumulative\n * event-frame bytes are unbounded by spec — MCP and A2A both stream tool\n * responses this way. The MCP/A2A SDKs consume SSE incrementally and frame\n * termination bounds memory in practice, so this is not a memory-bomb risk\n * for well-formed transports. Adopters relying on `maxResponseBytes` as a\n * hostile-server defense should treat it as best-effort for non-SSE\n * responses only.\n *\n * @remarks\n * Future hardening knobs (DNS-rebind defense, scheme allow-list, request\n * timeout overrides) will land here as additional fields. When `fetchFn`\n * is supplied, the SDK composes it inside its signing, capture, size-limit,\n * timeout, and diagnostics wrappers so callers do not have to reproduce\n * that non-obvious ordering themselves.\n */\n maxResponseBytes?: number;\n /**\n * Scoped fetch implementation for all outbound HTTP performed on behalf of\n * this client or call, including endpoint/card discovery, tool listing,\n * OAuth discovery and token refresh, and MCP/A2A tool requests.\n *\n * The function is runtime-only configuration and is never serialized into\n * agent records, storyboard artifacts, or compliance output. When unset,\n * the SDK uses the global `fetch` implementation.\n *\n * For SSRF-sensitive metadata probes, supplying this function makes it the\n * trusted network boundary: the SDK still validates schemes and resolved\n * addresses, but a custom fetch API cannot accept the SDK's pinned undici\n * dispatcher. The implementation must therefore prevent DNS rebinding (for\n * example with an egress proxy or its own DNS pinning).\n */\n fetchFn?: typeof fetch;\n /**\n * Timeout in milliseconds for bounded one-shot transport requests such as\n * A2A agent-card discovery and MCP read-path probes. Defaults to 60 seconds\n * for A2A discovery so an unresponsive card endpoint cannot hang forever.\n * Set to `0` to disable the SDK-imposed discovery timeout.\n */\n requestTimeoutMs?: number;\n}\n\n/**\n * Options for {@link ProtocolClient.callTool}. All fields are optional.\n *\n * `webhookUrl` / `webhookSecret` / `webhookToken` are for ASYNC TASK STATUS\n * notifications (push_notification_config). For reporting webhooks\n * (reporting_webhook), include them directly in `args` — they stay in skill\n * parameters and are sent verbatim to the agent.\n */\nexport interface CallToolOptions {\n /** Debug log array. Mutated in place by the protocol layer. */\n debugLogs?: DebugLogEntry[];\n /** URL for async task status notifications. */\n webhookUrl?: string;\n /** HMAC-SHA256 secret for push_notification_config authentication. */\n webhookSecret?: string;\n /** Bearer token for push_notification_config validation. */\n webhookToken?: string;\n /** Pinned protocol generation when the agent advertises both v2 and v3. */\n serverVersion?: 'v2' | 'v3';\n /** A2A session continuity (contextId carries conversation, taskId resumes a task). */\n session?: { contextId?: string; taskId?: string };\n /**\n * AdCP version pin from the calling client/server instance. Sets the\n * wire-level `adcp_major_version` field per-call instead of from the\n * SDK-pinned `ADCP_MAJOR_VERSION` constant. Default falls back to the\n * constant so call sites that don't plumb a per-instance version keep\n * their existing behavior. An explicit `adcp_major_version` /\n * `adcp_version` in `args` overrides this — conformance harnesses use\n * that path to probe seller version negotiation.\n */\n adcpVersion?: string;\n /**\n * Optional wire-only version override. Schema selection and client\n * construction can remain pinned to `adcpVersion`; the request envelope is\n * emitted for this release-precision line.\n */\n wireAdcpVersion?: string;\n /**\n * Controls whether the SDK injects AdCP version envelope fields into the\n * outgoing request. Defaults to `auto`. 3.0 pins emit only the legacy\n * `adcp_major_version`; 3.1+ pins emit both the legacy major and exact\n * `adcp_version` marker. `major-only` forces the legacy integer marker\n * without the 3.1 string marker for strict pre-3.1 peers discovered at\n * runtime.\n */\n versionEnvelope?: VersionEnvelopeMode;\n /**\n * Transport-level safeguards (size caps, etc.). Per-call override of any\n * matching field on the client constructor's `transport` option.\n */\n transport?: TransportOptions;\n /** Caller-owned cancellation signal for the in-flight protocol call. */\n signal?: AbortSignal;\n /** Transport-level diagnostics callback for outbound HTTP requests. */\n onTransportActivity?: TransportActivityHandlerFn;\n /**\n * Correlation metadata attached to transport diagnostics events emitted\n * while this protocol call is active.\n */\n transportActivityContext?: {\n operationId?: string;\n taskId?: string;\n contextId?: string;\n idempotencyKey?: string;\n };\n}\n\n/**\n * Universal protocol client - automatically routes to the correct protocol implementation\n */\nexport class ProtocolClient {\n /**\n * Call a tool on an agent using the appropriate protocol.\n *\n * @param agent - Agent configuration\n * @param toolName - Name of the tool/skill to call\n * @param args - Tool arguments (includes reporting_webhook if needed - NOT removed)\n * @param options - Optional call-level configuration. See {@link CallToolOptions}.\n */\n static async callTool(\n agent: AgentConfig,\n toolName: string,\n args: Record<string, unknown>,\n options: CallToolOptions = {}\n ): Promise<unknown> {\n const {\n debugLogs = [],\n webhookUrl,\n webhookSecret,\n webhookToken,\n serverVersion,\n session,\n adcpVersion,\n wireAdcpVersion,\n versionEnvelope: versionEnvelopeMode = 'auto',\n transport,\n signal,\n onTransportActivity,\n transportActivityContext,\n } = options;\n // Per-instance version envelope. Throws on unparseable pins via\n // `resolveWireMajor`; construction-time `resolveAdcpVersion` is the\n // primary gate but this is the failsafe for callers reaching\n // `ProtocolClient.callTool` directly (test harnesses, the in-process\n // MCP path). Returns `{ adcp_major_version }` for 3.0 pins and\n // `{ adcp_major_version, adcp_version }` for 3.1+ pins.\n const versionEnvelope = buildVersionEnvelopeForMode(\n versionEnvelopeMode,\n wireAdcpVersion ?? adcpVersion,\n serverVersion\n );\n // Enter the response-size-limit ALS slot once for this call. The slot is\n // read by `wrapFetchWithSizeLimit` in both protocol transports, so the\n // cap applies regardless of which path (MCP / A2A / OAuth refresh) the\n // call ends up taking. No-op when the cap is unset or non-positive.\n return withResponseSizeLimit(transport?.maxResponseBytes, () =>\n withTransportDiagnostics(\n {\n agentId: agent.id,\n protocol: agent.protocol,\n tool: toolName,\n taskType: toolName,\n ...transportActivityContext,\n onTransportActivity,\n },\n () =>\n withSpan(\n `adcp.${agent.protocol}.call_tool`,\n {\n 'adcp.agent_id': agent.id,\n 'adcp.protocol': agent.protocol,\n 'adcp.tool': toolName,\n 'http.url': agent.agent_uri,\n },\n async () => {\n // In-process MCP path: pre-connected client, no HTTP transport.\n // Idempotency injection, schema validation, and governance middleware all\n // still apply (they run in SingleAgentClient above this call). We skip\n // URL validation, OAuth refresh, and signing — none apply in-process.\n if (agent.protocol === 'mcp' && agent._inProcessMcpClient) {\n const inProcArgs = applyVersionEnvelope(args, versionEnvelope);\n return callMCPToolWithClient(agent._inProcessMcpClient, toolName, inProcArgs, debugLogs, {\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n });\n }\n\n validateAgentUrl(agent.agent_uri);\n\n // OAuth 2.0 client credentials (RFC 6749 §4.4): re-exchange the\n // secret for a fresh access token whenever the cached one is within\n // its expiration skew. Runs before every call so mid-session expiry\n // can't leave the caller with a stale bearer. No-op if the agent\n // doesn't declare client credentials. Cheap on warm cache (single\n // `Date.now()` compare); a single POST to the token endpoint on miss.\n //\n // `allowPrivateIp` inherits the trust the caller already placed in\n // `agent.agent_uri` — if they're making a call to a private-IP agent,\n // they've authorized this process to talk to private-IP hosts, so\n // the token endpoint on the same network is reachable too. Public\n // agent URLs with private-IP token endpoints still require an\n // explicit opt-in via the library API.\n if (agent.oauth_client_credentials) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n }\n\n const authToken = getAuthToken(agent);\n\n // RFC 9421 signing context. Built once per call and passed through\n // to each protocol-layer entry (`callMCPToolWithTasks`, `callA2ATool`,\n // `callMCPToolWithOAuth`) — those entries seed `signingContextStorage`\n // (AsyncLocalStorage) so the internal transport helpers read it\n // without an explicit parameter. Keep the explicit arg here: it's the\n // ALS seed, not incidental plumbing. `get_adcp_capabilities` is\n // exempt from signing (it's the discovery call itself) and also\n // triggers cache priming for any other op on agents with\n // `request_signing` configured.\n const signingContext = buildAgentSigningContext(agent);\n if (signingContext && toolName !== CAPABILITY_OP) {\n await ensureCapabilityLoaded(agent, signingContext, primeArgs =>\n ProtocolClient.callTool(agent, CAPABILITY_OP, primeArgs, {\n debugLogs,\n serverVersion,\n adcpVersion,\n ...(versionEnvelopeMode !== 'auto' && { versionEnvelope: versionEnvelopeMode }),\n transport,\n signal,\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n onTransportActivity,\n transportActivityContext,\n })\n );\n }\n\n // Inject the version envelope on every request so sellers can validate\n // compatibility. Skip for v2 servers — they don't recognise the\n // version fields and strict-schema agents reject them. The envelope\n // shape is per-pin: 3.0 pins get the integer `adcp_major_version`\n // alone; 3.1+ pins get both that and the release-precision string\n // `adcp_version` (`'3.1'` / `'3.1.0-beta.1'`) per spec PR\n // `adcontextprotocol/adcp#3493`.\n const argsWithVersion = applyVersionEnvelope(args, versionEnvelope);\n\n // Build push_notification_config for ASYNC TASK STATUS notifications\n // (NOT for reporting_webhook - that stays in args)\n // Schema: https://adcontextprotocol.org/schemas/v1/core/push-notification-config.json\n // `authentication` is a scheme SELECTOR, not a fallback: from AdCP\n // 3.0 on, push-notification-config.json makes its presence opt the\n // seller into legacy HMAC-SHA256 and its absence select the RFC\n // 9421 webhook profile, with `required: [\"url\"]` only. Emitting it\n // with a placeholder credential would therefore downgrade every\n // webhook to legacy HMAC keyed by a constant that ships in this\n // file, so the block is omitted unless a real secret backs it.\n //\n // v2.5 predates the selector: there `required` is\n // `[\"url\", \"authentication\"]` and there is no 9421 path, so an\n // omitted block is schema-invalid rather than a mode selection.\n // With no secret there is nothing honest to send a v2 seller, so\n // suppress the registration instead of fabricating a credential.\n const pushNotificationConfig: PushNotificationConfig | undefined = (():\n | PushNotificationConfig\n | undefined => {\n if (!webhookUrl) return undefined;\n if (webhookSecret) {\n return {\n url: webhookUrl,\n ...(webhookToken && { token: webhookToken }),\n authentication: {\n schemes: ['HMAC-SHA256' as const],\n credentials: webhookSecret,\n },\n };\n }\n if (serverVersion === 'v2') {\n warnV2PushNotificationNeedsSecret();\n return undefined;\n }\n return {\n url: webhookUrl,\n ...(webhookToken && { token: webhookToken }),\n };\n })();\n\n if (agent.protocol === 'mcp') {\n // For MCP, include push_notification_config in tool arguments (MCP spec)\n const argsWithWebhook = pushNotificationConfig\n ? { ...argsWithVersion, push_notification_config: pushNotificationConfig }\n : argsWithVersion;\n\n // If the agent config carries authorization-code OAuth tokens,\n // route through the OAuth provider path so the MCP SDK can refresh\n // on 401 instead of hard-failing. Excludes client-credentials\n // agents: they have a cached access token but no refresh_token,\n // and their refresh path is a secret re-exchange (handled above),\n // not the SDK's refresh_token grant.\n if (agent.oauth_tokens && !agent.oauth_client_credentials) {\n const authProvider = getNonInteractiveOAuthProvider(agent, {\n agentHint: agent.id,\n storage: getAgentStorage(agent),\n allowHttp: isLikelyPrivateUrl(agent.agent_uri),\n });\n try {\n return await callMCPToolWithOAuth({\n agentUrl: agent.agent_uri,\n toolName,\n args: argsWithWebhook,\n authProvider,\n debugLogs,\n customHeaders: agent.headers,\n signingContext,\n signal,\n requestTimeoutMs: transport?.requestTimeoutMs,\n fetchFn: transport?.fetchFn,\n });\n } catch (err) {\n // Refresh failed or server rejected the refreshed token — walk the\n // discovery chain so the caller can distinguish \"re-auth needed\"\n // from other failure modes.\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n }\n\n // Use callMCPToolWithTasks which auto-detects server tasks capability\n // and falls back to standard callTool when tasks are not supported\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n authToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (err) {\n // Client-credentials agents: on 401, the AS may have rotated\n // something out-of-band. Force a fresh exchange and retry once\n // before surfacing the error. Bounded (single retry) so we don't\n // loop if the credentials are genuinely wrong.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callMCPToolWithTasks(\n agent.agent_uri,\n toolName,\n argsWithWebhook,\n retryAuthToken,\n debugLogs,\n agent.headers,\n {\n ...(signingContext && { signingContext }),\n ...(signal && { signal }),\n ...(transport?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: transport.requestTimeoutMs,\n }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else if (agent.protocol === 'a2a') {\n // For A2A, pass pushNotificationConfig separately (not in skill parameters)\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n authToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (err) {\n // Same single-retry-on-401 for client-credentials agents as the\n // MCP path above. Kept symmetric so A2A CC agents aren't a\n // second-class experience — including the NeedsAuthorizationError\n // rewrap on a retry that still 401s.\n if (agent.oauth_client_credentials && is401Error(err)) {\n const ccStorage = getAgentStorage(agent);\n const allowPrivateIp = isLikelyPrivateUrl(agent.agent_uri);\n await ensureClientCredentialsTokens(agent, {\n storage: ccStorage,\n force: true,\n allowPrivateIp,\n fetch: transport?.fetchFn,\n });\n const retryAuthToken = agent.oauth_tokens?.access_token ?? authToken;\n try {\n return await callA2ATool(\n agent.agent_uri,\n toolName,\n argsWithVersion,\n retryAuthToken,\n debugLogs,\n pushNotificationConfig,\n agent.headers,\n signingContext,\n session,\n signal,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n );\n } catch (retryErr) {\n await rethrowAsNeedsAuthorization(retryErr, agent.agent_uri, transport?.fetchFn);\n throw retryErr;\n }\n }\n await rethrowAsNeedsAuthorization(err, agent.agent_uri, transport?.fetchFn);\n throw err;\n }\n } else {\n throw new Error(`Unsupported protocol: ${agent.protocol}`);\n }\n }\n )\n )\n );\n }\n}\n\n/**\n * If `err` looks like a 401 from the MCP transport, probe the agent for a\n * Bearer challenge and throw a {@link NeedsAuthorizationError} carrying\n * walked discovery metadata. If the error isn't a 401 or we can't build a\n * requirements record, return silently so the caller re-throws the original.\n *\n * Keeping this off the hot path: we only probe on error, and the probe is\n * a single unauthenticated `tools/list` POST — no retries, no DNS rebind.\n */\nasync function rethrowAsNeedsAuthorization(err: unknown, agentUrl: string, fetchFn?: typeof fetch): Promise<void> {\n if (err instanceof NeedsAuthorizationError) throw err;\n if (!is401Error(err)) return;\n\n // If the caller has already connected to the agent URL, they've implicitly\n // trusted it — inherit that trust for the discovery probe so loopback /\n // private-IP development agents work the same way as public ones.\n const allowPrivateIp = isLikelyPrivateUrl(agentUrl);\n\n // discoverAuthorizationRequirements internally catches network failures and\n // returns null rather than throwing — anything that escapes is a genuine\n // bug we want to surface rather than mask the 401 with.\n const requirements = await discoverAuthorizationRequirements(agentUrl, { allowPrivateIp, fetchFn });\n if (requirements) {\n throw new NeedsAuthorizationError(requirements);\n }\n // No requirements walked; let the caller re-throw the original error.\n}\n\n/**\n * Simple factory functions for protocol-specific clients.\n *\n * Both factories accept a `transport` argument that flows through to the\n * size-cap surface so callers reaching the factory exports honor the same\n * `maxResponseBytes` contract as `ProtocolClient.callTool`. Without it,\n * the factories would silently bypass the cap, which the public API\n * (`TransportOptions`) implies they honor.\n */\nexport const createMCPClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n // Validate the pin at factory time so a typo surfaces here rather than at\n // first call. `buildVersionEnvelope` throws via `resolveWireMajor` on bad\n // input — call it once to surface, then close over the envelope.\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, args: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callMCPToolWithTasks(\n agentUrl,\n toolName,\n applyVersionEnvelope(args, versionEnvelope),\n authToken,\n debugLogs,\n headers,\n {\n ...(transport?.requestTimeoutMs !== undefined && { requestTimeoutMs: transport.requestTimeoutMs }),\n ...(transport?.fetchFn && { fetchFn: transport.fetchFn }),\n }\n )\n ),\n };\n};\n\nexport const createA2AClient = (\n agentUrl: string,\n authToken?: string,\n headers?: Record<string, string>,\n serverVersion?: 'v2' | 'v3',\n adcpVersion?: string,\n transport?: TransportOptions,\n versionEnvelopeMode: VersionEnvelopeMode = 'auto'\n) => {\n const versionEnvelope = buildVersionEnvelopeForMode(versionEnvelopeMode, adcpVersion, serverVersion);\n return {\n callTool: (toolName: string, parameters: Record<string, unknown>, debugLogs?: DebugLogEntry[]) =>\n withResponseSizeLimit(transport?.maxResponseBytes, () =>\n callA2ATool(\n agentUrl,\n toolName,\n applyVersionEnvelope(parameters, versionEnvelope),\n authToken,\n debugLogs,\n undefined,\n headers,\n undefined,\n undefined,\n undefined,\n transport?.requestTimeoutMs,\n transport?.fetchFn\n )\n ),\n };\n};\n"],"mappings":"AAAA,SAAS,iBAAiB,2BAA2B;AACrD,SAAS,WAAW,qBAAqB;AACzC,SAAS,iBAAiB,2BAA2B;AACrD,MAAM,YAAY,cAAc,oBAAoB,YAAY,GAAG,CAAC;AACpE,MAAMA,WAAU,oBAAoB,YAAY,GAAG;AAEnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,uBAAAC,4BAA2B;AACpC,SAAS,2BAA2B;AAMpC,eAAsB,iBAAiB,WAA0B,OAAsB;AACrF,MAAI,aAAa,OAAO;AACtB,UAAMA,qBAAoB;AAAA,EAC5B,OAAO;AACL,wBAAoB;AAAA,EACtB;AACF;AAEA,SAAS,mBAAmB;AA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kB,CAC7B,UACA,WACA,SACA,eACA,aACA,WACA,sBAA2C,WACxC;AAIH,QAAM,kBAAkB,4BAA4B,qBAAqB,aAAa,aAAa;AACnG,SAAO;AAAA,IACL,UAAU,CAAC,UAAkB,MAA+B,cAC1D;AAAA,MAAsB,WAAW;AAAA,MAAkB,MACjDF;AAAA,QACE;AAAA,QACA;AAAA,QACA,qBAAqB,MAAM,eAAe;AAAA,QAC1C;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,UACE,GAAI,WAAW,qBAAqB,UAAa,EAAE,kBAAkB,UAAU,iBAAiB;AAAA,UAChG,GAAI,WAAW,WAAW,EAAE,SAAS,UAAU,QAAQ;AAAA,QACzD;AAAA,MACF;AAAA,IACF;AAAA,EACJ;AACF;AAEO,MAAM,kBAAkB,CAC7B,UACA,WACA,SACA,eACA,aACA,WACA,sBAA2C,WACxC;AACH,QAAM,kBAAkB,4BAA4B,qBAAqB,aAAa,aAAa;AACnG,SAAO;AAAA,IACL,UAAU,CAAC,UAAkB,YAAqC,cAChE;AAAA,MAAsB,WAAW;AAAA,MAAkB,MACjDE;AAAA,QACE;AAAA,QACA;AAAA,QACA,qBAAqB,YAAY,eAAe;AAAA,QAChD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,WAAW;AAAA,QACX,WAAW;AAAA,MACb;AAAA,IACF;AAAA,EACJ;AACF;","names":["require","closeMCPConnections","callMCPToolWithTasks","callMCPToolWithOAuth","callA2ATool","withTransportDiagnostics"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-modern.d.ts","sourceRoot":"","sources":["../../../src/lib/protocols/mcp-modern.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAQL,KAAK,IAAI,EACV,MAAM,8BAA8B,CAAC;AAKtC,OAAO,EAAiD,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAC5G,OAAO,KAAK,EAAE,aAAa,EAA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AoB,CAAC,CAsD/B;AAED,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CAoB/D"}
@@ -180,7 +180,17 @@ function evictLeastRecentlyUsed() {
180
180
  void client?.close().catch(() => {
181
181
  });
182
182
  }
183
- async function createNegotiatedClient(cacheKey, options, authHeaders, useCachedDiscovery = true) {
183
+ function isNegotiationAuthFailure(error) {
184
+ return (0, import_errors.is401Error)(error) || httpStatusOf(error) === 403;
185
+ }
186
+ function presentedStaticCredential(authHeaders, authProvider) {
187
+ if (authProvider) return false;
188
+ return Object.keys(authHeaders).some((key) => {
189
+ const lower = key.toLowerCase();
190
+ return lower === "authorization" || lower === "x-adcp-auth";
191
+ });
192
+ }
193
+ async function createNegotiatedClient(cacheKey, options, authHeaders, useCachedDiscovery = true, skipProbe = false) {
184
194
  const generation = connectionGeneration;
185
195
  const requestTimeoutMs = (0, import_abort.resolveRequestTimeoutMs)(options.requestTimeoutMs);
186
196
  const clientRequestTimeoutMs = (0, import_abort.resolveClientRequestTimeoutMs)(options.requestTimeoutMs);
@@ -212,14 +222,14 @@ async function createNegotiatedClient(cacheKey, options, authHeaders, useCachedD
212
222
  }
213
223
  }
214
224
  );
215
- const prior = useCachedDiscovery ? getCachedModernDiscovery(cacheKey) : void 0;
225
+ const prior = skipProbe ? { kind: "legacy" } : useCachedDiscovery ? getCachedModernDiscovery(cacheKey) : void 0;
216
226
  try {
217
227
  await client.connect(transport, {
218
228
  ...options.signal && { signal: options.signal },
219
229
  ...clientRequestTimeoutMs !== void 0 && { timeout: clientRequestTimeoutMs },
220
230
  ...prior && { prior }
221
231
  });
222
- if (prior) clientsUsingCachedDiscovery.add(client);
232
+ if (prior && !skipProbe) clientsUsingCachedDiscovery.add(client);
223
233
  if (!prior) {
224
234
  const discover = client.getDiscoverResult();
225
235
  if (generation === connectionGeneration) {
@@ -229,14 +239,17 @@ async function createNegotiatedClient(cacheKey, options, authHeaders, useCachedD
229
239
  }
230
240
  return client;
231
241
  } catch (error) {
232
- if (prior) modernDiscoveries.delete(cacheKey);
242
+ if (prior && !skipProbe) modernDiscoveries.delete(cacheKey);
233
243
  try {
234
244
  await client.close();
235
245
  } catch {
236
246
  }
237
- if (prior && import_client.SdkError.isInstance(error) && error.code === import_client.SdkErrorCode.EraNegotiationFailed) {
247
+ if (prior && !skipProbe && import_client.SdkError.isInstance(error) && error.code === import_client.SdkErrorCode.EraNegotiationFailed) {
238
248
  return createNegotiatedClient(cacheKey, options, authHeaders, false);
239
249
  }
250
+ if (isNegotiationAuthFailure(error) && !skipProbe && presentedStaticCredential(authHeaders, options.authProvider)) {
251
+ return createNegotiatedClient(cacheKey, options, authHeaders, useCachedDiscovery, true);
252
+ }
240
253
  throw error;
241
254
  }
242
255
  }