Skip to content

fix #174272: carry upstream MCP server instructions through the loopback bridge - #174396

Closed
wangjx-xydt wants to merge 2 commits into
openclaw:mainfrom
wangjx-xydt:feat/issue-174272
Closed

wangjx-xydt wants to merge 2 commits into
openclaw:mainfrom
wangjx-xydt:feat/issue-174272

Conversation

@wangjx-xydt

Copy link
Copy Markdown
Contributor

Summary

  • Problem: MCP server instructions (the InitializeResult.instructions usage guidance) never reaches agents served through the OpenClaw loopback MCP bridge: the client runtime never reads the field from upstream servers, and the bridge's initialize reply has no instructions — so bridged agents silently lose server-level guidance that directly connected agents receive (issue [Bug]: MCP server instructions are dropped for agents using the loopback MCP bridge #174272).
  • Solution: the bundle MCP runtime now captures client.getInstructions() into the session catalog (sanitized like other untrusted MCP metadata), and the loopback bridge aggregates catalog instructions into its initialize reply, labeled per server, only for servers that still serve at least one tool under the effective policy.
  • What changed: src/agents/agent-bundle-mcp-types.ts, src/agents/agent-bundle-mcp-runtime.ts, src/gateway/mcp-http.ts, src/gateway/mcp-http.handlers.ts, plus new src/gateway/mcp-http.instructions.ts and tests.
  • What did NOT change: tool listing/calling behavior, protocol versions, and policy semantics are unchanged; a cold catalog (runtime not yet warm) simply omits instructions from that one handshake instead of triggering connections or tools/list from the HTTP handler; servers whose tools are fully denied contribute nothing; instructions text is scrubbed by the existing sanitizeMcpMetadataText (prompt-injection patterns redacted, length cap shared with other MCP metadata).
  • Data-model compatibility: the session catalog gains an optional in-memory field; nothing is persisted.

Fixes #174272

