fastmcp.server.middleware.usage
Per-user, per-component usage metrics.
FastMCP’s spans already carry the user, tool, latency and error for every
request, but traces are often sampled, which makes them a poor source for
usage counts. UsageMiddleware records the same facts as an OpenTelemetry
metric, independently of trace sampling.
Classes
UsageMiddleware
Record tool and prompt usage as an OpenTelemetry metric.
Each tools/call and prompts/get request is recorded once on the
mcp.server.operation.duration histogram (seconds), following the
OpenTelemetry MCP semantic conventions for that metric. The histogram’s
count is the number of calls, so one instrument answers “who called what,
how often, how fast, and how often it failed”.
Attributes on each data point:
mcp.method.name:tools/callorprompts/getgen_ai.tool.nameorgen_ai.prompt.name: the component name the client asked for, omitted for routing and access failuresgen_ai.operation.name:execute_tool, on tool calls onlyerror.type: present only when the call failed. A JSON-RPC error reports its code, an error tool result reportstool_error, and a cancelled or timed-out request reportscancelledrpc.status_code: the JSON-RPC error code, when the response is a JSON-RPC error. Codes that the conventions classify as client errors, such as-32602, are reported here withouterror.typemcp.protocol.version,network.transport,network.protocol.nameandnetwork.protocol.version: when the request came over a transportfastmcp.server.name: the server handling the requestenduser.pseudo.id(default) orenduser.id: the authenticated user, when the server has auth (seeuser_id)
UsageMiddleware first, before error
handling and any middleware that can answer without calling the next
handler. In that position the duration comes as close as middleware can to
the conventions’ receipt-to-response definition, and the error
classification matches the response the client receives.
FastMCP depends only on the OpenTelemetry API, so this middleware records
nothing until you configure an OpenTelemetry SDK MeterProvider with an
exporter.
Background tasks measure submission, not eventual execution or failure.
Guard continuations count as separate requests.
Args:
user_id: How to report the authenticated user."hashed"(default) reports a keyed SHA-256 digest asenduser.pseudo.id, so usage can be grouped per user without exporting the identity itself."raw"reports the token subject (or client ID) asenduser.id."omit"reports no user attribute.user_id_salt: Secret key for the"hashed"digest. Required whenuser_id="hashed", because an unkeyed digest of a known identifier such as an email address can be recomputed and matched. Ignored for"raw"and"omit".meter_provider: Meter provider to use. Defaults to the global provider.