Repository navigation
feat: MCP stdio server so Claude Code can use repl-simple (repl, repl_resume, repl_reset, repl_abandon, rlm) - #242
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
An MCP stdio server so Claude Code (or any MCP client) can use repl-simple without pi. New
binrepl-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 sameReplRunnerandrunRlm, plus an Anthropic-SDKLlmClientsorlmhas a model outside pi. The pi extension's behaviour is unchanged.Repo files carry code only (user rule): the README's one-line description and
package.json'sdescriptionare 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 viaui.select, therlmmodel 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:
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 projectwrites.mcp.jsonfor 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).rlm;replworks without one.@earendil-works/pi-coding-agent(peer + dev dependency, unchanged) is required at runtime bysrc/bridge.ts; a clone'snpm installhas it. Without it the server fails at startup withERR_MODULE_NOT_FOUND— nothing runs half-configured.Then ask Claude Code to run Python via
repl; ask forbash("echo hi")and watch the run suspend; approve by letting therepl_resumepermission prompt through.Environment
ANTHROPIC_API_KEYrlmonly. Never logged or echoed; withheld from the sandboxedbashby the existingBASH_ENV_ALLOWLIST(docs/bash-env.md). Unset →replworks,rlmreturnsstatus: error. The SDK's other credential sources (ANTHROPIC_AUTH_TOKEN,ANTHROPIC_BASE_URL, anant auth loginprofile) work too.REPL_RLM_ANTHROPIC_MODELclaude-opus-5-5rlmloop queries. Operator-only — the MCPrlmtool has nomodel/providerparameters.REPL_MCP_ROOTCLAUDE_PROJECT_DIR, else cwd.pi/code-tools, bridge cwd. Claude Code setsCLAUDE_PROJECT_DIRfor the servers it spawns.REPL_MCP_TRUST_PROJECT1/true/yestrusts 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-preambleoracceptPreamble().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 unlistedhttp_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 itsapprovalId, 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 seesPermissionErrorand continues, as a denied dialog does in pi.repl_abandon(sessionId)drops the suspended run; the session keeps its state. Newreplcode 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-permissionsremoves the human: every call the model chooses to resume then runs. There is noyoloon the server side; that switch is the client's. Insiderlmgated 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'sexecutionMode: "sequential". Sessions live as long as the server process; a pending approval dies with it, unexecuted.rlmcosts real API money per call, bounded byREPL_RLM_BUDGET. No pi commands (/repl-approvals yolo,/repl-accept-preamble), and the trace pi carries ondetailsis not sent over MCP — the result text is what the model gets.Design decisions
repl_resumeis the human gate (above). Chosen over MCP elicitation because the library already had the third answer and elicitation support in clients is uneven.approvalIdrather than having the model echo the call text: descriptions can be long (awritebody) and a near-miss echo turns into a fuzzy-match rule. The precedingreplresult in the transcript carries the exact call.src/model_boundary.ts).clampModelLimits,clampRlmLimits,defaultRlmBudget,DEFAULT_RLM_BUDGET,buildRlmRegistry,formatRlmResultmoved out of the extension intosrc/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 therepltool description lists the real host tools from the runner's registry rather than a typed list.REPL_MCP_TRUST_PROJECT=1opts 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.REPL_MCP_ROOT→CLAUDE_PROJECT_DIR→ cwd. Claude Code documentsCLAUDE_PROJECT_DIRas the thing to use instead of cwd (code.claude.com/docs/en/mcp). Tested over real stdio.rlmquery, so a keyless server servesrepl. The existingBASH_ENV_ALLOWLISTis untouched; a test approvesbash("printenv ANTHROPIC_API_KEY || echo key=unset")with a fake key in the server env and asserts it never appears.@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.messages.create,max_tokens: 16000(one RLM iteration is a code block; the loop needs the whole reply to extract it).refusalandmax_tokensstop reasons reject rather than hand the loop an empty or truncated code block; other SDK errors propagate unchanged sorunRlm's provider-error redaction applies.src/mcp_main.ts(the stdio shim) is excluded from stryker'smutate: its only test runs it as a child process, so a mutant there is invisible to the in-process runner. Same reason it sits inUNMEASURED_SOURCE_FILESfor coverage (captured only intermittently; a floor on a file that is sometimes absent is a hard error by design).wf.tomlcommitted 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-agentstays 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" problemtest/packaging.test.tspins. Kept as is; failure mode documented above.REPL_RLM_BASE_URL(the existing OpenAI-compatible tier insrc/rlm_client.ts) is not honoured by the MCP server. The server uses the Anthropic adapter only. Honouring it would be ~5 lines (createLlmClientwith a stub registry falls through to that tier when the variable is set) — left out to keep one documented path; the Anthropic SDK's ownANTHROPIC_BASE_URLalready covers Anthropic-compatible endpoints (which is how t6 below ran). Unchanged in this follow-up, as asked.fallbacksbeta on the Anthropic calls. The claude-api guidance recommends it by default forclaude-opus-5-5code; this is a library adapter in a code-gen loop, not a chat surface, and a refusal there is correctly anrlmstatus: errorresult 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.wf.tomlto 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 SDKClientoverInMemoryTransportwith a cannedLlmClient: 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 frombash, 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 vsCLAUDE_PROJECT_DIR, exit 0 on stdin close.test/packaging.test.ts—binin the manifest,dist/mcp_main.jswith shebang in build and tarball, packed bin answering an MCPinitializeoffline.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=1so the fd/rg bridge tests fail rather than skip.wf gatemaps to the repo's scripts viawf.toml: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 intest/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/mainbefore 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
d1ab2fdvia headlessclaude -pon the claude.ai login, Claude Code's Bash/Read/Edit disallowed, server started asnode dist/mcp_main.jsin a throwaway untrusted git project containingdata.csv(alpha,3 / beta,5 / gamma,8):x = 41thenx + 1on one sessionimport subprocess;read_file("/etc/passwd")[error: typing] unresolved-import;PermissionError: absolute paths are not alloweddata.csvcolumn 2csvmodule and fell back tosplitbash("echo approved-run")approvalId;repl_resume→approved-run.repl_resumewas pre-allowed in that headless run, so the interactive permission prompt itself was not exercised.repl_abandonrlm: largest label indata.csvstatus: ok, answergamma— 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'sbuildApprovalRequestspells 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: errorfor t6.Open questions / risks
npm run mutationnot re-run (hours); per-file mutation score of the new files is unmeasured until the next run.src/preamble.tscoverage floor moved 100 → 97.05 bycoverage: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