agenthawk 0.2.0__py3-none-any.whl

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.
agenthawk/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """AgentHawk public import surface.
2
+
3
+ The implementation remains in ``mcp_trace`` so existing integrations keep
4
+ working. New code may import the query functions from ``agenthawk``.
5
+ """
6
+ from mcp_trace import * # noqa: F401,F403
7
+ from mcp_trace import __version__
agenthawk/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from agenthawk.server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
agenthawk/core.py ADDED
@@ -0,0 +1,2 @@
1
+ """AgentHawk query functions; compatibility implementation in ``mcp_trace.core``."""
2
+ from mcp_trace.core import * # noqa: F401,F403
agenthawk/server.py ADDED
@@ -0,0 +1,6 @@
1
+ """AgentHawk MCP server entry point."""
2
+ from mcp_trace.server import * # noqa: F401,F403
3
+ from mcp_trace.server import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.5
2
+ Name: agenthawk
3
+ Version: 0.2.0
4
+ Summary: Agent observability MCP server for querying OpenTelemetry traces, failures, tool health, security evidence, and regressions.
5
+ Project-URL: Homepage, https://github.com/abhishekash/agenthawk
6
+ Project-URL: Repository, https://github.com/abhishekash/agenthawk
7
+ Project-URL: Issues, https://github.com/abhishekash/agenthawk/issues
8
+ Author-email: Abhishek Ash <ash.abhishek@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: agent-evals,ai-agents,mcp,model-context-protocol,observability,opentelemetry
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: mcp>=2.0.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=8; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # AgentHawk
24
+
25
+ <!-- mcp-name: io.github.abhishekash/agenthawk -->
26
+
27
+ [![CI](https://github.com/abhishekash/agenthawk/actions/workflows/ci.yml/badge.svg)](https://github.com/abhishekash/agenthawk/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
28
+
29
+ **Agents that can debug themselves.** An MCP server that exposes your agent runs — stored as plain OpenTelemetry JSONL span files — as queryable tools: runs, span trees, failures, tool health, security evidence, live activity, regressions, human-approval logs, token/cost usage.
30
+
31
+ The idea: observability shouldn't be a dashboard you read after the fact. It should be *tools your agent can call mid-run* — "why was I slow yesterday?", "what did the human deny me last time?", "which tool keeps timing out?" — or query interactively from Claude Desktop / pi / any MCP client.
32
+
33
+ Pairs with [agent-harness](https://github.com/abhishekash/agent-harness) (which writes the traces), but the reader is format-simple: any JSONL of OTel-shaped spans works.
34
+
35
+ ## AI-native use cases
36
+
37
+ | Question during an agent run | MCP tool | Evidence returned |
38
+ |---|---|---|
39
+ | "Why did yesterday's run stall?" | `list_runs` → `slowest_spans` | Run IDs and the longest model or tool spans. |
40
+ | "Did the agent act after I denied the write?" | `approval_log` → `span_tree` | The recorded decision and subsequent execution path. |
41
+ | "How many model tokens did this run use?" | `token_usage` → `span_tree` | Run-level usage totals and the span tree for context. |
42
+ | "Which tool is failing or timing out?" | `failure_report` / `tool_stats` | Redacted diagnostics, error rates, denials, and p95 latency. |
43
+ | "Who/what was allowed to act?" | `security_audit` | Caller, tenant, server provenance, risk, and missing-evidence findings. |
44
+ | "What is happening in the run right now?" | `recent_activity` | Cursor-based polling of newly written spans. |
45
+ | "Did this model/version regress?" | `compare_runs` | Cost, latency, tokens, tool calls, and failure deltas. |
46
+
47
+ The tools read stored traces and can poll files being written, but they do not push events or infer intent from the final answer. See the [real trace fixture](examples/example_trace.jsonl) and the [tool descriptions](src/mcp_trace/server.py) for the exact query contract.
48
+
49
+ ## Install & run
50
+
51
+ AgentHawk is the new canonical name. The legacy `abhishekash-mcp-trace` distribution and `mcp-trace` commands remain compatibility aliases for existing users.
52
+
53
+ ```bash
54
+ uvx agenthawk --trace-dir ./traces
55
+ # or, for local development:
56
+ git clone https://github.com/abhishekash/agenthawk
57
+ cd agenthawk && uv pip install -e .
58
+ agenthawk --trace-dir ./traces
59
+ ```
60
+
61
+ The `agenthawk` 0.2.0 release is the renamed successor to the published
62
+ [`abhishekash-mcp-trace` 0.1.1](https://pypi.org/project/abhishekash-mcp-trace/0.1.1/)
63
+ distribution. Existing clients can continue using the legacy command while
64
+ migrating.
65
+
66
+ ## Client configuration
67
+
68
+ **Claude Desktop** (`claude_desktop_config.json`):
69
+
70
+ ```json
71
+ {
72
+ "mcpServers": {
73
+ "agent-traces": {
74
+ "command": "uvx",
75
+ "args": ["agenthawk", "--trace-dir", "/path/to/traces"]
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ **pi** (`~/.pi/agent/settings.json`):
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "agent-traces": {
87
+ "command": "uvx",
88
+ "args": ["agenthawk", "--trace-dir", "/path/to/traces"]
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ **agent-harness** (mounted as gated tools):
95
+
96
+ ```bash
97
+ harness run "Why was my last run slow?" --mcp "uvx agenthawk --trace-dir ./traces"
98
+ ```
99
+
100
+ ## Tools
101
+
102
+ | Tool | Use it when |
103
+ |---|---|
104
+ | `list_runs` | Starting out — recent runs with task, model, duration, cost, decision counts |
105
+ | `run_summary` | One run at a glance (accepts trace-id prefix) |
106
+ | `span_tree` | "What did the agent actually do?" — nested shape of the run |
107
+ | `slowest_spans` | "Why was it slow?" — top-k spans by duration |
108
+ | `approval_log` | HITL audit — every approve/deny/**edit**, who decided, and *the rationale* |
109
+ | `token_usage` | Cost questions — aggregated across runs or per-run |
110
+ | `search_spans` | Find spans by tool name, file path, "denied", … |
111
+ | `failure_report` | Find actionable, bounded, redacted errors and failed tool calls. |
112
+ | `tool_stats` | Rank tools by volume, error rate, denials, and latency. |
113
+ | `security_audit` | Audit caller identity, tenant, server provenance, risk, and approval evidence. |
114
+ | `recent_activity` | Poll new spans with a cursor while a run is active. |
115
+ | `compare_runs` | Compare selected traces for regressions across models or versions. |
116
+
117
+ Tool descriptions are written as prompts (when-to-use, not just what-it-does) — descriptions are the interface for agent-called tools.
118
+
119
+ ## Example session (real fixture trace)
120
+
121
+ ```
122
+ > list_runs
123
+ [{ "trace_id": "f920798dd255…", "task": "Summarize the workspace's notes…",
124
+ "tool_calls": 4, "human_decisions": 2, "stopped_reason": "completed" }]
125
+
126
+ > approval_log
127
+ [{ "tool": "write_file", "decision": "approve", "approver": "auto", … },
128
+ { "tool": "run_shell", "decision": "approve", "approver": "auto", … }]
129
+ ```
130
+
131
+ ## Design
132
+
133
+ ```
134
+ traces/*.jsonl ──▶ agenthawk.core (pure query functions, zero deps)
135
+ │
136
+ agenthawk.server (thin MCPServer adapter, mcp 2.x)
137
+ │
138
+ stdio (NDJSON JSON-RPC)
139
+ ```
140
+
141
+ - **core/server split**: all logic is pure functions over parsed spans; the MCP layer only parses args and JSON-encodes results. Tests hit both layers.
142
+ - **trace_id prefixes**: agents fumble full 32-char hex ids; every tool accepts prefixes.
143
+ - **bounded output**: diagnostics are truncated and obvious credentials are redacted before query results leave the server.
144
+ - **cursor polling**: `recent_activity` makes the snapshot reader useful while a run is still writing spans.
145
+ - The demo fixture ([`examples/example_trace.jsonl`](examples/example_trace.jsonl)) is a *real* agent-harness run, not hand-written.
146
+
147
+ ## Research-driven gaps addressed
148
+
149
+ A small Reddit review surfaced the same production problems repeatedly: auth and
150
+ identity are unclear after the demo, versions and logs are hard to compare,
151
+ tool fleets become noisy and expensive, operators lack visibility into what is
152
+ happening, and raw logs are not a useful analysis surface. Examples:
153
+
154
+ - [ChatGPT + MCP gets painful after the demo](https://www.reddit.com/r/ChatGPTPro/comments/1uz6tzs/where_chatgpt_mcp_gets_painful_after_the_demo/) — auth, versions, logs, and safe tools.
155
+ - [MCP logging and correlation IDs](https://www.reddit.com/r/softwarearchitecture/comments/1r2wnfd/is_mcp_effectively_introducing_a_probabilistic/o51k4zq/) — preserve intent, tool arguments, results, and correlation IDs.
156
+ - [180 tools becomes a permission/context/debugging problem](https://www.reddit.com/r/ClaudeAI/comments/1tuqqpn/i_ship_ai_agents_in_production_the_mess_is_mcp/opbh78y/).
157
+ - [MCP security](https://www.reddit.com/r/cybersecurity/comments/1tgs4gg/mcp_security/) — identity, access, credentials, approved versions, and audit logs.
158
+ - [Raw logs are noisy and hard to query](https://www.reddit.com/r/ChatGPTPro/comments/1ur2tx4/i_made_my_codex_usage_tracker_more_agentnative/).
159
+
160
+ This update adds five focused query surfaces rather than pretending a
161
+ Dashboard solves those problems: `failure_report`, `tool_stats`,
162
+ `security_audit`, `recent_activity`, and `compare_runs`. Trace discovery is also
163
+ recursive, and query results redact obvious credential patterns.
164
+
165
+ ## Honest limitations
166
+
167
+ - stdio transport only (Streamable HTTP plus authenticated remote access is the next transport boundary)
168
+ - live polling re-reads snapshots; it is not a push subscription
169
+ - security audit can only report identity/provenance that the trace producer records
170
+ - read-only tools; trace mutation (annotations) is roadmap
171
+ - `mcp_trace` remains the compatibility Python import; new code should use `agenthawk`
172
+
173
+ ## License
174
+
175
+ MIT
@@ -0,0 +1,13 @@
1
+ agenthawk/__init__.py,sha256=3zuwO87lVDgfKmznSCcCyDzrSuMycHVj3OW4BVOqlE4,261
2
+ agenthawk/__main__.py,sha256=DhRm9z974nLZZYQG9B1RwYVMqr7wT6TsxXhAbrPXU5Q,73
3
+ agenthawk/core.py,sha256=fPtXteNMQY2vNWJwjd0Ac04B4BoQGZo2tgtKdkBeEuE,133
4
+ agenthawk/server.py,sha256=XynTk8ycKh8_1aS1MGUuv24zkAcjhIm78H_MezDoKmg,163
5
+ mcp_trace/__init__.py,sha256=mKoS0m7R7uw5sdLgVVuS_krrNdsLqONvWhJuGNpDvFg,784
6
+ mcp_trace/__main__.py,sha256=_a1ue5xhiF_NlxafbnRzOQufSpjxCeN5kxAhHwv1618,95
7
+ mcp_trace/core.py,sha256=Lv2GBz0xy6qKaXIQAPedAVMBguZpJ5d3asGPVgpCVg0,19999
8
+ mcp_trace/server.py,sha256=1mMhmzccF-fYZG85Rgx1hbGAgoJcOj66h6GChBQo9Xs,5790
9
+ agenthawk-0.2.0.dist-info/METADATA,sha256=p4sA4vXtwsYMfQI6t4Gh5CKHrzTywEmoXnsG1ANpbRI,8821
10
+ agenthawk-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
11
+ agenthawk-0.2.0.dist-info/entry_points.txt,sha256=Qu_9IU3aIs7hYfEYtW3qXAp5Jf7tkfqhTQFxQHO5lAQ,167
12
+ agenthawk-0.2.0.dist-info/licenses/LICENSE,sha256=SJsmUc1lDzPkFMOSg3R0DTJdt983IP3kY_ow_TrzJ_E,1069
13
+ agenthawk-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ abhishekash-mcp-trace = mcp_trace.server:main
3
+ agent-hawk = mcp_trace.server:main
4
+ agenthawk = mcp_trace.server:main
5
+ mcp-trace = mcp_trace.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abhishek Ash
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.
mcp_trace/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """AgentHawk: MCP server over trace query core.
2
+
3
+ The ``mcp_trace`` import remains as a compatibility module for pre-0.2 users.
4
+ """
5
+ from mcp_trace.core import (
6
+ approval_log,
7
+ compare_runs,
8
+ failure_report,
9
+ group_traces,
10
+ list_runs,
11
+ load_spans,
12
+ load_trace_dir,
13
+ recent_activity,
14
+ run_summary,
15
+ search_spans,
16
+ security_audit,
17
+ slowest_spans,
18
+ span_tree,
19
+ token_usage,
20
+ tool_stats,
21
+ )
22
+
23
+ __version__ = "0.2.0"
24
+ __all__ = [
25
+ "approval_log",
26
+ "compare_runs",
27
+ "failure_report",
28
+ "group_traces",
29
+ "list_runs",
30
+ "load_spans",
31
+ "load_trace_dir",
32
+ "recent_activity",
33
+ "run_summary",
34
+ "search_spans",
35
+ "security_audit",
36
+ "slowest_spans",
37
+ "span_tree",
38
+ "token_usage",
39
+ "tool_stats",
40
+ "__version__",
41
+ ]
mcp_trace/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from mcp_trace.server import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
mcp_trace/core.py ADDED
@@ -0,0 +1,523 @@
1
+ """Trace query engine over JSONL span files.
2
+
3
+ Pure functions — no MCP or OTel imports — so the query logic is testable
4
+ offline and reusable. The MCP server (server.py) is a thin adapter over this.
5
+
6
+ Span format is the agent-harness contract: one JSON object per line with
7
+ trace_id, span_id, parent_span_id, name, start/end unix nanos, status,
8
+ attributes, events.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any, Iterable
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # loading
18
+
19
+
20
+ def load_spans(path: str | Path) -> list[dict[str, Any]]:
21
+ spans: list[dict[str, Any]] = []
22
+ with Path(path).open(encoding="utf-8") as f:
23
+ for lineno, line in enumerate(f, 1):
24
+ line = line.strip()
25
+ if not line:
26
+ continue
27
+ try:
28
+ span = json.loads(line)
29
+ except json.JSONDecodeError as e:
30
+ raise ValueError(f"{path}:{lineno}: invalid span JSON: {e}") from e
31
+ span["_source_file"] = str(path)
32
+ spans.append(span)
33
+ return spans
34
+
35
+
36
+ def load_trace_dir(trace_dir: str | Path) -> list[dict[str, Any]]:
37
+ """Load every JSONL span file below a trace directory."""
38
+ root = Path(trace_dir)
39
+ if not root.is_dir():
40
+ raise FileNotFoundError(f"trace dir not found: {root}")
41
+ spans: list[dict[str, Any]] = []
42
+ for path in sorted(p for p in root.rglob("*.jsonl") if p.is_file()):
43
+ spans.extend(load_spans(path))
44
+ return spans
45
+
46
+
47
+ def group_traces(spans: Iterable[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
48
+ traces: dict[str, list[dict[str, Any]]] = {}
49
+ for s in spans:
50
+ traces.setdefault(s["trace_id"], []).append(s)
51
+ for tid in traces:
52
+ traces[tid].sort(key=lambda s: (s["start_unix_nano"], s["end_unix_nano"]))
53
+ return traces
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # queries
58
+
59
+
60
+ _SECRET_PATTERNS = (
61
+ (r"(?i)(authorization\s*:\s*bearer\s+)[^\s,]+", r"\1<redacted>"),
62
+ (r"(?i)((?:api[_-]?key|token|secret|password)\s*[:=]\s*[\"']?)[^\s,\"']+", r"\1<redacted>"),
63
+ (r"(?i)\b(?:sk|ghp|github_pat|xoxb|xoxp)-[A-Za-z0-9_\-]{12,}\b", "<redacted>"),
64
+ )
65
+
66
+
67
+ def _redact_text(value: Any, limit: int = 500) -> str:
68
+ import re
69
+
70
+ text = str(value)
71
+ for pattern, replacement in _SECRET_PATTERNS:
72
+ text = re.sub(pattern, replacement, text)
73
+ return text[:limit]
74
+
75
+
76
+ def _status_code(span: dict[str, Any]) -> str:
77
+ status = span.get("status") or {}
78
+ code = status.get("code", "") if isinstance(status, dict) else ""
79
+ return str(code).upper()
80
+
81
+
82
+ def _span_error(span: dict[str, Any]) -> bool:
83
+ attrs = span.get("attributes", {})
84
+ result_status = str(attrs.get("tool.result_status", "")).lower()
85
+ stopped = str(attrs.get("agent.stopped_reason", "")).lower()
86
+ events = span.get("events", []) or []
87
+ return bool(
88
+ _status_code(span) in {"ERROR", "2"}
89
+ or result_status in {"error", "denied"}
90
+ or attrs.get("tool.error")
91
+ or stopped not in {"", "completed"}
92
+ or any(str(event.get("name", "")).lower() in {"exception", "error"} for event in events)
93
+ )
94
+
95
+
96
+ def _span_error_detail(span: dict[str, Any]) -> str | None:
97
+ attrs = span.get("attributes", {})
98
+ for key in (
99
+ "tool.error_message",
100
+ "error.message",
101
+ "exception.message",
102
+ "llm.error",
103
+ "agent.error",
104
+ "tool.error",
105
+ "agent.stopped_reason",
106
+ ):
107
+ if attrs.get(key) and not (
108
+ key == "agent.stopped_reason" and str(attrs[key]).lower() == "completed"
109
+ ):
110
+ return _redact_text(attrs[key])
111
+ for event in span.get("events", []) or []:
112
+ event_attrs = event.get("attributes", {}) or {}
113
+ for key in ("exception.message", "error.message"):
114
+ if event_attrs.get(key):
115
+ return _redact_text(event_attrs[key])
116
+ return None
117
+
118
+
119
+ def _p95(values: list[float]) -> float:
120
+ if not values:
121
+ return 0.0
122
+ ordered = sorted(values)
123
+ return ordered[min(len(ordered) - 1, round((len(ordered) - 1) * 0.95))]
124
+
125
+
126
+ def _trace_groups(spans: Iterable[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
127
+ return group_traces(spans)
128
+
129
+
130
+ def _resolve_trace_prefix(spans: Iterable[dict[str, Any]], prefix: str) -> tuple[str, list[dict[str, Any]]]:
131
+ groups = _trace_groups(spans)
132
+ matches = [(trace_id, trace_spans) for trace_id, trace_spans in groups.items() if trace_id.startswith(prefix)]
133
+ if not matches:
134
+ raise ValueError(f"no trace matching {prefix!r}")
135
+ if len(matches) > 1:
136
+ raise ValueError(f"trace prefix {prefix!r} is ambiguous")
137
+ return matches[0]
138
+
139
+
140
+ def _duration_ms(span: dict[str, Any]) -> float:
141
+ return max(0, span["end_unix_nano"] - span["start_unix_nano"]) / 1e6
142
+
143
+
144
+ def _root(spans: list[dict[str, Any]]) -> dict[str, Any] | None:
145
+ ids = {s["span_id"] for s in spans}
146
+ for s in spans:
147
+ if s["parent_span_id"] is None or s["parent_span_id"] not in ids:
148
+ return s
149
+ return None
150
+
151
+
152
+ def run_summary(trace_id: str, spans: list[dict[str, Any]]) -> dict[str, Any]:
153
+ """Compact summary of one run (one trace)."""
154
+ root = _root(spans)
155
+ attrs = (root or {}).get("attributes", {})
156
+ started = min(s["start_unix_nano"] for s in spans)
157
+ ended = max(s["end_unix_nano"] for s in spans)
158
+ llm_spans = [s for s in spans if s["name"] == "llm.complete"]
159
+ tool_spans = [s for s in spans if s["name"] == "tool.call"]
160
+ decisions = [
161
+ e for s in spans for e in s.get("events", []) if e["name"] == "hitl.decision"
162
+ ]
163
+ return {
164
+ "trace_id": trace_id,
165
+ "task": attrs.get("agent.task"),
166
+ "model": attrs.get("llm.model"),
167
+ "started_unix_nano": started,
168
+ "duration_ms": round((ended - started) / 1e6, 2),
169
+ "spans": len(spans),
170
+ "llm_calls": len(llm_spans),
171
+ "tool_calls": len(tool_spans),
172
+ "tools_used": sorted({s["attributes"].get("tool.name", "?") for s in tool_spans}),
173
+ "human_decisions": len(decisions),
174
+ "denials": sum(1 for e in decisions if e["attributes"].get("hitl.decision") == "deny"),
175
+ "input_tokens": attrs.get("agent.usage.input_tokens"),
176
+ "output_tokens": attrs.get("agent.usage.output_tokens"),
177
+ "cost_usd": attrs.get("agent.cost_usd"),
178
+ "stopped_reason": attrs.get("agent.stopped_reason"),
179
+ "source": (root or spans[0]).get("_source_file"),
180
+ }
181
+
182
+
183
+ def list_runs(spans: list[dict[str, Any]], limit: int = 20) -> list[dict[str, Any]]:
184
+ """Newest-first summaries of every trace."""
185
+ traces = group_traces(spans)
186
+ summaries = [run_summary(tid, t) for tid, t in traces.items()]
187
+ summaries.sort(key=lambda s: s["started_unix_nano"], reverse=True)
188
+ return summaries[:limit]
189
+
190
+
191
+ def span_tree(trace_id: str, spans: list[dict[str, Any]]) -> dict[str, Any]:
192
+ """Nested span tree with durations — the shape of the run."""
193
+ by_parent: dict[str | None, list[dict[str, Any]]] = {}
194
+ for s in spans:
195
+ by_parent.setdefault(s["parent_span_id"], []).append(s)
196
+ for children in by_parent.values():
197
+ children.sort(key=lambda s: s["start_unix_nano"])
198
+
199
+ def node(span: dict[str, Any]) -> dict[str, Any]:
200
+ events = [e["name"] for e in span.get("events", [])]
201
+ out = {
202
+ "name": span["name"],
203
+ "duration_ms": round(_duration_ms(span), 2),
204
+ "status": span["status"],
205
+ "events": events,
206
+ "children": [node(c) for c in by_parent.get(span["span_id"], [])],
207
+ }
208
+ attrs = span["attributes"]
209
+ keep = {
210
+ k: v
211
+ for k, v in attrs.items()
212
+ if k.startswith(("tool.", "llm.", "hitl.", "agent.stopped"))
213
+ }
214
+ if keep:
215
+ out["attributes"] = {
216
+ key: _redact_text(value) if isinstance(value, str) else value
217
+ for key, value in keep.items()
218
+ }
219
+ return out
220
+
221
+ root = _root(spans)
222
+ return node(root) if root else {"error": f"no root span in trace {trace_id}"}
223
+
224
+
225
+ def slowest_spans(spans: list[dict[str, Any]], k: int = 5, name_filter: str | None = None) -> list[dict[str, Any]]:
226
+ """Top-k slowest spans — 'why was this run slow?' in one call."""
227
+ pool = [s for s in spans if name_filter is None or name_filter in s["name"]]
228
+ pool.sort(key=_duration_ms, reverse=True)
229
+ return [
230
+ {
231
+ "name": s["name"],
232
+ "duration_ms": round(_duration_ms(s), 2),
233
+ "tool": s["attributes"].get("tool.name"),
234
+ "trace_id": s["trace_id"],
235
+ }
236
+ for s in pool[:k]
237
+ ]
238
+
239
+
240
+ def approval_log(spans: list[dict[str, Any]]) -> list[dict[str, Any]]:
241
+ """Every human decision in a run: what was gated, who decided, why."""
242
+ out: list[dict[str, Any]] = []
243
+ for s in sorted(spans, key=lambda s: s["start_unix_nano"]):
244
+ tool = s["attributes"].get("tool.name", s["name"])
245
+ for e in s.get("events", []):
246
+ if e["name"] != "hitl.decision":
247
+ continue
248
+ a = e["attributes"]
249
+ out.append(
250
+ {
251
+ "tool": tool,
252
+ "decision": a.get("hitl.decision"),
253
+ "approver": a.get("hitl.approver"),
254
+ "rationale": _redact_text(a.get("hitl.rationale", "")),
255
+ "edited": bool(a.get("hitl.edited")),
256
+ "trace_id": s["trace_id"],
257
+ }
258
+ )
259
+ return out
260
+
261
+
262
+ def token_usage(spans: list[dict[str, Any]]) -> dict[str, Any]:
263
+ """Aggregate token + cost accounting across llm.complete spans."""
264
+ in_tok = out_tok = 0
265
+ cost = 0.0
266
+ calls = 0
267
+ for s in spans:
268
+ if s["name"] != "llm.complete":
269
+ continue
270
+ calls += 1
271
+ in_tok += int(s["attributes"].get("llm.usage.input_tokens", 0))
272
+ out_tok += int(s["attributes"].get("llm.usage.output_tokens", 0))
273
+ cost += float(s["attributes"].get("llm.cost_usd", 0.0))
274
+ return {
275
+ "llm_calls": calls,
276
+ "input_tokens": in_tok,
277
+ "output_tokens": out_tok,
278
+ "total_tokens": in_tok + out_tok,
279
+ "cost_usd": round(cost, 8),
280
+ }
281
+
282
+
283
+ def failure_report(
284
+ spans: list[dict[str, Any]],
285
+ *,
286
+ trace_id: str | None = None,
287
+ limit: int = 20,
288
+ ) -> list[dict[str, Any]]:
289
+ """Return actionable failed/error spans instead of raw JSONL.
290
+
291
+ This deliberately reports bounded, redacted diagnostics. It does not copy
292
+ normal tool output into the result, which keeps an observability query from
293
+ becoming a secret-exfiltration path.
294
+ """
295
+ pool = spans if trace_id is None else _resolve_trace_prefix(spans, trace_id)[1]
296
+ failures = [span for span in pool if _span_error(span)]
297
+ failures.sort(key=lambda span: span.get("start_unix_nano", 0), reverse=True)
298
+ out = []
299
+ for span in failures[: max(0, limit)]:
300
+ attrs = span.get("attributes", {})
301
+ out.append(
302
+ {
303
+ "trace_id": span.get("trace_id"),
304
+ "span_id": span.get("span_id"),
305
+ "name": span.get("name"),
306
+ "duration_ms": round(_duration_ms(span), 2),
307
+ "tool": attrs.get("tool.name"),
308
+ "status": _status_code(span) or "UNSET",
309
+ "result_status": attrs.get("tool.result_status"),
310
+ "detail": _span_error_detail(span),
311
+ "events": [event.get("name") for event in span.get("events", []) or []],
312
+ }
313
+ )
314
+ return out
315
+
316
+
317
+ def tool_stats(
318
+ spans: list[dict[str, Any]],
319
+ *,
320
+ trace_id: str | None = None,
321
+ tool_name: str | None = None,
322
+ limit: int = 50,
323
+ ) -> list[dict[str, Any]]:
324
+ """Aggregate tool health: volume, latency, errors, and denials."""
325
+ pool = spans if trace_id is None else _resolve_trace_prefix(spans, trace_id)[1]
326
+ grouped: dict[str, list[dict[str, Any]]] = {}
327
+ for span in pool:
328
+ name = span.get("attributes", {}).get("tool.name")
329
+ if span.get("name") != "tool.call" or not name:
330
+ continue
331
+ if tool_name and name != tool_name:
332
+ continue
333
+ grouped.setdefault(str(name), []).append(span)
334
+
335
+ rows = []
336
+ for name, calls in grouped.items():
337
+ durations = [_duration_ms(span) for span in calls]
338
+ errors = [span for span in calls if _span_error(span)]
339
+ denials = [
340
+ event
341
+ for span in calls
342
+ for event in span.get("events", []) or []
343
+ if event.get("name") == "hitl.decision"
344
+ and event.get("attributes", {}).get("hitl.decision") == "deny"
345
+ ]
346
+ last_error = next((_span_error_detail(span) for span in calls if _span_error_detail(span)), None)
347
+ rows.append(
348
+ {
349
+ "tool": name,
350
+ "calls": len(calls),
351
+ "errors": len(errors),
352
+ "error_rate": round(len(errors) / len(calls), 4),
353
+ "denials": len(denials),
354
+ "mean_duration_ms": round(sum(durations) / len(durations), 2),
355
+ "p95_duration_ms": round(_p95(durations), 2),
356
+ "last_error": last_error,
357
+ "traces": sorted({span.get("trace_id") for span in calls}),
358
+ }
359
+ )
360
+ rows.sort(key=lambda row: (-row["errors"], -row["mean_duration_ms"], row["tool"]))
361
+ return rows[: max(0, limit)]
362
+
363
+
364
+ def security_audit(
365
+ spans: list[dict[str, Any]],
366
+ *,
367
+ trace_id: str | None = None,
368
+ limit: int = 100,
369
+ ) -> dict[str, Any]:
370
+ """Summarize identity, provenance, authorization, and dangerous actions.
371
+
372
+ Missing identity/provenance is returned explicitly as a finding. The trace
373
+ reader cannot infer who authorized a call when the producer did not record
374
+ it.
375
+ """
376
+ pool = spans if trace_id is None else _resolve_trace_prefix(spans, trace_id)[1]
377
+ calls = [span for span in pool if span.get("name") == "tool.call"]
378
+ identity_keys = ("agent.identity", "auth.subject", "user.id", "mcp.client_id")
379
+ tenant_keys = ("auth.tenant", "tenant.id", "agent.tenant")
380
+ server_keys = ("mcp.server", "mcp.server.name", "mcp.server.version")
381
+ records = []
382
+ missing_identity = 0
383
+ missing_provenance = 0
384
+ denied = 0
385
+ for index, span in enumerate(sorted(calls, key=lambda item: item.get("start_unix_nano", 0))):
386
+ attrs = span.get("attributes", {})
387
+ identity = next((attrs[key] for key in identity_keys if attrs.get(key)), None)
388
+ tenant = next((attrs[key] for key in tenant_keys if attrs.get(key)), None)
389
+ server = next((attrs[key] for key in server_keys if attrs.get(key)), None)
390
+ decision_events = [
391
+ event for event in span.get("events", []) or [] if event.get("name") == "hitl.decision"
392
+ ]
393
+ decision = decision_events[-1].get("attributes", {}).get("hitl.decision") if decision_events else None
394
+ if not identity:
395
+ missing_identity += 1
396
+ if not server:
397
+ missing_provenance += 1
398
+ if decision == "deny":
399
+ denied += 1
400
+ if index >= max(0, limit):
401
+ continue
402
+ records.append(
403
+ {
404
+ "trace_id": span.get("trace_id"),
405
+ "span_id": span.get("span_id"),
406
+ "tool": attrs.get("tool.name"),
407
+ "risk": attrs.get("tool.risk"),
408
+ "identity": _redact_text(identity) if identity else None,
409
+ "tenant": _redact_text(tenant) if tenant else None,
410
+ "server": _redact_text(server) if server else None,
411
+ "decision": decision,
412
+ "result_status": attrs.get("tool.result_status"),
413
+ }
414
+ )
415
+ return {
416
+ "calls": len(calls),
417
+ "denied": denied,
418
+ "missing_identity": missing_identity,
419
+ "missing_server_provenance": missing_provenance,
420
+ "findings": [
421
+ finding
422
+ for finding in (
423
+ "tool calls lack recorded caller identity" if missing_identity else None,
424
+ "tool calls lack recorded MCP server provenance" if missing_provenance else None,
425
+ )
426
+ if finding
427
+ ],
428
+ "records": records,
429
+ }
430
+
431
+
432
+ def recent_activity(
433
+ spans: list[dict[str, Any]],
434
+ *,
435
+ cursor: str | None = None,
436
+ trace_id: str | None = None,
437
+ limit: int = 50,
438
+ ) -> dict[str, Any]:
439
+ """Return an incremental, redacted span feed for polling a live directory."""
440
+ pool = spans if trace_id is None else _resolve_trace_prefix(spans, trace_id)[1]
441
+ after = (0, "")
442
+ if cursor:
443
+ try:
444
+ start, span_id = cursor.split(":", 1)
445
+ after = (int(start), span_id)
446
+ except ValueError as exc:
447
+ raise ValueError("cursor must be '<start_unix_nano>:<span_id>'") from exc
448
+ ordered = sorted(
449
+ (span for span in pool if (span.get("start_unix_nano", 0), span.get("span_id", "")) > after),
450
+ key=lambda span: (span.get("start_unix_nano", 0), span.get("span_id", "")),
451
+ )
452
+ selected = ordered[: max(0, limit)]
453
+ records = []
454
+ for span in selected:
455
+ attrs = span.get("attributes", {})
456
+ records.append(
457
+ {
458
+ "trace_id": span.get("trace_id"),
459
+ "span_id": span.get("span_id"),
460
+ "name": span.get("name"),
461
+ "start_unix_nano": span.get("start_unix_nano"),
462
+ "duration_ms": round(_duration_ms(span), 2),
463
+ "status": _status_code(span) or "UNSET",
464
+ "tool": attrs.get("tool.name"),
465
+ "result_status": attrs.get("tool.result_status"),
466
+ "error": _span_error_detail(span),
467
+ "events": [event.get("name") for event in span.get("events", []) or []],
468
+ }
469
+ )
470
+ next_cursor = cursor
471
+ if selected:
472
+ last = selected[-1]
473
+ next_cursor = f"{last.get('start_unix_nano', 0)}:{last.get('span_id', '')}"
474
+ return {"next_cursor": next_cursor, "count": len(records), "spans": records}
475
+
476
+
477
+ def compare_runs(spans: list[dict[str, Any]], trace_ids: list[str]) -> dict[str, Any]:
478
+ """Compare selected runs for latency, cost, tokens, tools, and failures."""
479
+ if not trace_ids:
480
+ raise ValueError("trace_ids must contain at least one trace-id prefix")
481
+ runs = []
482
+ for prefix in trace_ids:
483
+ full_id, trace_spans = _resolve_trace_prefix(spans, prefix)
484
+ summary = run_summary(full_id, trace_spans)
485
+ usage = token_usage(trace_spans)
486
+ runs.append(
487
+ {
488
+ "trace_id": full_id,
489
+ "task": summary.get("task"),
490
+ "model": summary.get("model"),
491
+ "stopped_reason": summary.get("stopped_reason"),
492
+ "duration_ms": summary.get("duration_ms", 0),
493
+ "cost_usd": usage["cost_usd"],
494
+ "total_tokens": usage["total_tokens"],
495
+ "tool_calls": summary.get("tool_calls", 0),
496
+ "failures": len(failure_report(trace_spans)),
497
+ }
498
+ )
499
+ baseline = runs[0]
500
+ numeric = ("duration_ms", "cost_usd", "total_tokens", "tool_calls", "failures")
501
+ for run in runs:
502
+ run["delta_vs_first"] = {
503
+ key: round(float(run[key]) - float(baseline[key]), 8) for key in numeric
504
+ }
505
+ return {"baseline": baseline["trace_id"], "runs": runs}
506
+
507
+
508
+ def search_spans(spans: list[dict[str, Any]], needle: str) -> list[dict[str, Any]]:
509
+ """Substring search over span names and attribute values."""
510
+ needle_l = needle.lower()
511
+ hits = []
512
+ for s in spans:
513
+ haystacks = [s["name"]] + [str(v) for v in s["attributes"].values()]
514
+ if any(needle_l in h.lower() for h in haystacks):
515
+ hits.append(
516
+ {
517
+ "trace_id": s["trace_id"],
518
+ "name": s["name"],
519
+ "duration_ms": round(_duration_ms(s), 2),
520
+ "matched": [_redact_text(h) for h in haystacks if needle_l in h.lower()][:3],
521
+ }
522
+ )
523
+ return hits
mcp_trace/server.py ADDED
@@ -0,0 +1,163 @@
1
+ """FastMCP stdio server: agents querying their own traces.
2
+
3
+ Tool design notes (these are prompts, not just schemas):
4
+ - every tool says *when* to use it, not just what it does
5
+ - results are compact JSON; trees are the only nested shape
6
+ - trace_dir comes from --trace-dir / MCP_TRACE_DIR / ./traces
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from mcp.server.mcpserver import MCPServer
17
+
18
+ from mcp_trace import core
19
+
20
+ mcp = MCPServer(
21
+ "agenthawk",
22
+ instructions=(
23
+ "Query OpenTelemetry traces of agent runs (JSONL span files). "
24
+ "Use list_runs to see recent runs, run_summary/span_tree to inspect one, "
25
+ "slowest_spans for latency questions, approval_log for what humans "
26
+ "approved/denied, token_usage for cost questions, failure_report for "
27
+ "errors, tool_stats for tool health, security_audit for identity and "
28
+ "provenance gaps, recent_activity for incremental live polling, and "
29
+ "compare_runs for regressions."
30
+ ),
31
+ )
32
+
33
+ _trace_dir: Path = Path("./traces")
34
+
35
+
36
+ def _spans() -> list[dict]:
37
+ try:
38
+ return core.load_trace_dir(_trace_dir)
39
+ except FileNotFoundError:
40
+ return []
41
+
42
+
43
+ def _resolve(trace_id: str) -> list[dict]:
44
+ spans = [s for s in _spans() if s["trace_id"].startswith(trace_id)]
45
+ if not spans:
46
+ known = ", ".join(t[:12] for t in core.group_traces(_spans())) or "(none)"
47
+ raise ValueError(f"no trace matching {trace_id!r}; known prefixes: {known}")
48
+ return spans
49
+
50
+
51
+ def _dump(obj) -> str:
52
+ return json.dumps(obj, indent=2, ensure_ascii=False, default=str)
53
+
54
+
55
+ @mcp.tool()
56
+ def list_runs(limit: int = 10) -> str:
57
+ """List recent agent runs: task, model, duration, tool use, human decisions, cost.
58
+
59
+ Use first to find the trace_id for deeper inspection.
60
+ """
61
+ runs = core.list_runs(_spans(), limit=limit)
62
+ if not runs:
63
+ return f"No traces found in {_trace_dir}. Point --trace-dir at your harness traces."
64
+ for r in runs:
65
+ r["trace_id"] = r["trace_id"][:12] + "…"
66
+ return _dump(runs)
67
+
68
+
69
+ @mcp.tool()
70
+ def run_summary(trace_id: str) -> str:
71
+ """Compact summary of one run (accepts trace_id prefix)."""
72
+ spans = _resolve(trace_id)
73
+ return _dump(core.run_summary(spans[0]["trace_id"], spans))
74
+
75
+
76
+ @mcp.tool()
77
+ def span_tree(trace_id: str) -> str:
78
+ """Nested span tree of a run — the shape of what the agent did, with durations."""
79
+ spans = _resolve(trace_id)
80
+ return _dump(core.span_tree(spans[0]["trace_id"], spans))
81
+
82
+
83
+ @mcp.tool()
84
+ def slowest_spans(trace_id: str | None = None, k: int = 5) -> str:
85
+ """Top-k slowest spans. Use for 'why was this run slow?'. Omit trace_id to search all runs."""
86
+ spans = _resolve(trace_id) if trace_id else _spans()
87
+ return _dump(core.slowest_spans(spans, k=k))
88
+
89
+
90
+ @mcp.tool()
91
+ def approval_log(trace_id: str | None = None) -> str:
92
+ """Human-in-the-loop audit: every approval/denial/edit, who decided, and the rationale.
93
+
94
+ Use when asked 'why did the agent get to do X?' or 'what was denied?'.
95
+ """
96
+ spans = _resolve(trace_id) if trace_id else _spans()
97
+ return _dump(core.approval_log(spans))
98
+
99
+
100
+ @mcp.tool()
101
+ def token_usage(trace_id: str | None = None) -> str:
102
+ """Token and cost totals. Omit trace_id to aggregate across all runs."""
103
+ spans = _resolve(trace_id) if trace_id else _spans()
104
+ return _dump(core.token_usage(spans))
105
+
106
+
107
+ @mcp.tool()
108
+ def search_spans(needle: str, trace_id: str | None = None) -> str:
109
+ """Substring search over span names/attributes, e.g. a tool name, file path, or 'denied'."""
110
+ spans = _resolve(trace_id) if trace_id else _spans()
111
+ return _dump(core.search_spans(spans, needle))
112
+
113
+
114
+ @mcp.tool()
115
+ def failure_report(trace_id: str | None = None, limit: int = 20) -> str:
116
+ """Show bounded, redacted tool/provider failures and their actionable diagnostics."""
117
+ spans = _resolve(trace_id) if trace_id else _spans()
118
+ return _dump(core.failure_report(spans, trace_id=None, limit=limit))
119
+
120
+
121
+ @mcp.tool()
122
+ def tool_stats(trace_id: str | None = None, tool_name: str | None = None, limit: int = 50) -> str:
123
+ """Rank tools by errors, denials, latency, and call volume to find unhealthy integrations."""
124
+ spans = _resolve(trace_id) if trace_id else _spans()
125
+ return _dump(core.tool_stats(spans, trace_id=None, tool_name=tool_name, limit=limit))
126
+
127
+
128
+ @mcp.tool()
129
+ def security_audit(trace_id: str | None = None, limit: int = 100) -> str:
130
+ """Audit caller identity, tenant, server provenance, risk, and approval evidence for tool calls."""
131
+ spans = _resolve(trace_id) if trace_id else _spans()
132
+ return _dump(core.security_audit(spans, trace_id=None, limit=limit))
133
+
134
+
135
+ @mcp.tool()
136
+ def recent_activity(
137
+ cursor: str | None = None,
138
+ trace_id: str | None = None,
139
+ limit: int = 50,
140
+ ) -> str:
141
+ """Poll newly written spans using a cursor; useful while an agent run is still active."""
142
+ spans = _resolve(trace_id) if trace_id else _spans()
143
+ return _dump(core.recent_activity(spans, cursor=cursor, trace_id=None, limit=limit))
144
+
145
+
146
+ @mcp.tool()
147
+ def compare_runs(trace_ids: list[str]) -> str:
148
+ """Compare selected trace-id prefixes for latency, cost, tokens, tools, and failures."""
149
+ return _dump(core.compare_runs(_spans(), trace_ids))
150
+
151
+
152
+ def main() -> None:
153
+ global _trace_dir
154
+ parser = argparse.ArgumentParser(description="MCP server for agent self-observability")
155
+ parser.add_argument(
156
+ "--trace-dir",
157
+ default=os.environ.get("MCP_TRACE_DIR", "./traces"),
158
+ help="directory of JSONL span files (default: $MCP_TRACE_DIR or ./traces)",
159
+ )
160
+ args = parser.parse_args()
161
+ _trace_dir = Path(args.trace_dir).resolve()
162
+ print(f"AgentHawk serving traces from {_trace_dir}", file=sys.stderr)
163
+ mcp.run(transport="stdio")