Skip to content

fix(gateway): claude-cli session tools fail after the turn that started the MCP loopback ends - #165432

Merged
steipete merged 10 commits into
openclaw:mainfrom
Oldrich333:fix/mcp-loopback-boot-context
Oct 7, 2026
Merged

steipete merged 10 commits into
openclaw:mainfrom
Oldrich333:fix/mcp-loopback-boot-context

Conversation

@Oldrich333

@Oldrich333 Oldrich333 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: CLI-backed agents lose admin or session tools after the turn that first starts the shared MCP bridge ends. The listener can retain that starter's permission ceiling, caller liveness, and transcript read fence.

Fixes #157126.

User Impact

Later CLI turns keep their own permissions and working session tools regardless of which turn started the listener. Write-only and revoked callers remain rejected. The listener also retains the Gateway's process broker and database-reader lifecycle. No new configuration, protocol, schema, or migration is required.

Why This Change Was Made

The earlier operator-authority fix in #165428 does not clear the other turn-local stores. Start the listener through the existing detached async-context owner, retain the Gateway resolver, and restore each grant's host-owned request scope for dispatch. Use the existing GatewayConnectionWork owner to retain the Gateway's spawn broker and read-only worker scope without retaining creator-turn authority.

The previous revision incorrectly used a plain AsyncWorkScope, dropping those host resources. The new HTTP regression requires the reader scope to survive while both the transcript fence and unrelated turn-local store disappear.

The previous exact-head CI run also exposed a separate routing defect: mcp-http.test.ts and mcp-http.session-controls.test.ts reached host-only SQLite from Vitest worker threads. The direct-dispatch cases failed too, before using the listener. Both files now use the existing parallel database-worker fork lane, like their MCP storage siblings; no new serial configuration or worker-count pin was added.

Evidence

Verified head: 62dd7172822ec72dac19e57a71be362f34c7099a.

Local static checks passed: scoped oxfmt, oxlint from a clean trusted-main worktree, and git diff --check. Fresh independent Codex autoreview returned scoped-clean through P2 on the exact candidate tree before commit.

Fresh untrusted AWS proof: lease cbx_c81e884c7cc4, run run_570d6c85fc3ce51a891d54556d684279; lease released after testing. The trusted-main bootstrap verified the pushed full SHA and no-role IMDS boundary. Public networking, no Tailscale, no credential hydration, isolated HOME.

pnpm tsgo:core && pnpm test src/gateway/mcp-http*.test.ts src/gateway/mcp-http/*.test.ts src/gateway/mcp-grant-store.test.ts src/entry.update-failure.process.test.ts src/gateway/server-connection-work.test.ts --maxWorkers=1

Result: core typecheck and 205 tests / 22 files passed, including all 19 MCP HTTP files and both previously failing files. Combined wall time 259.82 s; test orchestration 243.12 s. The native runner placed both database-dependent files in gateway-database-workers, where all collector and direct-dispatch/HTTP session-control cases passed.

Two production-only negative controls ran on the same lease, leaving regressions unchanged:

# Previous repair: isolate the missing host-resource retention.
git checkout c8fbc4a64bc1f887ed38e6d49d21e7d281efe1e9 -- src/gateway/mcp-http.ts
pnpm test src/gateway/mcp-http.async-scope.test.ts --maxWorkers=1 -t 'keeps Gateway readers'

# Main merge base: isolate the original request-scope and transcript-fence defects.
git checkout 7880834c19616b5efb871e1755cd4b30cf2f2481 -- src/entry.ts src/index.ts src/gateway/mcp-grant-store.ts src/gateway/mcp-http.ts
pnpm test src/gateway/mcp-http.async-scope.test.ts --maxWorkers=1 -t 'keeps Gateway readers|keeps each CLI grant'

Previous-head control: 1 expected failure, exit 1, 31.55 s wall. The HTTP callback returned [undefined, undefined, undefined] instead of [undefined, undefined, readerContext]: turn stores were clear, but the Gateway reader was lost.

Main control: 2 expected failures, exit 1, 31.65 s wall. The callback retained the first-turn receipt and first-turn marker, and the owner-call assertion failed with:

- "text": "admin-dispatched"
+ "text": "missing scope: operator.admin"

Exact-head CI: run 37556999602 passed, elapsed 449 s. The previous failed run 37554842902 exposed the missing host-main-thread test routing: its direct-dispatch stack reached openSharedStateSqliteWorkerStore and the !isMainThread guard. That failure is separate from the resource-context regression, which the new negative control proves independently.

Test cost: grouped single-worker shards took 19.13 s (unit), 156.77 s (Gateway), and 39.36 s (infrastructure), plus preparation/orchestration. Reported test-body time: async-scope 1.148 s; MCP HTTP 10.347 s; session-controls 31.287 s. These are grouped measurements, not independent per-file command wall times. The existing ten session-control cases exercise real SQLite writes and final-effect revocation across direct and HTTP boundaries; replacing that boundary with mocks would lose the contract being checked. No new process boots, polling, or sleep-based tests were added. Full build and live Claude inference were not run in this pass.

LOC versus main merge base: production +57/-61 (net -4); tests/support +344/-4; test routing +2/-0; docs +3/-0. The cold-import probe is Vitest-only support. Exact numstat:

3   0  docs/gateway/cli-backends.md
1   1  src/entry.ts
3   1  src/entry.update-failure.process.test.ts
27 37  src/gateway/mcp-grant-store.ts
238 3  src/gateway/mcp-http.async-scope.test.ts
7   0  src/gateway/mcp-http.cold-import-default.test.ts
7   0  src/gateway/mcp-http.cold-import-legacy.test.ts
89  0  src/gateway/mcp-http.cold-import-probe.ts
28 23  src/gateway/mcp-http.ts
1   0  src/index.ts
2   0  test/vitest/vitest.gateway-server-paths.mjs

ClawSweeper's earlier P1 remains addressed by per-grant permission ceilings and live caller checks. The latest reviewed findings were empty; the human cold-import concern remains covered by both entrypoint tests.

Original fix by @Oldrich333; incorporated request-scope work by @Leit-motif retains its original commits. Maintainer cleanup by Peter Steinberger reuses the existing context/resource owners, simplifies host-only projections, and removes duplicate coverage while preserving both cold-import tests and the installation-replacement fixture.

…rn's context

The loopback listener starts lazily inside the first claude-cli turn and Node
serves every later request in that listen-time async context, so requests
inherited the starting turn's stores (transcript read fence, operator
authority). Start the listener in a module-load snapshot and carry only the
starter's Gateway resolver.
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 6, 2026, 9:31 PM ET / October 7, 2026, 01:31 UTC (Revision 6).

ClawSweeper review

What this changes

The PR isolates the shared CLI tool listener from its starting turn while preserving Gateway resources and restoring each calling run’s permissions and liveness checks.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: current main still has the request-scope and transcript-context leak, and the merged listener fix addresses a different lifetime. No blocking correctness defect was found in the pinned patch.

Priority: P1
Reviewed head: 62dd7172822ec72dac19e57a71be362f34c7099a

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong existing behavior evidence and no blocking code finding; required PR context and build validation remain.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Existing disposable-Gateway observations and incorporated live restart/revocation logs demonstrate later owner success and forbidden-caller rejection through the changed grant/dispatch path. The HTTP regressions provide supplemental final-handler checks and transcript isolation coverage. The latest resource-retention change has source and regression coverage, but prior-head execution is not exact-head validation. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): Existing disposable-Gateway observations and incorporated live restart/revocation logs demonstrate later owner success and forbidden-caller rejection through the changed grant/dispatch path. The HTTP regressions provide supplemental final-handler checks and transcript isolation coverage. The latest resource-retention change has source and regression coverage, but prior-head execution is not exact-head validation. No stored-data contract changes.
Evidence reviewed 10 items Pinned introduction: Reviewed the merge-base-to-head delta, with checkout and original head both pinned to 62dd717. The supplied test merge has mismatched parents and was not used to infer removal of current-main behavior.
Still necessary on main: Current main starts the listener by exiting only operator-tool authority, plugin generation, and root-work admission. It neither detaches every turn-local store nor restores each grant’s minting request scope. The merged #165428 therefore does not cover this PR’s remaining behavior.
Latest release remains affected: The latest release’s listener startup exits generation and work admission without clearing the starting request scope. Inspected the pinned release blob through GitHub after a local lazy-object read failed with HTTP 403.
Findings None None.
Security None None.

How this fits together

CLI-backed agents call OpenClaw tools through a shared local MCP HTTP listener. The listener resolves each run’s grant and dispatches tools into the Gateway, where permissions and current caller authority govern the action.

flowchart TD
  A[CLI agent turn] --> B[Host-owned run grant]
  B --> C[Shared local MCP listener]
  D[Gateway resource lifetime] --> C
  C --> E[Restore calling run scope]
  E --> F[Check permissions and live authority]
  F --> G[Tool result or rejection]
Loading

Before merge

  • Complete next step (P2) - Restore What Problem This Solves, User Impact, and Why This Change Was Made in the PR body, and record a successful full build for the reviewed preload changes.
Agent review details

Security

None.

PR surface

Source +85, Tests +253, Docs +3. Total +341 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 146 61 +85
Tests 5 257 4 +253
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 406 65 +341

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #157126
Summary: This PR is a candidate repair for the canonical request-scope issue and additionally clears the retained transcript context.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Use the shared detached-context and Gateway resource owners while keeping every tool call bound to its own live run authority.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main startup retains the first request’s scope, and supplied production-file negative controls reproduce both the admin ceiling and stale transcript store. This read-only review did not execute target code.

Is this the best way to solve the issue?

Yes: the patch reuses existing lifecycle owners and restores per-run authority without adding configuration, protocol, or persisted-state changes.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 63938d89f149.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The reported leak breaks established CLI-agent admin and session-tool workflows across later turns.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Existing disposable-Gateway observations and incorporated live restart/revocation logs demonstrate later owner success and forbidden-caller rejection through the changed grant/dispatch path. The HTTP regressions provide supplemental final-handler checks and transcript isolation coverage. The latest resource-retention change has source and regression coverage, but prior-head execution is not exact-head validation. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Existing disposable-Gateway observations and incorporated live restart/revocation logs demonstrate later owner success and forbidden-caller rejection through the changed grant/dispatch path. The HTTP regressions provide supplemental final-handler checks and transcript isolation coverage. The latest resource-retention change has source and regression coverage, but prior-head execution is not exact-head validation. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction: Reviewed the merge-base-to-head delta, with checkout and original head both pinned to 62dd717. The supplied test merge has mismatched parents and was not used to infer removal of current-main behavior. (62dd7172822e)
  • Still necessary on main: Current main starts the listener by exiting only operator-tool authority, plugin generation, and root-work admission. It neither detaches every turn-local store nor restores each grant’s minting request scope. The merged fix(gateway): later CLI bridge calls fail after the listener's creator turn completes #165428 therefore does not cover this PR’s remaining behavior. (src/gateway/mcp-http.ts:571, 63938d89f149)
  • Latest release remains affected: The latest release’s listener startup exits generation and work admission without clearing the starting request scope. Inspected the pinned release blob through GitHub after a local lazy-object read failed with HTTP 403. (src/gateway/mcp-http.ts, fc23bc864e45)
  • Prior authority finding resolved: Grant minting retains the host request scope outside child-visible context; HTTP execution re-enters that scope. Existing grant replacement, admission, cancellation, and revocation checks remain. The dispatch owner consumes the caller’s scope ceiling and live-authority callback. (src/gateway/mcp-http.ts:435, 62dd7172822e)
  • Latest resource-retention repair: The latest commit replaces the listener’s plain work scope with the existing Gateway connection-work owner, which restores captured SQLite readers and the spawn broker for received work. It extends reader-retention coverage and routes the two host-SQLite suites through the existing database-worker lane, addressing the previous collector/session-control concern without removing assertions. (src/gateway/mcp-http.ts:575, 62dd7172822e)
  • Behavior and forbidden-caller evidence: The supplied contributor comment describes a disposable Gateway where later owner admin calls and history reads succeed while write-only recovery remains denied. Incorporated live evidence at fix(gateway): run CLI bridge tool calls in their own run's request scope #157144 records device revocation before a refused secrets call. The retained HTTP regression exercises real listener and dispatch owners, checks owner success, write-only rejection, closed-caller rejection, and revoked-grant HTTP 401, and verifies the admin handler is not called again. The body reports passing c8fbc4a tests and two failing production-file negative controls; those results are prior-head evidence, not execution of the latest resource change. (src/gateway/mcp-http.async-scope.test.ts:253, 62dd7172822e)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Shakker: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Restore the required authored PR-template sections using the existing problem, impact, and evidence text.
  • Record a successful full build for the reviewed CLI preload and listener-loading changes.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-05T08:03:58.503Z sha bd87480 :: needs real behavior proof before merge. :: [P1] [P1] Restore each grant’s authority scope before clearing the listener
  • reviewed 2026-10-06T04:53:52.856Z sha 7939176 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T05:05:24.736Z sha efc5951 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T05:25:57.525Z sha efc5951 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-07T01:12:45.674Z sha c8fbc4a :: needs changes before merge. :: none

@chessing234 chessing234 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit bd874809fb55b650ea7efca17c7a90ac7e49bfae.

Inspected MCP listener context capture and startup/shutdown import ordering. No actionable correctness issue found.

Validation: static source review only; runtime tests were not run. This review makes no assertion that CI or platform tests pass.

@XX441

XX441 commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Agent-written on behalf of @XX441 · agent: Java (OpenClaw main) · model: anthropic/claude-opus-5-5

Independent confirmation of this bug on 2026.9.5 (macOS arm64, Node 24.21.0, claude-cli runtime with a reusable live CLI session), plus one extra symptom path.

Symptom in production. Six lane task error … Current-turn transcript admission identity changed: <entryId> over two days on one dashboard session, all with the same entryId. That id is a still-visible user message from the turn during which the loopback listener was lazily started. The session's transcript_rewrite_watermarks.generation changed afterwards, during a cold-maintain reclamation and a later rewrite. From then on:

  • every sessions_history call on that session from the bridge failed;
  • every queued announce turn for replies to sessions_send failed in prepare. These turns are enqueued from inside an MCP request, so they inherit the listener's stale fence store, and runWithSessionTranscriptReadFence(undefined, run) simply calls run() in the ambient context.

Turns started by real inbound user messages kept working, because they carry their own receipt.

Minimal repro of the leak (Node 24), matching your new test:

import { AsyncLocalStorage } from "node:async_hooks";
import { createServer, request } from "node:http";
const fence = new AsyncLocalStorage(), rootWork = new AsyncLocalStorage();
let server;
await fence.run({ entryId: "stale" }, () => rootWork.run({}, () => rootWork.exit(() => new Promise(r => {
  server = createServer((req, res) => res.end(JSON.stringify({ fence: fence.getStore() ?? null })));
  server.listen(0, r);
}))));
request({ port: server.address().port }, res => res.on("data", d => { console.log(String(d)); server.close(); })).end();
// {"fence":{"entryId":"stale"}}

One caveat on the module-load snapshot. It is only clean if mcp-http is first evaluated outside any turn. In our 9.5 dist build the module is reached through prepare.runtime (cli-runner prepare), so it may first evaluate lazily inside a fenced turn, and the snapshot would then capture that turn's stores. For our 9.5 local carry we therefore explicitly exit the transcript read-fence and question-answer stores when starting the listener, combined with your withPluginRuntimeGatewayContextResolver(…, { inheritRequestScope: false }), instead of relying on load order. A regression test that starts the listener while mcp-http is first imported inside a fenced turn might be worth adding.

Hardening suggestion (separate from this PR): make runWithSessionTranscriptReadFence(undefined, run) explicit about whether it inherits or clears. Callers that pass "no receipt" for system/announce turns probably intend "no fence".

Leit-motif and others added 6 commits October 6, 2026 04:34
The listener no longer inherits its starter's scope, so each CLI grant now
carries the Gateway request scope it was minted in. Bridge tool calls re-enter
that scope, as in-process runtimes do, so a write-only restart-recovery run stays
capped and a run whose client authority closed is still refused.
…its starting turn

Node serves each loopback request in the listener's listen-time async
context. Exiting stores one by one (caller identity, request scope,
operator authority) still left the starting turn's transcript read fence
and other turn-local stores on every later bridge call. Start the listener
in a load-time AsyncLocalStorage snapshot, as runInMcpManagerContext does,
keeping only the starter's Gateway resolver; each grant still re-enters its
own run's request scope.

The authority-chain regression test is adapted from Grynn's patch on openclaw#157144.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal channel: slack Channel integration: slack labels Oct 6, 2026
@Oldrich333

Copy link
Copy Markdown
Contributor Author

Agent-written on behalf of @Oldrich333 · agent: hive-admin/executor · model: openai/gpt-6-sol · origin: agent-initiated

@clawsweeper re-review

Updated head 7939176832685d5306ddc487ad435db0660d63ab (9-file diff). Your P1 on the prior head is addressed: #157144's two commits retain authorship and restore each CLI grant's own request-scope ceiling and caller liveness before dispatch; the listener separately starts outside every async store of its first turn. Both executable bootstraps capture the process-root context before a CLI turn can first import the listener.

Evidence in the updated PR body: a fresh disposable Gateway built from the reviewed tree lets owner admin calls and cross-session history reads succeed; a write-only restart-recovery run that starts the listener receives missing scope: operator.admin; a later owner call succeeds. In-process HTTP tests cover closed caller liveness and revoked grant (401) before admin handler dispatch. Default and legacy cold-first-import tests fail under a negative control that removes their early preload. Two independent GPT-6.1-Sol high reviews found no remaining defect.

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Merge current main and reuse its detached async context owner instead of adding a second process-root snapshot. Keep each MCP grant bound to the originating request scope so later turns do not inherit the listener creator permission ceiling, liveness, or transcript fence. Preserve cold-entry and real HTTP authority regressions while removing duplicate coverage and host-only projection boilerplate.
Use the existing GatewayConnectionWork owner to retain spawn-broker and database-reader lifetimes while the shared MCP listener sheds creator turn context. Extend the HTTP regression to require the retained readers. Route the two MCP suites that use host-only SQLite through the existing database-worker fork lane; their CI thread-pool failures also affected direct dispatch.
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: claude-cli MCP bridge inherits the request scope that first started it; after a restart-recovery run, owner turns lose operator.admin

5 participants