Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Fix #5563: OTel: prefer `AccessToken.subject` over `client_id` for `enduser.id` (#5565)

Nandana Dileepbbe30de287ea
diff --git a/docs/servers/telemetry.mdx b/docs/servers/telemetry.mdx
index 6b0c238dc..0b6641a26 100644
--- a/docs/servers/telemetry.mdx
+++ b/docs/servers/telemetry.mdx
@@ -461,7 +461,7 @@ Standard [identity attributes](https://opentelemetry.io/docs/specs/semconv/attri
| Attribute | Description |
|-----------|-------------|
-| `enduser.id` | Client ID from access token (when authenticated) |
+| `enduser.id` | Token subject (`sub`) when present, else client ID (when authenticated) |
| `enduser.scope` | Space-separated OAuth scopes (when authenticated) |
### FastMCP Custom Attributes
diff --git a/fastmcp_slim/fastmcp/server/telemetry.py b/fastmcp_slim/fastmcp/server/telemetry.py
index 5df804807..9cc65de3d 100644
--- a/fastmcp_slim/fastmcp/server/telemetry.py
+++ b/fastmcp_slim/fastmcp/server/telemetry.py
@@ -64,8 +64,9 @@ def get_auth_span_attributes() -> dict[str, str]:
try:
token = get_access_token()
if token:
- if token.client_id:
- attrs["enduser.id"] = token.client_id
+ user_id = token.subject or token.client_id
+ if user_id:
+ attrs["enduser.id"] = user_id
if token.scopes:
attrs["enduser.scope"] = " ".join(token.scopes)
except RuntimeError:
diff --git a/tests/telemetry/test_module.py b/tests/telemetry/test_module.py
index c760af5cf..f0c62bc08 100644
--- a/tests/telemetry/test_module.py
+++ b/tests/telemetry/test_module.py
@@ -35,6 +35,35 @@ class TestGetAuthSpanAttributes:
attrs = get_auth_span_attributes()
assert attrs == {}
+ def test_prefers_subject_over_client_id(self):
+ from unittest.mock import patch
+
+ from fastmcp.server.auth.auth import AccessToken
+
+ token = AccessToken(
+ token="test-token",
+ client_id="oauth-client-id",
+ scopes=["read"],
+ subject="user-sub-123",
+ )
+ with patch("fastmcp.server.dependencies.get_access_token", return_value=token):
+ attrs = get_auth_span_attributes()
+ assert attrs["enduser.id"] == "user-sub-123"
+
+ def test_falls_back_to_client_id_without_subject(self):
+ from unittest.mock import patch
+
+ from fastmcp.server.auth.auth import AccessToken
+
+ token = AccessToken(
+ token="test-token",
+ client_id="oauth-client-id",
+ scopes=["read"],
+ )
+ with patch("fastmcp.server.dependencies.get_access_token", return_value=token):
+ attrs = get_auth_span_attributes()
+ assert attrs["enduser.id"] == "oauth-client-id"
+
VALID_TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
VALID_TRACESTATE = "congo=t61rcWkgMzE"