MCP server: AccessToken class should have field for subject claim ("sub")
Description
I'm proposing to add subject to AccessToken in mcp/server/auth/provider.py, which can be used to store the sub JWT claim that usually corresponds to the user ID:
class AccessToken(BaseModel):
token: str
client_id: str
scopes: list[str]
expires_at: int | None = None
resource: str | None = None # RFC 8707 resource indicator
# Proposed:
subject: str | None = None # Subject (user ID)
Then we can implement a token verifier as follows:
class MyTokenVerifier:
async def verify_token(self, token: str) -> AccessToken | None:
try:
token_claims = decode_and_validate_jwt(token)
except ...:
return None
return AccessToken(
token=token,
...
subject=token_claims["sub"],
)
and directly retrieve the user ID from the auth token in the context:
from mcp.server.auth.middleware.auth_context import get_access_token
user_id = get_access_token().subject
References
No response
Exactly! I want the same.
I would only add that the subject should also be injected in the Context class, then the higher level APIs can easily access the user id.
But why not adding all claims? The JWT specification (RFC 7519) defines only a small set of reserved claim so in the end is very normal that companies add custom claims.
This has an initial attempted implementation by @robertofalk https://github.com/modelcontextprotocol/python-sdk/pull/1165 but has been closed for inactivity - new PRs welcome if this is still an issue to the folks here.
Hi @felixweinberger — I'd like to pick this up since #1165 was closed for inactivity.
Proposed approach:
- Add a \ field to \ in 2. Also add a \ field to cover custom claims (as @robertofalk suggested — the JWT spec has few reserved claims and companies commonly add custom ones)
- Add tests covering the new fields and backward compatibility
This keeps backward compatibility (both fields are optional) while addressing the original request and the broader use case from the comments.
Happy to adjust the approach based on feedback before I start coding.
Hi @felixweinberger — picking this up since @aptsalt's PR (#2125) was closed when they deleted their fork.
Plan:
- Add
subject: str | None = NonetoAccessToken(the original ask) - Add
claims: dict[str, Any] | None = Nonefor arbitrary custom JWT claims (as @robertofalk suggested — the JWT spec has few reserved claims and companies commonly add custom ones) - Expose
subjectviaContext.subjectproperty for easy access in tool handlers (as @lukebuehler suggested) - Tests covering new fields and backward compatibility
Both fields are optional so this is fully backward compatible. Working on branch feat/access-token-subject-claims. Happy to adjust scope before opening the PR.