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
¶
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.
tools ¶
Tool definitions in a provider's format: openai, openai-responses, anthropic or mcp.
tool_definitions ¶
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.
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.
handle_openai_tool_call
async
¶
Run an OpenAI Chat Completions tool_call and return the role=tool message.
handle_anthropic_tool_use
async
¶
Run an Anthropic tool_use content block and return the tool_result block.
stats ¶
Context cost of tool definitions per LLM request: classic MCP vs Code Mode.
record_llm_usage ¶
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
¶
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 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
¶
Wall-clock limit (seconds) for one run_code execution, including tool calls.
tool_call_timeout
class-attribute
instance-attribute
¶
Limit (seconds) for a single upstream tool call.
max_output_chars
class-attribute
instance-attribute
¶
Output of run_code returned to the LLM is truncated beyond this many characters.
max_tool_calls
class-attribute
instance-attribute
¶
Upper bound on upstream tool calls per run_code execution.
inline_catalog_tokens
class-attribute
instance-attribute
¶
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
¶
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
¶
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
¶
V8 heap limit for the sandbox process.
deno_path
class-attribute
instance-attribute
¶
Override the Deno executable (defaults to the one installed by the deno wheel).
persistent_state
class-attribute
instance-attribute
¶
Keep Python variables between run_code calls (reset on timeout or restart).
expose_tools
class-attribute
instance-attribute
¶
Hybrid mode: server.tool names (globs allowed) also exposed directly as regular tools.
require_approval
class-attribute
instance-attribute
¶
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
¶
Record token accounting (counts only, never content) for codemode-mcp usage / dashboard.
usage_db
class-attribute
instance-attribute
¶
SQLite path for usage data (default ~/.codemode-mcp/usage.db, or $CODEMODE_HOME).
tokenizer
class-attribute
instance-attribute
¶
Token counting: tiktoken if installed (auto), or ~4 chars/token.
audit_log
class-attribute
instance-attribute
¶
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 ¶
Aggregate estimated savings (tool activity) plus measured LLM/benchmark data.
codemode_mcp.UsageEvent
dataclass
¶
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.