Skip to content

feat: MCP stdio server so Claude Code can use repl-simple (repl, repl_resume, repl_reset, repl_abandon, rlm) - #242

Merged
AdarGit008 merged 8 commits into
mainfrom
feat/mcp-server
Oct 5, 2026
Merged

AdarGit008 merged 8 commits into
mainfrom
feat/mcp-server

Conversation

@AdarGit008

@AdarGit008 AdarGit008 commented Oct 5, 2026 •

Copy link
Copy Markdown
Owner

What

An MCP stdio server so Claude Code (or any MCP client) can use repl-simple without pi. New bin repl-simple-mcp (dist/mcp_main.js) exposes the same five tools the pi extension registers — repl, repl_resume, repl_reset, repl_abandon, rlm — over the same ReplRunner and runRlm, plus an Anthropic-SDK LlmClient so rlm has a model outside pi. The pi extension's behaviour is unchanged.

Claude Code ──stdio/JSON-RPC──▶ src/mcp_main.ts (bin) ──▶ src/mcp_server.ts ──▶ ReplRunner (src/repl.ts)
                                                              │                └─▶ runRlm (src/rlm.ts) ◀── src/anthropic_client.ts ── ANTHROPIC_API_KEY (server process only)
                                                              └─▶ src/model_boundary.ts  (clamps, rlm knobs, rlm registry, rlm rendering — shared with extensions/repl-extension.ts)

Repo files carry code only (user rule): the README's one-line description and package.json's description are the only prose edits ("Pi extension —" → "Pi extension and MCP server —"). Everything a reviewer or user needs to know about the server is in this PR body.

Why

repl-simple was reachable only from pi: tools via defineTool, approvals via ui.select, the rlm model via pi's model registry. Claude Code speaks MCP and has none of those.

How to try it from Claude Code

The package is not on npm, so install from the branch and build:

git clone https://github.com/AdarGit008/repl-simple && cd repl-simple && git switch feat/mcp-server
npm install && npm run build            # dist/mcp_main.js is the bin

Register it from the project you want the sandbox rooted at:

claude mcp add --transport stdio repl-simple \
  --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \
  -- node /absolute/path/to/repl-simple/dist/mcp_main.js
  • --scope project writes .mcp.json for the team instead of local config. Claude Code asks before using a project-scoped server and strips credential-named variables (*KEY*, *TOKEN*, …) from the env it hands such servers, so pass the key explicitly (--env, or "env": {"ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}"} in .mcp.json).
  • The key is only needed by rlm; repl works without one.
  • @earendil-works/pi-coding-agent (peer + dev dependency, unchanged) is required at runtime by src/bridge.ts; a clone's npm install has it. Without it the server fails at startup with ERR_MODULE_NOT_FOUND — nothing runs half-configured.

Then ask Claude Code to run Python via repl; ask for bash("echo hi") and watch the run suspend; approve by letting the repl_resume permission prompt through.

Environment

Variable Default Meaning
ANTHROPIC_API_KEY — Read by the Anthropic SDK in the server process, for rlm only. Never logged or echoed; withheld from the sandboxed bash by the existing BASH_ENV_ALLOWLIST (docs/bash-env.md). Unset → repl works, rlm returns status: error. The SDK's other credential sources (ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL, an ant auth login profile) work too.
REPL_RLM_ANTHROPIC_MODEL claude-opus-5-5 Model id the rlm loop queries. Operator-only — the MCP rlm tool has no model/provider parameters.
REPL_MCP_ROOT CLAUDE_PROJECT_DIR, else cwd Project root: path jail, .pi/code-tools, bridge cwd. Claude Code sets CLAUDE_PROJECT_DIR for the servers it spawns.
REPL_MCP_TRUST_PROJECT unset — untrusted 1/true/yes trusts the project so an accepted saved-tool set may load (docs/project-trust.md). Trust alone loads nothing: acceptance comes from pi's /repl-accept-preamble or acceptPreamble().

All existing REPL_* variables apply unchanged (REPL_RLM_BUDGET, REPL_MAX_*, REPL_HTTP_ALLOWLIST, REPL_BASH_ENV_ALLOW, REPL_PREAMBLE_STORE_DIR).

