@adcp/sdk 14.0.0-beta.11 → 14.0.0-beta.13

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 (235) hide show
  1. package/bin/adcp-storyboard-sandbox.js +16 -0
  2. package/bin/adcp.js +28 -30
  3. package/dist/lib/index.d.mts +3 -3
  4. package/dist/lib/index.d.ts +3 -3
  5. package/dist/lib/index.d.ts.map +1 -1
  6. package/dist/lib/index.js +2 -0
  7. package/dist/lib/index.js.map +1 -1
  8. package/dist/lib/index.mjs +3 -1
  9. package/dist/lib/index.mjs.map +1 -1
  10. package/dist/lib/schemas/index.d.mts +385 -1
  11. package/dist/lib/schemas/index.d.ts +385 -1
  12. package/dist/lib/schemas/index.d.ts.map +1 -1
  13. package/dist/lib/schemas/index.js +13 -0
  14. package/dist/lib/schemas/index.js.map +1 -1
  15. package/dist/lib/schemas/index.mjs +11 -0
  16. package/dist/lib/schemas/index.mjs.map +1 -1
  17. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  18. package/dist/lib/server/create-adcp-server.d.mts +2 -2
  19. package/dist/lib/server/create-adcp-server.d.ts +2 -2
  20. package/dist/lib/server/create-adcp-server.d.ts.map +1 -1
  21. package/dist/lib/server/create-adcp-server.js +6 -1
  22. package/dist/lib/server/create-adcp-server.js.map +1 -1
  23. package/dist/lib/server/create-adcp-server.mjs +6 -1
  24. package/dist/lib/server/create-adcp-server.mjs.map +1 -1
  25. package/dist/lib/server/decisioning/index.d.mts +3 -3
  26. package/dist/lib/server/decisioning/index.d.ts +3 -3
  27. package/dist/lib/server/decisioning/index.d.ts.map +1 -1
  28. package/dist/lib/server/decisioning/index.js.map +1 -1
  29. package/dist/lib/server/decisioning/index.mjs.map +1 -1
  30. package/dist/lib/server/decisioning/runtime/from-platform.d.mts +24 -17
  31. package/dist/lib/server/decisioning/runtime/from-platform.d.ts +24 -17
  32. package/dist/lib/server/decisioning/runtime/from-platform.d.ts.map +1 -1
  33. package/dist/lib/server/decisioning/runtime/from-platform.js +71 -42
  34. package/dist/lib/server/decisioning/runtime/from-platform.js.map +1 -1
  35. package/dist/lib/server/decisioning/runtime/from-platform.mjs +75 -43
  36. package/dist/lib/server/decisioning/runtime/from-platform.mjs.map +1 -1
  37. package/dist/lib/server/decisioning/runtime/postgres-task-registry.d.mts +15 -21
  38. package/dist/lib/server/decisioning/runtime/postgres-task-registry.d.ts +15 -21
  39. package/dist/lib/server/decisioning/runtime/postgres-task-registry.d.ts.map +1 -1
  40. package/dist/lib/server/decisioning/runtime/postgres-task-registry.js +100 -30
  41. package/dist/lib/server/decisioning/runtime/postgres-task-registry.js.map +1 -1
  42. package/dist/lib/server/decisioning/runtime/postgres-task-registry.mjs +100 -30
  43. package/dist/lib/server/decisioning/runtime/postgres-task-registry.mjs.map +1 -1
  44. package/dist/lib/server/decisioning/runtime/task-registry.d.mts +30 -16
  45. package/dist/lib/server/decisioning/runtime/task-registry.d.ts +30 -16
  46. package/dist/lib/server/decisioning/runtime/task-registry.d.ts.map +1 -1
  47. package/dist/lib/server/decisioning/runtime/task-registry.js +40 -20
  48. package/dist/lib/server/decisioning/runtime/task-registry.js.map +1 -1
  49. package/dist/lib/server/decisioning/runtime/task-registry.mjs +38 -19
  50. package/dist/lib/server/decisioning/runtime/task-registry.mjs.map +1 -1
  51. package/dist/lib/server/decisioning/runtime/to-context.d.mts +2 -2
  52. package/dist/lib/server/decisioning/runtime/to-context.d.ts +2 -2
  53. package/dist/lib/server/decisioning/runtime/to-context.d.ts.map +1 -1
  54. package/dist/lib/server/decisioning/runtime/to-context.js +2 -2
  55. package/dist/lib/server/decisioning/runtime/to-context.js.map +1 -1
  56. package/dist/lib/server/decisioning/runtime/to-context.mjs +2 -2
  57. package/dist/lib/server/decisioning/runtime/to-context.mjs.map +1 -1
  58. package/dist/lib/server/decisioning/specialisms/creative-ad-server.d.mts +3 -2
  59. package/dist/lib/server/decisioning/specialisms/creative-ad-server.d.ts +3 -2
  60. package/dist/lib/server/decisioning/specialisms/creative-ad-server.d.ts.map +1 -1
  61. package/dist/lib/server/decisioning/specialisms/creative-ad-server.js.map +1 -1
  62. package/dist/lib/server/decisioning/specialisms/creative.d.mts +10 -10
  63. package/dist/lib/server/decisioning/specialisms/creative.d.ts +10 -10
  64. package/dist/lib/server/decisioning/specialisms/creative.d.ts.map +1 -1
  65. package/dist/lib/server/decisioning/specialisms/creative.js.map +1 -1
  66. package/dist/lib/server/index.d.mts +1 -1
  67. package/dist/lib/server/index.d.ts +1 -1
  68. package/dist/lib/server/index.d.ts.map +1 -1
  69. package/dist/lib/server/index.js.map +1 -1
  70. package/dist/lib/server/index.mjs.map +1 -1
  71. package/dist/lib/signing/agent-context.d.mts +1 -0
  72. package/dist/lib/signing/agent-context.d.ts +1 -0
  73. package/dist/lib/signing/agent-context.d.ts.map +1 -1
  74. package/dist/lib/signing/agent-context.js +37 -2
  75. package/dist/lib/signing/agent-context.js.map +1 -1
  76. package/dist/lib/signing/agent-context.mjs +38 -3
  77. package/dist/lib/signing/agent-context.mjs.map +1 -1
  78. package/dist/lib/signing/agent-fetch.d.mts +1 -2
  79. package/dist/lib/signing/agent-fetch.d.ts +1 -2
  80. package/dist/lib/signing/agent-fetch.d.ts.map +1 -1
  81. package/dist/lib/signing/agent-fetch.js +2 -0
  82. package/dist/lib/signing/agent-fetch.js.map +1 -1
  83. package/dist/lib/signing/agent-fetch.mjs +2 -0
  84. package/dist/lib/signing/agent-fetch.mjs.map +1 -1
  85. package/dist/lib/signing/agent-resolver/etld.js.map +1 -1
  86. package/dist/lib/signing/agent-resolver/etld.mjs.map +1 -1
  87. package/dist/lib/testing/client.d.mts +6 -0
  88. package/dist/lib/testing/client.d.ts +6 -0
  89. package/dist/lib/testing/client.d.ts.map +1 -1
  90. package/dist/lib/testing/client.js +76 -4
  91. package/dist/lib/testing/client.js.map +1 -1
  92. package/dist/lib/testing/client.mjs +75 -4
  93. package/dist/lib/testing/client.mjs.map +1 -1
  94. package/dist/lib/testing/compliance/comply.d.ts.map +1 -1
  95. package/dist/lib/testing/compliance/comply.js +6 -0
  96. package/dist/lib/testing/compliance/comply.js.map +1 -1
  97. package/dist/lib/testing/compliance/comply.mjs +7 -1
  98. package/dist/lib/testing/compliance/comply.mjs.map +1 -1
  99. package/dist/lib/testing/storyboard/default-invariants.d.ts.map +1 -1
  100. package/dist/lib/testing/storyboard/default-invariants.js +11 -2
  101. package/dist/lib/testing/storyboard/default-invariants.js.map +1 -1
  102. package/dist/lib/testing/storyboard/default-invariants.mjs +11 -2
  103. package/dist/lib/testing/storyboard/default-invariants.mjs.map +1 -1
  104. package/dist/lib/testing/storyboard/index.d.mts +1 -1
  105. package/dist/lib/testing/storyboard/index.d.ts +1 -1
  106. package/dist/lib/testing/storyboard/index.d.ts.map +1 -1
  107. package/dist/lib/testing/storyboard/index.js.map +1 -1
  108. package/dist/lib/testing/storyboard/index.mjs.map +1 -1
  109. package/dist/lib/testing/storyboard/loader.d.ts.map +1 -1
  110. package/dist/lib/testing/storyboard/loader.js +14 -0
  111. package/dist/lib/testing/storyboard/loader.js.map +1 -1
  112. package/dist/lib/testing/storyboard/loader.mjs +14 -0
  113. package/dist/lib/testing/storyboard/loader.mjs.map +1 -1
  114. package/dist/lib/testing/storyboard/phase-condition.d.mts +41 -0
  115. package/dist/lib/testing/storyboard/phase-condition.d.ts +42 -0
  116. package/dist/lib/testing/storyboard/phase-condition.d.ts.map +1 -0
  117. package/dist/lib/testing/storyboard/phase-condition.js +215 -0
  118. package/dist/lib/testing/storyboard/phase-condition.js.map +1 -0
  119. package/dist/lib/testing/storyboard/phase-condition.mjs +189 -0
  120. package/dist/lib/testing/storyboard/phase-condition.mjs.map +1 -0
  121. package/dist/lib/testing/storyboard/request-builder.d.ts.map +1 -1
  122. package/dist/lib/testing/storyboard/request-builder.js +15 -2
  123. package/dist/lib/testing/storyboard/request-builder.js.map +1 -1
  124. package/dist/lib/testing/storyboard/request-builder.mjs +15 -2
  125. package/dist/lib/testing/storyboard/request-builder.mjs.map +1 -1
  126. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.d.mts +15 -0
  127. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.d.ts +16 -0
  128. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.d.ts.map +1 -0
  129. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.js +106 -0
  130. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.js.map +1 -0
  131. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.mjs +82 -0
  132. package/dist/lib/testing/storyboard/request-signing/functional-dispatch.mjs.map +1 -0
  133. package/dist/lib/testing/storyboard/request-signing/test-kit.d.mts +15 -0
  134. package/dist/lib/testing/storyboard/request-signing/test-kit.d.ts +15 -0
  135. package/dist/lib/testing/storyboard/request-signing/test-kit.d.ts.map +1 -1
  136. package/dist/lib/testing/storyboard/request-signing/test-kit.js +58 -0
  137. package/dist/lib/testing/storyboard/request-signing/test-kit.js.map +1 -1
  138. package/dist/lib/testing/storyboard/request-signing/test-kit.mjs +58 -0
  139. package/dist/lib/testing/storyboard/request-signing/test-kit.mjs.map +1 -1
  140. package/dist/lib/testing/storyboard/request-signing/vector-loader.d.mts +2 -0
  141. package/dist/lib/testing/storyboard/request-signing/vector-loader.d.ts +2 -0
  142. package/dist/lib/testing/storyboard/request-signing/vector-loader.d.ts.map +1 -1
  143. package/dist/lib/testing/storyboard/request-signing/vector-loader.js +7 -1
  144. package/dist/lib/testing/storyboard/request-signing/vector-loader.js.map +1 -1
  145. package/dist/lib/testing/storyboard/request-signing/vector-loader.mjs +6 -1
  146. package/dist/lib/testing/storyboard/request-signing/vector-loader.mjs.map +1 -1
  147. package/dist/lib/testing/storyboard/runner.d.ts.map +1 -1
  148. package/dist/lib/testing/storyboard/runner.js +67 -24
  149. package/dist/lib/testing/storyboard/runner.js.map +1 -1
  150. package/dist/lib/testing/storyboard/runner.mjs +67 -24
  151. package/dist/lib/testing/storyboard/runner.mjs.map +1 -1
  152. package/dist/lib/testing/storyboard/task-map.d.ts.map +1 -1
  153. package/dist/lib/testing/storyboard/task-map.js +6 -2
  154. package/dist/lib/testing/storyboard/task-map.js.map +1 -1
  155. package/dist/lib/testing/storyboard/task-map.mjs +6 -2
  156. package/dist/lib/testing/storyboard/task-map.mjs.map +1 -1
  157. package/dist/lib/testing/storyboard/types.d.mts +5 -4
  158. package/dist/lib/testing/storyboard/types.d.ts +5 -4
  159. package/dist/lib/testing/storyboard/types.d.ts.map +1 -1
  160. package/dist/lib/testing/storyboard/types.js.map +1 -1
  161. package/dist/lib/testing/storyboard/types.mjs.map +1 -1
  162. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  163. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  164. package/dist/lib/testing/storyboard/webhook-assertions.d.ts.map +1 -1
  165. package/dist/lib/testing/storyboard/webhook-assertions.js +60 -4
  166. package/dist/lib/testing/storyboard/webhook-assertions.js.map +1 -1
  167. package/dist/lib/testing/storyboard/webhook-assertions.mjs +60 -4
  168. package/dist/lib/testing/storyboard/webhook-assertions.mjs.map +1 -1
  169. package/dist/lib/testing/storyboard/webhook-receiver.d.mts +15 -0
  170. package/dist/lib/testing/storyboard/webhook-receiver.d.ts +15 -0
  171. package/dist/lib/testing/storyboard/webhook-receiver.d.ts.map +1 -1
  172. package/dist/lib/testing/storyboard/webhook-receiver.js +57 -6
  173. package/dist/lib/testing/storyboard/webhook-receiver.js.map +1 -1
  174. package/dist/lib/testing/storyboard/webhook-receiver.mjs +57 -6
  175. package/dist/lib/testing/storyboard/webhook-receiver.mjs.map +1 -1
  176. package/dist/lib/testing/types.d.mts +12 -0
  177. package/dist/lib/testing/types.d.ts +12 -0
  178. package/dist/lib/testing/types.d.ts.map +1 -1
  179. package/dist/lib/testing/types.js.map +1 -1
  180. package/dist/lib/types/comply-test-controller.d.ts +1 -14
  181. package/dist/lib/types/core.generated.d.mts +6 -3
  182. package/dist/lib/types/core.generated.d.ts +6 -3
  183. package/dist/lib/types/core.generated.d.ts.map +1 -1
  184. package/dist/lib/types/core.generated.js.map +1 -1
  185. package/dist/lib/types/get-products.d.ts +1 -14
  186. package/dist/lib/types/index.d.mts +1 -1
  187. package/dist/lib/types/index.d.ts +1 -1
  188. package/dist/lib/types/index.d.ts.map +1 -1
  189. package/dist/lib/types/index.js.map +1 -1
  190. package/dist/lib/types/index.mjs.map +1 -1
  191. package/dist/lib/types/list-transformers.d.ts +9 -5
  192. package/dist/lib/types/schemas.generated.d.ts +23 -352
  193. package/dist/lib/types/schemas.generated.d.ts.map +1 -1
  194. package/dist/lib/types/schemas.generated.js +7 -4
  195. package/dist/lib/types/schemas.generated.js.map +1 -1
  196. package/dist/lib/types/schemas.generated.mjs +6 -4
  197. package/dist/lib/types/schemas.generated.mjs.map +1 -1
  198. package/dist/lib/types/server-payload-aliases.d.mts +2 -1
  199. package/dist/lib/types/server-payload-aliases.d.ts +2 -1
  200. package/dist/lib/types/server-payload-aliases.d.ts.map +1 -1
  201. package/dist/lib/types/server-payload-aliases.js.map +1 -1
  202. package/dist/lib/types/tools.generated.d.mts +6 -3
  203. package/dist/lib/types/tools.generated.d.ts +6 -3
  204. package/dist/lib/types/tools.generated.d.ts.map +1 -1
  205. package/dist/lib/types/tools.generated.js.map +1 -1
  206. package/dist/lib/utils/build-creative-return-builders.d.mts +5 -1
  207. package/dist/lib/utils/build-creative-return-builders.d.ts +5 -1
  208. package/dist/lib/utils/build-creative-return-builders.d.ts.map +1 -1
  209. package/dist/lib/utils/build-creative-return-builders.js +9 -3
  210. package/dist/lib/utils/build-creative-return-builders.js.map +1 -1
  211. package/dist/lib/utils/build-creative-return-builders.mjs +7 -2
  212. package/dist/lib/utils/build-creative-return-builders.mjs.map +1 -1
  213. package/dist/lib/utils/response-unwrapper.js +1 -1
  214. package/dist/lib/utils/response-unwrapper.js.map +1 -1
  215. package/dist/lib/utils/response-unwrapper.mjs +1 -1
  216. package/dist/lib/utils/response-unwrapper.mjs.map +1 -1
  217. package/dist/lib/validation/schema-loader.d.ts.map +1 -1
  218. package/dist/lib/validation/schema-loader.js +16 -7
  219. package/dist/lib/validation/schema-loader.js.map +1 -1
  220. package/dist/lib/validation/schema-loader.mjs +16 -7
  221. package/dist/lib/validation/schema-loader.mjs.map +1 -1
  222. package/dist/lib/version.d.mts +3 -3
  223. package/dist/lib/version.d.ts +3 -3
  224. package/dist/lib/version.js +3 -3
  225. package/dist/lib/version.js.map +1 -1
  226. package/dist/lib/version.mjs +3 -3
  227. package/dist/lib/version.mjs.map +1 -1
  228. package/docs/llms.txt +2 -2
  229. package/docs/migration-5.x-to-6.x.md +3 -2
  230. package/docs/migration-task-registry-scoping.md +61 -0
  231. package/examples/hello_seller_adapter_guaranteed.ts +1 -1
  232. package/package.json +5 -5
  233. package/skills/build-decisioning-creative-template/SKILL.md +2 -2
  234. package/skills/build-decisioning-platform/SKILL.md +4 -2
  235. package/skills/build-decisioning-platform/advanced/REFERENCE.md +7 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/server/create-adcp-server.ts"],"sourcesContent":["/**\n * Declarative AdCP server builder.\n *\n * `createAdcpServer` wires domain-grouped handler functions to Zod input\n * schemas, response builders, and account resolution.\n * Handlers only run when preconditions pass. `get_adcp_capabilities` is\n * auto-generated from the tools you register.\n *\n * For governance on financial tools (create_media_buy, update_media_buy,\n * activate_signal), use the composable `checkGovernance()` helper inside\n * your handler — see `governance.ts`.\n *\n * @example\n * ```typescript\n * import {\n * createAdcpServer,\n * createIdempotencyStore,\n * memoryBackend,\n * serve,\n * } from '@adcp/sdk/server/legacy/v5';\n *\n * // Single-process example. Use pgBackend(pool) or redisBackend(client) for\n * // durable, replica-safe production replay.\n * const idempotency = createIdempotencyStore({ backend: memoryBackend(), ttlSeconds: 86400 });\n *\n * serve(() => createAdcpServer({\n * name: 'My Publisher',\n * version: '1.0.0',\n * idempotency,\n *\n * // Second argument carries `toolName` and (when `authenticate` is wired\n * // on `serve()`) the caller's `authInfo`. Adapters that front an\n * // upstream platform API can use the caller's token here to resolve\n * // the platform account in one pass.\n * resolveAccount: async (ref, { authInfo }) => db.findAccount(ref, authInfo),\n *\n * mediaBuy: {\n * getProducts: async (params, ctx) => ({ products: catalog.search(params) }),\n * createMediaBuy: async (params, ctx) => ({\n * media_buy_id: `mb_${Date.now()}`,\n * packages: [],\n * }),\n * },\n * }));\n * ```\n */\n\nimport { z } from 'zod';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport {\n COMPATIBLE_ADCP_VERSIONS,\n parseAdcpMajorVersion,\n toReleasePrecisionVersion,\n type AdcpVersion,\n} from '../version';\nimport {\n isAdcpVersionAtLeast,\n isMovingAdcpPrereleaseFamilyAlias,\n resolveAdcpVersion,\n} from '../utils/adcp-version-config';\nimport { getValidator, hasSchemaBundle, resolveBundleKey, getMcpProfileInputSchema } from '../validation/schema-loader';\nimport { TOOL_INPUT_SHAPES } from '../schemas';\nimport { TaskTypeValues } from '../types/enums.generated';\nimport { bundleSupportsAdcpVersionField } from '../protocols';\nimport { getToolsWithErrorArm, type ErrorArmDescriptor } from './error-arm-tools';\nimport type { ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ZodRawShapeCompat, AnySchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';\nimport type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';\nimport type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';\nimport {\n ADCP_CAPABILITIES,\n ADCP_STATE_STORE,\n wrapMcpServer,\n setSdkServerInstructions,\n setMcpAppResources,\n setMcpToolProfile,\n wrapInitializeHandler,\n wrapSdkRequestHandler,\n type AdcpServer,\n type AdcpServerInternal,\n} from './adcp-server';\nimport {\n mcpAppResourceMetadata,\n normalizeMcpAppResources,\n readMcpAppResource,\n type AdcpMcpResourceDefinition,\n} from './mcp-app';\nimport { ADCP_TASK_MESSAGE_QUEUE, createTaskCapableServer, InMemoryTaskStore } from './tasks';\nimport type { TaskStore, TaskMessageQueue } from './tasks';\nimport { adcpError, applyAdcpErrorAllowlist, sanitizeStructuredAdcpError } from './errors';\nimport type { BuyerAgent, BuyerAgentRegistry } from './decisioning/buyer-agent';\nimport type { ResolvedAuthInfo } from './decisioning/account';\nimport type { TaskRecord, TaskRegistry } from './decisioning/runtime/task-registry';\nimport { protocolForTool } from './decisioning/runtime/protocol-for-tool';\nimport { AdcpError } from './decisioning/async-outcome';\nimport { redactCredentialPatterns } from './redact';\nimport {\n scanArgsForCredentials,\n resolveCredentialPolicyForTool,\n validateCredentialPolicy,\n type CredentialPolicy,\n} from './credential-policy';\nimport { ADCP_ERROR_FIELD_ALLOWLIST } from './envelope-allowlist';\nimport { InMemoryStateStore } from './state-store';\nimport type { AdcpStateStore } from './state-store';\nimport { AuthError, getServeRequestContext, type AuthPrincipal } from './auth';\nimport { principalForVerifiedSigner } from './auth-signature';\nimport {\n capabilitiesResponse,\n productsResponse,\n mediaBuyResponse,\n deliveryResponse,\n listAccountsResponse,\n listCreativeFormatsResponse,\n updateMediaBuyResponse,\n getMediaBuysResponse,\n performanceFeedbackResponse,\n buildCreativeResponse,\n buildCreativeMultiResponse,\n creativeDeliveryResponse,\n listCreativesResponse,\n syncCreativesResponse,\n getSignalsResponse,\n activateSignalResponse,\n acquireRightsResponse,\n updateRightsResponse,\n syncAccountsResponse,\n syncGovernanceResponse,\n reportUsageResponse,\n toStructuredContent,\n _getExplicitResponseSummary,\n type McpToolResponse,\n} from './responses';\n\nimport { TOOL_REQUEST_SCHEMAS } from '../utils/tool-request-schemas';\nimport { defineProposalRefinementCapabilities } from '../negotiation/seller';\nimport {\n ProposalRefinementValidationError,\n refinementDimensions,\n validateRefineProposalsRequest,\n} from '../negotiation/buyer';\nimport { validateRefineProposalsResponseShape } from '../negotiation/verification';\nimport type {\n ProposalRefinementCapabilities,\n RefineProposalsRequest,\n RefineProposalsResponse,\n} from '../negotiation/types';\nimport type { ProposalRefinementScope } from '../negotiation/seller';\n\n// NOTE on `outputSchema`: the MCP SDK's client-side `callTool` validates\n// `result.structuredContent` against the registered `outputSchema`\n// whenever structuredContent is present — regardless of `isError`. See\n// `node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js` line\n// 504. AdCP's `adcpError()` envelope carries\n// `structuredContent: { adcp_error: {...} }` with `isError: true`, which\n// would fail every client-side outputSchema check (the error shape\n// doesn't match the success schema). Until the SDK gates that client\n// check on `!isError` too, we do not declare `outputSchema` on\n// framework-registered tools — response drift is caught by the\n// dispatcher's AJV validator (#727) instead, and custom tools opt in\n// explicitly via `customTools[*].outputSchema`.\n\nfunction hasIdempotencyClearAll(store: IdempotencyStore): boolean {\n // `clearAll` is optional on `IdempotencyStore` — only present when the\n // configured backend opts in (memory backend does; pg backend does not).\n return typeof store.clearAll === 'function';\n}\n\n// Built-in request claims use the full replay window as their base fence.\n// Renew periodically while a handler is active so genuinely long-running\n// work retains that full window from its latest liveness point; the base\n// fence itself still prevents a transient renewal outage from reopening the\n// mutation.\nconst IDEMPOTENCY_CLAIM_RENEW_INTERVAL_MS = 60_000;\nimport { isMutatingTask, requestUsesIdempotency, IDEMPOTENCY_KEY_PATTERN, MUTATING_TASKS } from '../utils/idempotency';\nimport { STATUS_FREE_SYNC_RESPONSE_TOOLS } from '../utils/envelope-status-compat';\nimport { validateRequest, validateResponse, formatIssues, type ValidationIssue } from '../validation/schema-validator';\nimport { buildAdcpValidationErrorPayload } from '../validation/schema-errors';\nimport { hashPayload, IdempotencyClaimOwnershipError, type IdempotencyStore } from './idempotency';\nimport {\n createWebhookEmitter,\n type WebhookEmitParams,\n type WebhookEmitResult,\n type WebhookEmitterOptions,\n} from './webhook-emitter';\nimport { createExpressVerifier, type ExpressLike } from '../signing/middleware';\nimport { isSandboxOrMockAccount } from './account-mode';\nimport {\n isSandboxRequest as isSandboxRequestForSeeding,\n mergeSeededProductsIntoResponse,\n mergeSeededCreativesIntoResponse,\n mergeSeededMediaBuysIntoResponse,\n mergeSeededMediaBuyDeliveryIntoResponse,\n mergeSeededAccountsIntoResponse,\n mergeSeededCreativeFormatsIntoResponse,\n mergeSeededPropertyListsIntoResponse,\n mergeSeededCollectionListsIntoResponse,\n mergeSeededContentStandardsIntoResponse,\n mergeSeededSignalsIntoResponse,\n mergeSeededCreativeDeliveryIntoResponse,\n mergeSeededCreativeFeaturesIntoResponse,\n mergeSeededRightsIntoResponse,\n replaceAccountFinancialsIfSeeded,\n replacePropertyListIfSeeded,\n replaceCollectionListIfSeeded,\n replaceContentStandardsIfSeeded,\n replaceBrandIdentityIfSeeded,\n replaceSiOfferingIfSeeded,\n filterValidSeededProducts,\n filterValidSeededCreatives,\n filterValidSeededMediaBuys,\n filterValidSeededMediaBuyDeliveries,\n filterValidSeededAccounts,\n filterValidSeededAccountFinancials,\n filterValidSeededCreativeFormats,\n filterValidSeededPropertyLists,\n filterValidSeededCollectionLists,\n filterValidSeededContentStandards,\n filterValidSeededSignals,\n filterValidSeededCreativeDelivery,\n filterValidSeededCreativeFeatures,\n filterValidSeededBrandIdentity,\n filterValidSeededRights,\n filterValidSeededSiOffering,\n type TestControllerBridge,\n type TestControllerBridgeContext,\n} from './test-controller-bridge';\nimport type { JwksResolver } from '../signing/jwks';\nimport type { ReplayStore } from '../signing/replay';\nimport type { RevocationStore } from '../signing/revocation';\nimport type { ContentDigestPolicy } from '../signing/types';\nimport { ADCP_VERSION, LIBRARY_VERSION } from '../version';\n\n// Type-only imports for AdcpToolMap handler signatures (z.input<typeof ...>)\nimport type {\n GetProductsRequestSchema,\n ListProductsRequestSchema,\n RequestProposalsRequestSchema,\n DeclineProposalsRequestSchema,\n BuyProductsRequestSchema,\n AcceptProposalRequestSchema,\n ControlMediaBuyRequestSchema,\n CreateMediaBuyRequestSchema,\n UpdateMediaBuyRequestSchema,\n GetMediaBuysRequestSchema,\n GetMediaBuyDeliveryRequestSchema,\n ProvidePerformanceFeedbackRequestSchema,\n GetTaskStatusRequestSchema,\n ListTasksRequestSchema,\n SyncAgentNotificationConfigsRequestSchema,\n ListCreativeFormatsRequestSchema,\n ListTransformersRequestSchema,\n BuildCreativeRequestSchema,\n GetCreativeDeliveryRequestSchema,\n ListCreativesRequestSchema,\n SyncCreativesRequestSchema,\n GetSignalsRequestSchema,\n ActivateSignalRequestSchema,\n ListAccountsRequestSchema,\n SyncAccountsRequestSchema,\n SyncGovernanceRequestSchema,\n GetAccountFinancialsRequestSchema,\n ReportUsageRequestSchema,\n SyncEventSourcesRequestSchema,\n LogEventRequestSchema,\n SyncAudiencesRequestSchema,\n SyncCatalogsRequestSchema,\n CreatePropertyListRequestSchema,\n UpdatePropertyListRequestSchema,\n GetPropertyListRequestSchema,\n ListPropertyListsRequestSchema,\n DeletePropertyListRequestSchema,\n CreateCollectionListRequestSchema,\n UpdateCollectionListRequestSchema,\n GetCollectionListRequestSchema,\n ListCollectionListsRequestSchema,\n DeleteCollectionListRequestSchema,\n ListContentStandardsRequestSchema,\n GetContentStandardsRequestSchema,\n CreateContentStandardsRequestSchema,\n UpdateContentStandardsRequestSchema,\n CalibrateContentRequestSchema,\n ValidateContentDeliveryRequestSchema,\n GetMediaBuyArtifactsRequestSchema,\n GetCreativeFeaturesRequestSchema,\n SyncPlansRequestSchema,\n CheckGovernanceRequestSchema,\n ReportPlanOutcomeRequestSchema,\n ReportPlanAdjustmentRequestSchema,\n GetPlanAuditLogsRequestSchema,\n SIGetOfferingRequestSchema,\n SIInitiateSessionRequestSchema,\n SISendMessageRequestSchema,\n SITerminateSessionRequestSchema,\n PreviewCreativeRequestSchema,\n GetBrandIdentityRequestSchema,\n GetRightsRequestSchema,\n AcquireRightsRequestSchema,\n UpdateRightsRequestSchema,\n} from '../types/schemas.generated';\nimport { AccountReferenceSchema } from '../types/schemas.generated';\n\nimport type {\n AcquireRightsAcquired,\n AcquireRightsPendingApproval,\n AcquireRightsRejected,\n UpdateRightsResponse,\n UpdateRightsSuccess,\n GetBrandIdentitySuccess,\n GetRightsSuccess,\n} from '../types/core.generated';\nimport type {\n GetProductsResponse,\n ListProductsResponse,\n RequestProposalsResponse,\n DeclineProposalsResponse,\n BuyProductsResponse,\n AcceptProposalResponse,\n ControlMediaBuyResponse,\n CreateMediaBuyResponse,\n UpdateMediaBuySuccess,\n UpdateMediaBuyResponse,\n GetMediaBuysResponse,\n GetMediaBuyDeliveryResponse,\n GetTaskStatusResponse,\n ListTasksResponse,\n SyncAgentNotificationConfigsResponse,\n ListAccountsResponse,\n ListCreativeFormatsResponse,\n ListTransformersResponse,\n ProvidePerformanceFeedbackSuccess,\n ProvidePerformanceFeedbackResponse,\n BuildCreativeSuccess,\n BuildCreativeMultiSuccess,\n BuildCreativeResponse,\n GetCreativeDeliveryResponse,\n ListCreativesResponse,\n SyncCreativesError,\n SyncCreativesSuccess,\n SyncCreativesResponse,\n GetSignalsResponse,\n ActivateSignalSuccess,\n ActivateSignalResponse,\n GetAdCPCapabilitiesResponse,\n CreatePropertyListResponse,\n UpdatePropertyListResponse,\n GetPropertyListResponse,\n ListPropertyListsResponse,\n DeletePropertyListResponse,\n CreateCollectionListResponse,\n UpdateCollectionListResponse,\n GetCollectionListResponse,\n ListCollectionListsResponse,\n DeleteCollectionListResponse,\n SyncPlansResponse,\n CheckGovernanceResponse,\n ReportPlanOutcomeResponse,\n ReportPlanAdjustmentResponse,\n GetPlanAuditLogsResponse,\n SIGetOfferingResponse,\n SIInitiateSessionResponse,\n SISendMessageResponse,\n SITerminateSessionResponse,\n SyncEventSourcesSuccess,\n SyncEventSourcesResponse,\n LogEventSuccess,\n LogEventResponse,\n SyncAudiencesSuccess,\n SyncAudiencesResponse,\n SyncCatalogsSuccess,\n SyncCatalogsResponse,\n SyncAccountsSuccess,\n SyncAccountsResponse,\n SyncGovernanceSuccess,\n SyncGovernanceResponse,\n GetAccountFinancialsSuccess,\n GetAccountFinancialsResponse,\n GetCreativeFeaturesResponse,\n ReportUsageResponse,\n PreviewCreativeResponse,\n AccountReference,\n BrandReference,\n ListContentStandardsResponse,\n GetContentStandardsResponse,\n CreateContentStandardsResponse,\n UpdateContentStandardsResponse,\n CalibrateContentResponse,\n ValidateContentDeliveryResponse,\n GetMediaBuyArtifactsResponse,\n ListTasksRequest,\n TaskStatus,\n TaskType,\n AdCPProtocol as WireAdcpProtocol,\n} from '../types/tools.generated';\n\nimport type { AdcpProtocol, MediaBuyFeatures, AccountCapabilities, CreativeCapabilities } from '../utils/capabilities';\nimport type { MediaChannel } from '../types/tools.generated';\nimport type { RequireCacheScopeWhenProducts, ServerPayload } from '../types/server-payload';\nimport type { CreateMediaBuyPayload as CreateMediaBuyServerPayload } from '../types/server-payload-aliases';\nimport {\n DEFAULT_UNKNOWN_ERROR_RECOVERY,\n STANDARD_ERROR_CODES,\n isStandardErrorCode,\n type ErrorRecovery,\n} from '../types/error-codes';\n\n// ---------------------------------------------------------------------------\n// Logger\n// ---------------------------------------------------------------------------\n\nexport interface AdcpLogger {\n debug(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n error(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Module-singleton default `InMemoryStateStore`. Adopters who use the\n * factory pattern `serve(() => createAdcpServer({...}))` get a fresh\n * `createAdcpServer` invocation per request — without this singleton, the\n * destructured default `stateStore = new InMemoryStateStore()` would mint\n * a brand-new in-memory store per request, silently dropping every\n * `ctx.store.put(...)` between calls. Empirically reproduced in matrix\n * v3: an LLM-built SI agent that put session state in `ctx.store` on\n * `si_initiate_session` failed to find it on the next request's\n * `si_send_message`.\n *\n * Sharing one default store across the process is what every other Node\n * framework's \"memory store\" already does, and it's what the skills\n * (creative, SI, etc.) explicitly promise: \"framework provides\n * InMemoryStateStore by default — no need for module-level Maps\".\n *\n * Multi-tenant adopters and production deployments pass their own store\n * (`PostgresStateStore`, etc.); the default is for development and\n * single-tenant agents only.\n *\n * Tests that need isolation pass an explicit `stateStore: new\n * InMemoryStateStore()`. The module-level default does not break\n * existing test isolation because tests have always opted-in to a fresh\n * store per case.\n */\nconst DEFAULT_STATE_STORE = new InMemoryStateStore();\n\nconst noopLogger: AdcpLogger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n\n// ---------------------------------------------------------------------------\n// Handler context\n// ---------------------------------------------------------------------------\n\n/** Trusted caller namespace for agent-level and governance mutations. */\nexport interface CallerMutationScope {\n tenant_id: string;\n principal_id: string;\n /** Optional account boundary when the mutation is account-owned. */\n account_id?: string;\n}\n\n/**\n * Context passed to every handler.\n *\n * If the tool has an account ref and `resolveAccount` is configured,\n * `account` is the resolved account object (guaranteed non-null —\n * the handler only runs if resolution succeeds).\n *\n * If `resolveSessionKey` is configured, `sessionKey` is the scoping key\n * derived from the request — usually tenant/brand/publisher-account id.\n * Handlers can pass it to `scopedStore(ctx.store, ctx.sessionKey!)` to get\n * a session-scoped view that works on any `AdcpStateStore` implementation.\n */\nexport interface HandlerContext<TAccount = unknown> {\n account?: TAccount;\n /** Transport cancellation signal for the current request. */\n signal?: AbortSignal;\n /**\n * AdCP release selected for this request after applying the buyer pin to\n * `capabilities.adcp.supported_versions`. This may be older than the\n * server's configured maximum release when the seller downshifts.\n */\n servedAdcpVersion?: string;\n /**\n * Resolved buyer agent for this request, populated by `BuyerAgentRegistry`\n * when an `agentRegistry` is configured on the server (Phase 1 of #1269).\n * Carries the durable commercial relationship — status, billing\n * capabilities, default account terms — distinct from the per-request\n * credential. Undefined when no registry is configured OR when the\n * registry returned `null` for the request's credential.\n */\n agent?: BuyerAgent;\n /** Session scoping key derived from the request. Populated when `resolveSessionKey` is configured. */\n sessionKey?: string;\n /** State store for persisting domain objects (media buys, accounts, creatives). */\n store: AdcpStateStore;\n /**\n * Authentication info for the caller, when `ServeOptions.authenticate` is\n * configured. Populated from the MCP SDK's `extra.authInfo`, which\n * `serve()` sets from the auth principal. Use this to enforce\n * per-principal authorization in handlers.\n *\n * Stage 3 of #1269 added the kind-discriminated `credential` and the\n * `operator` fields. The legacy `token` / `clientId` / `scopes` are\n * preserved as optional fields through the deprecation cycle; new code\n * should read `credential` and switch on its `kind`.\n *\n * Buyer-agent identity post-resolution is on `ctx.agent` (the resolved\n * `BuyerAgent` record), NOT here — this surface only carries\n * authentication information about the credential, not the registry\n * lookup result.\n */\n authInfo?: ResolvedAuthInfo;\n /** Trusted proposal namespace resolved by `proposalNegotiation.resolveScope`. */\n proposalRefinementScope?: Readonly<ProposalRefinementScope>;\n /** Trusted namespace for caller-scoped 3.2 mutations. Persist records under this tuple. */\n callerMutationScope?: Readonly<CallerMutationScope>;\n /**\n * Emit a signed webhook to a buyer's `push_notification_config.url`.\n * Populated when `AdcpServerConfig.webhooks` is configured. Handles\n * RFC 9421 signing, stable `idempotency_key` across retries, and\n * retry/backoff per adcp#2417 + adcp#2423 + adcp#2478.\n *\n * Typical call from inside a completion handler:\n *\n * await ctx.emitWebhook({\n * url: push_notification_config.url,\n * payload: { operation_id, task_id, task_type: 'create_media_buy', status: 'completed', timestamp, result },\n * delivery_id: `create_media_buy.${media_buy_id}.completed`,\n * });\n */\n emitWebhook?: (params: WebhookEmitParams) => Promise<WebhookEmitResult>;\n}\n\n/** Request metadata passed to `resolveSessionKey` so the hook can derive a key from any field. */\nexport interface SessionKeyContext<TAccount = unknown> {\n toolName: AdcpServerToolName;\n params: Record<string, unknown>;\n account?: TAccount;\n /** Resolved buyer agent (Phase 1 of #1269), when `agentRegistry` is configured. */\n agent?: BuyerAgent;\n}\n\n/**\n * Request context passed to `resolveAccount` so the resolver can inspect the\n * authenticated principal at resolution time. This matters for adapters that\n * front an upstream platform API (Snap, Meta, TikTok, retail media networks)\n * where the upstream account lookup requires the caller's platform OAuth\n * token — forwarding `authInfo` into `resolveAccount` lets the resolver put\n * platform identifiers (ad_account_id, upstream token state) directly on the\n * resolved `TAccount` rather than re-resolving inside every handler.\n */\nexport interface ResolveAccountContext {\n /** The AdCP tool being called. */\n toolName: AdcpServerToolName;\n /**\n * Authentication info for the caller, populated from `extra.authInfo` on the\n * MCP request. Undefined when no `authenticate` is configured on `serve()`.\n */\n authInfo?: HandlerContext['authInfo'];\n /**\n * Resolved buyer agent (Phase 1 of #1269), when an `agentRegistry` is\n * configured on the server. Adopters whose `accounts.resolve` shape varies\n * with the buyer agent's commercial relationship (e.g., agency-mediated\n * vs. direct billing) read it here without re-resolving from `authInfo`.\n * Undefined when no registry is configured OR when the registry returned\n * null for the request's credential.\n */\n agent?: BuyerAgent;\n /**\n * Original tool arguments. Account resolvers that need request-scope\n * metadata for test overlays or dry-run/delete-missing behavior should read\n * it here rather than re-parsing transport envelopes.\n */\n input?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Narrow `ctx.sessionKey` from `string | undefined` to `string`. Use this in\n * handlers that require session scoping so you don't litter `!` assertions:\n *\n * ```ts\n * const sessionKey = requireSessionKey(ctx);\n * const sessionStore = scopedStore(ctx.store, sessionKey);\n * ```\n *\n * Throws a `SERVICE_UNAVAILABLE`-style error if `sessionKey` is missing — typically\n * meaning `resolveSessionKey` isn't configured or returned `undefined` for this tool.\n */\nexport function requireSessionKey<TAccount = unknown>(ctx: HandlerContext<TAccount>): string {\n if (ctx.sessionKey == null) {\n throw new Error(\n 'ctx.sessionKey is undefined. Configure resolveSessionKey on createAdcpServer, or guard per-tool before calling requireSessionKey.'\n );\n }\n return ctx.sessionKey;\n}\n\n// ---------------------------------------------------------------------------\n// Tool → type mapping (kept from v1 for type-level handler signatures)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-tool param / result / response types.\n *\n * `result` is the server-handler payload — normally the narrow success arm\n * consumed by the framework's response builders (`mediaBuyResponse`,\n * `syncCreativesResponse`, ...), plus a structured Error arm when the tool\n * supports returning one directly.\n * `response` is the full AdCP response union (Success | Error | Submitted).\n * Handlers can return either shape: adapter patterns that produce\n * `Result<FooResponse, ...>` now type-check without `as any`, and the\n * dispatcher narrows Error / Submitted arms at runtime so the response\n * builder only fires on the Success arm.\n */\nexport interface AdcpToolMap {\n list_products: {\n params: z.input<typeof ListProductsRequestSchema>;\n result: ServerPayload<ListProductsResponse>;\n response: ListProductsResponse;\n };\n request_proposals: {\n params: z.input<typeof RequestProposalsRequestSchema>;\n result: ServerPayload<RequestProposalsResponse>;\n response: RequestProposalsResponse;\n };\n refine_proposals: {\n params: RefineProposalsRequest;\n result: RefineProposalsResponse;\n response: RefineProposalsResponse;\n };\n decline_proposals: {\n params: z.input<typeof DeclineProposalsRequestSchema>;\n result: ServerPayload<DeclineProposalsResponse>;\n response: DeclineProposalsResponse;\n };\n buy_products: {\n params: z.input<typeof BuyProductsRequestSchema>;\n result: ServerPayload<BuyProductsResponse>;\n response: BuyProductsResponse;\n };\n accept_proposal: {\n params: z.input<typeof AcceptProposalRequestSchema>;\n result: ServerPayload<AcceptProposalResponse>;\n response: AcceptProposalResponse;\n };\n control_media_buy: {\n params: z.input<typeof ControlMediaBuyRequestSchema>;\n result: ServerPayload<ControlMediaBuyResponse>;\n response: ControlMediaBuyResponse;\n };\n get_products: {\n params: z.input<typeof GetProductsRequestSchema>;\n result: RequireCacheScopeWhenProducts<ServerPayload<GetProductsResponse>>;\n response: GetProductsResponse;\n };\n create_media_buy: {\n params: z.input<typeof CreateMediaBuyRequestSchema>;\n result: CreateMediaBuyServerPayload;\n response: CreateMediaBuyResponse;\n };\n update_media_buy: {\n params: z.input<typeof UpdateMediaBuyRequestSchema>;\n result: ServerPayload<UpdateMediaBuySuccess>;\n response: UpdateMediaBuyResponse;\n };\n get_media_buys: {\n params: z.input<typeof GetMediaBuysRequestSchema>;\n result: ServerPayload<GetMediaBuysResponse>;\n response: GetMediaBuysResponse;\n };\n get_media_buy_delivery: {\n params: z.input<typeof GetMediaBuyDeliveryRequestSchema>;\n result: ServerPayload<GetMediaBuyDeliveryResponse>;\n response: GetMediaBuyDeliveryResponse;\n };\n provide_performance_feedback: {\n params: z.input<typeof ProvidePerformanceFeedbackRequestSchema>;\n result: ServerPayload<ProvidePerformanceFeedbackSuccess>;\n response: ProvidePerformanceFeedbackResponse;\n };\n get_task_status: {\n params: z.input<typeof GetTaskStatusRequestSchema>;\n result: ServerPayload<GetTaskStatusResponse>;\n response: GetTaskStatusResponse;\n };\n list_tasks: {\n params: z.input<typeof ListTasksRequestSchema>;\n result: ServerPayload<ListTasksResponse>;\n response: ListTasksResponse;\n };\n sync_agent_notification_configs: {\n params: z.input<typeof SyncAgentNotificationConfigsRequestSchema>;\n result: ServerPayload<SyncAgentNotificationConfigsResponse>;\n response: SyncAgentNotificationConfigsResponse;\n };\n list_creative_formats: {\n params: z.input<typeof ListCreativeFormatsRequestSchema>;\n result: ServerPayload<ListCreativeFormatsResponse>;\n response: ListCreativeFormatsResponse;\n };\n list_transformers: {\n params: z.input<typeof ListTransformersRequestSchema>;\n result: ServerPayload<ListTransformersResponse>;\n response: ListTransformersResponse;\n };\n build_creative: {\n params: z.input<typeof BuildCreativeRequestSchema>;\n result: ServerPayload<BuildCreativeSuccess> | ServerPayload<BuildCreativeMultiSuccess>;\n response: BuildCreativeResponse;\n };\n preview_creative: {\n params: z.input<typeof PreviewCreativeRequestSchema>;\n result: ServerPayload<PreviewCreativeResponse>;\n response: PreviewCreativeResponse;\n };\n get_creative_delivery: {\n params: z.input<typeof GetCreativeDeliveryRequestSchema>;\n result: ServerPayload<GetCreativeDeliveryResponse>;\n response: GetCreativeDeliveryResponse;\n };\n list_creatives: {\n params: z.input<typeof ListCreativesRequestSchema>;\n result: ServerPayload<ListCreativesResponse>;\n response: ListCreativesResponse;\n };\n sync_creatives: {\n params: z.input<typeof SyncCreativesRequestSchema>;\n result: ServerPayload<SyncCreativesSuccess> | ServerPayload<SyncCreativesError>;\n response: SyncCreativesResponse;\n };\n get_signals: {\n params: z.input<typeof GetSignalsRequestSchema>;\n result: ServerPayload<GetSignalsResponse>;\n response: GetSignalsResponse;\n };\n activate_signal: {\n params: z.input<typeof ActivateSignalRequestSchema>;\n result: ServerPayload<ActivateSignalSuccess>;\n response: ActivateSignalResponse;\n };\n list_accounts: {\n params: z.input<typeof ListAccountsRequestSchema>;\n result: ServerPayload<ListAccountsResponse>;\n response: ListAccountsResponse;\n };\n sync_accounts: {\n params: z.input<typeof SyncAccountsRequestSchema>;\n result: ServerPayload<SyncAccountsSuccess>;\n response: SyncAccountsResponse;\n };\n sync_governance: {\n params: z.input<typeof SyncGovernanceRequestSchema>;\n result: ServerPayload<SyncGovernanceSuccess>;\n response: SyncGovernanceResponse;\n };\n get_account_financials: {\n params: z.input<typeof GetAccountFinancialsRequestSchema>;\n result: ServerPayload<GetAccountFinancialsSuccess>;\n response: GetAccountFinancialsResponse;\n };\n report_usage: {\n params: z.input<typeof ReportUsageRequestSchema>;\n result: ServerPayload<ReportUsageResponse>;\n response: ReportUsageResponse;\n };\n sync_event_sources: {\n params: z.input<typeof SyncEventSourcesRequestSchema>;\n result: ServerPayload<SyncEventSourcesSuccess>;\n response: SyncEventSourcesResponse;\n };\n log_event: {\n params: z.input<typeof LogEventRequestSchema>;\n result: ServerPayload<LogEventSuccess>;\n response: LogEventResponse;\n };\n sync_audiences: {\n params: z.input<typeof SyncAudiencesRequestSchema>;\n result: ServerPayload<SyncAudiencesSuccess>;\n response: SyncAudiencesResponse;\n };\n sync_catalogs: {\n params: z.input<typeof SyncCatalogsRequestSchema>;\n result: ServerPayload<SyncCatalogsSuccess>;\n response: SyncCatalogsResponse;\n };\n create_property_list: {\n params: z.input<typeof CreatePropertyListRequestSchema>;\n result: ServerPayload<CreatePropertyListResponse>;\n response: CreatePropertyListResponse;\n };\n update_property_list: {\n params: z.input<typeof UpdatePropertyListRequestSchema>;\n result: ServerPayload<UpdatePropertyListResponse>;\n response: UpdatePropertyListResponse;\n };\n get_property_list: {\n params: z.input<typeof GetPropertyListRequestSchema>;\n result: ServerPayload<GetPropertyListResponse>;\n response: GetPropertyListResponse;\n };\n list_property_lists: {\n params: z.input<typeof ListPropertyListsRequestSchema>;\n result: ServerPayload<ListPropertyListsResponse>;\n response: ListPropertyListsResponse;\n };\n delete_property_list: {\n params: z.input<typeof DeletePropertyListRequestSchema>;\n result: ServerPayload<DeletePropertyListResponse>;\n response: DeletePropertyListResponse;\n };\n create_collection_list: {\n params: z.input<typeof CreateCollectionListRequestSchema>;\n result: ServerPayload<CreateCollectionListResponse>;\n response: CreateCollectionListResponse;\n };\n update_collection_list: {\n params: z.input<typeof UpdateCollectionListRequestSchema>;\n result: ServerPayload<UpdateCollectionListResponse>;\n response: UpdateCollectionListResponse;\n };\n get_collection_list: {\n params: z.input<typeof GetCollectionListRequestSchema>;\n result: ServerPayload<GetCollectionListResponse>;\n response: GetCollectionListResponse;\n };\n list_collection_lists: {\n params: z.input<typeof ListCollectionListsRequestSchema>;\n result: ServerPayload<ListCollectionListsResponse>;\n response: ListCollectionListsResponse;\n };\n delete_collection_list: {\n params: z.input<typeof DeleteCollectionListRequestSchema>;\n result: ServerPayload<DeleteCollectionListResponse>;\n response: DeleteCollectionListResponse;\n };\n list_content_standards: {\n params: z.input<typeof ListContentStandardsRequestSchema>;\n result: ServerPayload<ListContentStandardsResponse>;\n response: ListContentStandardsResponse;\n };\n get_content_standards: {\n params: z.input<typeof GetContentStandardsRequestSchema>;\n result: ServerPayload<GetContentStandardsResponse>;\n response: GetContentStandardsResponse;\n };\n create_content_standards: {\n params: z.input<typeof CreateContentStandardsRequestSchema>;\n result: ServerPayload<CreateContentStandardsResponse>;\n response: CreateContentStandardsResponse;\n };\n update_content_standards: {\n params: z.input<typeof UpdateContentStandardsRequestSchema>;\n result: ServerPayload<UpdateContentStandardsResponse>;\n response: UpdateContentStandardsResponse;\n };\n calibrate_content: {\n params: z.input<typeof CalibrateContentRequestSchema>;\n result: ServerPayload<CalibrateContentResponse>;\n response: CalibrateContentResponse;\n };\n validate_content_delivery: {\n params: z.input<typeof ValidateContentDeliveryRequestSchema>;\n result: ServerPayload<ValidateContentDeliveryResponse>;\n response: ValidateContentDeliveryResponse;\n };\n get_media_buy_artifacts: {\n params: z.input<typeof GetMediaBuyArtifactsRequestSchema>;\n result: ServerPayload<GetMediaBuyArtifactsResponse>;\n response: GetMediaBuyArtifactsResponse;\n };\n get_creative_features: {\n params: z.input<typeof GetCreativeFeaturesRequestSchema>;\n result: ServerPayload<GetCreativeFeaturesResponse>;\n response: GetCreativeFeaturesResponse;\n };\n sync_plans: {\n params: z.input<typeof SyncPlansRequestSchema>;\n result: ServerPayload<SyncPlansResponse>;\n response: SyncPlansResponse;\n };\n check_governance: {\n params: z.input<typeof CheckGovernanceRequestSchema>;\n result: ServerPayload<CheckGovernanceResponse>;\n response: CheckGovernanceResponse;\n };\n report_plan_outcome: {\n params: z.input<typeof ReportPlanOutcomeRequestSchema>;\n result: ServerPayload<ReportPlanOutcomeResponse>;\n response: ReportPlanOutcomeResponse;\n };\n report_plan_adjustment: {\n params: z.input<typeof ReportPlanAdjustmentRequestSchema>;\n result: ServerPayload<ReportPlanAdjustmentResponse>;\n response: ReportPlanAdjustmentResponse;\n };\n get_plan_audit_logs: {\n params: z.input<typeof GetPlanAuditLogsRequestSchema>;\n result: ServerPayload<GetPlanAuditLogsResponse>;\n response: GetPlanAuditLogsResponse;\n };\n si_get_offering: {\n params: z.input<typeof SIGetOfferingRequestSchema>;\n result: ServerPayload<SIGetOfferingResponse>;\n response: SIGetOfferingResponse;\n };\n si_initiate_session: {\n params: z.input<typeof SIInitiateSessionRequestSchema>;\n result: ServerPayload<SIInitiateSessionResponse>;\n response: SIInitiateSessionResponse;\n };\n si_send_message: {\n params: z.input<typeof SISendMessageRequestSchema>;\n result: ServerPayload<SISendMessageResponse>;\n response: SISendMessageResponse;\n };\n si_terminate_session: {\n params: z.input<typeof SITerminateSessionRequestSchema>;\n result: ServerPayload<SITerminateSessionResponse>;\n response: SITerminateSessionResponse;\n };\n\n get_brand_identity: {\n params: z.input<typeof GetBrandIdentityRequestSchema>;\n result: ServerPayload<GetBrandIdentitySuccess>;\n response: GetBrandIdentitySuccess;\n };\n get_rights: {\n params: z.input<typeof GetRightsRequestSchema>;\n result: ServerPayload<GetRightsSuccess>;\n response: GetRightsSuccess;\n };\n acquire_rights: {\n params: z.input<typeof AcquireRightsRequestSchema>;\n result:\n | ServerPayload<AcquireRightsAcquired>\n | ServerPayload<AcquireRightsPendingApproval>\n | ServerPayload<AcquireRightsRejected>;\n response: AcquireRightsAcquired | AcquireRightsPendingApproval | AcquireRightsRejected;\n };\n update_rights: {\n params: z.input<typeof UpdateRightsRequestSchema>;\n result: ServerPayload<UpdateRightsSuccess>;\n response: UpdateRightsResponse;\n };\n}\n\nexport type AdcpServerToolName = keyof AdcpToolMap;\n\n/**\n * Parameter shape passed to `resolveIdempotencyPrincipal`. Wide enough to\n * carry any wire request (the framework calls every mutating tool through\n * the same resolver), narrow enough to surface the most-common scoping\n * fields (`account`, `brand`) using the canonical wire types.\n *\n * `account` and `brand` resolve to the same `AccountReference` /\n * `BrandReference` types the rest of the SDK uses. The\n * `account: AccountReference` discriminated union forces adopters scoping\n * by tenant to narrow before reading variant-specific fields:\n *\n * ```ts\n * resolveIdempotencyPrincipal: (ctx, params) => {\n * if (params.account && 'account_id' in params.account) {\n * return params.account.account_id; // narrowed to {account_id: string}\n * }\n * if (params.account?.brand?.domain) {\n * return `${params.account.brand.domain}:${params.account.operator}`;\n * }\n * return ctx.account?.id ?? 'anon';\n * }\n * ```\n *\n * Tool-specific scoping (e.g., custom session header on `si_send_message`)\n * still has the open `Record<string, unknown>` index signature for\n * everything else.\n */\nexport interface IdempotencyPrincipalParams extends Record<string, unknown> {\n /** Buyer-supplied account reference. Most mutating tools carry this. */\n account?: AccountReference;\n /** Buyer-supplied brand reference (used by some tools without account). */\n brand?: BrandReference;\n}\n\n// ---------------------------------------------------------------------------\n// Domain handler types\n// ---------------------------------------------------------------------------\n\n/** Handler that receives validated params and a resolved context.\n *\n * Return any of:\n * - The narrow Success arm (`result`) — framework applies the response builder.\n * - The full response union (`response` = Success | Error | Submitted) — the\n * dispatcher narrows Error / Submitted arms at runtime. Useful for adapters\n * that already produce a `Result<FooResponse, ...>` and don't want to\n * pre-narrow.\n * - A pre-formatted `McpToolResponse` (e.g. from `adcpError(...)`) — passed\n * through unchanged.\n */\ntype DomainHandler<K extends AdcpServerToolName, TAccount> = (\n params: AdcpToolMap[K]['params'],\n ctx: HandlerContext<TAccount>\n) => Promise<AdcpToolMap[K]['result'] | AdcpToolMap[K]['response'] | McpToolResponse>;\n\nexport interface MediaBuyHandlers<TAccount = unknown> {\n getProducts?: DomainHandler<'get_products', TAccount>;\n listProducts?: DomainHandler<'list_products', TAccount>;\n requestProposals?: DomainHandler<'request_proposals', TAccount>;\n declineProposals?: DomainHandler<'decline_proposals', TAccount>;\n buyProducts?: DomainHandler<'buy_products', TAccount>;\n acceptProposal?: DomainHandler<'accept_proposal', TAccount>;\n controlMediaBuy?: DomainHandler<'control_media_buy', TAccount>;\n createMediaBuy?: DomainHandler<'create_media_buy', TAccount>;\n updateMediaBuy?: DomainHandler<'update_media_buy', TAccount>;\n getMediaBuys?: DomainHandler<'get_media_buys', TAccount>;\n getMediaBuyDelivery?: DomainHandler<'get_media_buy_delivery', TAccount>;\n providePerformanceFeedback?: DomainHandler<'provide_performance_feedback', TAccount>;\n listCreativeFormats?: DomainHandler<'list_creative_formats', TAccount>;\n syncCreatives?: DomainHandler<'sync_creatives', TAccount>;\n listCreatives?: DomainHandler<'list_creatives', TAccount>;\n}\n\n/** First-class AdCP 3.2 proposal negotiation server seam. */\nexport interface ProposalNegotiationHandlers<TAccount = unknown> {\n /** Projected to `media_buy.proposal_refinement` during capability discovery. */\n capabilities: ProposalRefinementCapabilities;\n /** Resolve a stable tenant/account namespace from authenticated server context. */\n resolveScope: (ctx: HandlerContext<TAccount>) => MaybePromise<ProposalRefinementScope>;\n refineProposals: DomainHandler<'refine_proposals', TAccount>;\n}\n\nexport interface EventTrackingHandlers<TAccount = unknown> {\n syncEventSources?: DomainHandler<'sync_event_sources', TAccount>;\n logEvent?: DomainHandler<'log_event', TAccount>;\n syncAudiences?: DomainHandler<'sync_audiences', TAccount>;\n syncCatalogs?: DomainHandler<'sync_catalogs', TAccount>;\n}\n\nexport interface SignalsHandlers<TAccount = unknown> {\n getSignals?: DomainHandler<'get_signals', TAccount>;\n activateSignal?: DomainHandler<'activate_signal', TAccount>;\n}\n\nexport interface CreativeHandlers<TAccount = unknown> {\n listCreativeFormats?: DomainHandler<'list_creative_formats', TAccount>;\n listTransformers?: DomainHandler<'list_transformers', TAccount>;\n buildCreative?: DomainHandler<'build_creative', TAccount>;\n previewCreative?: DomainHandler<'preview_creative', TAccount>;\n listCreatives?: DomainHandler<'list_creatives', TAccount>;\n syncCreatives?: DomainHandler<'sync_creatives', TAccount>;\n getCreativeDelivery?: DomainHandler<'get_creative_delivery', TAccount>;\n}\n\nexport interface GovernanceHandlers<TAccount = unknown> {\n createPropertyList?: DomainHandler<'create_property_list', TAccount>;\n updatePropertyList?: DomainHandler<'update_property_list', TAccount>;\n getPropertyList?: DomainHandler<'get_property_list', TAccount>;\n listPropertyLists?: DomainHandler<'list_property_lists', TAccount>;\n deletePropertyList?: DomainHandler<'delete_property_list', TAccount>;\n createCollectionList?: DomainHandler<'create_collection_list', TAccount>;\n updateCollectionList?: DomainHandler<'update_collection_list', TAccount>;\n getCollectionList?: DomainHandler<'get_collection_list', TAccount>;\n listCollectionLists?: DomainHandler<'list_collection_lists', TAccount>;\n deleteCollectionList?: DomainHandler<'delete_collection_list', TAccount>;\n listContentStandards?: DomainHandler<'list_content_standards', TAccount>;\n getContentStandards?: DomainHandler<'get_content_standards', TAccount>;\n createContentStandards?: DomainHandler<'create_content_standards', TAccount>;\n updateContentStandards?: DomainHandler<'update_content_standards', TAccount>;\n calibrateContent?: DomainHandler<'calibrate_content', TAccount>;\n validateContentDelivery?: DomainHandler<'validate_content_delivery', TAccount>;\n getMediaBuyArtifacts?: DomainHandler<'get_media_buy_artifacts', TAccount>;\n getCreativeFeatures?: DomainHandler<'get_creative_features', TAccount>;\n syncPlans?: DomainHandler<'sync_plans', TAccount>;\n checkGovernance?: DomainHandler<'check_governance', TAccount>;\n reportPlanOutcome?: DomainHandler<'report_plan_outcome', TAccount>;\n /** Authorize and scope report_plan_adjustment to its tenant and plan owner. */\n resolveReportPlanAdjustmentScope?: (\n ctx: HandlerContext<TAccount>,\n params: AdcpToolMap['report_plan_adjustment']['params']\n ) => CallerMutationScope | Promise<CallerMutationScope>;\n reportPlanAdjustment?: DomainHandler<'report_plan_adjustment', TAccount>;\n getPlanAuditLogs?: DomainHandler<'get_plan_audit_logs', TAccount>;\n}\n\nexport interface ProtocolHandlers<TAccount = unknown> {\n /** Resolve the authenticated caller namespace used to isolate its subscriber set. */\n resolveScope?: (\n ctx: HandlerContext<TAccount>,\n params: AdcpToolMap['sync_agent_notification_configs']['params']\n ) => CallerMutationScope | Promise<CallerMutationScope>;\n syncAgentNotificationConfigs?: DomainHandler<'sync_agent_notification_configs', TAccount>;\n}\n\nexport interface AccountHandlers<TAccount = unknown> {\n listAccounts?: DomainHandler<'list_accounts', TAccount>;\n syncAccounts?: DomainHandler<'sync_accounts', TAccount>;\n syncGovernance?: DomainHandler<'sync_governance', TAccount>;\n getAccountFinancials?: DomainHandler<'get_account_financials', TAccount>;\n reportUsage?: DomainHandler<'report_usage', TAccount>;\n}\n\nexport interface SponsoredIntelligenceHandlers<TAccount = unknown> {\n getOffering?: DomainHandler<'si_get_offering', TAccount>;\n initiateSession?: DomainHandler<'si_initiate_session', TAccount>;\n sendMessage?: DomainHandler<'si_send_message', TAccount>;\n terminateSession?: DomainHandler<'si_terminate_session', TAccount>;\n}\n\n/**\n * Brand rights covers identity and licensing workflows.\n *\n * `update_rights` is a first-class mutating tool — modify an existing rights\n * grant (extend dates, adjust impression caps, change pricing, pause/resume).\n * Schemas published in AdCP 3.0.x; framework dispatch parallels\n * `acquire_rights`.\n *\n * `creative_approval` is intentionally NOT in this handler bag — the spec\n * models it as an HTTP webhook (the buyer POSTs to the `approval_webhook`\n * URL returned from `acquire_rights`), not as an MCP/A2A tool. Adopters\n * wire the receiver to `BrandRightsPlatform.reviewCreativeApproval` and\n * use `creativeApproved` / `creativeApprovalRejected` /\n * `creativeApprovalPendingReview` / `creativeApprovalError` from\n * `@adcp/sdk/server` to build the webhook response.\n */\nexport interface BrandRightsHandlers<TAccount = unknown> {\n getBrandIdentity?: DomainHandler<'get_brand_identity', TAccount>;\n getRights?: DomainHandler<'get_rights', TAccount>;\n acquireRights?: DomainHandler<'acquire_rights', TAccount>;\n updateRights?: DomainHandler<'update_rights', TAccount>;\n}\n\n// ---------------------------------------------------------------------------\n// Capabilities config\n// ---------------------------------------------------------------------------\n\nexport interface AdcpCapabilitiesConfig {\n major_versions?: number[];\n /**\n * Release-precision versions this seller supports (AdCP 3.1+ per spec PR\n * `adcontextprotocol/adcp#3493`). Each entry parses to a major via\n * `parseAdcpMajorVersion` — the union of these majors and `major_versions`\n * defines the seller's accepted set for the wire-level\n * `adcp_major_version` / `adcp_version` claim a buyer may carry.\n *\n * 3.0-pinned sellers can ignore this field. 3.1+ sellers should declare\n * here the same release-precision strings they emit in `adcp_version` on\n * responses, so buyers receiving `VERSION_UNSUPPORTED` can read the\n * supported set off the error envelope and downgrade their pin.\n */\n supported_versions?: string[];\n features?: Partial<MediaBuyFeatures>;\n account?: Partial<AccountCapabilities>;\n creative?: Partial<CreativeCapabilities>;\n extensions_supported?: readonly string[];\n /**\n * Vendor-namespaced extension capability data emitted at the top-level\n * `get_adcp_capabilities.ext` field. Each populated namespace should also\n * be listed in {@link extensions_supported}.\n */\n ext?: NonNullable<GetAdCPCapabilitiesResponse['ext']>;\n /**\n * RFC 9421 request-signing verifier capability. See\n * docs/building/implementation/security.mdx#signed-requests-transport-layer.\n * Emitted verbatim in `get_adcp_capabilities.request_signing`. Omit unless\n * the agent actually verifies incoming signatures — a `supported: true`\n * claim without a working verifier is graded as FAIL by the conformance\n * runner (see `@adcp/sdk/testing/storyboard/request-signing`).\n */\n request_signing?: NonNullable<GetAdCPCapabilitiesResponse['request_signing']>;\n /**\n * Specialism claims the agent supports. Each entry maps to a storyboard\n * bundle under `/compliance/{version}/specialisms/{id}/`; the AAO\n * compliance runner executes the matching storyboards to verify. Only\n * list specialisms the agent actually implements.\n */\n specialisms?: NonNullable<GetAdCPCapabilitiesResponse['specialisms']>;\n /**\n * @deprecated Idempotency capability data is derived exclusively from\n * the active `idempotency` store. This legacy override is ignored so an\n * unwired or mismatched store can never be advertised to buyers.\n */\n idempotency?: {\n replay_ttl_seconds?: number;\n };\n /** Freshness and notification support for the capability document. */\n capability_changes?: NonNullable<GetAdCPCapabilitiesResponse['adcp']['capability_changes']>;\n portfolio?: {\n publisher_domains: string[];\n primary_channels?: MediaChannel[];\n primary_countries?: string[];\n description?: string;\n advertising_policies?: string;\n };\n /**\n * Per-domain capability blocks deep-merged on top of the framework's\n * auto-derived response. Use when you need to surface fields the top-level\n * `AdcpCapabilitiesConfig` doesn't model — execution.targeting,\n * audience_targeting, content_standards channels, conversion_tracking\n * identifier types, compliance_testing scenarios, etc.\n *\n * Deep-merge semantics:\n * - nested objects merge recursively;\n * - arrays REPLACE (not concat) so callers stay in control of cardinality;\n * - primitive overrides replace the auto-derived value.\n *\n * Top-level fields the framework owns (`adcp`, `supported_protocols`,\n * `specialisms`, `extensions_supported`, `ext`) are not accepted here — configure\n * them via their dedicated fields on {@link AdcpCapabilitiesConfig}.\n */\n overrides?: AdcpCapabilitiesOverrides;\n}\n\n/**\n * Per-domain capability overrides. See {@link AdcpCapabilitiesConfig.overrides}.\n *\n * Each field accepts the same shape as the corresponding block on\n * {@link GetAdCPCapabilitiesResponse}. A value of `null` explicitly removes\n * the auto-derived block; `undefined` (omission) is a no-op.\n *\n * **Values must be JSON-serializable plain objects.** Class instances, `Date`,\n * `Map`, `Set`, or any value with a non-`Object.prototype` prototype are\n * treated as opaque leaves and replace their target rather than merging.\n */\nexport interface AdcpCapabilitiesOverrides {\n media_buy?: Partial<NonNullable<GetAdCPCapabilitiesResponse['media_buy']>> | null;\n creative?: Partial<NonNullable<GetAdCPCapabilitiesResponse['creative']>> | null;\n signals?: Partial<NonNullable<GetAdCPCapabilitiesResponse['signals']>> | null;\n governance?: Partial<NonNullable<GetAdCPCapabilitiesResponse['governance']>> | null;\n brand?: Partial<NonNullable<GetAdCPCapabilitiesResponse['brand']>> | null;\n sponsored_intelligence?: Partial<NonNullable<GetAdCPCapabilitiesResponse['sponsored_intelligence']>> | null;\n measurement?: Partial<NonNullable<GetAdCPCapabilitiesResponse['measurement']>> | null;\n experimental_features?: GetAdCPCapabilitiesResponse['experimental_features'] | null;\n account?: Partial<NonNullable<GetAdCPCapabilitiesResponse['account']>> | null;\n compliance_testing?: GetAdCPCapabilitiesResponse['compliance_testing'] | null;\n webhook_signing?: GetAdCPCapabilitiesResponse['webhook_signing'] | null;\n identity?: GetAdCPCapabilitiesResponse['identity'] | null;\n request_signing?: GetAdCPCapabilitiesResponse['request_signing'] | null;\n}\n\n// ---------------------------------------------------------------------------\n// Signed-requests auto-wiring\n// ---------------------------------------------------------------------------\n\n/**\n * Inputs for the auto-wired RFC 9421 request-signature verifier. When set on\n * {@link AdcpServerConfig}, `createAdcpServer` builds an Express-shaped\n * verifier middleware and attaches it to the returned `McpServer` via\n * {@link ADCP_PRE_TRANSPORT}. `serve()` discovers the attached middleware and\n * mounts it as the transport-layer `preTransport` hook, so every inbound MCP\n * request passes the verifier before reaching the JSON-RPC router.\n *\n * A seller wiring this config MUST also publish a buyer-visible discovery\n * surface in `capabilities`, one of:\n *\n * - **3.1+ canonical (recommended):** set\n * `capabilities.request_signing.supported: true`. Buyers learn the agent\n * verifies signatures from `get_adcp_capabilities`; no deprecated specialism\n * claim required. The universal `signed_requests` storyboard grades on this\n * signal alone.\n * - **Back-compat:** add `'signed-requests'` to `capabilities.specialisms`.\n * The 3.0-era enum value is preserved through the AdCP 4.0 deprecation cycle\n * (adcp#3075); when this path is taken the runner emits\n * `signed_requests_specialism_deprecated` (adcp-client#2082, adcp#4796).\n *\n * `createAdcpServer` throws at construction time when `signedRequests` is set\n * but neither discovery surface is declared, closing the footgun where the\n * verifier silently rejects every signed request from buyers who never learned\n * to sign. The inverse (specialism or capability declared without a\n * `signedRequests` config) is logged loudly but not thrown — legacy servers\n * that hand-build the middleware via `serve({ preTransport })` stay\n * conformant.\n *\n * `jwks`, `replayStore`, and `revocationStore` should be hoisted outside\n * the agent factory so a single verifier instance serves every request —\n * otherwise each request would build a fresh replay store and the rate-\n * abuse / replay-detection guards would be per-request (i.e. broken).\n */\nexport interface SignedRequestsConfig {\n /** Resolves verification keys by `keyid`. */\n jwks: JwksResolver;\n /** Stores `(keyid, signature-bytes, expires)` tuples for replay detection. */\n replayStore: ReplayStore;\n /** Consulted for revoked `kid` / `jti` before accepting a signature. */\n revocationStore: RevocationStore;\n /**\n * Operation names that MUST arrive signed. Defaults to every statically\n * mutating AdCP tool (per the framework's {@link MUTATING_TASKS}) plus\n * `get_products`, whose AdCP 3.2 proposal-finalize variant is state-changing.\n * Because signing policy is advertised at tool granularity, enabling that\n * protection also requires signatures on ordinary `get_products` reads.\n */\n required_for?: string[];\n /**\n * JSON-RPC protocol method names that MUST arrive signed. Separate from\n * AdCP tool names in `required_for`; examples include `tasks/cancel`.\n */\n protocol_methods_required_for?: string[];\n /** Defaults to `required` on 3.2 and `either` on legacy endpoints. */\n covers_content_digest?: ContentDigestPolicy;\n /**\n * Resolve the `agent_url` claim the verifier stamps on successful results.\n * Useful when a single seller hosts multiple brands and the buyer's\n * signing key is scoped to a brand identifier rather than the root.\n */\n agentUrlForKeyid?: (keyid: string) => string | undefined;\n /**\n * Shape the signer identity exposed to handlers. The framework attaches a\n * branded `http_sig` credential when `agentUrlForKeyid` resolves, unless\n * this callback explicitly supplies another credential. When `serve()` also\n * authenticates the request, this callback must resolve the signer to that\n * same authenticated principal or the request is rejected.\n */\n makePrincipal?: (signer: import('../signing/types').VerifiedSigner) => AuthPrincipal;\n}\n\n/**\n * Symbol under which `createAdcpServer` attaches the auto-wired `preTransport`\n * function to the returned `McpServer`. `serve()` reads this symbol to mount\n * the verifier. Consumers typically don't need to touch it; it's exported for\n * tests and for downstream frameworks that want the same wiring.\n */\nexport const ADCP_PRE_TRANSPORT: unique symbol = Symbol.for('@adcp/client.preTransport');\n\n/**\n * Per-request canonical endpoint scope stamped by `serve()` on the underlying\n * SDK server while it dispatches a request. Internal transport contract; it\n * is intentionally independent of authentication so anonymous deployments\n * receive the same multi-host idempotency isolation.\n */\nexport const ADCP_SERVE_IDEMPOTENCY_SCOPE: unique symbol = Symbol.for('@adcp/client.serveIdempotencyScope');\n\n/**\n * Diagnostic snapshot of the signed-requests wiring on a returned server.\n * Read via `server[ADCP_SIGNED_REQUESTS_STATE]` so integration tests and\n * operator boot diagnostics can assert on the claim/config pairing without\n * parsing log output. Populated on every `createAdcpServer` call.\n */\nexport interface AdcpSignedRequestsState {\n /** True when `signedRequests: {...}` was passed and the verifier is auto-wired. */\n autoWired: boolean;\n /** True when `capabilities.specialisms` includes `'signed-requests'`. */\n specialismClaimed: boolean;\n /** True when `capabilities.request_signing.supported === true`. */\n capabilitySupported: boolean;\n /**\n * Non-fatal mismatch state. `'ok'` when wiring + claim + supported are\n * all aligned (or all off); `'claim_without_config'` when the claim is\n * set but no `signedRequests` config was passed (legacy manual\n * `serve({ preTransport })` path — logged but not thrown).\n */\n mismatch: 'ok' | 'claim_without_config';\n}\n\n/**\n * Symbol under which `createAdcpServer` attaches the `AdcpSignedRequestsState`\n * snapshot. Use `server[ADCP_SIGNED_REQUESTS_STATE]` to inspect wiring from\n * tests or boot diagnostics.\n */\nexport const ADCP_SIGNED_REQUESTS_STATE: unique symbol = Symbol.for('@adcp/client.signedRequestsState');\n\n/**\n * Symbol marking that a server's `instructions` was supplied as a function\n * (lazy / per-session form) rather than a static string. `serve()` reads\n * this to refuse `reuseAgent: true` — the function is captured once at\n * construction and would not re-evaluate per session under server reuse.\n *\n * Internal contract between `createAdcpServer` and `serve()`. Adopters\n * who instantiate `McpServer` directly (without `createAdcpServer`) and\n * want their own marker semantics should not import this symbol.\n */\nexport const ADCP_INSTRUCTIONS_FN: unique symbol = Symbol.for('@adcp/client.instructionsFn');\n\n/**\n * Resolve function-form instructions for transports without a legacy\n * `initialize` handshake (notably MCP 2026-07-28). Internal contract between\n * `createAdcpServer` and transport adapters.\n */\nexport const ADCP_INSTRUCTIONS_RESOLVER: unique symbol = Symbol.for('@adcp/client.instructionsResolver');\n\n/**\n * Pre-resolution session context passed to a function-form `instructions`.\n * Slim by design — no `account` (resolution hasn't run yet at MCP `initialize`\n * time, which is the natural eval moment for per-session instructions).\n *\n * Both fields are reserved: today they are always `undefined` because the\n * framework's `serve()` does not yet plumb auth + registry state into the\n * factory before MCP `initialize`. Adopters who need tenant identity should\n * use closures captured in their factory's HTTP-scoped state. The shape is\n * forward-compatible: when the framework wires authInfo/agent through, the\n * fields will populate without breaking existing function bodies.\n *\n * @see AdcpServerConfig.instructions\n * @public\n */\nexport interface SessionContext {\n /**\n * @reserved Always `undefined` in v6.x. The framework does not yet plumb\n * `authInfo` into the factory before MCP `initialize` — use closures\n * captured in your factory's HTTP-scoped state for tenant identity today.\n * Forward-compatible: when the framework wires this through, your\n * `ctx.authInfo?.…` reads start returning real values without breaking\n * existing function bodies.\n */\n readonly authInfo?: ResolvedAuthInfo;\n\n /**\n * @reserved Always `undefined` in v6.x. The framework does not yet plumb\n * the resolved `BuyerAgent` into the factory before MCP `initialize` —\n * use closures captured in your factory's HTTP-scoped state for tenant\n * identity today. Forward-compatible: when the framework wires this\n * through, your `ctx.agent?.…` reads start returning real values without\n * breaking existing function bodies.\n */\n readonly agent?: BuyerAgent;\n}\n\n/**\n * Behavior when a function-form `instructions` callback throws or its\n * returned Promise rejects.\n *\n * - `'skip'` (default) — log server-side, treat as `undefined` (no\n * instructions). Right for prose-of-flavor (brand manifests, marketing\n * copy) where a registry fetch failure must not kill the buyer's session.\n * - `'fail'` — rethrow (sync) / re-reject (async). The MCP `initialize`\n * handshake then fails at the transport layer (this is NOT an\n * `adcp_error` envelope — it kills the session). Right for adopters\n * whose instructions carry load-bearing policy where stale/missing\n * guidance is worse than a connection retry.\n *\n * @public\n */\nexport type OnInstructionsError = 'skip' | 'fail';\n\n/**\n * A value that is either `T` directly or a `Promise<T>`.\n *\n * Used in callback signatures that support both synchronous and asynchronous\n * returns (e.g. `instructions`), so adopters can return either a plain\n * string or an `async` function without separate overloads.\n *\n * @public\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Shape of the preTransport function attached by `createAdcpServer` when\n * `signedRequests` is configured. Returns `true` if the middleware has already\n * sent a response (e.g., 401 on verification failure), `false` to continue\n * into MCP dispatch.\n */\nexport type AdcpPreTransport = (\n req: import('http').IncomingMessage & { rawBody?: string },\n res: import('http').ServerResponse\n) => Promise<boolean>;\n\n// ---------------------------------------------------------------------------\n// Custom tool config\n// ---------------------------------------------------------------------------\n\n/** UI hints for a custom tool backed by an MCP App. */\nexport interface McpAppUiMeta {\n /** URI of the MCP App resource rendered when the tool is invoked. */\n resourceUri?: string;\n /** Audiences a compliant host exposes the tool to. Routing metadata, not authorization. */\n visibility?: Array<'model' | 'app'>;\n}\n\n/** Typed MCP App metadata forwarded unchanged in `tools/list`. */\nexport interface McpAppMeta {\n ui?: McpAppUiMeta;\n}\n\n/**\n * The active AdCP 3.2 media-buy MCP catalog.\n *\n * Deprecated compatibility entry points such as `get_products`,\n * `create_media_buy`, and `update_media_buy` are deliberately absent. A\n * server may still keep those tools callable for older buyers while\n * advertising this compact surface to new MCP clients.\n *\n * @public\n */\nexport const MEDIA_BUY_MCP_TOOL_PROFILE = [\n 'accept_proposal',\n 'buy_products',\n 'control_media_buy',\n 'decline_proposals',\n 'get_account_financials',\n 'get_adcp_capabilities',\n 'get_media_buy_delivery',\n 'get_media_buys',\n 'get_task_status',\n 'list_accounts',\n 'list_creatives',\n 'list_products',\n 'list_tasks',\n 'log_event',\n 'provide_performance_feedback',\n 'refine_proposals',\n 'report_usage',\n 'request_proposals',\n 'sync_accounts',\n 'sync_agent_notification_configs',\n 'sync_audiences',\n 'sync_catalogs',\n 'sync_creatives',\n 'sync_event_sources',\n 'sync_governance',\n] as const;\n\nexport type AdcpMcpToolProfile = 'auto' | 'media-buy' | 'all';\n\n/**\n * Declarative registration for a tool outside {@link AdcpToolMap} — seller\n * extensions (e.g. collection-list helpers), test-harness endpoints\n * (`comply_test_controller`), or AdCP surfaces whose JSON Schemas haven't\n * landed in the framework yet.\n *\n * These tools **bypass the framework's spec-tool pipeline**:\n * idempotency middleware, governance pre-checks, account resolution,\n * and response wrapping are all skipped. The handler receives the\n * SDK-validated arguments and must return a `CallToolResult` directly.\n * If you need any of those behaviors, call the framework helpers from\n * inside the handler (e.g., `checkGovernance(...)`, `adcpError(...)`).\n *\n * Type parameters match the SDK's `McpServer.registerTool` signature so\n * argument and response types infer from the declared schemas.\n */\nexport interface AdcpCustomToolConfig<\n InputArgs extends undefined | ZodRawShapeCompat | AnySchema = undefined,\n OutputArgs extends ZodRawShapeCompat | AnySchema | undefined = undefined,\n> {\n /** Human-readable description — surfaced in `tools/list`. */\n description?: string;\n /** Optional title hint for the MCP inspector. */\n title?: string;\n /** Zod raw shape or schema for argument validation. */\n inputSchema?: InputArgs;\n /**\n * Zod raw shape or schema for the declared response payload.\n *\n * Forwarded verbatim to `registerTool`. The MCP SDK validates every\n * non-error response's `structuredContent` against this schema on the\n * server AND on the buyer's client (the latter fires regardless of\n * `isError` — see the `NOTE on outputSchema` block earlier in this\n * file). Framework-registered AdCP tools skip this field for that\n * reason; custom tools opt in here and own the trade-off.\n *\n * Footgun: a too-strict schema (e.g. `z.never()`, or one that\n * accidentally rejects the caller's own valid shape) turns the tool\n * into a silent client-side validation error for every buyer. The\n * seller sees a successful response go out; the buyer receives an\n * `Output validation error`. Test against a real buyer call before\n * relying on this.\n */\n outputSchema?: OutputArgs;\n /** Tool annotations (readOnlyHint / destructiveHint / idempotentHint / openWorldHint). */\n annotations?: ToolAnnotations;\n /** Portable MCP App metadata surfaced unchanged in `tools/list`. */\n _meta?: McpAppMeta;\n /**\n * Tool handler. Gets SDK-validated `args` based on `inputSchema` and\n * must return a `CallToolResult`. Use `capabilitiesResponse`,\n * `mediaBuyResponse`, `adcpError`, or a hand-built `{ content, structuredContent? }`.\n */\n handler: ToolCallback<InputArgs>;\n}\n\n// ---------------------------------------------------------------------------\n// Server config\n// ---------------------------------------------------------------------------\n\n/**\n * Public shape for the `webhooks` option on {@link AdcpServerConfig}.\n * Concrete name + export so adopters can write `webhooks: WebhooksConfig`\n * without reaching for a `Pick<WebhookEmitterOptions, ...>` reproduction\n * (and without falling back to `as any` when they typed it loosely).\n *\n * Subset of {@link WebhookEmitterOptions} the framework lifts to the\n * server config: signing key/provider, retry policy, immutable delivery\n * store, fetch override, user-agent + tag, and the per-emit observability\n * hooks. Other emitter-internal knobs (rate limits, transport pool\n * sizing) stay on `WebhookEmitterOptions` for direct emitter callers.\n *\n * @public\n */\nexport type WebhooksConfig = Pick<\n WebhookEmitterOptions,\n | 'signerKey'\n | 'signerProvider'\n | 'retries'\n | 'deliveryStore'\n | 'idempotencyKeyStore'\n | 'deliveryRetryHorizonSeconds'\n | 'deliveryRecovery'\n | 'generateIdempotencyKey'\n | 'fetch'\n | 'userAgent'\n | 'tag'\n> & {\n /** Stable publisher namespace for shared delivery-store keys. Defaults to the trusted server name. */\n publisherScope?: string;\n /** Trusted fallback namespace for a genuinely single-tenant server. */\n tenantScope?: string;\n /** Observability: emitter-wide onAttempt hook. */\n onAttempt?: WebhookEmitterOptions['onAttempt'];\n /** Observability: emitter-wide onAttemptResult hook. */\n onAttemptResult?: WebhookEmitterOptions['onAttemptResult'];\n};\n\nexport interface AdcpServerConfig<TAccount = unknown> {\n name: string;\n version: string;\n\n /**\n * Controls the tools advertised by MCP `tools/list` without removing\n * compatibility call routes.\n *\n * - `auto` (default): a 3.2 server with any compact media-buy lifecycle\n * handler advertises the spec's active `media-buy` profile.\n * - `media-buy`: always advertise the intersection of registered tools and\n * the active 3.2 media-buy profile.\n * - `all`: advertise every registered tool, including deprecated aliases.\n *\n * This is a discovery filter, not an authorization boundary. In `auto` and\n * `media-buy` modes, registered legacy tools remain callable so 3.0/3.1\n * buyers that already know their tool names continue to work.\n */\n mcpToolProfile?: AdcpMcpToolProfile;\n\n /**\n * Require framework-resolved account context on compact lifecycle\n * mutations before replay lookup. Enabled by the decisioning-platform\n * adapter; raw-handler adopters can retain their own scope resolver during\n * the compatibility window.\n *\n * @internal\n */\n requireCompactMutationAccountScope?: boolean;\n\n /**\n * Expose generated top-level AdCP request shapes in MCP `tools/list`.\n *\n * Defaults to `false`, preserving the long-standing passthrough schema so\n * the framework AJV validator remains the only validation gate shared by\n * MCP and A2A. Set to `true` when generic MCP clients need argument hints\n * from `tools/list`; known AdCP tools use shallow key hints derived from\n * `TOOL_INPUT_SHAPES` and unknown/custom framework surfaces fall back to\n * passthrough.\n */\n exposeToolSchemas?: boolean;\n\n /**\n * AdCP protocol version this server speaks. Defaults to {@link ADCP_VERSION}\n * — the GA version the SDK ships against. Override to pin to an older\n * stable (e.g., `'3.0.0'`) or opt into a beta channel (`'3.1.0-beta.1'`)\n * once that registry ships.\n *\n * Not the same as `version` (the publisher's app version, e.g., `'1.4.2'`).\n *\n * Stage 2 plumbs the option through and validates it at construction\n * time; cross-major pins (e.g. `'4.0.0-beta.1'` while the SDK ships\n * against major 3) throw `ConfigurationError`. Stage 3 wires per-instance\n * schema/validator selection off this field.\n *\n * Typed as `AdcpVersion | (string & {})` so editors autocomplete\n * canonical values from {@link COMPATIBLE_ADCP_VERSIONS} while still\n * accepting forward-compatible strings.\n */\n adcpVersion?: AdcpVersion | (string & {});\n\n /**\n * Resolve an account from an AccountReference.\n * Called on every request that has an `account` field.\n * Return null if the account doesn't exist — framework responds ACCOUNT_NOT_FOUND.\n *\n * The second argument carries the AdCP `toolName` and, when `serve()` is\n * configured with `authenticate`, the caller's `authInfo`. Adapters that\n * need the caller's upstream platform token to look up the account can\n * read it from `ctx.authInfo` here and attach anything they want to the\n * resolved account.\n *\n * Single-argument resolvers (`async (ref) => ...`) are valid — TypeScript\n * allows a shorter parameter list.\n *\n * **Do not persist `authInfo` outside the returned account object.** The\n * framework makes no isolation guarantees about values closed over by the\n * resolver; caching `authInfo` into shared state can leak the caller's\n * principal across requests.\n */\n resolveAccount?: (ref: AccountReference, ctx: ResolveAccountContext) => Promise<TAccount | null>;\n\n /**\n * Resolve an account when the wire request doesn't carry one.\n *\n * For tools whose request schema lacks an `account` field\n * (`provide_performance_feedback`, `list_creative_formats`, the\n * `tasks/get` polling path, etc.), the framework can't extract a wire\n * ref. When this resolver is configured, the framework calls it with the\n * caller's `authInfo` instead so single-tenant agents (`resolution: 'derived'`)\n * and principal-keyed agents (`resolution: 'implicit'`) still get a\n * tenant-scoped `ctx.account`.\n *\n * Returns `null` when no account can be derived. The handler then runs\n * with `ctx.account` undefined — appropriate for tools that legitimately\n * don't need tenant scoping (publisher-wide format catalogs).\n */\n resolveAccountFromAuth?: (ctx: ResolveAccountContext) => Promise<TAccount | null>;\n\n /**\n * Buyer-agent identity registry. Optional. When\n * configured, framework calls `agentRegistry.resolve(authInfo)` once per\n * request after `authInfo` is populated and before `resolveAccount`. The\n * resolved {@link BuyerAgent} is threaded through `ctx.agent` to\n * `resolveAccount`, `resolveAccountFromAuth`, `resolveSessionKey`, and\n * the specialism handlers.\n *\n * Adopters construct via {@link BuyerAgentRegistry.signingOnly},\n * {@link BuyerAgentRegistry.bearerOnly}, or {@link BuyerAgentRegistry.mixed}.\n * When omitted, `ctx.agent` stays `undefined` and the framework's request\n * flow is unchanged — strict opt-in.\n *\n * Behavior:\n * - Registry returns a `BuyerAgent` → framework freezes the record (and\n * its `billing_capabilities` Set) and sets `ctx.agent`.\n * - Registry returns `null` → `ctx.agent` stays undefined; dispatch\n * continues. For `sync_accounts.billing`, an unresolved agent under a\n * configured registry gets the oracle-safe `BILLING_NOT_SUPPORTED`\n * surface rather than `BILLING_NOT_PERMITTED_FOR_AGENT`.\n * - Registry throws → framework returns `SERVICE_UNAVAILABLE`. Inner\n * error logged server-side.\n *\n * Resolved records drive status/sandbox enforcement and\n * `sync_accounts.billing` capability gates.\n */\n agentRegistry?: BuyerAgentRegistry;\n\n /**\n * Derive a session-scoping key from the request. Populates `ctx.sessionKey`\n * so handlers don't re-implement key derivation (tenant, brand, publisher\n * account id, etc.). Called after `resolveAccount`, so the resolved account\n * is available.\n *\n * Return `undefined` to leave `ctx.sessionKey` unset (e.g., for anonymous\n * or public tools).\n */\n resolveSessionKey?: (ctx: SessionKeyContext<TAccount>) => string | undefined | Promise<string | undefined>;\n\n /**\n * When `true`, framework-produced `SERVICE_UNAVAILABLE` errors include the\n * underlying `err.message` in `details.reason` (helpful in dev, but can leak\n * DB driver messages, file paths, or schema info to remote callers).\n *\n * Defaults:\n * - `NODE_ENV === 'production'` → `false` (safe default for live agents).\n * - Otherwise → `true` (dev/test/CI surface the cause chain so\n * `SERVICE_UNAVAILABLE: encountered an internal error` becomes\n * `SERVICE_UNAVAILABLE: Cannot find module '@adcp/sdk/foo'`.\n * Matrix runs spent weeks on opaque SU errors before this default flipped).\n *\n * Explicit `exposeErrorDetails: true | false` always wins.\n */\n exposeErrorDetails?: boolean;\n\n /** Logger for framework decisions. Defaults to no-op. */\n logger?: AdcpLogger;\n\n /**\n * State store for persisting domain objects across requests.\n * Defaults to InMemoryStateStore. Use PostgresStateStore for production.\n */\n stateStore?: AdcpStateStore;\n\n /**\n * Task registry for async task lifecycle records.\n *\n * Usually supplied by `createAdcpServerFromPlatform`; low-level callers\n * only need this when they want `compliance.reset()` to flush in-memory\n * task records between repeated test runs.\n */\n taskRegistry?: TaskRegistry;\n\n // Domain handler groups — register only what you support\n mediaBuy?: MediaBuyHandlers<TAccount>;\n proposalNegotiation?: ProposalNegotiationHandlers<TAccount>;\n signals?: SignalsHandlers<TAccount>;\n creative?: CreativeHandlers<TAccount>;\n governance?: GovernanceHandlers<TAccount>;\n protocol?: ProtocolHandlers<TAccount>;\n accounts?: AccountHandlers<TAccount>;\n eventTracking?: EventTrackingHandlers<TAccount>;\n sponsoredIntelligence?: SponsoredIntelligenceHandlers<TAccount>;\n brandRights?: BrandRightsHandlers<TAccount>;\n\n /** Explicit capabilities overrides (merged on top of auto-detected). */\n capabilities?: AdcpCapabilitiesConfig;\n /**\n * Idempotency store for mutating requests. When configured, the framework:\n *\n * - Requires `idempotency_key` on every mutating request (returns\n * `INVALID_REQUEST` when missing)\n * - Replays the cached response for matching `(principal, key, payload)`\n * and injects `replayed: true` on the envelope\n * - Returns `IDEMPOTENCY_CONFLICT` for same-key-different-payload\n * - Returns `IDEMPOTENCY_EXPIRED` when the key is past the TTL\n * - Declares `adcp.idempotency.replay_ttl_seconds` on `get_adcp_capabilities`\n *\n * Scoping: by default uses `ctx.sessionKey` as the principal. Override\n * via `resolveIdempotencyPrincipal`.\n *\n * Pass the literal string `'disabled'` to suppress idempotency\n * enforcement end-to-end: schema validation tolerates a missing\n * `idempotency_key` on mutating tools, the replay/conflict middleware\n * is skipped, and the missing-store guardrail log is silenced. Intended\n * for non-production test fleets that don't model idempotency replay\n * — production servers should always wire a real store. The framework\n * logs an info-level warning at construction when this mode is used\n * outside `NODE_ENV=test` so the choice is visible.\n */\n idempotency?: IdempotencyStore | 'disabled';\n /**\n * Derive the idempotency principal from the handler context, the\n * request params, and the tool name. Defaults to `ctx.sessionKey`. Two\n * buyers that share a sessionKey would share cache entries — if that's\n * not what you want, return something more specific (e.g., an\n * operator_id) from this hook.\n *\n * Receives `params` and `toolName` so callers can fold request-shape\n * identity into the principal when needed (e.g., scoping by a custom\n * tenant header). For per-session scoping (`si_send_message`), the\n * framework already folds `params.session_id` into the scope tuple —\n * the principal is still the authenticated buyer.\n */\n resolveIdempotencyPrincipal?: (\n ctx: HandlerContext<TAccount>,\n params: IdempotencyPrincipalParams,\n toolName: AdcpServerToolName\n ) => string | undefined;\n /**\n * Server-level prose surfaced on MCP `initialize`. Two forms:\n *\n * 1. **Static string** (the historical form) — captured at construction,\n * same value for every session.\n * 2. **Function** `(ctx: SessionContext) => string | undefined` — re-evaluated\n * each time `createAdcpServer` is called. Under the canonical\n * `serve({ reuseAgent: false })` flow (the default) the factory\n * runs per HTTP request, which under streamable-HTTP MCP is per\n * session — so the closure can surface tenant-shaped prose (per-buyer\n * brand manifests, storefront copy, \"premium vs standard\" partner\n * guidance).\n *\n * **Eval moment.** Strictly: once per `createAdcpServer` invocation.\n * `serve({ reuseAgent: false })` makes that \"per HTTP request, which is\n * per session for streamable-HTTP MCP.\" Custom transports / hand-rolled\n * dispatch must invoke `createAdcpServer` per session themselves to\n * preserve the per-session semantic. `reuseAgent: true` would fire the\n * function once for the lifetime of the shared agent — which defeats\n * the purpose, so `serve()` refuses that combination at the first\n * request.\n *\n * **`SessionContext` is reserved.** `authInfo` and `agent` are typed for\n * forward compatibility but currently always `undefined` — the framework\n * does not yet plumb auth/registry state into the factory. **Use closures\n * captured in your factory's HTTP-scoped state for tenant identity today;\n * `ctx.agent`/`ctx.authInfo` reads silently return `undefined` and ship\n * empty prose to prod.** The function body will pick up populated fields\n * when the framework wires them through.\n *\n * @example Per-tenant prose via factory closure (recommended pattern):\n * ```ts\n * serve(({ taskStore, host }) => createAdcpServer({\n * // host is HTTP-scoped — captured in the closure, NOT from ctx.\n * instructions: () => brandManifests.get(host)?.intro ?? defaultProse,\n * // ... rest of config\n * }));\n * ```\n *\n * **Async functions are supported.** The framework awaits the returned\n * Promise during MCP `initialize` — the session does not proceed until\n * the promise settles. A slow fetch adds session-establishment latency,\n * not per-tool latency; add a timeout inside your function if needed\n * (e.g. `Promise.race([fetchProse(), timeout(2000)])`). A rejected\n * promise is governed by `onInstructionsError`: `'skip'` (default) logs\n * and sends no instructions; `'fail'` causes the `initialize` handshake\n * to fail, dropping the session.\n *\n * @see SessionContext\n * @see onInstructionsError\n */\n instructions?: string | ((ctx: SessionContext) => MaybePromise<string | undefined>);\n /**\n * Behavior when a function-form `instructions` callback throws. Defaults\n * to `'skip'` — best-effort prose (brand manifests, marketing copy)\n * should not kill the buyer's session on a registry fetch failure.\n * Set `'fail'` for adopters whose instructions carry load-bearing\n * policy. See {@link OnInstructionsError}.\n */\n onInstructionsError?: OnInstructionsError;\n taskStore?: TaskStore;\n taskMessageQueue?: TaskMessageQueue;\n /**\n * Webhook-emission config. When set, `ctx.emitWebhook` is populated on\n * every handler's context — handlers post signed, retried,\n * idempotency-stable webhooks without hand-rolling the pipeline. Omit\n * if your server never emits webhooks.\n *\n * Provide exactly one of `signerKey` (in-process JWK) or `signerProvider`\n * (KMS-backed async signing). The signing key or provider key SHOULD have\n * `adcp_use: \"request-signing\"`; the deprecated `\"webhook-signing\"` value is\n * accepted for compatibility. Publishers publishing\n * their JWKS at the `jwks_uri` on brand.json's `agents[]` entry reuse the\n * same key across every buyer they deliver to.\n */\n webhooks?: WebhooksConfig;\n /**\n * Optional callback that can mutate MCP tool responses before they are\n * returned. Runs for framework tools, custom tools, and generated discovery\n * responses registered by `createAdcpServer`.\n */\n responseEnhancer?: (response: McpToolResponse) => void;\n /**\n * Auto-wire the RFC 9421 request-signature verifier onto the HTTP transport.\n * When set together with `capabilities.specialisms` containing\n * `signed-requests`, `serve()` mounts the verifier as `preTransport` so\n * every inbound MCP request is verified before JSON-RPC dispatch. Setting\n * one without the other throws at construction time — the spec requires\n * the specialism claim and a working verifier to stay in lock-step.\n *\n * Omit entirely when the seller doesn't verify inbound signatures. Servers\n * that wire the verifier manually via `serve({ preTransport })` are\n * unaffected — auto-wiring only kicks in through this field.\n */\n signedRequests?: SignedRequestsConfig;\n\n /**\n * Schema-driven validation of requests and responses against the bundled\n * AdCP JSON schemas. When enabled, the dispatcher rejects bad requests\n * with `VALIDATION_ERROR` before the handler runs and catches drift in\n * handler-returned responses before they leave the server.\n *\n * Defaults:\n * - When `NODE_ENV === 'production'` → both sides `'off'` (zero overhead\n * in prod; trust the handler after its test suite has exercised it).\n * - Otherwise (dev, test, CI) → `responses: 'strict'`, `requests: 'warn'`.\n * Strict on responses turns handler-returned drift into a\n * `VALIDATION_ERROR` with the offending field path — surfaces the\n * \"handler returned a sparse object that fails the wire schema\" class\n * of bug at development time instead of letting it ship and surface\n * downstream as a cryptic `SERVICE_UNAVAILABLE` or `oneOf`\n * discriminator failure. Warn on requests logs incoming payloads that\n * don't match the bundled AdCP schema but still dispatches, so\n * upstream schema tightenings show up as diagnostics without breaking\n * clients that haven't caught up.\n *\n * Pass an explicit `validation: { requests: 'off', responses: 'off' }` to\n * override the dev-mode default. Set `responses: 'warn'` to keep the\n * logger diagnostic without failing the request — useful while\n * migrating a handler set from sparse fixtures to spec-compliant\n * responses. (The logger warning fires in both `'warn'` and `'strict'`\n * modes; `'strict'` additionally promotes the failure to a\n * `VALIDATION_ERROR` envelope.)\n *\n * Per-side modes:\n * - `requests: 'strict'` — reject malformed requests with VALIDATION_ERROR.\n * `'warn'` — log a warning, allow the handler to run.\n * `'off'` — skip.\n * - `responses: 'strict'` — handler-returned drift throws (dev/test canary).\n * `'warn'` — log a warning, return the response unchanged.\n * `'off'` — skip.\n *\n * Cost: one AJV compile per tool on cold start, one validator invocation\n * per call. The dev-mode default trades that for field-level diagnostics\n * when handlers drift from the wire contract.\n */\n validation?: {\n requests?: import('../validation/client-hooks').ValidationMode;\n responses?: import('../validation/client-hooks').ValidationMode;\n };\n\n /**\n * Reject buyer requests that smuggle credential-shaped keys through\n * the args bag. Closes the bug class observed in storefront fan-out\n * paths where keys like `<platform>_access_token` (top-level, in\n * `context`, or in `ext`) flow through to upstream calls under the\n * storefront's TLS / IP reputation — confused-deputy by default.\n *\n * Modes:\n * - `'lax'` (default) — no scan; preserves existing behavior.\n * - `'authInfo-only'` — scan args for credential-shaped keys at any\n * depth and reject with `INVALID_REQUEST`. Credentials must arrive\n * on `authInfo` (resolved by the framework's authenticator) and\n * never on the args bag.\n *\n * Pass the object form for pattern customization or per-tool overrides:\n *\n * ```ts\n * credentialPolicy: {\n * policy: 'authInfo-only',\n * patterns: { extend: [/^bearer$/i, /credentials/i] },\n * tools: { activate_signal: 'lax' }, // legitimate buyer-creds tool\n * }\n * ```\n *\n * Default patterns: `_access_token$`, `_secret$`, `_password$`,\n * `accessToken`, `refreshToken`. The next platform-specific vector\n * lives in adopter config, not in the SDK.\n *\n * @see {@link CredentialPolicy}\n * @see docs/guides/CTX-METADATA-SAFETY.md\n */\n credentialPolicy?: CredentialPolicy;\n\n /**\n * Register tools outside {@link AdcpToolMap}. Keys are the public tool\n * names; values follow {@link AdcpCustomToolConfig}.\n *\n * Gives sellers a declarative extension point without reaching for the\n * `getSdkServer()` escape hatch. Typical callers:\n *\n * - AdCP surfaces whose JSON Schemas haven't landed yet.\n * - Governance specialism helpers (`*_collection_list` family).\n * - Test-harness tools (`comply_test_controller` — prefer\n * {@link registerTestController} which wraps this).\n * - Seller-specific extensions outside the AdCP spec.\n *\n * **Custom tools bypass the framework's spec-tool pipeline.** No\n * idempotency middleware, no governance pre-check, no account\n * resolution, no response wrapping. The handler receives SDK-validated\n * args and must return a `CallToolResult`. Call framework helpers\n * (`checkGovernance`, `adcpError`, `capabilitiesResponse`, …) from\n * inside the handler if you need those behaviors.\n *\n * Name collisions with registered AdcpToolMap tools (from `mediaBuy`,\n * `signals`, `creative`, `governance`, `accounts`, `eventTracking`,\n * `sponsoredIntelligence`) or with `get_adcp_capabilities` throw at\n * construction time — the spec handler wins by convention.\n */\n customTools?: Record<string, AdcpCustomToolConfig<any, any>>;\n\n /**\n * Portable HTML MCP Apps served through standard MCP resources.\n *\n * Each definition is registered on both the legacy MCP server and every\n * modern per-request server reconstruction. A custom tool links to a\n * resource with `_meta.ui.resourceUri`; a startup warning identifies any\n * link whose URI is absent here. Hosts without MCP Apps support can ignore\n * the metadata and consume the tool's normal text result.\n */\n resources?: readonly AdcpMcpResourceDefinition[];\n\n /**\n * Opt-in bridge between the `comply_test_controller` seed store and the\n * spec-tool pipeline. When `getSeededProducts` is provided, seeded\n * products flow into `get_products` responses on sandbox requests — the\n * Group A compliance storyboards rely on this end-to-end flow.\n * Production traffic (no sandbox marker, or a resolved non-sandbox\n * account) bypasses the bridge entirely; omit the field in production\n * configs to be explicit about it.\n *\n * ## Do you need the bridge?\n *\n * The bridge is one of two mechanisms for closing the seed→read loop in\n * compliance testing. Pick by where your read handlers fetch from — not\n * by seller class:\n *\n * - **Handler reads from a store you control** (most SSPs, most\n * creative agents). `comply_test_controller.seed_product` writes to\n * your DB; your handler reads from your DB; the seed→read loop\n * closes naturally. **Don't wire the bridge** — test mode alone\n * covers you.\n * - **Handler reads from a system you don't control** (DSPs proxying\n * to Meta/Snap/TikTok, retail-media networks reading retailer\n * catalog APIs, signals agents brokering third-party data\n * marketplaces). `comply_test_controller.seed_product` is a dead\n * write for you because the handler will never see it. **Wire the\n * bridge.** The real handler still runs first (so a broken upstream\n * call still fails the conformance gate — adapter exercise is\n * preserved), and the SDK merges seeded fixtures into the response\n * after.\n *\n * Either path earns wire-conformance credit when storyboards pass; it\n * is *not* a separate certification category. Live-integration credit\n * requires marker-free passes against a real test surface (sandbox\n * credentials, real catalog data, real adapter traffic) — independent\n * of whether the bridge is wired. See `docs/guides/VALIDATE-YOUR-AGENT.md`\n * § \"Platform-proxy sellers\" for the wiring mechanics, and\n * [`adcp-client#1782`](https://github.com/adcontextprotocol/adcp-client/issues/1782)\n * plus the upstream taxonomy proposal at\n * [`adcontextprotocol/adcp#4593`](https://github.com/adcontextprotocol/adcp/issues/4593)\n * for the certification model under review.\n *\n * ## Security — trust boundary\n *\n * The bridge is gated by `isSandboxRequest(params) &&\n * isSandboxOrMockAccount(ctx.account)`. The resolved account is the\n * authority boundary; the first predicate is caller-supplied\n * (`account.sandbox` or `context.sandbox` on the request body) and is NOT\n * a trust boundary on its own. Requests without a resolved account fail\n * closed and never receive seeded fixtures.\n *\n * Production deployments that register `testController` MUST:\n * 1. Configure `resolveAccount` for account-bearing tools and\n * `resolveAccountFromAuth` for account-less tools so the framework\n * can prove the resolved account is `mode: 'sandbox' | 'mock'` (or\n * carries the legacy `sandbox: true` flag), or\n * 2. Omit `testController` entirely outside test / staging environments.\n *\n * The `createAdcpServerFromPlatform` flow already enforces this via the\n * sandbox-authority gate (see Phase 2 of #1435 — resolved-account `mode`\n * is the trust boundary, not buyer-supplied `account.sandbox`). The direct\n * `createAdcpServer` flow enforces the same resolved-account predicate;\n * adopters wiring the bridge here are responsible for providing both\n * resolver paths. See the top-of-file JSDoc on\n * `TestControllerBridge` for the full adopter-responsibility note (#1779).\n *\n * See `src/lib/server/test-controller-bridge.ts` for the sandbox-marker\n * predicate and the merge contract.\n *\n * @example\n * ```ts\n * import { createAdcpServer, bridgeFromTestControllerStore } from '@adcp/sdk/server/legacy/v5';\n *\n * const seedStore = new Map<string, unknown>();\n * const server = createAdcpServer({\n * resolveAccount: (ref, ctx) => accounts.resolve(ref, ctx),\n * resolveAccountFromAuth: ctx => accounts.resolve(undefined, ctx),\n * mediaBuy: { getProducts: handleGetProducts },\n * testController: bridgeFromTestControllerStore(seedStore, {\n * delivery_type: 'guaranteed',\n * channels: ['display'],\n * }),\n * });\n * ```\n */\n testController?: TestControllerBridge<TAccount>;\n}\n\n// ---------------------------------------------------------------------------\n// Tool metadata registry\n// ---------------------------------------------------------------------------\n\ninterface ToolAnnotation {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\ninterface ToolMeta {\n wrap: ((data: any, summary?: string) => McpToolResponse) | null;\n annotations?: ToolAnnotation;\n}\n\n/**\n * Deep-merge the per-domain blocks from `overrides` onto `target`. Nested\n * objects merge recursively; arrays and primitives replace. `null` at the\n * top-level field explicitly drops the block; `undefined` is a no-op.\n */\nfunction applyCapabilityOverrides(target: GetAdCPCapabilitiesResponse, overrides: AdcpCapabilitiesOverrides): void {\n const targetAny = target as unknown as Record<string, unknown>;\n const allowedKeys = new Set([\n 'media_buy',\n 'creative',\n 'signals',\n 'governance',\n 'brand',\n 'sponsored_intelligence',\n 'measurement',\n 'experimental_features',\n 'account',\n 'compliance_testing',\n 'webhook_signing',\n 'identity',\n 'request_signing',\n ]);\n for (const [key, value] of Object.entries(overrides)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `createAdcpServer: capabilities.overrides.${key} is not allowed. ` +\n 'Framework-owned capability fields must be configured through their dedicated options.'\n );\n }\n if (value === undefined) continue;\n if (value === null) {\n delete targetAny[key];\n continue;\n }\n targetAny[key] = deepMergePlainObjects(targetAny[key], value);\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (v === null || typeof v !== 'object') return false;\n if (Array.isArray(v)) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction hasInvalidGetProductsFinalizeIntent(toolName: string, params: Record<string, unknown>): boolean {\n if (toolName !== 'get_products') return false;\n if (isPlainObject(params.refine)) return params.refine.action === 'finalize';\n if (!Array.isArray(params.refine)) return false;\n const containsFinalize = params.refine.some(entry => isPlainObject(entry) && entry.action === 'finalize');\n if (!containsFinalize) return false;\n if (params.buying_mode !== 'refine') return true;\n // Finalize is exclusive: every entry must finalize a proposal. Multiple\n // proposal entries are valid and carry atomic multi-finalize semantics.\n return params.refine.some(\n entry =>\n !isPlainObject(entry) ||\n entry.action !== 'finalize' ||\n entry.scope !== 'proposal' ||\n typeof entry.proposal_id !== 'string' ||\n entry.proposal_id.length === 0\n );\n}\n\nfunction deepMergePlainObjects(target: unknown, source: unknown): unknown {\n if (source === undefined) return target;\n if (source === null) return null;\n if (!isPlainObject(source)) return source;\n if (!isPlainObject(target)) return { ...(source as Record<string, unknown>) };\n const out: Record<string, unknown> = { ...target };\n for (const [k, v] of Object.entries(source as Record<string, unknown>)) {\n if (v === undefined) continue;\n if (v === null) {\n delete out[k];\n continue;\n }\n out[k] = deepMergePlainObjects(out[k], v);\n }\n return out;\n}\n\n/**\n * Stamp `replayed: true` on the response envelope for replay paths only.\n * `protocol-envelope.json` permits the field to be \"omitted when the\n * request was executed fresh\" — fresh-path responses therefore carry no\n * `replayed` field, and the field's presence implies `true`. Buyers read\n * the field to distinguish cached replays from new executions for billing\n * and audit.\n *\n * Mirrors the marker into both L3 `structuredContent` and the L2\n * `content[0].text` JSON fallback so A2A/REST adapters that consume the\n * text body see the same envelope MCP does — matching the lockstep\n * pattern in `injectContextIntoResponse` / `sanitizeAdcpErrorEnvelope`.\n */\nfunction stampReplayed(response: McpToolResponse): void {\n if (!response.structuredContent || typeof response.structuredContent !== 'object') return;\n const sc = response.structuredContent as Record<string, unknown>;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.replayed = true;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\n/**\n * Shape of the `_bridge` marker stamped on responses where the\n * `testController` bridge merged seeded fixtures into the handler's reply.\n *\n * The marker is non-normative — every bridge-augmented response schema in\n * AdCP 3.0 allows additional top-level properties (verified across the 13\n * bridge-touching response schemas), and the underscore prefix advertises\n * \"internal / out-of-spec\" to validators that round-trip unknown fields.\n * Consumers (storyboard runners, compliance leaderboards, audit pipelines)\n * read this marker to distinguish \"this pass exercised the adopter's\n * adapter against upstream\" from \"this pass exercised wire conformance\n * against fixture data merged by the SDK\". See `adcp-client#1775` for the\n * cross-repo coordination context.\n *\n * ## Why on the response body, not MCP `_meta`?\n *\n * MCP defines `result._meta` as the canonical place for non-normative\n * server-side annotations, and `_meta` would be the textbook home for this\n * marker on MCP-only deployments. We put it on the response body instead\n * for three reasons:\n *\n * 1. **Cross-transport parity.** A2A has no `_meta` equivalent —\n * `structuredContent` passes through the A2A artifact pipeline\n * verbatim, but a hypothetical envelope-level marker would have to be\n * duplicated or lost. One wire location across both transports keeps\n * the storyboard runner's read logic uniform.\n * 2. **L2-text-body parity.** Buyers consuming the L2 text body (the\n * JSON-stringified `content[0].text`) see the same envelope MCP does,\n * because the opportunistic text-body mirror copies the marker into\n * both.\n * 3. **Precedent.** `replayed: true` already lives on the response body\n * via the same `stampReplayed` pattern this marker mirrors. Splitting\n * framework-emitted annotations across `_meta` and the body would\n * create two conventions for the same job.\n */\nexport interface BridgeMarker {\n /** Bridge callback that produced the seeded entries (e.g. `getSeededCreatives`). */\n callback: string;\n /** Tool name whose response was augmented (mirrors envelope context). */\n tool: string;\n /** Count of seeded entries the callback returned (post-validation). */\n merged_count: number;\n}\n\n/**\n * Stamp a non-normative `_bridge` marker on a response that the\n * `testController` bridge augmented with seeded fixtures.\n *\n * Mirrors {@link stampReplayed} — sets `_bridge` on `structuredContent`\n * AND on the parsed JSON in `content[0].text`, so A2A/REST adapters that\n * consume the text body see the same envelope MCP does.\n *\n * Only call this AFTER a successful merge — for singleton-replace tools\n * (`get_account_financials`, `get_brand_identity`, `si_get_offering`,\n * `get_property_list`, `get_collection_list`, `get_content_standards`)\n * gate on `merged !== sc` so the marker only fires when the seeded fixture\n * actually replaced the handler payload.\n */\nfunction stampBridge(response: McpToolResponse, callback: string, tool: string, mergedCount: number): void {\n if (!response.structuredContent || typeof response.structuredContent !== 'object') return;\n const marker: BridgeMarker = { callback, tool, merged_count: mergedCount };\n const sc = response.structuredContent as Record<string, unknown>;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc._bridge = marker;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\n/**\n * Remove per-request echo fields (`context`) from a formatted MCP response\n * before caching. The buyer's `correlation_id` is scoped to the individual\n * retry attempt and must not be baked into the cached envelope — replays\n * need to echo back the CURRENT retry's context, not the first caller's.\n * Other fields (media_buy_id, status, timestamps) are part of the pinned\n * response and stay put.\n */\nfunction stripEnvelopeEcho(response: McpToolResponse): McpToolResponse {\n const cloned = cloneFormattedResponse(response);\n if (cloned.structuredContent && typeof cloned.structuredContent === 'object') {\n const sc = cloned.structuredContent as Record<string, unknown>;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(cloned, sc);\n delete sc.context;\n syncContentJsonText(cloned, sc, mirrorsStructuredContent);\n }\n return cloned;\n}\n\n/**\n * Shallow-clone a formatted MCP response so callers can mutate envelope\n * fields (`replayed`, echo-back `context`) without stomping on the cache\n * entry. The backend returns a fresh object (memory clones, pg\n * serializes) but re-wrapping via `wrap()` can still alias pieces of the\n * handler's return value — belt-and-suspenders against mutation leaks.\n */\nfunction cloneFormattedResponse(response: McpToolResponse): McpToolResponse {\n const cloned: McpToolResponse = { ...response };\n if (cloned.structuredContent && typeof cloned.structuredContent === 'object') {\n cloned.structuredContent = { ...(cloned.structuredContent as Record<string, unknown>) };\n }\n if (Array.isArray(cloned.content)) {\n cloned.content = cloned.content.map(item => ({ ...item }));\n }\n return cloned;\n}\n\n/**\n * Detect whether a formatted MCP response represents a failure. Failures\n * are NOT cached — a retry should re-execute rather than replay a\n * transient error. Checks all three shapes the framework emits:\n * `isError: true`, `structuredContent.adcp_error`, or envelope\n * `status: 'failed'` (the envelope example in the spec for failed async\n * tasks doesn't always include `adcp_error`).\n */\nfunction isErrorResponse(response: McpToolResponse): boolean {\n if (response.isError === true) return true;\n const sc = response.structuredContent;\n if (sc && typeof sc === 'object') {\n if ('adcp_error' in sc) return true;\n const status = (sc as Record<string, unknown>).status;\n if (status === 'failed' || status === 'canceled' || status === 'rejected') return true;\n }\n return false;\n}\n\nconst UNCACHEABLE_SYNC_ACCOUNT_ERROR_CODES = new Set([\n 'BILLING_NOT_SUPPORTED',\n 'BILLING_NOT_PERMITTED_FOR_AGENT',\n 'PAYMENT_TERMS_NOT_SUPPORTED',\n]);\n\nfunction hasUncacheableSyncAccountRejection(response: McpToolResponse): boolean {\n const sc = response.structuredContent;\n if (!sc || typeof sc !== 'object') return false;\n const accounts = (sc as Record<string, unknown>).accounts;\n if (!Array.isArray(accounts)) return false;\n return accounts.some(row => {\n if (!row || typeof row !== 'object') return false;\n const record = row as Record<string, unknown>;\n if (record.status !== 'rejected' && record.action !== 'failed') return false;\n const errors = record.errors;\n if (!Array.isArray(errors)) return false;\n return errors.some(error => {\n if (!error || typeof error !== 'object') return false;\n return UNCACHEABLE_SYNC_ACCOUNT_ERROR_CODES.has(String((error as Record<string, unknown>).code));\n });\n });\n}\n\nfunction shouldCacheIdempotencyResponse(response: McpToolResponse): boolean {\n return !isErrorResponse(response) && !hasUncacheableSyncAccountRejection(response);\n}\n\n/**\n * Detect a thrown `adcpError(...)` envelope. Handlers that `throw` an\n * envelope (instead of `return`-ing it) would otherwise surface as\n * `[object Object]` inside a SERVICE_UNAVAILABLE wrapper — the dispatcher\n * unwraps and returns the envelope directly when the shape matches.\n */\n/**\n * Project a thrown {@link AdcpError} to the wire envelope. Used by the\n * account-resolution and tool-handler catch blocks so adopters can throw\n * typed errors at any depth and have the framework project the structured\n * fields verbatim — without coercion to `SERVICE_UNAVAILABLE`. Mirrors the\n * `isThrownAdcpError` unwrap, but for the in-process class throw rather\n * than the already-projected envelope throw.\n */\nfunction projectThrownAdcpError(err: AdcpError): McpToolResponse {\n return adcpError(err.code, {\n recovery: err.recovery,\n message: err.message,\n ...(err.field !== undefined && { field: err.field }),\n ...(err.suggestion !== undefined && { suggestion: err.suggestion }),\n ...(err.retry_after !== undefined && { retry_after: err.retry_after }),\n ...(err.details !== undefined && { details: err.details }),\n });\n}\n\nfunction isThrownAdcpError(value: unknown): value is McpToolResponse {\n if (!value || typeof value !== 'object') return false;\n const sc = (value as { structuredContent?: unknown }).structuredContent;\n if (!sc || typeof sc !== 'object') return false;\n const env = (sc as { adcp_error?: unknown }).adcp_error;\n if (!env || typeof env !== 'object') return false;\n // `adcpError()` guarantees both `code` and `message` as strings — assert\n // both so a malformed envelope throw doesn't produce a half-formed\n // response. Also rules out MCP SDK `McpError` (numeric `code`) and any\n // other thrown object with a coincidentally-shaped sub-tree.\n if (typeof (env as { code?: unknown }).code !== 'string') return false;\n if (typeof (env as { message?: unknown }).message !== 'string') return false;\n return Array.isArray((value as { content?: unknown }).content) && (value as { isError?: unknown }).isError === true;\n}\n\nfunction thrownAdcpErrorRecovery(response: McpToolResponse): ErrorRecovery {\n const error = (response.structuredContent as { adcp_error: { code: string; recovery?: unknown } }).adcp_error;\n if (isStandardErrorCode(error.code)) {\n return STANDARD_ERROR_CODES[error.code].recovery;\n }\n if (error.recovery === 'transient' || error.recovery === 'correctable' || error.recovery === 'terminal') {\n return error.recovery;\n }\n return DEFAULT_UNKNOWN_ERROR_RECOVERY;\n}\n\n/**\n * Resolve the framework-owned cache namespace for a concrete mutation.\n *\n * Existing tools retain their SDK 13 scope so an in-flight mutation cannot\n * miss its replay record during a rolling upgrade. The new get_products\n * finalize path adds trusted session/account identity; other tool/session\n * special cases preserve their established scopes.\n */\nfunction resolveExtraScope(\n toolName: string,\n params: Record<string, unknown>,\n account?: unknown,\n sessionKey?: string,\n proposalScope?: Readonly<ProposalRefinementScope>,\n callerMutationScope?: Readonly<CallerMutationScope>\n): string | undefined {\n const accountLike = account as\n | { id?: unknown; account_id?: unknown; tenant_id?: unknown; tenantId?: unknown }\n | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const tenantId =\n typeof accountLike?.tenant_id === 'string'\n ? accountLike.tenant_id\n : typeof accountLike?.tenantId === 'string'\n ? accountLike.tenantId\n : undefined;\n if (CALLER_SCOPED_MUTATION_TOOLS.has(toolName) && callerMutationScope) {\n return JSON.stringify([\n callerMutationScope.tenant_id,\n callerMutationScope.principal_id,\n callerMutationScope.account_id ?? null,\n ]);\n }\n if (toolName === 'si_send_message') {\n const sessionId = params.session_id;\n return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined;\n }\n if (toolName === 'refine_proposals' && proposalScope) {\n // The proposal namespace is framework-owned trusted context. Keep the\n // complete tuple in the replay scope so one authenticated principal\n // cannot replay a response across tenant or account boundaries.\n return JSON.stringify([proposalScope.tenant_id, proposalScope.principal_id, proposalScope.account_id ?? null]);\n }\n if (toolName === 'get_products') {\n return JSON.stringify([sessionKey ?? null, tenantId ?? null, accountId ?? null]);\n }\n return undefined;\n}\n\nfunction buildIdempotencyPayload(\n toolName: string,\n params: Record<string, unknown>,\n account?: unknown,\n sessionKey?: string\n): readonly unknown[] {\n const accountLike = account as\n | { id?: unknown; account_id?: unknown; tenant_id?: unknown; tenantId?: unknown }\n | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const tenantId =\n typeof accountLike?.tenant_id === 'string'\n ? accountLike.tenant_id\n : typeof accountLike?.tenantId === 'string'\n ? accountLike.tenantId\n : undefined;\n // Keep framework identity in the canonical payload hash rather than\n // changing the established cache key. The tuple root is deliberately\n // impossible for an SDK 13 entry: legacy dispatch always hashed the\n // object-shaped tool arguments directly. Unknown request fields therefore\n // cannot forge these trusted discriminators. A legacy entry yields\n // IDEMPOTENCY_CONFLICT after upgrade instead of a cache miss and duplicate\n // execution; new entries cannot replay across tools or tenants.\n return [\n '@adcp/sdk-idempotency/v2',\n toolName,\n [sessionKey ?? null, tenantId ?? null, accountId ?? null],\n hashPayload(params),\n ] as const;\n}\n\nfunction genericResponse(toolName: string, data: object, summary?: string): McpToolResponse {\n const structuredContent = { ...toStructuredContent(data) };\n if (STATUS_FREE_SYNC_RESPONSE_TOOLS.has(toolName)) delete structuredContent.status;\n return {\n content: [{ type: 'text', text: summary ?? `${toolName} completed` }],\n structuredContent,\n };\n}\n\nconst ADCP_TASK_TYPES = new Set<TaskType>(TaskTypeValues);\n\nfunction readRegistryTaskType(task: TaskRecord): TaskType | undefined {\n return ADCP_TASK_TYPES.has(task.tool as TaskType) ? (task.tool as TaskType) : undefined;\n}\n\nfunction toProtocolTaskStatus(task: TaskRecord): GetTaskStatusResponse | undefined {\n const taskType = readRegistryTaskType(task);\n if (taskType === undefined) return undefined;\n const protocol = protocolForTool(taskType) as WireAdcpProtocol;\n return {\n task_id: task.taskId,\n task_type: taskType,\n protocol,\n status: task.status as TaskStatus,\n created_at: task.createdAt,\n updated_at: task.updatedAt,\n ...(task.status === 'completed' || task.status === 'failed' || task.status === 'canceled'\n ? { completed_at: task.updatedAt }\n : {}),\n ...(task.hasWebhook !== undefined ? { has_webhook: task.hasWebhook === true } : {}),\n ...(task.progress !== undefined ? { progress: task.progress } : {}),\n ...(task.error !== undefined\n ? { error: sanitizeStructuredAdcpError(task.error) as GetTaskStatusResponse['error'] }\n : task.statusMessage !== undefined\n ? {\n error: {\n code: task.status === 'failed' ? 'TASK_FAILED' : 'TASK_STATUS_MESSAGE',\n message: task.statusMessage,\n },\n }\n : {}),\n };\n}\n\nfunction toProtocolTaskListItem(task: TaskRecord): ListTasksResponse['tasks'][number] | undefined {\n const taskType = readRegistryTaskType(task);\n if (taskType === undefined) return undefined;\n const protocol = protocolForTool(taskType) as WireAdcpProtocol;\n return {\n task_id: task.taskId,\n task_type: taskType,\n domain: protocol === 'signals' || protocol === 'creative' ? protocol : 'media-buy',\n status: task.status as TaskStatus,\n created_at: task.createdAt,\n updated_at: task.updatedAt,\n ...(task.status === 'completed' || task.status === 'failed' || task.status === 'canceled'\n ? { completed_at: task.updatedAt }\n : {}),\n ...(task.hasWebhook !== undefined ? { has_webhook: task.hasWebhook === true } : {}),\n };\n}\n\nfunction appendSearchableTaskValue(values: string[], value: unknown): void {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n values.push(String(value));\n }\n}\n\nfunction appendSearchableResultIdentifiers(values: string[], value: unknown, depth = 0): void {\n if (depth > 3 || value == null || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const item of value) appendSearchableResultIdentifiers(values, item, depth + 1);\n return;\n }\n if (!isPlainObject(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (/(^|_)(id|ids|ref|refs)$/.test(key)) {\n if (Array.isArray(child)) {\n for (const item of child) appendSearchableTaskValue(values, item);\n } else {\n appendSearchableTaskValue(values, child);\n }\n }\n if (child != null && typeof child === 'object') {\n appendSearchableResultIdentifiers(values, child, depth + 1);\n }\n }\n}\n\nfunction taskSearchHaystack(task: TaskRecord, item: ListTasksResponse['tasks'][number]): string {\n const values = [item.task_id, item.task_type, item.status, item.domain, task.accountId];\n appendSearchableResultIdentifiers(values, task.result);\n appendSearchableResultIdentifiers(values, task.progress);\n return values.join('\\n');\n}\n\nfunction taskMatchesFilters(task: TaskRecord, filters: ListTasksRequest['filters']): boolean {\n if (!isPlainObject(filters)) return true;\n const item = toProtocolTaskListItem(task);\n if (item === undefined) return false;\n const protocol = protocolForTool(item.task_type) as WireAdcpProtocol;\n if (typeof filters.protocol === 'string' && protocol !== filters.protocol) return false;\n if (Array.isArray(filters.protocols) && !filters.protocols.includes(protocol)) return false;\n if (typeof filters.status === 'string' && item.status !== filters.status) return false;\n if (Array.isArray(filters.statuses) && !filters.statuses.includes(item.status)) return false;\n if (typeof filters.task_type === 'string' && item.task_type !== filters.task_type) return false;\n if (Array.isArray(filters.task_types) && !filters.task_types.includes(item.task_type)) return false;\n if (Array.isArray(filters.task_ids) && !filters.task_ids.includes(item.task_id)) return false;\n if (!taskTimestampMatches(item.created_at, filters.created_after, 'after')) return false;\n if (!taskTimestampMatches(item.created_at, filters.created_before, 'before')) return false;\n if (!taskTimestampMatches(item.updated_at, filters.updated_after, 'after')) return false;\n if (!taskTimestampMatches(item.updated_at, filters.updated_before, 'before')) return false;\n if (typeof filters.has_webhook === 'boolean' && (task.hasWebhook === true) !== filters.has_webhook) return false;\n if (typeof filters.context_contains === 'string' && filters.context_contains.length > 0) {\n if (!taskSearchHaystack(task, item).includes(filters.context_contains)) return false;\n }\n return true;\n}\n\nfunction taskTimestampMatches(value: string, boundary: unknown, direction: 'after' | 'before'): boolean {\n if (typeof boundary !== 'string') return true;\n const valueMs = Date.parse(value);\n const boundaryMs = Date.parse(boundary);\n if (!Number.isFinite(valueMs) || !Number.isFinite(boundaryMs)) return false;\n return direction === 'after' ? valueMs > boundaryMs : valueMs < boundaryMs;\n}\n\nfunction taskBelongsToCaller(task: TaskRecord, accountId: string, ownerScope: string | undefined): boolean {\n if (task.accountId !== accountId) return false;\n if (ownerScope === undefined) return false;\n if (task.ownerScope === undefined) return ownerScope === `account:${accountId}`;\n return task.ownerScope === ownerScope;\n}\n\nfunction authenticatedPrincipalForContext(\n authInfo: ResolvedAuthInfo | undefined,\n agent: BuyerAgent | undefined\n): string | undefined {\n if (agent?.agent_url) return `agent:${agent.agent_url}`;\n const credential = authInfo?.credential;\n if (credential?.kind === 'http_sig') return `http_sig:${credential.agent_url}`;\n if (credential?.kind === 'oauth') return `oauth:${credential.client_id}`;\n if (credential?.kind === 'api_key') return `api_key:${credential.key_id}`;\n if (typeof authInfo?.clientId === 'string' && authInfo.clientId.length > 0) return `client:${authInfo.clientId}`;\n return undefined;\n}\n\nfunction taskOwnerScopeForContext(\n authInfo: ResolvedAuthInfo | undefined,\n sessionKey: string | undefined,\n agent: BuyerAgent | undefined,\n accountId: string\n): string {\n if (sessionKey !== undefined) return `session:${sessionKey}`;\n if (agent?.agent_url) return `agent:${agent.agent_url}`;\n const credential = authInfo?.credential;\n if (credential?.kind === 'http_sig') return `http_sig:${credential.agent_url}`;\n if (credential?.kind === 'oauth') return `oauth:${credential.client_id}`;\n if (credential?.kind === 'api_key') return `api_key:${credential.key_id}`;\n if (typeof authInfo?.clientId === 'string' && authInfo.clientId.length > 0) return `client:${authInfo.clientId}`;\n return `account:${accountId}`;\n}\n\n/**\n * Build the webhook delivery-store tenant namespace exclusively from trusted,\n * resolved server context. Webhook payload and request-body delivery fields\n * never participate, so one tenant cannot preclaim another tenant's delivery\n * binding in a shared durable store.\n */\nfunction webhookTenantScopeForContext<TAccount>(ctx: HandlerContext<TAccount>): string | undefined {\n if (ctx.callerMutationScope) {\n return JSON.stringify([\n 'caller',\n ctx.callerMutationScope.tenant_id,\n ctx.callerMutationScope.principal_id,\n ctx.callerMutationScope.account_id ?? null,\n ]);\n }\n const accountLike = ctx.account as\n | { id?: unknown; account_id?: unknown; tenant_id?: unknown; tenantId?: unknown }\n | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const tenantId =\n typeof accountLike?.tenant_id === 'string'\n ? accountLike.tenant_id\n : typeof accountLike?.tenantId === 'string'\n ? accountLike.tenantId\n : undefined;\n const principal = authenticatedPrincipalForContext(ctx.authInfo, ctx.agent);\n if (ctx.sessionKey !== undefined) {\n return JSON.stringify(['session', ctx.sessionKey, tenantId ?? null, accountId ?? null, principal ?? null]);\n }\n if (tenantId !== undefined || accountId !== undefined) {\n return JSON.stringify(['account', tenantId ?? null, accountId ?? null, principal ?? null]);\n }\n if (principal !== undefined) return JSON.stringify(['principal', principal]);\n return undefined;\n}\n\nfunction compareProtocolTaskItems(\n left: ListTasksResponse['tasks'][number],\n right: ListTasksResponse['tasks'][number],\n sort: ListTasksRequest['sort']\n): number {\n const field = isPlainObject(sort) && typeof sort.field === 'string' ? sort.field : 'created_at';\n const direction = isPlainObject(sort) && sort.direction === 'asc' ? 'asc' : 'desc';\n const multiplier = direction === 'asc' ? 1 : -1;\n let result = 0;\n if (field === 'updated_at') result = left.updated_at.localeCompare(right.updated_at);\n else if (field === 'status') result = left.status.localeCompare(right.status);\n else if (field === 'task_type') result = left.task_type.localeCompare(right.task_type);\n else if (field === 'protocol') {\n const leftProtocol = protocolForTool(left.task_type);\n const rightProtocol = protocolForTool(right.task_type);\n result = leftProtocol.localeCompare(rightProtocol);\n } else {\n result = left.created_at.localeCompare(right.created_at);\n }\n return result === 0 ? left.task_id.localeCompare(right.task_id) * multiplier : result * multiplier;\n}\n\nfunction parseTaskListCursor(cursor: unknown): number | undefined {\n if (cursor === undefined) return undefined;\n if (typeof cursor !== 'string' || !/^(0|[1-9]\\d*)$/.test(cursor)) {\n throw new Error('Invalid task list cursor');\n }\n return Number.parseInt(cursor, 10);\n}\n\nfunction taskListPageSize(pagination: unknown): number {\n if (!isPlainObject(pagination) || typeof pagination.max_results !== 'number') return 50;\n return Math.min(Math.max(Math.floor(pagination.max_results), 1), 100);\n}\n\nfunction wrapBuildCreative(data: any, summary?: string): McpToolResponse {\n if ('creative_manifests' in data) {\n return buildCreativeMultiResponse(data, summary);\n }\n return buildCreativeResponse(data, summary);\n}\n\n// Shorthand annotation constants\nconst RO: ToolAnnotation = { readOnlyHint: true };\nconst MUT: ToolAnnotation = { readOnlyHint: false, destructiveHint: false };\nconst DEST: ToolAnnotation = { readOnlyHint: false, destructiveHint: true };\nconst IDEMP: ToolAnnotation = { readOnlyHint: false, idempotentHint: true };\n\n// Passthrough schema for framework-registered tools by default (#909). See\n// the comment at the registerTool call sites for rationale — short version:\n// makes our AJV validator authoritative on both transports without destroying\n// args on MCP when the SDK's tool dispatcher would otherwise coerce\n// `undefined` into the handler for schemaless tools. Servers can opt into\n// shallow MCP discovery hints derived from `TOOL_INPUT_SHAPES` with\n// config.exposeToolSchemas.\nconst PASSTHROUGH_INPUT_SCHEMA = z.object({}).passthrough();\ntype ToolInputShapeMap = Readonly<Record<string, ZodRawShapeCompat | undefined>>;\nlet cachedToolInputShapes: ToolInputShapeMap | undefined;\nconst SHALLOW_HINT_FIELD_SCHEMA = z.unknown().optional();\nconst SHALLOW_HINT_SCHEMAS = new Map<string, AnySchema>();\nconst REFINE_PROPOSALS_INPUT_SHAPE = {\n idempotency_key: SHALLOW_HINT_FIELD_SCHEMA,\n refinements: SHALLOW_HINT_FIELD_SCHEMA,\n context_id: SHALLOW_HINT_FIELD_SCHEMA,\n context: SHALLOW_HINT_FIELD_SCHEMA,\n governance_context: SHALLOW_HINT_FIELD_SCHEMA,\n push_notification_config: SHALLOW_HINT_FIELD_SCHEMA,\n adcp_version: SHALLOW_HINT_FIELD_SCHEMA,\n adcp_major_version: SHALLOW_HINT_FIELD_SCHEMA,\n} as unknown as ZodRawShapeCompat;\n\nfunction getToolInputShapes(): ToolInputShapeMap {\n cachedToolInputShapes ??= TOOL_INPUT_SHAPES as unknown as ToolInputShapeMap;\n return cachedToolInputShapes;\n}\n\nfunction shallowToolInputHintSchema(toolName: string): AnySchema | undefined {\n const inputShape = toolName === 'refine_proposals' ? REFINE_PROPOSALS_INPUT_SHAPE : getToolInputShapes()[toolName];\n if (inputShape === undefined) return undefined;\n\n const cached = SHALLOW_HINT_SCHEMAS.get(toolName);\n if (cached !== undefined) return cached;\n\n const hintShape = Object.fromEntries(Object.keys(inputShape).map(key => [key, SHALLOW_HINT_FIELD_SCHEMA]));\n const schema = z.object(hintShape).passthrough();\n SHALLOW_HINT_SCHEMAS.set(toolName, schema);\n return schema;\n}\n\nfunction validateFrameworkPayload(\n toolName: string,\n direction: 'request' | 'response',\n payload: unknown,\n version: Parameters<typeof validateRequest>[2],\n proposalCapabilities?: ProposalRefinementCapabilities\n) {\n if (toolName !== 'refine_proposals') {\n return direction === 'request'\n ? validateRequest(toolName, payload, version)\n : validateResponse(toolName, payload, version);\n }\n if (direction === 'request') {\n try {\n validateRefineProposalsRequest(payload as RefineProposalsRequest, proposalCapabilities);\n return {\n valid: true as const,\n issues: [] as ValidationIssue[],\n schemaId: '/schemas/media-buy/refine-proposals-request.json',\n variant: undefined,\n };\n } catch (error) {\n const refinementError =\n error instanceof ProposalRefinementValidationError\n ? error\n : new ProposalRefinementValidationError(\n error instanceof Error ? error.message : 'invalid refine_proposals request'\n );\n return {\n valid: false as const,\n refinementError,\n issues: [\n {\n pointer: fieldPathToPointer(refinementError.field),\n message: refinementError.message,\n keyword: 'validation',\n schemaPath: '#/local/validation',\n schemaId: '/schemas/media-buy/refine-proposals-request.json',\n },\n ],\n schemaId: '/schemas/media-buy/refine-proposals-request.json',\n variant: undefined,\n };\n }\n }\n const verification = validateRefineProposalsResponseShape(payload);\n if (verification.ok) {\n return {\n valid: true as const,\n issues: [] as ValidationIssue[],\n schemaId: '/schemas/media-buy/refine-proposals-response.json',\n variant: undefined,\n };\n }\n const issues: ValidationIssue[] = verification.issues.map(issue => ({\n pointer: fieldPathToPointer(issue.path),\n message: issue.message,\n keyword: issue.code,\n schemaPath: `#/local/${issue.code}`,\n schemaId: '/schemas/media-buy/refine-proposals-response.json',\n }));\n return {\n valid: false as const,\n issues,\n schemaId: '/schemas/media-buy/refine-proposals-response.json',\n variant: undefined,\n };\n}\n\nfunction fieldPathToPointer(path: string | undefined): string {\n if (!path) return '';\n const segments = path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter(Boolean);\n return `/${segments.map(segment => segment.replaceAll('~', '~0').replaceAll('/', '~1')).join('/')}`;\n}\n\nconst TOOL_META: Record<string, ToolMeta> = {\n // Media Buy\n list_products: { wrap: null, annotations: RO },\n request_proposals: { wrap: null, annotations: IDEMP },\n refine_proposals: { wrap: null, annotations: IDEMP },\n decline_proposals: { wrap: null, annotations: IDEMP },\n buy_products: { wrap: null, annotations: IDEMP },\n accept_proposal: { wrap: null, annotations: IDEMP },\n control_media_buy: { wrap: null, annotations: IDEMP },\n get_products: { wrap: productsResponse, annotations: RO },\n create_media_buy: { wrap: mediaBuyResponse, annotations: MUT },\n update_media_buy: { wrap: updateMediaBuyResponse, annotations: MUT },\n get_media_buys: { wrap: getMediaBuysResponse, annotations: RO },\n get_media_buy_delivery: { wrap: deliveryResponse, annotations: RO },\n provide_performance_feedback: { wrap: performanceFeedbackResponse, annotations: MUT },\n\n // Protocol\n get_task_status: { wrap: null, annotations: RO },\n list_tasks: { wrap: null, annotations: RO },\n sync_agent_notification_configs: { wrap: null, annotations: IDEMP },\n\n // Creative\n list_creative_formats: { wrap: listCreativeFormatsResponse, annotations: RO },\n list_transformers: { wrap: null, annotations: RO },\n build_creative: { wrap: wrapBuildCreative, annotations: MUT },\n preview_creative: { wrap: null, annotations: RO },\n get_creative_delivery: { wrap: creativeDeliveryResponse, annotations: RO },\n list_creatives: { wrap: listCreativesResponse, annotations: RO },\n sync_creatives: { wrap: syncCreativesResponse, annotations: IDEMP },\n\n // Signals\n get_signals: { wrap: getSignalsResponse, annotations: RO },\n activate_signal: { wrap: activateSignalResponse, annotations: MUT },\n\n // Accounts\n list_accounts: { wrap: listAccountsResponse, annotations: RO },\n sync_accounts: { wrap: syncAccountsResponse, annotations: IDEMP },\n sync_governance: { wrap: syncGovernanceResponse, annotations: IDEMP },\n get_account_financials: { wrap: null, annotations: RO },\n report_usage: { wrap: reportUsageResponse, annotations: MUT },\n\n // Event Tracking\n sync_event_sources: { wrap: null, annotations: IDEMP },\n log_event: { wrap: null, annotations: MUT },\n\n // Audiences & Catalogs\n sync_audiences: { wrap: null, annotations: IDEMP },\n sync_catalogs: { wrap: null, annotations: IDEMP },\n\n // Governance - Property Lists\n create_property_list: { wrap: null, annotations: MUT },\n update_property_list: { wrap: null, annotations: MUT },\n get_property_list: { wrap: null, annotations: RO },\n list_property_lists: { wrap: null, annotations: RO },\n delete_property_list: { wrap: null, annotations: DEST },\n\n // Governance - Collection Lists\n create_collection_list: { wrap: null, annotations: MUT },\n update_collection_list: { wrap: null, annotations: MUT },\n get_collection_list: { wrap: null, annotations: RO },\n list_collection_lists: { wrap: null, annotations: RO },\n delete_collection_list: { wrap: null, annotations: DEST },\n\n // Governance - Content Standards\n list_content_standards: { wrap: null, annotations: RO },\n get_content_standards: { wrap: null, annotations: RO },\n create_content_standards: { wrap: null, annotations: MUT },\n update_content_standards: { wrap: null, annotations: MUT },\n calibrate_content: { wrap: null, annotations: MUT },\n validate_content_delivery: { wrap: null, annotations: RO },\n get_media_buy_artifacts: { wrap: null, annotations: RO },\n\n // Governance - Campaign\n get_creative_features: { wrap: null, annotations: RO },\n sync_plans: { wrap: null, annotations: IDEMP },\n check_governance: { wrap: null, annotations: RO },\n report_plan_outcome: { wrap: null, annotations: MUT },\n report_plan_adjustment: { wrap: null, annotations: IDEMP },\n get_plan_audit_logs: { wrap: null, annotations: RO },\n\n // Sponsored Intelligence\n si_get_offering: { wrap: null, annotations: RO },\n si_initiate_session: { wrap: null, annotations: MUT },\n si_send_message: { wrap: null, annotations: MUT },\n si_terminate_session: { wrap: null, annotations: DEST },\n\n // Brand Rights\n get_brand_identity: { wrap: null, annotations: RO },\n get_rights: { wrap: null, annotations: RO },\n acquire_rights: { wrap: acquireRightsResponse, annotations: MUT },\n update_rights: { wrap: updateRightsResponse, annotations: MUT },\n};\n\nconst CALLER_SCOPED_MUTATION_TOOLS = new Set(['sync_agent_notification_configs', 'report_plan_adjustment']);\n\nconst COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS = [\n 'list_products',\n 'request_proposals',\n 'refine_proposals',\n 'decline_proposals',\n 'buy_products',\n 'accept_proposal',\n 'control_media_buy',\n] as const;\n\ntype ProjectionSchema = Record<string, unknown>;\n\nconst OMIT_PROJECTED_VALUE = Symbol('omit-projected-value');\n\nfunction asProjectionSchema(value: unknown): ProjectionSchema | undefined {\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction resolveLocalProjectionRef(root: ProjectionSchema, schema: ProjectionSchema): ProjectionSchema {\n const ref = schema.$ref;\n if (typeof ref !== 'string' || !ref.startsWith('#/')) return schema;\n let current: unknown = root;\n for (const encodedSegment of ref.slice(2).split('/')) {\n if (!isPlainObject(current)) return schema;\n const segment = encodedSegment.replace(/~1/g, '/').replace(/~0/g, '~');\n current = current[segment];\n }\n return asProjectionSchema(current) ?? schema;\n}\n\nfunction projectionDiscriminatorMatch(\n root: ProjectionSchema,\n schema: ProjectionSchema,\n value: unknown\n): boolean | undefined {\n if (!isPlainObject(value)) return undefined;\n const resolved = resolveLocalProjectionRef(root, schema);\n const properties = asProjectionSchema(resolved.properties);\n if (!properties) return undefined;\n let found = false;\n for (const [key, propertySchemaValue] of Object.entries(properties)) {\n const propertySchema = asProjectionSchema(propertySchemaValue);\n if (!propertySchema || !Object.hasOwn(propertySchema, 'const')) continue;\n found = true;\n if (value[key] !== propertySchema.const) return false;\n }\n return found ? true : undefined;\n}\n\nfunction collectProjectionSchemas(\n root: ProjectionSchema,\n schema: ProjectionSchema,\n value: unknown,\n depth = 0\n): ProjectionSchema[] {\n if (depth > 64) return [];\n const resolved = resolveLocalProjectionRef(root, schema);\n const schemas: ProjectionSchema[] = [resolved];\n for (const keyword of ['allOf'] as const) {\n const branches = resolved[keyword];\n if (!Array.isArray(branches)) continue;\n for (const branch of branches) {\n const branchSchema = asProjectionSchema(branch);\n if (branchSchema) schemas.push(...collectProjectionSchemas(root, branchSchema, value, depth + 1));\n }\n }\n for (const keyword of ['oneOf', 'anyOf'] as const) {\n const branches = resolved[keyword];\n if (!Array.isArray(branches)) continue;\n const branchSchemas = branches.map(asProjectionSchema).filter((branch): branch is ProjectionSchema => !!branch);\n const matched = branchSchemas.filter(branch => projectionDiscriminatorMatch(root, branch, value) === true);\n const selected = matched.length > 0 ? matched : branchSchemas;\n for (const branch of selected) {\n schemas.push(...collectProjectionSchemas(root, branch, value, depth + 1));\n }\n }\n return schemas;\n}\n\nfunction projectValueToCapabilitySchema(\n root: ProjectionSchema,\n schema: ProjectionSchema,\n value: unknown,\n depth = 0\n): unknown | typeof OMIT_PROJECTED_VALUE {\n if (depth > 64) return OMIT_PROJECTED_VALUE;\n const schemas = collectProjectionSchemas(root, schema, value, depth);\n\n const allowedValues = schemas.flatMap(candidate => (Array.isArray(candidate.enum) ? candidate.enum : []));\n if (allowedValues.length > 0 && !allowedValues.some(allowed => Object.is(allowed, value))) {\n return OMIT_PROJECTED_VALUE;\n }\n const constants = schemas.filter(candidate => Object.hasOwn(candidate, 'const')).map(candidate => candidate.const);\n if (constants.length > 0 && !constants.some(constant => Object.is(constant, value))) {\n return OMIT_PROJECTED_VALUE;\n }\n\n if (Array.isArray(value)) {\n const itemSchemas = schemas.map(candidate => asProjectionSchema(candidate.items)).filter(Boolean);\n if (itemSchemas.length === 0) return value;\n const itemSchema: ProjectionSchema = { allOf: itemSchemas };\n return value\n .map(item => projectValueToCapabilitySchema(root, itemSchema, item, depth + 1))\n .filter(item => item !== OMIT_PROJECTED_VALUE);\n }\n\n if (!isPlainObject(value)) return value;\n\n const propertySchemas = new Map<string, ProjectionSchema[]>();\n for (const candidate of schemas) {\n const properties = asProjectionSchema(candidate.properties);\n if (!properties) continue;\n for (const [key, propertySchemaValue] of Object.entries(properties)) {\n const propertySchema = asProjectionSchema(propertySchemaValue);\n if (!propertySchema) continue;\n const existing = propertySchemas.get(key) ?? [];\n existing.push(propertySchema);\n propertySchemas.set(key, existing);\n }\n }\n\n if (propertySchemas.size === 0) {\n const mapValueSchema = schemas\n .map(candidate => asProjectionSchema(candidate.additionalProperties))\n .find((candidate): candidate is ProjectionSchema => !!candidate);\n if (!mapValueSchema) return value;\n const projectedMap: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const projected = projectValueToCapabilitySchema(root, mapValueSchema, entry, depth + 1);\n if (projected !== OMIT_PROJECTED_VALUE) projectedMap[key] = projected;\n }\n return projectedMap;\n }\n\n const projectedObject: Record<string, unknown> = {};\n for (const [key, candidateSchemas] of propertySchemas) {\n if (!Object.hasOwn(value, key)) continue;\n const projected = projectValueToCapabilitySchema(root, { allOf: candidateSchemas }, value[key], depth + 1);\n if (projected !== OMIT_PROJECTED_VALUE) projectedObject[key] = projected;\n }\n return projectedObject;\n}\n\nfunction projectCapabilitiesToVersion(data: GetAdCPCapabilitiesResponse, version: string): GetAdCPCapabilitiesResponse {\n const validator = getValidator('get_adcp_capabilities', 'sync', version);\n const schema = asProjectionSchema((validator as { schema?: unknown } | undefined)?.schema);\n if (!schema) return data;\n const projected = projectValueToCapabilitySchema(schema, schema, data);\n if (!isPlainObject(projected)) return data;\n const result = projected as unknown as GetAdCPCapabilitiesResponse;\n\n // The 3.0 response contract predates account inference: every media-buy\n // seller must advertise a billing party even when the modern source\n // capability relied on implicit-account defaults.\n if (result.supported_protocols?.includes('media_buy')) {\n if (!result.account) {\n result.account = { supported_billing: ['agent'] };\n } else if (!Array.isArray(result.account.supported_billing) || result.account.supported_billing.length === 0) {\n result.account.supported_billing = ['agent'];\n }\n }\n\n // A modern request-signing block can contain only post-3.0 fields. After\n // projection, omit that empty optional block rather than emitting an object\n // that violates 3.0's required `supported` discriminator.\n if (result.request_signing && Object.keys(result.request_signing).length === 0) {\n delete result.request_signing;\n }\n return result;\n}\n\n/** @internal Shared by the platform adapter's principal resolver and dispatcher gate. */\nexport const COMPACT_MEDIA_BUY_MUTATION_TOOLS = new Set<string>([\n 'request_proposals',\n 'refine_proposals',\n 'decline_proposals',\n 'buy_products',\n 'accept_proposal',\n 'control_media_buy',\n]);\n\n// ---------------------------------------------------------------------------\n// Domain → tool name mapping\n// ---------------------------------------------------------------------------\n\ntype HandlerEntry = { handlerKey: string; toolName: string };\n\nconst MEDIA_BUY_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getProducts', toolName: 'get_products' },\n { handlerKey: 'listProducts', toolName: 'list_products' },\n { handlerKey: 'requestProposals', toolName: 'request_proposals' },\n { handlerKey: 'declineProposals', toolName: 'decline_proposals' },\n { handlerKey: 'buyProducts', toolName: 'buy_products' },\n { handlerKey: 'acceptProposal', toolName: 'accept_proposal' },\n { handlerKey: 'controlMediaBuy', toolName: 'control_media_buy' },\n { handlerKey: 'createMediaBuy', toolName: 'create_media_buy' },\n { handlerKey: 'updateMediaBuy', toolName: 'update_media_buy' },\n { handlerKey: 'getMediaBuys', toolName: 'get_media_buys' },\n { handlerKey: 'getMediaBuyDelivery', toolName: 'get_media_buy_delivery' },\n { handlerKey: 'providePerformanceFeedback', toolName: 'provide_performance_feedback' },\n { handlerKey: 'listCreativeFormats', toolName: 'list_creative_formats' },\n { handlerKey: 'syncCreatives', toolName: 'sync_creatives' },\n { handlerKey: 'listCreatives', toolName: 'list_creatives' },\n];\n\nconst MEDIA_BUY_PROTOCOL_ENTRIES = MEDIA_BUY_ENTRIES.filter(\n ({ handlerKey }) => !['listCreativeFormats', 'syncCreatives', 'listCreatives'].includes(handlerKey)\n);\n\nconst PROPOSAL_NEGOTIATION_ENTRIES: HandlerEntry[] = [{ handlerKey: 'refineProposals', toolName: 'refine_proposals' }];\n\nconst EVENT_TRACKING_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'syncEventSources', toolName: 'sync_event_sources' },\n { handlerKey: 'logEvent', toolName: 'log_event' },\n { handlerKey: 'syncAudiences', toolName: 'sync_audiences' },\n { handlerKey: 'syncCatalogs', toolName: 'sync_catalogs' },\n];\n\nconst SIGNALS_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getSignals', toolName: 'get_signals' },\n { handlerKey: 'activateSignal', toolName: 'activate_signal' },\n];\n\nconst CREATIVE_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'listCreativeFormats', toolName: 'list_creative_formats' },\n { handlerKey: 'listTransformers', toolName: 'list_transformers' },\n { handlerKey: 'buildCreative', toolName: 'build_creative' },\n { handlerKey: 'previewCreative', toolName: 'preview_creative' },\n { handlerKey: 'listCreatives', toolName: 'list_creatives' },\n { handlerKey: 'syncCreatives', toolName: 'sync_creatives' },\n { handlerKey: 'getCreativeDelivery', toolName: 'get_creative_delivery' },\n];\n\nconst GOVERNANCE_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'createPropertyList', toolName: 'create_property_list' },\n { handlerKey: 'updatePropertyList', toolName: 'update_property_list' },\n { handlerKey: 'getPropertyList', toolName: 'get_property_list' },\n { handlerKey: 'listPropertyLists', toolName: 'list_property_lists' },\n { handlerKey: 'deletePropertyList', toolName: 'delete_property_list' },\n { handlerKey: 'createCollectionList', toolName: 'create_collection_list' },\n { handlerKey: 'updateCollectionList', toolName: 'update_collection_list' },\n { handlerKey: 'getCollectionList', toolName: 'get_collection_list' },\n { handlerKey: 'listCollectionLists', toolName: 'list_collection_lists' },\n { handlerKey: 'deleteCollectionList', toolName: 'delete_collection_list' },\n { handlerKey: 'listContentStandards', toolName: 'list_content_standards' },\n { handlerKey: 'getContentStandards', toolName: 'get_content_standards' },\n { handlerKey: 'createContentStandards', toolName: 'create_content_standards' },\n { handlerKey: 'updateContentStandards', toolName: 'update_content_standards' },\n { handlerKey: 'calibrateContent', toolName: 'calibrate_content' },\n { handlerKey: 'validateContentDelivery', toolName: 'validate_content_delivery' },\n { handlerKey: 'getMediaBuyArtifacts', toolName: 'get_media_buy_artifacts' },\n { handlerKey: 'getCreativeFeatures', toolName: 'get_creative_features' },\n { handlerKey: 'syncPlans', toolName: 'sync_plans' },\n { handlerKey: 'checkGovernance', toolName: 'check_governance' },\n { handlerKey: 'reportPlanOutcome', toolName: 'report_plan_outcome' },\n { handlerKey: 'reportPlanAdjustment', toolName: 'report_plan_adjustment' },\n { handlerKey: 'getPlanAuditLogs', toolName: 'get_plan_audit_logs' },\n];\n\nconst PROTOCOL_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'syncAgentNotificationConfigs', toolName: 'sync_agent_notification_configs' },\n];\n\nconst ACCOUNT_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'listAccounts', toolName: 'list_accounts' },\n { handlerKey: 'syncAccounts', toolName: 'sync_accounts' },\n { handlerKey: 'syncGovernance', toolName: 'sync_governance' },\n { handlerKey: 'getAccountFinancials', toolName: 'get_account_financials' },\n { handlerKey: 'reportUsage', toolName: 'report_usage' },\n];\n\nconst SI_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getOffering', toolName: 'si_get_offering' },\n { handlerKey: 'initiateSession', toolName: 'si_initiate_session' },\n { handlerKey: 'sendMessage', toolName: 'si_send_message' },\n { handlerKey: 'terminateSession', toolName: 'si_terminate_session' },\n];\n\nconst BRAND_RIGHTS_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getBrandIdentity', toolName: 'get_brand_identity' },\n { handlerKey: 'getRights', toolName: 'get_rights' },\n { handlerKey: 'acquireRights', toolName: 'acquire_rights' },\n { handlerKey: 'updateRights', toolName: 'update_rights' },\n];\n\n// ---------------------------------------------------------------------------\n// Protocol detection\n// ---------------------------------------------------------------------------\n\nfunction hasDomainHandler(entries: readonly HandlerEntry[], handlers: object | undefined): boolean {\n if (handlers === undefined) return false;\n const candidate = handlers as Record<string, unknown>;\n return entries.some(({ handlerKey }) => typeof candidate[handlerKey] === 'function');\n}\n\n/**\n * Derive buyer-visible protocol domains from the handler group that owns each\n * operation, not from the flattened tools/list catalog. Several compatibility\n * tools intentionally appear in more than one protocol's discovery list\n * (`list_creative_formats`, `list_creatives`, and `sync_creatives`), so tool\n * names alone cannot distinguish a creative agent from a media-buy seller.\n * Utility groups (accounts, tasks, event tracking, protocol helpers, custom\n * tools) do not independently activate a protocol domain.\n */\nfunction detectProtocolsFromHandlers<TAccount>(config: AdcpServerConfig<TAccount>): AdcpProtocol[] {\n const protocols: AdcpProtocol[] = [];\n const declaresSalesSpecialism = config.capabilities?.specialisms?.some(specialism => specialism.startsWith('sales-'));\n const hasAnyMediaBuyHandler = hasDomainHandler(MEDIA_BUY_ENTRIES, config.mediaBuy);\n if (\n hasDomainHandler(MEDIA_BUY_PROTOCOL_ENTRIES, config.mediaBuy) ||\n hasDomainHandler(PROPOSAL_NEGOTIATION_ENTRIES, config.proposalNegotiation) ||\n (declaresSalesSpecialism && hasAnyMediaBuyHandler)\n ) {\n protocols.push('media_buy');\n }\n if (hasDomainHandler(SIGNALS_ENTRIES, config.signals)) protocols.push('signals');\n if (hasDomainHandler(GOVERNANCE_ENTRIES, config.governance)) protocols.push('governance');\n if (hasDomainHandler(CREATIVE_ENTRIES, config.creative)) protocols.push('creative');\n if (hasDomainHandler(SI_ENTRIES, config.sponsoredIntelligence)) protocols.push('sponsored_intelligence');\n if (hasDomainHandler(BRAND_RIGHTS_ENTRIES, config.brandRights)) protocols.push('brand');\n return protocols;\n}\n\n// ---------------------------------------------------------------------------\n// Tool coherence warnings\n// ---------------------------------------------------------------------------\n\nconst COHERENCE_RULES: [string, string, string][] = [\n [\n 'create_media_buy',\n 'get_products',\n 'create_media_buy without get_products — buyers cannot discover products before purchasing',\n ],\n [\n 'update_media_buy',\n 'get_media_buys',\n 'update_media_buy without get_media_buys — buyers cannot look up what to modify',\n ],\n [\n 'activate_signal',\n 'get_signals',\n 'activate_signal without get_signals — buyers cannot discover signals before activating',\n ],\n [\n 'sync_creatives',\n 'list_creative_formats',\n 'sync_creatives without list_creative_formats — buyers cannot discover valid formats',\n ],\n];\n\nfunction checkCoherence(toolNames: Set<string>, logger: AdcpLogger): void {\n for (const [tool, requires, message] of COHERENCE_RULES) {\n if (toolNames.has(tool) && !toolNames.has(requires)) {\n logger.warn(message);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Response detection\n// ---------------------------------------------------------------------------\n\nfunction isFormattedResponse(value: unknown): value is McpToolResponse {\n if (value == null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n return Array.isArray(obj.content) && 'structuredContent' in obj;\n}\n\n/**\n * Detect an AdCP Submitted envelope (async task acknowledgement).\n *\n * Every *Submitted arm in the generated types has `status: 'submitted'`\n * plus a required `task_id: string`. The discriminant is stable enough\n * to use for routing at dispatch time without per-tool knowledge.\n */\nfunction isSubmittedEnvelope(value: unknown): value is { status: 'submitted'; task_id: string; message?: string } {\n if (value == null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n return obj.status === 'submitted' && typeof obj.task_id === 'string';\n}\n\n/**\n * Detect an AdCP *Error arm (union member, not the framework `adcp_error`\n * envelope). Every *Error interface in the generated types carries a\n * required `errors: Error[]` and a narrow set of allowed siblings\n * (`context`, `ext`, plus a couple of tool-specific extras). Success\n * arms may have optional advisory fields but never a required `errors`\n * array — the `status === 'submitted'` exclusion keeps us from\n * confusing a Submitted envelope that advisory-echoes errors as an\n * Error arm. The set of allowed sibling keys is intentionally narrow:\n * any other top-level key means the payload carries Success-only fields\n * (`media_buy_id`, `creatives`, `signal_id`, ...) and should fall\n * through to the response builder.\n */\nconst ERROR_ARM_ALLOWED_KEYS = new Set(['errors', 'context', 'ext', 'success', 'conflicting_standards_id']);\nfunction isErrorArm(value: unknown): value is { errors: unknown[]; context?: unknown; ext?: unknown } {\n if (value == null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n if (!Array.isArray(obj.errors)) return false;\n if ('status' in obj) return false;\n for (const key of Object.keys(obj)) {\n if (!ERROR_ARM_ALLOWED_KEYS.has(key)) return false;\n }\n return true;\n}\n\nfunction sanitizePayloadError(value: unknown): unknown {\n if (!isPlainObject(value)) return value;\n const code = value.code;\n if (typeof code !== 'string') return value;\n const sanitized = applyAdcpErrorAllowlist(code, value);\n if (!isStandardErrorCode(code)) return sanitized;\n\n const safe = sanitized as unknown as Record<string, unknown>;\n const projected: Record<string, unknown> = {\n code,\n message: typeof safe.message === 'string' ? safe.message : 'operation failed',\n recovery: STANDARD_ERROR_CODES[code].recovery,\n };\n for (const key of ['field', 'suggestion', 'retry_after', 'issues']) {\n if (safe[key] !== undefined) projected[key] = safe[key];\n }\n if (safe.details !== undefined) {\n projected.details = safe.details;\n }\n return projected;\n}\n\nfunction sanitizePayloadErrors(sc: Record<string, unknown>): boolean {\n if (!Array.isArray(sc.errors)) return false;\n const sanitized = sc.errors.map(sanitizePayloadError);\n const changed = sanitized.some((value, index) => value !== (sc.errors as unknown[])[index]);\n if (changed) sc.errors = sanitized;\n return changed;\n}\n\n/**\n * Wrap a Submitted envelope returned directly by a handler. Skips the\n * Success-builder defaults (`revision`, `confirmed_at`, `valid_actions`)\n * — those fields are specific to `CreateMediaBuySuccess` and would\n * corrupt the async-task shape if applied.\n */\nfunction wrapSubmittedEnvelope(value: { status: 'submitted'; task_id: string; message?: string }): McpToolResponse {\n const summary = value.message ?? `Task ${value.task_id} submitted`;\n return {\n content: [{ type: 'text', text: summary }],\n structuredContent: value as unknown as Record<string, unknown>,\n };\n}\n\n/**\n * Wrap an *Error arm returned directly by a handler. Preserves the\n * generated-type shape (`errors: Error[]`) on `structuredContent` so\n * buyers reading the typed response union see the exact branch the\n * spec defines; also sets `isError: true` so the MCP-level signal\n * matches `adcp_error` envelopes, which keeps `isErrorResponse()` and\n * `response-validation: strict` consistent across both error paths.\n */\nfunction wrapErrorArm(value: { errors: unknown[] }): McpToolResponse {\n const sanitizedErrors = value.errors.map(sanitizePayloadError);\n const firstError = sanitizedErrors[0] as { code?: unknown; message?: unknown } | undefined;\n const summary =\n firstError && typeof firstError === 'object'\n ? `${typeof firstError.code === 'string' ? firstError.code : 'ERROR'}: ${typeof firstError.message === 'string' ? firstError.message : 'operation failed'}`\n : 'operation failed';\n return {\n content: [{ type: 'text', text: summary }],\n isError: true,\n structuredContent: { ...value, errors: sanitizedErrors } as unknown as Record<string, unknown>,\n };\n}\n\n/**\n * Defence-in-depth sanitizer for handler-returned error envelopes.\n *\n * `adcpError()` filters its own output against `ADCP_ERROR_FIELD_ALLOWLIST`,\n * but a handler that hand-rolls `{ isError: true, structuredContent: {\n * adcp_error: {...} } }` (or constructs the envelope through a different\n * builder) bypasses that sanitizer. The storyboard invariant\n * `idempotency.conflict_no_payload_leak` catches this at conformance-test\n * time, but production traffic would be unprotected — so we re-apply the\n * allowlist here too. Silent no-op when the code has no registered entry,\n * or when `structuredContent.adcp_error` is missing its `code` field.\n *\n * Keeps L2 (`content[0].text`) and L3 (`structuredContent`) in lockstep —\n * both transport layers get the same filtered payload.\n */\nfunction sanitizeAdcpErrorEnvelope(response: McpToolResponse): void {\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n const err = sc.adcp_error as Record<string, unknown> | undefined;\n if (!err || typeof err !== 'object') return;\n const code = err.code;\n if (typeof code !== 'string') return;\n const allow = ADCP_ERROR_FIELD_ALLOWLIST[code];\n if (!allow) return;\n\n const filtered = applyAdcpErrorAllowlist(code, err);\n const filteredRecord = filtered as unknown as Record<string, unknown>;\n let changed = false;\n for (const key of new Set([...Object.keys(err), ...Object.keys(filtered)])) {\n if (err[key] !== filteredRecord[key]) {\n changed = true;\n break;\n }\n }\n if (!changed) return;\n\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.adcp_error = filtered;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\n/**\n * Fields valid on a payload-layer `errors[]` item per the bundled\n * `core/error.json` schema. Both layers of the AdCP error model carry\n * the same conceptual fields, so the dispatcher projects from one to\n * the other 1:1 — but the projection still needs to know which keys\n * are part of the contract.\n *\n * `recovery` is included even though the schema marks it optional: it\n * is the autonomous-buyer dispatch signal, and dropping it on the\n * payload while keeping it on the envelope would force callers to read\n * both layers to classify the failure. Mirroring matches the spec's\n * intent (both layers carry the same data) without surprising adopters\n * who rely on either side.\n */\nconst PAYLOAD_ERROR_FIELDS: ReadonlySet<string> = new Set([\n 'code',\n 'message',\n 'recovery',\n 'field',\n 'suggestion',\n 'retry_after',\n 'issues',\n 'details',\n]);\n\nfunction projectEnvelopeToPayloadError(envelope: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(envelope)) {\n if (PAYLOAD_ERROR_FIELDS.has(key)) out[key] = envelope[key];\n }\n return out;\n}\n\nfunction projectPayloadErrorToEnvelope(payloadError: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(payloadError)) {\n if (PAYLOAD_ERROR_FIELDS.has(key)) out[key] = payloadError[key];\n }\n return out;\n}\n\n/**\n * Two-layer error emission for tools whose response schema declares a\n * typed Error arm (`errors[]` required) at the top level.\n *\n * The AdCP spec (RFC `docs/proposals/adcperror-two-layer-emission.md`,\n * `error-code.json#GOVERNANCE_DENIED`) requires both layers on the\n * failure path:\n *\n * - **Envelope layer**: `structuredContent.adcp_error: {code, message, ...}`\n * — the cross-protocol marker, programmatic extraction.\n * - **Payload layer**: `structuredContent.errors: [{code, message, ...}]`\n * — the typed Error arm of the response union.\n *\n * `adcpError()` emits the envelope only; `wrapErrorArm()` emits the\n * payload only. This dispatcher seam fills in whichever layer is\n * missing so the wire is two-layer regardless of which helper the\n * adopter used. Idempotent on already-two-layer payloads (presence of\n * both `adcp_error` and `errors[]` is a no-op).\n *\n * Gated on `toolsWithErrorArm` derived from the bundled schema cache:\n * tools whose schema doesn't define `errors[]` (`get_adcp_capabilities`,\n * `tasks/get`, `get_products`, etc.) are left unchanged.\n *\n * Scope is the failure path only — early returns when neither layer is\n * present. Success-arm responses pass through untouched.\n */\nfunction enrichErrorTwoLayer(\n response: McpToolResponse,\n toolName: string,\n toolsWithErrorArm: ReadonlyMap<string, ErrorArmDescriptor>\n): void {\n const descriptor = toolsWithErrorArm.get(toolName);\n if (!descriptor) return;\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n\n const env = sc.adcp_error as Record<string, unknown> | undefined;\n const envValid = env != null && typeof env === 'object' && typeof env.code === 'string';\n const payloadList = sc.errors;\n const payloadValid = Array.isArray(payloadList) && payloadList.length > 0;\n const mirrorsBeforePayloadSanitization = contentTextMirrorsStructuredContent(response, sc);\n if (payloadValid && sanitizePayloadErrors(sc)) {\n syncContentJsonText(response, sc, mirrorsBeforePayloadSanitization);\n }\n\n // Path A: envelope present, payload missing → synthesise payload-layer\n // `errors[]` from the envelope. The `adcpError()` builder always lands\n // here; hand-rolled `{adcp_error: {...}}` envelopes too.\n if (envValid && !payloadValid) {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.errors = [projectEnvelopeToPayloadError(env)];\n applyArmDiscriminators(sc, descriptor);\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n return;\n }\n\n // Path B: payload present, envelope missing → synthesise envelope from\n // the first payload item. `wrapErrorArm()` lands here when adopters\n // return a typed Error arm directly.\n if (!envValid && payloadValid) {\n const first = (sc.errors as unknown[])[0];\n if (first && typeof first === 'object') {\n const projected = projectPayloadErrorToEnvelope(first as Record<string, unknown>);\n // Only stamp the envelope if the payload's first item carries the\n // minimum spec-required `code` + `message`. A malformed Error arm\n // (already warned about by the dispatcher's `isErrorArm` branch)\n // shouldn't synthesise a half-formed envelope.\n if (typeof projected.code === 'string' && typeof projected.message === 'string') {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.adcp_error = projected;\n applyArmDiscriminators(sc, descriptor);\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n }\n }\n return;\n }\n\n // Path C: both layers present (handler emitted a fully-formed\n // two-layer payload). Idempotent passthrough — adopters that already\n // ship the correct shape are not mutated. Discriminator constants\n // are NOT stamped here: an adopter that built both layers also chose\n // their own discriminator value, and overriding it could break the\n // arm they intended to land in.\n}\n\n/**\n * Stamp a tool's Error-arm discriminator constants on the response\n * payload. For most tools the descriptor is empty (the arm requires\n * `errors[]` only) and this is a no-op. `update_content_standards` is\n * the canonical case: its Error arm declares `success: { const: false }`\n * — without this stamp, the synthesised payload would still match the\n * Success arm's `success: false` value (absent → undefined, neither\n * `const: true` nor `const: false`), so the schema would reject the\n * response on either branch.\n *\n * Only stamps fields that are NOT already set on the payload — adopters\n * who deliberately set the discriminator (e.g. mid-migration) keep\n * their choice.\n */\nfunction applyArmDiscriminators(sc: Record<string, unknown>, descriptor: ErrorArmDescriptor): void {\n for (const [key, value] of Object.entries(descriptor.extraRequired)) {\n if (!(key in sc)) sc[key] = value;\n }\n}\n\n/**\n * Detect the framework's JSON-bodied L2 fallback before mutating L3. Merely\n * parsing as JSON is insufficient: an adopter-authored summary may itself be\n * a JSON object and must remain exact text.\n */\nfunction contentTextMirrorsStructuredContent(\n response: McpToolResponse,\n structuredContent: Record<string, unknown>\n): boolean {\n if (!Array.isArray(response.content)) return false;\n const first = response.content[0];\n return first?.type === 'text' && first.text === JSON.stringify(structuredContent);\n}\n\nfunction syncContentJsonText(\n response: McpToolResponse,\n structuredContent: Record<string, unknown>,\n mirroredBeforeMutation: boolean\n): void {\n if (!mirroredBeforeMutation || !Array.isArray(response.content)) return;\n const first = response.content[0];\n if (!first || first.type !== 'text') return;\n first.text = JSON.stringify(structuredContent);\n}\n\nfunction missingGetProductsCacheScopeIssue(): ValidationIssue {\n return {\n pointer: '/cache_scope',\n message: \"must have required property 'cache_scope'\",\n keyword: 'required',\n schemaPath: '#/required',\n hint: '`get_products` responses with `products` or `unchanged: true` must include `cache_scope`: use `public` for the universal rate card, `account` for account-specific overlays.',\n };\n}\n\nfunction normalizeGetProductsCacheScope(\n response: McpToolResponse,\n params: unknown,\n account: unknown,\n authInfo: unknown,\n exposeSchemaPath: boolean\n): McpToolResponse | undefined {\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return undefined;\n if (!Array.isArray(sc.products) && sc.unchanged !== true) return undefined;\n if (sc.cache_scope !== undefined) return undefined;\n\n const request =\n params && typeof params === 'object' && !Array.isArray(params) ? (params as Record<string, unknown>) : {};\n if (request.account != null || account != null || authInfo != null) {\n return adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload('get_products', 'response', [missingGetProductsCacheScopeIssue()], {\n exposeSchemaPath,\n })\n );\n }\n\n // Safe inference only: a product feed with neither an inline account nor an\n // auth context cannot contain an account-specific overlay, so it is cacheable\n // as the public layer. Any account or auth context makes omission ambiguous;\n // strict response validation should surface that.\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.cache_scope = 'public';\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n return undefined;\n}\n\n// Echo the request context into a formatted MCP tool response so buyers can\n// trace correlation_id across both success and error responses. Only plain\n// objects are echoed: `si_get_offering` and `si_initiate_session` override\n// the request schema's `context` to a domain-specific string, while the\n// response schema still requires the protocol echo object — copying a\n// string there would fail response validation.\nfunction injectContextIntoResponse(response: McpToolResponse, context: unknown): void {\n if (context === null || typeof context !== 'object' || Array.isArray(context)) return;\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (sc && typeof sc === 'object' && !('context' in sc)) {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.context = context;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n }\n}\n\n/**\n * Inject `adcp_version` into the response body so the seller echoes the\n * release served per spec PR `adcontextprotocol/adcp#3493`. Mirrors\n * `injectContextIntoResponse`'s structuredContent + L2-text-fallback dual\n * write so MCP clients reading either layer see the field. Only injects on\n * AdCP 3.1+ — 3.0 schemas don't define the field.\n *\n * `servedVersion` is the seller's release-precision identifier (output of\n * `resolveBundleKey(adcpVersion)`). For now it always reflects the seller's\n * own pin; downshift (3.1 seller serving a 3.0 buyer at 3.0) is a follow-up.\n */\n/**\n * Stamp the v3 protocol envelope's required `status` field on success\n * responses. Per AdCP #4876, every task response envelope MUST carry\n * `status`; synchronous calls emit `\"completed\"`. Mirrors\n * `injectContextIntoResponse`'s structuredContent + L2-text-fallback\n * dual write so MCP clients reading either layer see the field.\n *\n * Skipped when:\n * - `isError: true` — error envelopes carry their own status semantics\n * (`failed` / `rejected` / etc.). Wired separately by the adcp_error\n * path; not this seam's concern.\n * - `structuredContent.status` already present — handler-declared status\n * takes precedence. Preserves:\n * • the Submitted envelope's `status: 'submitted'`,\n * • payloads whose typed shape carries its own top-level `status`\n * discriminator (`CreateMediaBuySuccess.status: MediaBuyStatus`,\n * `UpdateMediaBuySuccess.status: MediaBuyStatus`, the\n * `cancelMediaBuyResponse` builder's hard-coded `status: 'canceled'`).\n * The MediaBuyStatus/TaskStatus collision at the same top-level key is\n * a spec ambiguity tracked at adcp-client#1897; this seam refuses to\n * destroy payload semantics until the spec disambiguates.\n */\nfunction injectEnvelopeStatusIntoResponse(response: McpToolResponse, toolName: string): void {\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n if ('status' in sc) return;\n if (STATUS_FREE_SYNC_RESPONSE_TOOLS.has(toolName)) return;\n // AdCP 3.1.0-beta.2+ requires envelope `status` on EVERY response, error\n // or otherwise. Map MCP's `isError` to the wire-level task state:\n // - `isError: true` → `'failed'` (task explicitly failed)\n // - `isError: false`/absent → `'completed'` (default for success path)\n // Tools that need richer states (`submitted`, `working`, `input-required`)\n // should set `status` themselves; this injector only fills in the default\n // when the handler hasn't.\n const status = response.isError === true ? 'failed' : 'completed';\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.status = status;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\nconst MEDIA_BUY_RESPONSE_TOOLS_REQUIRING_STATUS_SPLIT = new Set([\n 'create_media_buy',\n 'update_media_buy',\n 'cancel_media_buy',\n]);\n\nconst MEDIA_BUY_STATUS_VALUES = new Set([\n 'pending_creatives',\n 'pending_start',\n 'active',\n 'paused',\n 'completed',\n 'rejected',\n 'canceled',\n]);\n\nfunction normalizeMediaBuyStatusCollision(response: McpToolResponse, toolName: string): void {\n if (!MEDIA_BUY_RESPONSE_TOOLS_REQUIRING_STATUS_SPLIT.has(toolName)) return;\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n const status = sc.status;\n if (typeof status !== 'string' || !MEDIA_BUY_STATUS_VALUES.has(status)) return;\n const looksLikeMediaBuyPayload =\n typeof sc.media_buy_id === 'string' || 'media_buy_status' in sc || Array.isArray(sc.packages);\n if (!looksLikeMediaBuyPayload) return;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n if (sc.media_buy_status === undefined) sc.media_buy_status = status;\n delete sc.status;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\nfunction injectVersionIntoResponse(response: McpToolResponse, servedVersion: string | undefined): void {\n if (!servedVersion) return;\n // Normalize to release-precision (`3.1-beta.3`) before emitting — the wire\n // regex rejects full-semver (`3.1.0-beta.3`). Bundle metadata is published\n // with the patch digit; on-the-wire `adcp_version` is not. See the spec\n // note on `adcp_version` in `core.generated.ts` and the helper itself.\n const wireVersion = toReleasePrecisionVersion(servedVersion);\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (sc && typeof sc === 'object' && !('adcp_version' in sc)) {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.adcp_version = wireVersion;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Signed-requests preTransport builder\n// ---------------------------------------------------------------------------\n\ntype EffectiveSignedRequestPolicy = NonNullable<GetAdCPCapabilitiesResponse['request_signing']> & {\n supported: true;\n covers_content_digest: ContentDigestPolicy;\n required_for: string[];\n};\n\nfunction resolveEffectiveSignedRequestPolicy(\n signedRequests: SignedRequestsConfig,\n capabilityRequestSigning: GetAdCPCapabilitiesResponse['request_signing'] | undefined,\n adcpVersion?: string\n): EffectiveSignedRequestPolicy {\n const signingRelease = adcpVersion ? parseAdcpRelease(adcpVersion) : undefined;\n const requiredFor = signedRequests.required_for ??\n capabilityRequestSigning?.required_for ?? [...MUTATING_TASKS, 'get_products'];\n const protocolMethodsRequiredFor =\n signedRequests.protocol_methods_required_for ?? capabilityRequestSigning?.protocol_methods_required_for;\n const coversContentDigest: ContentDigestPolicy =\n signedRequests.covers_content_digest ??\n capabilityRequestSigning?.covers_content_digest ??\n (signingRelease?.major === 3 && signingRelease.minor >= 2 ? 'required' : 'either');\n return {\n ...capabilityRequestSigning,\n supported: true,\n covers_content_digest: coversContentDigest,\n required_for: requiredFor,\n ...(protocolMethodsRequiredFor ? { protocol_methods_required_for: protocolMethodsRequiredFor } : {}),\n };\n}\n\n/**\n * Build a `preTransport` middleware that runs `createExpressVerifier` against\n * the incoming Node request/response. The returned function matches the shape\n * `serve({ preTransport })` expects: it resolves to `true` when the verifier\n * has already written a 401 (headers sent), `false` otherwise.\n *\n * `serve()` buffers the request body into `req.rawBody` before invoking the\n * preTransport hook, so the verifier sees the exact bytes the signer hashed\n * for Content-Digest. For MCP the operation name comes from the JSON-RPC\n * `params.name`; the resolver below falls back to `undefined` for non-JSON or\n * non-`tools/call` bodies, which makes the verifier treat them as not-in-\n * `required_for` rather than rejecting (discovery probes, health checks).\n */\nfunction buildSignedRequestsPreTransport(\n signedRequests: SignedRequestsConfig,\n effectiveRequestSigning: EffectiveSignedRequestPolicy,\n adcpVersion?: string\n): AdcpPreTransport {\n const requiredFor = effectiveRequestSigning.required_for ?? [];\n const verifier = createExpressVerifier({\n capability: {\n supported: true,\n covers_content_digest: effectiveRequestSigning.covers_content_digest,\n required_for: requiredFor,\n ...(effectiveRequestSigning.protocol_methods_required_for\n ? { protocol_methods_required_for: effectiveRequestSigning.protocol_methods_required_for }\n : {}),\n },\n jwks: signedRequests.jwks,\n replayStore: signedRequests.replayStore,\n revocationStore: signedRequests.revocationStore,\n adcpVersion,\n ...(signedRequests.agentUrlForKeyid ? { agentUrlForKeyid: signedRequests.agentUrlForKeyid } : {}),\n resolveOperation: req => {\n const raw = (req as { rawBody?: string }).rawBody;\n if (!raw) return undefined;\n try {\n const parsed = JSON.parse(raw) as unknown;\n const messages = Array.isArray(parsed) ? parsed : [parsed];\n const operations = messages.flatMap(message => {\n if (message == null || typeof message !== 'object') return [];\n const candidate = message as { method?: unknown; params?: { name?: unknown } };\n return candidate.method === 'tools/call' && typeof candidate.params?.name === 'string'\n ? [candidate.params.name]\n : [];\n });\n return operations.find(operation => requiredFor.includes(operation)) ?? operations[0];\n } catch {\n // Non-JSON or malformed body — let transport handle rejection.\n }\n return undefined;\n },\n });\n\n return async function adcpPreTransport(req, res) {\n const serveContext = getServeRequestContext(req);\n const canonicalPublicUrl = serveContext?.publicUrl ? new URL(serveContext.publicUrl) : undefined;\n const reqShim: ExpressLike = {\n method: req.method ?? 'POST',\n url: req.url ?? '/mcp',\n originalUrl: req.url ?? '/mcp',\n headers: req.headers,\n rawBody: req.rawBody ?? '',\n protocol: canonicalPublicUrl?.protocol.replace(/:$/, '') ?? 'http',\n get(name: string) {\n const normalizedName = name.toLowerCase();\n if (canonicalPublicUrl && normalizedName === 'host') return canonicalPublicUrl.host;\n if (canonicalPublicUrl && normalizedName === 'x-forwarded-proto') {\n return canonicalPublicUrl.protocol.replace(/:$/, '');\n }\n const v = req.headers[name.toLowerCase()];\n return Array.isArray(v) ? v.join(', ') : v;\n },\n };\n const resShim = {\n status(code: number) {\n res.statusCode = code;\n return {\n set(k: string, v: string) {\n res.setHeader(k, v);\n return {\n json(body: unknown) {\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(body));\n },\n };\n },\n };\n },\n };\n\n let handled = false;\n let verifierCompleted = false;\n // The verifier calls `next(err?)` in the success / error path, but the\n // 401 RequestSignatureError path writes the response and returns WITHOUT\n // calling next. Race the next-callback against the response's 'finish' /\n // 'close' events so a terminal 401 resolves the promise; otherwise the\n // wrapper hangs forever and the agent server leaks (one McpServer per\n // unsigned request under attack).\n //\n // Security: if 'close' fires before the verifier completes (client\n // aborted the TCP connection mid-JWKS-fetch), we MUST NOT fall through\n // to the MCP transport — doing so would execute the tool handler\n // without a verified signature on an attacker-dropped connection. Mark\n // handled=true so serve.ts skips dispatch.\n await new Promise<void>(resolve => {\n let resolved = false;\n const done = () => {\n if (resolved) return;\n resolved = true;\n resolve();\n };\n res.once('finish', () => {\n if (res.writableEnded) handled = true;\n done();\n });\n res.once('close', () => {\n if (!verifierCompleted) handled = true;\n done();\n });\n verifier(reqShim, resShim, err => {\n verifierCompleted = true;\n if (err) {\n // Log internally; a leaked stack trace to the caller would\n // enumerate the verifier pipeline (js/stack-trace-exposure).\n // Narrow to name+code only — full error stringification can embed\n // JWKS URLs from transport failures, which leaks counterparty\n // key-discovery topology on shared log aggregators.\n const errName = (err as Error).name || 'Error';\n const errCode = (err as { code?: string }).code ?? 'unknown';\n console.error(`[adcp/signed-requests] verifier middleware error: ${errName} (${errCode})`);\n if (!res.writableEnded) {\n res.statusCode = 500;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ error: 'verifier_error' }));\n }\n handled = true;\n }\n const verifiedSigner = reqShim.verifiedSigner as import('../signing/types').VerifiedSigner | undefined;\n if (!err && verifiedSigner) {\n try {\n const principal = principalForVerifiedSigner(verifiedSigner, signedRequests.makePrincipal);\n attachVerifiedSignerAuth(req, principal, verifiedSigner);\n } catch (identityError) {\n const errName = (identityError as Error).name || 'Error';\n console.error(`[adcp/signed-requests] signer identity rejected: ${errName}`);\n if (!res.writableEnded) {\n res.statusCode = 401;\n res.setHeader('WWW-Authenticate', 'Signature error=\"request_signature_invalid\"');\n res.setHeader('Content-Type', 'application/json');\n res.end(\n JSON.stringify({\n error: 'request_signature_invalid',\n message: 'Request signature verification failed',\n })\n );\n }\n handled = true;\n }\n }\n if (res.writableEnded) handled = true;\n done();\n });\n });\n return handled;\n };\n}\n\nfunction attachVerifiedSignerAuth(\n req: import('http').IncomingMessage,\n principal: AuthPrincipal,\n signer: import('../signing/types').VerifiedSigner\n): void {\n const request = req as import('http').IncomingMessage & { auth?: AuthInfo; verifiedSigner?: typeof signer };\n const existing = request.auth;\n if (existing && existing.clientId !== principal.principal) {\n throw new AuthError('Request signature identity does not match the authenticated principal.');\n }\n const claims = principal.claims !== undefined ? { ...principal.claims } : {};\n const adopterExtra =\n principal.extra && typeof principal.extra === 'object' ? (principal.extra as Record<string, unknown>) : {};\n const extra = {\n ...(existing?.extra ?? {}),\n ...claims,\n ...adopterExtra,\n ...(principal.credential !== undefined ? { credential: principal.credential } : {}),\n };\n request.auth = existing\n ? { ...existing, extra }\n : {\n token: principal.token ?? '',\n clientId: principal.principal,\n scopes: principal.scopes ?? [],\n ...(principal.expiresAt !== undefined ? { expiresAt: principal.expiresAt } : {}),\n extra,\n };\n request.verifiedSigner = signer;\n}\n\n// ---------------------------------------------------------------------------\n// Version-claim validation helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the set of `adcp_major_version` integers this seller accepts on\n * inbound requests. Used by the single-field VERSION_UNSUPPORTED check\n * (issue #1075) to reject buyer claims outside the seller's advertised\n * window.\n *\n * Sources, in priority order:\n * 1. `capConfig.major_versions` — deprecated integer list (AdCP <3.1).\n * 2. `capConfig.supported_versions` — release-precision strings (AdCP 3.1+\n * per spec PR `adcontextprotocol/adcp#3493`); each entry's parsed major\n * is added to the set.\n * 3. Fallback to the major of `serverPin` so a seller that omits both lists\n * still rejects out-of-window claims rather than silently dispatching.\n */\nfunction getAdvertisedSupportedMajors(capConfig: AdcpCapabilitiesConfig | undefined, serverPin: string): Set<number> {\n const out = new Set<number>();\n for (const m of capConfig?.major_versions ?? []) {\n if (Number.isFinite(m)) out.add(m);\n }\n for (const v of capConfig?.supported_versions ?? []) {\n const m = parseAdcpMajorVersion(v);\n if (Number.isFinite(m)) out.add(m);\n }\n if (out.size === 0) {\n const pinMajor = parseAdcpMajorVersion(serverPin);\n if (Number.isFinite(pinMajor)) out.add(pinMajor);\n }\n return out;\n}\n\n/**\n * Build the `supported_versions` string array shipped on the\n * `VERSION_UNSUPPORTED` error envelope so buyers can downgrade their pin\n * and retry. Mirrors `getAdvertisedSupportedMajors` precedence:\n *\n * 1. `capConfig.supported_versions` — emit verbatim (release-precision strings).\n * 2. Else `capConfig.major_versions` — stringify each integer.\n * 3. Else fall back to the server pin's major as a single-entry list.\n *\n * Strings are preferred over integers because release-precision strings\n * round-trip more information; emitting a single-source listing avoids\n * confusing buyers with both integer and string shapes for the same major.\n * (`getAdvertisedSupportedMajors` unions both sources for the accepted-set\n * check, but this function picks one to avoid that ambiguity on the wire.)\n *\n * Buyer-side parser (`extractVersionUnsupportedDetails`) already filters\n * non-strings, so a `String(N)` fallback round-trips cleanly across 3.0\n * and 3.1 sellers.\n */\nfunction buildSupportedVersionsList(capConfig: AdcpCapabilitiesConfig | undefined, serverPin: string): string[] {\n if (capConfig?.supported_versions?.length) {\n return [...capConfig.supported_versions];\n }\n if (capConfig?.major_versions?.length) {\n return capConfig.major_versions.filter(m => Number.isFinite(m)).map(m => String(m));\n }\n const pinMajor = parseAdcpMajorVersion(serverPin);\n return Number.isFinite(pinMajor) ? [String(pinMajor)] : [];\n}\n\ninterface ParsedAdcpRelease {\n major: number;\n minor: number;\n prerelease?: string;\n value: string;\n}\n\ninterface ServedAdcpRelease {\n validationVersion: string;\n wireVersion?: string;\n}\n\nfunction isMcpToolResponse(value: ServedAdcpRelease | McpToolResponse): value is McpToolResponse {\n return Array.isArray((value as McpToolResponse).content);\n}\n\nfunction parseAdcpRelease(value: unknown): ParsedAdcpRelease | undefined {\n if (typeof value !== 'string') return undefined;\n let wire: string;\n try {\n wire = toReleasePrecisionVersion(value);\n } catch {\n return undefined;\n }\n const match = /^v?(\\d+)\\.(\\d+)(?:-([a-zA-Z0-9.-]+))?$/.exec(wire);\n if (!match) return undefined;\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n ...(match[3] !== undefined && { prerelease: match[3] }),\n value: wire,\n };\n}\n\nfunction compareAdcpRelease(left: ParsedAdcpRelease, right: ParsedAdcpRelease): number {\n if (left.major !== right.major) return left.major - right.major;\n if (left.minor !== right.minor) return left.minor - right.minor;\n if (left.prerelease === right.prerelease) return 0;\n if (left.prerelease === undefined) return 1;\n if (right.prerelease === undefined) return -1;\n const leftParts = left.prerelease.split('.');\n const rightParts = right.prerelease.split('.');\n for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {\n const leftPart = leftParts[index];\n const rightPart = rightParts[index];\n if (leftPart === undefined) return -1;\n if (rightPart === undefined) return 1;\n if (leftPart === rightPart) continue;\n const leftNumeric = /^\\d+$/.test(leftPart);\n const rightNumeric = /^\\d+$/.test(rightPart);\n if (leftNumeric && rightNumeric) return Number(leftPart) - Number(rightPart);\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;\n return leftPart.localeCompare(rightPart);\n }\n return 0;\n}\n\nconst PUSH_OPERATION_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,255}$/;\n\nfunction releaseRequiresPushOperationId(release: string): boolean {\n return isAdcpVersionAtLeast(resolveBundleKey(release), '3.2.0-beta.5');\n}\n\nfunction pushOperationIdError(\n params: Record<string, unknown>,\n release: ServedAdcpRelease\n): McpToolResponse | undefined {\n if (!releaseRequiresPushOperationId(release.validationVersion)) return undefined;\n const config = params.push_notification_config;\n if (config === undefined) return undefined;\n if (\n !isPlainObject(config) ||\n typeof config.operation_id !== 'string' ||\n !PUSH_OPERATION_ID_PATTERN.test(config.operation_id)\n ) {\n return adcpError('INVALID_REQUEST', {\n message: `push_notification_config.operation_id must match ${PUSH_OPERATION_ID_PATTERN.source}`,\n field: 'push_notification_config.operation_id',\n });\n }\n return undefined;\n}\n\nlet bundledCompatibleReleases: ParsedAdcpRelease[] | undefined;\n\nfunction bundledReleasesForMajors(majors: readonly number[], configured: ParsedAdcpRelease): ParsedAdcpRelease[] {\n const acceptedMajors = new Set(majors);\n const releases = new Map<string, ParsedAdcpRelease>();\n bundledCompatibleReleases ??= COMPATIBLE_ADCP_VERSIONS.flatMap(version => {\n if (!hasSchemaBundle(version)) return [];\n const parsed = parseAdcpRelease(version);\n return parsed ? [parsed] : [];\n });\n for (const parsed of bundledCompatibleReleases) {\n if (!acceptedMajors.has(parsed.major) || compareAdcpRelease(parsed, configured) > 0) continue;\n const key = `${parsed.major}.${parsed.minor}${parsed.prerelease ? `-${parsed.prerelease}` : ''}`;\n const existing = releases.get(key);\n // Preserve the v2.5 alias because that is the actual bundled directory;\n // stable semver patches otherwise collapse to release precision.\n if (!existing || parsed.value.startsWith('v')) releases.set(key, parsed);\n }\n // A server may explicitly opt into a bundled forward release before the\n // SDK-wide compatibility list advances (proposal negotiation does this for\n // 3.2). Include that configured release in major-only negotiation.\n if (acceptedMajors.has(configured.major)) {\n const key = `${configured.major}.${configured.minor}${configured.prerelease ? `-${configured.prerelease}` : ''}`;\n releases.set(key, configured);\n }\n return [...releases.values()];\n}\n\nfunction selectServedAdcpRelease(\n params: Record<string, unknown>,\n capConfig: AdcpCapabilitiesConfig | undefined,\n serverPin: string\n): ServedAdcpRelease | McpToolResponse {\n const configured = parseAdcpRelease(serverPin);\n if (!configured) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: `Configured AdCP release ${JSON.stringify(serverPin)} is invalid.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n\n const advertisedValues = capConfig?.supported_versions?.length ? capConfig.supported_versions : undefined;\n const advertised = advertisedValues\n ? advertisedValues.flatMap(value => {\n // SDK <=13 and early 3.x adopters sometimes placed a major-only\n // string in supported_versions. Interpret it like major_versions so\n // an SDK 14 server can still negotiate 3.0/3.1 wire bundles.\n if (/^v?\\d+$/.test(value.trim())) {\n return bundledReleasesForMajors([Number.parseInt(value.replace(/^v/, ''), 10)], configured);\n }\n return [parseAdcpRelease(value)];\n })\n : capConfig?.major_versions?.length\n ? bundledReleasesForMajors(capConfig.major_versions, configured)\n : bundledReleasesForMajors([configured.major], configured);\n if (advertised.some(value => value === undefined)) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: 'Seller capabilities contain an invalid supported_versions release.',\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n const supported = (advertised as ParsedAdcpRelease[]).filter(\n candidate => compareAdcpRelease(candidate, configured) <= 0\n );\n if (supported.length === 0) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: 'Seller capabilities do not include a release this server can serve.',\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n\n const requestedVersion = params.adcp_version;\n const requestedMajorRaw = params.adcp_major_version;\n const requestedMajor =\n typeof requestedMajorRaw === 'number'\n ? requestedMajorRaw\n : typeof requestedMajorRaw === 'string'\n ? Number.parseInt(requestedMajorRaw, 10)\n : undefined;\n let selected: ParsedAdcpRelease | undefined;\n\n if (requestedVersion !== undefined) {\n const requested = parseAdcpRelease(requestedVersion);\n if (!requested) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: `Request carries invalid adcp_version=${JSON.stringify(requestedVersion)}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n if (requestedMajor !== undefined && Number.isFinite(requestedMajor) && requestedMajor !== requested.major) {\n return adcpError('VERSION_UNSUPPORTED', {\n message:\n `Request carries adcp_version=${JSON.stringify(requestedVersion)} (major ${requested.major}) and ` +\n `adcp_major_version=${JSON.stringify(requestedMajorRaw)}; majors must agree.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n selected = supported\n .filter(candidate => candidate.major === requested.major && compareAdcpRelease(candidate, requested) <= 0)\n .sort((left, right) => compareAdcpRelease(right, left))[0];\n } else if (requestedMajor !== undefined && Number.isFinite(requestedMajor)) {\n // A major-only request may be a 3.0 buyer that cannot send\n // `adcp_version`. Select the oldest advertised release in that major so\n // the server never upgrades its wire shape implicitly.\n selected = supported.filter(candidate => candidate.major === requestedMajor).sort(compareAdcpRelease)[0];\n } else {\n // With no buyer claim, serve the newest release the seller actually\n // advertises rather than silently using a configured pin omitted from\n // supported_versions.\n selected = [...supported].sort((left, right) => compareAdcpRelease(right, left))[0];\n }\n\n if (!selected) {\n const claim =\n requestedVersion !== undefined\n ? `adcp_version=${JSON.stringify(requestedVersion)}`\n : requestedMajorRaw !== undefined\n ? `adcp_major_version=${JSON.stringify(requestedMajorRaw)} (major ${String(requestedMajor)})`\n : 'no AdCP version';\n return adcpError('VERSION_UNSUPPORTED', {\n message: `Request claims ${claim}; no mutually supported AdCP release is available.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n\n const validationVersion = selected.value;\n return {\n validationVersion,\n ...(bundleSupportsAdcpVersionField(resolveBundleKey(validationVersion)) && { wireVersion: validationVersion }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// createAdcpServer\n// ---------------------------------------------------------------------------\n\n/**\n * Create an AdCP-compliant MCP server from domain-grouped handler functions.\n *\n * @deprecated New adopters should use `createAdcpServerFromPlatform` from\n * `@adcp/sdk/server` instead. This v5 handler-bag entry point is kept for\n * legacy / mid-migration code; LLM-generated platforms scaffolding from\n * any of the v6 skills should NEVER call this. The v6 path\n * (`createAdcpServerFromPlatform`) wraps this function with: typed\n * specialism interfaces (`SalesPlatform`, `CreativeBuilderPlatform`, etc.),\n * compile-time capability enforcement (`RequiredPlatformsFor<S>`), the\n * `ctx_metadata` round-trip cache for adapter-internal state,\n * auto-hydration of `req.packages[i].product` on createMediaBuy,\n * default `resolveIdempotencyPrincipal` synthesis, capability projection,\n * async-task envelopes, status normalization via `StatusMappers`,\n * multi-tenant routing via `TenantRegistry`, and async task completion\n * webhook delivery. Under AdCP 3.2 synchronous terminal responses remain\n * silent on the task-webhook channel.\n *\n * Reach for `createAdcpServer` directly only when you need fine control\n * over individual handlers, are mid-migration from a v5 codebase, or\n * have custom-shaped tools the platform interface doesn't yet model.\n *\n * @see {@link createAdcpServerFromPlatform} — the canonical v6 entry.\n * @see `@adcp/sdk/server/legacy/v5` — the stable subpath for long-term\n * v5 pinning. The top-level re-export here may be removed in a\n * future major; the subpath is the supported home.\n * See `docs/migration-5.x-to-6.x.md`.\n *\n * Before each handler runs, the framework:\n * 1. Validates the request against the tool's Zod schema (MCP SDK)\n * 2. Resolves the account (if the tool has an `account` field and `resolveAccount` is configured)\n *\n * The handler only runs when all preconditions pass. It receives the validated\n * params and a context with the resolved account and state store.\n *\n * `get_adcp_capabilities` is auto-generated from registered tools.\n */\nexport function createAdcpServer<TAccount = unknown>(config: AdcpServerConfig<TAccount>): AdcpServer {\n const {\n name,\n version,\n adcpVersion: configuredAdcpVersion,\n mcpToolProfile = 'auto',\n requireCompactMutationAccountScope = false,\n resolveAccount,\n resolveAccountFromAuth,\n resolveSessionKey,\n agentRegistry,\n exposeErrorDetails = process.env.NODE_ENV !== 'production',\n stateStore = DEFAULT_STATE_STORE,\n taskRegistry,\n logger = noopLogger,\n capabilities: capConfig,\n idempotency: idempotencyConfig,\n resolveIdempotencyPrincipal,\n instructions: instructionsOption,\n onInstructionsError = 'skip',\n taskStore,\n taskMessageQueue,\n webhooks,\n signedRequests,\n validation: validationConfig,\n credentialPolicy,\n testController: testControllerBridge,\n responseEnhancer,\n } = config;\n if (!['auto', 'media-buy', 'all'].includes(mcpToolProfile)) {\n throw new Error(\n `createAdcpServer: mcpToolProfile must be \"auto\", \"media-buy\", or \"all\"; got ${JSON.stringify(mcpToolProfile)}`\n );\n }\n const notificationHandlerConfigured = typeof config.protocol?.syncAgentNotificationConfigs === 'function';\n const notificationCapabilitySupported = capConfig?.capability_changes?.notifications?.supported === true;\n if (notificationHandlerConfigured !== notificationCapabilitySupported) {\n throw new Error(\n 'createAdcpServer: syncAgentNotificationConfigs and capabilities.capability_changes.notifications.supported must be enabled together'\n );\n }\n if (notificationHandlerConfigured && typeof config.protocol?.resolveScope !== 'function') {\n throw new Error(\n 'createAdcpServer: protocol.resolveScope is required to isolate sync_agent_notification_configs by authenticated caller'\n );\n }\n if (\n typeof config.governance?.reportPlanAdjustment === 'function' &&\n typeof config.governance.resolveReportPlanAdjustmentScope !== 'function'\n ) {\n throw new Error(\n 'createAdcpServer: governance.resolveReportPlanAdjustmentScope is required to authorize report_plan_adjustment'\n );\n }\n const frameworkInputSchemaFor = (toolName: string) =>\n config.exposeToolSchemas === true\n ? (shallowToolInputHintSchema(toolName) ?? PASSTHROUGH_INPUT_SCHEMA)\n : PASSTHROUGH_INPUT_SCHEMA;\n const mcpAppResources = normalizeMcpAppResources(config.resources);\n const mcpAppResourceUris = new Set<string>(mcpAppResources.map(resource => resource.uri));\n for (const [toolName, tool] of Object.entries(config.customTools ?? {})) {\n const resourceUri = tool?._meta?.ui?.resourceUri;\n if (resourceUri === undefined || mcpAppResourceUris.has(resourceUri)) continue;\n const message =\n `[adcp/createAdcpServer] customTools[\"${toolName}\"]._meta.ui.resourceUri references ` +\n `\"${resourceUri}\", but no matching MCP App resource is configured in resources[].`;\n process.emitWarning(message, { type: 'AdcpServerConfigWarning', code: 'ADCP_MCP_APP_RESOURCE_MISSING' });\n logger.warn(message);\n }\n\n // One-shot construction-time warn when `testController` is wired without\n // both resolver paths. Account-bearing calls use `resolveAccount`; account-\n // less calls use `resolveAccountFromAuth`. The dispatch gate fails closed\n // when either path cannot produce an account, so make partial resolver\n // wiring diagnosable at construction time.\n //\n // Dual-emit: `process.emitWarning` writes to stderr by default so the\n // signal is visible even when `logger` is the default `noopLogger`\n // (the day-one case where the misconfig is most likely). `logger.warn`\n // also fires so adopters with configured logging pipelines see it in\n // their normal channel. The stable warning `code` lets logging pipelines\n // classify this configuration fault without parsing the message. See\n // `AdcpServerConfig.testController`\n // JSDoc § \"Security — trust boundary\" and #1784.\n if (testControllerBridge != null && (resolveAccount === undefined || resolveAccountFromAuth === undefined)) {\n const missingResolvers = [\n ...(resolveAccount === undefined ? ['resolveAccount'] : []),\n ...(resolveAccountFromAuth === undefined ? ['resolveAccountFromAuth'] : []),\n ];\n const message =\n `[adcp/createAdcpServer] testController is wired without ${missingResolvers.join(' and ')} — ` +\n 'both account-bearing and account-less tools require a trusted resolved sandbox/mock account before seeded fixtures can be merged. Configure both resolver paths. Details: https://github.com/adcontextprotocol/adcp-client/blob/main/docs/guides/VALIDATE-YOUR-AGENT.md';\n process.emitWarning(message, { type: 'AdcpServerConfigWarning', code: 'ADCP_BRIDGE_NO_RESOLVER' });\n logger.warn(message);\n }\n\n // Pre-resolve credential-policy patterns once. The patterns config is\n // a stable property of `CredentialPolicyConfig`; pulling it out here\n // keeps the per-call hot path (`scanArgsForCredentials`) free of the\n // string-vs-object discrimination on every dispatch.\n const credentialPolicyPatterns =\n credentialPolicy === undefined || typeof credentialPolicy === 'string' ? undefined : credentialPolicy.patterns;\n\n // Resolve `adcpVersion` early — the validator-call closures below capture\n // it by reference and would hit a TDZ ReferenceError if any of them ran\n // synchronously during setup. They don't today (`createAdcpServer`\n // registers handlers; the handlers fire on incoming requests after\n // `wrapMcpServer` returns), but the ordering hides a sharp edge for\n // future refactors. Throws `ConfigurationError` on cross-major pins\n // whose schema bundle isn't shipped — see utils/adcp-version-config.ts.\n // Registering a 3.2-only proposal tool is an explicit opt-in to the\n // bundled 3.2 server surface. Keep the SDK-wide client pin unchanged,\n // but make this server instance negotiate and advertise the release it\n // actually serves. An explicit older pin is rejected below.\n const adcpVersion = resolveAdcpVersion(\n configuredAdcpVersion ?? (config.proposalNegotiation ? ADCP_VERSION : undefined)\n );\n const movingSupportedVersion = capConfig?.supported_versions?.find(isMovingAdcpPrereleaseFamilyAlias);\n if (movingSupportedVersion) {\n throw new Error(\n `createAdcpServer: capabilities.supported_versions contains moving prerelease-family alias ${JSON.stringify(movingSupportedVersion)}; pin ${JSON.stringify(toReleasePrecisionVersion(ADCP_VERSION))} instead`\n );\n }\n const proposalRefinementCapabilities = config.proposalNegotiation\n ? defineProposalRefinementCapabilities(config.proposalNegotiation.capabilities)\n : undefined;\n const proposalRelease = parseAdcpRelease(adcpVersion);\n if (\n proposalRefinementCapabilities &&\n (!proposalRelease || proposalRelease.major !== 3 || proposalRelease.minor < 2)\n ) {\n throw new Error('createAdcpServer: proposalNegotiation requires adcpVersion 3.2 or newer');\n }\n if (proposalRefinementCapabilities && capConfig?.supported_versions?.length) {\n const supportsProposalRelease = capConfig.supported_versions.some(value => {\n const release = parseAdcpRelease(value);\n return (\n release !== undefined &&\n release.major === 3 &&\n release.minor >= 2 &&\n proposalRelease !== undefined &&\n compareAdcpRelease(release, proposalRelease) <= 0\n );\n });\n if (!supportsProposalRelease) {\n throw new Error(\n 'createAdcpServer: proposalNegotiation requires capabilities.supported_versions to include a served AdCP 3.2 release'\n );\n }\n }\n if (\n proposalRefinementCapabilities &&\n !capConfig?.supported_versions?.length &&\n capConfig?.major_versions?.length &&\n !capConfig.major_versions.includes(3)\n ) {\n throw new Error(\n 'createAdcpServer: proposalNegotiation requires capabilities.major_versions to include AdCP major 3'\n );\n }\n if (proposalRefinementCapabilities && proposalRefinementCapabilities.supported_dimensions === undefined) {\n throw new Error(\n 'createAdcpServer: proposalNegotiation.capabilities.supported_dimensions is required when refineProposals is registered'\n );\n }\n\n // Pre-resolved release-precision identifier the seller echoes on every\n // response per AdCP 3.1 spec PR `adcontextprotocol/adcp#3493`. `undefined`\n // when this seller pins a 3.0 bundle (3.0 schemas don't define the field).\n // Computed once at construction since the seller's pin is fixed for the\n // server's lifetime — every dispatch reuses the same value. Downshift\n // (3.1 seller serving a 3.0 buyer at 3.0) is a follow-up; today this\n // always reflects the seller's own pin.\n const protocolBundleKey = resolveBundleKey(adcpVersion);\n const frameworkToolMeta = { adcp_version: adcpVersion } as const;\n const servedAdcpVersion = (() => {\n const bundleKey = protocolBundleKey;\n return bundleSupportsAdcpVersionField(bundleKey) ? bundleKey : undefined;\n })();\n const protocolTaskRelease = parseAdcpRelease(protocolBundleKey);\n const supportsProtocolTaskTools =\n protocolTaskRelease !== undefined &&\n (protocolTaskRelease.major > 3 || (protocolTaskRelease.major === 3 && protocolTaskRelease.minor >= 1));\n\n // Tool-name set for two-layer error emission. Computed once at server\n // build from the bundled response schemas: any tool whose top-level\n // `oneOf`/`anyOf` declares an arm with `required: [\"errors\"]` joins\n // the set, and the dispatcher mirrors `errors[]` ↔ `adcp_error` on\n // the failure path so both spec-mandated layers ride on every\n // failing response. Tools without an Error arm are untouched.\n // RFC: docs/proposals/adcperror-two-layer-emission.md.\n const toolsWithErrorArm = getToolsWithErrorArm(adcpVersion);\n\n // Defaults gated on `process.env.NODE_ENV`:\n // - Production → both sides `'off'` (zero AJV overhead; trust the\n // handler after its test suite has exercised it).\n // - Dev/test/CI → BOTH sides `'strict'`. Request validation is now\n // authoritative on both transports (#909) — we dropped the SDK\n // Zod from `registerTool` inputSchema, so if our framework validator\n // doesn't reject malformed payloads they reach the handler\n // unchecked over A2A. Matching responses' existing `'strict'`\n // default keeps behavior consistent across the wire in both\n // directions.\n // Explicit `validation: { requests, responses }` on the config always\n // wins. `process.env.NODE_ENV` matches the convention every other SDK\n // consumer already tunes (Express, React, etc.); containers/CI that\n // want prod-like behavior set NODE_ENV=production before start.\n const isProduction = process.env.NODE_ENV === 'production';\n const requestValidationMode = validationConfig?.requests ?? (isProduction ? 'off' : 'strict');\n const responseValidationMode = validationConfig?.responses ?? (isProduction ? 'off' : 'strict');\n\n // Split the `idempotency` config field into \"the active store\" and\n // \"explicitly opted out\" so existing call sites keep working with a\n // single nullable variable while the disabled-mode branches stay\n // surgical. `idempotencyDisabled` gates: schema-level missing-key\n // tolerance, the missing-store guardrail log, the capability\n // declaration shift to `IdempotencyUnsupported`, and the runtime\n // production check below.\n const idempotencyDisabled = idempotencyConfig === 'disabled';\n const idempotency: IdempotencyStore | undefined = idempotencyDisabled ? undefined : idempotencyConfig;\n if (\n idempotency &&\n (!Number.isSafeInteger(idempotency.ttlSeconds) || idempotency.ttlSeconds < 3600 || idempotency.ttlSeconds > 604800)\n ) {\n throw new TypeError('createAdcpServer: idempotency.ttlSeconds must be a safe integer between 3600 and 604800.');\n }\n if (idempotency && typeof idempotency.renew !== 'function') {\n throw new TypeError(\n 'createAdcpServer: idempotency.renew is required so long-running mutation handlers cannot outlive their owner claim.'\n );\n }\n if (idempotencyDisabled) {\n // Allowlist gate. The earlier draft refused the flag only when\n // NODE_ENV === 'production', which is a footgun: NODE_ENV defaults to\n // unset in raw Lambda, custom containers, and many K8s deployments,\n // so the strict equality returned `false` in exactly the\n // hard-to-debug environments where disabled mode is most dangerous.\n // Inverted to an allowlist of dev/test environments; any other value\n // (unset, 'production', 'staging', 'qa', custom names) requires the\n // operator to explicitly acknowledge the risk via\n // `ADCP_IDEMPOTENCY_DISABLED_ACK=1`. Hard to set by accident, makes\n // the choice deliberate, and turns a missing-NODE_ENV config into a\n // startup crash instead of a silent money-flow incident on retry.\n const env = process.env.NODE_ENV;\n const acknowledged = process.env.ADCP_IDEMPOTENCY_DISABLED_ACK === '1';\n const isAllowlistedDevEnv = env === 'test' || env === 'development';\n if (!isAllowlistedDevEnv && !acknowledged) {\n throw new Error(\n \"createAdcpServer: idempotency: 'disabled' refuses to start with NODE_ENV=\" +\n (env === undefined ? '<unset>' : JSON.stringify(env)) +\n '. Disabled mode skips replay enforcement and silently double-executes mutating handlers on retry, ' +\n 'so the SDK only allows it under NODE_ENV=test or NODE_ENV=development by default. ' +\n 'Either: (a) wire a real store via `createIdempotencyStore({ backend, ttlSeconds })`, ' +\n '(b) set NODE_ENV=test or NODE_ENV=development if this is a dev-only environment, or ' +\n '(c) set ADCP_IDEMPOTENCY_DISABLED_ACK=1 to explicitly acknowledge the risk for non-standard environments.'\n );\n }\n logger.warn(\n \"createAdcpServer: idempotency: 'disabled' is set. Mutating requests will not be replay-checked and \" +\n '`get_adcp_capabilities` will declare `idempotency.supported: false`. Use only in non-production test fleets.'\n );\n }\n\n // Production gate on the default in-memory `stateStore`. Mirrors\n // `buildDefaultTaskRegistry` policy in `from-platform.ts` and the\n // `idempotency: 'disabled'` allowlist above: the module-singleton\n // default is correct for dev and single-tenant agents, but\n // multi-tenant production deployments that mint one\n // `createAdcpServer` per resolved tenant would silently share state\n // across tenants. Refuse outside `{NODE_ENV=test, NODE_ENV=development}`\n // unless the adopter sets `ADCP_DECISIONING_ALLOW_INMEMORY_STATE=1` as\n // an explicit ops escape hatch. v6.0 shipped this as a one-time warn;\n // 6.0.1 promotes it to a hard refusal so the production footgun closes\n // before any adopter trips on it.\n //\n // Ordered AFTER the idempotency-disabled gate so adopters who hit\n // both surface the higher-severity error (idempotency-disabled\n // double-executes mutations on retry; state-store sharing leaks\n // tenant data — both bad, idempotency goes first because the\n // recovery is \"wire a store\" while state-store recovery is \"pass\n // your own\").\n if (stateStore === DEFAULT_STATE_STORE) {\n const env = process.env.NODE_ENV;\n const safe = env === 'test' || env === 'development';\n const ack = process.env.ADCP_DECISIONING_ALLOW_INMEMORY_STATE === '1';\n if (!safe && !ack) {\n throw new Error(\n 'createAdcpServer: in-memory state store refused outside ' +\n '{NODE_ENV=test, NODE_ENV=development}. The default ' +\n '`InMemoryStateStore` is a process-shared module singleton — ' +\n 'single-tenant agents get the documented `ctx.store` cross-request ' +\n 'persistence, but multi-tenant deployments would silently share ' +\n 'state across resolved tenants. Pick one of:\\n' +\n ' 1. (Recommended) Pass `stateStore: new PostgresStateStore({ pool })` ' +\n 'to keep state across restarts AND partition across tenants. See ' +\n '`@adcp/sdk/server` for the migration helper.\\n' +\n ' 2. Pass `stateStore: new InMemoryStateStore()` explicitly if you ' +\n 'accept that state is per-process and shared across all resolved ' +\n 'tenants. Single-tenant agents only.\\n' +\n ' 3. ADCP_DECISIONING_ALLOW_INMEMORY_STATE=1 env flag is the ops ' +\n 'escape hatch (same effect as #2 but config-only); prefer #2 in ' +\n 'adopter code so the choice is visible at the call site.'\n );\n }\n }\n\n // Enforce that the verifier config has a buyer-visible discovery surface.\n // When `signedRequests` is set but neither the deprecated `signed-requests`\n // specialism claim NOR `capabilities.request_signing.supported: true` is\n // declared, buyers can't discover the signing requirement from\n // `get_adcp_capabilities` — they won't sign, the verifier rejects every\n // mutating call, and the agent is dead on arrival. Two discovery surfaces\n // are accepted:\n //\n // - **3.1+ canonical (recommended):** `capabilities.request_signing.supported: true`.\n // The universal signed_requests storyboard runs on this signal alone and\n // the runner emits `request_signing.required` notices for buyers.\n // - **Back-compat:** `specialisms: ['signed-requests']`. The 3.0-era enum\n // is preserved through the AdCP 4.0 deprecation cycle (adcp#3075). The\n // runner emits `signed_requests_specialism_deprecated` notice when this\n // path is taken (adcp-client#2082, adcp#4796).\n //\n // The opposite direction — advertising signing without a `signedRequests`\n // config — is only wrong when the agent also doesn't wire a verifier via\n // `serve({ preTransport })`. Legacy servers that hand-build the middleware\n // fall into this case and are still conformant. We log a loud error so\n // operators notice (matching the idempotency guardrail precedent) but\n // don't throw, leaving the manual path working.\n const specialismsClaimed = capConfig?.specialisms ?? [];\n const claimsSignedRequests = specialismsClaimed.includes('signed-requests');\n const declaresRequestSigningCapability = capConfig?.request_signing?.supported === true;\n if (signedRequests && !claimsSignedRequests && !declaresRequestSigningCapability) {\n throw new Error(\n 'createAdcpServer: `signedRequests` is configured but neither ' +\n '`capabilities.request_signing.supported: true` nor `capabilities.specialisms: [\"signed-requests\"]` is declared. ' +\n 'Buyers discover the signing requirement from get_adcp_capabilities — ' +\n 'set `capabilities.request_signing = { supported: true, ... }` (canonical 3.1+ form, recommended) ' +\n 'or claim the deprecated `signed-requests` specialism (back-compat). ' +\n \"Omitting both surfaces means buyers won't sign their requests.\"\n );\n }\n if (claimsSignedRequests && !signedRequests) {\n logger.error(\n 'createAdcpServer: `capabilities.specialisms` claims \"signed-requests\" but no `signedRequests` config was provided. ' +\n 'Either pass `signedRequests: { jwks, replayStore, revocationStore }` to auto-wire the verifier, or ensure you wire ' +\n 'one manually via `serve({ preTransport })`. Claiming the specialism without verifying signatures is a spec violation.'\n );\n }\n // The specialism is only meaningful when `capabilities.request_signing.supported`\n // is true — the compliance storyboard treats a missing or false `supported`\n // flag as \"not opted in\" and silently skips the whole conformance run. Claim\n // + supported:false is the worst failure mode: the claim advertises\n // signature enforcement while the capability block tells buyers the agent\n // doesn't verify. Fail fast so the mismatch is caught at construction.\n if (claimsSignedRequests && capConfig?.request_signing?.supported !== true) {\n throw new Error(\n 'createAdcpServer: `capabilities.specialisms` claims \"signed-requests\" but `capabilities.request_signing.supported` is not true. ' +\n 'Set `capabilities.request_signing = { supported: true, ... }` — the compliance storyboard skips conformance entirely when ' +\n '`supported` is falsy, and buyers cannot discover the signing requirement without the capability block.'\n );\n }\n\n // Cross-domain specialism declaration check. When a domain handler group\n // is wired, `capabilities.specialisms` SHOULD include at least one of that\n // domain's specialisms — otherwise the conformance runner grades the agent\n // as \"No applicable tracks found for this agent\" silently, even when every\n // tool works. The matrix v18 run (issue #785) had this drift class account\n // for ~30% of \"agent built every tool but storyboard reports no applicable\n // tracks\" cases.\n //\n // Logged via `logger.error` (matching the idempotency-disabled precedent)\n // rather than thrown because middleware-only test harnesses legitimately\n // wire handlers without declaring specialisms — production agents will see\n // the warning and conformance fail loudly, but tests stay passing.\n //\n // mediaBuy is intentionally excluded — its specialism choices\n // (sales-non-guaranteed vs sales-guaranteed vs sales-broadcast-tv vs\n // sales-social etc.) are commercially significant and an agent wiring\n // `mediaBuy.getProducts` may legitimately defer the specialism\n // declaration to a follow-up. The skill examples in build-seller-agent\n // already cover the right declaration; the runtime guardrail floor is\n // set at \"if you wire creative/signals/brand/governance handlers,\n // you SHOULD claim a specialism.\"\n //\n // governance is intentionally COARSE: any governance specialism\n // satisfies the check even though individual handlers map to specific\n // specialisms (createPropertyList → property-lists, calibrateContent →\n // content-standards, etc.). Per-handler-subgroup mapping is a\n // follow-up; the coarse rule catches the drift class (governance\n // handlers wired, no claim at all) without false-positives on\n // legitimate cross-cutting reads (e.g., a sales agent that calls\n // getPropertyList for read-only joins and claims its sales specialism).\n const isWired = (handlers: Record<string, unknown> | undefined): boolean => {\n // Filter to function-valued keys so `{ listCreativeFormats: undefined }`\n // (a key set to undefined, e.g. via `{ ...maybeHandlers }` spread) is\n // treated as not wired. `Object.keys` would otherwise count the key.\n if (!handlers) return false;\n return Object.values(handlers).some(v => typeof v === 'function');\n };\n\n const DOMAIN_SPECIALISM_REQUIREMENTS = [\n {\n domain: 'creative' as const,\n wired: isWired(config.creative as Record<string, unknown> | undefined),\n specialisms: ['creative-ad-server', 'creative-generative', 'creative-template', 'creative-transformers'] as const,\n },\n {\n domain: 'signals' as const,\n wired: isWired(config.signals as Record<string, unknown> | undefined),\n specialisms: ['signal-marketplace', 'signal-owned'] as const,\n },\n {\n domain: 'brandRights' as const,\n wired: isWired(config.brandRights as Record<string, unknown> | undefined),\n specialisms: ['brand-rights'] as const,\n },\n {\n domain: 'governance' as const,\n wired: isWired(config.governance as Record<string, unknown> | undefined),\n specialisms: [\n 'governance-spend-authority',\n 'governance-delivery-monitor',\n 'property-lists',\n 'collection-lists',\n 'content-standards',\n ] as const,\n },\n ];\n\n for (const req of DOMAIN_SPECIALISM_REQUIREMENTS) {\n if (!req.wired) continue;\n const claimedFromDomain = req.specialisms.filter(s => (specialismsClaimed as readonly string[]).includes(s));\n if (claimedFromDomain.length === 0) {\n logger.error(\n `createAdcpServer: ${req.domain} handlers are wired but capabilities.specialisms ` +\n `does not include any ${req.domain} specialism. Add at least one of ` +\n `${req.specialisms.map(s => `'${s}'`).join(', ')} to capabilities.specialisms — ` +\n `without it, the conformance runner reports \"No applicable tracks found\" and ` +\n `the agent grades as failing despite working tools.`\n );\n }\n }\n\n // Instantiate the emitter once — handler contexts expose its `emit`\n // bound method so per-request code calls `ctx.emitWebhook(...)` without\n // knowing about the emitter's construction or options.\n const configuredWebhookStore = webhooks?.deliveryStore ?? webhooks?.idempotencyKeyStore;\n if (\n webhooks &&\n process.env.NODE_ENV !== 'test' &&\n process.env.NODE_ENV !== 'development' &&\n configuredWebhookStore?.durability !== 'durable'\n ) {\n throw new Error(\n 'createAdcpServer: production webhook emission requires a durable WebhookDeliveryStore. ' +\n 'The store atomically retains each delivery key, canonical payload fingerprint, and first-attempt time ' +\n 'through the advertised retry horizon. Pass the shared store as webhooks.deliveryStore; ' +\n 'memoryWebhookDeliveryStore() is for development and tests only.'\n );\n }\n if (\n webhooks &&\n process.env.NODE_ENV !== 'test' &&\n process.env.NODE_ENV !== 'development' &&\n webhooks.deliveryRecovery?.durability !== 'durable'\n ) {\n throw new Error(\n 'createAdcpServer: production webhook emission requires durable deliveryRecovery. ' +\n 'Checkpoint the exact destination, payload/timestamp, authentication reference, and retry policy before ' +\n 'the first attempt, then recover unsettled deliveries after restart.'\n );\n }\n const webhookEmitter = webhooks\n ? createWebhookEmitter({\n ...webhooks,\n publisherScope: webhooks.publisherScope ?? name,\n // Intentionally unbound until handler dispatch derives trusted scope.\n tenantScope: undefined,\n })\n : undefined;\n const configuredWebhookTenantScope = webhooks?.tenantScope;\n const configuredWebhookEmitter =\n webhookEmitter && configuredWebhookTenantScope !== undefined\n ? webhookEmitter.forTenantScope(configuredWebhookTenantScope)\n : webhookEmitter;\n\n // Resolve `instructions` — sync function form is evaluated at construction.\n // Under `serve({ reuseAgent: false })` (the default) the factory runs\n // per HTTP request, so the function fires per session. Under\n // `reuseAgent: true` the function would fire once and never again —\n // `serve()` refuses that combination via `ADCP_INSTRUCTIONS_FN`.\n // Async function form: a Promise return is stored here; resolution is\n // deferred to the MCP `initialize` handler via `wrapInitializeHandler`.\n const instructionsIsFn = typeof instructionsOption === 'function';\n let resolvedInstructions: string | undefined;\n let pendingInstructions: Promise<string | undefined> | undefined;\n let resolveInstructionsForTransport: (() => Promise<string | undefined>) | undefined;\n if (typeof instructionsOption === 'string') {\n resolvedInstructions = instructionsOption;\n } else if (instructionsIsFn) {\n try {\n const result = (instructionsOption as (ctx: SessionContext) => string | undefined | Promise<string | undefined>)(\n {}\n );\n // Promise detection — must guard for null + non-object before reading\n // `.then`, otherwise `typeof null.then` throws TypeError and the user\n // sees a confusing framework-internal stack instead of their own bug.\n const isThenable =\n result !== null && typeof result === 'object' && typeof (result as { then?: unknown }).then === 'function';\n if (isThenable) {\n // Async return: store the running Promise; resolution happens in the\n // wrapInitializeHandler block below, just before the MCP response.\n pendingInstructions = Promise.resolve(result as Promise<string | undefined>);\n // Mark eager rejection as observed immediately. The original promise\n // remains rejected and is awaited by the transport resolver later,\n // where onInstructionsError decides fail vs skip. Without this\n // observer, stateless modern tool requests that never run discovery\n // could surface an unhandled rejection from an async instructions fn.\n void pendingInstructions.catch(() => {});\n } else {\n // Reject non-string non-undefined sync returns instead of silently coercing\n // (`String({})` → \"[object Object]\" would ship as instructions otherwise).\n // The TS signature constrains return to `string | undefined`; this catches\n // `as any` escapees and untyped JS callers.\n if (result !== undefined && typeof result !== 'string') {\n throw new Error(\n `function-form \\`instructions\\` must return string | undefined, got ${result === null ? 'null' : typeof result}. ` +\n `Return a string for the prose, or undefined for \"no instructions on this session.\"`\n );\n }\n resolvedInstructions = result;\n }\n } catch (err) {\n if (onInstructionsError === 'fail') {\n throw err;\n }\n // 'skip' — log server-side, surface no instructions to MCP `initialize`.\n logger.warn('[adcp/createAdcpServer] instructions() threw; skipping (onInstructionsError: \"skip\")', {\n error: err instanceof Error ? err.message : String(err),\n });\n resolvedInstructions = undefined;\n }\n } else {\n resolvedInstructions = undefined;\n }\n\n const mcpTaskStore = taskStore ?? new InMemoryTaskStore();\n const server = createTaskCapableServer(name, version, {\n taskStore: mcpTaskStore,\n taskMessageQueue,\n instructions: resolvedInstructions,\n });\n\n // The v1 SDK server remains the canonical legacy path. The modern adapter\n // separately mirrors these validated definitions onto every per-request\n // MCP v2 server reconstruction.\n for (const resource of mcpAppResources) {\n server.registerResource(\n resource.name,\n resource.uri,\n mcpAppResourceMetadata(resource) as Parameters<typeof server.registerResource>[2],\n async (uri, extra) =>\n readMcpAppResource(resource, uri, {\n signal: extra.signal,\n })\n );\n }\n\n // Wire async instructions resolution into the MCP `initialize` handler.\n // The function returned a Promise at construction time; await it here\n // (just before the initialize response) so the resolved string is included\n // in the MCP handshake without making createAdcpServer itself async.\n if (pendingInstructions !== undefined) {\n const pending = pendingInstructions;\n let resolvedOnce: Promise<string | undefined> | undefined;\n resolveInstructionsForTransport = () => {\n resolvedOnce ??= (async () => {\n try {\n const resolved = await pending;\n if (resolved !== undefined && typeof resolved !== 'string') {\n throw new Error(\n `function-form \\`instructions\\` resolved to ${typeof resolved}, expected string | undefined. ` +\n `Return a string for the prose, or undefined for \"no instructions on this session.\"`\n );\n }\n setSdkServerInstructions(server, resolved);\n return resolved;\n } catch (err) {\n if (onInstructionsError === 'fail') throw err;\n logger.warn('[adcp/createAdcpServer] async instructions threw; skipping (onInstructionsError: \"skip\")', {\n error: err instanceof Error ? err.message : String(err),\n });\n return undefined;\n }\n })();\n return resolvedOnce;\n };\n wrapInitializeHandler(server, async (origHandler, req, extra) => {\n await resolveInstructionsForTransport?.();\n return origHandler(req, extra);\n });\n }\n\n const registeredToolNames = new Set<string>();\n let warnedAboutOptionalReplayWithoutIdempotency = false;\n\n const applyResponseEnhancer = (response: McpToolResponse): McpToolResponse => {\n responseEnhancer?.(response);\n return response;\n };\n\n const requestServedRelease = (params: Record<string, unknown>): ServedAdcpRelease | undefined => {\n const selected = selectServedAdcpRelease(params, capConfig, adcpVersion);\n return isMcpToolResponse(selected) ? undefined : selected;\n };\n\n const releaseDefinesTool = (toolName: string, release: ServedAdcpRelease): boolean => {\n if (toolName === 'refine_proposals') return true;\n try {\n return getValidator(toolName, 'request', release.validationVersion) !== undefined;\n } catch {\n return false;\n }\n };\n\n const finalizeProtocolTaskToolResponse = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>,\n response: McpToolResponse,\n opts: { echoContext?: boolean } = {}\n ): McpToolResponse => {\n const release = requestServedRelease(params) ?? {\n validationVersion: adcpVersion,\n ...(servedAdcpVersion !== undefined && { wireVersion: servedAdcpVersion }),\n };\n sanitizeAdcpErrorEnvelope(response);\n enrichErrorTwoLayer(response, toolName, getToolsWithErrorArm(release.validationVersion));\n if (!isErrorResponse(response)) {\n normalizeMediaBuyStatusCollision(response, toolName);\n injectEnvelopeStatusIntoResponse(response, toolName);\n const validationError = protocolTaskResponseValidationError(toolName, response, params);\n if (validationError) return finalizeProtocolTaskToolResponse(toolName, params, validationError, opts);\n }\n if (opts.echoContext !== false) injectContextIntoResponse(response, params.context);\n injectVersionIntoResponse(response, release.wireVersion);\n return applyResponseEnhancer(response);\n };\n\n const unsupportedVersionResponse = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>\n ): McpToolResponse | undefined => {\n const selected = selectServedAdcpRelease(params, capConfig, adcpVersion);\n if (isMcpToolResponse(selected)) return selected;\n if (!releaseDefinesTool(toolName, selected)) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: `${toolName} is not defined in the selected AdCP release ${selected.validationVersion}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n });\n }\n return undefined;\n };\n\n const protocolTaskAccountExtensionIssues = (params: Record<string, unknown>): ValidationIssue[] => {\n if (params.account === undefined) return [];\n const parsed = AccountReferenceSchema.safeParse(params.account);\n if (parsed.success) return [];\n return [\n {\n pointer: '/account',\n message: 'must be a valid AccountReference',\n keyword: 'oneOf',\n schemaPath: '#/properties/account',\n },\n ];\n };\n\n const protocolTaskRequestValidationError = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>\n ): McpToolResponse | undefined => {\n const accountIssues = protocolTaskAccountExtensionIssues(params);\n const outcome =\n requestValidationMode === 'off'\n ? ({ valid: true, issues: [], schemaId: undefined } as const)\n : validateRequest(toolName, params, requestServedRelease(params)?.validationVersion ?? adcpVersion);\n const issues = [...(outcome.valid ? [] : outcome.issues), ...accountIssues];\n if (issues.length === 0) return undefined;\n if (requestValidationMode === 'strict' || accountIssues.length > 0) {\n return adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload(toolName, 'request', issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n })\n );\n }\n logger.warn(\n `Schema validation warning (request) for ${toolName}: ${formatIssues(issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues,\n }\n );\n return undefined;\n };\n\n const protocolTaskResponseValidationError = (\n toolName: 'get_task_status' | 'list_tasks',\n response: McpToolResponse,\n params: Record<string, unknown> = {}\n ): McpToolResponse | undefined => {\n if (responseValidationMode === 'off') return undefined;\n const outcome = validateResponse(\n toolName,\n response.structuredContent,\n requestServedRelease(params)?.validationVersion ?? adcpVersion\n );\n if (outcome.valid) return undefined;\n logger.warn(\n `Schema validation warning (response) for ${toolName}: ${formatIssues(outcome.issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues: outcome.issues,\n variant: outcome.variant,\n }\n );\n if (responseValidationMode !== 'strict') return undefined;\n return adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload(toolName, 'response', outcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n })\n );\n };\n\n const protocolTaskBoundsError = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>\n ): McpToolResponse | undefined => {\n if (params.include_history === true) {\n return adcpError('INVALID_REQUEST', {\n message: 'include_history is not supported by this task registry',\n field: 'include_history',\n });\n }\n if (toolName === 'get_task_status') {\n if (typeof params.task_id !== 'string' || params.task_id.length === 0) {\n return adcpError('INVALID_REQUEST', {\n message: 'task_id must be a non-empty string',\n field: 'task_id',\n });\n }\n }\n const filters = params.filters;\n if (isPlainObject(filters) && Array.isArray(filters.task_ids)) {\n if (\n filters.task_ids.length > 100 ||\n filters.task_ids.some(taskId => typeof taskId !== 'string' || taskId.length === 0)\n ) {\n return adcpError('INVALID_REQUEST', {\n message: 'filters.task_ids must contain at most 100 non-empty strings',\n field: 'filters.task_ids',\n });\n }\n }\n return undefined;\n };\n\n const taskToolCredentialPolicyError = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>,\n mcpExtra: any\n ): McpToolResponse | undefined => {\n if (credentialPolicy === undefined) return undefined;\n const effectivePolicy =\n typeof credentialPolicy === 'string' || credentialPolicy.tools?.[toolName] !== undefined\n ? resolveCredentialPolicyForTool(credentialPolicy, toolName)\n : (credentialPolicy.tools?.tasks_get ?? credentialPolicy.policy);\n if (effectivePolicy !== 'lax') {\n const hits = scanArgsForCredentials(params, credentialPolicyPatterns);\n const blockedPaths =\n typeof effectivePolicy === 'object' ? hits.filter(p => !effectivePolicy.allow.includes(p)) : hits;\n if (blockedPaths.length > 0) {\n return adcpError('PERMISSION_DENIED', {\n message:\n 'Request args carry credential-shaped keys. Credentials must arrive on authInfo, not in the request body.',\n recovery: 'correctable',\n details: { scope: 'credentials', credential_paths: blockedPaths },\n });\n }\n }\n if (\n typeof credentialPolicy !== 'string' &&\n credentialPolicy.scanAuthInfo === true &&\n mcpExtra?.authInfo?.extra !== null &&\n mcpExtra?.authInfo?.extra !== undefined &&\n typeof mcpExtra.authInfo.extra === 'object'\n ) {\n const authInfoHits = scanArgsForCredentials(mcpExtra.authInfo.extra, credentialPolicyPatterns);\n if (authInfoHits.length > 0) {\n try {\n logger.warn('credentialPolicy: authInfo.extra carries credential-shaped keys', {\n tool: toolName,\n paths: authInfoHits.map(p => `authInfo.extra.${p}`),\n });\n } catch {\n // Ignore logger failures on the rejection path.\n }\n return adcpError('PERMISSION_DENIED', {\n message:\n 'Request authentication context carries credential-shaped keys. Configure your authenticator to keep credentials off authInfo.extra.',\n recovery: 'terminal',\n details: { scope: 'credentials' },\n });\n }\n }\n return undefined;\n };\n\n const resolveTaskQueryAccountId = async (\n params: Record<string, unknown>,\n extra: any,\n toolName: 'get_task_status' | 'list_tasks'\n ): Promise<{\n accountId?: string;\n ownerScope?: string;\n accountResolutionAttempted: boolean;\n error?: McpToolResponse;\n }> => {\n const ctx: HandlerContext<TAccount> = { store: stateStore };\n let accountResolutionAttempted = false;\n if (extra?.authInfo) {\n const authInfo = extra.authInfo as ResolvedAuthInfo;\n ctx.authInfo = authInfo;\n const inboundCredential = authInfo.extra?.credential;\n if (inboundCredential !== undefined && authInfo.credential === undefined) {\n authInfo.credential = inboundCredential as ResolvedAuthInfo['credential'];\n }\n }\n\n if (agentRegistry !== undefined) {\n try {\n const resolved = await agentRegistry.resolve({\n ...(ctx.authInfo?.credential !== undefined && { credential: ctx.authInfo.credential }),\n ...(ctx.authInfo?.extra !== undefined && { extra: ctx.authInfo.extra }),\n input: params,\n });\n if (resolved != null) {\n if (!Object.isFrozen(resolved)) {\n if (resolved.billing_capabilities instanceof Set) {\n Object.freeze(resolved.billing_capabilities);\n }\n Object.freeze(resolved);\n }\n ctx.agent = resolved;\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Buyer-agent registry resolution failed during task poll', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Buyer-agent registry resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n }\n\n const accountRef = params.account;\n if (accountRef != null) {\n accountResolutionAttempted = true;\n if (!resolveAccount) {\n return {\n accountResolutionAttempted,\n error: adcpError('ACCOUNT_NOT_FOUND', {\n message: 'The specified account does not exist',\n field: 'account',\n }),\n };\n }\n try {\n const account = await resolveAccount(accountRef as AccountReference, {\n toolName: toolName as AdcpServerToolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n if (account != null) ctx.account = account;\n if (account == null) {\n return {\n accountResolutionAttempted,\n error: adcpError('ACCOUNT_NOT_FOUND', {\n message: 'The specified account does not exist',\n field: 'account',\n }),\n };\n }\n } catch (err) {\n if (isThrownAdcpError(err)) return { accountResolutionAttempted, error: err };\n if (err instanceof AdcpError) {\n return { accountResolutionAttempted, error: projectThrownAdcpError(err) };\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Account resolution failed', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n } else if (resolveAccountFromAuth) {\n try {\n const account = await resolveAccountFromAuth({\n toolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n accountResolutionAttempted = true;\n if (account != null) {\n ctx.account = account;\n }\n } catch (err) {\n accountResolutionAttempted = true;\n if (isThrownAdcpError(err)) return { accountResolutionAttempted, error: err };\n if (err instanceof AdcpError) {\n return { accountResolutionAttempted, error: projectThrownAdcpError(err) };\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Auth-derived account resolution failed', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n }\n\n if (resolveSessionKey) {\n try {\n const sessionKey = await resolveSessionKey({\n toolName: toolName as AdcpServerToolName,\n params,\n account: ctx.account,\n ...(ctx.agent != null && { agent: ctx.agent }),\n });\n if (sessionKey !== undefined) ctx.sessionKey = sessionKey;\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Session key resolution failed during task poll', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Session key resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n }\n\n const accountLike = ctx.account as { id?: unknown; account_id?: unknown } | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const ownerScope =\n accountId !== undefined\n ? taskOwnerScopeForContext(ctx.authInfo, ctx.sessionKey, ctx.agent, accountId)\n : undefined;\n return { accountId, ownerScope, accountResolutionAttempted };\n };\n\n // Collect all domain handlers into a flat toolName → handler map\n const domainGroups: [Record<string, Function> | undefined, HandlerEntry[]][] = [\n [config.mediaBuy as Record<string, Function> | undefined, MEDIA_BUY_ENTRIES],\n [config.proposalNegotiation as unknown as Record<string, Function> | undefined, PROPOSAL_NEGOTIATION_ENTRIES],\n [config.signals as Record<string, Function> | undefined, SIGNALS_ENTRIES],\n [config.creative as Record<string, Function> | undefined, CREATIVE_ENTRIES],\n [config.governance as Record<string, Function> | undefined, GOVERNANCE_ENTRIES],\n [config.protocol as Record<string, Function> | undefined, PROTOCOL_ENTRIES],\n [config.accounts as Record<string, Function> | undefined, ACCOUNT_ENTRIES],\n [config.eventTracking as Record<string, Function> | undefined, EVENT_TRACKING_ENTRIES],\n [config.sponsoredIntelligence as Record<string, Function> | undefined, SI_ENTRIES],\n [config.brandRights as Record<string, Function> | undefined, BRAND_RIGHTS_ENTRIES],\n ];\n\n for (const [handlers, entries] of domainGroups) {\n if (!handlers) continue;\n\n // Warn on unrecognized handler keys (likely typos)\n const knownKeys = new Set(entries.map(e => e.handlerKey));\n for (const key of ['capabilities', 'resolveScope', 'resolveReportPlanAdjustmentScope']) knownKeys.add(key);\n for (const key of Object.keys(handlers)) {\n if (typeof (handlers as Record<string, unknown>)[key] === 'function' && !knownKeys.has(key)) {\n logger.warn(`Unknown handler key \"${key}\" — will not be registered. Check for typos.`);\n }\n }\n\n for (const { handlerKey, toolName } of entries) {\n const handler = (handlers as Record<string, Function>)[handlerKey];\n if (!handler) continue;\n\n if (registeredToolNames.has(toolName)) {\n // Tool already registered by another domain (e.g., list_creative_formats\n // in both mediaBuy and creative). First domain wins.\n logger.warn(`Tool \"${toolName}\" already registered by another domain, skipping`);\n continue;\n }\n\n const meta = TOOL_META[toolName];\n const schema =\n toolName === 'refine_proposals'\n ? { shape: REFINE_PROPOSALS_INPUT_SHAPE }\n : (TOOL_REQUEST_SCHEMAS as Readonly<Record<string, { shape: Record<string, unknown> }>>)[toolName];\n if (!schema?.shape) {\n logger.warn(`No schema found for tool \"${toolName}\" in TOOL_REQUEST_SCHEMAS, skipping`);\n continue;\n }\n const hasAccount = 'account' in schema.shape;\n\n const wrap = meta?.wrap ?? ((data: any, summary?: string) => genericResponse(toolName, data, summary));\n const toolHandler = async (params: any, extra: any) => {\n const releaseSelection = selectServedAdcpRelease(params, capConfig, adcpVersion);\n let releaseError: McpToolResponse | undefined;\n let requestRelease: ServedAdcpRelease;\n if (isMcpToolResponse(releaseSelection)) {\n releaseError = releaseSelection;\n requestRelease = {\n validationVersion: adcpVersion,\n ...(servedAdcpVersion !== undefined && { wireVersion: servedAdcpVersion }),\n };\n } else {\n requestRelease = releaseSelection;\n }\n const requestErrorArms = getToolsWithErrorArm(requestRelease.validationVersion);\n const ctx: HandlerContext<TAccount> = {\n store: stateStore,\n servedAdcpVersion: requestRelease.validationVersion,\n ...(extra?.signal !== undefined && { signal: extra.signal }),\n };\n if (extra?.authInfo) {\n ctx.authInfo = extra.authInfo;\n // Hoist the kind-discriminated credential from MCP's `extra`\n // shape onto top-level `ctx.authInfo.credential` so adopter\n // `resolveAccount` callbacks and the `BuyerAgentRegistry` can\n // route on it directly without unpacking `extra`. Stage 3 of\n // #1269 — the built-in authenticators stamp this in\n // `serve.ts:attachAuthInfo`. Custom `authenticate` callbacks\n // that don't populate `credential` see `ctx.authInfo.credential`\n // stay undefined; downstream code branches on `credential\n // !== undefined` for the new path and falls back to the\n // `@deprecated` legacy fields (`token`, `clientId`, `scopes`)\n // for the old path. Both paths coexist for two minors.\n const authInfo = ctx.authInfo;\n if (authInfo !== undefined) {\n const inboundCredential = authInfo.extra?.credential;\n if (inboundCredential !== undefined && authInfo.credential === undefined) {\n authInfo.credential = inboundCredential as ResolvedAuthInfo['credential'];\n }\n }\n }\n // Echo params.context into any response (success or error) so buyers\n // can trace correlation_id end-to-end. Framework-generated errors\n // (ACCOUNT_NOT_FOUND, SERVICE_UNAVAILABLE) go through this too.\n // `injectContextIntoResponse` skips non-object values so SI tools\n // that override `context` as a string on the request don't leak the\n // string into the response envelope.\n //\n // `sanitizeAdcpErrorEnvelope` re-applies `ADCP_ERROR_FIELD_ALLOWLIST`\n // as a runtime belt-and-suspenders for handlers that build an error\n // envelope outside `adcpError()` — `adcpError()` already filters its\n // own output, but a hand-rolled `{ isError, structuredContent:\n // { adcp_error: ... } }` would otherwise ship unfiltered.\n const finalizeProtocolEnvelope = (response: McpToolResponse): McpToolResponse => {\n sanitizeAdcpErrorEnvelope(response);\n // Two-layer error emission: when the tool's response schema\n // declares an Error arm (`errors: [...]` required), mirror\n // `adcp_error` ↔ `errors[]` so both spec-mandated layers are\n // present on the wire. Order: AFTER sanitize so we project\n // the allowlist-filtered envelope; BEFORE context/version\n // injection so those run on the final two-layer payload.\n enrichErrorTwoLayer(response, toolName, requestErrorArms);\n normalizeMediaBuyStatusCollision(response, toolName);\n injectEnvelopeStatusIntoResponse(response, toolName);\n injectContextIntoResponse(response, params.context);\n injectVersionIntoResponse(response, requestRelease.wireVersion);\n return response;\n };\n const finalize = (response: McpToolResponse): McpToolResponse =>\n applyResponseEnhancer(finalizeProtocolEnvelope(response));\n\n if (releaseError) return finalize(releaseError);\n if (!releaseDefinesTool(toolName, requestRelease)) {\n return finalize(\n adcpError('VERSION_UNSUPPORTED', {\n message: `${toolName} is not defined in the selected AdCP release ${requestRelease.validationVersion}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n const operationIdError = pushOperationIdError(params, requestRelease);\n if (operationIdError) return finalize(operationIdError);\n\n // --- Buyer-agent registry resolution (#1269 / #1292) ---\n // Runs after `authInfo` is populated and before account resolution\n // so adopters' `resolveAccount` callbacks see `ctx.agent`. The\n // registry receives the kind-discriminated `credential` (Stage 3)\n // synthesized by the framework's built-in authenticators in\n // `serve.ts:attachAuthInfo`; factories route on `credential.kind`\n // and return null when no credential was stamped (custom adopter\n // auth callbacks that haven't migrated).\n if (agentRegistry !== undefined) {\n try {\n // Stage 3 of #1269: pass the kind-discriminated `credential`\n // synthesized in `serve.ts:attachAuthInfo` (and hoisted to\n // top-level above) into the registry. Factory functions\n // (`signingOnly` / `bearerOnly` / `mixed`) route on\n // `credential.kind`; absent credential → factories return\n // null → ctx.agent stays undefined.\n const resolved = await agentRegistry.resolve({\n ...(ctx.authInfo?.credential !== undefined && { credential: ctx.authInfo.credential }),\n ...(ctx.authInfo?.extra !== undefined && { extra: ctx.authInfo.extra }),\n input: params,\n });\n if (resolved != null) {\n // Shallow-freeze the resolved record so downstream code cannot\n // accidentally mutate `status`, `agent_url`, or other own\n // properties. NOTE: `Object.freeze` on the `billing_capabilities`\n // Set locks the Set object's own properties but does NOT\n // protect the internal `[[SetData]]` slot — `.add()` /\n // `.delete()` / `.clear()` still mutate. `ReadonlySet` is a\n // TypeScript-only contract; adopters constructing a Set MUST\n // NOT rely on freeze preventing membership changes at runtime.\n // The billing-capability check only reads via `.has()`,\n // so adopter mis-mutation would only affect the same request's\n // own logic — no cross-request leak.\n if (!Object.isFrozen(resolved)) {\n // Map-backed wrappers and other Set-shaped types skip the\n // Set-freeze branch; the outer record's freeze still applies.\n if (resolved.billing_capabilities instanceof Set) {\n Object.freeze(resolved.billing_capabilities);\n }\n Object.freeze(resolved);\n }\n ctx.agent = resolved;\n // Adopters reading the registry's view of `agent_url` get it\n // from `ctx.agent.agent_url` (the resolved `BuyerAgent`\n // record). Stage 3 of #1269 deliberately does NOT stamp a\n // top-level `agent_url` on `ctx.authInfo` — that would\n // invite handler code to gate on a non-cryptographically-\n // verified URL while the spec (adcontextprotocol/adcp#3831)\n // requires verified `agent_url` reads to come from the\n // `http_sig` credential variant. Adopters who use bearer or\n // OAuth credentials get a registry-resolved `ctx.agent` but\n // NO verified `agent_url` — that's correct: bearer auth\n // doesn't prove the agent_url cryptographically.\n\n // --- Status enforcement (Stage 4 of #1269) ---\n // Reject new requests from `suspended` / `blocked` agents\n // with the dedicated 3.1 codes `AGENT_SUSPENDED` /\n // `AGENT_BLOCKED` (adcp#3906 consolidates the 3.0.5\n // `PERMISSION_DENIED + details.status` placeholder shape).\n // In-flight tasks owned by a now-suspended agent are NOT\n // retroactively cancelled — this seam runs once per\n // synchronous request, not on `tasks_get` polls or\n // background webhook deliveries. Sellers who need hard\n // cutoff implement that in their platform method via\n // `BuyerAgent.status` checks (the resolved record is\n // available on every method that takes ctx.agent).\n //\n // Recovery is `terminal` for both — a buyer cannot\n // \"wait out\" a suspension by retrying the same request.\n // The transient-vs-permanent distinction lives at the\n // seller's `BuyerAgent.status` record (suspension may\n // lift via re-onboarding), not on the wire envelope.\n // The placeholder shape's `recovery: 'transient'` for\n // suspended contradicted the no-retry MUST.\n if (resolved.status === 'suspended' || resolved.status === 'blocked') {\n return finalize(\n adcpError(resolved.status === 'suspended' ? 'AGENT_SUSPENDED' : 'AGENT_BLOCKED', {\n message:\n resolved.status === 'suspended'\n ? 'Buyer agent is suspended. Contact the seller to restore access.'\n : 'Buyer agent is blocked.',\n recovery: 'terminal',\n })\n );\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Buyer-agent registry resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Buyer-agent registry resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n const toolIsMutating = isMutatingTask(toolName);\n const requestIsStateChanging = requestUsesIdempotency(toolName, params);\n const hasIdempotencyKeyField = Object.prototype.hasOwnProperty.call(params, 'idempotency_key');\n const requestUsesOptionalIdempotency = toolName === 'get_products' && hasIdempotencyKeyField;\n let suppliedIdempotencyKey = typeof params.idempotency_key === 'string' ? params.idempotency_key : undefined;\n // The 3.2 compatibility schema deliberately leaves the finalize key\n // optional. Replay a supplied key, but do not reject older callers\n // that omit it. SDK 14 buyers auto-inject one on this path.\n const requestUsesReplay = toolIsMutating || requestIsStateChanging || requestUsesOptionalIdempotency;\n if (hasInvalidGetProductsFinalizeIntent(toolName, params)) {\n return finalize(\n adcpError('INVALID_REQUEST', {\n message:\n 'get_products finalize requires buying_mode refine and an exclusive array of proposal-scoped finalize entries with non-empty proposal_id values',\n field: 'refine',\n })\n );\n }\n if (requestIsStateChanging && !toolIsMutating && !idempotency && !idempotencyDisabled) {\n if (!warnedAboutOptionalReplayWithoutIdempotency) {\n warnedAboutOptionalReplayWithoutIdempotency = true;\n logger.error(\n 'createAdcpServer: get_products proposal finalization was refused because no idempotency store is configured.'\n );\n }\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Proposal finalization requires an idempotency store',\n })\n );\n }\n if (requestIsStateChanging && !toolIsMutating && idempotency && suppliedIdempotencyKey === undefined) {\n // The 3.2 compatibility schema leaves this key optional for older\n // callers. Derive a stable server-side key from the canonical\n // finalize request so the compatibility path remains replay-safe\n // instead of either double-executing or becoming a breaking\n // missing-field rejection.\n // Hash the request directly: hashPayload's exclusion rules are\n // intentionally shallow and apply to these top-level retry-only\n // fields. Wrapping `params` would accidentally make refreshed\n // context/governance/webhook credentials mint a different key.\n suppliedIdempotencyKey = `compat_finalize_${hashPayload(params)}`;\n }\n if (\n requestUsesOptionalIdempotency &&\n !toolIsMutating &&\n !idempotency &&\n !idempotencyDisabled &&\n !warnedAboutOptionalReplayWithoutIdempotency\n ) {\n warnedAboutOptionalReplayWithoutIdempotency = true;\n logger.error(\n 'createAdcpServer: get_products was called with idempotency_key but no idempotency store is configured. ' +\n 'Replay protection is unavailable; configure idempotency or explicitly disable it.'\n );\n }\n\n // Field-disagreement detection per spec PR `adcontextprotocol/adcp#3493`:\n // when the request carries both `adcp_version` (string, AdCP 3.1+)\n // and `adcp_major_version` (integer, deprecated) and the majors\n // disagree, the server MUST return `VERSION_UNSUPPORTED`. Catches\n // a buyer that pinned a string but kept a stale integer in their\n // call-site config — the discrepancy is silent drift otherwise.\n //\n // Intentionally runs before the `requestValidationMode === 'off'`\n // short-circuit below: this is a spec MUST, not opt-in validation.\n // Production servers run with validation off by default; without\n // this check, a stale-integer drift on those servers would silently\n // dispatch to the wrong schema bundle.\n //\n // Coerces a stringified `adcp_major_version` (e.g. `\"3\"` from a\n // buyer that JSON-stringified a number) before comparing — AJV\n // strict-mode rejects this in dev, but production-default off-mode\n // would otherwise let the bypass through.\n const reqAdcpVersion = (params as { adcp_version?: unknown }).adcp_version;\n const reqAdcpMajorRaw = (params as { adcp_major_version?: unknown }).adcp_major_version;\n const reqAdcpMajor =\n typeof reqAdcpMajorRaw === 'number'\n ? reqAdcpMajorRaw\n : typeof reqAdcpMajorRaw === 'string'\n ? Number.parseInt(reqAdcpMajorRaw, 10)\n : undefined;\n if (typeof reqAdcpVersion === 'string' && reqAdcpMajor !== undefined && Number.isFinite(reqAdcpMajor)) {\n const stringMajor = parseAdcpMajorVersion(reqAdcpVersion);\n if (Number.isFinite(stringMajor) && stringMajor !== reqAdcpMajor) {\n return finalize(\n adcpError('VERSION_UNSUPPORTED', {\n message:\n `Request carries adcp_version=\"${reqAdcpVersion}\" (major ${stringMajor}) and ` +\n `adcp_major_version=${JSON.stringify(reqAdcpMajorRaw)}; majors must agree.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n }\n\n // Single-field rejection (issue #1075). The dual-field check above\n // catches drift between `adcp_version` and `adcp_major_version` when\n // both are present. A buyer that sends only one field — typically a\n // conformance harness probing the seller's `VERSION_UNSUPPORTED`\n // path — bypasses that check; the seller would otherwise dispatch\n // against its server-pinned bundle and the buyer's claim would\n // silently no-op. Resolve the effective major from whichever field\n // the buyer set, then reject if it falls outside the seller's\n // advertised window.\n //\n // The advertised window is the union of `major_versions` and parsed\n // majors from `supported_versions` (3.1+ release-precision strings),\n // with a fallback to the server pin's major when both lists are\n // absent — see `getAdvertisedSupportedMajors`. Same precedence\n // governs the `supported_versions` echo in the error envelope so\n // buyers can downgrade and retry.\n const effectiveReqMajor =\n reqAdcpMajor !== undefined && Number.isFinite(reqAdcpMajor)\n ? reqAdcpMajor\n : typeof reqAdcpVersion === 'string'\n ? parseAdcpMajorVersion(reqAdcpVersion)\n : undefined;\n if (effectiveReqMajor !== undefined && Number.isFinite(effectiveReqMajor)) {\n const supportedMajors = getAdvertisedSupportedMajors(capConfig, adcpVersion);\n if (!supportedMajors.has(effectiveReqMajor)) {\n const claimed =\n typeof reqAdcpVersion === 'string'\n ? `adcp_version=\"${reqAdcpVersion}\"`\n : `adcp_major_version=${JSON.stringify(reqAdcpMajorRaw)}`;\n const supportedList = [...supportedMajors].sort((a, b) => a - b).join(', ');\n return finalize(\n adcpError('VERSION_UNSUPPORTED', {\n message: `Request claims ${claimed} (major ${effectiveReqMajor}); this seller supports major ${supportedList}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n }\n\n // --- Credential discipline scan (opt-in) ---\n // Runs before request validation so the rejection is uniform\n // whether validation is `'off'`, `'warn'`, or `'strict'`. Closes\n // the buyer-args credential-smuggling vector class — round-1\n // top-level, round-2 nested-context, round-3 nested-ext from\n // PR scope3data/agentic-adapters#248. Args-bag scan only;\n // `authInfo` and `ctx_metadata` are not scanned (those are the\n // blessed credential channels). `'lax'` short-circuits.\n //\n // Bypasses `finalize` deliberately — `injectContextIntoResponse`\n // echoes `params.context` back into every response, which would\n // re-export the credential the scan just caught. The rejection\n // envelope reports paths (not values) and skips correlation_id\n // / version injection on this path.\n if (credentialPolicy !== undefined) {\n const effectivePolicy = resolveCredentialPolicyForTool(credentialPolicy, toolName);\n if (effectivePolicy !== 'lax') {\n const hits = scanArgsForCredentials(params, credentialPolicyPatterns);\n // Granular allow-list: filter hits by the per-tool\n // allowlist. Adopters whose tool legitimately accepts a\n // specific buyer-presented credential field list it here;\n // other credential-shaped keys still reject. String mode\n // ('authInfo-only') means no allowlist — every hit blocks.\n const blockedPaths =\n typeof effectivePolicy === 'object' ? hits.filter(p => !effectivePolicy.allow.includes(p)) : hits;\n if (blockedPaths.length > 0) {\n // Spec-correct code: the caller is authenticated and the\n // payload is schema-valid (every AdCP request schema sets\n // `additionalProperties: true`). What's refused is the\n // SELLER POLICY of \"credentials must arrive on authInfo,\n // not in args\". That's `PERMISSION_DENIED` per\n // `enums/error-code.json`, not `INVALID_REQUEST` (which\n // is for malformed/schema violations). `details.scope:\n // 'credentials'` mirrors the existing agent-status\n // rejection's `details.scope: 'agent'`.\n //\n // Deliberately omit `field` — it implies a single offending\n // path, which under-discloses when several vectors are\n // present together. Full list lives in\n // `details.credential_paths`.\n return applyResponseEnhancer(\n adcpError('PERMISSION_DENIED', {\n message:\n 'Request args carry credential-shaped keys. Credentials must arrive on authInfo, not in the request body.',\n recovery: 'correctable',\n details: { scope: 'credentials', credential_paths: blockedPaths },\n })\n );\n }\n }\n }\n\n // --- authInfo.extra credential scan (opt-in via #1539) ---\n // FULLY ORTHOGONAL to the args-bag scan above. Whereas the args\n // scan branches on `policy` mode and per-tool overrides\n // (`'lax'` short-circuits), `scanAuthInfo: true` ALWAYS fires\n // when set. The two settings answer different questions:\n //\n // - `policy` / `tools` — does this server / tool accept buyer\n // credentials in the args bag?\n // - `scanAuthInfo` — does authInfo.extra carry credential-\n // shaped keys that adopter handler code or log lines could\n // leak?\n //\n // Per-tool `'lax'` opt-out only affects args. authInfo.extra\n // is server-internal; adopters who legitimately stamp\n // credential-shaped values into it should restructure the\n // authenticator (extra is the wrong layer for credentials)\n // rather than per-tool-disable the scan.\n //\n // Wire-envelope discipline (per #1539 design): args-bag hits\n // surface in `details.credential_paths` (the buyer already\n // knows what they sent); authInfo.extra hits are LOG-ONLY.\n // Disclosing authInfo.extra paths to the buyer would create\n // a probing oracle for an internal value the buyer has no\n // read access to. The wire envelope reports a coarse signal:\n // `details.scope: 'credentials'`, generic message, no paths.\n if (\n credentialPolicy !== undefined &&\n typeof credentialPolicy !== 'string' &&\n credentialPolicy.scanAuthInfo === true\n ) {\n const extra = ctx.authInfo?.extra;\n if (extra !== null && extra !== undefined && typeof extra === 'object') {\n const authInfoHits = scanArgsForCredentials(extra, credentialPolicyPatterns);\n if (authInfoHits.length > 0) {\n // Wrap the log call defensively. Adopter loggers that throw\n // on serialization (Pino circular-ref edge cases, custom\n // transports that reject deep nesting, OTel exporters\n // mid-flush) would otherwise fault the rejection path and\n // surface as a generic 500 / unhandled rejection instead of\n // the intended PERMISSION_DENIED. The asymmetry with the\n // args-scan rejection (which doesn't log) made this a\n // logger-misconfig DoS vector before this guard.\n try {\n logger.warn('credentialPolicy: authInfo.extra carries credential-shaped keys', {\n tool: toolName,\n paths: authInfoHits.map(p => `authInfo.extra.${p}`),\n });\n } catch {\n // Swallow — the rejection envelope is the load-bearing\n // signal; losing the diagnostic log is acceptable when\n // the alternative is failing the request entirely.\n }\n return applyResponseEnhancer(\n adcpError('PERMISSION_DENIED', {\n message:\n 'Request authentication context carries credential-shaped keys. Configure your authenticator to keep credentials off authInfo.extra.',\n recovery: 'terminal',\n details: { scope: 'credentials' },\n })\n );\n }\n }\n }\n\n // --- Request schema validation (opt-in) ---\n // Runs before idempotency so drifted payloads never touch the\n // replay cache. `off` short-circuits without calling AJV.\n // Capability policy is not optional schema validation: an adopter\n // that disables AJV must still never receive a dimension it did not\n // advertise. Run that gate unconditionally for this forward tool.\n if (toolName === 'refine_proposals' && proposalRefinementCapabilities && Array.isArray(params.refinements)) {\n const supported = new Set(proposalRefinementCapabilities.supported_dimensions);\n for (const [index, candidate] of params.refinements.entries()) {\n if (!isPlainObject(candidate)) continue;\n const unsupported = refinementDimensions(candidate as never).find(dimension => !supported.has(dimension));\n if (unsupported) {\n return finalize(\n adcpError('UNSUPPORTED_FEATURE', {\n message: `seller does not advertise proposal refinement dimension ${unsupported}`,\n field: `refinements[${index}]`,\n details: {\n unsupported_dimension: unsupported,\n supported_dimensions: [...proposalRefinementCapabilities.supported_dimensions],\n },\n })\n );\n }\n }\n }\n if (requestValidationMode !== 'off') {\n const outcome = validateFrameworkPayload(\n toolName,\n 'request',\n params,\n requestRelease.validationVersion,\n proposalRefinementCapabilities\n );\n if (!outcome.valid) {\n if ('refinementError' in outcome && outcome.refinementError?.code === 'UNSUPPORTED_FEATURE') {\n return finalize(\n adcpError('UNSUPPORTED_FEATURE', {\n message: outcome.refinementError.message,\n ...(outcome.refinementError.field !== undefined && {\n field: outcome.refinementError.field,\n }),\n ...(outcome.refinementError.details !== undefined && {\n details: outcome.refinementError.details,\n }),\n })\n );\n }\n // When `idempotency: 'disabled'` is set, drop the synthetic\n // \"missing idempotency_key\" failure on mutating tools — the\n // operator has explicitly opted out of enforcement and would\n // otherwise need to UUID-inject every test payload to satisfy\n // the spec-required field. All other schema issues still fail.\n //\n // The exact-match `pointer === '/idempotency_key'` is\n // load-bearing: AJV builds the pointer from `instancePath +\n // /missingProperty`, so today every mutating tool's\n // idempotency_key sits at the top level (instancePath = '',\n // pointer = '/idempotency_key'). If a future spec revision\n // ever nests this field under another object, the new pointer\n // (`/foo/idempotency_key`) won't match this filter and the\n // strict-mode failure will correctly bubble up — drift is\n // surfaced rather than silently swallowed.\n const issues =\n idempotencyDisabled && requestIsStateChanging\n ? outcome.issues.filter(i => !(i.keyword === 'required' && i.pointer === '/idempotency_key'))\n : outcome.issues;\n if (issues.length > 0) {\n if (requestValidationMode === 'strict') {\n // Thread `exposeSchemaPath` the same way response-side does\n // so request-side schemaPath also ships in dev and stays\n // gated in production. Prior to this, request-side silently\n // stripped schemaPath even in dev — asymmetric with response-side.\n const payload = buildAdcpValidationErrorPayload(toolName, 'request', issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n });\n return finalize(adcpError('VALIDATION_ERROR', payload));\n }\n logger.warn(\n `Schema validation warning (request) for ${toolName}: ${formatIssues(issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues,\n }\n );\n }\n }\n }\n\n // --- Account resolution ---\n if (hasAccount && params.account != null && resolveAccount) {\n try {\n const account = await resolveAccount(params.account, {\n toolName: toolName as AdcpServerToolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n if (account == null) {\n logger.warn('Account not found', { tool: toolName, account: params.account });\n return finalize(\n adcpError('ACCOUNT_NOT_FOUND', {\n message: 'The specified account does not exist',\n field: 'account',\n suggestion: 'Use list_accounts to discover available accounts, or sync_accounts to create one',\n })\n );\n }\n ctx.account = account;\n } catch (err) {\n // Typed errors propagate verbatim — both the already-projected\n // envelope shape (`isThrownAdcpError`) and the raw class throw\n // (`AdcpError instanceof`). Resolvers can surface\n // `INVALID_REQUEST` for inline `account_id` against an\n // `'implicit'`-resolution platform (#1364), or any other typed\n // wire error, without coercion. Generic exceptions still\n // project to SERVICE_UNAVAILABLE so upstream leaks don't cross\n // the trust boundary.\n if (isThrownAdcpError(err)) return finalize(err);\n if (err instanceof AdcpError) {\n return finalize(projectThrownAdcpError(err));\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Account resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n } else if ((!hasAccount || params.account == null) && resolveAccountFromAuth) {\n // Auth-derived path for tools whose wire schema lacks an `account`\n // field (provide_performance_feedback, list_creative_formats, the\n // `tasks/get` polling path). Single-tenant agents return their\n // singleton; principal-keyed agents look up by authInfo. A `null`\n // return is allowed — handler sees ctx.account undefined and\n // either tolerates it (publisher-wide reads) or throws AdcpError.\n try {\n const account = await resolveAccountFromAuth({\n toolName: toolName as AdcpServerToolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n if (account != null) ctx.account = account;\n } catch (err) {\n // Same typed-error pass-through as the explicit `resolveAccount`\n // catch above — both the already-projected envelope shape and\n // the raw `AdcpError` class throw propagate verbatim. Generic\n // exceptions project to SERVICE_UNAVAILABLE.\n if (isThrownAdcpError(err)) return finalize(err);\n if (err instanceof AdcpError) {\n return finalize(projectThrownAdcpError(err));\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Auth-derived account resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // --- Sandbox-only enforcement (Phase 1.5 of #1269) ---\n // Runs after account resolution so we can compare the resolved\n // account's `sandbox` flag against the agent's `sandbox_only`\n // capability. Account-less tools (provide_performance_feedback,\n // list_creative_formats, etc.) pass the gate — they don't\n // operate on a specific account, so the sandbox/production axis\n // doesn't apply.\n //\n // Defense-in-depth for test agents (CI runners, internal QA\n // agents, partner pre-prod environments): if a sandbox-only\n // agent's credential leaks, blast radius is bounded to sandbox\n // accounts. Production agents leave `sandbox_only` unset.\n // Strict-by-default: any non-Account shape (legacy v5 adopters,\n // bespoke account types) lacking the `sandbox` field reads as\n // `undefined !== true → reject`. That's correct: a sandbox-only\n // agent operating against an unknown-shape account is the\n // case where rejection is the safe default — adopters who want\n // to opt in either flip the agent's `sandbox_only` off or\n // populate `sandbox: true` on their resolved account.\n if (\n ctx.agent?.sandbox_only === true &&\n ctx.account !== undefined &&\n (ctx.account as { sandbox?: boolean }).sandbox !== true\n ) {\n return finalize(\n adcpError('PERMISSION_DENIED', {\n message: 'Buyer agent is sandbox-only; this request targets a non-sandbox account.',\n recovery: 'terminal',\n details: { scope: 'agent', reason: 'sandbox-only' },\n })\n );\n }\n\n // --- Session key resolution ---\n if (resolveSessionKey) {\n try {\n const sessionKey = await resolveSessionKey({\n toolName: toolName as AdcpServerToolName,\n params,\n account: ctx.account,\n ...(ctx.agent != null && { agent: ctx.agent }),\n });\n if (sessionKey !== undefined) ctx.sessionKey = sessionKey;\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Session key resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Session key resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n if (CALLER_SCOPED_MUTATION_TOOLS.has(toolName)) {\n if (ctx.authInfo === undefined && ctx.agent === undefined) {\n return finalize(\n adcpError('AUTH_MISSING', {\n message: `${toolName} requires an authenticated caller principal`,\n })\n );\n }\n try {\n const scope =\n toolName === 'sync_agent_notification_configs'\n ? await config.protocol!.resolveScope!(ctx, params)\n : await config.governance!.resolveReportPlanAdjustmentScope!(ctx, params);\n if (!scope?.tenant_id || !scope.principal_id) {\n throw new Error('scope resolver must return non-empty tenant_id and principal_id');\n }\n ctx.callerMutationScope = Object.freeze({ ...scope });\n } catch (err) {\n if (err instanceof AdcpError) return finalize(projectThrownAdcpError(err));\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Caller-scoped mutation resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Caller-scoped mutation resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // Compact lifecycle mutations are account- and principal-scoped.\n // Enforce both before idempotency lookup: a cache hit returns without\n // invoking the adopter handler, so a handler-only gate would allow an\n // unauthenticated retry to receive a prior authenticated response\n // whenever a custom principal resolver collapses their namespaces.\n if (COMPACT_MEDIA_BUY_MUTATION_TOOLS.has(toolName)) {\n if (authenticatedPrincipalForContext(ctx.authInfo, ctx.agent) === undefined) {\n return finalize(\n adcpError('AUTH_MISSING', {\n message: `${toolName} requires an authenticated buyer principal`,\n })\n );\n }\n if (requireCompactMutationAccountScope && ctx.account == null) {\n return finalize(\n adcpError('ACCOUNT_NOT_FOUND', {\n message: `${toolName} requires a resolved account scope`,\n })\n );\n }\n }\n\n if (toolName === 'refine_proposals') {\n if (ctx.authInfo === undefined && ctx.agent === undefined) {\n return finalize(\n adcpError('AUTH_MISSING', {\n message: 'refine_proposals requires an authenticated buyer principal',\n })\n );\n }\n try {\n const scope = await config.proposalNegotiation!.resolveScope(ctx);\n if (!scope?.tenant_id || !scope.principal_id) {\n throw new Error('resolveScope must return non-empty tenant_id and principal_id');\n }\n ctx.proposalRefinementScope = Object.freeze({ ...scope });\n } catch (err) {\n if (err instanceof AdcpError) return finalize(projectThrownAdcpError(err));\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Proposal refinement scope resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Proposal refinement scope resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // --- idempotency_key shape gate (runs even in disabled mode) ---\n // Defense-in-depth against buyers that bypass MCP schema\n // validation (different transport, bespoke client) AND against\n // disabled-mode environments where the replay middleware below is\n // skipped. Low-entropy keys pollute the cache and enable\n // enumeration; keys containing the internal scope-separator byte\n // would collide with the cache's scope tuple. Even in disabled\n // mode (no cache, no enforcement) a malformed key flowing into\n // handler logs is a debuggability hazard — so we reject the\n // shape whenever a key was supplied, regardless of whether the\n // replay middleware will execute. Missing-key enforcement\n // remains scoped to the middleware below (gated on `idempotency`),\n // so disabled mode tolerates absence per the schema-filter\n // contract earlier in this dispatcher.\n if (\n (requestIsStateChanging || requestUsesOptionalIdempotency) &&\n hasIdempotencyKeyField &&\n (typeof params.idempotency_key !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(params.idempotency_key))\n ) {\n return finalize(\n adcpError('INVALID_REQUEST', {\n message: 'idempotency_key must match the spec pattern ^[A-Za-z0-9_.:-]{16,255}$',\n field: 'idempotency_key',\n })\n );\n }\n\n // --- Idempotency (mutating tools + get_products proposal finalize) ---\n let idempotencyCheck:\n | { key: string; principal: string; payloadHash: string; claimToken: string; extraScope?: string }\n | undefined;\n if (idempotency && requestUsesReplay) {\n const key = suppliedIdempotencyKey;\n if (!key) {\n return finalize(\n adcpError('INVALID_REQUEST', {\n message: 'idempotency_key is required on state-changing requests',\n field: 'idempotency_key',\n })\n );\n }\n // Pattern check already ran in the shape gate above. By this\n // point `key` is guaranteed to match IDEMPOTENCY_KEY_PATTERN.\n const callerMutationPrincipal = ctx.callerMutationScope\n ? JSON.stringify([\n ctx.callerMutationScope.tenant_id,\n ctx.callerMutationScope.principal_id,\n ctx.callerMutationScope.account_id ?? null,\n ])\n : undefined;\n const resolvedPrincipal =\n (resolveIdempotencyPrincipal\n ? resolveIdempotencyPrincipal(ctx, params, toolName as AdcpServerToolName)\n : (callerMutationPrincipal ?? ctx.sessionKey)) ?? '';\n const serveScope = (server as unknown as Record<symbol, unknown>)[ADCP_SERVE_IDEMPOTENCY_SCOPE];\n const principal =\n resolvedPrincipal && typeof serveScope === 'string' && serveScope.length > 0\n ? JSON.stringify([serveScope, resolvedPrincipal])\n : resolvedPrincipal;\n if (!principal) {\n logger.error('Idempotency principal unresolved', { tool: toolName });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'Idempotency principal could not be resolved — configure resolveSessionKey or resolveIdempotencyPrincipal',\n })\n );\n }\n // SI `si_send_message` is scoped per-session — the same key under\n // two different sessions must not replay into each other. The\n // caller's session_id enters the scope tuple so each session has\n // its own idempotency namespace.\n const extraScope = resolveExtraScope(\n toolName,\n params,\n ctx.account,\n ctx.sessionKey,\n ctx.proposalRefinementScope,\n ctx.callerMutationScope\n );\n const idempotencyPayload = buildIdempotencyPayload(toolName, params, ctx.account, ctx.sessionKey);\n\n try {\n const checkResult = await idempotency.check({ principal, key, payload: idempotencyPayload, extraScope });\n if (checkResult.kind === 'replay') {\n // The cache stores the already-formatted envelope (so\n // non-deterministic wrap fields like `confirmed_at` are\n // pinned to the first execution's values). Clone before\n // mutating so envelope stamps (replayed, echo-back context)\n // don't leak into the cache — the backend also clones on\n // read, but belt-and-suspenders: handler-returned objects\n // can alias pieces of the formatted envelope.\n const cachedFormatted = cloneFormattedResponse(checkResult.response as McpToolResponse);\n // Only stamp `replayed: true` on success envelopes — the\n // field is defined for successful replays, and transient\n // error cache entries (VALIDATION_ERROR from strict-mode\n // drift) are retry-storm guards, not spec replays.\n if (!isErrorResponse(cachedFormatted)) {\n stampReplayed(cachedFormatted);\n }\n // The cached envelope has already passed through the adopter's\n // response enhancer. Reapply only protocol-owned per-request\n // stamps here: enhancers may be non-idempotent (for example,\n // appending audit metadata), so invoking one again would make\n // a replay differ from the original response.\n return finalizeProtocolEnvelope(cachedFormatted);\n }\n if (checkResult.kind === 'conflict') {\n return finalize(\n adcpError('IDEMPOTENCY_CONFLICT', {\n message:\n 'idempotency_key was used earlier with a different canonical payload. Do not blindly retry with a fresh key: reconcile the prior operation by natural key, then continue only after confirming whether it succeeded.',\n })\n );\n }\n if (checkResult.kind === 'expired') {\n return finalize(\n adcpError('IDEMPOTENCY_EXPIRED', {\n message: `idempotency_key is past the seller's replay window (${idempotency.ttlSeconds}s). Use a fresh UUID v4, or look up the resource by natural key if the prior call succeeded.`,\n })\n );\n }\n if (checkResult.kind === 'in-flight') {\n // A parallel request is currently executing this same key.\n // Surface AdCP 3.1's `IDEMPOTENCY_IN_FLIGHT` with a transient\n // recovery + store-derived `retry_after`. Buyer SDKs that\n // already auto-retry transient + retry_after replay shortly;\n // the prior request either lands the cached response or\n // (different payload) triggers IDEMPOTENCY_CONFLICT.\n return finalize(\n adcpError('IDEMPOTENCY_IN_FLIGHT', {\n message: 'A parallel request with the same idempotency_key is still in flight. Retry shortly.',\n recovery: 'transient',\n retry_after: checkResult.retryAfterSeconds,\n })\n );\n }\n idempotencyCheck = {\n key,\n principal,\n payloadHash: checkResult.payloadHash,\n claimToken: checkResult.claimToken,\n extraScope,\n };\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Idempotency check failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Idempotency check failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // Keep the request owner fence alive for the entire handler and\n // response-publication path. Without renewal, a mutation running\n // longer than the 120-second claim lease could be reclaimed and\n // executed concurrently by a retry. Renewal is serialized so a\n // slow backend cannot accumulate overlapping timer callbacks; the\n // final save/release CAS remains the authoritative ownership check.\n let claimRenewalTimer: ReturnType<typeof setInterval> | undefined;\n let claimRenewalPending: Promise<void> | undefined;\n if (idempotencyCheck && idempotency) {\n const renewClaim = () => {\n if (claimRenewalPending) return;\n claimRenewalPending = idempotency\n .renew({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n })\n .catch(err => {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency claim renewal failed; final publication will re-check ownership', {\n tool: toolName,\n error: reason,\n });\n })\n .finally(() => {\n claimRenewalPending = undefined;\n });\n };\n claimRenewalTimer = setInterval(renewClaim, IDEMPOTENCY_CLAIM_RENEW_INTERVAL_MS);\n if (typeof claimRenewalTimer === 'object' && 'unref' in claimRenewalTimer) claimRenewalTimer.unref();\n }\n\n // --- Handler ---\n let mutationHandlerCompleted = false;\n try {\n if (webhookEmitter) {\n const tenantScope = webhookTenantScopeForContext(ctx);\n const scopedEmitter =\n tenantScope === undefined ? configuredWebhookEmitter! : webhookEmitter.forTenantScope(tenantScope);\n ctx.emitWebhook = scopedEmitter.emit.bind(scopedEmitter);\n }\n const result = await handler(params, ctx);\n mutationHandlerCompleted = true;\n // Narrow Error / Submitted arms of the *Response union before\n // reaching the success-arm builder: wrap() on an Error payload\n // would still serialize it but apply success-shaped defaults\n // (revision, confirmed_at, 'Media buy undefined created') to\n // a shape that doesn't have those fields. Routing here keeps\n // the wire shape correct regardless of which arm the handler\n // chose to return.\n let formatted: McpToolResponse;\n if (isFormattedResponse(result)) {\n formatted = result;\n } else if (isSubmittedEnvelope(result)) {\n formatted = wrapSubmittedEnvelope(result);\n } else if (isErrorArm(result)) {\n // Log-warn (always) on spec-violating Error items — required\n // `code`/`message` are spec-mandatory on core/error.json. We\n // must fail closed here: error envelopes skip response-schema\n // validation, and blindly wrapping malformed primitives can leak\n // secret-bearing strings in `errors[]`.\n const malformed = (result.errors as unknown[]).some(\n e =>\n e == null ||\n typeof e !== 'object' ||\n typeof (e as Record<string, unknown>).code !== 'string' ||\n typeof (e as Record<string, unknown>).message !== 'string'\n );\n if (malformed) {\n logger.warn(`Handler returned ${toolName} Error arm with spec-violating errors[]`, {\n tool: toolName,\n count: (result.errors as unknown[]).length,\n });\n const errPayload = buildAdcpValidationErrorPayload(\n toolName,\n 'response',\n [\n {\n pointer: '/errors',\n message: 'must contain Error objects with string code and message fields',\n keyword: 'type',\n schemaPath: '#/properties/errors/items',\n hint: 'Return errors as `{ code, message }` objects; do not return raw strings or exception values.',\n },\n ],\n { exposeSchemaPath: exposeErrorDetails }\n );\n formatted = adcpError('VALIDATION_ERROR', errPayload);\n } else {\n formatted = wrapErrorArm(result);\n }\n } else {\n formatted = wrap(result);\n }\n\n // --- Test-controller bridge: augment read-side tools with seeded fixtures. ---\n // Each per-tool callback (`getSeededProducts`, `getSeededCreatives`, ...)\n // is opt-in by presence on the bridge interface. All callbacks share the\n // same triply-gated contract:\n // 1. The bridge is registered AND has the matching callback;\n // 2. The handler returned a success envelope (not an `adcp_error`);\n // 3. The request carries a sandbox marker (account.sandbox === true or\n // context.sandbox === true) AND the applicable resolver produced\n // a trusted account in sandbox/mock mode (legacy sandbox:true is\n // accepted during migration). Unresolved accounts fail closed.\n // For array-collection tools, seeded entries append to the handler's\n // response with seeded winning on id collision (same as `getSeededProducts`).\n // `get_account_financials` is the exception — singleton response, so the\n // seeded entry REPLACES the handler payload when its `account.account_id`\n // matches the request's `account.account_id`.\n // Diagnostic for adopters chasing \"why aren't my fixtures showing\":\n // when the request carries a sandbox marker but the resolved account\n // is explicitly non-sandbox, the gate rejects silently. Emit a\n // `debug` line so the rejection is observable in dev logs without\n // adding noise to production traffic (where the gate's first check\n // — `isSandboxRequestForSeeding` — fails first and never reaches\n // this branch).\n if (\n testControllerBridge &&\n !isErrorResponse(formatted) &&\n isSandboxRequestForSeeding(params) &&\n ctx.account !== undefined &&\n !isSandboxOrMockAccount(ctx.account)\n ) {\n // Include the resolved account_id so the log line is self-\n // diagnostic — an adopter chasing \"why aren't my fixtures\n // showing\" can match the rejected account against their\n // resolveAccount source without correlating across log lines.\n // account_ids appear in normal request logs already; no new\n // PII surface.\n const resolvedAccountId =\n typeof ctx.account === 'object' &&\n ctx.account !== null &&\n typeof (ctx.account as { account_id?: unknown }).account_id === 'string'\n ? ((ctx.account as { account_id?: unknown }).account_id as string)\n : undefined;\n logger.debug(\n 'test-controller bridge: request is sandbox-flagged but resolved account is not sandbox; skipping merge',\n { tool: toolName, resolved_account_id: resolvedAccountId }\n );\n }\n\n if (\n testControllerBridge &&\n !isErrorResponse(formatted) &&\n isSandboxRequestForSeeding(params) &&\n isSandboxOrMockAccount(ctx.account)\n ) {\n const bridgeCtx: TestControllerBridgeContext<TAccount> = { input: params, account: ctx.account };\n\n // get_products\n if (toolName === 'get_products' && testControllerBridge.getSeededProducts) {\n try {\n const rawSeeded = await testControllerBridge.getSeededProducts(bridgeCtx);\n const seeded = filterValidSeededProducts(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetProductsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededProductsIntoResponse(sc, seeded);\n formatted = wrap(merged, _getExplicitResponseSummary(formatted));\n stampBridge(formatted, 'getSeededProducts', toolName, seeded.length);\n }\n }\n } catch (err) {\n // Bridge failures are sandbox-only by construction, so logging +\n // returning the handler's response is the right default — a broken\n // test fixture shouldn't tank the request under test.\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededProducts failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_creatives\n else if (toolName === 'list_creatives' && testControllerBridge.getSeededCreatives) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreatives(bridgeCtx);\n const seeded = filterValidSeededCreatives(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListCreativesResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativesIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreatives', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreatives failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_media_buys\n else if (toolName === 'get_media_buys' && testControllerBridge.getSeededMediaBuys) {\n try {\n const rawSeeded = await testControllerBridge.getSeededMediaBuys(bridgeCtx);\n const seeded = filterValidSeededMediaBuys(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetMediaBuysResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededMediaBuysIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededMediaBuys', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededMediaBuys failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_media_buy_delivery\n else if (toolName === 'get_media_buy_delivery' && testControllerBridge.getSeededMediaBuyDelivery) {\n try {\n const rawSeeded = await testControllerBridge.getSeededMediaBuyDelivery(bridgeCtx);\n const seeded = filterValidSeededMediaBuyDeliveries(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetMediaBuyDeliveryResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededMediaBuyDeliveryIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededMediaBuyDelivery', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededMediaBuyDelivery failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_accounts\n else if (toolName === 'list_accounts' && testControllerBridge.getSeededAccounts) {\n try {\n const rawSeeded = await testControllerBridge.getSeededAccounts(bridgeCtx);\n const seeded = filterValidSeededAccounts(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListAccountsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededAccountsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededAccounts', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededAccounts failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_account_financials (singleton — replace, not append)\n else if (toolName === 'get_account_financials' && testControllerBridge.getSeededAccountFinancials) {\n try {\n const rawSeeded = await testControllerBridge.getSeededAccountFinancials(bridgeCtx);\n const seeded = filterValidSeededAccountFinancials(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetAccountFinancialsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n // Brand+operator `AccountReference` variants don't carry\n // `account_id` on the wire — the framework's resolved\n // account does, so prefer it for the match key.\n const resolvedAccountId =\n ctx.account && typeof ctx.account === 'object' && !Array.isArray(ctx.account)\n ? ((ctx.account as { account_id?: unknown }).account_id as string | undefined)\n : undefined;\n const merged = replaceAccountFinancialsIfSeeded(\n params as import('../types/tools.generated').GetAccountFinancialsRequest,\n sc,\n seeded,\n typeof resolvedAccountId === 'string' && resolvedAccountId.length > 0\n ? resolvedAccountId\n : undefined\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededAccountFinancials', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededAccountFinancials failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_creative_formats\n else if (toolName === 'list_creative_formats' && testControllerBridge.getSeededCreativeFormats) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreativeFormats(bridgeCtx);\n const seeded = filterValidSeededCreativeFormats(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListCreativeFormatsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativeFormatsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreativeFormats', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreativeFormats failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_property_lists / get_property_list — one seeded fixture array\n // feeds both. List path: append-merge with seeded-wins on `list_id`\n // collision. Get path: pick by request.list_id and replace the\n // response's `list` field, preserving handler's resolved data\n // (`identifiers` / `pagination` / `resolved_at` / `cache_valid_until`\n // / `coverage_gaps` / `context` / `ext`).\n else if (\n (toolName === 'list_property_lists' || toolName === 'get_property_list') &&\n testControllerBridge.getSeededPropertyLists\n ) {\n try {\n const rawSeeded = await testControllerBridge.getSeededPropertyLists(bridgeCtx);\n const seeded = filterValidSeededPropertyLists(rawSeeded, logger);\n if (seeded.length > 0) {\n if (toolName === 'list_property_lists') {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListPropertyListsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededPropertyListsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededPropertyLists', toolName, seeded.length);\n }\n } else {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetPropertyListResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replacePropertyListIfSeeded(\n params as import('../types/tools.generated').GetPropertyListRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededPropertyLists', toolName, seeded.length);\n }\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededPropertyLists failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_collection_lists / get_collection_list — symmetric with\n // property lists.\n else if (\n (toolName === 'list_collection_lists' || toolName === 'get_collection_list') &&\n testControllerBridge.getSeededCollectionLists\n ) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCollectionLists(bridgeCtx);\n const seeded = filterValidSeededCollectionLists(rawSeeded, logger);\n if (seeded.length > 0) {\n if (toolName === 'list_collection_lists') {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListCollectionListsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCollectionListsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCollectionLists', toolName, seeded.length);\n }\n } else {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetCollectionListResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceCollectionListIfSeeded(\n params as import('../types/tools.generated').GetCollectionListRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCollectionLists', toolName, seeded.length);\n }\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCollectionLists failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_signals — append-merge by signal_id. Works uniformly across\n // signal-marketplace and signal-owned specialisms (one bridge, both\n // dispatched on the same tool; the per-signal `signal_type` field\n // is the marketplace-vs-owned discriminator).\n else if (toolName === 'get_signals' && testControllerBridge.getSeededSignals) {\n try {\n const rawSeeded = await testControllerBridge.getSeededSignals(bridgeCtx);\n const seeded = filterValidSeededSignals(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetSignalsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededSignalsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededSignals', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededSignals failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_creative_delivery — append-merge by creative_id;\n // `pagination.total` (when set by the handler) updates by the\n // count of new non-colliding seeded entries. No aggregated-totals\n // recomputation — this response has no top-level totals envelope.\n else if (toolName === 'get_creative_delivery' && testControllerBridge.getSeededCreativeDelivery) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreativeDelivery(bridgeCtx);\n const seeded = filterValidSeededCreativeDelivery(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetCreativeDeliveryResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativeDeliveryIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreativeDelivery', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreativeDelivery failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_creative_features — `oneOf` envelope. Success arm: merge\n // seeded `CreativeFeatureResult[]` into `results` (dedup by\n // `feature_id`, seeded wins). Error arm: no-op (the helper\n // discriminates by presence of `results: []`).\n else if (toolName === 'get_creative_features' && testControllerBridge.getSeededCreativeFeatures) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreativeFeatures(bridgeCtx);\n const seeded = filterValidSeededCreativeFeatures(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetCreativeFeaturesResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativeFeaturesIntoResponse(sc, seeded);\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreativeFeatures', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreativeFeatures failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_brand_identity — singleton replace keyed by `brand_id`.\n // Seeded fixture is authoritative on the GetBrandIdentitySuccess\n // body; handler's `context` / `ext` round-trip. The response is\n // a union (success | error) — the dispatcher already gated on\n // `!isErrorResponse`, so we narrow defensively when reading.\n else if (toolName === 'get_brand_identity' && testControllerBridge.getSeededBrandIdentity) {\n try {\n const rawSeeded = await testControllerBridge.getSeededBrandIdentity(bridgeCtx);\n const seeded = filterValidSeededBrandIdentity(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/core.generated').GetBrandIdentityResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceBrandIdentityIfSeeded(\n params as import('../types/core.generated').GetBrandIdentityRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededBrandIdentity', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededBrandIdentity failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_rights — append-merge keyed by `rights_id`. Discovery /\n // search tool (NL `query`); the response carries `rights[]`.\n // Drops to a no-op on the error arm of the response union.\n else if (toolName === 'get_rights' && testControllerBridge.getSeededRights) {\n try {\n const rawSeeded = await testControllerBridge.getSeededRights(bridgeCtx);\n const seeded = filterValidSeededRights(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/core.generated').GetRightsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededRightsIntoResponse(sc, seeded);\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededRights', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededRights failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // si_get_offering — singleton replace keyed by `offering_id`.\n // Stateless catalog lookup; the response's `offering_token` is\n // produced for a future session but the lookup itself does not\n // consume one. Handler's `context` / `ext` round-trip.\n else if (toolName === 'si_get_offering' && testControllerBridge.getSeededSiOffering) {\n try {\n const rawSeeded = await testControllerBridge.getSeededSiOffering(bridgeCtx);\n const seeded = filterValidSeededSiOffering(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').SIGetOfferingResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceSiOfferingIfSeeded(\n params as import('../types/tools.generated').SIGetOfferingRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededSiOffering', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededSiOffering failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_content_standards / get_content_standards — list returns\n // `{ standards: ContentStandards[] }` (success arm of a union; the\n // error arm is gated out upstream). Get returns `ContentStandards`\n // directly (success arm); replace the ContentStandards body and\n // round-trip handler's `context` / `ext` (both are framework-\n // managed envelope fields per the spec).\n else if (\n (toolName === 'list_content_standards' || toolName === 'get_content_standards') &&\n testControllerBridge.getSeededContentStandards\n ) {\n try {\n const rawSeeded = await testControllerBridge.getSeededContentStandards(bridgeCtx);\n const seeded = filterValidSeededContentStandards(rawSeeded, logger);\n if (seeded.length > 0) {\n if (toolName === 'list_content_standards') {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListContentStandardsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededContentStandardsIntoResponse(sc, seeded);\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededContentStandards', toolName, seeded.length);\n }\n }\n } else {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetContentStandardsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceContentStandardsIfSeeded(\n params as import('../types/tools.generated').GetContentStandardsRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededContentStandards', toolName, seeded.length);\n }\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededContentStandards failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n }\n\n if (!isErrorResponse(formatted)) {\n if (toolName === 'get_products') {\n formatted =\n normalizeGetProductsCacheScope(formatted, params, ctx.account, ctx.authInfo, exposeErrorDetails) ??\n formatted;\n }\n if (!isErrorResponse(formatted)) {\n normalizeMediaBuyStatusCollision(formatted, toolName);\n injectEnvelopeStatusIntoResponse(formatted, toolName);\n }\n }\n\n // --- Response schema validation (opt-in) ---\n // Runs on the structured payload the handler produced. Errors\n // have their own envelope (`adcp_error`) and are skipped here —\n // their shape is enforced by the adcpError() builder.\n if (responseValidationMode !== 'off' && !isErrorResponse(formatted)) {\n const payload = formatted.structuredContent;\n const outcome = validateFrameworkPayload(toolName, 'response', payload, requestRelease.validationVersion);\n if (!outcome.valid) {\n logger.warn(\n `Schema validation warning (response) for ${toolName}: ${formatIssues(outcome.issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues: outcome.issues,\n variant: outcome.variant,\n }\n );\n if (responseValidationMode === 'strict') {\n const errPayload = buildAdcpValidationErrorPayload(toolName, 'response', outcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n });\n const errEnvelope = finalize(adcpError('VALIDATION_ERROR', errPayload));\n if (idempotencyCheck && idempotency) {\n // A mutating handler has already returned, so its side\n // effect may be committed even though strict response\n // validation rejected the representation. Fence that\n // ambiguity for the full replay window: a short-lived\n // retry-storm entry could disappear and permit the same\n // mutation to execute again. Read-only keyed operations\n // retain the short transient-error behavior.\n try {\n if (toolIsMutating || requestIsStateChanging) {\n await idempotency.save({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: stripEnvelopeEcho(errEnvelope),\n extraScope: idempotencyCheck.extraScope,\n });\n } else if (idempotency.saveTransientError) {\n await idempotency.saveTransientError({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: errEnvelope,\n extraScope: idempotencyCheck.extraScope,\n });\n } else {\n await idempotency.release({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n });\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency validation-error publication failed', {\n tool: toolName,\n error: reason,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n err instanceof IdempotencyClaimOwnershipError\n ? 'The request lost its idempotency claim before its response could be published. Retry safely.'\n : 'The response could not be published to the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n }\n return errEnvelope;\n }\n }\n }\n // Complete every potentially-throwing framework transformation\n // before publishing the successful idempotency record. If an\n // enhancer or envelope normalizer fails, the catch below still\n // owns the request claim and can replace it with an ambiguity\n // fence; publishing success first would make that replacement\n // impossible and an exact retry would re-trigger the same broken\n // post-processing path.\n formatted = finalize(formatted);\n\n // Cache successful mutations for replay. Errors and commercial\n // rejection rows re-execute on retry, not replayed — capability /\n // status changes in the seller's ledger must take effect without\n // waiting for an idempotency TTL to expire. Release the in-flight\n // claim on uncacheable responses so a retry can re-execute.\n //\n // Cache the FORMATTED envelope, not the raw handler return:\n // some wrap functions inject non-deterministic fields\n // (`confirmed_at = new Date().toISOString()`) when the handler\n // omits them. Re-wrapping on replay would produce a different\n // `confirmed_at` each time, breaking the \"same response on\n // replay\" contract. Caching the formatted envelope pins those\n // fields to their first-execution values.\n if (idempotencyCheck && idempotency) {\n if (shouldCacheIdempotencyResponse(formatted)) {\n try {\n // Strip `context` before caching — it's a per-request echo\n // field (buyer's correlation_id), not part of the cached\n // payload. If we cached it, replays would return the\n // FIRST caller's correlation_id to every subsequent\n // retry, breaking end-to-end request tracing. On replay,\n // `finalize()` re-injects the current request's context.\n const cacheable = stripEnvelopeEcho(formatted);\n await idempotency.save({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: cacheable,\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency save failed — response will not be cached', {\n tool: toolName,\n error: reason,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n err instanceof IdempotencyClaimOwnershipError\n ? 'The request lost its idempotency claim before its response could be published. Retry safely.'\n : 'The response could not be published to the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n // Fresh-path responses omit `replayed` — per envelope spec,\n // absence signals fresh execution. The replay path stamps\n // `replayed: true` on the cached copy at retrieval.\n } else {\n try {\n await idempotency.release({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (err) {\n // Best-effort release; if it fails the claim TTL will\n // eventually evict. Log and move on.\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency release failed — in-flight claim will expire on TTL', {\n tool: toolName,\n error: reason,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n err instanceof IdempotencyClaimOwnershipError\n ? 'The request lost its idempotency claim before its response could be published. Retry safely.'\n : 'The response could not be released from the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n }\n }\n return formatted;\n } catch (err) {\n if (idempotencyCheck && idempotency && (toolIsMutating || requestIsStateChanging)) {\n // Once a mutating application handler has been invoked, a thrown\n // exception cannot prove that no side effect committed. Never\n // release that claim for blind re-execution. Stable typed errors\n // are cached as the handler outcome; unknown exceptions and\n // post-handler framework failures become a full-window ambiguity\n // fence that requires natural-key reconciliation.\n let thrownTypedEnvelope: McpToolResponse | undefined;\n if (isThrownAdcpError(err)) {\n const env = (err.structuredContent as { adcp_error: { code: string; message: string } }).adcp_error;\n logger.warn('Handler threw an adcpError envelope — prefer `return` over `throw` for typed errors', {\n tool: toolName,\n handler: handlerKey,\n code: env.code,\n message: env.message,\n stack: err instanceof Error ? err.stack : undefined,\n });\n thrownTypedEnvelope = err;\n } else if (err instanceof AdcpError) {\n logger.warn('Handler threw an AdcpError', {\n tool: toolName,\n handler: handlerKey,\n code: err.code,\n message: err.message,\n stack: err.stack,\n });\n thrownTypedEnvelope = projectThrownAdcpError(err);\n }\n\n const thrownRecovery = thrownTypedEnvelope ? thrownAdcpErrorRecovery(thrownTypedEnvelope) : undefined;\n let replayEnvelope: McpToolResponse;\n if (!mutationHandlerCompleted && thrownTypedEnvelope && thrownRecovery !== 'transient') {\n // A terminal typed rejection thrown directly by the handler is\n // a stable outcome. Cache it so exact retry cannot re-enter the\n // mutation. Transient typed errors are intentionally not\n // replayed as retryable for the full window: after handler\n // admission they are indistinguishable from commit-then-throw.\n replayEnvelope = thrownTypedEnvelope;\n } else {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Mutating handler outcome is uncertain and requires reconciliation', {\n tool: toolName,\n handler: handlerKey,\n error: reason,\n stack: err instanceof Error ? err.stack : undefined,\n });\n replayEnvelope = adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'The mutating handler did not produce a safely publishable response. Reconcile the operation by natural key before retrying.',\n });\n }\n\n try {\n replayEnvelope = finalize(replayEnvelope);\n } catch (finalizeErr) {\n const finalizeReason = finalizeErr instanceof Error ? finalizeErr.message : String(finalizeErr);\n logger.error('Response processing failed while formatting a fenced mutation outcome', {\n tool: toolName,\n error: finalizeReason,\n });\n replayEnvelope = adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'The mutating handler did not produce a safely publishable response. Reconcile the operation by natural key before retrying.',\n });\n }\n\n try {\n await idempotency.save({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: stripEnvelopeEcho(replayEnvelope),\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (saveErr) {\n const saveReason = saveErr instanceof Error ? saveErr.message : String(saveErr);\n logger.error('Idempotency mutation-outcome publication failed; retaining the live owner claim', {\n tool: toolName,\n error: saveReason,\n });\n return adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'The mutating handler outcome could not be published to the idempotency store. Reconcile by natural key before retrying.',\n });\n }\n return replayEnvelope;\n }\n // Non-mutating thrown paths may release their optional claim: no\n // state-changing handler was invoked, so exact retry is safe.\n let idempotencyReleaseError: unknown;\n if (idempotencyCheck && idempotency) {\n try {\n await idempotency.release({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (releaseErr) {\n const releaseReason = releaseErr instanceof Error ? releaseErr.message : String(releaseErr);\n logger.warn('Idempotency release failed — in-flight claim will expire on TTL', {\n tool: toolName,\n error: releaseReason,\n });\n idempotencyReleaseError = releaseErr;\n }\n }\n if (idempotencyReleaseError !== undefined) {\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n idempotencyReleaseError instanceof IdempotencyClaimOwnershipError\n ? 'The failed request lost its idempotency claim before the claim could be released. Retry safely.'\n : 'The failed request could not be released from the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n // Auto-unwrap `throw adcpError(...)`. Handlers that throw an\n // envelope (instead of returning it) should behave identically —\n // otherwise the envelope surfaces as `[object Object]` inside\n // SERVICE_UNAVAILABLE and the buyer loses the typed domain code.\n // Matrix harnesses and fresh-built agents consistently get this\n // wrong; unwrapping at the dispatcher closes the class of bugs\n // instead of relying on every skill to show `return` over `throw`.\n if (isThrownAdcpError(err)) {\n const env = (err.structuredContent as { adcp_error: { code: string; message: string } }).adcp_error;\n // Log message + stack so forensic review sees what was thrown\n // (not just the code). The thrown envelope is a plain object so\n // `.stack` is typically absent, but authors sometimes subclass\n // `Error` and attach envelope fields; capture it defensively.\n logger.warn('Handler threw an adcpError envelope — prefer `return` over `throw` for typed errors', {\n tool: toolName,\n handler: handlerKey,\n code: env.code,\n message: env.message,\n stack: err instanceof Error ? err.stack : undefined,\n });\n return finalize(err);\n }\n // Raw `AdcpError` class throws — distinct from the\n // already-projected envelope above. The framework has long\n // documented `throw new AdcpError(...)` as the canonical way\n // to signal structured rejection from any specialism method\n // (see `AdcpError` JSDoc). Project to the typed envelope so\n // the buyer sees the typed code, not `SERVICE_UNAVAILABLE`.\n if (err instanceof AdcpError) {\n logger.warn('Handler threw an AdcpError', {\n tool: toolName,\n handler: handlerKey,\n code: err.code,\n message: err.message,\n stack: err.stack,\n });\n return finalize(projectThrownAdcpError(err));\n }\n const reason = err instanceof Error ? err.message : String(err);\n // Log the full stack — `logger.error` with just the message turned\n // every \"Handler failed\" into a guessing game for agent authors.\n // Stack tells you which import/typo/access chain blew up.\n logger.error('Handler failed', {\n tool: toolName,\n handler: handlerKey,\n error: reason,\n stack: err instanceof Error ? err.stack : undefined,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n // Include the cause message directly in the response text when\n // `exposeErrorDetails` is on. The opaque\n // \"Tool X encountered an internal error\" string cost us weeks\n // of diagnostic time on the matrix harness — dev callers want\n // the real reason at the call site, not hidden in server logs.\n message: exposeErrorDetails\n ? `Tool ${toolName} handler threw: ${redactCredentialPatterns(reason)}`\n : `Tool ${toolName} encountered an internal error`,\n ...(exposeErrorDetails && {\n details: { reason: redactCredentialPatterns(reason), handler: handlerKey },\n }),\n })\n );\n } finally {\n if (claimRenewalTimer !== undefined) clearInterval(claimRenewalTimer);\n if (claimRenewalPending) await claimRenewalPending;\n }\n };\n\n // Register a PASSTHROUGH input schema by default (#909). The MCP\n // SDK's Zod validator only fires on the MCP transport — A2A calls\n // the handler via AdcpServer.invoke(), bypassing it. Registering the\n // real per-tool Zod schema meant MCP and A2A produced different\n // verdicts and different error shapes for the same malformed request.\n // Our framework request validator (AJV, loaded from\n // schemas/cache/<version>/) runs inside the handler closure on BOTH\n // transports and produces a structured adcp_error envelope; make it\n // authoritative unless the adopter opts into MCP discovery schemas.\n //\n // Passthrough (not omit): the SDK's `validateToolInput` returns\n // `undefined` when `inputSchema` is absent (see @modelcontextprotocol/sdk\n // server/mcp.js), and passes that `undefined` verbatim to the\n // handler — destroying the actual arguments. `z.object({}).passthrough()`\n // keeps every key intact, so args still reach the closure.\n //\n // Trade-off: default MCP `tools/list` publishes `{ type: 'object' }`\n // for every tool (no per-tool parameter schema). This is intentional,\n // not a wiring gap — inlining full request schemas in `tools/list`\n // would balloon the context window for LLM consumers. Tool shapes\n // live in `docs/llms.txt`, the SKILL.md files, and `schemas/cache/`,\n // which curated agents read on demand instead of paying the cost\n // every connection. AdCP-native discovery via `get_adcp_capabilities`\n // already works over both transports; upstream #3057 proposes a\n // `get_schema` capability tool for programmatic per-tool shape\n // discovery. For generic MCP clients that need hints directly in\n // `tools/list`, set `exposeToolSchemas: true` to publish shallow\n // top-level key hints derived from `TOOL_INPUT_SHAPES`. Those hint\n // schemas use optional `unknown` fields plus passthrough so MCP keeps\n // all args intact and leaves substantive validation under the\n // framework validator.\n //\n // Implication for downstream consumers: if you need a tool's shape\n // (cross-version field-stripping, gating, validation), read raw\n // JSON from `schemas/cache/{version}/` via `schema-loader.ts` —\n // see `schemaAllowsTopLevelField` for the canonical pattern (#940).\n // Don't try to recover the canonical shape from `tools/list` when\n // `exposeToolSchemas` is off; it's empty by design and will fail open.\n server.registerTool(\n toolName,\n {\n inputSchema: frameworkInputSchemaFor(toolName),\n ...(meta?.annotations != null && { annotations: meta.annotations }),\n _meta: frameworkToolMeta,\n },\n toolHandler as Parameters<typeof server.registerTool>[2]\n );\n\n registeredToolNames.add(toolName);\n }\n }\n\n if (supportsProtocolTaskTools && taskRegistry !== undefined) {\n server.registerTool(\n 'get_task_status',\n {\n inputSchema: frameworkInputSchemaFor('get_task_status'),\n annotations: RO,\n _meta: frameworkToolMeta,\n },\n (async (params: any, extra: any) => {\n const credentialError = taskToolCredentialPolicyError('get_task_status', params ?? {}, extra);\n if (credentialError) {\n return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, credentialError, {\n echoContext: false,\n });\n }\n const validationError = protocolTaskRequestValidationError('get_task_status', params ?? {});\n if (validationError) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, validationError);\n const boundsError = protocolTaskBoundsError('get_task_status', params ?? {});\n if (boundsError) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, boundsError);\n const versionError = unsupportedVersionResponse('get_task_status', params ?? {});\n if (versionError) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, versionError);\n const taskId = typeof params?.task_id === 'string' ? params.task_id : '';\n const { accountId, ownerScope, error } = await resolveTaskQueryAccountId(\n params ?? {},\n extra,\n 'get_task_status'\n );\n if (error) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, error);\n let task: TaskRecord | null = null;\n try {\n task = taskId && taskRegistry !== undefined ? await taskRegistry.getTask(taskId) : null;\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Task registry read failed during task poll', { tool: 'get_task_status', error: reason });\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Task registry read failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n if (task == null || accountId === undefined || !taskBelongsToCaller(task, accountId, ownerScope)) {\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n adcpError('REFERENCE_NOT_FOUND', {\n message: taskId ? `Task ${taskId} not found` : 'Task not found',\n field: 'task_id',\n })\n );\n }\n\n const response = toProtocolTaskStatus(task);\n if (response === undefined) {\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n adcpError('REFERENCE_NOT_FOUND', {\n message: taskId ? `Task ${taskId} not found` : 'Task not found',\n field: 'task_id',\n })\n );\n }\n if (\n params?.include_result === true &&\n (response.status === 'completed' || response.status === 'failed' || response.status === 'rejected') &&\n task.result !== undefined\n ) {\n response.result = task.result as GetTaskStatusResponse['result'];\n }\n if (isPlainObject(params?.context)) response.context = params.context;\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n genericResponse('get_task_status', response)\n );\n }) as Parameters<typeof server.registerTool>[2]\n );\n registeredToolNames.add('get_task_status');\n }\n\n if (supportsProtocolTaskTools && taskRegistry?.list !== undefined) {\n server.registerTool(\n 'list_tasks',\n {\n inputSchema: frameworkInputSchemaFor('list_tasks'),\n annotations: RO,\n _meta: frameworkToolMeta,\n },\n (async (params: any, extra: any) => {\n const credentialError = taskToolCredentialPolicyError('list_tasks', params ?? {}, extra);\n if (credentialError) {\n return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, credentialError, { echoContext: false });\n }\n const validationError = protocolTaskRequestValidationError('list_tasks', params ?? {});\n if (validationError) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, validationError);\n const boundsError = protocolTaskBoundsError('list_tasks', params ?? {});\n if (boundsError) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, boundsError);\n const versionError = unsupportedVersionResponse('list_tasks', params ?? {});\n if (versionError) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, versionError);\n const { accountId, ownerScope, error } = await resolveTaskQueryAccountId(params ?? {}, extra, 'list_tasks');\n if (error) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, error);\n let cursorStart = 0;\n try {\n cursorStart =\n parseTaskListCursor(isPlainObject(params?.pagination) ? params.pagination.cursor : undefined) ?? 0;\n } catch (err) {\n return finalizeProtocolTaskToolResponse(\n 'list_tasks',\n params ?? {},\n adcpError('INVALID_REQUEST', {\n message: err instanceof Error ? err.message : 'Invalid task list cursor',\n field: 'pagination.cursor',\n })\n );\n }\n\n let listed: { tasks: TaskRecord[] };\n try {\n listed =\n accountId !== undefined && ownerScope !== undefined && taskRegistry?.list !== undefined\n ? await taskRegistry.list({ accountId, ownerScope })\n : { tasks: [] };\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Task registry list failed during task poll', { tool: 'list_tasks', error: reason });\n return finalizeProtocolTaskToolResponse(\n 'list_tasks',\n params ?? {},\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Task registry list failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n const filteredTasks = listed.tasks.filter(\n task =>\n accountId !== undefined &&\n taskBelongsToCaller(task, accountId, ownerScope) &&\n taskMatchesFilters(task, params?.filters)\n );\n const sortedTasks = filteredTasks\n .map(toProtocolTaskListItem)\n .filter((task): task is ListTasksResponse['tasks'][number] => task !== undefined)\n .sort((left, right) => compareProtocolTaskItems(left, right, params?.sort));\n const pageSize = taskListPageSize(params?.pagination);\n const tasks = sortedTasks.slice(cursorStart, cursorStart + pageSize);\n const nextOffset = cursorStart + tasks.length;\n const hasMore = nextOffset < sortedTasks.length;\n const status_breakdown = sortedTasks.reduce<Record<string, number>>((counts, task) => {\n counts[task.status] = (counts[task.status] ?? 0) + 1;\n return counts;\n }, {});\n const domain_breakdown = sortedTasks.reduce<Record<string, number>>((counts, task) => {\n counts[task.domain] = (counts[task.domain] ?? 0) + 1;\n return counts;\n }, {});\n const response: ListTasksResponse = {\n status: 'completed',\n query_summary: {\n total_matching: sortedTasks.length,\n returned: tasks.length,\n domain_breakdown,\n status_breakdown,\n filters_applied: isPlainObject(params?.filters) ? Object.keys(params.filters) : [],\n sort_applied: {\n field:\n isPlainObject(params?.sort) && typeof params.sort.field === 'string' ? params.sort.field : 'created_at',\n direction: isPlainObject(params?.sort) && params.sort.direction === 'asc' ? 'asc' : 'desc',\n },\n },\n tasks,\n pagination: {\n has_more: hasMore,\n ...(hasMore && { cursor: String(nextOffset) }),\n total_count: sortedTasks.length,\n },\n };\n if (isPlainObject(params?.context)) response.context = params.context;\n return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, genericResponse('list_tasks', response));\n }) as Parameters<typeof server.registerTool>[2]\n );\n registeredToolNames.add('list_tasks');\n }\n\n // ─── Custom tools ──────────────────────────────────────────\n // Seller extensions outside AdcpToolMap. No idempotency / governance /\n // response-wrapping — handlers own those concerns directly. Registered\n // after spec tools so the collision check can authoritatively block\n // overlap with framework-owned names.\n if (config.customTools) {\n const customNames = Object.keys(config.customTools);\n for (const customName of customNames) {\n if (registeredToolNames.has(customName)) {\n throw new Error(\n `createAdcpServer: customTools[\"${customName}\"] collides with a framework-registered tool. ` +\n `If this customTool worked in an earlier SDK version, the tool was promoted to first-class — ` +\n `remove the customTools entry and wire the corresponding platform handler instead ` +\n `(e.g. BrandRightsPlatform.updateRights for \"update_rights\" as of 6.7.0). ` +\n `If you intended a new tool, rename it to avoid the framework name.`\n );\n }\n if (customName === 'get_adcp_capabilities') {\n throw new Error(\n `createAdcpServer: customTools[\"get_adcp_capabilities\"] is not allowed. ` +\n `The framework auto-generates this tool from registered handlers and capability config.`\n );\n }\n const custom = config.customTools[customName];\n if (!custom) continue;\n const { description, title, inputSchema, outputSchema, annotations, _meta, handler } = custom;\n // Wrap the adopter-supplied handler so `throw new AdcpError(...)` and\n // `throw adcpError(...)` from inside it project to the typed envelope —\n // matching the behavior framework-registered tools get from the catch\n // at line ~3494. Without the wrap, AdcpError throws escape to the MCP\n // SDK as generic JSON-RPC errors and the buyer loses the typed code.\n // The framework's own `tasks_get` is registered through this path.\n const rawHandler = handler as (...args: unknown[]) => Promise<McpToolResponse> | McpToolResponse;\n const wrappedHandler = (async (...args: unknown[]) => {\n try {\n return applyResponseEnhancer(await rawHandler(...args));\n } catch (err) {\n if (isThrownAdcpError(err)) return applyResponseEnhancer(err);\n if (err instanceof AdcpError) return applyResponseEnhancer(projectThrownAdcpError(err));\n throw err;\n }\n }) as Parameters<typeof server.registerTool>[2];\n server.registerTool(\n customName,\n {\n ...(description != null && { description }),\n ...(title != null && { title }),\n ...(inputSchema != null && { inputSchema }),\n ...(outputSchema != null && { outputSchema }),\n ...(annotations != null && { annotations }),\n ...(_meta != null && { _meta }),\n } as Parameters<typeof server.registerTool>[1],\n wrappedHandler\n );\n registeredToolNames.add(customName);\n }\n }\n\n // Tool coherence warnings\n checkCoherence(registeredToolNames, logger);\n\n // --- Idempotency configuration guardrails ---\n //\n // A seller that registers mutating handlers but doesn't supply an\n // `idempotency` store cannot honor the v3 retry contract: buyer\n // retries will double-book because there's no replay cache. The\n // framework permits this implicit omission only in development/test,\n // where idempotency may not be the unit under test. All other\n // environments fail startup. Operators who deliberately cannot provide\n // replay safety must use the explicit `idempotency: 'disabled'` mode and\n // its acknowledgement gate. The advertised capability remains\n // `supported: false`; only a wired store can declare replay safety.\n const registeredMutatingTools = [...registeredToolNames].filter(t => MUTATING_TASKS.has(t));\n if (registeredMutatingTools.length > 0 && !idempotency && !idempotencyDisabled) {\n const message =\n `createAdcpServer: ${registeredMutatingTools.length} mutating tools registered ` +\n `(${registeredMutatingTools.slice(0, 3).join(', ')}${\n registeredMutatingTools.length > 3 ? ', ...' : ''\n }) without an idempotency store. AdCP v3 requires sellers to support idempotent replay ` +\n `on mutating requests — buyer retries will double-book without it. ` +\n `Pass \\`idempotency: createIdempotencyStore({ backend, ttlSeconds })\\` or explicitly set ` +\n `\\`idempotency: 'disabled'\\` when the seller intentionally cannot provide replay safety.`;\n const env = process.env.NODE_ENV;\n if (env !== 'test' && env !== 'development') {\n throw new Error(message);\n }\n logger.error(message);\n }\n\n // MUTATING_TASKS is derived at module load by introspecting Zod\n // schemas. If Zod's internals change or the tool-request-schemas map\n // shifts, the derivation can silently return an empty set — which\n // would make every mutating request bypass idempotency enforcement.\n // Fail loud at server startup if the introspection produced\n // surprisingly few results.\n if (MUTATING_TASKS.size < 20) {\n throw new Error(\n `createAdcpServer: MUTATING_TASKS set has only ${MUTATING_TASKS.size} entries — expected at least 20. ` +\n `Schema introspection likely broke (Zod upgrade? tool-request-schemas change?). ` +\n `Check \\`src/lib/utils/idempotency.ts:deriveMutatingTasks\\`.`\n );\n }\n\n // --- Auto-register get_adcp_capabilities ---\n const protocols = detectProtocolsFromHandlers(config);\n\n // Idempotency capability declaration. Spec defines a discriminated\n // union (`get-adcp-capabilities-response.json` `adcp.idempotency.oneOf`):\n // - `IdempotencySupported` → `{ supported: true, replay_ttl_seconds: N }`\n // - `IdempotencyUnsupported` → `{ supported: false }` (replay_ttl_seconds MUST be absent)\n // Disabled mode flips to `IdempotencyUnsupported` so the wire contract\n // matches actual behavior — buyers reading capabilities can fall back to\n // natural-key dedup before retrying spend-committing operations. Lying\n // here (declaring `supported: true` while skipping replay) is a\n // money-flow footgun: a 504-retry under the same key double-books.\n const idempotencyCapability: GetAdCPCapabilitiesResponse['adcp']['idempotency'] =\n idempotencyDisabled || !idempotency\n ? { supported: false }\n : {\n supported: true,\n replay_ttl_seconds: idempotency.ttlSeconds,\n };\n\n const capabilitiesData: GetAdCPCapabilitiesResponse = {\n status: 'completed',\n adcp: {\n major_versions: capConfig?.major_versions ?? [3],\n ...(capConfig?.supported_versions?.length && { supported_versions: [...capConfig.supported_versions] }),\n idempotency: idempotencyCapability,\n ...(capConfig?.capability_changes && { capability_changes: structuredClone(capConfig.capability_changes) }),\n },\n supported_protocols: protocols as GetAdCPCapabilitiesResponse['supported_protocols'],\n };\n\n const hasExplicitMediaBuyFeatures = Object.keys(capConfig?.features ?? {}).length > 0;\n if (protocols.includes('media_buy') || hasExplicitMediaBuyFeatures) {\n capabilitiesData.media_buy = {\n features: {\n ...(capConfig?.features?.canonicalCreatives !== undefined && {\n canonical_creatives: capConfig.features.canonicalCreatives,\n }),\n inline_creative_management: capConfig?.features?.inlineCreativeManagement ?? false,\n property_list_filtering: capConfig?.features?.propertyListFiltering ?? false,\n content_standards: capConfig?.features?.contentStandards ?? false,\n conversion_tracking: capConfig?.features?.conversionTracking ?? false,\n audience_targeting: capConfig?.features?.audienceTargeting ?? false,\n },\n ...(capConfig?.portfolio && { portfolio: capConfig.portfolio }),\n };\n }\n\n if (capConfig?.account) {\n capabilitiesData.account = {\n require_operator_auth: capConfig.account.requireOperatorAuth ?? false,\n ...(capConfig.account.authorizationEndpoint && {\n authorization_endpoint: capConfig.account.authorizationEndpoint,\n }),\n supported_billing: capConfig.account.supportedBilling ?? [],\n ...(capConfig.account.defaultBilling && { default_billing: capConfig.account.defaultBilling }),\n required_for_products: capConfig.account.requiredForProducts ?? false,\n sandbox: capConfig.account.sandbox ?? false,\n };\n }\n\n if (capConfig?.creative) {\n capabilitiesData.creative = {\n supports_compliance: capConfig.creative.supportsCompliance ?? false,\n has_creative_library: capConfig.creative.hasCreativeLibrary ?? false,\n supports_generation: capConfig.creative.supportsGeneration ?? false,\n supports_transformation: capConfig.creative.supportsTransformation ?? false,\n };\n }\n\n if (capConfig?.extensions_supported !== undefined) {\n capabilitiesData.extensions_supported = [...capConfig.extensions_supported];\n }\n\n if (capConfig?.ext !== undefined) {\n capabilitiesData.ext = structuredClone(capConfig.ext);\n }\n\n if (capConfig?.request_signing) {\n capabilitiesData.request_signing = capConfig.request_signing;\n }\n\n if (capConfig?.specialisms?.length) {\n capabilitiesData.specialisms = capConfig.specialisms;\n }\n\n if (capConfig?.overrides) {\n applyCapabilityOverrides(capabilitiesData, capConfig.overrides);\n }\n\n if (webhooks) {\n const profile = webhooks.tag ?? 'adcp/webhook-signing/v1';\n if (profile !== 'adcp/webhook-signing/v1') {\n throw new Error(\n `createAdcpServer: webhooks.tag must be \"adcp/webhook-signing/v1\" so the emitted tag matches the advertised AdCP profile; got ${JSON.stringify(profile)}`\n );\n }\n const algorithm = webhooks.signerKey?.alg ?? webhooks.signerProvider?.algorithm;\n if (algorithm === undefined) {\n throw new Error('createAdcpServer: webhooks must provide a signing key or provider with an advertised algorithm');\n }\n capabilitiesData.webhook_signing = {\n ...capabilitiesData.webhook_signing,\n supported: true,\n profile,\n algorithms: [algorithm],\n legacy_hmac_fallback: capabilitiesData.webhook_signing?.legacy_hmac_fallback ?? false,\n delivery_retry_horizon_seconds: webhooks.deliveryRetryHorizonSeconds ?? 86_400,\n };\n }\n\n // Resolve signing once, after capability overrides, then use this exact\n // policy for both discovery and transport enforcement. Explicit verifier\n // config remains authoritative over a conflicting capability override;\n // otherwise the post-override advertised list controls enforcement.\n const enforcedRequestSigningPolicy = signedRequests\n ? resolveEffectiveSignedRequestPolicy(\n signedRequests,\n capabilitiesData.request_signing ?? capConfig?.request_signing,\n adcpVersion\n )\n : undefined;\n if (enforcedRequestSigningPolicy) capabilitiesData.request_signing = enforcedRequestSigningPolicy;\n\n if (proposalRefinementCapabilities) {\n const mediaBuy = (capabilitiesData.media_buy ??= {\n features: {\n inline_creative_management: false,\n property_list_filtering: false,\n content_standards: false,\n conversion_tracking: false,\n audience_targeting: false,\n },\n });\n mediaBuy.proposal_refinement = {\n ...proposalRefinementCapabilities,\n supported_dimensions: [...proposalRefinementCapabilities.supported_dimensions],\n };\n }\n\n const compactLifecycleTools = COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS.filter(tool => registeredToolNames.has(tool));\n if (compactLifecycleTools.length > 0) {\n const mediaBuy = (capabilitiesData.media_buy ??= {\n features: {\n inline_creative_management: false,\n property_list_filtering: false,\n content_standards: false,\n conversion_tracking: false,\n audience_targeting: false,\n },\n });\n mediaBuy.lifecycle_tools = compactLifecycleTools;\n }\n\n if (\n capabilitiesData.measurement !== undefined &&\n Array.isArray(capabilitiesData.experimental_features) &&\n capabilitiesData.experimental_features.includes('measurement.core') &&\n !capabilitiesData.supported_protocols.includes('measurement' as never)\n ) {\n capabilitiesData.supported_protocols = [\n ...capabilitiesData.supported_protocols,\n 'measurement',\n ] as GetAdCPCapabilitiesResponse['supported_protocols'];\n }\n\n // Stamp the SDK version so conformance tooling can surface version-staleness\n // hints when the agent's reported version predates recommended helpers.\n // Cast needed because GetAdCPCapabilitiesResponse is generated and lacks\n // this field; it remains a forward-compatible extension until the spec\n // formally defines library_version in a future AdCP minor.\n (capabilitiesData as unknown as Record<string, unknown>).library_version = `@adcp/client@${LIBRARY_VERSION}`;\n\n // Passthrough inputSchema — framework validation is authoritative on\n // both transports (#909). Same rationale as the domain-tool loop above.\n server.registerTool(\n 'get_adcp_capabilities',\n {\n inputSchema: frameworkInputSchemaFor('get_adcp_capabilities'),\n annotations: { readOnlyHint: true },\n _meta: frameworkToolMeta,\n },\n (async (params: any, extra: { authInfo?: ResolvedAuthInfo } = {}) => {\n const requestParams = isPlainObject(params) ? params : {};\n const releaseSelection = selectServedAdcpRelease(requestParams, capConfig, adcpVersion);\n const release = isMcpToolResponse(releaseSelection)\n ? {\n validationVersion: adcpVersion,\n ...(servedAdcpVersion !== undefined && { wireVersion: servedAdcpVersion }),\n }\n : releaseSelection;\n const finalizeCapabilityResponse = (response: McpToolResponse): McpToolResponse => {\n sanitizeAdcpErrorEnvelope(response);\n injectContextIntoResponse(response, requestParams.context);\n injectVersionIntoResponse(response, release.wireVersion);\n return applyResponseEnhancer(response);\n };\n\n if (isMcpToolResponse(releaseSelection)) {\n return finalizeCapabilityResponse(releaseSelection);\n }\n if (!releaseDefinesTool('get_adcp_capabilities', release)) {\n return finalizeCapabilityResponse(\n adcpError('VERSION_UNSUPPORTED', {\n message: `get_adcp_capabilities is not defined in the selected AdCP release ${release.validationVersion}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n\n if (requestValidationMode !== 'off') {\n const requestOutcome = validateRequest('get_adcp_capabilities', requestParams, release.validationVersion);\n if (!requestOutcome.valid) {\n logger.warn(\n `Schema validation warning (request) for get_adcp_capabilities: ${formatIssues(requestOutcome.issues, 3, { rootSchemaId: requestOutcome.schemaId })}`,\n {\n tool: 'get_adcp_capabilities',\n issues: requestOutcome.issues,\n }\n );\n if (requestValidationMode === 'strict') {\n return finalizeCapabilityResponse(\n adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload('get_adcp_capabilities', 'request', requestOutcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: requestOutcome.schemaId,\n })\n )\n );\n }\n }\n }\n\n if (agentRegistry !== undefined && extra.authInfo !== undefined) {\n const authInfo = extra.authInfo;\n const inboundCredential = authInfo.extra?.credential;\n const credential = authInfo.credential ?? (inboundCredential as ResolvedAuthInfo['credential'] | undefined);\n try {\n const resolved = await agentRegistry.resolve({\n ...(credential !== undefined && { credential }),\n ...(authInfo.extra !== undefined && { extra: authInfo.extra }),\n input: params,\n });\n if (resolved?.status === 'suspended' || resolved?.status === 'blocked') {\n return finalizeCapabilityResponse(\n adcpError(resolved.status === 'suspended' ? 'AGENT_SUSPENDED' : 'AGENT_BLOCKED', {\n message:\n resolved.status === 'suspended'\n ? 'Buyer agent is suspended. Contact the seller to restore access.'\n : 'Buyer agent is blocked.',\n recovery: 'terminal',\n })\n );\n }\n } catch (err) {\n logger.warn('Buyer-agent registry resolution failed for get_adcp_capabilities', {\n error: err instanceof Error ? redactCredentialPatterns(err.message) : redactCredentialPatterns(String(err)),\n });\n return finalizeCapabilityResponse(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Buyer-agent registry is unavailable',\n recovery: 'transient',\n })\n );\n }\n }\n let data = structuredClone(capabilitiesData) as GetAdCPCapabilitiesResponse;\n const selected = parseAdcpRelease(release.validationVersion);\n if (\n selected !== undefined &&\n (selected.major > 3 || (selected.major === 3 && selected.minor >= 2)) &&\n data.request_signing?.supported === true\n ) {\n // 3.2's advertised contract is strict even when the internal verifier\n // temporarily accepts the legacy serialization during a rolling deploy.\n data.request_signing = { ...data.request_signing, covers_content_digest: 'required' };\n }\n if (selected?.major === 3 && selected.minor === 0) {\n data = projectCapabilitiesToVersion(data, release.validationVersion);\n }\n if (selected !== undefined && (selected.major < 3 || (selected.major === 3 && selected.minor === 1))) {\n if (data.webhook_signing) {\n delete (\n data.webhook_signing as NonNullable<GetAdCPCapabilitiesResponse['webhook_signing']> & {\n delivery_retry_horizon_seconds?: number;\n }\n ).delivery_retry_horizon_seconds;\n }\n delete (data.adcp as GetAdCPCapabilitiesResponse['adcp'] & { capability_changes?: unknown }).capability_changes;\n const forwardMediaBuy = data.media_buy as\n | (NonNullable<typeof data.media_buy> & {\n lifecycle_tools?: string[];\n proposal_refinement?: ProposalRefinementCapabilities;\n })\n | undefined;\n if (forwardMediaBuy) {\n delete forwardMediaBuy.proposal_refinement;\n if (forwardMediaBuy.lifecycle_tools) {\n forwardMediaBuy.lifecycle_tools = forwardMediaBuy.lifecycle_tools.filter(\n tool =>\n !COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS.includes(tool as (typeof COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS)[number])\n );\n if (forwardMediaBuy.lifecycle_tools.length === 0) delete forwardMediaBuy.lifecycle_tools;\n }\n }\n }\n if (selected !== undefined && selected.major < 3) {\n delete (data.adcp as GetAdCPCapabilitiesResponse['adcp'] & { supported_versions?: string[] })\n .supported_versions;\n if (data.media_buy?.features !== undefined) {\n delete (data.media_buy.features as { canonical_creatives?: boolean }).canonical_creatives;\n }\n delete (data as unknown as Record<string, unknown>).library_version;\n }\n const ctx = requestParams.context;\n if (ctx !== null && typeof ctx === 'object' && !Array.isArray(ctx)) {\n (data as any).context = ctx;\n }\n const response = capabilitiesResponse(data);\n injectVersionIntoResponse(response, release.wireVersion);\n // A capabilities-only server (no domain tools registered yet) has no\n // protocol name it can truthfully place in supported_protocols. Keep\n // discovery callable without inventing one; once a protocol is\n // registered, the selected release schema is authoritative.\n if (responseValidationMode !== 'off' && data.supported_protocols.length > 0) {\n const validationPayload = structuredClone(response.structuredContent);\n if (proposalRefinementCapabilities && isPlainObject(validationPayload?.media_buy)) {\n delete validationPayload.media_buy.proposal_refinement;\n delete validationPayload.media_buy.lifecycle_tools;\n }\n const responseOutcome = validateResponse('get_adcp_capabilities', validationPayload, release.validationVersion);\n if (!responseOutcome.valid) {\n logger.warn(\n `Schema validation warning (response) for get_adcp_capabilities: ${formatIssues(responseOutcome.issues, 3, { rootSchemaId: responseOutcome.schemaId })}`,\n {\n tool: 'get_adcp_capabilities',\n issues: responseOutcome.issues,\n variant: responseOutcome.variant,\n }\n );\n if (responseValidationMode === 'strict') {\n return finalizeCapabilityResponse(\n adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload('get_adcp_capabilities', 'response', responseOutcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: responseOutcome.schemaId,\n })\n )\n );\n }\n }\n }\n return applyResponseEnhancer(response);\n }) as Parameters<typeof server.registerTool>[2]\n );\n registeredToolNames.add('get_adcp_capabilities');\n\n const configuredRelease = parseAdcpRelease(protocolBundleKey);\n const serves32OrNewer =\n configuredRelease !== undefined &&\n (configuredRelease.major > 3 || (configuredRelease.major === 3 && configuredRelease.minor >= 2));\n if (mcpToolProfile === 'media-buy' && !serves32OrNewer) {\n throw new Error('createAdcpServer: mcpToolProfile=\"media-buy\" requires adcpVersion 3.2 or newer');\n }\n const activeMcpToolProfile: Exclude<AdcpMcpToolProfile, 'auto'> =\n mcpToolProfile === 'media-buy' || (mcpToolProfile === 'auto' && serves32OrNewer && compactLifecycleTools.length > 0)\n ? 'media-buy'\n : 'all';\n const mediaBuyProfileTools = new Set<string>(MEDIA_BUY_MCP_TOOL_PROFILE);\n const wrappedToolsList = wrapSdkRequestHandler(server, 'tools/list', async (original, request, extra) => {\n const response = await original(request, extra);\n if (response == null || typeof response !== 'object') return response;\n const tools = (response as { tools?: unknown }).tools;\n if (!Array.isArray(tools)) return response;\n\n const visibleTools = tools.filter(tool => {\n const toolName = (tool as { name?: unknown } | null)?.name;\n if (typeof toolName !== 'string') return true;\n // Compact lifecycle names do not exist before 3.2. Keep a mistakenly\n // supplied forward handler callable only after the configured server\n // pin advances; never advertise it from a 3.0/3.1 endpoint.\n if (!serves32OrNewer && COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS.includes(toolName as never)) return false;\n return activeMcpToolProfile === 'all' || mediaBuyProfileTools.has(toolName);\n });\n const projectedTools = visibleTools.map(tool => {\n if (activeMcpToolProfile !== 'media-buy') return tool;\n const toolName = (tool as { name?: unknown } | null)?.name;\n if (typeof toolName !== 'string') return tool;\n const inputSchema = getMcpProfileInputSchema(toolName, 'media-buy', adcpVersion);\n return inputSchema ? { ...(tool as Record<string, unknown>), inputSchema } : tool;\n });\n\n return {\n ...(response as Record<string, unknown>),\n tools: projectedTools,\n _meta: {\n ...((response as { _meta?: Record<string, unknown> })._meta ?? {}),\n adcp_version: adcpVersion,\n adcp_profile: activeMcpToolProfile,\n },\n };\n });\n if (!wrappedToolsList) {\n throw new Error(\n 'createAdcpServer: failed to install MCP tools/list profile filtering; the MCP SDK request-handler internals may have changed'\n );\n }\n\n // Validate `credentialPolicy.tools` keys against the FULL registered\n // tool set, including `get_adcp_capabilities` (registered just above).\n // Earlier placement (before this tool was added) made\n // `tools: { get_adcp_capabilities: 'lax' }` spuriously throw — low\n // real-world impact (the tool never carries credentials) but the\n // typo-check claim \"the registered tool set is authoritative\" was\n // false for that one tool. Catches typos at construction so an\n // adopter's `tools: { activte_signal: 'lax' }` (missing 'a') doesn't\n // silently no-op the per-tool override and start fail-closing\n // legitimate buyer-creds traffic in production. Also re-validates\n // the `patterns.matcher`/`patterns.extend` mutual-exclusion at\n // construction so the diagnostic doesn't wait for first traffic.\n validateCredentialPolicy(credentialPolicy, registeredToolNames);\n\n const compliance = {\n async reset({\n force = false,\n allowProduction = false,\n }: { force?: boolean; allowProduction?: boolean } = {}): Promise<void> {\n // Check NODE_ENV BEFORE store-shape probes: the environment guard\n // is the strongest signal that \"this is not a test harness.\" An\n // operator who reached this call in production by mistake hits the\n // env gate regardless of which backend they wired.\n if (!allowProduction && process.env.NODE_ENV === 'production') {\n throw new Error(\n 'AdcpServer.compliance.reset: refused to run with NODE_ENV=production. ' +\n 'Pass `{ allowProduction: true }` if you deliberately set NODE_ENV=production in a test environment, ' +\n 'or unset NODE_ENV before running storyboards.'\n );\n }\n // Positive allowlist for stores, not method-presence. A\n // PostgresStateStore might expose `.clear()` for its own test\n // utility needs — we don't want method-existence alone to permit\n // a flush that would take out a shared test cluster. `force: true`\n // is the documented opt-in for non-memory backends.\n const stateStoreIsMemory = stateStore instanceof InMemoryStateStore;\n const idempotencyIsFlushable = !idempotency || hasIdempotencyClearAll(idempotency);\n if (!force) {\n if (!stateStoreIsMemory) {\n throw new Error(\n 'AdcpServer.compliance.reset: configured stateStore is not InMemoryStateStore. ' +\n 'Pass `{ force: true }` to acknowledge that flushing the configured backend is safe for this environment ' +\n '(e.g., a disposable test Postgres).'\n );\n }\n if (!idempotencyIsFlushable) {\n throw new Error(\n 'AdcpServer.compliance.reset: configured idempotency backend does not expose `clearAll()`. ' +\n 'Use `memoryBackend()` for test harnesses, or pass `{ force: true }` to skip idempotency flush.'\n );\n }\n }\n // `force` bypasses the allowlist checks but never the flush\n // itself — if we reached here, the caller wants the flush to\n // happen. `clear()` is only called when the store exposes it;\n // a store without `clear()` reaching here under `force: true`\n // is a no-op for the state side, which matches the shape the\n // caller opted into.\n const storeWithClear = stateStore as unknown as { clear?: () => void };\n if (typeof storeWithClear.clear === 'function') storeWithClear.clear();\n if (idempotency && idempotency.clearAll) await idempotency.clearAll();\n if (taskRegistry?.clear) await taskRegistry.clear();\n },\n };\n const wrapped: AdcpServerInternal = wrapMcpServer(server, compliance, adcpVersion);\n setMcpToolProfile(wrapped, activeMcpToolProfile);\n setMcpAppResources(wrapped, mcpAppResources);\n\n // Attach the auto-wired preTransport so `serve()` mounts the verifier\n // on the HTTP transport. Stashed under a non-enumerable symbol property\n // on the wrapper — it's a private contract between this function and\n // `serve()` for wiring, not part of the AdcpServer public API.\n if (signedRequests) {\n const preTransport = buildSignedRequestsPreTransport(signedRequests, enforcedRequestSigningPolicy!, adcpVersion);\n Object.defineProperty(wrapped, ADCP_PRE_TRANSPORT, {\n value: preTransport,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n }\n\n const signedRequestsState: AdcpSignedRequestsState = {\n autoWired: Boolean(signedRequests),\n specialismClaimed: claimsSignedRequests,\n capabilitySupported: capConfig?.request_signing?.supported === true,\n mismatch: claimsSignedRequests && !signedRequests ? 'claim_without_config' : 'ok',\n };\n Object.defineProperty(wrapped, ADCP_SIGNED_REQUESTS_STATE, {\n value: signedRequestsState,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(wrapped, ADCP_STATE_STORE, {\n value: stateStore,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(wrapped, ADCP_TASK_MESSAGE_QUEUE, {\n value: Boolean(taskMessageQueue),\n enumerable: false,\n configurable: true,\n writable: false,\n });\n // Mark when `instructions` was supplied as a function, so `serve()` can\n // refuse `reuseAgent: true` — the function is captured once at construction\n // and would not re-evaluate per session under server reuse.\n if (instructionsIsFn) {\n Object.defineProperty(wrapped, ADCP_INSTRUCTIONS_FN, {\n value: true,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n if (resolveInstructionsForTransport) {\n Object.defineProperty(wrapped, ADCP_INSTRUCTIONS_RESOLVER, {\n value: resolveInstructionsForTransport,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n }\n }\n // Expose the capabilitiesData object so post-registration helpers\n // (registerTestController) can add spec-defined capability blocks\n // — comply_test_controller is registered AFTER createAdcpServer,\n // so the compliance_testing block can't be emitted eagerly.\n Object.defineProperty(wrapped, ADCP_CAPABILITIES, {\n value: capabilitiesData,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n\n logger.info('AdCP server created', {\n tools: [...registeredToolNames],\n protocols,\n signedRequests: signedRequestsState,\n });\n\n return wrapped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+CA,iBAAkB;AAElB,qBAKO;AACP,iCAIO;AACP,2BAA0F;AAC1F,qBAAkC;AAClC,mBAA+B;AAC/B,uBAA+C;AAC/C,6BAA8D;AAK9D,yBAWO;AACP,qBAKO;AACP,mBAAoF;AAEpF,oBAAgF;AAIhF,+B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AgB;AAAA,IAC/B,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,EACZ,CAAC;AAID,MAAI,kBAAkB;AACpB,WAAO,eAAe,SAAS,sBAAsB;AAAA,MACnD,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,UAAU;AAAA,IACZ,CAAC;AACD,QAAI,iCAAiC;AACnC,aAAO,eAAe,SAAS,4BAA4B;AAAA,QACzD,OAAO;AAAA,QACP,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,UAAU;AAAA,MACZ,CAAC;AAAA,IACH;AAAA,EACF;AAKA,SAAO,eAAe,SAAS,sCAAmB;AAAA,IAChD,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,EACZ,CAAC;AAED,SAAO,KAAK,uBAAuB;AAAA,IACjC,OAAO,CAAC,GAAG,mBAAmB;AAAA,IAC9B;AAAA,IACA,gBAAgB;AAAA,EAClB,CAAC;AAED,SAAO;AACT;","names":["import_idempotency","import_version","import_schemas","extra","isSandboxRequestForSeeding","reason","response"]}
1
+ {"version":3,"sources":["../../../src/lib/server/create-adcp-server.ts"],"sourcesContent":["/**\n * Declarative AdCP server builder.\n *\n * `createAdcpServer` wires domain-grouped handler functions to Zod input\n * schemas, response builders, and account resolution.\n * Handlers only run when preconditions pass. `get_adcp_capabilities` is\n * auto-generated from the tools you register.\n *\n * For governance on financial tools (create_media_buy, update_media_buy,\n * activate_signal), use the composable `checkGovernance()` helper inside\n * your handler — see `governance.ts`.\n *\n * @example\n * ```typescript\n * import {\n * createAdcpServer,\n * createIdempotencyStore,\n * memoryBackend,\n * serve,\n * } from '@adcp/sdk/server/legacy/v5';\n *\n * // Single-process example. Use pgBackend(pool) or redisBackend(client) for\n * // durable, replica-safe production replay.\n * const idempotency = createIdempotencyStore({ backend: memoryBackend(), ttlSeconds: 86400 });\n *\n * serve(() => createAdcpServer({\n * name: 'My Publisher',\n * version: '1.0.0',\n * idempotency,\n *\n * // Second argument carries `toolName` and (when `authenticate` is wired\n * // on `serve()`) the caller's `authInfo`. Adapters that front an\n * // upstream platform API can use the caller's token here to resolve\n * // the platform account in one pass.\n * resolveAccount: async (ref, { authInfo }) => db.findAccount(ref, authInfo),\n *\n * mediaBuy: {\n * getProducts: async (params, ctx) => ({ products: catalog.search(params) }),\n * createMediaBuy: async (params, ctx) => ({\n * media_buy_id: `mb_${Date.now()}`,\n * packages: [],\n * }),\n * },\n * }));\n * ```\n */\n\nimport { z } from 'zod';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport {\n COMPATIBLE_ADCP_VERSIONS,\n parseAdcpMajorVersion,\n toReleasePrecisionVersion,\n type AdcpVersion,\n} from '../version';\nimport {\n isAdcpVersionAtLeast,\n isMovingAdcpPrereleaseFamilyAlias,\n resolveAdcpVersion,\n} from '../utils/adcp-version-config';\nimport { getValidator, hasSchemaBundle, resolveBundleKey, getMcpProfileInputSchema } from '../validation/schema-loader';\nimport { TOOL_INPUT_SHAPES } from '../schemas';\nimport { TaskTypeValues } from '../types/enums.generated';\nimport { bundleSupportsAdcpVersionField } from '../protocols';\nimport { getToolsWithErrorArm, type ErrorArmDescriptor } from './error-arm-tools';\nimport type { ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ZodRawShapeCompat, AnySchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';\nimport type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';\nimport type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';\nimport {\n ADCP_CAPABILITIES,\n ADCP_STATE_STORE,\n wrapMcpServer,\n setSdkServerInstructions,\n setMcpAppResources,\n setMcpToolProfile,\n wrapInitializeHandler,\n wrapSdkRequestHandler,\n type AdcpServer,\n type AdcpServerInternal,\n} from './adcp-server';\nimport {\n mcpAppResourceMetadata,\n normalizeMcpAppResources,\n readMcpAppResource,\n type AdcpMcpResourceDefinition,\n} from './mcp-app';\nimport { ADCP_TASK_MESSAGE_QUEUE, createTaskCapableServer, InMemoryTaskStore } from './tasks';\nimport type { TaskStore, TaskMessageQueue } from './tasks';\nimport { adcpError, applyAdcpErrorAllowlist, sanitizeStructuredAdcpError } from './errors';\nimport type { BuyerAgent, BuyerAgentRegistry } from './decisioning/buyer-agent';\nimport type { ResolvedAuthInfo } from './decisioning/account';\nimport type { TaskRecord, TaskRegistry } from './decisioning/runtime/task-registry';\nimport { protocolForTool } from './decisioning/runtime/protocol-for-tool';\nimport { AdcpError } from './decisioning/async-outcome';\nimport { redactCredentialPatterns } from './redact';\nimport {\n scanArgsForCredentials,\n resolveCredentialPolicyForTool,\n validateCredentialPolicy,\n type CredentialPolicy,\n} from './credential-policy';\nimport { ADCP_ERROR_FIELD_ALLOWLIST } from './envelope-allowlist';\nimport { InMemoryStateStore } from './state-store';\nimport type { AdcpStateStore } from './state-store';\nimport { AuthError, getServeRequestContext, type AuthPrincipal } from './auth';\nimport { principalForVerifiedSigner } from './auth-signature';\nimport {\n capabilitiesResponse,\n productsResponse,\n mediaBuyResponse,\n deliveryResponse,\n listAccountsResponse,\n listCreativeFormatsResponse,\n updateMediaBuyResponse,\n getMediaBuysResponse,\n performanceFeedbackResponse,\n buildCreativeResponse,\n buildCreativeMultiResponse,\n creativeDeliveryResponse,\n listCreativesResponse,\n syncCreativesResponse,\n getSignalsResponse,\n activateSignalResponse,\n acquireRightsResponse,\n updateRightsResponse,\n syncAccountsResponse,\n syncGovernanceResponse,\n reportUsageResponse,\n toStructuredContent,\n _getExplicitResponseSummary,\n type McpToolResponse,\n} from './responses';\n\nimport { TOOL_REQUEST_SCHEMAS } from '../utils/tool-request-schemas';\nimport { defineProposalRefinementCapabilities } from '../negotiation/seller';\nimport {\n ProposalRefinementValidationError,\n refinementDimensions,\n validateRefineProposalsRequest,\n} from '../negotiation/buyer';\nimport { validateRefineProposalsResponseShape } from '../negotiation/verification';\nimport type {\n ProposalRefinementCapabilities,\n RefineProposalsRequest,\n RefineProposalsResponse,\n} from '../negotiation/types';\nimport type { ProposalRefinementScope } from '../negotiation/seller';\n\n// NOTE on `outputSchema`: the MCP SDK's client-side `callTool` validates\n// `result.structuredContent` against the registered `outputSchema`\n// whenever structuredContent is present — regardless of `isError`. See\n// `node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js` line\n// 504. AdCP's `adcpError()` envelope carries\n// `structuredContent: { adcp_error: {...} }` with `isError: true`, which\n// would fail every client-side outputSchema check (the error shape\n// doesn't match the success schema). Until the SDK gates that client\n// check on `!isError` too, we do not declare `outputSchema` on\n// framework-registered tools — response drift is caught by the\n// dispatcher's AJV validator (#727) instead, and custom tools opt in\n// explicitly via `customTools[*].outputSchema`.\n\nfunction hasIdempotencyClearAll(store: IdempotencyStore): boolean {\n // `clearAll` is optional on `IdempotencyStore` — only present when the\n // configured backend opts in (memory backend does; pg backend does not).\n return typeof store.clearAll === 'function';\n}\n\n// Built-in request claims use the full replay window as their base fence.\n// Renew periodically while a handler is active so genuinely long-running\n// work retains that full window from its latest liveness point; the base\n// fence itself still prevents a transient renewal outage from reopening the\n// mutation.\nconst IDEMPOTENCY_CLAIM_RENEW_INTERVAL_MS = 60_000;\nimport { isMutatingTask, requestUsesIdempotency, IDEMPOTENCY_KEY_PATTERN, MUTATING_TASKS } from '../utils/idempotency';\nimport { STATUS_FREE_SYNC_RESPONSE_TOOLS } from '../utils/envelope-status-compat';\nimport { validateRequest, validateResponse, formatIssues, type ValidationIssue } from '../validation/schema-validator';\nimport { buildAdcpValidationErrorPayload } from '../validation/schema-errors';\nimport { hashPayload, IdempotencyClaimOwnershipError, type IdempotencyStore } from './idempotency';\nimport {\n createWebhookEmitter,\n type WebhookEmitParams,\n type WebhookEmitResult,\n type WebhookEmitterOptions,\n} from './webhook-emitter';\nimport { createExpressVerifier, type ExpressLike } from '../signing/middleware';\nimport { isSandboxOrMockAccount } from './account-mode';\nimport {\n isSandboxRequest as isSandboxRequestForSeeding,\n mergeSeededProductsIntoResponse,\n mergeSeededCreativesIntoResponse,\n mergeSeededMediaBuysIntoResponse,\n mergeSeededMediaBuyDeliveryIntoResponse,\n mergeSeededAccountsIntoResponse,\n mergeSeededCreativeFormatsIntoResponse,\n mergeSeededPropertyListsIntoResponse,\n mergeSeededCollectionListsIntoResponse,\n mergeSeededContentStandardsIntoResponse,\n mergeSeededSignalsIntoResponse,\n mergeSeededCreativeDeliveryIntoResponse,\n mergeSeededCreativeFeaturesIntoResponse,\n mergeSeededRightsIntoResponse,\n replaceAccountFinancialsIfSeeded,\n replacePropertyListIfSeeded,\n replaceCollectionListIfSeeded,\n replaceContentStandardsIfSeeded,\n replaceBrandIdentityIfSeeded,\n replaceSiOfferingIfSeeded,\n filterValidSeededProducts,\n filterValidSeededCreatives,\n filterValidSeededMediaBuys,\n filterValidSeededMediaBuyDeliveries,\n filterValidSeededAccounts,\n filterValidSeededAccountFinancials,\n filterValidSeededCreativeFormats,\n filterValidSeededPropertyLists,\n filterValidSeededCollectionLists,\n filterValidSeededContentStandards,\n filterValidSeededSignals,\n filterValidSeededCreativeDelivery,\n filterValidSeededCreativeFeatures,\n filterValidSeededBrandIdentity,\n filterValidSeededRights,\n filterValidSeededSiOffering,\n type TestControllerBridge,\n type TestControllerBridgeContext,\n} from './test-controller-bridge';\nimport type { JwksResolver } from '../signing/jwks';\nimport type { ReplayStore } from '../signing/replay';\nimport type { RevocationStore } from '../signing/revocation';\nimport type { ContentDigestPolicy } from '../signing/types';\nimport { ADCP_VERSION, LIBRARY_VERSION } from '../version';\n\n// Type-only imports for AdcpToolMap handler signatures (z.input<typeof ...>)\nimport type {\n GetProductsRequestSchema,\n ListProductsRequestSchema,\n RequestProposalsRequestSchema,\n DeclineProposalsRequestSchema,\n BuyProductsRequestSchema,\n AcceptProposalRequestSchema,\n ControlMediaBuyRequestSchema,\n CreateMediaBuyRequestSchema,\n UpdateMediaBuyRequestSchema,\n GetMediaBuysRequestSchema,\n GetMediaBuyDeliveryRequestSchema,\n ProvidePerformanceFeedbackRequestSchema,\n GetTaskStatusRequestSchema,\n ListTasksRequestSchema,\n SyncAgentNotificationConfigsRequestSchema,\n ListCreativeFormatsRequestSchema,\n ListTransformersRequestSchema,\n BuildCreativeRequestSchema,\n GetCreativeDeliveryRequestSchema,\n ListCreativesRequestSchema,\n SyncCreativesRequestSchema,\n GetSignalsRequestSchema,\n ActivateSignalRequestSchema,\n ListAccountsRequestSchema,\n SyncAccountsRequestSchema,\n SyncGovernanceRequestSchema,\n GetAccountFinancialsRequestSchema,\n ReportUsageRequestSchema,\n SyncEventSourcesRequestSchema,\n LogEventRequestSchema,\n SyncAudiencesRequestSchema,\n SyncCatalogsRequestSchema,\n CreatePropertyListRequestSchema,\n UpdatePropertyListRequestSchema,\n GetPropertyListRequestSchema,\n ListPropertyListsRequestSchema,\n DeletePropertyListRequestSchema,\n CreateCollectionListRequestSchema,\n UpdateCollectionListRequestSchema,\n GetCollectionListRequestSchema,\n ListCollectionListsRequestSchema,\n DeleteCollectionListRequestSchema,\n ListContentStandardsRequestSchema,\n GetContentStandardsRequestSchema,\n CreateContentStandardsRequestSchema,\n UpdateContentStandardsRequestSchema,\n CalibrateContentRequestSchema,\n ValidateContentDeliveryRequestSchema,\n GetMediaBuyArtifactsRequestSchema,\n GetCreativeFeaturesRequestSchema,\n SyncPlansRequestSchema,\n CheckGovernanceRequestSchema,\n ReportPlanOutcomeRequestSchema,\n ReportPlanAdjustmentRequestSchema,\n GetPlanAuditLogsRequestSchema,\n SIGetOfferingRequestSchema,\n SIInitiateSessionRequestSchema,\n SISendMessageRequestSchema,\n SITerminateSessionRequestSchema,\n PreviewCreativeRequestSchema,\n GetBrandIdentityRequestSchema,\n GetRightsRequestSchema,\n AcquireRightsRequestSchema,\n UpdateRightsRequestSchema,\n} from '../types/schemas.generated';\nimport { AccountReferenceSchema } from '../types/schemas.generated';\n\nimport type {\n AcquireRightsAcquired,\n AcquireRightsPendingApproval,\n AcquireRightsRejected,\n UpdateRightsResponse,\n UpdateRightsSuccess,\n GetBrandIdentitySuccess,\n GetRightsSuccess,\n} from '../types/core.generated';\nimport type {\n GetProductsResponse,\n ListProductsResponse,\n RequestProposalsResponse,\n DeclineProposalsResponse,\n BuyProductsResponse,\n AcceptProposalResponse,\n ControlMediaBuyResponse,\n CreateMediaBuyResponse,\n UpdateMediaBuySuccess,\n UpdateMediaBuyResponse,\n GetMediaBuysResponse,\n GetMediaBuyDeliveryResponse,\n GetTaskStatusResponse,\n ListTasksResponse,\n SyncAgentNotificationConfigsResponse,\n ListAccountsResponse,\n ListCreativeFormatsResponse,\n ListTransformersResponse,\n ProvidePerformanceFeedbackSuccess,\n ProvidePerformanceFeedbackResponse,\n BuildCreativeSuccess,\n BuildCreativeMultiSuccess,\n BuildCreativeVariantSuccess,\n BuildCreativeResponse,\n GetCreativeDeliveryResponse,\n ListCreativesResponse,\n SyncCreativesError,\n SyncCreativesSuccess,\n SyncCreativesResponse,\n GetSignalsResponse,\n ActivateSignalSuccess,\n ActivateSignalResponse,\n GetAdCPCapabilitiesResponse,\n CreatePropertyListResponse,\n UpdatePropertyListResponse,\n GetPropertyListResponse,\n ListPropertyListsResponse,\n DeletePropertyListResponse,\n CreateCollectionListResponse,\n UpdateCollectionListResponse,\n GetCollectionListResponse,\n ListCollectionListsResponse,\n DeleteCollectionListResponse,\n SyncPlansResponse,\n CheckGovernanceResponse,\n ReportPlanOutcomeResponse,\n ReportPlanAdjustmentResponse,\n GetPlanAuditLogsResponse,\n SIGetOfferingResponse,\n SIInitiateSessionResponse,\n SISendMessageResponse,\n SITerminateSessionResponse,\n SyncEventSourcesSuccess,\n SyncEventSourcesResponse,\n LogEventSuccess,\n LogEventResponse,\n SyncAudiencesSuccess,\n SyncAudiencesResponse,\n SyncCatalogsSuccess,\n SyncCatalogsResponse,\n SyncAccountsSuccess,\n SyncAccountsResponse,\n SyncGovernanceSuccess,\n SyncGovernanceResponse,\n GetAccountFinancialsSuccess,\n GetAccountFinancialsResponse,\n GetCreativeFeaturesResponse,\n ReportUsageResponse,\n PreviewCreativeResponse,\n AccountReference,\n BrandReference,\n ListContentStandardsResponse,\n GetContentStandardsResponse,\n CreateContentStandardsResponse,\n UpdateContentStandardsResponse,\n CalibrateContentResponse,\n ValidateContentDeliveryResponse,\n GetMediaBuyArtifactsResponse,\n ListTasksRequest,\n TaskStatus,\n TaskType,\n AdCPProtocol as WireAdcpProtocol,\n} from '../types/tools.generated';\n\nimport type { AdcpProtocol, MediaBuyFeatures, AccountCapabilities, CreativeCapabilities } from '../utils/capabilities';\nimport type { MediaChannel } from '../types/tools.generated';\nimport type { RequireCacheScopeWhenProducts, ServerPayload } from '../types/server-payload';\nimport type { CreateMediaBuyPayload as CreateMediaBuyServerPayload } from '../types/server-payload-aliases';\nimport {\n DEFAULT_UNKNOWN_ERROR_RECOVERY,\n STANDARD_ERROR_CODES,\n isStandardErrorCode,\n type ErrorRecovery,\n} from '../types/error-codes';\n\n// ---------------------------------------------------------------------------\n// Logger\n// ---------------------------------------------------------------------------\n\nexport interface AdcpLogger {\n debug(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n error(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Module-singleton default `InMemoryStateStore`. Adopters who use the\n * factory pattern `serve(() => createAdcpServer({...}))` get a fresh\n * `createAdcpServer` invocation per request — without this singleton, the\n * destructured default `stateStore = new InMemoryStateStore()` would mint\n * a brand-new in-memory store per request, silently dropping every\n * `ctx.store.put(...)` between calls. Empirically reproduced in matrix\n * v3: an LLM-built SI agent that put session state in `ctx.store` on\n * `si_initiate_session` failed to find it on the next request's\n * `si_send_message`.\n *\n * Sharing one default store across the process is what every other Node\n * framework's \"memory store\" already does, and it's what the skills\n * (creative, SI, etc.) explicitly promise: \"framework provides\n * InMemoryStateStore by default — no need for module-level Maps\".\n *\n * Multi-tenant adopters and production deployments pass their own store\n * (`PostgresStateStore`, etc.); the default is for development and\n * single-tenant agents only.\n *\n * Tests that need isolation pass an explicit `stateStore: new\n * InMemoryStateStore()`. The module-level default does not break\n * existing test isolation because tests have always opted-in to a fresh\n * store per case.\n */\nconst DEFAULT_STATE_STORE = new InMemoryStateStore();\n\nconst noopLogger: AdcpLogger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n\n// ---------------------------------------------------------------------------\n// Handler context\n// ---------------------------------------------------------------------------\n\n/** Trusted caller namespace for agent-level and governance mutations. */\nexport interface CallerMutationScope {\n tenant_id: string;\n principal_id: string;\n /** Optional account boundary when the mutation is account-owned. */\n account_id?: string;\n}\n\n/**\n * Context passed to every handler.\n *\n * If the tool has an account ref and `resolveAccount` is configured,\n * `account` is the resolved account object (guaranteed non-null —\n * the handler only runs if resolution succeeds).\n *\n * If `resolveSessionKey` is configured, `sessionKey` is the scoping key\n * derived from the request — usually tenant/brand/publisher-account id.\n * Handlers can pass it to `scopedStore(ctx.store, ctx.sessionKey!)` to get\n * a session-scoped view that works on any `AdcpStateStore` implementation.\n */\nexport interface HandlerContext<TAccount = unknown> {\n account?: TAccount;\n /** Transport cancellation signal for the current request. */\n signal?: AbortSignal;\n /**\n * AdCP release selected for this request after applying the buyer pin to\n * `capabilities.adcp.supported_versions`. This may be older than the\n * server's configured maximum release when the seller downshifts.\n */\n servedAdcpVersion?: string;\n /**\n * Resolved buyer agent for this request, populated by `BuyerAgentRegistry`\n * when an `agentRegistry` is configured on the server (Phase 1 of #1269).\n * Carries the durable commercial relationship — status, billing\n * capabilities, default account terms — distinct from the per-request\n * credential. Undefined when no registry is configured OR when the\n * registry returned `null` for the request's credential.\n */\n agent?: BuyerAgent;\n /** Session scoping key derived from the request. Populated when `resolveSessionKey` is configured. */\n sessionKey?: string;\n /** State store for persisting domain objects (media buys, accounts, creatives). */\n store: AdcpStateStore;\n /**\n * Authentication info for the caller, when `ServeOptions.authenticate` is\n * configured. Populated from the MCP SDK's `extra.authInfo`, which\n * `serve()` sets from the auth principal. Use this to enforce\n * per-principal authorization in handlers.\n *\n * Stage 3 of #1269 added the kind-discriminated `credential` and the\n * `operator` fields. The legacy `token` / `clientId` / `scopes` are\n * preserved as optional fields through the deprecation cycle; new code\n * should read `credential` and switch on its `kind`.\n *\n * Buyer-agent identity post-resolution is on `ctx.agent` (the resolved\n * `BuyerAgent` record), NOT here — this surface only carries\n * authentication information about the credential, not the registry\n * lookup result.\n */\n authInfo?: ResolvedAuthInfo;\n /** Trusted proposal namespace resolved by `proposalNegotiation.resolveScope`. */\n proposalRefinementScope?: Readonly<ProposalRefinementScope>;\n /** Trusted namespace for caller-scoped 3.2 mutations. Persist records under this tuple. */\n callerMutationScope?: Readonly<CallerMutationScope>;\n /**\n * Emit a signed webhook to a buyer's `push_notification_config.url`.\n * Populated when `AdcpServerConfig.webhooks` is configured. Handles\n * RFC 9421 signing, stable `idempotency_key` across retries, and\n * retry/backoff per adcp#2417 + adcp#2423 + adcp#2478.\n *\n * Typical call from inside a completion handler:\n *\n * await ctx.emitWebhook({\n * url: push_notification_config.url,\n * payload: { operation_id, task_id, task_type: 'create_media_buy', status: 'completed', timestamp, result },\n * delivery_id: `create_media_buy.${media_buy_id}.completed`,\n * });\n */\n emitWebhook?: (params: WebhookEmitParams) => Promise<WebhookEmitResult>;\n}\n\n/** Request metadata passed to `resolveSessionKey` so the hook can derive a key from any field. */\nexport interface SessionKeyContext<TAccount = unknown> {\n toolName: AdcpServerToolName;\n params: Record<string, unknown>;\n account?: TAccount;\n /** Resolved buyer agent (Phase 1 of #1269), when `agentRegistry` is configured. */\n agent?: BuyerAgent;\n}\n\n/**\n * Request context passed to `resolveAccount` so the resolver can inspect the\n * authenticated principal at resolution time. This matters for adapters that\n * front an upstream platform API (Snap, Meta, TikTok, retail media networks)\n * where the upstream account lookup requires the caller's platform OAuth\n * token — forwarding `authInfo` into `resolveAccount` lets the resolver put\n * platform identifiers (ad_account_id, upstream token state) directly on the\n * resolved `TAccount` rather than re-resolving inside every handler.\n */\nexport interface ResolveAccountContext {\n /** The AdCP tool being called. */\n toolName: AdcpServerToolName;\n /**\n * Authentication info for the caller, populated from `extra.authInfo` on the\n * MCP request. Undefined when no `authenticate` is configured on `serve()`.\n */\n authInfo?: HandlerContext['authInfo'];\n /**\n * Resolved buyer agent (Phase 1 of #1269), when an `agentRegistry` is\n * configured on the server. Adopters whose `accounts.resolve` shape varies\n * with the buyer agent's commercial relationship (e.g., agency-mediated\n * vs. direct billing) read it here without re-resolving from `authInfo`.\n * Undefined when no registry is configured OR when the registry returned\n * null for the request's credential.\n */\n agent?: BuyerAgent;\n /**\n * Original tool arguments. Account resolvers that need request-scope\n * metadata for test overlays or dry-run/delete-missing behavior should read\n * it here rather than re-parsing transport envelopes.\n */\n input?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Narrow `ctx.sessionKey` from `string | undefined` to `string`. Use this in\n * handlers that require session scoping so you don't litter `!` assertions:\n *\n * ```ts\n * const sessionKey = requireSessionKey(ctx);\n * const sessionStore = scopedStore(ctx.store, sessionKey);\n * ```\n *\n * Throws a `SERVICE_UNAVAILABLE`-style error if `sessionKey` is missing — typically\n * meaning `resolveSessionKey` isn't configured or returned `undefined` for this tool.\n */\nexport function requireSessionKey<TAccount = unknown>(ctx: HandlerContext<TAccount>): string {\n if (ctx.sessionKey == null) {\n throw new Error(\n 'ctx.sessionKey is undefined. Configure resolveSessionKey on createAdcpServer, or guard per-tool before calling requireSessionKey.'\n );\n }\n return ctx.sessionKey;\n}\n\n// ---------------------------------------------------------------------------\n// Tool → type mapping (kept from v1 for type-level handler signatures)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-tool param / result / response types.\n *\n * `result` is the server-handler payload — normally the narrow success arm\n * consumed by the framework's response builders (`mediaBuyResponse`,\n * `syncCreativesResponse`, ...), plus a structured Error arm when the tool\n * supports returning one directly.\n * `response` is the full AdCP response union (Success | Error | Submitted).\n * Handlers can return either shape: adapter patterns that produce\n * `Result<FooResponse, ...>` now type-check without `as any`, and the\n * dispatcher narrows Error / Submitted arms at runtime so the response\n * builder only fires on the Success arm.\n */\nexport interface AdcpToolMap {\n list_products: {\n params: z.input<typeof ListProductsRequestSchema>;\n result: ServerPayload<ListProductsResponse>;\n response: ListProductsResponse;\n };\n request_proposals: {\n params: z.input<typeof RequestProposalsRequestSchema>;\n result: ServerPayload<RequestProposalsResponse>;\n response: RequestProposalsResponse;\n };\n refine_proposals: {\n params: RefineProposalsRequest;\n result: RefineProposalsResponse;\n response: RefineProposalsResponse;\n };\n decline_proposals: {\n params: z.input<typeof DeclineProposalsRequestSchema>;\n result: ServerPayload<DeclineProposalsResponse>;\n response: DeclineProposalsResponse;\n };\n buy_products: {\n params: z.input<typeof BuyProductsRequestSchema>;\n result: ServerPayload<BuyProductsResponse>;\n response: BuyProductsResponse;\n };\n accept_proposal: {\n params: z.input<typeof AcceptProposalRequestSchema>;\n result: ServerPayload<AcceptProposalResponse>;\n response: AcceptProposalResponse;\n };\n control_media_buy: {\n params: z.input<typeof ControlMediaBuyRequestSchema>;\n result: ServerPayload<ControlMediaBuyResponse>;\n response: ControlMediaBuyResponse;\n };\n get_products: {\n params: z.input<typeof GetProductsRequestSchema>;\n result: RequireCacheScopeWhenProducts<ServerPayload<GetProductsResponse>>;\n response: GetProductsResponse;\n };\n create_media_buy: {\n params: z.input<typeof CreateMediaBuyRequestSchema>;\n result: CreateMediaBuyServerPayload;\n response: CreateMediaBuyResponse;\n };\n update_media_buy: {\n params: z.input<typeof UpdateMediaBuyRequestSchema>;\n result: ServerPayload<UpdateMediaBuySuccess>;\n response: UpdateMediaBuyResponse;\n };\n get_media_buys: {\n params: z.input<typeof GetMediaBuysRequestSchema>;\n result: ServerPayload<GetMediaBuysResponse>;\n response: GetMediaBuysResponse;\n };\n get_media_buy_delivery: {\n params: z.input<typeof GetMediaBuyDeliveryRequestSchema>;\n result: ServerPayload<GetMediaBuyDeliveryResponse>;\n response: GetMediaBuyDeliveryResponse;\n };\n provide_performance_feedback: {\n params: z.input<typeof ProvidePerformanceFeedbackRequestSchema>;\n result: ServerPayload<ProvidePerformanceFeedbackSuccess>;\n response: ProvidePerformanceFeedbackResponse;\n };\n get_task_status: {\n params: z.input<typeof GetTaskStatusRequestSchema>;\n result: ServerPayload<GetTaskStatusResponse>;\n response: GetTaskStatusResponse;\n };\n list_tasks: {\n params: z.input<typeof ListTasksRequestSchema>;\n result: ServerPayload<ListTasksResponse>;\n response: ListTasksResponse;\n };\n sync_agent_notification_configs: {\n params: z.input<typeof SyncAgentNotificationConfigsRequestSchema>;\n result: ServerPayload<SyncAgentNotificationConfigsResponse>;\n response: SyncAgentNotificationConfigsResponse;\n };\n list_creative_formats: {\n params: z.input<typeof ListCreativeFormatsRequestSchema>;\n result: ServerPayload<ListCreativeFormatsResponse>;\n response: ListCreativeFormatsResponse;\n };\n list_transformers: {\n params: z.input<typeof ListTransformersRequestSchema>;\n result: ServerPayload<ListTransformersResponse>;\n response: ListTransformersResponse;\n };\n build_creative: {\n params: z.input<typeof BuildCreativeRequestSchema>;\n result:\n | ServerPayload<BuildCreativeSuccess>\n | ServerPayload<BuildCreativeMultiSuccess>\n | ServerPayload<BuildCreativeVariantSuccess>;\n response: BuildCreativeResponse;\n };\n preview_creative: {\n params: z.input<typeof PreviewCreativeRequestSchema>;\n result: ServerPayload<PreviewCreativeResponse>;\n response: PreviewCreativeResponse;\n };\n get_creative_delivery: {\n params: z.input<typeof GetCreativeDeliveryRequestSchema>;\n result: ServerPayload<GetCreativeDeliveryResponse>;\n response: GetCreativeDeliveryResponse;\n };\n list_creatives: {\n params: z.input<typeof ListCreativesRequestSchema>;\n result: ServerPayload<ListCreativesResponse>;\n response: ListCreativesResponse;\n };\n sync_creatives: {\n params: z.input<typeof SyncCreativesRequestSchema>;\n result: ServerPayload<SyncCreativesSuccess> | ServerPayload<SyncCreativesError>;\n response: SyncCreativesResponse;\n };\n get_signals: {\n params: z.input<typeof GetSignalsRequestSchema>;\n result: ServerPayload<GetSignalsResponse>;\n response: GetSignalsResponse;\n };\n activate_signal: {\n params: z.input<typeof ActivateSignalRequestSchema>;\n result: ServerPayload<ActivateSignalSuccess>;\n response: ActivateSignalResponse;\n };\n list_accounts: {\n params: z.input<typeof ListAccountsRequestSchema>;\n result: ServerPayload<ListAccountsResponse>;\n response: ListAccountsResponse;\n };\n sync_accounts: {\n params: z.input<typeof SyncAccountsRequestSchema>;\n result: ServerPayload<SyncAccountsSuccess>;\n response: SyncAccountsResponse;\n };\n sync_governance: {\n params: z.input<typeof SyncGovernanceRequestSchema>;\n result: ServerPayload<SyncGovernanceSuccess>;\n response: SyncGovernanceResponse;\n };\n get_account_financials: {\n params: z.input<typeof GetAccountFinancialsRequestSchema>;\n result: ServerPayload<GetAccountFinancialsSuccess>;\n response: GetAccountFinancialsResponse;\n };\n report_usage: {\n params: z.input<typeof ReportUsageRequestSchema>;\n result: ServerPayload<ReportUsageResponse>;\n response: ReportUsageResponse;\n };\n sync_event_sources: {\n params: z.input<typeof SyncEventSourcesRequestSchema>;\n result: ServerPayload<SyncEventSourcesSuccess>;\n response: SyncEventSourcesResponse;\n };\n log_event: {\n params: z.input<typeof LogEventRequestSchema>;\n result: ServerPayload<LogEventSuccess>;\n response: LogEventResponse;\n };\n sync_audiences: {\n params: z.input<typeof SyncAudiencesRequestSchema>;\n result: ServerPayload<SyncAudiencesSuccess>;\n response: SyncAudiencesResponse;\n };\n sync_catalogs: {\n params: z.input<typeof SyncCatalogsRequestSchema>;\n result: ServerPayload<SyncCatalogsSuccess>;\n response: SyncCatalogsResponse;\n };\n create_property_list: {\n params: z.input<typeof CreatePropertyListRequestSchema>;\n result: ServerPayload<CreatePropertyListResponse>;\n response: CreatePropertyListResponse;\n };\n update_property_list: {\n params: z.input<typeof UpdatePropertyListRequestSchema>;\n result: ServerPayload<UpdatePropertyListResponse>;\n response: UpdatePropertyListResponse;\n };\n get_property_list: {\n params: z.input<typeof GetPropertyListRequestSchema>;\n result: ServerPayload<GetPropertyListResponse>;\n response: GetPropertyListResponse;\n };\n list_property_lists: {\n params: z.input<typeof ListPropertyListsRequestSchema>;\n result: ServerPayload<ListPropertyListsResponse>;\n response: ListPropertyListsResponse;\n };\n delete_property_list: {\n params: z.input<typeof DeletePropertyListRequestSchema>;\n result: ServerPayload<DeletePropertyListResponse>;\n response: DeletePropertyListResponse;\n };\n create_collection_list: {\n params: z.input<typeof CreateCollectionListRequestSchema>;\n result: ServerPayload<CreateCollectionListResponse>;\n response: CreateCollectionListResponse;\n };\n update_collection_list: {\n params: z.input<typeof UpdateCollectionListRequestSchema>;\n result: ServerPayload<UpdateCollectionListResponse>;\n response: UpdateCollectionListResponse;\n };\n get_collection_list: {\n params: z.input<typeof GetCollectionListRequestSchema>;\n result: ServerPayload<GetCollectionListResponse>;\n response: GetCollectionListResponse;\n };\n list_collection_lists: {\n params: z.input<typeof ListCollectionListsRequestSchema>;\n result: ServerPayload<ListCollectionListsResponse>;\n response: ListCollectionListsResponse;\n };\n delete_collection_list: {\n params: z.input<typeof DeleteCollectionListRequestSchema>;\n result: ServerPayload<DeleteCollectionListResponse>;\n response: DeleteCollectionListResponse;\n };\n list_content_standards: {\n params: z.input<typeof ListContentStandardsRequestSchema>;\n result: ServerPayload<ListContentStandardsResponse>;\n response: ListContentStandardsResponse;\n };\n get_content_standards: {\n params: z.input<typeof GetContentStandardsRequestSchema>;\n result: ServerPayload<GetContentStandardsResponse>;\n response: GetContentStandardsResponse;\n };\n create_content_standards: {\n params: z.input<typeof CreateContentStandardsRequestSchema>;\n result: ServerPayload<CreateContentStandardsResponse>;\n response: CreateContentStandardsResponse;\n };\n update_content_standards: {\n params: z.input<typeof UpdateContentStandardsRequestSchema>;\n result: ServerPayload<UpdateContentStandardsResponse>;\n response: UpdateContentStandardsResponse;\n };\n calibrate_content: {\n params: z.input<typeof CalibrateContentRequestSchema>;\n result: ServerPayload<CalibrateContentResponse>;\n response: CalibrateContentResponse;\n };\n validate_content_delivery: {\n params: z.input<typeof ValidateContentDeliveryRequestSchema>;\n result: ServerPayload<ValidateContentDeliveryResponse>;\n response: ValidateContentDeliveryResponse;\n };\n get_media_buy_artifacts: {\n params: z.input<typeof GetMediaBuyArtifactsRequestSchema>;\n result: ServerPayload<GetMediaBuyArtifactsResponse>;\n response: GetMediaBuyArtifactsResponse;\n };\n get_creative_features: {\n params: z.input<typeof GetCreativeFeaturesRequestSchema>;\n result: ServerPayload<GetCreativeFeaturesResponse>;\n response: GetCreativeFeaturesResponse;\n };\n sync_plans: {\n params: z.input<typeof SyncPlansRequestSchema>;\n result: ServerPayload<SyncPlansResponse>;\n response: SyncPlansResponse;\n };\n check_governance: {\n params: z.input<typeof CheckGovernanceRequestSchema>;\n result: ServerPayload<CheckGovernanceResponse>;\n response: CheckGovernanceResponse;\n };\n report_plan_outcome: {\n params: z.input<typeof ReportPlanOutcomeRequestSchema>;\n result: ServerPayload<ReportPlanOutcomeResponse>;\n response: ReportPlanOutcomeResponse;\n };\n report_plan_adjustment: {\n params: z.input<typeof ReportPlanAdjustmentRequestSchema>;\n result: ServerPayload<ReportPlanAdjustmentResponse>;\n response: ReportPlanAdjustmentResponse;\n };\n get_plan_audit_logs: {\n params: z.input<typeof GetPlanAuditLogsRequestSchema>;\n result: ServerPayload<GetPlanAuditLogsResponse>;\n response: GetPlanAuditLogsResponse;\n };\n si_get_offering: {\n params: z.input<typeof SIGetOfferingRequestSchema>;\n result: ServerPayload<SIGetOfferingResponse>;\n response: SIGetOfferingResponse;\n };\n si_initiate_session: {\n params: z.input<typeof SIInitiateSessionRequestSchema>;\n result: ServerPayload<SIInitiateSessionResponse>;\n response: SIInitiateSessionResponse;\n };\n si_send_message: {\n params: z.input<typeof SISendMessageRequestSchema>;\n result: ServerPayload<SISendMessageResponse>;\n response: SISendMessageResponse;\n };\n si_terminate_session: {\n params: z.input<typeof SITerminateSessionRequestSchema>;\n result: ServerPayload<SITerminateSessionResponse>;\n response: SITerminateSessionResponse;\n };\n\n get_brand_identity: {\n params: z.input<typeof GetBrandIdentityRequestSchema>;\n result: ServerPayload<GetBrandIdentitySuccess>;\n response: GetBrandIdentitySuccess;\n };\n get_rights: {\n params: z.input<typeof GetRightsRequestSchema>;\n result: ServerPayload<GetRightsSuccess>;\n response: GetRightsSuccess;\n };\n acquire_rights: {\n params: z.input<typeof AcquireRightsRequestSchema>;\n result:\n | ServerPayload<AcquireRightsAcquired>\n | ServerPayload<AcquireRightsPendingApproval>\n | ServerPayload<AcquireRightsRejected>;\n response: AcquireRightsAcquired | AcquireRightsPendingApproval | AcquireRightsRejected;\n };\n update_rights: {\n params: z.input<typeof UpdateRightsRequestSchema>;\n result: ServerPayload<UpdateRightsSuccess>;\n response: UpdateRightsResponse;\n };\n}\n\nexport type AdcpServerToolName = keyof AdcpToolMap;\n\n/**\n * Parameter shape passed to `resolveIdempotencyPrincipal`. Wide enough to\n * carry any wire request (the framework calls every mutating tool through\n * the same resolver), narrow enough to surface the most-common scoping\n * fields (`account`, `brand`) using the canonical wire types.\n *\n * `account` and `brand` resolve to the same `AccountReference` /\n * `BrandReference` types the rest of the SDK uses. The\n * `account: AccountReference` discriminated union forces adopters scoping\n * by tenant to narrow before reading variant-specific fields:\n *\n * ```ts\n * resolveIdempotencyPrincipal: (ctx, params) => {\n * if (params.account && 'account_id' in params.account) {\n * return params.account.account_id; // narrowed to {account_id: string}\n * }\n * if (params.account?.brand?.domain) {\n * return `${params.account.brand.domain}:${params.account.operator}`;\n * }\n * return ctx.account?.id ?? 'anon';\n * }\n * ```\n *\n * Tool-specific scoping (e.g., custom session header on `si_send_message`)\n * still has the open `Record<string, unknown>` index signature for\n * everything else.\n */\nexport interface IdempotencyPrincipalParams extends Record<string, unknown> {\n /** Buyer-supplied account reference. Most mutating tools carry this. */\n account?: AccountReference;\n /** Buyer-supplied brand reference (used by some tools without account). */\n brand?: BrandReference;\n}\n\n// ---------------------------------------------------------------------------\n// Domain handler types\n// ---------------------------------------------------------------------------\n\n/** Handler that receives validated params and a resolved context.\n *\n * Return any of:\n * - The narrow Success arm (`result`) — framework applies the response builder.\n * - The full response union (`response` = Success | Error | Submitted) — the\n * dispatcher narrows Error / Submitted arms at runtime. Useful for adapters\n * that already produce a `Result<FooResponse, ...>` and don't want to\n * pre-narrow.\n * - A pre-formatted `McpToolResponse` (e.g. from `adcpError(...)`) — passed\n * through unchanged.\n */\ntype DomainHandler<K extends AdcpServerToolName, TAccount> = (\n params: AdcpToolMap[K]['params'],\n ctx: HandlerContext<TAccount>\n) => Promise<AdcpToolMap[K]['result'] | AdcpToolMap[K]['response'] | McpToolResponse>;\n\nexport interface MediaBuyHandlers<TAccount = unknown> {\n getProducts?: DomainHandler<'get_products', TAccount>;\n listProducts?: DomainHandler<'list_products', TAccount>;\n requestProposals?: DomainHandler<'request_proposals', TAccount>;\n declineProposals?: DomainHandler<'decline_proposals', TAccount>;\n buyProducts?: DomainHandler<'buy_products', TAccount>;\n acceptProposal?: DomainHandler<'accept_proposal', TAccount>;\n controlMediaBuy?: DomainHandler<'control_media_buy', TAccount>;\n createMediaBuy?: DomainHandler<'create_media_buy', TAccount>;\n updateMediaBuy?: DomainHandler<'update_media_buy', TAccount>;\n getMediaBuys?: DomainHandler<'get_media_buys', TAccount>;\n getMediaBuyDelivery?: DomainHandler<'get_media_buy_delivery', TAccount>;\n providePerformanceFeedback?: DomainHandler<'provide_performance_feedback', TAccount>;\n listCreativeFormats?: DomainHandler<'list_creative_formats', TAccount>;\n syncCreatives?: DomainHandler<'sync_creatives', TAccount>;\n listCreatives?: DomainHandler<'list_creatives', TAccount>;\n}\n\n/** First-class AdCP 3.2 proposal negotiation server seam. */\nexport interface ProposalNegotiationHandlers<TAccount = unknown> {\n /** Projected to `media_buy.proposal_refinement` during capability discovery. */\n capabilities: ProposalRefinementCapabilities;\n /** Resolve a stable tenant/account namespace from authenticated server context. */\n resolveScope: (ctx: HandlerContext<TAccount>) => MaybePromise<ProposalRefinementScope>;\n refineProposals: DomainHandler<'refine_proposals', TAccount>;\n}\n\nexport interface EventTrackingHandlers<TAccount = unknown> {\n syncEventSources?: DomainHandler<'sync_event_sources', TAccount>;\n logEvent?: DomainHandler<'log_event', TAccount>;\n syncAudiences?: DomainHandler<'sync_audiences', TAccount>;\n syncCatalogs?: DomainHandler<'sync_catalogs', TAccount>;\n}\n\nexport interface SignalsHandlers<TAccount = unknown> {\n getSignals?: DomainHandler<'get_signals', TAccount>;\n activateSignal?: DomainHandler<'activate_signal', TAccount>;\n}\n\nexport interface CreativeHandlers<TAccount = unknown> {\n listCreativeFormats?: DomainHandler<'list_creative_formats', TAccount>;\n listTransformers?: DomainHandler<'list_transformers', TAccount>;\n buildCreative?: DomainHandler<'build_creative', TAccount>;\n previewCreative?: DomainHandler<'preview_creative', TAccount>;\n listCreatives?: DomainHandler<'list_creatives', TAccount>;\n syncCreatives?: DomainHandler<'sync_creatives', TAccount>;\n getCreativeDelivery?: DomainHandler<'get_creative_delivery', TAccount>;\n}\n\nexport interface GovernanceHandlers<TAccount = unknown> {\n createPropertyList?: DomainHandler<'create_property_list', TAccount>;\n updatePropertyList?: DomainHandler<'update_property_list', TAccount>;\n getPropertyList?: DomainHandler<'get_property_list', TAccount>;\n listPropertyLists?: DomainHandler<'list_property_lists', TAccount>;\n deletePropertyList?: DomainHandler<'delete_property_list', TAccount>;\n createCollectionList?: DomainHandler<'create_collection_list', TAccount>;\n updateCollectionList?: DomainHandler<'update_collection_list', TAccount>;\n getCollectionList?: DomainHandler<'get_collection_list', TAccount>;\n listCollectionLists?: DomainHandler<'list_collection_lists', TAccount>;\n deleteCollectionList?: DomainHandler<'delete_collection_list', TAccount>;\n listContentStandards?: DomainHandler<'list_content_standards', TAccount>;\n getContentStandards?: DomainHandler<'get_content_standards', TAccount>;\n createContentStandards?: DomainHandler<'create_content_standards', TAccount>;\n updateContentStandards?: DomainHandler<'update_content_standards', TAccount>;\n calibrateContent?: DomainHandler<'calibrate_content', TAccount>;\n validateContentDelivery?: DomainHandler<'validate_content_delivery', TAccount>;\n getMediaBuyArtifacts?: DomainHandler<'get_media_buy_artifacts', TAccount>;\n getCreativeFeatures?: DomainHandler<'get_creative_features', TAccount>;\n syncPlans?: DomainHandler<'sync_plans', TAccount>;\n checkGovernance?: DomainHandler<'check_governance', TAccount>;\n reportPlanOutcome?: DomainHandler<'report_plan_outcome', TAccount>;\n /** Authorize and scope report_plan_adjustment to its tenant and plan owner. */\n resolveReportPlanAdjustmentScope?: (\n ctx: HandlerContext<TAccount>,\n params: AdcpToolMap['report_plan_adjustment']['params']\n ) => CallerMutationScope | Promise<CallerMutationScope>;\n reportPlanAdjustment?: DomainHandler<'report_plan_adjustment', TAccount>;\n getPlanAuditLogs?: DomainHandler<'get_plan_audit_logs', TAccount>;\n}\n\nexport interface ProtocolHandlers<TAccount = unknown> {\n /** Resolve the authenticated caller namespace used to isolate its subscriber set. */\n resolveScope?: (\n ctx: HandlerContext<TAccount>,\n params: AdcpToolMap['sync_agent_notification_configs']['params']\n ) => CallerMutationScope | Promise<CallerMutationScope>;\n syncAgentNotificationConfigs?: DomainHandler<'sync_agent_notification_configs', TAccount>;\n}\n\nexport interface AccountHandlers<TAccount = unknown> {\n listAccounts?: DomainHandler<'list_accounts', TAccount>;\n syncAccounts?: DomainHandler<'sync_accounts', TAccount>;\n syncGovernance?: DomainHandler<'sync_governance', TAccount>;\n getAccountFinancials?: DomainHandler<'get_account_financials', TAccount>;\n reportUsage?: DomainHandler<'report_usage', TAccount>;\n}\n\nexport interface SponsoredIntelligenceHandlers<TAccount = unknown> {\n getOffering?: DomainHandler<'si_get_offering', TAccount>;\n initiateSession?: DomainHandler<'si_initiate_session', TAccount>;\n sendMessage?: DomainHandler<'si_send_message', TAccount>;\n terminateSession?: DomainHandler<'si_terminate_session', TAccount>;\n}\n\n/**\n * Brand rights covers identity and licensing workflows.\n *\n * `update_rights` is a first-class mutating tool — modify an existing rights\n * grant (extend dates, adjust impression caps, change pricing, pause/resume).\n * Schemas published in AdCP 3.0.x; framework dispatch parallels\n * `acquire_rights`.\n *\n * `creative_approval` is intentionally NOT in this handler bag — the spec\n * models it as an HTTP webhook (the buyer POSTs to the `approval_webhook`\n * URL returned from `acquire_rights`), not as an MCP/A2A tool. Adopters\n * wire the receiver to `BrandRightsPlatform.reviewCreativeApproval` and\n * use `creativeApproved` / `creativeApprovalRejected` /\n * `creativeApprovalPendingReview` / `creativeApprovalError` from\n * `@adcp/sdk/server` to build the webhook response.\n */\nexport interface BrandRightsHandlers<TAccount = unknown> {\n getBrandIdentity?: DomainHandler<'get_brand_identity', TAccount>;\n getRights?: DomainHandler<'get_rights', TAccount>;\n acquireRights?: DomainHandler<'acquire_rights', TAccount>;\n updateRights?: DomainHandler<'update_rights', TAccount>;\n}\n\n// ---------------------------------------------------------------------------\n// Capabilities config\n// ---------------------------------------------------------------------------\n\nexport interface AdcpCapabilitiesConfig {\n major_versions?: number[];\n /**\n * Release-precision versions this seller supports (AdCP 3.1+ per spec PR\n * `adcontextprotocol/adcp#3493`). Each entry parses to a major via\n * `parseAdcpMajorVersion` — the union of these majors and `major_versions`\n * defines the seller's accepted set for the wire-level\n * `adcp_major_version` / `adcp_version` claim a buyer may carry.\n *\n * 3.0-pinned sellers can ignore this field. 3.1+ sellers should declare\n * here the same release-precision strings they emit in `adcp_version` on\n * responses, so buyers receiving `VERSION_UNSUPPORTED` can read the\n * supported set off the error envelope and downgrade their pin.\n */\n supported_versions?: string[];\n features?: Partial<MediaBuyFeatures>;\n account?: Partial<AccountCapabilities>;\n creative?: Partial<CreativeCapabilities>;\n extensions_supported?: readonly string[];\n /**\n * Vendor-namespaced extension capability data emitted at the top-level\n * `get_adcp_capabilities.ext` field. Each populated namespace should also\n * be listed in {@link extensions_supported}.\n */\n ext?: NonNullable<GetAdCPCapabilitiesResponse['ext']>;\n /**\n * RFC 9421 request-signing verifier capability. See\n * docs/building/implementation/security.mdx#signed-requests-transport-layer.\n * Emitted verbatim in `get_adcp_capabilities.request_signing`. Omit unless\n * the agent actually verifies incoming signatures — a `supported: true`\n * claim without a working verifier is graded as FAIL by the conformance\n * runner (see `@adcp/sdk/testing/storyboard/request-signing`).\n */\n request_signing?: NonNullable<GetAdCPCapabilitiesResponse['request_signing']>;\n /**\n * Specialism claims the agent supports. Each entry maps to a storyboard\n * bundle under `/compliance/{version}/specialisms/{id}/`; the AAO\n * compliance runner executes the matching storyboards to verify. Only\n * list specialisms the agent actually implements.\n */\n specialisms?: NonNullable<GetAdCPCapabilitiesResponse['specialisms']>;\n /**\n * @deprecated Idempotency capability data is derived exclusively from\n * the active `idempotency` store. This legacy override is ignored so an\n * unwired or mismatched store can never be advertised to buyers.\n */\n idempotency?: {\n replay_ttl_seconds?: number;\n };\n /** Freshness and notification support for the capability document. */\n capability_changes?: NonNullable<GetAdCPCapabilitiesResponse['adcp']['capability_changes']>;\n portfolio?: {\n publisher_domains: string[];\n primary_channels?: MediaChannel[];\n primary_countries?: string[];\n description?: string;\n advertising_policies?: string;\n };\n /**\n * Per-domain capability blocks deep-merged on top of the framework's\n * auto-derived response. Use when you need to surface fields the top-level\n * `AdcpCapabilitiesConfig` doesn't model — execution.targeting,\n * audience_targeting, content_standards channels, conversion_tracking\n * identifier types, compliance_testing scenarios, etc.\n *\n * Deep-merge semantics:\n * - nested objects merge recursively;\n * - arrays REPLACE (not concat) so callers stay in control of cardinality;\n * - primitive overrides replace the auto-derived value.\n *\n * Top-level fields the framework owns (`adcp`, `supported_protocols`,\n * `specialisms`, `extensions_supported`, `ext`) are not accepted here — configure\n * them via their dedicated fields on {@link AdcpCapabilitiesConfig}.\n */\n overrides?: AdcpCapabilitiesOverrides;\n}\n\n/**\n * Per-domain capability overrides. See {@link AdcpCapabilitiesConfig.overrides}.\n *\n * Each field accepts the same shape as the corresponding block on\n * {@link GetAdCPCapabilitiesResponse}. A value of `null` explicitly removes\n * the auto-derived block; `undefined` (omission) is a no-op.\n *\n * **Values must be JSON-serializable plain objects.** Class instances, `Date`,\n * `Map`, `Set`, or any value with a non-`Object.prototype` prototype are\n * treated as opaque leaves and replace their target rather than merging.\n */\nexport interface AdcpCapabilitiesOverrides {\n media_buy?: Partial<NonNullable<GetAdCPCapabilitiesResponse['media_buy']>> | null;\n creative?: Partial<NonNullable<GetAdCPCapabilitiesResponse['creative']>> | null;\n signals?: Partial<NonNullable<GetAdCPCapabilitiesResponse['signals']>> | null;\n governance?: Partial<NonNullable<GetAdCPCapabilitiesResponse['governance']>> | null;\n brand?: Partial<NonNullable<GetAdCPCapabilitiesResponse['brand']>> | null;\n sponsored_intelligence?: Partial<NonNullable<GetAdCPCapabilitiesResponse['sponsored_intelligence']>> | null;\n measurement?: Partial<NonNullable<GetAdCPCapabilitiesResponse['measurement']>> | null;\n experimental_features?: GetAdCPCapabilitiesResponse['experimental_features'] | null;\n account?: Partial<NonNullable<GetAdCPCapabilitiesResponse['account']>> | null;\n compliance_testing?: GetAdCPCapabilitiesResponse['compliance_testing'] | null;\n webhook_signing?: GetAdCPCapabilitiesResponse['webhook_signing'] | null;\n identity?: GetAdCPCapabilitiesResponse['identity'] | null;\n request_signing?: GetAdCPCapabilitiesResponse['request_signing'] | null;\n}\n\n// ---------------------------------------------------------------------------\n// Signed-requests auto-wiring\n// ---------------------------------------------------------------------------\n\n/**\n * Inputs for the auto-wired RFC 9421 request-signature verifier. When set on\n * {@link AdcpServerConfig}, `createAdcpServer` builds an Express-shaped\n * verifier middleware and attaches it to the returned `McpServer` via\n * {@link ADCP_PRE_TRANSPORT}. `serve()` discovers the attached middleware and\n * mounts it as the transport-layer `preTransport` hook, so every inbound MCP\n * request passes the verifier before reaching the JSON-RPC router.\n *\n * A seller wiring this config MUST also publish a buyer-visible discovery\n * surface in `capabilities`, one of:\n *\n * - **3.1+ canonical (recommended):** set\n * `capabilities.request_signing.supported: true`. Buyers learn the agent\n * verifies signatures from `get_adcp_capabilities`; no deprecated specialism\n * claim required. The universal `signed_requests` storyboard grades on this\n * signal alone.\n * - **Back-compat:** add `'signed-requests'` to `capabilities.specialisms`.\n * The 3.0-era enum value is preserved through the AdCP 4.0 deprecation cycle\n * (adcp#3075); when this path is taken the runner emits\n * `signed_requests_specialism_deprecated` (adcp-client#2082, adcp#4796).\n *\n * `createAdcpServer` throws at construction time when `signedRequests` is set\n * but neither discovery surface is declared, closing the footgun where the\n * verifier silently rejects every signed request from buyers who never learned\n * to sign. The inverse (specialism or capability declared without a\n * `signedRequests` config) is logged loudly but not thrown — legacy servers\n * that hand-build the middleware via `serve({ preTransport })` stay\n * conformant.\n *\n * `jwks`, `replayStore`, and `revocationStore` should be hoisted outside\n * the agent factory so a single verifier instance serves every request —\n * otherwise each request would build a fresh replay store and the rate-\n * abuse / replay-detection guards would be per-request (i.e. broken).\n */\nexport interface SignedRequestsConfig {\n /** Resolves verification keys by `keyid`. */\n jwks: JwksResolver;\n /** Stores `(keyid, signature-bytes, expires)` tuples for replay detection. */\n replayStore: ReplayStore;\n /** Consulted for revoked `kid` / `jti` before accepting a signature. */\n revocationStore: RevocationStore;\n /**\n * Operation names that MUST arrive signed. Defaults to every statically\n * mutating AdCP tool (per the framework's {@link MUTATING_TASKS}) plus\n * `get_products`, whose AdCP 3.2 proposal-finalize variant is state-changing.\n * Because signing policy is advertised at tool granularity, enabling that\n * protection also requires signatures on ordinary `get_products` reads.\n */\n required_for?: string[];\n /**\n * JSON-RPC protocol method names that MUST arrive signed. Separate from\n * AdCP tool names in `required_for`; examples include `tasks/cancel`.\n */\n protocol_methods_required_for?: string[];\n /** Defaults to `required` on 3.2 and `either` on legacy endpoints. */\n covers_content_digest?: ContentDigestPolicy;\n /**\n * Resolve the `agent_url` claim the verifier stamps on successful results.\n * Useful when a single seller hosts multiple brands and the buyer's\n * signing key is scoped to a brand identifier rather than the root.\n */\n agentUrlForKeyid?: (keyid: string) => string | undefined;\n /**\n * Shape the signer identity exposed to handlers. The framework attaches a\n * branded `http_sig` credential when `agentUrlForKeyid` resolves, unless\n * this callback explicitly supplies another credential. When `serve()` also\n * authenticates the request, this callback must resolve the signer to that\n * same authenticated principal or the request is rejected.\n */\n makePrincipal?: (signer: import('../signing/types').VerifiedSigner) => AuthPrincipal;\n}\n\n/**\n * Symbol under which `createAdcpServer` attaches the auto-wired `preTransport`\n * function to the returned `McpServer`. `serve()` reads this symbol to mount\n * the verifier. Consumers typically don't need to touch it; it's exported for\n * tests and for downstream frameworks that want the same wiring.\n */\nexport const ADCP_PRE_TRANSPORT: unique symbol = Symbol.for('@adcp/client.preTransport');\n\n/**\n * Per-request canonical endpoint scope stamped by `serve()` on the underlying\n * SDK server while it dispatches a request. Internal transport contract; it\n * is intentionally independent of authentication so anonymous deployments\n * receive the same multi-host idempotency isolation.\n */\nexport const ADCP_SERVE_IDEMPOTENCY_SCOPE: unique symbol = Symbol.for('@adcp/client.serveIdempotencyScope');\n\n/**\n * Diagnostic snapshot of the signed-requests wiring on a returned server.\n * Read via `server[ADCP_SIGNED_REQUESTS_STATE]` so integration tests and\n * operator boot diagnostics can assert on the claim/config pairing without\n * parsing log output. Populated on every `createAdcpServer` call.\n */\nexport interface AdcpSignedRequestsState {\n /** True when `signedRequests: {...}` was passed and the verifier is auto-wired. */\n autoWired: boolean;\n /** True when `capabilities.specialisms` includes `'signed-requests'`. */\n specialismClaimed: boolean;\n /** True when `capabilities.request_signing.supported === true`. */\n capabilitySupported: boolean;\n /**\n * Non-fatal mismatch state. `'ok'` when wiring + claim + supported are\n * all aligned (or all off); `'claim_without_config'` when the claim is\n * set but no `signedRequests` config was passed (legacy manual\n * `serve({ preTransport })` path — logged but not thrown).\n */\n mismatch: 'ok' | 'claim_without_config';\n}\n\n/**\n * Symbol under which `createAdcpServer` attaches the `AdcpSignedRequestsState`\n * snapshot. Use `server[ADCP_SIGNED_REQUESTS_STATE]` to inspect wiring from\n * tests or boot diagnostics.\n */\nexport const ADCP_SIGNED_REQUESTS_STATE: unique symbol = Symbol.for('@adcp/client.signedRequestsState');\n\n/**\n * Symbol marking that a server's `instructions` was supplied as a function\n * (lazy / per-session form) rather than a static string. `serve()` reads\n * this to refuse `reuseAgent: true` — the function is captured once at\n * construction and would not re-evaluate per session under server reuse.\n *\n * Internal contract between `createAdcpServer` and `serve()`. Adopters\n * who instantiate `McpServer` directly (without `createAdcpServer`) and\n * want their own marker semantics should not import this symbol.\n */\nexport const ADCP_INSTRUCTIONS_FN: unique symbol = Symbol.for('@adcp/client.instructionsFn');\n\n/**\n * Resolve function-form instructions for transports without a legacy\n * `initialize` handshake (notably MCP 2026-07-28). Internal contract between\n * `createAdcpServer` and transport adapters.\n */\nexport const ADCP_INSTRUCTIONS_RESOLVER: unique symbol = Symbol.for('@adcp/client.instructionsResolver');\n\n/**\n * Pre-resolution session context passed to a function-form `instructions`.\n * Slim by design — no `account` (resolution hasn't run yet at MCP `initialize`\n * time, which is the natural eval moment for per-session instructions).\n *\n * Both fields are reserved: today they are always `undefined` because the\n * framework's `serve()` does not yet plumb auth + registry state into the\n * factory before MCP `initialize`. Adopters who need tenant identity should\n * use closures captured in their factory's HTTP-scoped state. The shape is\n * forward-compatible: when the framework wires authInfo/agent through, the\n * fields will populate without breaking existing function bodies.\n *\n * @see AdcpServerConfig.instructions\n * @public\n */\nexport interface SessionContext {\n /**\n * @reserved Always `undefined` in v6.x. The framework does not yet plumb\n * `authInfo` into the factory before MCP `initialize` — use closures\n * captured in your factory's HTTP-scoped state for tenant identity today.\n * Forward-compatible: when the framework wires this through, your\n * `ctx.authInfo?.…` reads start returning real values without breaking\n * existing function bodies.\n */\n readonly authInfo?: ResolvedAuthInfo;\n\n /**\n * @reserved Always `undefined` in v6.x. The framework does not yet plumb\n * the resolved `BuyerAgent` into the factory before MCP `initialize` —\n * use closures captured in your factory's HTTP-scoped state for tenant\n * identity today. Forward-compatible: when the framework wires this\n * through, your `ctx.agent?.…` reads start returning real values without\n * breaking existing function bodies.\n */\n readonly agent?: BuyerAgent;\n}\n\n/**\n * Behavior when a function-form `instructions` callback throws or its\n * returned Promise rejects.\n *\n * - `'skip'` (default) — log server-side, treat as `undefined` (no\n * instructions). Right for prose-of-flavor (brand manifests, marketing\n * copy) where a registry fetch failure must not kill the buyer's session.\n * - `'fail'` — rethrow (sync) / re-reject (async). The MCP `initialize`\n * handshake then fails at the transport layer (this is NOT an\n * `adcp_error` envelope — it kills the session). Right for adopters\n * whose instructions carry load-bearing policy where stale/missing\n * guidance is worse than a connection retry.\n *\n * @public\n */\nexport type OnInstructionsError = 'skip' | 'fail';\n\n/**\n * A value that is either `T` directly or a `Promise<T>`.\n *\n * Used in callback signatures that support both synchronous and asynchronous\n * returns (e.g. `instructions`), so adopters can return either a plain\n * string or an `async` function without separate overloads.\n *\n * @public\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Shape of the preTransport function attached by `createAdcpServer` when\n * `signedRequests` is configured. Returns `true` if the middleware has already\n * sent a response (e.g., 401 on verification failure), `false` to continue\n * into MCP dispatch.\n */\nexport type AdcpPreTransport = (\n req: import('http').IncomingMessage & { rawBody?: string },\n res: import('http').ServerResponse\n) => Promise<boolean>;\n\n// ---------------------------------------------------------------------------\n// Custom tool config\n// ---------------------------------------------------------------------------\n\n/** UI hints for a custom tool backed by an MCP App. */\nexport interface McpAppUiMeta {\n /** URI of the MCP App resource rendered when the tool is invoked. */\n resourceUri?: string;\n /** Audiences a compliant host exposes the tool to. Routing metadata, not authorization. */\n visibility?: Array<'model' | 'app'>;\n}\n\n/** Typed MCP App metadata forwarded unchanged in `tools/list`. */\nexport interface McpAppMeta {\n ui?: McpAppUiMeta;\n}\n\n/**\n * The active AdCP 3.2 media-buy MCP catalog.\n *\n * Deprecated compatibility entry points such as `get_products`,\n * `create_media_buy`, and `update_media_buy` are deliberately absent. A\n * server may still keep those tools callable for older buyers while\n * advertising this compact surface to new MCP clients.\n *\n * @public\n */\nexport const MEDIA_BUY_MCP_TOOL_PROFILE = [\n 'accept_proposal',\n 'buy_products',\n 'control_media_buy',\n 'decline_proposals',\n 'get_account_financials',\n 'get_adcp_capabilities',\n 'get_media_buy_delivery',\n 'get_media_buys',\n 'get_task_status',\n 'list_accounts',\n 'list_creatives',\n 'list_products',\n 'list_tasks',\n 'log_event',\n 'provide_performance_feedback',\n 'refine_proposals',\n 'report_usage',\n 'request_proposals',\n 'sync_accounts',\n 'sync_agent_notification_configs',\n 'sync_audiences',\n 'sync_catalogs',\n 'sync_creatives',\n 'sync_event_sources',\n 'sync_governance',\n] as const;\n\nexport type AdcpMcpToolProfile = 'auto' | 'media-buy' | 'all';\n\n/**\n * Declarative registration for a tool outside {@link AdcpToolMap} — seller\n * extensions (e.g. collection-list helpers), test-harness endpoints\n * (`comply_test_controller`), or AdCP surfaces whose JSON Schemas haven't\n * landed in the framework yet.\n *\n * These tools **bypass the framework's spec-tool pipeline**:\n * idempotency middleware, governance pre-checks, account resolution,\n * and response wrapping are all skipped. The handler receives the\n * SDK-validated arguments and must return a `CallToolResult` directly.\n * If you need any of those behaviors, call the framework helpers from\n * inside the handler (e.g., `checkGovernance(...)`, `adcpError(...)`).\n *\n * Type parameters match the SDK's `McpServer.registerTool` signature so\n * argument and response types infer from the declared schemas.\n */\nexport interface AdcpCustomToolConfig<\n InputArgs extends undefined | ZodRawShapeCompat | AnySchema = undefined,\n OutputArgs extends ZodRawShapeCompat | AnySchema | undefined = undefined,\n> {\n /** Human-readable description — surfaced in `tools/list`. */\n description?: string;\n /** Optional title hint for the MCP inspector. */\n title?: string;\n /** Zod raw shape or schema for argument validation. */\n inputSchema?: InputArgs;\n /**\n * Zod raw shape or schema for the declared response payload.\n *\n * Forwarded verbatim to `registerTool`. The MCP SDK validates every\n * non-error response's `structuredContent` against this schema on the\n * server AND on the buyer's client (the latter fires regardless of\n * `isError` — see the `NOTE on outputSchema` block earlier in this\n * file). Framework-registered AdCP tools skip this field for that\n * reason; custom tools opt in here and own the trade-off.\n *\n * Footgun: a too-strict schema (e.g. `z.never()`, or one that\n * accidentally rejects the caller's own valid shape) turns the tool\n * into a silent client-side validation error for every buyer. The\n * seller sees a successful response go out; the buyer receives an\n * `Output validation error`. Test against a real buyer call before\n * relying on this.\n */\n outputSchema?: OutputArgs;\n /** Tool annotations (readOnlyHint / destructiveHint / idempotentHint / openWorldHint). */\n annotations?: ToolAnnotations;\n /** Portable MCP App metadata surfaced unchanged in `tools/list`. */\n _meta?: McpAppMeta;\n /**\n * Tool handler. Gets SDK-validated `args` based on `inputSchema` and\n * must return a `CallToolResult`. Use `capabilitiesResponse`,\n * `mediaBuyResponse`, `adcpError`, or a hand-built `{ content, structuredContent? }`.\n */\n handler: ToolCallback<InputArgs>;\n}\n\n// ---------------------------------------------------------------------------\n// Server config\n// ---------------------------------------------------------------------------\n\n/**\n * Public shape for the `webhooks` option on {@link AdcpServerConfig}.\n * Concrete name + export so adopters can write `webhooks: WebhooksConfig`\n * without reaching for a `Pick<WebhookEmitterOptions, ...>` reproduction\n * (and without falling back to `as any` when they typed it loosely).\n *\n * Subset of {@link WebhookEmitterOptions} the framework lifts to the\n * server config: signing key/provider, retry policy, immutable delivery\n * store, fetch override, user-agent + tag, and the per-emit observability\n * hooks. Other emitter-internal knobs (rate limits, transport pool\n * sizing) stay on `WebhookEmitterOptions` for direct emitter callers.\n *\n * @public\n */\nexport type WebhooksConfig = Pick<\n WebhookEmitterOptions,\n | 'signerKey'\n | 'signerProvider'\n | 'retries'\n | 'deliveryStore'\n | 'idempotencyKeyStore'\n | 'deliveryRetryHorizonSeconds'\n | 'deliveryRecovery'\n | 'generateIdempotencyKey'\n | 'fetch'\n | 'userAgent'\n | 'tag'\n> & {\n /** Stable publisher namespace for shared delivery-store keys. Defaults to the trusted server name. */\n publisherScope?: string;\n /** Trusted fallback namespace for a genuinely single-tenant server. */\n tenantScope?: string;\n /** Observability: emitter-wide onAttempt hook. */\n onAttempt?: WebhookEmitterOptions['onAttempt'];\n /** Observability: emitter-wide onAttemptResult hook. */\n onAttemptResult?: WebhookEmitterOptions['onAttemptResult'];\n};\n\nexport interface AdcpServerConfig<TAccount = unknown> {\n name: string;\n version: string;\n\n /**\n * Controls the tools advertised by MCP `tools/list` without removing\n * compatibility call routes.\n *\n * - `auto` (default): a 3.2 server with any compact media-buy lifecycle\n * handler advertises the spec's active `media-buy` profile.\n * - `media-buy`: always advertise the intersection of registered tools and\n * the active 3.2 media-buy profile.\n * - `all`: advertise every registered tool, including deprecated aliases.\n *\n * This is a discovery filter, not an authorization boundary. In `auto` and\n * `media-buy` modes, registered legacy tools remain callable so 3.0/3.1\n * buyers that already know their tool names continue to work.\n */\n mcpToolProfile?: AdcpMcpToolProfile;\n\n /**\n * Require framework-resolved account context on compact lifecycle\n * mutations before replay lookup. Enabled by the decisioning-platform\n * adapter; raw-handler adopters can retain their own scope resolver during\n * the compatibility window.\n *\n * @internal\n */\n requireCompactMutationAccountScope?: boolean;\n\n /**\n * Expose generated top-level AdCP request shapes in MCP `tools/list`.\n *\n * Defaults to `false`, preserving the long-standing passthrough schema so\n * the framework AJV validator remains the only validation gate shared by\n * MCP and A2A. Set to `true` when generic MCP clients need argument hints\n * from `tools/list`; known AdCP tools use shallow key hints derived from\n * `TOOL_INPUT_SHAPES` and unknown/custom framework surfaces fall back to\n * passthrough.\n */\n exposeToolSchemas?: boolean;\n\n /**\n * AdCP protocol version this server speaks. Defaults to {@link ADCP_VERSION}\n * — the GA version the SDK ships against. Override to pin to an older\n * stable (e.g., `'3.0.0'`) or opt into a beta channel (`'3.1.0-beta.1'`)\n * once that registry ships.\n *\n * Not the same as `version` (the publisher's app version, e.g., `'1.4.2'`).\n *\n * Stage 2 plumbs the option through and validates it at construction\n * time; cross-major pins (e.g. `'4.0.0-beta.1'` while the SDK ships\n * against major 3) throw `ConfigurationError`. Stage 3 wires per-instance\n * schema/validator selection off this field.\n *\n * Typed as `AdcpVersion | (string & {})` so editors autocomplete\n * canonical values from {@link COMPATIBLE_ADCP_VERSIONS} while still\n * accepting forward-compatible strings.\n */\n adcpVersion?: AdcpVersion | (string & {});\n\n /**\n * Resolve an account from an AccountReference.\n * Called on every request that has an `account` field.\n * Return null if the account doesn't exist — framework responds ACCOUNT_NOT_FOUND.\n *\n * The second argument carries the AdCP `toolName` and, when `serve()` is\n * configured with `authenticate`, the caller's `authInfo`. Adapters that\n * need the caller's upstream platform token to look up the account can\n * read it from `ctx.authInfo` here and attach anything they want to the\n * resolved account.\n *\n * Single-argument resolvers (`async (ref) => ...`) are valid — TypeScript\n * allows a shorter parameter list.\n *\n * **Do not persist `authInfo` outside the returned account object.** The\n * framework makes no isolation guarantees about values closed over by the\n * resolver; caching `authInfo` into shared state can leak the caller's\n * principal across requests.\n */\n resolveAccount?: (ref: AccountReference, ctx: ResolveAccountContext) => Promise<TAccount | null>;\n\n /**\n * Resolve an account when the wire request doesn't carry one.\n *\n * For tools whose request schema lacks an `account` field\n * (`provide_performance_feedback`, `list_creative_formats`, the\n * `tasks/get` polling path, etc.), the framework can't extract a wire\n * ref. When this resolver is configured, the framework calls it with the\n * caller's `authInfo` instead so single-tenant agents (`resolution: 'derived'`)\n * and principal-keyed agents (`resolution: 'implicit'`) still get a\n * tenant-scoped `ctx.account`.\n *\n * Returns `null` when no account can be derived. The handler then runs\n * with `ctx.account` undefined — appropriate for tools that legitimately\n * don't need tenant scoping (publisher-wide format catalogs).\n */\n resolveAccountFromAuth?: (ctx: ResolveAccountContext) => Promise<TAccount | null>;\n\n /**\n * Buyer-agent identity registry. Optional. When\n * configured, framework calls `agentRegistry.resolve(authInfo)` once per\n * request after `authInfo` is populated and before `resolveAccount`. The\n * resolved {@link BuyerAgent} is threaded through `ctx.agent` to\n * `resolveAccount`, `resolveAccountFromAuth`, `resolveSessionKey`, and\n * the specialism handlers.\n *\n * Adopters construct via {@link BuyerAgentRegistry.signingOnly},\n * {@link BuyerAgentRegistry.bearerOnly}, or {@link BuyerAgentRegistry.mixed}.\n * When omitted, `ctx.agent` stays `undefined` and the framework's request\n * flow is unchanged — strict opt-in.\n *\n * Behavior:\n * - Registry returns a `BuyerAgent` → framework freezes the record (and\n * its `billing_capabilities` Set) and sets `ctx.agent`.\n * - Registry returns `null` → `ctx.agent` stays undefined; dispatch\n * continues. For `sync_accounts.billing`, an unresolved agent under a\n * configured registry gets the oracle-safe `BILLING_NOT_SUPPORTED`\n * surface rather than `BILLING_NOT_PERMITTED_FOR_AGENT`.\n * - Registry throws → framework returns `SERVICE_UNAVAILABLE`. Inner\n * error logged server-side.\n *\n * Resolved records drive status/sandbox enforcement and\n * `sync_accounts.billing` capability gates.\n */\n agentRegistry?: BuyerAgentRegistry;\n\n /**\n * Derive a session-scoping key from the request. Populates `ctx.sessionKey`\n * so handlers don't re-implement key derivation (tenant, brand, publisher\n * account id, etc.). Called after `resolveAccount`, so the resolved account\n * is available.\n *\n * Return `undefined` to leave `ctx.sessionKey` unset (e.g., for anonymous\n * or public tools).\n */\n resolveSessionKey?: (ctx: SessionKeyContext<TAccount>) => string | undefined | Promise<string | undefined>;\n\n /**\n * When `true`, framework-produced `SERVICE_UNAVAILABLE` errors include the\n * underlying `err.message` in `details.reason` (helpful in dev, but can leak\n * DB driver messages, file paths, or schema info to remote callers).\n *\n * Defaults:\n * - `NODE_ENV === 'production'` → `false` (safe default for live agents).\n * - Otherwise → `true` (dev/test/CI surface the cause chain so\n * `SERVICE_UNAVAILABLE: encountered an internal error` becomes\n * `SERVICE_UNAVAILABLE: Cannot find module '@adcp/sdk/foo'`.\n * Matrix runs spent weeks on opaque SU errors before this default flipped).\n *\n * Explicit `exposeErrorDetails: true | false` always wins.\n */\n exposeErrorDetails?: boolean;\n\n /** Logger for framework decisions. Defaults to no-op. */\n logger?: AdcpLogger;\n\n /**\n * State store for persisting domain objects across requests.\n * Defaults to InMemoryStateStore. Use PostgresStateStore for production.\n */\n stateStore?: AdcpStateStore;\n\n /**\n * Task registry for async task lifecycle records.\n *\n * Usually supplied by `createAdcpServerFromPlatform`; low-level callers\n * only need this when they want `compliance.reset()` to flush in-memory\n * task records between repeated test runs.\n */\n taskRegistry?: TaskRegistry;\n\n // Domain handler groups — register only what you support\n mediaBuy?: MediaBuyHandlers<TAccount>;\n proposalNegotiation?: ProposalNegotiationHandlers<TAccount>;\n signals?: SignalsHandlers<TAccount>;\n creative?: CreativeHandlers<TAccount>;\n governance?: GovernanceHandlers<TAccount>;\n protocol?: ProtocolHandlers<TAccount>;\n accounts?: AccountHandlers<TAccount>;\n eventTracking?: EventTrackingHandlers<TAccount>;\n sponsoredIntelligence?: SponsoredIntelligenceHandlers<TAccount>;\n brandRights?: BrandRightsHandlers<TAccount>;\n\n /** Explicit capabilities overrides (merged on top of auto-detected). */\n capabilities?: AdcpCapabilitiesConfig;\n /**\n * Idempotency store for mutating requests. When configured, the framework:\n *\n * - Requires `idempotency_key` on every mutating request (returns\n * `INVALID_REQUEST` when missing)\n * - Replays the cached response for matching `(principal, key, payload)`\n * and injects `replayed: true` on the envelope\n * - Returns `IDEMPOTENCY_CONFLICT` for same-key-different-payload\n * - Returns `IDEMPOTENCY_EXPIRED` when the key is past the TTL\n * - Declares `adcp.idempotency.replay_ttl_seconds` on `get_adcp_capabilities`\n *\n * Scoping: by default uses `ctx.sessionKey` as the principal. Override\n * via `resolveIdempotencyPrincipal`.\n *\n * Pass the literal string `'disabled'` to suppress idempotency\n * enforcement end-to-end: schema validation tolerates a missing\n * `idempotency_key` on mutating tools, the replay/conflict middleware\n * is skipped, and the missing-store guardrail log is silenced. Intended\n * for non-production test fleets that don't model idempotency replay\n * — production servers should always wire a real store. The framework\n * logs an info-level warning at construction when this mode is used\n * outside `NODE_ENV=test` so the choice is visible.\n */\n idempotency?: IdempotencyStore | 'disabled';\n /**\n * Derive the idempotency principal from the handler context, the\n * request params, and the tool name. Defaults to `ctx.sessionKey`. Two\n * buyers that share a sessionKey would share cache entries — if that's\n * not what you want, return something more specific (e.g., an\n * operator_id) from this hook.\n *\n * Receives `params` and `toolName` so callers can fold request-shape\n * identity into the principal when needed (e.g., scoping by a custom\n * tenant header). For per-session scoping (`si_send_message`), the\n * framework already folds `params.session_id` into the scope tuple —\n * the principal is still the authenticated buyer.\n */\n resolveIdempotencyPrincipal?: (\n ctx: HandlerContext<TAccount>,\n params: IdempotencyPrincipalParams,\n toolName: AdcpServerToolName\n ) => string | undefined;\n /**\n * Server-level prose surfaced on MCP `initialize`. Two forms:\n *\n * 1. **Static string** (the historical form) — captured at construction,\n * same value for every session.\n * 2. **Function** `(ctx: SessionContext) => string | undefined` — re-evaluated\n * each time `createAdcpServer` is called. Under the canonical\n * `serve({ reuseAgent: false })` flow (the default) the factory\n * runs per HTTP request, which under streamable-HTTP MCP is per\n * session — so the closure can surface tenant-shaped prose (per-buyer\n * brand manifests, storefront copy, \"premium vs standard\" partner\n * guidance).\n *\n * **Eval moment.** Strictly: once per `createAdcpServer` invocation.\n * `serve({ reuseAgent: false })` makes that \"per HTTP request, which is\n * per session for streamable-HTTP MCP.\" Custom transports / hand-rolled\n * dispatch must invoke `createAdcpServer` per session themselves to\n * preserve the per-session semantic. `reuseAgent: true` would fire the\n * function once for the lifetime of the shared agent — which defeats\n * the purpose, so `serve()` refuses that combination at the first\n * request.\n *\n * **`SessionContext` is reserved.** `authInfo` and `agent` are typed for\n * forward compatibility but currently always `undefined` — the framework\n * does not yet plumb auth/registry state into the factory. **Use closures\n * captured in your factory's HTTP-scoped state for tenant identity today;\n * `ctx.agent`/`ctx.authInfo` reads silently return `undefined` and ship\n * empty prose to prod.** The function body will pick up populated fields\n * when the framework wires them through.\n *\n * @example Per-tenant prose via factory closure (recommended pattern):\n * ```ts\n * serve(({ taskStore, host }) => createAdcpServer({\n * // host is HTTP-scoped — captured in the closure, NOT from ctx.\n * instructions: () => brandManifests.get(host)?.intro ?? defaultProse,\n * // ... rest of config\n * }));\n * ```\n *\n * **Async functions are supported.** The framework awaits the returned\n * Promise during MCP `initialize` — the session does not proceed until\n * the promise settles. A slow fetch adds session-establishment latency,\n * not per-tool latency; add a timeout inside your function if needed\n * (e.g. `Promise.race([fetchProse(), timeout(2000)])`). A rejected\n * promise is governed by `onInstructionsError`: `'skip'` (default) logs\n * and sends no instructions; `'fail'` causes the `initialize` handshake\n * to fail, dropping the session.\n *\n * @see SessionContext\n * @see onInstructionsError\n */\n instructions?: string | ((ctx: SessionContext) => MaybePromise<string | undefined>);\n /**\n * Behavior when a function-form `instructions` callback throws. Defaults\n * to `'skip'` — best-effort prose (brand manifests, marketing copy)\n * should not kill the buyer's session on a registry fetch failure.\n * Set `'fail'` for adopters whose instructions carry load-bearing\n * policy. See {@link OnInstructionsError}.\n */\n onInstructionsError?: OnInstructionsError;\n taskStore?: TaskStore;\n taskMessageQueue?: TaskMessageQueue;\n /**\n * Webhook-emission config. When set, `ctx.emitWebhook` is populated on\n * every handler's context — handlers post signed, retried,\n * idempotency-stable webhooks without hand-rolling the pipeline. Omit\n * if your server never emits webhooks.\n *\n * Provide exactly one of `signerKey` (in-process JWK) or `signerProvider`\n * (KMS-backed async signing). The signing key or provider key SHOULD have\n * `adcp_use: \"request-signing\"`; the deprecated `\"webhook-signing\"` value is\n * accepted for compatibility. Publishers publishing\n * their JWKS at the `jwks_uri` on brand.json's `agents[]` entry reuse the\n * same key across every buyer they deliver to.\n */\n webhooks?: WebhooksConfig;\n /**\n * Optional callback that can mutate MCP tool responses before they are\n * returned. Runs for framework tools, custom tools, and generated discovery\n * responses registered by `createAdcpServer`.\n */\n responseEnhancer?: (response: McpToolResponse) => void;\n /**\n * Auto-wire the RFC 9421 request-signature verifier onto the HTTP transport.\n * When set together with `capabilities.specialisms` containing\n * `signed-requests`, `serve()` mounts the verifier as `preTransport` so\n * every inbound MCP request is verified before JSON-RPC dispatch. Setting\n * one without the other throws at construction time — the spec requires\n * the specialism claim and a working verifier to stay in lock-step.\n *\n * Omit entirely when the seller doesn't verify inbound signatures. Servers\n * that wire the verifier manually via `serve({ preTransport })` are\n * unaffected — auto-wiring only kicks in through this field.\n */\n signedRequests?: SignedRequestsConfig;\n\n /**\n * Schema-driven validation of requests and responses against the bundled\n * AdCP JSON schemas. When enabled, the dispatcher rejects bad requests\n * with `VALIDATION_ERROR` before the handler runs and catches drift in\n * handler-returned responses before they leave the server.\n *\n * Defaults:\n * - When `NODE_ENV === 'production'` → both sides `'off'` (zero overhead\n * in prod; trust the handler after its test suite has exercised it).\n * - Otherwise (dev, test, CI) → `responses: 'strict'`, `requests: 'warn'`.\n * Strict on responses turns handler-returned drift into a\n * `VALIDATION_ERROR` with the offending field path — surfaces the\n * \"handler returned a sparse object that fails the wire schema\" class\n * of bug at development time instead of letting it ship and surface\n * downstream as a cryptic `SERVICE_UNAVAILABLE` or `oneOf`\n * discriminator failure. Warn on requests logs incoming payloads that\n * don't match the bundled AdCP schema but still dispatches, so\n * upstream schema tightenings show up as diagnostics without breaking\n * clients that haven't caught up.\n *\n * Pass an explicit `validation: { requests: 'off', responses: 'off' }` to\n * override the dev-mode default. Set `responses: 'warn'` to keep the\n * logger diagnostic without failing the request — useful while\n * migrating a handler set from sparse fixtures to spec-compliant\n * responses. (The logger warning fires in both `'warn'` and `'strict'`\n * modes; `'strict'` additionally promotes the failure to a\n * `VALIDATION_ERROR` envelope.)\n *\n * Per-side modes:\n * - `requests: 'strict'` — reject malformed requests with VALIDATION_ERROR.\n * `'warn'` — log a warning, allow the handler to run.\n * `'off'` — skip.\n * - `responses: 'strict'` — handler-returned drift throws (dev/test canary).\n * `'warn'` — log a warning, return the response unchanged.\n * `'off'` — skip.\n *\n * Cost: one AJV compile per tool on cold start, one validator invocation\n * per call. The dev-mode default trades that for field-level diagnostics\n * when handlers drift from the wire contract.\n */\n validation?: {\n requests?: import('../validation/client-hooks').ValidationMode;\n responses?: import('../validation/client-hooks').ValidationMode;\n };\n\n /**\n * Reject buyer requests that smuggle credential-shaped keys through\n * the args bag. Closes the bug class observed in storefront fan-out\n * paths where keys like `<platform>_access_token` (top-level, in\n * `context`, or in `ext`) flow through to upstream calls under the\n * storefront's TLS / IP reputation — confused-deputy by default.\n *\n * Modes:\n * - `'lax'` (default) — no scan; preserves existing behavior.\n * - `'authInfo-only'` — scan args for credential-shaped keys at any\n * depth and reject with `INVALID_REQUEST`. Credentials must arrive\n * on `authInfo` (resolved by the framework's authenticator) and\n * never on the args bag.\n *\n * Pass the object form for pattern customization or per-tool overrides:\n *\n * ```ts\n * credentialPolicy: {\n * policy: 'authInfo-only',\n * patterns: { extend: [/^bearer$/i, /credentials/i] },\n * tools: { activate_signal: 'lax' }, // legitimate buyer-creds tool\n * }\n * ```\n *\n * Default patterns: `_access_token$`, `_secret$`, `_password$`,\n * `accessToken`, `refreshToken`. The next platform-specific vector\n * lives in adopter config, not in the SDK.\n *\n * @see {@link CredentialPolicy}\n * @see docs/guides/CTX-METADATA-SAFETY.md\n */\n credentialPolicy?: CredentialPolicy;\n\n /**\n * Register tools outside {@link AdcpToolMap}. Keys are the public tool\n * names; values follow {@link AdcpCustomToolConfig}.\n *\n * Gives sellers a declarative extension point without reaching for the\n * `getSdkServer()` escape hatch. Typical callers:\n *\n * - AdCP surfaces whose JSON Schemas haven't landed yet.\n * - Governance specialism helpers (`*_collection_list` family).\n * - Test-harness tools (`comply_test_controller` — prefer\n * {@link registerTestController} which wraps this).\n * - Seller-specific extensions outside the AdCP spec.\n *\n * **Custom tools bypass the framework's spec-tool pipeline.** No\n * idempotency middleware, no governance pre-check, no account\n * resolution, no response wrapping. The handler receives SDK-validated\n * args and must return a `CallToolResult`. Call framework helpers\n * (`checkGovernance`, `adcpError`, `capabilitiesResponse`, …) from\n * inside the handler if you need those behaviors.\n *\n * Name collisions with registered AdcpToolMap tools (from `mediaBuy`,\n * `signals`, `creative`, `governance`, `accounts`, `eventTracking`,\n * `sponsoredIntelligence`) or with `get_adcp_capabilities` throw at\n * construction time — the spec handler wins by convention.\n */\n customTools?: Record<string, AdcpCustomToolConfig<any, any>>;\n\n /**\n * Portable HTML MCP Apps served through standard MCP resources.\n *\n * Each definition is registered on both the legacy MCP server and every\n * modern per-request server reconstruction. A custom tool links to a\n * resource with `_meta.ui.resourceUri`; a startup warning identifies any\n * link whose URI is absent here. Hosts without MCP Apps support can ignore\n * the metadata and consume the tool's normal text result.\n */\n resources?: readonly AdcpMcpResourceDefinition[];\n\n /**\n * Opt-in bridge between the `comply_test_controller` seed store and the\n * spec-tool pipeline. When `getSeededProducts` is provided, seeded\n * products flow into `get_products` responses on sandbox requests — the\n * Group A compliance storyboards rely on this end-to-end flow.\n * Production traffic (no sandbox marker, or a resolved non-sandbox\n * account) bypasses the bridge entirely; omit the field in production\n * configs to be explicit about it.\n *\n * ## Do you need the bridge?\n *\n * The bridge is one of two mechanisms for closing the seed→read loop in\n * compliance testing. Pick by where your read handlers fetch from — not\n * by seller class:\n *\n * - **Handler reads from a store you control** (most SSPs, most\n * creative agents). `comply_test_controller.seed_product` writes to\n * your DB; your handler reads from your DB; the seed→read loop\n * closes naturally. **Don't wire the bridge** — test mode alone\n * covers you.\n * - **Handler reads from a system you don't control** (DSPs proxying\n * to Meta/Snap/TikTok, retail-media networks reading retailer\n * catalog APIs, signals agents brokering third-party data\n * marketplaces). `comply_test_controller.seed_product` is a dead\n * write for you because the handler will never see it. **Wire the\n * bridge.** The real handler still runs first (so a broken upstream\n * call still fails the conformance gate — adapter exercise is\n * preserved), and the SDK merges seeded fixtures into the response\n * after.\n *\n * Either path earns wire-conformance credit when storyboards pass; it\n * is *not* a separate certification category. Live-integration credit\n * requires marker-free passes against a real test surface (sandbox\n * credentials, real catalog data, real adapter traffic) — independent\n * of whether the bridge is wired. See `docs/guides/VALIDATE-YOUR-AGENT.md`\n * § \"Platform-proxy sellers\" for the wiring mechanics, and\n * [`adcp-client#1782`](https://github.com/adcontextprotocol/adcp-client/issues/1782)\n * plus the upstream taxonomy proposal at\n * [`adcontextprotocol/adcp#4593`](https://github.com/adcontextprotocol/adcp/issues/4593)\n * for the certification model under review.\n *\n * ## Security — trust boundary\n *\n * The bridge is gated by `isSandboxRequest(params) &&\n * isSandboxOrMockAccount(ctx.account)`. The resolved account is the\n * authority boundary; the first predicate is caller-supplied\n * (`account.sandbox` or `context.sandbox` on the request body) and is NOT\n * a trust boundary on its own. Requests without a resolved account fail\n * closed and never receive seeded fixtures.\n *\n * Production deployments that register `testController` MUST:\n * 1. Configure `resolveAccount` for account-bearing tools and\n * `resolveAccountFromAuth` for account-less tools so the framework\n * can prove the resolved account is `mode: 'sandbox' | 'mock'` (or\n * carries the legacy `sandbox: true` flag), or\n * 2. Omit `testController` entirely outside test / staging environments.\n *\n * The `createAdcpServerFromPlatform` flow already enforces this via the\n * sandbox-authority gate (see Phase 2 of #1435 — resolved-account `mode`\n * is the trust boundary, not buyer-supplied `account.sandbox`). The direct\n * `createAdcpServer` flow enforces the same resolved-account predicate;\n * adopters wiring the bridge here are responsible for providing both\n * resolver paths. See the top-of-file JSDoc on\n * `TestControllerBridge` for the full adopter-responsibility note (#1779).\n *\n * See `src/lib/server/test-controller-bridge.ts` for the sandbox-marker\n * predicate and the merge contract.\n *\n * @example\n * ```ts\n * import { createAdcpServer, bridgeFromTestControllerStore } from '@adcp/sdk/server/legacy/v5';\n *\n * const seedStore = new Map<string, unknown>();\n * const server = createAdcpServer({\n * resolveAccount: (ref, ctx) => accounts.resolve(ref, ctx),\n * resolveAccountFromAuth: ctx => accounts.resolve(undefined, ctx),\n * mediaBuy: { getProducts: handleGetProducts },\n * testController: bridgeFromTestControllerStore(seedStore, {\n * delivery_type: 'guaranteed',\n * channels: ['display'],\n * }),\n * });\n * ```\n */\n testController?: TestControllerBridge<TAccount>;\n}\n\n// ---------------------------------------------------------------------------\n// Tool metadata registry\n// ---------------------------------------------------------------------------\n\ninterface ToolAnnotation {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\ninterface ToolMeta {\n wrap: ((data: any, summary?: string) => McpToolResponse) | null;\n annotations?: ToolAnnotation;\n}\n\n/**\n * Deep-merge the per-domain blocks from `overrides` onto `target`. Nested\n * objects merge recursively; arrays and primitives replace. `null` at the\n * top-level field explicitly drops the block; `undefined` is a no-op.\n */\nfunction applyCapabilityOverrides(target: GetAdCPCapabilitiesResponse, overrides: AdcpCapabilitiesOverrides): void {\n const targetAny = target as unknown as Record<string, unknown>;\n const allowedKeys = new Set([\n 'media_buy',\n 'creative',\n 'signals',\n 'governance',\n 'brand',\n 'sponsored_intelligence',\n 'measurement',\n 'experimental_features',\n 'account',\n 'compliance_testing',\n 'webhook_signing',\n 'identity',\n 'request_signing',\n ]);\n for (const [key, value] of Object.entries(overrides)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `createAdcpServer: capabilities.overrides.${key} is not allowed. ` +\n 'Framework-owned capability fields must be configured through their dedicated options.'\n );\n }\n if (value === undefined) continue;\n if (value === null) {\n delete targetAny[key];\n continue;\n }\n targetAny[key] = deepMergePlainObjects(targetAny[key], value);\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (v === null || typeof v !== 'object') return false;\n if (Array.isArray(v)) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction hasInvalidGetProductsFinalizeIntent(toolName: string, params: Record<string, unknown>): boolean {\n if (toolName !== 'get_products') return false;\n if (isPlainObject(params.refine)) return params.refine.action === 'finalize';\n if (!Array.isArray(params.refine)) return false;\n const containsFinalize = params.refine.some(entry => isPlainObject(entry) && entry.action === 'finalize');\n if (!containsFinalize) return false;\n if (params.buying_mode !== 'refine') return true;\n // Finalize is exclusive: every entry must finalize a proposal. Multiple\n // proposal entries are valid and carry atomic multi-finalize semantics.\n return params.refine.some(\n entry =>\n !isPlainObject(entry) ||\n entry.action !== 'finalize' ||\n entry.scope !== 'proposal' ||\n typeof entry.proposal_id !== 'string' ||\n entry.proposal_id.length === 0\n );\n}\n\nfunction deepMergePlainObjects(target: unknown, source: unknown): unknown {\n if (source === undefined) return target;\n if (source === null) return null;\n if (!isPlainObject(source)) return source;\n if (!isPlainObject(target)) return { ...(source as Record<string, unknown>) };\n const out: Record<string, unknown> = { ...target };\n for (const [k, v] of Object.entries(source as Record<string, unknown>)) {\n if (v === undefined) continue;\n if (v === null) {\n delete out[k];\n continue;\n }\n out[k] = deepMergePlainObjects(out[k], v);\n }\n return out;\n}\n\n/**\n * Stamp `replayed: true` on the response envelope for replay paths only.\n * `protocol-envelope.json` permits the field to be \"omitted when the\n * request was executed fresh\" — fresh-path responses therefore carry no\n * `replayed` field, and the field's presence implies `true`. Buyers read\n * the field to distinguish cached replays from new executions for billing\n * and audit.\n *\n * Mirrors the marker into both L3 `structuredContent` and the L2\n * `content[0].text` JSON fallback so A2A/REST adapters that consume the\n * text body see the same envelope MCP does — matching the lockstep\n * pattern in `injectContextIntoResponse` / `sanitizeAdcpErrorEnvelope`.\n */\nfunction stampReplayed(response: McpToolResponse): void {\n if (!response.structuredContent || typeof response.structuredContent !== 'object') return;\n const sc = response.structuredContent as Record<string, unknown>;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.replayed = true;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\n/**\n * Shape of the `_bridge` marker stamped on responses where the\n * `testController` bridge merged seeded fixtures into the handler's reply.\n *\n * The marker is non-normative — every bridge-augmented response schema in\n * AdCP 3.0 allows additional top-level properties (verified across the 13\n * bridge-touching response schemas), and the underscore prefix advertises\n * \"internal / out-of-spec\" to validators that round-trip unknown fields.\n * Consumers (storyboard runners, compliance leaderboards, audit pipelines)\n * read this marker to distinguish \"this pass exercised the adopter's\n * adapter against upstream\" from \"this pass exercised wire conformance\n * against fixture data merged by the SDK\". See `adcp-client#1775` for the\n * cross-repo coordination context.\n *\n * ## Why on the response body, not MCP `_meta`?\n *\n * MCP defines `result._meta` as the canonical place for non-normative\n * server-side annotations, and `_meta` would be the textbook home for this\n * marker on MCP-only deployments. We put it on the response body instead\n * for three reasons:\n *\n * 1. **Cross-transport parity.** A2A has no `_meta` equivalent —\n * `structuredContent` passes through the A2A artifact pipeline\n * verbatim, but a hypothetical envelope-level marker would have to be\n * duplicated or lost. One wire location across both transports keeps\n * the storyboard runner's read logic uniform.\n * 2. **L2-text-body parity.** Buyers consuming the L2 text body (the\n * JSON-stringified `content[0].text`) see the same envelope MCP does,\n * because the opportunistic text-body mirror copies the marker into\n * both.\n * 3. **Precedent.** `replayed: true` already lives on the response body\n * via the same `stampReplayed` pattern this marker mirrors. Splitting\n * framework-emitted annotations across `_meta` and the body would\n * create two conventions for the same job.\n */\nexport interface BridgeMarker {\n /** Bridge callback that produced the seeded entries (e.g. `getSeededCreatives`). */\n callback: string;\n /** Tool name whose response was augmented (mirrors envelope context). */\n tool: string;\n /** Count of seeded entries the callback returned (post-validation). */\n merged_count: number;\n}\n\n/**\n * Stamp a non-normative `_bridge` marker on a response that the\n * `testController` bridge augmented with seeded fixtures.\n *\n * Mirrors {@link stampReplayed} — sets `_bridge` on `structuredContent`\n * AND on the parsed JSON in `content[0].text`, so A2A/REST adapters that\n * consume the text body see the same envelope MCP does.\n *\n * Only call this AFTER a successful merge — for singleton-replace tools\n * (`get_account_financials`, `get_brand_identity`, `si_get_offering`,\n * `get_property_list`, `get_collection_list`, `get_content_standards`)\n * gate on `merged !== sc` so the marker only fires when the seeded fixture\n * actually replaced the handler payload.\n */\nfunction stampBridge(response: McpToolResponse, callback: string, tool: string, mergedCount: number): void {\n if (!response.structuredContent || typeof response.structuredContent !== 'object') return;\n const marker: BridgeMarker = { callback, tool, merged_count: mergedCount };\n const sc = response.structuredContent as Record<string, unknown>;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc._bridge = marker;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\n/**\n * Remove per-request echo fields (`context`) from a formatted MCP response\n * before caching. The buyer's `correlation_id` is scoped to the individual\n * retry attempt and must not be baked into the cached envelope — replays\n * need to echo back the CURRENT retry's context, not the first caller's.\n * Other fields (media_buy_id, status, timestamps) are part of the pinned\n * response and stay put.\n */\nfunction stripEnvelopeEcho(response: McpToolResponse): McpToolResponse {\n const cloned = cloneFormattedResponse(response);\n if (cloned.structuredContent && typeof cloned.structuredContent === 'object') {\n const sc = cloned.structuredContent as Record<string, unknown>;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(cloned, sc);\n delete sc.context;\n syncContentJsonText(cloned, sc, mirrorsStructuredContent);\n }\n return cloned;\n}\n\n/**\n * Shallow-clone a formatted MCP response so callers can mutate envelope\n * fields (`replayed`, echo-back `context`) without stomping on the cache\n * entry. The backend returns a fresh object (memory clones, pg\n * serializes) but re-wrapping via `wrap()` can still alias pieces of the\n * handler's return value — belt-and-suspenders against mutation leaks.\n */\nfunction cloneFormattedResponse(response: McpToolResponse): McpToolResponse {\n const cloned: McpToolResponse = { ...response };\n if (cloned.structuredContent && typeof cloned.structuredContent === 'object') {\n cloned.structuredContent = { ...(cloned.structuredContent as Record<string, unknown>) };\n }\n if (Array.isArray(cloned.content)) {\n cloned.content = cloned.content.map(item => ({ ...item }));\n }\n return cloned;\n}\n\n/**\n * Detect whether a formatted MCP response represents a failure. Failures\n * are NOT cached — a retry should re-execute rather than replay a\n * transient error. Checks all three shapes the framework emits:\n * `isError: true`, `structuredContent.adcp_error`, or envelope\n * `status: 'failed'` (the envelope example in the spec for failed async\n * tasks doesn't always include `adcp_error`).\n */\nfunction isErrorResponse(response: McpToolResponse): boolean {\n if (response.isError === true) return true;\n const sc = response.structuredContent;\n if (sc && typeof sc === 'object') {\n if ('adcp_error' in sc) return true;\n const status = (sc as Record<string, unknown>).status;\n if (status === 'failed' || status === 'canceled' || status === 'rejected') return true;\n }\n return false;\n}\n\nconst UNCACHEABLE_SYNC_ACCOUNT_ERROR_CODES = new Set([\n 'BILLING_NOT_SUPPORTED',\n 'BILLING_NOT_PERMITTED_FOR_AGENT',\n 'PAYMENT_TERMS_NOT_SUPPORTED',\n]);\n\nfunction hasUncacheableSyncAccountRejection(response: McpToolResponse): boolean {\n const sc = response.structuredContent;\n if (!sc || typeof sc !== 'object') return false;\n const accounts = (sc as Record<string, unknown>).accounts;\n if (!Array.isArray(accounts)) return false;\n return accounts.some(row => {\n if (!row || typeof row !== 'object') return false;\n const record = row as Record<string, unknown>;\n if (record.status !== 'rejected' && record.action !== 'failed') return false;\n const errors = record.errors;\n if (!Array.isArray(errors)) return false;\n return errors.some(error => {\n if (!error || typeof error !== 'object') return false;\n return UNCACHEABLE_SYNC_ACCOUNT_ERROR_CODES.has(String((error as Record<string, unknown>).code));\n });\n });\n}\n\nfunction shouldCacheIdempotencyResponse(response: McpToolResponse): boolean {\n return !isErrorResponse(response) && !hasUncacheableSyncAccountRejection(response);\n}\n\n/**\n * Detect a thrown `adcpError(...)` envelope. Handlers that `throw` an\n * envelope (instead of `return`-ing it) would otherwise surface as\n * `[object Object]` inside a SERVICE_UNAVAILABLE wrapper — the dispatcher\n * unwraps and returns the envelope directly when the shape matches.\n */\n/**\n * Project a thrown {@link AdcpError} to the wire envelope. Used by the\n * account-resolution and tool-handler catch blocks so adopters can throw\n * typed errors at any depth and have the framework project the structured\n * fields verbatim — without coercion to `SERVICE_UNAVAILABLE`. Mirrors the\n * `isThrownAdcpError` unwrap, but for the in-process class throw rather\n * than the already-projected envelope throw.\n */\nfunction projectThrownAdcpError(err: AdcpError): McpToolResponse {\n return adcpError(err.code, {\n recovery: err.recovery,\n message: err.message,\n ...(err.field !== undefined && { field: err.field }),\n ...(err.suggestion !== undefined && { suggestion: err.suggestion }),\n ...(err.retry_after !== undefined && { retry_after: err.retry_after }),\n ...(err.details !== undefined && { details: err.details }),\n });\n}\n\nfunction isThrownAdcpError(value: unknown): value is McpToolResponse {\n if (!value || typeof value !== 'object') return false;\n const sc = (value as { structuredContent?: unknown }).structuredContent;\n if (!sc || typeof sc !== 'object') return false;\n const env = (sc as { adcp_error?: unknown }).adcp_error;\n if (!env || typeof env !== 'object') return false;\n // `adcpError()` guarantees both `code` and `message` as strings — assert\n // both so a malformed envelope throw doesn't produce a half-formed\n // response. Also rules out MCP SDK `McpError` (numeric `code`) and any\n // other thrown object with a coincidentally-shaped sub-tree.\n if (typeof (env as { code?: unknown }).code !== 'string') return false;\n if (typeof (env as { message?: unknown }).message !== 'string') return false;\n return Array.isArray((value as { content?: unknown }).content) && (value as { isError?: unknown }).isError === true;\n}\n\nfunction thrownAdcpErrorRecovery(response: McpToolResponse): ErrorRecovery {\n const error = (response.structuredContent as { adcp_error: { code: string; recovery?: unknown } }).adcp_error;\n if (isStandardErrorCode(error.code)) {\n return STANDARD_ERROR_CODES[error.code].recovery;\n }\n if (error.recovery === 'transient' || error.recovery === 'correctable' || error.recovery === 'terminal') {\n return error.recovery;\n }\n return DEFAULT_UNKNOWN_ERROR_RECOVERY;\n}\n\n/**\n * Resolve the framework-owned cache namespace for a concrete mutation.\n *\n * Existing tools retain their SDK 13 scope so an in-flight mutation cannot\n * miss its replay record during a rolling upgrade. The new get_products\n * finalize path adds trusted session/account identity; other tool/session\n * special cases preserve their established scopes.\n */\nfunction resolveExtraScope(\n toolName: string,\n params: Record<string, unknown>,\n account?: unknown,\n sessionKey?: string,\n proposalScope?: Readonly<ProposalRefinementScope>,\n callerMutationScope?: Readonly<CallerMutationScope>\n): string | undefined {\n const accountLike = account as\n | { id?: unknown; account_id?: unknown; tenant_id?: unknown; tenantId?: unknown }\n | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const tenantId =\n typeof accountLike?.tenant_id === 'string'\n ? accountLike.tenant_id\n : typeof accountLike?.tenantId === 'string'\n ? accountLike.tenantId\n : undefined;\n if (CALLER_SCOPED_MUTATION_TOOLS.has(toolName) && callerMutationScope) {\n return JSON.stringify([\n callerMutationScope.tenant_id,\n callerMutationScope.principal_id,\n callerMutationScope.account_id ?? null,\n ]);\n }\n if (toolName === 'si_send_message') {\n const sessionId = params.session_id;\n return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined;\n }\n if (toolName === 'refine_proposals' && proposalScope) {\n // The proposal namespace is framework-owned trusted context. Keep the\n // complete tuple in the replay scope so one authenticated principal\n // cannot replay a response across tenant or account boundaries.\n return JSON.stringify([proposalScope.tenant_id, proposalScope.principal_id, proposalScope.account_id ?? null]);\n }\n if (toolName === 'get_products') {\n return JSON.stringify([sessionKey ?? null, tenantId ?? null, accountId ?? null]);\n }\n return undefined;\n}\n\nfunction buildIdempotencyPayload(\n toolName: string,\n params: Record<string, unknown>,\n account?: unknown,\n sessionKey?: string\n): readonly unknown[] {\n const accountLike = account as\n | { id?: unknown; account_id?: unknown; tenant_id?: unknown; tenantId?: unknown }\n | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const tenantId =\n typeof accountLike?.tenant_id === 'string'\n ? accountLike.tenant_id\n : typeof accountLike?.tenantId === 'string'\n ? accountLike.tenantId\n : undefined;\n // Keep framework identity in the canonical payload hash rather than\n // changing the established cache key. The tuple root is deliberately\n // impossible for an SDK 13 entry: legacy dispatch always hashed the\n // object-shaped tool arguments directly. Unknown request fields therefore\n // cannot forge these trusted discriminators. A legacy entry yields\n // IDEMPOTENCY_CONFLICT after upgrade instead of a cache miss and duplicate\n // execution; new entries cannot replay across tools or tenants.\n return [\n '@adcp/sdk-idempotency/v2',\n toolName,\n [sessionKey ?? null, tenantId ?? null, accountId ?? null],\n hashPayload(params),\n ] as const;\n}\n\nfunction genericResponse(toolName: string, data: object, summary?: string): McpToolResponse {\n const structuredContent = { ...toStructuredContent(data) };\n if (STATUS_FREE_SYNC_RESPONSE_TOOLS.has(toolName)) delete structuredContent.status;\n return {\n content: [{ type: 'text', text: summary ?? `${toolName} completed` }],\n structuredContent,\n };\n}\n\nconst ADCP_TASK_TYPES = new Set<TaskType>(TaskTypeValues);\n\nfunction readRegistryTaskType(task: TaskRecord): TaskType | undefined {\n return ADCP_TASK_TYPES.has(task.tool as TaskType) ? (task.tool as TaskType) : undefined;\n}\n\nfunction toProtocolTaskStatus(task: TaskRecord): GetTaskStatusResponse | undefined {\n const taskType = readRegistryTaskType(task);\n if (taskType === undefined) return undefined;\n const protocol = protocolForTool(taskType) as WireAdcpProtocol;\n return {\n task_id: task.taskId,\n task_type: taskType,\n protocol,\n status: task.status as TaskStatus,\n created_at: task.createdAt,\n updated_at: task.updatedAt,\n ...(task.status === 'completed' || task.status === 'failed' || task.status === 'canceled'\n ? { completed_at: task.updatedAt }\n : {}),\n ...(task.hasWebhook !== undefined ? { has_webhook: task.hasWebhook === true } : {}),\n ...(task.progress !== undefined ? { progress: task.progress } : {}),\n ...(task.error !== undefined\n ? { error: sanitizeStructuredAdcpError(task.error) as GetTaskStatusResponse['error'] }\n : task.statusMessage !== undefined\n ? {\n error: {\n code: task.status === 'failed' ? 'TASK_FAILED' : 'TASK_STATUS_MESSAGE',\n message: task.statusMessage,\n },\n }\n : {}),\n };\n}\n\nfunction toProtocolTaskListItem(task: TaskRecord): ListTasksResponse['tasks'][number] | undefined {\n const taskType = readRegistryTaskType(task);\n if (taskType === undefined) return undefined;\n const protocol = protocolForTool(taskType) as WireAdcpProtocol;\n return {\n task_id: task.taskId,\n task_type: taskType,\n domain: protocol === 'signals' || protocol === 'creative' ? protocol : 'media-buy',\n status: task.status as TaskStatus,\n created_at: task.createdAt,\n updated_at: task.updatedAt,\n ...(task.status === 'completed' || task.status === 'failed' || task.status === 'canceled'\n ? { completed_at: task.updatedAt }\n : {}),\n ...(task.hasWebhook !== undefined ? { has_webhook: task.hasWebhook === true } : {}),\n };\n}\n\nfunction appendSearchableTaskValue(values: string[], value: unknown): void {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n values.push(String(value));\n }\n}\n\nfunction appendSearchableResultIdentifiers(values: string[], value: unknown, depth = 0): void {\n if (depth > 3 || value == null || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const item of value) appendSearchableResultIdentifiers(values, item, depth + 1);\n return;\n }\n if (!isPlainObject(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (/(^|_)(id|ids|ref|refs)$/.test(key)) {\n if (Array.isArray(child)) {\n for (const item of child) appendSearchableTaskValue(values, item);\n } else {\n appendSearchableTaskValue(values, child);\n }\n }\n if (child != null && typeof child === 'object') {\n appendSearchableResultIdentifiers(values, child, depth + 1);\n }\n }\n}\n\nfunction taskSearchHaystack(task: TaskRecord, item: ListTasksResponse['tasks'][number]): string {\n const values = [item.task_id, item.task_type, item.status, item.domain, task.accountId];\n appendSearchableResultIdentifiers(values, task.result);\n appendSearchableResultIdentifiers(values, task.progress);\n return values.join('\\n');\n}\n\nfunction taskMatchesFilters(task: TaskRecord, filters: ListTasksRequest['filters']): boolean {\n if (!isPlainObject(filters)) return true;\n const item = toProtocolTaskListItem(task);\n if (item === undefined) return false;\n const protocol = protocolForTool(item.task_type) as WireAdcpProtocol;\n if (typeof filters.protocol === 'string' && protocol !== filters.protocol) return false;\n if (Array.isArray(filters.protocols) && !filters.protocols.includes(protocol)) return false;\n if (typeof filters.status === 'string' && item.status !== filters.status) return false;\n if (Array.isArray(filters.statuses) && !filters.statuses.includes(item.status)) return false;\n if (typeof filters.task_type === 'string' && item.task_type !== filters.task_type) return false;\n if (Array.isArray(filters.task_types) && !filters.task_types.includes(item.task_type)) return false;\n if (Array.isArray(filters.task_ids) && !filters.task_ids.includes(item.task_id)) return false;\n if (!taskTimestampMatches(item.created_at, filters.created_after, 'after')) return false;\n if (!taskTimestampMatches(item.created_at, filters.created_before, 'before')) return false;\n if (!taskTimestampMatches(item.updated_at, filters.updated_after, 'after')) return false;\n if (!taskTimestampMatches(item.updated_at, filters.updated_before, 'before')) return false;\n if (typeof filters.has_webhook === 'boolean' && (task.hasWebhook === true) !== filters.has_webhook) return false;\n if (typeof filters.context_contains === 'string' && filters.context_contains.length > 0) {\n if (!taskSearchHaystack(task, item).includes(filters.context_contains)) return false;\n }\n return true;\n}\n\nfunction taskTimestampMatches(value: string, boundary: unknown, direction: 'after' | 'before'): boolean {\n if (typeof boundary !== 'string') return true;\n const valueMs = Date.parse(value);\n const boundaryMs = Date.parse(boundary);\n if (!Number.isFinite(valueMs) || !Number.isFinite(boundaryMs)) return false;\n return direction === 'after' ? valueMs > boundaryMs : valueMs < boundaryMs;\n}\n\nfunction taskBelongsToCaller(task: TaskRecord, accountId: string, ownerScope: string | undefined): boolean {\n if (task.accountId !== accountId) return false;\n if (ownerScope === undefined) return false;\n if (task.ownerScope === undefined) return ownerScope === `account:${accountId}`;\n return task.ownerScope === ownerScope;\n}\n\nfunction authenticatedPrincipalForContext(\n authInfo: ResolvedAuthInfo | undefined,\n agent: BuyerAgent | undefined\n): string | undefined {\n if (agent?.agent_url) return `agent:${agent.agent_url}`;\n const credential = authInfo?.credential;\n if (credential?.kind === 'http_sig') return `http_sig:${credential.agent_url}`;\n if (credential?.kind === 'oauth') return `oauth:${credential.client_id}`;\n if (credential?.kind === 'api_key') return `api_key:${credential.key_id}`;\n if (typeof authInfo?.clientId === 'string' && authInfo.clientId.length > 0) return `client:${authInfo.clientId}`;\n return undefined;\n}\n\nfunction taskOwnerScopeForContext(\n authInfo: ResolvedAuthInfo | undefined,\n sessionKey: string | undefined,\n agent: BuyerAgent | undefined,\n accountId: string\n): string {\n if (sessionKey !== undefined) return `session:${sessionKey}`;\n if (agent?.agent_url) return `agent:${agent.agent_url}`;\n const credential = authInfo?.credential;\n if (credential?.kind === 'http_sig') return `http_sig:${credential.agent_url}`;\n if (credential?.kind === 'oauth') return `oauth:${credential.client_id}`;\n if (credential?.kind === 'api_key') return `api_key:${credential.key_id}`;\n if (typeof authInfo?.clientId === 'string' && authInfo.clientId.length > 0) return `client:${authInfo.clientId}`;\n return `account:${accountId}`;\n}\n\n/**\n * Build the webhook delivery-store tenant namespace exclusively from trusted,\n * resolved server context. Webhook payload and request-body delivery fields\n * never participate, so one tenant cannot preclaim another tenant's delivery\n * binding in a shared durable store.\n */\nfunction webhookTenantScopeForContext<TAccount>(ctx: HandlerContext<TAccount>): string | undefined {\n if (ctx.callerMutationScope) {\n return JSON.stringify([\n 'caller',\n ctx.callerMutationScope.tenant_id,\n ctx.callerMutationScope.principal_id,\n ctx.callerMutationScope.account_id ?? null,\n ]);\n }\n const accountLike = ctx.account as\n | { id?: unknown; account_id?: unknown; tenant_id?: unknown; tenantId?: unknown }\n | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const tenantId =\n typeof accountLike?.tenant_id === 'string'\n ? accountLike.tenant_id\n : typeof accountLike?.tenantId === 'string'\n ? accountLike.tenantId\n : undefined;\n const principal = authenticatedPrincipalForContext(ctx.authInfo, ctx.agent);\n if (ctx.sessionKey !== undefined) {\n return JSON.stringify(['session', ctx.sessionKey, tenantId ?? null, accountId ?? null, principal ?? null]);\n }\n if (tenantId !== undefined || accountId !== undefined) {\n return JSON.stringify(['account', tenantId ?? null, accountId ?? null, principal ?? null]);\n }\n if (principal !== undefined) return JSON.stringify(['principal', principal]);\n return undefined;\n}\n\nfunction compareProtocolTaskItems(\n left: ListTasksResponse['tasks'][number],\n right: ListTasksResponse['tasks'][number],\n sort: ListTasksRequest['sort']\n): number {\n const field = isPlainObject(sort) && typeof sort.field === 'string' ? sort.field : 'created_at';\n const direction = isPlainObject(sort) && sort.direction === 'asc' ? 'asc' : 'desc';\n const multiplier = direction === 'asc' ? 1 : -1;\n let result = 0;\n if (field === 'updated_at') result = left.updated_at.localeCompare(right.updated_at);\n else if (field === 'status') result = left.status.localeCompare(right.status);\n else if (field === 'task_type') result = left.task_type.localeCompare(right.task_type);\n else if (field === 'protocol') {\n const leftProtocol = protocolForTool(left.task_type);\n const rightProtocol = protocolForTool(right.task_type);\n result = leftProtocol.localeCompare(rightProtocol);\n } else {\n result = left.created_at.localeCompare(right.created_at);\n }\n return result === 0 ? left.task_id.localeCompare(right.task_id) * multiplier : result * multiplier;\n}\n\nfunction parseTaskListCursor(cursor: unknown): number | undefined {\n if (cursor === undefined) return undefined;\n if (typeof cursor !== 'string' || !/^(0|[1-9]\\d*)$/.test(cursor)) {\n throw new Error('Invalid task list cursor');\n }\n return Number.parseInt(cursor, 10);\n}\n\nfunction taskListPageSize(pagination: unknown): number {\n if (!isPlainObject(pagination) || typeof pagination.max_results !== 'number') return 50;\n return Math.min(Math.max(Math.floor(pagination.max_results), 1), 100);\n}\n\nfunction wrapBuildCreative(data: any, summary?: string): McpToolResponse {\n if ('creative_manifests' in data) {\n return buildCreativeMultiResponse(data, summary);\n }\n return buildCreativeResponse(data, summary);\n}\n\n// Shorthand annotation constants\nconst RO: ToolAnnotation = { readOnlyHint: true };\nconst MUT: ToolAnnotation = { readOnlyHint: false, destructiveHint: false };\nconst DEST: ToolAnnotation = { readOnlyHint: false, destructiveHint: true };\nconst IDEMP: ToolAnnotation = { readOnlyHint: false, idempotentHint: true };\n\n// Passthrough schema for framework-registered tools by default (#909). See\n// the comment at the registerTool call sites for rationale — short version:\n// makes our AJV validator authoritative on both transports without destroying\n// args on MCP when the SDK's tool dispatcher would otherwise coerce\n// `undefined` into the handler for schemaless tools. Servers can opt into\n// shallow MCP discovery hints derived from `TOOL_INPUT_SHAPES` with\n// config.exposeToolSchemas.\nconst PASSTHROUGH_INPUT_SCHEMA = z.object({}).passthrough();\ntype ToolInputShapeMap = Readonly<Record<string, ZodRawShapeCompat | undefined>>;\nlet cachedToolInputShapes: ToolInputShapeMap | undefined;\nconst SHALLOW_HINT_FIELD_SCHEMA = z.unknown().optional();\nconst SHALLOW_HINT_SCHEMAS = new Map<string, AnySchema>();\nconst REFINE_PROPOSALS_INPUT_SHAPE = {\n idempotency_key: SHALLOW_HINT_FIELD_SCHEMA,\n refinements: SHALLOW_HINT_FIELD_SCHEMA,\n context_id: SHALLOW_HINT_FIELD_SCHEMA,\n context: SHALLOW_HINT_FIELD_SCHEMA,\n governance_context: SHALLOW_HINT_FIELD_SCHEMA,\n push_notification_config: SHALLOW_HINT_FIELD_SCHEMA,\n adcp_version: SHALLOW_HINT_FIELD_SCHEMA,\n adcp_major_version: SHALLOW_HINT_FIELD_SCHEMA,\n} as unknown as ZodRawShapeCompat;\n\nfunction getToolInputShapes(): ToolInputShapeMap {\n cachedToolInputShapes ??= TOOL_INPUT_SHAPES as unknown as ToolInputShapeMap;\n return cachedToolInputShapes;\n}\n\nfunction shallowToolInputHintSchema(toolName: string): AnySchema | undefined {\n const inputShape = toolName === 'refine_proposals' ? REFINE_PROPOSALS_INPUT_SHAPE : getToolInputShapes()[toolName];\n if (inputShape === undefined) return undefined;\n\n const cached = SHALLOW_HINT_SCHEMAS.get(toolName);\n if (cached !== undefined) return cached;\n\n const hintShape = Object.fromEntries(Object.keys(inputShape).map(key => [key, SHALLOW_HINT_FIELD_SCHEMA]));\n const schema = z.object(hintShape).passthrough();\n SHALLOW_HINT_SCHEMAS.set(toolName, schema);\n return schema;\n}\n\nfunction validateFrameworkPayload(\n toolName: string,\n direction: 'request' | 'response',\n payload: unknown,\n version: Parameters<typeof validateRequest>[2],\n proposalCapabilities?: ProposalRefinementCapabilities\n) {\n if (toolName !== 'refine_proposals') {\n return direction === 'request'\n ? validateRequest(toolName, payload, version)\n : validateResponse(toolName, payload, version);\n }\n if (direction === 'request') {\n try {\n validateRefineProposalsRequest(payload as RefineProposalsRequest, proposalCapabilities);\n return {\n valid: true as const,\n issues: [] as ValidationIssue[],\n schemaId: '/schemas/media-buy/refine-proposals-request.json',\n variant: undefined,\n };\n } catch (error) {\n const refinementError =\n error instanceof ProposalRefinementValidationError\n ? error\n : new ProposalRefinementValidationError(\n error instanceof Error ? error.message : 'invalid refine_proposals request'\n );\n return {\n valid: false as const,\n refinementError,\n issues: [\n {\n pointer: fieldPathToPointer(refinementError.field),\n message: refinementError.message,\n keyword: 'validation',\n schemaPath: '#/local/validation',\n schemaId: '/schemas/media-buy/refine-proposals-request.json',\n },\n ],\n schemaId: '/schemas/media-buy/refine-proposals-request.json',\n variant: undefined,\n };\n }\n }\n const verification = validateRefineProposalsResponseShape(payload);\n if (verification.ok) {\n return {\n valid: true as const,\n issues: [] as ValidationIssue[],\n schemaId: '/schemas/media-buy/refine-proposals-response.json',\n variant: undefined,\n };\n }\n const issues: ValidationIssue[] = verification.issues.map(issue => ({\n pointer: fieldPathToPointer(issue.path),\n message: issue.message,\n keyword: issue.code,\n schemaPath: `#/local/${issue.code}`,\n schemaId: '/schemas/media-buy/refine-proposals-response.json',\n }));\n return {\n valid: false as const,\n issues,\n schemaId: '/schemas/media-buy/refine-proposals-response.json',\n variant: undefined,\n };\n}\n\nfunction fieldPathToPointer(path: string | undefined): string {\n if (!path) return '';\n const segments = path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter(Boolean);\n return `/${segments.map(segment => segment.replaceAll('~', '~0').replaceAll('/', '~1')).join('/')}`;\n}\n\nconst TOOL_META: Record<string, ToolMeta> = {\n // Media Buy\n list_products: { wrap: null, annotations: RO },\n request_proposals: { wrap: null, annotations: IDEMP },\n refine_proposals: { wrap: null, annotations: IDEMP },\n decline_proposals: { wrap: null, annotations: IDEMP },\n buy_products: { wrap: null, annotations: IDEMP },\n accept_proposal: { wrap: null, annotations: IDEMP },\n control_media_buy: { wrap: null, annotations: IDEMP },\n get_products: { wrap: productsResponse, annotations: RO },\n create_media_buy: { wrap: mediaBuyResponse, annotations: MUT },\n update_media_buy: { wrap: updateMediaBuyResponse, annotations: MUT },\n get_media_buys: { wrap: getMediaBuysResponse, annotations: RO },\n get_media_buy_delivery: { wrap: deliveryResponse, annotations: RO },\n provide_performance_feedback: { wrap: performanceFeedbackResponse, annotations: MUT },\n\n // Protocol\n get_task_status: { wrap: null, annotations: RO },\n list_tasks: { wrap: null, annotations: RO },\n sync_agent_notification_configs: { wrap: null, annotations: IDEMP },\n\n // Creative\n list_creative_formats: { wrap: listCreativeFormatsResponse, annotations: RO },\n list_transformers: { wrap: null, annotations: RO },\n build_creative: { wrap: wrapBuildCreative, annotations: MUT },\n preview_creative: { wrap: null, annotations: RO },\n get_creative_delivery: { wrap: creativeDeliveryResponse, annotations: RO },\n list_creatives: { wrap: listCreativesResponse, annotations: RO },\n sync_creatives: { wrap: syncCreativesResponse, annotations: IDEMP },\n\n // Signals\n get_signals: { wrap: getSignalsResponse, annotations: RO },\n activate_signal: { wrap: activateSignalResponse, annotations: MUT },\n\n // Accounts\n list_accounts: { wrap: listAccountsResponse, annotations: RO },\n sync_accounts: { wrap: syncAccountsResponse, annotations: IDEMP },\n sync_governance: { wrap: syncGovernanceResponse, annotations: IDEMP },\n get_account_financials: { wrap: null, annotations: RO },\n report_usage: { wrap: reportUsageResponse, annotations: MUT },\n\n // Event Tracking\n sync_event_sources: { wrap: null, annotations: IDEMP },\n log_event: { wrap: null, annotations: MUT },\n\n // Audiences & Catalogs\n sync_audiences: { wrap: null, annotations: IDEMP },\n sync_catalogs: { wrap: null, annotations: IDEMP },\n\n // Governance - Property Lists\n create_property_list: { wrap: null, annotations: MUT },\n update_property_list: { wrap: null, annotations: MUT },\n get_property_list: { wrap: null, annotations: RO },\n list_property_lists: { wrap: null, annotations: RO },\n delete_property_list: { wrap: null, annotations: DEST },\n\n // Governance - Collection Lists\n create_collection_list: { wrap: null, annotations: MUT },\n update_collection_list: { wrap: null, annotations: MUT },\n get_collection_list: { wrap: null, annotations: RO },\n list_collection_lists: { wrap: null, annotations: RO },\n delete_collection_list: { wrap: null, annotations: DEST },\n\n // Governance - Content Standards\n list_content_standards: { wrap: null, annotations: RO },\n get_content_standards: { wrap: null, annotations: RO },\n create_content_standards: { wrap: null, annotations: MUT },\n update_content_standards: { wrap: null, annotations: MUT },\n calibrate_content: { wrap: null, annotations: MUT },\n validate_content_delivery: { wrap: null, annotations: RO },\n get_media_buy_artifacts: { wrap: null, annotations: RO },\n\n // Governance - Campaign\n get_creative_features: { wrap: null, annotations: RO },\n sync_plans: { wrap: null, annotations: IDEMP },\n check_governance: { wrap: null, annotations: RO },\n report_plan_outcome: { wrap: null, annotations: MUT },\n report_plan_adjustment: { wrap: null, annotations: IDEMP },\n get_plan_audit_logs: { wrap: null, annotations: RO },\n\n // Sponsored Intelligence\n si_get_offering: { wrap: null, annotations: RO },\n si_initiate_session: { wrap: null, annotations: MUT },\n si_send_message: { wrap: null, annotations: MUT },\n si_terminate_session: { wrap: null, annotations: DEST },\n\n // Brand Rights\n get_brand_identity: { wrap: null, annotations: RO },\n get_rights: { wrap: null, annotations: RO },\n acquire_rights: { wrap: acquireRightsResponse, annotations: MUT },\n update_rights: { wrap: updateRightsResponse, annotations: MUT },\n};\n\nconst CALLER_SCOPED_MUTATION_TOOLS = new Set(['sync_agent_notification_configs', 'report_plan_adjustment']);\n\nconst COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS = [\n 'list_products',\n 'request_proposals',\n 'refine_proposals',\n 'decline_proposals',\n 'buy_products',\n 'accept_proposal',\n 'control_media_buy',\n] as const;\n\ntype ProjectionSchema = Record<string, unknown>;\n\nconst OMIT_PROJECTED_VALUE = Symbol('omit-projected-value');\n\nfunction asProjectionSchema(value: unknown): ProjectionSchema | undefined {\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction resolveLocalProjectionRef(root: ProjectionSchema, schema: ProjectionSchema): ProjectionSchema {\n const ref = schema.$ref;\n if (typeof ref !== 'string' || !ref.startsWith('#/')) return schema;\n let current: unknown = root;\n for (const encodedSegment of ref.slice(2).split('/')) {\n if (!isPlainObject(current)) return schema;\n const segment = encodedSegment.replace(/~1/g, '/').replace(/~0/g, '~');\n current = current[segment];\n }\n return asProjectionSchema(current) ?? schema;\n}\n\nfunction projectionDiscriminatorMatch(\n root: ProjectionSchema,\n schema: ProjectionSchema,\n value: unknown\n): boolean | undefined {\n if (!isPlainObject(value)) return undefined;\n const resolved = resolveLocalProjectionRef(root, schema);\n const properties = asProjectionSchema(resolved.properties);\n if (!properties) return undefined;\n let found = false;\n for (const [key, propertySchemaValue] of Object.entries(properties)) {\n const propertySchema = asProjectionSchema(propertySchemaValue);\n if (!propertySchema || !Object.hasOwn(propertySchema, 'const')) continue;\n found = true;\n if (value[key] !== propertySchema.const) return false;\n }\n return found ? true : undefined;\n}\n\nfunction collectProjectionSchemas(\n root: ProjectionSchema,\n schema: ProjectionSchema,\n value: unknown,\n depth = 0\n): ProjectionSchema[] {\n if (depth > 64) return [];\n const resolved = resolveLocalProjectionRef(root, schema);\n const schemas: ProjectionSchema[] = [resolved];\n for (const keyword of ['allOf'] as const) {\n const branches = resolved[keyword];\n if (!Array.isArray(branches)) continue;\n for (const branch of branches) {\n const branchSchema = asProjectionSchema(branch);\n if (branchSchema) schemas.push(...collectProjectionSchemas(root, branchSchema, value, depth + 1));\n }\n }\n for (const keyword of ['oneOf', 'anyOf'] as const) {\n const branches = resolved[keyword];\n if (!Array.isArray(branches)) continue;\n const branchSchemas = branches.map(asProjectionSchema).filter((branch): branch is ProjectionSchema => !!branch);\n const matched = branchSchemas.filter(branch => projectionDiscriminatorMatch(root, branch, value) === true);\n const selected = matched.length > 0 ? matched : branchSchemas;\n for (const branch of selected) {\n schemas.push(...collectProjectionSchemas(root, branch, value, depth + 1));\n }\n }\n return schemas;\n}\n\nfunction projectValueToCapabilitySchema(\n root: ProjectionSchema,\n schema: ProjectionSchema,\n value: unknown,\n depth = 0\n): unknown | typeof OMIT_PROJECTED_VALUE {\n if (depth > 64) return OMIT_PROJECTED_VALUE;\n const schemas = collectProjectionSchemas(root, schema, value, depth);\n\n const allowedValues = schemas.flatMap(candidate => (Array.isArray(candidate.enum) ? candidate.enum : []));\n if (allowedValues.length > 0 && !allowedValues.some(allowed => Object.is(allowed, value))) {\n return OMIT_PROJECTED_VALUE;\n }\n const constants = schemas.filter(candidate => Object.hasOwn(candidate, 'const')).map(candidate => candidate.const);\n if (constants.length > 0 && !constants.some(constant => Object.is(constant, value))) {\n return OMIT_PROJECTED_VALUE;\n }\n\n if (Array.isArray(value)) {\n const itemSchemas = schemas.map(candidate => asProjectionSchema(candidate.items)).filter(Boolean);\n if (itemSchemas.length === 0) return value;\n const itemSchema: ProjectionSchema = { allOf: itemSchemas };\n return value\n .map(item => projectValueToCapabilitySchema(root, itemSchema, item, depth + 1))\n .filter(item => item !== OMIT_PROJECTED_VALUE);\n }\n\n if (!isPlainObject(value)) return value;\n\n const propertySchemas = new Map<string, ProjectionSchema[]>();\n for (const candidate of schemas) {\n const properties = asProjectionSchema(candidate.properties);\n if (!properties) continue;\n for (const [key, propertySchemaValue] of Object.entries(properties)) {\n const propertySchema = asProjectionSchema(propertySchemaValue);\n if (!propertySchema) continue;\n const existing = propertySchemas.get(key) ?? [];\n existing.push(propertySchema);\n propertySchemas.set(key, existing);\n }\n }\n\n if (propertySchemas.size === 0) {\n const mapValueSchema = schemas\n .map(candidate => asProjectionSchema(candidate.additionalProperties))\n .find((candidate): candidate is ProjectionSchema => !!candidate);\n if (!mapValueSchema) return value;\n const projectedMap: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const projected = projectValueToCapabilitySchema(root, mapValueSchema, entry, depth + 1);\n if (projected !== OMIT_PROJECTED_VALUE) projectedMap[key] = projected;\n }\n return projectedMap;\n }\n\n const projectedObject: Record<string, unknown> = {};\n for (const [key, candidateSchemas] of propertySchemas) {\n if (!Object.hasOwn(value, key)) continue;\n const projected = projectValueToCapabilitySchema(root, { allOf: candidateSchemas }, value[key], depth + 1);\n if (projected !== OMIT_PROJECTED_VALUE) projectedObject[key] = projected;\n }\n return projectedObject;\n}\n\nfunction projectCapabilitiesToVersion(data: GetAdCPCapabilitiesResponse, version: string): GetAdCPCapabilitiesResponse {\n const validator = getValidator('get_adcp_capabilities', 'sync', version);\n const schema = asProjectionSchema((validator as { schema?: unknown } | undefined)?.schema);\n if (!schema) return data;\n const projected = projectValueToCapabilitySchema(schema, schema, data);\n if (!isPlainObject(projected)) return data;\n const result = projected as unknown as GetAdCPCapabilitiesResponse;\n\n // The 3.0 response contract predates account inference: every media-buy\n // seller must advertise a billing party even when the modern source\n // capability relied on implicit-account defaults.\n if (result.supported_protocols?.includes('media_buy')) {\n if (!result.account) {\n result.account = { supported_billing: ['agent'] };\n } else if (!Array.isArray(result.account.supported_billing) || result.account.supported_billing.length === 0) {\n result.account.supported_billing = ['agent'];\n }\n }\n\n // A modern request-signing block can contain only post-3.0 fields. After\n // projection, omit that empty optional block rather than emitting an object\n // that violates 3.0's required `supported` discriminator.\n if (result.request_signing && Object.keys(result.request_signing).length === 0) {\n delete result.request_signing;\n }\n return result;\n}\n\n/** @internal Shared by the platform adapter's principal resolver and dispatcher gate. */\nexport const COMPACT_MEDIA_BUY_MUTATION_TOOLS = new Set<string>([\n 'request_proposals',\n 'refine_proposals',\n 'decline_proposals',\n 'buy_products',\n 'accept_proposal',\n 'control_media_buy',\n]);\n\n// ---------------------------------------------------------------------------\n// Domain → tool name mapping\n// ---------------------------------------------------------------------------\n\ntype HandlerEntry = { handlerKey: string; toolName: string };\n\nconst MEDIA_BUY_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getProducts', toolName: 'get_products' },\n { handlerKey: 'listProducts', toolName: 'list_products' },\n { handlerKey: 'requestProposals', toolName: 'request_proposals' },\n { handlerKey: 'declineProposals', toolName: 'decline_proposals' },\n { handlerKey: 'buyProducts', toolName: 'buy_products' },\n { handlerKey: 'acceptProposal', toolName: 'accept_proposal' },\n { handlerKey: 'controlMediaBuy', toolName: 'control_media_buy' },\n { handlerKey: 'createMediaBuy', toolName: 'create_media_buy' },\n { handlerKey: 'updateMediaBuy', toolName: 'update_media_buy' },\n { handlerKey: 'getMediaBuys', toolName: 'get_media_buys' },\n { handlerKey: 'getMediaBuyDelivery', toolName: 'get_media_buy_delivery' },\n { handlerKey: 'providePerformanceFeedback', toolName: 'provide_performance_feedback' },\n { handlerKey: 'listCreativeFormats', toolName: 'list_creative_formats' },\n { handlerKey: 'syncCreatives', toolName: 'sync_creatives' },\n { handlerKey: 'listCreatives', toolName: 'list_creatives' },\n];\n\nconst MEDIA_BUY_PROTOCOL_ENTRIES = MEDIA_BUY_ENTRIES.filter(\n ({ handlerKey }) => !['listCreativeFormats', 'syncCreatives', 'listCreatives'].includes(handlerKey)\n);\n\nconst PROPOSAL_NEGOTIATION_ENTRIES: HandlerEntry[] = [{ handlerKey: 'refineProposals', toolName: 'refine_proposals' }];\n\nconst EVENT_TRACKING_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'syncEventSources', toolName: 'sync_event_sources' },\n { handlerKey: 'logEvent', toolName: 'log_event' },\n { handlerKey: 'syncAudiences', toolName: 'sync_audiences' },\n { handlerKey: 'syncCatalogs', toolName: 'sync_catalogs' },\n];\n\nconst SIGNALS_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getSignals', toolName: 'get_signals' },\n { handlerKey: 'activateSignal', toolName: 'activate_signal' },\n];\n\nconst CREATIVE_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'listCreativeFormats', toolName: 'list_creative_formats' },\n { handlerKey: 'listTransformers', toolName: 'list_transformers' },\n { handlerKey: 'buildCreative', toolName: 'build_creative' },\n { handlerKey: 'previewCreative', toolName: 'preview_creative' },\n { handlerKey: 'listCreatives', toolName: 'list_creatives' },\n { handlerKey: 'syncCreatives', toolName: 'sync_creatives' },\n { handlerKey: 'getCreativeDelivery', toolName: 'get_creative_delivery' },\n];\n\nconst GOVERNANCE_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'createPropertyList', toolName: 'create_property_list' },\n { handlerKey: 'updatePropertyList', toolName: 'update_property_list' },\n { handlerKey: 'getPropertyList', toolName: 'get_property_list' },\n { handlerKey: 'listPropertyLists', toolName: 'list_property_lists' },\n { handlerKey: 'deletePropertyList', toolName: 'delete_property_list' },\n { handlerKey: 'createCollectionList', toolName: 'create_collection_list' },\n { handlerKey: 'updateCollectionList', toolName: 'update_collection_list' },\n { handlerKey: 'getCollectionList', toolName: 'get_collection_list' },\n { handlerKey: 'listCollectionLists', toolName: 'list_collection_lists' },\n { handlerKey: 'deleteCollectionList', toolName: 'delete_collection_list' },\n { handlerKey: 'listContentStandards', toolName: 'list_content_standards' },\n { handlerKey: 'getContentStandards', toolName: 'get_content_standards' },\n { handlerKey: 'createContentStandards', toolName: 'create_content_standards' },\n { handlerKey: 'updateContentStandards', toolName: 'update_content_standards' },\n { handlerKey: 'calibrateContent', toolName: 'calibrate_content' },\n { handlerKey: 'validateContentDelivery', toolName: 'validate_content_delivery' },\n { handlerKey: 'getMediaBuyArtifacts', toolName: 'get_media_buy_artifacts' },\n { handlerKey: 'getCreativeFeatures', toolName: 'get_creative_features' },\n { handlerKey: 'syncPlans', toolName: 'sync_plans' },\n { handlerKey: 'checkGovernance', toolName: 'check_governance' },\n { handlerKey: 'reportPlanOutcome', toolName: 'report_plan_outcome' },\n { handlerKey: 'reportPlanAdjustment', toolName: 'report_plan_adjustment' },\n { handlerKey: 'getPlanAuditLogs', toolName: 'get_plan_audit_logs' },\n];\n\nconst PROTOCOL_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'syncAgentNotificationConfigs', toolName: 'sync_agent_notification_configs' },\n];\n\nconst ACCOUNT_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'listAccounts', toolName: 'list_accounts' },\n { handlerKey: 'syncAccounts', toolName: 'sync_accounts' },\n { handlerKey: 'syncGovernance', toolName: 'sync_governance' },\n { handlerKey: 'getAccountFinancials', toolName: 'get_account_financials' },\n { handlerKey: 'reportUsage', toolName: 'report_usage' },\n];\n\nconst SI_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getOffering', toolName: 'si_get_offering' },\n { handlerKey: 'initiateSession', toolName: 'si_initiate_session' },\n { handlerKey: 'sendMessage', toolName: 'si_send_message' },\n { handlerKey: 'terminateSession', toolName: 'si_terminate_session' },\n];\n\nconst BRAND_RIGHTS_ENTRIES: HandlerEntry[] = [\n { handlerKey: 'getBrandIdentity', toolName: 'get_brand_identity' },\n { handlerKey: 'getRights', toolName: 'get_rights' },\n { handlerKey: 'acquireRights', toolName: 'acquire_rights' },\n { handlerKey: 'updateRights', toolName: 'update_rights' },\n];\n\n// ---------------------------------------------------------------------------\n// Protocol detection\n// ---------------------------------------------------------------------------\n\nfunction hasDomainHandler(entries: readonly HandlerEntry[], handlers: object | undefined): boolean {\n if (handlers === undefined) return false;\n const candidate = handlers as Record<string, unknown>;\n return entries.some(({ handlerKey }) => typeof candidate[handlerKey] === 'function');\n}\n\n/**\n * Derive buyer-visible protocol domains from the handler group that owns each\n * operation, not from the flattened tools/list catalog. Several compatibility\n * tools intentionally appear in more than one protocol's discovery list\n * (`list_creative_formats`, `list_creatives`, and `sync_creatives`), so tool\n * names alone cannot distinguish a creative agent from a media-buy seller.\n * Utility groups (accounts, tasks, event tracking, protocol helpers, custom\n * tools) do not independently activate a protocol domain.\n */\nfunction detectProtocolsFromHandlers<TAccount>(config: AdcpServerConfig<TAccount>): AdcpProtocol[] {\n const protocols: AdcpProtocol[] = [];\n const declaresSalesSpecialism = config.capabilities?.specialisms?.some(specialism => specialism.startsWith('sales-'));\n const hasAnyMediaBuyHandler = hasDomainHandler(MEDIA_BUY_ENTRIES, config.mediaBuy);\n if (\n hasDomainHandler(MEDIA_BUY_PROTOCOL_ENTRIES, config.mediaBuy) ||\n hasDomainHandler(PROPOSAL_NEGOTIATION_ENTRIES, config.proposalNegotiation) ||\n (declaresSalesSpecialism && hasAnyMediaBuyHandler)\n ) {\n protocols.push('media_buy');\n }\n if (hasDomainHandler(SIGNALS_ENTRIES, config.signals)) protocols.push('signals');\n if (hasDomainHandler(GOVERNANCE_ENTRIES, config.governance)) protocols.push('governance');\n if (hasDomainHandler(CREATIVE_ENTRIES, config.creative)) protocols.push('creative');\n if (hasDomainHandler(SI_ENTRIES, config.sponsoredIntelligence)) protocols.push('sponsored_intelligence');\n if (hasDomainHandler(BRAND_RIGHTS_ENTRIES, config.brandRights)) protocols.push('brand');\n return protocols;\n}\n\n// ---------------------------------------------------------------------------\n// Tool coherence warnings\n// ---------------------------------------------------------------------------\n\nconst COHERENCE_RULES: [string, string, string][] = [\n [\n 'create_media_buy',\n 'get_products',\n 'create_media_buy without get_products — buyers cannot discover products before purchasing',\n ],\n [\n 'update_media_buy',\n 'get_media_buys',\n 'update_media_buy without get_media_buys — buyers cannot look up what to modify',\n ],\n [\n 'activate_signal',\n 'get_signals',\n 'activate_signal without get_signals — buyers cannot discover signals before activating',\n ],\n [\n 'sync_creatives',\n 'list_creative_formats',\n 'sync_creatives without list_creative_formats — buyers cannot discover valid formats',\n ],\n];\n\nfunction checkCoherence(toolNames: Set<string>, logger: AdcpLogger): void {\n for (const [tool, requires, message] of COHERENCE_RULES) {\n if (toolNames.has(tool) && !toolNames.has(requires)) {\n logger.warn(message);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Response detection\n// ---------------------------------------------------------------------------\n\nfunction isFormattedResponse(value: unknown): value is McpToolResponse {\n if (value == null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n return Array.isArray(obj.content) && 'structuredContent' in obj;\n}\n\n/**\n * Detect an AdCP Submitted envelope (async task acknowledgement).\n *\n * Every *Submitted arm in the generated types has `status: 'submitted'`\n * plus a required `task_id: string`. The discriminant is stable enough\n * to use for routing at dispatch time without per-tool knowledge.\n */\nfunction isSubmittedEnvelope(value: unknown): value is { status: 'submitted'; task_id: string; message?: string } {\n if (value == null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n return obj.status === 'submitted' && typeof obj.task_id === 'string';\n}\n\n/**\n * Detect an AdCP *Error arm (union member, not the framework `adcp_error`\n * envelope). Every *Error interface in the generated types carries a\n * required `errors: Error[]` and a narrow set of allowed siblings\n * (`context`, `ext`, plus a couple of tool-specific extras). Success\n * arms may have optional advisory fields but never a required `errors`\n * array — the `status === 'submitted'` exclusion keeps us from\n * confusing a Submitted envelope that advisory-echoes errors as an\n * Error arm. The set of allowed sibling keys is intentionally narrow:\n * any other top-level key means the payload carries Success-only fields\n * (`media_buy_id`, `creatives`, `signal_id`, ...) and should fall\n * through to the response builder.\n */\nconst ERROR_ARM_ALLOWED_KEYS = new Set(['errors', 'context', 'ext', 'success', 'conflicting_standards_id']);\nfunction isErrorArm(value: unknown): value is { errors: unknown[]; context?: unknown; ext?: unknown } {\n if (value == null || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n if (!Array.isArray(obj.errors)) return false;\n if ('status' in obj) return false;\n for (const key of Object.keys(obj)) {\n if (!ERROR_ARM_ALLOWED_KEYS.has(key)) return false;\n }\n return true;\n}\n\nfunction sanitizePayloadError(value: unknown): unknown {\n if (!isPlainObject(value)) return value;\n const code = value.code;\n if (typeof code !== 'string') return value;\n const sanitized = applyAdcpErrorAllowlist(code, value);\n if (!isStandardErrorCode(code)) return sanitized;\n\n const safe = sanitized as unknown as Record<string, unknown>;\n const projected: Record<string, unknown> = {\n code,\n message: typeof safe.message === 'string' ? safe.message : 'operation failed',\n recovery: STANDARD_ERROR_CODES[code].recovery,\n };\n for (const key of ['field', 'suggestion', 'retry_after', 'issues']) {\n if (safe[key] !== undefined) projected[key] = safe[key];\n }\n if (safe.details !== undefined) {\n projected.details = safe.details;\n }\n return projected;\n}\n\nfunction sanitizePayloadErrors(sc: Record<string, unknown>): boolean {\n if (!Array.isArray(sc.errors)) return false;\n const sanitized = sc.errors.map(sanitizePayloadError);\n const changed = sanitized.some((value, index) => value !== (sc.errors as unknown[])[index]);\n if (changed) sc.errors = sanitized;\n return changed;\n}\n\n/**\n * Wrap a Submitted envelope returned directly by a handler. Skips the\n * Success-builder defaults (`revision`, `confirmed_at`, `valid_actions`)\n * — those fields are specific to `CreateMediaBuySuccess` and would\n * corrupt the async-task shape if applied.\n */\nfunction wrapSubmittedEnvelope(value: { status: 'submitted'; task_id: string; message?: string }): McpToolResponse {\n const summary = value.message ?? `Task ${value.task_id} submitted`;\n return {\n content: [{ type: 'text', text: summary }],\n structuredContent: value as unknown as Record<string, unknown>,\n };\n}\n\n/**\n * Wrap an *Error arm returned directly by a handler. Preserves the\n * generated-type shape (`errors: Error[]`) on `structuredContent` so\n * buyers reading the typed response union see the exact branch the\n * spec defines; also sets `isError: true` so the MCP-level signal\n * matches `adcp_error` envelopes, which keeps `isErrorResponse()` and\n * `response-validation: strict` consistent across both error paths.\n */\nfunction wrapErrorArm(value: { errors: unknown[] }): McpToolResponse {\n const sanitizedErrors = value.errors.map(sanitizePayloadError);\n const firstError = sanitizedErrors[0] as { code?: unknown; message?: unknown } | undefined;\n const summary =\n firstError && typeof firstError === 'object'\n ? `${typeof firstError.code === 'string' ? firstError.code : 'ERROR'}: ${typeof firstError.message === 'string' ? firstError.message : 'operation failed'}`\n : 'operation failed';\n return {\n content: [{ type: 'text', text: summary }],\n isError: true,\n structuredContent: { ...value, errors: sanitizedErrors } as unknown as Record<string, unknown>,\n };\n}\n\n/**\n * Defence-in-depth sanitizer for handler-returned error envelopes.\n *\n * `adcpError()` filters its own output against `ADCP_ERROR_FIELD_ALLOWLIST`,\n * but a handler that hand-rolls `{ isError: true, structuredContent: {\n * adcp_error: {...} } }` (or constructs the envelope through a different\n * builder) bypasses that sanitizer. The storyboard invariant\n * `idempotency.conflict_no_payload_leak` catches this at conformance-test\n * time, but production traffic would be unprotected — so we re-apply the\n * allowlist here too. Silent no-op when the code has no registered entry,\n * or when `structuredContent.adcp_error` is missing its `code` field.\n *\n * Keeps L2 (`content[0].text`) and L3 (`structuredContent`) in lockstep —\n * both transport layers get the same filtered payload.\n */\nfunction sanitizeAdcpErrorEnvelope(response: McpToolResponse): void {\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n const err = sc.adcp_error as Record<string, unknown> | undefined;\n if (!err || typeof err !== 'object') return;\n const code = err.code;\n if (typeof code !== 'string') return;\n const allow = ADCP_ERROR_FIELD_ALLOWLIST[code];\n if (!allow) return;\n\n const filtered = applyAdcpErrorAllowlist(code, err);\n const filteredRecord = filtered as unknown as Record<string, unknown>;\n let changed = false;\n for (const key of new Set([...Object.keys(err), ...Object.keys(filtered)])) {\n if (err[key] !== filteredRecord[key]) {\n changed = true;\n break;\n }\n }\n if (!changed) return;\n\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.adcp_error = filtered;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\n/**\n * Fields valid on a payload-layer `errors[]` item per the bundled\n * `core/error.json` schema. Both layers of the AdCP error model carry\n * the same conceptual fields, so the dispatcher projects from one to\n * the other 1:1 — but the projection still needs to know which keys\n * are part of the contract.\n *\n * `recovery` is included even though the schema marks it optional: it\n * is the autonomous-buyer dispatch signal, and dropping it on the\n * payload while keeping it on the envelope would force callers to read\n * both layers to classify the failure. Mirroring matches the spec's\n * intent (both layers carry the same data) without surprising adopters\n * who rely on either side.\n */\nconst PAYLOAD_ERROR_FIELDS: ReadonlySet<string> = new Set([\n 'code',\n 'message',\n 'recovery',\n 'field',\n 'suggestion',\n 'retry_after',\n 'issues',\n 'details',\n]);\n\nfunction projectEnvelopeToPayloadError(envelope: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(envelope)) {\n if (PAYLOAD_ERROR_FIELDS.has(key)) out[key] = envelope[key];\n }\n return out;\n}\n\nfunction projectPayloadErrorToEnvelope(payloadError: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(payloadError)) {\n if (PAYLOAD_ERROR_FIELDS.has(key)) out[key] = payloadError[key];\n }\n return out;\n}\n\n/**\n * Two-layer error emission for tools whose response schema declares a\n * typed Error arm (`errors[]` required) at the top level.\n *\n * The AdCP spec (RFC `docs/proposals/adcperror-two-layer-emission.md`,\n * `error-code.json#GOVERNANCE_DENIED`) requires both layers on the\n * failure path:\n *\n * - **Envelope layer**: `structuredContent.adcp_error: {code, message, ...}`\n * — the cross-protocol marker, programmatic extraction.\n * - **Payload layer**: `structuredContent.errors: [{code, message, ...}]`\n * — the typed Error arm of the response union.\n *\n * `adcpError()` emits the envelope only; `wrapErrorArm()` emits the\n * payload only. This dispatcher seam fills in whichever layer is\n * missing so the wire is two-layer regardless of which helper the\n * adopter used. Idempotent on already-two-layer payloads (presence of\n * both `adcp_error` and `errors[]` is a no-op).\n *\n * Gated on `toolsWithErrorArm` derived from the bundled schema cache:\n * tools whose schema doesn't define `errors[]` (`get_adcp_capabilities`,\n * `tasks/get`, `get_products`, etc.) are left unchanged.\n *\n * Scope is the failure path only — early returns when neither layer is\n * present. Success-arm responses pass through untouched.\n */\nfunction enrichErrorTwoLayer(\n response: McpToolResponse,\n toolName: string,\n toolsWithErrorArm: ReadonlyMap<string, ErrorArmDescriptor>\n): void {\n const descriptor = toolsWithErrorArm.get(toolName);\n if (!descriptor) return;\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n\n const env = sc.adcp_error as Record<string, unknown> | undefined;\n const envValid = env != null && typeof env === 'object' && typeof env.code === 'string';\n const payloadList = sc.errors;\n const payloadValid = Array.isArray(payloadList) && payloadList.length > 0;\n const mirrorsBeforePayloadSanitization = contentTextMirrorsStructuredContent(response, sc);\n if (payloadValid && sanitizePayloadErrors(sc)) {\n syncContentJsonText(response, sc, mirrorsBeforePayloadSanitization);\n }\n\n // Path A: envelope present, payload missing → synthesise payload-layer\n // `errors[]` from the envelope. The `adcpError()` builder always lands\n // here; hand-rolled `{adcp_error: {...}}` envelopes too.\n if (envValid && !payloadValid) {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.errors = [projectEnvelopeToPayloadError(env)];\n applyArmDiscriminators(sc, descriptor);\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n return;\n }\n\n // Path B: payload present, envelope missing → synthesise envelope from\n // the first payload item. `wrapErrorArm()` lands here when adopters\n // return a typed Error arm directly.\n if (!envValid && payloadValid) {\n const first = (sc.errors as unknown[])[0];\n if (first && typeof first === 'object') {\n const projected = projectPayloadErrorToEnvelope(first as Record<string, unknown>);\n // Only stamp the envelope if the payload's first item carries the\n // minimum spec-required `code` + `message`. A malformed Error arm\n // (already warned about by the dispatcher's `isErrorArm` branch)\n // shouldn't synthesise a half-formed envelope.\n if (typeof projected.code === 'string' && typeof projected.message === 'string') {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.adcp_error = projected;\n applyArmDiscriminators(sc, descriptor);\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n }\n }\n return;\n }\n\n // Path C: both layers present (handler emitted a fully-formed\n // two-layer payload). Idempotent passthrough — adopters that already\n // ship the correct shape are not mutated. Discriminator constants\n // are NOT stamped here: an adopter that built both layers also chose\n // their own discriminator value, and overriding it could break the\n // arm they intended to land in.\n}\n\n/**\n * Stamp a tool's Error-arm discriminator constants on the response\n * payload. For most tools the descriptor is empty (the arm requires\n * `errors[]` only) and this is a no-op. `update_content_standards` is\n * the canonical case: its Error arm declares `success: { const: false }`\n * — without this stamp, the synthesised payload would still match the\n * Success arm's `success: false` value (absent → undefined, neither\n * `const: true` nor `const: false`), so the schema would reject the\n * response on either branch.\n *\n * Only stamps fields that are NOT already set on the payload — adopters\n * who deliberately set the discriminator (e.g. mid-migration) keep\n * their choice.\n */\nfunction applyArmDiscriminators(sc: Record<string, unknown>, descriptor: ErrorArmDescriptor): void {\n for (const [key, value] of Object.entries(descriptor.extraRequired)) {\n if (!(key in sc)) sc[key] = value;\n }\n}\n\n/**\n * Detect the framework's JSON-bodied L2 fallback before mutating L3. Merely\n * parsing as JSON is insufficient: an adopter-authored summary may itself be\n * a JSON object and must remain exact text.\n */\nfunction contentTextMirrorsStructuredContent(\n response: McpToolResponse,\n structuredContent: Record<string, unknown>\n): boolean {\n if (!Array.isArray(response.content)) return false;\n const first = response.content[0];\n return first?.type === 'text' && first.text === JSON.stringify(structuredContent);\n}\n\nfunction syncContentJsonText(\n response: McpToolResponse,\n structuredContent: Record<string, unknown>,\n mirroredBeforeMutation: boolean\n): void {\n if (!mirroredBeforeMutation || !Array.isArray(response.content)) return;\n const first = response.content[0];\n if (!first || first.type !== 'text') return;\n first.text = JSON.stringify(structuredContent);\n}\n\nfunction missingGetProductsCacheScopeIssue(): ValidationIssue {\n return {\n pointer: '/cache_scope',\n message: \"must have required property 'cache_scope'\",\n keyword: 'required',\n schemaPath: '#/required',\n hint: '`get_products` responses with `products` or `unchanged: true` must include `cache_scope`: use `public` for the universal rate card, `account` for account-specific overlays.',\n };\n}\n\nfunction normalizeGetProductsCacheScope(\n response: McpToolResponse,\n params: unknown,\n account: unknown,\n authInfo: unknown,\n exposeSchemaPath: boolean\n): McpToolResponse | undefined {\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return undefined;\n if (!Array.isArray(sc.products) && sc.unchanged !== true) return undefined;\n if (sc.cache_scope !== undefined) return undefined;\n\n const request =\n params && typeof params === 'object' && !Array.isArray(params) ? (params as Record<string, unknown>) : {};\n if (request.account != null || account != null || authInfo != null) {\n return adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload('get_products', 'response', [missingGetProductsCacheScopeIssue()], {\n exposeSchemaPath,\n })\n );\n }\n\n // Safe inference only: a product feed with neither an inline account nor an\n // auth context cannot contain an account-specific overlay, so it is cacheable\n // as the public layer. Any account or auth context makes omission ambiguous;\n // strict response validation should surface that.\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.cache_scope = 'public';\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n return undefined;\n}\n\n// Echo the request context into a formatted MCP tool response so buyers can\n// trace correlation_id across both success and error responses. Only plain\n// objects are echoed: `si_get_offering` and `si_initiate_session` override\n// the request schema's `context` to a domain-specific string, while the\n// response schema still requires the protocol echo object — copying a\n// string there would fail response validation.\nfunction injectContextIntoResponse(response: McpToolResponse, context: unknown): void {\n if (context === null || typeof context !== 'object' || Array.isArray(context)) return;\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (sc && typeof sc === 'object' && !('context' in sc)) {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.context = context;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n }\n}\n\n/**\n * Inject `adcp_version` into the response body so the seller echoes the\n * release served per spec PR `adcontextprotocol/adcp#3493`. Mirrors\n * `injectContextIntoResponse`'s structuredContent + L2-text-fallback dual\n * write so MCP clients reading either layer see the field. Only injects on\n * AdCP 3.1+ — 3.0 schemas don't define the field.\n *\n * `servedVersion` is the seller's release-precision identifier (output of\n * `resolveBundleKey(adcpVersion)`). For now it always reflects the seller's\n * own pin; downshift (3.1 seller serving a 3.0 buyer at 3.0) is a follow-up.\n */\n/**\n * Stamp the v3 protocol envelope's required `status` field on success\n * responses. Per AdCP #4876, every task response envelope MUST carry\n * `status`; synchronous calls emit `\"completed\"`. Mirrors\n * `injectContextIntoResponse`'s structuredContent + L2-text-fallback\n * dual write so MCP clients reading either layer see the field.\n *\n * Skipped when:\n * - `isError: true` — error envelopes carry their own status semantics\n * (`failed` / `rejected` / etc.). Wired separately by the adcp_error\n * path; not this seam's concern.\n * - `structuredContent.status` already present — handler-declared status\n * takes precedence. Preserves:\n * • the Submitted envelope's `status: 'submitted'`,\n * • payloads whose typed shape carries its own top-level `status`\n * discriminator (`CreateMediaBuySuccess.status: MediaBuyStatus`,\n * `UpdateMediaBuySuccess.status: MediaBuyStatus`, the\n * `cancelMediaBuyResponse` builder's hard-coded `status: 'canceled'`).\n * The MediaBuyStatus/TaskStatus collision at the same top-level key is\n * a spec ambiguity tracked at adcp-client#1897; this seam refuses to\n * destroy payload semantics until the spec disambiguates.\n */\nfunction injectEnvelopeStatusIntoResponse(response: McpToolResponse, toolName: string): void {\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n if ('status' in sc) return;\n if (STATUS_FREE_SYNC_RESPONSE_TOOLS.has(toolName)) return;\n // AdCP 3.1.0-beta.2+ requires envelope `status` on EVERY response, error\n // or otherwise. Map MCP's `isError` to the wire-level task state:\n // - `isError: true` → `'failed'` (task explicitly failed)\n // - `isError: false`/absent → `'completed'` (default for success path)\n // Tools that need richer states (`submitted`, `working`, `input-required`)\n // should set `status` themselves; this injector only fills in the default\n // when the handler hasn't.\n const status = response.isError === true ? 'failed' : 'completed';\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.status = status;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\nconst MEDIA_BUY_RESPONSE_TOOLS_REQUIRING_STATUS_SPLIT = new Set([\n 'create_media_buy',\n 'update_media_buy',\n 'cancel_media_buy',\n]);\n\nconst MEDIA_BUY_STATUS_VALUES = new Set([\n 'pending_creatives',\n 'pending_start',\n 'active',\n 'paused',\n 'completed',\n 'rejected',\n 'canceled',\n]);\n\nfunction normalizeMediaBuyStatusCollision(response: McpToolResponse, toolName: string): void {\n if (!MEDIA_BUY_RESPONSE_TOOLS_REQUIRING_STATUS_SPLIT.has(toolName)) return;\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (!sc || typeof sc !== 'object') return;\n const status = sc.status;\n if (typeof status !== 'string' || !MEDIA_BUY_STATUS_VALUES.has(status)) return;\n const looksLikeMediaBuyPayload =\n typeof sc.media_buy_id === 'string' || 'media_buy_status' in sc || Array.isArray(sc.packages);\n if (!looksLikeMediaBuyPayload) return;\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n if (sc.media_buy_status === undefined) sc.media_buy_status = status;\n delete sc.status;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n}\n\nfunction injectVersionIntoResponse(response: McpToolResponse, servedVersion: string | undefined): void {\n if (!servedVersion) return;\n // Normalize to release-precision (`3.1-beta.3`) before emitting — the wire\n // regex rejects full-semver (`3.1.0-beta.3`). Bundle metadata is published\n // with the patch digit; on-the-wire `adcp_version` is not. See the spec\n // note on `adcp_version` in `core.generated.ts` and the helper itself.\n const wireVersion = toReleasePrecisionVersion(servedVersion);\n const sc = response.structuredContent as Record<string, unknown> | undefined;\n if (sc && typeof sc === 'object' && !('adcp_version' in sc)) {\n const mirrorsStructuredContent = contentTextMirrorsStructuredContent(response, sc);\n sc.adcp_version = wireVersion;\n syncContentJsonText(response, sc, mirrorsStructuredContent);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Signed-requests preTransport builder\n// ---------------------------------------------------------------------------\n\ntype EffectiveSignedRequestPolicy = NonNullable<GetAdCPCapabilitiesResponse['request_signing']> & {\n supported: true;\n covers_content_digest: ContentDigestPolicy;\n required_for: string[];\n};\n\nfunction resolveEffectiveSignedRequestPolicy(\n signedRequests: SignedRequestsConfig,\n capabilityRequestSigning: GetAdCPCapabilitiesResponse['request_signing'] | undefined,\n adcpVersion?: string\n): EffectiveSignedRequestPolicy {\n const signingRelease = adcpVersion ? parseAdcpRelease(adcpVersion) : undefined;\n const requiredFor = signedRequests.required_for ??\n capabilityRequestSigning?.required_for ?? [...MUTATING_TASKS, 'get_products'];\n const protocolMethodsRequiredFor =\n signedRequests.protocol_methods_required_for ?? capabilityRequestSigning?.protocol_methods_required_for;\n const coversContentDigest: ContentDigestPolicy =\n signedRequests.covers_content_digest ??\n capabilityRequestSigning?.covers_content_digest ??\n (signingRelease?.major === 3 && signingRelease.minor >= 2 ? 'required' : 'either');\n return {\n ...capabilityRequestSigning,\n supported: true,\n covers_content_digest: coversContentDigest,\n required_for: requiredFor,\n ...(protocolMethodsRequiredFor ? { protocol_methods_required_for: protocolMethodsRequiredFor } : {}),\n };\n}\n\n/**\n * Build a `preTransport` middleware that runs `createExpressVerifier` against\n * the incoming Node request/response. The returned function matches the shape\n * `serve({ preTransport })` expects: it resolves to `true` when the verifier\n * has already written a 401 (headers sent), `false` otherwise.\n *\n * `serve()` buffers the request body into `req.rawBody` before invoking the\n * preTransport hook, so the verifier sees the exact bytes the signer hashed\n * for Content-Digest. For MCP the operation name comes from the JSON-RPC\n * `params.name`; the resolver below falls back to `undefined` for non-JSON or\n * non-`tools/call` bodies, which makes the verifier treat them as not-in-\n * `required_for` rather than rejecting (discovery probes, health checks).\n */\nfunction buildSignedRequestsPreTransport(\n signedRequests: SignedRequestsConfig,\n effectiveRequestSigning: EffectiveSignedRequestPolicy,\n adcpVersion?: string\n): AdcpPreTransport {\n const requiredFor = effectiveRequestSigning.required_for ?? [];\n const verifier = createExpressVerifier({\n capability: {\n supported: true,\n covers_content_digest: effectiveRequestSigning.covers_content_digest,\n required_for: requiredFor,\n ...(effectiveRequestSigning.protocol_methods_required_for\n ? { protocol_methods_required_for: effectiveRequestSigning.protocol_methods_required_for }\n : {}),\n },\n jwks: signedRequests.jwks,\n replayStore: signedRequests.replayStore,\n revocationStore: signedRequests.revocationStore,\n adcpVersion,\n ...(signedRequests.agentUrlForKeyid ? { agentUrlForKeyid: signedRequests.agentUrlForKeyid } : {}),\n resolveOperation: req => {\n const raw = (req as { rawBody?: string }).rawBody;\n if (!raw) return undefined;\n try {\n const parsed = JSON.parse(raw) as unknown;\n const messages = Array.isArray(parsed) ? parsed : [parsed];\n const operations = messages.flatMap(message => {\n if (message == null || typeof message !== 'object') return [];\n const candidate = message as { method?: unknown; params?: { name?: unknown } };\n return candidate.method === 'tools/call' && typeof candidate.params?.name === 'string'\n ? [candidate.params.name]\n : [];\n });\n return operations.find(operation => requiredFor.includes(operation)) ?? operations[0];\n } catch {\n // Non-JSON or malformed body — let transport handle rejection.\n }\n return undefined;\n },\n });\n\n return async function adcpPreTransport(req, res) {\n const serveContext = getServeRequestContext(req);\n const canonicalPublicUrl = serveContext?.publicUrl ? new URL(serveContext.publicUrl) : undefined;\n const reqShim: ExpressLike = {\n method: req.method ?? 'POST',\n url: req.url ?? '/mcp',\n originalUrl: req.url ?? '/mcp',\n headers: req.headers,\n rawBody: req.rawBody ?? '',\n protocol: canonicalPublicUrl?.protocol.replace(/:$/, '') ?? 'http',\n get(name: string) {\n const normalizedName = name.toLowerCase();\n if (canonicalPublicUrl && normalizedName === 'host') return canonicalPublicUrl.host;\n if (canonicalPublicUrl && normalizedName === 'x-forwarded-proto') {\n return canonicalPublicUrl.protocol.replace(/:$/, '');\n }\n const v = req.headers[name.toLowerCase()];\n return Array.isArray(v) ? v.join(', ') : v;\n },\n };\n const resShim = {\n status(code: number) {\n res.statusCode = code;\n return {\n set(k: string, v: string) {\n res.setHeader(k, v);\n return {\n json(body: unknown) {\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(body));\n },\n };\n },\n };\n },\n };\n\n let handled = false;\n let verifierCompleted = false;\n // The verifier calls `next(err?)` in the success / error path, but the\n // 401 RequestSignatureError path writes the response and returns WITHOUT\n // calling next. Race the next-callback against the response's 'finish' /\n // 'close' events so a terminal 401 resolves the promise; otherwise the\n // wrapper hangs forever and the agent server leaks (one McpServer per\n // unsigned request under attack).\n //\n // Security: if 'close' fires before the verifier completes (client\n // aborted the TCP connection mid-JWKS-fetch), we MUST NOT fall through\n // to the MCP transport — doing so would execute the tool handler\n // without a verified signature on an attacker-dropped connection. Mark\n // handled=true so serve.ts skips dispatch.\n await new Promise<void>(resolve => {\n let resolved = false;\n const done = () => {\n if (resolved) return;\n resolved = true;\n resolve();\n };\n res.once('finish', () => {\n if (res.writableEnded) handled = true;\n done();\n });\n res.once('close', () => {\n if (!verifierCompleted) handled = true;\n done();\n });\n verifier(reqShim, resShim, err => {\n verifierCompleted = true;\n if (err) {\n // Log internally; a leaked stack trace to the caller would\n // enumerate the verifier pipeline (js/stack-trace-exposure).\n // Narrow to name+code only — full error stringification can embed\n // JWKS URLs from transport failures, which leaks counterparty\n // key-discovery topology on shared log aggregators.\n const errName = (err as Error).name || 'Error';\n const errCode = (err as { code?: string }).code ?? 'unknown';\n console.error(`[adcp/signed-requests] verifier middleware error: ${errName} (${errCode})`);\n if (!res.writableEnded) {\n res.statusCode = 500;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ error: 'verifier_error' }));\n }\n handled = true;\n }\n const verifiedSigner = reqShim.verifiedSigner as import('../signing/types').VerifiedSigner | undefined;\n if (!err && verifiedSigner) {\n try {\n const principal = principalForVerifiedSigner(verifiedSigner, signedRequests.makePrincipal);\n attachVerifiedSignerAuth(req, principal, verifiedSigner);\n } catch (identityError) {\n const errName = (identityError as Error).name || 'Error';\n console.error(`[adcp/signed-requests] signer identity rejected: ${errName}`);\n if (!res.writableEnded) {\n res.statusCode = 401;\n res.setHeader('WWW-Authenticate', 'Signature error=\"request_signature_invalid\"');\n res.setHeader('Content-Type', 'application/json');\n res.end(\n JSON.stringify({\n error: 'request_signature_invalid',\n message: 'Request signature verification failed',\n })\n );\n }\n handled = true;\n }\n }\n if (res.writableEnded) handled = true;\n done();\n });\n });\n return handled;\n };\n}\n\nfunction attachVerifiedSignerAuth(\n req: import('http').IncomingMessage,\n principal: AuthPrincipal,\n signer: import('../signing/types').VerifiedSigner\n): void {\n const request = req as import('http').IncomingMessage & { auth?: AuthInfo; verifiedSigner?: typeof signer };\n const existing = request.auth;\n if (existing && existing.clientId !== principal.principal) {\n throw new AuthError('Request signature identity does not match the authenticated principal.');\n }\n const claims = principal.claims !== undefined ? { ...principal.claims } : {};\n const adopterExtra =\n principal.extra && typeof principal.extra === 'object' ? (principal.extra as Record<string, unknown>) : {};\n const extra = {\n ...(existing?.extra ?? {}),\n ...claims,\n ...adopterExtra,\n ...(principal.credential !== undefined ? { credential: principal.credential } : {}),\n };\n request.auth = existing\n ? { ...existing, extra }\n : {\n token: principal.token ?? '',\n clientId: principal.principal,\n scopes: principal.scopes ?? [],\n ...(principal.expiresAt !== undefined ? { expiresAt: principal.expiresAt } : {}),\n extra,\n };\n request.verifiedSigner = signer;\n}\n\n// ---------------------------------------------------------------------------\n// Version-claim validation helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the set of `adcp_major_version` integers this seller accepts on\n * inbound requests. Used by the single-field VERSION_UNSUPPORTED check\n * (issue #1075) to reject buyer claims outside the seller's advertised\n * window.\n *\n * Sources, in priority order:\n * 1. `capConfig.major_versions` — deprecated integer list (AdCP <3.1).\n * 2. `capConfig.supported_versions` — release-precision strings (AdCP 3.1+\n * per spec PR `adcontextprotocol/adcp#3493`); each entry's parsed major\n * is added to the set.\n * 3. Fallback to the major of `serverPin` so a seller that omits both lists\n * still rejects out-of-window claims rather than silently dispatching.\n */\nfunction getAdvertisedSupportedMajors(capConfig: AdcpCapabilitiesConfig | undefined, serverPin: string): Set<number> {\n const out = new Set<number>();\n for (const m of capConfig?.major_versions ?? []) {\n if (Number.isFinite(m)) out.add(m);\n }\n for (const v of capConfig?.supported_versions ?? []) {\n const m = parseAdcpMajorVersion(v);\n if (Number.isFinite(m)) out.add(m);\n }\n if (out.size === 0) {\n const pinMajor = parseAdcpMajorVersion(serverPin);\n if (Number.isFinite(pinMajor)) out.add(pinMajor);\n }\n return out;\n}\n\n/**\n * Build the `supported_versions` string array shipped on the\n * `VERSION_UNSUPPORTED` error envelope so buyers can downgrade their pin\n * and retry. Mirrors `getAdvertisedSupportedMajors` precedence:\n *\n * 1. `capConfig.supported_versions` — emit verbatim (release-precision strings).\n * 2. Else `capConfig.major_versions` — stringify each integer.\n * 3. Else fall back to the server pin's major as a single-entry list.\n *\n * Strings are preferred over integers because release-precision strings\n * round-trip more information; emitting a single-source listing avoids\n * confusing buyers with both integer and string shapes for the same major.\n * (`getAdvertisedSupportedMajors` unions both sources for the accepted-set\n * check, but this function picks one to avoid that ambiguity on the wire.)\n *\n * Buyer-side parser (`extractVersionUnsupportedDetails`) already filters\n * non-strings, so a `String(N)` fallback round-trips cleanly across 3.0\n * and 3.1 sellers.\n */\nfunction buildSupportedVersionsList(capConfig: AdcpCapabilitiesConfig | undefined, serverPin: string): string[] {\n if (capConfig?.supported_versions?.length) {\n return [...capConfig.supported_versions];\n }\n if (capConfig?.major_versions?.length) {\n return capConfig.major_versions.filter(m => Number.isFinite(m)).map(m => String(m));\n }\n const pinMajor = parseAdcpMajorVersion(serverPin);\n return Number.isFinite(pinMajor) ? [String(pinMajor)] : [];\n}\n\ninterface ParsedAdcpRelease {\n major: number;\n minor: number;\n prerelease?: string;\n value: string;\n}\n\ninterface ServedAdcpRelease {\n validationVersion: string;\n wireVersion?: string;\n}\n\nfunction isMcpToolResponse(value: ServedAdcpRelease | McpToolResponse): value is McpToolResponse {\n return Array.isArray((value as McpToolResponse).content);\n}\n\nfunction parseAdcpRelease(value: unknown): ParsedAdcpRelease | undefined {\n if (typeof value !== 'string') return undefined;\n let wire: string;\n try {\n wire = toReleasePrecisionVersion(value);\n } catch {\n return undefined;\n }\n const match = /^v?(\\d+)\\.(\\d+)(?:-([a-zA-Z0-9.-]+))?$/.exec(wire);\n if (!match) return undefined;\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n ...(match[3] !== undefined && { prerelease: match[3] }),\n value: wire,\n };\n}\n\nfunction compareAdcpRelease(left: ParsedAdcpRelease, right: ParsedAdcpRelease): number {\n if (left.major !== right.major) return left.major - right.major;\n if (left.minor !== right.minor) return left.minor - right.minor;\n if (left.prerelease === right.prerelease) return 0;\n if (left.prerelease === undefined) return 1;\n if (right.prerelease === undefined) return -1;\n const leftParts = left.prerelease.split('.');\n const rightParts = right.prerelease.split('.');\n for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {\n const leftPart = leftParts[index];\n const rightPart = rightParts[index];\n if (leftPart === undefined) return -1;\n if (rightPart === undefined) return 1;\n if (leftPart === rightPart) continue;\n const leftNumeric = /^\\d+$/.test(leftPart);\n const rightNumeric = /^\\d+$/.test(rightPart);\n if (leftNumeric && rightNumeric) return Number(leftPart) - Number(rightPart);\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;\n return leftPart.localeCompare(rightPart);\n }\n return 0;\n}\n\nconst PUSH_OPERATION_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,255}$/;\n\nfunction releaseRequiresPushOperationId(release: string): boolean {\n return isAdcpVersionAtLeast(resolveBundleKey(release), '3.2.0-beta.5');\n}\n\nfunction pushOperationIdError(\n params: Record<string, unknown>,\n release: ServedAdcpRelease\n): McpToolResponse | undefined {\n if (!releaseRequiresPushOperationId(release.validationVersion)) return undefined;\n const config = params.push_notification_config;\n if (config === undefined) return undefined;\n if (\n !isPlainObject(config) ||\n typeof config.operation_id !== 'string' ||\n !PUSH_OPERATION_ID_PATTERN.test(config.operation_id)\n ) {\n return adcpError('INVALID_REQUEST', {\n message: `push_notification_config.operation_id must match ${PUSH_OPERATION_ID_PATTERN.source}`,\n field: 'push_notification_config.operation_id',\n });\n }\n return undefined;\n}\n\nlet bundledCompatibleReleases: ParsedAdcpRelease[] | undefined;\n\nfunction bundledReleasesForMajors(majors: readonly number[], configured: ParsedAdcpRelease): ParsedAdcpRelease[] {\n const acceptedMajors = new Set(majors);\n const releases = new Map<string, ParsedAdcpRelease>();\n bundledCompatibleReleases ??= COMPATIBLE_ADCP_VERSIONS.flatMap(version => {\n if (!hasSchemaBundle(version)) return [];\n const parsed = parseAdcpRelease(version);\n return parsed ? [parsed] : [];\n });\n for (const parsed of bundledCompatibleReleases) {\n if (!acceptedMajors.has(parsed.major) || compareAdcpRelease(parsed, configured) > 0) continue;\n const key = `${parsed.major}.${parsed.minor}${parsed.prerelease ? `-${parsed.prerelease}` : ''}`;\n const existing = releases.get(key);\n // Preserve the v2.5 alias because that is the actual bundled directory;\n // stable semver patches otherwise collapse to release precision.\n if (!existing || parsed.value.startsWith('v')) releases.set(key, parsed);\n }\n // A server may explicitly opt into a bundled forward release before the\n // SDK-wide compatibility list advances (proposal negotiation does this for\n // 3.2). Include that configured release in major-only negotiation.\n if (acceptedMajors.has(configured.major)) {\n const key = `${configured.major}.${configured.minor}${configured.prerelease ? `-${configured.prerelease}` : ''}`;\n releases.set(key, configured);\n }\n return [...releases.values()];\n}\n\nfunction selectServedAdcpRelease(\n params: Record<string, unknown>,\n capConfig: AdcpCapabilitiesConfig | undefined,\n serverPin: string\n): ServedAdcpRelease | McpToolResponse {\n const configured = parseAdcpRelease(serverPin);\n if (!configured) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: `Configured AdCP release ${JSON.stringify(serverPin)} is invalid.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n\n const advertisedValues = capConfig?.supported_versions?.length ? capConfig.supported_versions : undefined;\n const advertised = advertisedValues\n ? advertisedValues.flatMap(value => {\n // SDK <=13 and early 3.x adopters sometimes placed a major-only\n // string in supported_versions. Interpret it like major_versions so\n // an SDK 14 server can still negotiate 3.0/3.1 wire bundles.\n if (/^v?\\d+$/.test(value.trim())) {\n return bundledReleasesForMajors([Number.parseInt(value.replace(/^v/, ''), 10)], configured);\n }\n return [parseAdcpRelease(value)];\n })\n : capConfig?.major_versions?.length\n ? bundledReleasesForMajors(capConfig.major_versions, configured)\n : bundledReleasesForMajors([configured.major], configured);\n if (advertised.some(value => value === undefined)) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: 'Seller capabilities contain an invalid supported_versions release.',\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n const supported = (advertised as ParsedAdcpRelease[]).filter(\n candidate => compareAdcpRelease(candidate, configured) <= 0\n );\n if (supported.length === 0) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: 'Seller capabilities do not include a release this server can serve.',\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n\n const requestedVersion = params.adcp_version;\n const requestedMajorRaw = params.adcp_major_version;\n const requestedMajor =\n typeof requestedMajorRaw === 'number'\n ? requestedMajorRaw\n : typeof requestedMajorRaw === 'string'\n ? Number.parseInt(requestedMajorRaw, 10)\n : undefined;\n let selected: ParsedAdcpRelease | undefined;\n\n if (requestedVersion !== undefined) {\n const requested = parseAdcpRelease(requestedVersion);\n if (!requested) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: `Request carries invalid adcp_version=${JSON.stringify(requestedVersion)}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n if (requestedMajor !== undefined && Number.isFinite(requestedMajor) && requestedMajor !== requested.major) {\n return adcpError('VERSION_UNSUPPORTED', {\n message:\n `Request carries adcp_version=${JSON.stringify(requestedVersion)} (major ${requested.major}) and ` +\n `adcp_major_version=${JSON.stringify(requestedMajorRaw)}; majors must agree.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n selected = supported\n .filter(candidate => candidate.major === requested.major && compareAdcpRelease(candidate, requested) <= 0)\n .sort((left, right) => compareAdcpRelease(right, left))[0];\n } else if (requestedMajor !== undefined && Number.isFinite(requestedMajor)) {\n // A major-only request may be a 3.0 buyer that cannot send\n // `adcp_version`. Select the oldest advertised release in that major so\n // the server never upgrades its wire shape implicitly.\n selected = supported.filter(candidate => candidate.major === requestedMajor).sort(compareAdcpRelease)[0];\n } else {\n // With no buyer claim, serve the newest release the seller actually\n // advertises rather than silently using a configured pin omitted from\n // supported_versions.\n selected = [...supported].sort((left, right) => compareAdcpRelease(right, left))[0];\n }\n\n if (!selected) {\n const claim =\n requestedVersion !== undefined\n ? `adcp_version=${JSON.stringify(requestedVersion)}`\n : requestedMajorRaw !== undefined\n ? `adcp_major_version=${JSON.stringify(requestedMajorRaw)} (major ${String(requestedMajor)})`\n : 'no AdCP version';\n return adcpError('VERSION_UNSUPPORTED', {\n message: `Request claims ${claim}; no mutually supported AdCP release is available.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, serverPin) },\n });\n }\n\n const validationVersion = selected.value;\n return {\n validationVersion,\n ...(bundleSupportsAdcpVersionField(resolveBundleKey(validationVersion)) && { wireVersion: validationVersion }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// createAdcpServer\n// ---------------------------------------------------------------------------\n\n/**\n * Create an AdCP-compliant MCP server from domain-grouped handler functions.\n *\n * @deprecated New adopters should use `createAdcpServerFromPlatform` from\n * `@adcp/sdk/server` instead. This v5 handler-bag entry point is kept for\n * legacy / mid-migration code; LLM-generated platforms scaffolding from\n * any of the v6 skills should NEVER call this. The v6 path\n * (`createAdcpServerFromPlatform`) wraps this function with: typed\n * specialism interfaces (`SalesPlatform`, `CreativeBuilderPlatform`, etc.),\n * compile-time capability enforcement (`RequiredPlatformsFor<S>`), the\n * `ctx_metadata` round-trip cache for adapter-internal state,\n * auto-hydration of `req.packages[i].product` on createMediaBuy,\n * default `resolveIdempotencyPrincipal` synthesis, capability projection,\n * async-task envelopes, status normalization via `StatusMappers`,\n * multi-tenant routing via `TenantRegistry`, and async task completion\n * webhook delivery. Under AdCP 3.2 synchronous terminal responses remain\n * silent on the task-webhook channel.\n *\n * Reach for `createAdcpServer` directly only when you need fine control\n * over individual handlers, are mid-migration from a v5 codebase, or\n * have custom-shaped tools the platform interface doesn't yet model.\n *\n * @see {@link createAdcpServerFromPlatform} — the canonical v6 entry.\n * @see `@adcp/sdk/server/legacy/v5` — the stable subpath for long-term\n * v5 pinning. The top-level re-export here may be removed in a\n * future major; the subpath is the supported home.\n * See `docs/migration-5.x-to-6.x.md`.\n *\n * Before each handler runs, the framework:\n * 1. Validates the request against the tool's Zod schema (MCP SDK)\n * 2. Resolves the account (if the tool has an `account` field and `resolveAccount` is configured)\n *\n * The handler only runs when all preconditions pass. It receives the validated\n * params and a context with the resolved account and state store.\n *\n * `get_adcp_capabilities` is auto-generated from registered tools.\n */\nexport function createAdcpServer<TAccount = unknown>(config: AdcpServerConfig<TAccount>): AdcpServer {\n const {\n name,\n version,\n adcpVersion: configuredAdcpVersion,\n mcpToolProfile = 'auto',\n requireCompactMutationAccountScope = false,\n resolveAccount,\n resolveAccountFromAuth,\n resolveSessionKey,\n agentRegistry,\n exposeErrorDetails = process.env.NODE_ENV !== 'production',\n stateStore = DEFAULT_STATE_STORE,\n taskRegistry,\n logger = noopLogger,\n capabilities: capConfig,\n idempotency: idempotencyConfig,\n resolveIdempotencyPrincipal,\n instructions: instructionsOption,\n onInstructionsError = 'skip',\n taskStore,\n taskMessageQueue,\n webhooks,\n signedRequests,\n validation: validationConfig,\n credentialPolicy,\n testController: testControllerBridge,\n responseEnhancer,\n } = config;\n if (taskRegistry !== undefined && taskRegistry.scopeVersion !== 1) {\n throw new Error(\n 'createAdcpServer: taskRegistry.scopeVersion must be 1. Migrate custom registries to the account/principal-scoped TaskRegistry signatures before use.'\n );\n }\n if (!['auto', 'media-buy', 'all'].includes(mcpToolProfile)) {\n throw new Error(\n `createAdcpServer: mcpToolProfile must be \"auto\", \"media-buy\", or \"all\"; got ${JSON.stringify(mcpToolProfile)}`\n );\n }\n const notificationHandlerConfigured = typeof config.protocol?.syncAgentNotificationConfigs === 'function';\n const notificationCapabilitySupported = capConfig?.capability_changes?.notifications?.supported === true;\n if (notificationHandlerConfigured !== notificationCapabilitySupported) {\n throw new Error(\n 'createAdcpServer: syncAgentNotificationConfigs and capabilities.capability_changes.notifications.supported must be enabled together'\n );\n }\n if (notificationHandlerConfigured && typeof config.protocol?.resolveScope !== 'function') {\n throw new Error(\n 'createAdcpServer: protocol.resolveScope is required to isolate sync_agent_notification_configs by authenticated caller'\n );\n }\n if (\n typeof config.governance?.reportPlanAdjustment === 'function' &&\n typeof config.governance.resolveReportPlanAdjustmentScope !== 'function'\n ) {\n throw new Error(\n 'createAdcpServer: governance.resolveReportPlanAdjustmentScope is required to authorize report_plan_adjustment'\n );\n }\n const frameworkInputSchemaFor = (toolName: string) =>\n config.exposeToolSchemas === true\n ? (shallowToolInputHintSchema(toolName) ?? PASSTHROUGH_INPUT_SCHEMA)\n : PASSTHROUGH_INPUT_SCHEMA;\n const mcpAppResources = normalizeMcpAppResources(config.resources);\n const mcpAppResourceUris = new Set<string>(mcpAppResources.map(resource => resource.uri));\n for (const [toolName, tool] of Object.entries(config.customTools ?? {})) {\n const resourceUri = tool?._meta?.ui?.resourceUri;\n if (resourceUri === undefined || mcpAppResourceUris.has(resourceUri)) continue;\n const message =\n `[adcp/createAdcpServer] customTools[\"${toolName}\"]._meta.ui.resourceUri references ` +\n `\"${resourceUri}\", but no matching MCP App resource is configured in resources[].`;\n process.emitWarning(message, { type: 'AdcpServerConfigWarning', code: 'ADCP_MCP_APP_RESOURCE_MISSING' });\n logger.warn(message);\n }\n\n // One-shot construction-time warn when `testController` is wired without\n // both resolver paths. Account-bearing calls use `resolveAccount`; account-\n // less calls use `resolveAccountFromAuth`. The dispatch gate fails closed\n // when either path cannot produce an account, so make partial resolver\n // wiring diagnosable at construction time.\n //\n // Dual-emit: `process.emitWarning` writes to stderr by default so the\n // signal is visible even when `logger` is the default `noopLogger`\n // (the day-one case where the misconfig is most likely). `logger.warn`\n // also fires so adopters with configured logging pipelines see it in\n // their normal channel. The stable warning `code` lets logging pipelines\n // classify this configuration fault without parsing the message. See\n // `AdcpServerConfig.testController`\n // JSDoc § \"Security — trust boundary\" and #1784.\n if (testControllerBridge != null && (resolveAccount === undefined || resolveAccountFromAuth === undefined)) {\n const missingResolvers = [\n ...(resolveAccount === undefined ? ['resolveAccount'] : []),\n ...(resolveAccountFromAuth === undefined ? ['resolveAccountFromAuth'] : []),\n ];\n const message =\n `[adcp/createAdcpServer] testController is wired without ${missingResolvers.join(' and ')} — ` +\n 'both account-bearing and account-less tools require a trusted resolved sandbox/mock account before seeded fixtures can be merged. Configure both resolver paths. Details: https://github.com/adcontextprotocol/adcp-client/blob/main/docs/guides/VALIDATE-YOUR-AGENT.md';\n process.emitWarning(message, { type: 'AdcpServerConfigWarning', code: 'ADCP_BRIDGE_NO_RESOLVER' });\n logger.warn(message);\n }\n\n // Pre-resolve credential-policy patterns once. The patterns config is\n // a stable property of `CredentialPolicyConfig`; pulling it out here\n // keeps the per-call hot path (`scanArgsForCredentials`) free of the\n // string-vs-object discrimination on every dispatch.\n const credentialPolicyPatterns =\n credentialPolicy === undefined || typeof credentialPolicy === 'string' ? undefined : credentialPolicy.patterns;\n\n // Resolve `adcpVersion` early — the validator-call closures below capture\n // it by reference and would hit a TDZ ReferenceError if any of them ran\n // synchronously during setup. They don't today (`createAdcpServer`\n // registers handlers; the handlers fire on incoming requests after\n // `wrapMcpServer` returns), but the ordering hides a sharp edge for\n // future refactors. Throws `ConfigurationError` on cross-major pins\n // whose schema bundle isn't shipped — see utils/adcp-version-config.ts.\n // Registering a 3.2-only proposal tool is an explicit opt-in to the\n // bundled 3.2 server surface. Keep the SDK-wide client pin unchanged,\n // but make this server instance negotiate and advertise the release it\n // actually serves. An explicit older pin is rejected below.\n const adcpVersion = resolveAdcpVersion(\n configuredAdcpVersion ?? (config.proposalNegotiation ? ADCP_VERSION : undefined)\n );\n const movingSupportedVersion = capConfig?.supported_versions?.find(isMovingAdcpPrereleaseFamilyAlias);\n if (movingSupportedVersion) {\n throw new Error(\n `createAdcpServer: capabilities.supported_versions contains moving prerelease-family alias ${JSON.stringify(movingSupportedVersion)}; pin ${JSON.stringify(toReleasePrecisionVersion(ADCP_VERSION))} instead`\n );\n }\n const proposalRefinementCapabilities = config.proposalNegotiation\n ? defineProposalRefinementCapabilities(config.proposalNegotiation.capabilities)\n : undefined;\n const proposalRelease = parseAdcpRelease(adcpVersion);\n if (\n proposalRefinementCapabilities &&\n (!proposalRelease || proposalRelease.major !== 3 || proposalRelease.minor < 2)\n ) {\n throw new Error('createAdcpServer: proposalNegotiation requires adcpVersion 3.2 or newer');\n }\n if (proposalRefinementCapabilities && capConfig?.supported_versions?.length) {\n const supportsProposalRelease = capConfig.supported_versions.some(value => {\n const release = parseAdcpRelease(value);\n return (\n release !== undefined &&\n release.major === 3 &&\n release.minor >= 2 &&\n proposalRelease !== undefined &&\n compareAdcpRelease(release, proposalRelease) <= 0\n );\n });\n if (!supportsProposalRelease) {\n throw new Error(\n 'createAdcpServer: proposalNegotiation requires capabilities.supported_versions to include a served AdCP 3.2 release'\n );\n }\n }\n if (\n proposalRefinementCapabilities &&\n !capConfig?.supported_versions?.length &&\n capConfig?.major_versions?.length &&\n !capConfig.major_versions.includes(3)\n ) {\n throw new Error(\n 'createAdcpServer: proposalNegotiation requires capabilities.major_versions to include AdCP major 3'\n );\n }\n if (proposalRefinementCapabilities && proposalRefinementCapabilities.supported_dimensions === undefined) {\n throw new Error(\n 'createAdcpServer: proposalNegotiation.capabilities.supported_dimensions is required when refineProposals is registered'\n );\n }\n\n // Pre-resolved release-precision identifier the seller echoes on every\n // response per AdCP 3.1 spec PR `adcontextprotocol/adcp#3493`. `undefined`\n // when this seller pins a 3.0 bundle (3.0 schemas don't define the field).\n // Computed once at construction since the seller's pin is fixed for the\n // server's lifetime — every dispatch reuses the same value. Downshift\n // (3.1 seller serving a 3.0 buyer at 3.0) is a follow-up; today this\n // always reflects the seller's own pin.\n const protocolBundleKey = resolveBundleKey(adcpVersion);\n const frameworkToolMeta = { adcp_version: adcpVersion } as const;\n const servedAdcpVersion = (() => {\n const bundleKey = protocolBundleKey;\n return bundleSupportsAdcpVersionField(bundleKey) ? bundleKey : undefined;\n })();\n const protocolTaskRelease = parseAdcpRelease(protocolBundleKey);\n const supportsProtocolTaskTools =\n protocolTaskRelease !== undefined &&\n (protocolTaskRelease.major > 3 || (protocolTaskRelease.major === 3 && protocolTaskRelease.minor >= 1));\n\n // Tool-name set for two-layer error emission. Computed once at server\n // build from the bundled response schemas: any tool whose top-level\n // `oneOf`/`anyOf` declares an arm with `required: [\"errors\"]` joins\n // the set, and the dispatcher mirrors `errors[]` ↔ `adcp_error` on\n // the failure path so both spec-mandated layers ride on every\n // failing response. Tools without an Error arm are untouched.\n // RFC: docs/proposals/adcperror-two-layer-emission.md.\n const toolsWithErrorArm = getToolsWithErrorArm(adcpVersion);\n\n // Defaults gated on `process.env.NODE_ENV`:\n // - Production → both sides `'off'` (zero AJV overhead; trust the\n // handler after its test suite has exercised it).\n // - Dev/test/CI → BOTH sides `'strict'`. Request validation is now\n // authoritative on both transports (#909) — we dropped the SDK\n // Zod from `registerTool` inputSchema, so if our framework validator\n // doesn't reject malformed payloads they reach the handler\n // unchecked over A2A. Matching responses' existing `'strict'`\n // default keeps behavior consistent across the wire in both\n // directions.\n // Explicit `validation: { requests, responses }` on the config always\n // wins. `process.env.NODE_ENV` matches the convention every other SDK\n // consumer already tunes (Express, React, etc.); containers/CI that\n // want prod-like behavior set NODE_ENV=production before start.\n const isProduction = process.env.NODE_ENV === 'production';\n const requestValidationMode = validationConfig?.requests ?? (isProduction ? 'off' : 'strict');\n const responseValidationMode = validationConfig?.responses ?? (isProduction ? 'off' : 'strict');\n\n // Split the `idempotency` config field into \"the active store\" and\n // \"explicitly opted out\" so existing call sites keep working with a\n // single nullable variable while the disabled-mode branches stay\n // surgical. `idempotencyDisabled` gates: schema-level missing-key\n // tolerance, the missing-store guardrail log, the capability\n // declaration shift to `IdempotencyUnsupported`, and the runtime\n // production check below.\n const idempotencyDisabled = idempotencyConfig === 'disabled';\n const idempotency: IdempotencyStore | undefined = idempotencyDisabled ? undefined : idempotencyConfig;\n if (\n idempotency &&\n (!Number.isSafeInteger(idempotency.ttlSeconds) || idempotency.ttlSeconds < 3600 || idempotency.ttlSeconds > 604800)\n ) {\n throw new TypeError('createAdcpServer: idempotency.ttlSeconds must be a safe integer between 3600 and 604800.');\n }\n if (idempotency && typeof idempotency.renew !== 'function') {\n throw new TypeError(\n 'createAdcpServer: idempotency.renew is required so long-running mutation handlers cannot outlive their owner claim.'\n );\n }\n if (idempotencyDisabled) {\n // Allowlist gate. The earlier draft refused the flag only when\n // NODE_ENV === 'production', which is a footgun: NODE_ENV defaults to\n // unset in raw Lambda, custom containers, and many K8s deployments,\n // so the strict equality returned `false` in exactly the\n // hard-to-debug environments where disabled mode is most dangerous.\n // Inverted to an allowlist of dev/test environments; any other value\n // (unset, 'production', 'staging', 'qa', custom names) requires the\n // operator to explicitly acknowledge the risk via\n // `ADCP_IDEMPOTENCY_DISABLED_ACK=1`. Hard to set by accident, makes\n // the choice deliberate, and turns a missing-NODE_ENV config into a\n // startup crash instead of a silent money-flow incident on retry.\n const env = process.env.NODE_ENV;\n const acknowledged = process.env.ADCP_IDEMPOTENCY_DISABLED_ACK === '1';\n const isAllowlistedDevEnv = env === 'test' || env === 'development';\n if (!isAllowlistedDevEnv && !acknowledged) {\n throw new Error(\n \"createAdcpServer: idempotency: 'disabled' refuses to start with NODE_ENV=\" +\n (env === undefined ? '<unset>' : JSON.stringify(env)) +\n '. Disabled mode skips replay enforcement and silently double-executes mutating handlers on retry, ' +\n 'so the SDK only allows it under NODE_ENV=test or NODE_ENV=development by default. ' +\n 'Either: (a) wire a real store via `createIdempotencyStore({ backend, ttlSeconds })`, ' +\n '(b) set NODE_ENV=test or NODE_ENV=development if this is a dev-only environment, or ' +\n '(c) set ADCP_IDEMPOTENCY_DISABLED_ACK=1 to explicitly acknowledge the risk for non-standard environments.'\n );\n }\n logger.warn(\n \"createAdcpServer: idempotency: 'disabled' is set. Mutating requests will not be replay-checked and \" +\n '`get_adcp_capabilities` will declare `idempotency.supported: false`. Use only in non-production test fleets.'\n );\n }\n\n // Production gate on the default in-memory `stateStore`. Mirrors\n // `buildDefaultTaskRegistry` policy in `from-platform.ts` and the\n // `idempotency: 'disabled'` allowlist above: the module-singleton\n // default is correct for dev and single-tenant agents, but\n // multi-tenant production deployments that mint one\n // `createAdcpServer` per resolved tenant would silently share state\n // across tenants. Refuse outside `{NODE_ENV=test, NODE_ENV=development}`\n // unless the adopter sets `ADCP_DECISIONING_ALLOW_INMEMORY_STATE=1` as\n // an explicit ops escape hatch. v6.0 shipped this as a one-time warn;\n // 6.0.1 promotes it to a hard refusal so the production footgun closes\n // before any adopter trips on it.\n //\n // Ordered AFTER the idempotency-disabled gate so adopters who hit\n // both surface the higher-severity error (idempotency-disabled\n // double-executes mutations on retry; state-store sharing leaks\n // tenant data — both bad, idempotency goes first because the\n // recovery is \"wire a store\" while state-store recovery is \"pass\n // your own\").\n if (stateStore === DEFAULT_STATE_STORE) {\n const env = process.env.NODE_ENV;\n const safe = env === 'test' || env === 'development';\n const ack = process.env.ADCP_DECISIONING_ALLOW_INMEMORY_STATE === '1';\n if (!safe && !ack) {\n throw new Error(\n 'createAdcpServer: in-memory state store refused outside ' +\n '{NODE_ENV=test, NODE_ENV=development}. The default ' +\n '`InMemoryStateStore` is a process-shared module singleton — ' +\n 'single-tenant agents get the documented `ctx.store` cross-request ' +\n 'persistence, but multi-tenant deployments would silently share ' +\n 'state across resolved tenants. Pick one of:\\n' +\n ' 1. (Recommended) Pass `stateStore: new PostgresStateStore({ pool })` ' +\n 'to keep state across restarts AND partition across tenants. See ' +\n '`@adcp/sdk/server` for the migration helper.\\n' +\n ' 2. Pass `stateStore: new InMemoryStateStore()` explicitly if you ' +\n 'accept that state is per-process and shared across all resolved ' +\n 'tenants. Single-tenant agents only.\\n' +\n ' 3. ADCP_DECISIONING_ALLOW_INMEMORY_STATE=1 env flag is the ops ' +\n 'escape hatch (same effect as #2 but config-only); prefer #2 in ' +\n 'adopter code so the choice is visible at the call site.'\n );\n }\n }\n\n // Enforce that the verifier config has a buyer-visible discovery surface.\n // When `signedRequests` is set but neither the deprecated `signed-requests`\n // specialism claim NOR `capabilities.request_signing.supported: true` is\n // declared, buyers can't discover the signing requirement from\n // `get_adcp_capabilities` — they won't sign, the verifier rejects every\n // mutating call, and the agent is dead on arrival. Two discovery surfaces\n // are accepted:\n //\n // - **3.1+ canonical (recommended):** `capabilities.request_signing.supported: true`.\n // The universal signed_requests storyboard runs on this signal alone and\n // the runner emits `request_signing.required` notices for buyers.\n // - **Back-compat:** `specialisms: ['signed-requests']`. The 3.0-era enum\n // is preserved through the AdCP 4.0 deprecation cycle (adcp#3075). The\n // runner emits `signed_requests_specialism_deprecated` notice when this\n // path is taken (adcp-client#2082, adcp#4796).\n //\n // The opposite direction — advertising signing without a `signedRequests`\n // config — is only wrong when the agent also doesn't wire a verifier via\n // `serve({ preTransport })`. Legacy servers that hand-build the middleware\n // fall into this case and are still conformant. We log a loud error so\n // operators notice (matching the idempotency guardrail precedent) but\n // don't throw, leaving the manual path working.\n const specialismsClaimed = capConfig?.specialisms ?? [];\n const claimsSignedRequests = specialismsClaimed.includes('signed-requests');\n const declaresRequestSigningCapability = capConfig?.request_signing?.supported === true;\n if (signedRequests && !claimsSignedRequests && !declaresRequestSigningCapability) {\n throw new Error(\n 'createAdcpServer: `signedRequests` is configured but neither ' +\n '`capabilities.request_signing.supported: true` nor `capabilities.specialisms: [\"signed-requests\"]` is declared. ' +\n 'Buyers discover the signing requirement from get_adcp_capabilities — ' +\n 'set `capabilities.request_signing = { supported: true, ... }` (canonical 3.1+ form, recommended) ' +\n 'or claim the deprecated `signed-requests` specialism (back-compat). ' +\n \"Omitting both surfaces means buyers won't sign their requests.\"\n );\n }\n if (claimsSignedRequests && !signedRequests) {\n logger.error(\n 'createAdcpServer: `capabilities.specialisms` claims \"signed-requests\" but no `signedRequests` config was provided. ' +\n 'Either pass `signedRequests: { jwks, replayStore, revocationStore }` to auto-wire the verifier, or ensure you wire ' +\n 'one manually via `serve({ preTransport })`. Claiming the specialism without verifying signatures is a spec violation.'\n );\n }\n // The specialism is only meaningful when `capabilities.request_signing.supported`\n // is true — the compliance storyboard treats a missing or false `supported`\n // flag as \"not opted in\" and silently skips the whole conformance run. Claim\n // + supported:false is the worst failure mode: the claim advertises\n // signature enforcement while the capability block tells buyers the agent\n // doesn't verify. Fail fast so the mismatch is caught at construction.\n if (claimsSignedRequests && capConfig?.request_signing?.supported !== true) {\n throw new Error(\n 'createAdcpServer: `capabilities.specialisms` claims \"signed-requests\" but `capabilities.request_signing.supported` is not true. ' +\n 'Set `capabilities.request_signing = { supported: true, ... }` — the compliance storyboard skips conformance entirely when ' +\n '`supported` is falsy, and buyers cannot discover the signing requirement without the capability block.'\n );\n }\n\n // Cross-domain specialism declaration check. When a domain handler group\n // is wired, `capabilities.specialisms` SHOULD include at least one of that\n // domain's specialisms — otherwise the conformance runner grades the agent\n // as \"No applicable tracks found for this agent\" silently, even when every\n // tool works. The matrix v18 run (issue #785) had this drift class account\n // for ~30% of \"agent built every tool but storyboard reports no applicable\n // tracks\" cases.\n //\n // Logged via `logger.error` (matching the idempotency-disabled precedent)\n // rather than thrown because middleware-only test harnesses legitimately\n // wire handlers without declaring specialisms — production agents will see\n // the warning and conformance fail loudly, but tests stay passing.\n //\n // mediaBuy is intentionally excluded — its specialism choices\n // (sales-non-guaranteed vs sales-guaranteed vs sales-broadcast-tv vs\n // sales-social etc.) are commercially significant and an agent wiring\n // `mediaBuy.getProducts` may legitimately defer the specialism\n // declaration to a follow-up. The skill examples in build-seller-agent\n // already cover the right declaration; the runtime guardrail floor is\n // set at \"if you wire creative/signals/brand/governance handlers,\n // you SHOULD claim a specialism.\"\n //\n // governance is intentionally COARSE: any governance specialism\n // satisfies the check even though individual handlers map to specific\n // specialisms (createPropertyList → property-lists, calibrateContent →\n // content-standards, etc.). Per-handler-subgroup mapping is a\n // follow-up; the coarse rule catches the drift class (governance\n // handlers wired, no claim at all) without false-positives on\n // legitimate cross-cutting reads (e.g., a sales agent that calls\n // getPropertyList for read-only joins and claims its sales specialism).\n const isWired = (handlers: Record<string, unknown> | undefined): boolean => {\n // Filter to function-valued keys so `{ listCreativeFormats: undefined }`\n // (a key set to undefined, e.g. via `{ ...maybeHandlers }` spread) is\n // treated as not wired. `Object.keys` would otherwise count the key.\n if (!handlers) return false;\n return Object.values(handlers).some(v => typeof v === 'function');\n };\n\n const DOMAIN_SPECIALISM_REQUIREMENTS = [\n {\n domain: 'creative' as const,\n wired: isWired(config.creative as Record<string, unknown> | undefined),\n specialisms: ['creative-ad-server', 'creative-generative', 'creative-template', 'creative-transformers'] as const,\n },\n {\n domain: 'signals' as const,\n wired: isWired(config.signals as Record<string, unknown> | undefined),\n specialisms: ['signal-marketplace', 'signal-owned'] as const,\n },\n {\n domain: 'brandRights' as const,\n wired: isWired(config.brandRights as Record<string, unknown> | undefined),\n specialisms: ['brand-rights'] as const,\n },\n {\n domain: 'governance' as const,\n wired: isWired(config.governance as Record<string, unknown> | undefined),\n specialisms: [\n 'governance-spend-authority',\n 'governance-delivery-monitor',\n 'property-lists',\n 'collection-lists',\n 'content-standards',\n ] as const,\n },\n ];\n\n for (const req of DOMAIN_SPECIALISM_REQUIREMENTS) {\n if (!req.wired) continue;\n const claimedFromDomain = req.specialisms.filter(s => (specialismsClaimed as readonly string[]).includes(s));\n if (claimedFromDomain.length === 0) {\n logger.error(\n `createAdcpServer: ${req.domain} handlers are wired but capabilities.specialisms ` +\n `does not include any ${req.domain} specialism. Add at least one of ` +\n `${req.specialisms.map(s => `'${s}'`).join(', ')} to capabilities.specialisms — ` +\n `without it, the conformance runner reports \"No applicable tracks found\" and ` +\n `the agent grades as failing despite working tools.`\n );\n }\n }\n\n // Instantiate the emitter once — handler contexts expose its `emit`\n // bound method so per-request code calls `ctx.emitWebhook(...)` without\n // knowing about the emitter's construction or options.\n const configuredWebhookStore = webhooks?.deliveryStore ?? webhooks?.idempotencyKeyStore;\n if (\n webhooks &&\n process.env.NODE_ENV !== 'test' &&\n process.env.NODE_ENV !== 'development' &&\n configuredWebhookStore?.durability !== 'durable'\n ) {\n throw new Error(\n 'createAdcpServer: production webhook emission requires a durable WebhookDeliveryStore. ' +\n 'The store atomically retains each delivery key, canonical payload fingerprint, and first-attempt time ' +\n 'through the advertised retry horizon. Pass the shared store as webhooks.deliveryStore; ' +\n 'memoryWebhookDeliveryStore() is for development and tests only.'\n );\n }\n if (\n webhooks &&\n process.env.NODE_ENV !== 'test' &&\n process.env.NODE_ENV !== 'development' &&\n webhooks.deliveryRecovery?.durability !== 'durable'\n ) {\n throw new Error(\n 'createAdcpServer: production webhook emission requires durable deliveryRecovery. ' +\n 'Checkpoint the exact destination, payload/timestamp, authentication reference, and retry policy before ' +\n 'the first attempt, then recover unsettled deliveries after restart.'\n );\n }\n const webhookEmitter = webhooks\n ? createWebhookEmitter({\n ...webhooks,\n publisherScope: webhooks.publisherScope ?? name,\n // Intentionally unbound until handler dispatch derives trusted scope.\n tenantScope: undefined,\n })\n : undefined;\n const configuredWebhookTenantScope = webhooks?.tenantScope;\n const configuredWebhookEmitter =\n webhookEmitter && configuredWebhookTenantScope !== undefined\n ? webhookEmitter.forTenantScope(configuredWebhookTenantScope)\n : webhookEmitter;\n\n // Resolve `instructions` — sync function form is evaluated at construction.\n // Under `serve({ reuseAgent: false })` (the default) the factory runs\n // per HTTP request, so the function fires per session. Under\n // `reuseAgent: true` the function would fire once and never again —\n // `serve()` refuses that combination via `ADCP_INSTRUCTIONS_FN`.\n // Async function form: a Promise return is stored here; resolution is\n // deferred to the MCP `initialize` handler via `wrapInitializeHandler`.\n const instructionsIsFn = typeof instructionsOption === 'function';\n let resolvedInstructions: string | undefined;\n let pendingInstructions: Promise<string | undefined> | undefined;\n let resolveInstructionsForTransport: (() => Promise<string | undefined>) | undefined;\n if (typeof instructionsOption === 'string') {\n resolvedInstructions = instructionsOption;\n } else if (instructionsIsFn) {\n try {\n const result = (instructionsOption as (ctx: SessionContext) => string | undefined | Promise<string | undefined>)(\n {}\n );\n // Promise detection — must guard for null + non-object before reading\n // `.then`, otherwise `typeof null.then` throws TypeError and the user\n // sees a confusing framework-internal stack instead of their own bug.\n const isThenable =\n result !== null && typeof result === 'object' && typeof (result as { then?: unknown }).then === 'function';\n if (isThenable) {\n // Async return: store the running Promise; resolution happens in the\n // wrapInitializeHandler block below, just before the MCP response.\n pendingInstructions = Promise.resolve(result as Promise<string | undefined>);\n // Mark eager rejection as observed immediately. The original promise\n // remains rejected and is awaited by the transport resolver later,\n // where onInstructionsError decides fail vs skip. Without this\n // observer, stateless modern tool requests that never run discovery\n // could surface an unhandled rejection from an async instructions fn.\n void pendingInstructions.catch(() => {});\n } else {\n // Reject non-string non-undefined sync returns instead of silently coercing\n // (`String({})` → \"[object Object]\" would ship as instructions otherwise).\n // The TS signature constrains return to `string | undefined`; this catches\n // `as any` escapees and untyped JS callers.\n if (result !== undefined && typeof result !== 'string') {\n throw new Error(\n `function-form \\`instructions\\` must return string | undefined, got ${result === null ? 'null' : typeof result}. ` +\n `Return a string for the prose, or undefined for \"no instructions on this session.\"`\n );\n }\n resolvedInstructions = result;\n }\n } catch (err) {\n if (onInstructionsError === 'fail') {\n throw err;\n }\n // 'skip' — log server-side, surface no instructions to MCP `initialize`.\n logger.warn('[adcp/createAdcpServer] instructions() threw; skipping (onInstructionsError: \"skip\")', {\n error: err instanceof Error ? err.message : String(err),\n });\n resolvedInstructions = undefined;\n }\n } else {\n resolvedInstructions = undefined;\n }\n\n const mcpTaskStore = taskStore ?? new InMemoryTaskStore();\n const server = createTaskCapableServer(name, version, {\n taskStore: mcpTaskStore,\n taskMessageQueue,\n instructions: resolvedInstructions,\n });\n\n // The v1 SDK server remains the canonical legacy path. The modern adapter\n // separately mirrors these validated definitions onto every per-request\n // MCP v2 server reconstruction.\n for (const resource of mcpAppResources) {\n server.registerResource(\n resource.name,\n resource.uri,\n mcpAppResourceMetadata(resource) as Parameters<typeof server.registerResource>[2],\n async (uri, extra) =>\n readMcpAppResource(resource, uri, {\n signal: extra.signal,\n })\n );\n }\n\n // Wire async instructions resolution into the MCP `initialize` handler.\n // The function returned a Promise at construction time; await it here\n // (just before the initialize response) so the resolved string is included\n // in the MCP handshake without making createAdcpServer itself async.\n if (pendingInstructions !== undefined) {\n const pending = pendingInstructions;\n let resolvedOnce: Promise<string | undefined> | undefined;\n resolveInstructionsForTransport = () => {\n resolvedOnce ??= (async () => {\n try {\n const resolved = await pending;\n if (resolved !== undefined && typeof resolved !== 'string') {\n throw new Error(\n `function-form \\`instructions\\` resolved to ${typeof resolved}, expected string | undefined. ` +\n `Return a string for the prose, or undefined for \"no instructions on this session.\"`\n );\n }\n setSdkServerInstructions(server, resolved);\n return resolved;\n } catch (err) {\n if (onInstructionsError === 'fail') throw err;\n logger.warn('[adcp/createAdcpServer] async instructions threw; skipping (onInstructionsError: \"skip\")', {\n error: err instanceof Error ? err.message : String(err),\n });\n return undefined;\n }\n })();\n return resolvedOnce;\n };\n wrapInitializeHandler(server, async (origHandler, req, extra) => {\n await resolveInstructionsForTransport?.();\n return origHandler(req, extra);\n });\n }\n\n const registeredToolNames = new Set<string>();\n let warnedAboutOptionalReplayWithoutIdempotency = false;\n\n const applyResponseEnhancer = (response: McpToolResponse): McpToolResponse => {\n responseEnhancer?.(response);\n return response;\n };\n\n const requestServedRelease = (params: Record<string, unknown>): ServedAdcpRelease | undefined => {\n const selected = selectServedAdcpRelease(params, capConfig, adcpVersion);\n return isMcpToolResponse(selected) ? undefined : selected;\n };\n\n const releaseDefinesTool = (toolName: string, release: ServedAdcpRelease): boolean => {\n if (toolName === 'refine_proposals') return true;\n try {\n return getValidator(toolName, 'request', release.validationVersion) !== undefined;\n } catch {\n return false;\n }\n };\n\n const finalizeProtocolTaskToolResponse = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>,\n response: McpToolResponse,\n opts: { echoContext?: boolean } = {}\n ): McpToolResponse => {\n const release = requestServedRelease(params) ?? {\n validationVersion: adcpVersion,\n ...(servedAdcpVersion !== undefined && { wireVersion: servedAdcpVersion }),\n };\n sanitizeAdcpErrorEnvelope(response);\n enrichErrorTwoLayer(response, toolName, getToolsWithErrorArm(release.validationVersion));\n if (!isErrorResponse(response)) {\n normalizeMediaBuyStatusCollision(response, toolName);\n injectEnvelopeStatusIntoResponse(response, toolName);\n const validationError = protocolTaskResponseValidationError(toolName, response, params);\n if (validationError) return finalizeProtocolTaskToolResponse(toolName, params, validationError, opts);\n }\n if (opts.echoContext !== false) injectContextIntoResponse(response, params.context);\n injectVersionIntoResponse(response, release.wireVersion);\n return applyResponseEnhancer(response);\n };\n\n const unsupportedVersionResponse = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>\n ): McpToolResponse | undefined => {\n const selected = selectServedAdcpRelease(params, capConfig, adcpVersion);\n if (isMcpToolResponse(selected)) return selected;\n if (!releaseDefinesTool(toolName, selected)) {\n return adcpError('VERSION_UNSUPPORTED', {\n message: `${toolName} is not defined in the selected AdCP release ${selected.validationVersion}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n });\n }\n return undefined;\n };\n\n const protocolTaskAccountExtensionIssues = (params: Record<string, unknown>): ValidationIssue[] => {\n if (params.account === undefined) return [];\n const parsed = AccountReferenceSchema.safeParse(params.account);\n if (parsed.success) return [];\n return [\n {\n pointer: '/account',\n message: 'must be a valid AccountReference',\n keyword: 'oneOf',\n schemaPath: '#/properties/account',\n },\n ];\n };\n\n const protocolTaskRequestValidationError = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>\n ): McpToolResponse | undefined => {\n const accountIssues = protocolTaskAccountExtensionIssues(params);\n const outcome =\n requestValidationMode === 'off'\n ? ({ valid: true, issues: [], schemaId: undefined } as const)\n : validateRequest(toolName, params, requestServedRelease(params)?.validationVersion ?? adcpVersion);\n const issues = [...(outcome.valid ? [] : outcome.issues), ...accountIssues];\n if (issues.length === 0) return undefined;\n if (requestValidationMode === 'strict' || accountIssues.length > 0) {\n return adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload(toolName, 'request', issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n })\n );\n }\n logger.warn(\n `Schema validation warning (request) for ${toolName}: ${formatIssues(issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues,\n }\n );\n return undefined;\n };\n\n const protocolTaskResponseValidationError = (\n toolName: 'get_task_status' | 'list_tasks',\n response: McpToolResponse,\n params: Record<string, unknown> = {}\n ): McpToolResponse | undefined => {\n if (responseValidationMode === 'off') return undefined;\n const outcome = validateResponse(\n toolName,\n response.structuredContent,\n requestServedRelease(params)?.validationVersion ?? adcpVersion\n );\n if (outcome.valid) return undefined;\n logger.warn(\n `Schema validation warning (response) for ${toolName}: ${formatIssues(outcome.issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues: outcome.issues,\n variant: outcome.variant,\n }\n );\n if (responseValidationMode !== 'strict') return undefined;\n return adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload(toolName, 'response', outcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n })\n );\n };\n\n const protocolTaskBoundsError = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>\n ): McpToolResponse | undefined => {\n if (params.include_history === true) {\n return adcpError('INVALID_REQUEST', {\n message: 'include_history is not supported by this task registry',\n field: 'include_history',\n });\n }\n if (toolName === 'get_task_status') {\n if (typeof params.task_id !== 'string' || params.task_id.length === 0) {\n return adcpError('INVALID_REQUEST', {\n message: 'task_id must be a non-empty string',\n field: 'task_id',\n });\n }\n }\n const filters = params.filters;\n if (isPlainObject(filters) && Array.isArray(filters.task_ids)) {\n if (\n filters.task_ids.length > 100 ||\n filters.task_ids.some(taskId => typeof taskId !== 'string' || taskId.length === 0)\n ) {\n return adcpError('INVALID_REQUEST', {\n message: 'filters.task_ids must contain at most 100 non-empty strings',\n field: 'filters.task_ids',\n });\n }\n }\n return undefined;\n };\n\n const taskToolCredentialPolicyError = (\n toolName: 'get_task_status' | 'list_tasks',\n params: Record<string, unknown>,\n mcpExtra: any\n ): McpToolResponse | undefined => {\n if (credentialPolicy === undefined) return undefined;\n const effectivePolicy =\n typeof credentialPolicy === 'string' || credentialPolicy.tools?.[toolName] !== undefined\n ? resolveCredentialPolicyForTool(credentialPolicy, toolName)\n : (credentialPolicy.tools?.tasks_get ?? credentialPolicy.policy);\n if (effectivePolicy !== 'lax') {\n const hits = scanArgsForCredentials(params, credentialPolicyPatterns);\n const blockedPaths =\n typeof effectivePolicy === 'object' ? hits.filter(p => !effectivePolicy.allow.includes(p)) : hits;\n if (blockedPaths.length > 0) {\n return adcpError('PERMISSION_DENIED', {\n message:\n 'Request args carry credential-shaped keys. Credentials must arrive on authInfo, not in the request body.',\n recovery: 'correctable',\n details: { scope: 'credentials', credential_paths: blockedPaths },\n });\n }\n }\n if (\n typeof credentialPolicy !== 'string' &&\n credentialPolicy.scanAuthInfo === true &&\n mcpExtra?.authInfo?.extra !== null &&\n mcpExtra?.authInfo?.extra !== undefined &&\n typeof mcpExtra.authInfo.extra === 'object'\n ) {\n const authInfoHits = scanArgsForCredentials(mcpExtra.authInfo.extra, credentialPolicyPatterns);\n if (authInfoHits.length > 0) {\n try {\n logger.warn('credentialPolicy: authInfo.extra carries credential-shaped keys', {\n tool: toolName,\n paths: authInfoHits.map(p => `authInfo.extra.${p}`),\n });\n } catch {\n // Ignore logger failures on the rejection path.\n }\n return adcpError('PERMISSION_DENIED', {\n message:\n 'Request authentication context carries credential-shaped keys. Configure your authenticator to keep credentials off authInfo.extra.',\n recovery: 'terminal',\n details: { scope: 'credentials' },\n });\n }\n }\n return undefined;\n };\n\n const resolveTaskQueryAccountId = async (\n params: Record<string, unknown>,\n extra: any,\n toolName: 'get_task_status' | 'list_tasks'\n ): Promise<{\n accountId?: string;\n ownerScope?: string;\n accountResolutionAttempted: boolean;\n error?: McpToolResponse;\n }> => {\n const ctx: HandlerContext<TAccount> = { store: stateStore };\n let accountResolutionAttempted = false;\n if (extra?.authInfo) {\n const authInfo = extra.authInfo as ResolvedAuthInfo;\n ctx.authInfo = authInfo;\n const inboundCredential = authInfo.extra?.credential;\n if (inboundCredential !== undefined && authInfo.credential === undefined) {\n authInfo.credential = inboundCredential as ResolvedAuthInfo['credential'];\n }\n }\n\n if (agentRegistry !== undefined) {\n try {\n const resolved = await agentRegistry.resolve({\n ...(ctx.authInfo?.credential !== undefined && { credential: ctx.authInfo.credential }),\n ...(ctx.authInfo?.extra !== undefined && { extra: ctx.authInfo.extra }),\n input: params,\n });\n if (resolved != null) {\n if (!Object.isFrozen(resolved)) {\n if (resolved.billing_capabilities instanceof Set) {\n Object.freeze(resolved.billing_capabilities);\n }\n Object.freeze(resolved);\n }\n ctx.agent = resolved;\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Buyer-agent registry resolution failed during task poll', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Buyer-agent registry resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n }\n\n const accountRef = params.account;\n if (accountRef != null) {\n accountResolutionAttempted = true;\n if (!resolveAccount) {\n return {\n accountResolutionAttempted,\n error: adcpError('ACCOUNT_NOT_FOUND', {\n message: 'The specified account does not exist',\n field: 'account',\n }),\n };\n }\n try {\n const account = await resolveAccount(accountRef as AccountReference, {\n toolName: toolName as AdcpServerToolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n if (account != null) ctx.account = account;\n if (account == null) {\n return {\n accountResolutionAttempted,\n error: adcpError('ACCOUNT_NOT_FOUND', {\n message: 'The specified account does not exist',\n field: 'account',\n }),\n };\n }\n } catch (err) {\n if (isThrownAdcpError(err)) return { accountResolutionAttempted, error: err };\n if (err instanceof AdcpError) {\n return { accountResolutionAttempted, error: projectThrownAdcpError(err) };\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Account resolution failed', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n } else if (resolveAccountFromAuth) {\n try {\n const account = await resolveAccountFromAuth({\n toolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n accountResolutionAttempted = true;\n if (account != null) {\n ctx.account = account;\n }\n } catch (err) {\n accountResolutionAttempted = true;\n if (isThrownAdcpError(err)) return { accountResolutionAttempted, error: err };\n if (err instanceof AdcpError) {\n return { accountResolutionAttempted, error: projectThrownAdcpError(err) };\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Auth-derived account resolution failed', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n }\n\n if (resolveSessionKey) {\n try {\n const sessionKey = await resolveSessionKey({\n toolName: toolName as AdcpServerToolName,\n params,\n account: ctx.account,\n ...(ctx.agent != null && { agent: ctx.agent }),\n });\n if (sessionKey !== undefined) ctx.sessionKey = sessionKey;\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Session key resolution failed during task poll', { tool: toolName, error: reason });\n return {\n accountResolutionAttempted,\n error: adcpError('SERVICE_UNAVAILABLE', {\n message: 'Session key resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n }),\n };\n }\n }\n\n const accountLike = ctx.account as { id?: unknown; account_id?: unknown } | undefined;\n const accountId =\n typeof accountLike?.id === 'string'\n ? accountLike.id\n : typeof accountLike?.account_id === 'string'\n ? accountLike.account_id\n : undefined;\n const ownerScope =\n accountId !== undefined\n ? taskOwnerScopeForContext(ctx.authInfo, ctx.sessionKey, ctx.agent, accountId)\n : undefined;\n return { accountId, ownerScope, accountResolutionAttempted };\n };\n\n // Collect all domain handlers into a flat toolName → handler map\n const domainGroups: [Record<string, Function> | undefined, HandlerEntry[]][] = [\n [config.mediaBuy as Record<string, Function> | undefined, MEDIA_BUY_ENTRIES],\n [config.proposalNegotiation as unknown as Record<string, Function> | undefined, PROPOSAL_NEGOTIATION_ENTRIES],\n [config.signals as Record<string, Function> | undefined, SIGNALS_ENTRIES],\n [config.creative as Record<string, Function> | undefined, CREATIVE_ENTRIES],\n [config.governance as Record<string, Function> | undefined, GOVERNANCE_ENTRIES],\n [config.protocol as Record<string, Function> | undefined, PROTOCOL_ENTRIES],\n [config.accounts as Record<string, Function> | undefined, ACCOUNT_ENTRIES],\n [config.eventTracking as Record<string, Function> | undefined, EVENT_TRACKING_ENTRIES],\n [config.sponsoredIntelligence as Record<string, Function> | undefined, SI_ENTRIES],\n [config.brandRights as Record<string, Function> | undefined, BRAND_RIGHTS_ENTRIES],\n ];\n\n for (const [handlers, entries] of domainGroups) {\n if (!handlers) continue;\n\n // Warn on unrecognized handler keys (likely typos)\n const knownKeys = new Set(entries.map(e => e.handlerKey));\n for (const key of ['capabilities', 'resolveScope', 'resolveReportPlanAdjustmentScope']) knownKeys.add(key);\n for (const key of Object.keys(handlers)) {\n if (typeof (handlers as Record<string, unknown>)[key] === 'function' && !knownKeys.has(key)) {\n logger.warn(`Unknown handler key \"${key}\" — will not be registered. Check for typos.`);\n }\n }\n\n for (const { handlerKey, toolName } of entries) {\n const handler = (handlers as Record<string, Function>)[handlerKey];\n if (!handler) continue;\n\n if (registeredToolNames.has(toolName)) {\n // Tool already registered by another domain (e.g., list_creative_formats\n // in both mediaBuy and creative). First domain wins.\n logger.warn(`Tool \"${toolName}\" already registered by another domain, skipping`);\n continue;\n }\n\n const meta = TOOL_META[toolName];\n const schema =\n toolName === 'refine_proposals'\n ? { shape: REFINE_PROPOSALS_INPUT_SHAPE }\n : (TOOL_REQUEST_SCHEMAS as Readonly<Record<string, { shape: Record<string, unknown> }>>)[toolName];\n if (!schema?.shape) {\n logger.warn(`No schema found for tool \"${toolName}\" in TOOL_REQUEST_SCHEMAS, skipping`);\n continue;\n }\n const hasAccount = 'account' in schema.shape;\n\n const wrap = meta?.wrap ?? ((data: any, summary?: string) => genericResponse(toolName, data, summary));\n const toolHandler = async (params: any, extra: any) => {\n const releaseSelection = selectServedAdcpRelease(params, capConfig, adcpVersion);\n let releaseError: McpToolResponse | undefined;\n let requestRelease: ServedAdcpRelease;\n if (isMcpToolResponse(releaseSelection)) {\n releaseError = releaseSelection;\n requestRelease = {\n validationVersion: adcpVersion,\n ...(servedAdcpVersion !== undefined && { wireVersion: servedAdcpVersion }),\n };\n } else {\n requestRelease = releaseSelection;\n }\n const requestErrorArms = getToolsWithErrorArm(requestRelease.validationVersion);\n const ctx: HandlerContext<TAccount> = {\n store: stateStore,\n servedAdcpVersion: requestRelease.validationVersion,\n ...(extra?.signal !== undefined && { signal: extra.signal }),\n };\n if (extra?.authInfo) {\n ctx.authInfo = extra.authInfo;\n // Hoist the kind-discriminated credential from MCP's `extra`\n // shape onto top-level `ctx.authInfo.credential` so adopter\n // `resolveAccount` callbacks and the `BuyerAgentRegistry` can\n // route on it directly without unpacking `extra`. Stage 3 of\n // #1269 — the built-in authenticators stamp this in\n // `serve.ts:attachAuthInfo`. Custom `authenticate` callbacks\n // that don't populate `credential` see `ctx.authInfo.credential`\n // stay undefined; downstream code branches on `credential\n // !== undefined` for the new path and falls back to the\n // `@deprecated` legacy fields (`token`, `clientId`, `scopes`)\n // for the old path. Both paths coexist for two minors.\n const authInfo = ctx.authInfo;\n if (authInfo !== undefined) {\n const inboundCredential = authInfo.extra?.credential;\n if (inboundCredential !== undefined && authInfo.credential === undefined) {\n authInfo.credential = inboundCredential as ResolvedAuthInfo['credential'];\n }\n }\n }\n // Echo params.context into any response (success or error) so buyers\n // can trace correlation_id end-to-end. Framework-generated errors\n // (ACCOUNT_NOT_FOUND, SERVICE_UNAVAILABLE) go through this too.\n // `injectContextIntoResponse` skips non-object values so SI tools\n // that override `context` as a string on the request don't leak the\n // string into the response envelope.\n //\n // `sanitizeAdcpErrorEnvelope` re-applies `ADCP_ERROR_FIELD_ALLOWLIST`\n // as a runtime belt-and-suspenders for handlers that build an error\n // envelope outside `adcpError()` — `adcpError()` already filters its\n // own output, but a hand-rolled `{ isError, structuredContent:\n // { adcp_error: ... } }` would otherwise ship unfiltered.\n const finalizeProtocolEnvelope = (response: McpToolResponse): McpToolResponse => {\n sanitizeAdcpErrorEnvelope(response);\n // Two-layer error emission: when the tool's response schema\n // declares an Error arm (`errors: [...]` required), mirror\n // `adcp_error` ↔ `errors[]` so both spec-mandated layers are\n // present on the wire. Order: AFTER sanitize so we project\n // the allowlist-filtered envelope; BEFORE context/version\n // injection so those run on the final two-layer payload.\n enrichErrorTwoLayer(response, toolName, requestErrorArms);\n normalizeMediaBuyStatusCollision(response, toolName);\n injectEnvelopeStatusIntoResponse(response, toolName);\n injectContextIntoResponse(response, params.context);\n injectVersionIntoResponse(response, requestRelease.wireVersion);\n return response;\n };\n const finalize = (response: McpToolResponse): McpToolResponse =>\n applyResponseEnhancer(finalizeProtocolEnvelope(response));\n\n if (releaseError) return finalize(releaseError);\n if (!releaseDefinesTool(toolName, requestRelease)) {\n return finalize(\n adcpError('VERSION_UNSUPPORTED', {\n message: `${toolName} is not defined in the selected AdCP release ${requestRelease.validationVersion}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n const operationIdError = pushOperationIdError(params, requestRelease);\n if (operationIdError) return finalize(operationIdError);\n\n // --- Buyer-agent registry resolution (#1269 / #1292) ---\n // Runs after `authInfo` is populated and before account resolution\n // so adopters' `resolveAccount` callbacks see `ctx.agent`. The\n // registry receives the kind-discriminated `credential` (Stage 3)\n // synthesized by the framework's built-in authenticators in\n // `serve.ts:attachAuthInfo`; factories route on `credential.kind`\n // and return null when no credential was stamped (custom adopter\n // auth callbacks that haven't migrated).\n if (agentRegistry !== undefined) {\n try {\n // Stage 3 of #1269: pass the kind-discriminated `credential`\n // synthesized in `serve.ts:attachAuthInfo` (and hoisted to\n // top-level above) into the registry. Factory functions\n // (`signingOnly` / `bearerOnly` / `mixed`) route on\n // `credential.kind`; absent credential → factories return\n // null → ctx.agent stays undefined.\n const resolved = await agentRegistry.resolve({\n ...(ctx.authInfo?.credential !== undefined && { credential: ctx.authInfo.credential }),\n ...(ctx.authInfo?.extra !== undefined && { extra: ctx.authInfo.extra }),\n input: params,\n });\n if (resolved != null) {\n // Shallow-freeze the resolved record so downstream code cannot\n // accidentally mutate `status`, `agent_url`, or other own\n // properties. NOTE: `Object.freeze` on the `billing_capabilities`\n // Set locks the Set object's own properties but does NOT\n // protect the internal `[[SetData]]` slot — `.add()` /\n // `.delete()` / `.clear()` still mutate. `ReadonlySet` is a\n // TypeScript-only contract; adopters constructing a Set MUST\n // NOT rely on freeze preventing membership changes at runtime.\n // The billing-capability check only reads via `.has()`,\n // so adopter mis-mutation would only affect the same request's\n // own logic — no cross-request leak.\n if (!Object.isFrozen(resolved)) {\n // Map-backed wrappers and other Set-shaped types skip the\n // Set-freeze branch; the outer record's freeze still applies.\n if (resolved.billing_capabilities instanceof Set) {\n Object.freeze(resolved.billing_capabilities);\n }\n Object.freeze(resolved);\n }\n ctx.agent = resolved;\n // Adopters reading the registry's view of `agent_url` get it\n // from `ctx.agent.agent_url` (the resolved `BuyerAgent`\n // record). Stage 3 of #1269 deliberately does NOT stamp a\n // top-level `agent_url` on `ctx.authInfo` — that would\n // invite handler code to gate on a non-cryptographically-\n // verified URL while the spec (adcontextprotocol/adcp#3831)\n // requires verified `agent_url` reads to come from the\n // `http_sig` credential variant. Adopters who use bearer or\n // OAuth credentials get a registry-resolved `ctx.agent` but\n // NO verified `agent_url` — that's correct: bearer auth\n // doesn't prove the agent_url cryptographically.\n\n // --- Status enforcement (Stage 4 of #1269) ---\n // Reject new requests from `suspended` / `blocked` agents\n // with the dedicated 3.1 codes `AGENT_SUSPENDED` /\n // `AGENT_BLOCKED` (adcp#3906 consolidates the 3.0.5\n // `PERMISSION_DENIED + details.status` placeholder shape).\n // In-flight tasks owned by a now-suspended agent are NOT\n // retroactively cancelled — this seam runs once per\n // synchronous request, not on `tasks_get` polls or\n // background webhook deliveries. Sellers who need hard\n // cutoff implement that in their platform method via\n // `BuyerAgent.status` checks (the resolved record is\n // available on every method that takes ctx.agent).\n //\n // Recovery is `terminal` for both — a buyer cannot\n // \"wait out\" a suspension by retrying the same request.\n // The transient-vs-permanent distinction lives at the\n // seller's `BuyerAgent.status` record (suspension may\n // lift via re-onboarding), not on the wire envelope.\n // The placeholder shape's `recovery: 'transient'` for\n // suspended contradicted the no-retry MUST.\n if (resolved.status === 'suspended' || resolved.status === 'blocked') {\n return finalize(\n adcpError(resolved.status === 'suspended' ? 'AGENT_SUSPENDED' : 'AGENT_BLOCKED', {\n message:\n resolved.status === 'suspended'\n ? 'Buyer agent is suspended. Contact the seller to restore access.'\n : 'Buyer agent is blocked.',\n recovery: 'terminal',\n })\n );\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Buyer-agent registry resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Buyer-agent registry resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n const toolIsMutating = isMutatingTask(toolName);\n const requestIsStateChanging = requestUsesIdempotency(toolName, params);\n const hasIdempotencyKeyField = Object.prototype.hasOwnProperty.call(params, 'idempotency_key');\n const requestUsesOptionalIdempotency = toolName === 'get_products' && hasIdempotencyKeyField;\n let suppliedIdempotencyKey = typeof params.idempotency_key === 'string' ? params.idempotency_key : undefined;\n // The 3.2 compatibility schema deliberately leaves the finalize key\n // optional. Replay a supplied key, but do not reject older callers\n // that omit it. SDK 14 buyers auto-inject one on this path.\n const requestUsesReplay = toolIsMutating || requestIsStateChanging || requestUsesOptionalIdempotency;\n if (hasInvalidGetProductsFinalizeIntent(toolName, params)) {\n return finalize(\n adcpError('INVALID_REQUEST', {\n message:\n 'get_products finalize requires buying_mode refine and an exclusive array of proposal-scoped finalize entries with non-empty proposal_id values',\n field: 'refine',\n })\n );\n }\n if (requestIsStateChanging && !toolIsMutating && !idempotency && !idempotencyDisabled) {\n if (!warnedAboutOptionalReplayWithoutIdempotency) {\n warnedAboutOptionalReplayWithoutIdempotency = true;\n logger.error(\n 'createAdcpServer: get_products proposal finalization was refused because no idempotency store is configured.'\n );\n }\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Proposal finalization requires an idempotency store',\n })\n );\n }\n if (requestIsStateChanging && !toolIsMutating && idempotency && suppliedIdempotencyKey === undefined) {\n // The 3.2 compatibility schema leaves this key optional for older\n // callers. Derive a stable server-side key from the canonical\n // finalize request so the compatibility path remains replay-safe\n // instead of either double-executing or becoming a breaking\n // missing-field rejection.\n // Hash the request directly: hashPayload's exclusion rules are\n // intentionally shallow and apply to these top-level retry-only\n // fields. Wrapping `params` would accidentally make refreshed\n // context/governance/webhook credentials mint a different key.\n suppliedIdempotencyKey = `compat_finalize_${hashPayload(params)}`;\n }\n if (\n requestUsesOptionalIdempotency &&\n !toolIsMutating &&\n !idempotency &&\n !idempotencyDisabled &&\n !warnedAboutOptionalReplayWithoutIdempotency\n ) {\n warnedAboutOptionalReplayWithoutIdempotency = true;\n logger.error(\n 'createAdcpServer: get_products was called with idempotency_key but no idempotency store is configured. ' +\n 'Replay protection is unavailable; configure idempotency or explicitly disable it.'\n );\n }\n\n // Field-disagreement detection per spec PR `adcontextprotocol/adcp#3493`:\n // when the request carries both `adcp_version` (string, AdCP 3.1+)\n // and `adcp_major_version` (integer, deprecated) and the majors\n // disagree, the server MUST return `VERSION_UNSUPPORTED`. Catches\n // a buyer that pinned a string but kept a stale integer in their\n // call-site config — the discrepancy is silent drift otherwise.\n //\n // Intentionally runs before the `requestValidationMode === 'off'`\n // short-circuit below: this is a spec MUST, not opt-in validation.\n // Production servers run with validation off by default; without\n // this check, a stale-integer drift on those servers would silently\n // dispatch to the wrong schema bundle.\n //\n // Coerces a stringified `adcp_major_version` (e.g. `\"3\"` from a\n // buyer that JSON-stringified a number) before comparing — AJV\n // strict-mode rejects this in dev, but production-default off-mode\n // would otherwise let the bypass through.\n const reqAdcpVersion = (params as { adcp_version?: unknown }).adcp_version;\n const reqAdcpMajorRaw = (params as { adcp_major_version?: unknown }).adcp_major_version;\n const reqAdcpMajor =\n typeof reqAdcpMajorRaw === 'number'\n ? reqAdcpMajorRaw\n : typeof reqAdcpMajorRaw === 'string'\n ? Number.parseInt(reqAdcpMajorRaw, 10)\n : undefined;\n if (typeof reqAdcpVersion === 'string' && reqAdcpMajor !== undefined && Number.isFinite(reqAdcpMajor)) {\n const stringMajor = parseAdcpMajorVersion(reqAdcpVersion);\n if (Number.isFinite(stringMajor) && stringMajor !== reqAdcpMajor) {\n return finalize(\n adcpError('VERSION_UNSUPPORTED', {\n message:\n `Request carries adcp_version=\"${reqAdcpVersion}\" (major ${stringMajor}) and ` +\n `adcp_major_version=${JSON.stringify(reqAdcpMajorRaw)}; majors must agree.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n }\n\n // Single-field rejection (issue #1075). The dual-field check above\n // catches drift between `adcp_version` and `adcp_major_version` when\n // both are present. A buyer that sends only one field — typically a\n // conformance harness probing the seller's `VERSION_UNSUPPORTED`\n // path — bypasses that check; the seller would otherwise dispatch\n // against its server-pinned bundle and the buyer's claim would\n // silently no-op. Resolve the effective major from whichever field\n // the buyer set, then reject if it falls outside the seller's\n // advertised window.\n //\n // The advertised window is the union of `major_versions` and parsed\n // majors from `supported_versions` (3.1+ release-precision strings),\n // with a fallback to the server pin's major when both lists are\n // absent — see `getAdvertisedSupportedMajors`. Same precedence\n // governs the `supported_versions` echo in the error envelope so\n // buyers can downgrade and retry.\n const effectiveReqMajor =\n reqAdcpMajor !== undefined && Number.isFinite(reqAdcpMajor)\n ? reqAdcpMajor\n : typeof reqAdcpVersion === 'string'\n ? parseAdcpMajorVersion(reqAdcpVersion)\n : undefined;\n if (effectiveReqMajor !== undefined && Number.isFinite(effectiveReqMajor)) {\n const supportedMajors = getAdvertisedSupportedMajors(capConfig, adcpVersion);\n if (!supportedMajors.has(effectiveReqMajor)) {\n const claimed =\n typeof reqAdcpVersion === 'string'\n ? `adcp_version=\"${reqAdcpVersion}\"`\n : `adcp_major_version=${JSON.stringify(reqAdcpMajorRaw)}`;\n const supportedList = [...supportedMajors].sort((a, b) => a - b).join(', ');\n return finalize(\n adcpError('VERSION_UNSUPPORTED', {\n message: `Request claims ${claimed} (major ${effectiveReqMajor}); this seller supports major ${supportedList}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n }\n\n // --- Credential discipline scan (opt-in) ---\n // Runs before request validation so the rejection is uniform\n // whether validation is `'off'`, `'warn'`, or `'strict'`. Closes\n // the buyer-args credential-smuggling vector class — round-1\n // top-level, round-2 nested-context, round-3 nested-ext from\n // PR scope3data/agentic-adapters#248. Args-bag scan only;\n // `authInfo` and `ctx_metadata` are not scanned (those are the\n // blessed credential channels). `'lax'` short-circuits.\n //\n // Bypasses `finalize` deliberately — `injectContextIntoResponse`\n // echoes `params.context` back into every response, which would\n // re-export the credential the scan just caught. The rejection\n // envelope reports paths (not values) and skips correlation_id\n // / version injection on this path.\n if (credentialPolicy !== undefined) {\n const effectivePolicy = resolveCredentialPolicyForTool(credentialPolicy, toolName);\n if (effectivePolicy !== 'lax') {\n const hits = scanArgsForCredentials(params, credentialPolicyPatterns);\n // Granular allow-list: filter hits by the per-tool\n // allowlist. Adopters whose tool legitimately accepts a\n // specific buyer-presented credential field list it here;\n // other credential-shaped keys still reject. String mode\n // ('authInfo-only') means no allowlist — every hit blocks.\n const blockedPaths =\n typeof effectivePolicy === 'object' ? hits.filter(p => !effectivePolicy.allow.includes(p)) : hits;\n if (blockedPaths.length > 0) {\n // Spec-correct code: the caller is authenticated and the\n // payload is schema-valid (every AdCP request schema sets\n // `additionalProperties: true`). What's refused is the\n // SELLER POLICY of \"credentials must arrive on authInfo,\n // not in args\". That's `PERMISSION_DENIED` per\n // `enums/error-code.json`, not `INVALID_REQUEST` (which\n // is for malformed/schema violations). `details.scope:\n // 'credentials'` mirrors the existing agent-status\n // rejection's `details.scope: 'agent'`.\n //\n // Deliberately omit `field` — it implies a single offending\n // path, which under-discloses when several vectors are\n // present together. Full list lives in\n // `details.credential_paths`.\n return applyResponseEnhancer(\n adcpError('PERMISSION_DENIED', {\n message:\n 'Request args carry credential-shaped keys. Credentials must arrive on authInfo, not in the request body.',\n recovery: 'correctable',\n details: { scope: 'credentials', credential_paths: blockedPaths },\n })\n );\n }\n }\n }\n\n // --- authInfo.extra credential scan (opt-in via #1539) ---\n // FULLY ORTHOGONAL to the args-bag scan above. Whereas the args\n // scan branches on `policy` mode and per-tool overrides\n // (`'lax'` short-circuits), `scanAuthInfo: true` ALWAYS fires\n // when set. The two settings answer different questions:\n //\n // - `policy` / `tools` — does this server / tool accept buyer\n // credentials in the args bag?\n // - `scanAuthInfo` — does authInfo.extra carry credential-\n // shaped keys that adopter handler code or log lines could\n // leak?\n //\n // Per-tool `'lax'` opt-out only affects args. authInfo.extra\n // is server-internal; adopters who legitimately stamp\n // credential-shaped values into it should restructure the\n // authenticator (extra is the wrong layer for credentials)\n // rather than per-tool-disable the scan.\n //\n // Wire-envelope discipline (per #1539 design): args-bag hits\n // surface in `details.credential_paths` (the buyer already\n // knows what they sent); authInfo.extra hits are LOG-ONLY.\n // Disclosing authInfo.extra paths to the buyer would create\n // a probing oracle for an internal value the buyer has no\n // read access to. The wire envelope reports a coarse signal:\n // `details.scope: 'credentials'`, generic message, no paths.\n if (\n credentialPolicy !== undefined &&\n typeof credentialPolicy !== 'string' &&\n credentialPolicy.scanAuthInfo === true\n ) {\n const extra = ctx.authInfo?.extra;\n if (extra !== null && extra !== undefined && typeof extra === 'object') {\n const authInfoHits = scanArgsForCredentials(extra, credentialPolicyPatterns);\n if (authInfoHits.length > 0) {\n // Wrap the log call defensively. Adopter loggers that throw\n // on serialization (Pino circular-ref edge cases, custom\n // transports that reject deep nesting, OTel exporters\n // mid-flush) would otherwise fault the rejection path and\n // surface as a generic 500 / unhandled rejection instead of\n // the intended PERMISSION_DENIED. The asymmetry with the\n // args-scan rejection (which doesn't log) made this a\n // logger-misconfig DoS vector before this guard.\n try {\n logger.warn('credentialPolicy: authInfo.extra carries credential-shaped keys', {\n tool: toolName,\n paths: authInfoHits.map(p => `authInfo.extra.${p}`),\n });\n } catch {\n // Swallow — the rejection envelope is the load-bearing\n // signal; losing the diagnostic log is acceptable when\n // the alternative is failing the request entirely.\n }\n return applyResponseEnhancer(\n adcpError('PERMISSION_DENIED', {\n message:\n 'Request authentication context carries credential-shaped keys. Configure your authenticator to keep credentials off authInfo.extra.',\n recovery: 'terminal',\n details: { scope: 'credentials' },\n })\n );\n }\n }\n }\n\n // --- Request schema validation (opt-in) ---\n // Runs before idempotency so drifted payloads never touch the\n // replay cache. `off` short-circuits without calling AJV.\n // Capability policy is not optional schema validation: an adopter\n // that disables AJV must still never receive a dimension it did not\n // advertise. Run that gate unconditionally for this forward tool.\n if (toolName === 'refine_proposals' && proposalRefinementCapabilities && Array.isArray(params.refinements)) {\n const supported = new Set(proposalRefinementCapabilities.supported_dimensions);\n for (const [index, candidate] of params.refinements.entries()) {\n if (!isPlainObject(candidate)) continue;\n const unsupported = refinementDimensions(candidate as never).find(dimension => !supported.has(dimension));\n if (unsupported) {\n return finalize(\n adcpError('UNSUPPORTED_FEATURE', {\n message: `seller does not advertise proposal refinement dimension ${unsupported}`,\n field: `refinements[${index}]`,\n details: {\n unsupported_dimension: unsupported,\n supported_dimensions: [...proposalRefinementCapabilities.supported_dimensions],\n },\n })\n );\n }\n }\n }\n if (requestValidationMode !== 'off') {\n const outcome = validateFrameworkPayload(\n toolName,\n 'request',\n params,\n requestRelease.validationVersion,\n proposalRefinementCapabilities\n );\n if (!outcome.valid) {\n if ('refinementError' in outcome && outcome.refinementError?.code === 'UNSUPPORTED_FEATURE') {\n return finalize(\n adcpError('UNSUPPORTED_FEATURE', {\n message: outcome.refinementError.message,\n ...(outcome.refinementError.field !== undefined && {\n field: outcome.refinementError.field,\n }),\n ...(outcome.refinementError.details !== undefined && {\n details: outcome.refinementError.details,\n }),\n })\n );\n }\n // When `idempotency: 'disabled'` is set, drop the synthetic\n // \"missing idempotency_key\" failure on mutating tools — the\n // operator has explicitly opted out of enforcement and would\n // otherwise need to UUID-inject every test payload to satisfy\n // the spec-required field. All other schema issues still fail.\n //\n // The exact-match `pointer === '/idempotency_key'` is\n // load-bearing: AJV builds the pointer from `instancePath +\n // /missingProperty`, so today every mutating tool's\n // idempotency_key sits at the top level (instancePath = '',\n // pointer = '/idempotency_key'). If a future spec revision\n // ever nests this field under another object, the new pointer\n // (`/foo/idempotency_key`) won't match this filter and the\n // strict-mode failure will correctly bubble up — drift is\n // surfaced rather than silently swallowed.\n const issues =\n idempotencyDisabled && requestIsStateChanging\n ? outcome.issues.filter(i => !(i.keyword === 'required' && i.pointer === '/idempotency_key'))\n : outcome.issues;\n if (issues.length > 0) {\n if (requestValidationMode === 'strict') {\n // Thread `exposeSchemaPath` the same way response-side does\n // so request-side schemaPath also ships in dev and stays\n // gated in production. Prior to this, request-side silently\n // stripped schemaPath even in dev — asymmetric with response-side.\n const payload = buildAdcpValidationErrorPayload(toolName, 'request', issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n });\n return finalize(adcpError('VALIDATION_ERROR', payload));\n }\n logger.warn(\n `Schema validation warning (request) for ${toolName}: ${formatIssues(issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues,\n }\n );\n }\n }\n }\n\n // --- Account resolution ---\n if (hasAccount && params.account != null && resolveAccount) {\n try {\n const account = await resolveAccount(params.account, {\n toolName: toolName as AdcpServerToolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n if (account == null) {\n logger.warn('Account not found', { tool: toolName, account: params.account });\n return finalize(\n adcpError('ACCOUNT_NOT_FOUND', {\n message: 'The specified account does not exist',\n field: 'account',\n suggestion: 'Use list_accounts to discover available accounts, or sync_accounts to create one',\n })\n );\n }\n ctx.account = account;\n } catch (err) {\n // Typed errors propagate verbatim — both the already-projected\n // envelope shape (`isThrownAdcpError`) and the raw class throw\n // (`AdcpError instanceof`). Resolvers can surface\n // `INVALID_REQUEST` for inline `account_id` against an\n // `'implicit'`-resolution platform (#1364), or any other typed\n // wire error, without coercion. Generic exceptions still\n // project to SERVICE_UNAVAILABLE so upstream leaks don't cross\n // the trust boundary.\n if (isThrownAdcpError(err)) return finalize(err);\n if (err instanceof AdcpError) {\n return finalize(projectThrownAdcpError(err));\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Account resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n } else if ((!hasAccount || params.account == null) && resolveAccountFromAuth) {\n // Auth-derived path for tools whose wire schema lacks an `account`\n // field (provide_performance_feedback, list_creative_formats, the\n // `tasks/get` polling path). Single-tenant agents return their\n // singleton; principal-keyed agents look up by authInfo. A `null`\n // return is allowed — handler sees ctx.account undefined and\n // either tolerates it (publisher-wide reads) or throws AdcpError.\n try {\n const account = await resolveAccountFromAuth({\n toolName: toolName as AdcpServerToolName,\n authInfo: ctx.authInfo,\n ...(ctx.agent != null && { agent: ctx.agent }),\n input: params,\n });\n if (account != null) ctx.account = account;\n } catch (err) {\n // Same typed-error pass-through as the explicit `resolveAccount`\n // catch above — both the already-projected envelope shape and\n // the raw `AdcpError` class throw propagate verbatim. Generic\n // exceptions project to SERVICE_UNAVAILABLE.\n if (isThrownAdcpError(err)) return finalize(err);\n if (err instanceof AdcpError) {\n return finalize(projectThrownAdcpError(err));\n }\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Auth-derived account resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Account resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // --- Sandbox-only enforcement (Phase 1.5 of #1269) ---\n // Runs after account resolution so we can compare the resolved\n // account's `sandbox` flag against the agent's `sandbox_only`\n // capability. Account-less tools (provide_performance_feedback,\n // list_creative_formats, etc.) pass the gate — they don't\n // operate on a specific account, so the sandbox/production axis\n // doesn't apply.\n //\n // Defense-in-depth for test agents (CI runners, internal QA\n // agents, partner pre-prod environments): if a sandbox-only\n // agent's credential leaks, blast radius is bounded to sandbox\n // accounts. Production agents leave `sandbox_only` unset.\n // Strict-by-default: any non-Account shape (legacy v5 adopters,\n // bespoke account types) lacking the `sandbox` field reads as\n // `undefined !== true → reject`. That's correct: a sandbox-only\n // agent operating against an unknown-shape account is the\n // case where rejection is the safe default — adopters who want\n // to opt in either flip the agent's `sandbox_only` off or\n // populate `sandbox: true` on their resolved account.\n if (\n ctx.agent?.sandbox_only === true &&\n ctx.account !== undefined &&\n (ctx.account as { sandbox?: boolean }).sandbox !== true\n ) {\n return finalize(\n adcpError('PERMISSION_DENIED', {\n message: 'Buyer agent is sandbox-only; this request targets a non-sandbox account.',\n recovery: 'terminal',\n details: { scope: 'agent', reason: 'sandbox-only' },\n })\n );\n }\n\n // --- Session key resolution ---\n if (resolveSessionKey) {\n try {\n const sessionKey = await resolveSessionKey({\n toolName: toolName as AdcpServerToolName,\n params,\n account: ctx.account,\n ...(ctx.agent != null && { agent: ctx.agent }),\n });\n if (sessionKey !== undefined) ctx.sessionKey = sessionKey;\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Session key resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Session key resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n if (CALLER_SCOPED_MUTATION_TOOLS.has(toolName)) {\n if (ctx.authInfo === undefined && ctx.agent === undefined) {\n return finalize(\n adcpError('AUTH_MISSING', {\n message: `${toolName} requires an authenticated caller principal`,\n })\n );\n }\n try {\n const scope =\n toolName === 'sync_agent_notification_configs'\n ? await config.protocol!.resolveScope!(ctx, params)\n : await config.governance!.resolveReportPlanAdjustmentScope!(ctx, params);\n if (!scope?.tenant_id || !scope.principal_id) {\n throw new Error('scope resolver must return non-empty tenant_id and principal_id');\n }\n ctx.callerMutationScope = Object.freeze({ ...scope });\n } catch (err) {\n if (err instanceof AdcpError) return finalize(projectThrownAdcpError(err));\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Caller-scoped mutation resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Caller-scoped mutation resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // Compact lifecycle mutations are account- and principal-scoped.\n // Enforce both before idempotency lookup: a cache hit returns without\n // invoking the adopter handler, so a handler-only gate would allow an\n // unauthenticated retry to receive a prior authenticated response\n // whenever a custom principal resolver collapses their namespaces.\n if (COMPACT_MEDIA_BUY_MUTATION_TOOLS.has(toolName)) {\n if (authenticatedPrincipalForContext(ctx.authInfo, ctx.agent) === undefined) {\n return finalize(\n adcpError('AUTH_MISSING', {\n message: `${toolName} requires an authenticated buyer principal`,\n })\n );\n }\n if (requireCompactMutationAccountScope && ctx.account == null) {\n return finalize(\n adcpError('ACCOUNT_NOT_FOUND', {\n message: `${toolName} requires a resolved account scope`,\n })\n );\n }\n }\n\n if (toolName === 'refine_proposals') {\n if (ctx.authInfo === undefined && ctx.agent === undefined) {\n return finalize(\n adcpError('AUTH_MISSING', {\n message: 'refine_proposals requires an authenticated buyer principal',\n })\n );\n }\n try {\n const scope = await config.proposalNegotiation!.resolveScope(ctx);\n if (!scope?.tenant_id || !scope.principal_id) {\n throw new Error('resolveScope must return non-empty tenant_id and principal_id');\n }\n ctx.proposalRefinementScope = Object.freeze({ ...scope });\n } catch (err) {\n if (err instanceof AdcpError) return finalize(projectThrownAdcpError(err));\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Proposal refinement scope resolution failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Proposal refinement scope resolution failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // --- idempotency_key shape gate (runs even in disabled mode) ---\n // Defense-in-depth against buyers that bypass MCP schema\n // validation (different transport, bespoke client) AND against\n // disabled-mode environments where the replay middleware below is\n // skipped. Low-entropy keys pollute the cache and enable\n // enumeration; keys containing the internal scope-separator byte\n // would collide with the cache's scope tuple. Even in disabled\n // mode (no cache, no enforcement) a malformed key flowing into\n // handler logs is a debuggability hazard — so we reject the\n // shape whenever a key was supplied, regardless of whether the\n // replay middleware will execute. Missing-key enforcement\n // remains scoped to the middleware below (gated on `idempotency`),\n // so disabled mode tolerates absence per the schema-filter\n // contract earlier in this dispatcher.\n if (\n (requestIsStateChanging || requestUsesOptionalIdempotency) &&\n hasIdempotencyKeyField &&\n (typeof params.idempotency_key !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(params.idempotency_key))\n ) {\n return finalize(\n adcpError('INVALID_REQUEST', {\n message: 'idempotency_key must match the spec pattern ^[A-Za-z0-9_.:-]{16,255}$',\n field: 'idempotency_key',\n })\n );\n }\n\n // --- Idempotency (mutating tools + get_products proposal finalize) ---\n let idempotencyCheck:\n | { key: string; principal: string; payloadHash: string; claimToken: string; extraScope?: string }\n | undefined;\n if (idempotency && requestUsesReplay) {\n const key = suppliedIdempotencyKey;\n if (!key) {\n return finalize(\n adcpError('INVALID_REQUEST', {\n message: 'idempotency_key is required on state-changing requests',\n field: 'idempotency_key',\n })\n );\n }\n // Pattern check already ran in the shape gate above. By this\n // point `key` is guaranteed to match IDEMPOTENCY_KEY_PATTERN.\n const callerMutationPrincipal = ctx.callerMutationScope\n ? JSON.stringify([\n ctx.callerMutationScope.tenant_id,\n ctx.callerMutationScope.principal_id,\n ctx.callerMutationScope.account_id ?? null,\n ])\n : undefined;\n const resolvedPrincipal =\n (resolveIdempotencyPrincipal\n ? resolveIdempotencyPrincipal(ctx, params, toolName as AdcpServerToolName)\n : (callerMutationPrincipal ?? ctx.sessionKey)) ?? '';\n const serveScope = (server as unknown as Record<symbol, unknown>)[ADCP_SERVE_IDEMPOTENCY_SCOPE];\n const principal =\n resolvedPrincipal && typeof serveScope === 'string' && serveScope.length > 0\n ? JSON.stringify([serveScope, resolvedPrincipal])\n : resolvedPrincipal;\n if (!principal) {\n logger.error('Idempotency principal unresolved', { tool: toolName });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'Idempotency principal could not be resolved — configure resolveSessionKey or resolveIdempotencyPrincipal',\n })\n );\n }\n // SI `si_send_message` is scoped per-session — the same key under\n // two different sessions must not replay into each other. The\n // caller's session_id enters the scope tuple so each session has\n // its own idempotency namespace.\n const extraScope = resolveExtraScope(\n toolName,\n params,\n ctx.account,\n ctx.sessionKey,\n ctx.proposalRefinementScope,\n ctx.callerMutationScope\n );\n const idempotencyPayload = buildIdempotencyPayload(toolName, params, ctx.account, ctx.sessionKey);\n\n try {\n const checkResult = await idempotency.check({ principal, key, payload: idempotencyPayload, extraScope });\n if (checkResult.kind === 'replay') {\n // The cache stores the already-formatted envelope (so\n // non-deterministic wrap fields like `confirmed_at` are\n // pinned to the first execution's values). Clone before\n // mutating so envelope stamps (replayed, echo-back context)\n // don't leak into the cache — the backend also clones on\n // read, but belt-and-suspenders: handler-returned objects\n // can alias pieces of the formatted envelope.\n const cachedFormatted = cloneFormattedResponse(checkResult.response as McpToolResponse);\n // Only stamp `replayed: true` on success envelopes — the\n // field is defined for successful replays, and transient\n // error cache entries (VALIDATION_ERROR from strict-mode\n // drift) are retry-storm guards, not spec replays.\n if (!isErrorResponse(cachedFormatted)) {\n stampReplayed(cachedFormatted);\n }\n // The cached envelope has already passed through the adopter's\n // response enhancer. Reapply only protocol-owned per-request\n // stamps here: enhancers may be non-idempotent (for example,\n // appending audit metadata), so invoking one again would make\n // a replay differ from the original response.\n return finalizeProtocolEnvelope(cachedFormatted);\n }\n if (checkResult.kind === 'conflict') {\n return finalize(\n adcpError('IDEMPOTENCY_CONFLICT', {\n message:\n 'idempotency_key was used earlier with a different canonical payload. Do not blindly retry with a fresh key: reconcile the prior operation by natural key, then continue only after confirming whether it succeeded.',\n })\n );\n }\n if (checkResult.kind === 'expired') {\n return finalize(\n adcpError('IDEMPOTENCY_EXPIRED', {\n message: `idempotency_key is past the seller's replay window (${idempotency.ttlSeconds}s). Use a fresh UUID v4, or look up the resource by natural key if the prior call succeeded.`,\n })\n );\n }\n if (checkResult.kind === 'in-flight') {\n // A parallel request is currently executing this same key.\n // Surface AdCP 3.1's `IDEMPOTENCY_IN_FLIGHT` with a transient\n // recovery + store-derived `retry_after`. Buyer SDKs that\n // already auto-retry transient + retry_after replay shortly;\n // the prior request either lands the cached response or\n // (different payload) triggers IDEMPOTENCY_CONFLICT.\n return finalize(\n adcpError('IDEMPOTENCY_IN_FLIGHT', {\n message: 'A parallel request with the same idempotency_key is still in flight. Retry shortly.',\n recovery: 'transient',\n retry_after: checkResult.retryAfterSeconds,\n })\n );\n }\n idempotencyCheck = {\n key,\n principal,\n payloadHash: checkResult.payloadHash,\n claimToken: checkResult.claimToken,\n extraScope,\n };\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Idempotency check failed', { tool: toolName, error: reason });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Idempotency check failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n }\n\n // Keep the request owner fence alive for the entire handler and\n // response-publication path. Without renewal, a mutation running\n // longer than the 120-second claim lease could be reclaimed and\n // executed concurrently by a retry. Renewal is serialized so a\n // slow backend cannot accumulate overlapping timer callbacks; the\n // final save/release CAS remains the authoritative ownership check.\n let claimRenewalTimer: ReturnType<typeof setInterval> | undefined;\n let claimRenewalPending: Promise<void> | undefined;\n if (idempotencyCheck && idempotency) {\n const renewClaim = () => {\n if (claimRenewalPending) return;\n claimRenewalPending = idempotency\n .renew({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n })\n .catch(err => {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency claim renewal failed; final publication will re-check ownership', {\n tool: toolName,\n error: reason,\n });\n })\n .finally(() => {\n claimRenewalPending = undefined;\n });\n };\n claimRenewalTimer = setInterval(renewClaim, IDEMPOTENCY_CLAIM_RENEW_INTERVAL_MS);\n if (typeof claimRenewalTimer === 'object' && 'unref' in claimRenewalTimer) claimRenewalTimer.unref();\n }\n\n // --- Handler ---\n let mutationHandlerCompleted = false;\n try {\n if (webhookEmitter) {\n const tenantScope = webhookTenantScopeForContext(ctx);\n const scopedEmitter =\n tenantScope === undefined ? configuredWebhookEmitter! : webhookEmitter.forTenantScope(tenantScope);\n ctx.emitWebhook = scopedEmitter.emit.bind(scopedEmitter);\n }\n const result = await handler(params, ctx);\n mutationHandlerCompleted = true;\n // Narrow Error / Submitted arms of the *Response union before\n // reaching the success-arm builder: wrap() on an Error payload\n // would still serialize it but apply success-shaped defaults\n // (revision, confirmed_at, 'Media buy undefined created') to\n // a shape that doesn't have those fields. Routing here keeps\n // the wire shape correct regardless of which arm the handler\n // chose to return.\n let formatted: McpToolResponse;\n if (isFormattedResponse(result)) {\n formatted = result;\n } else if (isSubmittedEnvelope(result)) {\n formatted = wrapSubmittedEnvelope(result);\n } else if (isErrorArm(result)) {\n // Log-warn (always) on spec-violating Error items — required\n // `code`/`message` are spec-mandatory on core/error.json. We\n // must fail closed here: error envelopes skip response-schema\n // validation, and blindly wrapping malformed primitives can leak\n // secret-bearing strings in `errors[]`.\n const malformed = (result.errors as unknown[]).some(\n e =>\n e == null ||\n typeof e !== 'object' ||\n typeof (e as Record<string, unknown>).code !== 'string' ||\n typeof (e as Record<string, unknown>).message !== 'string'\n );\n if (malformed) {\n logger.warn(`Handler returned ${toolName} Error arm with spec-violating errors[]`, {\n tool: toolName,\n count: (result.errors as unknown[]).length,\n });\n const errPayload = buildAdcpValidationErrorPayload(\n toolName,\n 'response',\n [\n {\n pointer: '/errors',\n message: 'must contain Error objects with string code and message fields',\n keyword: 'type',\n schemaPath: '#/properties/errors/items',\n hint: 'Return errors as `{ code, message }` objects; do not return raw strings or exception values.',\n },\n ],\n { exposeSchemaPath: exposeErrorDetails }\n );\n formatted = adcpError('VALIDATION_ERROR', errPayload);\n } else {\n formatted = wrapErrorArm(result);\n }\n } else {\n formatted = wrap(result);\n }\n\n // --- Test-controller bridge: augment read-side tools with seeded fixtures. ---\n // Each per-tool callback (`getSeededProducts`, `getSeededCreatives`, ...)\n // is opt-in by presence on the bridge interface. All callbacks share the\n // same triply-gated contract:\n // 1. The bridge is registered AND has the matching callback;\n // 2. The handler returned a success envelope (not an `adcp_error`);\n // 3. The request carries a sandbox marker (account.sandbox === true or\n // context.sandbox === true) AND the applicable resolver produced\n // a trusted account in sandbox/mock mode (legacy sandbox:true is\n // accepted during migration). Unresolved accounts fail closed.\n // For array-collection tools, seeded entries append to the handler's\n // response with seeded winning on id collision (same as `getSeededProducts`).\n // `get_account_financials` is the exception — singleton response, so the\n // seeded entry REPLACES the handler payload when its `account.account_id`\n // matches the request's `account.account_id`.\n // Diagnostic for adopters chasing \"why aren't my fixtures showing\":\n // when the request carries a sandbox marker but the resolved account\n // is explicitly non-sandbox, the gate rejects silently. Emit a\n // `debug` line so the rejection is observable in dev logs without\n // adding noise to production traffic (where the gate's first check\n // — `isSandboxRequestForSeeding` — fails first and never reaches\n // this branch).\n if (\n testControllerBridge &&\n !isErrorResponse(formatted) &&\n isSandboxRequestForSeeding(params) &&\n ctx.account !== undefined &&\n !isSandboxOrMockAccount(ctx.account)\n ) {\n // Include the resolved account_id so the log line is self-\n // diagnostic — an adopter chasing \"why aren't my fixtures\n // showing\" can match the rejected account against their\n // resolveAccount source without correlating across log lines.\n // account_ids appear in normal request logs already; no new\n // PII surface.\n const resolvedAccountId =\n typeof ctx.account === 'object' &&\n ctx.account !== null &&\n typeof (ctx.account as { account_id?: unknown }).account_id === 'string'\n ? ((ctx.account as { account_id?: unknown }).account_id as string)\n : undefined;\n logger.debug(\n 'test-controller bridge: request is sandbox-flagged but resolved account is not sandbox; skipping merge',\n { tool: toolName, resolved_account_id: resolvedAccountId }\n );\n }\n\n if (\n testControllerBridge &&\n !isErrorResponse(formatted) &&\n isSandboxRequestForSeeding(params) &&\n isSandboxOrMockAccount(ctx.account)\n ) {\n const bridgeCtx: TestControllerBridgeContext<TAccount> = { input: params, account: ctx.account };\n\n // get_products\n if (toolName === 'get_products' && testControllerBridge.getSeededProducts) {\n try {\n const rawSeeded = await testControllerBridge.getSeededProducts(bridgeCtx);\n const seeded = filterValidSeededProducts(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetProductsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededProductsIntoResponse(sc, seeded);\n formatted = wrap(merged, _getExplicitResponseSummary(formatted));\n stampBridge(formatted, 'getSeededProducts', toolName, seeded.length);\n }\n }\n } catch (err) {\n // Bridge failures are sandbox-only by construction, so logging +\n // returning the handler's response is the right default — a broken\n // test fixture shouldn't tank the request under test.\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededProducts failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_creatives\n else if (toolName === 'list_creatives' && testControllerBridge.getSeededCreatives) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreatives(bridgeCtx);\n const seeded = filterValidSeededCreatives(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListCreativesResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativesIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreatives', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreatives failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_media_buys\n else if (toolName === 'get_media_buys' && testControllerBridge.getSeededMediaBuys) {\n try {\n const rawSeeded = await testControllerBridge.getSeededMediaBuys(bridgeCtx);\n const seeded = filterValidSeededMediaBuys(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetMediaBuysResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededMediaBuysIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededMediaBuys', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededMediaBuys failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_media_buy_delivery\n else if (toolName === 'get_media_buy_delivery' && testControllerBridge.getSeededMediaBuyDelivery) {\n try {\n const rawSeeded = await testControllerBridge.getSeededMediaBuyDelivery(bridgeCtx);\n const seeded = filterValidSeededMediaBuyDeliveries(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetMediaBuyDeliveryResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededMediaBuyDeliveryIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededMediaBuyDelivery', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededMediaBuyDelivery failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_accounts\n else if (toolName === 'list_accounts' && testControllerBridge.getSeededAccounts) {\n try {\n const rawSeeded = await testControllerBridge.getSeededAccounts(bridgeCtx);\n const seeded = filterValidSeededAccounts(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListAccountsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededAccountsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededAccounts', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededAccounts failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_account_financials (singleton — replace, not append)\n else if (toolName === 'get_account_financials' && testControllerBridge.getSeededAccountFinancials) {\n try {\n const rawSeeded = await testControllerBridge.getSeededAccountFinancials(bridgeCtx);\n const seeded = filterValidSeededAccountFinancials(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetAccountFinancialsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n // Brand+operator `AccountReference` variants don't carry\n // `account_id` on the wire — the framework's resolved\n // account does, so prefer it for the match key.\n const resolvedAccountId =\n ctx.account && typeof ctx.account === 'object' && !Array.isArray(ctx.account)\n ? ((ctx.account as { account_id?: unknown }).account_id as string | undefined)\n : undefined;\n const merged = replaceAccountFinancialsIfSeeded(\n params as import('../types/tools.generated').GetAccountFinancialsRequest,\n sc,\n seeded,\n typeof resolvedAccountId === 'string' && resolvedAccountId.length > 0\n ? resolvedAccountId\n : undefined\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededAccountFinancials', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededAccountFinancials failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_creative_formats\n else if (toolName === 'list_creative_formats' && testControllerBridge.getSeededCreativeFormats) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreativeFormats(bridgeCtx);\n const seeded = filterValidSeededCreativeFormats(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListCreativeFormatsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativeFormatsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreativeFormats', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreativeFormats failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_property_lists / get_property_list — one seeded fixture array\n // feeds both. List path: append-merge with seeded-wins on `list_id`\n // collision. Get path: pick by request.list_id and replace the\n // response's `list` field, preserving handler's resolved data\n // (`identifiers` / `pagination` / `resolved_at` / `cache_valid_until`\n // / `coverage_gaps` / `context` / `ext`).\n else if (\n (toolName === 'list_property_lists' || toolName === 'get_property_list') &&\n testControllerBridge.getSeededPropertyLists\n ) {\n try {\n const rawSeeded = await testControllerBridge.getSeededPropertyLists(bridgeCtx);\n const seeded = filterValidSeededPropertyLists(rawSeeded, logger);\n if (seeded.length > 0) {\n if (toolName === 'list_property_lists') {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListPropertyListsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededPropertyListsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededPropertyLists', toolName, seeded.length);\n }\n } else {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetPropertyListResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replacePropertyListIfSeeded(\n params as import('../types/tools.generated').GetPropertyListRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededPropertyLists', toolName, seeded.length);\n }\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededPropertyLists failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_collection_lists / get_collection_list — symmetric with\n // property lists.\n else if (\n (toolName === 'list_collection_lists' || toolName === 'get_collection_list') &&\n testControllerBridge.getSeededCollectionLists\n ) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCollectionLists(bridgeCtx);\n const seeded = filterValidSeededCollectionLists(rawSeeded, logger);\n if (seeded.length > 0) {\n if (toolName === 'list_collection_lists') {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListCollectionListsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCollectionListsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCollectionLists', toolName, seeded.length);\n }\n } else {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetCollectionListResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceCollectionListIfSeeded(\n params as import('../types/tools.generated').GetCollectionListRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCollectionLists', toolName, seeded.length);\n }\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCollectionLists failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_signals — append-merge by signal_id. Works uniformly across\n // signal-marketplace and signal-owned specialisms (one bridge, both\n // dispatched on the same tool; the per-signal `signal_type` field\n // is the marketplace-vs-owned discriminator).\n else if (toolName === 'get_signals' && testControllerBridge.getSeededSignals) {\n try {\n const rawSeeded = await testControllerBridge.getSeededSignals(bridgeCtx);\n const seeded = filterValidSeededSignals(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetSignalsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededSignalsIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededSignals', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededSignals failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_creative_delivery — append-merge by creative_id;\n // `pagination.total` (when set by the handler) updates by the\n // count of new non-colliding seeded entries. No aggregated-totals\n // recomputation — this response has no top-level totals envelope.\n else if (toolName === 'get_creative_delivery' && testControllerBridge.getSeededCreativeDelivery) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreativeDelivery(bridgeCtx);\n const seeded = filterValidSeededCreativeDelivery(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetCreativeDeliveryResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativeDeliveryIntoResponse(sc, seeded);\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreativeDelivery', toolName, seeded.length);\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreativeDelivery failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_creative_features — `oneOf` envelope. Success arm: merge\n // seeded `CreativeFeatureResult[]` into `results` (dedup by\n // `feature_id`, seeded wins). Error arm: no-op (the helper\n // discriminates by presence of `results: []`).\n else if (toolName === 'get_creative_features' && testControllerBridge.getSeededCreativeFeatures) {\n try {\n const rawSeeded = await testControllerBridge.getSeededCreativeFeatures(bridgeCtx);\n const seeded = filterValidSeededCreativeFeatures(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetCreativeFeaturesResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededCreativeFeaturesIntoResponse(sc, seeded);\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededCreativeFeatures', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededCreativeFeatures failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_brand_identity — singleton replace keyed by `brand_id`.\n // Seeded fixture is authoritative on the GetBrandIdentitySuccess\n // body; handler's `context` / `ext` round-trip. The response is\n // a union (success | error) — the dispatcher already gated on\n // `!isErrorResponse`, so we narrow defensively when reading.\n else if (toolName === 'get_brand_identity' && testControllerBridge.getSeededBrandIdentity) {\n try {\n const rawSeeded = await testControllerBridge.getSeededBrandIdentity(bridgeCtx);\n const seeded = filterValidSeededBrandIdentity(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/core.generated').GetBrandIdentityResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceBrandIdentityIfSeeded(\n params as import('../types/core.generated').GetBrandIdentityRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededBrandIdentity', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededBrandIdentity failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // get_rights — append-merge keyed by `rights_id`. Discovery /\n // search tool (NL `query`); the response carries `rights[]`.\n // Drops to a no-op on the error arm of the response union.\n else if (toolName === 'get_rights' && testControllerBridge.getSeededRights) {\n try {\n const rawSeeded = await testControllerBridge.getSeededRights(bridgeCtx);\n const seeded = filterValidSeededRights(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/core.generated').GetRightsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededRightsIntoResponse(sc, seeded);\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededRights', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededRights failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // si_get_offering — singleton replace keyed by `offering_id`.\n // Stateless catalog lookup; the response's `offering_token` is\n // produced for a future session but the lookup itself does not\n // consume one. Handler's `context` / `ext` round-trip.\n else if (toolName === 'si_get_offering' && testControllerBridge.getSeededSiOffering) {\n try {\n const rawSeeded = await testControllerBridge.getSeededSiOffering(bridgeCtx);\n const seeded = filterValidSeededSiOffering(rawSeeded, logger);\n if (seeded.length > 0) {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').SIGetOfferingResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceSiOfferingIfSeeded(\n params as import('../types/tools.generated').SIGetOfferingRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededSiOffering', toolName, seeded.length);\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededSiOffering failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n\n // list_content_standards / get_content_standards — list returns\n // `{ standards: ContentStandards[] }` (success arm of a union; the\n // error arm is gated out upstream). Get returns `ContentStandards`\n // directly (success arm); replace the ContentStandards body and\n // round-trip handler's `context` / `ext` (both are framework-\n // managed envelope fields per the spec).\n else if (\n (toolName === 'list_content_standards' || toolName === 'get_content_standards') &&\n testControllerBridge.getSeededContentStandards\n ) {\n try {\n const rawSeeded = await testControllerBridge.getSeededContentStandards(bridgeCtx);\n const seeded = filterValidSeededContentStandards(rawSeeded, logger);\n if (seeded.length > 0) {\n if (toolName === 'list_content_standards') {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').ListContentStandardsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = mergeSeededContentStandardsIntoResponse(sc, seeded);\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededContentStandards', toolName, seeded.length);\n }\n }\n } else {\n const sc = formatted.structuredContent as\n | import('../types/tools.generated').GetContentStandardsResponse\n | undefined;\n if (sc && typeof sc === 'object') {\n const merged = replaceContentStandardsIfSeeded(\n params as import('../types/tools.generated').GetContentStandardsRequest,\n sc,\n seeded\n );\n if (merged !== sc) {\n formatted = wrap(merged);\n stampBridge(formatted, 'getSeededContentStandards', toolName, seeded.length);\n }\n }\n }\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('testController.getSeededContentStandards failed; returning handler response unchanged', {\n tool: toolName,\n error: reason,\n });\n }\n }\n }\n\n if (!isErrorResponse(formatted)) {\n if (toolName === 'get_products') {\n formatted =\n normalizeGetProductsCacheScope(formatted, params, ctx.account, ctx.authInfo, exposeErrorDetails) ??\n formatted;\n }\n if (!isErrorResponse(formatted)) {\n normalizeMediaBuyStatusCollision(formatted, toolName);\n injectEnvelopeStatusIntoResponse(formatted, toolName);\n }\n }\n\n // --- Response schema validation (opt-in) ---\n // Runs on the structured payload the handler produced. Errors\n // have their own envelope (`adcp_error`) and are skipped here —\n // their shape is enforced by the adcpError() builder.\n if (responseValidationMode !== 'off' && !isErrorResponse(formatted)) {\n const payload = formatted.structuredContent;\n const outcome = validateFrameworkPayload(toolName, 'response', payload, requestRelease.validationVersion);\n if (!outcome.valid) {\n logger.warn(\n `Schema validation warning (response) for ${toolName}: ${formatIssues(outcome.issues, 3, { rootSchemaId: outcome.schemaId })}`,\n {\n tool: toolName,\n issues: outcome.issues,\n variant: outcome.variant,\n }\n );\n if (responseValidationMode === 'strict') {\n const errPayload = buildAdcpValidationErrorPayload(toolName, 'response', outcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: outcome.schemaId,\n });\n const errEnvelope = finalize(adcpError('VALIDATION_ERROR', errPayload));\n if (idempotencyCheck && idempotency) {\n // A mutating handler has already returned, so its side\n // effect may be committed even though strict response\n // validation rejected the representation. Fence that\n // ambiguity for the full replay window: a short-lived\n // retry-storm entry could disappear and permit the same\n // mutation to execute again. Read-only keyed operations\n // retain the short transient-error behavior.\n try {\n if (toolIsMutating || requestIsStateChanging) {\n await idempotency.save({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: stripEnvelopeEcho(errEnvelope),\n extraScope: idempotencyCheck.extraScope,\n });\n } else if (idempotency.saveTransientError) {\n await idempotency.saveTransientError({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: errEnvelope,\n extraScope: idempotencyCheck.extraScope,\n });\n } else {\n await idempotency.release({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n });\n }\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency validation-error publication failed', {\n tool: toolName,\n error: reason,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n err instanceof IdempotencyClaimOwnershipError\n ? 'The request lost its idempotency claim before its response could be published. Retry safely.'\n : 'The response could not be published to the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n }\n return errEnvelope;\n }\n }\n }\n // Complete every potentially-throwing framework transformation\n // before publishing the successful idempotency record. If an\n // enhancer or envelope normalizer fails, the catch below still\n // owns the request claim and can replace it with an ambiguity\n // fence; publishing success first would make that replacement\n // impossible and an exact retry would re-trigger the same broken\n // post-processing path.\n formatted = finalize(formatted);\n\n // Cache successful mutations for replay. Errors and commercial\n // rejection rows re-execute on retry, not replayed — capability /\n // status changes in the seller's ledger must take effect without\n // waiting for an idempotency TTL to expire. Release the in-flight\n // claim on uncacheable responses so a retry can re-execute.\n //\n // Cache the FORMATTED envelope, not the raw handler return:\n // some wrap functions inject non-deterministic fields\n // (`confirmed_at = new Date().toISOString()`) when the handler\n // omits them. Re-wrapping on replay would produce a different\n // `confirmed_at` each time, breaking the \"same response on\n // replay\" contract. Caching the formatted envelope pins those\n // fields to their first-execution values.\n if (idempotencyCheck && idempotency) {\n if (shouldCacheIdempotencyResponse(formatted)) {\n try {\n // Strip `context` before caching — it's a per-request echo\n // field (buyer's correlation_id), not part of the cached\n // payload. If we cached it, replays would return the\n // FIRST caller's correlation_id to every subsequent\n // retry, breaking end-to-end request tracing. On replay,\n // `finalize()` re-injects the current request's context.\n const cacheable = stripEnvelopeEcho(formatted);\n await idempotency.save({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: cacheable,\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency save failed — response will not be cached', {\n tool: toolName,\n error: reason,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n err instanceof IdempotencyClaimOwnershipError\n ? 'The request lost its idempotency claim before its response could be published. Retry safely.'\n : 'The response could not be published to the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n // Fresh-path responses omit `replayed` — per envelope spec,\n // absence signals fresh execution. The replay path stamps\n // `replayed: true` on the cached copy at retrieval.\n } else {\n try {\n await idempotency.release({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (err) {\n // Best-effort release; if it fails the claim TTL will\n // eventually evict. Log and move on.\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn('Idempotency release failed — in-flight claim will expire on TTL', {\n tool: toolName,\n error: reason,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n err instanceof IdempotencyClaimOwnershipError\n ? 'The request lost its idempotency claim before its response could be published. Retry safely.'\n : 'The response could not be released from the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n }\n }\n return formatted;\n } catch (err) {\n if (idempotencyCheck && idempotency && (toolIsMutating || requestIsStateChanging)) {\n // Once a mutating application handler has been invoked, a thrown\n // exception cannot prove that no side effect committed. Never\n // release that claim for blind re-execution. Stable typed errors\n // are cached as the handler outcome; unknown exceptions and\n // post-handler framework failures become a full-window ambiguity\n // fence that requires natural-key reconciliation.\n let thrownTypedEnvelope: McpToolResponse | undefined;\n if (isThrownAdcpError(err)) {\n const env = (err.structuredContent as { adcp_error: { code: string; message: string } }).adcp_error;\n logger.warn('Handler threw an adcpError envelope — prefer `return` over `throw` for typed errors', {\n tool: toolName,\n handler: handlerKey,\n code: env.code,\n message: env.message,\n stack: err instanceof Error ? err.stack : undefined,\n });\n thrownTypedEnvelope = err;\n } else if (err instanceof AdcpError) {\n logger.warn('Handler threw an AdcpError', {\n tool: toolName,\n handler: handlerKey,\n code: err.code,\n message: err.message,\n stack: err.stack,\n });\n thrownTypedEnvelope = projectThrownAdcpError(err);\n }\n\n const thrownRecovery = thrownTypedEnvelope ? thrownAdcpErrorRecovery(thrownTypedEnvelope) : undefined;\n let replayEnvelope: McpToolResponse;\n if (!mutationHandlerCompleted && thrownTypedEnvelope && thrownRecovery !== 'transient') {\n // A terminal typed rejection thrown directly by the handler is\n // a stable outcome. Cache it so exact retry cannot re-enter the\n // mutation. Transient typed errors are intentionally not\n // replayed as retryable for the full window: after handler\n // admission they are indistinguishable from commit-then-throw.\n replayEnvelope = thrownTypedEnvelope;\n } else {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Mutating handler outcome is uncertain and requires reconciliation', {\n tool: toolName,\n handler: handlerKey,\n error: reason,\n stack: err instanceof Error ? err.stack : undefined,\n });\n replayEnvelope = adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'The mutating handler did not produce a safely publishable response. Reconcile the operation by natural key before retrying.',\n });\n }\n\n try {\n replayEnvelope = finalize(replayEnvelope);\n } catch (finalizeErr) {\n const finalizeReason = finalizeErr instanceof Error ? finalizeErr.message : String(finalizeErr);\n logger.error('Response processing failed while formatting a fenced mutation outcome', {\n tool: toolName,\n error: finalizeReason,\n });\n replayEnvelope = adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'The mutating handler did not produce a safely publishable response. Reconcile the operation by natural key before retrying.',\n });\n }\n\n try {\n await idempotency.save({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n payloadHash: idempotencyCheck.payloadHash,\n claimToken: idempotencyCheck.claimToken,\n response: stripEnvelopeEcho(replayEnvelope),\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (saveErr) {\n const saveReason = saveErr instanceof Error ? saveErr.message : String(saveErr);\n logger.error('Idempotency mutation-outcome publication failed; retaining the live owner claim', {\n tool: toolName,\n error: saveReason,\n });\n return adcpError('SERVICE_UNAVAILABLE', {\n message:\n 'The mutating handler outcome could not be published to the idempotency store. Reconcile by natural key before retrying.',\n });\n }\n return replayEnvelope;\n }\n // Non-mutating thrown paths may release their optional claim: no\n // state-changing handler was invoked, so exact retry is safe.\n let idempotencyReleaseError: unknown;\n if (idempotencyCheck && idempotency) {\n try {\n await idempotency.release({\n principal: idempotencyCheck.principal,\n key: idempotencyCheck.key,\n claimToken: idempotencyCheck.claimToken,\n extraScope: idempotencyCheck.extraScope,\n });\n } catch (releaseErr) {\n const releaseReason = releaseErr instanceof Error ? releaseErr.message : String(releaseErr);\n logger.warn('Idempotency release failed — in-flight claim will expire on TTL', {\n tool: toolName,\n error: releaseReason,\n });\n idempotencyReleaseError = releaseErr;\n }\n }\n if (idempotencyReleaseError !== undefined) {\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n message:\n idempotencyReleaseError instanceof IdempotencyClaimOwnershipError\n ? 'The failed request lost its idempotency claim before the claim could be released. Retry safely.'\n : 'The failed request could not be released from the idempotency store. Reconcile by natural key before retrying.',\n })\n );\n }\n // Auto-unwrap `throw adcpError(...)`. Handlers that throw an\n // envelope (instead of returning it) should behave identically —\n // otherwise the envelope surfaces as `[object Object]` inside\n // SERVICE_UNAVAILABLE and the buyer loses the typed domain code.\n // Matrix harnesses and fresh-built agents consistently get this\n // wrong; unwrapping at the dispatcher closes the class of bugs\n // instead of relying on every skill to show `return` over `throw`.\n if (isThrownAdcpError(err)) {\n const env = (err.structuredContent as { adcp_error: { code: string; message: string } }).adcp_error;\n // Log message + stack so forensic review sees what was thrown\n // (not just the code). The thrown envelope is a plain object so\n // `.stack` is typically absent, but authors sometimes subclass\n // `Error` and attach envelope fields; capture it defensively.\n logger.warn('Handler threw an adcpError envelope — prefer `return` over `throw` for typed errors', {\n tool: toolName,\n handler: handlerKey,\n code: env.code,\n message: env.message,\n stack: err instanceof Error ? err.stack : undefined,\n });\n return finalize(err);\n }\n // Raw `AdcpError` class throws — distinct from the\n // already-projected envelope above. The framework has long\n // documented `throw new AdcpError(...)` as the canonical way\n // to signal structured rejection from any specialism method\n // (see `AdcpError` JSDoc). Project to the typed envelope so\n // the buyer sees the typed code, not `SERVICE_UNAVAILABLE`.\n if (err instanceof AdcpError) {\n logger.warn('Handler threw an AdcpError', {\n tool: toolName,\n handler: handlerKey,\n code: err.code,\n message: err.message,\n stack: err.stack,\n });\n return finalize(projectThrownAdcpError(err));\n }\n const reason = err instanceof Error ? err.message : String(err);\n // Log the full stack — `logger.error` with just the message turned\n // every \"Handler failed\" into a guessing game for agent authors.\n // Stack tells you which import/typo/access chain blew up.\n logger.error('Handler failed', {\n tool: toolName,\n handler: handlerKey,\n error: reason,\n stack: err instanceof Error ? err.stack : undefined,\n });\n return finalize(\n adcpError('SERVICE_UNAVAILABLE', {\n // Include the cause message directly in the response text when\n // `exposeErrorDetails` is on. The opaque\n // \"Tool X encountered an internal error\" string cost us weeks\n // of diagnostic time on the matrix harness — dev callers want\n // the real reason at the call site, not hidden in server logs.\n message: exposeErrorDetails\n ? `Tool ${toolName} handler threw: ${redactCredentialPatterns(reason)}`\n : `Tool ${toolName} encountered an internal error`,\n ...(exposeErrorDetails && {\n details: { reason: redactCredentialPatterns(reason), handler: handlerKey },\n }),\n })\n );\n } finally {\n if (claimRenewalTimer !== undefined) clearInterval(claimRenewalTimer);\n if (claimRenewalPending) await claimRenewalPending;\n }\n };\n\n // Register a PASSTHROUGH input schema by default (#909). The MCP\n // SDK's Zod validator only fires on the MCP transport — A2A calls\n // the handler via AdcpServer.invoke(), bypassing it. Registering the\n // real per-tool Zod schema meant MCP and A2A produced different\n // verdicts and different error shapes for the same malformed request.\n // Our framework request validator (AJV, loaded from\n // schemas/cache/<version>/) runs inside the handler closure on BOTH\n // transports and produces a structured adcp_error envelope; make it\n // authoritative unless the adopter opts into MCP discovery schemas.\n //\n // Passthrough (not omit): the SDK's `validateToolInput` returns\n // `undefined` when `inputSchema` is absent (see @modelcontextprotocol/sdk\n // server/mcp.js), and passes that `undefined` verbatim to the\n // handler — destroying the actual arguments. `z.object({}).passthrough()`\n // keeps every key intact, so args still reach the closure.\n //\n // Trade-off: default MCP `tools/list` publishes `{ type: 'object' }`\n // for every tool (no per-tool parameter schema). This is intentional,\n // not a wiring gap — inlining full request schemas in `tools/list`\n // would balloon the context window for LLM consumers. Tool shapes\n // live in `docs/llms.txt`, the SKILL.md files, and `schemas/cache/`,\n // which curated agents read on demand instead of paying the cost\n // every connection. AdCP-native discovery via `get_adcp_capabilities`\n // already works over both transports; upstream #3057 proposes a\n // `get_schema` capability tool for programmatic per-tool shape\n // discovery. For generic MCP clients that need hints directly in\n // `tools/list`, set `exposeToolSchemas: true` to publish shallow\n // top-level key hints derived from `TOOL_INPUT_SHAPES`. Those hint\n // schemas use optional `unknown` fields plus passthrough so MCP keeps\n // all args intact and leaves substantive validation under the\n // framework validator.\n //\n // Implication for downstream consumers: if you need a tool's shape\n // (cross-version field-stripping, gating, validation), read raw\n // JSON from `schemas/cache/{version}/` via `schema-loader.ts` —\n // see `schemaAllowsTopLevelField` for the canonical pattern (#940).\n // Don't try to recover the canonical shape from `tools/list` when\n // `exposeToolSchemas` is off; it's empty by design and will fail open.\n server.registerTool(\n toolName,\n {\n inputSchema: frameworkInputSchemaFor(toolName),\n ...(meta?.annotations != null && { annotations: meta.annotations }),\n _meta: frameworkToolMeta,\n },\n toolHandler as Parameters<typeof server.registerTool>[2]\n );\n\n registeredToolNames.add(toolName);\n }\n }\n\n if (supportsProtocolTaskTools && taskRegistry !== undefined) {\n server.registerTool(\n 'get_task_status',\n {\n inputSchema: frameworkInputSchemaFor('get_task_status'),\n annotations: RO,\n _meta: frameworkToolMeta,\n },\n (async (params: any, extra: any) => {\n const credentialError = taskToolCredentialPolicyError('get_task_status', params ?? {}, extra);\n if (credentialError) {\n return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, credentialError, {\n echoContext: false,\n });\n }\n const validationError = protocolTaskRequestValidationError('get_task_status', params ?? {});\n if (validationError) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, validationError);\n const boundsError = protocolTaskBoundsError('get_task_status', params ?? {});\n if (boundsError) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, boundsError);\n const versionError = unsupportedVersionResponse('get_task_status', params ?? {});\n if (versionError) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, versionError);\n const taskId = typeof params?.task_id === 'string' ? params.task_id : '';\n const { accountId, ownerScope, error } = await resolveTaskQueryAccountId(\n params ?? {},\n extra,\n 'get_task_status'\n );\n if (error) return finalizeProtocolTaskToolResponse('get_task_status', params ?? {}, error);\n let task: TaskRecord | null = null;\n try {\n task =\n taskId && taskRegistry !== undefined && accountId !== undefined && ownerScope !== undefined\n ? await taskRegistry.getTask(taskId, { accountId, ownerScope })\n : null;\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Task registry read failed during task poll', { tool: 'get_task_status', error: reason });\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Task registry read failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n if (task == null || accountId === undefined || !taskBelongsToCaller(task, accountId, ownerScope)) {\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n adcpError('REFERENCE_NOT_FOUND', {\n message: taskId ? `Task ${taskId} not found` : 'Task not found',\n field: 'task_id',\n })\n );\n }\n\n const response = toProtocolTaskStatus(task);\n if (response === undefined) {\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n adcpError('REFERENCE_NOT_FOUND', {\n message: taskId ? `Task ${taskId} not found` : 'Task not found',\n field: 'task_id',\n })\n );\n }\n if (\n params?.include_result === true &&\n (response.status === 'completed' || response.status === 'failed' || response.status === 'rejected') &&\n task.result !== undefined\n ) {\n response.result = task.result as GetTaskStatusResponse['result'];\n }\n if (isPlainObject(params?.context)) response.context = params.context;\n return finalizeProtocolTaskToolResponse(\n 'get_task_status',\n params ?? {},\n genericResponse('get_task_status', response)\n );\n }) as Parameters<typeof server.registerTool>[2]\n );\n registeredToolNames.add('get_task_status');\n }\n\n if (supportsProtocolTaskTools && taskRegistry?.list !== undefined) {\n server.registerTool(\n 'list_tasks',\n {\n inputSchema: frameworkInputSchemaFor('list_tasks'),\n annotations: RO,\n _meta: frameworkToolMeta,\n },\n (async (params: any, extra: any) => {\n const credentialError = taskToolCredentialPolicyError('list_tasks', params ?? {}, extra);\n if (credentialError) {\n return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, credentialError, { echoContext: false });\n }\n const validationError = protocolTaskRequestValidationError('list_tasks', params ?? {});\n if (validationError) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, validationError);\n const boundsError = protocolTaskBoundsError('list_tasks', params ?? {});\n if (boundsError) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, boundsError);\n const versionError = unsupportedVersionResponse('list_tasks', params ?? {});\n if (versionError) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, versionError);\n const { accountId, ownerScope, error } = await resolveTaskQueryAccountId(params ?? {}, extra, 'list_tasks');\n if (error) return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, error);\n let cursorStart = 0;\n try {\n cursorStart =\n parseTaskListCursor(isPlainObject(params?.pagination) ? params.pagination.cursor : undefined) ?? 0;\n } catch (err) {\n return finalizeProtocolTaskToolResponse(\n 'list_tasks',\n params ?? {},\n adcpError('INVALID_REQUEST', {\n message: err instanceof Error ? err.message : 'Invalid task list cursor',\n field: 'pagination.cursor',\n })\n );\n }\n\n let listed: { tasks: TaskRecord[] };\n try {\n listed =\n accountId !== undefined && ownerScope !== undefined && taskRegistry?.list !== undefined\n ? await taskRegistry.list({ accountId, ownerScope })\n : { tasks: [] };\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.error('Task registry list failed during task poll', { tool: 'list_tasks', error: reason });\n return finalizeProtocolTaskToolResponse(\n 'list_tasks',\n params ?? {},\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Task registry list failed',\n ...(exposeErrorDetails && { details: { reason: redactCredentialPatterns(reason) } }),\n })\n );\n }\n const filteredTasks = listed.tasks.filter(\n task =>\n accountId !== undefined &&\n taskBelongsToCaller(task, accountId, ownerScope) &&\n taskMatchesFilters(task, params?.filters)\n );\n const sortedTasks = filteredTasks\n .map(toProtocolTaskListItem)\n .filter((task): task is ListTasksResponse['tasks'][number] => task !== undefined)\n .sort((left, right) => compareProtocolTaskItems(left, right, params?.sort));\n const pageSize = taskListPageSize(params?.pagination);\n const tasks = sortedTasks.slice(cursorStart, cursorStart + pageSize);\n const nextOffset = cursorStart + tasks.length;\n const hasMore = nextOffset < sortedTasks.length;\n const status_breakdown = sortedTasks.reduce<Record<string, number>>((counts, task) => {\n counts[task.status] = (counts[task.status] ?? 0) + 1;\n return counts;\n }, {});\n const domain_breakdown = sortedTasks.reduce<Record<string, number>>((counts, task) => {\n counts[task.domain] = (counts[task.domain] ?? 0) + 1;\n return counts;\n }, {});\n const response: ListTasksResponse = {\n status: 'completed',\n query_summary: {\n total_matching: sortedTasks.length,\n returned: tasks.length,\n domain_breakdown,\n status_breakdown,\n filters_applied: isPlainObject(params?.filters) ? Object.keys(params.filters) : [],\n sort_applied: {\n field:\n isPlainObject(params?.sort) && typeof params.sort.field === 'string' ? params.sort.field : 'created_at',\n direction: isPlainObject(params?.sort) && params.sort.direction === 'asc' ? 'asc' : 'desc',\n },\n },\n tasks,\n pagination: {\n has_more: hasMore,\n ...(hasMore && { cursor: String(nextOffset) }),\n total_count: sortedTasks.length,\n },\n };\n if (isPlainObject(params?.context)) response.context = params.context;\n return finalizeProtocolTaskToolResponse('list_tasks', params ?? {}, genericResponse('list_tasks', response));\n }) as Parameters<typeof server.registerTool>[2]\n );\n registeredToolNames.add('list_tasks');\n }\n\n // ─── Custom tools ──────────────────────────────────────────\n // Seller extensions outside AdcpToolMap. No idempotency / governance /\n // response-wrapping — handlers own those concerns directly. Registered\n // after spec tools so the collision check can authoritatively block\n // overlap with framework-owned names.\n if (config.customTools) {\n const customNames = Object.keys(config.customTools);\n for (const customName of customNames) {\n if (registeredToolNames.has(customName)) {\n throw new Error(\n `createAdcpServer: customTools[\"${customName}\"] collides with a framework-registered tool. ` +\n `If this customTool worked in an earlier SDK version, the tool was promoted to first-class — ` +\n `remove the customTools entry and wire the corresponding platform handler instead ` +\n `(e.g. BrandRightsPlatform.updateRights for \"update_rights\" as of 6.7.0). ` +\n `If you intended a new tool, rename it to avoid the framework name.`\n );\n }\n if (customName === 'get_adcp_capabilities') {\n throw new Error(\n `createAdcpServer: customTools[\"get_adcp_capabilities\"] is not allowed. ` +\n `The framework auto-generates this tool from registered handlers and capability config.`\n );\n }\n const custom = config.customTools[customName];\n if (!custom) continue;\n const { description, title, inputSchema, outputSchema, annotations, _meta, handler } = custom;\n // Wrap the adopter-supplied handler so `throw new AdcpError(...)` and\n // `throw adcpError(...)` from inside it project to the typed envelope —\n // matching the behavior framework-registered tools get from the catch\n // at line ~3494. Without the wrap, AdcpError throws escape to the MCP\n // SDK as generic JSON-RPC errors and the buyer loses the typed code.\n // The framework's own `tasks_get` is registered through this path.\n const rawHandler = handler as (...args: unknown[]) => Promise<McpToolResponse> | McpToolResponse;\n const wrappedHandler = (async (...args: unknown[]) => {\n try {\n return applyResponseEnhancer(await rawHandler(...args));\n } catch (err) {\n if (isThrownAdcpError(err)) return applyResponseEnhancer(err);\n if (err instanceof AdcpError) return applyResponseEnhancer(projectThrownAdcpError(err));\n throw err;\n }\n }) as Parameters<typeof server.registerTool>[2];\n server.registerTool(\n customName,\n {\n ...(description != null && { description }),\n ...(title != null && { title }),\n ...(inputSchema != null && { inputSchema }),\n ...(outputSchema != null && { outputSchema }),\n ...(annotations != null && { annotations }),\n ...(_meta != null && { _meta }),\n } as Parameters<typeof server.registerTool>[1],\n wrappedHandler\n );\n registeredToolNames.add(customName);\n }\n }\n\n // Tool coherence warnings\n checkCoherence(registeredToolNames, logger);\n\n // --- Idempotency configuration guardrails ---\n //\n // A seller that registers mutating handlers but doesn't supply an\n // `idempotency` store cannot honor the v3 retry contract: buyer\n // retries will double-book because there's no replay cache. The\n // framework permits this implicit omission only in development/test,\n // where idempotency may not be the unit under test. All other\n // environments fail startup. Operators who deliberately cannot provide\n // replay safety must use the explicit `idempotency: 'disabled'` mode and\n // its acknowledgement gate. The advertised capability remains\n // `supported: false`; only a wired store can declare replay safety.\n const registeredMutatingTools = [...registeredToolNames].filter(t => MUTATING_TASKS.has(t));\n if (registeredMutatingTools.length > 0 && !idempotency && !idempotencyDisabled) {\n const message =\n `createAdcpServer: ${registeredMutatingTools.length} mutating tools registered ` +\n `(${registeredMutatingTools.slice(0, 3).join(', ')}${\n registeredMutatingTools.length > 3 ? ', ...' : ''\n }) without an idempotency store. AdCP v3 requires sellers to support idempotent replay ` +\n `on mutating requests — buyer retries will double-book without it. ` +\n `Pass \\`idempotency: createIdempotencyStore({ backend, ttlSeconds })\\` or explicitly set ` +\n `\\`idempotency: 'disabled'\\` when the seller intentionally cannot provide replay safety.`;\n const env = process.env.NODE_ENV;\n if (env !== 'test' && env !== 'development') {\n throw new Error(message);\n }\n logger.error(message);\n }\n\n // MUTATING_TASKS is derived at module load by introspecting Zod\n // schemas. If Zod's internals change or the tool-request-schemas map\n // shifts, the derivation can silently return an empty set — which\n // would make every mutating request bypass idempotency enforcement.\n // Fail loud at server startup if the introspection produced\n // surprisingly few results.\n if (MUTATING_TASKS.size < 20) {\n throw new Error(\n `createAdcpServer: MUTATING_TASKS set has only ${MUTATING_TASKS.size} entries — expected at least 20. ` +\n `Schema introspection likely broke (Zod upgrade? tool-request-schemas change?). ` +\n `Check \\`src/lib/utils/idempotency.ts:deriveMutatingTasks\\`.`\n );\n }\n\n // --- Auto-register get_adcp_capabilities ---\n const protocols = detectProtocolsFromHandlers(config);\n\n // Idempotency capability declaration. Spec defines a discriminated\n // union (`get-adcp-capabilities-response.json` `adcp.idempotency.oneOf`):\n // - `IdempotencySupported` → `{ supported: true, replay_ttl_seconds: N }`\n // - `IdempotencyUnsupported` → `{ supported: false }` (replay_ttl_seconds MUST be absent)\n // Disabled mode flips to `IdempotencyUnsupported` so the wire contract\n // matches actual behavior — buyers reading capabilities can fall back to\n // natural-key dedup before retrying spend-committing operations. Lying\n // here (declaring `supported: true` while skipping replay) is a\n // money-flow footgun: a 504-retry under the same key double-books.\n const idempotencyCapability: GetAdCPCapabilitiesResponse['adcp']['idempotency'] =\n idempotencyDisabled || !idempotency\n ? { supported: false }\n : {\n supported: true,\n replay_ttl_seconds: idempotency.ttlSeconds,\n };\n\n const capabilitiesData: GetAdCPCapabilitiesResponse = {\n status: 'completed',\n adcp: {\n major_versions: capConfig?.major_versions ?? [3],\n ...(capConfig?.supported_versions?.length && { supported_versions: [...capConfig.supported_versions] }),\n idempotency: idempotencyCapability,\n ...(capConfig?.capability_changes && { capability_changes: structuredClone(capConfig.capability_changes) }),\n },\n supported_protocols: protocols as GetAdCPCapabilitiesResponse['supported_protocols'],\n };\n\n const hasExplicitMediaBuyFeatures = Object.keys(capConfig?.features ?? {}).length > 0;\n if (protocols.includes('media_buy') || hasExplicitMediaBuyFeatures) {\n capabilitiesData.media_buy = {\n features: {\n ...(capConfig?.features?.canonicalCreatives !== undefined && {\n canonical_creatives: capConfig.features.canonicalCreatives,\n }),\n inline_creative_management: capConfig?.features?.inlineCreativeManagement ?? false,\n property_list_filtering: capConfig?.features?.propertyListFiltering ?? false,\n content_standards: capConfig?.features?.contentStandards ?? false,\n conversion_tracking: capConfig?.features?.conversionTracking ?? false,\n audience_targeting: capConfig?.features?.audienceTargeting ?? false,\n },\n ...(capConfig?.portfolio && { portfolio: capConfig.portfolio }),\n };\n }\n\n if (capConfig?.account) {\n capabilitiesData.account = {\n require_operator_auth: capConfig.account.requireOperatorAuth ?? false,\n ...(capConfig.account.authorizationEndpoint && {\n authorization_endpoint: capConfig.account.authorizationEndpoint,\n }),\n supported_billing: capConfig.account.supportedBilling ?? [],\n ...(capConfig.account.defaultBilling && { default_billing: capConfig.account.defaultBilling }),\n required_for_products: capConfig.account.requiredForProducts ?? false,\n sandbox: capConfig.account.sandbox ?? false,\n };\n }\n\n if (capConfig?.creative) {\n capabilitiesData.creative = {\n supports_compliance: capConfig.creative.supportsCompliance ?? false,\n has_creative_library: capConfig.creative.hasCreativeLibrary ?? false,\n supports_generation: capConfig.creative.supportsGeneration ?? false,\n supports_transformation: capConfig.creative.supportsTransformation ?? false,\n };\n }\n\n if (capConfig?.extensions_supported !== undefined) {\n capabilitiesData.extensions_supported = [...capConfig.extensions_supported];\n }\n\n if (capConfig?.ext !== undefined) {\n capabilitiesData.ext = structuredClone(capConfig.ext);\n }\n\n if (capConfig?.request_signing) {\n capabilitiesData.request_signing = capConfig.request_signing;\n }\n\n if (capConfig?.specialisms?.length) {\n capabilitiesData.specialisms = capConfig.specialisms;\n }\n\n if (capConfig?.overrides) {\n applyCapabilityOverrides(capabilitiesData, capConfig.overrides);\n }\n\n if (webhooks) {\n const profile = webhooks.tag ?? 'adcp/webhook-signing/v1';\n if (profile !== 'adcp/webhook-signing/v1') {\n throw new Error(\n `createAdcpServer: webhooks.tag must be \"adcp/webhook-signing/v1\" so the emitted tag matches the advertised AdCP profile; got ${JSON.stringify(profile)}`\n );\n }\n const algorithm = webhooks.signerKey?.alg ?? webhooks.signerProvider?.algorithm;\n if (algorithm === undefined) {\n throw new Error('createAdcpServer: webhooks must provide a signing key or provider with an advertised algorithm');\n }\n capabilitiesData.webhook_signing = {\n ...capabilitiesData.webhook_signing,\n supported: true,\n profile,\n algorithms: [algorithm],\n legacy_hmac_fallback: capabilitiesData.webhook_signing?.legacy_hmac_fallback ?? false,\n delivery_retry_horizon_seconds: webhooks.deliveryRetryHorizonSeconds ?? 86_400,\n };\n }\n\n // Resolve signing once, after capability overrides, then use this exact\n // policy for both discovery and transport enforcement. Explicit verifier\n // config remains authoritative over a conflicting capability override;\n // otherwise the post-override advertised list controls enforcement.\n const enforcedRequestSigningPolicy = signedRequests\n ? resolveEffectiveSignedRequestPolicy(\n signedRequests,\n capabilitiesData.request_signing ?? capConfig?.request_signing,\n adcpVersion\n )\n : undefined;\n if (enforcedRequestSigningPolicy) capabilitiesData.request_signing = enforcedRequestSigningPolicy;\n\n if (proposalRefinementCapabilities) {\n const mediaBuy = (capabilitiesData.media_buy ??= {\n features: {\n inline_creative_management: false,\n property_list_filtering: false,\n content_standards: false,\n conversion_tracking: false,\n audience_targeting: false,\n },\n });\n mediaBuy.proposal_refinement = {\n ...proposalRefinementCapabilities,\n supported_dimensions: [...proposalRefinementCapabilities.supported_dimensions],\n };\n }\n\n const compactLifecycleTools = COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS.filter(tool => registeredToolNames.has(tool));\n if (compactLifecycleTools.length > 0) {\n const mediaBuy = (capabilitiesData.media_buy ??= {\n features: {\n inline_creative_management: false,\n property_list_filtering: false,\n content_standards: false,\n conversion_tracking: false,\n audience_targeting: false,\n },\n });\n mediaBuy.lifecycle_tools = compactLifecycleTools;\n }\n\n if (\n capabilitiesData.measurement !== undefined &&\n Array.isArray(capabilitiesData.experimental_features) &&\n capabilitiesData.experimental_features.includes('measurement.core') &&\n !capabilitiesData.supported_protocols.includes('measurement' as never)\n ) {\n capabilitiesData.supported_protocols = [\n ...capabilitiesData.supported_protocols,\n 'measurement',\n ] as GetAdCPCapabilitiesResponse['supported_protocols'];\n }\n\n // Stamp the SDK version so conformance tooling can surface version-staleness\n // hints when the agent's reported version predates recommended helpers.\n // Cast needed because GetAdCPCapabilitiesResponse is generated and lacks\n // this field; it remains a forward-compatible extension until the spec\n // formally defines library_version in a future AdCP minor.\n (capabilitiesData as unknown as Record<string, unknown>).library_version = `@adcp/client@${LIBRARY_VERSION}`;\n\n // Passthrough inputSchema — framework validation is authoritative on\n // both transports (#909). Same rationale as the domain-tool loop above.\n server.registerTool(\n 'get_adcp_capabilities',\n {\n inputSchema: frameworkInputSchemaFor('get_adcp_capabilities'),\n annotations: { readOnlyHint: true },\n _meta: frameworkToolMeta,\n },\n (async (params: any, extra: { authInfo?: ResolvedAuthInfo } = {}) => {\n const requestParams = isPlainObject(params) ? params : {};\n const releaseSelection = selectServedAdcpRelease(requestParams, capConfig, adcpVersion);\n const release = isMcpToolResponse(releaseSelection)\n ? {\n validationVersion: adcpVersion,\n ...(servedAdcpVersion !== undefined && { wireVersion: servedAdcpVersion }),\n }\n : releaseSelection;\n const finalizeCapabilityResponse = (response: McpToolResponse): McpToolResponse => {\n sanitizeAdcpErrorEnvelope(response);\n injectContextIntoResponse(response, requestParams.context);\n injectVersionIntoResponse(response, release.wireVersion);\n return applyResponseEnhancer(response);\n };\n\n if (isMcpToolResponse(releaseSelection)) {\n return finalizeCapabilityResponse(releaseSelection);\n }\n if (!releaseDefinesTool('get_adcp_capabilities', release)) {\n return finalizeCapabilityResponse(\n adcpError('VERSION_UNSUPPORTED', {\n message: `get_adcp_capabilities is not defined in the selected AdCP release ${release.validationVersion}.`,\n details: { supported_versions: buildSupportedVersionsList(capConfig, adcpVersion) },\n })\n );\n }\n\n if (requestValidationMode !== 'off') {\n const requestOutcome = validateRequest('get_adcp_capabilities', requestParams, release.validationVersion);\n if (!requestOutcome.valid) {\n logger.warn(\n `Schema validation warning (request) for get_adcp_capabilities: ${formatIssues(requestOutcome.issues, 3, { rootSchemaId: requestOutcome.schemaId })}`,\n {\n tool: 'get_adcp_capabilities',\n issues: requestOutcome.issues,\n }\n );\n if (requestValidationMode === 'strict') {\n return finalizeCapabilityResponse(\n adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload('get_adcp_capabilities', 'request', requestOutcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: requestOutcome.schemaId,\n })\n )\n );\n }\n }\n }\n\n if (agentRegistry !== undefined && extra.authInfo !== undefined) {\n const authInfo = extra.authInfo;\n const inboundCredential = authInfo.extra?.credential;\n const credential = authInfo.credential ?? (inboundCredential as ResolvedAuthInfo['credential'] | undefined);\n try {\n const resolved = await agentRegistry.resolve({\n ...(credential !== undefined && { credential }),\n ...(authInfo.extra !== undefined && { extra: authInfo.extra }),\n input: params,\n });\n if (resolved?.status === 'suspended' || resolved?.status === 'blocked') {\n return finalizeCapabilityResponse(\n adcpError(resolved.status === 'suspended' ? 'AGENT_SUSPENDED' : 'AGENT_BLOCKED', {\n message:\n resolved.status === 'suspended'\n ? 'Buyer agent is suspended. Contact the seller to restore access.'\n : 'Buyer agent is blocked.',\n recovery: 'terminal',\n })\n );\n }\n } catch (err) {\n logger.warn('Buyer-agent registry resolution failed for get_adcp_capabilities', {\n error: err instanceof Error ? redactCredentialPatterns(err.message) : redactCredentialPatterns(String(err)),\n });\n return finalizeCapabilityResponse(\n adcpError('SERVICE_UNAVAILABLE', {\n message: 'Buyer-agent registry is unavailable',\n recovery: 'transient',\n })\n );\n }\n }\n let data = structuredClone(capabilitiesData) as GetAdCPCapabilitiesResponse;\n const selected = parseAdcpRelease(release.validationVersion);\n if (\n selected !== undefined &&\n (selected.major > 3 || (selected.major === 3 && selected.minor >= 2)) &&\n data.request_signing?.supported === true\n ) {\n // 3.2's advertised contract is strict even when the internal verifier\n // temporarily accepts the legacy serialization during a rolling deploy.\n data.request_signing = { ...data.request_signing, covers_content_digest: 'required' };\n }\n if (selected?.major === 3 && selected.minor === 0) {\n data = projectCapabilitiesToVersion(data, release.validationVersion);\n }\n if (selected !== undefined && (selected.major < 3 || (selected.major === 3 && selected.minor === 1))) {\n if (data.webhook_signing) {\n delete (\n data.webhook_signing as NonNullable<GetAdCPCapabilitiesResponse['webhook_signing']> & {\n delivery_retry_horizon_seconds?: number;\n }\n ).delivery_retry_horizon_seconds;\n }\n delete (data.adcp as GetAdCPCapabilitiesResponse['adcp'] & { capability_changes?: unknown }).capability_changes;\n const forwardMediaBuy = data.media_buy as\n | (NonNullable<typeof data.media_buy> & {\n lifecycle_tools?: string[];\n proposal_refinement?: ProposalRefinementCapabilities;\n })\n | undefined;\n if (forwardMediaBuy) {\n delete forwardMediaBuy.proposal_refinement;\n if (forwardMediaBuy.lifecycle_tools) {\n forwardMediaBuy.lifecycle_tools = forwardMediaBuy.lifecycle_tools.filter(\n tool =>\n !COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS.includes(tool as (typeof COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS)[number])\n );\n if (forwardMediaBuy.lifecycle_tools.length === 0) delete forwardMediaBuy.lifecycle_tools;\n }\n }\n }\n if (selected !== undefined && selected.major < 3) {\n delete (data.adcp as GetAdCPCapabilitiesResponse['adcp'] & { supported_versions?: string[] })\n .supported_versions;\n if (data.media_buy?.features !== undefined) {\n delete (data.media_buy.features as { canonical_creatives?: boolean }).canonical_creatives;\n }\n delete (data as unknown as Record<string, unknown>).library_version;\n }\n const ctx = requestParams.context;\n if (ctx !== null && typeof ctx === 'object' && !Array.isArray(ctx)) {\n (data as any).context = ctx;\n }\n const response = capabilitiesResponse(data);\n injectVersionIntoResponse(response, release.wireVersion);\n // A capabilities-only server (no domain tools registered yet) has no\n // protocol name it can truthfully place in supported_protocols. Keep\n // discovery callable without inventing one; once a protocol is\n // registered, the selected release schema is authoritative.\n if (responseValidationMode !== 'off' && data.supported_protocols.length > 0) {\n const validationPayload = structuredClone(response.structuredContent);\n if (proposalRefinementCapabilities && isPlainObject(validationPayload?.media_buy)) {\n delete validationPayload.media_buy.proposal_refinement;\n delete validationPayload.media_buy.lifecycle_tools;\n }\n const responseOutcome = validateResponse('get_adcp_capabilities', validationPayload, release.validationVersion);\n if (!responseOutcome.valid) {\n logger.warn(\n `Schema validation warning (response) for get_adcp_capabilities: ${formatIssues(responseOutcome.issues, 3, { rootSchemaId: responseOutcome.schemaId })}`,\n {\n tool: 'get_adcp_capabilities',\n issues: responseOutcome.issues,\n variant: responseOutcome.variant,\n }\n );\n if (responseValidationMode === 'strict') {\n return finalizeCapabilityResponse(\n adcpError(\n 'VALIDATION_ERROR',\n buildAdcpValidationErrorPayload('get_adcp_capabilities', 'response', responseOutcome.issues, {\n exposeSchemaPath: exposeErrorDetails,\n rootSchemaId: responseOutcome.schemaId,\n })\n )\n );\n }\n }\n }\n return applyResponseEnhancer(response);\n }) as Parameters<typeof server.registerTool>[2]\n );\n registeredToolNames.add('get_adcp_capabilities');\n\n const configuredRelease = parseAdcpRelease(protocolBundleKey);\n const serves32OrNewer =\n configuredRelease !== undefined &&\n (configuredRelease.major > 3 || (configuredRelease.major === 3 && configuredRelease.minor >= 2));\n if (mcpToolProfile === 'media-buy' && !serves32OrNewer) {\n throw new Error('createAdcpServer: mcpToolProfile=\"media-buy\" requires adcpVersion 3.2 or newer');\n }\n const activeMcpToolProfile: Exclude<AdcpMcpToolProfile, 'auto'> =\n mcpToolProfile === 'media-buy' || (mcpToolProfile === 'auto' && serves32OrNewer && compactLifecycleTools.length > 0)\n ? 'media-buy'\n : 'all';\n const mediaBuyProfileTools = new Set<string>(MEDIA_BUY_MCP_TOOL_PROFILE);\n const wrappedToolsList = wrapSdkRequestHandler(server, 'tools/list', async (original, request, extra) => {\n const response = await original(request, extra);\n if (response == null || typeof response !== 'object') return response;\n const tools = (response as { tools?: unknown }).tools;\n if (!Array.isArray(tools)) return response;\n\n const visibleTools = tools.filter(tool => {\n const toolName = (tool as { name?: unknown } | null)?.name;\n if (typeof toolName !== 'string') return true;\n // Compact lifecycle names do not exist before 3.2. Keep a mistakenly\n // supplied forward handler callable only after the configured server\n // pin advances; never advertise it from a 3.0/3.1 endpoint.\n if (!serves32OrNewer && COMPACT_MEDIA_BUY_LIFECYCLE_TOOLS.includes(toolName as never)) return false;\n return activeMcpToolProfile === 'all' || mediaBuyProfileTools.has(toolName);\n });\n const projectedTools = visibleTools.map(tool => {\n if (activeMcpToolProfile !== 'media-buy') return tool;\n const toolName = (tool as { name?: unknown } | null)?.name;\n if (typeof toolName !== 'string') return tool;\n const inputSchema = getMcpProfileInputSchema(toolName, 'media-buy', adcpVersion);\n return inputSchema ? { ...(tool as Record<string, unknown>), inputSchema } : tool;\n });\n\n return {\n ...(response as Record<string, unknown>),\n tools: projectedTools,\n _meta: {\n ...((response as { _meta?: Record<string, unknown> })._meta ?? {}),\n adcp_version: adcpVersion,\n adcp_profile: activeMcpToolProfile,\n },\n };\n });\n if (!wrappedToolsList) {\n throw new Error(\n 'createAdcpServer: failed to install MCP tools/list profile filtering; the MCP SDK request-handler internals may have changed'\n );\n }\n\n // Validate `credentialPolicy.tools` keys against the FULL registered\n // tool set, including `get_adcp_capabilities` (registered just above).\n // Earlier placement (before this tool was added) made\n // `tools: { get_adcp_capabilities: 'lax' }` spuriously throw — low\n // real-world impact (the tool never carries credentials) but the\n // typo-check claim \"the registered tool set is authoritative\" was\n // false for that one tool. Catches typos at construction so an\n // adopter's `tools: { activte_signal: 'lax' }` (missing 'a') doesn't\n // silently no-op the per-tool override and start fail-closing\n // legitimate buyer-creds traffic in production. Also re-validates\n // the `patterns.matcher`/`patterns.extend` mutual-exclusion at\n // construction so the diagnostic doesn't wait for first traffic.\n validateCredentialPolicy(credentialPolicy, registeredToolNames);\n\n const compliance = {\n async reset({\n force = false,\n allowProduction = false,\n }: { force?: boolean; allowProduction?: boolean } = {}): Promise<void> {\n // Check NODE_ENV BEFORE store-shape probes: the environment guard\n // is the strongest signal that \"this is not a test harness.\" An\n // operator who reached this call in production by mistake hits the\n // env gate regardless of which backend they wired.\n if (!allowProduction && process.env.NODE_ENV === 'production') {\n throw new Error(\n 'AdcpServer.compliance.reset: refused to run with NODE_ENV=production. ' +\n 'Pass `{ allowProduction: true }` if you deliberately set NODE_ENV=production in a test environment, ' +\n 'or unset NODE_ENV before running storyboards.'\n );\n }\n // Positive allowlist for stores, not method-presence. A\n // PostgresStateStore might expose `.clear()` for its own test\n // utility needs — we don't want method-existence alone to permit\n // a flush that would take out a shared test cluster. `force: true`\n // is the documented opt-in for non-memory backends.\n const stateStoreIsMemory = stateStore instanceof InMemoryStateStore;\n const idempotencyIsFlushable = !idempotency || hasIdempotencyClearAll(idempotency);\n if (!force) {\n if (!stateStoreIsMemory) {\n throw new Error(\n 'AdcpServer.compliance.reset: configured stateStore is not InMemoryStateStore. ' +\n 'Pass `{ force: true }` to acknowledge that flushing the configured backend is safe for this environment ' +\n '(e.g., a disposable test Postgres).'\n );\n }\n if (!idempotencyIsFlushable) {\n throw new Error(\n 'AdcpServer.compliance.reset: configured idempotency backend does not expose `clearAll()`. ' +\n 'Use `memoryBackend()` for test harnesses, or pass `{ force: true }` to skip idempotency flush.'\n );\n }\n }\n // `force` bypasses the allowlist checks but never the flush\n // itself — if we reached here, the caller wants the flush to\n // happen. `clear()` is only called when the store exposes it;\n // a store without `clear()` reaching here under `force: true`\n // is a no-op for the state side, which matches the shape the\n // caller opted into.\n const storeWithClear = stateStore as unknown as { clear?: () => void };\n if (typeof storeWithClear.clear === 'function') storeWithClear.clear();\n if (idempotency && idempotency.clearAll) await idempotency.clearAll();\n if (taskRegistry?.clear) await taskRegistry.clear();\n },\n };\n const wrapped: AdcpServerInternal = wrapMcpServer(server, compliance, adcpVersion);\n setMcpToolProfile(wrapped, activeMcpToolProfile);\n setMcpAppResources(wrapped, mcpAppResources);\n\n // Attach the auto-wired preTransport so `serve()` mounts the verifier\n // on the HTTP transport. Stashed under a non-enumerable symbol property\n // on the wrapper — it's a private contract between this function and\n // `serve()` for wiring, not part of the AdcpServer public API.\n if (signedRequests) {\n const preTransport = buildSignedRequestsPreTransport(signedRequests, enforcedRequestSigningPolicy!, adcpVersion);\n Object.defineProperty(wrapped, ADCP_PRE_TRANSPORT, {\n value: preTransport,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n }\n\n const signedRequestsState: AdcpSignedRequestsState = {\n autoWired: Boolean(signedRequests),\n specialismClaimed: claimsSignedRequests,\n capabilitySupported: capConfig?.request_signing?.supported === true,\n mismatch: claimsSignedRequests && !signedRequests ? 'claim_without_config' : 'ok',\n };\n Object.defineProperty(wrapped, ADCP_SIGNED_REQUESTS_STATE, {\n value: signedRequestsState,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(wrapped, ADCP_STATE_STORE, {\n value: stateStore,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n Object.defineProperty(wrapped, ADCP_TASK_MESSAGE_QUEUE, {\n value: Boolean(taskMessageQueue),\n enumerable: false,\n configurable: true,\n writable: false,\n });\n // Mark when `instructions` was supplied as a function, so `serve()` can\n // refuse `reuseAgent: true` — the function is captured once at construction\n // and would not re-evaluate per session under server reuse.\n if (instructionsIsFn) {\n Object.defineProperty(wrapped, ADCP_INSTRUCTIONS_FN, {\n value: true,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n if (resolveInstructionsForTransport) {\n Object.defineProperty(wrapped, ADCP_INSTRUCTIONS_RESOLVER, {\n value: resolveInstructionsForTransport,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n }\n }\n // Expose the capabilitiesData object so post-registration helpers\n // (registerTestController) can add spec-defined capability blocks\n // — comply_test_controller is registered AFTER createAdcpServer,\n // so the compliance_testing block can't be emitted eagerly.\n Object.defineProperty(wrapped, ADCP_CAPABILITIES, {\n value: capabilitiesData,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n\n logger.info('AdCP server created', {\n tools: [...registeredToolNames],\n protocols,\n sign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,QAAM,sBAA+C;AAAA,IACnD,WAAW,QAAQ,cAAc;AAAA,IACjC,mBAAmB;AAAA,IACnB,qBAAqB,WAAW,iBAAiB,cAAc;AAAA,IAC/D,UAAU,wBAAwB,CAAC,iBAAiB,yBAAyB;AAAA,EAC/E;AACA,SAAO,eAAe,SAAS,4BAA4B;AAAA,IACzD,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,EACZ,CAAC;AACD,SAAO,eAAe,SAAS,qCAAkB;AAAA,IAC/C,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,EACZ,CAAC;AACD,SAAO,eAAe,SAAS,sCAAyB;AAAA,IACtD,OAAO,QAAQ,gBAAgB;AAAA,IAC/B,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,EACZ,CAAC;AAID,MAAI,kBAAkB;AACpB,WAAO,eAAe,SAAS,sBAAsB;AAAA,MACnD,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,UAAU;AAAA,IACZ,CAAC;AACD,QAAI,iCAAiC;AACnC,aAAO,eAAe,SAAS,4BAA4B;AAAA,QACzD,OAAO;AAAA,QACP,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,UAAU;AAAA,MACZ,CAAC;AAAA,IACH;AAAA,EACF;AAKA,SAAO,eAAe,SAAS,sCAAmB;AAAA,IAChD,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,UAAU;AAAA,EACZ,CAAC;AAED,SAAO,KAAK,uBAAuB;AAAA,IACjC,OAAO,CAAC,GAAG,mBAAmB;AAAA,IAC9B;AAAA,IACA,gBAAgB;AAAA,EAClB,CAAC;AAED,SAAO;AACT;","names":["import_idempotency","import_version","import_schemas","extra","isSandboxRequestForSeeding","reason","response"]}