Skip to main content

MLflow Tutorial for AI Agents in Python — Part 2: Trace an AI Agent's Tool Calls

· 43 min read
Jagdish Kumawat
Founder @ Dewiride

In Part 1, each customer message made one trace with one step in it: the call to Claude. An agent that uses tools does more for each message. It asks Claude, runs the tools Claude picks, and asks Claude again. In Part 2 you give the support agent three tools on a shop database, and trace each of those steps as one tree per message.

This is Part 2 of the series.

  1. Part 1: Trace Your First Claude Call with MLflow
  2. Part 2: Trace an AI Agent's Tool Calls (you are here)

Every command and output on this page is real, captured while building the project.

Where the Agent Is Now​

After Part 1, the support agent answers questions about shipping, returns and the rest of the shop's handbook. Each answer is one trace with one span, Messages.create. The agent can't see orders, so for anything about a specific order it sends the customer to the support team's email.

This part gives it three tools on a small shop database:

ToolWhat it doesWhat its traces show
find_orderLooks up an order by its number and the email address it was placed withA tool call, and a tool that fails when the email is wrong
check_stockFinds products by name, with their price and stockTwo tool calls in one turn
start_returnStarts a return for one item and works out the refundA tool that changes data, and the record of what it changed

The shop and its tools are the example. What this part teaches is how to trace them: one tree per customer message, holding the agent's turn, each call to Claude and each tool call.

How MLflow Traces an Agent​

To answer one message, a tool-using agent takes several steps. It sends the conversation to Claude, with the tools Claude may use. When Claude answers with a request to use a tool, the agent runs the tool and sends the result back. Claude then asks for another tool or writes the answer.

MLflow already records the calls to Claude, through the autologging from Part 1. The loop and the tools are your own code, so MLflow sees them only where you mark them with the @mlflow.trace decorator:

WhatWhereWhat it adds to the trace
@mlflow.trace(name="support_agent", span_type=SpanType.AGENT)The method that answers one customer messageThe root span of each trace
@mlflow.trace(span_type=SpanType.TOOL)Each tool methodOne span per tool call, with its arguments and its result
mlflow.anthropic.autolog(), from Part 1Every messages.create callOne Messages.create span per call to Claude

A traced function that runs while another traced function's span is open becomes its child, and so does an autologged call. MLflow's manual tracing guide says the decorator "detects the parent-child relationships between functions, making it compatible with auto-tracing integrations." So one customer message gives one tree:

The span type says what kind of step a span is. MLflow's span concepts page describes AGENT as "an autonomous agent operation" and TOOL as "a tool execution (typically by an agent), such as querying a search engine."

What This Part Costs​

MLflow is free, and the shop database is a file on your computer. The Claude API is paid: Claude Opus 5.5 costs $4 per million input tokens and $20 per million output tokens. The five customer messages in this part cost $0.064 in all, between $0.0077 and $0.0152 each, as MLflow reports on their traces. A message that uses a tool costs more than a plain answer, because the agent calls Claude at least twice for it, and every call sends the tools' descriptions along with the conversation.

Prerequisites​

Step 1: Give the Agent a Shop​

The tools need something to work on: a shop with products, orders and returns. It lives in a SQLite database, a single file that Python's built-in sqlite3 module opens. This step has nothing to do with MLflow yet.

Create src/store_support_agent/shop.sql with the shop's tables and sample data:

src/store_support_agent/shop.sql
-- The demo shop's tables and sample data.
-- Dates are counted back from the day you create the database, so the orders are always
-- recent. Money is stored in cents, as whole numbers, so amounts add up exactly.

PRAGMA foreign_keys = ON;

BEGIN;

CREATE TABLE products (
sku TEXT NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
price_cents INTEGER NOT NULL CHECK (price_cents > 0),
in_stock INTEGER NOT NULL CHECK (in_stock >= 0),
final_sale INTEGER NOT NULL DEFAULT 0 CHECK (final_sale IN (0, 1))
);

CREATE TABLE orders (
order_number TEXT NOT NULL PRIMARY KEY,
email TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('processing', 'shipped', 'delivered')),
ordered_on TEXT NOT NULL,
delivered_on TEXT,
tracking_number TEXT
);

CREATE TABLE order_items (
order_number TEXT NOT NULL REFERENCES orders (order_number),
sku TEXT NOT NULL REFERENCES products (sku),
quantity INTEGER NOT NULL CHECK (quantity > 0),
price_cents INTEGER NOT NULL CHECK (price_cents > 0),
PRIMARY KEY (order_number, sku)
);

CREATE TABLE returns (
return_id INTEGER PRIMARY KEY,
order_number TEXT NOT NULL,
sku TEXT NOT NULL,
reason TEXT NOT NULL CHECK (reason IN ('changed_mind', 'defective', 'wrong_item')),
refund_cents INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE (order_number, sku),
FOREIGN KEY (order_number, sku) REFERENCES order_items (order_number, sku)
);

INSERT INTO products (sku, name, price_cents, in_stock, final_sale) VALUES
('TENT-RL2', 'Ridgeline 2 Tent', 24900, 6, 0),
('TENT-RL4', 'Ridgeline 4 Tent', 38900, 0, 0),
('BAG-AL20', 'Alder 20 Sleeping Bag', 17900, 12, 0),
('PACK-SM30', 'Summit 30L Backpack', 12900, 9, 0),
('PACK-SM55', 'Summit 55L Backpack', 21900, 3, 0),
('LAMP-TR300', 'Trail 300 Headlamp', 3995, 25, 0),
('STOVE-CM1', 'Compact Camp Stove', 5900, 7, 1),
('MUG-TR', 'Trail Mug', 1450, 40, 0);

INSERT INTO orders (order_number, email, status, ordered_on, delivered_on, tracking_number) VALUES
('CF-1001', 'maya.chen@example.com', 'delivered', date('now', '-16 days'), date('now', '-12 days'), 'CFX-40218837'),
('CF-1002', 'sam.ortiz@example.com', 'shipped', date('now', '-3 days'), NULL, 'CFX-40219564'),
('CF-1003', 'maya.chen@example.com', 'delivered', date('now', '-49 days'), date('now', '-45 days'), 'CFX-40177102'),
('CF-1004', 'lee.park@example.com', 'processing', date('now'), NULL, NULL),
('CF-1005', 'sam.ortiz@example.com', 'delivered', date('now', '-9 days'), date('now', '-6 days'), 'CFX-40225419');

