Skip to main content
Glama
mcp-context-inspector

mcp-context-inspector

mcp-context-inspector

Un servidor MCP plug-and-play + grabador de métricas de ejecución para cualquier agente que llame a herramientas. Apunta el bucle de tu agente a record_session(prompt, model_id, loop_result) después de cada ejecución y esto te ofrece, de forma gratuita:

  • Un verdadero servidor MCP (HTTP transmisible) al que puede conectarse cualquier cliente MCP — Claude Desktop, Cursor, tu propia interfaz de chat — que expone 7 herramientas de solo lectura sobre el historial de sesiones, costes, métricas de tokens/herramientas, y...

  • El Explorador de la Ventana de Contexto — transparencia total sobre qué entró exactamente en la ventana de contexto del modelo, bloque por bloque, con recuentos de tokens honestos (estimados y etiquetados explícitamente), una barra segmentada proporcional y un panel de detalle que se expande al hacer clic por cada bloque:

    Context Window Explorer

    (captura de pantalla de la interfaz de chat de referencia construida junto con esto — sre-investigation-agent; el panel superior es lo que cualquier cliente MCP obtiene al consultar get_context_timeline.)

La mayoría de las herramientas de observabilidad de agentes te vuelven a mostrar datos que tu propia interfaz ya mostraba. Esta te muestra algo que normalmente no puedes ver en absoluto: el prompt del sistema frente a las especificaciones de las herramientas, el razonamiento, la llamada/resultado de la herramienta, la respuesta final, en el orden en que realmente entraron en el contexto, con un total de tokens acumulados frente a la ventana de contexto real del modelo — y cuáles de esos bloques son visibles para el usuario final frente a los que son sobrecarga invisible.

Instalar

uv add mcp-context-inspector   # or: pip install mcp-context-inspector
# while co-developing locally against an editable checkout:
uv add --editable ../mcp-context-inspector

Related MCP server: ai-usage-metrics-mcp

Conéctalo a tu agente

from metrics import store

session_id = store.record_session(prompt, model_id, loop_result)

loop_result es lo que sea que devuelva el bucle de tu agente — este paquete solo necesita que tenga el siguiente aspecto:

{
    "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},
        ...
    ],
}

Categorías de context_blocks: system, tools, user, reasoning, thinking, tool_call, tool_result (opcionalmente lleva una clave "status" para codificar fallos por colores), answer.

Ejecutar el servidor

uv run python -m mcp_server.server

Si no se establece MCP_AUTH_TOKEN → genera e imprime uno al iniciar, el mismo modelo de confianza que el token impreso de un servidor Jupyter. Establécelo tú mismo para obtener un valor estable entre reinicios. Apunta cualquier cliente MCP a http://127.0.0.1:8787/mcp con Authorization: Bearer <token>.

Backends de almacenamiento

STORAGE_BACKEND=sqlite (por defecto, desarrollo local — data/metrics.db) o STORAGE_BACKEND=dynamodb (establece METRICS_TABLE/AWS_REGION) — las mismas firmas de función en ambos casos, los llamadores nunca saben cuál está activo.

Las 7 herramientas MCP

get_session_metrics, get_token_breakdown, get_tool_metrics, get_agent_trace, get_cost_estimate, get_recent_sessions, get_context_timeline. También se exponen equivalentes REST simples bajo /api/* — una alternativa de depuración compatible con curl, que llama a las mismas funciones subyacentes de metrics/store.py.

Repositorios relacionados

sre-investigation-agent — la interfaz de chat de referencia + agente Bedrock del cual se extrajo este paquete y con el que se desarrolla conjuntamente.

Available Tools

8 tools
get_agent_traceA
Read-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_timelineA
Read-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_estimateA
Read-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_sessionsA
Read-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_metricsA
Read-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_breakdownA
Read-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_metricsA
Read-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 turns item: input_tokens (int), output_tokens (int), latency_ms (float); optional cache_read_input_tokens / cache_write_input_tokens (int, default 0).

  • each trace item: tool (str), args (dict), status (str); optional latency_ms (float, default 0), timestamp (float epoch seconds, default record time).

  • each context_blocks item: 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

    A4.9/5.0

    Scored across 8 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count5/5

    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.

    Completeness5/5

    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

    ActivityStale
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      MCP-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.
      12
      199 npm
      10
      MIT
    • A
      license
      A
      quality
      F
      maintenance
      An 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.
      6
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server that gives AI agents observability over their own tool calls, enabling auditing, cost tracking, latency analysis, and alerting.
      MIT