Trace-Driven Debugging Workflow for Vercel AI SDK Agents

Read agent traces to find where execution left the plan.

· 9 min read · Updated
Cover illustration for “Trace-Driven Debugging Workflow for Vercel AI SDK Agents”
Trace Analysis · October 29, 2026 · 9 min read · 2,033 words

Debugging Vercel AI SDK agents requires traces that show where intended behavior diverged from execution. Automatic grouping of recurring AI agent failure patterns requires comparable records of those divergences. Stable metadata groups runs by session and account, while span-level evidence distinguishes planning, tool, retrieval, reasoning, and safety/policy failures. The workflow turns that evidence into a targeted fix and a regression test.

Why standard debugging tools miss most Vercel AI SDK agent failures

An agent can return a success code while selecting the wrong tool, skipping a permission check, or presenting unsupported conclusions. Crash logs and error monitors record execution faults, but these failures give output that looks right and may never raise exceptions. Planning errors, tool errors, retrieval errors, reasoning errors, and safety/policy violations therefore require inspection beyond request status.

Production incidents show the consequences of that distinction. Replit’s AI assistant deleted a production database despite explicit instructions forbidding it. OpenAI’s Operator made an unauthorized purchase that bypassed user confirmation, while an NYC government chatbot provided illegal business advice. Each agent passed internal assessment and failed in deployment. A dashboard tracking errors and latency could miss the behavioral failure because neither signal establishes whether the task was completed correctly.

The debugging unit must therefore preserve actions. Engineers need to know what information reached the agent, which tools it selected, and where execution departed from the required sequence. Of these debugging artifacts, only traces show what the agent actually did, step by step.

What a Vercel AI SDK trace actually contains and what each field tells you

A trace records each action in an agent run. Its root generation provides the enclosing context, while model calls, individual steps, and tool executions expose the work beneath it. Embedding and reranking spans show how context was prepared. Usage, errors, and selected runtime or tool context help show what was happening around each action. Read forward, the trace establishes the sequence of decisions and results, while reading backward from a wrong answer helps locate the first divergence.

Lifecycle hooks offer a consistent way to watch model calls, agents, tools, and other SDK functions. Span fields record when a call started, which model it used where that applies, how many tokens it used, and its completion status. These fields answer different questions. Timing identifies delay, usage exposes consumption, and completion information distinguishes an unfinished operation from a completed operation that returned bad content.

Metadata makes those observations findable during an incident. Session ID, user ID, organization, and agent name connect an isolated call to its run and account, but grouping by those identifiers is not itself failure-pattern detection. The nested structure supplies the behavioral evidence. An agent loop with ten tool calls produces ten child spans within its parent agent span, allowing the waterfall view to isolate an expensive call or a sequence violation without treating the entire run as one opaque event.

Setting up instrumentation that produces traces worth reading

A gap in the span tree can be worse than having no trace because it creates false confidence in coverage. An omitted call may be the very step that introduced the failure. In AI SDK v5/v6, every production call needs experimental_telemetry configured with isEnabled set to true. AI SDK v7 introduces a global telemetry registry that removes the need for per-call opt-in. The setup must match the SDK version.

To make those traces useful, attach stable session, user, organization, and agent identifiers to each call’s metadata. Runs can then group automatically by session and account. Avoid per-chunk spans for streaming responses because they cause cardinality explosion and non-linear backend cost growth. Exporters must also be asynchronous. A synchronous exporter on the request path adds latency to every production call.

Content recording needs a separate, explicit decision. recordInputs and recordOutputs are on by default when telemetry is enabled, so production code in regulated environments must opt out to avoid logging sensitive content. Restart loss creates another visibility gap for multi-step runs and human approval waits. WorkflowAgent from @ai-sdk/workflow checkpoints execution state so runs survive restarts and deployments, with their spans intact.

Reading a trace to locate where the agent's plan went wrong

Begin the failure investigation with the plan span and the executed span tree. Compare the intended tool sequence with the actual sequence before diagnosing downstream output. A wrong-tool-selected failure appears when the plan names one tool and execution names another, especially when the executed tool belongs to the wrong MCP server. A missing-step failure has a different signature. The required authentication, balance check, or permission verification appears nowhere in the tree.

Step count helps separate looping from slow progress. Repeated calls to the same tool with similar arguments, a climbing step count, and a flat task-completion signal indicate an infinite-loop failure. Premature termination reverses that pattern of excess execution. The plan contains more steps than the executed tree, and the agent returns to the user before the final required tool call completes. Plan-vs-execute divergence is also the canonical planning-layer fingerprint of indirect prompt injection, making the point where divergence begins important to inspect.

These failures require fixes at the planner. A four-agent loop accumulated large charges over many days because the Analyzer and Verifier agents kept exchanging clarification requests without a cycle detector. Per-call rate limits did not stop the loop. The appropriate controls are explicit termination conditions in the system prompt, a cycle detector for repeated tools with similar arguments beyond a defined count, and a plan-vs-execute evaluator that scores divergence.

Reading a trace to locate tool and MCP failures

A fabricated answer can originate in a failed tool call. The agent may receive an error or malformed observation and then continue as though execution succeeded. Look at the tool span before judging the final response. Start with the invoked function and server namespace, then examine arguments, status, output, and completion timing. That order separates selection errors from execution failures and from the agent’s handling of results.

Wrong arguments appear as payloads that fail the schema, often followed by retries with identical malformed structures and non-success status codes. Tool hallucination instead invokes a function absent from the runtime tool catalog. A missing error-handling path appears when a tool returns a 500 or malformed observation and the next span proceeds as though it succeeded. MCP adds distinct fingerprints. Malformed server observations appear in the output field, and a tool that runs past the per-step latency budget can leave a span with no completion timestamp under a parent that ended early.

