Repository navigation
feat(mcp): per-request header provider for volatile turn attribution on OpenClaw-owned HTTP transports - #154043
TreyLawrence wants to merge 71 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. What this changesAdds plugin-provided turn-specific MCP HTTP headers without rebuilding cached transports or tool catalogs. Example: Two turns call the same MCP server with traceparent values trace-first and trace-second.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains Keep this PR open: it supplies a missing per-request MCP capability with meaningful transport proof and no verified code findings, but acceptance of the public SDK contract remains unresolved. Priority: P2 Decision needed
Before merge
FindingsNone. Agent review detailsHow this fits togetherThe embedded runner binds run identity, materialized MCP tools retain attribution, and the HTTP fetch boundary combines plugin-provided headers with authoritative transport credentials before network dispatch. flowchart LR
A[Embedded run] --> B[Host-bound context]
B --> C[Materialized MCP tools]
C --> D[Retained HTTP transport]
E[Plugin header provider] --> F[Guarded request dispatch]
D --> F
F --> G[MCP server]
Technical reviewBest possible solution: Accept a narrow plugin-owned attribution seam if the SDK owners endorse its public contract and separation from requester authentication. Do we have a high-confidence way to reproduce the issue? Source confirms that declarative header changes affect catalog identity and resolved connection headers affect rotation; supplied loopback traces demonstrate distinct turn headers on a retained transport, though this review ran no target code. Is this the best way to solve the issue? Separating volatile attribution from cached credentials addresses the demonstrated boundary cleanly, while the exact supported public API remains an owner decision. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 9f83c05ea3a4. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +334, Tests +1217, Docs +75, Other +2. Total +1628 across 27 files. Added test files: 6. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (46 earlier review cycles; latest 8 shown)
Reviewed October 14, 2026, 9:55 AM ET / 13:55 UTC (Revision 47). |
3b78e62 to
b764fbf
Compare
…spatch A tool call canceled while the request-header provider resolves settles its attribution scope; the dispatch fallback then forwarded the original request without volatile headers on the retained transport. Reject the expired attributed operation before any HTTP I/O instead. Adds unit coverage and a real-runtime loopback proof (test/pr154043-real-runtime-proof.e2e.test.ts). Co-Authored-By: Claude Fable 5 <[email protected]>
b764fbf to
43a4d95
Compare
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Retriggering CI: the failing tests are outside this PR and pass on current main. |
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Retriggering CI: the failing Slack test is outside this PR and passes on current main. |
…t-header-provider
…tion-order proof Main removed the agent-bundle-mcp-runtime testing facade (openclaw#174347). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Retriggering CI: the failing test is outside this PR and passes on current main. |
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts # src/agents/embedded-agent-runner/run/backend.test.ts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Retriggering CI: the failing checks are outside this PR and pass on current main. |
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts # src/agents/mcp-http-transport.ts
|
Retriggering CI: the failing checks are outside this PR and pass on current main. |
…t-header-provider # Conflicts: # docs/plugins/sdk-overview/infrastructure.md # src/plugins/registry-registrars-network.ts
…t-header-provider # Conflicts: # scripts/plugin-sdk-surface-report.mts
|
Retriggering CI: the failing checks are outside this PR and pass on current main. |
What Problem This Solves
Per-turn MCP attribution currently has to enter declarative server headers or the connection resolver. Declarative header changes invalidate the catalog; the reported Reef production measurement was 221 re-catalogs across 222 runs. The existing connection resolver caches requester credentials for five minutes, and changed resolved headers rotate the connection. Neither path can provide fresh turn attribution while retaining a transport and its catalog.
This adds a separate plugin request-header provider for OpenClaw-owned MCP HTTP transports. Upstream main was checked at
7aaef70932b30f4d7410ae00aa65b07089de2ce0; no equivalent provider existed.Deployment consumer. The Reef embedder plugin (the same production deployment behind the measurement above) adopts this provider on release adoption: it moves
traceparentand signed per-turn context headers off declarative server configuration and onto this seam, which retires the measured per-run re-catalog. Requester authentication stays entirely on the existing connection-resolver contract — this consumer sends attribution and turn-scoped credentials only, and its stable credentials are unchanged.User Impact
Plugins can attach
traceparent, signed turn credentials, and optional direct-request credentials to individual MCP requests without rebuilding the catalog or connection. Stable authentication remains in static server configuration or the existing connection resolver.The SDK infrastructure documentation includes registration and embedded-runtime usage. This contract covers OpenClaw-owned HTTP transports; external harness-native MCP clients need OpenClaw materialized tools to use it.
Design
api.registerMcpServerRequestHeaderProvider({ serverName, resolve }), following connection-resolver registration conventions. Resolver and header-provider registrations share per-server plugin ownership, and the connection resolver is authoritative regardless of registration order: a foreign provider is rejected when the resolver already exists and displaced (removed, error diagnostic on the provider's plugin) when the resolver registers later. Registry state is identical in both orders, so a declared server with a resolver is never partitioned as static.sessionId/sessionKey/runId(internalbindMcpRequestRun), and the binding is revoked when that run settles. A context the host did not issue (forged) or whose run has settled (stale/reassigned) is dropped: the provider is not called and no volatile headers are sent. The public export fromopenclaw/plugin-sdk/agent-harness-runtimeisrunWithMcpRequestMetadata(metadata, callback)— caller tracing metadata only (e.g.traceparent), never identity.Correctness
Each operation owns an immutable context. Missing context explicitly clears inherited attribution and skips the provider. No transport stores a mutable latest-turn header map. Provider results are freshly merged into a new request header object and are not retained for redirect replay.
Initial SSE discovery can carry its discovery context. Shared streamable notification GETs and legacy SSE reconnects carry no volatile attribution. The streamable initialized-notification send has a short-lived scope so its shared stream parser and reconnect timers cannot retain the opening turn, including reconnects with
Last-Event-ID. Resumable RPC streams retain their own still-active operation context. Completed scopes cannot supply headers to background callbacks.Static authentication, requester credential revalidation/rotation, genuine configuration invalidation,
tools/list_changed, and transport-close recovery retain their existing owners and behavior.Evidence
Guarded caller-authority revalidation (Rev 24 P1, head
34a4b55ad)Defect (ClawSweeper Rev 24).
fetchWithSsrFGuardasserts the captured guarded caller authority (captureGuardedFetchRequestAuthority, e.g. a live cron-root claim) before invoking the transportfetchImpl. The header wrapper is thatfetchImpland awaitsprovider.resolve(), so authority revoked during resolution was not re-checked before stable credentials and volatile headers reached the server.Fix.
withMcpRequestHeaderscaptures the guarded assertion on entry and re-asserts it immediately before dispatch, alongside the existing abort and run-context checks. A revoked caller gets the assertion's own error, and no request is sent.Final-effect proof. The real-runtime e2e adds a call under
withGuardedFetchRequestAuthoritywhose MCP run stays active. Caller authority is revoked while the provider is resolving. The call is rejected, and the recording loopback server's request count is unchanged (no request forrevoked_authority_operation). Regression-before-repair: with the re-assertion removed, the same scenario fails withpromise resolved "{ content: [ ... ] }" instead of rejecting, meaning the real server received and answered the revoked call. A matching unit case (mcp-request-headers.test.ts) fails without the fix and passes with it.Redacted terminal capture (
OPENCLAW_E2E_SKIP_BUILD=1 OPENCLAW_E2E_VERBOSE=1 pnpm vitest run --config test/vitest/vitest.e2e.config.ts test/pr154043-real-runtime-proof.e2e.test.ts):At this head: focused suites 8 files / 156 tests passed; core
tsgopassed; timeout-race ratchet clean for PR files; formatting and lint clean.Run-identity authority + final-I/O proof (Rev 22 security item, head
a6194b291)Concern (ClawSweeper Rev 22). The public
runWithMcpRequestContextaccepted caller-suppliedsessionId/runId, and the documented provider signs those IDs, so a caller could assert a foreign run and obtain a signed header at final HTTP I/O. A captured context also stayed usable after its run settled.Fix — bind signed identity to admitted runs (the recommended option).
runEmbeddedAttemptWithBackendcalls the internalbindMcpRequestRunwith the admitted run's identity, keeping enclosing caller metadata.getMcpRequestContext()returns nothing for a revoked or never-issued context, so the provider is never invoked for it. A run that settles while headers resolve is refused before dispatch by the existingMCP request context expiredcheck.runWithMcpRequestMetadata(metadata only). Plugins and embedded callers can no longer name a session or run.Final-effect proof.
test/pr154043-real-runtime-proof.e2e.test.tsnow also drives, on the same real MCP SDK client + guarded streamable-HTTP transport + recording loopback server:{ runId: "victim-run" }and the public SDK helper each reach the server with no attribution header; the provider never seesvictim-run.Regression-before-repair. With the old trust semantics temporarily restored (any context accepted, no revocation), the proof fails at final I/O. The server received a signed header for the forged run:
Redacted terminal capture after the fix (
OPENCLAW_E2E_SKIP_BUILD=1 OPENCLAW_E2E_VERBOSE=1 pnpm vitest run --config test/vitest/vitest.e2e.config.ts test/pr154043-real-runtime-proof.e2e.test.ts):Unit coverage (
src/agents/mcp-request-headers.test.ts) adds: forged identity never resolves headers, captured context revoked after its run settles, and a run settling mid-resolution refuses dispatch.agent-bundle-mcp-runtime.request-headers.test.tsnow holds each turn open across acquisition and execution, as a host run does, and asserts that a settled turn's executor sends no attribution. On the merged head (current main3f7689e64): focused suites (mcp-request-headers,agent-bundle-mcp-runtime{,.request-headers},mcp-transport,mcp-http-transport,mcp-http-fetch,backend, requester-connect,registry-registrars-network.mcp-request-headers) 10 files / 159 tests passed; both PR e2e proofs passed; coretsgopassed;plugin-sdk:surface:checkpassed (budget pinned to exactly this PR's two exports); formatting and lint clean. The merge resolved main'smcp-http-fetch.tsredirect-policy refactor by applying the provider wrap inside the shared builder.Registration-order fix + authority-chain proof (head
2587f4f3)Defect (ClawSweeper P1, Rev 8).
hasMcpServerOwnerConflictwas first-registration-wins across both seams: a request-header provider registered first by plugin A caused plugin B's laterregisterMcpServerConnectionResolverfor the same server to be rejected.partitionMcpServersByConnectionScopethen found no resolver and classified the declared server as static, exposing its configured connection to requesters the resolver would have excluded. The PR's own registrar test pinned that behavior.Fix. The connection resolver is authoritative regardless of order.
registerMcpServerConnectionResolverstill fails closed against a different plugin's resolver; against a different plugin's provider it now displaces it — the provider entry is removed and an error diagnostic is reported on the provider's plugin (MCP server request header provider for "<name>" displaced: connection resolver registered by plugin "<resolver plugin>" owns requester admission).registerMcpServerRequestHeaderProvideris unchanged (rejected when a different plugin owns either seam). Final registry state is identical in both registration orders.docs/plugins/sdk-overview/infrastructure.mdstates the rule.Regression proof, unit (
src/plugins/registry-registrars-network.mcp-request-headers.test.ts,it.each(["provider","resolver"])): with the registrar fix reverted, the provider-first case fails —— and passes with the fix (5/5). Both orders additionally assert, under
withPluginRuntimeRegistryScope, thatpartitionMcpServersByConnectionScopeputsuser-mailinresolverRequesterServerNamesandstaticServersis empty.Authority-chain proof, real transports (
test/pr154043-registration-order-proof.e2e.test.ts, no transport/SDK mocks). plugin-a registers a request-header provider foruser-mail; plugin-b registers a requester-scoped connection resolver that returns{ url: <loopback>, headers: { Authorization: "Bearer proof-token" } }only forallowed-requesterandnullotherwise. The declared config isurl: "https://placeholder.invalid/mcp"; the loopback (startRequesterScopedMcpProofServer) 404s without the bearer and records every request. Driven throughmaterializeRequesterScopedMcpToolsForHarnessRunfromopenclaw/plugin-sdk/agent-harness-runtime. In both orders:user-mailpartitions as resolver-scoped, never static; the allowed requester materializes tools and executesrequester_probe, and every loopback request carried the bearer and none carried plugin-a's header; an excluded requester and a run with norequesterSenderIdget no tools and the loopback request count does not move; plugin-a's provider is never invoked.With the registrar fix reverted, the provider-first case fails at the static-partition assertion (the exact exposure):
Redacted passing capture (
OPENCLAW_E2E_SKIP_BUILD=1 OPENCLAW_E2E_VERBOSE=1 pnpm vitest run --config test/vitest/vitest.e2e.config.ts test/pr154043-registration-order-proof.e2e.test.ts test/pr154043-real-runtime-proof.e2e.test.ts):Merge with main. Branch merged
upstream/main(a08479ac, plain merge commit). Conflicts:backend.ts(main dropped harness-finalization imports; therunWithMcpRequestContextwrapper aroundrunAgentHarnessAttemptis re-grafted on main's shape) andagent-bundle-mcp-runtime.test.ts(main extractedstartRequesterScopedMcpProofServerto a test-support module; the PR'sstartRequestHeaderMcpProofServernow lives inagent-bundle-mcp-request-headers.test-support.ts, and the per-request header runtime tests moved to the siblingagent-bundle-mcp-runtime.request-headers.test.tsto satisfy the line-cap ratchet, leavingagent-bundle-mcp-runtime.test.tsuntouched).scripts/plugin-sdk-surface-report.mtsbudget raised by this PR's two public exports (runWithMcpRequestContext,McpServerRequestContext).Verification at this head: core
tsgo0 errors; unit batch (agent-bundle-mcp-runtime,backend,mcp-http-transport,mcp-request-headers,mcp-transport,registry-registrars-network.mcp-request-headers,mcp-connection-resolver) 7 files / 193 passed;agent-bundle-mcp-runtime.request-headers2 passed; e2e proofs 2 files / 3 passed;test/scripts/eager-import-closure.test.ts16 passed;pnpm config:docs:checkOK; fullpnpm lint(core + extensions) passed;pnpm check:changedgreen through the SDK surface budget, plugin boundaries, wrapper shadowing and core typecheck (the only failure,typecheck core tests, is twoassertReliabilityForcedExitimport errors insrc/infra/package-update-activation-*.test.ts, present on untouched upstream main).Cancellation lifecycle fix + real-runtime proof (head
15fdd821)The prior head had a defect at the dispatch boundary: an operation canceled while
provider.resolve()was awaited settles its attribution scope, and the fallback then forwarded the request without volatile headers on the retained transport — final I/O after cancellation, under stable connection credentials. The dispatch point now rejects an expired attributed operation with a content-free error instead of falling back; the shared-transport abort check is unchanged. Regression-before-repair was verified both ways: the new unit case fails on the old expression (fetch dispatches), and temporarily restoring the old expression makes the runtime proof's server-request-count assertion fail (expected 5, received 6).test/pr154043-real-runtime-proof.e2e.test.tsdrives the real transport path —resolveMcpTransport+ the real MCP SDKClientover streamable HTTP against a loopback server that records every request it receives, with synthetic attribution and no real credentials. It proves, on one retained transport: (1) an allowedtools/callarrives carrying its volatile attribution header; (2) an operation aborted mid-header-resolution is rejected and the server receives no request for it (the real pendingtransport.sendis observed to settle rejected, so the zero-I/O assertion cannot race dispatch); (3) a subsequent attributed call on the same transport succeeds.Redacted terminal capture (
OPENCLAW_E2E_SKIP_BUILD=1 OPENCLAW_E2E_VERBOSE=1 pnpm vitest run --config test/vitest/vitest.e2e.config.ts test/pr154043-real-runtime-proof.e2e.test.ts):At this head: focused suites
mcp-request-headers,mcp-http-transport,mcp-transport,registry-registrars-network.mcp-request-headers— 4 files / 46 tests passed; coretsgopassed; formatting clean.Original evidence (unchanged)
Last-Event-ID, and attributed RPC resumptions.Validation on Node 24.18.0 with the pinned pnpm 12.4.0 toolchain:
pnpm build: passed.tsgo: passed.agent-bundle-mcp-runtime.test.ts: 120 passed, 6 failed (all six reproduced on untouched upstream main); final source verification completed.agents-root,agents-other,plugins-platform): passed.Both complete runtime runs had 120 passes and six failures. All six failures reproduced on untouched upstream main in an isolated archive using the same dependencies. They involve existing stdio cleanup exceeding test deadlines: concurrent catalog startup, catalog invalidation during connection, default hung tools/list timeout, reconnect after child exit, and private acquisition cancellation during initialize/tools-list. No deadlines, assertions, or production stdio behavior were changed. The final run used the settled source and completed artifact verification.
Changed upstream files
docs/plugins/sdk-overview/infrastructure.mdscripts/plugin-sdk-surface-report.mtssrc/agents/agent-bundle-mcp-materialize.tssrc/agents/agent-bundle-mcp-request-headers.test-support.tssrc/agents/agent-bundle-mcp-requester.test-support.tssrc/agents/agent-bundle-mcp-runtime.request-headers.test.tssrc/agents/embedded-agent-runner/run/backend.test.tssrc/agents/embedded-agent-runner/run/backend.tssrc/agents/mcp-http-fetch.tssrc/agents/mcp-http-transport.test.tssrc/agents/mcp-http-transport.tssrc/agents/mcp-request-context.tssrc/agents/mcp-request-headers.test.tssrc/agents/mcp-request-headers.tssrc/agents/mcp-transport.test.tssrc/agents/mcp-transport.tssrc/plugin-sdk/agent-harness-runtime.tssrc/plugin-sdk/plugin-test-api.tssrc/plugins/api-builder.tssrc/plugins/plugin-api.types.tssrc/plugins/registry-empty.tssrc/plugins/registry-registrars-network.mcp-request-headers.test.tssrc/plugins/registry-registrars-network.tssrc/plugins/registry-types.tssrc/plugins/types.mcp-connection.tstest/pr154043-real-runtime-proof.e2e.test.tstest/pr154043-registration-order-proof.e2e.test.ts