security: add API key auth and user scoping to MCP server#28
Merged
Conversation
- Add `_resolve_user_from_api_key` helper: SHA-256 hash lookup against
api_keys table, returns associated User or None for missing/inactive keys
- Add `_current_user` and `_current_transport` ContextVars to carry auth
state into tool functions without threading issues
- Add `ApiKeyAuthMiddleware` (Starlette BaseHTTPMiddleware) that enforces
X-Api-Key header on all HTTP requests when `settings.auth_enabled=True`;
skips /health endpoint and no-ops when auth is disabled
- Add `_build_http_app()` that wraps FastMCP's streamable-http ASGI app
with the auth middleware via Starlette mount
- Update `__main__` block: HTTP mode uses uvicorn + `_build_http_app()`;
stdio mode runs as before (trusted local agent, no auth)
- Scope collection tools to authenticated user when `_current_user` is set:
- `list_collections`: filters by user_id
- `create_collection`: stamps user_id on new collection
- `add_to_collection`, `get_collection`, `export_collection`,
`export_collection_custom`: verify ownership, return 404-style error
for cross-user access
- stdio mode (no user set) retains full unrestricted access
- Add 17 unit tests covering key resolution, scoping, and ownership checks
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
X-Api-Keyheader, Starlette middleware)Files changed
mcp_server/server.py— auth middleware, context vars, user scoping on all collection toolstests/unit/test_mcp_auth.py— 17 new tests covering auth + scopingTest plan
uv run pytestpasses (594 passed, 1 skipped)X-Api-Keywhenauth_enabled=True🤖 Generated with Claude Code