|
| 1 | +# MCP Run Python |
| 2 | + |
| 3 | +The **MCP Run Python** package is an MCP server that allows agents to execute Python code in a secure, sandboxed environment. It uses [Pyodide](https://pyodide.org/) to run Python code in a JavaScript environment, isolating execution from the host system. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +* **Secure Execution**: Run Python code in a sandboxed WebAssembly environment |
| 8 | +* **Package Management**: Automatically detects and installs required dependencies |
| 9 | +* **Complete Results**: Captures standard output, standard error, and return values |
| 10 | +* **Asynchronous Support**: Runs async code properly |
| 11 | +* **Error Handling**: Provides detailed error reports for debugging |
| 12 | + |
| 13 | +## Installation |
| 14 | + |
| 15 | +The MCP Run Python server is distributed as an [NPM package](https://www.npmjs.com/package/@pydantic/mcp-run-python) and can be run directly using [`npx`](https://docs.npmjs.com/cli/v8/commands/npx): |
| 16 | + |
| 17 | +```bash |
| 18 | +npx @pydantic/mcp-run-python [stdio|sse] |
| 19 | +``` |
| 20 | + |
| 21 | +Where: |
| 22 | + |
| 23 | +* `stdio`: Runs the server with [stdin/stdout transport](https://modelcontextprotocol.io/docs/concepts/transports#standard-input%2Foutput-stdio) (for subprocess usage) |
| 24 | +* `sse`: Runs the server with [HTTP Server-Sent Events transport](https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse) (for remote connections) |
| 25 | + |
| 26 | +Usage of `@pydantic/mcp-run-python` with PydanticAI is described in the [client](client.md#mcp-stdio-server) documentation. |
| 27 | + |
| 28 | +## Direct Usage |
| 29 | + |
| 30 | +As well as using this server with PydanticAI, it can be connected to other MCP clients. For clarity, in this example we connect directly using the [Python MCP client](https://github.com/modelcontextprotocol/python-sdk). |
| 31 | + |
| 32 | +```python {title="mcp_run_python.py" py="3.10"} |
| 33 | +from mcp import ClientSession, StdioServerParameters |
| 34 | +from mcp.client.stdio import stdio_client |
| 35 | + |
| 36 | +code = """ |
| 37 | +import numpy |
| 38 | +a = numpy.array([1, 2, 3]) |
| 39 | +print(a) |
| 40 | +a |
| 41 | +""" |
| 42 | + |
| 43 | + |
| 44 | +async def main(): |
| 45 | + server_params = StdioServerParameters( |
| 46 | + command='npx', args=['-y', '@pydantic/mcp-run-python', 'stdio'] |
| 47 | + ) |
| 48 | + async with stdio_client(server_params) as (read, write): |
| 49 | + async with ClientSession(read, write) as session: |
| 50 | + await session.initialize() |
| 51 | + tools = await session.list_tools() |
| 52 | + print(len(tools.tools)) |
| 53 | + #> 1 |
| 54 | + print(repr(tools.tools[0].name)) |
| 55 | + #> 'run_python_code' |
| 56 | + print(repr(tools.tools[0].inputSchema)) |
| 57 | + """ |
| 58 | + {'type': 'object', 'properties': {'python_code': {'type': 'string', 'description': 'Python code to run'}}, 'required': ['python_code'], 'additionalProperties': False, '$schema': 'http://json-schema.org/draft-07/schema#'} |
| 59 | + """ |
| 60 | + result = await session.call_tool('run_python_code', {'python_code': code}) |
| 61 | + print(result.content[0].text) |
| 62 | + """ |
| 63 | + <status>success</status> |
| 64 | + <dependencies>["numpy"]</dependencies> |
| 65 | + <output> |
| 66 | + [1 2 3] |
| 67 | + </output> |
| 68 | + <return_value> |
| 69 | + [ |
| 70 | + 1, |
| 71 | + 2, |
| 72 | + 3 |
| 73 | + ] |
| 74 | + </return_value> |
| 75 | + """ |
| 76 | +``` |
| 77 | + |
| 78 | +## Dependencies |
| 79 | + |
| 80 | +Dependencies are installed when code is run. |
| 81 | + |
| 82 | +Dependencies can be defined in one of two ways: |
| 83 | + |
| 84 | +### Inferred from imports |
| 85 | + |
| 86 | +If there's no metadata, dependencies are inferred from imports in the code, |
| 87 | +as shown in the example [above](#direct-usage). |
| 88 | + |
| 89 | +### Inline script metadata |
| 90 | + |
| 91 | +As introduced in PEP 723, explained [here](https://packaging.python.org/en/latest/specifications/inline-script-metadata/#inline-script-metadata), and popularized by [uv](https://docs.astral.sh/uv/guides/scripts/#declaring-script-dependencies) — dependencies can be defined in a comment at the top of the file. |
| 92 | + |
| 93 | +This allows use of dependencies that aren't imported in the code, and is more explicit. |
| 94 | + |
| 95 | +```py {title="inline_script_metadata.py" py="3.10"} |
| 96 | +from mcp import ClientSession, StdioServerParameters |
| 97 | +from mcp.client.stdio import stdio_client |
| 98 | + |
| 99 | +code = """\ |
| 100 | +# /// script |
| 101 | +# dependencies = ["pydantic", "email-validator"] |
| 102 | +# /// |
| 103 | +import pydantic |
| 104 | +
|
| 105 | +class Model(pydantic.BaseModel): |
| 106 | + email: pydantic.EmailStr |
| 107 | +
|
| 108 | +print(Model(email='[email protected]')) |
| 109 | +""" |
| 110 | + |
| 111 | + |
| 112 | +async def main(): |
| 113 | + server_params = StdioServerParameters( |
| 114 | + command='npx', args=['-y', '@pydantic/mcp-run-python', 'stdio'] |
| 115 | + ) |
| 116 | + async with stdio_client(server_params) as (read, write): |
| 117 | + async with ClientSession(read, write) as session: |
| 118 | + await session.initialize() |
| 119 | + result = await session.call_tool('run_python_code', {'python_code': code}) |
| 120 | + print(result.content[0].text) |
| 121 | + """ |
| 122 | + <status>success</status> |
| 123 | + <dependencies>["pydantic","email-validator"]</dependencies> |
| 124 | + <output> |
| 125 | + |
| 126 | + </output> |
| 127 | + """ |
| 128 | +``` |
| 129 | + |
| 130 | +It also allows versions to be pinned for non-binary packages (Pyodide only supports a single version for the binary packages it supports, like `pydantic` and `numpy`). |
| 131 | + |
| 132 | +E.g. you could set the dependencies to |
| 133 | + |
| 134 | +```python |
| 135 | +# /// script |
| 136 | +# dependencies = ["rich<13"] |
| 137 | +# /// |
| 138 | +``` |
| 139 | + |
| 140 | +## Logging |
| 141 | + |
| 142 | +MCP Run Python supports emitting stdout and stderr from the python execution as [MCP logging messages](https://github.com/modelcontextprotocol/specification/blob/eb4abdf2bb91e0d5afd94510741eadd416982350/docs/specification/draft/server/utilities/logging.md?plain=1). |
| 143 | + |
| 144 | +For logs to be emitted you must set the logging level when connecting to the server. By default, the log level is set to the highest level, `emergency`. |
| 145 | + |
| 146 | +Currently, it's not possible to demonstrate this due to a bug in the Python MCP Client, see [modelcontextprotocol/python-sdk#201](https://github.com/modelcontextprotocol/python-sdk/issues/201#issuecomment-2727663121). |
0 commit comments