Skip to main content

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.

Tool What it answers
list_traces Recent runs with status, duration, span/error counts, tokens and cost. Filters: status, name, project, time window.
get_trace The full span tree of one run, with timing, model, tokens, events, exceptions and (optionally clipped) inputs/outputs.
analyze_trace A 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_traces Good run vs bad run: duration/token/error deltas, the first divergence, steps only in one run and per-step changes.
get_failed_spans Failed steps with exception type, message and the tail of the stack trace.
get_slow_spans The slowest operations, optionally filtered by trace or span type.
get_stats A time-window overview: run count, error rate, p50/p95 latency, tokens, cost, per-model usage, top tools and top error types.

What is recorded

Concept Meaning OpenTelemetry
Trace one full agent run root span
Span one operation: an llm, tool, agent (LangGraph node), chain, retriever or custom step child span
Event something 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 variable Effect
AGENTTRACE_STORE=1 turn the local store on without changing code
AGENTTRACE_DB path of the trace database (SDK and MCP server)
AGENTTRACE_ENDPOINT / AGENTTRACE_API_KEY OTLP export target and key
AGENTTRACE_DISABLED=1 turn 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 © Alex Omra

Metadata

Release files for agenttrace-mcp 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agenttrace-mcp 0.1.2
File Size Uploaded Provenance Actions
agenttrace_mcp-0.1.2.tar.gz 36.9 kB With provenance Details for agenttrace_mcp-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agenttrace-mcp 0.1.2
File Interpreter ABI Platform Actions
agenttrace_mcp-0.1.2-py3-none-any.whl Python 3 none any Details for agenttrace_mcp-0.1.2-py3-none-any.whl

Total release size: 70.1 kB

Release files / agenttrace_mcp-0.1.2.tar.gz

Download URL agenttrace_mcp-0.1.2.tar.gz
Size 36.9 kB
Tags Source
SHA-256 checksum
How to use checksums
30c3d9ef06c5c39c176bec8ffd73952c62000b1118f4ee208deac3e570da4b94
BLAKE2b-256 checksum
How to use checksums
66b0c990bd9e04d774f285a494183077d72bc0901aa382784e93c35bda30b30b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / agenttrace_mcp-0.1.2-py3-none-any.whl

Download URL agenttrace_mcp-0.1.2-py3-none-any.whl
Size 33.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
80c8888077835295ef4c266031c918fb7afdc62f443b69cb74fe226f47120944
BLAKE2b-256 checksum
How to use checksums
4b861d672b1d4cfd0b96008f64d27d6fedbd5b9cd6e3a1d37b7bb3da9621377d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for agenttrace-mcp 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for agenttrace_mcp-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page