Metadata-Version: 2.4
Name: python-repl-mcp
Version: 0.2.5
Summary: Persistent Python REPL MCP server for OpenCode chats
License-Expression: MIT
Requires-Python: >=3.14
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mcp==2.3.0
Requires-Dist: pydantic<3,>=2.14
Provides-Extra: dev
Requires-Dist: bandit>=1.9; extra == "dev"
Requires-Dist: hypothesis>=6.170; extra == "dev"
Requires-Dist: mypy>=2.4; extra == "dev"
Requires-Dist: pip-audit>=2.10; extra == "dev"
Requires-Dist: psutil>=7.2; extra == "dev"
Requires-Dist: pytest>=9.2; extra == "dev"
Requires-Dist: pytest-cov>=7.1; extra == "dev"
Requires-Dist: pyright>=1.1; extra == "dev"
Requires-Dist: ruff>=0.17; extra == "dev"
Dynamic: license-file

# python-repl-mcp

[![CI](https://github.com/magicprinc/python-mcp/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/magicprinc/python-mcp/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/release/magicprinc/python-mcp?sort=semver)](https://github.com/magicprinc/python-mcp/releases)
[![Python](https://img.shields.io/badge/python-3.14%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![Platform](https://img.shields.io/badge/platform-Windows-0078D4?logo=windows&logoColor=white)](https://www.microsoft.com/windows)
[![MCP](https://img.shields.io/badge/MCP-stdio-6E56CF)](https://modelcontextprotocol.io/)
[![License](https://img.shields.io/github/license/magicprinc/python-mcp)](LICENSE)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=magicprinc_python-mcp&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=magicprinc_python-mcp)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/magicprinc/python-mcp/badge)](https://scorecard.dev/viewer/?uri=github.com/magicprinc/python-mcp)

A Windows MCP stdio server that keeps **one persistent CPython interpreter per
OpenCode chat**. State, imports and helpers survive between tool calls.
Connecting to the server does not start a worker.

For another agent, start with [HANDOFF.md](HANDOFF.md): install, OpenCode
configuration, tool rules and known limits. The
[local completion plan](docs/completion-plan.md) tracks the remaining fixes
and acceptance on OpenCode, DSH and Command Code.

## Tools

| Tool | Purpose |
|---|---|
| `repl_execute(code, timeout_seconds=30)` | Run one complete Python cell; returns `stdout`, `stderr`, the final value, and a structured error report. |
| `repl_run_file(file_path, args=[], timeout_seconds=30)` | Run a `.py` file in the same persistent namespace with `__file__` and `sys.argv`; useful for AtlaWire workflows and scripts that save plots to disk. |
| `repl_reset()` | End the chat's interpreter and wait for a clean replacement to be ready. |
| `repl_stop()` | End the chat's interpreter without replacement. |

Standalone session resolution: OpenCode's `_meta["ai.opencode/sessionID"]` when present;
otherwise `PYTHON_REPL_MCP_SESSION`; otherwise the per-process `"default"` key.
There is no session tool argument. On a host without per-call metadata,
run one server process per chat to isolate state. An environment variable is
fixed for the lifetime of a process and cannot distinguish chats sharing it.

## Requirements

- Windows 10/11, CPython 3.14.x (verified on 3.14.10), and `uv`.
- Use the interpreter or venv that launches the server; its site-packages are available to executed cells. User-site imports are available only when enabled.
- Optional `PYTHON_REPL_MCP_SESSION` for hosts that do not send OpenCode
  metadata.

## Install and run

`uv` is the standard installer.

```powershell
uv venv --python 3.14 .venv
uv pip install --python .\.venv\Scripts\python.exe .
.\.venv\Scripts\python.exe -P -m python_repl_mcp.server
```

On this machine the local agents share `C:\Z\py\.venv`; install the wheel
there with `uv pip install --python C:\Z\py\.venv\Scripts\python.exe <wheel>`.
The dispatcher and workers then use that venv's site-packages for cells.

Configure OpenCode to launch the interpreter used to install the package. Replace
the example path with its absolute path. The server speaks MCP over stdin/stdout
only. Verified against OpenCode v2.4.2's
`mcp.servers.<name>` shape:

```json
{
  "mcp": {
    "servers": {
      "python-repl": {
        "type": "local",
        "protocol": "2026-07-28",
        "command": ["D:/work/my-project/.venv/Scripts/python.exe", "-P", "-m", "python_repl_mcp.server"],
        "environment": {
          "PYTHON_REPL_MCP_WORKDIR": "D:/work/my-project"
        }
      }
    }
  }
}
```

For calls made on behalf of a chat, OpenCode supplies
`_meta["ai.opencode/sessionID"]`. A host that starts a separate server for each
chat can use the `"default"` key without setting `PYTHON_REPL_MCP_SESSION`.

In standalone mode, `PYTHON_REPL_MCP_WORKDIR` selects the working directory for executed cells
(defaults to the server's current directory). The server's `PYTHONPATH` is
prepended with the installed package path for the worker; the worker uses the
server interpreter and its site-packages, with user-site enabled only when the
environment allows it.

### Share one server across OpenCode projects

For a local authenticated OpenCode 2.4.3 service, use the same entry, command,
environment and absolute `cwd` in each project. With `pool: true` and identical
entries, connected locations share **one** dispatcher process; each chat still
gets its own worker on first use. The verified setup uses OpenCode's
[runtime API](https://opencode.ai/docs/api): register `python-repl` in each
location with `PUT /api/experimental/mcp/python-repl`, wrapping the following
entry in `{"config": ...}`.

```json
{
  "type": "local",
  "protocol": "2026-07-28",
  "pool": true,
  "disabled": true,
  "codemode": false,
  "cwd": "D:/repl-dispatcher",
  "command": ["D:/repl-dispatcher/.venv/Scripts/python.exe", "-P", "-B", "-m", "python_repl_mcp.server"],
  "environment": {
    "PYTHONNOUSERSITE": "1",
    "PYTHON_REPL_MCP_OPENCODE_SERVER": "http://127.0.0.1:4321",
    "PYTHON_REPL_MCP_OPENCODE_CLI": "C:/path/to/native/opencode.exe"
  }
}
```

Use `"auto"` for the desktop background service: the native CLI discovers the
running service, so the dispatcher does not depend on an ephemeral port after a
restart. For an explicit endpoint, use the actual loopback address of the
owning service; that mode requires the dispatcher to inherit the service's
`OPENCODE_PASSWORD`. In both modes the credential is excluded from the worker
environment. Keep `disabled: true` and connect the registered entry when the
project needs Python: `POST /api/experimental/mcp/python-repl/connect` for that
location. This avoids starting the dispatcher at project open; until Connect,
the `python-repl` tools are absent from the agent catalog, so tell the agent to
use them only after the explicit connection.

```json
{
  "environment": {
    "PYTHONNOUSERSITE": "1",
    "PYTHON_REPL_MCP_OPENCODE_SERVER": "auto",
    "PYTHON_REPL_MCP_OPENCODE_CLI": "C:/path/to/native/opencode.exe"
  }
}
```

In pooled mode each request needs OpenCode's chat metadata. The first
execution (or explicit reset) binds the worker to the chat directory returned
by OpenCode. That binding also governs relative `repl_run_file` paths until the
worker is replaced, even if a cell calls `os.chdir()`. A drive-relative path
such as `C:script.py` is rejected as ambiguous; use a path relative to the chat
directory or a fully qualified one. A failed lookup returns
`SessionDirectoryUnavailable`. `repl_stop()` ends only the calling chat's
worker; disconnect the MCP entry only when you intend to close the connection.
If a directory helper cannot confirm its own exit after termination, further
pooled lookups are refused until the MCP server restarts; running chats and
`repl_stop()` keep working, while new chats and `repl_reset()` are refused.

## Behaviour and limits

- `input()` and `getpass()` return a structured `InputRequired` report. Ask in
  chat only for non-secret input. Use an approved local mechanism for secrets;
  do not put them in chat, Python cells or tool arguments.
- `repl_execute` returns the final expression's `result` as a bounded repr.
  `result_type` names the value's type, `result_json` carries the parsed JSON
  value when the result is JSON-serialisable, and `result_truncated` marks a
  capped repr. `kernel_id` identifies the worker; `workdir` is the chat's bound
  directory. These fields are optional and appear only when meaningful.
- `repl_run_file` resolves relative paths against the worker's bound workdir and
  restores the previous `__file__`/`sys.argv` after the script. File and argument
  size are checked before a worker starts, with a private frame cap of 2 MiB
  including overhead. The read runs in a short-lived isolated interpreter under
  the 15 s startup budget; expiry is a `FileError` and starts no worker. Files
  written by a script (for example a matplotlib PNG) remain on disk and can be
  opened by the host's browser.
- `stdout`/`stderr` are captured per cell, bounded to 16,384 characters each;
  `truncated` reports a cut snapshot, and `capture_complete=false` reports
  unavailable output or unconfirmed cleanup of an interrupted cell. Worker stdio
  is UTF-8. Disk use by a surviving child process is not capped.
- After idle exit or a fatal idle protocol error, the server frees the slot
  once it confirms the worker tree has exited. A capture directory that was
  locked at that moment is retried once by the next `repl_stop` (even for an
  absent chat) or by normal shutdown; a still-locked or overflow path is
  logged and dropped.
- An uncaught Python exception is a normal execution report; it does not kill
  the interpreter. `os._exit()` kills the worker; the next call starts clean.
- A timeout terminates the whole worker process tree (Windows Job Object) and
  loses in-memory state.
- At most 16 chats are owned at once; release one with `repl_stop`.
- Worker startup hooks must be quiet on stdout. Noisy startup output fails
  closed.

## Tests

```powershell
$env:PYTHONPATH = "src"
python -m pytest
python -m ruff check src tests
python -m pyright
```


## References

- [MCP-сервер проверки и запуска кода на Python](https://habr.com/ru/articles/967042/)
  — summary and design notes in [docs/references.md](docs/references.md).