Real behavior proof

  • Behavior or issue addressed: Bridged agents received upstream MCP tools but not the servers' instructions, so server-level usage rules (ranking, quota, safety) silently diverged between bridged and direct connections.
  • Real environment tested: feat/issue-174272 worktree on current main (25d31d0), Node v24.20.0. A real streamable-http MCP server (in-process node:http fixture returning a multi-paragraph instructions string) handshake with the real session MCP runtime, plus the real loopback initialize handler and the real aggregation helper against policy-filtered tool lists.
  • Exact steps or command run after this patch:
    npx vitest run src/agents/agent-bundle-mcp-instructions.test.ts src/gateway/mcp-http.instructions.test.ts src/gateway/mcp-http.handlers.initialize.test.ts
  • Evidence after fix:
    ✓ session MCP runtime server instructions > carries sanitized upstream instructions into the catalog
      catalog.servers.legal.instructions = "Always cite authority levels when ranking results.\n\n[redacted MCP metadata instruction]."
      (the fixture's "Ignore all previous instructions." tail was scrubbed by the existing sanitizer)
    ✓ resolveMcpLoopbackInstructions > aggregates instructions from servers that still serve tools
      → "[legal]\nCite authority levels.\n\n[search]\nPrefer recent sources."
    ✓ resolveMcpLoopbackInstructions > omits servers whose tools are fully filtered out of the served list
    ✓ mcp loopback initialize > carries aggregated upstream server instructions when present
      → initialize result now includes instructions; omitted when nothing contributes
    Test Files 3 passed (3), Tests 6 passed (6)
    
    The session MCP runtime stdio variant of the catalog test could not run on this machine (its process-ownership admission blocks child spawning for every such test, including pre-existing ones on pristine main); the streamable-http path above exercises the same loadCatalog capture code.
  • Observed result after fix: the loopback bridge initialize reply now carries aggregated, per-server-labeled, sanitized upstream instructions, so bridged agents receive the same server-level guidance as directly connected agents.
  • What was not tested: no live prompt-level comparison against a directly connected CLI backend (the issue's end-user surface); no cold-catalog race timing beyond asserting the handshake degrades to omission; stdio transport cataloging is environment-blocked locally and covered here through the streamable-http path.

Regression Test Plan

  • Coverage level: Unit test
  • Target test file: src/gateway/mcp-http.instructions.test.ts, src/gateway/mcp-http.handlers.initialize.test.ts, src/agents/agent-bundle-mcp-instructions.test.ts
  • Scenario locked in: catalog entries carry sanitized upstream instructions; the bridge aggregates them per server, skips fully filtered-out servers, and omits the field when nothing contributes.
  • Why this is the smallest reliable guardrail: the fix is two field hand-offs (client capture, bridge reply) joined by one aggregation rule; the three tests pin each hand-off and the policy filter independently.

Root Cause

  • Root cause: loadCatalog read getServerCapabilities()/getServerVersion() from the upstream initialize result but never getInstructions(), and the loopback initialize handler never emitted an instructions field.
  • Missing detection / guardrail: no test pinned the instructions field on either the catalog or the loopback initialize reply, so the field was dropped silently at both boundaries.

Agents served through the loopback MCP bridge received upstream tools but
not the servers' instructions from the initialize result, so server-level
usage guidance silently diverged from direct connections. Capture the
sanitized instructions into the session catalog when connecting upstream,
and aggregate them per server into the loopback initialize reply for
servers that still serve at least one tool under the effective policy.

Fixes openclaw#174272
@clawsweeper

clawsweeper Bot commented Oct 16, 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 agents Agent runtime and tooling size: M labels Oct 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR captures upstream MCP instructions in the runtime catalog and adds policy-filtered aggregation to loopback initialization replies.

Example: The supplied helper tests provide a legal server with instructions saying “Cite authority levels.”

  • Before: The initialization handler omits instructions.
  • After: The handler can return “[legal]\nCite authority levels.” when supplied aggregated instructions.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful catalog groundwork remains disconnected from the confirmed user flow, and the new mock violates an enforced guard.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: No · Fix scope: Partial
User problem: Embedded agents receive MCP tools but lose the servers' cross-tool usage guidance.
Reason: As submitted, the bridge work has no demonstrated affected upstream consumer; the catalog capture is useful groundwork for the confirmed embedded bug.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open for correction: catalog capture is useful, but the loopback change misses the confirmed embedded-runtime failure and a new mock violates the CI ratchet.

Priority: P2
Reviewed head: c4104df7e0a1f7814f1a2f53a28dc5719afae577

Before merge

  • Add real behavior proof - The supplied Vitest output exercises real upstream HTTP catalog loading plus isolated aggregation and initialization handlers, but no shipped agent flow demonstrates instructions reaching a model; provide redacted terminal output or logs for the corrected embedded flow and a fully denied server, removing credentials, IPs, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Deliver instructions through the affected embedded consumer (P2) - For a configured MCP server such as the reporter's guided server, the confirmed failure is an embedded model request that contains lookup's description but omits SERVER-INSTRUCTIONS-MARKER. This collector only feeds loopback initialization: production loopback resolution builds Gateway tools rather than these catalog tools, and CLI configuration already connects configured servers natively. Embedded materialization and prompt preparation never consume the new catalog field, so that input still loses its instructions after this patch. Retain the catalog capture and wire it into the existing embedded prompt owner after effective tool filtering, removing the unsupported bridge path unless a supported consumer is demonstrated.
  • Make the new manager mock satisfy the export ratchet (P2) - This new first-party vi.mock factory returns only peekSessionMcpRuntime and has neither real-module passthrough nor an adjacent mock-isolation explanation. scripts/check-test-mock-exports.mts rejects new factories with exactly that shape, and this file has no grandfathered baseline entry, so the patch introduces a deterministic guard failure. Preserve the module exports or document the concrete state-isolation reason using the supported annotation; do not expand the baseline.
  • Product: not worth merging - As submitted, the bridge work has no demonstrated affected upstream consumer; the catalog capture is useful groundwork for the confirmed embedded bug.

Findings

  • [P2] Deliver instructions through the affected embedded consumer — src/gateway/mcp-http.instructions.ts:25-29
  • [P2] Make the new manager mock satisfy the export ratchet — src/gateway/mcp-http.instructions.test.ts:7-9

Provenance

  • Loopback initialization: original intent not found (25b069a: Extract loopback transport helpers; inspected history identifies no intentional instruction-suppression policy, and the original omission's introduction remains unknown.)

Tests

  • Missing end-to-end proof: No shipped embedded-agent request capture or base-fail/head-pass regression shows instructions reaching the model for allowed servers while excluding fully denied servers.
Agent review details

How this fits together

Configured MCP servers connect natively to CLI backends, while embedded agents consume OpenClaw's MCP catalog; the loopback bridge separately exposes Gateway tools.

flowchart TD
  A[Configured MCP server] --> B[Native CLI MCP configuration]
  B --> C[CLI agent]
  A --> D[OpenClaw MCP catalog]
  D --> E[Embedded tool assembly]
  E --> F[Embedded model request]
  G[Gateway tools] --> H[Loopback MCP bridge]
Loading

Technical review

Best possible solution:

Retain catalog capture and deliver policy-filtered server guidance through the existing embedded prompt owner.

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

Source confirms the catalog omission and unchanged embedded consumer; the reporter's official-release request capture supports that failure, while their correction disproves the stated Claude loopback route.

Is this the best way to solve the issue?

Capturing instructions at the catalog owner is sound, but forwarding them through loopback does not reach the reproduced embedded model request.

Full review comments:

  • [P2] Deliver instructions through the affected embedded consumer — src/gateway/mcp-http.instructions.ts:25-29
    For a configured MCP server such as the reporter's guided server, the confirmed failure is an embedded model request that contains lookup's description but omits SERVER-INSTRUCTIONS-MARKER. This collector only feeds loopback initialization: production loopback resolution builds Gateway tools rather than these catalog tools, and CLI configuration already connects configured servers natively. Embedded materialization and prompt preparation never consume the new catalog field, so that input still loses its instructions after this patch. Retain the catalog capture and wire it into the existing embedded prompt owner after effective tool filtering, removing the unsupported bridge path unless a supported consumer is demonstrated.
    Confidence: 0.99
  • [P2] Make the new manager mock satisfy the export ratchet — src/gateway/mcp-http.instructions.test.ts:7-9
    This new first-party vi.mock factory returns only peekSessionMcpRuntime and has neither real-module passthrough nor an adjacent mock-isolation explanation. scripts/check-test-mock-exports.mts rejects new factories with exactly that shape, and this file has no grandfathered baseline entry, so the patch introduces a deterministic guard failure. Preserve the module exports or document the concrete state-isolation reason using the supported annotation; do not expand the baseline.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Per-server catalog ownership keeps the original intent (89c1a09: Preserve healthy transports and catalogs across MCP configuration reloads.)
  • Catalog metadata projection keeps the original intent (6046d4f: Support MCP Apps across conversations and workspace files through the existing runtime and metadata owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/agent-bundle-mcp-instructions.test.ts src/agents/agent-bundle-mcp-runtime.test.ts src/agents/agent-bundle-mcp-tools.materialize.test.ts src/agents/embedded-agent-runner/run/attempt-system-prompt.test.ts --maxWorkers=1
  • pnpm check:test-mock-exports
  • pnpm check:changed
  • git diff --check
  • Verify a regression fails before the repair and passes afterward for allowed and fully denied MCP servers.

What I checked:

Likely related people:

  • Vincent Koc: Raw commit c037ab5 adds src/agents/agent-bundle-mcp-types.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c037ab5c7480; files: src/agents/agent-bundle-mcp-types.ts)

PR surface

Source +60, Tests +221. Total +281 across 8 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 5 61 1 +60
Tests 3 221 0 +221
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 282 1 +281

Review metrics

Metric Value Why it matters
Production versus test LOC Production +61/-1; tests +221/-0 The HTTP fixture supports catalog capture, but the separate helper and handler suites do not establish delivery through the affected embedded consumer.

Root-cause cluster

Relationship: partial_overlap
Canonical: #174336
Summary: The canonical issue establishes embedded instruction loss; this PR captures the missing field but targets the withdrawn bridge premise.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: MCP tools remain usable, but the confirmed embedded path silently loses server-wide usage guidance and needs a focused repair.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 16, 2026, 12:26 PM ET / 16:26 UTC.

…tructions coverage

Import SessionMcpRuntime from the types barrel, brace the server.listen
promise executor, and spread the original module in the manager-api mock.
roboclaw-bot added a commit to Marvinthebored/openclaw that referenced this pull request Oct 20, 2026
Managed Claude turns used to connect configured MCP servers natively and
received each server's initialize instructions. The bridge kept the tools
but dropped the instructions. Capture them in the session MCP catalog and
return them from the loopback initialize reply, ordered by server name,
for servers that still have a listed tool. Catalog capture follows the
approach proposed in openclaw#174396.

Co-authored-by: VACInc <[email protected]>
VACInc added a commit that referenced this pull request Oct 20, 2026
)

* fix(claude-cli): stop cache-prefix churn after child completion

Ordinary local claude-cli turns now use the same exact OpenClaw-mediated
tool projection as verified child completions, so a completion no longer
swaps the tools-first cached prefix of a running native session.

Co-authored-by: VACInc <[email protected]>

* test(claude-cli): expect the mediated surface on ordinary turns

Co-authored-by: VACInc <[email protected]>

* test(claude-cli): select native tools in the workspace-only override case

Managed Claude turns are mediated by default, so the agent workspace-only override is
covered on the explicit native-selection path that still exposes native file tools.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): serve configured MCP servers through the loopback bridge

Exclusive CLI runs omit native MCP servers because the CLI would call them
outside OpenClaw's per-turn caps. Managed local Claude turns are now all
exclusive, so configured mcp.servers disappeared from ordinary turns.

Materialize the session's configured MCP tools for the run and serve them
through the loopback grant. They pass the same Gateway policy pipeline and
exact grant allowlist as other tools, so ordinary and completion turns list
one catalog while each turn's cap still decides what is listed and callable.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): ignore request echoes when checking for orphaned tool calls

Claude Code logs api-request-blob records that repeat already answered
tool calls under role=assistant. Counting them made a finished turn look
orphaned until the final reply was written, so a completion that resumed
the parent right after a spawn reset its native session. Only user and
assistant conversation records now count.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): keep skill_workshop stable on internal turns

