Skip to main content

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. 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

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:

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:

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:

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 for details.

Further reading

License

MIT

Metadata

Release files for py-codemode 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for py-codemode 0.1.1
File Size Uploaded
py_codemode-0.1.1.tar.gz 11.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for py-codemode 0.1.1
File Interpreter ABI Platform
py_codemode-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 25.8 kB

Release files / py_codemode-0.1.1.tar.gz

Download URL py_codemode-0.1.1.tar.gz
Size 11.0 kB
Tags Source
SHA-256 checksum
How to use checksums
910fda43c87a2c9a6f8e26dd1c4b9defea8681fe9ee0973dfb82e49292d19933
BLAKE2b-256 checksum
How to use checksums
aa723d9cd3679415864dcb1ad94796d48902cadc5658e477f4be788cbe24ce1e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 23, 2026.

Transparency log

Release files / py_codemode-0.1.1-py3-none-any.whl

Download URL py_codemode-0.1.1-py3-none-any.whl
Size 14.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
84c1c7385dad6fb2cbedea4bb32324468103bd4dcf7bbe8f1cb4f666b7b91006
BLAKE2b-256 checksum
How to use checksums
fdf4b25633df4ab586f63d2b016f5d7c530108fe8086324a3690e9b63f32601c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 23, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page