|
| 1 | +import ast |
| 2 | +import inspect |
| 3 | +from collections.abc import Awaitable, Sequence |
| 4 | +from typing import Any, Callable, Literal |
| 5 | + |
| 6 | +from .mcp import MCPServerStdio |
| 7 | + |
| 8 | +__all__ = ('mcp_run_python_stdio',) |
| 9 | + |
| 10 | +MCP_RUN_PYTHON_VERSION = '0.0.13' |
| 11 | +Callback = Callable[..., Awaitable[Any]] |
| 12 | + |
| 13 | + |
| 14 | +def mcp_run_python_stdio(callbacks: Sequence[Callback] = (), *, local_code: bool = False) -> MCPServerStdio: |
| 15 | + """Prepare a server server connection using `'stdio'` transport. |
| 16 | +
|
| 17 | + Args: |
| 18 | + callbacks: A sequence of callback functions to be register on the server. |
| 19 | + local_code: Whether to run local `mcp-run-python` code. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + A server connection definition. |
| 23 | + """ |
| 24 | + return MCPServerStdio('deno', args=_deno_args('stdio', callbacks, local_code)) |
| 25 | + |
| 26 | + |
| 27 | +def _deno_args(mode: Literal['stdio', 'sse'], callbacks: Sequence[Callback], local_code: bool) -> list[str]: |
| 28 | + path_prefix = 'mcp-run-python/' if local_code else '' |
| 29 | + args = [ |
| 30 | + 'run', |
| 31 | + '-N', |
| 32 | + f'-R={path_prefix}node_modules', |
| 33 | + f'-W={path_prefix}node_modules', |
| 34 | + '--node-modules-dir=auto', |
| 35 | + 'mcp-run-python/src/main.ts' if local_code else f'jsr:@pydantic/mcp-run-python@{MCP_RUN_PYTHON_VERSION}', |
| 36 | + mode, |
| 37 | + ] |
| 38 | + |
| 39 | + if callbacks: |
| 40 | + sigs = '\n\n'.join(_callback_signature(cb) for cb in callbacks) |
| 41 | + args += ['--callbacks', sigs] |
| 42 | + return args |
| 43 | + |
| 44 | + |
| 45 | +def _callback_signature(func: Callback) -> str: |
| 46 | + """Extract the signature of a function. |
| 47 | +
|
| 48 | + This simply means getting the source code of the function, and removing the body of the function while keeping the docstring. |
| 49 | + """ |
| 50 | + source = inspect.getsource(func) |
| 51 | + ast_mod = ast.parse(source) |
| 52 | + assert isinstance(ast_mod, ast.Module), f'Expected Module, got {type(ast_mod)}' |
| 53 | + assert len(ast_mod.body) == 1, f'Expected single function definition, got {len(ast_mod.body)}' |
| 54 | + f = ast_mod.body[0] |
| 55 | + assert isinstance(f, ast.AsyncFunctionDef), f'Expected an async function, got {type(func)}' |
| 56 | + lines = lines = source.splitlines() |
| 57 | + e = f.body[0] |
| 58 | + # if the first expression is a docstring, keep it and no need for an ellipsis as the body |
| 59 | + if isinstance(e, ast.Expr) and isinstance(e.value, ast.Constant) and isinstance(e.value.value, str): |
| 60 | + e = f.body[1] |
| 61 | + lines = lines[: e.lineno - 1] |
| 62 | + else: |
| 63 | + lines = lines[: e.lineno - 1] |
| 64 | + lines.append(e.col_offset * ' ' + '...') |
| 65 | + return '\n'.join(lines) |
0 commit comments