Skip to content

fix(gateway): run CLI bridge tool calls in their own run's request scope - #157144

Closed
Leit-motif wants to merge 2 commits into
openclaw:mainfrom
Leit-motif:fix/mcp-bridge-request-scope
Closed

Leit-motif wants to merge 2 commits into
openclaw:mainfrom
Leit-motif:fix/mcp-bridge-request-scope

Conversation

@Leit-motif

@Leit-motif Leit-motif commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Current disposition — October 11, 2026

The implementation in this PR has been incorporated into main by #165432, commit fdcbcf5c2ebd83316f411d406315f08225949c59, which credits Amrit Chana and adapts this PR's authority-chain regression. There is no remaining production fix to merge from this branch.

Current main uses a detached process context for listener startup, retains the Gateway's worker resources, records each grant's minting request scope, and restores that scope for its tool calls. Its HTTP coverage checks starter isolation, fresh replacement scopes, allowed owner dispatch, the write-only ceiling, closed requester refusal, and revoked-grant rejection.

Fresh verification on main cbe0b272883c68210aee33b67e4bdf66d9106587: node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts passed 6/6 tests on macOS/Node 24.16.0. Vitest reported 221.45 s, including cold transformation. This was HTTP/in-process authority boundary proof, not a new live Claude or channel test. No production or test changes were needed.

The v2026.10.1 tag predates the merged detached-context implementation, so the release-pinned follow-up remains relevant to that tag. The original branch's old CI/conflict state is historical; rebasing it would duplicate the implementation and weaker coverage already on main. This PR remains open and non-draft for maintainer disposition; no merge or closure was requested or performed.


Original contributor proposal and historical evidence

Closes #157126

What Problem This Solves

Fixes: after a Gateway restart that resumes an in-flight CLI-runtime turn (for example claude-cli), the owner's later chat turns fail admin-only tools with missing scope: operator.admin until the Gateway restarts again. The same leak also breaks a second owner turn once the first turn's connection has closed (Gateway client authority closed before dispatching ...).

User Impact

User impact: owners of CLI-runtime agents keep their normal tool authority after a restart. Admin-only tools (automations with triggers, secrets, system and config tools) work from chat again. Lower-authority runs keep their own ceiling: the write-only restart-recovery run is still refused admin tools, and a run whose device was revoked mid-turn is still refused before its action. No configuration or migration is required.

Why This Change Was Made

The loopback MCP listener is process-owned but starts lazily inside whichever Gateway request first needs it. Its handlers kept that request's scope and tool-caller identity. So every bridge tool call ran with the authority of whichever run started the listener, not the run making the call. If the restart-recovery continuation (a write-only system caller) started it, every later owner call was capped at operator.write.

The fix has two parts:

  1. The listener no longer inherits its starter. It starts outside the tool-caller identity (withoutGatewayToolCallerIdentity) and outside the request scope (withPluginRuntimeGatewayContextResolver(..., { inheritRequestScope: false })), keeping only the Gateway context resolver. This matches the rule already applied to follow-up and scheduled runs.
  2. Each bridge call runs in its own run's request scope. A CLI client grant now records the Gateway request scope it was minted in (mintMcpLoopbackClientGrant, called while the run's request is active), and the handler re-enters that scope for the grant's tool calls. That is what in-process runtimes already get implicitly, so dispatch sees the calling run's own client: its scopes stay the ceiling, and its hasCurrentClientAuthority liveness still applies.

Part 1 alone would have removed the accidental ceiling without restoring the intended one. With no scope, a write-only recovery run and a revoked run both completed an admin-only call in live testing. Part 2 is why those runs are still refused (see the proof below).

Evidence

Real behavior proof

Setup. This PR's branch at 3ff6fbe1d78, built, running as an isolated foreground Gateway (openclaw --profile <test> gateway run, loopback, its own state dir, clean environment). macOS arm64, Node v26.8.2, OpenClaw 2026.9.6 (3ff6fbe). Agent main runs claude-cli/claude-sonnet-5. Owner turns come from openclaw agent --agent main on a local CLI device paired with operator.admin (senderIsOwner: true). The admin-only action is the secrets tool with action: "list" (secrets.store.list, needs operator.admin). Heartbeat, Bonjour, and dreaming are off, so no other system run can start the bridge first.

Steps:

  1. step0: owner turn on a fresh Gateway calls secrets list.
  2. step0b: a second owner turn in the same process.
  3. step1: an owner turn runs a 90 s probe script, then calls secrets list. Mid-probe the Gateway is restarted (gateway restart --wait 5s). The drain runs out, the turn is marked for recovery, and the restart-recovery continuation (a write-only system caller) is the first CLI run after startup, so it starts the bridge. It then calls secrets list itself.
  4. step2: after recovery settles, a new owner turn calls secrets list.
  5. step3 (fresh Gateway process): an owner turn runs the probe, and 5 s in the owner device's operator token is revoked (devices revoke --role operator, connection closed 4001 device removed). After the probe, the run calls secrets list.

Results are the exact tool results the agent received, from the Claude Code stream in the Gateway log and chat.history. The "unpatched" column is the same checkout with src/gateway/mcp-http.ts reverted to 6907f58b136 (upstream main) and rebuilt. "Part 1 only" is this PR's first commit, 3b3536613b4.

Step Caller Unpatched main Part 1 only This PR
step0 owner The secret store is empty. The secret store is empty. The secret store is empty.
step0b owner, 2nd turn Gateway client authority closed before dispatching secrets.store.list. The secret store is empty. The secret store is empty.
step1 restart recovery (system, write-only) missing scope: operator.admin The secret store is empty. missing scope: operator.admin
step2 owner, after recovery missing scope: operator.admin The secret store is empty. The secret store is empty.
step3 owner, device revoked mid-run Gateway client authority closed before dispatching secrets.store.list. The secret store is empty. Gateway client authority closed before dispatching secrets.store.list.

On unpatched main, step1 and step3 are refused only because each of those runs happened to start the bridge itself. On this PR they are refused by their own run's scope, whichever run started the listener.

Restart and recovery on this PR (Gateway log, local time, redacted):

17:37:19.641 mcp loopback listening on <loopback>:<port>
17:37:56.086 [gateway] received SIGUSR2; restarting
17:38:01.088 [gateway] restart drain budget 4999.5ms exhausted; cutting short queueSize=1 embeddedRuns=1 activeTasks=1 sessionAdmissions=2 rootRequests=1
17:38:01.129 [main-session-restart-recovery] marked 1 interrupted main session(s) for restart recovery (gateway restart shutdown)
17:38:05.456 mcp loopback listening on <loopback>:<port>
17:38:05.460 [main-session-restart-recovery] started interrupted main session: agent:main:main

secrets tool results on this PR, in order (step0, step0b, recovery, step2):