Approval semantics over MCP

MCP has no dialog for the server to open, and the server never approves anything itself. Every gated call (bash, edit, write, save_tool, an unlisted http_get) suspends the run — the library's existing "decide later" answer — and the result says: the call has not run, here is the call, here is its approvalId, and these decide it:

  • repl_resume(sessionId, approvalId) runs it. Claude Code's permission prompt in front of that tool call is the human approval. The id binds the decision to the call that was shown: a stale/guessed/mistyped id resumes nothing and the result repeats the pending call and its id. If the continuation reaches another gated call it suspends again under a new id — one prompt per gated call, the MCP form of strict mode's "one approval covers one execution".
  • repl_resume(sessionId, approvalId, decision='deny') refuses it: Python sees PermissionError and continues, as a denied dialog does in pi.
  • repl_abandon(sessionId) drops the suspended run; the session keeps its state. New repl code on that session does the same and says so ([discarded]).

The gate holds exactly as long as Claude Code asks. Allow-listing mcp__repl-simple__repl_resume (or the server, mcp__repl-simple), "don't ask again", or --dangerously-skip-permissions removes the human: every call the model chooses to resume then runs. There is no yolo on the server side; that switch is the client's. Inside rlm gated tools are denied outright, as in pi.

Limits

Everything in the README's Sandbox section (Monty's fixed stdlib, no subprocess/sockets, language gaps, type checker, output caps). glibc only — no musl build of @pydantic/monty (docs/platform-support.md); Node ≥ 22.19.0. One server serves one root; tool calls are serialised like the extension's executionMode: "sequential". Sessions live as long as the server process; a pending approval dies with it, unexecuted. rlm costs real API money per call, bounded by REPL_RLM_BUDGET. No pi commands (/repl-approvals yolo, /repl-accept-preamble), and the trace pi carries on details is not sent over MCP — the result text is what the model gets.

Design decisions

  1. Suspend, then repl_resume is the human gate (above). Chosen over MCP elicitation because the library already had the third answer and elicitation support in clients is uneven.
  2. Opaque approvalId rather than having the model echo the call text: descriptions can be long (a write body) and a near-miss echo turns into a fuzzy-match rule. The preceding repl result in the transcript carries the exact call.
  3. Shared model boundary (src/model_boundary.ts). clampModelLimits, clampRlmLimits, defaultRlmBudget, DEFAULT_RLM_BUDGET, buildRlmRegistry, formatRlmResult moved out of the extension into src/ and are re-exported from the extension under their old names — two hosts, one copy; extension, loader and README tests pass unmodified. ReplRunner.describeHostTools() is one additive method so the repl tool description lists the real host tools from the runner's registry rather than a typed list.
  4. Trust off by default, REPL_MCP_TRUST_PROJECT=1 opts in, nothing unapproved loads even then (A trusted project silently runs a later-added .pi/code-tools file (preamble TOFU residual) #198). Tested both ways.
  5. Root = REPL_MCP_ROOT → CLAUDE_PROJECT_DIR → cwd. Claude Code documents CLAUDE_PROJECT_DIR as the thing to use instead of cwd (code.claude.com/docs/en/mcp). Tested over real stdio.
  6. Key handling. SDK client constructed lazily on the first rlm query, so a keyless server serves repl. The existing BASH_ENV_ALLOWLIST is untouched; a test approves bash("printenv ANTHROPIC_API_KEY || echo key=unset") with a fake key in the server env and asserts it never appears.
  7. New deps, exact-pinned like the existing runtime deps: @modelcontextprotocol/sdk@1.32.0 (official SDK), zod@4.6.5 (its required peer for tool schemas), @anthropic-ai/sdk@0.131.0. The MCP SDK brings a sizeable transitive tree (express/hono/jose for HTTP transports we do not use) — unavoidable with the official package.
  8. Anthropic adapter. Non-streaming messages.create, max_tokens: 16000 (one RLM iteration is a code block; the loop needs the whole reply to extract it). refusal and max_tokens stop reasons reject rather than hand the loop an empty or truncated code block; other SDK errors propagate unchanged so runRlm's provider-error redaction applies.
  9. Mutation set. src/mcp_main.ts (the stdio shim) is excluded from stryker's mutate: its only test runs it as a child process, so a mutant there is invisible to the in-process runner. Same reason it sits in UNMEASURED_SOURCE_FILES for coverage (captured only intermittently; a floor on a file that is sometimes absent is a hard error by design).
  10. wf.toml committed per the okf-dev-workflow convention (lint/typecheck/test/build → the repo's scripts). Drop that commit if the repo should not carry it.

Calls made below the 90% conviction floor (conservative choice taken, flagged for review)

  • @earendil-works/pi-coding-agent stays peer + dev (no change). The MCP path is the first consumer outside pi, so a regular dependency is defensible; but moving it reopens the "second copy next to pi's own" problem test/packaging.test.ts pins. Kept as is; failure mode documented above.
  • REPL_RLM_BASE_URL (the existing OpenAI-compatible tier in src/rlm_client.ts) is not honoured by the MCP server. The server uses the Anthropic adapter only. Honouring it would be ~5 lines (createLlmClient with a stub registry falls through to that tier when the variable is set) — left out to keep one documented path; the Anthropic SDK's own ANTHROPIC_BASE_URL already covers Anthropic-compatible endpoints (which is how t6 below ran). Unchanged in this follow-up, as asked.
  • No server-side fallbacks beta on the Anthropic calls. The claude-api guidance recommends it by default for claude-opus-5-5 code; this is a library adapter in a code-gen loop, not a chat surface, and a refusal there is correctly an rlm status: error result rather than a silent model switch (which would also change which model's output the "untrusted" marker refers to). Unchanged in this follow-up, as asked.
  • Committing wf.toml to the repo (decision 10).

Tests

  • test/anthropic_client.test.ts (12) — adapter through an injected recorder client: params, signal forwarding, text-block joining, env model, refusal/max_tokens rejection, error passthrough, lazy construction. No key, no network.
  • test/mcp_server.test.ts (40) — the server through the MCP SDK Client over InMemoryTransport with a canned LlmClient: registration/schemas/annotations, state across calls, typing refusal, path jail, suspend → wrong id → right id → runs, deny, nested gated calls, abandon, discard-on-new-code, key withheld from bash, reset, trust (untrusted default / opt-in + accept), rlm ok/error/clamp, close().
  • test/mcp_stdio.test.ts (4) — the real bin as a child over stdio: tool list, clean protocol stream, clean stderr, cwd vs CLAUDE_PROJECT_DIR, exit 0 on stdin close.
  • test/packaging.test.ts — bin in the manifest, dist/mcp_main.js with shebang in build and tarball, packed bin answering an MCP initialize offline.
  • test/readme.test.ts — unchanged from main (the MCP-table assertion added earlier on this branch was removed with the README section).

Gate (real output)

Final tree (bba4b86), REQUIRE_BRIDGE_TOOLS=1 so the fd/rg bridge tests fail rather than skip. wf gate maps to the repo's scripts via wf.toml:

lint: pass        # npm run lint  → biome check --error-on-warnings && knip (70 files, 0 diagnostics)
typecheck: pass   # npm run check → tsc --noEmit
test: pass        # npm test
build: pass       # npm run build → dist/, incl. dist/mcp_main.js with shebang
wf gate exit=0

npm test (standalone, for the totals wf swallows):
  ℹ tests 1907  suites 398  pass 1896  fail 0  skipped 0  todo 11   # the 11 todo are main's pre-existing ⚠ TODOs
npm run coverage: All per-file floors met (exit 0); all files 98.97% (reported, not a gate)

Honesty note: three full-suite runs on the final tree were green (the gate's own, the coverage run's, and the standalone one above). A fourth, run back-to-back between them while this shared host sat at load average 36–54, recorded pass 1895 fail 1; my log filter kept the totals but not the test's name, and the next run at comparable load was clean. The repo already marks several timing-calibrated tests as load-sensitive on this host (see the ⚠ notes in test/session.test.ts). I am reporting it rather than hiding it; if it recurs in CI I will chase the name.

Baseline on untouched origin/main before any change: check 0, lint 0, test 0.

Not run: npm run mutation (hours; see risks).

E2E (real Claude Code sessions)

Run by the coordinator on d1ab2fd via headless claude -p on the claude.ai login, Claude Code's Bash/Read/Edit disallowed, server started as node dist/mcp_main.js in a throwaway untrusted git project containing data.csv (alpha,3 / beta,5 / gamma,8):

# Scenario Result
t1 x = 41 then x + 1 on one session 42
t2 import subprocess; read_file("/etc/passwd") [error: typing] unresolved-import; PermissionError: absolute paths are not allowed
t3 sum of data.csv column 2 16 — the model hit the missing csv module and fell back to split
t4 bash("echo approved-run") suspended with an approvalId; repl_resume → approved-run. repl_resume was pre-allowed in that headless run, so the interactive permission prompt itself was not exercised.
t5 suspended, then repl_abandon "dropped and never executed"
t6 rlm: largest label in data.csv status: ok, answer gamma — run against DeepSeek's Anthropic-compatible endpoint (ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic, REPL_RLM_ANTHROPIC_MODEL=deepseek-chat). The Anthropic key is at its usage cap until 2026-11-01, so this was not run against a Claude model.

Cost: ~$0.99 across the six sessions. Known cosmetic issue: the approval text renders timeout=undefined (the library's buildApprovalRequest spells an omitted optional parameter that way; pre-existing, untouched here).

An earlier scripted run of the same six scenarios through the MCP SDK client against the built bin (no model in the loop) gave the same results for t1–t5 and the graceful usage-limit status: error for t6.

Open questions / risks

  • The four sub-90% calls above.
  • Claude Code's docs do not confirm whether its permission prompt shows MCP tool arguments; the design relies on the transcript carrying the exact call either way, and t4 did not exercise the interactive prompt.
  • MCP SDK transitive footprint.
  • npm run mutation not re-run (hours); per-file mutation score of the new files is unmeasured until the next run.
  • src/preamble.ts coverage floor moved 100 → 97.05 by coverage:update (one-line observation on a 34-line file, the coverage:update writes floors that the instrument's own variance can turn red #113 instrument defect the gate's one-line tolerance absorbs). Flagged because lowering a floor is a decision.

🤖 Generated with Claude Code

AdarGit008 and others added 8 commits October 5, 2026 09:32
lint → npm run lint, typecheck → npm run check, test → npx tsx --test
(test paths appended), build → npm run build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
clampModelLimits, clampRlmLimits, defaultRlmBudget, DEFAULT_RLM_BUDGET,
buildRlmRegistry and formatRlmResult are the clamps, knobs and rendering a
host applies where untrusted model input meets the library. The MCP server
is a second host with the same boundary, so they now live once in src/ and
the extension re-exports them under their original names — its surface and
behaviour are unchanged (extension, loader and README tests: 152/152).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
createAnthropicLlmClient() implements LlmClient over one non-streaming
messages.create per query. The SDK client is constructed lazily on the
first query, so a process without credentials still builds the client (and
the MCP server that owns it still serves repl); a missing key surfaces as
the rlm call's own error. Model from REPL_RLM_ANTHROPIC_MODEL, default
claude-opus-5-5. A refusal or a max_tokens cut rejects instead of handing
the loop an empty or truncated code block. Tests drive an injected
recorder client — no key, no network.

Dependencies: @modelcontextprotocol/sdk 1.32.0 (MCP server), @anthropic-ai/sdk
0.131.0 (this adapter), zod 4.6.5 (the MCP SDK's required peer for tool
schemas), all pinned exactly like the existing runtime deps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and rlm

createReplMcpServer() builds an @modelcontextprotocol/sdk McpServer over the
same ReplRunner and runRlm the pi extension uses, through the shared model
boundary (src/model_boundary.ts). No transport is attached here: the entry
point connects stdio, the tests an in-memory pair.

Approvals without a dialog: every gated call suspends the run (the
library's 'suspend' answer), the result tells the model the call has NOT
run and mints an approvalId, and repl_resume takes that id — any other id
resumes nothing. Claude Code's own permission prompt in front of
repl_resume is the human approval point; a later gated call in the same
continuation suspends again with a new id, so each decision is its own
prompt. decision='deny' refuses the call (PermissionError in Python, run
continues); repl_abandon drops the run.

Trust defaults to untrusted; REPL_MCP_TRUST_PROJECT opts in, and even then
nothing unapproved loads. Root: REPL_MCP_ROOT, else CLAUDE_PROJECT_DIR
(which Claude Code sets for MCP servers), else cwd. The rlm model is the
Anthropic adapter unless an LlmClient is injected. Tool calls are
serialised, as the extension's executionMode: 'sequential' does. Nothing
writes to stdout. ReplRunner.describeHostTools() is added so the repl
tool's description lists the real host tools instead of a typed copy.

Tests drive the server through the SDK Client over InMemoryTransport with a
canned LlmClient: state across calls, typing refusal, path jail, the
suspend → wrong id → right id → runs flow, deny, nested gated calls,
abandon, discard-on-new-code, ANTHROPIC_API_KEY withheld from bash, reset,
trust wiring, rlm result/error/clamp, close().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
src/mcp_main.ts is the process edge and nothing else: configuration from
the environment (REPL_MCP_ROOT, else CLAUDE_PROJECT_DIR, else cwd;
REPL_MCP_TRUST_PROJECT), the server on StdioServerTransport, and a shutdown
on stdin close / SIGINT / SIGTERM that abandons pending approvals, resets
sessions and closes the worker pool. package.json gains
bin.repl-simple-mcp → dist/mcp_main.js; tsc keeps the shebang.

test/mcp_stdio.test.ts spawns the entry as a child and drives it over
stdio through the SDK client: tool list, a clean protocol stream (a sandbox
worker leaking to stdout would break it), clean stderr, cwd vs
CLAUDE_PROJECT_DIR as root, exit 0 when stdin closes. packaging.test.ts
pins the bin in the manifest, the shebang in dist/, the file in the
tarball, and the packed bin answering an MCP initialize offline.

stryker: src/mcp_main.ts leaves the mutate set — its only test runs it as a
child process, so a mutant there is invisible to the in-process runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Install from a clone, the claude mcp add command, the five MCP tools (table
pinned by test/readme.test.ts against MCP_TOOL_NAMES), the approval
semantics — suspend, approvalId, repl_resume as the human gate behind
Claude Code's permission prompt, deny, abandon, and what allow-listing
removes — the environment variables, and the limits (Monty sandbox, glibc
only / no musl, serialised calls, no pi commands). Module map rows for the
new files; the mutate-set exclusion noted under Mutation score.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… its reason

npm run coverage:update (3 runs, per-file minima): src/anthropic_client.ts
99.07, src/mcp_server.ts 97.78, src/model_boundary.ts 100; the existing
floors re-measured on the same tree (extensions/repl-extension.ts 99.88
after the move). src/preamble.ts fell 100 → 97.05: a one-line observation
on a 34-line file — the documented instrument defect (#113), which the
gate's one-line tolerance already absorbs.

src/mcp_main.ts joins UNMEASURED_SOURCE_FILES: its test spawns it as a
child process over stdio, and Node's coverage does not follow into a child
run through the tsx loader, so it never reaches the report. Everything it
calls (src/mcp_server.ts) is floored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nes it made false

README.md returns to main's text except its first line, and package.json's
description changes in the same few words: both said "Pi extension —", and
the package now also ships the repl-simple-mcp bin. The "Claude Code (MCP
server)" section, the module-map rows and the mutate-set paragraph the
branch had added are removed — install, claude mcp add, approval semantics
and results live in the PR body. test/readme.test.ts loses the assertion
that pinned the removed MCP table, so it describes only what remains; the
file is byte-identical to main again. No behaviour changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AdarGit008
AdarGit008 merged commit 79ac0c2 into main Oct 5, 2026
12 checks passed
@AdarGit008
AdarGit008 deleted the feat/mcp-server branch October 5, 2026 08:17
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.

1 participant