Skip to content

Code Mode for MCP servers: tools behind execute_code scripts, never in the prompt - #609

Merged
FMXExpress merged 3 commits into
mainfrom
claude/opencode2-b-codemode
Oct 23, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/opencode2-b-codemode

Conversation

@FMXExpress

@FMXExpress FMXExpress commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

PR B of the OpenCode 2.0 plan. #608 has merged, so this now targets main directly and main is merged in.

What it does

OpenCode 2.0's one real idea: an MCP server's tools are not sent to the model as schemas. The model calls them from a script that chains calls and filters results, so only the final output enters the conversation. PasClaw already had the script tool (execute_code) and the RPC back into the registry; this PR gives the model the shape it needs and keeps the language bash/PowerShell rather than adding a JavaScript runtime.

  • mcp_servers[].codemode (default from new mcp_codemode_default: true): the server's tools register with a new TTool.CodeMode flag. They dispatch normally but are never a provider tool def (a stale Reveal cannot resurrect the schema), and tool_search neither lists nor loads them. Asked to select: one, tool_search explains that it is a code-mode tool and gives the recipe.
  • Prompt. The ## Deferred Tools section now names each code-mode server with its tool count and the recipe, and renders when only code-mode servers exist. Rule 6 says a chain of tool calls is one script, and that code-mode servers are reachable only that way.
  • code_catalog(server?) returns name, server, description and argument schema for the code-mode tools. The same catalog is available from inside a script as tool --catalog [server], through a new RPC catalog verb.
  • Every execute_code script starts with a one-line tool function over pasclaw __tool, with $PASCLAW_BIN (the running executable, in the backend's namespace) exported into the script's environment. The model writes tool github__list_issues '<json>' | jq .... The prologue avoids parameter-expansion braces because the denylist rejects them in the model's own code.
  • Calls from scripts go through the dispatch gates Close the gates scripts and skills walked around, bound the shell, deliver background results in the gateway #608 installed, so plan mode refuses a mutating MCP tool from a script exactly as from a direct call.

"codemode": false on a server, or "mcp_codemode_default": false, keeps the classic shape (deferred behind tool_search).

Review fixes (three P1s, each a way code mode leaked away)

A server added by any supported flow was pinned to classic exposure. mcp add, mcp install and onboarding build the TMCPServer record zero-initialised, so CodeMode came out False, and MCPToJSON wrote the key unconditionally — persisting that False whatever mcp_codemode_default said. All three creation sites now take the config default, and the key is written only when it differs from it, so a server that follows the default keeps following it.

A subagent got the full MCP schemas its parent had kept out of the prompt. BuildFilteredRegistry copies tools through TToolRegistry.Register, which force-clears IsDeferred / Hidden / CodeMode. That clear is right for the legacy call sites it exists for (stack-built records with untouched fields) and wrong for a record that came out of Find. Both copy paths now re-register through RegisterCodeMode when the flag is set; the defensive clear in Register stays.

Under the Docker shell backend the callback could not work at all. The binary is bind-mounted into the container so pasclaw __tool runs there, but the client dialled a hardcoded 127.0.0.1 — inside a container, the container — while the parent's RPC server listened on the host's loopback. Every tool ... call failed to connect, and with code mode on that is the only route to an MCP server's tools.

  • New optional capability IShellHostRPC, the network counterpart of IShellPathMapper. The docker backend answers with the default bridge's gateway to listen on (what host-gateway resolves to, probed once per process) and host.docker.internal to dial; docker run gets --add-host=host.docker.internal:host-gateway so the name exists on Linux too. --network host answers with nothing — the namespace is shared.
  • TToolRPCServer takes BindIP / AdvertiseHost; the discovery file carries "host" when it isn't loopback and pasclaw __tool dials what it finds there. A BindIP this host does not own falls back to loopback instead of failing the call — exactly the Docker Desktop shape, where the daemon's bridge gateway lives in a VM and host.docker.internal already forwards to the host.
  • --network none is reported at container start: no route, so scripts cannot call tools back there at all.

The per-call random token still authorises every request and the listener still lives only for one execute_code call. docs/security.md spells out what moving off loopback does and does not widen.

Tests

test-codemode: registry filters (provider defs, DeferredNames, DeferredFind, stale reveal), Find/RunTool dispatch, the catalog (all, per server, unknown, escaping, empty schema), Register clearing the flag; tool_search's explanation; the prompt section with and without classic deferred tools; code_catalog registration and output; the RPC catalog verb over the loopback socket with and without a token; config per server, the global default and a round-trip; the prologue for both shells and a real bash run that sees the function. The review fixes add: pasclaw mcp add run for real against a temp home (no codemode key, follows the default in both directions), and a script's discovery file carrying the active backend's callback host.

test-subagent-default: a code-mode tool copied into a child registry stays out of ToProviderDefs and DeferredNames and stays dispatchable, in both copy paths.

test-tool-rpc: BindIP moves the listener (loopback then refuses) and AdvertiseHost records it; an unbindable address degrades to loopback and still serves; the real pasclaw __tool binary reaches a server that is not on its own loopback.

test-shell-backend: the docker backend's IShellHostRPC answers, the --add-host flag and the gateway parser, all read without a daemon on the box.

Every fix negative-verified by reverting it and watching the specific assertion fail. Full make test on this branch: green, 0 make errors.

Docs

docs/mcp.md gains a Code Mode section (and the container-callback route); configuration.md the two keys; tools.md the tool helper and --catalog; security.md the callback's network posture.

Behaviour change to be aware of

Code Mode is the default. Existing MCP servers stop appearing as tool schemas after upgrading; the model reaches them from scripts, which is the point, and the prompt tells it so. Set mcp_codemode_default: false to keep the previous behaviour everywhere.


🤖 Generated with Claude Code

https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U

…n the prompt

PR B of docs/opencode2-plan.md. OpenCode 2.0's one real idea: an MCP
server's tools are not sent to the model as schemas; the model calls
them from a script that chains calls and filters results, so only the
final output enters the conversation. PasClaw already had the script
tool and the RPC back into the registry; what was missing was the
shape the model sees.

mcp_servers[].codemode (default from mcp_codemode_default, true): the
server's tools register with the new TTool.CodeMode flag --
dispatchable, never a provider def (a stale reveal cannot resurrect
the schema), never listed or loaded by tool_search. tool_search told
to select: one explains that it is a code-mode tool and gives the
recipe. The "## Deferred Tools" section names each code-mode server
with its tool count and the recipe, and renders when only code-mode
servers exist. code_catalog(server?) returns name, server, description
and argument schema, as does `tool --catalog [server]` from a script
through a new RPC catalog verb.

Every execute_code script now starts with a one-line `tool` function
over `pasclaw __tool`, with $PASCLAW_BIN (the running executable, in
the backend's namespace) exported into the script's environment, so
the model writes `tool github__list_issues '<json>' | jq ...`. The
prologue avoids parameter-expansion braces because the denylist
rejects them in the model's own code. The Docker backend binds the
executable read-only at the same path on POSIX so `tool` works inside
the container. Rule 6 of the system prompt says a chain of tool calls
is one script, and that code-mode servers are reachable only that way.

Calls from scripts go through the dispatch gates PR A installed, so a
plan-mode turn is refused from a script exactly as from a direct call.

Tested (test-codemode): the registry filters, Find/RunTool dispatch,
the catalog (all, per server, unknown, escaping, empty schema),
Register clearing the flag; tool_search's explanation; the prompt
section with and without classic deferred tools; code_catalog
registration and output; the RPC catalog verb over the loopback socket
with and without a token; config per server, the global default and a
round-trip; the prologue for both shells and a real bash run that sees
the function. Negative-tested by removing the provider-defs filter,
which failed on the stale-reveal assertion.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T07:27:38.079084Z 124eebf PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 124eebfb5f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/config/PasClaw.Config.pas Outdated
Result.PutStr ('args', M.Args);
Result.PutStr ('env', M.Env);
Result.PutBool('enabled', M.Enabled);
Result.PutBool('codemode', M.CodeMode);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Initialize added servers from the code-mode default

When pasclaw mcp add, pasclaw mcp install, or onboarding appends a TMCPServer, those existing creation paths set Name, Cmd, Args, and Enabled but never CodeMode. The new dynamic-array record is therefore zero-initialized to False, and this unconditional serialization persists "codemode": false, overriding MCPCodeModeDefault = True on subsequent loads. Consequently, servers installed through the supported setup flows do not use the advertised default; initialize new records from Cfg.MCPCodeModeDefault or preserve whether the field was omitted.

Useful? React with 👍 / 👎.

records never set it, so garbage there could silently drop a core tool
from ToProviderDefs. Aliases go through RegisterHidden instead. }
Modified.Hidden := False;
Modified.CodeMode := False;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve code mode when cloning subagent registries

For a wildcard subagent, BuildFilteredRegistry gets code-mode tools from Source.Names, but they are intentionally absent from Source.DeferredNames, so it copies them with Result.Register(T); explicit allowlists use that path unconditionally too. Clearing CodeMode here converts those copied entries into ordinary provider-visible tools, causing spawned children to receive the full MCP schemas and call them directly despite the code-mode invariant. The copy path needs to re-register records with RegisterCodeMode when this flag is set.

Useful? React with 👍 / 👎.

Comment on lines +396 to +397
Args.Add('-v');
Args.Add(ExpandFileName(ParamStr(0)) + ':' + ExpandFileName(ParamStr(0)) + ':ro');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Route Docker callbacks to the host RPC listener

With the default Docker bridge network, mounting the executable makes pasclaw __tool runnable but does not make its RPC destination reachable: the client always connects to 127.0.0.1, while TToolRPCServer is bound to the host's 127.0.0.1; inside the container that address refers to the container itself. Thus every tool ... or tool --catalog call fails under the default Docker backend, and because code-mode MCP tools are now reachable only through that callback, Docker users lose access to them. Expose a host-reachable endpoint/address or otherwise bridge the callback rather than only mounting the binary.

Useful? React with 👍 / 👎.

Only docs/configuration.md conflicted: this branch added the
mcp_codemode_default and mcp_servers[].codemode rows directly above the
shell_timeout_sec row that #608 rewrote in main. Kept both new rows and
main's corrected timeout row.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
… containers

Three review findings, each one a way a code-mode MCP server stopped
being in code mode.

**A server added by any supported flow was pinned to classic exposure.**
`mcp add`, `mcp install` and onboarding build the TMCPServer record
zero-initialised, so CodeMode came out False; MCPToJSON then wrote the
key unconditionally, persisting that False. The server was stuck on
classic exposure whatever mcp_codemode_default said, before or after.
All three creation sites now set CodeMode from the config default, and
MCPToJSON omits the key when it matches the default -- so a server that
follows the default keeps following it, the way every other
default-valued setting in this file is serialised.

**A subagent got the full MCP schemas its parent had kept out of the
prompt.** BuildFilteredRegistry copies the parent's tools through
TToolRegistry.Register, which force-clears IsDeferred / Hidden /
CodeMode. That clear is right for the legacy call sites it was written
for -- they build a TTool on the stack and never touch those fields --
and wrong for a record that came out of Find, where every flag is real.
Both copy paths (wildcard and explicit allowlist) now re-register
through RegisterCodeMode when the flag is set. The defensive clear in
Register stays as it is.

**Under the Docker shell backend the callback could not work at all.**
The binary is bind-mounted into the container so `pasclaw __tool` runs
there, but the client dialled a hardcoded 127.0.0.1 -- which inside a
container is the container -- while the parent's RPC server listened on
the host's loopback. Every `tool ...` / `tool --catalog` call failed to
connect, and with code mode on that is the only route to an MCP
server's tools. Now:

  - IShellHostRPC, the network counterpart of IShellPathMapper: an
    optional capability a backend implements when its commands run in
    another network namespace. The docker backend answers with the
    default bridge's gateway to listen on (which is what `host-gateway`
    resolves to, probed once per process from `docker network inspect`)
    and host.docker.internal to dial; `docker run` gets
    --add-host=host.docker.internal:host-gateway so the name exists on
    Linux too. --network host answers with nothing: the namespace is
    shared and loopback already works.
  - TToolRPCServer takes BindIP / AdvertiseHost. The discovery file
    carries "host" when it isn't loopback, and `pasclaw __tool` dials
    what it finds there. A BindIP this host does not own is not fatal --
    it falls back to loopback, which is exactly the Docker Desktop
    shape, where the daemon's bridge gateway lives in a VM and
    host.docker.internal already forwards to the host.
  - --network none is reported at container start: there is no route,
    so scripts cannot call tools back there at all.