INSERT INTO order_items (order_number, sku, quantity, price_cents) VALUES
('CF-1001', 'TENT-RL2', 1, 24900),
('CF-1001', 'LAMP-TR300', 2, 3995),
('CF-1002', 'PACK-SM30', 1, 12900),
('CF-1003', 'BAG-AL20', 1, 17900),
('CF-1004', 'MUG-TR', 2, 1450),
('CF-1005', 'STOVE-CM1', 1, 5900),
('CF-1005', 'PACK-SM55', 1, 21900);

COMMIT;

What it sets up:

  • Four tables: products; orders; order_items, which lists what each order contains; and returns, which starts empty.
  • Money in cents, as whole numbers, so amounts add up exactly. The tools turn them into dollars.
  • Dates counted back from today, such as date('now', '-12 days'), so the orders stay recent whenever you create the database. Order CF-1001 was delivered 12 days ago, inside the 30-day return window.
  • Rules the database enforces: required columns, allowed values such as the three order statuses, and keys that link the tables.

src/store_support_agent/shop.py creates the database from that file, and opens it:

src/store_support_agent/shop.py
"""The demo shop's SQLite database: create it with sample data, and open it."""

import sqlite3
from contextlib import closing
from importlib.resources import files
from pathlib import Path

from store_support_agent.config import load_settings

SAMPLE_SHOP = files("store_support_agent").joinpath("shop.sql").read_text(encoding="utf-8")


def create_shop(database: Path) -> None:
"""Create the database with the demo shop's tables and data, replacing any earlier copy."""
database.unlink(missing_ok=True)
with closing(sqlite3.connect(database)) as connection:
connection.executescript(SAMPLE_SHOP)


def open_shop(database: Path) -> sqlite3.Connection:
"""Open the shop's database. Each row it returns can be read by column name."""
if not database.is_file():
raise FileNotFoundError(
f"There's no shop database at {database}. Create it with: uv run seed-shop"
)
connection = sqlite3.connect(database)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys = ON")
return connection


def main() -> None:
"""Create the demo shop's database: the seed-shop command."""
settings = load_settings()
create_shop(settings.shop_database)
print(f"Created {settings.shop_database} with the demo shop's products and orders.")
  • create_shop deletes any earlier copy and runs the whole script with executescript.
  • open_shop refuses to start when the file is missing, with a message that says how to create it. sqlite3.connect creates a new, empty file when there's none, so without the check the agent would start with a shop that has no tables.
  • row_factory = sqlite3.Row lets the tools read a column by its name, as in order["status"].
  • PRAGMA foreign_keys = ON turns on the checks between linked tables, which SQLite leaves off on each new connection.

The agent needs to know where the file is. src/store_support_agent/config.py gets a shop_database setting, and a load_settings function that both commands use to stop with a clear message when .env is wrong. It's the settings check that Part 1 had in chat.py, moved here so the new command can use it too. The complete file:

src/store_support_agent/config.py
"""Settings, read from environment variables and the .env file."""

import sys
from functools import lru_cache
from pathlib import Path
from typing import Annotated, Literal

from pydantic import Field, Secret, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict

# A secret text that must not be empty. The constraint goes on the text inside the secret.
ApiKey = Secret[Annotated[str, Field(min_length=1)]]


class Settings(BaseSettings):
"""The Claude API key and model the agent uses, its shop database, and where its traces go."""

model_config = SettingsConfigDict(
env_prefix="SUPPORT_",
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)

anthropic_api_key: ApiKey = Field(
validation_alias="ANTHROPIC_API_KEY",
description="Your Claude API key, from the Claude Console.",
)
claude_model: str = Field(
default="claude-opus-5-5",
min_length=1,
description="The Claude model that answers customers.",
)
effort: Literal["low", "medium", "high", "xhigh", "max"] = Field(
default="medium",
description="How much Claude thinks before it answers. More effort means more tokens.",
)
max_tokens: int = Field(
default=16000,
gt=0,
description="The most tokens one reply may use, thinking included.",
)
shop_database: Path = Field(
default=Path("shop.db"),
description="The SQLite file that holds the shop's products and orders.",
)
mlflow_tracking_uri: str = Field(
default="http://127.0.0.1:8080",
validation_alias="MLFLOW_TRACKING_URI",
description="The address of the MLflow tracking server.",
)
mlflow_experiment_name: str = Field(
default="store-support-agent",
min_length=1,
validation_alias="MLFLOW_EXPERIMENT_NAME",
description="The MLflow experiment that groups the agent's traces.",
)


@lru_cache
def get_settings() -> Settings:
"""Read the settings once, then reuse the same object everywhere."""
return Settings()


def load_settings() -> Settings:
"""Read the settings for a command, or stop with a message that says what to fix."""
try:
return get_settings()
except ValidationError as error:
problems = "; ".join(f"{e['loc'][0]}: {e['msg']}" for e in error.errors())
sys.exit(f"Check your .env file. {problems}")

Add the setting to .env.example, after SUPPORT_EFFORT:

.env.example (add after SUPPORT_EFFORT)
# The SQLite file that holds the demo shop's products and orders. Create it with: uv run seed-shop
SUPPORT_SHOP_DATABASE=shop.db

shop.db is also the default, so your .env from Part 1 works as it is. Keep the database out of Git, at the end of .gitignore:

.gitignore (add at the end)
# The demo shop's database: create it again any time with uv run seed-shop
shop.db

Then give the shop its own command in pyproject.toml:

pyproject.toml (changed lines)
[project.scripts]
seed-shop = "store_support_agent.shop:main"
support-chat = "store_support_agent.chat:main"

Create the database:

Terminal 2
uv run seed-shop
Output
Created shop.db with the demo shop's products and orders.

A terminal running uv run seed-shop, which prints Created shop.db with the demo shop's products and orders.

shop.db now sits in the project folder. Run uv run seed-shop again whenever you want the shop back as it started, without the returns you made.

Step 2: Describe the Tools to Claude​

Claude can only use a tool it has been told about. Each tool gets a name, a description of what it does and when to use it, and an input_schema for its arguments. This is find_order, the first entry of the TOOL_DEFINITIONS list in tools.py, which the next step creates:

src/store_support_agent/tools.py (the find_order tool)
{
"name": "find_order",
"description": (
"Look up an order by its order number and the email address it was placed with. "
"Returns its status (processing, shipped or delivered), its dates, its tracking "
"number and its items. Use it whenever a customer asks about an order."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"order_number": {
"type": "string",
"description": "The order number, such as CF-1001.",
},
"email": {
"type": "string",
"description": "The email address the order was placed with.",
},
},
"required": ["order_number", "email"],
"additionalProperties": False,
},
},

check_stock takes a product_name. start_return takes the order number, the email, the item's SKU and a reason, which enum limits to three values. Both are in the complete file in the next step.

Step 3: Trace Each Tool as a TOOL Span​

The tools are methods of a ShopTools class, which holds the database connection. Each tool method gets @mlflow.trace(span_type=SpanType.TOOL):

src/store_support_agent/tools.py (ShopTools, first part)
class ShopTools:
"""The shop actions Claude can ask for."""

def __init__(self, connection: sqlite3.Connection) -> None:
self._connection = connection
self._tools = {
"find_order": self.find_order,
"check_stock": self.check_stock,
"start_return": self.start_return,
}

def run(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
"""Run the tool Claude asked for, with the arguments Claude gave it."""
tool = self._tools.get(name)
if tool is None:
raise ToolError(f"There's no tool called {name}.")
return tool(**arguments)

@mlflow.trace(span_type=SpanType.TOOL)
def find_order(self, order_number: str, email: str) -> dict[str, Any]:
"""Return an order's status, dates, tracking number and items."""
order = self._verified_order(order_number, email)
items = self._connection.execute(
"""
SELECT i.sku, p.name, i.quantity, i.price_cents, p.final_sale,
r.return_id IS NOT NULL AS returned
FROM order_items AS i
JOIN products AS p ON p.sku = i.sku
LEFT JOIN returns AS r ON r.order_number = i.order_number AND r.sku = i.sku
WHERE i.order_number = ?
ORDER BY i.sku
""",
(order["order_number"],),
).fetchall()
return {
"order_number": order["order_number"],
"status": order["status"],
"ordered_on": order["ordered_on"],
"delivered_on": order["delivered_on"],
"tracking_number": order["tracking_number"],
"items": [
{
"sku": item["sku"],
"name": item["name"],
"quantity": item["quantity"],
"unit_price": dollars(item["price_cents"]),
"final_sale": bool(item["final_sale"]),
"returned": bool(item["returned"]),
}
for item in items
],
}

The tools.py file in a macOS-style code window: the ShopTools class keeps the database connection and a dictionary of its three tools, run calls the tool Claude asked for by name, and find_order, decorated with mlflow.trace and span type TOOL, verifies the order, reads its items with a SQL join and returns the order's status, dates, tracking number and items.

For each call, the decorator records:

The decorators sit on the three tool methods, not on run, which only picks the tool by its name. That way each span carries its tool's own name and arguments.

_verified_order, at the end of the file, gives the same message for a wrong order number and a wrong email address, so a guess reveals nothing about which orders exist. The complete file, with check_stock, start_return and the shop's return rules:

src/store_support_agent/tools.py
"""The agent's tools: look up an order, check stock and start a return.

MLflow traces each tool as a TOOL span: what Claude asked for, what the tool answered,
how long it took, and the error when it fails.
"""

import sqlite3
from datetime import UTC, date, datetime, timedelta
from typing import Any

import mlflow
from anthropic.types import ToolParam
from mlflow.entities import SpanType

RETURN_WINDOW = timedelta(days=30)
RETURN_SHIPPING_CENTS = 695
FREE_RETURN_REASONS = {"defective", "wrong_item"}

TOOL_DEFINITIONS: list[ToolParam] = [
{
"name": "find_order",
"description": (
"Look up an order by its order number and the email address it was placed with. "
"Returns its status (processing, shipped or delivered), its dates, its tracking "
"number and its items. Use it whenever a customer asks about an order."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"order_number": {
"type": "string",
"description": "The order number, such as CF-1001.",
},
"email": {
"type": "string",
"description": "The email address the order was placed with.",
},
},
"required": ["order_number", "email"],
"additionalProperties": False,
},
},
{
"name": "check_stock",
"description": (
"Find the shop's products whose name contains the given text, with each one's "
"SKU, price and how many are in stock. Use it whenever a customer asks whether "
"a product is available."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"product_name": {
"type": "string",
"description": "A product name or part of one, such as Ridgeline or headlamp.",
},
},
"required": ["product_name"],
"additionalProperties": False,
},
},
{
"name": "start_return",
"description": (
"Start a return for one item of a delivered order and work out the refund. The "
"shop's rules are checked: the order was delivered at most 30 days ago, and the "
"item isn't final sale or already returned. Only call it after the customer has "
"confirmed which item to return."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"order_number": {
"type": "string",
"description": "The order number, such as CF-1001.",
},
"email": {
"type": "string",
"description": "The email address the order was placed with.",
},
"sku": {
"type": "string",
"description": "The item's SKU, as find_order returns it.",
},
"reason": {
"type": "string",
"enum": ["changed_mind", "defective", "wrong_item"],
"description": (
"Why the customer returns the item. Return shipping is free for "
"defective and wrong_item. Use changed_mind for any other reason."
),
},
},
"required": ["order_number", "email", "sku", "reason"],
"additionalProperties": False,
},
},
]


class ToolError(Exception):
"""A tool couldn't do what Claude asked. Its message is sent back to Claude."""


def dollars(cents: int) -> str:
"""Format an amount in cents as dollars, such as 3995 as $39.95."""
return f"${cents / 100:,.2f}"


