PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Guides> Tools and the Model Context Protocol (MCP)

Code-Action Agents in Python: One Program vs 37 Tool Calls

Build a code-action agent in Python over an MCP server: the model writes one program that calls your tools in a Docker sandbox, within a budget you set.

Level
Advanced
Reading time
15 min
Published
Oct 15, 2026
Last updated
Oct 24, 2026
Tested with
Promptise 1.9.0
By
Promptise Team
  • Agent Reasoning Patterns
  • ReAct
  • Model Context Protocol (MCP)
  • Code Execution and Sandboxing
Contents · 8 sections↓
  1. 01What is a code-action agent?
  2. 02How does a code-action agent work?
  3. 03What you need
  4. 04How to build a code-action agent in Python, step by step
  5. 05Code-action vs ReAct: which should you use?
  6. 06Common mistakes with code-action agents
  7. 07Frequently asked questions
  8. 08Where to go next

A code-action agent answers a question by writing one Python program that calls your tools and computes the result, instead of making one tool call per model turn. For questions that need dozens of tool calls, that means one model call instead of several, and tool results that never enter the model's context. This guide explains how a code-action agent works and builds one in Python with Promptise Foundry on top of a real MCP server. You'll run it next to a ReAct agent on the same question, size its tool budget so a run never returns a partial answer, and learn the mistakes to watch for. The code runs on Promptise Foundry 1.9.0 with GPT-5 mini and Docker, and the outputs come from real runs.

[01]

What is a code-action agent?

A code-action agent (the idea is often called CodeAct, or code as action) changes what the model's action is. A ReAct agent acts by calling one tool, reading the result, and deciding the next call. A code-action agent acts by writing a program: loops, filters and sums run as Python, and the tools are ordinary functions the program calls. One model turn can stand for dozens of tool calls.

In Promptise Foundry it's one argument on build_agent:

Pythoncode_action_agent.py
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="code-action",  # starts a Docker sandbox for the program
    )

[02]

How does a code-action agent work?

Promptise starts a Docker container for the program with no network, gives it a Python stub for each tool, and runs the real tools on your side when the program calls them. MCP results that are JSON arrive in the program as lists and dicts. The answer is the line the program prints after RESULT:.

Rendering diagram…

Three parts of the design shape how a code-action agent behaves:

  • The model sees each tool as one line. The prompt lists every tool as a Python signature followed by the first line of its description. Parameter descriptions and return types never reach the model, so that first line has to name the fields the tool returns.

  • Every program gets a new container. That's the safe choice, and a repair attempt pays for another one. build_agent also starts and removes one up front to check that Docker works. Starting and removing a container takes well under a second.

  • Bridged calls are served one at a time. The program writes a request file and waits. A loop on your side polls the container for request files, runs the tool, and writes the response back. Each call adds a fraction of a second, so a program that makes 30 calls spends about five seconds on the bridge. A ReAct agent can run the same 30 calls in parallel in one step.

When a program crashes, Promptise sends the last 800 characters of its error output back to the model with the program it wrote, and the model answers with a corrected program. max_repairs sets how many times that can happen.

The sandbox guide covers the container itself: what it blocks, how to set limits, and what happened when an agent was asked to break out. This guide is about the other half: building a code-action agent over your MCP tools, and where it goes wrong.


[03]

What you need

  • Python 3.10 or newer.

  • Docker, installed and running. There's no fallback: without a working sandbox, build_agent raises RuntimeError instead of running model-written code on your machine. The first run pulls the python:3.11-slim image. Since 1.10.0 the pull logs a warning when it starts (Pulling Docker image python:3.11-slim (first use, this can take a few minutes)), a progress line every 10 seconds and one when it ends; a failed pull raises with Docker's error.

  • Promptise Foundry 1.9.0 or newer with the sandbox extra, which adds the Docker SDK for Python.

  • An API key for a model provider. The examples use openai:gpt-5-mini.

>_Terminal
pip install "promptise[sandbox]>=1.9.0"
export OPENAI_API_KEY="sk-..."

[04]

How to build a code-action agent in Python, step by step

Step 01

Give the agent a job that takes many tool calls

A code-action agent earns its keep on gather-then-compute work, so the MCP server below makes the agent gather. list_orders returns 30 order IDs, get_order returns one order with its lines, and get_price returns one product's price. Any question about September revenue means one call per order, plus prices.

Pythonshop_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import random

from promptise.mcp.server import MCPServer

server = MCPServer("shop")

# Sample data: 30 September orders, generated the same way on every run.
PRICES = {"KB-101": 89, "MS-220": 35, "MN-270": 249, "HD-330": 119, "DK-410": 179, "CB-055": 13}
CUSTOMERS = ["Acme Corp", "Birchwood Ltd", "Cobalt Labs", "Dunmore Studio",
             "Elmfield Cafe", "Fjordline Design", "Granite Health", "Halcyon Books"]

rng = random.Random(2)
ORDERS = {}
for n in range(1, 31):
    order_id = f"SO-{9000 + n}"
    skus = rng.sample(list(PRICES), rng.randint(1, 3))
    ORDERS[order_id] = {
        "id": order_id,
        "customer": rng.choice(CUSTOMERS),
        "status": rng.choice(["shipped"] * 6 + ["refunded", "pending"]),
        "discount_pct": rng.choice([0, 0, 5, 10, 15]),
        "lines": [{"sku": sku, "qty": rng.randint(1, 12)} for sku in skus],
    }


@server.tool()
async def list_orders(month: str) -> list[str]:
    """List the IDs of the orders placed in a month, e.g. "2026-09".

    Args:
        month: The month as YYYY-MM.
    """
    return list(ORDERS) if month == "2026-09" else []


@server.tool()
async def get_order(order_id: str) -> dict:
    """Get one order as {id, customer, status, discount_pct, lines: [{sku, qty}]}.

    Args:
        order_id: An order ID from list_orders, e.g. "SO-9001".
    """
    order = ORDERS.get(order_id)
    if order is None:
        raise ValueError(f"No order {order_id}")
    return order


@server.tool()
async def get_price(sku: str) -> dict:
    """Get a product's unit price in USD as {sku, unit_price}.

    Args:
        sku: A product SKU from an order line, e.g. "KB-101".
    """
    if sku not in PRICES:
        raise ValueError(f"No product {sku}")
    return {"sku": sku, "unit_price": PRICES[sku]}


if __name__ == "__main__":
    server.run()

The first line of each docstring matters more than usual here. The code-action prompt shows the model each tool as a Python signature followed by that line, and nothing else, so the line names the fields the tool returns.

The question in the next steps asks for the customer who spent the most on shipped orders, which needs prices and discounts. Computed straight from the data, these are the answers an agent has to reach for this question and two others:

Pythontruth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""The right answers, computed straight from the server's data."""
from collections import Counter, defaultdict

from shop_server import ORDERS, PRICES


def order_total(order):
    gross = sum(line["qty"] * PRICES[line["sku"]] for line in order["lines"])
    return gross * (100 - order["discount_pct"]) / 100


shipped = [o for o in ORDERS.values() if o["status"] == "shipped"]
print(f"orders: {len(ORDERS)}, shipped: {len(shipped)}")
print(f"net revenue, shipped: ${sum(order_total(o) for o in shipped):,.2f}")

by_customer = defaultdict(float)
for o in shipped:
    by_customer[o["customer"]] += order_total(o)
top = max(by_customer, key=by_customer.get)
print(f"top customer, shipped: {top} ${by_customer[top]:,.2f}")

units = Counter()
for o in ORDERS.values():
    if o["status"] != "refunded":
        for line in o["lines"]:
            units[line["sku"]] += line["qty"]
(sku, qty), (second, second_qty) = units.most_common(2)
print(f"most units, not refunded: {sku} {qty} (next: {second} {second_qty})")
Output
orders: 30, shipped: 24
net revenue, shipped: $34,959.30
top customer, shipped: Elmfield Cafe $7,452.85
most units, not refunded: MN-270 105 (next: CB-055 74)
Step 02

Run a ReAct agent first

Start with what you'd get anyway. A small LangChain callback counts model calls and tokens for any pattern, because Promptise passes the run's config to every model call, including the one that writes the program:

Pythonusage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from langchain_core.callbacks import BaseCallbackHandler


class Usage(BaseCallbackHandler):
    """Count model calls and tokens for one run."""

    def __init__(self):
        self.calls = self.input_tokens = self.output_tokens = 0

    def on_llm_end(self, response, **kwargs):
        self.calls += 1
        usage = response.generations[0][0].message.usage_metadata or {}
        self.input_tokens += usage.get("input_tokens", 0)
        self.output_tokens += usage.get("output_tokens", 0)

    def __str__(self):
        return f"{self.calls} model calls, {self.input_tokens:,} input + {self.output_tokens:,} output tokens"
Pythonreact_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import asyncio
import sys
import time

from promptise import build_agent
from promptise.config import StdioServerSpec

from usage import Usage

QUESTION = (
    "Which customer spent the most on shipped orders in September 2026, after discounts, "
    "and how much? An order's total is qty x unit price over its lines, minus its discount."
)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="react",  # the default
    )
    try:
        usage = Usage()
        start = time.perf_counter()
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [usage]},
        )
        report = agent.last_report
        print(">>>", result["messages"][-1].content)
        print(f"tool calls: {report.tool_calls}, path: {' -> '.join(report.nodes_visited)}")
        print(f"usage: {usage}, {time.perf_counter() - start:.1f} s")
    finally:
        await agent.shutdown()


asyncio.run(main())
Output
>>> Elmfield Cafe — $7,452.85
…
Total = 3,640.00 + 1,819.85 + 820.00 + 1,173.00 = 7,452.85
…
tool calls: 37, path: reason -> reason -> reason -> reason
usage: 4 model calls, 7,324 input + 4,050 output tokens, 31.3 s

Right answer, from 37 tool calls (the list, 30 orders and each of the six prices once) in four model calls: when the model asks for several tools in one turn, Promptise runs them in parallel. The arithmetic happened in the model's head, and on 30 orders it came out right. Every result went through the model's context, though, which is where the 7,324 input tokens come from.

Step 03

Switch to code-action

code_action_agent.py is react_agent.py with agent_pattern="code-action" and two logging lines that print the program the model writes. Promptise logs it at DEBUG level:

Pythoncode_action_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import asyncio
import logging
import sys
import time

from promptise import build_agent
from promptise.config import StdioServerSpec

from usage import Usage

QUESTION = (
    "Which customer spent the most on shipped orders in September 2026, after discounts, "
    "and how much? An order's total is qty x unit price over its lines, minus its discount."
)

# Print the program the model writes (Promptise logs it at DEBUG level).
logging.basicConfig(format="%(message)s")
logging.getLogger("promptise.engine.code_action").setLevel(logging.DEBUG)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="code-action",  # starts a Docker sandbox for the program
    )
    try:
        usage = Usage()
        start = time.perf_counter()
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [usage]},
        )
        print(">>>", result["messages"][-1].content)
        print(f"usage: {usage}, {time.perf_counter() - start:.1f} s")
    finally:
        await agent.shutdown()


asyncio.run(main())

Here's a run with every default, trimmed to the lines that matter:

Output
[promptise] Initializing sandbox environment...
[promptise] Sandbox ready for code-action (backend: docker)
code-action program:
…
def main():
    month = "2026-09"
    order_ids = list_orders(month)
    # Ensure it's a list
    if order_ids is None:
        order_ids = []
    # totals per customer
    totals = defaultdict(float)
    price_cache = {}
    for oid in order_ids:
        order_raw = get_order(oid)
        order = normalize_order(order_raw)
…
            # get price from cache or fetch
            if sku not in price_cache:
                p_raw = get_price(sku)
                p = normalize_price(p_raw)
…
code-action exit=0 stdout='RESULT: Elmfield Cafe, $7452.85\n' stderr=''
>>> Elmfield Cafe, $7452.85
usage: 1 model calls, 467 input + 1,969 output tokens, 25.1 s

One model call, about a fifth of ReAct's tokens, and the right answer. list_orders returned a real list, so the loop worked on the first try, and the program kept a price cache, so it made the same 37 calls ReAct did. It calls the tools without try, so a tool error stops the program instead of becoming a zero. It still wrote helpers for results that might be strings: it can't know the shape of the data until the program runs, so it writes defensively.

The program also reads every order. The prompt says each program has a cap on tool calls but not its value, and tells the model never to skip records or stop early to stay under it. A model that knows the number counts its own calls and stops short of it, and the partial result becomes the answer. Step 4 shows what a cap that's too small does instead.

