Skip to content

Python API

The main entry point is CodeMode. Most applications only need from_config, tools(), call() and usage(). See Python library & LLMs for worked examples.

CodeMode

codemode_mcp.CodeMode

Expose any number of MCP servers to an LLM through two small tools.

Example::

async with CodeMode.from_config("mcp.json") as cm:
    tools = cm.tools(format="openai")
    ...  # give `tools` to your LLM, then for each tool call:
    output = await cm.call(name, arguments)

system_prompt property

system_prompt: str

Optional short system-prompt addendum that nudges models toward efficient use.

from_config classmethod

from_config(
    path: str | PathLike[str] | dict[str, Any],
    *,
    approval_callback: Approver | None = None,
    usage_store: UsageStore | None = None,
    **settings: Any,
) -> CodeMode

from_servers classmethod

from_servers(
    servers: dict[str, dict[str, Any]],
    *,
    approval_callback: Approver | None = None,
    usage_store: UsageStore | None = None,
    **settings: Any,
) -> CodeMode

Build from an mcpServers-style mapping without a config file.

start async

start() -> CodeMode

close async

close() -> None

tools

tools(format: str = 'openai') -> list[dict[str, Any]]

Tool definitions in a provider's format: openai, openai-responses, anthropic or mcp.

tool_definitions

tool_definitions() -> list[dict[str, Any]]

Provider-neutral definitions: name, description, input_schema.

call async

call(
    name: str,
    arguments: dict[str, Any] | str | None,
    *,
    approver: Approver | None = None,
) -> str

Execute one of the exposed tools and return text for the LLM.

run_code async

run_code(
    code: str, *, approver: Approver | None = None
) -> str

search_tools

search_tools(query: str, limit: int | None = None) -> str

call_direct async

call_direct(
    name: str,
    arguments: dict[str, Any],
    *,
    approver: Approver | None = None,
) -> types.CallToolResult

Call a hybrid-mode (directly exposed) tool, returning the raw MCP result.

reset_state async

reset_state() -> None

Forget variables kept by persistent_state.

handle_openai_tool_call async

handle_openai_tool_call(tool_call: Any) -> dict[str, Any]

Run an OpenAI Chat Completions tool_call and return the role=tool message.

handle_anthropic_tool_use async

handle_anthropic_tool_use(block: Any) -> dict[str, Any]

Run an Anthropic tool_use content block and return the tool_result block.

usage

usage() -> dict[str, Any]

Token accounting for this CodeMode instance (since start).

stats

stats() -> dict[str, Any]

Context cost of tool definitions per LLM request: classic MCP vs Code Mode.

record_llm_usage

record_llm_usage(
    model: str,
    input_tokens: int,
    output_tokens: int,
    **details: Any,
) -> None

Log provider-reported token usage of one LLM request (shown as measured data).

Agent loops

codemode_mcp.agent.run_openai async

run_openai(
    cm: CodeMode,
    prompt: str,
    *,
    model: str,
    client: Any = None,
    base_url: str | None = None,
    api_key: str | None = None,
    system: str | None = None,
    max_turns: int = 12,
    on_event: Callable[[str, Any], None] | None = None,
    record_usage: bool = True,
    keep_state: bool = True,
) -> AgentResult

Run a tool-calling loop against any OpenAI-compatible Chat Completions API (OpenAI, Azure, GitHub Models, OpenRouter, Ollama, vLLM, LM Studio, ...).

codemode_mcp.agent.run_anthropic async

run_anthropic(
    cm: CodeMode,
    prompt: str,
    *,
    model: str,
    client: Any = None,
    api_key: str | None = None,
    system: str | None = None,
    max_turns: int = 12,
    max_tokens: int = 4096,
    on_event: Callable[[str, Any], None] | None = None,
    record_usage: bool = True,
    keep_state: bool = True,
) -> AgentResult

Run a tool-calling loop against the Anthropic Messages API.

codemode_mcp.agent.AgentResult dataclass

cached_tokens class-attribute instance-attribute

cached_tokens: int = 0

Input tokens the provider served from its prompt cache (a subset of input_tokens).

Benchmarks

codemode_mcp.benchmark.run_benchmark async