Only human turns receive personal-library authoring, so completion and
other internal turns published a different skill_workshop definition and
broke the native prompt cache for profiled users. Since #176587 this also
affects token-authenticated clients.

CLI turns without authoring now reuse the session's last human shape with
an expired grant, as goal continuation already does. The definition stays
identical and every call, including Workshop calls through the
workspace-default wrapper, is refused, so no sandboxed internal turn gains
Workshop access.

Co-authored-by: VACInc <[email protected]>

* fix(skill-workshop): keep workspace Workshop on internal CLI turns

The stable skill_workshop shape for internal turns refused every call,
including workspace Workshop calls that an unsandboxed no-grant turn may
make on main. Pass the run's sandbox state to the workspace-default
wrapper so the expired grant refuses only personal-library calls and
sandboxed workspace calls.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): recheck loopback grant at configured-server I/O

The loopback handler checked grant and completion lineage before
executing a tool, but a configured MCP tool could still reach its server
after that check, for example after waiting for a session reconnection.
Carry the caller's check into MCP tools/call so it runs immediately
before server I/O.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): serve configured server instructions through the loopback

Managed Claude turns used to connect configured MCP servers natively and
received each server's initialize instructions. The bridge kept the tools
but dropped the instructions. Capture them in the session MCP catalog and
return them from the loopback initialize reply, ordered by server name,
for servers that still have a listed tool. Catalog capture follows the
approach proposed in #174396.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): guard every bridged request and serve server instructions whole

Resource reads, prompt fetches and paginated lists now recheck the loopback
caller's grant and completion lineage at the request boundary, as tool calls
already did. Configured server instructions are no longer capped at 1,200
characters. A Gateway loopback test revokes a real grant or reassigns a real
completion lineage during a server-driven catalog refresh.

Co-authored-by: VACInc <[email protected]>

* test(gateway): prove Workshop shape and refusal on completion turns

Through the real loopback, a completion turn after a human turn lists the
same skill_workshop definition, refuses personal-library calls without
reaching the human grant, and keeps unsandboxed workspace calls.

Co-authored-by: VACInc <[email protected]>

* test(gateway): prove sandboxed completions cannot write through Workshop

Sandboxed completion turns, with or without skill_workshop admitted by the
sandbox tool policy, list the same Workshop surface as the human turn and
refuse a workspace create before any file changes. The Gateway authority
file runs in the database-worker project, which owns the main-thread
shared-state broker. Drops the mock-sequenced revocation case now covered
by real grant and lineage owners.

Co-authored-by: VACInc <[email protected]>

* test(cli-runner): drop Workshop helper cases covered by the Gateway suite

Definition parity, personal refusal and workspace access are now proven
through the real loopback; keep session isolation and latest-shape cases.

Co-authored-by: VACInc <[email protected]>