The per-call random token still authorises every request and the
listener still lives only for the duration of one execute_code call;
docs/security.md spells out what the move off loopback does and does
not widen.

Tested, each fix negative-verified by reverting it:

  - test-codemode: `pasclaw mcp add` run for real against a temp home
    writes no codemode key and follows the default in both directions
    (fails with either half of the fix reverted); a script's discovery
    file carries the active backend's callback host.
  - test-subagent-default: a code-mode tool copied into a child
    registry stays out of ToProviderDefs, stays out of DeferredNames,
    stays dispatchable, in both copy paths.
  - test-tool-rpc: BindIP moves the listener (loopback refuses) and
    AdvertiseHost records it; an unbindable address degrades to
    loopback and still serves; the real `pasclaw __tool` binary reaches
    a server that is not on its own loopback.
  - test-shell-backend: the docker backend's IShellHostRPC answers and
    the --add-host flag, read off BuildRunArgv without a daemon on the
    box.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
@FMXExpress
FMXExpress changed the base branch from claude/opencode2-a-fixes to main October 22, 2026 22:53
@FMXExpress
FMXExpress merged commit ea0f799 into main Oct 23, 2026
2 checks passed
FMXExpress pushed a commit that referenced this pull request Oct 23, 2026
…lag, and refuse before touching the repo

