PARAS MADAN
All writing

Latest in AI

How to count MCP tool calls with FastMCP 4.2.5

Use FastMCP's opt-in UsageMiddleware to measure tool calls and latency, avoid double counting, and start without exporting user IDs.

If your FastMCP server samples traces, counting the spans in your dashboard won't tell you how often a tool runs. FastMCP 4.2.5, released November 23, adds an opt-in UsageMiddleware for that job. It records each tool call or prompt retrieval that reaches it in an OpenTelemetry histogram, independently of trace sampling.

Start with aggregate counts and durations. You can check both in memory before deciding whether the metrics belong in your production collector.

Add one middleware at the top of the chain

Use mcp.add_middleware(UsageMiddleware(user_id="omit")) on a server with a configured OpenTelemetry metrics provider. Add it before error-handling middleware and anything that can return a result without calling the next handler. If a handler returns first, the usage middleware can't count that request.

The FastMCP telemetry guide for 4.2.5 recommends adding it to just one server in a mounted hierarchy. If both a parent and its mounted child record usage with the same meter provider, a tool on the child can show up twice. Check the registration on both before assuming a rise in the chart means more traffic.

Check two calls without an exporter

This fixture uses a local in-memory client and a metrics reader. It doesn't send data to an external service. Run it in a test environment with FastMCP 4.2.5 and the OpenTelemetry Python SDK.

import asyncio

from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.server.middleware.usage import UsageMiddleware
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader

reader = InMemoryMetricReader()
provider = MeterProvider(metric_readers=[reader])
server = FastMCP("fixture")
server.add_middleware(
    UsageMiddleware(user_id="omit", meter_provider=provider)
)

@server.tool
def fixture_status() -> str:
    return "ready"

async def main():
    async with Client(server) as client:
        await client.call_tool("fixture_status", {})
        await client.call_tool("fixture_status", {})

asyncio.run(main())
points = [
    point
    for resource in reader.get_metrics_data().resource_metrics
    for scope in resource.scope_metrics
    for metric in scope.metrics
    if metric.name == "mcp.server.operation.duration"
    for point in metric.data.data_points
]
assert len(points) == 1 and points[0].count == 2
assert points[0].attributes["gen_ai.tool.name"] == "fixture_status"
assert not any(key.startswith("enduser.") for key in points[0].attributes)

The tagged regression tests use the same in-memory reader to verify counts and check that failures like unknown tool names don't create a series for every rejected name.

Read the metric at the right boundary

The histogram's count tells you how many matching requests the middleware saw; its recorded durations are in seconds. It covers tools/call and prompts/get, not tools/list or resources/read. Use mcp.method.name to separate the operations.

For a background tool, the duration measures submission, not how long the job takes to finish. A successful submission can still be followed by a failed job. Keep a separate completion metric if you're trying to measure job reliability.

Add identity only if you need it

For a first deployment, leave user_id="omit". The middleware implementation defaults to hashed identities, so calling UsageMiddleware() without a secret salt raises an error. Even a hashed identity can be linked across requests and creates more time series. Review access, retention and how many identities your metrics backend can handle before sending any user dimension.

Check the exported attributes in staging, especially if other instrumentation is also enabled. Omitting identity in this middleware says nothing about what your separate traces or logs contain.

Need help documenting a developer release?

I'm Paras Madan. I help AI teams write technical guides and product stories that give developers a concrete way to test a release in their own setup. Book a 30-minute call.