Mcp Agent Trace Inspector

io.github.dbsectrainer由 GitHub 帳號 dbsectrainer 發布v1.0.1更新於 Nov 4, 2026

Step-by-step observability for MCP agent workflows

概覽

AI 產生的概覽

本地優先的 MCP 伺服器,讓助理記錄、檢視、比較並匯出自身代理工作流程各步驟的追蹤資料。

可以做什麼
  • 開始、記錄步驟並結束追蹤,保存工具名稱、輸入、輸出、token 數與延遲
  • 列出追蹤紀錄並產生摘要,含步驟數、token、延遲、成本估算與推理鏈辨識
  • 比較兩筆追蹤,並單獨擷取推理或規劃步驟
  • 匯出獨立 HTML 儀表板、OTLP/JSON span,或將合規稽核日誌匯出為 JSON 或 CSV
  • 設定延遲、錯誤率與成本告警規則(可選 Slack 或通用 webhook),並設定保留政策
適用情境
適合需要了解代理如何執行多步驟工具流程的情境:分析延遲與 token 成本、比較兩次執行、找出推理步驟,或產生稽核紀錄與可分享的 HTML 報告。追蹤是顯式的,需要代理主動呼叫追蹤工具。
執行需求
透過 npx 以 stdio 在本機執行,需要 Node.js 22.13 或更新版本。核心追蹤不需帳號、API 金鑰或資料庫伺服器,資料存於本機 SQLite 檔案(預設位於使用者家目錄下)。選用 HTTP 模式使用 MCP_API_KEY 與 MCP_JWT_SECRET,告警 webhook 使用 MCP_SLACK_WEBHOOK 或 MCP_ALERT_WEBHOOK。
安裝前請注意
追蹤會保存工具輸入與輸出,可能包含密鑰、提示詞或個人資料;除設定告警 webhook 外不會外傳,分享 HTML 匯出前請先檢查內容。保留工具會封存並刪除追蹤紀錄,啟動時的清理無法復原。HTTP 模式應僅綁定回環位址,並在上游設定認證與 TLS。稽核日誌僅依慣例附加寫入,不具防竄改能力。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Mcp Agent Trace Inspector,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

MCP Agent Trace Inspector

Local-first, MCP-native observability for agent workflows. Every tool call, prompt transformation, latency, token estimate, and cost estimate is recorded in a local SQLite database — no cloud account, no API key, and no traces leaving your machine.

Built specifically for MCP rather than bolted onto a generic LLM proxy.

Tools · Configuration · HTTP transport · Verification · Known limitations · Contributing

Overview

mcp-agent-trace-inspector is an MCP server. Agents call its tools to start a trace, record each step they take, and finish the trace. Humans then inspect summaries, compare runs, export a self-contained HTML dashboard, export OTLP/JSON spans, or stream the compliance audit log.

text
Agent / MCP client      │  trace_start → trace_step → trace_end      ▼MCP Agent Trace Inspector      ├── SQLite (~/.mcp/traces.db)      ├── JSONL audit log (~/.mcp/trace-inspector-audit.jsonl)      └── tools: summaries, diffs, HTML, OTLP/JSON, retention, alerts

Key features

  • Tool-call tracing — inputs, outputs, latency, caller-supplied or automatic token estimates for every step.
  • Persistent local storage — SQLite via Node's built-in node:sqlite; traces survive restarts and never require a service.
  • Self-contained HTML dashboard — error highlighting, step timeline, latency waterfall, responsive layout, and expandable input/output JSON.
  • Cost estimation — offline cl100k_base tokenizer plus a configurable pricing table; no API calls and no billing-account data.
  • Trace comparison — aggregate and step-by-step diffs between two runs.
  • Reasoning-chain extraction — finds reasoning/thinking/planning steps.
  • OTLP/JSON export — standard resourceSpans → scopeSpans → spans documents.
  • Compliance audit log — append-only JSONL of recorded steps, exportable as JSON or CSV with date filtering.
  • Alerts — persisted latency, error-rate, and cost thresholds evaluated when a trace ends; optional Slack or generic webhook delivery.
  • Retention controls — startup purge or explicit archive/delete policy.
  • Two transports — stdio (default) and stateless Streamable HTTP with optional API-key/JWT authentication and rate limiting.

