Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Agentic Python Coder

Python 3.13 License: Apache 2.0 MCP Compatible UV

This package provides two utilities for Python code execution:

  1. coder — An autonomous coding agent using the ReAct pattern (CLI + Python library)
  2. ipython_mcp — An MCP server that gives any MCP-compatible client (Claude Desktop, etc.) Python execution capability

Both share a persistent IPython kernel for stateful code execution.

For details on architecture and constraint modelling applications, see [Szeider 2025, arxiv-2508.07468].

Installation

Prerequisites

  • Python 3.13 or newer
  • UV package manager: curl -LsSf https://astral.sh/uv/install.sh | sh

For the Coding Agent

# Install as CLI tool (--python 3.14: ortools, used by cpmpy, has no 3.15 wheels yet)
uv tool install --python 3.14 agentic-python-coder

# Set up OpenRouter API key
mkdir -p ~/.config/coder
echo 'OPENROUTER_API_KEY="your-key-here"' > ~/.config/coder/.env

Get your API key from openrouter.ai.

For the MCP Server

No installation required — use uvx to run directly. See MCP Server Configuration.


Quick Start

Option A: Autonomous Agent

# Simple task
coder "Create a function that calculates factorial"

# With packages and project template
coder --with cpmpy --project coder-examples/cpmpy/cpmpy.md "Solve 8-queens"

# Interactive mode
coder -i

Option B: MCP Server

Add to your Claude Desktop MCP configuration:

{
  "mcpServers": {
    "ipython": {
      "command": "uvx",
      "args": ["--python", "3.14", "--from", "agentic-python-coder", "ipython_mcp"]
    }
  }
}

Then ask Claude Desktop to execute Python code — it will use the persistent IPython session.


The Coding Agent

CLI Usage

# Inline task
coder "your task"

# Task from file (creates {basename}_code.py and {basename}.jsonl)
coder --task problem.md

# Specify working directory
coder --dir results/test1 "your task"

# Interactive mode
coder -i

CLI Options

Flag Description
--version, -V Show version and exit
--init [TEMPLATE] Initialize example templates (cpmpy, clingo, regex, or all)
--task, -t FILE Load task from markdown file
--model MODEL Model name or JSON file (default: sonnet55)
--project, -p FILE Project template for domain-specific prompts
--with PACKAGE Add packages dynamically (repeatable)
--dir, -d DIR Working directory
--api-key KEY Override API key
--todo Enable task tracking tool
--quiet, -q Suppress console output
--step-limit N Max agent steps (default: 200)
-i, --interactive Interactive conversation mode

Model Selection

# Built-in models (versioned names)
coder --model sonnet45 "task"   # Claude Sonnet 4.5
coder --model sonnet46 "task"   # Claude Sonnet 4.6
coder --model sonnet5 "task"    # Claude Sonnet 5
coder --model opus45 "task"     # Claude Opus 4.5
coder --model opus48 "task"     # Claude Opus 4.8
coder --model sonnet55 "task"   # Claude Sonnet 5.5 (default)
coder --model opus55 "task"     # Claude Opus 5.5
coder --model deepseek31 "task" # DeepSeek v3.1
coder --model grok47 "task"     # X.AI Grok 4.7
coder --model qwen3 "task"      # Qwen3 Coder
coder --model gemini25 "task"     # Gemini Pro 2.5
coder --model gemini31 "task"      # Gemini 3.1 Pro Preview
coder --model gemini3flash "task"  # Gemini 3 Flash Preview (fast, low-cost)
coder --model gpt52 "task"         # GPT-5.2
coder --model gpt56sol "task"      # GPT-5.6 Sol
coder --model gpt56terra "task"    # GPT-5.6 Terra
coder --model gpt6sol "task"       # GPT-6 Sol
coder --model gpt6astra "task"     # GPT-6 Astra
coder --model gemini4argon "task"  # Gemini 4 Argon

# Custom model (JSON file)
coder --model ./mymodel.json "task"

A custom model JSON can also point at any OpenAI-compatible endpoint (OpenAI directly, a local Ollama/vLLM server, etc.) instead of OpenRouter:

{
  "path": "gpt-4o-mini",
  "base_url": "https://api.openai.com/v1",
  "api_key_env": "OPENAI_API_KEY",
  "temperature": 0.0
}

base_url overrides the OpenRouter endpoint; api_key_env names the environment variable holding the key for that endpoint (default: OPENROUTER_API_KEY).

Project Templates

Domain-specific templates improve results. Bundled examples are available on GitHub at coder/src/agentic_python_coder/examples/. Use --init to copy them locally:

# Copy all bundled examples to coder-examples/
coder --init

# Or copy a specific template
coder --init cpmpy

# Then use with your task
coder --with cpmpy --project coder-examples/cpmpy/cpmpy.md "Solve 8-queens"
coder --with clingo --project coder-examples/clingo/clingo.md "Model bird flight"

Interactive Mode

Interactive mode (-i) maintains a persistent session for multi-turn conversations:

coder -i --project coder-examples/cpmpy/cpmpy.md --with cpmpy

State is preserved across turns. Type exit or quit to end.

Library Usage

import agentic_python_coder as coder

# High-level: run a complete task
messages, stats, log_path = coder.solve_task(
    "Write a fibonacci function",
    working_directory="/tmp/workspace",
    model="sonnet55",
    quiet=True,
)

# Get the final response
response = coder.get_final_response(messages)
print(response)

Library API Reference

solve_task() — High-Level API

from agentic_python_coder import solve_task

messages, stats, log_path = solve_task(
    task="Your task description",
    working_directory=".",           # Where to run and save files
    model=None,                      # Model name: "sonnet55", "opus55", or JSON file
    system_prompt=None,              # Custom system prompt (string)
    system_prompt_path=None,         # Path to system prompt file
    project_prompt=None,             # Domain-specific context
    with_packages=None,              # ["pandas", "numpy"] for dynamic install
    api_key=None,                    # Override API key
    todo=False,                      # Enable todo_write tool
    quiet=False,                     # Suppress console output
    save_log=True,                   # Save conversation log
    task_basename=None,              # Base name for output files
    step_limit=None,                 # Max agent steps (default: 200)
    llm_config=None,                 # Pre-built LLMConfig (overrides model/api_key)
)

Returns: (messages, stats, log_path)

  • messages: List of agent messages
  • stats: Dict with tool_usage, token_consumption, execution_time_seconds
  • log_path: Path to saved log file (or None if save_log=False)

create_coding_agent() / run_agent() — Low-Level API

from agentic_python_coder import create_coding_agent, run_agent, get_final_response

# Create agent
agent = create_coding_agent(
    working_directory="/tmp/workspace",
    system_prompt="You are a Python expert.",
    model="deepseek31",
    with_packages=["pandas"],
)

# Run one or more turns
messages, stats = run_agent(agent, "Load data.csv", quiet=True)
messages2, stats2 = run_agent(agent, "Now plot column A", quiet=True)

print(get_final_response(messages2))

Instead of a model name, you can pass a pre-built LLMConfig wrapping any OpenAI-compatible client:

from openai import OpenAI
from agentic_python_coder import LLMConfig, create_coding_agent

llm_config = LLMConfig(
    client=OpenAI(api_key="...", base_url="https://api.openai.com/v1"),
    model="gpt-4o-mini",
    api_params={"temperature": 0.0},
)

agent = create_coding_agent(
    working_directory="/tmp/workspace",
    llm_config=llm_config,
)

get_openrouter_llm() — LLM Access

from agentic_python_coder import get_openrouter_llm, list_available_models

llm = get_openrouter_llm(model="sonnet55")
print(list_available_models())
# ['deepseek31', 'gemini25', 'gemini31', 'gemini3flash', 'gpt52', ...]

The MCP Server

The ipython_mcp server provides Python code execution via the Model Context Protocol. Use it to give Claude Desktop (or any MCP-compatible client) the ability to run Python code in a persistent session.

MCP Server Configuration

Add to your MCP settings (e.g., ~/.claude/claude_desktop_config.json or project .mcp.json):

{
  "mcpServers": {
    "ipython": {
      "command": "uvx",
      "args": ["--python", "3.14", "--from", "agentic-python-coder", "ipython_mcp"]
    }
  }
}

Available Tools

Tool Description
python_exec Execute Python code. Auto-starts session if needed. Default 30s timeout.
python_reset Restart a kernel with a clean state, optionally with packages. Without kernel_id: the default kernel. With kernel_id: that kernel, created if no kernel has this id ("created": true).
python_status Check session state: active flag, all active kernel IDs, crash flag, Python version, packages, variables.
python_interrupt Send interrupt signal to stop long-running code. Session state is preserved.
submit_code Submit the final standalone program (code). Syntax-checked with compile(), not executed or saved; returns {"ok": true} or {"ok": false, "error": ...}.

Kernels and Multi-Agent Workflow

Every call without kernel_id uses the default kernel _default. It starts on the first python_exec; python_reset(packages=[...]) restarts it with those packages, and later python_exec calls without kernel_id run there:

python_reset(packages=["numpy"])    → kernel_id="_default"
python_exec(code="import numpy")    → runs in _default

A separate kernel is created by python_reset with an id of your choice (1 to 64 letters, digits, _, -, ., starting with a letter or digit; default, new, none, null and ids starting with _ are reserved). Pass the same kernel_id on every later call:

Agent A                                   Agent B
────────                                  ────────
python_reset(kernel_id="a-1") → created   python_reset(kernel_id="b-1") → created
python_exec(kernel_id="a-1", ...)         python_exec(kernel_id="b-1", ...)
python_exec(kernel_id="a-1", ...)         python_exec(kernel_id="b-1", ...)
  • python_reset with a known id restarts that kernel ("created": false). The same call works on first use, to clear state, and after a crash.
  • packages: a non-empty list replaces the kernel's packages; omitted, null or [] keeps them.
  • python_exec, python_status and python_interrupt never create a named kernel; an unknown id is an error that lists the live kernels.
  • If the default kernel crashed, the next python_exec restarts it with the same packages but does not run its code: the reply is an error with "kernel_restarted": true and "executed": false, and the code must be sent again. Earlier variables and imports are gone. A crashed named kernel is restarted by python_reset(kernel_id=...).
  • All clients of one server process that omit kernel_id share the default kernel, and two clients that pick the same name share that kernel.
  • CODER_MAX_KERNELS (default 10) limits the named kernels; the default kernel does not count.

Features

  • Persistent state: Variables, imports, and definitions persist across executions
  • Auto-start: Default session starts automatically on first python_exec
  • Package installation: Use python_reset with packages parameter to install dependencies
  • Timeout handling: Long-running code times out gracefully (session preserved)
  • Interrupt support: Stop runaway code without losing session state
  • Multi-kernel: python_reset(kernel_id=...) creates a separate named kernel for parallel agents

Usage Tips

When using the MCP server for domain-specific tasks (constraint programming, ASP, etc.), provide the project template content directly in your conversation. For example, paste the contents of coder-examples/cpmpy/cpmpy.md when working with CPMpy.


Configuration

API Key (Coding Agent only)

The coding agent requires an OpenRouter API key. It looks in order:

  1. --api-key flag or api_key parameter
  2. ~/.config/coder/.env file
  3. OPENROUTER_API_KEY environment variable
mkdir -p ~/.config/coder
echo 'OPENROUTER_API_KEY="sk-or-v1-..."' > ~/.config/coder/.env

The MCP server does not require an API key — it only executes code.

Environment Variables

Variable Description
OPENROUTER_API_KEY API key for OpenRouter (agent only)
CODER_VERBOSE Show detailed model configuration

Security Notice

This is experimental software. Both the coding agent and MCP server execute code automatically.

  • Run in a VM or container for untrusted inputs
  • Code executes in the working directory
  • Use isolated environments for sensitive projects

License

Apache License 2.0 - see LICENSE for details.

Metadata

Release files for agentic-python-coder 4.0.0rc1

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

Source distribution (sdist)

Source distribution for agentic-python-coder 4.0.0rc1
File Size Uploaded Provenance Actions
agentic_python_coder-4.0.0rc1.tar.gz 120.5 kB Without provenance Details for agentic_python_coder-4.0.0rc1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agentic-python-coder 4.0.0rc1
File Interpreter ABI Platform Actions
agentic_python_coder-4.0.0rc1-py3-none-any.whl Python 3 none any Details for agentic_python_coder-4.0.0rc1-py3-none-any.whl

Total release size: 219.9 kB

Release files / agentic_python_coder-4.0.0rc1.tar.gz

Download URL agentic_python_coder-4.0.0rc1.tar.gz
Size 120.5 kB
Tags Source
SHA-256 checksum
How to use checksums
9a5340b6befacf157fb569bf0a9116b0833d14afbc714adfff29e43b328d4a43
BLAKE2b-256 checksum
How to use checksums
4e21b1d13073a8ef2a59ec2d7b459a6a14fa1bc2e544326dd82c64449e5df050
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / agentic_python_coder-4.0.0rc1-py3-none-any.whl

Download URL agentic_python_coder-4.0.0rc1-py3-none-any.whl
Size 99.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e9d31a46746011e15b9c9a8f0124635f47a2383cb2dbc803c3cde930c9a8392b
BLAKE2b-256 checksum
How to use checksums
d5e328a960e63ccb5949cfdcbfd118e483194dc54135df82984dc20140142a11
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for agentic-python-coder 4.0.0rc1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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