Metadata-Version: 2.4
Name: python-repl-mcp
Version: 0.3.0
Summary: Persistent Python REPL MCP server with explicit, UID-addressed sessions
License-Expression: MIT
Keywords: mcp,model context protocol,repl,python,agent,opencode
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Win32 (MS Windows)
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Interpreters
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)
[![PyPI](https://img.shields.io/pypi/v/python-repl-mcp?label=PyPI&logo=pypi&logoColor=white)](https://pypi.org/project/python-repl-mcp/)
[![Python versions](https://img.shields.io/pypi/pyversions/python-repl-mcp?logo=python&logoColor=white)](https://pypi.org/project/python-repl-mcp/)
[![Status](https://img.shields.io/pypi/status/python-repl-mcp)](https://pypi.org/project/python-repl-mcp/)
[![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
explicit session**. State, imports and helpers survive between tool calls that
name the same session. Connecting to the server does not start a worker:
`repl_open_session` starts one and returns the opaque `session_uid` that every
other tool must pass.

This page describes the **0.3.0** explicit-session API. The candidate is
vetted locally before publication. [HANDOFF.md](HANDOFF.md) and
[HANDOFF-test-report.md](HANDOFF-test-report.md) are historical 0.2.6-era
evidence and document the removed per-chat routing.

## Tools

| Tool | Purpose |
|---|---|
| `repl_open_session(workdir)` | Start a ready interpreter in an existing absolute directory; returns `session_uid`, `workdir` and `kernel_id`. |
| `repl_execute(session_uid, code, timeout_seconds=30)` | Run one complete Python cell in that session; returns `stdout`, `stderr`, the final value, and a structured error report. |
| `repl_run_file(session_uid, file_path, args=[], timeout_seconds=30)` | Run a `.py` file in the same persistent namespace with `__file__` and `sys.argv`; relative paths resolve against the directory the session was opened with. |
| `repl_reset(session_uid)` | Replace that session's interpreter with a clean one; the UID and bound directory stay the same. |
| `repl_stop(session_uid)` | End that session's interpreter; the UID becomes invalid. |

## Session model

One stdio flow works for every host; no host metadata is required.

1. Call `repl_open_session` with an existing absolute directory. Each call mints
   a new 128-bit `secrets.token_urlsafe(16)` UID and starts a ready worker with
   that directory as its cwd. Two opens of the same absolute folder are two
   independent interpreters with the same cwd, never one shared worker.
2. Keep the UID in the chat's own context and pass it as `session_uid` to every
   later call. There is no chat key, `_meta` field, environment variable,
   default session or "pick a chat" argument; the UID is the only selector.
3. `repl_reset` keeps the UID and the bound directory but replaces the kernel,
   so the namespace is clean and relative paths keep resolving the same way.
4. `repl_stop` retires the UID once the worker exit is confirmed. Idle expiry,
   a cell timeout, worker death and a fatal protocol fault also retire it.
5. An empty, unknown, stopped or expired UID gets the same tool error:
   `InvalidSession: Open a session with repl_open_session first.` The reply never
   echoes the UID.
6. If the chat loses the UID (compaction, restart), open a new session for a
   clean interpreter. The server writes no UID files and no host environment
   variable holds one.
7. A UID is valid only while its stdio dispatcher process lives. If the host
   restarts the dispatcher, old UIDs are invalid. A host that keeps one
   dispatcher alive across a chat restart keeps old UIDs valid until stop, idle
   expiry or worker loss; the client should still discard handles and open anew.
8. A dispatcher owns at most 16 live sessions by default; `repl_stop` frees a
   slot. `PYTHON_REPL_MCP_IDLE_TIMEOUT` sets the idle window in seconds
   (default `1800`); `0` explicitly disables idle expiry. The window starts as
   soon as a worker is ready, even before its first cell. Rejected calls do
   not extend it, and an executing cell is not idle.

## 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_IDLE_TIMEOUT`, in seconds: default `1800`, `0` disables.

## Install and run

For candidate testing, install the local **0.3.0 wheel** in a disposable
environment. Published `0.2.6` artifacts use the previous per-chat API.

```powershell
uv venv --python C:\Z\python\python.exe <candidate-venv>
uv pip install --python <candidate-venv>\Scripts\python.exe <candidate-wheel>
```

See [native host acceptance](docs/host-compatibility.md) for the DSH and
Command Code smoke tests. The dispatcher and its workers use the interpreter
selected in the host entry.

Configure the host to launch the interpreter used to install the package. Replace
the example paths with their absolute values. The server speaks MCP over
stdin/stdout only. OpenCode v2.4.2 uses the `mcp.servers.<name>` shape; keep the
entry `disabled: true` and connect it explicitly so no dispatcher starts when a
project opens:

```json
{
  "mcp": {
    "servers": {
      "python-repl": {
        "type": "local",
        "protocol": "2026-07-28",
        "pool": true,
        "disabled": true,
        "command": ["<candidate-venv>/Scripts/python.exe", "-P", "-B", "-m", "python_repl_mcp.server"],
        "environment": {
          "PYTHONNOUSERSITE": "1"
        },
        "cwd": "<dispatcher-directory>"
      }
    }
  }
}
```

Keep `disabled: true` and connect the registered entry when the project needs
Python: `POST /api/experimental/mcp/python-repl/connect` for that location. Until
Connect, the `python-repl` tools are absent from the agent catalog. With
`pool: true` and identical entries, connected locations share one dispatcher
process; each chat still opens its own UID-addressed session, so no metadata or
per-chat process is needed.

DSH and Command Code call the same five tools over stdio and need no metadata
field. The agent itself carries the returned UID between turns.

## 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 session's
  bound directory. `repl_open_session` also returns the `session_uid`. These
  fields are optional and appear only when meaningful.
- The interpreter starts in the session's bound directory; an intentional
  `os.chdir()` changes its cwd for subsequent cells. `repl_run_file`
  resolves an ordinary relative path against the bound directory and rejects a
  Windows drive-relative (`C:script.py`) or root-relative path as ambiguous. It
  restores the previous `__file__`/`sys.argv` after the script. File and
  argument size are checked before dispatch, 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`. Files written by a script
  (for example a matplotlib PNG) remain on disk.
- `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, a timeout or a fatal protocol error, the server frees the slot
  once it confirms the worker tree has exited, and the old UID is invalid. A
  capture directory that was locked at that moment is retried once by the next
  acknowledged `repl_stop` (of any live session) or by normal shutdown; a
  still-locked 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 and retires the UID; open a new
  session for a clean interpreter.
- A timeout terminates the whole worker process tree (Windows Job Object), loses
  in-memory state and retires the UID.
- At most 16 sessions 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).