Technology stack

LayerChoice
RuntimeNode.js ≥ 22.13 (ESM, built-in node:sqlite)
LanguageTypeScript 5, strict mode
Protocol@modelcontextprotocol/sdk (tools, resources, prompts)
HTTPExpress 5 + MCP Streamable HTTP transport
StorageSQLite through node:sqlite
Tokenizationgpt-tokenizer (cl100k_base)
CLIyargs
TestsVitest + V8 coverage
Lint / formattingESLint + Prettier
CIGitHub Actions (install, audit, lint, format, test, build)

Requirements

  • Node.js 22.13.0 or newer. node:sqlite first became available in Node 22.5.0 behind --experimental-sqlite; it is unflagged from 22.13.0. This project does not pass the flag.
  • npm.
  • No database server, API key, or external account is required for core tracing.

Quick start (MCP client)

Add the server to your MCP client configuration:

json
{  "mcpServers": {    "trace-inspector": {      "command": "npx",      "args": ["-y", "mcp-agent-trace-inspector@latest"]    }  }}

Use a project-specific database:

json
{  "mcpServers": {    "trace-inspector": {      "command": "npx",      "args": [        "-y",        "mcp-agent-trace-inspector@latest",        "--db=~/traces/my-project.db"      ]    }  }}

Then ask your agent to trace its own work:

text
Start a trace named "test-run" with trace_start.Record a trace_step for each tool you call, including that tool's input and output.Call trace_end when you are done, then call get_trace_summary for the trace.

The summary contains the step count, estimated token total, total recorded latency, wall-clock duration, cost estimate, and reasoning-chain detection. Tracing is explicit: the inspector records steps when the agent calls trace_step; it does not intercept other MCP servers automatically.

From source

bash
npm cinpm run buildnode dist/index.js --db=~/.mcp/traces.db

Development mode runs TypeScript directly and logs MCP protocol messages on stderr:

bash
npm run dev -- --db=/tmp/traces.db

Streamable HTTP transport

HTTP mode is useful for a local team instance or a container. It is stateless: every POST gets a fresh MCP server and transport, there is no Mcp-Session-Id, and the endpoint does not offer a server-initiated SSE stream. Send every JSON-RPC message as its own POST /mcp request.

bash
node dist/index.js --db=~/.mcp/traces.db --http-port=3000 --http-host=127.0.0.1# stderr: MCP Agent Trace Inspector HTTP server listening on http://127.0.0.1:3000/mcp

Initialize the endpoint:

bash
curl -s http://127.0.0.1:3000/mcp \  -H 'Content-Type: application/json' \  -H 'Accept: application/json, text/event-stream' \  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'

The response is an SSE frame. Call a tool:

bash
curl -s http://127.0.0.1:3000/mcp \  -H 'Content-Type: application/json' \  -H 'Accept: application/json, text/event-stream' \  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_traces","arguments":{}}}'
BehaviorValue
EndpointPOST /mcp
GET / DELETE /mcp405 with Allow: POST
Default bind address127.0.0.1 (loopback only)
Request body limit10 MB
Rate limit60 requests / 60 s per validated API key or client IP
Auth (optional)X-API-Key and/or Authorization: Bearer <HS256 JWT>
DNS-rebinding guardHost header must be localhost/127.0.0.1 when bound to loopback

HTTP authentication

Set one or both environment variables before starting the server:

bash
MCP_API_KEY=change-me \MCP_JWT_SECRET=change-me-too \node dist/index.js --http-port=3000 --http-host=127.0.0.1
  • If MCP_API_KEY is set, every HTTP request must send X-API-Key: <value>.
  • If MCP_JWT_SECRET is set, every HTTP request must send Authorization: Bearer <HS256 JWT>; exp and nbf claims are checked.
  • If both are set, both are required.
  • The stdio transport ignores both variables.