Step 04

Size the tool budget with CodeActionConfig

Code-action has three settings. Pass them to build_agent as code_action=, either a dict or a CodeActionConfig from promptise.engine. An unknown key raises, and so does code_action= with any other pattern:

Setting

Default

What it does

What to watch

exec_timeout

120

Seconds a program may run in the sandbox; then its processes are killed

Bridged calls count against it, a fraction of a second each

max_repairs

1

How many times a failed program goes back to the model for a fix

Each repair is another model call and another container

max_tool_calls

50

Bridged tool calls each program may make; every call counts, failed ones too

Size it above what a correct program needs, never below

The budget is per program: a repaired program starts with a fresh one, so a run makes at most (max_repairs + 1) × max_tool_calls calls. A call beyond it raises ToolBudgetExceeded inside the program. Promptise logs a warning and discards the program's output, even if the program caught the error. The repair prompt then asks for a program that does the whole job with fewer calls, or the reply CANNOT_FINISH_WITHIN_CALL_CAP. That reply, or a budget hit with no repair left, raises CodeActionBudgetError from promptise.engine, a GraphExecutionError.

To see it at work, limits_demo.py gives the agent a budget of 20 tool calls for the top-customer question, which needs 37, and two repairs:

Pythonlimits_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import asyncio
import logging
import sys

from promptise import build_agent
from promptise.config import StdioServerSpec
from promptise.engine import CodeActionConfig, GraphExecutionError

QUESTION = (
    "Which customer spent the most on shipped orders in September 2026, after discounts, "
    "and how much? An order's total is qty x unit price over its lines, minus its discount."
)

logging.basicConfig(format="%(message)s")
logging.getLogger("promptise.engine.code_action").setLevel(logging.DEBUG)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="code-action",
        code_action=CodeActionConfig(exec_timeout=60, max_repairs=2, max_tool_calls=20),
        trace_tools=True,  # print every tool call
    )
    try:
        result = await agent.ainvoke({"messages": [{"role": "user", "content": QUESTION}]})
        print(">>>", result["messages"][-1].content)
    except GraphExecutionError as exc:
        print("GraphExecutionError:", exc)
    finally:
        await agent.shutdown()


asyncio.run(main())

Here's a run, trimmed:

Output
[promptise] Initializing sandbox environment...
[promptise] Sandbox ready for code-action (backend: docker)
→ Invoking tool: list_orders with {'month': '2026-09'}
…
→ Invoking tool: get_order with {'order_id': 'SO-9019'}
✔ Tool result from get_order: {"id": "SO-9019", "customer": "Granite Health", "status": "shipped", "discount_pct": 10, "lines": [{"sku": "CB-055", "qty": 4}, {"sku": "KB-101", "qty": 2}, {"sku": "MN-270", "qty": 11}]}
code-action node 'reason': tool-call budget exhausted: the program already made 20 tool call(s) (max_tool_calls=20); the call to 'get_order' was refused and the program's output will be discarded
code-action program:
…
code-action exit=1 stdout='' stderr='Traceback (most recent call last):\n  File "/workspace/program.py", line 151, in <module>\n    main()\n …
GraphExecutionError: Graph 'code-action' failed at node 'reason': program failed after 2 attempt(s); last attempt: the job needs more tool calls than the per-program budget (max_tool_calls=20) allows: a program reached it, and the model reported that the whole job cannot be done in fewer calls

The first program made 20 calls, and the 21st was refused. The warning went to the log, and the program crashed. The repair prompt asked for the whole job in fewer calls. This server has no tool that returns many orders at once, so the model replied that it couldn't, and the run raised CodeActionBudgetError. limits_demo.py catches GraphExecutionError, which covers it.

In a second run, two programs caught the refused call and printed a partial total, Elmfield Cafe spent $3640.00 and then Acme Corp spent $296.15. Promptise discarded both, and that run raised too. A budget that's too small costs you a failed run, not a wrong answer. Size it anyway:

  • Size the budget above what a correct program needs. Count the calls one honest pass over the data takes and leave room. The default of 50 fits this question with 13 to spare.

  • Watch the log. A tool-call budget exhausted warning on promptise.engine.code_action means a program hit the cap. A second warning says when an answer came from a program written after a budget hit. Send that logger to your monitoring.

  • Give the model a bulk tool. A tool that returns many records at once lets a program do the same job in a few calls.