This branch now targets main. It brings in the updated #611 branch,
which carries main -- #609 code mode and #619 background jobs, both
merged -- so the PR's diff against main is permissions plus worktrees
until #611 lands, then worktrees alone. Worktrees depend on #611: they
add resource mappings to PasClaw.Permissions, the file #611 creates.

Three conflicts:

  docs/configuration.md -- this branch's worktree rows sat where main
  reworded shell_timeout_sec. Kept both, and said that
  worktree.enabled:false takes the spawn argument away too.

  PasClaw.Permissions.pas, ResourceOf -- this branch added
  worktree_remove/worktree_create cases to the old name list that #611
  replaced with a generic path/url/command fall-through. worktree_remove
  takes a `path`, which the fall-through already reads; worktree_create
  is named by its `branch`, which no generic field covers, so it keeps a
  named case.

  PasClaw.Agent.SubagentBg.pas, the spawn_background registration --
  #619 put it inside `if Length(Specs) > 0` so the shell tools survive
  subagents being off; this branch added a `worktree` schema property.
  Kept #619's structure; the property is now conditional (below).

And the two review findings, both P2, both real:

**worktree.enabled:false only took away one door of three.** Callers
dropped the worktree_* tools, but spawn and spawn_background still
advertised a `worktree` argument and still created a branch and a
checkout when it was passed. WorktreeArgEnabled (a nil Cfg reads as the
documented default, on) now gates both handlers, which refuse the
argument with a message saying how to proceed, and both schemas, which
stop offering it.

**spawn_background created the worktree before checking the job cap.**
A spawn the cap was always going to refuse still made a branch and a
checkout on disk, then returned the capacity error. Checking first is
not enough by itself -- two spawns in one parallel batch would both pass
and both create -- so the slot is reserved under the lock (FReserved,
counted by SlotsInUse alongside running jobs, and shell_background's cap
check counts it too), the slow git work runs outside the lock, and the
reservation becomes the job or is handed back on failure.

spawn had the same shape with its cheap checks: an unknown agent or an
empty prompt made a worktree on its way to being refused. EnsureWorktree
now runs after every check that can reject the call.

Tested (test-worktree), each fix negative-verified by reverting it:

  - with worktree.enabled:false, neither spawn nor spawn_background
    offers the property, both refuse it, and no directory or branch
    appears; with it on, spawn offers it again. Reverting the gate fails
    on the schema assertion.
  - spawn with an unknown agent or no prompt, and spawn_background at a
    cap of 1 held by a running shell job, each leave no worktree
    directory and no branch. Reverting the reservation fails on the cap
    case. Reverting spawn's ordering fails too -- on the flag test first,
    since the reverted order also runs ahead of the flag check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants