agenttrace-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. agenttrace_mcp-0.1.0/.github/workflows/ci.yml +51 -0
  2. agenttrace_mcp-0.1.0/.github/workflows/publish.yml +59 -0
  3. agenttrace_mcp-0.1.0/.gitignore +6 -0
  4. agenttrace_mcp-0.1.0/LICENSE +21 -0
  5. agenttrace_mcp-0.1.0/PKG-INFO +245 -0
  6. agenttrace_mcp-0.1.0/README.md +212 -0
  7. agenttrace_mcp-0.1.0/examples/langgraph_sql_agent.py +95 -0
  8. agenttrace_mcp-0.1.0/examples/simple_agent.py +25 -0
  9. agenttrace_mcp-0.1.0/pyproject.toml +61 -0
  10. agenttrace_mcp-0.1.0/server.json +30 -0
  11. agenttrace_mcp-0.1.0/src/agenttrace/__init__.py +10 -0
  12. agenttrace_mcp-0.1.0/src/agenttrace/analysis.py +354 -0
  13. agenttrace_mcp-0.1.0/src/agenttrace/core/__init__.py +1 -0
  14. agenttrace_mcp-0.1.0/src/agenttrace/core/redaction.py +83 -0
  15. agenttrace_mcp-0.1.0/src/agenttrace/core/semconv.py +32 -0
  16. agenttrace_mcp-0.1.0/src/agenttrace/core/span.py +103 -0
  17. agenttrace_mcp-0.1.0/src/agenttrace/core/tracer.py +267 -0
  18. agenttrace_mcp-0.1.0/src/agenttrace/exporters/__init__.py +5 -0
  19. agenttrace_mcp-0.1.0/src/agenttrace/exporters/console.py +111 -0
  20. agenttrace_mcp-0.1.0/src/agenttrace/exporters/otlp.py +21 -0
  21. agenttrace_mcp-0.1.0/src/agenttrace/integrations/__init__.py +1 -0
  22. agenttrace_mcp-0.1.0/src/agenttrace/integrations/langchain.py +332 -0
  23. agenttrace_mcp-0.1.0/src/agenttrace/mcp_server.py +183 -0
  24. agenttrace_mcp-0.1.0/src/agenttrace/store/__init__.py +5 -0
  25. agenttrace_mcp-0.1.0/src/agenttrace/store/sqlite.py +419 -0
  26. agenttrace_mcp-0.1.0/tests/__init__.py +0 -0
  27. agenttrace_mcp-0.1.0/tests/conftest.py +17 -0
  28. agenttrace_mcp-0.1.0/tests/test_langchain.py +164 -0
  29. agenttrace_mcp-0.1.0/tests/test_mcp.py +142 -0
  30. agenttrace_mcp-0.1.0/tests/test_otlp_e2e.py +40 -0
  31. agenttrace_mcp-0.1.0/tests/test_store.py +169 -0
  32. agenttrace_mcp-0.1.0/tests/test_tracer.py +169 -0
