feat(mcp): per-request user_id contextvar for tool handlers

Adds mcp._context.current_user_id() backed by a ContextVar. The ASGI
auth middleware sets it before dispatching to FastMCP and resets it
on the way out, so tool handlers can read the acting user without
re-parsing the request scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-26 20:17:04 -04:00
parent 3cc5c7dcab
commit 3579db2f06
3 changed files with 51 additions and 1 deletions
+6 -1
View File
@@ -63,7 +63,12 @@ def mount_mcp(app: Quart) -> None:
})
return
scope["fable_user_id"] = user_id
await mcp_asgi(scope, receive, send)
from fabledassistant.mcp._context import _user_id_ctx
token = _user_id_ctx.set(user_id)
try:
await mcp_asgi(scope, receive, send)
finally:
_user_id_ctx.reset(token)
original_asgi = app.asgi_app