DocsSend data
MCP servers
If you run an MCP server, StatsRaven shows who calls it, what their agents do in each session, which tools are called, how fast they answer and what fails, and it keeps the directory crawlers and liveness probes apart from real use. Often all it needs is a few more fields in your web server's access log.
This page is about analytics of MCP servers you run yourself. To ask StatsRaven questions from Claude, Cursor or another MCP client, see Claude and MCP.
What you get#
The MCP page in the app, under Explore in the menu, shows for the chosen period, each with its change against the previous one:
- Tool calls as the headline, then every request, callers, sessions, the error rate (its change in points) and the p95 duration. A connection an agent holds open to listen for updates (
subscriptions/listen, or a GET on the endpoint) counts as a request but not as a duration, since it says how long the agent stayed, not how long an answer took. - Calls over time, with failures and calls refused at sign-in.
- Who calls: every caller your server names, by user id or API key id, as one row across the page. A person shows by the name and email your product sent with
identifyor with the call, and a row has their tool calls, the tools they use most, their activity over the period, sessions, error rate, and when they were first and last seen. A click opens the caller beside the page with every tool they called, what failed and their recent sessions step by step. The same user id in two projects is two people. Under the callers, each server that does not name its callers says how many calls and callers that leaves unnamed, and how to name them. A directory's test account that signs in, such as one named "MCP Directory Test", counts as a probe. - Tools, each with its calls, error rate, p95 duration and number of callers, and the same by method.
- Clients, grouped as AI apps (Claude, ChatGPT, Cursor and the like), SDKs and scripts (node, python, curl), directories and probes, and callers that never got past sign-in.
- What failed, by error message or status code, with when it last happened.
- Sessions: calls per session, how long a session lasts, how many hit a failure, and how many listed your tools and called none of them. Recent sessions show their steps in order, such as
initialize,tools/list,searchthree times,get_order, with failed steps in red. - How long calls take and the protocol revisions clients speak, and a server switch at the top when you run more than one.
A card whose detail your logs do not carry yet, such as tool names or callers, says so in its own place, with the share of calls that carry it and the few lines that add it.
Three tabs choose the traffic: Real use, the default, leaves out probes and directories; Probes shows only them; All shows everything. Click any caller, tool, client, error or method to filter the whole page by it.
The same numbers are in chat and in Claude through the mcp_report tool, and every field below can be used in queries, sheets and alerts.
What counts as an MCP call#
A record is an MCP call when it has an mcp_method field, or when it is an HTTP request to an MCP endpoint: /mcp, a short path that ends in /mcp such as /v1/mcp, /mcp/sse, /mcp/messages, /sse or /messages. A request to one of those paths without the method still counts, as a call with no tool name. A page about MCP such as /docs/mcp, a file under /.well-known or /.cursor/mcp.json, a browser opening the endpoint, and a request the site answered with 404, 405 or 410 are not calls.
| Field | What it holds | Example |
|---|---|---|
mcp_method | The JSON-RPC method | tools/call, tools/list, resources/read, prompts/get, initialize |
mcp_name | The tool name, resource URI or prompt name | search, file:///docs/readme.md |
mcp_protocol | The protocol revision the client spoke | 2026-07-28 |
mcp_client, mcp_client_version | The client's own name and version, when known | claude-ai, 1.0 |
mcp_error | A short error type or message when the call failed, tool errors returned with isError included | RateLimited |
duration_ms | How long the call took, in milliseconds | 120 |
user_id | Your own id for the signed-in user. Names the caller and joins the call to People | u_42 |
key_id | The public id of the API key the call used, the one your dashboard shows. Never the key itself | sk_live_7Qm2 |
mcp_session | The Mcp-Session-Id header, which groups the calls of one session | 1868a90c |
In SQL these are attributes, for example attr(attrs, 'mcp_name'). In chat and run_query they are fields like any other.
Pick one path per server#
There are two ways in, and they can be combined across servers but not on one server:
- From the access log of the web server or proxy in front of your MCP server (paths A to F). No change to your code. You get every request, the tool name, the status, the duration and the client from its user agent.
- From your server's code, as JSON events or OpenTelemetry (paths G and H). You also get the client's exact name and version, tool errors returned as HTTP 200 with
isError, and the signed-in user. This is the only way for stdio servers, which have no HTTP request to log.
Why the access log is enough#
Since the MCP revision 2026-07-28, every Streamable HTTP request must carry its method in an Mcp-Method header, and tools/call, resources/read and prompts/get must also carry the tool name or resource URI in Mcp-Name. Every request also carries MCP-Protocol-Version. These headers exist so that proxies and logging can see what a request does without reading its body. Log them, and the access log becomes a log of tool calls.
A name that is not safe in a header, such as one with non-ASCII characters, arrives wrapped as =?base64?...?=. StatsRaven decodes it.
Two limits come with this, and they are the spec's, not ours:
- Older clients do not send the headers. A client on a revision before 2026-07-28 still counts, by its path, but without a method or tool name. The MCP page shows what share of calls carry a tool name.
- The client's name is not in a header. It travels in the request body, under
_metaasio.modelcontextprotocol/clientInfo. From a log, StatsRaven names the client by its user agent, such as Claude-User, node or curl. For the exact name and version, send events from your code.
Who called#
Your MCP server already turns each token into an account when it checks it. StatsRaven needs only the result: the account's id as user_id, or the API key's public id as key_id. It never needs the token, and it cannot take it from the log anyway: Cloudflare redacts the Authorization header, and logging it in nginx would write a secret to disk. An OAuth access token also changes every hour or so, so its hash would name an hour, not a person.
From a log, the server puts the id in a response header and the web server logs that header and hides it from the client (path B). From code, the id goes in the event (paths A, G and H). Until calls carry one, callers are estimated from the address and the app, a count that changes every day.
Sessions#
A server that hands out sessions gets the Mcp-Session-Id header on every request after initialize, from old and new clients alike. Log it, and the calls of one agent's session are grouped by it. Without it, StatsRaven groups calls by caller and app, and starts a new session after 30 quiet minutes.
A. Cloudflare Workers#
If your MCP server is a Cloudflare Worker, set up the tail Worker from Sending data, Cloudflare Workers and point your MCP Worker at it. That is all: the tail Worker forwards each invocation with its request headers, so StatsRaven reads the MCP headers, the session header and the Worker's wall time with no change to the MCP Worker itself.
Clients on a revision before 2026-07-28 send no method header, and the tail cannot read the request body. For the tool name, the caller, the client's exact name and tool errors, add one log line per call inside your MCP Worker:
// clientInfo: from the request's _meta; userId or keyId: from your auth. All optional.
console.log(JSON.stringify({
event: "mcp_call",
mcp_method: body.method, // "tools/call"
mcp_name: body.params?.name, // "search"
mcp_client: clientInfo?.name,
mcp_client_version: clientInfo?.version,
user_id: props?.userId, // or key_id: the key's public prefix
mcp_error: result?.isError ? "isError" : null,
}));
StatsRaven merges that line into the request record it came from, so the call is still counted once, now with the client, the person and the error.
B. nginx#
Add the MCP headers, the session and the request time to the end of the usual combined format. The log_format goes in the http block:
log_format statsraven '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent" '
'rt=$request_time mcp_method="$http_mcp_method" mcp_name="$http_mcp_name" '
'mcp_protocol="$http_mcp_protocol_version" mcp_session="$http_mcp_session_id" '
'user_id="$upstream_http_x_user_id" key_id="$upstream_http_x_key_id"';
The last two fields name the caller. Have your MCP server set X-User-Id or X-Key-Id on its answer, from the account it already looked up, and keep nginx from passing them on:
proxy_hide_header X-User-Id;
proxy_hide_header X-Key-Id;
Then use it, either for the whole site or only for the MCP endpoint:
server {
server_name mcp.example.com;
access_log /var/log/nginx/access.log statsraven;
location /mcp {
proxy_pass http://127.0.0.1:3000;
}
}location /mcp {
access_log /var/log/nginx/mcp.log statsraven;
proxy_pass http://127.0.0.1:3000;
}The format is still the combined format with fields after it, so the rest of the site's report keeps working from the same file. nginx writes - for a header that was not sent, which StatsRaven reads as missing. An access_log inside a location replaces the server's own for those requests, so with the second tab MCP requests are written to mcp.log only, never to both files.
Reload nginx with sudo nginx -t && sudo systemctl reload nginx, then get the log to StatsRaven.
C. nginx, as JSON#
If you prefer JSON logs, use a JSON format. StatsRaven recognises a JSON access line by its keys, whether it follows the file or receives the line over /ingest:
log_format statsraven_json escape=json '{'
'"time_iso8601":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"request_time":$request_time,'
'"mcp_method":"$http_mcp_method",'
'"mcp_name":"$http_mcp_name",'
'"mcp_protocol":"$http_mcp_protocol_version",'
'"mcp_session":"$http_mcp_session_id",'
'"user_id":"$upstream_http_x_user_id",'
'"key_id":"$upstream_http_x_key_id"'
'}';
# in the server or location block
access_log /var/log/nginx/mcp.json statsraven_json;
The keys StatsRaven reads are time_iso8601 (or time), remote_addr, request (or request_method with request_uri), status, body_bytes_sent, http_referer, http_user_agent, request_time in seconds, the three MCP fields, mcp_session, and user_id or key_id from your server's response header as in path B.
D. Caddy#
Caddy's JSON access log already includes the request headers, so turning the log on is enough:
mcp.example.com {
log {
output file /var/log/caddy/mcp.log
format json
}
reverse_proxy 127.0.0.1:3000
}
StatsRaven reads ts, request.method, request.uri, request.remote_ip, request.headers, status, size and duration in seconds. Caddy hides the values of Authorization and Cookie headers in its log by default, which is what you want.
E. Apache#
For Apache 2.4.13 or newer, which can log the duration in milliseconds:
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\" duration_ms=%{ms}T mcp_method=\"%{Mcp-Method}i\" mcp_name=\"%{Mcp-Name}i\" mcp_protocol=\"%{MCP-Protocol-Version}i\"" statsraven
CustomLog ${APACHE_LOG_DIR}/access.log statsraven
Apache writes - for a missing header, read as missing. Reload with sudo systemctl reload apache2.
F. Traefik#
Traefik drops request headers from its access log unless told to keep them. Keep the user agent and the three MCP headers:
accessLog:
filePath: /var/log/traefik/access.log
format: json
fields:
headers:
defaultMode: drop
names:
User-Agent: keep
Mcp-Method: keep
Mcp-Name: keep
Mcp-Protocol-Version: keep
StatsRaven reads StartUTC, ClientHost, RequestMethod, RequestPath, DownstreamStatus, Duration in nanoseconds, and the kept headers as request_User-Agent, request_Mcp-Method, request_Mcp-Name and request_Mcp-Protocol-Version.
Getting the log to StatsRaven#
For paths B to F, the log reaches StatsRaven in one of two ways:
- On the same machine, StatsRaven follows the file. In Settings, Projects, open the project, add a Log file with the access format and the file's path. JSON access lines are recognised in the same format. From the command line:
statsraven watch --project mcp --source mcp --format access /var/log/nginx/access.log. - On another machine, ship the file with Vector or Fluent Bit to
/ingest. A JSON format (C, D or F) arrives with its fields as they are. A text line (B or E) works as well when it is sent as themessagefield, which is what both shippers do by default: StatsRaven reads the combined part and the fields after it.
The source name, here mcp, is what the MCP page lists under Servers. Give each MCP server its own source when you run several.
G. JSON events from your code#
Any language and any host works: Vercel, Cloud Run, Fly, a VPS, or a stdio server on a laptop. Send one event per call to /ingest with an ingest token:
curl https://stats.example.com/ingest?source=docs-mcp \
-H 'Authorization: Bearer YOUR_TOKEN' \
-H 'Content-Type: application/json' \
-d '{"ts": "2026-11-22T09:30:00Z", "event": "mcp_call", "mcp_method": "tools/call", "mcp_name": "search", "mcp_client": "claude-ai", "mcp_client_version": "1.0", "mcp_protocol": "2026-07-28", "duration_ms": 120, "user_id": "u_42", "mcp_error": null}'
A batch can be an array or one object per line, as with any JSON over HTTP. The ?source= names the server.
The snippets below wrap your tool handlers: they time each call, notice a thrown error or an isError result, and send the event without waiting for it. A failed send is dropped quietly and can never break or slow a tool. They send no tool arguments and no results. Put the token in an environment variable, STATSRAVEN_TOKEN; without it, nothing is sent.
TypeScript#
For the official TypeScript SDK. Save the helper next to your server:
// Times each tool call and sends one event to StatsRaven. Never blocks or throws into a tool.
const ENDPOINT = "https://stats.example.com/ingest?source=docs-mcp";
const TOKEN = process.env.STATSRAVEN_TOKEN;
type ClientInfo = { name?: string; version?: string };
type Options = {
userId?: (ctx: any) => string | undefined; // your signed-in user's id, if any
client?: () => ClientInfo | undefined; // fallback for older protocol sessions
};
function send(event: Record<string, unknown>) {
if (!TOKEN) return;
fetch(ENDPOINT, {
method: "POST",
headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json" },
body: JSON.stringify(event),
signal: AbortSignal.timeout(5000),
}).catch(() => {});
}
export function tracked<A extends unknown[], R>(name: string, handler: (...args: A) => R | Promise<R>, opts: Options = {}) {
return async (...args: A): Promise<R> => {
const ctx: any = args[args.length - 1];
const started = performance.now();
let error: string | null = null;
try {
const result: any = await handler(...args);
if (result?.isError) error = "isError";
return result;
} catch (e) {
error = e instanceof Error ? e.name : "Error";
throw e;
} finally {
try {
const meta = ctx?.mcpReq?._meta ?? ctx?._meta;
const info: ClientInfo | undefined = meta?.["io.modelcontextprotocol/clientInfo"] ?? opts.client?.();
send({
ts: new Date().toISOString(),
event: "mcp_call",
mcp_method: "tools/call",
mcp_name: name,
mcp_client: info?.name,
mcp_client_version: info?.version,
mcp_protocol: meta?.["io.modelcontextprotocol/protocolVersion"],
duration_ms: Math.round(performance.now() - started),
user_id: opts.userId?.(ctx),
mcp_error: error,
});
} catch {}
}
};
}
Then wrap each handler where you register it:
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";
import { tracked } from "./statsraven.js";
const server = new McpServer({ name: "docs-search", version: "1.0.0" });
server.registerTool(
"search",
{ description: "Search the docs", inputSchema: z.object({ query: z.string() }) },
tracked("search", async ({ query }: { query: string }) => ({
content: [{ type: "text", text: await searchDocs(query) }],
}), {
// However your auth exposes the user. On stdio there is no HTTP request.
userId: (ctx) => ctx.http?.authInfo?.extra?.userId,
}),
);import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { tracked } from "./statsraven.js";
const server = new McpServer({ name: "docs-search", version: "1.0.0" });
server.registerTool(
"search",
{ description: "Search the docs", inputSchema: { query: z.string() } },
tracked("search", async ({ query }: { query: string }) => ({
content: [{ type: "text", text: await searchDocs(query) }],
}), {
client: () => server.server.getClientVersion(),
userId: (extra) => extra.authInfo?.extra?.userId,
}),
);On the 2026-07-28 revision the client sends its name and version with every request, in _meta, and the helper reads it from there. On older revisions the client sent it once, at initialize, and getClientVersion() returns what it sent. The helper takes the handler's last argument as the request context, so it also works for tools without an input schema.
Python#
The helper that sends, shared by both variants:
import asyncio
import os
from datetime import datetime, timezone
import httpx
ENDPOINT = "https://stats.example.com/ingest?source=docs-mcp"
TOKEN = os.environ.get("STATSRAVEN_TOKEN", "")
_client = httpx.AsyncClient(timeout=5)
_pending: set[asyncio.Task] = set()
async def _post(event: dict) -> None:
try:
await _client.post(ENDPOINT, json=event, headers={"Authorization": f"Bearer {TOKEN}"})
except Exception:
pass # never let analytics break a tool
def send(name: str, started: float, error: str | None, user_id: str | None = None) -> None:
if not TOKEN:
return
event = {
"ts": datetime.now(timezone.utc).isoformat(),
"event": "mcp_call",
"mcp_method": "tools/call",
"mcp_name": name,
"duration_ms": round((asyncio.get_running_loop().time() - started) * 1000),
"user_id": user_id,
"mcp_error": error,
}
task = asyncio.create_task(_post(event)) # fire and forget, keep a reference until done
_pending.add(task)
task.add_done_callback(_pending.discard)
import asyncio
from fastmcp import FastMCP
from fastmcp.server.middleware import Middleware, MiddlewareContext
from statsraven_mcp import send
mcp = FastMCP("docs-search")
class StatsRaven(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
started = asyncio.get_running_loop().time()
error = None
try:
result = await call_next(context)
if getattr(result, "is_error", False):
error = "isError"
return result
except Exception as e:
error = type(e).__name__
raise
finally:
send(context.message.name, started, error)
mcp.add_middleware(StatsRaven())import asyncio
import functools
import inspect
from mcp.server.fastmcp import FastMCP # in SDK v2: from mcp.server import MCPServer
from statsraven_mcp import send
mcp = FastMCP("docs-search")
def tracked(fn):
@functools.wraps(fn) # keeps the name and signature the SDK builds the tool from
async def wrapper(*args, **kwargs):
started = asyncio.get_running_loop().time()
error = None
try:
result = fn(*args, **kwargs)
if inspect.isawaitable(result):
result = await result
return result
except Exception as e:
error = type(e).__name__
raise
finally:
send(fn.__name__, started, error)
return wrapper
@mcp.tool()
@tracked
async def search(query: str) -> str:
"""Search the docs."""
return await search_docs(query)To join calls to People, pass your signed-in user's id as user_id to send, from wherever your auth keeps it. The Python variants leave the client out; add mcp_client to the event if your framework gives you the client's name.
H. OpenTelemetry#
If your server already makes OpenTelemetry spans, send them to StatsRaven's OTLP endpoint as described in Sending data, OpenTelemetry. StatsRaven reads the OpenTelemetry conventions for MCP:
| Span attribute | Becomes |
|---|---|
mcp.method.name | mcp_method |
gen_ai.tool.name, mcp.resource.uri or gen_ai.prompt.name | mcp_name |
mcp.protocol.version | mcp_protocol |
mcp.client.name, mcp.client.version | mcp_client, mcp_client_version |
enduser.id or user.id | user_id |
mcp.session.id | mcp_session |
| The span's duration | duration_ms |
An error status, with its message or error.type | A failed call, with that as mcp_error |
The service name becomes the server's name on the MCP page.
Ask about it#
In chat, or from Claude over StatsRaven's own MCP server, ask the way you would ask a colleague:
- "Which tool fails most this week, and with what error?"
- "Which callers came back this week, and which tools do they use?"
- "How many sessions list my tools and then call none of them?"
- "Which clients call the search tool, and how slow is it for each?"
- "How much of the traffic to /mcp is real use, and how much is directory probes?"
- "Who used the export tool for the first time this month, and where did they sign up from?"
- "Tell me when errors of the search tool pass 20 in an hour." (makes an alert)
These go through the mcp_report tool, which takes a project, a period and filters on tool, client, kind of caller, method, server, status, person and caller. For anything else, run_query and the SQL API see every field.
Privacy#
- Tool arguments and results are never needed, and the snippets on this page do not send them.
mcp_erroris meant for an error type. If your error messages repeat user input, send the type only, as the snippets do.- A
key_idis the public part of a key, the one your dashboard shows. Never send the key or an access token. - Everything stays on your StatsRaven server. Nothing is sent to us or to anyone else.
- When a call carries a user id, it is personal data in the same way as a signed-in visit; see signed-in people.
When something looks wrong#
- Calls show up, but with no tool names
- Either the client speaks a revision older than 2026-07-28 and sends no
Mcp-Nameheader, or the header is not in the log. Check one line of the log: ifmcp_methodis-for a client you know is current, the log format is not the one with the MCP fields, or a proxy in front strips the headers. For older clients, send events from your code (path G). - Every call is counted twice
- The server is sent two ways, for example from its nginx log and from the snippet in its code. Keep one path per server. On Workers, the
console.logline is merged and never doubles. - Almost every call is a 401
- That is normal for a public MCP server. Directory crawlers and liveness probes call
/mcpwithout signing in and get turned away. Most of them are directory crawlers and probes, which have their own tab and which Real use leaves out. - Clients show as node or python instead of Claude
- From a log, the client is named by its user agent, and many clients send their HTTP library's. Send events from your code to get the name the client gives itself.
- Callers say "estimated"
- No call carries a
user_idorkey_idyet, so callers are counted by address and app, which changes every day. Name them as in Who called. - Sessions are cut by time
- The log has no
mcp_session. Add$http_mcp_session_idto the nginx format; Workers send it by themselves, and only servers that hand out sessions have one. - Durations are missing
- The log format has no time field. Add
rt=$request_timein nginx,%{ms}Tin Apache; Caddy and Traefik log it by default. - All servers show as one
- They share a source. Give each server its own
?source=or log file source.