"tool_result","content":[{"type":"text","text":"The secret store is empty."
"tool_result","content":[{"type":"text","text":"The secret store is empty."
"tool_result","content":"missing scope: operator.admin","is_error":true
"tool_result","content":[{"type":"text","text":"The secret store is empty."

The refused call belongs to the recovery turn: in chat.history it follows the [System] Your previous turn was interrupted by a gateway restart ... continuation message, and step2's owner turn after it succeeds.

step3 on this PR (device revoked mid-run):

17:41:27.494 [gateway] device token revoked device=<device-id> role=operator
17:41:27.495 [ws] → close code=4001 reason=device removed ... lastFrameMethod=agent
17:42:54.300 [agent/cli-backend] cli turn: provider=claude-cli model=claude-sonnet-5 durationMs=102068
"tool_result","content":"Gateway client authority closed before dispatching secrets.store.list.","is_error":true

Differences from the issue's scenario. Owner turns come from the local CLI (openclaw agent, a device with operator.admin), not Control UI webchat. The restart is the supported foreground restart (gateway restart --wait 5s, in-process SIGUSR2 with a 5 s drain), not a LaunchAgent handoff. The admin-only tool is secrets list only.

Tests

  • src/gateway/mcp-http.async-scope.test.ts:
    • "does not retain the Gateway caller of the request that started it": the listener started inside a write-only request scope and a tool-caller identity; a later owner-token call sees neither, and the Gateway context resolver is preserved. Fails before part 1.
    • "runs each CLI grant's tool calls in the request scope that minted it": the listener is started under a write-only recovery scope; grants minted under an owner scope, under the recovery scope, and under no scope each see exactly their own client ([owner, recovery, undefined]). Fails without part 2 ([undefined, undefined, undefined]).
  • pnpm vitest run src/gateway/mcp-http src/gateway/mcp-grant-store src/agents/cli-runner/prepare: 275 of 276 pass. The one failure, mcp-http.keepalive.test.ts › "keeps a GET notification stream alive and releases it during shutdown", fails identically on unmodified origin/main at 6907f58.
  • pnpm check:changed: passes (exit 0).
  • Autoreview (Codex), --mode branch --base origin/main --max-priority P2: scoped-clean, "patch is correct" (0.78). Its sandbox could not read unchanged files or run tests; the tests above ran locally.

@clawsweeper

clawsweeper Bot commented Sep 24, 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 Sep 24, 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I did a careful shell check against current main, and this is already implemented.

This PR’s implementation was incorporated into a formally linked merged PR, and current main fixes the requested behavior with stronger authority coverage.

I found the merged PR that appears to have closed this: #165432: fix(gateway): claude-cli session tools fail after the turn that started the MCP loopback ends.

Root-cause cluster
Relationship: superseded
Canonical: #165432
Summary: The merged canonical PR incorporates this work and completes listener-context isolation.

Members:

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

So I’m closing this as already implemented rather than keeping a duplicate issue open.

Review details

Best possible solution:

Retain the merged implementation and close this absorbed branch.

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

The contributor supplied live before/after reproduction through an isolated Gateway and Claude CLI; current-main source and regression coverage repair that path, and this read-only review ran no code.

Is this the best way to solve the issue?

The merged solution is more complete because it clears all starter-local async stores while retaining Gateway resources and restoring each grant’s own authority.

Security review:

Security review cleared: Recorded live proof and merged HTTP coverage preserve caller ceilings and reject closed or revoked authority before dispatch.

AGENTS.md: found and applied where relevant.

What I checked:

  • Verified merged replacement and formal connection: fix(gateway): claude-cli session tools fail after the turn that started the MCP loopback ends #165432 merged on October 7, explicitly incorporates this PR’s request-scope work, credits Leit-motif, and adapts Grynn’s authority regression. This PR’s GitHub timeline links that PR and references its fixing commit. (fdcbcf5c2ebd)
  • Current-main listener isolation: Listener startup uses the detached async-context owner, retains Gateway worker resources, and explicitly excludes the starter’s request scope. (src/gateway/mcp-http.ts:590, e3604e876c8f)
  • Current-main per-grant scope: Grant minting records the host request scope, and HTTP tool dispatch restores that exact scope rather than the listener starter’s scope. (src/gateway/mcp-grant-store.ts:287, e3604e876c8f)
  • Authority regression coverage: HTTP coverage exercises owner admin dispatch after a write-only starter, rejects the write-only caller, prevents dispatch after caller authority closes, and returns 401 after grant revocation. (src/gateway/mcp-http.async-scope.test.ts:250, e3604e876c8f)
  • Fix provenance: The merged commit contains both original request-scope commit messages, credits Amrit Chana, and explains the subsequent complete detachment and resource-retention repair. (src/gateway/mcp-http.ts:590, fdcbcf5c2ebd)
  • First containing prerelease: The published v2026.10.5-beta.1 release contains the fixing commit: GitHub comparison reports behind_by=0 and that commit as the merge base. Earlier published v2026.9.9 and v2026.10.1-beta.2 retain the older listener startup. (fdcbcf5c2ebd)

Codex review notes: model internal, reasoning medium; reviewed against e3604e876c8f; fix evidence: merged PR #165432, release v2026.10.5-beta.1, commit fdcbcf5c2ebd.

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.
@Leit-motif Leit-motif changed the title fix(gateway): admin tools fail from chat after a restart resumes a CLI-runtime turn fix(gateway): run CLI bridge tool calls in their own run's request scope Sep 24, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@kiranvk-2011

Copy link
Copy Markdown
Contributor

Independent confirmation on a Linux Docker gateway: this branch cherry-picked onto main at 1e9f0d0 (2026.9.6), claude-cli backend, Claude Code 2.1.280, Telegram forum topics that reply through the message tool.

Before, on main without this PR: after a deploy, the first claude-cli turn was a short-lived shell openclaw agent probe. Every later group-topic reply then failed with Gateway client authority closed before dispatching message.action. Five attempts over two user turns, and the user saw "I generated a reply but could not deliver it". A gateway restart cleared it. Same pattern as #158550.

After, with this PR:

  1. Fresh boot, 0 claude-cli turns.
  2. A shell openclaw agent turn runs first and exits, the same poisoning sequence.
  3. A second shell turn asks the model to send to a Telegram forum topic with the message tool. It returns sent, and the channel logs outbound send ok … threadId=35.
  4. authority closed before dispatching log lines: 0.

On current main the branch applies cleanly: tsgo:core is clean, the gateway MCP and in-process-dispatch suites pass 337/337, and oxlint is clean on the changed files.

@Grynn

Grynn commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Confirmed on a systemd Gateway with claude-cli agents, on 2026.9.5 and 2026.9.6:

One more listener gap on current main. #158567 (2026-09-27) added an operator-tool-invocation authority (an AsyncLocalStorage store), and the listener inherits that from its starter too. With this PR rebased onto main (02cf3f0), an owner grant's admin-only call made after a write-only starter still fails with operator tool invocation authority expired. Wrapping the listener start in runOutsideOperatorToolGatewayAuthority fixes it.

Our regression test for this is in the patch below, on top of this PR rebased onto main. It checks three things:

  • the owner grant's admin dispatch succeeds;
  • the write-only grant is refused with missing scope: operator.admin;
  • once the owner's client authority closes, the grant is refused with Gateway client authority closed ..., and after revocation it gets 401.

It fails on main and on this PR alone, and passes with the one-line exit added. The suite passes 6/6.

Patch: operator-authority exit + regression test (on top of this PR rebased onto main)
diff --git a/src/gateway/mcp-http.async-scope.test.ts b/src/gateway/mcp-http.async-scope.test.ts
index 1ecc5194980..3e65ea7ac82 100644
--- a/src/gateway/mcp-http.async-scope.test.ts
+++ b/src/gateway/mcp-http.async-scope.test.ts
@@ -18,6 +18,17 @@ import {
   tryBeginGatewayRootWorkAdmission,
 } from "../process/gateway-work-admission.js";
 import { AsyncWorkScope, getAsyncWorkSignal, trackAsyncWork } from "../shared/async-work-scope.js";
+import {
+  activateMcpLoopbackClientGrantCapture,
+  mintMcpLoopbackClientGrant,
+  revokeMcpLoopbackClientGrant,
+} from "./mcp-grant-store.js";
+import { createGatewayMethodRegistry } from "./methods/registry.js";
+import { createDirectChatContext } from "./server-chat.agent-events.test-helpers.js";
+import type { GatewayRequestHandlerOptions } from "./server-methods/types.js";
+import { withOperatorToolGatewayAuthority } from "./server-plugin-in-process-authority.js";
+import { dispatchGatewayMethodInProcessRaw } from "./server-plugin-in-process-dispatch.js";
+import { createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client.js";
 
 const { execute, resolveTools } = vi.hoisted(() => ({ execute: vi.fn(), resolveTools: vi.fn() }));
 vi.mock("../config/io.js", () => {
@@ -29,16 +40,13 @@ vi.mock("../agents/agent-tools.before-tool-call.js", () => ({
 }));
 vi.mock("./tool-resolution.js", () => ({ resolveGatewayScopedTools: resolveTools }));
 
-import {
-  activateMcpLoopbackClientGrantCapture,
-  mintMcpLoopbackClientGrant,
-} from "./mcp-grant-store.js";
 import { closeMcpLoopbackServer, ensureMcpLoopbackServer } from "./mcp-http.js";
 import { getActiveMcpLoopbackRuntime } from "./mcp-http.loopback-runtime.js";
 
 const completed = { content: [{ type: "text", text: "tracked tool completed" }] };
 const executionScopes: Array<AbortSignal | undefined> = [];
 const constructionScopes: Array<AbortSignal | undefined> = [];
+const admissions: PreparedAgentRunAdmission[] = [];
 
 beforeEach(() => {
   executionScopes.length = 0;
@@ -67,8 +75,6 @@ beforeEach(() => {
   });
 });
 
-const admissions: PreparedAgentRunAdmission[] = [];
-
 afterEach(async () => {
   await closeMcpLoopbackServer();
   for (const admission of admissions.splice(0)) {
@@ -114,7 +120,136 @@ async function startFromCaller() {
   }
 }
 
+async function callBoundTool(token: string, captureKey: string) {
+  const runtime = getActiveMcpLoopbackRuntime();
+  if (!runtime) {
+    throw new Error("MCP runtime missing");
+  }
+  const response = await fetch(`http://127.0.0.1:${runtime.port}/mcp`, {
+    method: "POST",
+    headers: {
+      authorization: `Bearer ${token}`,
+      "content-type": "application/json",
+      "x-openclaw-cli-capture-key": captureKey,
+    },
+    body: JSON.stringify({
+      jsonrpc: "2.0",
+      id: 1,
+      method: "tools/call",
+      params: { name: "scope_probe", arguments: {} },
+    }),
+  });
+  return { status: response.status, body: await response.json() };
+}
+
 describe("MCP HTTP work ownership", () => {
+  it("uses each admitted CLI run's scope for an admin dispatch after a write-only starter", async () => {
+    const adminDispatch = vi.fn(({ respond }: GatewayRequestHandlerOptions) => {
+      respond(true, { allowed: true });
+    });
+    const registry = createGatewayMethodRegistry([
+      {
+        name: "scope.probe",
+        owner: { kind: "core", area: "scope-proof" },
+        scope: "operator.admin",
+        handler: adminDispatch,
+      },
+    ]);
+    const context = createDirectChatContext({
+      getRuntimeConfig: () => ({}),
+      getGatewayMethodRegistry: () => registry,
+    });
+    const scopeFor = (
+      client: ReturnType<typeof createSyntheticPluginRuntimeClient>,
+      isCurrent: () => boolean,
+    ) => ({
+      client,
+      isWebchatConnect: () => false,
+      resolveGatewayContext: () => context,
+      hasCurrentClientAuthority: isCurrent,
+    });
+    const writeOnly = createSyntheticPluginRuntimeClient({ scopes: ["operator.write"] });
+    const admin = createSyntheticPluginRuntimeClient({ scopes: ["operator.admin"] });
+    let ownerCurrent = true;
+    execute.mockImplementation(async () => {
+      const result = await dispatchGatewayMethodInProcessRaw(
+        "scope.probe",
+        {},
+        {
+          resolveGatewayContext: () => context,
+        },
+      );
+      return {
+        content: [{ type: "text", text: result.ok ? "admin-dispatched" : result.error?.message }],
+      };
+    });
+    await withPluginRuntimeGatewayRequestScope(
+      scopeFor(writeOnly, () => true),
+      () =>
+        withOperatorToolGatewayAuthority({ scopes: ["operator.write"] }, () =>
+          ensureMcpLoopbackServer(),
+        ),
+    );
+    const runtime = getActiveMcpLoopbackRuntime();
+    if (!runtime) {
+      throw new Error("MCP runtime missing");
+    }
+    const admit = async (runId: string, client: typeof admin, isCurrent: () => boolean) => {
+      const admission = prepareAgentRunAdmission({
+        cfg: {},
+        facts: {
+          runId,
+          agentId: "main",
+          ingress: { kind: "system", boundary: "mcp-scope-proof", state: "present" },
+        },
+        operationalRunInstance: createOperationalRunInstanceRef(runId),
+      });
+      admissions.push(admission);
+      const admittedRunContext = await admission.admit("gateway", `gateway-${runId}`);
+      const grant = withPluginRuntimeGatewayRequestScope(scopeFor(client, isCurrent), () =>
+        mintMcpLoopbackClientGrant({
+          context: { sessionKey: "agent:main:scope-proof", senderIsOwner: true },
+          runtimeOwnerToken: runtime.ownerToken,
+          admittedRunContext,
+        }),
+      );
+      const captureKey = `capture-${runId}`;
+      expect(
+        activateMcpLoopbackClientGrantCapture({
+          token: grant.token,
+          runtimeOwnerToken: runtime.ownerToken,
+          captureKey,
+        }),
+      ).toBeTruthy();
+      return { token: grant.token, captureKey };
+    };
+    const ownerGrant = await admit("mcp-owner", admin, () => ownerCurrent);
+    const recoveryGrant = await admit("mcp-recovery", writeOnly, () => true);
+
+    expect(await callBoundTool(ownerGrant.token, ownerGrant.captureKey)).toMatchObject({
+      status: 200,
+      body: { result: { content: [{ text: "admin-dispatched" }], isError: false } },
+    });
+    expect(await callBoundTool(recoveryGrant.token, recoveryGrant.captureKey)).toMatchObject({
+      status: 200,
+      body: { result: { content: [{ text: "missing scope: operator.admin" }], isError: false } },
+    });
+    expect(adminDispatch).toHaveBeenCalledTimes(1);
+
+    ownerCurrent = false;
+    expect(await callBoundTool(ownerGrant.token, ownerGrant.captureKey)).toMatchObject({
+      status: 200,
+      body: {
+        result: {
+          content: [{ text: "Gateway client authority closed before dispatching scope.probe." }],
+        },
+      },
+    });
+    expect(adminDispatch).toHaveBeenCalledTimes(1);
+    expect(revokeMcpLoopbackClientGrant(ownerGrant.token)).toBe(true);
+    expect((await callBoundTool(ownerGrant.token, ownerGrant.captureKey)).status).toBe(401);
+  });
+
   it.each([false, true])(
     "serves fresh request scopes after its creator closes (replacement=%s)",
     async (replace) => {
diff --git a/src/gateway/mcp-http.ts b/src/gateway/mcp-http.ts
index 27cd85a8840..7f9b21d9978 100644
--- a/src/gateway/mcp-http.ts
+++ b/src/gateway/mcp-http.ts
@@ -58,6 +58,7 @@ import {
   resolveMcpRequestContext,
   validateMcpLoopbackRequest,
 } from "./mcp-http.request.js";
+import { runOutsideOperatorToolGatewayAuthority } from "./operator-tool-gateway-authority.js";
 
 // Loopback MCP server exposes gateway-scoped tools to local MCP clients over a
 // bearer-token HTTP endpoint bound to 127.0.0.1. Only one active server/runtime
@@ -571,16 +572,18 @@ export async function ensureMcpLoopbackServer(port = 0): Promise<void> {
     // restart-recovery run would otherwise cap every later turn's bridge calls.
     const work = new AsyncWorkScope();
     const resolveGatewayContext = getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
-    activeMcpLoopbackServerPromise = withoutGatewayToolCallerIdentity(() =>
-      withPluginRuntimeGatewayContextResolver(
-        resolveGatewayContext,
-        () =>
-          runOutsidePluginRuntimeGenerationScope(() =>
-            runOutsideGatewayRootWorkAdmission(() =>
-              work.run(() => startMcpLoopbackServer(port, work)),
+    activeMcpLoopbackServerPromise = runOutsideOperatorToolGatewayAuthority(() =>
+      withoutGatewayToolCallerIdentity(() =>
+        withPluginRuntimeGatewayContextResolver(
+          resolveGatewayContext,
+          () =>
+            runOutsidePluginRuntimeGenerationScope(() =>
+              runOutsideGatewayRootWorkAdmission(() =>
+                work.run(() => startMcpLoopbackServer(port, work)),
+              ),
             ),
-          ),
-        { inheritRequestScope: false },
+          { inheritRequestScope: false },
+        ),
       ),
     )
       .then((close) => {

The listener also inherits its starter's Cron creator authority store. A runId check stops it from being used today, but it could be exited in the same place.

@bitfroest

Copy link
Copy Markdown
Contributor

Another affected deployment, with one more way to trigger it that is easy to hit by accident.

Setup: OpenClaw 2026.9.6 (eb377ac), Linux, npm global install, gateway as a systemd user unit, claude-cli runtime (Claude Opus), Telegram + Discord + Signal, replies delivered through the message tool.

Trigger here: after a gateway restart, the first CLI turn was not a user message but a short-lived openclaw gateway call sessions.send from a local watchdog script (it nudges the main session after restarts). That client exited immediately. From then on:

  • every message.action from the main session failed with Gateway client authority closed before dispatching message.action.;
  • a subagent spawned in that window had no working message tool either, and admin-only bridge tools answered missing scope: operator.admin;
  • openclaw message send from a shell kept working (its own client), which made it look like a per-session problem at first.

Impact: about one hour (one morning, 08:16–09:12 local) in which the agent produced answers and could not deliver any of them to Telegram. Only a gateway restart cleared it.

Two things that may be useful for review:

  1. The poisoning client does not need to be an openclaw agent probe or a cron run — any RPC that causes the first CLI turn (here sessions.send) starts the loopback listener inside its own request scope. Post-restart nudges, health checks and monitoring hooks are exactly the things operators add after an incident, so this regresses hardest for people who already had one.
  2. Our current mitigation is purely procedural (never let a short-lived client cause the first turn after a start). It holds, but it is fragile, and it is the reason we are holding back upgrades: neither 2026.9.7 nor 2026.9.8 contains this fix.

If it helps to get this merged: we can cherry-pick this branch onto 2026.9.6, replay the exact sequence (fresh start → sessions.send from an exiting client → message-tool send to Telegram → admin-only bridge call from the owner session) and post the before/after journal lines, including the operator-tool-invocation-authority case @Grynn describes.

@clawsweeper clawsweeper Bot added the rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. label Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Oct 13, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@vincentkoc

Copy link
Copy Markdown
Member

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

This implementation was incorporated into #165432 (fdcbcf5c2ebd). Current main starts the shared MCP listener outside the starter’s request context, restores each grant’s own request scope, and retains Gateway resources. HTTP regressions cover owner access, the write-only ceiling, closed callers, and revoked grants.

Thanks @Leit-motif (Amrit Chana) for the fix and proof, and @Grynn for the authority regression. Closing this absorbed branch unmerged. The release-pinned follow-up, separate Cron-management report, and cross-agent authority report in #185303 are outside this closeout. Please reopen with current-main reproduction details if this specific caller-scope leak persists.

@vincentkoc vincentkoc closed this Oct 28, 2026
obviyus added a commit that referenced this pull request Oct 29, 2026
…tomations (#162237)

Related: #147614, #157126, #157144

## What Problem This Solves

Fixes: admitted owners using CLI-backed agents cannot see or manage existing ownerless automations because the later MCP request constructs the tool outside the owner's automation-management scope.

## User Impact

Authorized owners regain Gateway-wide list/get/update of existing automations through CLI MCP. Removing owner membership or revoking the grant still denies access, and later callers without management authority remain caller-scoped. Ownerless jobs remain ownerless. No configuration or stored-data migration is required.

## Why This Change Was Made

Automation tools bind management authority when constructed, before their later execution. The host-only CLI grant now retains the exact live construction scope, and tool resolution enters it under the admitted caller identity and stored request scope. The construction identity deliberately omits execution's requester-grant issuer. Actual execution retains the existing one-use, method-bound grant and final-effect checks.

The retained callback rechecks the exact grant row, active run, abort/currentness and current channel-owner membership. Stale scope exits any ambient management scope rather than inheriting it. The implementation builds on current requester-origin and detached-listener ownership; it does not restore superseded listener or ambient-authority code.


## Evidence

- **Live Claude CLI proof:** new QA scenario `cron-claude-cli-owner-management` (live-frontier, `claude-cli/claude-sonnet-4-6`, subscription auth). A configured channel owner asks the Claude CLI agent to `get` and then disable an automation owned by another account. On this branch the agent replies with the success marker; the job is disabled and keeps its original owner. With the four source files reverted to `main`, the same live turn fails with `cron job not found: <id> ... For cross-session management, use a fresh authenticated configured channel owner ...`, which is the production report in #186696.
- **Production:** on 2026.10.8, a configured channel owner on a `claude-cli` agent got `cron job not found` for a job owned by the same conversation, with no `cron: admin management` log line; the same owner on the embedded runtime is granted management.
- **Real boundary regression:** `src/gateway/server-methods/mcp-cron-management.integration.test.ts` drives the actual detached loopback HTTP MCP listener, production tool resolution and isolated durable Cron persistence. On the unchanged owner it fails with `expected 'caller' to be 'gateway'`; with this repair it lists, reads and updates the ownerless job without assigning an owner.
- The same scenario then removes the configured owner and observes update refusal; revokes the grant and observes HTTP401; starts a later unentitled run on the same listener and observes caller scope with no access to the job. The only mocked boundary is unrelated attached-node inventory.
- **Construction/execution separation:** a real HTTP regression proves the admitted identity cannot mint a requester grant during construction, while execution can mint and redeem its one-use grant. It failed before the construction identity was narrowed and passes afterward.
- Final affected command: `OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts src/gateway/server-methods/mcp-cron-management.integration.test.ts src/agents/tools/cron-tool.management.test.ts --maxWorkers=1`: **21/21 pass** (7 HTTP-scope, 1 durable Cron integration, 13 management controls). Wrapper wall **65.13s**, including compiler/bootstrap work; the integrated owner scenario took **6.772s**. These are test costs, not production-latency benchmarks.
- Earlier broader affected runs cover **85 distinct tests across the runs**, including grant-store, grant construction, authority and requester-continuation consumers. Core/gateway test types, touched type-aware lint, formatting, scoped line-cap and diff checks pass.
- Simplification keeps the existing grant row and Cron authority owner; no second authority registry, wire credential, database schema or permission option is added. Construction and execution share one identity builder with an explicit phase. Necessary patch growth is the retained host callback and separate real authority/revocation regressions.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 30, 2026
…tomations (openclaw#162237)

Related: openclaw#147614, openclaw#157126, openclaw#157144

## What Problem This Solves

Fixes: admitted owners using CLI-backed agents cannot see or manage existing ownerless automations because the later MCP request constructs the tool outside the owner's automation-management scope.

## User Impact

Authorized owners regain Gateway-wide list/get/update of existing automations through CLI MCP. Removing owner membership or revoking the grant still denies access, and later callers without management authority remain caller-scoped. Ownerless jobs remain ownerless. No configuration or stored-data migration is required.

## Why This Change Was Made

Automation tools bind management authority when constructed, before their later execution. The host-only CLI grant now retains the exact live construction scope, and tool resolution enters it under the admitted caller identity and stored request scope. The construction identity deliberately omits execution's requester-grant issuer. Actual execution retains the existing one-use, method-bound grant and final-effect checks.

The retained callback rechecks the exact grant row, active run, abort/currentness and current channel-owner membership. Stale scope exits any ambient management scope rather than inheriting it. The implementation builds on current requester-origin and detached-listener ownership; it does not restore superseded listener or ambient-authority code.


## Evidence

- **Live Claude CLI proof:** new QA scenario `cron-claude-cli-owner-management` (live-frontier, `claude-cli/claude-sonnet-4-6`, subscription auth). A configured channel owner asks the Claude CLI agent to `get` and then disable an automation owned by another account. On this branch the agent replies with the success marker; the job is disabled and keeps its original owner. With the four source files reverted to `main`, the same live turn fails with `cron job not found: <id> ... For cross-session management, use a fresh authenticated configured channel owner ...`, which is the production report in openclaw#186696.
- **Production:** on 2026.10.8, a configured channel owner on a `claude-cli` agent got `cron job not found` for a job owned by the same conversation, with no `cron: admin management` log line; the same owner on the embedded runtime is granted management.
- **Real boundary regression:** `src/gateway/server-methods/mcp-cron-management.integration.test.ts` drives the actual detached loopback HTTP MCP listener, production tool resolution and isolated durable Cron persistence. On the unchanged owner it fails with `expected 'caller' to be 'gateway'`; with this repair it lists, reads and updates the ownerless job without assigning an owner.
- The same scenario then removes the configured owner and observes update refusal; revokes the grant and observes HTTP401; starts a later unentitled run on the same listener and observes caller scope with no access to the job. The only mocked boundary is unrelated attached-node inventory.
- **Construction/execution separation:** a real HTTP regression proves the admitted identity cannot mint a requester grant during construction, while execution can mint and redeem its one-use grant. It failed before the construction identity was narrowed and passes afterward.
- Final affected command: `OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts src/gateway/server-methods/mcp-cron-management.integration.test.ts src/agents/tools/cron-tool.management.test.ts --maxWorkers=1`: **21/21 pass** (7 HTTP-scope, 1 durable Cron integration, 13 management controls). Wrapper wall **65.13s**, including compiler/bootstrap work; the integrated owner scenario took **6.772s**. These are test costs, not production-latency benchmarks.
- Earlier broader affected runs cover **85 distinct tests across the runs**, including grant-store, grant construction, authority and requester-continuation consumers. Core/gateway test types, touched type-aware lint, formatting, scoped line-cap and diff checks pass.
- Simplification keeps the existing grant row and Cron authority owner; no second authority registry, wire credential, database schema or permission option is added. Construction and execution share one identity builder with an explicit phase. Necessary patch growth is the retained host callback and separate real authority/revocation regressions.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S stale Marked as stale due to inactivity

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

6 participants