@adcp/sdk 12.0.0 → 12.0.2

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 (959) hide show
  1. package/dist/lib/adapters/content-standards-adapter.mjs +0 -6
  2. package/dist/lib/adapters/content-standards-adapter.mjs.map +1 -1
  3. package/dist/lib/adapters/derived-account-store.mjs +0 -6
  4. package/dist/lib/adapters/derived-account-store.mjs.map +1 -1
  5. package/dist/lib/adapters/governance-adapter.mjs +0 -6
  6. package/dist/lib/adapters/governance-adapter.mjs.map +1 -1
  7. package/dist/lib/adapters/implicit-account-store.mjs +0 -6
  8. package/dist/lib/adapters/implicit-account-store.mjs.map +1 -1
  9. package/dist/lib/adapters/index.mjs +0 -6
  10. package/dist/lib/adapters/index.mjs.map +1 -1
  11. package/dist/lib/adapters/legacy/v2-5/create_media_buy.mjs +0 -6
  12. package/dist/lib/adapters/legacy/v2-5/create_media_buy.mjs.map +1 -1
  13. package/dist/lib/adapters/legacy/v2-5/get_products.mjs +0 -6
  14. package/dist/lib/adapters/legacy/v2-5/get_products.mjs.map +1 -1
  15. package/dist/lib/adapters/legacy/v2-5/index.mjs +0 -6
  16. package/dist/lib/adapters/legacy/v2-5/index.mjs.map +1 -1
  17. package/dist/lib/adapters/legacy/v2-5/list_creative_formats.mjs +0 -6
  18. package/dist/lib/adapters/legacy/v2-5/list_creative_formats.mjs.map +1 -1
  19. package/dist/lib/adapters/legacy/v2-5/preview_creative.mjs +0 -6
  20. package/dist/lib/adapters/legacy/v2-5/preview_creative.mjs.map +1 -1
  21. package/dist/lib/adapters/legacy/v2-5/sync_creatives.mjs +0 -6
  22. package/dist/lib/adapters/legacy/v2-5/sync_creatives.mjs.map +1 -1
  23. package/dist/lib/adapters/legacy/v2-5/types.mjs +0 -6
  24. package/dist/lib/adapters/legacy/v2-5/update_media_buy.mjs +0 -6
  25. package/dist/lib/adapters/legacy/v2-5/update_media_buy.mjs.map +1 -1
  26. package/dist/lib/adapters/oauth-passthrough-resolver.mjs +0 -6
  27. package/dist/lib/adapters/oauth-passthrough-resolver.mjs.map +1 -1
  28. package/dist/lib/adapters/property-list-adapter.mjs +0 -6
  29. package/dist/lib/adapters/property-list-adapter.mjs.map +1 -1
  30. package/dist/lib/adapters/roster-account-store.mjs +0 -6
  31. package/dist/lib/adapters/roster-account-store.mjs.map +1 -1
  32. package/dist/lib/adapters/si-session-manager.mjs +0 -6
  33. package/dist/lib/adapters/si-session-manager.mjs.map +1 -1
  34. package/dist/lib/adapters/version/3.0/brand-fields.mjs +0 -6
  35. package/dist/lib/adapters/version/3.0/brand-fields.mjs.map +1 -1
  36. package/dist/lib/adapters/version/3.0/get-products.mjs +0 -6
  37. package/dist/lib/adapters/version/3.0/get-products.mjs.map +1 -1
  38. package/dist/lib/adapters/version/3.0/index.mjs +0 -6
  39. package/dist/lib/adapters/version/3.0/index.mjs.map +1 -1
  40. package/dist/lib/adapters/version/3.0/sync-accounts.mjs +0 -6
  41. package/dist/lib/adapters/version/3.0/sync-accounts.mjs.map +1 -1
  42. package/dist/lib/adapters/version/index.mjs +0 -6
  43. package/dist/lib/adapters/version/index.mjs.map +1 -1
  44. package/dist/lib/adapters/version/types.mjs +0 -6
  45. package/dist/lib/advanced.mjs +0 -6
  46. package/dist/lib/advanced.mjs.map +1 -1
  47. package/dist/lib/agents/index.generated.mjs +0 -6
  48. package/dist/lib/agents/index.generated.mjs.map +1 -1
  49. package/dist/lib/auth/index.mjs +0 -6
  50. package/dist/lib/auth/index.mjs.map +1 -1
  51. package/dist/lib/auth/oauth/CLIFlowHandler.mjs +0 -6
  52. package/dist/lib/auth/oauth/CLIFlowHandler.mjs.map +1 -1
  53. package/dist/lib/auth/oauth/ClientCredentialsFlow.mjs +0 -6
  54. package/dist/lib/auth/oauth/ClientCredentialsFlow.mjs.map +1 -1
  55. package/dist/lib/auth/oauth/MCPOAuthProvider.mjs +0 -6
  56. package/dist/lib/auth/oauth/MCPOAuthProvider.mjs.map +1 -1
  57. package/dist/lib/auth/oauth/NonInteractiveFlowHandler.mjs +0 -6
  58. package/dist/lib/auth/oauth/NonInteractiveFlowHandler.mjs.map +1 -1
  59. package/dist/lib/auth/oauth/authorization-required.mjs +0 -6
  60. package/dist/lib/auth/oauth/authorization-required.mjs.map +1 -1
  61. package/dist/lib/auth/oauth/diagnose.mjs +0 -6
  62. package/dist/lib/auth/oauth/diagnose.mjs.map +1 -1
  63. package/dist/lib/auth/oauth/diagnostics.mjs +0 -6
  64. package/dist/lib/auth/oauth/diagnostics.mjs.map +1 -1
  65. package/dist/lib/auth/oauth/discovery.mjs +0 -6
  66. package/dist/lib/auth/oauth/discovery.mjs.map +1 -1
  67. package/dist/lib/auth/oauth/file-storage.mjs +0 -6
  68. package/dist/lib/auth/oauth/file-storage.mjs.map +1 -1
  69. package/dist/lib/auth/oauth/index.mjs +0 -6
  70. package/dist/lib/auth/oauth/index.mjs.map +1 -1
  71. package/dist/lib/auth/oauth/secret-resolver.mjs +0 -6
  72. package/dist/lib/auth/oauth/secret-resolver.mjs.map +1 -1
  73. package/dist/lib/auth/oauth/storage-registry.mjs +0 -6
  74. package/dist/lib/auth/oauth/storage-registry.mjs.map +1 -1
  75. package/dist/lib/auth/oauth/types.mjs +0 -6
  76. package/dist/lib/auth/oauth/types.mjs.map +1 -1
  77. package/dist/lib/auth/oauth/web-flow.mjs +0 -6
  78. package/dist/lib/auth/oauth/web-flow.mjs.map +1 -1
  79. package/dist/lib/brand/index.mjs +0 -6
  80. package/dist/lib/brand/index.mjs.map +1 -1
  81. package/dist/lib/canonical-references/index.mjs +6 -7
  82. package/dist/lib/canonical-references/index.mjs.map +1 -1
  83. package/dist/lib/client/index.mjs +0 -6
  84. package/dist/lib/client/index.mjs.map +1 -1
  85. package/dist/lib/compliance/index.mjs +0 -6
  86. package/dist/lib/compliance/index.mjs.map +1 -1
  87. package/dist/lib/compliance-fixtures/index.mjs +0 -6
  88. package/dist/lib/compliance-fixtures/index.mjs.map +1 -1
  89. package/dist/lib/compliance-fixtures/test-authorization-server.mjs +0 -6
  90. package/dist/lib/compliance-fixtures/test-authorization-server.mjs.map +1 -1
  91. package/dist/lib/conformance/index.mjs +0 -6
  92. package/dist/lib/conformance/index.mjs.map +1 -1
  93. package/dist/lib/conformance/invariants/uniformError.mjs +0 -6
  94. package/dist/lib/conformance/invariants/uniformError.mjs.map +1 -1
  95. package/dist/lib/conformance/invariants/uniformErrorComparator.mjs +0 -6
  96. package/dist/lib/conformance/invariants/uniformErrorComparator.mjs.map +1 -1
  97. package/dist/lib/conformance/oracle.mjs +0 -6
  98. package/dist/lib/conformance/oracle.mjs.map +1 -1
  99. package/dist/lib/conformance/runConformance.mjs +0 -6
  100. package/dist/lib/conformance/runConformance.mjs.map +1 -1
  101. package/dist/lib/conformance/runners.mjs +0 -6
  102. package/dist/lib/conformance/runners.mjs.map +1 -1
  103. package/dist/lib/conformance/schemaArbitrary.mjs +0 -6
  104. package/dist/lib/conformance/schemaArbitrary.mjs.map +1 -1
  105. package/dist/lib/conformance/schemaLoader.mjs +5 -6
  106. package/dist/lib/conformance/schemaLoader.mjs.map +1 -1
  107. package/dist/lib/conformance/seeder.mjs +0 -6
  108. package/dist/lib/conformance/seeder.mjs.map +1 -1
  109. package/dist/lib/conformance/types.mjs +0 -6
  110. package/dist/lib/conformance/types.mjs.map +1 -1
  111. package/dist/lib/conformance/webhook.mjs +0 -6
  112. package/dist/lib/conformance/webhook.mjs.map +1 -1
  113. package/dist/lib/core/ADCPMultiAgentClient.mjs +0 -6
  114. package/dist/lib/core/ADCPMultiAgentClient.mjs.map +1 -1
  115. package/dist/lib/core/AgentClient.mjs +0 -6
  116. package/dist/lib/core/AgentClient.mjs.map +1 -1
  117. package/dist/lib/core/AsyncHandler.mjs +0 -6
  118. package/dist/lib/core/AsyncHandler.mjs.map +1 -1
  119. package/dist/lib/core/ConfigurationManager.mjs +0 -6
  120. package/dist/lib/core/ConfigurationManager.mjs.map +1 -1
  121. package/dist/lib/core/ConversationTypes.mjs +0 -6
  122. package/dist/lib/core/CreativeAgentClient.mjs +0 -6
  123. package/dist/lib/core/CreativeAgentClient.mjs.map +1 -1
  124. package/dist/lib/core/GovernanceMiddleware.mjs +0 -6
  125. package/dist/lib/core/GovernanceMiddleware.mjs.map +1 -1
  126. package/dist/lib/core/GovernanceTypes.mjs +0 -6
  127. package/dist/lib/core/GovernanceTypes.mjs.map +1 -1
  128. package/dist/lib/core/ProtocolResponseParser.mjs +0 -6
  129. package/dist/lib/core/ProtocolResponseParser.mjs.map +1 -1
  130. package/dist/lib/core/ResponseValidator.mjs +0 -6
  131. package/dist/lib/core/ResponseValidator.mjs.map +1 -1
  132. package/dist/lib/core/SingleAgentClient.mjs +0 -6
  133. package/dist/lib/core/SingleAgentClient.mjs.map +1 -1
  134. package/dist/lib/core/TaskEventTypes.mjs +0 -6
  135. package/dist/lib/core/TaskEventTypes.mjs.map +1 -1
  136. package/dist/lib/core/TaskExecutor.mjs +0 -6
  137. package/dist/lib/core/TaskExecutor.mjs.map +1 -1
  138. package/dist/lib/core/match.mjs +0 -6
  139. package/dist/lib/core/match.mjs.map +1 -1
  140. package/dist/lib/core/task-status.mjs +0 -6
  141. package/dist/lib/core/task-status.mjs.map +1 -1
  142. package/dist/lib/core/webhook-url.mjs +0 -6
  143. package/dist/lib/core/webhook-url.mjs.map +1 -1
  144. package/dist/lib/discovery/adagents-redirects.mjs +0 -6
  145. package/dist/lib/discovery/adagents-redirects.mjs.map +1 -1
  146. package/dist/lib/discovery/agent-directory.mjs +0 -6
  147. package/dist/lib/discovery/agent-directory.mjs.map +1 -1
  148. package/dist/lib/discovery/inline-publisher-properties.mjs +0 -6
  149. package/dist/lib/discovery/inline-publisher-properties.mjs.map +1 -1
  150. package/dist/lib/discovery/network-consistency-checker.mjs +0 -6
  151. package/dist/lib/discovery/network-consistency-checker.mjs.map +1 -1
  152. package/dist/lib/discovery/property-crawler.mjs +0 -6
  153. package/dist/lib/discovery/property-crawler.mjs.map +1 -1
  154. package/dist/lib/discovery/property-index.mjs +0 -6
  155. package/dist/lib/discovery/property-index.mjs.map +1 -1
  156. package/dist/lib/discovery/publisher-property-selector.mjs +0 -6
  157. package/dist/lib/discovery/publisher-property-selector.mjs.map +1 -1
  158. package/dist/lib/discovery/resolve-agent-properties.mjs +0 -6
  159. package/dist/lib/discovery/resolve-agent-properties.mjs.map +1 -1
  160. package/dist/lib/discovery/types.mjs +0 -6
  161. package/dist/lib/discovery/validate-adagents.mjs +0 -6
  162. package/dist/lib/discovery/validate-adagents.mjs.map +1 -1
  163. package/dist/lib/enums.mjs +0 -6
  164. package/dist/lib/enums.mjs.map +1 -1
  165. package/dist/lib/errors/index.mjs +0 -6
  166. package/dist/lib/errors/index.mjs.map +1 -1
  167. package/dist/lib/express-mcp/index.mjs +0 -6
  168. package/dist/lib/express-mcp/index.mjs.map +1 -1
  169. package/dist/lib/governance/index.mjs +0 -6
  170. package/dist/lib/governance/index.mjs.map +1 -1
  171. package/dist/lib/handlers/types.mjs +0 -6
  172. package/dist/lib/handlers/types.mjs.map +1 -1
  173. package/dist/lib/index.d.mts +1 -1
  174. package/dist/lib/index.d.ts +1 -1
  175. package/dist/lib/index.d.ts.map +1 -1
  176. package/dist/lib/index.js.map +1 -1
  177. package/dist/lib/index.mjs +0 -6
  178. package/dist/lib/index.mjs.map +1 -1
  179. package/dist/lib/media-buy/available-actions.mjs +0 -6
  180. package/dist/lib/media-buy/available-actions.mjs.map +1 -1
  181. package/dist/lib/media-buy/index.mjs +0 -6
  182. package/dist/lib/media-buy/index.mjs.map +1 -1
  183. package/dist/lib/media-buy/preflight.mjs +0 -6
  184. package/dist/lib/media-buy/preflight.mjs.map +1 -1
  185. package/dist/lib/media-buy/property-policy.mjs +0 -6
  186. package/dist/lib/media-buy/property-policy.mjs.map +1 -1
  187. package/dist/lib/media-buy/types.mjs +0 -6
  188. package/dist/lib/media-buy/types.mjs.map +1 -1
  189. package/dist/lib/media-buy/update-fields.generated.mjs +0 -6
  190. package/dist/lib/media-buy/update-fields.generated.mjs.map +1 -1
  191. package/dist/lib/mock-server/creative-ad-server/seed-data.mjs +0 -6
  192. package/dist/lib/mock-server/creative-ad-server/seed-data.mjs.map +1 -1
  193. package/dist/lib/mock-server/creative-ad-server/server.mjs +0 -6
  194. package/dist/lib/mock-server/creative-ad-server/server.mjs.map +1 -1
  195. package/dist/lib/mock-server/creative-template/seed-data.mjs +0 -6
  196. package/dist/lib/mock-server/creative-template/seed-data.mjs.map +1 -1
  197. package/dist/lib/mock-server/creative-template/server.mjs +0 -6
  198. package/dist/lib/mock-server/creative-template/server.mjs.map +1 -1
  199. package/dist/lib/mock-server/index.mjs +0 -6
  200. package/dist/lib/mock-server/index.mjs.map +1 -1
  201. package/dist/lib/mock-server/sales-guaranteed/recipe.mjs +0 -6
  202. package/dist/lib/mock-server/sales-guaranteed/recipe.mjs.map +1 -1
  203. package/dist/lib/mock-server/sales-guaranteed/seed-data.mjs +0 -6
  204. package/dist/lib/mock-server/sales-guaranteed/seed-data.mjs.map +1 -1
  205. package/dist/lib/mock-server/sales-guaranteed/server.mjs +0 -6
  206. package/dist/lib/mock-server/sales-guaranteed/server.mjs.map +1 -1
  207. package/dist/lib/mock-server/sales-non-guaranteed/recipe.mjs +0 -6
  208. package/dist/lib/mock-server/sales-non-guaranteed/recipe.mjs.map +1 -1
  209. package/dist/lib/mock-server/sales-non-guaranteed/seed-data.mjs +0 -6
  210. package/dist/lib/mock-server/sales-non-guaranteed/seed-data.mjs.map +1 -1
  211. package/dist/lib/mock-server/sales-non-guaranteed/server.mjs +0 -6
  212. package/dist/lib/mock-server/sales-non-guaranteed/server.mjs.map +1 -1
  213. package/dist/lib/mock-server/sales-social/seed-data.mjs +0 -6
  214. package/dist/lib/mock-server/sales-social/seed-data.mjs.map +1 -1
  215. package/dist/lib/mock-server/sales-social/server.mjs +0 -6
  216. package/dist/lib/mock-server/sales-social/server.mjs.map +1 -1
  217. package/dist/lib/mock-server/scenario.mjs +0 -6
  218. package/dist/lib/mock-server/scenario.mjs.map +1 -1
  219. package/dist/lib/mock-server/signal-marketplace/seed-data.mjs +0 -6
  220. package/dist/lib/mock-server/signal-marketplace/seed-data.mjs.map +1 -1
  221. package/dist/lib/mock-server/signal-marketplace/server.mjs +0 -6
  222. package/dist/lib/mock-server/signal-marketplace/server.mjs.map +1 -1
  223. package/dist/lib/mock-server/sponsored-intelligence/seed-data.mjs +0 -6
  224. package/dist/lib/mock-server/sponsored-intelligence/seed-data.mjs.map +1 -1
  225. package/dist/lib/mock-server/sponsored-intelligence/server.mjs +0 -6
  226. package/dist/lib/mock-server/sponsored-intelligence/server.mjs.map +1 -1
  227. package/dist/lib/net/address-guards.mjs +0 -6
  228. package/dist/lib/net/address-guards.mjs.map +1 -1
  229. package/dist/lib/net/index.mjs +0 -6
  230. package/dist/lib/net/index.mjs.map +1 -1
  231. package/dist/lib/net/ssrf-fetch.mjs +0 -6
  232. package/dist/lib/net/ssrf-fetch.mjs.map +1 -1
  233. package/dist/lib/observability/index.mjs +0 -6
  234. package/dist/lib/observability/index.mjs.map +1 -1
  235. package/dist/lib/observability/tracing.mjs +6 -7
  236. package/dist/lib/observability/tracing.mjs.map +1 -1
  237. package/dist/lib/protocols/a2a.mjs +0 -6
  238. package/dist/lib/protocols/a2a.mjs.map +1 -1
  239. package/dist/lib/protocols/abort.mjs +0 -6
  240. package/dist/lib/protocols/abort.mjs.map +1 -1
  241. package/dist/lib/protocols/index.mjs +0 -6
  242. package/dist/lib/protocols/index.mjs.map +1 -1
  243. package/dist/lib/protocols/mcp-modern.mjs +0 -6
  244. package/dist/lib/protocols/mcp-modern.mjs.map +1 -1
  245. package/dist/lib/protocols/mcp-tasks.mjs +0 -6
  246. package/dist/lib/protocols/mcp-tasks.mjs.map +1 -1
  247. package/dist/lib/protocols/mcp.mjs +0 -6
  248. package/dist/lib/protocols/mcp.mjs.map +1 -1
  249. package/dist/lib/protocols/rawResponseCapture.mjs +0 -6
  250. package/dist/lib/protocols/rawResponseCapture.mjs.map +1 -1
  251. package/dist/lib/protocols/responseSizeLimit.mjs +0 -6
  252. package/dist/lib/protocols/responseSizeLimit.mjs.map +1 -1
  253. package/dist/lib/protocols/transportDiagnostics.mjs +0 -6
  254. package/dist/lib/protocols/transportDiagnostics.mjs.map +1 -1
  255. package/dist/lib/registry/cursor-store.mjs +0 -6
  256. package/dist/lib/registry/cursor-store.mjs.map +1 -1
  257. package/dist/lib/registry/feed-stream.mjs +0 -6
  258. package/dist/lib/registry/feed-stream.mjs.map +1 -1
  259. package/dist/lib/registry/index.mjs +0 -6
  260. package/dist/lib/registry/index.mjs.map +1 -1
  261. package/dist/lib/registry/property-registry.mjs +0 -6
  262. package/dist/lib/registry/property-registry.mjs.map +1 -1
  263. package/dist/lib/registry/sync.mjs +0 -6
  264. package/dist/lib/registry/sync.mjs.map +1 -1
  265. package/dist/lib/registry/types.generated.mjs +0 -6
  266. package/dist/lib/registry/types.mjs +0 -6
  267. package/dist/lib/schemas/index.mjs +0 -6
  268. package/dist/lib/schemas/index.mjs.map +1 -1
  269. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  270. package/dist/lib/server/a2a-adapter.mjs +0 -6
  271. package/dist/lib/server/a2a-adapter.mjs.map +1 -1
  272. package/dist/lib/server/account-mode.mjs +0 -6
  273. package/dist/lib/server/account-mode.mjs.map +1 -1
  274. package/dist/lib/server/adcp-server.mjs +0 -6
  275. package/dist/lib/server/adcp-server.mjs.map +1 -1
  276. package/dist/lib/server/auth-introspection.mjs +0 -6
  277. package/dist/lib/server/auth-introspection.mjs.map +1 -1
  278. package/dist/lib/server/auth-signature.mjs +0 -6
  279. package/dist/lib/server/auth-signature.mjs.map +1 -1
  280. package/dist/lib/server/auth.mjs +0 -6
  281. package/dist/lib/server/auth.mjs.map +1 -1
  282. package/dist/lib/server/create-adcp-server.d.mts +13 -0
  283. package/dist/lib/server/create-adcp-server.d.ts +13 -0
  284. package/dist/lib/server/create-adcp-server.d.ts.map +1 -1
  285. package/dist/lib/server/create-adcp-server.js +3 -2
  286. package/dist/lib/server/create-adcp-server.js.map +1 -1
  287. package/dist/lib/server/create-adcp-server.mjs +3 -8
  288. package/dist/lib/server/create-adcp-server.mjs.map +1 -1
  289. package/dist/lib/server/credential-policy.mjs +0 -6
  290. package/dist/lib/server/credential-policy.mjs.map +1 -1
  291. package/dist/lib/server/ctx-metadata/backends/memory.mjs +0 -6
  292. package/dist/lib/server/ctx-metadata/backends/memory.mjs.map +1 -1
  293. package/dist/lib/server/ctx-metadata/backends/pg.mjs +0 -6
  294. package/dist/lib/server/ctx-metadata/backends/pg.mjs.map +1 -1
  295. package/dist/lib/server/ctx-metadata/backends/redis.mjs +0 -6
  296. package/dist/lib/server/ctx-metadata/backends/redis.mjs.map +1 -1
  297. package/dist/lib/server/ctx-metadata/index.mjs +0 -6
  298. package/dist/lib/server/ctx-metadata/index.mjs.map +1 -1
  299. package/dist/lib/server/ctx-metadata/store.mjs +0 -6
  300. package/dist/lib/server/ctx-metadata/store.mjs.map +1 -1
  301. package/dist/lib/server/ctx-metadata/wire-shape.mjs +0 -6
  302. package/dist/lib/server/ctx-metadata/wire-shape.mjs.map +1 -1
  303. package/dist/lib/server/decisioning/account.mjs +0 -6
  304. package/dist/lib/server/decisioning/account.mjs.map +1 -1
  305. package/dist/lib/server/decisioning/admin-router.mjs +0 -6
  306. package/dist/lib/server/decisioning/admin-router.mjs.map +1 -1
  307. package/dist/lib/server/decisioning/assembly-helpers.mjs +0 -6
  308. package/dist/lib/server/decisioning/assembly-helpers.mjs.map +1 -1
  309. package/dist/lib/server/decisioning/async-outcome.mjs +0 -6
  310. package/dist/lib/server/decisioning/async-outcome.mjs.map +1 -1
  311. package/dist/lib/server/decisioning/buyer-agent.mjs +0 -6
  312. package/dist/lib/server/decisioning/buyer-agent.mjs.map +1 -1
  313. package/dist/lib/server/decisioning/capabilities.mjs +0 -6
  314. package/dist/lib/server/decisioning/capabilities.mjs.map +1 -1
  315. package/dist/lib/server/decisioning/compose.mjs +0 -6
  316. package/dist/lib/server/decisioning/compose.mjs.map +1 -1
  317. package/dist/lib/server/decisioning/context.mjs +0 -6
  318. package/dist/lib/server/decisioning/errors-typed.mjs +0 -6
  319. package/dist/lib/server/decisioning/errors-typed.mjs.map +1 -1
  320. package/dist/lib/server/decisioning/helpers.mjs +0 -6
  321. package/dist/lib/server/decisioning/helpers.mjs.map +1 -1
  322. package/dist/lib/server/decisioning/index.mjs +0 -6
  323. package/dist/lib/server/decisioning/index.mjs.map +1 -1
  324. package/dist/lib/server/decisioning/list-helpers.mjs +0 -6
  325. package/dist/lib/server/decisioning/list-helpers.mjs.map +1 -1
  326. package/dist/lib/server/decisioning/manifest-helpers.mjs +0 -6
  327. package/dist/lib/server/decisioning/manifest-helpers.mjs.map +1 -1
  328. package/dist/lib/server/decisioning/pagination.mjs +0 -6
  329. package/dist/lib/server/decisioning/platform-helpers.mjs +0 -6
  330. package/dist/lib/server/decisioning/platform-helpers.mjs.map +1 -1
  331. package/dist/lib/server/decisioning/platform.mjs +0 -6
  332. package/dist/lib/server/decisioning/proposal/dispatch.mjs +0 -6
  333. package/dist/lib/server/decisioning/proposal/dispatch.mjs.map +1 -1
  334. package/dist/lib/server/decisioning/proposal/index.mjs +0 -6
  335. package/dist/lib/server/decisioning/proposal/index.mjs.map +1 -1
  336. package/dist/lib/server/decisioning/proposal/lifecycle.mjs +0 -6
  337. package/dist/lib/server/decisioning/proposal/lifecycle.mjs.map +1 -1
  338. package/dist/lib/server/decisioning/proposal/mock-manager.mjs +0 -6
  339. package/dist/lib/server/decisioning/proposal/mock-manager.mjs.map +1 -1
  340. package/dist/lib/server/decisioning/proposal/store.mjs +0 -6
  341. package/dist/lib/server/decisioning/proposal/store.mjs.map +1 -1
  342. package/dist/lib/server/decisioning/proposal/types.mjs +0 -6
  343. package/dist/lib/server/decisioning/proposal/types.mjs.map +1 -1
  344. package/dist/lib/server/decisioning/resolve-presets.mjs +0 -6
  345. package/dist/lib/server/decisioning/resolve-presets.mjs.map +1 -1
  346. package/dist/lib/server/decisioning/runtime/entity-hydration.generated.mjs +0 -6
  347. package/dist/lib/server/decisioning/runtime/entity-hydration.generated.mjs.map +1 -1
  348. package/dist/lib/server/decisioning/runtime/from-platform.mjs +0 -6
  349. package/dist/lib/server/decisioning/runtime/from-platform.mjs.map +1 -1
  350. package/dist/lib/server/decisioning/runtime/observed-modes.mjs +0 -6
  351. package/dist/lib/server/decisioning/runtime/observed-modes.mjs.map +1 -1
  352. package/dist/lib/server/decisioning/runtime/postgres-task-registry.mjs +0 -6
  353. package/dist/lib/server/decisioning/runtime/postgres-task-registry.mjs.map +1 -1
  354. package/dist/lib/server/decisioning/runtime/protocol-for-tool.mjs +0 -6
  355. package/dist/lib/server/decisioning/runtime/protocol-for-tool.mjs.map +1 -1
  356. package/dist/lib/server/decisioning/runtime/task-registry.mjs +0 -6
  357. package/dist/lib/server/decisioning/runtime/task-registry.mjs.map +1 -1
  358. package/dist/lib/server/decisioning/runtime/to-context.mjs +0 -6
  359. package/dist/lib/server/decisioning/runtime/to-context.mjs.map +1 -1
  360. package/dist/lib/server/decisioning/runtime/validate-platform.mjs +0 -6
  361. package/dist/lib/server/decisioning/runtime/validate-platform.mjs.map +1 -1
  362. package/dist/lib/server/decisioning/specialisms/audiences.mjs +0 -6
  363. package/dist/lib/server/decisioning/specialisms/brand-rights.mjs +0 -6
  364. package/dist/lib/server/decisioning/specialisms/campaign-governance.mjs +0 -6
  365. package/dist/lib/server/decisioning/specialisms/content-standards.mjs +0 -6
  366. package/dist/lib/server/decisioning/specialisms/creative-ad-server.mjs +0 -6
  367. package/dist/lib/server/decisioning/specialisms/creative.mjs +0 -6
  368. package/dist/lib/server/decisioning/specialisms/lists.mjs +0 -6
  369. package/dist/lib/server/decisioning/specialisms/sales.mjs +0 -6
  370. package/dist/lib/server/decisioning/specialisms/signals.mjs +0 -6
  371. package/dist/lib/server/decisioning/specialisms/sponsored-intelligence.mjs +0 -6
  372. package/dist/lib/server/decisioning/start-time.mjs +0 -6
  373. package/dist/lib/server/decisioning/start-time.mjs.map +1 -1
  374. package/dist/lib/server/decisioning/status-changes.mjs +0 -6
  375. package/dist/lib/server/decisioning/status-changes.mjs.map +1 -1
  376. package/dist/lib/server/decisioning/status-mappers.mjs +0 -6
  377. package/dist/lib/server/decisioning/status-mappers.mjs.map +1 -1
  378. package/dist/lib/server/decisioning/tenant-registry.mjs +0 -6
  379. package/dist/lib/server/decisioning/tenant-registry.mjs.map +1 -1
  380. package/dist/lib/server/decisioning/tenant-store.mjs +0 -6
  381. package/dist/lib/server/decisioning/tenant-store.mjs.map +1 -1
  382. package/dist/lib/server/decisioning/validate-specialisms.mjs +0 -6
  383. package/dist/lib/server/decisioning/validate-specialisms.mjs.map +1 -1
  384. package/dist/lib/server/dynamic-registry.mjs +0 -6
  385. package/dist/lib/server/dynamic-registry.mjs.map +1 -1
  386. package/dist/lib/server/envelope-allowlist.mjs +0 -6
  387. package/dist/lib/server/envelope-allowlist.mjs.map +1 -1
  388. package/dist/lib/server/error-arm-tools.mjs +5 -6
  389. package/dist/lib/server/error-arm-tools.mjs.map +1 -1
  390. package/dist/lib/server/errors.mjs +0 -6
  391. package/dist/lib/server/errors.mjs.map +1 -1
  392. package/dist/lib/server/example-tld-guard.mjs +0 -6
  393. package/dist/lib/server/example-tld-guard.mjs.map +1 -1
  394. package/dist/lib/server/express-adapter.mjs +0 -6
  395. package/dist/lib/server/express-adapter.mjs.map +1 -1
  396. package/dist/lib/server/governance.mjs +0 -6
  397. package/dist/lib/server/governance.mjs.map +1 -1
  398. package/dist/lib/server/idempotency/backends/lazy.mjs +0 -6
  399. package/dist/lib/server/idempotency/backends/lazy.mjs.map +1 -1
  400. package/dist/lib/server/idempotency/backends/memory.mjs +0 -6
  401. package/dist/lib/server/idempotency/backends/memory.mjs.map +1 -1
  402. package/dist/lib/server/idempotency/backends/pg.mjs +0 -6
  403. package/dist/lib/server/idempotency/backends/pg.mjs.map +1 -1
  404. package/dist/lib/server/idempotency/backends/redis.mjs +0 -6
  405. package/dist/lib/server/idempotency/backends/redis.mjs.map +1 -1
  406. package/dist/lib/server/idempotency/index.mjs +0 -6
  407. package/dist/lib/server/idempotency/index.mjs.map +1 -1
  408. package/dist/lib/server/idempotency/store.mjs +0 -6
  409. package/dist/lib/server/idempotency/store.mjs.map +1 -1
  410. package/dist/lib/server/index.d.mts +1 -1
  411. package/dist/lib/server/index.d.ts +1 -1
  412. package/dist/lib/server/index.d.ts.map +1 -1
  413. package/dist/lib/server/index.js.map +1 -1
  414. package/dist/lib/server/index.mjs +0 -6
  415. package/dist/lib/server/index.mjs.map +1 -1
  416. package/dist/lib/server/legacy/v5/index.d.mts +1 -1
  417. package/dist/lib/server/legacy/v5/index.d.ts +1 -1
  418. package/dist/lib/server/legacy/v5/index.d.ts.map +1 -1
  419. package/dist/lib/server/legacy/v5/index.js.map +1 -1
  420. package/dist/lib/server/legacy/v5/index.mjs +0 -6
  421. package/dist/lib/server/legacy/v5/index.mjs.map +1 -1
  422. package/dist/lib/server/mcp-modern-server.mjs +0 -6
  423. package/dist/lib/server/mcp-modern-server.mjs.map +1 -1
  424. package/dist/lib/server/media-buy-actions.mjs +0 -6
  425. package/dist/lib/server/media-buy-actions.mjs.map +1 -1
  426. package/dist/lib/server/media-buy-helpers.mjs +0 -6
  427. package/dist/lib/server/media-buy-helpers.mjs.map +1 -1
  428. package/dist/lib/server/media-buy-store.mjs +0 -6
  429. package/dist/lib/server/media-buy-store.mjs.map +1 -1
  430. package/dist/lib/server/normalize-errors.mjs +0 -6
  431. package/dist/lib/server/normalize-errors.mjs.map +1 -1
  432. package/dist/lib/server/operational-platform.mjs +0 -6
  433. package/dist/lib/server/operational-platform.mjs.map +1 -1
  434. package/dist/lib/server/pick-safe-details.mjs +0 -6
  435. package/dist/lib/server/pick-safe-details.mjs.map +1 -1
  436. package/dist/lib/server/pin-and-bind-fetch.mjs +0 -6
  437. package/dist/lib/server/pin-and-bind-fetch.mjs.map +1 -1
  438. package/dist/lib/server/postgres-state-store.mjs +0 -6
  439. package/dist/lib/server/postgres-state-store.mjs.map +1 -1
  440. package/dist/lib/server/postgres-task-store.mjs +0 -6
  441. package/dist/lib/server/postgres-task-store.mjs.map +1 -1
  442. package/dist/lib/server/product-defaults.mjs +0 -6
  443. package/dist/lib/server/product-defaults.mjs.map +1 -1
  444. package/dist/lib/server/redact.mjs +0 -6
  445. package/dist/lib/server/redact.mjs.map +1 -1
  446. package/dist/lib/server/responses.mjs +0 -6
  447. package/dist/lib/server/responses.mjs.map +1 -1
  448. package/dist/lib/server/serve.mjs +0 -6
  449. package/dist/lib/server/serve.mjs.map +1 -1
  450. package/dist/lib/server/socket-mode/conformance-client.mjs +0 -6
  451. package/dist/lib/server/socket-mode/conformance-client.mjs.map +1 -1
  452. package/dist/lib/server/socket-mode/index.mjs +0 -6
  453. package/dist/lib/server/socket-mode/index.mjs.map +1 -1
  454. package/dist/lib/server/socket-mode/ws-transport.mjs +0 -6
  455. package/dist/lib/server/socket-mode/ws-transport.mjs.map +1 -1
  456. package/dist/lib/server/state-machine.mjs +0 -6
  457. package/dist/lib/server/state-machine.mjs.map +1 -1
  458. package/dist/lib/server/state-store.mjs +0 -6
  459. package/dist/lib/server/state-store.mjs.map +1 -1
  460. package/dist/lib/server/structured-serialize.mjs +0 -6
  461. package/dist/lib/server/structured-serialize.mjs.map +1 -1
  462. package/dist/lib/server/targeting-helpers.mjs +0 -6
  463. package/dist/lib/server/targeting-helpers.mjs.map +1 -1
  464. package/dist/lib/server/tasks.mjs +0 -6
  465. package/dist/lib/server/tasks.mjs.map +1 -1
  466. package/dist/lib/server/test-controller-bridge.mjs +0 -6
  467. package/dist/lib/server/test-controller-bridge.mjs.map +1 -1
  468. package/dist/lib/server/test-controller.mjs +0 -6
  469. package/dist/lib/server/test-controller.mjs.map +1 -1
  470. package/dist/lib/server/upstream-helpers.mjs +0 -6
  471. package/dist/lib/server/upstream-helpers.mjs.map +1 -1
  472. package/dist/lib/server/webhook-emitter.mjs +0 -6
  473. package/dist/lib/server/webhook-emitter.mjs.map +1 -1
  474. package/dist/lib/server/wire-safe.mjs +0 -6
  475. package/dist/lib/server/wire-safe.mjs.map +1 -1
  476. package/dist/lib/server/wire-spec-fields.generated.mjs +0 -6
  477. package/dist/lib/server/wire-spec-fields.generated.mjs.map +1 -1
  478. package/dist/lib/server/wrap-envelope.mjs +0 -6
  479. package/dist/lib/server/wrap-envelope.mjs.map +1 -1
  480. package/dist/lib/signing/agent-context.mjs +0 -6
  481. package/dist/lib/signing/agent-context.mjs.map +1 -1
  482. package/dist/lib/signing/agent-fetch.mjs +0 -6
  483. package/dist/lib/signing/agent-fetch.mjs.map +1 -1
  484. package/dist/lib/signing/agent-resolver/canonicalize.mjs +0 -6
  485. package/dist/lib/signing/agent-resolver/canonicalize.mjs.map +1 -1
  486. package/dist/lib/signing/agent-resolver/capabilities-types.mjs +0 -6
  487. package/dist/lib/signing/agent-resolver/capabilities-types.mjs.map +1 -1
  488. package/dist/lib/signing/agent-resolver/consistency.mjs +0 -6
  489. package/dist/lib/signing/agent-resolver/consistency.mjs.map +1 -1
  490. package/dist/lib/signing/agent-resolver/errors.mjs +0 -6
  491. package/dist/lib/signing/agent-resolver/errors.mjs.map +1 -1
  492. package/dist/lib/signing/agent-resolver/etld.mjs +0 -6
  493. package/dist/lib/signing/agent-resolver/etld.mjs.map +1 -1
  494. package/dist/lib/signing/agent-resolver/fetch-helpers.mjs +0 -6
  495. package/dist/lib/signing/agent-resolver/fetch-helpers.mjs.map +1 -1
  496. package/dist/lib/signing/agent-resolver/index.mjs +0 -6
  497. package/dist/lib/signing/agent-resolver/index.mjs.map +1 -1
  498. package/dist/lib/signing/agent-resolver/jwks-set.mjs +0 -6
  499. package/dist/lib/signing/agent-resolver/jwks-set.mjs.map +1 -1
  500. package/dist/lib/signing/agent-resolver/resolve-agent.mjs +0 -6
  501. package/dist/lib/signing/agent-resolver/resolve-agent.mjs.map +1 -1
  502. package/dist/lib/signing/agent-resolver/select-agent.mjs +0 -6
  503. package/dist/lib/signing/agent-resolver/select-agent.mjs.map +1 -1
  504. package/dist/lib/signing/agent-resolver/strict-json.mjs +0 -6
  505. package/dist/lib/signing/agent-resolver/strict-json.mjs.map +1 -1
  506. package/dist/lib/signing/brand-jwks.mjs +0 -6
  507. package/dist/lib/signing/brand-jwks.mjs.map +1 -1
  508. package/dist/lib/signing/canonicalize.mjs +0 -6
  509. package/dist/lib/signing/canonicalize.mjs.map +1 -1
  510. package/dist/lib/signing/capability-cache.mjs +0 -6
  511. package/dist/lib/signing/capability-cache.mjs.map +1 -1
  512. package/dist/lib/signing/capability-priming.mjs +0 -6
  513. package/dist/lib/signing/capability-priming.mjs.map +1 -1
  514. package/dist/lib/signing/client.mjs +0 -6
  515. package/dist/lib/signing/client.mjs.map +1 -1
  516. package/dist/lib/signing/content-digest.mjs +0 -6
  517. package/dist/lib/signing/content-digest.mjs.map +1 -1
  518. package/dist/lib/signing/crypto.mjs +0 -6
  519. package/dist/lib/signing/crypto.mjs.map +1 -1
  520. package/dist/lib/signing/ecdsa-encoding.mjs +0 -6
  521. package/dist/lib/signing/ecdsa-encoding.mjs.map +1 -1
  522. package/dist/lib/signing/errors.mjs +0 -6
  523. package/dist/lib/signing/errors.mjs.map +1 -1
  524. package/dist/lib/signing/fetch-async.mjs +0 -6
  525. package/dist/lib/signing/fetch-async.mjs.map +1 -1
  526. package/dist/lib/signing/fetch.mjs +0 -6
  527. package/dist/lib/signing/fetch.mjs.map +1 -1
  528. package/dist/lib/signing/index.mjs +0 -6
  529. package/dist/lib/signing/index.mjs.map +1 -1
  530. package/dist/lib/signing/jwks-helpers.mjs +0 -6
  531. package/dist/lib/signing/jwks-helpers.mjs.map +1 -1
  532. package/dist/lib/signing/jwks-https.mjs +0 -6
  533. package/dist/lib/signing/jwks-https.mjs.map +1 -1
  534. package/dist/lib/signing/jwks.mjs +0 -6
  535. package/dist/lib/signing/jwks.mjs.map +1 -1
  536. package/dist/lib/signing/middleware.mjs +0 -6
  537. package/dist/lib/signing/middleware.mjs.map +1 -1
  538. package/dist/lib/signing/parser.mjs +0 -6
  539. package/dist/lib/signing/parser.mjs.map +1 -1
  540. package/dist/lib/signing/postgres-replay-store.mjs +0 -6
  541. package/dist/lib/signing/postgres-replay-store.mjs.map +1 -1
  542. package/dist/lib/signing/protocol-response.mjs +0 -6
  543. package/dist/lib/signing/protocol-response.mjs.map +1 -1
  544. package/dist/lib/signing/provider.mjs +0 -6
  545. package/dist/lib/signing/redis-replay-store.mjs +0 -6
  546. package/dist/lib/signing/redis-replay-store.mjs.map +1 -1
  547. package/dist/lib/signing/replay.mjs +0 -6
  548. package/dist/lib/signing/replay.mjs.map +1 -1
  549. package/dist/lib/signing/request-context.mjs +0 -6
  550. package/dist/lib/signing/request-context.mjs.map +1 -1
  551. package/dist/lib/signing/revocation-https.mjs +0 -6
  552. package/dist/lib/signing/revocation-https.mjs.map +1 -1
  553. package/dist/lib/signing/revocation.mjs +0 -6
  554. package/dist/lib/signing/revocation.mjs.map +1 -1
  555. package/dist/lib/signing/server.mjs +0 -6
  556. package/dist/lib/signing/server.mjs.map +1 -1
  557. package/dist/lib/signing/signer-async.mjs +0 -6
  558. package/dist/lib/signing/signer-async.mjs.map +1 -1
  559. package/dist/lib/signing/signer.mjs +0 -6
  560. package/dist/lib/signing/signer.mjs.map +1 -1
  561. package/dist/lib/signing/testing.mjs +0 -6
  562. package/dist/lib/signing/testing.mjs.map +1 -1
  563. package/dist/lib/signing/types.mjs +0 -6
  564. package/dist/lib/signing/types.mjs.map +1 -1
  565. package/dist/lib/signing/verifier.mjs +0 -6
  566. package/dist/lib/signing/verifier.mjs.map +1 -1
  567. package/dist/lib/signing/webhook-auth-detection.mjs +0 -6
  568. package/dist/lib/signing/webhook-auth-detection.mjs.map +1 -1
  569. package/dist/lib/signing/webhook-verifier.mjs +0 -6
  570. package/dist/lib/signing/webhook-verifier.mjs.map +1 -1
  571. package/dist/lib/storage/MemoryStorage.mjs +0 -6
  572. package/dist/lib/storage/MemoryStorage.mjs.map +1 -1
  573. package/dist/lib/storage/interfaces.mjs +0 -6
  574. package/dist/lib/substitution/encoder/SubstitutionEncoder.mjs +0 -6
  575. package/dist/lib/substitution/encoder/SubstitutionEncoder.mjs.map +1 -1
  576. package/dist/lib/substitution/encoder/index.mjs +0 -6
  577. package/dist/lib/substitution/encoder/index.mjs.map +1 -1
  578. package/dist/lib/substitution/index.mjs +0 -6
  579. package/dist/lib/substitution/index.mjs.map +1 -1
  580. package/dist/lib/substitution/observer/SubstitutionObserver.mjs +0 -6
  581. package/dist/lib/substitution/observer/SubstitutionObserver.mjs.map +1 -1
  582. package/dist/lib/substitution/observer/alignment.mjs +0 -6
  583. package/dist/lib/substitution/observer/alignment.mjs.map +1 -1
  584. package/dist/lib/substitution/observer/assertions.mjs +0 -6
  585. package/dist/lib/substitution/observer/assertions.mjs.map +1 -1
  586. package/dist/lib/substitution/observer/html-parser.mjs +0 -6
  587. package/dist/lib/substitution/observer/html-parser.mjs.map +1 -1
  588. package/dist/lib/substitution/observer/index.mjs +0 -6
  589. package/dist/lib/substitution/observer/index.mjs.map +1 -1
  590. package/dist/lib/substitution/observer/ssrf.mjs +0 -6
  591. package/dist/lib/substitution/observer/ssrf.mjs.map +1 -1
  592. package/dist/lib/substitution/rfc3986.mjs +0 -6
  593. package/dist/lib/substitution/rfc3986.mjs.map +1 -1
  594. package/dist/lib/substitution/translate.mjs +0 -6
  595. package/dist/lib/substitution/translate.mjs.map +1 -1
  596. package/dist/lib/substitution/types.mjs +0 -6
  597. package/dist/lib/substitution/vectors.mjs +0 -6
  598. package/dist/lib/substitution/vectors.mjs.map +1 -1
  599. package/dist/lib/testing/agent-tester.mjs +0 -6
  600. package/dist/lib/testing/agent-tester.mjs.map +1 -1
  601. package/dist/lib/testing/client.mjs +0 -6
  602. package/dist/lib/testing/client.mjs.map +1 -1
  603. package/dist/lib/testing/compliance/briefs.mjs +0 -6
  604. package/dist/lib/testing/compliance/briefs.mjs.map +1 -1
  605. package/dist/lib/testing/compliance/comply.mjs +0 -6
  606. package/dist/lib/testing/compliance/comply.mjs.map +1 -1
  607. package/dist/lib/testing/compliance/index.mjs +0 -6
  608. package/dist/lib/testing/compliance/index.mjs.map +1 -1
  609. package/dist/lib/testing/compliance/spec-conformance.mjs +0 -6
  610. package/dist/lib/testing/compliance/spec-conformance.mjs.map +1 -1
  611. package/dist/lib/testing/compliance/storyboard-tracks.mjs +0 -6
  612. package/dist/lib/testing/compliance/storyboard-tracks.mjs.map +1 -1
  613. package/dist/lib/testing/compliance/summary.mjs +0 -6
  614. package/dist/lib/testing/compliance/summary.mjs.map +1 -1
  615. package/dist/lib/testing/compliance/types.mjs +0 -6
  616. package/dist/lib/testing/comply-controller.mjs +0 -6
  617. package/dist/lib/testing/comply-controller.mjs.map +1 -1
  618. package/dist/lib/testing/controller-assertions.mjs +0 -6
  619. package/dist/lib/testing/controller-assertions.mjs.map +1 -1
  620. package/dist/lib/testing/formatter.mjs +0 -6
  621. package/dist/lib/testing/formatter.mjs.map +1 -1
  622. package/dist/lib/testing/index.mjs +0 -6
  623. package/dist/lib/testing/index.mjs.map +1 -1
  624. package/dist/lib/testing/local-agent-runner.mjs +0 -6
  625. package/dist/lib/testing/local-agent-runner.mjs.map +1 -1
  626. package/dist/lib/testing/orchestrator.mjs +0 -6
  627. package/dist/lib/testing/orchestrator.mjs.map +1 -1
  628. package/dist/lib/testing/personas/index.mjs +0 -6
  629. package/dist/lib/testing/personas/index.mjs.map +1 -1
  630. package/dist/lib/testing/scenarios/brand-rights.mjs +0 -6
  631. package/dist/lib/testing/scenarios/brand-rights.mjs.map +1 -1
  632. package/dist/lib/testing/scenarios/capabilities.mjs +0 -6
  633. package/dist/lib/testing/scenarios/capabilities.mjs.map +1 -1
  634. package/dist/lib/testing/scenarios/creative.mjs +0 -6
  635. package/dist/lib/testing/scenarios/creative.mjs.map +1 -1
  636. package/dist/lib/testing/scenarios/deterministic.mjs +0 -6
  637. package/dist/lib/testing/scenarios/deterministic.mjs.map +1 -1
  638. package/dist/lib/testing/scenarios/discovery.mjs +0 -6
  639. package/dist/lib/testing/scenarios/discovery.mjs.map +1 -1
  640. package/dist/lib/testing/scenarios/edge-cases.mjs +0 -6
  641. package/dist/lib/testing/scenarios/edge-cases.mjs.map +1 -1
  642. package/dist/lib/testing/scenarios/error-compliance.mjs +0 -6
  643. package/dist/lib/testing/scenarios/error-compliance.mjs.map +1 -1
  644. package/dist/lib/testing/scenarios/governance.mjs +0 -6
  645. package/dist/lib/testing/scenarios/governance.mjs.map +1 -1
  646. package/dist/lib/testing/scenarios/health.mjs +0 -6
  647. package/dist/lib/testing/scenarios/health.mjs.map +1 -1
  648. package/dist/lib/testing/scenarios/index.mjs +0 -6
  649. package/dist/lib/testing/scenarios/index.mjs.map +1 -1
  650. package/dist/lib/testing/scenarios/media-buy.mjs +0 -6
  651. package/dist/lib/testing/scenarios/media-buy.mjs.map +1 -1
  652. package/dist/lib/testing/scenarios/schema-compliance.mjs +0 -6
  653. package/dist/lib/testing/scenarios/schema-compliance.mjs.map +1 -1
  654. package/dist/lib/testing/scenarios/signals.mjs +0 -6
  655. package/dist/lib/testing/scenarios/signals.mjs.map +1 -1
  656. package/dist/lib/testing/scenarios/sponsored-intelligence.mjs +0 -6
  657. package/dist/lib/testing/scenarios/sponsored-intelligence.mjs.map +1 -1
  658. package/dist/lib/testing/scenarios/trusted-match.mjs +0 -6
  659. package/dist/lib/testing/scenarios/trusted-match.mjs.map +1 -1
  660. package/dist/lib/testing/seed-merge.mjs +0 -6
  661. package/dist/lib/testing/seed-merge.mjs.map +1 -1
  662. package/dist/lib/testing/storyboard/agent-routing.mjs +0 -6
  663. package/dist/lib/testing/storyboard/agent-routing.mjs.map +1 -1
  664. package/dist/lib/testing/storyboard/assertions.mjs +0 -6
  665. package/dist/lib/testing/storyboard/assertions.mjs.map +1 -1
  666. package/dist/lib/testing/storyboard/canonical-format-satisfaction.mjs +0 -6
  667. package/dist/lib/testing/storyboard/canonical-format-satisfaction.mjs.map +1 -1
  668. package/dist/lib/testing/storyboard/compliance.mjs +5 -6
  669. package/dist/lib/testing/storyboard/compliance.mjs.map +1 -1
  670. package/dist/lib/testing/storyboard/context.mjs +0 -6
  671. package/dist/lib/testing/storyboard/context.mjs.map +1 -1
  672. package/dist/lib/testing/storyboard/default-invariants.mjs +0 -6
  673. package/dist/lib/testing/storyboard/default-invariants.mjs.map +1 -1
  674. package/dist/lib/testing/storyboard/index.mjs +0 -6
  675. package/dist/lib/testing/storyboard/index.mjs.map +1 -1
  676. package/dist/lib/testing/storyboard/junit.mjs +0 -6
  677. package/dist/lib/testing/storyboard/junit.mjs.map +1 -1
  678. package/dist/lib/testing/storyboard/loader.mjs +0 -6
  679. package/dist/lib/testing/storyboard/loader.mjs.map +1 -1
  680. package/dist/lib/testing/storyboard/parallel-dispatch.mjs +0 -6
  681. package/dist/lib/testing/storyboard/parallel-dispatch.mjs.map +1 -1
  682. package/dist/lib/testing/storyboard/path.mjs +0 -6
  683. package/dist/lib/testing/storyboard/path.mjs.map +1 -1
  684. package/dist/lib/testing/storyboard/probes.mjs +0 -6
  685. package/dist/lib/testing/storyboard/probes.mjs.map +1 -1
  686. package/dist/lib/testing/storyboard/rate-limit-trip.mjs +0 -6
  687. package/dist/lib/testing/storyboard/rate-limit-trip.mjs.map +1 -1
  688. package/dist/lib/testing/storyboard/rejection-hints.mjs +0 -6
  689. package/dist/lib/testing/storyboard/rejection-hints.mjs.map +1 -1
  690. package/dist/lib/testing/storyboard/request-builder.mjs +0 -6
  691. package/dist/lib/testing/storyboard/request-builder.mjs.map +1 -1
  692. package/dist/lib/testing/storyboard/request-signing/builder.mjs +0 -6
  693. package/dist/lib/testing/storyboard/request-signing/builder.mjs.map +1 -1
  694. package/dist/lib/testing/storyboard/request-signing/grader.mjs +0 -6
  695. package/dist/lib/testing/storyboard/request-signing/grader.mjs.map +1 -1
  696. package/dist/lib/testing/storyboard/request-signing/index.mjs +0 -6
  697. package/dist/lib/testing/storyboard/request-signing/index.mjs.map +1 -1
  698. package/dist/lib/testing/storyboard/request-signing/probe-dispatch.mjs +0 -6
  699. package/dist/lib/testing/storyboard/request-signing/probe-dispatch.mjs.map +1 -1
  700. package/dist/lib/testing/storyboard/request-signing/probe.mjs +0 -6
  701. package/dist/lib/testing/storyboard/request-signing/probe.mjs.map +1 -1
  702. package/dist/lib/testing/storyboard/request-signing/synthesize.mjs +0 -6
  703. package/dist/lib/testing/storyboard/request-signing/synthesize.mjs.map +1 -1
  704. package/dist/lib/testing/storyboard/request-signing/test-kit.mjs +0 -6
  705. package/dist/lib/testing/storyboard/request-signing/test-kit.mjs.map +1 -1
  706. package/dist/lib/testing/storyboard/request-signing/types.mjs +0 -6
  707. package/dist/lib/testing/storyboard/request-signing/types.mjs.map +1 -1
  708. package/dist/lib/testing/storyboard/request-signing/vector-loader.mjs +0 -6
  709. package/dist/lib/testing/storyboard/request-signing/vector-loader.mjs.map +1 -1
  710. package/dist/lib/testing/storyboard/runner.mjs +0 -6
  711. package/dist/lib/testing/storyboard/runner.mjs.map +1 -1
  712. package/dist/lib/testing/storyboard/sandbox-entities.mjs +0 -6
  713. package/dist/lib/testing/storyboard/sandbox-entities.mjs.map +1 -1
  714. package/dist/lib/testing/storyboard/seeding.mjs +0 -6
  715. package/dist/lib/testing/storyboard/seeding.mjs.map +1 -1
  716. package/dist/lib/testing/storyboard/shape-drift-hints.mjs +0 -6
  717. package/dist/lib/testing/storyboard/shape-drift-hints.mjs.map +1 -1
  718. package/dist/lib/testing/storyboard/signer-grader/grader.mjs +0 -6
  719. package/dist/lib/testing/storyboard/signer-grader/grader.mjs.map +1 -1
  720. package/dist/lib/testing/storyboard/signer-grader/index.mjs +0 -6
  721. package/dist/lib/testing/storyboard/signer-grader/index.mjs.map +1 -1
  722. package/dist/lib/testing/storyboard/signer-grader/types.mjs +0 -6
  723. package/dist/lib/testing/storyboard/strict-validation-hints.mjs +0 -6
  724. package/dist/lib/testing/storyboard/strict-validation-hints.mjs.map +1 -1
  725. package/dist/lib/testing/storyboard/task-map.mjs +0 -6
  726. package/dist/lib/testing/storyboard/task-map.mjs.map +1 -1
  727. package/dist/lib/testing/storyboard/test-kit.mjs +0 -6
  728. package/dist/lib/testing/storyboard/test-kit.mjs.map +1 -1
  729. package/dist/lib/testing/storyboard/types.mjs +0 -6
  730. package/dist/lib/testing/storyboard/types.mjs.map +1 -1
  731. package/dist/lib/testing/storyboard/validations.mjs +0 -6
  732. package/dist/lib/testing/storyboard/validations.mjs.map +1 -1
  733. package/dist/lib/testing/storyboard/webhook-assertions.mjs +0 -6
  734. package/dist/lib/testing/storyboard/webhook-assertions.mjs.map +1 -1
  735. package/dist/lib/testing/storyboard/webhook-receiver.mjs +0 -6
  736. package/dist/lib/testing/storyboard/webhook-receiver.mjs.map +1 -1
  737. package/dist/lib/testing/stubs/governance-agent-stub.mjs +0 -6
  738. package/dist/lib/testing/stubs/governance-agent-stub.mjs.map +1 -1
  739. package/dist/lib/testing/stubs/index.mjs +0 -6
  740. package/dist/lib/testing/stubs/index.mjs.map +1 -1
  741. package/dist/lib/testing/test-controller.mjs +0 -6
  742. package/dist/lib/testing/test-controller.mjs.map +1 -1
  743. package/dist/lib/testing/test-helpers.mjs +0 -6
  744. package/dist/lib/testing/test-helpers.mjs.map +1 -1
  745. package/dist/lib/testing/types.mjs +0 -6
  746. package/dist/lib/types/adcp.mjs +0 -6
  747. package/dist/lib/types/adcp.mjs.map +1 -1
  748. package/dist/lib/types/asset-instances.mjs +0 -6
  749. package/dist/lib/types/compat.mjs +0 -6
  750. package/dist/lib/types/compat.mjs.map +1 -1
  751. package/dist/lib/types/core.generated.mjs +0 -6
  752. package/dist/lib/types/enums.generated.mjs +0 -6
  753. package/dist/lib/types/enums.generated.mjs.map +1 -1
  754. package/dist/lib/types/error-codes.mjs +0 -6
  755. package/dist/lib/types/error-codes.mjs.map +1 -1
  756. package/dist/lib/types/error-details.aliases.mjs +0 -6
  757. package/dist/lib/types/error-details.aliases.mjs.map +1 -1
  758. package/dist/lib/types/format-asset-slots.mjs +0 -6
  759. package/dist/lib/types/forward-compat-error-codes.mjs +0 -6
  760. package/dist/lib/types/forward-compat-error-codes.mjs.map +1 -1
  761. package/dist/lib/types/index.mjs +0 -6
  762. package/dist/lib/types/index.mjs.map +1 -1
  763. package/dist/lib/types/inline-enums.aliases.mjs +0 -6
  764. package/dist/lib/types/inline-enums.aliases.mjs.map +1 -1
  765. package/dist/lib/types/inline-enums.generated.mjs +0 -6
  766. package/dist/lib/types/inline-enums.generated.mjs.map +1 -1
  767. package/dist/lib/types/manifest.generated.mjs +0 -6
  768. package/dist/lib/types/manifest.generated.mjs.map +1 -1
  769. package/dist/lib/types/schemas.generated.mjs +0 -6
  770. package/dist/lib/types/schemas.generated.mjs.map +1 -1
  771. package/dist/lib/types/server-payload-aliases.mjs +0 -6
  772. package/dist/lib/types/server-payload.mjs +0 -6
  773. package/dist/lib/types/sync-rows.mjs +0 -6
  774. package/dist/lib/types/tools.generated.mjs +0 -6
  775. package/dist/lib/types/v2-5/index.mjs +0 -6
  776. package/dist/lib/types/v2-5/index.mjs.map +1 -1
  777. package/dist/lib/types/v2-5/tools.generated.mjs +0 -6
  778. package/dist/lib/types/v3-1-beta/index.mjs +0 -6
  779. package/dist/lib/types/v3-1-beta/index.mjs.map +1 -1
  780. package/dist/lib/types/v3-1-beta/tools.generated.mjs +0 -6
  781. package/dist/lib/types/wellknown-schemas.generated.mjs +0 -6
  782. package/dist/lib/types/wellknown-schemas.generated.mjs.map +1 -1
  783. package/dist/lib/upstream-recorder/constants.mjs +0 -6
  784. package/dist/lib/upstream-recorder/constants.mjs.map +1 -1
  785. package/dist/lib/upstream-recorder/index.mjs +0 -6
  786. package/dist/lib/upstream-recorder/index.mjs.map +1 -1
  787. package/dist/lib/upstream-recorder/recorder.mjs +0 -6
  788. package/dist/lib/upstream-recorder/recorder.mjs.map +1 -1
  789. package/dist/lib/upstream-recorder/types.mjs +0 -6
  790. package/dist/lib/upstream-recorder/types.mjs.map +1 -1
  791. package/dist/lib/utils/a2a-artifacts.mjs +0 -6
  792. package/dist/lib/utils/a2a-artifacts.mjs.map +1 -1
  793. package/dist/lib/utils/a2a-discovery.mjs +0 -6
  794. package/dist/lib/utils/a2a-discovery.mjs.map +1 -1
  795. package/dist/lib/utils/activation-key-builders.mjs +0 -6
  796. package/dist/lib/utils/activation-key-builders.mjs.map +1 -1
  797. package/dist/lib/utils/adcp-version-config.mjs +0 -6
  798. package/dist/lib/utils/adcp-version-config.mjs.map +1 -1
  799. package/dist/lib/utils/asset-builders.mjs +0 -6
  800. package/dist/lib/utils/asset-builders.mjs.map +1 -1
  801. package/dist/lib/utils/build-creative-return-builders.mjs +0 -6
  802. package/dist/lib/utils/build-creative-return-builders.mjs.map +1 -1
  803. package/dist/lib/utils/buyer-retry-policy.mjs +0 -6
  804. package/dist/lib/utils/buyer-retry-policy.mjs.map +1 -1
  805. package/dist/lib/utils/capabilities.mjs +0 -6
  806. package/dist/lib/utils/capabilities.mjs.map +1 -1
  807. package/dist/lib/utils/capability-rollups.mjs +0 -6
  808. package/dist/lib/utils/capability-rollups.mjs.map +1 -1
  809. package/dist/lib/utils/creative-adapter.mjs +0 -6
  810. package/dist/lib/utils/creative-adapter.mjs.map +1 -1
  811. package/dist/lib/utils/creative-delivery.mjs +0 -6
  812. package/dist/lib/utils/creative-delivery.mjs.map +1 -1
  813. package/dist/lib/utils/deprecation.mjs +0 -6
  814. package/dist/lib/utils/deprecation.mjs.map +1 -1
  815. package/dist/lib/utils/envelope-status-compat.mjs +0 -6
  816. package/dist/lib/utils/envelope-status-compat.mjs.map +1 -1
  817. package/dist/lib/utils/error-extraction.mjs +0 -6
  818. package/dist/lib/utils/error-extraction.mjs.map +1 -1
  819. package/dist/lib/utils/extract-result.mjs +0 -6
  820. package/dist/lib/utils/extract-result.mjs.map +1 -1
  821. package/dist/lib/utils/format-asset-slot-builders.mjs +0 -6
  822. package/dist/lib/utils/format-asset-slot-builders.mjs.map +1 -1
  823. package/dist/lib/utils/format-assets.mjs +0 -6
  824. package/dist/lib/utils/format-assets.mjs.map +1 -1
  825. package/dist/lib/utils/format-render-builders.mjs +0 -6
  826. package/dist/lib/utils/format-render-builders.mjs.map +1 -1
  827. package/dist/lib/utils/format-renders.mjs +0 -6
  828. package/dist/lib/utils/format-renders.mjs.map +1 -1
  829. package/dist/lib/utils/get-products-cache-scope.mjs +0 -6
  830. package/dist/lib/utils/get-products-cache-scope.mjs.map +1 -1
  831. package/dist/lib/utils/glob.mjs +0 -6
  832. package/dist/lib/utils/glob.mjs.map +1 -1
  833. package/dist/lib/utils/global-async-local-storage.mjs +0 -6
  834. package/dist/lib/utils/global-async-local-storage.mjs.map +1 -1
  835. package/dist/lib/utils/idempotency.mjs +0 -6
  836. package/dist/lib/utils/idempotency.mjs.map +1 -1
  837. package/dist/lib/utils/index.mjs +0 -6
  838. package/dist/lib/utils/index.mjs.map +1 -1
  839. package/dist/lib/utils/jcs.mjs +0 -6
  840. package/dist/lib/utils/jcs.mjs.map +1 -1
  841. package/dist/lib/utils/json-depth.mjs +0 -6
  842. package/dist/lib/utils/json-depth.mjs.map +1 -1
  843. package/dist/lib/utils/logger.mjs +0 -6
  844. package/dist/lib/utils/logger.mjs.map +1 -1
  845. package/dist/lib/utils/media-buy-delivery-notification-builders.mjs +0 -6
  846. package/dist/lib/utils/media-buy-delivery-notification-builders.mjs.map +1 -1
  847. package/dist/lib/utils/media-buy-status.mjs +0 -6
  848. package/dist/lib/utils/media-buy-status.mjs.map +1 -1
  849. package/dist/lib/utils/pagination.mjs +0 -6
  850. package/dist/lib/utils/pagination.mjs.map +1 -1
  851. package/dist/lib/utils/preview-creative-builders.mjs +0 -6
  852. package/dist/lib/utils/preview-creative-builders.mjs.map +1 -1
  853. package/dist/lib/utils/preview-normalizer.mjs +0 -6
  854. package/dist/lib/utils/preview-normalizer.mjs.map +1 -1
  855. package/dist/lib/utils/preview-utils.mjs +0 -6
  856. package/dist/lib/utils/preview-utils.mjs.map +1 -1
  857. package/dist/lib/utils/pricing-adapter.mjs +0 -6
  858. package/dist/lib/utils/pricing-adapter.mjs.map +1 -1
  859. package/dist/lib/utils/probe-policy.mjs +0 -6
  860. package/dist/lib/utils/probe-policy.mjs.map +1 -1
  861. package/dist/lib/utils/protocol-detection.mjs +0 -6
  862. package/dist/lib/utils/protocol-detection.mjs.map +1 -1
  863. package/dist/lib/utils/redact-secrets.mjs +0 -6
  864. package/dist/lib/utils/redact-secrets.mjs.map +1 -1
  865. package/dist/lib/utils/redis-default-prefix-warn.mjs +0 -6
  866. package/dist/lib/utils/redis-default-prefix-warn.mjs.map +1 -1
  867. package/dist/lib/utils/render-builders.mjs +0 -6
  868. package/dist/lib/utils/render-builders.mjs.map +1 -1
  869. package/dist/lib/utils/request-normalizer.mjs +0 -6
  870. package/dist/lib/utils/request-normalizer.mjs.map +1 -1
  871. package/dist/lib/utils/response-schemas.mjs +0 -6
  872. package/dist/lib/utils/response-schemas.mjs.map +1 -1
  873. package/dist/lib/utils/response-unwrapper.mjs +0 -6
  874. package/dist/lib/utils/response-unwrapper.mjs.map +1 -1
  875. package/dist/lib/utils/retry.mjs +0 -6
  876. package/dist/lib/utils/retry.mjs.map +1 -1
  877. package/dist/lib/utils/signal-discovery-helpers.mjs +0 -6
  878. package/dist/lib/utils/signal-discovery-helpers.mjs.map +1 -1
  879. package/dist/lib/utils/signal-id-builders.mjs +0 -6
  880. package/dist/lib/utils/signal-id-builders.mjs.map +1 -1
  881. package/dist/lib/utils/sync-creatives-adapter.mjs +0 -6
  882. package/dist/lib/utils/sync-creatives-adapter.mjs.map +1 -1
  883. package/dist/lib/utils/task-state.mjs +0 -6
  884. package/dist/lib/utils/task-state.mjs.map +1 -1
  885. package/dist/lib/utils/tool-request-schemas.mjs +0 -6
  886. package/dist/lib/utils/tool-request-schemas.mjs.map +1 -1
  887. package/dist/lib/utils/typeGuards.mjs +0 -6
  888. package/dist/lib/utils/typeGuards.mjs.map +1 -1
  889. package/dist/lib/utils/union-errors.mjs +0 -6
  890. package/dist/lib/utils/union-errors.mjs.map +1 -1
  891. package/dist/lib/utils/validate-user-agent.mjs +0 -6
  892. package/dist/lib/utils/validate-user-agent.mjs.map +1 -1
  893. package/dist/lib/v2/format-schema/fetch.mjs +0 -6
  894. package/dist/lib/v2/format-schema/fetch.mjs.map +1 -1
  895. package/dist/lib/v2/format-schema/index.mjs +0 -6
  896. package/dist/lib/v2/format-schema/index.mjs.map +1 -1
  897. package/dist/lib/v2/format-schema/regex-safety.mjs +0 -6
  898. package/dist/lib/v2/format-schema/regex-safety.mjs.map +1 -1
  899. package/dist/lib/v2/format-schema/resolver.mjs +7 -8
  900. package/dist/lib/v2/format-schema/resolver.mjs.map +1 -1
  901. package/dist/lib/v2/format-schema/sandbox-refs.mjs +0 -6
  902. package/dist/lib/v2/format-schema/sandbox-refs.mjs.map +1 -1
  903. package/dist/lib/v2/projection/augment-response.mjs +0 -6
  904. package/dist/lib/v2/projection/augment-response.mjs.map +1 -1
  905. package/dist/lib/v2/projection/builders.mjs +0 -6
  906. package/dist/lib/v2/projection/builders.mjs.map +1 -1
  907. package/dist/lib/v2/projection/cache-versions.mjs +0 -6
  908. package/dist/lib/v2/projection/cache-versions.mjs.map +1 -1
  909. package/dist/lib/v2/projection/canonical-properties.mjs +5 -6
  910. package/dist/lib/v2/projection/canonical-properties.mjs.map +1 -1
  911. package/dist/lib/v2/projection/catalog.mjs +5 -6
  912. package/dist/lib/v2/projection/catalog.mjs.map +1 -1
  913. package/dist/lib/v2/projection/constants.mjs +0 -6
  914. package/dist/lib/v2/projection/constants.mjs.map +1 -1
  915. package/dist/lib/v2/projection/index.mjs +0 -6
  916. package/dist/lib/v2/projection/index.mjs.map +1 -1
  917. package/dist/lib/v2/projection/registry.mjs +5 -6
  918. package/dist/lib/v2/projection/registry.mjs.map +1 -1
  919. package/dist/lib/v2/projection/types.mjs +0 -6
  920. package/dist/lib/v2/projection/v1-to-v2.mjs +0 -6
  921. package/dist/lib/v2/projection/v1-to-v2.mjs.map +1 -1
  922. package/dist/lib/v2/projection/v2-to-v1.mjs +0 -6
  923. package/dist/lib/v2/projection/v2-to-v1.mjs.map +1 -1
  924. package/dist/lib/v2/projection/write-side.mjs +0 -6
  925. package/dist/lib/v2/projection/write-side.mjs.map +1 -1
  926. package/dist/lib/v2/publisher-catalog/formats.mjs +0 -6
  927. package/dist/lib/v2/publisher-catalog/formats.mjs.map +1 -1
  928. package/dist/lib/v2/publisher-catalog/index.mjs +0 -6
  929. package/dist/lib/v2/publisher-catalog/index.mjs.map +1 -1
  930. package/dist/lib/validation/client-hooks.mjs +0 -6
  931. package/dist/lib/validation/client-hooks.mjs.map +1 -1
  932. package/dist/lib/validation/hints.mjs +0 -6
  933. package/dist/lib/validation/hints.mjs.map +1 -1
  934. package/dist/lib/validation/index.mjs +0 -6
  935. package/dist/lib/validation/index.mjs.map +1 -1
  936. package/dist/lib/validation/schema-errors.mjs +0 -6
  937. package/dist/lib/validation/schema-errors.mjs.map +1 -1
  938. package/dist/lib/validation/schema-loader.mjs +5 -6
  939. package/dist/lib/validation/schema-loader.mjs.map +1 -1
  940. package/dist/lib/validation/schema-validator.mjs +0 -6
  941. package/dist/lib/validation/schema-validator.mjs.map +1 -1
  942. package/dist/lib/validation/sync-creatives.mjs +0 -6
  943. package/dist/lib/validation/sync-creatives.mjs.map +1 -1
  944. package/dist/lib/version.d.mts +3 -3
  945. package/dist/lib/version.d.ts +3 -3
  946. package/dist/lib/version.js +3 -3
  947. package/dist/lib/version.js.map +1 -1
  948. package/dist/lib/version.mjs +3 -9
  949. package/dist/lib/version.mjs.map +1 -1
  950. package/dist/lib/webhooks/index.mjs +0 -6
  951. package/dist/lib/webhooks/index.mjs.map +1 -1
  952. package/dist/lib/wholesale-feed-sync/index.mjs +0 -6
  953. package/dist/lib/wholesale-feed-sync/index.mjs.map +1 -1
  954. package/dist/lib/wholesale-feed-sync/sync.mjs +0 -6
  955. package/dist/lib/wholesale-feed-sync/sync.mjs.map +1 -1
  956. package/dist/lib/wholesale-feed-sync/types.mjs +0 -6
  957. package/dist/lib/wholesale-feed-sync/webhook-notification.mjs +0 -6
  958. package/dist/lib/wholesale-feed-sync/webhook-notification.mjs.map +1 -1
  959. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/mcp-tasks.ts"],"sourcesContent":["/**\n * MCP Tasks protocol integration for async tool calls.\n *\n * When an MCP server declares `capabilities.tasks.requests.tools.call`, this module\n * uses the SDK's experimental tasks API instead of custom AdCP tool calls for async\n * lifecycle management. This removes the LLM from the polling path.\n *\n * Detection: check `client.getServerCapabilities()?.tasks?.requests?.tools?.call`\n * after connection. The SDK's `isToolTask()` auto-detects per-tool `taskSupport`.\n */\n\nimport type { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { DebugLogEntry } from '../types/adcp';\nimport type { TaskInfo } from '../core/ConversationTypes';\nimport { withCachedConnection } from './mcp';\nimport { createMCPAuthHeaders } from '../auth';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { withResponseSizeLimit } from './responseSizeLimit';\nimport { withTransportDiagnostics, type TransportActivityHandler } from './transportDiagnostics';\nimport { isAbortOrTimeoutError, resolveClientRequestTimeoutMs } from './abort';\nimport { tryCallModernMCPTool } from './mcp-modern';\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\ninterface MCPTaskProtocolOptions {\n transport?: { maxResponseBytes?: number };\n onTransportActivity?: TransportActivityHandler;\n transportActivityContext?: {\n agentId: string;\n operationId?: string;\n taskId?: string;\n contextId?: string;\n idempotencyKey?: string;\n };\n}\n\n/**\n * Track which MCP clients have had listTools() called.\n * The SDK's isToolTask() needs tool metadata from listTools() to determine\n * per-tool taskSupport. Without this, callToolStream silently degrades to\n * a synchronous tools/call (no task creation).\n */\nconst toolsListedClients = new WeakSet<MCPClient>();\n\n/**\n * Ensure tool metadata is cached in the SDK so isToolTask() works.\n * Called once per client connection when tasks are supported.\n */\nasync function ensureToolsListed(client: MCPClient, signal?: AbortSignal, requestTimeoutMs?: number): Promise<void> {\n if (toolsListedClients.has(client)) return;\n await client.listTools(undefined, {\n ...(signal && { signal }),\n ...(requestTimeoutMs !== undefined && { timeout: requestTimeoutMs }),\n });\n toolsListedClients.add(client);\n}\n\n/**\n * Check if an MCP server supports the Tasks protocol for tool calls.\n */\nexport function serverSupportsTasks(client: MCPClient): boolean {\n const caps = client.getServerCapabilities();\n return !!(caps as Record<string, any>)?.tasks?.requests?.tools?.call;\n}\n\n/**\n * Map MCP Tasks status to AdCP status.\n *\n * MCP Tasks uses underscores and British spelling; AdCP uses hyphens and American spelling.\n */\nexport function mapMCPTaskStatus(mcpStatus: string): string {\n switch (mcpStatus) {\n case 'working':\n return 'working';\n case 'input_required':\n return 'input-required';\n case 'completed':\n return 'completed';\n case 'failed':\n return 'failed';\n case 'cancelled':\n return 'canceled';\n default:\n return mcpStatus;\n }\n}\n\n/**\n * Map an MCP Task object to an AdCP TaskInfo.\n */\nfunction mapMCPTaskToTaskInfo(\n task: {\n taskId: string;\n status: string;\n createdAt: string;\n lastUpdatedAt: string;\n statusMessage?: string;\n pollInterval?: number;\n },\n toolName?: string\n): TaskInfo {\n // Project `statusMessage → TaskInfo.error` against the\n // POST-MAPPING AdCP status (not the raw MCP-side status). MCP\n // Tasks emits `'cancelled'` (British) and never `'rejected'` as a\n // standard status; checking against the AdCP set after mapping\n // catches all terminal failures uniformly. Sellers that extend\n // MCP with custom statuses (e.g. emit `'rejected'` via spec\n // extension) flow through unchanged via the `default` arm of\n // {@link mapMCPTaskStatus}.\n const adcpStatus = mapMCPTaskStatus(task.status);\n const isTerminalFailure = adcpStatus === 'failed' || adcpStatus === 'rejected' || adcpStatus === 'canceled';\n return {\n taskId: task.taskId,\n status: adcpStatus,\n taskType: toolName ?? 'unknown',\n createdAt: new Date(task.createdAt).getTime(),\n updatedAt: new Date(task.lastUpdatedAt).getTime(),\n error: isTerminalFailure ? task.statusMessage : undefined,\n };\n}\n\n/**\n * Build auth headers for MCP connections.\n */\nfunction buildAuthHeaders(authToken?: string, customHeaders?: Record<string, string>): Record<string, string> {\n const traceHeaders = injectTraceHeaders();\n return {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n}\n\n/**\n * Redact sensitive fields from tool args before logging.\n *\n * Redacts:\n * - `push_notification_config.authentication` — webhook signing secret\n * - `idempotency_key` — retry-pattern oracle within the seller's TTL; opt-in\n * full logging via `ADCP_LOG_IDEMPOTENCY_KEYS=1`\n */\nfunction redactArgsForLog(args: Record<string, unknown>): Record<string, unknown> {\n let redacted: Record<string, unknown> = args;\n if (redacted.push_notification_config) {\n redacted = {\n ...redacted,\n push_notification_config: {\n ...(redacted.push_notification_config as object),\n authentication: '***',\n },\n };\n }\n return redactIdempotencyKeyInArgs(redacted);\n}\n\n/**\n * Validate taskId before passing to protocol methods.\n */\nfunction validateTaskId(taskId: string): void {\n if (!taskId || typeof taskId !== 'string' || taskId.length > 256) {\n throw new Error(`Invalid taskId: expected non-empty string (max 256 chars)`);\n }\n}\n\n/**\n * Call an MCP tool with Tasks protocol support.\n *\n * If the server supports MCP Tasks and the tool has `taskSupport: 'optional' | 'required'`,\n * uses `callToolStream()` which handles task creation, polling, and result retrieval.\n *\n * If the server doesn't support tasks, falls back to regular `client.callTool()`.\n *\n * The stream is consumed with a timeout. If the task doesn't complete within the timeout,\n * returns a working-status response with the MCP task_id for follow-up polling.\n */\nexport async function callMCPToolWithTasks(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n options?: {\n workingTimeout?: number;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n }\n): Promise<unknown> {\n // Keep the public debug-log contract identical across modern and legacy\n // protocol eras. Era negotiation happens after these common entries; the\n // selected transport appends its own connection diagnostics.\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactArgsForLog(args))}`,\n timestamp: new Date().toISOString(),\n });\n\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(options?.signingContext && { signingContext: options.signingContext }),\n ...(options?.signal && { signal: options.signal }),\n ...(options?.requestTimeoutMs !== undefined && { requestTimeoutMs: options.requestTimeoutMs }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () =>\n signingContextStorage.run(options?.signingContext, async () => {\n const authHeaders = buildAuthHeaders(authToken, customHeaders);\n const workingTimeout = options?.workingTimeout ?? 120_000;\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n callToolOnClient(\n client,\n toolName,\n args,\n debugLogs,\n workingTimeout,\n options?.signal,\n options?.requestTimeoutMs\n ),\n undefined,\n { signal: options?.signal, requestTimeoutMs: options?.requestTimeoutMs }\n );\n })\n );\n}\n\n/**\n * Call a tool on a pre-connected MCP `Client` without HTTP transport or connection caching.\n *\n * This is the in-process companion to `callMCPToolWithTasks`. It skips URL validation,\n * connection setup, OAuth refresh, and the reconnect-retry path — the caller owns the\n * client lifecycle. All other semantics (tasks protocol detection, stream handling,\n * timeout surfacing) are identical to the URL-based path.\n *\n * Use via `AgentClient.fromMCPClient()`. Not intended for direct import outside the\n * protocols directory.\n */\nexport async function callMCPToolWithClient(\n mcpClient: MCPClient,\n toolName: string,\n args: Record<string, unknown>,\n debugLogs: DebugLogEntry[] = [],\n options?: { workingTimeout?: number; signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} (in-process) with args: ${JSON.stringify(redactArgsForLog(args))}`,\n timestamp: new Date().toISOString(),\n });\n return callToolOnClient(\n mcpClient,\n toolName,\n args,\n debugLogs,\n options?.workingTimeout ?? 120_000,\n options?.signal,\n options?.requestTimeoutMs\n );\n}\n\n/**\n * Inner dispatch logic shared by `callMCPToolWithTasks` (URL path) and\n * `callMCPToolWithClient` (in-process path). Both paths converge here once\n * a connected `MCPClient` is in hand.\n */\nasync function callToolOnClient(\n client: MCPClient,\n toolName: string,\n args: Record<string, unknown>,\n debugLogs: DebugLogEntry[],\n workingTimeout: number,\n signal?: AbortSignal,\n requestTimeoutMs?: number\n): Promise<unknown> {\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n if (!serverSupportsTasks(client)) {\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Server does not support tasks, using standard callTool for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n const response = (await client.callTool(\n { name: toolName, arguments: args },\n undefined,\n requestOptions\n )) as CallToolResponse;\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n }\n\n // Ensure tool metadata is cached so the SDK's isToolTask() works correctly.\n // Without this, callToolStream silently skips task creation for tools that\n // declare taskSupport: 'optional' | 'required'.\n await ensureToolsListed(client, signal, resolvedRequestTimeoutMs);\n\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Server supports tasks, using callToolStream for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n // Use callToolStream which handles the full task lifecycle\n const stream = client.experimental.tasks.callToolStream({ name: toolName, arguments: args }, undefined, {\n timeout: resolvedRequestTimeoutMs ?? workingTimeout,\n resetTimeoutOnProgress: true,\n ...(signal && { signal }),\n });\n\n let capturedTaskId: string | undefined;\n let capturedTask: { taskId: string; status: string; pollInterval?: number } | undefined;\n\n try {\n for await (const message of stream) {\n switch (message.type) {\n case 'taskCreated':\n capturedTaskId = message.task.taskId;\n capturedTask = message.task;\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Task created ${capturedTaskId} for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n break;\n\n case 'taskStatus':\n capturedTask = message.task;\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Status update for ${capturedTaskId}: ${message.task.status}`,\n timestamp: new Date().toISOString(),\n });\n break;\n\n case 'result': {\n debugLogs.push({\n type: 'success',\n message: `MCP: Tool ${toolName} response received (success)`,\n timestamp: new Date().toISOString(),\n response: message.result,\n });\n return message.result as CallToolResponse;\n }\n\n case 'error': {\n debugLogs.push({\n type: 'error',\n message: `MCP Tasks: Error for ${toolName}: ${message.error.message}`,\n timestamp: new Date().toISOString(),\n });\n // The MCP Tasks SDK error event may strip structured content.\n // If we have a taskId, fetch the full result to recover adcp_error data\n // and return it as a proper isError response for downstream unwrapping.\n if (capturedTaskId) {\n try {\n const taskResult = await client.experimental.tasks.getTaskResult(\n capturedTaskId,\n undefined,\n requestOptions\n );\n const content = taskResult?.content as Array<{ type: string; text?: string }> | undefined;\n if (content) {\n return {\n isError: true,\n content,\n structuredContent: taskResult?.structuredContent,\n } as unknown as CallToolResponse;\n }\n } catch {\n // Failed to fetch task result — fall through to throw\n }\n }\n throw message.error;\n }\n }\n }\n } catch (error) {\n if (signal?.aborted && isAbortOrTimeoutError(error)) {\n throw error;\n }\n // If we timed out but have a taskId, return a working status\n // so the caller can poll via getMCPTaskStatus/getMCPTaskResult\n if (capturedTaskId && error instanceof Error && /timeout|timed out/i.test(error.message)) {\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Timeout for ${toolName}, returning working status with taskId ${capturedTaskId}`,\n timestamp: new Date().toISOString(),\n });\n\n return {\n structuredContent: {\n status: 'working',\n task_id: capturedTaskId,\n poll_interval: capturedTask?.pollInterval,\n },\n };\n }\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n // Servers may return a synchronous tool error (e.g. VERSION_UNSUPPORTED)\n // rather than creating a task. The Tasks SDK rejects these with a Zod\n // validation error about a missing `task` field. When no task was\n // captured, fall back to standard callTool so the error response\n // reaches the caller intact.\n const msg = error instanceof Error ? error.message : String(error);\n if (!capturedTaskId && /Invalid task creation result/i.test(msg)) {\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Server returned synchronous response for ${toolName}, falling back to callTool`,\n timestamp: new Date().toISOString(),\n });\n return (await client.callTool(\n { name: toolName, arguments: args },\n undefined,\n requestOptions\n )) as CallToolResponse;\n }\n throw error;\n }\n\n // Stream ended without result — shouldn't happen with well-behaved servers\n if (capturedTaskId) {\n return {\n structuredContent: {\n status: 'working',\n task_id: capturedTaskId,\n poll_interval: capturedTask?.pollInterval,\n },\n };\n }\n\n throw new Error(`MCP Tasks: callToolStream for ${toolName} ended without result or task`);\n}\n\n/**\n * Get task status via MCP Tasks protocol method (not tool call).\n *\n * Task lifecycle methods (`tasks/get`, `tasks/result`, `tasks/list`,\n * `tasks/cancel`) are MCP protocol methods, not AdCP operations.\n * `extractAdcpOperation` returns `undefined` for them, so the signing fetch\n * passes them through unsigned regardless of whether an `AgentSigningContext`\n * is present in ALS. That matches the RFC 9421 signing profile, which only\n * covers AdCP tool calls (`tools/call` / `message/send`).\n *\n * Re-throws auth errors (401) — only catches protocol capability errors.\n */\nexport async function getMCPTaskStatus(\n agentUrl: string,\n taskId: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n toolName?: string\n): Promise<TaskInfo> {\n validateTaskId(taskId);\n const authHeaders = buildAuthHeaders(authToken);\n\n return withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, `tasks/get:${taskId}`, async client => {\n const result = await client.experimental.tasks.getTask(taskId);\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: getTask ${taskId} → ${result.status}`,\n timestamp: new Date().toISOString(),\n });\n return mapMCPTaskToTaskInfo(\n result as {\n taskId: string;\n status: string;\n createdAt: string;\n lastUpdatedAt: string;\n statusMessage?: string;\n pollInterval?: number;\n },\n toolName\n );\n });\n}\n\n/**\n * Get task result via MCP Tasks protocol method (blocks until terminal).\n */\nexport async function getMCPTaskResult(\n agentUrl: string,\n taskId: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = []\n): Promise<unknown> {\n validateTaskId(taskId);\n const authHeaders = buildAuthHeaders(authToken);\n\n return withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, `tasks/result:${taskId}`, async client => {\n const result = await client.experimental.tasks.getTaskResult(taskId);\n debugLogs.push({\n type: 'success',\n message: `MCP Tasks: getTaskResult ${taskId} received`,\n timestamp: new Date().toISOString(),\n });\n return result;\n });\n}\n\n/**\n * List tasks via MCP Tasks protocol method.\n */\nexport async function listMCPTasks(\n agentUrl: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n options: MCPTaskProtocolOptions = {}\n): Promise<TaskInfo[]> {\n const authHeaders = buildAuthHeaders(authToken);\n\n return withResponseSizeLimit(options.transport?.maxResponseBytes, () =>\n withTransportDiagnostics(\n {\n agentId: options.transportActivityContext?.agentId ?? 'unknown-agent',\n protocol: 'mcp',\n tool: 'tasks/list',\n taskType: 'tasks/list',\n ...options.transportActivityContext,\n onTransportActivity: options.onTransportActivity,\n },\n () =>\n withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, 'tasks/list', async client => {\n const result = await client.experimental.tasks.listTasks();\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: listTasks returned ${result.tasks.length} tasks`,\n timestamp: new Date().toISOString(),\n });\n return result.tasks.map((task: any) => mapMCPTaskToTaskInfo(task));\n })\n )\n );\n}\n\n/**\n * Cancel a task via MCP Tasks protocol method.\n */\nexport async function cancelMCPTask(\n agentUrl: string,\n taskId: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = []\n): Promise<void> {\n validateTaskId(taskId);\n const authHeaders = buildAuthHeaders(authToken);\n\n await withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, `tasks/cancel:${taskId}`, async client => {\n await client.experimental.tasks.cancelTask(taskId);\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: cancelTask ${taskId} succeeded`,\n timestamp: new Date().toISOString(),\n });\n });\n}\n"],"mappings":";;;;;;AAcA,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,UAAU,0BAA0B;AAC7C,SAAS,6BAAuD;AAChE,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,gCAA+D;AACxE,SAAS,uBAAuB,qCAAqC;AACrE,SAAS,4BAA4B;AA2BrC,MAAM,qBAAqB,oBAAI,QAAmB;AAMlD,eAAe,kBAAkB,QAAmB,QAAsB,kBAA0C;AAClH,MAAI,mBAAmB,IAAI,MAAM,EAAG;AACpC,QAAM,OAAO,UAAU,QAAW;AAAA,IAChC,GAAI,UAAU,EAAE,OAAO;AAAA,IACvB,GAAI,qBAAqB,UAAa,EAAE,SAAS,iBAAiB;AAAA,EACpE,CAAC;AACD,qBAAmB,IAAI,MAAM;AAC/B;AAKO,SAAS,oBAAoB,QAA4B;AAC9D,QAAM,OAAO,OAAO,sBAAsB;AAC1C,SAAO,CAAC,CAAE,MAA8B,OAAO,UAAU,OAAO;AAClE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AO;AAAA,EACT,CAAC;AACH;AAKA,eAAsB,aACpB,UACA,WACA,YAA6B,CAAC,GAC9B,UAAkC,CAAC,GACd;AACrB,QAAM,cAAc,iBAAiB,SAAS;AAE9C,SAAO;AAAA,IAAsB,QAAQ,WAAW;AAAA,IAAkB,MAChE;AAAA,MACE;AAAA,QACE,SAAS,QAAQ,0BAA0B,WAAW;AAAA,QACtD,UAAU;AAAA,QACV,MAAM;AAAA,QACN,UAAU;AAAA,QACV,GAAG,QAAQ;AAAA,QACX,qBAAqB,QAAQ;AAAA,MAC/B;AAAA,MACA,MACE,qBAAqB,UAAU,WAAW,aAAa,WAAW,cAAc,OAAM,WAAU;AAC9F,cAAM,SAAS,MAAM,OAAO,aAAa,MAAM,UAAU;AACzD,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,SAAS,iCAAiC,OAAO,MAAM,MAAM;AAAA,UAC7D,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,QACpC,CAAC;AACD,eAAO,OAAO,MAAM,IAAI,CAAC,SAAc,qBAAqB,IAAI,CAAC;AAAA,MACnE,CAAC;AAAA,IACL;AAAA,EACF;AACF;AAKA,eAAsB,cACpB,UACA,QACA,WACA,YAA6B,CAAC,GACf;AACf,iBAAe,MAAM;AACrB,QAAM,cAAc,iBAAiB,SAAS;AAE9C,QAAM,qBAAqB,UAAU,WAAW,aAAa,WAAW,gBAAgB,MAAM,IAAI,OAAM,WAAU;AAChH,UAAM,OAAO,aAAa,MAAM,WAAW,MAAM;AACjD,cAAU,KAAK;AAAA,MACb,MAAM;AAAA,MACN,SAAS,yBAAyB,MAAM;AAAA,MACxC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/mcp-tasks.ts"],"sourcesContent":["/**\n * MCP Tasks protocol integration for async tool calls.\n *\n * When an MCP server declares `capabilities.tasks.requests.tools.call`, this module\n * uses the SDK's experimental tasks API instead of custom AdCP tool calls for async\n * lifecycle management. This removes the LLM from the polling path.\n *\n * Detection: check `client.getServerCapabilities()?.tasks?.requests?.tools?.call`\n * after connection. The SDK's `isToolTask()` auto-detects per-tool `taskSupport`.\n */\n\nimport type { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { DebugLogEntry } from '../types/adcp';\nimport type { TaskInfo } from '../core/ConversationTypes';\nimport { withCachedConnection } from './mcp';\nimport { createMCPAuthHeaders } from '../auth';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { withResponseSizeLimit } from './responseSizeLimit';\nimport { withTransportDiagnostics, type TransportActivityHandler } from './transportDiagnostics';\nimport { isAbortOrTimeoutError, resolveClientRequestTimeoutMs } from './abort';\nimport { tryCallModernMCPTool } from './mcp-modern';\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\ninterface MCPTaskProtocolOptions {\n transport?: { maxResponseBytes?: number };\n onTransportActivity?: TransportActivityHandler;\n transportActivityContext?: {\n agentId: string;\n operationId?: string;\n taskId?: string;\n contextId?: string;\n idempotencyKey?: string;\n };\n}\n\n/**\n * Track which MCP clients have had listTools() called.\n * The SDK's isToolTask() needs tool metadata from listTools() to determine\n * per-tool taskSupport. Without this, callToolStream silently degrades to\n * a synchronous tools/call (no task creation).\n */\nconst toolsListedClients = new WeakSet<MCPClient>();\n\n/**\n * Ensure tool metadata is cached in the SDK so isToolTask() works.\n * Called once per client connection when tasks are supported.\n */\nasync function ensureToolsListed(client: MCPClient, signal?: AbortSignal, requestTimeoutMs?: number): Promise<void> {\n if (toolsListedClients.has(client)) return;\n await client.listTools(undefined, {\n ...(signal && { signal }),\n ...(requestTimeoutMs !== undefined && { timeout: requestTimeoutMs }),\n });\n toolsListedClients.add(client);\n}\n\n/**\n * Check if an MCP server supports the Tasks protocol for tool calls.\n */\nexport function serverSupportsTasks(client: MCPClient): boolean {\n const caps = client.getServerCapabilities();\n return !!(caps as Record<string, any>)?.tasks?.requests?.tools?.call;\n}\n\n/**\n * Map MCP Tasks status to AdCP status.\n *\n * MCP Tasks uses underscores and British spelling; AdCP uses hyphens and American spelling.\n */\nexport function mapMCPTaskStatus(mcpStatus: string): string {\n switch (mcpStatus) {\n case 'working':\n return 'working';\n case 'input_required':\n return 'input-required';\n case 'completed':\n return 'completed';\n case 'failed':\n return 'failed';\n case 'cancelled':\n return 'canceled';\n default:\n return mcpStatus;\n }\n}\n\n/**\n * Map an MCP Task object to an AdCP TaskInfo.\n */\nfunction mapMCPTaskToTaskInfo(\n task: {\n taskId: string;\n status: string;\n createdAt: string;\n lastUpdatedAt: string;\n statusMessage?: string;\n pollInterval?: number;\n },\n toolName?: string\n): TaskInfo {\n // Project `statusMessage → TaskInfo.error` against the\n // POST-MAPPING AdCP status (not the raw MCP-side status). MCP\n // Tasks emits `'cancelled'` (British) and never `'rejected'` as a\n // standard status; checking against the AdCP set after mapping\n // catches all terminal failures uniformly. Sellers that extend\n // MCP with custom statuses (e.g. emit `'rejected'` via spec\n // extension) flow through unchanged via the `default` arm of\n // {@link mapMCPTaskStatus}.\n const adcpStatus = mapMCPTaskStatus(task.status);\n const isTerminalFailure = adcpStatus === 'failed' || adcpStatus === 'rejected' || adcpStatus === 'canceled';\n return {\n taskId: task.taskId,\n status: adcpStatus,\n taskType: toolName ?? 'unknown',\n createdAt: new Date(task.createdAt).getTime(),\n updatedAt: new Date(task.lastUpdatedAt).getTime(),\n error: isTerminalFailure ? task.statusMessage : undefined,\n };\n}\n\n/**\n * Build auth headers for MCP connections.\n */\nfunction buildAuthHeaders(authToken?: string, customHeaders?: Record<string, string>): Record<string, string> {\n const traceHeaders = injectTraceHeaders();\n return {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n}\n\n/**\n * Redact sensitive fields from tool args before logging.\n *\n * Redacts:\n * - `push_notification_config.authentication` — webhook signing secret\n * - `idempotency_key` — retry-pattern oracle within the seller's TTL; opt-in\n * full logging via `ADCP_LOG_IDEMPOTENCY_KEYS=1`\n */\nfunction redactArgsForLog(args: Record<string, unknown>): Record<string, unknown> {\n let redacted: Record<string, unknown> = args;\n if (redacted.push_notification_config) {\n redacted = {\n ...redacted,\n push_notification_config: {\n ...(redacted.push_notification_config as object),\n authentication: '***',\n },\n };\n }\n return redactIdempotencyKeyInArgs(redacted);\n}\n\n/**\n * Validate taskId before passing to protocol methods.\n */\nfunction validateTaskId(taskId: string): void {\n if (!taskId || typeof taskId !== 'string' || taskId.length > 256) {\n throw new Error(`Invalid taskId: expected non-empty string (max 256 chars)`);\n }\n}\n\n/**\n * Call an MCP tool with Tasks protocol support.\n *\n * If the server supports MCP Tasks and the tool has `taskSupport: 'optional' | 'required'`,\n * uses `callToolStream()` which handles task creation, polling, and result retrieval.\n *\n * If the server doesn't support tasks, falls back to regular `client.callTool()`.\n *\n * The stream is consumed with a timeout. If the task doesn't complete within the timeout,\n * returns a working-status response with the MCP task_id for follow-up polling.\n */\nexport async function callMCPToolWithTasks(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n options?: {\n workingTimeout?: number;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n }\n): Promise<unknown> {\n // Keep the public debug-log contract identical across modern and legacy\n // protocol eras. Era negotiation happens after these common entries; the\n // selected transport appends its own connection diagnostics.\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactArgsForLog(args))}`,\n timestamp: new Date().toISOString(),\n });\n\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(options?.signingContext && { signingContext: options.signingContext }),\n ...(options?.signal && { signal: options.signal }),\n ...(options?.requestTimeoutMs !== undefined && { requestTimeoutMs: options.requestTimeoutMs }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () =>\n signingContextStorage.run(options?.signingContext, async () => {\n const authHeaders = buildAuthHeaders(authToken, customHeaders);\n const workingTimeout = options?.workingTimeout ?? 120_000;\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n callToolOnClient(\n client,\n toolName,\n args,\n debugLogs,\n workingTimeout,\n options?.signal,\n options?.requestTimeoutMs\n ),\n undefined,\n { signal: options?.signal, requestTimeoutMs: options?.requestTimeoutMs }\n );\n })\n );\n}\n\n/**\n * Call a tool on a pre-connected MCP `Client` without HTTP transport or connection caching.\n *\n * This is the in-process companion to `callMCPToolWithTasks`. It skips URL validation,\n * connection setup, OAuth refresh, and the reconnect-retry path — the caller owns the\n * client lifecycle. All other semantics (tasks protocol detection, stream handling,\n * timeout surfacing) are identical to the URL-based path.\n *\n * Use via `AgentClient.fromMCPClient()`. Not intended for direct import outside the\n * protocols directory.\n */\nexport async function callMCPToolWithClient(\n mcpClient: MCPClient,\n toolName: string,\n args: Record<string, unknown>,\n debugLogs: DebugLogEntry[] = [],\n options?: { workingTimeout?: number; signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} (in-process) with args: ${JSON.stringify(redactArgsForLog(args))}`,\n timestamp: new Date().toISOString(),\n });\n return callToolOnClient(\n mcpClient,\n toolName,\n args,\n debugLogs,\n options?.workingTimeout ?? 120_000,\n options?.signal,\n options?.requestTimeoutMs\n );\n}\n\n/**\n * Inner dispatch logic shared by `callMCPToolWithTasks` (URL path) and\n * `callMCPToolWithClient` (in-process path). Both paths converge here once\n * a connected `MCPClient` is in hand.\n */\nasync function callToolOnClient(\n client: MCPClient,\n toolName: string,\n args: Record<string, unknown>,\n debugLogs: DebugLogEntry[],\n workingTimeout: number,\n signal?: AbortSignal,\n requestTimeoutMs?: number\n): Promise<unknown> {\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n if (!serverSupportsTasks(client)) {\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Server does not support tasks, using standard callTool for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n const response = (await client.callTool(\n { name: toolName, arguments: args },\n undefined,\n requestOptions\n )) as CallToolResponse;\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n }\n\n // Ensure tool metadata is cached so the SDK's isToolTask() works correctly.\n // Without this, callToolStream silently skips task creation for tools that\n // declare taskSupport: 'optional' | 'required'.\n await ensureToolsListed(client, signal, resolvedRequestTimeoutMs);\n\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Server supports tasks, using callToolStream for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n // Use callToolStream which handles the full task lifecycle\n const stream = client.experimental.tasks.callToolStream({ name: toolName, arguments: args }, undefined, {\n timeout: resolvedRequestTimeoutMs ?? workingTimeout,\n resetTimeoutOnProgress: true,\n ...(signal && { signal }),\n });\n\n let capturedTaskId: string | undefined;\n let capturedTask: { taskId: string; status: string; pollInterval?: number } | undefined;\n\n try {\n for await (const message of stream) {\n switch (message.type) {\n case 'taskCreated':\n capturedTaskId = message.task.taskId;\n capturedTask = message.task;\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Task created ${capturedTaskId} for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n break;\n\n case 'taskStatus':\n capturedTask = message.task;\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Status update for ${capturedTaskId}: ${message.task.status}`,\n timestamp: new Date().toISOString(),\n });\n break;\n\n case 'result': {\n debugLogs.push({\n type: 'success',\n message: `MCP: Tool ${toolName} response received (success)`,\n timestamp: new Date().toISOString(),\n response: message.result,\n });\n return message.result as CallToolResponse;\n }\n\n case 'error': {\n debugLogs.push({\n type: 'error',\n message: `MCP Tasks: Error for ${toolName}: ${message.error.message}`,\n timestamp: new Date().toISOString(),\n });\n // The MCP Tasks SDK error event may strip structured content.\n // If we have a taskId, fetch the full result to recover adcp_error data\n // and return it as a proper isError response for downstream unwrapping.\n if (capturedTaskId) {\n try {\n const taskResult = await client.experimental.tasks.getTaskResult(\n capturedTaskId,\n undefined,\n requestOptions\n );\n const content = taskResult?.content as Array<{ type: string; text?: string }> | undefined;\n if (content) {\n return {\n isError: true,\n content,\n structuredContent: taskResult?.structuredContent,\n } as unknown as CallToolResponse;\n }\n } catch {\n // Failed to fetch task result — fall through to throw\n }\n }\n throw message.error;\n }\n }\n }\n } catch (error) {\n if (signal?.aborted && isAbortOrTimeoutError(error)) {\n throw error;\n }\n // If we timed out but have a taskId, return a working status\n // so the caller can poll via getMCPTaskStatus/getMCPTaskResult\n if (capturedTaskId && error instanceof Error && /timeout|timed out/i.test(error.message)) {\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Timeout for ${toolName}, returning working status with taskId ${capturedTaskId}`,\n timestamp: new Date().toISOString(),\n });\n\n return {\n structuredContent: {\n status: 'working',\n task_id: capturedTaskId,\n poll_interval: capturedTask?.pollInterval,\n },\n };\n }\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n // Servers may return a synchronous tool error (e.g. VERSION_UNSUPPORTED)\n // rather than creating a task. The Tasks SDK rejects these with a Zod\n // validation error about a missing `task` field. When no task was\n // captured, fall back to standard callTool so the error response\n // reaches the caller intact.\n const msg = error instanceof Error ? error.message : String(error);\n if (!capturedTaskId && /Invalid task creation result/i.test(msg)) {\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: Server returned synchronous response for ${toolName}, falling back to callTool`,\n timestamp: new Date().toISOString(),\n });\n return (await client.callTool(\n { name: toolName, arguments: args },\n undefined,\n requestOptions\n )) as CallToolResponse;\n }\n throw error;\n }\n\n // Stream ended without result — shouldn't happen with well-behaved servers\n if (capturedTaskId) {\n return {\n structuredContent: {\n status: 'working',\n task_id: capturedTaskId,\n poll_interval: capturedTask?.pollInterval,\n },\n };\n }\n\n throw new Error(`MCP Tasks: callToolStream for ${toolName} ended without result or task`);\n}\n\n/**\n * Get task status via MCP Tasks protocol method (not tool call).\n *\n * Task lifecycle methods (`tasks/get`, `tasks/result`, `tasks/list`,\n * `tasks/cancel`) are MCP protocol methods, not AdCP operations.\n * `extractAdcpOperation` returns `undefined` for them, so the signing fetch\n * passes them through unsigned regardless of whether an `AgentSigningContext`\n * is present in ALS. That matches the RFC 9421 signing profile, which only\n * covers AdCP tool calls (`tools/call` / `message/send`).\n *\n * Re-throws auth errors (401) — only catches protocol capability errors.\n */\nexport async function getMCPTaskStatus(\n agentUrl: string,\n taskId: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n toolName?: string\n): Promise<TaskInfo> {\n validateTaskId(taskId);\n const authHeaders = buildAuthHeaders(authToken);\n\n return withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, `tasks/get:${taskId}`, async client => {\n const result = await client.experimental.tasks.getTask(taskId);\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: getTask ${taskId} → ${result.status}`,\n timestamp: new Date().toISOString(),\n });\n return mapMCPTaskToTaskInfo(\n result as {\n taskId: string;\n status: string;\n createdAt: string;\n lastUpdatedAt: string;\n statusMessage?: string;\n pollInterval?: number;\n },\n toolName\n );\n });\n}\n\n/**\n * Get task result via MCP Tasks protocol method (blocks until terminal).\n */\nexport async function getMCPTaskResult(\n agentUrl: string,\n taskId: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = []\n): Promise<unknown> {\n validateTaskId(taskId);\n const authHeaders = buildAuthHeaders(authToken);\n\n return withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, `tasks/result:${taskId}`, async client => {\n const result = await client.experimental.tasks.getTaskResult(taskId);\n debugLogs.push({\n type: 'success',\n message: `MCP Tasks: getTaskResult ${taskId} received`,\n timestamp: new Date().toISOString(),\n });\n return result;\n });\n}\n\n/**\n * List tasks via MCP Tasks protocol method.\n */\nexport async function listMCPTasks(\n agentUrl: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n options: MCPTaskProtocolOptions = {}\n): Promise<TaskInfo[]> {\n const authHeaders = buildAuthHeaders(authToken);\n\n return withResponseSizeLimit(options.transport?.maxResponseBytes, () =>\n withTransportDiagnostics(\n {\n agentId: options.transportActivityContext?.agentId ?? 'unknown-agent',\n protocol: 'mcp',\n tool: 'tasks/list',\n taskType: 'tasks/list',\n ...options.transportActivityContext,\n onTransportActivity: options.onTransportActivity,\n },\n () =>\n withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, 'tasks/list', async client => {\n const result = await client.experimental.tasks.listTasks();\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: listTasks returned ${result.tasks.length} tasks`,\n timestamp: new Date().toISOString(),\n });\n return result.tasks.map((task: any) => mapMCPTaskToTaskInfo(task));\n })\n )\n );\n}\n\n/**\n * Cancel a task via MCP Tasks protocol method.\n */\nexport async function cancelMCPTask(\n agentUrl: string,\n taskId: string,\n authToken?: string,\n debugLogs: DebugLogEntry[] = []\n): Promise<void> {\n validateTaskId(taskId);\n const authHeaders = buildAuthHeaders(authToken);\n\n await withCachedConnection(agentUrl, authToken, authHeaders, debugLogs, `tasks/cancel:${taskId}`, async client => {\n await client.experimental.tasks.cancelTask(taskId);\n debugLogs.push({\n type: 'info',\n message: `MCP Tasks: cancelTask ${taskId} succeeded`,\n timestamp: new Date().toISOString(),\n });\n });\n}\n"],"mappings":"AAcA,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,UAAU,0BAA0B;AAC7C,SAAS,6BAAuD;AAChE,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,gCAA+D;AACxE,SAAS,uBAAuB,qCAAqC;AACrE,SAAS,4BAA4B;AA2BrC,MAAM,qBAAqB,oBAAI,QAAmB;AAMlD,eAAe,kBAAkB,QAAmB,QAAsB,kBAA0C;AAClH,MAAI,mBAAmB,IAAI,MAAM,EAAG;AACpC,QAAM,OAAO,UAAU,QAAW;AAAA,IAChC,GAAI,UAAU,EAAE,OAAO;AAAA,IACvB,GAAI,qBAAqB,UAAa,EAAE,SAAS,iBAAiB;AAAA,EACpE,CAAC;AACD,qBAAmB,IAAI,MAAM;AAC/B;AAKO,SAAS,oBAAoB,QAA4B;AAC9D,QAAM,OAAO,OAAO,sBAAsB;AAC1C,SAAO,CAAC,CAAE,MAA8B,OAAO,UAAU,OAAO;AAClE;AAOO,SAAS,iBAAiB,WAA2B;AAC1D,UAAQ,WAAW;AAAA,IACjB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAKA,SAAS,qBACP,MAQA,UACU;AASV,QAAM,aAA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AAA,QACN,UAAU;AAAA,QACV,GAAG,QAAQ;AAAA,QACX,qBAAqB,QAAQ;AAAA,MAC/B;AAAA,MACA,MACE,qBAAqB,UAAU,WAAW,aAAa,WAAW,cAAc,OAAM,WAAU;AAC9F,cAAM,SAAS,MAAM,OAAO,aAAa,MAAM,UAAU;AACzD,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,SAAS,iCAAiC,OAAO,MAAM,MAAM;AAAA,UAC7D,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,QACpC,CAAC;AACD,eAAO,OAAO,MAAM,IAAI,CAAC,SAAc,qBAAqB,IAAI,CAAC;AAAA,MACnE,CAAC;AAAA,IACL;AAAA,EACF;AACF;AAKA,eAAsB,cACpB,UACA,QACA,WACA,YAA6B,CAAC,GACf;AACf,iBAAe,MAAM;AACrB,QAAM,cAAc,iBAAiB,SAAS;AAE9C,QAAM,qBAAqB,UAAU,WAAW,aAAa,WAAW,gBAAgB,MAAM,IAAI,OAAM,WAAU;AAChH,UAAM,OAAO,aAAa,MAAM,WAAW,MAAM;AACjD,cAAU,KAAK;AAAA,MACb,MAAM;AAAA,MACN,SAAS,yBAAyB,MAAM;AAAA,MACxC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
@@ -1,9 +1,3 @@
1
- import { fileURLToPath as __adcpFileURLToPath } from 'node:url';
2
- import { dirname as __adcpDirname } from 'node:path';
3
- import { createRequire as __adcpCreateRequire } from 'node:module';
4
- const __filename = __adcpFileURLToPath(import.meta.url);
5
- const __dirname = __adcpDirname(__filename);
6
- const require = __adcpCreateRequire(import.meta.url);
7
1
  import { Client as MCPClient } from "@modelcontextprotocol/sdk/client/index.js";
8
2
  import {
9
3
  StreamableHTTPClientTransport,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/mcp.ts"],"sourcesContent":["// Official MCP client implementation using HTTP streaming transport with SSE fallback\nimport { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n type StreamableHTTPClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';\nimport { createHmac } from 'node:crypto';\nimport { createMCPAuthHeaders } from '../auth';\nimport { is401Error } from '../errors';\nimport type { DebugLogEntry } from '../types/adcp';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { buildAgentSigningFetch, signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { wrapFetchWithCapture } from './rawResponseCapture';\nimport { wrapFetchWithSizeLimit } from './responseSizeLimit';\nimport { wrapFetchWithTransportDiagnostics } from './transportDiagnostics';\nimport {\n isAbortOrTimeoutError,\n resolveClientRequestTimeoutMs,\n resolveRequestTimeoutMs,\n withAbortSignal,\n} from './abort';\nimport { closeModernMCPConnections, tryCallModernMCPTool } from './mcp-modern';\n\n// Re-export for convenience\nexport { UnauthorizedError };\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\n/**\n * Module-level connection cache keyed by agent URL + auth token hash.\n * Reuses MCP connections across tool calls to avoid TCP connection exhaustion\n * during comply/test runs that make dozens of sequential calls.\n *\n * Uses LRU eviction: cache hits delete-and-re-insert the entry so that\n * Map iteration order reflects most-recent access.\n *\n * The cache key includes only URL + auth token hash. Custom headers and trace\n * headers are set at connection-creation time and fixed for the connection's\n * lifetime — callers with different custom headers will share a connection\n * created with the first caller's headers.\n *\n * Note: This is a process-global singleton. Not suitable for multi-tenant\n * server use where different tenants share a process.\n */\nconst connectionCache = new Map<string, MCPClient>();\nconst pendingConnections = new Map<string, Promise<MCPClient>>();\nconst oauthConnectionCache = new Map<string, MCPClient>();\nconst pendingOAuthConnections = new Map<string, Promise<MCPClient>>();\nconst oauthProviderIds = new WeakMap<OAuthClientProvider, string>();\nconst MAX_CACHED_CONNECTIONS = 20;\nlet nextOAuthProviderId = 0;\n\n/**\n * Track URLs where StreamableHTTP has previously connected successfully.\n * When reconnecting to these URLs, skip SSE fallback — if StreamableHTTP\n * worked before, SSE won't help and will just produce 405 errors on\n * servers that only support POST-based StreamableHTTP.\n *\n * Capped at MAX_CACHED_CONNECTIONS to avoid unbounded growth. Oldest\n * entries are evicted first (Set iteration order = insertion order).\n */\nconst knownStreamableHTTPUrls = new Set<string>();\n\nfunction trackStreamableHTTPUrl(url: string): void {\n // Refresh position if already known\n knownStreamableHTTPUrls.delete(url);\n knownStreamableHTTPUrls.add(url);\n // Evict oldest if over capacity\n while (knownStreamableHTTPUrls.size > MAX_CACHED_CONNECTIONS) {\n const oldest = knownStreamableHTTPUrls.values().next().value;\n if (oldest) knownStreamableHTTPUrls.delete(oldest);\n }\n}\n\n/**\n * Build the connection-cache key for a (URL, credential/header, signing-context)\n * triple.\n *\n * Two credential paths feed this cache. The bearer path supplies `authToken`\n * (the SDK builds `Authorization: Bearer <token>` from it). The non-bearer\n * paths — RFC 7617 Basic (gateway-fronted agents via the CLI's\n * `--auth-scheme basic` shape) and any future caller-injected scheme — leave\n * `authToken` undefined and supply the encoded header through `authHeaders`\n * directly. Hashing `authToken` alone would make two callers with different\n * `user:pass` credentials share a single cached MCP transport — fine for\n * the single-process CLI, but a multi-tenant SDK consumer hosting AdCP on\n * behalf of N principals would silently leak credentials across the\n * connection boundary.\n *\n * Also include non-trace custom headers in the key. Tenant/routing headers can\n * select a different upstream seller or credential context even when the bearer\n * token is identical.\n */\nfunction connectionCacheKey(\n agentUrl: string,\n authToken?: string,\n signingCacheKey?: string,\n authHeaders?: Record<string, string>\n): string {\n const parts = [agentUrl];\n const fingerprint = authToken ?? extractAuthHeader(authHeaders);\n if (fingerprint) parts.push(cacheDisambiguator(fingerprint));\n const headersKey = headersCacheDisambiguator(authHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (signingCacheKey) parts.push(signingCacheKey);\n return parts.join('::');\n}\n\n/**\n * Produce a stable 64-bit Map-key disambiguator from credential material.\n *\n * This is NOT a password hash. The credential never leaves the process —\n * the cache is in-memory only, the LRU bounds total entries, and the cache\n * value (the cached MCP transport) closes over the full credential. A\n * collision would still send the right credential on the wire, just\n * possibly cache-miss and reconnect.\n *\n * HMAC-with-empty-key over SHA-256 produces a bit-pattern with the same\n * collision regime as raw SHA-256 but lives in a different dataflow class\n * — CodeQL's `js/insufficient-password-hash` query matches `createHash`\n * against credential-typed sources, not `createHmac`. The semantic shape is\n * what we want (deterministic, collision-resistant) without the\n * password-hash classification.\n */\nfunction cacheDisambiguator(value: string): string {\n return createHmac('sha256', '').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Case-insensitive lookup of the `Authorization` header value on a header\n * bag. Returns `undefined` when no such header is present.\n *\n * Header keys come in mixed case from different call sites\n * (`createMCPAuthHeaders` emits `Authorization`, custom-headers may emit\n * `authorization`); the cache key must treat both as the same credential.\n */\nfunction extractAuthHeader(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'authorization' && value) return value;\n }\n return undefined;\n}\n\nfunction headersCacheDisambiguator(headers?: Record<string, string>): string | undefined {\n const entries = Object.entries(headers ?? {})\n .filter(([key]) => {\n const lower = key.toLowerCase();\n return lower !== 'traceparent' && lower !== 'tracestate' && lower !== 'baggage';\n })\n .map(([key, value]) => [key.toLowerCase(), value] as const)\n .sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? cacheDisambiguator(JSON.stringify(entries)) : undefined;\n}\n\n/** Get a cached connection, refreshing its LRU position. */\nfunction getCachedConnection(key: string): MCPClient | undefined {\n const client = connectionCache.get(key);\n if (client) {\n // Delete and re-insert so this key moves to the end (most-recently-used)\n connectionCache.delete(key);\n connectionCache.set(key, client);\n }\n return client;\n}\n\nfunction evictLeastRecentlyUsed(): void {\n if (connectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n // Map iteration order is insertion-order; first key = least-recently-used\n const lruKey = connectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = connectionCache.get(lruKey);\n connectionCache.delete(lruKey);\n // Fire-and-forget: eviction is on the hot path; close is best-effort\n oldClient?.close().catch(() => {});\n}\n\nfunction evictLeastRecentlyUsedOAuth(): void {\n if (oauthConnectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n const lruKey = oauthConnectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = oauthConnectionCache.get(lruKey);\n oauthConnectionCache.delete(lruKey);\n oldClient?.close().catch(() => {});\n}\n\n/**\n * Close all cached OAuth MCP connections.\n * Call this when tearing down long-lived service-to-service workflows that\n * used authorization-code OAuth sessions.\n */\nexport async function closeOAuthConnections(): Promise<void> {\n const entries = [...oauthConnectionCache.entries()];\n oauthConnectionCache.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n}\n\n/**\n * Close all cached MCP connections.\n * Call this at the end of comply/test runs or before process exit.\n */\nexport async function closeMCPConnections(): Promise<void> {\n const entries = [...connectionCache.entries()];\n connectionCache.clear();\n knownStreamableHTTPUrls.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n await closeOAuthConnections();\n await closeModernMCPConnections();\n}\n\n/**\n * Get or create a cached connection for the given cache key.\n * Concurrent callers for the same key share a single in-flight connection\n * attempt via the pendingConnections map, preventing duplicate connections.\n */\nasync function getOrCreateConnection(\n cacheKey: string,\n baseUrl: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const cached = getCachedConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCPWithFallback(baseUrl, authHeaders, debugLogs, label, undefined, requestOptions)\n .then(client => {\n connectionCache.set(cacheKey, client);\n evictLeastRecentlyUsed();\n return client;\n })\n .finally(() => {\n pendingConnections.delete(cacheKey);\n });\n\n pendingConnections.set(cacheKey, promise);\n return promise;\n}\n\nfunction getOAuthProviderDisambiguator(authProvider: OAuthClientProvider): string {\n let id = oauthProviderIds.get(authProvider);\n if (!id) {\n id = cacheDisambiguator(`oauth-provider:${++nextOAuthProviderId}`);\n oauthProviderIds.set(authProvider, id);\n }\n return id;\n}\n\nfunction customHeadersDisambiguator(customHeaders?: Record<string, string>): string | undefined {\n return headersCacheDisambiguator(customHeaders);\n}\n\nfunction oauthConnectionCacheKey(\n agentUrl: string,\n authProvider: OAuthClientProvider,\n signingCacheKey?: string,\n customHeaders?: Record<string, string>\n): string {\n const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];\n if (signingCacheKey) parts.push(signingCacheKey);\n const headersKey = customHeadersDisambiguator(customHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n return parts.join('::');\n}\n\n/** Get a cached OAuth connection, refreshing its LRU position. */\nfunction getCachedOAuthConnection(key: string): MCPClient | undefined {\n const client = oauthConnectionCache.get(key);\n if (client) {\n oauthConnectionCache.delete(key);\n oauthConnectionCache.set(key, client);\n }\n return client;\n}\n\nasync function getOrCreateOAuthConnection(\n cacheKey: string,\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n }\n): Promise<MCPClient> {\n const cached = getCachedOAuthConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingOAuthConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCP(options)\n .then(({ client }) => {\n oauthConnectionCache.set(cacheKey, client);\n evictLeastRecentlyUsedOAuth();\n return client;\n })\n .finally(() => {\n pendingOAuthConnections.delete(cacheKey);\n });\n\n pendingOAuthConnections.set(cacheKey, promise);\n return promise;\n}\n\nasync function withCachedOAuthConnection<T>(\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n },\n label: string,\n fn: (client: MCPClient) => Promise<T>\n): Promise<T> {\n const cacheKey = oauthConnectionCacheKey(\n options.agentUrl,\n options.authProvider,\n options.signingContext?.cacheKey,\n options.customHeaders\n );\n if (options.signal || options.requestTimeoutMs !== undefined) {\n const { client } = await connectMCP(options);\n try {\n return await fn(client);\n } finally {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const mcpClient = await getOrCreateOAuthConnection(cacheKey, options);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n options.debugLogs.push({\n type: 'error',\n message: `MCP: ${label} OAuth call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (is401Error(error)) {\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n options.debugLogs.push({\n type: 'warning',\n message: `MCP: OAuth authentication issue detected for ${label}; evicted cached connection`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateOAuthConnection(cacheKey, {\n ...options,\n debugLogs: options.debugLogs,\n });\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Get or create a cached MCP connection, then call `fn` with it.\n * On transport errors, evicts the stale connection and retries once.\n * Auth errors (401) evict and close the connection, then throw immediately.\n *\n * @internal Used by mcp-tasks.ts for protocol-level task operations.\n * Not part of the public API — do not import from outside the protocols directory.\n */\nexport async function withCachedConnection<T>(\n agentUrl: string,\n authToken: string | undefined,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n fn: (client: MCPClient) => Promise<T>,\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<T> {\n const signingContext = signingContextStorage.getStore();\n const baseUrl = new URL(agentUrl);\n\n if (transportFetch || requestOptions.signal || requestOptions.requestTimeoutMs !== undefined) {\n const guardedClient = await connectMCPWithFallback(\n baseUrl,\n authHeaders,\n debugLogs,\n label,\n transportFetch,\n requestOptions\n );\n try {\n return await fn(guardedClient);\n } finally {\n try {\n await guardedClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const cacheKey = connectionCacheKey(agentUrl, authToken, signingContext?.cacheKey, authHeaders);\n const mcpClient = await getOrCreateConnection(cacheKey, baseUrl, authHeaders, debugLogs, label, requestOptions);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n debugLogs.push({\n type: 'error',\n message: `MCP: ${label} call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n // Auth errors won't be fixed by reconnecting — fail fast\n if (is401Error(error)) {\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'warning',\n message: `MCP: Authentication issue detected for ${label} - headers may not be reaching server`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Evict stale connection and retry once with a fresh connection\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateConnection(\n cacheKey,\n baseUrl,\n authHeaders,\n debugLogs,\n `${label} (retry)`,\n requestOptions\n );\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n // Attach original error for diagnostics\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Options for MCP tool calls with OAuth support\n */\nexport interface MCPCallOptions {\n /** Agent URL */\n agentUrl: string;\n /** Tool name to call */\n toolName: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Static auth token (legacy) */\n authToken?: string;\n /** OAuth provider for dynamic auth */\n authProvider?: OAuthClientProvider;\n /** Debug logs array */\n debugLogs?: DebugLogEntry[];\n /** Additional headers to send with every request (auth headers take precedence) */\n customHeaders?: Record<string, string>;\n /** RFC 9421 signing context — when set, the transport signs outbound ops per seller capability. */\n signingContext?: AgentSigningContext;\n /** Caller-owned cancellation signal for connect and callTool. */\n signal?: AbortSignal;\n /** Optional per-request timeout for connect and callTool. */\n requestTimeoutMs?: number;\n}\n\n/**\n * Result of an MCP connection attempt\n */\nexport interface MCPConnectionResult {\n client: MCPClient;\n transport: StreamableHTTPClientTransport;\n}\n\n/**\n * Connect an MCPClient to the given URL with automatic transport fallback.\n *\n * Strategy:\n * 1. Try StreamableHTTPClientTransport.\n * 2. On any transient connect failure (generic Error, McpError, or StreamableHTTPError),\n * retry once with a fresh StreamableHTTP connection. Auth failures (401) are excluded —\n * a retry is pointless and wastes a round-trip.\n * 3. If a 401 is returned, throw immediately — auth failure is transport-agnostic.\n * 4. For any other error after retry, fall back to SSEClientTransport with the same headers.\n *\n * The returned client is connected and ready for use. Callers are responsible for\n * calling client.close() when done.\n */\nexport async function connectMCPWithFallback(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n return withSpan(\n 'adcp.mcp.connect',\n {\n 'http.url': url.toString(),\n 'adcp.connection_label': label,\n },\n async () => {\n return connectMCPWithFallbackImpl(url, authHeaders, debugLogs, label, transportFetch, requestOptions);\n }\n );\n}\n\nasync function connectMCPWithFallbackImpl(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const signingContext = signingContextStorage.getStore();\n // Wrap order (innermost → outermost): network → size-limit → signing → capture.\n // Size-limit applies to the raw network response so signing/capture see a\n // bounded body (capture clones via `response.clone()`, which would otherwise\n // buffer a hostile reply in memory).\n const requestTimeoutMs = resolveRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const mcpRequestOptions = {\n ...(requestOptions.signal && { signal: requestOptions.signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = transportFetch ?? ((input, init) => fetch(input as any, init));\n const networkFetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) =>\n withAbortSignal<Response>([requestOptions.signal, init?.signal], requestTimeoutMs, signal =>\n rawNetworkFetch(input, { ...init, signal })\n );\n const sizeLimited = wrapFetchWithSizeLimit(networkFetch);\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const baseFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n const transportOptions: StreamableHTTPClientTransportOptions = {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n };\n let failedClient: MCPClient | undefined;\n\n try {\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n failedClient = client;\n debugLogs.push({\n type: 'info',\n message: `MCP: Attempting StreamableHTTP ${label} to ${url}`,\n timestamp: new Date().toISOString(),\n });\n await client.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n failedClient = undefined;\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n } catch (error: unknown) {\n // Close the failed client to avoid resource leaks\n if (failedClient) {\n try {\n await failedClient.close();\n } catch {\n /* ignore */\n }\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const httpStatus = error instanceof StreamableHTTPError ? ` [HTTP ${error.code}]` : '';\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP failed for ${label}${httpStatus} (${errorClass}): ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Retry StreamableHTTP once on any transient connect failure — network blips,\n // JSON parse errors on half-buffered responses, and mid-handshake proxy\n // disconnects all surface as generic Error or McpError, not StreamableHTTPError.\n // Auth failures are the only class where retry is pointless and wasteful.\n if (!is401Error(error)) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transient connect error (${errorClass}) detected, retrying StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const retryClient = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await retryClient.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP (retry) for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return retryClient;\n } catch (retryError) {\n try {\n await retryClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP retry also failed for ${label}: ${retryError instanceof Error ? retryError.message : String(retryError)}`,\n timestamp: new Date().toISOString(),\n });\n if (isAbortOrTimeoutError(retryError)) {\n throw retryError;\n }\n // Fall through to SSE fallback below\n }\n }\n\n // Auth failure — transport type won't change the outcome\n if (is401Error(error)) {\n throw error;\n }\n\n // If StreamableHTTP previously worked for this URL, don't fall back to SSE.\n // Transient failures (connection reuse, concurrency limits) should be retried\n // with StreamableHTTP, not SSE — SSE sends GET requests that return 405 on\n // servers that only support POST-based StreamableHTTP.\n if (knownStreamableHTTPUrls.has(url.toString())) {\n debugLogs.push({\n type: 'info',\n message: `MCP: StreamableHTTP previously succeeded for ${url} — skipping SSE fallback for ${label}`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n // Fall back to SSE\n debugLogs.push({\n type: 'warning',\n message: `MCP: Falling back to SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await client.connect(\n new SSEClientTransport(url, {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n }),\n mcpRequestOptions\n );\n } catch (sseError) {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n throw sseError;\n }\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n }\n}\n\nexport async function callMCPTool(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactIdempotencyKeyInArgs(args))}`,\n timestamp: new Date().toISOString(),\n });\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Custom fetch injection is an internal conformance seam whose mocks use\n // the v1 transport shape. Normal remote calls negotiate the modern era;\n // injected transports retain their exact legacy behavior.\n if (!transportFetch) {\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(signingContext && { signingContext }),\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(requestOptions?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: requestOptions.requestTimeoutMs,\n }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () => {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch, requestOptions)\n );\n }\n );\n}\n\n/**\n * Call an MCP tool and return the raw CallToolResult (with isError, content, structuredContent).\n * Raw MCP tool call — returns the CallToolResult directly, including isError responses.\n */\nexport async function callMCPToolRaw(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolRawImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch)\n );\n}\n\nasync function callMCPToolImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n // Inject trace context headers for distributed tracing\n const traceHeaders = injectTraceHeaders();\n\n // Merge: custom < trace < auth (auth always wins)\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions?.requestTimeoutMs);\n const response = await withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n client.callTool({ name: toolName, arguments: args }, undefined, {\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n }) as Promise<CallToolResponse>,\n transportFetch,\n requestOptions\n );\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n}\n\n/**\n * Raw MCP tool call — returns the CallToolResult directly.\n */\nasync function callMCPToolRawImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n const traceHeaders = injectTraceHeaders();\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client => client.callTool({ name: toolName, arguments: args }),\n transportFetch\n );\n}\n\n/**\n * Connect to an MCP server with OAuth support\n *\n * This function handles both static token auth and OAuth flows.\n * When using OAuth, if the server requires authorization:\n * 1. UnauthorizedError is thrown\n * 2. The OAuth provider's redirectToAuthorization is called\n * 3. Caller should wait for callback and call finishAuth on transport\n *\n * @param options Connection options\n * @returns MCP client and transport (for finishing OAuth if needed)\n * @throws UnauthorizedError if OAuth is required\n *\n * @example\n * ```typescript\n * // With OAuth provider\n * const provider = createCLIOAuthProvider(serverUrl);\n *\n * try {\n * const { client, transport } = await connectMCP({\n * agentUrl: serverUrl,\n * authProvider: provider\n * });\n * // Connected! Use client...\n * } catch (error) {\n * if (error instanceof UnauthorizedError) {\n * // OAuth flow started, wait for callback\n * const code = await provider.waitForCallback();\n * await transport.finishAuth(code);\n * // Retry connection...\n * }\n * }\n * ```\n *\n * @deprecated Low-level v1/SSE escape hatch. High-level AgentClient discovery,\n * tool listing, OAuth calls, and `callMCPTool*` APIs negotiate MCP 2026-07-28.\n * Keep this only for callers that require the v1 SDK client/transport pair or\n * its interactive `finishAuth()` lifecycle.\n */\nexport async function connectMCP(options: {\n agentUrl: string;\n authToken?: string;\n authProvider?: OAuthClientProvider;\n debugLogs?: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n}): Promise<MCPConnectionResult> {\n const {\n agentUrl,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs: configuredRequestTimeoutMs,\n } = options;\n const baseUrl = new URL(agentUrl);\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Connecting to ${baseUrl}`,\n timestamp: new Date().toISOString(),\n authMethod: authProvider ? 'oauth' : authToken ? 'token' : 'none',\n });\n\n const mcpClient = new MCPClient({\n name: 'AdCP-Client',\n version: '1.0.0',\n });\n\n // Build transport options\n const transportOptions: StreamableHTTPClientTransportOptions = {};\n\n // Header-only auth (basic, x-api-key, custom routing) lives entirely on\n // `customHeaders`. Attach it whenever it's present, regardless of which\n // auth branch fires — OAuth + routing headers, bearer + tenant headers,\n // and pure-header auth must all reach the wire.\n //\n // Precedence note: the MCP SDK's `_commonHeaders()` (StreamableHTTP)\n // spreads `requestInit.headers` *over* any provider-emitted `Authorization`\n // (`new Headers({ ...providerHeaders, ...requestInitHeaders })`, last-write-\n // wins). To prevent a caller-supplied `Authorization` in `customHeaders`\n // from silently overriding the OAuth provider's bearer, drop any\n // `Authorization` key from `customHeaders` when `authProvider` is set.\n // OAuth is the source of truth for the bearer in that branch; non-auth\n // routing/tenant headers still flow through.\n const filteredCustomHeaders = authProvider\n ? Object.fromEntries(Object.entries(customHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization'))\n : customHeaders;\n const authHeaders: Record<string, string> = {\n ...filteredCustomHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n transportOptions.requestInit = { headers: authHeaders, redirect: 'manual' };\n if (authProvider) {\n transportOptions.authProvider = authProvider;\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using OAuth provider for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (authToken) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using static token for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (Object.keys(authHeaders).length > 0) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using custom headers for authentication',\n timestamp: new Date().toISOString(),\n });\n }\n\n // RFC 9421 signing — wrap the transport's fetch so the signer sees the final\n // headers the SDK assembled (including any OAuth-issued Authorization) and\n // decides per outbound request whether to sign. Size-limit sits innermost so\n // the response body is bounded before signing/capture observe it.\n const requestTimeoutMs = resolveRequestTimeoutMs(configuredRequestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(configuredRequestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const sizeLimited = wrapFetchWithSizeLimit((input, init) =>\n withAbortSignal<Response>([signal, init?.signal], requestTimeoutMs, linkedSignal =>\n fetch(input as string | URL, { ...init, signal: linkedSignal })\n )\n );\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const signedFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n transportOptions.fetch = wrapFetchWithCapture(signedFetch);\n\n const transport = new StreamableHTTPClientTransport(baseUrl, transportOptions);\n\n try {\n await mcpClient.connect(transport, requestOptions);\n debugLogs.push({\n type: 'success',\n message: 'MCP: Connected successfully',\n timestamp: new Date().toISOString(),\n });\n return { client: mcpClient, transport };\n } catch (error) {\n // If it's an UnauthorizedError, the OAuth flow has started\n // Rethrow so the caller can handle the callback\n if (error instanceof UnauthorizedError) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: OAuth authorization required, flow initiated',\n timestamp: new Date().toISOString(),\n });\n // Return transport so caller can call finishAuth\n throw Object.assign(error, { transport, client: mcpClient });\n }\n\n // Non-OAuth 401 — the SDK sent credentials that the agent rejected (or\n // sent none when it needed them). The raw transport error is shaped like\n // `Error POSTing to endpoint (HTTP 401): unauthorized`, which omits the\n // crucial piece of debug data: *which auth scheme did the SDK actually\n // use*. Without that, a caller can't diff against curl. Wrap the error\n // with a scheme tag and a remediation hint, preserving the original\n // under `.cause` so existing `is401Error` / `error.status` checks\n // downstream still resolve.\n if (is401Error(error)) {\n const scheme = authProvider\n ? 'oauth'\n : authToken\n ? 'bearer'\n : Object.keys(authHeaders).length > 0\n ? 'header'\n : 'none';\n const hint =\n scheme === 'none'\n ? 'No credentials were sent. Configure auth_token, headers, or oauth_tokens on the agent config (or pass --auth on the CLI).'\n : scheme === 'header'\n ? \"Verify the Authorization header value matches the gateway (basic-auth: 'Basic ' + base64(user:pass); pair with --auth-scheme basic on the CLI).\"\n : scheme === 'bearer'\n ? \"Verify the bearer token matches the agent's expected credential.\"\n : 'OAuth provider returned tokens that the agent rejected — check the provider configuration and token scopes.';\n const detail = `MCP connect rejected with HTTP 401 from ${agentUrl}. SDK sent auth scheme: ${scheme}. ${hint}`;\n const wrapped = Object.assign(new Error(detail), {\n cause: error,\n code: 'MCP_AUTH_REJECTED',\n scheme,\n agentUrl,\n originalError: error,\n });\n throw wrapped;\n }\n\n throw error;\n }\n}\n\n/**\n * Call an MCP tool with OAuth support.\n *\n * OAuth connections are cached by agent URL and OAuth provider identity so a\n * service-to-service workflow can reuse the initialized MCP session across\n * related tool calls. Reuse the same OAuthClientProvider instance for a\n * session/source/principal; the provider owns token refresh state for the\n * cached transport.\n *\n * Signing: this path consumes `options.signingContext` via the transport —\n * `connectMCP` attaches a signing-fetch wrapper at transport-creation time —\n * rather than via `signingContextStorage`. The OAuth cache key includes the\n * signing cache key so different signing identities do not share a transport.\n * The non-OAuth fallback (`callMCPTool`) does enter ALS.\n *\n * @param options Call options\n * @returns Tool response\n * @throws UnauthorizedError if OAuth is required (with transport attached)\n */\nexport async function callMCPToolWithOAuth(options: MCPCallOptions): Promise<unknown> {\n const {\n agentUrl,\n toolName,\n args,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n } = options;\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n\n // If no OAuth provider, use the legacy function\n if (!authProvider) {\n return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, undefined, {\n signal,\n requestTimeoutMs,\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, undefined, debugLogs, customHeaders, {\n authProvider,\n signingContext,\n signal,\n requestTimeoutMs,\n handleLegacy: true,\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n return modernAttempt.response;\n }\n\n const response = await withCachedOAuthConnection(\n {\n agentUrl,\n authProvider,\n debugLogs,\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n },\n toolName,\n async client => {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n const response = await client.callTool({ name: toolName, arguments: args }, undefined, requestOptions);\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n\n return response;\n }\n );\n\n return response;\n}\n"],"mappings":";;;;;;AACA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAElC,SAAS,kBAAkB;AAC3B,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAE3B,SAAS,UAAU,0BAA0B;AAC7C,SAAS,wBAAwB,6BAAuD;AACxF,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,4BAA4B;AA4BhE,MAAM,kBAAkB,oBAAI,IAAuB;AACnD,MAAM,qBAAqB,oBAAI,IAAgC;AAC/D,MAAM,uBAAuB,oBAAI,IAAuB;AACxD,MAAM,0BAA0B,oBAAI,IAAgC;AACpE,MAAM,mBAAmB,oBAAI,QAAqC;AAClE,MAAM,yBAAyB;AAC/B,IAAI,sBAAsB;AAW1B,MAAM,0BAA0B,oBAAI,IAAY;AAEhD,SAAS,uBAAuB,KAAmB;AAEjD,0BAAwB,OAAO,GAAG;AAClC,0BAAwB,IAAI,GAAG;AAE/B,SAAO,wBAAwB,OAAO,wBAAwB;AAC5D,UAAM,SAAS,wBAAwB,OAAO,EAAE,KAAK,EAAE;AACvD,QAAI,OAAQ,yBAAwB,OAAO,MAAM;AAAA,EACnD;AACF;AAqBA,SAAS,mBACP,UACA,WACA,iBACA,aACQ;AACR,QAAM,QAAQ,CAAC,QAAQ;AACvB,QAAM,cAAc,aAAa,kBAAkB,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IACA,OAAM,WAAU;AACd,gBAAU,KAAK;AAAA,QACb,MAAM;AAAA,QACN,SAAS,qBAAqB,QAAQ;AAAA,QACtC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,YAAMA,YAAW,MAAM,OAAO,SAAS,EAAE,MAAM,UAAU,WAAW,KAAK,GAAG,QAAW,cAAc;AAErG,gBAAU,KAAK;AAAA,QACb,MAAMA,WAAU,UAAU,UAAU;AAAA,QACpC,SAAS,aAAa,QAAQ;AAAA,QAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,aAAOA;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["response"]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/mcp.ts"],"sourcesContent":["// Official MCP client implementation using HTTP streaming transport with SSE fallback\nimport { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n type StreamableHTTPClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';\nimport type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';\nimport { createHmac } from 'node:crypto';\nimport { createMCPAuthHeaders } from '../auth';\nimport { is401Error } from '../errors';\nimport type { DebugLogEntry } from '../types/adcp';\nimport { withSpan, injectTraceHeaders } from '../observability/tracing';\nimport { buildAgentSigningFetch, signingContextStorage, type AgentSigningContext } from '../signing/client';\nimport { redactIdempotencyKeyInArgs } from '../utils/idempotency';\nimport { wrapFetchWithCapture } from './rawResponseCapture';\nimport { wrapFetchWithSizeLimit } from './responseSizeLimit';\nimport { wrapFetchWithTransportDiagnostics } from './transportDiagnostics';\nimport {\n isAbortOrTimeoutError,\n resolveClientRequestTimeoutMs,\n resolveRequestTimeoutMs,\n withAbortSignal,\n} from './abort';\nimport { closeModernMCPConnections, tryCallModernMCPTool } from './mcp-modern';\n\n// Re-export for convenience\nexport { UnauthorizedError };\n\n/** Response shape returned by MCPClient.callTool(). */\ntype CallToolResponse = {\n isError?: boolean;\n content?: Array<{ type: string; text?: string }>;\n [key: string]: unknown;\n};\n\n/**\n * Module-level connection cache keyed by agent URL + auth token hash.\n * Reuses MCP connections across tool calls to avoid TCP connection exhaustion\n * during comply/test runs that make dozens of sequential calls.\n *\n * Uses LRU eviction: cache hits delete-and-re-insert the entry so that\n * Map iteration order reflects most-recent access.\n *\n * The cache key includes only URL + auth token hash. Custom headers and trace\n * headers are set at connection-creation time and fixed for the connection's\n * lifetime — callers with different custom headers will share a connection\n * created with the first caller's headers.\n *\n * Note: This is a process-global singleton. Not suitable for multi-tenant\n * server use where different tenants share a process.\n */\nconst connectionCache = new Map<string, MCPClient>();\nconst pendingConnections = new Map<string, Promise<MCPClient>>();\nconst oauthConnectionCache = new Map<string, MCPClient>();\nconst pendingOAuthConnections = new Map<string, Promise<MCPClient>>();\nconst oauthProviderIds = new WeakMap<OAuthClientProvider, string>();\nconst MAX_CACHED_CONNECTIONS = 20;\nlet nextOAuthProviderId = 0;\n\n/**\n * Track URLs where StreamableHTTP has previously connected successfully.\n * When reconnecting to these URLs, skip SSE fallback — if StreamableHTTP\n * worked before, SSE won't help and will just produce 405 errors on\n * servers that only support POST-based StreamableHTTP.\n *\n * Capped at MAX_CACHED_CONNECTIONS to avoid unbounded growth. Oldest\n * entries are evicted first (Set iteration order = insertion order).\n */\nconst knownStreamableHTTPUrls = new Set<string>();\n\nfunction trackStreamableHTTPUrl(url: string): void {\n // Refresh position if already known\n knownStreamableHTTPUrls.delete(url);\n knownStreamableHTTPUrls.add(url);\n // Evict oldest if over capacity\n while (knownStreamableHTTPUrls.size > MAX_CACHED_CONNECTIONS) {\n const oldest = knownStreamableHTTPUrls.values().next().value;\n if (oldest) knownStreamableHTTPUrls.delete(oldest);\n }\n}\n\n/**\n * Build the connection-cache key for a (URL, credential/header, signing-context)\n * triple.\n *\n * Two credential paths feed this cache. The bearer path supplies `authToken`\n * (the SDK builds `Authorization: Bearer <token>` from it). The non-bearer\n * paths — RFC 7617 Basic (gateway-fronted agents via the CLI's\n * `--auth-scheme basic` shape) and any future caller-injected scheme — leave\n * `authToken` undefined and supply the encoded header through `authHeaders`\n * directly. Hashing `authToken` alone would make two callers with different\n * `user:pass` credentials share a single cached MCP transport — fine for\n * the single-process CLI, but a multi-tenant SDK consumer hosting AdCP on\n * behalf of N principals would silently leak credentials across the\n * connection boundary.\n *\n * Also include non-trace custom headers in the key. Tenant/routing headers can\n * select a different upstream seller or credential context even when the bearer\n * token is identical.\n */\nfunction connectionCacheKey(\n agentUrl: string,\n authToken?: string,\n signingCacheKey?: string,\n authHeaders?: Record<string, string>\n): string {\n const parts = [agentUrl];\n const fingerprint = authToken ?? extractAuthHeader(authHeaders);\n if (fingerprint) parts.push(cacheDisambiguator(fingerprint));\n const headersKey = headersCacheDisambiguator(authHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n if (signingCacheKey) parts.push(signingCacheKey);\n return parts.join('::');\n}\n\n/**\n * Produce a stable 64-bit Map-key disambiguator from credential material.\n *\n * This is NOT a password hash. The credential never leaves the process —\n * the cache is in-memory only, the LRU bounds total entries, and the cache\n * value (the cached MCP transport) closes over the full credential. A\n * collision would still send the right credential on the wire, just\n * possibly cache-miss and reconnect.\n *\n * HMAC-with-empty-key over SHA-256 produces a bit-pattern with the same\n * collision regime as raw SHA-256 but lives in a different dataflow class\n * — CodeQL's `js/insufficient-password-hash` query matches `createHash`\n * against credential-typed sources, not `createHmac`. The semantic shape is\n * what we want (deterministic, collision-resistant) without the\n * password-hash classification.\n */\nfunction cacheDisambiguator(value: string): string {\n return createHmac('sha256', '').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Case-insensitive lookup of the `Authorization` header value on a header\n * bag. Returns `undefined` when no such header is present.\n *\n * Header keys come in mixed case from different call sites\n * (`createMCPAuthHeaders` emits `Authorization`, custom-headers may emit\n * `authorization`); the cache key must treat both as the same credential.\n */\nfunction extractAuthHeader(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'authorization' && value) return value;\n }\n return undefined;\n}\n\nfunction headersCacheDisambiguator(headers?: Record<string, string>): string | undefined {\n const entries = Object.entries(headers ?? {})\n .filter(([key]) => {\n const lower = key.toLowerCase();\n return lower !== 'traceparent' && lower !== 'tracestate' && lower !== 'baggage';\n })\n .map(([key, value]) => [key.toLowerCase(), value] as const)\n .sort(([a], [b]) => a.localeCompare(b));\n return entries.length > 0 ? cacheDisambiguator(JSON.stringify(entries)) : undefined;\n}\n\n/** Get a cached connection, refreshing its LRU position. */\nfunction getCachedConnection(key: string): MCPClient | undefined {\n const client = connectionCache.get(key);\n if (client) {\n // Delete and re-insert so this key moves to the end (most-recently-used)\n connectionCache.delete(key);\n connectionCache.set(key, client);\n }\n return client;\n}\n\nfunction evictLeastRecentlyUsed(): void {\n if (connectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n // Map iteration order is insertion-order; first key = least-recently-used\n const lruKey = connectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = connectionCache.get(lruKey);\n connectionCache.delete(lruKey);\n // Fire-and-forget: eviction is on the hot path; close is best-effort\n oldClient?.close().catch(() => {});\n}\n\nfunction evictLeastRecentlyUsedOAuth(): void {\n if (oauthConnectionCache.size <= MAX_CACHED_CONNECTIONS) return;\n const lruKey = oauthConnectionCache.keys().next().value;\n if (!lruKey) return;\n const oldClient = oauthConnectionCache.get(lruKey);\n oauthConnectionCache.delete(lruKey);\n oldClient?.close().catch(() => {});\n}\n\n/**\n * Close all cached OAuth MCP connections.\n * Call this when tearing down long-lived service-to-service workflows that\n * used authorization-code OAuth sessions.\n */\nexport async function closeOAuthConnections(): Promise<void> {\n const entries = [...oauthConnectionCache.entries()];\n oauthConnectionCache.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n}\n\n/**\n * Close all cached MCP connections.\n * Call this at the end of comply/test runs or before process exit.\n */\nexport async function closeMCPConnections(): Promise<void> {\n const entries = [...connectionCache.entries()];\n connectionCache.clear();\n knownStreamableHTTPUrls.clear();\n for (const [, client] of entries) {\n try {\n await client.close();\n } catch {\n /* ignore close errors */\n }\n }\n await closeOAuthConnections();\n await closeModernMCPConnections();\n}\n\n/**\n * Get or create a cached connection for the given cache key.\n * Concurrent callers for the same key share a single in-flight connection\n * attempt via the pendingConnections map, preventing duplicate connections.\n */\nasync function getOrCreateConnection(\n cacheKey: string,\n baseUrl: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const cached = getCachedConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCPWithFallback(baseUrl, authHeaders, debugLogs, label, undefined, requestOptions)\n .then(client => {\n connectionCache.set(cacheKey, client);\n evictLeastRecentlyUsed();\n return client;\n })\n .finally(() => {\n pendingConnections.delete(cacheKey);\n });\n\n pendingConnections.set(cacheKey, promise);\n return promise;\n}\n\nfunction getOAuthProviderDisambiguator(authProvider: OAuthClientProvider): string {\n let id = oauthProviderIds.get(authProvider);\n if (!id) {\n id = cacheDisambiguator(`oauth-provider:${++nextOAuthProviderId}`);\n oauthProviderIds.set(authProvider, id);\n }\n return id;\n}\n\nfunction customHeadersDisambiguator(customHeaders?: Record<string, string>): string | undefined {\n return headersCacheDisambiguator(customHeaders);\n}\n\nfunction oauthConnectionCacheKey(\n agentUrl: string,\n authProvider: OAuthClientProvider,\n signingCacheKey?: string,\n customHeaders?: Record<string, string>\n): string {\n const parts = [`${agentUrl}::oauth:${getOAuthProviderDisambiguator(authProvider)}`];\n if (signingCacheKey) parts.push(signingCacheKey);\n const headersKey = customHeadersDisambiguator(customHeaders);\n if (headersKey) parts.push(`headers:${headersKey}`);\n return parts.join('::');\n}\n\n/** Get a cached OAuth connection, refreshing its LRU position. */\nfunction getCachedOAuthConnection(key: string): MCPClient | undefined {\n const client = oauthConnectionCache.get(key);\n if (client) {\n oauthConnectionCache.delete(key);\n oauthConnectionCache.set(key, client);\n }\n return client;\n}\n\nasync function getOrCreateOAuthConnection(\n cacheKey: string,\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n }\n): Promise<MCPClient> {\n const cached = getCachedOAuthConnection(cacheKey);\n if (cached) return cached;\n\n const pending = pendingOAuthConnections.get(cacheKey);\n if (pending) return pending;\n\n const promise = connectMCP(options)\n .then(({ client }) => {\n oauthConnectionCache.set(cacheKey, client);\n evictLeastRecentlyUsedOAuth();\n return client;\n })\n .finally(() => {\n pendingOAuthConnections.delete(cacheKey);\n });\n\n pendingOAuthConnections.set(cacheKey, promise);\n return promise;\n}\n\nasync function withCachedOAuthConnection<T>(\n options: {\n agentUrl: string;\n authProvider: OAuthClientProvider;\n debugLogs: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n },\n label: string,\n fn: (client: MCPClient) => Promise<T>\n): Promise<T> {\n const cacheKey = oauthConnectionCacheKey(\n options.agentUrl,\n options.authProvider,\n options.signingContext?.cacheKey,\n options.customHeaders\n );\n if (options.signal || options.requestTimeoutMs !== undefined) {\n const { client } = await connectMCP(options);\n try {\n return await fn(client);\n } finally {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const mcpClient = await getOrCreateOAuthConnection(cacheKey, options);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n options.debugLogs.push({\n type: 'error',\n message: `MCP: ${label} OAuth call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (is401Error(error)) {\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n options.debugLogs.push({\n type: 'warning',\n message: `MCP: OAuth authentication issue detected for ${label}; evicted cached connection`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n oauthConnectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateOAuthConnection(cacheKey, {\n ...options,\n debugLogs: options.debugLogs,\n });\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Get or create a cached MCP connection, then call `fn` with it.\n * On transport errors, evicts the stale connection and retries once.\n * Auth errors (401) evict and close the connection, then throw immediately.\n *\n * @internal Used by mcp-tasks.ts for protocol-level task operations.\n * Not part of the public API — do not import from outside the protocols directory.\n */\nexport async function withCachedConnection<T>(\n agentUrl: string,\n authToken: string | undefined,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[],\n label: string,\n fn: (client: MCPClient) => Promise<T>,\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<T> {\n const signingContext = signingContextStorage.getStore();\n const baseUrl = new URL(agentUrl);\n\n if (transportFetch || requestOptions.signal || requestOptions.requestTimeoutMs !== undefined) {\n const guardedClient = await connectMCPWithFallback(\n baseUrl,\n authHeaders,\n debugLogs,\n label,\n transportFetch,\n requestOptions\n );\n try {\n return await fn(guardedClient);\n } finally {\n try {\n await guardedClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n const cacheKey = connectionCacheKey(agentUrl, authToken, signingContext?.cacheKey, authHeaders);\n const mcpClient = await getOrCreateConnection(cacheKey, baseUrl, authHeaders, debugLogs, label, requestOptions);\n\n try {\n return await fn(mcpClient);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n debugLogs.push({\n type: 'error',\n message: `MCP: ${label} call failed: ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n // Auth errors won't be fixed by reconnecting — fail fast\n if (is401Error(error)) {\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'warning',\n message: `MCP: Authentication issue detected for ${label} - headers may not be reaching server`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Evict stale connection and retry once with a fresh connection\n connectionCache.delete(cacheKey);\n try {\n await mcpClient.close();\n } catch {\n /* ignore */\n }\n\n const retryClient = await getOrCreateConnection(\n cacheKey,\n baseUrl,\n authHeaders,\n debugLogs,\n `${label} (retry)`,\n requestOptions\n );\n\n try {\n return await fn(retryClient);\n } catch (retryError) {\n // Attach original error for diagnostics\n if (retryError instanceof Error && error instanceof Error) {\n retryError.cause = error;\n }\n throw retryError;\n }\n }\n}\n\n/**\n * Options for MCP tool calls with OAuth support\n */\nexport interface MCPCallOptions {\n /** Agent URL */\n agentUrl: string;\n /** Tool name to call */\n toolName: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Static auth token (legacy) */\n authToken?: string;\n /** OAuth provider for dynamic auth */\n authProvider?: OAuthClientProvider;\n /** Debug logs array */\n debugLogs?: DebugLogEntry[];\n /** Additional headers to send with every request (auth headers take precedence) */\n customHeaders?: Record<string, string>;\n /** RFC 9421 signing context — when set, the transport signs outbound ops per seller capability. */\n signingContext?: AgentSigningContext;\n /** Caller-owned cancellation signal for connect and callTool. */\n signal?: AbortSignal;\n /** Optional per-request timeout for connect and callTool. */\n requestTimeoutMs?: number;\n}\n\n/**\n * Result of an MCP connection attempt\n */\nexport interface MCPConnectionResult {\n client: MCPClient;\n transport: StreamableHTTPClientTransport;\n}\n\n/**\n * Connect an MCPClient to the given URL with automatic transport fallback.\n *\n * Strategy:\n * 1. Try StreamableHTTPClientTransport.\n * 2. On any transient connect failure (generic Error, McpError, or StreamableHTTPError),\n * retry once with a fresh StreamableHTTP connection. Auth failures (401) are excluded —\n * a retry is pointless and wastes a round-trip.\n * 3. If a 401 is returned, throw immediately — auth failure is transport-agnostic.\n * 4. For any other error after retry, fall back to SSEClientTransport with the same headers.\n *\n * The returned client is connected and ready for use. Callers are responsible for\n * calling client.close() when done.\n */\nexport async function connectMCPWithFallback(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n return withSpan(\n 'adcp.mcp.connect',\n {\n 'http.url': url.toString(),\n 'adcp.connection_label': label,\n },\n async () => {\n return connectMCPWithFallbackImpl(url, authHeaders, debugLogs, label, transportFetch, requestOptions);\n }\n );\n}\n\nasync function connectMCPWithFallbackImpl(\n url: URL,\n authHeaders: Record<string, string>,\n debugLogs: DebugLogEntry[] = [],\n label = 'connection',\n transportFetch?: typeof fetch,\n requestOptions: { signal?: AbortSignal; requestTimeoutMs?: number } = {}\n): Promise<MCPClient> {\n const signingContext = signingContextStorage.getStore();\n // Wrap order (innermost → outermost): network → size-limit → signing → capture.\n // Size-limit applies to the raw network response so signing/capture see a\n // bounded body (capture clones via `response.clone()`, which would otherwise\n // buffer a hostile reply in memory).\n const requestTimeoutMs = resolveRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions.requestTimeoutMs);\n const mcpRequestOptions = {\n ...(requestOptions.signal && { signal: requestOptions.signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const rawNetworkFetch: typeof fetch = transportFetch ?? ((input, init) => fetch(input as any, init));\n const networkFetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) =>\n withAbortSignal<Response>([requestOptions.signal, init?.signal], requestTimeoutMs, signal =>\n rawNetworkFetch(input, { ...init, signal })\n );\n const sizeLimited = wrapFetchWithSizeLimit(networkFetch);\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const baseFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n const transportOptions: StreamableHTTPClientTransportOptions = {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n };\n let failedClient: MCPClient | undefined;\n\n try {\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n failedClient = client;\n debugLogs.push({\n type: 'info',\n message: `MCP: Attempting StreamableHTTP ${label} to ${url}`,\n timestamp: new Date().toISOString(),\n });\n await client.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n failedClient = undefined;\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n } catch (error: unknown) {\n // Close the failed client to avoid resource leaks\n if (failedClient) {\n try {\n await failedClient.close();\n } catch {\n /* ignore */\n }\n }\n\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const httpStatus = error instanceof StreamableHTTPError ? ` [HTTP ${error.code}]` : '';\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP failed for ${label}${httpStatus} (${errorClass}): ${errorMessage}`,\n timestamp: new Date().toISOString(),\n error,\n });\n\n if (isAbortOrTimeoutError(error)) {\n throw error;\n }\n\n // Retry StreamableHTTP once on any transient connect failure — network blips,\n // JSON parse errors on half-buffered responses, and mid-handshake proxy\n // disconnects all surface as generic Error or McpError, not StreamableHTTPError.\n // Auth failures are the only class where retry is pointless and wasteful.\n if (!is401Error(error)) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transient connect error (${errorClass}) detected, retrying StreamableHTTP for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const retryClient = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await retryClient.connect(new StreamableHTTPClientTransport(url, transportOptions), mcpRequestOptions);\n trackStreamableHTTPUrl(url.toString());\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via StreamableHTTP (retry) for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return retryClient;\n } catch (retryError) {\n try {\n await retryClient.close();\n } catch {\n /* ignore */\n }\n debugLogs.push({\n type: 'error',\n message: `MCP: StreamableHTTP retry also failed for ${label}: ${retryError instanceof Error ? retryError.message : String(retryError)}`,\n timestamp: new Date().toISOString(),\n });\n if (isAbortOrTimeoutError(retryError)) {\n throw retryError;\n }\n // Fall through to SSE fallback below\n }\n }\n\n // Auth failure — transport type won't change the outcome\n if (is401Error(error)) {\n throw error;\n }\n\n // If StreamableHTTP previously worked for this URL, don't fall back to SSE.\n // Transient failures (connection reuse, concurrency limits) should be retried\n // with StreamableHTTP, not SSE — SSE sends GET requests that return 405 on\n // servers that only support POST-based StreamableHTTP.\n if (knownStreamableHTTPUrls.has(url.toString())) {\n debugLogs.push({\n type: 'info',\n message: `MCP: StreamableHTTP previously succeeded for ${url} — skipping SSE fallback for ${label}`,\n timestamp: new Date().toISOString(),\n });\n throw error;\n }\n\n // Fall back to SSE\n debugLogs.push({\n type: 'warning',\n message: `MCP: Falling back to SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n const client = new MCPClient({ name: 'AdCP-Client', version: '1.0.0' });\n try {\n await client.connect(\n new SSEClientTransport(url, {\n requestInit: { headers: authHeaders, redirect: 'manual' },\n fetch: wrapFetchWithCapture(baseFetch),\n }),\n mcpRequestOptions\n );\n } catch (sseError) {\n try {\n await client.close();\n } catch {\n /* ignore */\n }\n throw sseError;\n }\n debugLogs.push({\n type: 'success',\n message: `MCP: Connected via SSE transport for ${label}`,\n timestamp: new Date().toISOString(),\n });\n return client;\n }\n}\n\nexport async function callMCPTool(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n debugLogs.push({\n type: 'info',\n message: `MCP: Auth configuration`,\n timestamp: new Date().toISOString(),\n hasAuth: !!authToken,\n headers: authToken ? { 'x-adcp-auth': '***' } : {},\n customHeaderKeys: customHeaders ? Object.keys(customHeaders) : [],\n });\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName} with args: ${JSON.stringify(redactIdempotencyKeyInArgs(args))}`,\n timestamp: new Date().toISOString(),\n });\n if (authToken) {\n debugLogs.push({\n type: 'info',\n message: `MCP: Transport configured with x-adcp-auth header for ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Custom fetch injection is an internal conformance seam whose mocks use\n // the v1 transport shape. Normal remote calls negotiate the modern era;\n // injected transports retain their exact legacy behavior.\n if (!transportFetch) {\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, {\n ...(signingContext && { signingContext }),\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(requestOptions?.requestTimeoutMs !== undefined && {\n requestTimeoutMs: requestOptions.requestTimeoutMs,\n }),\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${modernAttempt.response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: modernAttempt.response,\n });\n return modernAttempt.response;\n }\n }\n\n return withSpan(\n 'adcp.mcp.call_tool',\n {\n 'adcp.tool': toolName,\n 'http.url': agentUrl,\n },\n async () => {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch, requestOptions)\n );\n }\n );\n}\n\n/**\n * Call an MCP tool and return the raw CallToolResult (with isError, content, structuredContent).\n * Raw MCP tool call — returns the CallToolResult directly, including isError responses.\n */\nexport async function callMCPToolRaw(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n signingContext?: AgentSigningContext,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n return signingContextStorage.run(signingContext, () =>\n callMCPToolRawImpl(agentUrl, toolName, args, authToken, debugLogs, customHeaders, transportFetch)\n );\n}\n\nasync function callMCPToolImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch,\n requestOptions?: { signal?: AbortSignal; requestTimeoutMs?: number }\n): Promise<unknown> {\n // Inject trace context headers for distributed tracing\n const traceHeaders = injectTraceHeaders();\n\n // Merge: custom < trace < auth (auth always wins)\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestOptions?.requestTimeoutMs);\n const response = await withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client =>\n client.callTool({ name: toolName, arguments: args }, undefined, {\n ...(requestOptions?.signal && { signal: requestOptions.signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n }) as Promise<CallToolResponse>,\n transportFetch,\n requestOptions\n );\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received (${response?.isError ? 'error' : 'success'})`,\n timestamp: new Date().toISOString(),\n response: response,\n });\n\n return response;\n}\n\n/**\n * Raw MCP tool call — returns the CallToolResult directly.\n */\nasync function callMCPToolRawImpl(\n agentUrl: string,\n toolName: string,\n args: Record<string, unknown>,\n authToken?: string,\n debugLogs: DebugLogEntry[] = [],\n customHeaders?: Record<string, string>,\n transportFetch?: typeof fetch\n): Promise<unknown> {\n const traceHeaders = injectTraceHeaders();\n const authHeaders = {\n ...customHeaders,\n ...traceHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n\n return withCachedConnection(\n agentUrl,\n authToken,\n authHeaders,\n debugLogs,\n toolName,\n client => client.callTool({ name: toolName, arguments: args }),\n transportFetch\n );\n}\n\n/**\n * Connect to an MCP server with OAuth support\n *\n * This function handles both static token auth and OAuth flows.\n * When using OAuth, if the server requires authorization:\n * 1. UnauthorizedError is thrown\n * 2. The OAuth provider's redirectToAuthorization is called\n * 3. Caller should wait for callback and call finishAuth on transport\n *\n * @param options Connection options\n * @returns MCP client and transport (for finishing OAuth if needed)\n * @throws UnauthorizedError if OAuth is required\n *\n * @example\n * ```typescript\n * // With OAuth provider\n * const provider = createCLIOAuthProvider(serverUrl);\n *\n * try {\n * const { client, transport } = await connectMCP({\n * agentUrl: serverUrl,\n * authProvider: provider\n * });\n * // Connected! Use client...\n * } catch (error) {\n * if (error instanceof UnauthorizedError) {\n * // OAuth flow started, wait for callback\n * const code = await provider.waitForCallback();\n * await transport.finishAuth(code);\n * // Retry connection...\n * }\n * }\n * ```\n *\n * @deprecated Low-level v1/SSE escape hatch. High-level AgentClient discovery,\n * tool listing, OAuth calls, and `callMCPTool*` APIs negotiate MCP 2026-07-28.\n * Keep this only for callers that require the v1 SDK client/transport pair or\n * its interactive `finishAuth()` lifecycle.\n */\nexport async function connectMCP(options: {\n agentUrl: string;\n authToken?: string;\n authProvider?: OAuthClientProvider;\n debugLogs?: DebugLogEntry[];\n customHeaders?: Record<string, string>;\n signingContext?: AgentSigningContext;\n signal?: AbortSignal;\n requestTimeoutMs?: number;\n}): Promise<MCPConnectionResult> {\n const {\n agentUrl,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs: configuredRequestTimeoutMs,\n } = options;\n const baseUrl = new URL(agentUrl);\n\n debugLogs.push({\n type: 'info',\n message: `MCP: Connecting to ${baseUrl}`,\n timestamp: new Date().toISOString(),\n authMethod: authProvider ? 'oauth' : authToken ? 'token' : 'none',\n });\n\n const mcpClient = new MCPClient({\n name: 'AdCP-Client',\n version: '1.0.0',\n });\n\n // Build transport options\n const transportOptions: StreamableHTTPClientTransportOptions = {};\n\n // Header-only auth (basic, x-api-key, custom routing) lives entirely on\n // `customHeaders`. Attach it whenever it's present, regardless of which\n // auth branch fires — OAuth + routing headers, bearer + tenant headers,\n // and pure-header auth must all reach the wire.\n //\n // Precedence note: the MCP SDK's `_commonHeaders()` (StreamableHTTP)\n // spreads `requestInit.headers` *over* any provider-emitted `Authorization`\n // (`new Headers({ ...providerHeaders, ...requestInitHeaders })`, last-write-\n // wins). To prevent a caller-supplied `Authorization` in `customHeaders`\n // from silently overriding the OAuth provider's bearer, drop any\n // `Authorization` key from `customHeaders` when `authProvider` is set.\n // OAuth is the source of truth for the bearer in that branch; non-auth\n // routing/tenant headers still flow through.\n const filteredCustomHeaders = authProvider\n ? Object.fromEntries(Object.entries(customHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization'))\n : customHeaders;\n const authHeaders: Record<string, string> = {\n ...filteredCustomHeaders,\n ...(authToken ? createMCPAuthHeaders(authToken) : {}),\n };\n transportOptions.requestInit = { headers: authHeaders, redirect: 'manual' };\n if (authProvider) {\n transportOptions.authProvider = authProvider;\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using OAuth provider for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (authToken) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using static token for authentication',\n timestamp: new Date().toISOString(),\n });\n } else if (Object.keys(authHeaders).length > 0) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: Using custom headers for authentication',\n timestamp: new Date().toISOString(),\n });\n }\n\n // RFC 9421 signing — wrap the transport's fetch so the signer sees the final\n // headers the SDK assembled (including any OAuth-issued Authorization) and\n // decides per outbound request whether to sign. Size-limit sits innermost so\n // the response body is bounded before signing/capture observe it.\n const requestTimeoutMs = resolveRequestTimeoutMs(configuredRequestTimeoutMs);\n const clientRequestTimeoutMs = resolveClientRequestTimeoutMs(configuredRequestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(clientRequestTimeoutMs !== undefined && { timeout: clientRequestTimeoutMs }),\n };\n const sizeLimited = wrapFetchWithSizeLimit((input, init) =>\n withAbortSignal<Response>([signal, init?.signal], requestTimeoutMs, linkedSignal =>\n fetch(input as string | URL, { ...init, signal: linkedSignal })\n )\n );\n const diagnosticFetch = wrapFetchWithTransportDiagnostics(sizeLimited);\n const signedFetch: typeof fetch = signingContext\n ? (buildAgentSigningFetch({\n upstream: diagnosticFetch,\n signing: signingContext.signing,\n getCapability: signingContext.getCapability,\n }) as typeof fetch)\n : diagnosticFetch;\n transportOptions.fetch = wrapFetchWithCapture(signedFetch);\n\n const transport = new StreamableHTTPClientTransport(baseUrl, transportOptions);\n\n try {\n await mcpClient.connect(transport, requestOptions);\n debugLogs.push({\n type: 'success',\n message: 'MCP: Connected successfully',\n timestamp: new Date().toISOString(),\n });\n return { client: mcpClient, transport };\n } catch (error) {\n // If it's an UnauthorizedError, the OAuth flow has started\n // Rethrow so the caller can handle the callback\n if (error instanceof UnauthorizedError) {\n debugLogs.push({\n type: 'info',\n message: 'MCP: OAuth authorization required, flow initiated',\n timestamp: new Date().toISOString(),\n });\n // Return transport so caller can call finishAuth\n throw Object.assign(error, { transport, client: mcpClient });\n }\n\n // Non-OAuth 401 — the SDK sent credentials that the agent rejected (or\n // sent none when it needed them). The raw transport error is shaped like\n // `Error POSTing to endpoint (HTTP 401): unauthorized`, which omits the\n // crucial piece of debug data: *which auth scheme did the SDK actually\n // use*. Without that, a caller can't diff against curl. Wrap the error\n // with a scheme tag and a remediation hint, preserving the original\n // under `.cause` so existing `is401Error` / `error.status` checks\n // downstream still resolve.\n if (is401Error(error)) {\n const scheme = authProvider\n ? 'oauth'\n : authToken\n ? 'bearer'\n : Object.keys(authHeaders).length > 0\n ? 'header'\n : 'none';\n const hint =\n scheme === 'none'\n ? 'No credentials were sent. Configure auth_token, headers, or oauth_tokens on the agent config (or pass --auth on the CLI).'\n : scheme === 'header'\n ? \"Verify the Authorization header value matches the gateway (basic-auth: 'Basic ' + base64(user:pass); pair with --auth-scheme basic on the CLI).\"\n : scheme === 'bearer'\n ? \"Verify the bearer token matches the agent's expected credential.\"\n : 'OAuth provider returned tokens that the agent rejected — check the provider configuration and token scopes.';\n const detail = `MCP connect rejected with HTTP 401 from ${agentUrl}. SDK sent auth scheme: ${scheme}. ${hint}`;\n const wrapped = Object.assign(new Error(detail), {\n cause: error,\n code: 'MCP_AUTH_REJECTED',\n scheme,\n agentUrl,\n originalError: error,\n });\n throw wrapped;\n }\n\n throw error;\n }\n}\n\n/**\n * Call an MCP tool with OAuth support.\n *\n * OAuth connections are cached by agent URL and OAuth provider identity so a\n * service-to-service workflow can reuse the initialized MCP session across\n * related tool calls. Reuse the same OAuthClientProvider instance for a\n * session/source/principal; the provider owns token refresh state for the\n * cached transport.\n *\n * Signing: this path consumes `options.signingContext` via the transport —\n * `connectMCP` attaches a signing-fetch wrapper at transport-creation time —\n * rather than via `signingContextStorage`. The OAuth cache key includes the\n * signing cache key so different signing identities do not share a transport.\n * The non-OAuth fallback (`callMCPTool`) does enter ALS.\n *\n * @param options Call options\n * @returns Tool response\n * @throws UnauthorizedError if OAuth is required (with transport attached)\n */\nexport async function callMCPToolWithOAuth(options: MCPCallOptions): Promise<unknown> {\n const {\n agentUrl,\n toolName,\n args,\n authToken,\n authProvider,\n debugLogs = [],\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n } = options;\n const resolvedRequestTimeoutMs = resolveClientRequestTimeoutMs(requestTimeoutMs);\n const requestOptions = {\n ...(signal && { signal }),\n ...(resolvedRequestTimeoutMs !== undefined && { timeout: resolvedRequestTimeoutMs }),\n };\n\n // If no OAuth provider, use the legacy function\n if (!authProvider) {\n return callMCPTool(agentUrl, toolName, args, authToken, debugLogs, customHeaders, signingContext, undefined, {\n signal,\n requestTimeoutMs,\n });\n }\n\n const modernAttempt = await tryCallModernMCPTool(agentUrl, toolName, args, undefined, debugLogs, customHeaders, {\n authProvider,\n signingContext,\n signal,\n requestTimeoutMs,\n handleLegacy: true,\n });\n if (modernAttempt.handled) {\n debugLogs.push({\n type: modernAttempt.response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n return modernAttempt.response;\n }\n\n const response = await withCachedOAuthConnection(\n {\n agentUrl,\n authProvider,\n debugLogs,\n customHeaders,\n signingContext,\n signal,\n requestTimeoutMs,\n },\n toolName,\n async client => {\n debugLogs.push({\n type: 'info',\n message: `MCP: Calling tool ${toolName}`,\n timestamp: new Date().toISOString(),\n });\n\n const response = await client.callTool({ name: toolName, arguments: args }, undefined, requestOptions);\n\n debugLogs.push({\n type: response?.isError ? 'error' : 'success',\n message: `MCP: Tool ${toolName} response received`,\n timestamp: new Date().toISOString(),\n });\n\n return response;\n }\n );\n\n return response;\n}\n"],"mappings":"AACA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAElC,SAAS,kBAAkB;AAC3B,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAE3B,SAAS,UAAU,0BAA0B;AAC7C,SAAS,wBAAwB,6BAAuD;AACxF,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,4BAA4B;AA4BhE,MAAM,kBAAkB,oBAAI,IAAuB;AACnD,MAAM,qBA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AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,gBAAgB,MAAM,qBAAqB,UAAU,UAAU,MAAM,QAAW,WAAW,eAAe;AAAA,IAC9G;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB,CAAC;AACD,MAAI,cAAc,SAAS;AACzB,cAAU,KAAK;AAAA,MACb,MAAM,cAAc,UAAU,UAAU,UAAU;AAAA,MAClD,SAAS,aAAa,QAAQ;AAAA,MAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC,CAAC;AACD,WAAO,cAAc;AAAA,EACvB;AAEA,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,IACA,OAAM,WAAU;AACd,gBAAU,KAAK;AAAA,QACb,MAAM;AAAA,QACN,SAAS,qBAAqB,QAAQ;AAAA,QACtC,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,YAAMA,YAAW,MAAM,OAAO,SAAS,EAAE,MAAM,UAAU,WAAW,KAAK,GAAG,QAAW,cAAc;AAErG,gBAAU,KAAK;AAAA,QACb,MAAMA,WAAU,UAAU,UAAU;AAAA,QACpC,SAAS,aAAa,QAAQ;AAAA,QAC9B,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,CAAC;AAED,aAAOA;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["response"]}
@@ -1,9 +1,3 @@
1
- import { fileURLToPath as __adcpFileURLToPath } from 'node:url';
2
- import { dirname as __adcpDirname } from 'node:path';
3
- import { createRequire as __adcpCreateRequire } from 'node:module';
4
- const __filename = __adcpFileURLToPath(import.meta.url);
5
- const __dirname = __adcpDirname(__filename);
6
- const require = __adcpCreateRequire(import.meta.url);
7
1
  import { globalAsyncLocalStorage } from "../utils/global-async-local-storage.mjs";
8
2
  const DEFAULT_MAX_BODY_BYTES = 1048576;
9
3
  const rawResponseCaptureStorage = globalAsyncLocalStorage("rawResponseCapture");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/rawResponseCapture.ts"],"sourcesContent":["// Raw HTTP response capture for conformance probing.\n//\n// Scoped via AsyncLocalStorage so MCP + A2A protocol adapters can record\n// status, headers, body, and latency without threading options through\n// every call site. When the capture slot is absent, the fetch wrapper is a\n// pass-through — production clients pay only one ALS lookup per request.\n//\n// Consumers call `withRawResponseCapture(fn)` and receive captures for\n// every HTTP request that happened inside `fn`. The uniform-error invariant\n// uses the captures to compare two probes byte-for-byte.\n\nimport { globalAsyncLocalStorage } from '../utils/global-async-local-storage';\n\nexport interface RawHttpCapture {\n url: string;\n method: string;\n status: number;\n headers: Record<string, string>;\n body: string;\n latencyMs: number;\n timestamp: string;\n /** True when body capture hit `maxBodyBytes` and was truncated. */\n bodyTruncated: boolean;\n}\n\ninterface CaptureSlot {\n captures: RawHttpCapture[];\n maxBodyBytes: number;\n}\n\n// Counted as UTF-16 code units (string.length), not UTF-8 bytes. Close\n// enough for ASCII-dominant response payloads and fine as a safety cap\n// against accidentally retaining huge responses.\nconst DEFAULT_MAX_BODY_BYTES = 1_048_576;\n\nexport const rawResponseCaptureStorage = globalAsyncLocalStorage<CaptureSlot>('rawResponseCapture');\n\n/**\n * Run `fn` with a raw-response capture slot active. Every HTTP request made\n * through the wrapped fetch inside `fn` is recorded.\n *\n * When `fn` rejects, the rejection propagates and the partial captures\n * are attached to the thrown error as `error.captures`. Callers that\n * need to inspect partial captures on failure can read that property;\n * callers that don't can ignore it. This lets storyboard validators\n * surface \"the SDK threw before the wire shape parsed\" diagnostics\n * with the actual bytes that arrived before the throw.\n */\nexport async function withRawResponseCapture<T>(\n fn: () => Promise<T>,\n options: { maxBodyBytes?: number } = {}\n): Promise<{ result: T; captures: RawHttpCapture[] }> {\n const slot: CaptureSlot = {\n captures: [],\n maxBodyBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,\n };\n try {\n const result = await rawResponseCaptureStorage.run(slot, fn);\n return { result, captures: slot.captures };\n } catch (err) {\n if (err && typeof err === 'object') {\n try {\n Object.defineProperty(err, 'captures', {\n value: slot.captures,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n } catch {\n // Frozen / sealed errors won't accept the property — drop the\n // captures rather than crash on a defineProperty TypeError.\n }\n }\n throw err;\n }\n}\n\n/** Type guard for errors carrying partial captures from `withRawResponseCapture`. */\nexport function getCapturesFromError(err: unknown): RawHttpCapture[] | undefined {\n if (err && typeof err === 'object' && Array.isArray((err as { captures?: unknown }).captures)) {\n return (err as { captures: RawHttpCapture[] }).captures;\n }\n return undefined;\n}\n\n/**\n * Credential-bearing response header names. A misbehaving proxy that\n * echoes caller-supplied auth headers back on the response would\n * otherwise land bearer tokens in the capture — and downstream, in\n * `UniformErrorReport.probes.*.headers` which is written to disk /\n * pasted into tickets. Redact verbatim at capture time.\n */\nconst REDACTED_HEADER_NAMES: ReadonlySet<string> = new Set([\n 'authorization',\n 'proxy-authorization',\n 'cookie',\n 'set-cookie',\n 'x-adcp-auth',\n 'x-api-key',\n]);\n\nconst REDACTED_PLACEHOLDER = '[redacted]';\n\n/**\n * Wrap a fetch implementation so it records raw responses when a capture\n * slot is active. Safe to install unconditionally — pass-through when no\n * slot is set.\n */\nexport function wrapFetchWithCapture(upstream: typeof fetch): typeof fetch {\n const wrapped: typeof fetch = async (input, init) => {\n const slot = rawResponseCaptureStorage.getStore();\n if (!slot) return upstream(input, init);\n\n const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const startedAt = Date.now();\n const response = await upstream(input, init);\n const latencyMs = Date.now() - startedAt;\n\n // Clone before reading so the SDK still gets a consumable body.\n const cloneForRead = response.clone();\n const { body, bodyTruncated } = await readBodyBounded(cloneForRead, slot.maxBodyBytes);\n\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n headers[key] = REDACTED_HEADER_NAMES.has(lower) ? REDACTED_PLACEHOLDER : value;\n });\n\n slot.captures.push({\n url,\n method,\n status: response.status,\n headers,\n body: redactBearerInBody(body),\n latencyMs,\n timestamp: new Date(startedAt).toISOString(),\n bodyTruncated,\n });\n\n return response;\n };\n return wrapped;\n}\n\n/**\n * Response bodies sometimes echo request headers — e.g., a misbehaving\n * \"debug\" handler that logs the Authorization header into its error\n * payload, or a 500 HTML page that templates the request dump. Strip\n * bearer-shaped tokens so they don't persist into captured output.\n *\n * Conservative: only masks the TOKEN portion of a `Bearer <token>` span\n * (case-insensitive). Doesn't try to detect arbitrary high-entropy\n * strings — false positives on those would damage the comparator's\n * byte-equivalence check.\n */\nfunction redactBearerInBody(body: string): string {\n return body.replace(/Bearer\\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]');\n}\n\nasync function readBodyBounded(\n response: Response,\n maxBodyBytes: number\n): Promise<{ body: string; bodyTruncated: boolean }> {\n let text: string;\n try {\n text = await response.text();\n } catch {\n return { body: '', bodyTruncated: false };\n }\n if (text.length <= maxBodyBytes) return { body: text, bodyTruncated: false };\n return { body: text.slice(0, maxBodyBytes), bodyTruncated: true };\n}\n"],"mappings":";;;;;;AAWA,SAAS,+BAA+B;AAsBxC,MAAM,yBAAyB;AAExB,MAAM,4BAA4B,wBAAqC,oBAAoB;AAalG,eAAsB,uBACpB,IACA,UAAqC,CAAC,GACc;AACpD,QAAM,OAAoB;AAAA,IACxB,UAAU,CAAC;AAAA,IACX,cAAc,QAAQ,gBAAgB;AAAA,EACxC;AACA,MAAI;AACF,UAAM,SAAS,MAAM,0BAA0B,IAAI,MAAM,EAAE;AAC3D,WAAO,EAAE,QAAQ,UAAU,KAAK,SAAS;AAAA,EAC3C,SAAS,KAAK;AACZ,QAAI,OAAO,OAAO,QAAQ,UAAU;AAClC,UAAI;AACF,eAAO,eAAe,KAAK,YAAY;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mBAAmB,IAAI;AAAA,MAC7B;AAAA,MACA,WAAW,IAAI,KAAK,SAAS,EAAE,YAAY;AAAA,MAC3C;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAaA,SAAS,mBAAmB,MAAsB;AAChD,SAAO,KAAK,QAAQ,kCAAkC,mBAAmB;AAC3E;AAEA,eAAe,gBACb,UACA,cACmD;AACnD,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,SAAS,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO,EAAE,MAAM,IAAI,eAAe,MAAM;AAAA,EAC1C;AACA,MAAI,KAAK,UAAU,aAAc,QAAO,EAAE,MAAM,MAAM,eAAe,MAAM;AAC3E,SAAO,EAAE,MAAM,KAAK,MAAM,GAAG,YAAY,GAAG,eAAe,KAAK;AAClE;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/rawResponseCapture.ts"],"sourcesContent":["// Raw HTTP response capture for conformance probing.\n//\n// Scoped via AsyncLocalStorage so MCP + A2A protocol adapters can record\n// status, headers, body, and latency without threading options through\n// every call site. When the capture slot is absent, the fetch wrapper is a\n// pass-through — production clients pay only one ALS lookup per request.\n//\n// Consumers call `withRawResponseCapture(fn)` and receive captures for\n// every HTTP request that happened inside `fn`. The uniform-error invariant\n// uses the captures to compare two probes byte-for-byte.\n\nimport { globalAsyncLocalStorage } from '../utils/global-async-local-storage';\n\nexport interface RawHttpCapture {\n url: string;\n method: string;\n status: number;\n headers: Record<string, string>;\n body: string;\n latencyMs: number;\n timestamp: string;\n /** True when body capture hit `maxBodyBytes` and was truncated. */\n bodyTruncated: boolean;\n}\n\ninterface CaptureSlot {\n captures: RawHttpCapture[];\n maxBodyBytes: number;\n}\n\n// Counted as UTF-16 code units (string.length), not UTF-8 bytes. Close\n// enough for ASCII-dominant response payloads and fine as a safety cap\n// against accidentally retaining huge responses.\nconst DEFAULT_MAX_BODY_BYTES = 1_048_576;\n\nexport const rawResponseCaptureStorage = globalAsyncLocalStorage<CaptureSlot>('rawResponseCapture');\n\n/**\n * Run `fn` with a raw-response capture slot active. Every HTTP request made\n * through the wrapped fetch inside `fn` is recorded.\n *\n * When `fn` rejects, the rejection propagates and the partial captures\n * are attached to the thrown error as `error.captures`. Callers that\n * need to inspect partial captures on failure can read that property;\n * callers that don't can ignore it. This lets storyboard validators\n * surface \"the SDK threw before the wire shape parsed\" diagnostics\n * with the actual bytes that arrived before the throw.\n */\nexport async function withRawResponseCapture<T>(\n fn: () => Promise<T>,\n options: { maxBodyBytes?: number } = {}\n): Promise<{ result: T; captures: RawHttpCapture[] }> {\n const slot: CaptureSlot = {\n captures: [],\n maxBodyBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,\n };\n try {\n const result = await rawResponseCaptureStorage.run(slot, fn);\n return { result, captures: slot.captures };\n } catch (err) {\n if (err && typeof err === 'object') {\n try {\n Object.defineProperty(err, 'captures', {\n value: slot.captures,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n } catch {\n // Frozen / sealed errors won't accept the property — drop the\n // captures rather than crash on a defineProperty TypeError.\n }\n }\n throw err;\n }\n}\n\n/** Type guard for errors carrying partial captures from `withRawResponseCapture`. */\nexport function getCapturesFromError(err: unknown): RawHttpCapture[] | undefined {\n if (err && typeof err === 'object' && Array.isArray((err as { captures?: unknown }).captures)) {\n return (err as { captures: RawHttpCapture[] }).captures;\n }\n return undefined;\n}\n\n/**\n * Credential-bearing response header names. A misbehaving proxy that\n * echoes caller-supplied auth headers back on the response would\n * otherwise land bearer tokens in the capture — and downstream, in\n * `UniformErrorReport.probes.*.headers` which is written to disk /\n * pasted into tickets. Redact verbatim at capture time.\n */\nconst REDACTED_HEADER_NAMES: ReadonlySet<string> = new Set([\n 'authorization',\n 'proxy-authorization',\n 'cookie',\n 'set-cookie',\n 'x-adcp-auth',\n 'x-api-key',\n]);\n\nconst REDACTED_PLACEHOLDER = '[redacted]';\n\n/**\n * Wrap a fetch implementation so it records raw responses when a capture\n * slot is active. Safe to install unconditionally — pass-through when no\n * slot is set.\n */\nexport function wrapFetchWithCapture(upstream: typeof fetch): typeof fetch {\n const wrapped: typeof fetch = async (input, init) => {\n const slot = rawResponseCaptureStorage.getStore();\n if (!slot) return upstream(input, init);\n\n const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const startedAt = Date.now();\n const response = await upstream(input, init);\n const latencyMs = Date.now() - startedAt;\n\n // Clone before reading so the SDK still gets a consumable body.\n const cloneForRead = response.clone();\n const { body, bodyTruncated } = await readBodyBounded(cloneForRead, slot.maxBodyBytes);\n\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n headers[key] = REDACTED_HEADER_NAMES.has(lower) ? REDACTED_PLACEHOLDER : value;\n });\n\n slot.captures.push({\n url,\n method,\n status: response.status,\n headers,\n body: redactBearerInBody(body),\n latencyMs,\n timestamp: new Date(startedAt).toISOString(),\n bodyTruncated,\n });\n\n return response;\n };\n return wrapped;\n}\n\n/**\n * Response bodies sometimes echo request headers — e.g., a misbehaving\n * \"debug\" handler that logs the Authorization header into its error\n * payload, or a 500 HTML page that templates the request dump. Strip\n * bearer-shaped tokens so they don't persist into captured output.\n *\n * Conservative: only masks the TOKEN portion of a `Bearer <token>` span\n * (case-insensitive). Doesn't try to detect arbitrary high-entropy\n * strings — false positives on those would damage the comparator's\n * byte-equivalence check.\n */\nfunction redactBearerInBody(body: string): string {\n return body.replace(/Bearer\\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]');\n}\n\nasync function readBodyBounded(\n response: Response,\n maxBodyBytes: number\n): Promise<{ body: string; bodyTruncated: boolean }> {\n let text: string;\n try {\n text = await response.text();\n } catch {\n return { body: '', bodyTruncated: false };\n }\n if (text.length <= maxBodyBytes) return { body: text, bodyTruncated: false };\n return { body: text.slice(0, maxBodyBytes), bodyTruncated: true };\n}\n"],"mappings":"AAWA,SAAS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AM,YAAY,KAAK,IAAI,IAAI;AAG/B,UAAM,eAAe,SAAS,MAAM;AACpC,UAAM,EAAE,MAAM,cAAc,IAAI,MAAM,gBAAgB,cAAc,KAAK,YAAY;AAErF,UAAM,UAAkC,CAAC;AACzC,aAAS,QAAQ,QAAQ,CAAC,OAAO,QAAQ;AACvC,YAAM,QAAQ,IAAI,YAAY;AAC9B,cAAQ,GAAG,IAAI,sBAAsB,IAAI,KAAK,IAAI,uBAAuB;AAAA,IAC3E,CAAC;AAED,SAAK,SAAS,KAAK;AAAA,MACjB;AAAA,MACA;AAAA,MACA,QAAQ,SAAS;AAAA,MACjB;AAAA,MACA,MAAM,mBAAmB,IAAI;AAAA,MAC7B;AAAA,MACA,WAAW,IAAI,KAAK,SAAS,EAAE,YAAY;AAAA,MAC3C;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAaA,SAAS,mBAAmB,MAAsB;AAChD,SAAO,KAAK,QAAQ,kCAAkC,mBAAmB;AAC3E;AAEA,eAAe,gBACb,UACA,cACmD;AACnD,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,SAAS,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO,EAAE,MAAM,IAAI,eAAe,MAAM;AAAA,EAC1C;AACA,MAAI,KAAK,UAAU,aAAc,QAAO,EAAE,MAAM,MAAM,eAAe,MAAM;AAC3E,SAAO,EAAE,MAAM,KAAK,MAAM,GAAG,YAAY,GAAG,eAAe,KAAK;AAClE;","names":[]}
@@ -1,9 +1,3 @@
1
- import { fileURLToPath as __adcpFileURLToPath } from 'node:url';
2
- import { dirname as __adcpDirname } from 'node:path';
3
- import { createRequire as __adcpCreateRequire } from 'node:module';
4
- const __filename = __adcpFileURLToPath(import.meta.url);
5
- const __dirname = __adcpDirname(__filename);
6
- const require = __adcpCreateRequire(import.meta.url);
7
1
  import { globalAsyncLocalStorage } from "../utils/global-async-local-storage.mjs";
8
2
  import { ResponseTooLargeError } from "../errors/index.mjs";
9
3
  const responseSizeLimitStorage = globalAsyncLocalStorage("responseSizeLimit");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/protocols/responseSizeLimit.ts"],"sourcesContent":["// Response-body byte cap enforcement for hostile-vendor protection.\n//\n// Wraps a base fetch with a streaming size counter so the SDK aborts large\n// responses before any application-layer parsing buffers them. Active when\n// `responseSizeLimitStorage` carries a slot — installed unconditionally as\n// the innermost transport wrapper so production callers without the slot\n// pay only one ALS lookup per request.\n//\n// The wrapper composes inside `wrapFetchWithCapture`: the diagnostic capture\n// reads the size-limited body via `response.clone()`, so a hostile reply\n// can't blow memory through the capture path either.\n\nimport { globalAsyncLocalStorage } from '../utils/global-async-local-storage';\nimport { ResponseTooLargeError } from '../errors';\n\ninterface SizeLimitSlot {\n maxResponseBytes: number;\n}\n\nexport const responseSizeLimitStorage = globalAsyncLocalStorage<SizeLimitSlot>('responseSizeLimit');\n\n/**\n * Run `fn` with a response body byte cap active. Every fetch made through\n * a wrapped transport inside `fn` aborts with `ResponseTooLargeError` when\n * the response body exceeds `maxResponseBytes`. Non-positive caps disable\n * enforcement (ALS slot is not entered).\n */\nexport function withResponseSizeLimit<T>(maxResponseBytes: number | undefined, fn: () => Promise<T>): Promise<T> {\n if (!maxResponseBytes || !Number.isFinite(maxResponseBytes) || maxResponseBytes <= 0) {\n return fn();\n }\n return responseSizeLimitStorage.run({ maxResponseBytes }, fn);\n}\n\nfunction urlOfInput(input: RequestInfo | URL): string {\n if (typeof input === 'string') return input;\n if (input instanceof URL) return input.toString();\n return input.url;\n}\n\n/**\n * Strip the search component from a URL before storing it on\n * `ResponseTooLargeError`. Some agents publish manifests with auth tokens\n * in the query string (`?api_key=…`); without redaction those land in\n * `err.message`, `err.details.url`, and downstream log sinks.\n *\n * Returns the input unchanged when it can't be parsed (relative paths,\n * non-URL inputs from custom test stubs) — the alternative is throwing,\n * which would mask the original `ResponseTooLargeError`.\n */\nfunction redactUrlForError(url: string): string {\n try {\n const parsed = new URL(url);\n parsed.search = '';\n return parsed.toString();\n } catch {\n return url;\n }\n}\n\n/**\n * Force `Accept-Encoding: identity` on outgoing requests when the size cap\n * is active. Without this, undici sets `Accept-Encoding: gzip, deflate, br`\n * by default and decompresses the body before our counter sees it — a\n * hostile vendor can ship a 5 KB gzip blob that decompresses to GBs and\n * costs the attacker nothing for asymmetric CPU burn before the cap fires.\n * Forcing identity removes the asymmetry: the bomb has to be sent on the\n * wire at full size, where `Content-Length` pre-check catches it.\n *\n * No-op when the caller already set their own `Accept-Encoding` (signing\n * fetch may need a specific value to keep the signed bytes stable).\n */\nfunction withIdentityEncoding(init: RequestInit | undefined): RequestInit {\n const headers = new Headers(init?.headers);\n if (!headers.has('accept-encoding')) {\n headers.set('accept-encoding', 'identity');\n }\n return { ...(init ?? {}), headers };\n}\n\n/**\n * Wrap a fetch implementation so its responses honor the size cap from the\n * active `responseSizeLimitStorage` slot. Pass-through when no slot is set.\n *\n * Pre-checks `Content-Length` and refuses to read the body when the declared\n * size already exceeds the cap. Otherwise wraps `Response.body` in a\n * `TransformStream` that counts bytes and errors with `ResponseTooLargeError`\n * at the cap boundary, propagating to anyone reading the response (including\n * `Response.clone()` branches used by the diagnostic capture wrapper).\n */\nexport function wrapFetchWithSizeLimit(upstream: typeof fetch): typeof fetch {\n const wrapped: typeof fetch = async (input, init) => {\n const slot = responseSizeLimitStorage.getStore();\n if (!slot) return upstream(input, init);\n\n const response = await upstream(input, withIdentityEncoding(init));\n return enforceSizeLimit(response, slot.maxResponseBytes, redactUrlForError(urlOfInput(input)));\n };\n return wrapped;\n}\n\nfunction enforceSizeLimit(response: Response, maxBytes: number, url: string): Response {\n // SSE responses are legitimately unbounded — a single tool call emits N\n // status frames + a final result. Pass through; the protocol-level framing\n // terminates the stream, not byte counts. Case-insensitive prefix match\n // covers `text/event-stream; charset=utf-8` and `Text/Event-Stream` variants.\n if (response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {\n return response;\n }\n\n // Cheap pre-check: if the server declares a Content-Length over the cap,\n // tear the connection down before reading any of the body. Servers can\n // omit or lie about Content-Length, which is why the streaming counter\n // below is the authoritative enforcement.\n const declared = parseContentLength(response.headers.get('content-length'));\n if (declared !== undefined && declared > maxBytes) {\n // Best-effort cancel so the runtime can release the socket. We swallow\n // any rejection because the typed `ResponseTooLargeError` below is the\n // signal the caller acts on — a `cancel()` rejection here would only\n // happen if the body stream is already errored / locked, in which case\n // the socket is already on its way down and there's nothing to recover.\n response.body?.cancel().catch(() => {});\n throw new ResponseTooLargeError(maxBytes, 0, url, declared);\n }\n\n if (!response.body) return response;\n\n let bytesRead = 0;\n const counter = new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n bytesRead += chunk.byteLength;\n if (bytesRead > maxBytes) {\n controller.error(new ResponseTooLargeError(maxBytes, bytesRead, url));\n return;\n }\n controller.enqueue(chunk);\n },\n });\n\n return new Response(response.body.pipeThrough(counter), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\nfunction parseContentLength(value: string | null): number | undefined {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (!/^\\d+$/.test(trimmed)) return undefined;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n"],"mappings":";;;;;;AAYA,SAAS,+BAA+B;AACxC,SAAS,6BAA6B;AAM/B,MAAM,2BAA2B,wBAAuC,mBAAmB;AAQ3F,SAAS,sBAAyB,kBAAsC,IAAkC;AAC/G,MAAI,CAAC,oBAAoB,CAAC,OAAO,SAAS,gBAAgB,KAAK,oBAAoB,GAAG;AACpF,WAAO,GAAG;AAAA,EACZ;AACA,SAAO,yBAAyB,IAAI,EAAE,iBAAiB,GAAG,EAAE;AAC9D;AAEA,SAAS,WAAW,OAAkC;AACpD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,iBAAiB,IAAK,QAAO,MAAM,SAAS;AAChD,SAAO,MAAM;AACf;AAYA,SAAS,kBAAkB,KAAqB;AAC9C,MAAI;AACF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C;AACpE;AAAA,MACF;AACA,iBAAW,QAAQ,KAAK;AAAA,IAC1B;AAAA,EACF,CAAC;AAED,SAAO,IAAI,SAAS,SAAS,KAAK,YAAY,OAAO,GAAG;AAAA,IACtD,QAAQ,SAAS;AAAA,IACjB,YAAY,SAAS;AAAA,IACrB,SAAS,SAAS;AAAA,EACpB,CAAC;AACH;AAEA,SAAS,mBAAmB,OAA0C;AACpE,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAQ,KAAK,OAAO,EAAG,QAAO;AACnC,QAAM,SAAS,OAAO,OAAO;AAC7B,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/protocols/responseSizeLimit.ts"],"sourcesContent":["// Response-body byte cap enforcement for hostile-vendor protection.\n//\n// Wraps a base fetch with a streaming size counter so the SDK aborts large\n// responses before any application-layer parsing buffers them. Active when\n// `responseSizeLimitStorage` carries a slot — installed unconditionally as\n// the innermost transport wrapper so production callers without the slot\n// pay only one ALS lookup per request.\n//\n// The wrapper composes inside `wrapFetchWithCapture`: the diagnostic capture\n// reads the size-limited body via `response.clone()`, so a hostile reply\n// can't blow memory through the capture path either.\n\nimport { globalAsyncLocalStorage } from '../utils/global-async-local-storage';\nimport { ResponseTooLargeError } from '../errors';\n\ninterface SizeLimitSlot {\n maxResponseBytes: number;\n}\n\nexport const responseSizeLimitStorage = globalAsyncLocalStorage<SizeLimitSlot>('responseSizeLimit');\n\n/**\n * Run `fn` with a response body byte cap active. Every fetch made through\n * a wrapped transport inside `fn` aborts with `ResponseTooLargeError` when\n * the response body exceeds `maxResponseBytes`. Non-positive caps disable\n * enforcement (ALS slot is not entered).\n */\nexport function withResponseSizeLimit<T>(maxResponseBytes: number | undefined, fn: () => Promise<T>): Promise<T> {\n if (!maxResponseBytes || !Number.isFinite(maxResponseBytes) || maxResponseBytes <= 0) {\n return fn();\n }\n return responseSizeLimitStorage.run({ maxResponseBytes }, fn);\n}\n\nfunction urlOfInput(input: RequestInfo | URL): string {\n if (typeof input === 'string') return input;\n if (input instanceof URL) return input.toString();\n return input.url;\n}\n\n/**\n * Strip the search component from a URL before storing it on\n * `ResponseTooLargeError`. Some agents publish manifests with auth tokens\n * in the query string (`?api_key=…`); without redaction those land in\n * `err.message`, `err.details.url`, and downstream log sinks.\n *\n * Returns the input unchanged when it can't be parsed (relative paths,\n * non-URL inputs from custom test stubs) — the alternative is throwing,\n * which would mask the original `ResponseTooLargeError`.\n */\nfunction redactUrlForError(url: string): string {\n try {\n const parsed = new URL(url);\n parsed.search = '';\n return parsed.toString();\n } catch {\n return url;\n }\n}\n\n/**\n * Force `Accept-Encoding: identity` on outgoing requests when the size cap\n * is active. Without this, undici sets `Accept-Encoding: gzip, deflate, br`\n * by default and decompresses the body before our counter sees it — a\n * hostile vendor can ship a 5 KB gzip blob that decompresses to GBs and\n * costs the attacker nothing for asymmetric CPU burn before the cap fires.\n * Forcing identity removes the asymmetry: the bomb has to be sent on the\n * wire at full size, where `Content-Length` pre-check catches it.\n *\n * No-op when the caller already set their own `Accept-Encoding` (signing\n * fetch may need a specific value to keep the signed bytes stable).\n */\nfunction withIdentityEncoding(init: RequestInit | undefined): RequestInit {\n const headers = new Headers(init?.headers);\n if (!headers.has('accept-encoding')) {\n headers.set('accept-encoding', 'identity');\n }\n return { ...(init ?? {}), headers };\n}\n\n/**\n * Wrap a fetch implementation so its responses honor the size cap from the\n * active `responseSizeLimitStorage` slot. Pass-through when no slot is set.\n *\n * Pre-checks `Content-Length` and refuses to read the body when the declared\n * size already exceeds the cap. Otherwise wraps `Response.body` in a\n * `TransformStream` that counts bytes and errors with `ResponseTooLargeError`\n * at the cap boundary, propagating to anyone reading the response (including\n * `Response.clone()` branches used by the diagnostic capture wrapper).\n */\nexport function wrapFetchWithSizeLimit(upstream: typeof fetch): typeof fetch {\n const wrapped: typeof fetch = async (input, init) => {\n const slot = responseSizeLimitStorage.getStore();\n if (!slot) return upstream(input, init);\n\n const response = await upstream(input, withIdentityEncoding(init));\n return enforceSizeLimit(response, slot.maxResponseBytes, redactUrlForError(urlOfInput(input)));\n };\n return wrapped;\n}\n\nfunction enforceSizeLimit(response: Response, maxBytes: number, url: string): Response {\n // SSE responses are legitimately unbounded — a single tool call emits N\n // status frames + a final result. Pass through; the protocol-level framing\n // terminates the stream, not byte counts. Case-insensitive prefix match\n // covers `text/event-stream; charset=utf-8` and `Text/Event-Stream` variants.\n if (response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {\n return response;\n }\n\n // Cheap pre-check: if the server declares a Content-Length over the cap,\n // tear the connection down before reading any of the body. Servers can\n // omit or lie about Content-Length, which is why the streaming counter\n // below is the authoritative enforcement.\n const declared = parseContentLength(response.headers.get('content-length'));\n if (declared !== undefined && declared > maxBytes) {\n // Best-effort cancel so the runtime can release the socket. We swallow\n // any rejection because the typed `ResponseTooLargeError` below is the\n // signal the caller acts on — a `cancel()` rejection here would only\n // happen if the body stream is already errored / locked, in which case\n // the socket is already on its way down and there's nothing to recover.\n response.body?.cancel().catch(() => {});\n throw new ResponseTooLargeError(maxBytes, 0, url, declared);\n }\n\n if (!response.body) return response;\n\n let bytesRead = 0;\n const counter = new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n bytesRead += chunk.byteLength;\n if (bytesRead > maxBytes) {\n controller.error(new ResponseTooLargeError(maxBytes, bytesRead, url));\n return;\n }\n controller.enqueue(chunk);\n },\n });\n\n return new Response(response.body.pipeThrough(counter), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n\nfunction parseContentLength(value: string | null): number | undefined {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (!/^\\d+$/.test(trimmed)) return undefined;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n"],"mappings":"AAYA,SAAS,+BAA+B;AACxC,SAAS,6BAA6B;AAM/B,MAAM,2BAA2B,wBAAuC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C;AAC1E,MAAI,aAAa,UAAa,WAAW,UAAU;AAMjD,aAAS,MAAM,OAAO,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AACtC,UAAM,IAAI,sBAAsB,UAAU,GAAG,KAAK,QAAQ;AAAA,EAC5D;AAEA,MAAI,CAAC,SAAS,KAAM,QAAO;AAE3B,MAAI,YAAY;AAChB,QAAM,UAAU,IAAI,gBAAwC;AAAA,IAC1D,UAAU,OAAO,YAAY;AAC3B,mBAAa,MAAM;AACnB,UAAI,YAAY,UAAU;AACxB,mBAAW,MAAM,IAAI,sBAAsB,UAAU,WAAW,GAAG,CAAC;AACpE;AAAA,MACF;AACA,iBAAW,QAAQ,KAAK;AAAA,IAC1B;AAAA,EACF,CAAC;AAED,SAAO,IAAI,SAAS,SAAS,KAAK,YAAY,OAAO,GAAG;AAAA,IACtD,QAAQ,SAAS;AAAA,IACjB,YAAY,SAAS;AAAA,IACrB,SAAS,SAAS;AAAA,EACpB,CAAC;AACH;AAEA,SAAS,mBAAmB,OAA0C;AACpE,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAQ,KAAK,OAAO,EAAG,QAAO;AACnC,QAAM,SAAS,OAAO,OAAO;AAC7B,SAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;","names":[]}
@@ -1,9 +1,3 @@
1
- import { fileURLToPath as __adcpFileURLToPath } from 'node:url';
2
- import { dirname as __adcpDirname } from 'node:path';
3
- import { createRequire as __adcpCreateRequire } from 'node:module';
4
- const __filename = __adcpFileURLToPath(import.meta.url);
5
- const __dirname = __adcpDirname(__filename);
6
- const require = __adcpCreateRequire(import.meta.url);
7
1
  import { globalAsyncLocalStorage } from "../utils/global-async-local-storage.mjs";
8
2
  import { createHmac } from "node:crypto";
9
3
  const BODY_SNIPPET_LIMIT = 64 * 1024;