class ShopTools:
"""The shop actions Claude can ask for."""

def __init__(self, connection: sqlite3.Connection) -> None:
self._connection = connection
self._tools = {
"find_order": self.find_order,
"check_stock": self.check_stock,
"start_return": self.start_return,
}

def run(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
"""Run the tool Claude asked for, with the arguments Claude gave it."""
tool = self._tools.get(name)
if tool is None:
raise ToolError(f"There's no tool called {name}.")
return tool(**arguments)

@mlflow.trace(span_type=SpanType.TOOL)
def find_order(self, order_number: str, email: str) -> dict[str, Any]:
"""Return an order's status, dates, tracking number and items."""
order = self._verified_order(order_number, email)
items = self._connection.execute(
"""
SELECT i.sku, p.name, i.quantity, i.price_cents, p.final_sale,
r.return_id IS NOT NULL AS returned
FROM order_items AS i
JOIN products AS p ON p.sku = i.sku
LEFT JOIN returns AS r ON r.order_number = i.order_number AND r.sku = i.sku
WHERE i.order_number = ?
ORDER BY i.sku
""",
(order["order_number"],),
).fetchall()
return {
"order_number": order["order_number"],
"status": order["status"],
"ordered_on": order["ordered_on"],
"delivered_on": order["delivered_on"],
"tracking_number": order["tracking_number"],
"items": [
{
"sku": item["sku"],
"name": item["name"],
"quantity": item["quantity"],
"unit_price": dollars(item["price_cents"]),
"final_sale": bool(item["final_sale"]),
"returned": bool(item["returned"]),
}
for item in items
],
}

@mlflow.trace(span_type=SpanType.TOOL)
def check_stock(self, product_name: str) -> dict[str, Any]:
"""Return the products whose name contains the text, with their price and stock."""
rows = self._connection.execute(
"""
SELECT sku, name, price_cents, in_stock, final_sale
FROM products
WHERE name LIKE '%' || ? || '%'
ORDER BY name
""",
(product_name.strip(),),
).fetchall()
return {
"products": [
{
"sku": row["sku"],
"name": row["name"],
"price": dollars(row["price_cents"]),
"in_stock": row["in_stock"],
"final_sale": bool(row["final_sale"]),
}
for row in rows
]
}

@mlflow.trace(span_type=SpanType.TOOL)
def start_return(self, order_number: str, email: str, sku: str, reason: str) -> dict[str, Any]:
"""Start a return for one item, after checking the shop's return rules."""
order = self._verified_order(order_number, email)
if order["status"] != "delivered":
raise ToolError(f"Order {order['order_number']} hasn't been delivered yet.")
delivered_on = date.fromisoformat(order["delivered_on"])
if datetime.now(UTC).date() - delivered_on > RETURN_WINDOW:
raise ToolError(
f"Order {order['order_number']} was delivered on {delivered_on}, "
"more than 30 days ago, so its items can't be returned."
)
item = self._connection.execute(
"""
SELECT i.sku, i.quantity, i.price_cents, p.final_sale,
r.return_id IS NOT NULL AS returned
FROM order_items AS i
JOIN products AS p ON p.sku = i.sku
LEFT JOIN returns AS r ON r.order_number = i.order_number AND r.sku = i.sku
WHERE i.order_number = ? AND i.sku = ?
""",
(order["order_number"], sku.strip().upper()),
).fetchone()
if item is None:
raise ToolError(f"Order {order['order_number']} has no item {sku}.")
if item["final_sale"]:
raise ToolError(f"{item['sku']} was sold as final sale, so it can't be returned.")
if item["returned"]:
raise ToolError(f"A return for {item['sku']} has already been started.")

refund_cents = item["quantity"] * item["price_cents"]
if reason not in FREE_RETURN_REASONS:
refund_cents -= RETURN_SHIPPING_CENTS
with self._connection:
cursor = self._connection.execute(
"INSERT INTO returns (order_number, sku, reason, refund_cents) VALUES (?, ?, ?, ?)",
(order["order_number"], item["sku"], reason, refund_cents),
)
return {
"return_number": f"R-{cursor.lastrowid}",
"order_number": order["order_number"],
"sku": item["sku"],
"refund": dollars(refund_cents),
"return_shipping": (
"free"
if reason in FREE_RETURN_REASONS
else f"{dollars(RETURN_SHIPPING_CENTS)}, taken off the refund"
),
}

def _verified_order(self, order_number: str, email: str) -> sqlite3.Row:
"""Return the order, if it was placed with this email address."""
order = self._connection.execute(
"SELECT * FROM orders WHERE order_number = ? AND email = ?",
(order_number.strip().upper(), email.strip().lower()),
).fetchone()
if order is None:
# One message for a wrong number and a wrong email, so it gives nothing away.
raise ToolError(f"There's no order {order_number} with that email address.")
return order
  • dollars() turns cents into text such as $39.95.
  • start_return checks the handbook's rules in code: the order was delivered at most 30 days ago, and the item isn't final sale or already returned. The refund is the price paid, less $6.95 return shipping unless the item is defective or wrong. A broken rule raises ToolError with a sentence Claude can pass on to the customer.
  • with self._connection: commits the new return, or rolls it back if the insert fails.

Step 4: Trace the Agent's Turn as an AGENT Span​

reply, in agent.py, answers one customer message. It now runs the tool loop, and it gets the AGENT decorator:

src/store_support_agent/agent.py (the start of reply)
@mlflow.trace(name="support_agent", span_type=SpanType.AGENT)
def reply(self, customer_message: str) -> str:
"""Answer the customer's message, running the tools Claude asks for along the way."""
set_span_attributes({"model": self._settings.claude_model, "effort": self._settings.effort})
start = len(self._messages)
self._messages.append({"role": "user", "content": customer_message})
  • name="support_agent" names the span. Without it, the span would be called reply, after the method.
  • Everything that runs inside reply nests under its span: each call to Claude that autologging records, and each tool span. Without this decorator, every call to Claude and every tool call would be a separate trace, with nothing linking them to the message they answered: How to Nest Spans in an MLflow Trace.
  • The span's input is customer_message and its output is the answer, so the trace list shows each conversation in plain words.

Inside the loop, the agent runs every tool Claude asked for and sends the results back together:

src/store_support_agent/agent.py (in the loop)
# Run every tool Claude asked for, and send all the results back in one message.
results = [self._run_tool(b) for b in response.content if b.type == "tool_use"]
self._messages.append({"role": "user", "content": results})

Each tool call goes through _run_tool, which turns its outcome into the tool_result block that Claude reads:

src/store_support_agent/agent.py (_run_tool)
def _run_tool(self, call: ToolUseBlock) -> ToolResultBlockParam:
"""Run one tool call and turn its outcome into the tool_result block Claude reads."""
try:
result = self._tools.run(call.name, call.input)
except ToolError as error:
return {
"type": "tool_result",
"tool_use_id": call.id,
"content": str(error),
"is_error": True,
}
except sqlite3.Error:
logger.exception("The %s tool failed on the shop's database", call.name)
return {
"type": "tool_result",
"tool_use_id": call.id,
"content": "The shop's database isn't available right now.",
"is_error": True,
}
return {"type": "tool_result", "tool_use_id": call.id, "content": json.dumps(result)}
  • One tool_result per tool_use block, all in one user message, each answering its call's id. Claude can ask for several tools at once, and the agent answers them all: How to Handle Several Tool Calls in One Claude Reply.
  • A ToolError becomes a result with "is_error": True, so Claude learns that the tool failed and why, and can tell the customer: How to Tell Claude a Tool Failed with is_error. A database error is logged, and Claude only hears that the database isn't available.
  • The results are JSON text, made with json.dumps from the tool's dictionary.

The complete file:

src/store_support_agent/agent.py
"""The support agent: answers customers with Claude, calling the shop's tools when it needs to."""

import json
import logging
import sqlite3

import anthropic
import mlflow
from anthropic.types import MessageParam, ToolResultBlockParam, ToolUseBlock
from mlflow.entities import SpanType

from store_support_agent.config import Settings
from store_support_agent.prompts import SYSTEM_PROMPT
from store_support_agent.tools import TOOL_DEFINITIONS, ShopTools, ToolError
from store_support_agent.tracing import set_span_attributes

logger = logging.getLogger(__name__)

FALLBACK_REPLY = (
"Sorry, I can't help with that here. "
"Please email our support team at support@cedarfield.example."
)

# The most rounds of tool calls Claude may make while answering one message.
MAX_TOOL_ROUNDS = 8


class SupportAgent:
"""One conversation between a customer and the shop's support agent."""

def __init__(self, client: anthropic.Anthropic, tools: ShopTools, settings: Settings) -> None:
self._client = client
self._tools = tools
self._settings = settings
self._messages: list[MessageParam] = []

@mlflow.trace(name="support_agent", span_type=SpanType.AGENT)
def reply(self, customer_message: str) -> str:
"""Answer the customer's message, running the tools Claude asks for along the way."""
set_span_attributes({"model": self._settings.claude_model, "effort": self._settings.effort})
start = len(self._messages)
self._messages.append({"role": "user", "content": customer_message})
try:
for tool_rounds in range(MAX_TOOL_ROUNDS + 1):
response = self._ask_claude()
if response.stop_reason == "refusal":
category = response.stop_details.category if response.stop_details else None
logger.warning("Claude declined a message (category: %s)", category)
break
if response.stop_reason == "max_tokens":
logger.warning(
"A reply reached max_tokens (%d) and was cut short",
response.usage.output_tokens,
)
break

# Keep Claude's whole turn, thinking included, so the next request sends it back.
self._messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
set_span_attributes({"tool_rounds": tool_rounds})
answer = "".join(b.text for b in response.content if b.type == "text")
if answer:
return answer
logger.warning(
"Claude returned no text (stop reason: %s)", response.stop_reason
)
break
if tool_rounds == MAX_TOOL_ROUNDS:
logger.warning("Claude still wanted tools after %d rounds", MAX_TOOL_ROUNDS)
break

# Run every tool Claude asked for, and send all the results back in one message.
results = [self._run_tool(b) for b in response.content if b.type == "tool_use"]
self._messages.append({"role": "user", "content": results})
except anthropic.APIError:
# The message never got an answer, so the whole exchange leaves the conversation.
del self._messages[start:]
raise

# No answer to show: drop the exchange, so the conversation goes on from before it.
del self._messages[start:]
return FALLBACK_REPLY

def _ask_claude(self) -> anthropic.types.Message:
"""Send the conversation so far, with the tools Claude may call."""
return self._client.messages.create(
model=self._settings.claude_model,
max_tokens=self._settings.max_tokens,
system=[
{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}
],
tools=TOOL_DEFINITIONS,
messages=self._messages,
output_config={"effort": self._settings.effort},
)

def _run_tool(self, call: ToolUseBlock) -> ToolResultBlockParam:
"""Run one tool call and turn its outcome into the tool_result block Claude reads."""
try:
result = self._tools.run(call.name, call.input)
except ToolError as error:
return {
"type": "tool_result",
"tool_use_id": call.id,
"content": str(error),
"is_error": True,
}
except sqlite3.Error:
logger.exception("The %s tool failed on the shop's database", call.name)
return {
"type": "tool_result",
"tool_use_id": call.id,
"content": "The shop's database isn't available right now.",
"is_error": True,
}
return {"type": "tool_result", "tool_use_id": call.id, "content": json.dumps(result)}

The reply method of agent.py in a macOS-style code window: mlflow.trace with the name support_agent and span type AGENT, the loop that calls Claude up to MAX_TOOL_ROUNDS plus one times, stops on a refusal or max_tokens, returns the text when Claude stops asking for tools, and otherwise runs every tool_use block and sends the results back.

How the loop works:

  • range(MAX_TOOL_ROUNDS + 1) allows at most 8 rounds of tools per message, so a confused exchange can't go on calling Claude, and costing money, forever.
  • The stop reason decides the next step. tool_use means Claude wants tools, so the agent runs them and asks again. Any other ending means Claude is done, and its text is the answer. refusal and max_tokens end the turn with the fallback reply, as in Part 1.
  • Claude's turn is kept whole, tool requests and thinking included, before the results go back. The API needs each tool_result to answer a tool_use block in the message just before it: How to Send a Tool Result Back to Claude in Python.
  • start marks where this message's exchange begins. When there's no answer to show, del self._messages[start:] removes the whole exchange, tool rounds included, and the conversation carries on from before it. Part 1 removed one message; with tools, one exchange can add several.

That's all the tracing code the loop needs: the decorator on reply here, and the one on each tool from Step 3.

Step 5: Record Attributes on the Agent's Span​

A span's inputs and outputs hold what a function received and returned. Attributes hold any other facts you want to see next to them. The agent records three: the model and the effort level, which say how the message was answered, and tool_rounds, the number of rounds of tools it took. Add a helper to src/store_support_agent/tracing.py:

src/store_support_agent/tracing.py
"""Send the agent's traces to the MLflow tracking server."""

from typing import Any

import mlflow

from store_support_agent.config import Settings


def start_tracing(settings: Settings) -> None:
"""Point MLflow at the tracking server and the experiment, then trace every Claude call."""
mlflow.set_tracking_uri(settings.mlflow_tracking_uri)
mlflow.set_experiment(settings.mlflow_experiment_name)
mlflow.anthropic.autolog()


def set_span_attributes(attributes: dict[str, Any]) -> None:
"""Add attributes to the span that is running now, if the call is being traced."""
span = mlflow.get_current_active_span()
if span is not None:
span.set_attributes(attributes)
  • mlflow.get_current_active_span() returns the span of the traced function that's running. Called from reply, that's support_agent.
  • set_attributes adds key-value pairs to it: How to Add Attributes to a Span in MLflow.
  • The None check matters. With nothing being traced, for example with tracing turned off, there's no active span, and get_current_active_span() returns None. Without the check, the agent itself would fail with an AttributeError.

reply calls it twice: with the model and effort as soon as it starts, and with tool_rounds when Claude writes the answer.

Step 6: Update the Instructions and the Chat​

Claude needs to know what the tools are for and how to use them with customers. The complete src/store_support_agent/prompts.py, with the paragraph about orders replaced:

src/store_support_agent/prompts.py
"""The instructions Claude follows as the shop's support agent."""

from importlib.resources import files

HANDBOOK = files("store_support_agent").joinpath("handbook.md").read_text(encoding="utf-8")

SYSTEM_PROMPT = f"""You are the customer support agent of Cedarfield Outdoor, an online shop for \
camping and hiking gear. Customers chat with you in a terminal window.

Answer questions about the shop's shipping, returns, refunds, exchanges, warranty and price \
adjustments, using only the handbook below. When the handbook doesn't answer a question, say so \
and give the support team's email address.

Your tools look up an order, check whether a product is in stock and start a return. To look up \
or return an order, you need its order number and the email address it was placed with, so ask \
for both first. Before you start a return, tell the customer which item you'll return and the \
refund they'll get, and wait for them to confirm. When a tool reports an error, explain it to the \
customer in plain words. Never guess an order's details or a product's stock: use the tools.

Keep replies short and friendly: two to four sentences of plain text, without Markdown.

<handbook>
{HANDBOOK}
</handbook>"""

The new paragraph asks for the order number and the email before any lookup, has Claude describe a return and wait for the customer to confirm it, and tells it to explain tool errors in plain words and never guess an order's details. Add one line at the end of the Returns section of src/store_support_agent/handbook.md, so the agent can say what happens next:

src/store_support_agent/handbook.md (add at the end of Returns)
- Once a return is started, the customer gets a return label by email, at the address used for the order.

src/store_support_agent/chat.py opens the shop and hands its tools to the agent. The complete file:

src/store_support_agent/chat.py
"""A terminal chat with the shop's support agent."""

import logging
import sys
from contextlib import closing

import anthropic

from store_support_agent.agent import SupportAgent
from store_support_agent.config import Settings, load_settings
from store_support_agent.shop import open_shop
from store_support_agent.tools import ShopTools
from store_support_agent.tracing import start_tracing

logger = logging.getLogger(__name__)

WELCOME = "Cedarfield Outdoor support. Ask a question, /new starts over, /quit leaves."


def main() -> None:
"""Chat with the support agent in the terminal until the customer quits."""
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
settings = load_settings()
try:
shop = open_shop(settings.shop_database)
except FileNotFoundError as error:
sys.exit(str(error))

with closing(shop):
start_tracing(settings)
client = anthropic.Anthropic(api_key=settings.anthropic_api_key.get_secret_value())
chat(client, ShopTools(shop), settings)


def chat(client: anthropic.Anthropic, tools: ShopTools, settings: Settings) -> None:
"""Read the customer's messages and print the agent's answers."""
agent = SupportAgent(client, tools, settings)
print(WELCOME)
while True:
try:
message = input("You: ").strip()
except EOFError, KeyboardInterrupt:
print()
break
if not message:
continue
if message == "/quit":
break
if message == "/new":
agent = SupportAgent(client, tools, settings)
print("Started a new conversation.")
continue

try:
answer = agent.reply(message)
except anthropic.AuthenticationError:
sys.exit("Claude rejected the API key. Check ANTHROPIC_API_KEY in your .env file.")
except anthropic.RateLimitError:
print("Claude is busy right now. Please try again in a minute.")
continue
except anthropic.APIConnectionError:
print("Can't reach Claude. Check your internet connection, then try again.")
continue
except anthropic.APIStatusError as error:
logger.warning(
"Claude API error %s (request ID %s)", error.status_code, error.request_id
)
print("Something went wrong on Claude's side. Please try again.")
continue
print(f"Agent: {answer}")
  • load_settings() checks .env first, as before.
  • open_shop stops the chat with its message when shop.db is missing.
  • closing(shop) closes the database connection when the chat ends, however it ends.
  • chat() is the loop from Part 1. Each new conversation, at the start and after /new, gets the same ShopTools.

Step 7: Chat with the Agent​

If the server from Part 1 isn't running, start it again in the first terminal, in the mlflow-server folder:

Terminal
uv run mlflow server --port 8080

Then, in the second terminal:

Terminal 2
uv run support-chat

Send these five messages, with /new before the return so it starts a new conversation, then type /quit:

Output
Cedarfield Outdoor support. Ask a question, /new starts over, /quit leaves.
You: Hi! Where is my order CF-1002? My email is sam@example.com
Agent: Sorry, I couldn't find an order CF-1002 placed with sam@example.com. Could you check the order number and email address? Your order confirmation email has both, and it's possible the order was placed with a different email address.
You: Sorry, it's sam.ortiz@example.com
Agent: I found it, thanks! Your order CF-1002 (one Summit 30L Backpack) was placed on November 30, 2026. It has shipped but hasn't been delivered yet. Your tracking number is CFX-40219564, and you can use it to follow your parcel.
You: Do you have the Ridgeline 2 Tent and the Summit 55L Backpack in stock?
Agent: Good news, both are in stock! We have 6 Ridgeline 2 Tents at $249.00 and 3 Summit 55L Backpacks at $219.00. If you order both, standard shipping is free, since your order would be over $75.
You: /new
Started a new conversation.
You: I'd like to return the two headlamps from order CF-1001. My email is maya.chen@example.com, and I just don't need them anymore.
Agent: I found order CF-1001, and the two Trail 300 Headlamps were delivered on November 21. I can return both of them for $79.90 ($39.95 each). Since you're returning them because you don't need them anymore, $6.95 for return shipping comes off, so you should get about $72.95 back, and I'll confirm the exact amount once the return is started.

To be returned, the headlamps need to be unused and in their original packaging with the tags still on. Would you like me to go ahead?
You: Yes, please go ahead.
Agent: Your return is started. The return number is R-1, and it covers both Trail 300 Headlamps. Your refund will be $72.95, which is $79.90 minus the $6.95 for return shipping.

A return label is on its way to maya.chen@example.com. Your refund will go back to your original payment method within 5 business days after the headlamps reach our warehouse.
You: /quit
2026/12/03 07:53:03 INFO mlflow.tracing.export.async_export_queue: Flushing the async trace logging queue before program exit. This may take a while...

The chat in a terminal: the agent can't find order CF-1002 with sam@example.com and asks the customer to check, finds it with sam.ortiz@example.com, reports both products in stock with prices, and after /new describes the return of two Trail 300 Headlamps, waits for the customer's yes, and starts return R-1 with a $72.95 refund.

The agent used its tools for every message. With the wrong email address, the lookup failed and the agent asked the customer to check. With the right one, it found the order. It checked two products at once. For the return, it described the item and the refund, waited for "Yes, please go ahead.", and only then started return R-1. Your conversation will be worded differently, and Claude may make other choices, such as checking the two products one after the other.

Each customer message made one trace: five in all.

Step 8: Find the Agent's Traces​

Open http://127.0.0.1:8080, click the store-support-agent experiment, then Traces in the sidebar:

The Traces page of store-support-agent: five new traces from 1 minute ago, with the customer's messages as inputs, the agent's answers as outputs, durations of 3.3 to 8.9 seconds, state OK and 4545 to 6449 tokens, above Part 1's three traces from 2 days ago, whose outputs are Claude's raw responses.

The five new traces sit above Part 1's three. Their Input is the customer's message, as {"customer_message": ...}, and their Output is the agent's answer, because the list shows each trace's root span, now support_agent. Part 1's root span was Messages.create, so its outputs are Claude's whole responses. Each trace's tokens add up every call to Claude made for that message.

Step 9: Read a Trace's Span Tree​

Click the oldest of the five, the first question about order CF-1002:

Trace af60cbc3: Success, 8.95 seconds, 4.5K tokens, about $0.0152. The span tree shows support_agent with three children: Messages.create taking 7.04 seconds and about $0.0122, find_order in red with an error dot taking 18.70 milliseconds, and Messages.create taking 1.86 seconds and about $0.003. The support_agent span's input is the customer's message and its output is the agent's answer.

The Spans tree on the left is the whole message, in order:

  1. support_agent, 8.95 seconds: the agent's turn, the root of the tree.
  2. Messages.create, 7.04 seconds: Claude read the message and asked for find_order.
  3. find_order, 18.70 milliseconds, in red: the tool failed.
  4. Messages.create, 1.86 seconds: Claude got the error and wrote the reply.

Almost all the time went to Claude; the database lookup took less than 20 milliseconds of the 8.95 seconds. The trace is still marked Success, although a span inside it failed, because the agent handled the failure and answered. A red span marks a failed step, even inside a successful trace.

Step 10: Read the Agent's Attributes​

With support_agent selected, click Attributes:

The Attributes tab of the support_agent span: model claude-opus-5-5, effort medium and tool_rounds 1.

The three attributes from Step 5: the model, the effort, and tool_rounds 1, one round of tools before the answer. A message that needed many rounds would stand out here at a glance.

Step 11: See What Claude Asked For​

Click the first Messages.create span and scroll down to its Outputs:

The Outputs of the first Messages.create span: an Assistant Tool calls card with find_order, order_number CF-1002 and email sam@example.com, then the response's id, container null, and content holding a tool_use block with its id, input, name find_order and type tool_use.

This is Claude's request, as the API returned it. MLflow shows it first as a card, Assistant Tool calls, with the tool and its arguments, then as the raw response: a tool_use block with an id, the tool's name and its input. The tool_result that the agent sent back answers that id.

Step 12: See Why a Tool Failed​

Click the red find_order span, then Events:

The Events tab of the find_order span, marked with 1 event: an Exception with exception.message There's no order CF-1002 with that email address, and exception.type ToolError.

The exception's message and type: There's no order CF-1002 with that email address., raised as a ToolError. Below them, exception.stacktrace holds the traceback. The exception didn't stop the agent: _run_tool caught it and sent its message to Claude as an is_error result. MLflow recorded it anyway, because it left the traced method, find_order, before anything caught it. MLflow's manual tracing guide describes this: the decorator "Captures exceptions during function execution and records them as span events."

Step 13: Follow a Tool's Inputs and Outputs​

Go back to the list and open the next trace, where the customer gave the right email address. Click its find_order span:

The find_order span of trace 0b187f6a, taking 0.58 milliseconds: inputs order_number CF-1002 and email sam.ortiz@example.com, outputs order_number CF-1002, status shipped, ordered_on 2026-11-30, delivered_on null, tracking_number CFX-40219564 and one item, PACK-SM30 Summit 30L Backpack, quantity 1, unit price $129.00, not final sale and not returned.

The Inputs are the tool's two arguments, without self. The Outputs are exactly what Claude saw before it answered. When an answer looks wrong, compare it with the tool's output. Here, Claude's "It has shipped but hasn't been delivered yet" matches the status shipped and the null delivery date.

Step 14: See Two Tools in One Turn​

Open the third trace, the stock question:

The span tree of trace 389ec04f: support_agent with Messages.create, two check_stock spans taking 2.68 and 0.39 milliseconds, and a second Messages.create. The selected check_stock span has the input product_name Summit 55L and the output product PACK-SM55, Summit 55L Backpack, price $219.00, 3 in stock, not final sale.

Claude asked for both products in one reply, so one round ran two check_stock spans, and the second call to Claude got both results. The second search was for Summit 55L: Claude shortened the product's name, and the tool's search on part of the name still found the Summit 55L Backpack.

Step 15: Check What a Tool Changed​

Open the newest trace, "Yes, please go ahead.", and click start_return:

The start_return span of trace 540de22e: inputs order_number CF-1001, email maya.chen@example.com, sku LAMP-TR300 and reason changed_mind, outputs return_number R-1, order_number CF-1001, sku LAMP-TR300, refund $72.95 and return_shipping $6.95, taken off the refund.

Claude turned "I just don't need them anymore" into the reason changed_mind, and the tool took $6.95 return shipping off the $79.90 the two headlamps cost. This span is the record of a change the agent made to the shop: who it was for, what it changed and why. Every tool that writes data leaves one.

Your Folders Now Look Like This​

source/
source/
├── mlflow-server/
│ ├── .venv/
│ ├── mlflow.db
│ ├── pyproject.toml
│ └── uv.lock
└── dewiride-store-support-agent/
├── .env
├── .env.example
├── .gitignore
├── .python-version
├── .venv/
├── README.md
├── pyproject.toml
├── shop.db
├── uv.lock
└── src/
└── store_support_agent/
├── __init__.py
├── agent.py
├── chat.py
├── config.py
├── handbook.md
├── prompts.py
├── shop.py
├── shop.sql
├── tools.py
└── tracing.py

shop.py, shop.sql and tools.py are new, and shop.db is the database they made. Part 3 continues from here.

Stop the Server When You're Done​

In the first terminal, press Ctrl+C. mlflow.db keeps every trace, and shop.db keeps the return the agent started; uv run seed-shop puts the shop back as it started.

To remove everything from this series so far instead:

  • delete the mlflow-server and dewiride-store-support-agent folders;
  • in the Claude Console, delete the API key if you created it only for this series.

The Claude API bills only for calls you make, so a stopped agent costs nothing.

Common Mistakes​

MistakeWhat happensDo this instead
Tracing the tools but not the function that runs themEvery call to Claude and every tool call becomes its own trace, with nothing linking themPut @mlflow.trace on the function that answers one message, as reply has it
Calling span.set_attributes(...) without checking for NoneAttributeError: 'NoneType' object has no attribute 'set_attributes' whenever tracing is offCheck if span is not None: first, as set_span_attributes does
Catching ToolError inside the tool method itselfThe span stays OK, with no exception eventLet it leave the traced method, and catch it one level up, as _run_tool does
Forcing a tool with tool_choice={"type": "any"} on Claude Opus 5.5400: tool_choice: type "tool" and "any" are not supported for this model.Leave tool_choice out, and say when to use each tool in its description and the system prompt
Answering only the first of two tool calls400: `tool_use` ids were found without `tool_result` blocks immediately afterSend a tool_result for every tool_use block, in one user message

Troubleshooting​

SymptomLikely causeFix
There's no shop database at shop.db. Create it with: uv run seed-shopThere's no shop.db in the folder you ran the chat fromRun uv run seed-shop in the agent's folder
A trace is marked Success, but one of its spans is redA tool failed, and the agent handled itOpen the red span's Events tab to see the error
Each call to Claude is its own trace, with no support_agent spanreply has no @mlflow.trace decoratorAdd it, as in Step 4
A tool span's Attributes tab says "No attributes found"Only support_agent gets attributes in this partNothing to fix

FAQ​

Why is the trace marked Success when find_order failed?​

Because the agent handled the failure. The exception left find_order, so its span is marked as failed, but _run_tool caught it and the customer still got an answer. A trace is marked Error only when an exception leaves its root span, here support_agent.

Do the traces store customers' email addresses?​

Yes. A tool span's inputs hold the order number and the email address the customer typed, and its outputs hold what the database returned. Treat mlflow.db like the shop's own customer data.

Why not trace run, which every tool call goes through?​

A span on run would be called run for every tool, with the tool's name as just another input. On the tool methods, each span carries its tool's own name and arguments, which is what you look for in a trace.

Does Claude always call two tools at once for two products?​

No. Claude decides, and in another run it may check the products one after the other, in two rounds. The trace shows which it did: two check_stock spans between the same two Messages.create spans, or separated by another call to Claude.

Conclusion​

You gave the support agent three tools on a SQLite shop and traced each customer message as one tree: an AGENT span for the agent's turn, a Messages.create span for each call to Claude, and a TOOL span for each tool call, with its arguments, result, timing and errors. Five messages cost $0.064, and their traces showed a failed lookup and why it failed, two tools in one turn, and the exact return the agent started.

Part 3, coming next, follows customers across many messages, with users and sessions.

Additional Resources​


← Previous: Part 1: Trace Your First Claude Call with MLflow