run_benchmark(
    cm: CodeMode,
    prompt: str,
    *,
    model: str,
    provider: str = "openai",
    client: Any = None,
    base_url: str | None = None,
    api_key: str | None = None,
    max_turns: int = 25,
) -> BenchmarkResult

codemode_mcp.benchmark.BenchmarkResult dataclass

Configuration

codemode_mcp.Config dataclass

codemode_mcp.ServerConfig dataclass

One upstream MCP server.

oauth class-attribute instance-attribute

oauth: dict[str, Any] | None = None

OAuth 2.1 for remote servers: true or {"client_id", "client_secret", "scopes", "redirect_port", "client_name"}. Tokens are cached under ~/.codemode-mcp/oauth.

codemode_mcp.Settings dataclass

Tunables for the Code Mode layer.

timeout class-attribute instance-attribute

timeout: float = 30.0

Wall-clock limit (seconds) for one run_code execution, including tool calls.

tool_call_timeout class-attribute instance-attribute

tool_call_timeout: float = 60.0

Limit (seconds) for a single upstream tool call.

max_output_chars class-attribute instance-attribute

max_output_chars: int = 20000

Output of run_code returned to the LLM is truncated beyond this many characters.

max_tool_calls class-attribute instance-attribute

max_tool_calls: int = 200

Upper bound on upstream tool calls per run_code execution.

inline_catalog_tokens class-attribute instance-attribute

inline_catalog_tokens: int = 1500

If every tool signature fits in this many tokens, they are embedded directly in the run_code description and search_tools is not exposed (one round-trip saved).

inline_signatures_tokens class-attribute instance-attribute

inline_signatures_tokens: int = 600

Otherwise, if one-line signatures of every tool fit in this budget they are embedded, so the model can write its first script without a search_tools round-trip. They are sent with every request, so this trades tokens for turns: in our benchmark (46 tools, about 1,150 tokens of signatures) embedding them cut turns by a fifth and raised tokens by a tenth. Raise it if latency matters more to you than tokens; set it to 0 to turn it off.

inline_names_tokens class-attribute instance-attribute

inline_names_tokens: int = 1500

Otherwise, if the list of tool names fits in this budget it is embedded so the model knows what exists; full signatures come from search_tools.

memory_mb class-attribute instance-attribute

memory_mb: int = 512

V8 heap limit for the sandbox process.

deno_path class-attribute instance-attribute

deno_path: str | None = None

Override the Deno executable (defaults to the one installed by the deno wheel).

persistent_state class-attribute instance-attribute

persistent_state: bool = False

Keep Python variables between run_code calls (reset on timeout or restart).

expose_tools class-attribute instance-attribute

expose_tools: list[str] = field(default_factory=list)

Hybrid mode: server.tool names (globs allowed) also exposed directly as regular tools.

require_approval class-attribute instance-attribute

require_approval: list[str] = field(default_factory=list)

server.tool globs (e.g. "*.delete_*") that need human approval before each call. The entry "@destructive" covers every tool its own server marks as destructive. codemode-mcp init writes a starting list; the library default is empty because a program that embeds Code Mode has to supply the way to ask (approval_callback).

usage_tracking class-attribute instance-attribute

usage_tracking: bool = True

Record token accounting (counts only, never content) for codemode-mcp usage / dashboard.

usage_db class-attribute instance-attribute

usage_db: str | None = None

SQLite path for usage data (default ~/.codemode-mcp/usage.db, or $CODEMODE_HOME).

tokenizer class-attribute instance-attribute

tokenizer: Literal['auto', 'tiktoken', 'chars'] = 'auto'

Token counting: tiktoken if installed (auto), or ~4 chars/token.

audit_log class-attribute instance-attribute

audit_log: str | None = None

Optional JSONL file recording every run: code, upstream calls (with args) and output.

Usage data

codemode_mcp.UsageStore

Thread-safe SQLite store of usage events.

summary

summary(since: float | None = None) -> dict[str, Any]

Aggregate estimated savings (tool activity) plus measured LLM/benchmark data.

codemode_mcp.UsageEvent dataclass

kind instance-attribute

kind: str

run_code | search_tools | direct | llm | benchmark

MCP server

codemode_mcp.server.build_server

build_server(
    cm: CodeMode,
    name: str = "codemode",
    approval_timeout: float = 300.0,
) -> Server[Any]

Create a low-level MCP server for a started CodeMode.