--http-host=0.0.0.0 is allowed but the server warns. Put TLS and an authenticating reverse proxy in front of any non-loopback deployment; do not expose the raw endpoint to an untrusted network.

When the server is bound to loopback behind a reverse proxy, the proxy must rewrite the Host header to 127.0.0.1:<port>. The loopback DNS-rebinding guard rejects other Host values with 403 by design.

Configuration

CLI flags

FlagDefaultDescription
--db, --db-path~/.mcp/traces.dbSQLite database file. ~ is expanded. :memory: is supported for tests.
--retention-days0On startup, delete traces older than N days. 0 disables.
--pricing-tablebuilt-in tableJSON file of { "model": { "input": number, "output": number } }. Merged over built-in rates.
--no-token-countfalseDisable automatic token counting (token_count values become null).
--http-portunsetStart in HTTP mode on this port (1–65535) instead of stdio.
--http-host127.0.0.1HTTP bind address. Prefer loopback unless authentication and TLS are used.
--help—Show usage.
--version—Print the package version.

Environment variables

The server does not load .env files automatically. Export variables in your shell or configure them in your MCP client.

VariableDefaultPurpose
MCP_API_KEYunsetHTTP only: require X-API-Key on every request.
MCP_JWT_SECRETunsetHTTP only: require a valid HS256 Bearer JWT.
MCP_AUDIT_LOG_PATH~/.mcp/trace-inspector-audit.jsonlCompliance audit log path. Created owner-readable/writable (0600).
MCP_SLACK_WEBHOOKunsetSlack incoming-webhook URL used when an alert fires.
MCP_ALERT_WEBHOOKunsetGeneric JSON webhook URL used when an alert fires.

See .env.example for a copy-paste template. Never commit real secrets or database files; both are ignored by .gitignore.

Tools

The server exposes 13 tools. Tool annotations mark state-changing tools (readOnlyHint: false) and destructive retention (destructiveHint: true).

Trace lifecycle

ToolPurpose
trace_startBegin a trace. Returns a trace_id. Pass "auto" or an empty string for a generated name.
trace_stepRecord one step for a running trace. Steps are rejected after trace_end.
trace_endMark a trace completed, evaluate alert rules, and return fired alerts. Repeated calls are idempotent.

trace_step requires trace_id, tool_name, input (object), and output (object). token_count must be a non-negative integer; latency_ms must be a finite, non-negative number. Caller-supplied token counts are used as-is.

Inspection

ToolPurpose
list_tracesList traces, newest first. Optional positive-integer limit.
get_trace_summaryStep/token/latency totals, duration, cost estimate, reasoning detection.
compare_tracesDiff two traces: aggregates, tool coverage, and per-position steps.
extract_reasoning_chainReturn only reasoning/thinking/planning steps.

Export

ToolPurpose
export_dashboardSelf-contained HTML dashboard with error rows, expandable JSON, and latency waterfall.
export_otelOTLP/JSON document (resourceSpans → scopeSpans → spans) for one trace or all traces.
export_compliance_logAudit log as JSON or CSV, optionally filtered by from_date / to_date (date-only upper bound includes the whole day).

export_otel returns a document; it does not push to a collector. Write the result to a file and submit it with your OTLP tooling, or adapt it in your client. Non-UUID trace/step IDs are hashed into valid lowercase 32/16-character hex IDs.

Operations

ToolPurpose
configure_alertsPersist alert rules (latency, error_rate, cost). Optional Slack/generic webhooks.
set_retention_policySet the in-process retention policy (days). Must be called before apply_retention in that process.
apply_retentionArchive traces older than N days; delete archived traces older than 2×N days.

Resources and prompts

  • Resources — every trace is exposed as trace://{trace_id} with trace metadata, totals, and step metadata as JSON.
  • Prompt — analyze-trace accepts trace_id and returns a structured investigation prompt covering performance, errors, reasoning chains, and optimization opportunities.

