Skip to content

Python library & LLMs

Use CodeMode directly when you write your own agent, or use the built-in agent loops.

Lifecycle

from codemode_mcp import CodeMode

async with CodeMode.from_config("mcp.json") as cm:   # connects to servers, starts the sandbox
    ...
# connections and sandbox are closed here

Ways to build one:

cm = CodeMode.from_config("mcp.json")                          # file path or dict
cm = CodeMode.from_config("mcp.json", timeout=60, persistent_state=True)   # override settings
cm = CodeMode.from_servers({"shop": {"command": "python", "args": ["shop_server.py"]}})
cm = CodeMode(config, approval_callback=my_approver, usage_store=UsageStore("usage.db"))

start() and close() may be called from different asyncio tasks. This is useful with FastAPI lifespans, for example.

The two calls you need

tools = cm.tools("openai")                 # tool definitions for your LLM
output = await cm.call(name, arguments)    # run a tool call, get text for the LLM

tools(format) supports "openai" (Chat Completions), "openai-responses", "anthropic" and "mcp". arguments may be a dict or a JSON string.

OpenAI (and every OpenAI-compatible API)

from openai import AsyncOpenAI
from codemode_mcp import CodeMode

async with CodeMode.from_config("mcp.json") as cm:
    client = AsyncOpenAI()  # or AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
    messages = [{"role": "system", "content": cm.system_prompt},
                {"role": "user", "content": "Which repos have PRs open for more than 30 days?"}]
    while True:
        resp = await client.chat.completions.create(model="gpt-4.1", messages=messages, tools=cm.tools("openai"))
        msg = resp.choices[0].message
        if not msg.tool_calls:
            print(msg.content)
            break
        messages.append(msg)
        for tc in msg.tool_calls:
            messages.append(await cm.handle_openai_tool_call(tc))   # {"role": "tool", ...}

Anthropic

from anthropic import AsyncAnthropic

async with CodeMode.from_config("mcp.json") as cm:
    client = AsyncAnthropic()
    messages = [{"role": "user", "content": "Summarise yesterday's error logs"}]
    while True:
        resp = await client.messages.create(model="claude-sonnet-4-5", max_tokens=4096,
                                            system=cm.system_prompt, tools=cm.tools("anthropic"),
                                            messages=messages)
        uses = [b for b in resp.content if b.type == "tool_use"]
        if not uses:
            print("".join(b.text for b in resp.content if b.type == "text"))
            break
        messages.append({"role": "assistant", "content": resp.content})
        messages.append({"role": "user", "content": [await cm.handle_anthropic_tool_use(b) for b in uses]})

Built-in agent loops

from codemode_mcp.agent import run_openai, run_anthropic

res = await run_openai(cm, "Find my 3 biggest customers", model="gpt-4.1-mini")
res = await run_openai(cm, "...", model="llama3.1", base_url="http://localhost:11434/v1", api_key="ollama")
res = await run_anthropic(cm, "...", model="claude-sonnet-4-5")

print(res.text, res.turns, res.input_tokens, res.output_tokens, res.tool_calls)

Both loops log the provider-reported token usage of each request to the usage database (pass record_usage=False to turn this off). They accept on_event(kind, payload) for streaming progress to a UI.

Other frameworks

Any framework that supports function calling can use Code Mode. Register the definitions from cm.tool_definitions() (provider-neutral name / description / input_schema) and forward the calls to await cm.call(name, args).

for d in cm.tool_definitions():
    register_tool(name=d["name"], description=d["description"], schema=d["input_schema"],
                  handler=lambda args, n=d["name"]: cm.call(n, args))

Running code directly

out = await cm.run_code("len(await github.list_repos(owner='me'))")
cm.last_run.calls      # [ToolCallRecord(server, tool, args, ok, error), ...]
cm.last_event          # UsageEvent with codemode_tokens / classic_tokens
cm.search_tools("create issue")   # the same text the LLM would get

Token accounting

cm.usage()   # this instance, since start
# {'codemode_tokens': 1634, 'classic_tokens': 8463, 'calls': 1, 'upstream_calls': 14,
#  'saved_tokens': 6829, 'saved_pct': 80.7, 'tokenizer': 'tiktoken:o200k_base'}
cm.stats()   # definition cost per request: classic vs Code Mode
cm.record_llm_usage("gpt-4.1", input_tokens=1200, output_tokens=80)  # log your own LLM calls

See Monitoring savings for the dashboard and benchmarks.