mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-11-24 12:01:25 +01:00
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QCgr8jTRjsyhy7iM3jirLD
602 lines
28 KiB
Text
602 lines
28 KiB
Text
---
|
|
title: OpenTelemetry
|
|
sidebarTitle: Telemetry
|
|
description: Native OpenTelemetry instrumentation for distributed tracing.
|
|
icon: chart-line
|
|
tag: NEW
|
|
---
|
|
|
|
import { VersionBadge } from "/snippets/version-badge.mdx"
|
|
|
|
FastMCP includes native OpenTelemetry instrumentation for observability. Traces are automatically generated for tool, prompt, resource, resource template, and task management operations, providing visibility into server behavior, request handling, and provider delegation chains.
|
|
|
|
## How It Works
|
|
|
|
FastMCP uses the OpenTelemetry API for instrumentation. This means:
|
|
|
|
- **On by default** - Instrumentation is active out of the box, no opt-in required
|
|
- **No overhead when unused** - Without an SDK, all operations are no-ops
|
|
- **Bring your own SDK** - You control collection, export, and sampling
|
|
- **Works with any OTEL backend** - Jaeger, Zipkin, Datadog, New Relic, etc.
|
|
|
|
Because FastMCP only depends on the OpenTelemetry API, span creation is a no-op until you configure an SDK and exporter — so being on by default costs nothing until you opt into collection.
|
|
|
|
### Telemetry Modes
|
|
|
|
<VersionBadge version="4.0.0" />
|
|
|
|
`FASTMCP_TELEMETRY_MODE` (or `fastmcp.settings.telemetry_mode`) controls how much of the instrumentation is active:
|
|
|
|
| Mode | FastMCP spans | Trace context |
|
|
|---|---|---|
|
|
| `native` (default) | Emitted | Propagated |
|
|
| `propagation_only` | Suppressed | Propagated |
|
|
| `off` | Suppressed | Untouched |
|
|
|
|
Use `off` to disable FastMCP's instrumentation entirely. No spans are created even if an SDK is configured, and FastMCP leaves the surrounding OpenTelemetry context exactly as it found it.
|
|
|
|
Use `propagation_only` when another instrumentation layer already owns the MCP span hierarchy — see [Interoperability](#interoperability) below.
|
|
|
|
## Enabling Telemetry
|
|
|
|
The easiest way to export traces is using `opentelemetry-instrument`, which configures the SDK automatically:
|
|
|
|
```bash
|
|
pip install opentelemetry-distro opentelemetry-exporter-otlp
|
|
opentelemetry-bootstrap -a install
|
|
```
|
|
|
|
Then run your server with tracing enabled:
|
|
|
|
```bash
|
|
opentelemetry-instrument \
|
|
--service_name my-fastmcp-server \
|
|
--exporter_otlp_endpoint http://localhost:4317 \
|
|
fastmcp run server.py
|
|
```
|
|
|
|
Or configure via environment variables:
|
|
|
|
```bash
|
|
export OTEL_SERVICE_NAME=my-fastmcp-server
|
|
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
|
|
|
opentelemetry-instrument fastmcp run server.py
|
|
```
|
|
|
|
This works with any OTLP-compatible backend (Jaeger, Zipkin, Grafana Tempo, Datadog, etc.) and requires no changes to your FastMCP code.
|
|
|
|
<Card title="OpenTelemetry Python Documentation" icon="book" href="https://opentelemetry.io/docs/languages/python/">
|
|
Learn more about the OpenTelemetry Python SDK, auto-instrumentation, and available exporters.
|
|
</Card>
|
|
|
|
## Logs
|
|
|
|
Export Python log records alongside traces with OpenTelemetry's [logging instrumentation](https://opentelemetry.io/docs/zero-code/python/logs-example/). Install it in the same environment as your server:
|
|
|
|
```bash
|
|
pip install opentelemetry-distro opentelemetry-exporter-otlp opentelemetry-instrumentation-logging
|
|
```
|
|
|
|
Use Python's standard `logging` module in your tools. Save this example as `server.py`:
|
|
|
|
```python
|
|
import logging
|
|
|
|
from fastmcp import FastMCP
|
|
|
|
logging.getLogger().setLevel(logging.INFO)
|
|
logger = logging.getLogger("inventory")
|
|
mcp = FastMCP("Inventory")
|
|
|
|
|
|
@mcp.tool
|
|
def stock_count(sku: str) -> int:
|
|
"""Return the available stock for a product."""
|
|
logger.info("Checking inventory", extra={"product_sku": sku})
|
|
return {"WIDGET": 12}.get(sku, 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
mcp.run(transport="http")
|
|
```
|
|
|
|
Records from your own loggers, such as `inventory` above, reach OpenTelemetry without further FastMCP configuration. To export FastMCP's own `fastmcp.*` records as well, set `FASTMCP_LOG_ENABLED=false` before starting the process. FastMCP's default console configuration stops its records from propagating to the root logger, where OpenTelemetry installs its handler; disabling that configuration lets them through, and also silences FastMCP's console output. Python logging levels still control which records are emitted.
|
|
|
|
```bash
|
|
export FASTMCP_LOG_ENABLED=false # optional, exports fastmcp.* records
|
|
export OTEL_SERVICE_NAME=inventory
|
|
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
|
export OTEL_LOGS_EXPORTER=otlp
|
|
|
|
opentelemetry-instrument python server.py
|
|
```
|
|
|
|
The endpoint must accept OTLP logs as well as traces. On current OpenTelemetry Python releases, installing `opentelemetry-instrumentation-logging` enables log export automatically. See the [OpenTelemetry agent configuration](https://opentelemetry.io/docs/zero-code/python/configuration/#logging) for version-specific settings.
|
|
|
|
When `stock_count` runs, its log record carries the active FastMCP tool span's trace and span IDs, letting you connect the message to the request. For local inspection without a collector, set `OTEL_LOGS_EXPORTER=console`, `OTEL_TRACES_EXPORTER=console`, and `OTEL_METRICS_EXPORTER=none`. The console exporter writes to stdout, so use it with HTTP servers as above; stdout belongs to the protocol when serving over STDIO.
|
|
|
|
`ctx.info()` and related methods send [MCP log notifications](/servers/logging) to the client. Their server-side copies are logged at `DEBUG` on `fastmcp.server.context.to_client`; they do not become OpenTelemetry `INFO` records automatically. Use a Python logger when you want to emit a server-side record at its original severity.
|
|
|
|
## Tracing
|
|
|
|
FastMCP creates spans for all MCP operations, providing end-to-end visibility into request handling.
|
|
|
|
### Server Spans
|
|
|
|
The server creates spans for each operation using [MCP semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/mcp/):
|
|
|
|
| Span Name | Description |
|
|
|-----------|-------------|
|
|
| `tools/call {name}` | Tool execution (e.g., `tools/call get_weather`) |
|
|
| `resources/read` | Resource read (URI in `mcp.resource.uri` attribute, not span name) |
|
|
| `prompts/get {name}` | Prompt render (e.g., `prompts/get greeting`) |
|
|
| `tasks/{operation}` | Task management (`tasks/get`, `tasks/update`, or `tasks/cancel`) |
|
|
| `tools/list`, `resources/list`, `resources/templates/list`, `prompts/list` | Component listing |
|
|
|
|
Any other request, such as `initialize` or `ping`, gets a server span named after its method.
|
|
|
|
For mounted servers, an additional `delegate {name}` span shows the delegation to the child server.
|
|
|
|
### Client Spans
|
|
|
|
The FastMCP client creates spans for outgoing requests with the same naming pattern (`tools/call {name}`, `resources/read`, `prompts/get {name}`, and `tasks/{operation}`).
|
|
|
|
### Span Hierarchy
|
|
|
|
Spans form a hierarchy showing the request flow. For mounted servers:
|
|
|
|
```text
|
|
tools/call weather_forecast (CLIENT)
|
|
└── tools/call weather_forecast (SERVER, provider=FastMCPProvider)
|
|
└── delegate get_weather (INTERNAL)
|
|
└── tools/call get_weather (INTERNAL, provider=LocalProvider)
|
|
```
|
|
|
|
Each request has exactly one `SERVER` span. The mounted server's span is `INTERNAL`, as is the span for a tool that calls another tool through `ctx.fastmcp.call_tool()`, so trace backends that count `SERVER` spans as requests count each call once.
|
|
|
|
For proxy providers connecting to remote servers:
|
|
|
|
```text
|
|
tools/call remote_search (CLIENT)
|
|
└── tools/call remote_search (SERVER, provider=ProxyProvider)
|
|
└── [remote server spans via trace context propagation]
|
|
```
|
|
|
|
### Background tasks
|
|
|
|
Background task traces have two parts:
|
|
|
|
- Task submission and management requests use normal client-to-server context propagation. `tasks/get`, `tasks/update`, and `tasks/cancel` server spans are descendants of the corresponding FastMCP client spans.
|
|
- Deferred execution runs in a Docket worker. Docket records its `CONSUMER` span as a new trace root with a span link to the submission context, rather than making it a child of the submission span. Custom spans created inside the task are children of that worker span.
|
|
|
|
Span links preserve the causal relationship without forcing worker sampling to inherit the submit trace's sampling decision. Some tracing backends do not display links prominently, so the worker trace may look disconnected even though the link is present.
|
|
|
|
To keep the whole request in one trace, make the worker span a child of the submission instead:
|
|
|
|
```python
|
|
from fastmcp import FastMCP
|
|
from fastmcp_tasks import TasksExtension
|
|
|
|
mcp = FastMCP("My Server")
|
|
mcp.add_extension(TasksExtension(parent_task_spans=True))
|
|
```
|
|
|
|
Or set `FASTMCP_DOCKET_PARENT_TASK_SPANS=true`. The span link is still recorded. With a `ParentBased` sampler, the execution now follows the submit trace's sampling decision, so a task submitted from an unsampled trace is not recorded.
|
|
|
|
Frequent status polling can produce more detail than you need. You can drop those client and server spans with a sampler that checks the span name before delegating to `ParentBased`:
|
|
|
|
```python
|
|
from opentelemetry import trace
|
|
from opentelemetry.sdk.trace import TracerProvider
|
|
from opentelemetry.sdk.trace.sampling import (
|
|
ALWAYS_ON,
|
|
Decision,
|
|
ParentBased,
|
|
Sampler,
|
|
SamplingResult,
|
|
)
|
|
|
|
|
|
class DropTaskPolls(Sampler):
|
|
def __init__(self):
|
|
self._delegate = ParentBased(ALWAYS_ON)
|
|
|
|
def should_sample(self, parent_context, trace_id, name, *args, **kwargs):
|
|
if name in {"tasks/get"}:
|
|
return SamplingResult(Decision.DROP)
|
|
return self._delegate.should_sample(
|
|
parent_context,
|
|
trace_id,
|
|
name,
|
|
*args,
|
|
**kwargs,
|
|
)
|
|
|
|
def get_description(self):
|
|
return "DropTaskPolls"
|
|
|
|
|
|
provider = TracerProvider(sampler=DropTaskPolls())
|
|
trace.set_tracer_provider(provider)
|
|
```
|
|
|
|
The name check must happen before `ParentBased` delegates. If the name-based sampler is nested inside `ParentBased`, it is not consulted for child spans whose parent was already sampled.
|
|
|
|
## Interoperability
|
|
|
|
<VersionBadge version="4.0.0" />
|
|
|
|
FastMCP assumes it owns the MCP span hierarchy. When something else already owns it — an MCP-aware OpenTelemetry instrumentation library, or a service mesh that understands the protocol — FastMCP's spans duplicate what that layer already emits, and the same request shows up twice in your traces.
|
|
|
|
Setting `propagation_only` resolves the duplication in favor of the other layer:
|
|
|
|
```bash
|
|
export FASTMCP_TELEMETRY_MODE=propagation_only
|
|
```
|
|
|
|
The distinction from `off` matters here. Both emit no FastMCP spans, but `off` is fully transparent, while `propagation_only` still extracts the trace context arriving in `_meta` and attaches it for the duration of the request. Spans created downstream — by your tool handlers, or by the instrumentation layer that owns the hierarchy — are parented to the calling trace rather than starting a new one. Outbound requests still carry `traceparent` and `tracestate` in `_meta`.
|
|
|
|
### Suppressing spans for a single block
|
|
|
|
Library authors embedding FastMCP inside their own instrumented stack often want to own the hierarchy for one specific operation rather than process-wide. `suppress_fastmcp_telemetry()` applies `propagation_only` semantics to a block:
|
|
|
|
```python
|
|
from fastmcp import Client
|
|
from fastmcp.telemetry import suppress_fastmcp_telemetry
|
|
|
|
async def search(client: Client, query: str):
|
|
with suppress_fastmcp_telemetry():
|
|
return await client.call_tool("search", {"query": query})
|
|
```
|
|
|
|
This is narrower than OpenTelemetry's global instrumentation suppression: only FastMCP's spans are skipped, so nested instrumentation for HTTP clients, databases, and everything else keeps emitting normally.
|
|
|
|
The context manager has no effect when `telemetry_mode` is already `off`. A request to skip FastMCP's spans cannot re-enable the context propagation that `off` deliberately omits.
|
|
|
|
## Programmatic Configuration
|
|
|
|
For more control, configure the SDK in your Python code:
|
|
|
|
```python
|
|
from opentelemetry import trace
|
|
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
|
from opentelemetry.sdk.trace import TracerProvider
|
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
|
|
from fastmcp import FastMCP
|
|
|
|
provider = TracerProvider()
|
|
processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4317"))
|
|
provider.add_span_processor(processor)
|
|
trace.set_tracer_provider(provider)
|
|
|
|
mcp = FastMCP("my-server")
|
|
|
|
@mcp.tool
|
|
def greet(name: str) -> str:
|
|
return f"Hello, {name}!"
|
|
```
|
|
|
|
FastMCP looks up the global tracer provider each time it creates a span, so import order does not matter. Set the provider at startup, before the server handles requests; spans created earlier are not exported.
|
|
|
|
### Local Development
|
|
|
|
For quick local trace visualization, [otel-desktop-viewer](https://github.com/CtrlSpice/otel-desktop-viewer) is a lightweight single-binary tool:
|
|
|
|
```bash
|
|
# macOS
|
|
brew tap ctrlspice/otel-desktop-viewer
|
|
brew install --cask otel-desktop-viewer
|
|
|
|
# Or download from GitHub releases
|
|
```
|
|
|
|
Run it alongside your server:
|
|
|
|
```bash
|
|
# Terminal 1: Start the viewer (UI at http://localhost:8000, OTLP on :4317)
|
|
otel-desktop-viewer
|
|
|
|
# Terminal 2: Run your server with tracing
|
|
opentelemetry-instrument fastmcp run server.py
|
|
```
|
|
|
|
For more features, use [Jaeger](https://www.jaegertracing.io/):
|
|
|
|
```bash
|
|
docker run -d --name jaeger \
|
|
-p 16686:16686 \
|
|
-p 4317:4317 \
|
|
jaegertracing/all-in-one:latest
|
|
```
|
|
|
|
Then view traces at http://localhost:16686
|
|
|
|
## Usage Metrics
|
|
|
|
Server spans already record who called which tool, how long it took, and whether it failed. Sampled traces cannot reliably answer how often each user calls a tool. `UsageMiddleware` records request counts, durations, and failures as OpenTelemetry metrics, independently of trace sampling.
|
|
|
|
Add the middleware and configure a meter provider with an exporter. Like the rest of FastMCP's instrumentation, the middleware records nothing until an SDK is configured.
|
|
|
|
```python
|
|
from opentelemetry import metrics
|
|
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
|
from opentelemetry.sdk.metrics import MeterProvider
|
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
|
|
|
from fastmcp import FastMCP
|
|
from fastmcp.server.middleware.usage import UsageMiddleware
|
|
|
|
reader = PeriodicExportingMetricReader(OTLPMetricExporter())
|
|
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
|
|
|
|
mcp = FastMCP("my-server")
|
|
mcp.add_middleware(UsageMiddleware(user_id_salt="a-secret-value"))
|
|
```
|
|
|
|
<Note>
|
|
The metric and attribute names follow the OpenTelemetry MCP semantic conventions, which are still in development upstream. These names may change in a future release to track the conventions, and the changelog will say when they do. If your dashboards or alerts depend on the exact names, pin your FastMCP version.
|
|
</Note>
|
|
|
|
Every `tools/call` and `prompts/get` request is recorded on the `mcp.server.operation.duration` histogram, in seconds. The metric follows the [MCP semantic conventions for `mcp.server.operation.duration`](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/mcp.md#metric-mcpserveroperationduration) for those two methods; other MCP methods, such as `tools/list` or `resources/read`, are not recorded. The histogram's count is the number of calls, and it uses the bucket boundaries the conventions recommend, from 10 ms to 300 s. Each data point carries:
|
|
|
|
| Attribute | Description |
|
|
|-----------|-------------|
|
|
| `mcp.method.name` | `tools/call` or `prompts/get` |
|
|
| `gen_ai.tool.name` / `gen_ai.prompt.name` | The requested component, omitted for routing and access failures |
|
|
| `gen_ai.operation.name` | `execute_tool`, on tool calls only |
|
|
| `error.type` | Present only on failed calls (see below) |
|
|
| `rpc.status_code` | The JSON-RPC error code, when the response is a JSON-RPC error |
|
|
| `mcp.protocol.version` | The negotiated MCP protocol version |
|
|
| `network.transport` | `tcp` over HTTP, `pipe` over stdio, absent for in-memory clients |
|
|
| `network.protocol.name` / `network.protocol.version` | `http` and the HTTP version, over HTTP |
|
|
| `fastmcp.server.name` | Server name |
|
|
| `enduser.pseudo.id` or `enduser.id` | The authenticated user, when the server has auth |
|
|
|
|
`error.type` describes the response the client receives, as the conventions define it. A tool call that fails comes back as a result with `isError` set, so it reports `tool_error`; that includes calls to unknown, disabled, or unauthorized tools. A prompt that fails comes back as a JSON-RPC error, so it reports the error code, such as `-32603`, in both `error.type` and `rpc.status_code`. The conventions treat `-32700`, `-32600`, `-32601`, `-32602`, and `-32002` as requests the server could not serve rather than server failures, so those codes, which include an unknown prompt or missing prompt arguments, set `rpc.status_code` without `error.type`. A request that is cancelled or times out reports `cancelled`. An unexpected exception that FastMCP has not mapped to an error code reports its class name.
|
|
|
|
Unknown, disabled, and unauthorized component requests still count, but omit the component name so arbitrary rejected names do not create a new metric series each time. Known components retain their name on execution failures.
|
|
|
|
The conventions measure from when the server receives a request until it sends the result. The middleware measures from when the request reaches it until the result comes back to it, so add `UsageMiddleware` first, before error handling and before any middleware that can answer without calling the next middleware. In that position the duration leaves out only the transport and protocol handling around the middleware chain, such as HTTP authentication and response serialization, and `error.type` matches what the client receives. Middleware that answers a request without calling the next middleware must come after `UsageMiddleware` for that request to be counted at all. For background tasks, the duration measures submission and excludes eventual execution failures. Each guard continuation is another request, not another completed tool execution.
|
|
|
|
Add `UsageMiddleware` to one server in a mounted hierarchy. If a parent and a mounted child both carry it and share a meter provider, a call to a child tool is recorded twice, once under each server's name and tool name.
|
|
|
|
The user attribute depends on `user_id`. The default, `"hashed"`, reports a keyed SHA-256 digest of the token subject (or client ID) as `enduser.pseudo.id`, which lets you group usage per user without exporting identities such as email addresses. Hashing requires a secret `user_id_salt`, because an unkeyed digest of a known email address can be recomputed and matched, so `UsageMiddleware()` without one raises a `ValueError`. Keep the salt stable across restarts and replicas, or the same user will show up under a new ID. Use `user_id="raw"` to report the identity itself as `enduser.id`, or `user_id="omit"` to report no user at all; neither needs a salt. Servers without authentication have no user to report, so their data points carry no user attribute.
|
|
|
|
For unauthenticated servers, use `UsageMiddleware(user_id="omit")` to avoid configuring an unused salt. Each distinct user adds metric cardinality; configure your metrics SDK's views and cardinality limits for your deployment.
|
|
|
|
## Custom Spans
|
|
|
|
You can add your own spans using the FastMCP tracer:
|
|
|
|
```python
|
|
from fastmcp import FastMCP
|
|
from fastmcp.telemetry import get_tracer
|
|
|
|
mcp = FastMCP("custom-spans")
|
|
|
|
|
|
def parse(text: str) -> list[str]:
|
|
return text.split()
|
|
|
|
|
|
def process(words: list[str]) -> str:
|
|
return " ".join(sorted(words))
|
|
|
|
|
|
@mcp.tool
|
|
async def complex_operation(input: str) -> str:
|
|
tracer = get_tracer()
|
|
|
|
with tracer.start_as_current_span("parse_input") as span:
|
|
span.set_attribute("input.length", len(input))
|
|
parsed = parse(input)
|
|
|
|
with tracer.start_as_current_span("process_data") as span:
|
|
span.set_attribute("data.count", len(parsed))
|
|
result = process(parsed)
|
|
|
|
return result
|
|
```
|
|
|
|
### Where custom spans help most
|
|
|
|
Custom spans are most useful around work that is expensive or hard to debug:
|
|
|
|
- External calls such as databases, vector stores, HTTP APIs, or queue operations
|
|
- Multi-step tool logic where one stage dominates latency
|
|
- Prompt or resource generation that fans out to other systems
|
|
- LLM calls a tool makes to a model provider
|
|
|
|
Avoid wrapping every small helper function or simple in-memory transformation. That usually adds noise without making traces easier to interpret.
|
|
|
|
### Recommended naming and attributes
|
|
|
|
- Use `{tool_name}.{operation}` or `{resource_name}.{operation}` for child spans such as `search.fetch`, `search.rank`, or `docs.render`
|
|
- Add attributes that explain workload shape, such as counts, sizes, cache hits, or IDs
|
|
- Do not record secrets, prompts with sensitive user data, or raw tokens as span attributes
|
|
- Let exceptions propagate unless you have a specific recovery path; FastMCP's server spans already mark failures and record exceptions
|
|
|
|
### Instrumenting tools, prompts, and resources
|
|
|
|
```python
|
|
from fastmcp import FastMCP
|
|
from fastmcp.telemetry import get_tracer
|
|
|
|
mcp = FastMCP("my-server")
|
|
|
|
|
|
async def fetch_results(query: str) -> list[str]:
|
|
return [f"{query} result {i}" for i in range(3)]
|
|
|
|
|
|
def rank_results(results: list[str]) -> list[str]:
|
|
return sorted(results)
|
|
|
|
|
|
def format_results(results: list[str]) -> str:
|
|
return "\n".join(results)
|
|
|
|
|
|
async def load_doc(slug: str) -> str:
|
|
return f"# {slug}"
|
|
|
|
|
|
@mcp.tool
|
|
async def search(query: str) -> str:
|
|
tracer = get_tracer()
|
|
|
|
with tracer.start_as_current_span("search.fetch") as span:
|
|
span.set_attribute("search.query_length", len(query))
|
|
results = await fetch_results(query)
|
|
span.set_attribute("search.result_count", len(results))
|
|
|
|
with tracer.start_as_current_span("search.rank"):
|
|
ranked = rank_results(results)
|
|
|
|
return format_results(ranked)
|
|
|
|
@mcp.prompt
|
|
async def summarize_prompt(topic: str) -> str:
|
|
tracer = get_tracer()
|
|
with tracer.start_as_current_span("summarize_prompt.render") as span:
|
|
span.set_attribute("prompt.topic_length", len(topic))
|
|
return f"Summarize the latest updates about {topic}."
|
|
|
|
@mcp.resource("docs://{slug}")
|
|
async def docs_resource(slug: str) -> str:
|
|
tracer = get_tracer()
|
|
with tracer.start_as_current_span("docs_resource.load") as span:
|
|
span.set_attribute("docs.slug", slug)
|
|
return await load_doc(slug)
|
|
```
|
|
|
|
### LLM calls inside tools
|
|
|
|
A tool that [calls an LLM directly](/servers/sampling) should keep the model work nested under the tool span, so traces show application logic and model latency together.
|
|
|
|
For providers with their own OTEL integrations, prefer enabling that instrumentation rather than manually creating a span around every model call. For example, if you use Google GenAI, `logfire.instrument_google_genai()` will emit child spans with token and request metadata under the active FastMCP tool span.
|
|
|
|
### Exporter choices
|
|
|
|
- For local debugging, `ConsoleSpanExporter` or `otel-desktop-viewer` gives quick feedback with minimal setup
|
|
- For shared environments, use OTLP exporters to backends like Logfire, Jaeger, Tempo, Datadog, or New Relic
|
|
- If traces are too noisy, tune sampling in your OpenTelemetry SDK instead of removing FastMCP instrumentation
|
|
|
|
## Error Handling
|
|
|
|
When a component raises, FastMCP marks its span with error status and records the exception:
|
|
|
|
```python
|
|
from fastmcp import FastMCP
|
|
|
|
mcp = FastMCP("my-server")
|
|
|
|
@mcp.tool
|
|
def risky_operation() -> str:
|
|
raise ValueError("Something went wrong")
|
|
```
|
|
|
|
The `tools/call risky_operation` server span gets status `ERROR` with the error message as its description, an exception event carrying the stack trace, and an `error.type` attribute. FastMCP wraps exceptions raised by a tool in a `ToolError`, so tool failures report `error.type` as `tool_error`. A request rejected with a JSON-RPC error, such as a read of an unknown resource, reports the error code (for example `-32602`) as both `error.type` and `rpc.response.status_code`. Other failures report the exception class name.
|
|
|
|
## Attributes Reference
|
|
|
|
<Warning>
|
|
**Migrating from v3.1 or earlier:** The `rpc.system`, `rpc.service`, and `rpc.method` span attributes were removed in favor of the [MCP semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/mcp/) listed below. If you have dashboards or alerts keyed on those `rpc.*` attributes, update them to use `mcp.method.name` and the `fastmcp.*` attributes instead.
|
|
</Warning>
|
|
|
|
### MCP Semantic Conventions
|
|
|
|
FastMCP implements the [OpenTelemetry MCP semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/mcp/):
|
|
|
|
| Attribute | Description |
|
|
|-----------|-------------|
|
|
| `mcp.method.name` | The MCP method being called (`tools/call`, `resources/read`, `prompts/get`, `tasks/get`, etc.) |
|
|
| `mcp.protocol.version` | The negotiated MCP protocol version for the request |
|
|
| `mcp.session.id` | Session identifier for the MCP connection |
|
|
| `jsonrpc.request.id` | JSON-RPC request ID (on server spans for inbound requests) |
|
|
| `mcp.resource.uri` | The resource URI (for resource operations) |
|
|
| `gen_ai.tool.name` | Tool name (on `tools/call` spans) |
|
|
| `gen_ai.operation.name` | `execute_tool` (on `tools/call` spans) |
|
|
| `gen_ai.prompt.name` | Prompt name (on `prompts/get` spans) |
|
|
| `error.type` | Error classification (the JSON-RPC error code for protocol errors, `tool_error` for ToolError, otherwise exception class name) |
|
|
| `rpc.response.status_code` | JSON-RPC error code (on spans that failed with a protocol error) |
|
|
|
|
### Auth Attributes
|
|
|
|
Standard [identity attributes](https://opentelemetry.io/docs/specs/semconv/attributes-registry/enduser/):
|
|
|
|
| Attribute | Description |
|
|
|-----------|-------------|
|
|
| `enduser.id` | Token subject (`sub`) when present, else client ID (when authenticated) |
|
|
| `enduser.scope` | Space-separated OAuth scopes (when authenticated) |
|
|
|
|
### FastMCP Custom Attributes
|
|
|
|
All custom attributes use the `fastmcp.` prefix for features unique to FastMCP:
|
|
|
|
| Attribute | Description |
|
|
|-----------|-------------|
|
|
| `fastmcp.server.name` | Server name |
|
|
| `fastmcp.component.type` | `tool`, `resource`, `prompt`, or `resource_template` |
|
|
| `fastmcp.component.key` | Full component key, including type and version delimiter (e.g., `tool:greet@` or `tool:greet@v2`) |
|
|
| `fastmcp.provider.type` | Provider class (`LocalProvider`, `FastMCPProvider`, `ProxyProvider`) |
|
|
|
|
Provider-specific attributes for delegation context:
|
|
|
|
| Attribute | Description |
|
|
|-----------|-------------|
|
|
| `fastmcp.delegate.original_name` | Original tool/prompt name before namespacing |
|
|
| `fastmcp.delegate.original_uri` | Original resource URI before namespacing |
|
|
| `fastmcp.delegate.original_uri_template` | Original resource template URI before namespacing |
|
|
| `fastmcp.proxy.backend_name` | Remote server tool/prompt name |
|
|
| `fastmcp.proxy.backend_uri` | Remote server resource URI |
|
|
| `fastmcp.proxy.backend_uri_template` | Remote server resource template URI |
|
|
|
|
## Testing with Telemetry
|
|
|
|
For testing, use the in-memory exporter. OpenTelemetry allows the global tracer provider to be set only once per process, so install it in a session-scoped fixture and clear the exporter between tests:
|
|
|
|
```python
|
|
from collections.abc import Generator
|
|
|
|
import pytest
|
|
from opentelemetry import trace
|
|
from opentelemetry.sdk.trace import TracerProvider
|
|
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
|
|
from fastmcp import FastMCP
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def span_exporter() -> InMemorySpanExporter:
|
|
exporter = InMemorySpanExporter()
|
|
provider = TracerProvider()
|
|
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
|
trace.set_tracer_provider(provider)
|
|
return exporter
|
|
|
|
|
|
@pytest.fixture
|
|
def trace_exporter(
|
|
span_exporter: InMemorySpanExporter,
|
|
) -> Generator[InMemorySpanExporter, None, None]:
|
|
span_exporter.clear()
|
|
yield span_exporter
|
|
span_exporter.clear()
|
|
|
|
|
|
async def test_tool_creates_span(trace_exporter: InMemorySpanExporter) -> None:
|
|
mcp = FastMCP("test")
|
|
|
|
@mcp.tool
|
|
def hello() -> str:
|
|
return "world"
|
|
|
|
await mcp.call_tool("hello", {})
|
|
|
|
spans = trace_exporter.get_finished_spans()
|
|
assert any(s.name == "tools/call hello" for s in spans)
|
|
```
|