Skip to content

feat: fix A2A artifact extraction and add protocol response validation - #28

Merged
bokelley merged 6 commits into
mainfrom
bokelley/debug-format-error
Oct 4, 2025
Merged

bokelley merged 6 commits into
mainfrom
bokelley/debug-format-error

Conversation

@bokelley

@bokelley bokelley commented Oct 4, 2025

Copy link
Copy Markdown
Contributor

Summary

  • Fixed A2A artifact extraction to properly handle nested result.artifacts[0].parts[0].data structure
  • Added ResponseValidator for comprehensive protocol response validation
  • Removed unsupported adcp_version parameter from list_creative_formats
  • Implemented missing updateCreativesDisplay() UI function
  • Added 54 integration tests covering artifact extraction and response validation
  • Added debug logging throughout extraction pipeline
  • Moved protocol implementation docs to development folder (internal docs)

Changes

Library Fixes (src/lib/)

  • TaskExecutor.ts: Enhanced extractResponseData() to detect and extract from A2A artifact structure
  • ResponseValidator.ts: New validator for protocol response validation with auto-detection
  • index.ts: Exported ResponseValidator for library users

UI Fixes (src/public/index.html)

  • Removed hardcoded adcp_version: '1.6.0' parameter that agents don't support
  • Implemented updateCreativesDisplay() function with proper formatting and status colors

Tests (test/lib/)

  • artifact-extraction.test.js: 21 tests covering A2A/MCP artifact extraction
  • response-validator.test.js: 33 tests covering response validation

Documentation

  • Moved PROTOCOL_DIFFERENCES.md to docs/development/ (internal docs for maintainers)

Test plan

  • All 54 tests passing (npm test)
  • Products now display correctly from A2A agents
  • Creatives now display correctly from both protocols
  • MCP list_creative_formats works (A2A has server-side bug)
  • Debug logs show extraction paths taken
  • ResponseValidator correctly detects protocol types and validates structure

Impact

Users: A2A tools now work transparently - products, creatives, and other responses extract correctly from artifact structure.

Developers: Debug logging and ResponseValidator make it easier to troubleshoot protocol issues.

🤖 Generated with Claude Code

bokelley and others added 6 commits October 4, 2025 09:16
A2A protocol responses nest data inside artifacts[0].parts[0].data, but the
extractResponseData method was only extracting response.result, which included
the artifact structure but not the actual data.

Enhanced extractResponseData to properly drill down into A2A artifact
structure when present, falling back to previous behavior for other formats.

Fixes issue where get_products succeeded but UI showed no products.
…mats

Both MCP and A2A agent implementations reject the adcp_version parameter
for list_creative_formats calls, even though it's defined as optional in
the AdCP TypeScript types.

MCP agent returns validation error: 'Unexpected keyword argument'
A2A agent has internal server error when parameter is present

Removed hardcoded adcp_version from UI's loadCreativeFormats function
to allow the tool to work with MCP agents. A2A agent still has server-side
bug that prevents list_creative_formats from working.
Improvements:
- Add comprehensive debug logging to artifact extraction showing which
  protocol path (MCP/A2A) was taken and what data was extracted
- Implement updateCreativesDisplay() function to show creatives in UI
- Add 21 integration tests for artifact extraction across all protocols
- Create detailed PROTOCOL_DIFFERENCES.md documentation explaining MCP vs
  A2A differences and best practices

Technical changes:
- Make TaskExecutor.extractResponseData() public for testing (marked @internal)
- Add logDebug() helper method for consistent debug logging
- Tests verify extraction from both MCP structuredContent and A2A artifacts
- Tests cover edge cases: empty responses, multiple artifacts, fallbacks

All tests passing (21/21)
Add comprehensive response validation system to help catch issues early:

Features:
- Validates MCP and A2A protocol response structures
- Auto-detects protocol type (mcp/a2a/unknown)
- Tool-specific validation (e.g., get_products expects 'products' field)
- Strict mode - treats warnings as errors
- Expected fields validation with empty array detection
- Helper methods: validateOrThrow(), isValidProtocolResponse()

