Metadata-Version: 2.4
Name: py-codemode
Version: 0.1.1
Summary: Code Mode: use LLMs to generate executable code that performs tool calls.
Keywords: llm,code-generation,tool-calling,mcp
Author: Xin
Author-email: Xin <xin@imfing.com>
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.28.1
Requires-Dist: jsrun>=0.1.0
Requires-Dist: mcp>=1.0,<2 ; extra == 'mcp'
Requires-Python: >=3.10
Project-URL: Homepage, https://github.com/imfing/codemode
Project-URL: Repository, https://github.com/imfing/codemode
Project-URL: Issues, https://github.com/imfing/codemode/issues
Provides-Extra: mcp
Description-Content-Type: text/markdown

# codemode

Instead of making tool calls one at a time, let the LLM write code that orchestrates your Python tools in a single, more token-efficient pass.

Codemode runs that code in an in-process V8 isolate via [jsrun](https://github.com/imfing/jsrun). Isolates spin up in under 5ms with the same runtime performance as Node.js, have no network or filesystem access by default, and cannot reach the host except through functions you explicitly provide.

> **Experimental**: this project is in early development

## Install

```bash
pip install py-codemode[mcp]
# or
uv add py-codemode[mcp]
```

For the core executor without MCP: `pip install py-codemode`

## Quick start

Create an MCP server with built-in capabilities and custom tools:

```python
from codemode import EnvCapability, FsCapability, HttpCapability
from codemode.mcp import CodeModeServer

server = CodeModeServer(
    name="example",
    capabilities=[
        EnvCapability(allowed_keys=["USER"]),
        FsCapability(allowed_paths=["./examples"]),
        HttpCapability(allowed_hosts=["httpbin.org"]),
    ],
    enable_search=True,
)


@server.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b


if __name__ == "__main__":
    server.mcp.run(transport="streamable-http")
```

Run with `uv run python examples/mcp_server.py` and connect any MCP client.

The `codemode[mcp]` extra wraps the executor as an MCP server, exposing:

- **`execute`** -- runs JavaScript that calls your Python functions. TypeScript declarations are auto-generated from your type hints and embedded in the tool description so the LLM knows what is callable.
- **`search`** (optional, via `enable_search=True`) -- searches registered capabilities and tools by name or description.

## How it works

```
┌─────────────────────┐         ┌──────────────────────┐
│  V8 isolate (jsrun) │         │  Python host         │
│                     │         │                      │
│  LLM-generated JS   │         │  Executor            │
│  runs in async IIFE │         │                      │
│                     │  bridge │                      │
│  codemode.fn({...}) ├────────►│  _dispatch()         │
│                     │◄────────┤  -> your_fn(**kwargs)│
│                     │  result │                      │
└─────────────────────┘         └──────────────────────┘
```

The executor wraps your code in a harness that captures console output and sets up a `codemode` proxy object. The proxy intercepts every `codemode.*()` call, serializes it to JSON, and bridges back to Python where `_dispatch()` routes it to the matching host function. The MCP server uses `Executor` under the hood.

## Host functions

Host functions use keyword-only parameters with type hints:

```python
async def read(*, path: str) -> str:
    return open(path).read()
```

Called from JavaScript as `await codemode.read({ path: "/tmp/f" })`. The type hints are used to generate TypeScript stubs (`str` becomes `string`, `int/float` becomes `number`, `list[T]` becomes `T[]`, etc.).

## Built-in capabilities

Capabilities are namespaced host functions with allowlist-based security. The sandbox has no filesystem, network, or environment access by default.

| Capability | Namespace | Description |
|---|---|---|
| `FsCapability(allowed_paths=[...])` | `codemode.fs` | Sandboxed read/write within allowed paths |
| `EnvCapability(allowed_keys=[...])` | `codemode.env` | Read environment variables from an allowlist |
| `HttpCapability(allowed_hosts=[...])` | `codemode.http` | HTTP requests to allowed hosts only |

## Limitations

- V8 runtime, not Node, so no Node built-in modules. JavaScript only.
- No top-level `import` or `require` in sandbox code

## Advanced

For step-by-step control over host calls, use the session API directly:

```python
import asyncio
from codemode import Executor, HostCallRequest, RunCompleted, RunFailed

async def main():
    executor = Executor(timeout_s=5)
    session = await executor.start("""
        async () => {
          const a = await codemode.double({ n: 3 });
          const b = await codemode.double({ n: a });
          return b;
        }
    """)

    while True:
        event = await session.next_event()
        if isinstance(event, HostCallRequest):
            result = event.input["n"] * 2
            await session.submit_result(event.call_id, result)
        elif isinstance(event, (RunCompleted, RunFailed)):
            break

    await session.cancel()
    executor.close()

asyncio.run(main())
```

This gives you full control over each host call, useful for logging, approval flows, or routing to external services.

jsrun also supports loading additional JavaScript libraries into the isolate via `Runtime.add_static_module()` or custom module loaders, V8 heap snapshots for faster cold starts, heap size limits, and per-call execution timeouts. See the [jsrun documentation](https://github.com/imfing/jsrun) for details.

## Further reading

- [jsrun](https://github.com/imfing/jsrun) -- the V8 isolate runtime that powers codemode
- [src/codemode](https://github.com/imfing/codemode/tree/main/src/codemode) -- executor, capabilities, and stub generation source
- [src/codemode/mcp](https://github.com/imfing/codemode/tree/main/src/codemode/mcp) -- MCP server and registry source
- [examples/](https://github.com/imfing/codemode/tree/main/examples) -- runnable examples

## License

MIT
