mcp-context-inspector
mcp-context-inspector
모든 도구 호출 에이전트에 바로 적용할 수 있는 MCP 서버 + 실행 메트릭 레코더입니다. 각 실행 후 에이전트 루프를 record_session(prompt, model_id, loop_result)로 연결하면 다음과 같은 기능을 무료로 제공합니다:
실제 MCP 서버(Streamable HTTP) — Claude Desktop, Cursor, 자체 채팅 UI 등 모든 MCP 클라이언트가 연결 가능 — 세션 기록, 비용, 토큰/도구 메트릭에 대한 7개의 읽기 전용 도구를 노출하며...
Context Window Explorer — 모델의 컨텍스트 윈도우에 실제로 입력된 내용을 블록별로 완전히 투명하게 보여줍니다. 정직한(명시적으로 추정치라고 표시된) 토큰 수, 비례 분할 막대, 블록별 클릭 시 확장되는 세부 패널을 제공합니다:

(이 패키지와 함께 개발된 참조 채팅 UI —
sre-investigation-agent의 스크린샷입니다. 위 패널은 MCP 클라이언트가get_context_timeline을 쿼리할 때 얻는 내용입니다.)
대부분의 에이전트 관측 도구는 자체 UI에 이미 표시된 데이터를 다시 보여줍니다. 이 도구는 일반적으로 전혀 볼 수 없는 것을 보여줍니다: 시스템 프롬프트 대 도구 사양 대 추론 대 도구 호출/결과 대 최종 답변을 실제로 컨텍스트에 입력된 순서대로, 모델의 실제 컨텍스트 윈도우에 대한 누적 토큰 합계와 함께 — 그리고 해당 블록 중 최종 사용자에게 표시되는 것과 보이지 않는 오버헤드가 무엇인지까지 알려줍니다.
설치
uv add mcp-context-inspector # or: pip install mcp-context-inspector
# while co-developing locally against an editable checkout:
uv add --editable ../mcp-context-inspectorRelated MCP server: ai-usage-metrics-mcp
에이전트에 연결하기
from metrics import store
session_id = store.record_session(prompt, model_id, loop_result)loop_result는 에이전트 루프가 반환하는 모든 값입니다. 이 패키지가 필요로 하는 형식은 다음과 같습니다:
{
"trace": [{"tool": "...", "args": {...}, "status": "ok"}, ...],
"turns": [{"input_tokens": int, "output_tokens": int, "latency_ms": int}, ...],
"input_tokens": int, "output_tokens": int, "total_tokens": int, "latency_ms": int,
"context_blocks": [ # optional — omit and you just lose the Explorer, nothing crashes
{"category": "system", "label": "...", "char_count": int, "token_estimate": int, "turn_n": int | None},
...
],
}context_blocks 카테고리: system, tools, user, reasoning, thinking, tool_call, tool_result (선택적으로 실패 색상 구분을 위한 "status" 키 포함), answer.
서버 실행하기
uv run python -m mcp_server.serverMCP_AUTH_TOKEN이 설정되지 않은 경우 → 시작 시 생성하여 출력합니다. Jupyter 서버의 출력 토큰과 동일한 신뢰 모델입니다. 재시작 간에 안정적인 값을 원하면 직접 설정하세요. http://127.0.0.1:8787/mcp에 Authorization: Bearer <token> 헤더와 함께 MCP 클라이언트를 연결하세요.
스토리지 백엔드
STORAGE_BACKEND=sqlite (기본값, 로컬 개발 — data/metrics.db) 또는 STORAGE_BACKEND=dynamodb (METRICS_TABLE/AWS_REGION 설정) — 두 경우 모두 동일한 함수 시그니처를 사용하므로 호출자는 어떤 백엔드가 활성화되어 있는지 알 필요가 없습니다.
7가지 MCP 도구
get_session_metrics, get_token_breakdown, get_tool_metrics, get_agent_trace, get_cost_estimate, get_recent_sessions, get_context_timeline. 일반 REST 엔드포인트도 /api/* 아래에 노출되어 있습니다. curl 친화적인 디버깅 대안으로, 동일한 기본 metrics/store.py 함수를 호출합니다.
관련 저장소
sre-investigation-agent — 이 패키지가 추출되고 함께 개발된 참조 채팅 UI + Bedrock 에이전트입니다.
Available Tools
8 toolsget_agent_traceARead-onlyIdempotent
The ordered sequence of tool calls for one session -- each entry {name, args, status}.
Use to replay what the agent actually did, in execution order; use get_tool_metrics for aggregate counts.
session_id: id from get_recent_sessions / record_session.
Returns [] for an unknown or non-owned session.
Inputs: session_id (required).
get_context_timelineARead-onlyIdempotent
Ordered, categorized breakdown of everything that entered ONE session's context window.
Each block (system prompt, tool specs, injected context, user turns, reasoning, tool calls/results, final answer) is marked user-visible vs invisible overhead, with cumulative character-based token estimates against the model's real window size. Use for context-window composition analysis; use get_session_metrics for exact provider token usage. The estimates here are character-based, not exact Bedrock counts.
session_id: id from get_recent_sessions / record_session.
Returns [] for an unknown or non-owned session, or one recorded without the optional context_blocks field.
Inputs: session_id (required).
get_cost_estimateARead-onlyIdempotent
Estimated USD cost as a float.
Pass session_id for one session's cost, or period_seconds for the summed cost of your sessions in the last N seconds. Give exactly one; non-owners are scoped to their own sessions. These are estimates from token counts and a static price table, not billed amounts.
session_id: optional session id. period_seconds: optional lookback window in seconds (e.g. 86400 for the last day).
Returns 0.0 for an unknown or non-owned session_id, and for a period with no matching sessions.
Inputs: session_id, period_seconds. Returns: result
get_recent_sessionsARead-onlyIdempotent
List recent sessions, newest first: [{session_id, prompt, model_id, created_at, ...}].
Call this first to discover session_ids for the other get_* tools. Non-owners see only their own sessions; the owner token sees all.
limit: max rows to return (default 10), newest first.
Inputs: limit.
get_session_metricsARead-onlyIdempotent
Full metrics for ONE recorded session: metadata plus per-prompt tokens, latency, and cost.
Use when you have a session_id and need exact provider usage numbers for that session. For the block-by-block token composition of the context window use get_context_timeline instead; for a cost total across many sessions use get_cost_estimate.
session_id: the opaque, case-sensitive id returned by record_session or listed by get_recent_sessions.
Returns {"error": "session not found"} if the id is unknown or not owned by the caller (the two are deliberately indistinguishable).
Inputs: session_id (required).
get_token_breakdownARead-onlyIdempotent
Per-turn input/output token and latency breakdown for one session, in turn order.
Use to see how token usage grew turn-by-turn within a session; use get_session_metrics for session totals.
session_id: id from get_recent_sessions / record_session.
Returns [] for an unknown or non-owned session.
Inputs: session_id (required).
get_tool_metricsARead-onlyIdempotent
Tool-call counts grouped by status (ok / error), for one session or aggregated.
Use for a quick success/failure summary; use get_agent_trace for the ordered call list. Non-owners only ever see their own sessions; the owner token sees everyone's.
session_id: optional. Omit for the aggregate across all your sessions; pass an id for just that session.
Inputs: session_id.
record_sessionA
Append ONE agent execution's metrics to this server's store; returns the new session_id.
This is how a remote agent gets its own runs into the server, rather than only being able to query what the server owner recorded locally. Attributed to the connected identity: your Google account if you signed in via /auth/login, or owner=None for the owner token. NOT idempotent -- each call mints a new session_id. Never updates or deletes an existing session; the get_* tools read what this writes.
prompt: the user prompt that started the run. model_id: the provider model identifier, e.g. "anthropic.claude-3-5-sonnet-20241022-v2:0". loop_result: the run's token / latency / trace payload. Required keys: input_tokens (int), output_tokens (int), total_tokens (int), latency_ms (float), turns (list). Optional: trace (list), context_blocks (list -- omit if you don't have per-block context data; get_context_timeline needs it).
each
turnsitem: input_tokens (int), output_tokens (int), latency_ms (float); optional cache_read_input_tokens / cache_write_input_tokens (int, default 0).each
traceitem: tool (str), args (dict), status (str); optional latency_ms (float, default 0), timestamp (float epoch seconds, default record time).each
context_blocksitem: category (str), label (str), char_count (int), token_estimate (int); optional turn_n (int or null -- null for a pre-conversation block), status (str), content (str).
Example loop_result:
{
"input_tokens": 1200, "output_tokens": 340, "total_tokens": 1540,
"latency_ms": 4210.0,
"turns": [
{"input_tokens": 1200, "output_tokens": 340, "latency_ms": 4210.0,
"cache_read_input_tokens": 800, "cache_write_input_tokens": 0}
],
"trace": [
{"tool": "grep_logs", "args": {"pattern": "ERROR"}, "status": "ok",
"latency_ms": 120.0, "timestamp": 1756400000.0}
]
}
Inputs: prompt (required), model_id (required), loop_result (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each read tool targets a distinct slice of session data—totals, per-turn breakdown, tool-call counts, ordered trace, cost, context timeline, and session discovery—and the descriptions explicitly point to which tool to use. record_session is the only write tool and is clearly separated. No two tools are fungible.
All read tools follow a consistent get_<object>_<metric> snake_case pattern, and the single write tool uses the verb record_session. The naming is predictable and matches each tool's function without mixing conventions.
Eight tools is well-scoped for a session-metrics store: one intake tool, one session-discovery tool, and six focused query/analytics views. Each tool earns its place with no redundancy or bloat.
The server covers the full intended lifecycle: record_session ingests runs, get_recent_sessions discovers session IDs, and the get_* tools provide totals, turn-level detail, tool traces, cost estimates, and context-window composition. Update and delete are deliberately excluded from this append-only metrics store, so there are no obvious dead ends.
Maintenance
Related MCP Connectors
MCP server for building and testing AI agents with multi-model experimentation and insights.
MCP observability. Query live traffic, errors, duration, and alerts from your AI agent.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Analytics for MCP servers. Find out which of your tools agents get wrong. MCPulse shows you which tools AI agents retry, which come back empty, and which they never call at all. Two lines inside your own server. It never sees your arguments or your results. getmcpulse.com
Related MCP Servers
- AlicenseAqualityBmaintenanceMCP-native agent evaluation and observability server. Log traces, evaluate output quality with 12 built-in rules (PII detection, prompt injection, cost thresholds), and track agent costs. Real-time dashboard, OTel-compatible spans. Self-hosted, MIT licensed.12199 npm10MIT
- AlicenseAqualityNot gradedmaintenanceA MCP server for tracking AI usage metrics and structured logs across applications. Monitor model calls, analyze usage patterns, track costs, and debug AI interactions.59 npmMIT
- AlicenseAqualityFmaintenanceAn MCP server that provides cost and reliability observability for LLM and agent workflows. It records model calls and allows querying and aggregating telemetry data through MCP tools.6MIT
- AlicenseNot gradedqualityCmaintenanceAn MCP server that gives AI agents observability over their own tool calls, enabling auditing, cost tracking, latency analysis, and alerting.MIT