Validation coverage:
- MCP: structuredContent, content arrays, error indicators
- A2A: JSON-RPC errors, artifact structure, parts validation
- Edge cases: null/undefined, malformed responses, missing fields

Test suite: 33 tests covering all validation scenarios

Export from main library index for easy use:
  import { responseValidator } from '@adcp/client';
  const result = validator.validate(response, 'get_products');
  if (!result.valid) console.error(result.errors);
Users shouldn't need to know about protocol differences - the library
abstracts them transparently. This doc is for maintainers/contributors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Minor version bump for new features:
- ResponseValidator for protocol response validation
- Enhanced A2A artifact extraction
- Debug logging throughout extraction pipeline

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@bokelley
bokelley merged commit c4fe2d9 into main Oct 4, 2025
bokelley added a commit that referenced this pull request Apr 20, 2026
#641

- Alert #41 (js/prototype-pollution-utility, medium): GovernanceMiddleware
  setAtPath() already blocked __proto__/constructor/prototype via
  FORBIDDEN_PATH_SEGMENTS set, but CodeQL's pattern matcher only
  recognizes inline equality checks. Added explicit `part === '__proto__'
  || part === 'constructor' || part === 'prototype'` inline guard, plus
  hasOwnProperty traversal check so a malicious prototype-chained value
  can't be followed mid-path. Belt-and-suspenders.
- Alerts #28 and #29 (js/clear-text-logging, high): manual test script
  .catch() handlers logged the full error object, which CodeQL traced
  back to OAuth metadata on auth failures. Narrowed to error.name and
  error.message; full stack restored via DEBUG=1.

Test suite: 4288 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 20, 2026
* feat: 5.2.2 client integration ergonomics

Five additive changes unblocking external client adoption after the 5.2.1
spec-compliance rollup.

- match() helper on TaskResult (src/lib/core/match.ts): exhaustive,
  compile-time-checked discriminated-union dispatcher. Eliminates manual
  `if (result.status === 'completed')` narrowing at response sites.
  Optional `_` catchall makes handlers optional.
- createAdcpServer.signedRequests auto-wires the RFC 9421 verifier when
  the seller declares the `signed-requests` specialism. Startup-fails
  when one is declared without the other — closes the footgun where
  claiming the specialism didn't enforce it.
- docs/guides/idempotency-crash-recovery.md: worked buyer-side recipe
  stitching IdempotencyConflictError + IdempotencyExpiredError +
  natural-key lookup + metadata.replayed into an end-to-end recovery
  flow. Cross-linked from README, llms.txt, and the seller SKILL.
- skills/build-seller-agent/SKILL.md governance extension: GDPR Art 22
  / EU AI Act Annex III worked example — plan.human_review_required
  threaded through createMediaBuy, buildHumanOverride on approval,
  decision table, regulated-category constants.
- Webhook HMAC-SHA256 deprecated: one-time console.warn on first use
  (suppress with ADCP_SUPPRESS_HMAC_WARNING=1), @deprecated JSDoc on
  WebhookAuthentication.hmac_sha256, removal target @adcp/client 6.0.0.
  Migration guide section added.

Test suite: 4277 pass, 1 pre-existing flake (task-executor timing,
unrelated), 12 skipped. New tests: match (6), auto-signed-requests (10),
webhook-hmac-deprecation (4) — all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address expert review feedback on 5.2.2 ergonomics

Addresses review findings on PR #641 from code-reviewer, security-reviewer,
dx-expert, and ad-tech-protocol-expert. Also fixes a production resource
leak discovered by new test coverage.

Blocking fixes:

- Rewrite GDPR governance worked example in skills/build-seller-agent/SKILL.md
  to compile against real handler types (taskToolResponse for submitted path,
  state-store for persistence, guarded ctx.account access, separate approval
  function taking AdcpStateStore rather than stale ctx reference).
- Fix resource leak on 401 path: buildSignedRequestsPreTransport now races
  the next-callback against the response's 'finish'/'close' events so the
  verifier's terminal 401 (which doesn't call next) resolves the wrapper
  promise. Without this every unsigned mutating request hung server-side
  and agentServer.close() never fired — slow resource exhaustion under
  signing-attack floods.

