Repository avatar
AI Tools
v0.1.1
active

agenttrace

io.github.Arashomranpour/agenttrace

Debug AI agent runs: list traces, find failed or slow steps, analyze and compare runs.

Documentation

AgentTrace

CI PyPI Python MCP Registry License: MIT

MCP-native observability for AI agents. AgentTrace records each step of an agent run: LLM calls, tool calls, LangGraph nodes, retries, errors, latency and tokens. It is built on OpenTelemetry. An MCP server then lets an AI agent (Claude, Cursor, any MCP client) investigate those runs for you:

"Why did my sales agent fail on its last run?"

โ†’ list_traces(status="error") โ†’ analyze_trace("4fc2fb22")

The run failed in tool run_sql (LangGraph > executor > run_sql): OperationalError: no such column: revenu. The SQL the planner LLM wrote has a typo. Check the tool's arguments against the schema. Compared with the last good run, the runs first diverge at executor > run_sql.

Why AgentTrace

When an agent gives a wrong answer, the cause could be in several places:

  • the LLM misread the request;
  • the SQL was wrong;
  • a tool returned nothing;
  • the analyst agent misread the data.

Langfuse, LangSmith and Arize Phoenix record this kind of data, and you browse it in their dashboards. AgentTrace is built around a different workflow: one agent debugs another.

  • ๐Ÿ” 7 read-only MCP tools. Find failed runs, locate the span where an error started (not where it surfaced), find bottlenecks and loops, and diff a good run against a bad one.
  • ๐Ÿงฉ Zero-config LangChain / LangGraph support. Every node, chat model call, tool and retriever becomes a span with the right parent/child structure.
  • ๐Ÿ“ฆ Runs locally, no backend. Traces go to a local SQLite file. Nothing leaves your machine unless you configure an OTLP endpoint.
  • ๐Ÿ”ญ Standard OpenTelemetry. It uses the GenAI semantic conventions (gen_ai.*) and OpenInference I/O attributes, so you can also export to Jaeger, Grafana Tempo, Phoenix, Langfuse or any OTLP collector.
  • ๐Ÿ”’ Private by default. API keys, tokens, JWTs, emails, passwords and card numbers are masked before they are stored or sent.

Install

pip install agenttrace-mcp                 # SDK + MCP server
pip install "agenttrace-mcp[langchain]"    # + LangChain / LangGraph integration
pip install "agenttrace-mcp[otlp]"         # + export to an OTLP backend

Python 3.10โ€“3.13 on Linux, macOS and Windows.

Quick start

1. Trace your agent

from agenttrace import AgentTrace

tracer = AgentTrace("sales-agent", store=True)   # store=True โ†’ ~/.agenttrace/traces.db

with tracer.trace("customer_analysis", input="Analyse last quarter's sales"):
    with tracer.llm("plan", model="gpt-4o-mini") as llm:
        sql = call_my_llm(...)
        llm.set_usage(input_tokens=420, output_tokens=96)
        llm.set_output(sql)
    with tracer.tool("run_sql", input={"query": sql}) as tool:
        rows = db.execute(sql)
        tool.set_output(rows)

LangGraph / LangChain need one line:

handler = tracer.langchain_handler()
graph.invoke({"question": "How did sales change?"}, config={"callbacks": [handler]})

Any function works with a decorator, sync or async:

@tracer.observe(span_type="tool")
def search_web(query: str) -> list[str]: ...

With console=True you also get a tree in the terminal:

Trace: LangGraph  [ERROR]  5ms
  trace_id: 4fc2fb22a4a50c3d8e9bdc7dfb4d5bf2
  โ”œโ”€โ”€ planner (agent)  0ms
  โ”‚   โ””โ”€โ”€ ChatOpenAI (llm, gpt-4o-mini)  0ms  tokens 180โ†’24
  โ””โ”€โ”€ executor (agent)  2ms  โœ— OperationalError: no such column: revenu
      โ””โ”€โ”€ run_sql (tool)  1ms  โœ— OperationalError: no such column: revenu
  Spans: 5 ยท Tokens: 180 in / 24 out

2. Connect the MCP server

Add this to Claude Desktop (claude_desktop_config.json), Cursor or any MCP client:

{
  "mcpServers": {
    "agenttrace": {
      "command": "uvx",
      "args": ["agenttrace-mcp"]
    }
  }
}

Without uv, run pip install agenttrace-mcp and use "command": "agenttrace-mcp". To use a different database, add "--db", "C:\\path\\traces.db" to args or set AGENTTRACE_DB.

3. Ask

  • "Show my failed agent runs from the last hour."
  • "Why did the last sales-agent run fail?"
  • "Compare the last successful run with the failed one."
  • "Which tool is the slowest, and what's my error rate today?"

Real session: Claude debugging a failed run

Recorded with Claude connected to AgentTrace on Windows (Python 3.14), after running examples/langgraph_sql_agent.py once with a good query and once with a typo. These are the real tool results, shortened:

get_stats(since_hours=48)

{ "traces": 2, "failed_traces": 1, "error_rate": 0.5,
  "latency_ms": { "p50": 13.5, "p95": 54.3 },
  "top_tools": [ { "name": "run_sql", "calls": 2, "errors": 1, "avg_ms": 20.9 } ],
  "error_types": [ { "error_type": "OperationalError", "count": 3 } ] }

analyze_trace("793ea506")

{ "findings": [
    "Run failed. The error originated in tool span 'run_sql' (LangGraph > executor > run_sql): OperationalError: no such column: revenu",
    "'run_sql' accounts for 74% of the run's time." ],
  "failure": {
    "path": "LangGraph > executor > run_sql",
    "input": "{\"query\": \"SELECT region, SUM(revenu) FROM sales GROUP BY region\"}",
    "exception": { "type": "sqlite3.OperationalError",
                   "stacktrace_tail": "... line 58, in run_sql ... no such column: revenu" } },
  "what_to_check": [ "Check the tool's arguments (the span input) against what the tool expects; the LLM may have produced malformed or out-of-range arguments." ] }

From these, Claude answered: the run failed because the planner LLM wrote SUM(revenu) instead of SUM(revenue); the error started in run_sql and propagated up through executor.

MCP tools

All tools are read-only. Trace IDs accept a unique prefix of 6 or more characters.

ToolWhat it answers
list_tracesRecent runs with status, duration, span/error counts, tokens and cost. Filters: status, name, project, time window.
get_traceThe full span tree of one run, with timing, model, tokens, events, exceptions and (optionally clipped) inputs/outputs.
analyze_traceA diagnosis of one run: the span where the failure originated and its path, errors that were caught and recovered, retries, repeated identical calls (loops), steps that "succeeded" with empty results, bottlenecks by self-time, the critical path, token use per model and what to check next.
compare_tracesGood run vs bad run: duration/token/error deltas, the first divergence, steps only in one run and per-step changes.
get_failed_spansFailed steps with exception type, message and the tail of the stack trace.
get_slow_spansThe slowest operations, optionally filtered by trace or span type.
get_statsA time-window overview: run count, error rate, p50/p95 latency, tokens, cost, per-model usage, top tools and top error types.

What is recorded

ConceptMeaningOpenTelemetry
Traceone full agent runroot span
Spanone operation: an llm, tool, agent (LangGraph node), chain, retriever or custom stepchild span
Eventsomething that happened inside a span (retry, validation_failed, exception)span event

Each span stores its name, type, timing, status, exception, input/output, model, token usage and cost. Attributes follow OTel conventions: gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.tool.name, input.value and output.value.

Configuration

AgentTrace(
    project_name,               # OTel service.name; used to filter traces
    store=None,                 # True / path โ†’ local SQLite store for the MCP server
    endpoint=None,              # OTLP/HTTP endpoint, e.g. "http://localhost:4318"
    api_key=None,               # sent as "Authorization: Bearer ..." to the endpoint
    console=None,               # print a tree per trace (default: on if nothing else is set)
    exporters=(),               # any extra OTel SpanExporter
    capture_io=True,            # False: never record inputs/outputs
    redact=True,                # True: built-in masking ยท False ยท or your own callable
    max_chars=8000,             # cap per input/output attribute
    retention_days=30,          # the store deletes older traces on start-up
)
Environment variableEffect
AGENTTRACE_STORE=1turn the local store on without changing code
AGENTTRACE_DBpath of the trace database (SDK and MCP server)
AGENTTRACE_ENDPOINT / AGENTTRACE_API_KEYOTLP export target and key
AGENTTRACE_DISABLED=1turn off all tracing (no overhead from exporters)

Design notes

  • No side effects on your app. AgentTrace uses its own TracerProvider and never touches the global OpenTelemetry setup. It can run next to your existing OTel instrumentation.
  • Tracing never breaks the agent. Exporter failures (a broken database or an unreachable endpoint) are logged and the agent keeps running. Exceptions inside your code are recorded and then re-raised unchanged.
  • Built for real workloads. Context propagation is correct across threads and asyncio. The local store uses SQLite WAL mode, so several agent processes can write while the MCP server reads. Spans are written in batches off the hot path. Overhead is about 40 ยตs per span.
  • Errors are attributed to where they started. A tool exception bubbles up through its node and the graph. analyze_trace reports the originating span and its path, and lists errors that were caught separately.
  • LangGraph aware. Internal plumbing runs (hidden runs) are skipped, node spans get langgraph.node and langgraph.step, and interrupt() is recorded as an event, not as a failure.

Privacy and security

  • Masking runs inside your process, before storage or export. Add your own patterns with Redactor(patterns={"customer_id": r"CUST-\d+"}) or pass redact=my_function.
  • capture_io=False keeps only structure, timing, status and token counts.
  • The MCP server opens the database read-only (mode=ro) and has no write tools.
  • A trace shows what happened, not whether an answer is semantically correct. Use VerifierMCP to check what agents output.

Known limitations

  • On Python 3.10, LangChain cannot pass callbacks to nested runs inside async code automatically. Pass config to child runnables there, or use Python 3.11+. Sync code is not affected.
  • The local store is meant for development and single-host use. For a team, export over OTLP. A hosted backend and dashboard are on the roadmap.

Examples

Roadmap

  • Core SDK: traces, spans, events, async/thread context, redaction, console, OTLP
  • LangChain / LangGraph integration
  • Local SQLite store with retention
  • MCP debugging server (PyPI + Official MCP Registry)
  • FastAPI backend with OTLP ingestion, API keys and PostgreSQL
  • Web dashboard: trace explorer, waterfall, span inspector
  • Rule-based alerts (latency, error rate, token spikes) and regression detection
  • More integrations: OpenAI Agents SDK, LlamaIndex, CrewAI

Development

git clone https://github.com/Arashomranpour/AgentTrace && cd AgentTrace
pip install -e ".[dev]"
pytest            # unit, integration (real LangGraph runs), store concurrency, MCP over stdio
ruff check . && ruff format --check .

Releasing: bump version in pyproject.toml and server.json, then publish a GitHub release. The publish workflow builds the package, uploads it to PyPI through Trusted Publishing and publishes it to the Official MCP Registry.

License

MIT ยฉ Arash Omranpour

PYPI
agenttrace-mcp
Install Command
pip install agenttrace-mcp