pyrepl-mcp
# pyrepl-mcp
An MCP server with a single tool, `ipython`, backed by a persistent Python kernel. It plugs into existing coding-agent CLIs (Antigravity CLI `agy`, Claude Code, Codex CLI) over stdio and keeps their auth, TUI and slash commands as they are.
Variables, imports, the working directory, `os.environ`, asyncio tasks and background shell jobs persist across tool calls, across turns and across context compaction. The model can load a log once and filter it many times, define a helper and reuse it, or start a build and check on it later. It does not have to re-read files and re-run commands every turn.
## How it works
The MCP server is a small supervisor that never runs user code. Cells run in a separate kernel process that does not own the MCP stdout, so nothing user code prints (C extensions and child processes included) can corrupt JSON-RPC framing. A runaway cell cannot wedge the server: when a call reaches its deadline it returns, and the cell keeps running in the background.
Requirements: Python 3.11 or newer, [uv](https://docs.astral.sh/uv/), macOS or Linux.
## Install
```sh
uv tool install git+https://github.com/zsxawerdu/pyrepl-mcp
```
This puts a `pyrepl-mcp` executable in `~/.local/bin` (run `uv tool update-shell` if that is not on your `PATH`). Upgrade with `uv tool upgrade pyrepl-mcp`, remove with `uv tool uninstall pyrepl-mcp`.
From a checkout, `mise run install` (`uv tool install --editable --force .`) installs the same executable but tracks the working tree. To run without installing, use `uvx --from git+https://github.com/zsxawerdu/pyrepl-mcp pyrepl-mcp` or `uv run --project /path/to/pyrepl-mcp pyrepl-mcp`. Do not use `uv run --directory`: it changes the working directory the kernel inherits.
The kernel runs on the server's own interpreter by default. Pass `--python auto` to run cells in the project's virtualenv instead (`$VIRTUAL_ENV`, then `./.venv`), so project packages can be imported. The kernel needs only the standard library; `dill` is needed only for `save()`/`load()`.
## Install with an LLM
Paste this into your coding agent (agy, Claude Code, Codex):
```
Install the pyrepl-mcp MCP server for this CLI by following the "Instructions for LLM agents"
section of https://github.com/zsxawerdu/pyrepl-mcp/blob/main/README.md
```
### Instructions for LLM agents
You are installing `pyrepl-mcp` for the user. Do the steps in order and report what you changed.
1. Check `uv --version`. If uv is missing, stop and ask the user to install it (https://docs.astral.sh/uv/); do not install it yourself.
2. Run `uv tool install git+https://github.com/zsxawerdu/pyrepl-mcp`, then confirm `command -v pyrepl-mcp` prints a path. If it does not, run `uv tool update-shell` and use the absolute path from `uv tool dir --bin` in the next step.
3. Register the server with the CLI you are running in. This edits the user's global config, so tell them which file changes before you do it. Use the command for your host from [Register with a host](#register-with-a-host), and apply that section's timeout setting. Register only the host you are running in unless the user asks for more.
4. Ask the user whether to add the usage rules. If yes, append the contents of [docs/AGENTS-snippet.md](docs/AGENTS-snippet.md) to the project's `AGENTS.md` (Claude Code: `CLAUDE.md`; agy also reads `GEMINI.md`). Do not overwrite existing content.
5. Tell the user to start a new session: hosts launch MCP servers at session start, so the tool is not available in the current one.
6. In the new session, verify with two separate calls: `x = 6*7`, then `print(x)`. The second must print `42`.
Do not use `sudo`, do not install into the project's virtualenv, and do not launch the server with `uv run --directory`.
## Use it
Once registered, start a new session and ask for work in plain language. The model calls the tool itself; naming it helps at first:
```
Use ipython to load every *.log under ./logs into a dict, then tell me which files contain "ERROR".
Now show the ten most common error messages. (reuses the dict, no re-reading)
Run the test suite with bash() in the background and tell me when it finishes.
```
The host's built-in file and shell tools stay available, and the model chooses per step. To make `ipython` the default for bulk reads, log filtering, multi-file edits and long commands, add [docs/AGENTS-snippet.md](docs/AGENTS-snippet.md) to your instruction file (see [below](#teach-the-model-when-to-use-it)). State lasts for the session and survives `/compact`; ask the model to `save()` before quitting, or run with `--restore`, to keep it across sessions.
## Register with a host
The examples assume `pyrepl-mcp` is on your `PATH` (see [Install](#install)). Each snippet raises the host's per-call limit to 660 s, so cells can use `timeout` up to the 600 s `--max-timeout`. See [docs/hosts.md](docs/hosts.md) for the details and their sources.
### Antigravity CLI (`agy`)
```sh
agy mcp add pyrepl pyrepl-mcp
```
This writes `~/.gemini/config/mcp_config.json`. Then edit the entry to raise the timeout (the default is 180 s per call):
```json
{
"mcpServers": {
"pyrepl": {
"command": "pyrepl-mcp",
"timeoutSeconds": 660,
"tools": { "ipython": { "eager": true } }
}
}
}
```
For a single project, put the same JSON in `<workspace>/.agents/mcp_config.json`. The server marks `ipython` with `_meta` `antigravity/alwaysLoad`, so agy loads it eagerly as `mcp_pyrepl_ipython`; `"eager": true` does the same from the config side. A lazy tool would be called through `call_mcp_tool`, with results over 10 KB saved to a file the model must read in an extra step.
### Claude Code
```sh
claude mcp add-json -s user pyrepl '{"type":"stdio","command":"pyrepl-mcp","timeout":660000,"alwaysLoad":true}'
```
Use `-s project` to write `.mcp.json` in the project root (shared, needs one-time approval) or `-s local` for this project only. The short form is `claude mcp add -s user pyrepl -- pyrepl-mcp`. The tool is shown as `mcp__pyrepl__ipython`. `alwaysLoad` in the entry, like the `_meta` `anthropic/alwaysLoad` the server sets on the tool, keeps it out of deferred tool search. Interactive Claude Code moves MCP calls running longer than 120 s into the background (`CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS` changes this).
### Codex CLI
```sh
codex mcp add pyrepl -- pyrepl-mcp
```
Then add the timeouts in `~/.codex/config.toml`. Codex defaults to 60 s per tool call and 10 s for start-up:
```toml
[mcp_servers.pyrepl]
command = "pyrepl-mcp"
tool_timeout_sec = 660
startup_timeout_sec = 30
```
For a single trusted project, use `.codex/config.toml` in the project. The tool is shown as `mcp__pyrepl__ipython`.
### Teach the model when to use it
Paste [docs/AGENTS-snippet.md](docs/AGENTS-snippet.md) into `AGENTS.md`, `GEMINI.md` or `CLAUDE.md`. It tells the model to prefer `ipython` for bulk reads, log filtering, multi-file edits, stateful helpers and long-running commands, and when to keep using the built-in tools. For agy, [docs/hosts.md](docs/hosts.md#hooks) has a `PreToolUse` hook that steers file-reading shell commands to `ipython`.
## Working directory
The kernel starts in the first of:
1. `--cwd DIR`
2. the first `file://` root the host reports, when it supports MCP roots (Claude Code does; agy most likely does)
3. the server's own working directory, which all three hosts set to the directory the CLI was started in
`os.chdir()` inside a cell persists, and `bash()` commands run in the kernel's current directory.
## Flags
| Flag | Env | Default | Meaning |
|---|---|---|---|
| `--python PATH\|auto` | `PYREPL_PYTHON` | server interpreter | interpreter for the kernel; `auto` picks `$VIRTUAL_ENV/bin/python`, then `./.venv/bin/python`, then the server's |
| `--cwd DIR` | `PYREPL_CWD` | see above | kernel working directory |
| `--timeout SECONDS` | `PYREPL_TIMEOUT` | 45 | how long a call waits before the cell detaches; keep it below the host's tool timeout (Codex: 60 s unless raised) and Claude Code's 120 s auto-background |
| `--max-timeout SECONDS` | `PYREPL_MAX_TIMEOUT` | 600 | upper bound for the per-call `timeout` argument |
| `--max-output CHARS` | `PYREPL_MAX_OUTPUT` | 30000 | response cap; one third head, two thirds tail |
| `--restore` | `PYREPL_RESTORE=1` | off | auto-save and auto-restore the namespace per working directory |
| `--restore-ttl SECONDS` | `PYREPL_RESTORE_TTL` | 604800 | ignore auto-snapshots older than this |
| `--state-dir DIR` | `PYREPL_STATE_DIR` | `$XDG_STATE_HOME/pyrepl-mcp` or `~/.local/state/pyrepl-mcp` | where snapshots live |
Flags go after the command in the host config, for example `"args": ["--python", "auto", "--restore"]`.
## The tool
```
ipython(code: str, timeout: float = <--timeout>) -> text
```
Cells behave like IPython: top-level `await` works, and a non-None trailing expression is shown as `Out[N]: ...` and bound to `_`. A traceback is a normal result, not a tool error. Every response ends with a one-line footer listing live names, most recent first:
```
[env: cwd=/work/proj | log: list[40000], errors: list[12], find_flaky(), df: DataFrame(1000, 8), np(module) | bash: 1 running]
```
### Control inputs
| `code` | Effect |
|---|---|
| Python source | run it and wait up to `timeout`; refused (not queued) while another cell is still running |
| `""` (empty) | wait for a running cell and collect its output; when idle, return any uncollected background output, or `[idle]` |
| `%interrupt` | interrupt the running cell (KeyboardInterrupt, or cancellation if it is awaiting) |
| `%restart` | kill the kernel and start a fresh one; all state is lost |
| `%status` | kernel pid, Python, cwd, uptime, running cell, `bash()` jobs; never blocks |
When a cell outlives `timeout`, the call returns what it has so far plus `[cell N still running after Ts — ipython("") waits and collects, ipython("%interrupt") stops it]`. The cell keeps running, and its later output is delivered by the next call. Output from asyncio tasks of finished cells, and raw writes made while the kernel is idle, show up under `[background output]` at the top of the next response. If the kernel dies mid-cell, the response ends with `[kernel died (exit code X) while running cell N: all state is gone; the next call starts a fresh kernel]` and no footer; the next call starts a new kernel and begins with `[kernel restarted (exit code X): previous state is gone]`.
### Helpers
These are injected into the namespace; `help(bash)` and similar work.
| Helper | Behaviour |
|---|---|
| `bash(command, timeout=600)` | start `/bin/bash -c command` in its own process group and return a handle at once |
| `env()` | full, uncapped listing of user names |
| `save(name="default")` | snapshot the namespace to disk with dill and return a report |
| `load(name="default")` | merge a snapshot back into the namespace and return a report |
| `reset()` | delete all user names |
A `bash()` handle offers `.pid`, `.command`, `.running`, `.returncode`, `.timed_out`, `.poll()`, `.tail(n=20)` (never blocks), `.output(timeout=None)` (waits for exit), `.wait(timeout=None)`, `.kill()`, and `await h`. Its repr shows the status and the last ten lines. stdout and stderr are merged, stdin is `/dev/null`, and the command sees the kernel's current `os.getcwd()` and `os.environ`. The first 256 KiB and the last 1 MiB of output are kept. When `timeout` expires, or on `.kill()`, the whole process group gets SIGTERM, then SIGKILL two seconds later. Every group is killed when the kernel or the server shuts down, so dev servers do not outlive the session.
```python
h = bash("pytest -x -q")
h
```
```python
print(h.tail(30)) if h.running else print(h.output()[-3000:])
```
## Persistence
- **Within a host session**: everything persists for as long as the host keeps the server process, which is for the whole CLI session. That includes turns, `/compact` and, in agy and Claude Code, subagents (they share the one kernel). The server is not told about compaction; the `[env: ...]` footer is how the model relearns what it has.
- **Across sessions**: quitting the CLI ends the kernel, and `--resume`/`--continue` starts a fresh one. `save()`/`load()` keep snapshots under `--state-dir`, one directory per working directory. Each variable is pickled separately with dill. Unpicklable or oversized values (more than 64 MiB each, 512 MiB in total) are skipped and listed, and modules are stored as imports. With `--restore`, the namespace is saved automatically on clean shutdown and every five minutes after a cell. It is restored when the next kernel starts in the same directory, if the snapshot is younger than `--restore-ttl`. `%restart` neither saves nor restores.
## Limitations
- **No wake-up.** An MCP server cannot start a model turn. When a detached cell or a `bash()` job finishes, nothing tells the model; it has to call `ipython("")` or check the handle.
- One cell runs at a time. New code sent while a cell runs is refused, not queued.
- No stdin: `input()` sees EOF and `bash()` commands get `/dev/null`. There is no TTY, so interactive programs do not work.
- Output is capped at `--max-output` characters per response (head and tail kept). Print summaries, not whole objects.
- The host's own tool timeout still applies. With a host limit shorter than the call's `timeout` (a model asking for `timeout=300` on Codex at its 60 s default, for example), the host reports a timeout error while the cell keeps running in the kernel. The next `ipython("")` still collects its output.
- Snapshots restore data, not live resources: open files, sockets, threads, running tasks and `bash()` handles are skipped.
- Code runs with your user's full permissions, outside any sandbox the host applies to its own shell tool.
- macOS and Linux only.
TDQS
Scored across 1 tool
There is only one tool, so there is no possibility of selecting the wrong one. The only ambiguity is internal (passing an empty string to collect output, or magic strings like %interrupt/%restart/%status), which is a mode overload inside a single tool rather than a boundary between tools.
With a single tool named 'ipython', there is no inconsistency to speak of, and the name accurately signals a persistent IPython kernel. It does not follow a verb_noun pattern, but nothing else exists to pattern-match against, so the deviation is inconsequential.
For a code-execution server, one entry point is the correct granularity: bash, env, save/load and kernel control are deliberately exposed as in-kernel helpers rather than separate tools, avoiding redundancy. It sits just below the typical 3-15 range, and those helpers are discoverable only via the description rather than as first-class tools.
Arbitrary Python execution plus background bash handles, snapshot save/load, and kernel lifecycle (%interrupt, %restart, %status) cover the realistic workflow with no dead ends. Minor gaps: no way to enumerate or delete saved snapshots, no named sessions or multiple kernels for parallel work, and no explicit per-call timeout parameter surfaced in the tool schema.