Token counting, pricing, and cost

  • Automatic counting uses the cl100k_base BPE encoding via gpt-tokenizer.
  • Payloads up to 128 KiB are tokenized exactly. Larger automatic payloads use the standard ceil(characters / 4) estimate to keep synchronous step recording bounded. Pass token_count explicitly if you need an exact count for a large payload.
  • --no-token-count disables automatic counting entirely.
  • The built-in pricing table contains Claude Opus/Sonnet/Haiku input and output rates. --pricing-table merges over those entries, so a custom file can add a model or override a rate while retaining the defaults.
  • get_trace_summary estimates cost from the aggregate token count using the input rate. Token counts are not split into input/output categories, so this is an estimate, not a billing figure.
  • The default model is claude-sonnet-4-6. Unknown models report N/A.

Retention semantics

There are two related mechanisms:

  1. Startup purge (--retention-days=N) deletes traces whose started_at is older than N days, plus their steps. This is irreversible and applied when the process starts.
  2. Tool policy (set_retention_policy then apply_retention) is held in memory for the lifetime of the process. It sets archived = 1 on traces older than N days and deletes archived traces older than 2×N days, along with their steps. The policy is not persisted across restarts; call set_retention_policy again after a restart. Archived traces remain queryable until deleted.

Alerts

Rules are persisted in the alert_rules table and evaluated when trace_end runs:

  • latency — average recorded step latency across all stored traces (ms).
  • error_rate — percentage of steps whose output contains error or isError: true.
  • cost — total recorded tokens × the default input rate ($0.003 / 1K tokens).

Metrics are global to the database, not scoped to the just-ended trace. When a rule fires, the alert is included in the trace_end response (alerts_fired, alerts) and delivered to configured webhooks. Webhook requests time out after 5 seconds and failures are logged without failing the tool call. There is no retry or deduplication.

Channel URLs are process configuration, not database rows: pass them to configure_alerts, or set MCP_SLACK_WEBHOOK / MCP_ALERT_WEBHOOK. Omitting a URL on a later configure_alerts call preserves the previously configured channel.

Verification

Automated checks (no external services required):

bash
npm cinpm run verify          # lint + format check + typecheck + testsnpm test -- --coverage  # unit/integration tests + V8 coveragenpm run build           # compile to dist/npm run verify:e2e      # build, then run real stdio + HTTP MCP processesnpm run screenshots     # Chrome/CDP capture of the generated dashboard (set CHROME_PATH if needed)

npm run verify:e2e starts the built server, exercises all 13 tools against a temp SQLite database, drives two sequential HTTP requests to prove the stateless transport works, checks auth/validation failures, and writes machine-readable evidence under docs/evidence/test-results/. It does not use a mock transport.

Optional MCP Inspector verification:

bash
npm run buildnpx @modelcontextprotocol/inspector node dist/index.js

Visual evidence

The dashboard is generated by the real export_dashboard tool from a real trace and opened in Chrome at desktop and mobile viewport sizes. See the verification report for the commands, test results, and per-screenshot workflow associations.

[Desktop dashboard showing the trace timeline, stats, and error row]

[Mobile dashboard with responsive stat cards and card-style step timeline]

