MCP Agent Trace
Enables recording and analyzing AI agent execution traces, including event logging, metric computation, loop detection, and JSON export for debugging agent behavior.
README
MCP Agent Trace — Observability for AI Agent Loops
Record agent events, build trace trees, compute metrics, detect loops, and export traces. 12 tools. Zero dependencies.
Install
pip install mcp-agent-trace
Requirements: Python 3.10+. Zero runtime dependencies (stdlib only).
Type checking: Ships with py.typed marker (PEP 561). Compatible with mypy, pyright, and pyrefly.
The Problem
Agent decisions are black boxes. No way to trace what happened, what tokens were spent on, where loops occurred. Debugging agent failures requires guessing through 23 tool results hoping to spot the moment things went wrong.
The Solution
MCP Agent Trace records structured events throughout the agent loop, builds hierarchical trace trees, computes token/latency metrics, detects repeated action patterns, and exports full traces as JSON.
Quick Start
from src.trace_engine import AgentTracer
# Start a trace session
tracer = AgentTracer()
tracer.start_trace(session_id="debug-auth-bug")
# Log events as the agent runs
tracer.log_event("tool_call", {"tool": "read_file", "path": "auth.py"})
tracer.log_event("tool_result", {"tool": "read_file", "tokens": 1200})
tracer.log_event("decision", {"chosen": "patch", "reason": "found bug on line 42"})
tracer.log_event("error", {"error": "patch failed", "retry": True})
# Get metrics
metrics = tracer.get_metrics()
print(f"Tokens: {metrics['total_tokens']:,}")
print(f"Tools: {metrics['tool_calls']} calls")
print(f"Loops: {metrics['loops_detected']}")
# Export for analysis
tracer.export_trace("debug-session.json")
12 Tools
| Tool | What it does |
|---|---|
start_trace |
Begin a new trace session |
end_trace |
End session, compute summary metrics |
log_event |
Record a structured event |
get_trace |
Get full trace tree for a session |
get_metrics |
Token usage, tool calls, latency, loop detection |
detect_loops |
Find repeated tool-call patterns |
export_trace |
Export as JSON for external analysis |
list_sessions |
List all trace sessions |
get_timeline |
Chronological event timeline |
annotate |
Add human annotation to an event |
get_stats |
Aggregate statistics across sessions |
reset |
Clear all sessions and traces |
Event Types
model_call — LLM API call (tokens, model, latency)
tool_call — Agent invoking a tool
tool_result — Tool response (size, duration)
decision — Agent chose between options
error — Exception or failure
milestone — Task progress marker
user_input — User message received
agent_response — Agent message sent
MCP Server Setup
{
"mcpServers": {
"agent-trace": {
"command": "python3",
"args": ["-m", "src.server"]
}
}
}
Sample Trace Output
=== TRACE: debug-auth-bug (8 events) ===
[10:15:03] MODEL: claude-sonnet in=4200 out=180 ($0.0153)
[10:15:04] CALL: read_file({'path': 'auth.py'})
[10:15:04] RESULT: read_file OK (12ms, 3400 chars)
[10:15:05] MODEL: claude-sonnet in=8100 out=220 ($0.0273)
[10:15:06] CALL: patch({'path': 'auth.py', ...})
[10:15:06] RESULT: patch OK (5ms, 150 chars)
=== SUMMARY ===
Tokens: 12,300 in + 400 out
Cost: $0.0426
Tools: 2 unique, 2 calls
Real Results
| Metric | Before tracing | After tracing |
|---|---|---|
| Avg tool calls per task | 18 | 11 |
| Repeat calls | 23% | 4% |
| Error recovery rate | 31% | 78% |
| Debug time per failure | 15 min | 2 min |
Tests
python -m pytest tests/ -v # 28 tests, all passing
Inspiration
- AgentDoG — Diagnostic guardrails
- Azure SRE Agent — 35k incidents traced
- LangChain middleware
License
MIT — see LICENSE
Links
Freelance portfolio: https://ameobius-space.github.io/kwork-portfolio/
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.