* test(gateway): wait for list_changed delivery instead of sleeping

The probe follows each tools/list_changed with a ping on the same SSE
stream; the client handles stream messages in order, so its ping reply
proves the notification was consumed before the next call.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: VACInc <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
obviyus added a commit that referenced this pull request Oct 20, 2026
)

fix(mcp): give embedded agents the MCP server's instructions, capped per server

MCP servers can publish usage guidance in their initialize result (for example "Before using lookup, always confirm the account name"). Embedded agents received the server's tools but never that guidance. The instructions read by #172026 are now also delivered to embedded agents, alongside the server's tools, in the system prompt, Tool Search and Code Mode, only for servers that still back at least one usable tool. Each server's text is capped at 2,000 characters for embedded prompts (cut at a character boundary with a truncation note), and OpenClaw prompt markers in it are neutralized. Claude CLI loopback delivery keeps the full text, as #172026 intends. This matches how Codex surfaces server instructions as the tool namespace description.

Proof: built Gateway with a stdio MCP server and a recording provider. On main the provider request had the tools but not the instructions (twice). With this change the instructions are present (twice); a server with over 2,000 characters shows the capped prefix with one truncation note; a server without instructions leaves the prompt unchanged; Claude CLI loopback still gets the full text. A live gpt-5.4-mini turn passes.

Supersedes #174425, #174508 and #174396. Thanks @xiaopan-xydt.

Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

Thanks @wangjx-xydt. This fixed the same gap for the Claude CLI loopback bridge, which #172026 has since covered (it serves MCP server instructions whole over loopback), and #174342 (f874f24) now delivers them to embedded agents too. Closing as superseded. Your PR is credited in the #174342 merge.

@obviyus obviyus closed this Oct 20, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
…claw#172026)

* fix(claude-cli): stop cache-prefix churn after child completion

Ordinary local claude-cli turns now use the same exact OpenClaw-mediated
tool projection as verified child completions, so a completion no longer
swaps the tools-first cached prefix of a running native session.

Co-authored-by: VACInc <[email protected]>

* test(claude-cli): expect the mediated surface on ordinary turns

Co-authored-by: VACInc <[email protected]>

* test(claude-cli): select native tools in the workspace-only override case

Managed Claude turns are mediated by default, so the agent workspace-only override is
covered on the explicit native-selection path that still exposes native file tools.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): serve configured MCP servers through the loopback bridge

Exclusive CLI runs omit native MCP servers because the CLI would call them
outside OpenClaw's per-turn caps. Managed local Claude turns are now all
exclusive, so configured mcp.servers disappeared from ordinary turns.

Materialize the session's configured MCP tools for the run and serve them
through the loopback grant. They pass the same Gateway policy pipeline and
exact grant allowlist as other tools, so ordinary and completion turns list
one catalog while each turn's cap still decides what is listed and callable.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): ignore request echoes when checking for orphaned tool calls

Claude Code logs api-request-blob records that repeat already answered
tool calls under role=assistant. Counting them made a finished turn look
orphaned until the final reply was written, so a completion that resumed
the parent right after a spawn reset its native session. Only user and
assistant conversation records now count.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): keep skill_workshop stable on internal turns

Only human turns receive personal-library authoring, so completion and
other internal turns published a different skill_workshop definition and
broke the native prompt cache for profiled users. Since openclaw#176587 this also
affects token-authenticated clients.

CLI turns without authoring now reuse the session's last human shape with
an expired grant, as goal continuation already does. The definition stays
identical and every call, including Workshop calls through the
workspace-default wrapper, is refused, so no sandboxed internal turn gains
Workshop access.

Co-authored-by: VACInc <[email protected]>