[Dashboard with an error step's input expanded]

Security

Traces contain tool inputs and outputs and may include secrets, prompts, or personal data. The inspector stores them locally and does not transmit them except when you configure alert webhooks. Review trace contents before sharing HTML exports.

  • The default database is ~/.mcp/traces.db; the audit log is created with mode 0600.
  • The HTTP server binds to 127.0.0.1 by default. Configure MCP_API_KEY and/or MCP_JWT_SECRET before binding to a non-loopback address, and use TLS upstream.
  • HTTP request bodies are limited to 10 MB and requests are rate-limited.
  • Do not commit .env, *.db, *.db-wal, or audit logs.
  • Report vulnerabilities privately as described in SECURITY.md.

Known limitations

  • Stateless HTTP only. There is no session resumption, server-initiated SSE stream, or OAuth 2.0 authorization (yet). GET/DELETE return 405 by design.
  • Single-node SQLite. WAL mode supports concurrent local processes, but this is not a distributed trace store.
  • Token counts are estimates. They are not a substitute for provider billing, and very large automatic payloads use a chars/4 approximation.
  • Alerts are evaluated only on trace_end over database-wide metrics, with best-effort webhook delivery and no retry/deduplication.
  • Retention tool state is in-memory. set_retention_policy must be called after each restart; only the CLI startup purge is automatic.
  • The dashboard is a file. There is no hosted dashboard or share link; the HTML is self-contained and can be saved/shared deliberately.
  • Audit log integrity is append-only by convention, not cryptographic or tamper-evident.
  • node:sqlite is still evolving (release candidate in newer Node releases). Pin a Node version in production if API stability is required.
  • No team sharing, search UI, or SSO. Those are tracked in ROADMAP.md.

Contributing

See CONTRIBUTING.md. Run the full local gate before opening a PR:

bash
npm cinpm run verify

Commit messages follow Conventional Commits. One focused change per pull request.

License

MIT — see LICENSE.

來源:README.md,提交 56e9f5b

工具

13

trace_start

Begin a new agent workflow trace. Returns a trace_id to use with subsequent calls. Example: { "name": "My Search Workflow" }. Pass "auto" or leave name blank for an auto-generated name.

輸入參數name必填

trace_step

Record a single step within a running trace. Captures tool name, input, output, optional token count and latency. Steps cannot be added after trace_end. Example: { "trace_id": "abc-123", "tool_name": "web_search", "input": {"query": "hello"}, "output": {"results": ["a","b"]}, "token_count": 50, "latency_ms": 320 }

輸入參數input必填output必填trace_id必填tool_name必填latency_mstoken_count

trace_end

Mark a trace as completed and evaluate the currently configured alert rules. Further trace_step calls for this trace are rejected. Example: { "trace_id": "abc-123" }

輸入參數trace_id必填

get_trace_summary

Retrieve a summary of a trace including step count, total tokens, total latency, cost estimate, and reasoning chain detection. Example: { "trace_id": "abc-123", "model": "claude-sonnet-4-6" }

輸入參數modeltrace_id必填

list_traces

List all stored traces with their names, statuses, and timestamps. Example: { "limit": 10 } to get the 10 most recent traces.

輸入參數limit

export_dashboard

Generate a self-contained HTML dashboard for a trace with error highlighting and latency waterfall visualization. Returns the full HTML as a string. Example: { "trace_id": "abc-123" }

輸入參數trace_id必填

compare_traces

Compare two traces side by side: step counts, tokens, latency, and step-by-step differences. Example: { "trace_id_a": "abc-123", "trace_id_b": "def-456" }

輸入參數trace_id_a必填trace_id_b必填

extract_reasoning_chain

Extract only the reasoning/thinking steps from a trace. Returns steps whose tool_name matches reasoning patterns (reason, think, plan, reflect, analyz, consider) or whose input/output content includes the word "think". Example: { "trace_id": "abc-123" }

輸入參數trace_id必填

export_otel

Export trace(s) as an OTLP/JSON document (resourceSpans → scopeSpans → spans) suitable for an OTLP collector or backend. Omit trace_id to export all traces. Example: { "format": "json" } or { "trace_id": "abc-123", "format": "json" }

輸入參數format必填trace_id

configure_alerts

Persist alert rules for latency, error rate, or cost thresholds. Rules are evaluated on trace_end; optional Slack or generic webhooks deliver fired alerts. Example: { "rules": [{"type":"latency","threshold":1000}], "slack_webhook": "https://hooks.slack.com/..." }

輸入參數rules必填webhook_urlslack_webhook

set_retention_policy

Set the trace retention policy (how many days to keep traces before archiving). Example: { "retention_days": 30 }

輸入參數retention_days必填

apply_retention

Apply the current in-process retention policy: archives traces older than retention_days and deletes archived traces past 2× threshold. Call set_retention_policy first. Example: {}

無需輸入參數。

export_compliance_log

Export the compliance audit log as JSON or CSV. Example: { "format": "json" } or { "format": "csv", "from_date": "2025-01-01", "to_date": "2025-12-31" }

輸入參數format必填to_datefrom_date

版本歷史

2
  1. v1.0.1最新Nov 4, 2026
  2. v1.0.0Sep 16, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分
  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分