Protocol alignment:

- required_for default now derives from capabilities.request_signing.required_for
  (fallback chain: explicit signedRequests.required_for → capability →
  MUTATING_TASKS). Prevents SDK enforcing beyond what the seller advertises.
- Specialism guard now throws when signed-requests is claimed but
  capabilities.request_signing.supported !== true (was a silent log;
  storyboard would skip the conformance run).

DX:

- Add TaskResult.match() fluent method via attachMatch() installer at public
  exit points (TaskExecutor, SingleAgentClient). Method and free function
  both exported; method form is discoverable via autocomplete. Non-enumerable
  property to keep JSON.stringify / spread clean.
- Add match() and signedRequests auto-wire sections to docs/llms.txt so
  LLMs writing seller code find both via the primary doc.

HMAC language softening (spec still supports HMAC as legacy fallback):

- Warning message, migration doc, @deprecated tag, and changeset all reframe
  as SDK-flagged deprecation rather than hard-committing to 6.0.0 removal.
  SDK keeps supporting HMAC; guidance is to migrate when counterparties ready.

Consistency + polish:

- Error logging in create-adcp-server.ts and serve.ts narrowed to name+code
  (instead of full err object) to avoid JWKS URLs leaking into shared log
  aggregators.
- Cookbook line 104: removed redundant getOrCreateKey call; carry the
  rotated/persisted key forward in a single variable.
- 5 new signed-requests tests (non-mutating pass, required_for honors list,
  agentServer close on 401, WWW-Authenticate shape, replay-scope via auto-wire).

Test suite: 4238 pass, 0 fail, 12 skipped. New production-bug regression
test (401 close-spy) now passes with the hang-fix above.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: round-2 review — signature bypass, proto guard, llms.txt, schema sync

Addresses round-2 expert review of PR #641:

- SECURITY: Fix signature bypass on client-disconnect race. The previous
  fix raced `res.once('finish')` and `res.once('close')` against the
  verifier's next-callback, but on 'close' (client aborted mid-JWKS-fetch)
  `handled` stayed false — serve.ts fell through to MCP dispatch and
  executed the tool handler WITHOUT a verified signature. Now tracks
  `verifierCompleted` and sets `handled=true` when close fires before the
  verifier resolves, so an attacker dropping TCP mid-flight cannot trigger
  side effects on unsigned requests. Regression test added.
- Guard `match()` dispatch against prototype pollution: use
  `Object.prototype.hasOwnProperty.call(handlers, result.status)` before
  lookup so a hostile `result.status === '__proto__'` resolves to the `_`
  catchall instead of calling `Object.prototype` as a handler.
- Fix docs/llms.txt match() example field accessors: `r.submitted?.taskId`
  / `r.metadata.taskId` / `r.deferred?.token` / `r.metadata.inputRequest?`
  — previous example used `r.task_id` which doesn't exist on any
  TaskResult variant. Also documents the `!` (non-null assertion) for TS
  users since `.match` is declared optional.
- Schema sync: upstream AdCP added `governance-aware-seller` specialism.
  Ran `npm run sync-schemas && npm run generate-types` — regenerated
  core.generated.ts, tools.generated.ts, schemas.generated.ts.

Test suite: 4302 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(generator): add match() + crash-recovery to llms.txt template

docs/llms.txt is generated by scripts/generate-agent-docs.ts; direct
edits get clobbered on regen. Moved the match() fluent dispatcher
example and the crash-recovery cookbook cross-link into the generator
template so they survive `npm run generate-agent-docs` and pass the
ci:docs-check step.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): address three pre-existing CodeQL alerts surfacing on PR #641

- Alert #41 (js/prototype-pollution-utility, medium): GovernanceMiddleware
  setAtPath() already blocked __proto__/constructor/prototype via
  FORBIDDEN_PATH_SEGMENTS set, but CodeQL's pattern matcher only
  recognizes inline equality checks. Added explicit `part === '__proto__'
  || part === 'constructor' || part === 'prototype'` inline guard, plus
  hasOwnProperty traversal check so a malicious prototype-chained value
  can't be followed mid-path. Belt-and-suspenders.