Tools with the same or similar names can lead the model to select a tool from the wrong namespace, so tool-selection accuracy across servers becomes a per-span production signal. For suspected MCP issues, use the MCP Inspector to isolate server behavior from the agent’s use of it. Its interactive, transport-agnostic UI connects to stdio or Streamable HTTP servers, invokes tools, prompts, and resources, and exposes the notification stream.

Injection requires tracing where the redirection entered. A poisoned MCP descriptor produces plan-vs-execute divergence immediately after the tool-list loads, while a malicious document accessed through resources/read can produce divergence at the retrieval span. Such content from Confluence, SharePoint, or Notion never enters the user’s prompt, so input sanitation does not cover it. Microsoft AI Red Team’s v2.0 taxonomy added MCP/Plugin Abuse and Agentic Supply Chain Compromise as distinct categories, and the team reported 99 CVEs for MCP-related software in 2025. Route fixes to tool allowlists, schema guards, retry policies, and MCP descriptor scans, with ingestion-layer sanitation for malicious documents entering the retrieval corpus.

Reading a trace to locate retrieval and reasoning failures

Blaming hallucination when the retriever supplied bad context sends the fix to the wrong component. Retrieval and reasoning failures can both produce confident, incorrect answers, but the trace separates their origins. Diagnosis requires establishing whether the correct information was available at that point. If it was, inspect how the generator used it. If it was not, move backward to the retrieval or tool span responsible for supplying it.

A wrong-chunk failure returns documents that do not have the information needed to answer the query. Missing context is more direct. The retrieval span contains no relevant documents, yet the generation span fabricates a source. A stale-cache failure can be harder to recognize because the agent reasons correctly from a document updated after caching. A role-switch token in a retrieved chunk can also cause a failure by making the agent treat document content as instructions.

A factual error appears when the retrieval span contains the right information but the generated answer contradicts or misreads it. An ignored instruction appears when output violates an explicit system constraint without a preceding tool or retrieval error. A math error is still a reasoning failure when the tool spans gave the agent the right inputs. The fix routing follows that boundary. Retrieval failures call for chunker re-evaluation, ingestion controls, or cache invalidation, while reasoning failures call for a rubric-based judge, a calibration set, or system prompt tightening.

The silent failure problem: why traces catch what monitoring dashboards miss

A polished success report can hide the failure it should report. These “fail-plausible” responses turn an execution error into a coherent narrative that suggests the task completed. The observer receives affirmative but misleading evidence. Error counts and latency thresholds do not establish whether that report matches the underlying actions. Normal-looking telemetry can therefore coexist with harmful behavior.

The 2026 When Errors Become Narratives analysis on arXiv found that people inspecting user-visible behavior caught about 70% of silent failures in a production personal-assistant agent running scheduled jobs. Tests, audits, and automated monitoring did not catch most of them. The analysis found that audits prevented no failures ahead of time but blocked recurrence at a much higher rate.

A UC Berkeley study in the NeurIPS 2025 Datasets and Benchmarks Track evaluated seven popular open-source multi-agent frameworks on coding, math, and general agent tasks. It found failure rates ranging from more than four in ten to nearly nine in ten, with gains that “often remain minimal compared to single-agent frameworks”. Separately, a case in which accuracy stayed stable across evaluation windows while output diversity collapsed shows why a familiar metric can miss a different kind of degradation. The structural response is to compare intended behavior with traced execution, rather than relying only on better alerts over existing metrics.

Building the feedback loop: from failing trace to regression test

A located failure becomes reusable evidence when it enters a labeled regression dataset. First, assign its category from the trace, namely planning, tool, retrieval, reasoning, or safety/policy. That label shows which part of the agent the test must check. Capture the failing inputs, expected tool sequence or output, and observed divergence as a golden example. Then write a deterministic check or rubric-based evaluation that reproduces the failure condition and rejects the observed behavior.

This labeling also clarifies automatic grouping of recurring failures. Session and account metadata show which runs belong together, while a failure category and its span fingerprint show what went wrong. The same malformed argument structures used again and again, tool calls repeated without progress, and correct context followed by a wrong answer are different patterns even when the final responses all look as though they could be right. Grouping records is not the same as diagnosing them. Lemma, a production monitoring platform for AI agents that audits traces and groups recurring silent failures into issues, aims to spare teams from sorting through odd traces by hand. The useful comparison is the shared failure condition.

To prevent recurrence, add the evaluation to CI for pull requests touching the agent’s prompt, model, tools, or retriever. Keep fast deterministic checks, including cycle detection, schema validation, and tool-allowlist checks, in the routine path. Expensive multi-turn and LLM-judge evaluations belong in nightly or pre-release pipelines. Compare the golden dataset’s pass rate with the last successful deploy’s baseline and block deployment when regression exceeds a defined threshold, unless explicitly overridden. Start conservatively. Tighten the threshold as the dataset grows.

Live monitoring remains a separate requirement from CI gating. CI catches known regressions before release, while production traces show failures that arise only when real users work with the agent. Each new incident can therefore add a labeled example and a deploy gate.

Sources

  1. Updating the taxonomy of failure modes in agentic AI systems: What a year of red teaming taught us
  2. Model or Harness? An Interaction-Centric Taxonomy for Localizing Agent Failures
  3. New whitepaper outlines the taxonomy of failure modes in AI agents
  4. Silent Failure in LLM Agent Systems: The Entropy Principle and the Inevitable Disorder of Autonomous Agents
Filed underTrace Analysis

More in Trace Analysis