Skip to content

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 89 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
682ff1e
wip
praboud-ant Mar 6, 2025
331d51e
Unwind changes
praboud-ant Mar 6, 2025
d283f56
wip
praboud-ant Mar 7, 2025
e96d280
Get tests passing
praboud-ant Mar 10, 2025
1e9dd4c
Clean up provider interface
praboud-ant Mar 10, 2025
d535089
Lint
praboud-ant Mar 10, 2025
031cadf
Clean up registration endpoint
praboud-ant Mar 10, 2025
765efb6
Lint
praboud-ant Mar 10, 2025
0637bc3
update token + revoke to use form data
praboud-ant Mar 10, 2025
b99633a
Adjust more things to fit spec
praboud-ant Mar 10, 2025
9ae1c21
Lint
praboud-ant Mar 10, 2025
50683b9
Remove dup
praboud-ant Mar 10, 2025
2c5f26a
Comment
praboud-ant Mar 10, 2025
e605994
Refactor back to authorize()
praboud-ant Mar 10, 2025
e7c5f87
Improve validation for /token
praboud-ant Mar 11, 2025
83c0c9f
Improve validation for registration
praboud-ant Mar 11, 2025
0c1aae9
Improve /authorize validation & add tests
praboud-ant Mar 11, 2025
038fb04
Hoist oauth token expiration check into bearer auth middleware
praboud-ant Mar 11, 2025
a4e17f3
Add tests for /revoke validation
praboud-ant Mar 11, 2025
5f11c60
Lint + typecheck
praboud-ant Mar 11, 2025
571913a
Clean up unused error classes
praboud-ant Mar 11, 2025
d43647f
Update to use Python 3.10 types
praboud-ant Mar 11, 2025
9d72c1e
Use classes for handlers
praboud-ant Mar 11, 2025
a5079af
Refactor
praboud-ant Mar 11, 2025
c4c2608
Simplify bearer auth logic
praboud-ant Mar 11, 2025
bc62d73
Avoid asyncio dependency in tests
praboud-ant Mar 11, 2025
3852179
Add comment
praboud-ant Mar 11, 2025
874838a
Lint
praboud-ant Mar 11, 2025
f788d79
Add json_response.py comment
praboud-ant Mar 11, 2025
152feb9
Format
praboud-ant Mar 11, 2025
f37ebc4
Move around the response models to be closer to the handlers
praboud-ant Mar 11, 2025
c2873fd
Get rid of silly TS comments
praboud-ant Mar 11, 2025
fe2c029
Remove ClientAuthRequest
praboud-ant Mar 11, 2025
3a13f5d
Reorganize AuthInfo
praboud-ant Mar 11, 2025
37c5fc4
Refactor client metadata endpoint
praboud-ant Mar 11, 2025
792d302
Make metadata more spec compliant
praboud-ant Mar 12, 2025
6c48b11
Use python 3.10 types everywhere
praboud-ant Mar 12, 2025
a437566
Add back authorization to the /revoke endpoint, simplify revoke
praboud-ant Mar 12, 2025
9fee929
Move around validation logic
praboud-ant Mar 12, 2025
d79be8f
Fixups while integrating new auth capabilities
praboud-ant Mar 19, 2025
8d637b4
Pull all auth settings out into a separate config
praboud-ant Mar 19, 2025
8c86bce
Move router file to be routes
praboud-ant Mar 19, 2025
31618c1
Add auth context middleware
praboud-ant Mar 19, 2025
5ebbc19
Validate scopes + provide default
praboud-ant Mar 19, 2025
50673c6
Validate grant_types on registration
praboud-ant Mar 19, 2025
02d76f3
auth: client implementation
dsp-ant Mar 12, 2025
88edddc
update lock
dsp-ant Mar 12, 2025
d774be7
fix
dsp-ant Mar 12, 2025
a09e958
foo
dsp-ant Mar 14, 2025
4e73552
Format
praboud-ant Mar 19, 2025
56f694e
Move StreamingASGITransport into the library code, so MCP integration…
praboud-ant Mar 19, 2025
60da682
Improved error handling, generic types for provider
praboud-ant Mar 21, 2025
374a0b4
Rename AuthInfo to AccessToken
praboud-ant Mar 21, 2025
fb5a568
Rename
praboud-ant Mar 22, 2025
76ddc65
Add docs
praboud-ant Mar 22, 2025
e42dbf5
Merge remote-tracking branch 'origin/main' into praboud/auth
praboud-ant Mar 22, 2025
10e00e7
Typecheck
praboud-ant Mar 22, 2025
87571d8
Return 401 on missing auth, not 403
praboud-ant Mar 25, 2025
c6f991b
Convert AuthContextMiddleware to plain ASGI middleware & add tests
praboud-ant Mar 25, 2025
482149e
Fix redirect_uri handling
praboud-ant Mar 25, 2025
5230180
Remove client for now
praboud-ant Mar 25, 2025
8e15abc
Add test for auth context middleware
praboud-ant Mar 25, 2025
0a1a408
Add CORS support
praboud-ant Mar 25, 2025
3069aa3
Comment
praboud-ant Mar 27, 2025
16f0688
Merge remote-tracking branch 'origin/main' into praboud/auth
praboud-ant Mar 27, 2025
5ecc7f0
Remove client tests
praboud-ant Mar 27, 2025
8c251c9
Add ignores
praboud-ant Mar 27, 2025
f46dcb1
Merge remote-tracking branch 'origin/main' into praboud/auth
praboud-ant Apr 18, 2025
d3725cf
Review feedback
praboud-ant Apr 18, 2025
07f4e3a
Fix stream resource leaks and upgrade Starlette
bhosmer-ant Apr 13, 2025
1237148
Lint
praboud-ant Apr 18, 2025
1ad1842
Review comments
praboud-ant Apr 18, 2025
fa068dd
Rename OAuthServerProvider to OAuthAuthorizationServerProvider
praboud-ant Apr 18, 2025
9b5709a
Merge branch 'main' into praboud/auth
ihrpr Apr 30, 2025
67d568b
revert starlette upgrade
ihrpr Apr 30, 2025
16a7efa
add python-multipart - was missing
ihrpr Apr 30, 2025
91c09a4
ruff
ihrpr Apr 30, 2025
0582bf5
try fixing test
ihrpr Apr 30, 2025
8194bce
increse timeout
ihrpr Apr 30, 2025
2c63020
fix test
ihrpr May 1, 2025
2ea68f2
test
ihrpr May 1, 2025
b0fe041
fix test
ihrpr May 1, 2025
ba366e3
test
ihrpr May 1, 2025
e1a9fec
test
ihrpr May 1, 2025
af4221f
skip test
ihrpr May 1, 2025
f2840fe
Test auth (#609)
ihrpr May 1, 2025
cda4401
remove pyright upgrade and ruff format
ihrpr May 1, 2025
f2cc6ee
uv lock
ihrpr May 1, 2025
23ef519
Merge branch 'main' into praboud/auth
ihrpr May 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Lint
  • Loading branch information
praboud-ant committed Mar 19, 2025
commit 765efb6a096ef187c103f5a95f5d3423885514b5
5 changes: 4 additions & 1 deletion src/mcp/server/auth/handlers/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ async def token_handler(request: Request):
client_info = await client_authenticator(token_request)

if token_request.grant_type not in client_info.grant_types:
raise InvalidRequestError(f"Unsupported grant type (supported grant types are {client_info.grant_types})")
raise InvalidRequestError(
f"Unsupported grant type (supported grant types are "
f"{client_info.grant_types})"
)

tokens: OAuthTokens

Expand Down
18 changes: 11 additions & 7 deletions src/mcp/server/auth/middleware/client_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ class ClientAuthRequest(BaseModel):
"""
Model for client authentication request body.

Corresponds to ClientAuthenticatedRequestSchema in src/server/auth/middleware/clientAuth.ts
Corresponds to ClientAuthenticatedRequestSchema in
src/server/auth/middleware/clientAuth.ts
"""

client_id: str
Expand All @@ -31,12 +32,14 @@ class ClientAuthRequest(BaseModel):

class ClientAuthenticator:
"""
ClientAuthenticator is a callable which validates requests from a client application,
ClientAuthenticator is a callable which validates requests from a client
application,
used to verify /token and /revoke calls.
If, during registration, the client requested to be issued a secret, the authenticator
asserts that /token and /register calls must be authenticated with that same token.
NOTE: clients can opt for no authentication during registration, in which case this logic
is skipped.
If, during registration, the client requested to be issued a secret, the
authenticator asserts that /token and /register calls must be authenticated with
that same token.
NOTE: clients can opt for no authentication during registration, in which case this
logic is skipped.
"""
def __init__(self, clients_store: OAuthRegisteredClientsStore):
"""
Expand All @@ -53,7 +56,8 @@ async def __call__(self, request: ClientAuthRequest) -> OAuthClientInformationFu
if not client:
raise InvalidClientError("Invalid client_id")

# If client from the store expects a secret, validate that the request provides that secret
# If client from the store expects a secret, validate that the request provides
# that secret
if client.client_secret:
if not request.client_secret:
raise InvalidClientError("Client secret is required")
Expand Down
6 changes: 4 additions & 2 deletions src/mcp/server/auth/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,11 @@ async def create_authorization_code(
self, client: OAuthClientInformationFull, params: AuthorizationParams
) -> str:
"""
Generates and stores an authorization code as part of completing the /authorize OAuth step.
Generates and stores an authorization code as part of completing the /authorize
OAuth step.

Implementations SHOULD generate an authorization code with at least 160 bits of entropy,
Implementations SHOULD generate an authorization code with at least 160 bits of
entropy,
and MUST generate an authorization code with at least 128 bits of entropy.
See https://datatracker.ietf.org/doc/html/rfc6749#section-10.10.
"""
Expand Down
1 change: 0 additions & 1 deletion src/mcp/server/fastmcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,6 @@ def starlette_app(self) -> Starlette:

async def handle_sse(request) -> EventSourceResponse:
# Add client ID from auth context into request context if available
request_meta = {}

async with sse.connect_sse(
request.scope, request.receive, request._send
Expand Down
3 changes: 2 additions & 1 deletion src/mcp/server/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ async def sse_writer():
logger.debug("Yielding read and write streams")
# TODO: hold on; shouldn't we be returning the EventSourceResponse?
# I think this is why the tests hang
# TODO: we probably shouldn't return response here, since it's a breaking change
# TODO: we probably shouldn't return response here, since it's a breaking
# change
# this is just to test
yield (read_stream, write_stream, response)

Expand Down
12 changes: 8 additions & 4 deletions src/mcp/shared/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,20 @@ class OAuthClientMetadata(BaseModel):
"""

redirect_uris: List[AnyHttpUrl] = Field(..., min_length=1)
# token_endpoint_auth_method: this implementation only supports none & client_secret_basic;
# token_endpoint_auth_method: this implementation only supports none &
# client_secret_basic;
# ie: we do not support client_secret_post
token_endpoint_auth_method: Literal["none", "client_secret_basic"] = "client_secret_basic"
token_endpoint_auth_method: Literal["none", "client_secret_basic"] = \
"client_secret_basic"
# grant_types: this implementation only supports authorization_code & refresh_token
grant_types: List[Literal["authorization_code", "refresh_token"]] = ["authorization_code"]
grant_types: List[Literal["authorization_code", "refresh_token"]] = \
["authorization_code"]
# this implementation only supports code; ie: it does not support implicit grants
response_types: List[Literal["code"]] = ["code"]
scope: Optional[str] = None

# these fields are currently unused, but we support & store them for potential future use
# these fields are currently unused, but we support & store them for potential
# future use
client_name: Optional[str] = None
client_uri: Optional[AnyHttpUrl] = None
logo_uri: Optional[AnyHttpUrl] = None
Expand Down
4 changes: 2 additions & 2 deletions tests/server/fastmcp/auth/streaming_asgi_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ async def process_messages() -> None:
response_complete.set()

# Create tasks for running the app and processing messages
app_task = asyncio.create_task(run_app())
process_task = asyncio.create_task(process_messages())
asyncio.create_task(run_app())
asyncio.create_task(process_messages())

# Wait for the initial response or timeout
await initial_response_ready.wait()
Expand Down
7 changes: 5 additions & 2 deletions tests/server/fastmcp/auth/test_auth_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,9 @@ async def test_client_registration(
assert client_info["redirect_uris"] == ["https://client.example.com/callback"]

# Verify that the client was registered
# assert await mock_oauth_provider.clients_store.get_client(client_info["client_id"]) is not None
# assert await mock_oauth_provider.clients_store.get_client(
# client_info["client_id"]
# ) is not None

@pytest.mark.anyio
async def test_authorization_flow(
Expand Down Expand Up @@ -553,7 +555,8 @@ def test_tool(x: int) -> str:
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
# 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},
Expand Down