- Alerts #28 and #29 (js/clear-text-logging, high): manual test script
  .catch() handlers logged the full error object, which CodeQL traced
  back to OAuth metadata on auth failures. Narrowed to error.name and
  error.message; full stack restored via DEBUG=1.

Test suite: 4288 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(security): drop redundant err truthiness check inside if (err) blocks

CodeQL flagged 'useless conditional' in the verifier/preTransport error
handlers. The err variable is already guaranteed truthy inside the
guarded branch, so err && (err as Error).name collapses to just
(err as Error).name.

Both sites in src/lib/server/create-adcp-server.ts (line 1228) and
src/lib/server/serve.ts (line 277) cleaned up.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(server): boot diagnostics + webhook suppressLegacyWarnings + reviewer followups

Addresses final-pass reviewer feedback on PR #641:

- ADCP_SIGNED_REQUESTS_STATE symbol + AdcpSignedRequestsState type
  on the returned McpServer. Carries {autoWired, specialismClaimed,
  capabilitySupported, mismatch} so operator boot diagnostics and
  integration tests can assert the wiring without parsing log output.
  Closes the claim-without-config asymmetry concern — the state is
  structured and testable; the logger.error still fires for the legacy
  manual-wiring path.
- createWebhookEmitter({ suppressLegacyWarnings: true }) — programmatic
  equivalent of ADCP_SUPPRESS_HMAC_WARNING=1 for libraries embedded in
  agents where env vars are awkward. Threaded through
  deliverOnce → buildHeaders → maybeWarnHmacDeprecation.
- attachMatch JSDoc: explicit note that shallow clones ({...result})
  don't carry the non-enumerable method — use the free function or
  attachMatch() on clones.
- Migration doc: HMAC timing window ("post-2026 H2 when buyer 9421
  adoption telemetry stabilizes") + two suppression paths documented
  side-by-side (env var vs programmatic).

New tests in test/server-auto-signed-requests.test.js:
- exposes auto-wire state via ADCP_SIGNED_REQUESTS_STATE symbol
- flags claim_without_config in state on legacy manual-wiring path
- asserts specific error messages for each misconfig pattern (config
  + no claim; claim + supported:false; claim + request_signing omitted)
- accepts non-tools/call JSON-RPC body (notifications/initialized)
  without triggering 401 — verifies operation=undefined falls through
- populates VerifyResult.agent_url when agentUrlForKeyid returns a URL
  (direct unit test on verifyRequestSignature)

Test suite: 4301 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(auth): audience-binding + multi-host caveats + diagnose oauth subcommand alias

Addresses final reviewer feedback on PR #641:

1. Audience-binding caveat — auth.ts JSDoc now calls out that custom
   authenticate callbacks (not using verifyBearer) MUST validate aud
   themselves. Same-tenant tokens are replayable against any agent
   sharing the tenant without per-resource isolation. verifyBearer's
   audience is already required and strictly validated; this just
   documents the custom-auth footgun.
2. Multi-host caveat on serve().publicUrl — JSDoc expanded to name
   the exact failure mode: one Node process fronting multiple hostnames
   silently advertises the wrong resource to all but one. Run one
   serve() per host until a host-aware helper ships.
3. `adcp diagnose oauth <alias>` subcommand alias for `adcp diagnose-auth`.
   Canonical form stays hyphenated; the `<noun> <verb>` alias matches
   what some docs expect. Usage line updated.

All four requested probe checks (wire trace, token claims pre/post
refresh, well-known cross-wiring detection, WWW-Authenticate check)
are already implemented by runAuthDiagnosis — H1 specifically is the
"Resource URL mismatch between well-known and agent host" hypothesis
that catches the cross-wiring case.

PR #562 body updated separately via gh pr edit to close the
"401 after successful authentication" known-limitation note — fully
diagnosed as server-side (no verifier wired + well-known cross-wiring);
client-side fix is complete.

Test suite: 4305 pass, 0 fail, 12 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant