-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Add support for serverside oauth #255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 15 commits
Commits
Show all changes
89 commits
Select commit
Hold shift + click to select a range
682ff1e
wip
praboud-ant 331d51e
Unwind changes
praboud-ant d283f56
wip
praboud-ant e96d280
Get tests passing
praboud-ant 1e9dd4c
Clean up provider interface
praboud-ant d535089
Lint
praboud-ant 031cadf
Clean up registration endpoint
praboud-ant 765efb6
Lint
praboud-ant 0637bc3
update token + revoke to use form data
praboud-ant b99633a
Adjust more things to fit spec
praboud-ant 9ae1c21
Lint
praboud-ant 50683b9
Remove dup
praboud-ant 2c5f26a
Comment
praboud-ant e605994
Refactor back to authorize()
praboud-ant e7c5f87
Improve validation for /token
praboud-ant 83c0c9f
Improve validation for registration
praboud-ant 0c1aae9
Improve /authorize validation & add tests
praboud-ant 038fb04
Hoist oauth token expiration check into bearer auth middleware
praboud-ant a4e17f3
Add tests for /revoke validation
praboud-ant 5f11c60
Lint + typecheck
praboud-ant 571913a
Clean up unused error classes
praboud-ant d43647f
Update to use Python 3.10 types
praboud-ant 9d72c1e
Use classes for handlers
praboud-ant a5079af
Refactor
praboud-ant c4c2608
Simplify bearer auth logic
praboud-ant bc62d73
Avoid asyncio dependency in tests
praboud-ant 3852179
Add comment
praboud-ant 874838a
Lint
praboud-ant f788d79
Add json_response.py comment
praboud-ant 152feb9
Format
praboud-ant f37ebc4
Move around the response models to be closer to the handlers
praboud-ant c2873fd
Get rid of silly TS comments
praboud-ant fe2c029
Remove ClientAuthRequest
praboud-ant 3a13f5d
Reorganize AuthInfo
praboud-ant 37c5fc4
Refactor client metadata endpoint
praboud-ant 792d302
Make metadata more spec compliant
praboud-ant 6c48b11
Use python 3.10 types everywhere
praboud-ant a437566
Add back authorization to the /revoke endpoint, simplify revoke
praboud-ant 9fee929
Move around validation logic
praboud-ant d79be8f
Fixups while integrating new auth capabilities
praboud-ant 8d637b4
Pull all auth settings out into a separate config
praboud-ant 8c86bce
Move router file to be routes
praboud-ant 31618c1
Add auth context middleware
praboud-ant 5ebbc19
Validate scopes + provide default
praboud-ant 50673c6
Validate grant_types on registration
praboud-ant 02d76f3
auth: client implementation
dsp-ant 88edddc
update lock
dsp-ant d774be7
fix
dsp-ant a09e958
foo
dsp-ant 4e73552
Format
praboud-ant 56f694e
Move StreamingASGITransport into the library code, so MCP integration…
praboud-ant 60da682
Improved error handling, generic types for provider
praboud-ant 374a0b4
Rename AuthInfo to AccessToken
praboud-ant fb5a568
Rename
praboud-ant 76ddc65
Add docs
praboud-ant e42dbf5
Merge remote-tracking branch 'origin/main' into praboud/auth
praboud-ant 10e00e7
Typecheck
praboud-ant 87571d8
Return 401 on missing auth, not 403
praboud-ant c6f991b
Convert AuthContextMiddleware to plain ASGI middleware & add tests
praboud-ant 482149e
Fix redirect_uri handling
praboud-ant 5230180
Remove client for now
praboud-ant 8e15abc
Add test for auth context middleware
praboud-ant 0a1a408
Add CORS support
praboud-ant 3069aa3
Comment
praboud-ant 16f0688
Merge remote-tracking branch 'origin/main' into praboud/auth
praboud-ant 5ecc7f0
Remove client tests
praboud-ant 8c251c9
Add ignores
praboud-ant f46dcb1
Merge remote-tracking branch 'origin/main' into praboud/auth
praboud-ant d3725cf
Review feedback
praboud-ant 07f4e3a
Fix stream resource leaks and upgrade Starlette
bhosmer-ant 1237148
Lint
praboud-ant 1ad1842
Review comments
praboud-ant fa068dd
Rename OAuthServerProvider to OAuthAuthorizationServerProvider
praboud-ant 9b5709a
Merge branch 'main' into praboud/auth
ihrpr 67d568b
revert starlette upgrade
ihrpr 16a7efa
add python-multipart - was missing
ihrpr 91c09a4
ruff
ihrpr 0582bf5
try fixing test
ihrpr 8194bce
increse timeout
ihrpr 2c63020
fix test
ihrpr 2ea68f2
test
ihrpr b0fe041
fix test
ihrpr ba366e3
test
ihrpr e1a9fec
test
ihrpr af4221f
skip test
ihrpr f2840fe
Test auth (#609)
ihrpr cda4401
remove pyright upgrade and ruff format
ihrpr f2cc6ee
uv lock
ihrpr 23ef519
Merge branch 'main' into praboud/auth
ihrpr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,16 +4,13 @@ | |
|
||
import base64 | ||
import hashlib | ||
import json | ||
import secrets | ||
import time | ||
import unittest.mock | ||
from urllib.parse import parse_qs, urlparse | ||
|
||
import anyio | ||
import httpx | ||
import pytest | ||
from httpx_sse import aconnect_sse | ||
from pydantic import AnyHttpUrl | ||
from starlette.applications import Starlette | ||
|
||
|
@@ -30,14 +27,10 @@ | |
RevocationOptions, | ||
create_auth_routes, | ||
) | ||
from mcp.server.auth.settings import AuthSettings | ||
from mcp.server.fastmcp import FastMCP | ||
from mcp.server.streaming_asgi_transport import StreamingASGITransport | ||
from mcp.shared.auth import ( | ||
OAuthClientInformationFull, | ||
OAuthToken, | ||
) | ||
from mcp.types import JSONRPCRequest | ||
|
||
|
||
# Mock OAuth provider for testing | ||
|
@@ -230,10 +223,11 @@ def auth_app(mock_oauth_provider): | |
|
||
|
||
@pytest.fixture | ||
def test_client(auth_app) -> httpx.AsyncClient: | ||
return httpx.AsyncClient( | ||
async def test_client(auth_app): | ||
async with httpx.AsyncClient( | ||
transport=httpx.ASGITransport(app=auth_app), base_url="https://mcptest.com" | ||
) | ||
) as client: | ||
yield client | ||
|
||
|
||
@pytest.fixture | ||
|
@@ -993,165 +987,6 @@ async def test_client_registration_invalid_grant_type( | |
) | ||
|
||
|
||
class TestFastMCPWithAuth: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. was this the test that leaked and made the other ones hang? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes, basically this :
|
||
"""Test FastMCP server with authentication.""" | ||
|
||
@pytest.mark.anyio | ||
async def test_fastmcp_with_auth( | ||
self, mock_oauth_provider: MockOAuthProvider, pkce_challenge | ||
): | ||
"""Test creating a FastMCP server with authentication.""" | ||
# Create FastMCP server with auth provider | ||
mcp = FastMCP( | ||
auth_server_provider=mock_oauth_provider, | ||
require_auth=True, | ||
auth=AuthSettings( | ||
issuer_url=AnyHttpUrl("https://auth.example.com"), | ||
client_registration_options=ClientRegistrationOptions(enabled=True), | ||
revocation_options=RevocationOptions(enabled=True), | ||
required_scopes=["read", "write"], | ||
), | ||
) | ||
|
||
# Add a test tool | ||
@mcp.tool() | ||
def test_tool(x: int) -> str: | ||
return f"Result: {x}" | ||
|
||
async with anyio.create_task_group() as task_group: | ||
transport = StreamingASGITransport( | ||
app=mcp.sse_app(), | ||
task_group=task_group, | ||
) | ||
test_client = httpx.AsyncClient( | ||
transport=transport, base_url="http://mcptest.com" | ||
) | ||
|
||
# Test metadata endpoint | ||
response = await test_client.get("/.well-known/oauth-authorization-server") | ||
assert response.status_code == 200 | ||
|
||
# Test that auth is required for protected endpoints | ||
response = await test_client.get("/sse") | ||
assert response.status_code == 401 | ||
|
||
response = await test_client.post("/messages/") | ||
assert response.status_code == 401, response.content | ||
|
||
response = await test_client.post( | ||
"/messages/", | ||
headers={"Authorization": "invalid"}, | ||
) | ||
assert response.status_code == 401 | ||
|
||
response = await test_client.post( | ||
"/messages/", | ||
headers={"Authorization": "Bearer invalid"}, | ||
) | ||
assert response.status_code == 401 | ||
|
||
# now, become authenticated and try to go through the flow again | ||
client_metadata = { | ||
"redirect_uris": ["https://client.example.com/callback"], | ||
"client_name": "Test Client", | ||
} | ||
|
||
response = await test_client.post( | ||
"/register", | ||
json=client_metadata, | ||
) | ||
assert response.status_code == 201 | ||
client_info = response.json() | ||
|
||
# Request authorization using POST with form-encoded data | ||
response = await test_client.post( | ||
"/authorize", | ||
data={ | ||
"response_type": "code", | ||
"client_id": client_info["client_id"], | ||
"redirect_uri": "https://client.example.com/callback", | ||
"code_challenge": pkce_challenge["code_challenge"], | ||
"code_challenge_method": "S256", | ||
"state": "test_state", | ||
}, | ||
) | ||
assert response.status_code == 302 | ||
|
||
# Extract the authorization code from the redirect URL | ||
redirect_url = response.headers["location"] | ||
parsed_url = urlparse(redirect_url) | ||
query_params = parse_qs(parsed_url.query) | ||
|
||
assert "code" in query_params | ||
auth_code = query_params["code"][0] | ||
|
||
# Exchange the authorization code for tokens | ||
response = await test_client.post( | ||
"/token", | ||
data={ | ||
"grant_type": "authorization_code", | ||
"client_id": client_info["client_id"], | ||
"client_secret": client_info["client_secret"], | ||
"code": auth_code, | ||
"code_verifier": pkce_challenge["code_verifier"], | ||
"redirect_uri": "https://client.example.com/callback", | ||
}, | ||
) | ||
assert response.status_code == 200 | ||
|
||
token_response = response.json() | ||
assert "access_token" in token_response | ||
authorization = f"Bearer {token_response['access_token']}" | ||
|
||
# Test the authenticated endpoint with valid token | ||
async with aconnect_sse( | ||
test_client, "GET", "/sse", headers={"Authorization": authorization} | ||
) as event_source: | ||
assert event_source.response.status_code == 200 | ||
events = event_source.aiter_sse() | ||
sse = await events.__anext__() | ||
assert sse.event == "endpoint" | ||
assert sse.data.startswith("/messages/?session_id=") | ||
messages_uri = sse.data | ||
|
||
# verify that we can now post to the /messages endpoint, | ||
# and get a response on the /sse endpoint | ||
response = await test_client.post( | ||
messages_uri, | ||
headers={"Authorization": authorization}, | ||
content=JSONRPCRequest( | ||
jsonrpc="2.0", | ||
id="123", | ||
method="initialize", | ||
params={ | ||
"protocolVersion": "2024-11-05", | ||
"capabilities": { | ||
"roots": {"listChanged": True}, | ||
"sampling": {}, | ||
}, | ||
"clientInfo": {"name": "ExampleClient", "version": "1.0.0"}, | ||
}, | ||
).model_dump_json(), | ||
) | ||
assert response.status_code == 202 | ||
assert response.content == b"Accepted" | ||
|
||
sse = await events.__anext__() | ||
assert sse.event == "message" | ||
sse_data = json.loads(sse.data) | ||
assert sse_data["id"] == "123" | ||
assert set(sse_data["result"]["capabilities"].keys()) == { | ||
"experimental", | ||
"prompts", | ||
"resources", | ||
"tools", | ||
} | ||
# the /sse endpoint will never finish; normally, the client could just | ||
# disconnect, but in tests the easiest way to do this is to cancel the | ||
# task group | ||
task_group.cancel_scope.cancel() | ||
|
||
|
||
class TestAuthorizeEndpointErrors: | ||
"""Test error handling in the OAuth authorization endpoint.""" | ||
|
||
|
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ooc was the outer
with
unnecessary or was it actively messing things up?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I just reverted all the changes to see transport, returning response was not needed at all.
The fun part for the top
async with
was that it was masking "bad test" and sse tests were just hanging. When reverted all the sse changes notices that some other test randomly fails with " ResourceWarning: Unclosed <MemoryObjectReceiveStream at 106c0dd20>"There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's a nice update, I would prefer to have it in a separate PR and test separately. There are a bunch of open PRs addressing different parts of memory leaks, maybe we can just bundle all of them together