Network cables and a hand-drawn trace diagram representing calls between an LLM and external tools

Tracing Tool Calls in LLM Agents: What to Log and Why

Tracing an LLM tool call means recording four things that often disagree: what the model asked for, the exact arguments it sent, what your code actually executed, and what went back into the context. When an agent books the wrong meeting or loops eleven times on a search tool, the bug nearly always lives in the gap between two of those four. Without a trace that keeps them side by side, you are debugging from a vibes-based summary.

This guide is about tracing LLM tool calls specifically: how to shape spans, what to put on them, which failures to name, and which queries pay for themselves. For the surrounding stack, start with the observability stack for LLM apps; for how calls get chosen in the first place, see agent tool routing.

The four-way mismatch

  1. Requested: the tool name and JSON the model emitted. It may name a tool that does not exist or omit a required field.
  2. Validated: what survived your schema check, defaults, and permission rules. Fields may be coerced or dropped here.
  3. Executed: the real HTTP call, SQL statement, or shell command, after templating and auth injection.
  4. Returned: the result as the model sees it, after truncation, redaction, and formatting. A 400 KB JSON body that is cut to 6 KB changes the next decision.

Logging only step 1 (what most frameworks show by default) leaves you unable to tell a model mistake from a harness mistake. Logging all four turns “the agent is flaky” into a specific, fixable claim.

Span design for an agent run

Use one trace per user request or agent run, with child spans for each model call and each tool invocation. The OpenTelemetry generative AI conventions include operation types for inference and tool execution, so following them keeps your data readable by standard tooling.

agent.run  (trace_id=4bf9, tenant=acme-eu, release=prompt@2026-11-27.2)
├─ llm.call #1        in=5,980 out=94   finish=tool_calls   1.1s
│  └─ tool.request    name=search_orders  args_hash=a91c
├─ tool.execute       name=search_orders  status=ok  rows=3  240ms
├─ llm.call #2        in=6,410 out=71   finish=tool_calls   0.9s
│  └─ tool.request    name=refund_order   args_hash=77be  idempotency_key=ord_1042:r1
├─ tool.execute       name=refund_order   status=policy_denied  3ms
├─ llm.call #3        in=6,520 out=210  finish=stop         2.4s
└─ guardrail.output   verdict=pass

Two design choices matter. Make the request span and the execute span separate, so the time between “model asked” and “code ran” (validation, approvals, queueing) is visible. And give every tool span a parent that is the LLM call that produced it, not just the run; parallel tool calls in one model turn then group naturally.

Fields to put on a tool span

FieldNotes
tool name, tool versionVersion your schemas; a changed description changes model behavior
arguments (redacted) and arguments hashHash always; store raw args only in the access-controlled content store
validation outcome and which fields were coercedShows where the harness repaired the model’s output
permission decision and policy rule IDTies to your permissions model
status: ok, error, timeout, denied, partial, skippedA closed enum so you can group on it
latency of queue, execute, and totalSlow tools and slow harnesses look different
result size before and after truncationTruncation is a hidden cause of wrong follow-up calls
retry count and idempotency keyDetect duplicate side effects
cost, if the tool bills (search API, sandbox minute)Feed the ledger in LLM cost attribution
step index and loop-detector countersEnables “same call three times” alerts

A failure taxonomy worth naming

Give failures names so dashboards can count them. Seven categories cover most of what goes wrong in production:

  • Unknown tool. The model called a function you never offered. Often a sign of a stale prompt or leaked examples.
  • Bad arguments. Missing required field, wrong type, or a value outside an enum. Track per tool; one noisy tool usually has a vague schema.
  • Wrong tool, valid call. Schema-clean but semantically off (searching orders when the user asked about invoices). Needs eval labels, not just traces.
  • Execution failure. Timeout, 5xx, auth expiry. Separate transient from permanent.
  • Partial success. The tool returned data and a warning; the model ignored the warning.
  • Truncated or poisoned result. The output was cut, or it contained instructions aimed at the model.
  • Loop. The same tool with near-identical arguments three or more times in one run.