Warning

CodeActionBudgetError ends the run without an answer. Catch it, or GraphExecutionError, wherever a code-action agent runs unattended, and raise max_tool_calls or add a tool that returns many records at once.

With max_tool_calls set to 20 for a question that needs 37 calls, call 21 is refused and the program's output discarded even if it caught the error; the repair prompt asks for the whole job with fewer calls or the reply CANNOT_FINISH_WITHIN_CALL_CAP, and either way the run raises CodeActionBudgetError instead of returning a partial total.
FigureHow a tool budget below what the job needs ends a code-action run with an error

[05]

Code-action vs ReAct: which should you use?

Both agents in this guide reached the right answer. Where they differ is what each one sends to the model, and what you can see afterwards:

  • Tokens. ReAct read every tool result, so its input grows with the data. The code-action agent's results never enter the model's context, and nearly all of its tokens are the program it writes. Output tokens cost more than input tokens (eight times as much for GPT-5 mini), so the cost gap is smaller than the token gap, but code-action still comes out cheaper on jobs like this one.

  • Accuracy. On 30 orders, a ReAct agent with GPT-5 mini gets the arithmetic right. The gap opens as the data grows: the sandbox guide shows the same model getting two of four totals wrong over 500 rows in one tool result. A program sums 500 rows as easily as 30.

  • Time. About the same here. The code-action agent saves model calls, and spends that time on the container and the sequential bridge. It wins when the model would otherwise read a lot of results, and loses when a few quick tool calls would do.

  • Visibility. A ReAct agent shows its work in the transcript. A code-action agent shows you one line, and whether that line is right depends on code nobody reviewed.

Use code-action when

Stay with ReAct when

The answer is computed from many records: sums, joins, counts, top-N

A few tool calls answer the question

Tool results are big, and you'd rather they never enter the context

Tools return prose the model has to read and judge

You can size the tool budget and validate the one-line result

You can't predict how many calls the job takes

Token cost matters

You need the reasoning visible in the transcript

Docker is available where the agent runs

There's no container runtime

The reasoning patterns guide runs code-action on a different kind of task, expense rules written as sentences, next to the other eight built-in patterns. Two neighbours are worth knowing too. agent_pattern="managed" keeps a ReAct loop but replaces the growing transcript with a deduplicated ledger of facts, and the context engineering guide shows that approach. And if what you want is a plan or a checking step rather than a program, the plan-and-execute guide builds those.


[06]

Common mistakes with code-action agents

A crash is the easy failure: the repair loop sends the error back, and the model fixes the program. A program that starts with a stray line reading python, for example, crashes with NameError, and the repaired program runs. The hard failure is a program that doesn't crash: it catches an error, skips a record or stops early, and prints a number. These are the mistakes that lead there:

  • Trusting the one-line answer without checks. Promptise can't tell whether a program that stayed within the cap read all the data. A total that's too small, zero or None points to a program that skipped records. A few lines of validation on the RESULT line catch what the program hid.

  • Assuming the program lets errors raise. Models wrap tool calls in try often, even when the instructions say not to. A refused call over the budget is discarded even when caught. Any other tool error that a program catches makes those records count as zero.

  • Not reading the programs. Log them with one logging line, as in step 3, and read a sample. That's the price of the token savings.

  • Vague tool descriptions. The model sees only the signature and the first line of each tool's description. If that line doesn't name the fields a tool returns, the program guesses.

  • Expecting a prose answer. The answer is whatever the program prints after RESULT: (or its last line), with no prose around it. Ask for the format you want in the question, or pass the result to a second call.

  • Giving the program write tools. The sandbox contains the code, not your tools. The program can call every tool the agent has, as often as the budget allows. Keep that tool set small and read-only where you can. The human-in-the-loop guide covers approvals for the rest.

  • Planning for hundreds of bridged calls. Calls are sequential, so hundreds of them add up to a minute or more, and they count against exec_timeout. Add a tool that returns many records at once instead.


[07]

Frequently asked questions

What is a code-action agent?