* fix(skill-workshop): keep workspace Workshop on internal CLI turns

The stable skill_workshop shape for internal turns refused every call,
including workspace Workshop calls that an unsandboxed no-grant turn may
make on main. Pass the run's sandbox state to the workspace-default
wrapper so the expired grant refuses only personal-library calls and
sandboxed workspace calls.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): recheck loopback grant at configured-server I/O

The loopback handler checked grant and completion lineage before
executing a tool, but a configured MCP tool could still reach its server
after that check, for example after waiting for a session reconnection.
Carry the caller's check into MCP tools/call so it runs immediately
before server I/O.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): serve configured server instructions through the loopback

Managed Claude turns used to connect configured MCP servers natively and
received each server's initialize instructions. The bridge kept the tools
but dropped the instructions. Capture them in the session MCP catalog and
return them from the loopback initialize reply, ordered by server name,
for servers that still have a listed tool. Catalog capture follows the
approach proposed in openclaw#174396.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): guard every bridged request and serve server instructions whole

Resource reads, prompt fetches and paginated lists now recheck the loopback
caller's grant and completion lineage at the request boundary, as tool calls
already did. Configured server instructions are no longer capped at 1,200
characters. A Gateway loopback test revokes a real grant or reassigns a real
completion lineage during a server-driven catalog refresh.

Co-authored-by: VACInc <[email protected]>

* test(gateway): prove Workshop shape and refusal on completion turns

Through the real loopback, a completion turn after a human turn lists the
same skill_workshop definition, refuses personal-library calls without
reaching the human grant, and keeps unsandboxed workspace calls.

Co-authored-by: VACInc <[email protected]>

* test(gateway): prove sandboxed completions cannot write through Workshop

Sandboxed completion turns, with or without skill_workshop admitted by the
sandbox tool policy, list the same Workshop surface as the human turn and
refuse a workspace create before any file changes. The Gateway authority
file runs in the database-worker project, which owns the main-thread
shared-state broker. Drops the mock-sequenced revocation case now covered
by real grant and lineage owners.

Co-authored-by: VACInc <[email protected]>

* test(cli-runner): drop Workshop helper cases covered by the Gateway suite

Definition parity, personal refusal and workspace access are now proven
through the real loopback; keep session isolation and latest-shape cases.

Co-authored-by: VACInc <[email protected]>

* test(gateway): wait for list_changed delivery instead of sleeping

The probe follows each tools/list_changed with a ping on the same SSE
stream; the client handles stream messages in order, so its ping reply
proves the notification was consumed before the next call.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: VACInc <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
…claw#174342)

fix(mcp): give embedded agents the MCP server's instructions, capped per server

MCP servers can publish usage guidance in their initialize result (for example "Before using lookup, always confirm the account name"). Embedded agents received the server's tools but never that guidance. The instructions read by openclaw#172026 are now also delivered to embedded agents, alongside the server's tools, in the system prompt, Tool Search and Code Mode, only for servers that still back at least one usable tool. Each server's text is capped at 2,000 characters for embedded prompts (cut at a character boundary with a truncation note), and OpenClaw prompt markers in it are neutralized. Claude CLI loopback delivery keeps the full text, as openclaw#172026 intends. This matches how Codex surfaces server instructions as the tool namespace description.

Proof: built Gateway with a stdio MCP server and a recording provider. On main the provider request had the tools but not the instructions (twice). With this change the instructions are present (twice); a server with over 2,000 characters shows the capped prefix with one truncation note; a server without instructions leaves the prompt unchanged; Claude CLI loopback still gets the full text. A live gpt-5.4-mini turn passes.

Supersedes openclaw#174425, openclaw#174508 and openclaw#174396. Thanks @xiaopan-xydt.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 22, 2026
)

* fix(claude-cli): stop cache-prefix churn after child completion

Ordinary local claude-cli turns now use the same exact OpenClaw-mediated
tool projection as verified child completions, so a completion no longer
swaps the tools-first cached prefix of a running native session.

Co-authored-by: VACInc <[email protected]>

* test(claude-cli): expect the mediated surface on ordinary turns

Co-authored-by: VACInc <[email protected]>

* test(claude-cli): select native tools in the workspace-only override case

Managed Claude turns are mediated by default, so the agent workspace-only override is
covered on the explicit native-selection path that still exposes native file tools.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): serve configured MCP servers through the loopback bridge

Exclusive CLI runs omit native MCP servers because the CLI would call them
outside OpenClaw's per-turn caps. Managed local Claude turns are now all
exclusive, so configured mcp.servers disappeared from ordinary turns.

Materialize the session's configured MCP tools for the run and serve them
through the loopback grant. They pass the same Gateway policy pipeline and
exact grant allowlist as other tools, so ordinary and completion turns list
one catalog while each turn's cap still decides what is listed and callable.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): ignore request echoes when checking for orphaned tool calls

Claude Code logs api-request-blob records that repeat already answered
tool calls under role=assistant. Counting them made a finished turn look
orphaned until the final reply was written, so a completion that resumed
the parent right after a spawn reset its native session. Only user and
assistant conversation records now count.

Co-authored-by: VACInc <[email protected]>

* fix(claude-cli): keep skill_workshop stable on internal turns

Only human turns receive personal-library authoring, so completion and
other internal turns published a different skill_workshop definition and
broke the native prompt cache for profiled users. Since #176587 this also
affects token-authenticated clients.

CLI turns without authoring now reuse the session's last human shape with
an expired grant, as goal continuation already does. The definition stays
identical and every call, including Workshop calls through the
workspace-default wrapper, is refused, so no sandboxed internal turn gains
Workshop access.

Co-authored-by: VACInc <[email protected]>

* fix(skill-workshop): keep workspace Workshop on internal CLI turns

The stable skill_workshop shape for internal turns refused every call,
including workspace Workshop calls that an unsandboxed no-grant turn may
make on main. Pass the run's sandbox state to the workspace-default
wrapper so the expired grant refuses only personal-library calls and
sandboxed workspace calls.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): recheck loopback grant at configured-server I/O

The loopback handler checked grant and completion lineage before
executing a tool, but a configured MCP tool could still reach its server
after that check, for example after waiting for a session reconnection.
Carry the caller's check into MCP tools/call so it runs immediately
before server I/O.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): serve configured server instructions through the loopback

Managed Claude turns used to connect configured MCP servers natively and
received each server's initialize instructions. The bridge kept the tools
but dropped the instructions. Capture them in the session MCP catalog and
return them from the loopback initialize reply, ordered by server name,
for servers that still have a listed tool. Catalog capture follows the
approach proposed in #174396.

Co-authored-by: VACInc <[email protected]>

* fix(mcp): guard every bridged request and serve server instructions whole

Resource reads, prompt fetches and paginated lists now recheck the loopback
caller's grant and completion lineage at the request boundary, as tool calls
already did. Configured server instructions are no longer capped at 1,200
characters. A Gateway loopback test revokes a real grant or reassigns a real
completion lineage during a server-driven catalog refresh.

Co-authored-by: VACInc <[email protected]>

* test(gateway): prove Workshop shape and refusal on completion turns

Through the real loopback, a completion turn after a human turn lists the
same skill_workshop definition, refuses personal-library calls without
reaching the human grant, and keeps unsandboxed workspace calls.

Co-authored-by: VACInc <[email protected]>

* test(gateway): prove sandboxed completions cannot write through Workshop

Sandboxed completion turns, with or without skill_workshop admitted by the
sandbox tool policy, list the same Workshop surface as the human turn and
refuse a workspace create before any file changes. The Gateway authority
file runs in the database-worker project, which owns the main-thread
shared-state broker. Drops the mock-sequenced revocation case now covered
by real grant and lineage owners.

Co-authored-by: VACInc <[email protected]>

* test(cli-runner): drop Workshop helper cases covered by the Gateway suite

Definition parity, personal refusal and workspace access are now proven
through the real loopback; keep session isolation and latest-shape cases.

Co-authored-by: VACInc <[email protected]>

* test(gateway): wait for list_changed delivery instead of sleeping

The probe follows each tools/list_changed with a ping on the same SSE
stream; the client handles stream messages in order, so its ping reply
proves the notification was consumed before the next call.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: VACInc <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
(cherry picked from commit 77d9f42)
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: MCP server instructions are dropped for agents using the loopback MCP bridge

2 participants