The sixth item is a security concern as much as a quality one; trace the source of the content that entered the context so you can find the injection point later. Treat tool results as untrusted input, a habit also stressed in MCP vs API function calling.

Side effects need idempotency keys in the trace

Reads are forgiving; writes are not. If a refund call times out and the harness retries, was the first attempt processed? Generate a deterministic idempotency key from the run ID, tool name, and a normalized argument hash, pass it to the downstream API where supported, and log it on both attempts. Then a single query can show whether any key has more than one successful execution.

For tools that cannot be made idempotent, log an explicit side_effect=true attribute and require an approval span before execution. The trace then doubles as the audit log your security reviewers will ask for.

Five queries that pay for the instrumentation

  1. Tool error rate by tool and release. Catches the schema edit that broke one function on Thursday.
  2. Bad-argument rate per tool, top five invalid fields. Tells you which description to rewrite or which parameter to make an enum.
  3. Runs with more than N tool calls (try 8 for support flows). These are your loops and your cost outliers.
  4. p95 duration per tool, split by queue and execute. Separates a slow API from a saturated worker pool.
  5. Idempotency keys with more than one success. A zero-tolerance duplicate-write detector.

A useful target for a mature agent: bad-argument rate under 2% per tool, unknown-tool calls effectively zero, and fewer than 1% of runs tripping the loop detector. Treat regressions on these as release blockers, the same way you would a latency regression.

Gateways, MCP servers, and where to emit spans

If tools are exposed over MCP, you have two vantage points: the client (agent harness) and the server. Emit spans in both and join them with a propagated trace context header or metadata field, otherwise the server’s slow query is a separate story from the agent’s slow step. A central proxy is a convenient place to enforce naming and redaction; see MCP gateway patterns. Frameworks differ in how much they emit by default, so check what yours records before assuming coverage, and read the OpenAI function calling guide for the exact request and response fields your provider produces.

Turn traces into regression tests

Every confirmed bug trace is a free test case. Export the request, the model’s emitted call, and the corrected expectation into your eval set; then the failure cannot silently return. The loop from production trace to CI test is described in agent evals in CI, and the dataset hygiene (dedupe, version, label source) in golden datasets for LLM apps.

Sample sensibly. Keep every failed or denied tool span, every run that hit the loop detector, and a few percent of healthy runs. Store arguments and results only in the redacted content store with short retention, as outlined earlier in the observability stack guide.

FAQ

What should I log for an LLM tool call?

Log the tool name and version, redacted arguments plus a hash, validation outcome, permission decision, execution status, latency split into queue and execute, result size before and after truncation, retry count, idempotency key, and cost if the tool bills.

How do I trace parallel tool calls from one model turn?

Create a span for the model call and make each tool request a child of it. Give each call its provider-assigned ID as an attribute so you can match results to requests, and record start and end times to see actual concurrency.

How can I tell a model mistake from a harness bug?

Compare the requested call, the validated call, and the executed call. If the model emitted wrong arguments, it is a prompt or schema problem. If the requested call was fine and the executed one differs, the harness or integration changed it.

Should I store tool arguments and results in traces?

Store a hash and metadata on every span, and keep raw arguments and results only in an access-controlled, redacted content store with short retention. Tool payloads often contain personal or confidential data.

How do I detect an agent stuck in a tool loop?

Count calls to the same tool with similar argument hashes within one run and flag runs above a threshold, such as three identical calls. Alert on the share of runs that trip the detector and cap steps per run in the harness.

Does OpenTelemetry support LLM tool calls?

Yes. The generative AI semantic conventions define attributes for model operations and tool execution, so you can emit standard spans and view them in any compatible backend. Add your own attributes for permissions and idempotency.

Related reading

About Mudasir Syed

Check Also

AI Agent Evaluation and Observability Guide — professional topic visual

AI Agent Evaluation and Observability Guide

AI agent evaluation: practical guide with definitions, implementation checklist, security notes, and internal links across the agentic stack.

Leave a Reply