smol-codeact-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@smol-codeact-mcp Run Python to average [4, 8, 15] and inspect persisted variables"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
smol-codeact
Zero-dependency AST-sandboxed Python CodeAct execution engine, JSON-Schema-to-Stub compiler, paradigm benchmark & MCP Server — inspired by huggingface/smolagents.
零外部依赖、纯 Python 标准库从零实现的受限 AST 树遍历 CodeAct 执行引擎、JSON 工具定义转函数签名编译器、范式对比基准测试与原生 MCP Server —— 致敬 huggingface/smolagents 与 ICML CodeAct 论文,用 1 段安全可持久化的 Python 代码块替代 10+ 轮繁琐 JSON Tool-Calling 往返,实测节省 ~93.6% 累计上下文 Token。
Why smol-codeact? / 核心痛点与价值
Traditional JSON Tool-Calling forces LLMs to interact with tools one rigid JSON blob at a time:
N+1 Roundtrip Explosion: Looping over 6 microservices, filtering unhealthy metrics, and joining deployment commits requires 10–15 sequential LLM roundtrips, re-billing the entire growing conversation history on every turn.
Context Window Pollution: Verbose JSON Tool Schemas bloat the system prompt, while intermediate raw arrays get echoed into the prompt history just so the model can filter or sum numbers on the next turn.
传统 JSON Tool-Calling 编排多步任务时存在两大工程瓶颈:
多轮往返爆炸:哪怕只是“遍历 6 个服务 → 过滤异常指标 → 关联最近发版 Commit → 排序输出”,JSON 工具调用也必须拆成 10 余次串行大模型请求,每一轮都重复发送全量历史上下文。
Schema 与中间数据膨胀:冗长的 JSON Schema 挤占系统提示词预算,大量原始列表/日志被迫塞进对话窗口做二次过滤。
smol-codeact brings the CodeAgent paradigm into a crisp, hackable, zero-dependency package:
Zero-
exec()AST Tree-Walking Sandbox (AstSandboxExecutor): Parses LLM-generated Python viaast.parse()and evaluates nodes step-by-step—never callingexec(),eval(), orcompile(). Supports loops, comprehensions, f-strings,try/except,lambda, user functions, and whitelisted stdlib modules (math,statistics,json,re, etc.).Hardened Guardrails & Resource Budgets: Blocks private/dunder attribute traversal (
__class__,__subclasses__,__globals__), unauthorized imports (os,subprocess,sys), dangerous builtins (open,eval,getattr), infinite loops (max_operations), deep recursion, CPU exponent bombs (9 ** 500000), and memory sequence bombs.Stateful Step-to-Step Memory & Line-Pinpointed Self-Healing: Variables bound in Step 1 (
snapshots) remain alive in Step 2. If a runtime error occurs,smol-codeactreports the exact offending source line so the LLM fixes the bug in one turn without re-fetching upstream tools.JSON-Schema-to-Python-Stub Compiler (
stubs): Compiles verbose OpenAI/MCP JSON Tool Schemas into typed Python signatures, cutting tool-definition tokens by ~71.9%.Drop-In stdio MCP Co-Processor (
smol-codeact-mcp): Plugs directly into Claude Code, Cursor, or Codex so any JSON-based coding agent gains a stateful, workspace-jailed CodeAct sandbox session (codeact_execute,codeact_inspect_state).
Related MCP server: Coding Tools MCP
Architecture / 核心架构图
flowchart LR
Tools["Python @tool Functions<br/>or MCP JSON Schemas"] --> Compiler["Signature & Stub Compiler<br/>(-71.9% Prompt Tokens)"]
Compiler --> Agent["CodeActAgent Loop<br/>Thought -> <code>...</code>"]
Agent <--> LLM["Offline Scripted Model /<br/>Ollama / OpenAI-Compatible API"]
Agent --> Parser["Python ast.parse()<br/>(Zero native exec/eval)"]
subgraph Sandbox["AstSandboxExecutor (Stateful & Capped)"]
Parser --> Guard["Security & Budget Guard<br/>No _dunder / Import Whitelist / Ops Cap"]
Guard --> Walker["AST Node-by-Node Evaluator<br/>Loops, Comprehensions, Lambdas, Try/Except"]
Walker <--> State[("Persistent Session State<br/>Step 1 -> Step N Memory")]
end
Walker --> Obs["Observation Formatter<br/>Bounded stdout + Line-Pinpointed Errors + final_answer()"]
Obs --> Agent
Sandbox <--> MCP["stdio MCP JSON-RPC 2.0 Server<br/>(Claude Code / Cursor / Codex)"]Inspired By & Architecture Comparison / 致敬与架构对比
Inspired by:
huggingface/smolagents — Full credit to Aymeric Roucher and the Hugging Face team for popularizing lightweight
CodeAgentorchestration and AST-walkedLocalPythonExecutor.CodeAct Paper (ICML 2024): Xingyao Wang et al., Executable Code Actions Elicit Better LLM Agents.
smol-codeact is a clean-room, From-Scratch zero-dependency implementation crafted for architectural clarity, instant CLI benchmarking, and plug-and-play MCP integration:
Dimension / 维度 |
|
|
Core Codebase / 代码体量 | Full multi-modal framework + Hub ecosystem + remote executors | ~2,000 LOC pure Python 3.10+ stdlib ( |
Dependencies / 运行依赖 |
| 0 external packages (100% Python stdlib; runs anywhere instantly) |
Sandbox Engine / 沙箱机制 |
| From-Scratch |
Schema Compiler / 协议桥接 | Python |
|
MCP Integration / 工具服务 | Consumes MCP tools as client | Acts as a Stateful CodeAct MCP Server ( |
Offline Verification / 离线评测 | Requires LLM model weights or API endpoint | Built-in deterministic |
30-Second Quickstart / 30 秒零配置上手
No API keys, Docker daemon, or third-party pip dependencies required:
git clone https://github.com/nanyun818/smol-codeact.git
cd smol-codeact
pip install -e .
# 1. Run the 2-turn self-healing CodeAct demo + AST red-team check
smol-codeact demo
# 2. Run the head-to-head JSON Tool-Calling vs. CodeAct token & roundtrip benchmark
smol-codeact bench
# 3. Execute inline Python directly inside the zero-exec() AST sandbox
smol-codeact exec "svcs = [get_service_metrics(s) for s in list_services('critical')]; final_answer(svcs)"
# 4. Compile JSON Tool Schemas into compact Python CodeAct stubs
smol-codeact stubs
# 5. (Optional) Connect to local Ollama or any OpenAI-compatible API
OPENAI_BASE_URL="http://localhost:11434/v1" OPENAI_API_KEY="ollama" \
smol-codeact run "Find which critical microservice has the highest p95 latency and inspect its deploy commit." --model qwen2.5-coder:7bReal Terminal Output / 真实终端运行实录
1. smol-codeact demo (Stateful Self-Healing + Token Compression)
$ smol-codeact demo
=== smol-codeact v0.1.0 | Zero-Dependency AST CodeAct Demo ===
[1] Tool Definition Compression: 566 JSON tokens -> 159 Python stub tokens (-71.9%)
[2] Running 2-Turn Self-Healing CodeAct Loop (Stateful AST Sandbox):
Step 1 [RECOVERABLE_ERR | 59 AST ops]: Thought: Let's inspect all microservices, gather their live metrics into `snapshots`, and filter services breaching SLO.
| Execution logs:
| Fetched metrics count: 6 sample keys: ['error_rate', 'p95_ms', 'replicas', 'service', 'tier']
| Execution error (KeyError): Line 4 (`breaches = [m for m in snapshots if m['error_rate'] > 0.03 or m['latency_p95'] > 500]`): 'latency_p95'
Step 2 [OK | 185 AST ops]: Thought: The observation shows `p95_ms` is the exact key and `snapshots` (6 items) is already persisted in memory! Let's filter SLO breaches, correlate deploys, rank by incident score, and return the remediation plan.
| Execution logs:
| Ranked SLO incidents: 2
| Final answer: [{'service': 'checkout-api', 'severity': 100.0, 'p95_ms': 920, 'error_rate': 0.084, 'suspect_commit': 'e7b4410', 'change': 'retry pool timeout=50ms'}, {'service': 'payment-ledger', 'severity': 67.5, 'p95_ms': 640, 'error_rate': 0.049, 'suspect_commit': '98d12fa', 'change': 'unindexed fx audit query'}]
[3] Verified Final Answer (Structured Python Object):
[{"service": "checkout-api", "severity": 100.0, "p95_ms": 920, "error_rate": 0.084, "suspect_commit": "e7b4410", "change": "retry pool timeout=50ms"}, {"service": "payment-ledger", "severity": 67.5, "p95_ms": 640, "error_rate": 0.049, "suspect_commit": "98d12fa", "change": "unindexed fx audit query"}]
Totals: turns=2, tool_calls=11, ast_ops=244, tokens_est=1311, elapsed=1.56ms
[4] AST Sandbox Red-Team Guardrails: 8/8 escape/DoS payloads blocked (100.0%)2. smol-codeact bench (JSON Tool-Calling vs. CodeAct + Security Audit)
$ smol-codeact bench
=== Paradigm Benchmark: Sequential JSON Tool-Calling vs. Python CodeAct ===
Scenario | JSON Turns | CodeAct | JSON Toks | CodeAct Toks | Saved
--------------------------------------------------------------------------------------------------------
Microservice Incident Triage (11 tool calls) | 12 | 1 | 10690 | 530 | - 95.0%
Multi-Currency FinOps Audit (8 tool calls) | 9 | 1 | 5694 | 517 | - 90.9%
--------------------------------------------------------------------------------------------------------
Overall: 21 JSON roundtrips -> 2 CodeAct turns (10.5x fewer roundtrips), -93.6% cumulative tokens.
=== AST Sandbox Adversarial Security Audit ===
[BLOCKED] OS command import -> SandboxSecurityError: Line 1 (`import os`): Import of 'os' is forbidden. Authorized imports: ['collections', 'datetime', 'decimal', 'functools', 'itertools', 'json', 'math', 're', 'statistics']
[BLOCKED] Subprocess import -> SandboxSecurityError: Line 1 (`from subprocess import Popen`): Import of 'subprocess' is forbidden. Authorized imports: ['collections', 'datetime', 'decimal', 'functools', 'itertools', 'json', 'math', 're', 'statistics']
[BLOCKED] Dunder MRO class escape -> SandboxSecurityError: Line 1 (`().__class__.__bases__[0].__subclasses__()`): Access to private/dunder attribute '__subclasses__' is prohibited.
[BLOCKED] Host file open() -> SandboxSecurityError: Line 1 (`open('/etc/passwd', 'r').read()`): Builtin 'open()' is prohibited inside the AST sandbox.
[BLOCKED] Nested eval/exec bypass -> SandboxSecurityError: Line 1 (`eval('1 + 1')`): Builtin 'eval()' is prohibited inside the AST sandbox.
[BLOCKED] Infinite loop CPU trap -> OperationLimitError: Execution exceeded max_operations budget (5000). Check for infinite or oversized loops.
[BLOCKED] CPU exponent bomb -> OperationLimitError: Line 1 (`x = 9 ** 500000`): Exponent magnitude (500000) exceeds sandbox limit of 1000.
[BLOCKED] Memory sequence bomb -> OperationLimitError: Line 1 (`blob = 'A' * 10_000_000`): Sequence repetition exceeds sandbox memory cap.
Pass rate: 8/8 (100.0%)Python Library API / Python 编程接入示例
from smol_codeact import CodeActAgent, OpenAICompatibleModel, tool
@tool
def fetch_order_items(order_id: str) -> list[dict]:
"""Fetch line items with unit_price and qty for an order."""
return [
{"sku": "GPU-H100", "unit_price": 2400.0, "qty": 2},
{"sku": "NVLINK-CABLE", "unit_price": 150.0, "qty": 4},
]
@tool
def get_discount_rate(tier: str) -> float:
"""Return fractional discount rate for customer loyalty tier."""
return {"gold": 0.12, "silver": 0.05}.get(tier, 0.0)
model = OpenAICompatibleModel(
model="qwen2.5-coder:7b",
base_url="http://localhost:11434/v1",
api_key="<YOUR_API_KEY_OR_OLLAMA>",
)
agent = CodeActAgent(model=model, tools=[fetch_order_items, get_discount_rate], max_steps=5)
result = agent.run("Calculate net total for order ORD-901 with 'gold' tier discount.")
print(result.final_answer)MCP Server Integration / 接入 Claude Code、Cursor 与 Codex
Add smol-codeact-mcp to your .mcp.json or Claude Desktop / Cursor MCP settings to give any agent a stateful Python AST co-processor with path-traversal-proof workspace helpers (list_files, read_lines, grep_files):
{
"mcpServers": {
"smol-codeact": {
"command": "smol-codeact-mcp",
"args": ["--workspace", "."]
}
}
}Exposed MCP tools:
codeact_execute: Execute Python loops, regex scans, and math inside a namedsession_idAST sandbox.codeact_inspect_state: View persisted variable names, types, lengths, and truncated previews without bloating context.codeact_reset_session: Clear session state.codeact_compile_stubs: Convert verbose JSON Tool Schemas into compact Python function stubs.
An accompanying Agent Skill playbook is included at skills/smol-codeact/SKILL.md.
Security Boundary Note / 安全边界说明
AstSandboxExecutor walks Python's Abstract Syntax Tree (ast) directly without calling exec() or eval(), enforcing strict import whitelists, dunder/MRO attribute blocking, and elementary operation/allocation caps. Like smolagents's LocalPythonExecutor, it is designed as a lightweight, zero-setup local guardrail against accidental LLM mistakes, runaway loops, and common prompt-injection escapes. For multi-tenant or hostile untrusted code execution in production, always layer an OS/VM boundary (Docker, gVisor, Firecracker, or E2B) underneath.
License
Released under the MIT License. Copyright (c) 2026 nanyun818.
Available Tools
4 toolscodeact_compile_stubsB
Compile verbose OpenAI/MCP JSON Tool Schemas into compact Python CodeAct stubs with token stats.
Inputs: schemas (required).
codeact_executeB
Execute multi-step Python logic inside a stateful, zero-exec() AST sandbox. Variables persist across calls per session_id. Includes workspace-jailed read-only helpers: list_files(pattern), read_lines(rel_path, start, end), grep_files(regex, glob_filter).
Inputs: code (required), session_id, reset_before, max_operations.
codeact_inspect_stateB
Inspect persisted variable names, types, lengths, and compact previews in a sandbox session.
Inputs: session_id, max_preview_chars.
codeact_reset_sessionC
Clear persisted variables for a sandbox session.
Inputs: session_id.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
Each tool maps to a distinct lifecycle or workflow action: compile schemas, execute code, inspect state, and reset state. Although reset_session and inspect_state both concern session variables, their purposes are clearly differentiated as destructive clearing versus read-only inspection.
All tools use the same codeact_ prefix followed by clear snake_case action names. The convention is predictable and consistent across the entire set.
Four tools is well-scoped for a focused CodeAct sandbox server. Each tool earns its place by covering compile, execute, inspect, and reset without redundancy.
The core lifecycle is covered: compile stubs, execute stateful code, inspect persisted variables, and reset sessions. Minor gaps such as explicit session creation or deletion are reasonable to omit or work around via reset.
Maintenance
Related MCP Connectors
Hosted MCP runtime where your agent publishes its own tools by tool call and keeps working.
Secure Linux sandboxes for AI agents, as MCP tools.
Remote MCP for NovaForge: sandboxed workspace, HA device control, official skill library.
Run commands, code and file operations for AI agents in Cloud Hypervisor microVM sandboxes.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to execute arbitrary Python code securely in a sandboxed environment with resource limits and security constraints via MCP protocol.MIT
- AlicenseNot gradedqualityDmaintenanceGives any MCP-compatible AI chat or agent a safe, model-neutral coding runtime with file read/search, structured multi-file patches, command execution, interactive sessions, and git operations, all confined to a single workspace and gated by permission modes.Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables LLM agents to run persistent Python code in a workspace-scoped shared kernel, with tools for execution, background tasks, file operations, and external MCP integrations.AGPL 3.0
- FlicenseNot gradedqualityNot gradedmaintenanceEnables agents and MCP-compliant clients to run multi-language code in a deterministic, zero-dependency sandbox where AST security analysis blocks dangerous syscalls and isolated execution telemetry is captured. It exposes this through JSON-RPC 2.0 stdio, letting frameworks like LangGraph, CrewAI, Cursor, and Claude Desktop validate and execute agent-generated code safely.-