Metadata-Version: 2.5
Name: python-session-mcp
Version: 0.1.0
Summary: Run Python in a persistent session, and expose it to LLM clients over MCP
Project-URL: Homepage, https://github.com/merwanroudane/mcp_python
Project-URL: Repository, https://github.com/merwanroudane/mcp_python
Project-URL: Issues, https://github.com/merwanroudane/mcp_python/issues
Author-email: Merwan Roudane <merwanroudane920@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Merwan Roudane
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: data-analysis,jupyter,mcp,model-context-protocol,python,repl
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.10
Requires-Dist: mcp[cli]>=1.2.0
Description-Content-Type: text/markdown

# python-session-mcp

[![Licence](https://img.shields.io/badge/licence-MIT-2c5f9e)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.10+-2c5f9e)](https://www.python.org/)

Run Python in a session that stays alive, and expose it to LLM clients over the
Model Context Protocol.

Author: Dr Merwan Roudane

## What makes it different

**The session persists.** A DataFrame loaded in one call is still there in the
next, so an analysis is built up in steps rather than resent whole each time.

**Your interpreter, not the server's.** The server may well be installed under
a bare Python with no pandas in it. The interpreter that runs your code is
chosen separately: a conda or Anaconda installation is preferred when one is
present, and `PYTHON_MCP_INTERPRETER` overrides that.

**A crash costs one process.** Code runs in a worker, not in the server. Exhaust
memory, call `sys.exit`, crash a C extension — the worker is replaced and the
server carries on. It also keeps user code away from the server's stdin, which
under MCP is the JSON-RPC stream itself.

## Install

```bash
pip install python-session-mcp
```

## Library use

```python
from python_mcp import PythonRunner

with PythonRunner() as py:
    py.run("import pandas as pd, statsmodels.api as sm")
    py.run("df = pd.read_csv('macro.csv')")
    print(py.run("df.describe()"))

    py.run("m = sm.OLS(df['y'], sm.add_constant(df[['x','z']])).fit()")
    print(py.run("m.summary()"))
    print(py.value("m.params.to_dict()"))    # a real Python dict
```

A final expression is shown the way a REPL would, so `df.head()` on its own
displays the frame without `print()`.

## MCP server use

```json
{
  "mcpServers": {
    "python": {
      "command": "python-session-mcp",
      "env": { "PYTHON_MCP_INTERPRETER": "C:\\Users\\you\\anaconda3\\python.exe" }
    }
  }
}
```

### Tools

**Session**

| Tool | Purpose |
|---|---|
| `python_status` | Which interpreter, and which packages it actually has |
| `reset_namespace` | Forget everything, optionally restarting the interpreter |

**Running code**

| Tool | Purpose |
|---|---|
| `run_python` | **Main tool.** Run code in the persistent session |
| `list_names` | What is currently defined |
| `describe_object` | Type, shape, dtypes and a peek at one object |
| `get_value` | Bring a JSON-representable value back |

**Data**

| Tool | Purpose |
|---|---|
| `load_data` | Read `.csv`, `.xlsx`, `.dta`, `.parquet`, `.sav` or `.json` |
| `save_data` | Write a DataFrame out, creating missing folders |
| `preview_data` | Shape, dtypes, missing counts and the first rows |
| `summary_statistics` | Descriptives with skew and kurtosis |
| `correlation` | Pearson, Spearman or Kendall |

**Estimation**

| Tool | Purpose |
|---|---|
| `regression` | OLS, optionally with HC or HAC standard errors |
| `regression_diagnostics` | Breusch-Godfrey, White and Jarque-Bera in one call |
| `unit_root` | ADF or KPSS, differencing until stationary |

**Charts**

| Tool | Purpose |
|---|---|
| `plot` | line, scatter, hist, box or bar — optionally straight to a file |
| `save_figure` | Write the open matplotlib figure to a file |

## Errors

Failures name the exception and the line of *your* code, and leave the session
intact:

```text
Python error: NameError on line 2: name 'undefined_name' is not defined
```

Anything printed before the failure is reported with it, since that output is
often what explains the failure.

## Figures

A plot cannot come back as text. Draw it, then save it:

```python
py.run("import matplotlib; matplotlib.use('Agg')")
py.run("import matplotlib.pyplot as plt; plt.plot(df['x'], df['y'], 'o')")
py.save_figure("figures/scatter.png")     # missing folders are created
```

## Worth knowing

- **The interpreter is separate from the server's.** Check `python_status`
  before relying on a package being there.
- **State is a convenience and a hazard.** Names persist, so a stale variable
  from an earlier step can quietly feed a later one. `reset_namespace` when
  starting something new.
- **`run_python` executes whatever it is given**, in your environment, with
  your file access. That is the point of it, and worth being deliberate about.
- **The final expression is echoed.** A long DataFrame will print in full unless
  you slice it.

## Tests

```bash
python tests/test_live.py     # 41 tests
```

They cover persistence, error reporting with line numbers, JSON round trips,
figure writing, recovery after user code kills the worker outright, and every
data and estimation tool against generated data with known coefficients.

Checked against EViews on the same data, the regression agrees to every printed
digit -- coefficients, R-squared, Durbin-Watson, and the Breusch-Godfrey and
Jarque-Bera statistics alike.

## Licence

MIT. Copyright (c) 2026 Merwan Roudane.