@@ -0,0 +1,51 @@
1
+ name: CI
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ strategy:
10
+ fail-fast: false
11
+ matrix:
12
+ os: [ubuntu-latest, windows-latest, macos-latest]
13
+ python: ["3.10", "3.11", "3.12", "3.13"]
14
+ runs-on: ${{ matrix.os }}
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python }}
20
+ - run: python -m pip install --upgrade pip
21
+ - run: pip install -e ".[dev]"
22
+ - run: ruff check .
23
+ - run: ruff format --check .
24
+ - run: pytest -q
25
+ - name: Examples run end to end
26
+ env:
27
+ AGENTTRACE_DB: ${{ runner.temp }}/ci-traces.db
28
+ run: |
29
+ python examples/simple_agent.py
30
+ python examples/langgraph_sql_agent.py
31
+ - run: agenttrace-mcp --version
32
+
33
+ package:
34
+ runs-on: ubuntu-latest
35
+ steps:
36
+ - uses: actions/checkout@v4
37
+ - uses: actions/setup-python@v5
38
+ with:
39
+ python-version: "3.12"
40
+ - run: python -m pip install build twine check-jsonschema
41
+ - run: python -m build && python -m twine check --strict dist/*
42
+ - name: Wheel installs cleanly and the MCP server starts
43
+ run: |
44
+ python -m venv /tmp/v && /tmp/v/bin/pip install dist/*.whl
45
+ /tmp/v/bin/agenttrace-mcp --version
46
+ - name: server.json versions match pyproject
47
+ run: |
48
+ V=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
49
+ test "$(jq -r .version server.json)" = "$V"
50
+ test "$(jq -r '.packages[0].version' server.json)" = "$V"
51
+ grep -q 'mcp-name: io.github.Arashomranpour/agenttrace' README.md
@@ -0,0 +1,59 @@
1
+ name: Publish to PyPI and MCP Registry
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.12"
16
+ - run: python -m pip install --upgrade build twine
17
+ - run: python -m build
18
+ - run: python -m twine check dist/*
19
+ - uses: actions/upload-artifact@v4
20
+ with:
21
+ name: dist
22
+ path: dist/
23
+
24
+ publish:
25
+ needs: build
26
+ runs-on: ubuntu-latest
27
+ environment:
28
+ name: pypi
29
+ url: https://pypi.org/project/agenttrace-mcp/
30
+ permissions:
31
+ id-token: write # PyPI Trusted Publishing (no API token needed)
32
+ steps:
33
+ - uses: actions/download-artifact@v4
34
+ with:
35
+ name: dist
36
+ path: dist/
37
+ - uses: pypa/gh-action-pypi-publish@release/v1
38
+
39
+ mcp-registry:
40
+ needs: publish
41
+ runs-on: ubuntu-latest
42
+ permissions:
43
+ id-token: write # GitHub OIDC login to the MCP Registry
44
+ contents: read
45
+ steps:
46
+ - uses: actions/checkout@v4
47
+ - name: Wait for PyPI to serve the new version
48
+ run: |
49
+ V=$(jq -r .version server.json)
50
+ for i in $(seq 1 30); do
51
+ curl -fsS "https://pypi.org/pypi/agenttrace-mcp/$V/json" >/dev/null && exit 0
52
+ sleep 10
53
+ done
54
+ echo "agenttrace-mcp $V not on PyPI yet" && exit 1
55
+ - name: Install mcp-publisher
56
+ run: |
57
+ curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher
58
+ - run: ./mcp-publisher login github-oidc
59
+ - run: ./mcp-publisher publish
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ .venv/
5
+ .pytest_cache/
6
+ .ruff_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Omra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.5
2
+ Name: agenttrace-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP-native observability for AI agents: trace LLM calls, tools and LangGraph nodes with OpenTelemetry, then let an AI agent debug the runs over MCP.
5
+ Project-URL: Homepage, https://github.com/Arashomranpour/AgentTrace
6
+ Project-URL: Repository, https://github.com/Arashomranpour/AgentTrace
7
+ Project-URL: Issues, https://github.com/Arashomranpour/AgentTrace/issues
8
+ Author: Alex Omra
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai-agents,langgraph,llm,mcp,observability,opentelemetry,tracing
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Debuggers
16
+ Classifier: Topic :: System :: Monitoring
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: mcp<2,>=1.9
19
+ Requires-Dist: opentelemetry-api>=1.25
20
+ Requires-Dist: opentelemetry-sdk>=1.25
21
+ Provides-Extra: dev
22
+ Requires-Dist: langchain-core>=0.3; extra == 'dev'
23
+ Requires-Dist: langgraph>=0.2; extra == 'dev'
24
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.25; extra == 'dev'
25
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
26
+ Requires-Dist: pytest>=8; extra == 'dev'
27
+ Requires-Dist: ruff>=0.6; extra == 'dev'
28
+ Provides-Extra: langchain
29
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
30
+ Provides-Extra: otlp
31
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.25; extra == 'otlp'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # AgentTrace
35
+
36
+ <!-- mcp-name: io.github.Arashomranpour/agenttrace -->
37
+
38
+ [![CI](https://github.com/Arashomranpour/AgentTrace/actions/workflows/ci.yml/badge.svg)](https://github.com/Arashomranpour/AgentTrace/actions/workflows/ci.yml)
39
+ [![PyPI](https://img.shields.io/pypi/v/agenttrace-mcp)](https://pypi.org/project/agenttrace-mcp/)
40
+ [![Python](https://img.shields.io/pypi/pyversions/agenttrace-mcp)](https://pypi.org/project/agenttrace-mcp/)
41
+ [![MCP Registry](https://img.shields.io/badge/MCP%20Registry-io.github.Arashomranpour%2Fagenttrace-blue)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Arashomranpour/agenttrace)
42
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
43
+
44
+ **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:
45
+
46
+ > *"Why did my sales agent fail on its last run?"*
47
+ >
48
+ > → `list_traces(status="error")` → `analyze_trace("4fc2fb22")`
49
+ >
50
+ > **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`.
51
+
52
+ ## Why AgentTrace
53
+
54
+ When an agent gives a wrong answer, the cause could be in several places:
55
+
56
+ - the LLM misread the request;
57
+ - the SQL was wrong;
58
+ - a tool returned nothing;
59
+ - the analyst agent misread the data.
60
+
61
+ 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.**
62
+
63
+ - 🔍 **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.
64
+ - 🧩 **Zero-config LangChain / LangGraph support.** Every node, chat model call, tool and retriever becomes a span with the right parent/child structure.
65
+ - 📦 **Runs locally, no backend.** Traces go to a local SQLite file. Nothing leaves your machine unless you configure an OTLP endpoint.
66
+ - 🔭 **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.
67
+ - 🔒 **Private by default.** API keys, tokens, JWTs, emails, passwords and card numbers are masked *before* they are stored or sent.
68
+
69
+ ## Install
70
+
71
+ ```bash
72
+ pip install agenttrace-mcp # SDK + MCP server
73
+ pip install "agenttrace-mcp[langchain]" # + LangChain / LangGraph integration
74
+ pip install "agenttrace-mcp[otlp]" # + export to an OTLP backend
75
+ ```
76
+
77
+ Python 3.10–3.13 on Linux, macOS and Windows.
78
+
79
+ ## Quick start
80
+
81
+ ### 1. Trace your agent
82
+
83
+ ```python
84
+ from agenttrace import AgentTrace
85
+
86
+ tracer = AgentTrace("sales-agent", store=True) # store=True → ~/.agenttrace/traces.db
87
+
88
+ with tracer.trace("customer_analysis", input="Analyse last quarter's sales"):
89
+ with tracer.llm("plan", model="gpt-4o-mini") as llm:
90
+ sql = call_my_llm(...)
91
+ llm.set_usage(input_tokens=420, output_tokens=96)
92
+ llm.set_output(sql)
93
+ with tracer.tool("run_sql", input={"query": sql}) as tool:
94
+ rows = db.execute(sql)
95
+ tool.set_output(rows)
96
+ ```
97
+
98
+ **LangGraph / LangChain** need one line:
99
+
100
+ ```python
101
+ handler = tracer.langchain_handler()
102
+ graph.invoke({"question": "How did sales change?"}, config={"callbacks": [handler]})
103
+ ```
104
+
105
+ **Any function** works with a decorator, sync or async:
106
+
107
+ ```python
108
+ @tracer.observe(span_type="tool")
109
+ def search_web(query: str) -> list[str]: ...
110
+ ```
111
+
112
+ With `console=True` you also get a tree in the terminal:
113
+
114
+ ```
115
+ Trace: LangGraph [ERROR] 5ms
116
+ trace_id: 4fc2fb22a4a50c3d8e9bdc7dfb4d5bf2
117
+ ├── planner (agent) 0ms
118
+ │ └── ChatOpenAI (llm, gpt-4o-mini) 0ms tokens 180→24
119
+ └── executor (agent) 2ms ✗ OperationalError: no such column: revenu
120
+ └── run_sql (tool) 1ms ✗ OperationalError: no such column: revenu
121
+ Spans: 5 · Tokens: 180 in / 24 out
122
+ ```
123
+
124
+ ### 2. Connect the MCP server
125
+
126
+ Add this to Claude Desktop (`claude_desktop_config.json`), Cursor or any MCP client:
127
+
128
+ ```json
129
+ {
130
+ "mcpServers": {
131
+ "agenttrace": {
132
+ "command": "uvx",
133
+ "args": ["agenttrace-mcp"]
134
+ }
135
+ }
136
+ }
137
+ ```
138
+
139
+ 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`.
140
+
141
+ ### 3. Ask
142
+
143
+ - *"Show my failed agent runs from the last hour."*
144
+ - *"Why did the last sales-agent run fail?"*
145
+ - *"Compare the last successful run with the failed one."*
146
+ - *"Which tool is the slowest, and what's my error rate today?"*
147
+
148
+ ## MCP tools
149
+
150
+ All tools are read-only. Trace IDs accept a unique prefix of 6 or more characters.
151
+
152
+ | Tool | What it answers |
153
+ |---|---|
154
+ | `list_traces` | Recent runs with status, duration, span/error counts, tokens and cost. Filters: status, name, project, time window. |
155
+ | `get_trace` | The full span tree of one run, with timing, model, tokens, events, exceptions and (optionally clipped) inputs/outputs. |
156
+ | `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. |
157
+ | `compare_traces` | Good run vs bad run: duration/token/error deltas, the **first divergence**, steps only in one run and per-step changes. |
158
+ | `get_failed_spans` | Failed steps with exception type, message and the tail of the stack trace. |
159
+ | `get_slow_spans` | The slowest operations, optionally filtered by trace or span type. |
160
+ | `get_stats` | A time-window overview: run count, error rate, p50/p95 latency, tokens, cost, per-model usage, top tools and top error types. |
161
+
162
+ ## What is recorded
163
+
164
+ | Concept | Meaning | OpenTelemetry |
165
+ |---|---|---|
166
+ | **Trace** | one full agent run | root span |
167
+ | **Span** | one operation: an `llm`, `tool`, `agent` (LangGraph node), `chain`, `retriever` or `custom` step | child span |
168
+ | **Event** | something that happened inside a span (`retry`, `validation_failed`, `exception`) | span event |
169
+
170
+ 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`.
171
+
172
+ ## Configuration
173
+
174
+ ```python
175
+ AgentTrace(
176
+ project_name, # OTel service.name; used to filter traces
177
+ store=None, # True / path → local SQLite store for the MCP server
178
+ endpoint=None, # OTLP/HTTP endpoint, e.g. "http://localhost:4318"
179
+ api_key=None, # sent as "Authorization: Bearer ..." to the endpoint
180
+ console=None, # print a tree per trace (default: on if nothing else is set)
181
+ exporters=(), # any extra OTel SpanExporter
182
+ capture_io=True, # False: never record inputs/outputs
183
+ redact=True, # True: built-in masking · False · or your own callable
184
+ max_chars=8000, # cap per input/output attribute
185
+ retention_days=30, # the store deletes older traces on start-up
186
+ )
187
+ ```
188
+
189
+ | Environment variable | Effect |
190
+ |---|---|
191
+ | `AGENTTRACE_STORE=1` | turn the local store on without changing code |
192
+ | `AGENTTRACE_DB` | path of the trace database (SDK and MCP server) |
193
+ | `AGENTTRACE_ENDPOINT` / `AGENTTRACE_API_KEY` | OTLP export target and key |
194
+ | `AGENTTRACE_DISABLED=1` | turn off all tracing (no overhead from exporters) |
195
+
196
+ ## Design notes
197
+
198
+ - **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.
199
+ - **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.
200
+ - **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.
201
+ - **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.
202
+ - **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.
203
+
204
+ ## Privacy and security
205
+
206
+ - 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`.
207
+ - `capture_io=False` keeps only structure, timing, status and token counts.
208
+ - The MCP server opens the database **read-only** (`mode=ro`) and has no write tools.
209
+ - A trace shows *what happened*, not whether an answer is semantically correct. Use [VerifierMCP](https://github.com/Arashomranpour/Verifier_MCP) to check what agents output.
210
+
211
+ ## Known limitations
212
+
213
+ - 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.
214
+ - 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.
215
+
216
+ ## Examples
217
+
218
+ - [`examples/simple_agent.py`](examples/simple_agent.py): manual spans, a decorator and events.
219
+ - [`examples/langgraph_sql_agent.py`](examples/langgraph_sql_agent.py): a LangGraph SQL agent with one good and one failing run. It runs offline with a fake LLM, so it's a good way to try the MCP tools.
220
+
221
+ ## Roadmap
222
+
223
+ - [x] Core SDK: traces, spans, events, async/thread context, redaction, console, OTLP
224
+ - [x] LangChain / LangGraph integration
225
+ - [x] Local SQLite store with retention
226
+ - [x] MCP debugging server (PyPI + Official MCP Registry)
227
+ - [ ] FastAPI backend with OTLP ingestion, API keys and PostgreSQL
228
+ - [ ] Web dashboard: trace explorer, waterfall, span inspector
229
+ - [ ] Rule-based alerts (latency, error rate, token spikes) and regression detection
230
+ - [ ] More integrations: OpenAI Agents SDK, LlamaIndex, CrewAI
231
+
232
+ ## Development
233
+
234
+ ```bash
235
+ git clone https://github.com/Arashomranpour/AgentTrace && cd AgentTrace
236
+ pip install -e ".[dev]"
237
+ pytest # unit, integration (real LangGraph runs), store concurrency, MCP over stdio
238
+ ruff check . && ruff format --check .
239
+ ```
240
+
241
+ **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.
242
+
243
+ ## License
244
+
245
+ MIT © Alex Omra
@@ -0,0 +1,212 @@
1
+ # AgentTrace
2
+
3
+ <!-- mcp-name: io.github.Arashomranpour/agenttrace -->
4
+
5
+ [![CI](https://github.com/Arashomranpour/AgentTrace/actions/workflows/ci.yml/badge.svg)](https://github.com/Arashomranpour/AgentTrace/actions/workflows/ci.yml)
6
+ [![PyPI](https://img.shields.io/pypi/v/agenttrace-mcp)](https://pypi.org/project/agenttrace-mcp/)
7
+ [![Python](https://img.shields.io/pypi/pyversions/agenttrace-mcp)](https://pypi.org/project/agenttrace-mcp/)
8
+ [![MCP Registry](https://img.shields.io/badge/MCP%20Registry-io.github.Arashomranpour%2Fagenttrace-blue)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Arashomranpour/agenttrace)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
10
+
11
+ **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:
12
+
13
+ > *"Why did my sales agent fail on its last run?"*
14
+ >
15
+ > → `list_traces(status="error")` → `analyze_trace("4fc2fb22")`
16
+ >
17
+ > **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`.
18
+
19
+ ## Why AgentTrace
20
+
21
+ When an agent gives a wrong answer, the cause could be in several places:
22
+
23
+ - the LLM misread the request;
24
+ - the SQL was wrong;
25
+ - a tool returned nothing;
26
+ - the analyst agent misread the data.
27
+
28
+ 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.**
29
+
30
+ - 🔍 **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.
31
+ - 🧩 **Zero-config LangChain / LangGraph support.** Every node, chat model call, tool and retriever becomes a span with the right parent/child structure.
32
+ - 📦 **Runs locally, no backend.** Traces go to a local SQLite file. Nothing leaves your machine unless you configure an OTLP endpoint.
33
+ - 🔭 **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.
34
+ - 🔒 **Private by default.** API keys, tokens, JWTs, emails, passwords and card numbers are masked *before* they are stored or sent.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install agenttrace-mcp # SDK + MCP server
40
+ pip install "agenttrace-mcp[langchain]" # + LangChain / LangGraph integration
41
+ pip install "agenttrace-mcp[otlp]" # + export to an OTLP backend
42
+ ```
43
+
44
+ Python 3.10–3.13 on Linux, macOS and Windows.
45
+
46
+ ## Quick start
47
+
48
+ ### 1. Trace your agent
49
+
50
+ ```python
51
+ from agenttrace import AgentTrace
52
+
53
+ tracer = AgentTrace("sales-agent", store=True) # store=True → ~/.agenttrace/traces.db
54
+
55
+ with tracer.trace("customer_analysis", input="Analyse last quarter's sales"):
56
+ with tracer.llm("plan", model="gpt-4o-mini") as llm:
57
+ sql = call_my_llm(...)
58
+ llm.set_usage(input_tokens=420, output_tokens=96)
59
+ llm.set_output(sql)
60
+ with tracer.tool("run_sql", input={"query": sql}) as tool:
61
+ rows = db.execute(sql)
62
+ tool.set_output(rows)
63
+ ```
64
+
65
+ **LangGraph / LangChain** need one line:
66
+
67
+ ```python
68
+ handler = tracer.langchain_handler()
69
+ graph.invoke({"question": "How did sales change?"}, config={"callbacks": [handler]})
70
+ ```
71
+
72
+ **Any function** works with a decorator, sync or async:
73
+
74
+ ```python
75
+ @tracer.observe(span_type="tool")
76
+ def search_web(query: str) -> list[str]: ...
77
+ ```
78
+
79
+ With `console=True` you also get a tree in the terminal:
80
+
81
+ ```
82
+ Trace: LangGraph [ERROR] 5ms
83
+ trace_id: 4fc2fb22a4a50c3d8e9bdc7dfb4d5bf2
84
+ ├── planner (agent) 0ms
85
+ │ └── ChatOpenAI (llm, gpt-4o-mini) 0ms tokens 180→24
86
+ └── executor (agent) 2ms ✗ OperationalError: no such column: revenu
87
+ └── run_sql (tool) 1ms ✗ OperationalError: no such column: revenu
88
+ Spans: 5 · Tokens: 180 in / 24 out
89
+ ```
90
+
91
+ ### 2. Connect the MCP server
92
+
93
+ Add this to Claude Desktop (`claude_desktop_config.json`), Cursor or any MCP client:
94
+
95
+ ```json
96
+ {
97
+ "mcpServers": {
98
+ "agenttrace": {
99
+ "command": "uvx",
100
+ "args": ["agenttrace-mcp"]
101
+ }
102
+ }
103
+ }
104
+ ```
105
+
106
+ 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`.
107
+
108
+ ### 3. Ask
109
+
110
+ - *"Show my failed agent runs from the last hour."*
111
+ - *"Why did the last sales-agent run fail?"*
112
+ - *"Compare the last successful run with the failed one."*
113
+ - *"Which tool is the slowest, and what's my error rate today?"*
114
+
115
+ ## MCP tools
116
+
117
+ All tools are read-only. Trace IDs accept a unique prefix of 6 or more characters.
118
+
119
+ | Tool | What it answers |
120
+ |---|---|
121
+ | `list_traces` | Recent runs with status, duration, span/error counts, tokens and cost. Filters: status, name, project, time window. |
122
+ | `get_trace` | The full span tree of one run, with timing, model, tokens, events, exceptions and (optionally clipped) inputs/outputs. |
123
+ | `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. |
124
+ | `compare_traces` | Good run vs bad run: duration/token/error deltas, the **first divergence**, steps only in one run and per-step changes. |
125
+ | `get_failed_spans` | Failed steps with exception type, message and the tail of the stack trace. |
126
+ | `get_slow_spans` | The slowest operations, optionally filtered by trace or span type. |
127
+ | `get_stats` | A time-window overview: run count, error rate, p50/p95 latency, tokens, cost, per-model usage, top tools and top error types. |
128
+
129
+ ## What is recorded
130
+
131
+ | Concept | Meaning | OpenTelemetry |
132
+ |---|---|---|
133
+ | **Trace** | one full agent run | root span |
134
+ | **Span** | one operation: an `llm`, `tool`, `agent` (LangGraph node), `chain`, `retriever` or `custom` step | child span |
135
+ | **Event** | something that happened inside a span (`retry`, `validation_failed`, `exception`) | span event |
136
+
137
+ 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`.
138
+
139
+ ## Configuration
140
+
141
+ ```python
142
+ AgentTrace(
143
+ project_name, # OTel service.name; used to filter traces
144
+ store=None, # True / path → local SQLite store for the MCP server
145
+ endpoint=None, # OTLP/HTTP endpoint, e.g. "http://localhost:4318"
146
+ api_key=None, # sent as "Authorization: Bearer ..." to the endpoint
147
+ console=None, # print a tree per trace (default: on if nothing else is set)
148
+ exporters=(), # any extra OTel SpanExporter
149
+ capture_io=True, # False: never record inputs/outputs
150
+ redact=True, # True: built-in masking · False · or your own callable
151
+ max_chars=8000, # cap per input/output attribute
152
+ retention_days=30, # the store deletes older traces on start-up
153
+ )
154
+ ```
155
+
156
+ | Environment variable | Effect |
157
+ |---|---|
158
+ | `AGENTTRACE_STORE=1` | turn the local store on without changing code |
159
+ | `AGENTTRACE_DB` | path of the trace database (SDK and MCP server) |
160
+ | `AGENTTRACE_ENDPOINT` / `AGENTTRACE_API_KEY` | OTLP export target and key |
161
+ | `AGENTTRACE_DISABLED=1` | turn off all tracing (no overhead from exporters) |
162
+
163
+ ## Design notes
164
+
165
+ - **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.
166
+ - **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.
167
+ - **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.
168
+ - **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.
169
+ - **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.
170
+
171
+ ## Privacy and security
172
+
173
+ - 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`.
174
+ - `capture_io=False` keeps only structure, timing, status and token counts.
175
+ - The MCP server opens the database **read-only** (`mode=ro`) and has no write tools.
176
+ - A trace shows *what happened*, not whether an answer is semantically correct. Use [VerifierMCP](https://github.com/Arashomranpour/Verifier_MCP) to check what agents output.
177
+
178
+ ## Known limitations
179
+
180
+ - 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.
181
+ - 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.
182
+
183
+ ## Examples
184
+
185
+ - [`examples/simple_agent.py`](examples/simple_agent.py): manual spans, a decorator and events.
186
+ - [`examples/langgraph_sql_agent.py`](examples/langgraph_sql_agent.py): a LangGraph SQL agent with one good and one failing run. It runs offline with a fake LLM, so it's a good way to try the MCP tools.
187
+
188
+ ## Roadmap
189
+
190
+ - [x] Core SDK: traces, spans, events, async/thread context, redaction, console, OTLP
191
+ - [x] LangChain / LangGraph integration
192
+ - [x] Local SQLite store with retention
193
+ - [x] MCP debugging server (PyPI + Official MCP Registry)
194
+ - [ ] FastAPI backend with OTLP ingestion, API keys and PostgreSQL
195
+ - [ ] Web dashboard: trace explorer, waterfall, span inspector
196
+ - [ ] Rule-based alerts (latency, error rate, token spikes) and regression detection
197
+ - [ ] More integrations: OpenAI Agents SDK, LlamaIndex, CrewAI
198
+
199
+ ## Development
200
+
201
+ ```bash
202
+ git clone https://github.com/Arashomranpour/AgentTrace && cd AgentTrace
203
+ pip install -e ".[dev]"
204
+ pytest # unit, integration (real LangGraph runs), store concurrency, MCP over stdio
205
+ ruff check . && ruff format --check .
206
+ ```
207
+
208
+ **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.
209
+
210
+ ## License
211
+
212
+ MIT © Alex Omra