An agent whose action is a program. Instead of calling tools one at a time, the model writes Python that calls them as functions and computes the answer, and the program runs in a sandbox. The approach is often called CodeAct after the 2024 paper Executable Code Actions Elicit Better LLM Agents.

Is a code-action agent better than ReAct?

For gather-then-compute jobs it uses far fewer tokens, because tool results never enter the model's context, and it does exact arithmetic over any amount of data. ReAct is the better default for short, conversational tasks, for tools that return prose, and when you can't predict how many tool calls a job takes.

Does a code-action agent need Docker?

In Promptise, yes. agent_pattern="code-action" turns on a Docker sandbox with no network, and if it can't start one, build_agent raises RuntimeError rather than running model-written code on your machine. The gVisor runtime is an option for stronger isolation.

Can a code-action agent call MCP tools?

Yes. Tools from servers= are bridged into the program like any other tool, and each call runs on your side through the normal MCP client. A result that is JSON arrives as a list or dict, other text as a string, and a tool error raises inside the program.

How do I stop a generated program from calling a tool too often?

Set max_tool_calls in code_action=. It counts every call each program makes, failed ones included, and a run makes at most (max_repairs + 1) × max_tool_calls. Size it above what a correct program needs: a budget below that ends the run with CodeActionBudgetError instead of an answer. Keep exec_timeout as a second limit on time.

How do I see the program a code-action agent wrote?

Set the promptise.engine.code_action logger to DEBUG, as code_action_agent.py does. Promptise logs each program, its exit code and its output. agent.last_report.tool_calls counts the bridged calls.


[08]

Where to go next

  • Code-Action: Agents that Write Programs: the pattern's reference, including the bridge, the tool-call budget and the security model.

  • Sandbox: container settings, limits and the gVisor backend.

  • AI Agent Reasoning Patterns in Python: all nine built-in patterns, code-action included, on three expense questions.

  • Reasoning Patterns and Prebuilt Patterns: every built-in agent_pattern and how each is wired.

  • AI Agent Code Execution Sandbox: the container, escape attempts and resource limits, with a CSV analysis agent.

  • Plan-and-Execute Agents in Python: when you want structure around a tool loop instead of a program.

  • Build a Production MCP Server in Python: design tools that return the structured data a program can use.

  • Trace Every Tool Call: see what an agent did, call by call.

Contents

  1. 01What is a code-action agent?
  2. 02How does a code-action agent work?
  3. 03What you need
  4. 04How to build a code-action agent in Python, step by step
  5. 05Code-action vs ReAct: which should you use?
  6. 06Common mistakes with code-action agents
  7. 07Frequently asked questions
  8. 08Where to go next

Learning paths

Want more structure? Paths put guides in order, like a short course.

See the paths →

> Tools and the Model Context Protocol (MCP)

Related guides

All guides in this topic →
  • // 01Advanced · 18 minMulti-Tenant AI Agents: Keep Each Customer's Data ApartBuild a multi-tenant AI agent in Python: per-user tokens, tenant-scoped MCP tools and isolated sessions, with runs proving one tenant can't read another.
  • // 02Beginner · 18 minWhat Is MCP (Model Context Protocol)? A Developer's GuideWhat MCP is and how it works: hosts, clients, servers, tools, resources, transports and SDK 2.x. Build a small MCP server and connect an agent to it.
  • // 03Beginner · 7 minWhat Is Tool Calling? LLM Function Calling ExplainedWhat tool calling (function calling) is: how an LLM asks your code to run a function, the JSON schema it sees, parallel calls, and how it differs from MCP.
  • // 04Intermediate · 20 minMCP Tools vs Resources vs Prompts (With Python Examples)When to use an MCP tool, resource or prompt, and how to build each in Python: resource templates, prompt arguments, tests and feeding them to an agent.
  • // 05Beginner · 12 minHow to Connect MCP Servers to Your AI Agent in PythonGive your AI agent real tools with the Model Context Protocol. Connect local and remote MCP servers to a Python agent, step by step, with code you can run.
  • // 06Intermediate · 18 minBuild a Production MCP Server in Python (Step by Step)Build an MCP server in Python ready for real agents: typed tools, clear errors, API keys with roles, rate limits, a tamper-evident audit log and tests.

Keep going.

Browse every guide by topic and level, or follow a learning path that puts them in order.

All guidesLearning paths