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
Clean up provider interface
  • Loading branch information
praboud-ant committed Mar 19, 2025
commit 1e9dd4c213a2e31920df0c7dab4e6db699c3c5bc
19 changes: 14 additions & 5 deletions src/mcp/server/auth/handlers/authorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ class AuthorizationRequest(BaseModel):

response_type: Literal["code"] = Field(..., description="Must be 'code' for authorization code flow")
code_challenge: str = Field(..., description="PKCE code challenge")
code_challenge_method: Literal["S256"] = Field("S256", description="PKCE code challenge method")
code_challenge_method: Literal["S256"] = Field("S256", description="PKCE code challenge method, must be S256")
state: Optional[str] = Field(None, description="Optional state parameter")
scope: Optional[str] = Field(None, description="Optional scope parameter")
scope: Optional[str] = Field(None, description="Optional scope; if specified, should be a space-separated list of scope strings")

class Config:
extra = "ignore"
Expand Down Expand Up @@ -113,12 +113,21 @@ async def authorization_handler(request: Request) -> Response:
code_challenge=auth_request.code_challenge,
redirect_uri=redirect_uri,
)

response = RedirectResponse(url="", status_code=302, headers={"Cache-Control": "no-store"})

try:
# Let the provider handle the authorization flow
await provider.authorize(client, auth_params, response)
authorization_code = await provider.create_authorization_code(client, auth_params)
response = RedirectResponse(url="", status_code=302, headers={"Cache-Control": "no-store"})

# Redirect with code
parsed_uri = urlparse(str(auth_params.redirect_uri))
query_params = [(k, v) for k, vs in parse_qs(parsed_uri.query) for v in vs]
query_params.append(("code", authorization_code))
if auth_params.state:
query_params.append(("state", auth_params.state))

redirect_url = urlunparse(parsed_uri._replace(query=urlencode(query_params)))
response.headers["location"] = redirect_url

return response
except Exception as e:
Expand Down
4 changes: 4 additions & 0 deletions src/mcp/server/auth/handlers/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ async def token_handler(request: Request):

match token_request:
case AuthorizationCodeRequest():
# TODO: verify that the redirect URIs match; does the client actually provide this?
# see https://datatracker.ietf.org/doc/html/rfc6749#section-10.6
# TODO: enforce TTL on the authorization code

# Verify PKCE code verifier
expected_challenge = await provider.challenge_for_authorization_code(
client_info, token_request.code
Expand Down
18 changes: 7 additions & 11 deletions src/mcp/server/auth/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,19 +72,15 @@ def clients_store(self) -> OAuthRegisteredClientsStore:
"""
...

# TODO: do we really want to be putting the response in this method?
async def authorize(self,
async def create_authorization_code(self,
client: OAuthClientInformationFull,
params: AuthorizationParams,
response: Response) -> None:
params: AuthorizationParams) -> str:
"""
Begins the authorization flow, which can be implemented by this server or via redirection.
Must eventually issue a redirect with authorization response or error to the given redirect URI.

Args:
client: The client requesting authorization.
params: Parameters for the authorization request.
response: The response object to write to.
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,
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
16 changes: 5 additions & 11 deletions tests/server/fastmcp/auth/test_auth_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,9 @@ def __init__(self):
def clients_store(self) -> OAuthRegisteredClientsStore:
return self.client_store

async def authorize(self,
async def create_authorization_code(self,
client: OAuthClientInformationFull,
params: AuthorizationParams,
response: Response):
params: AuthorizationParams) -> str:
# Generate an authorization code
code = f"code_{int(time.time())}"

Expand All @@ -78,14 +77,9 @@ async def authorize(self,
"redirect_uri": params.redirect_uri,
"expires_at": int(time.time()) + 600, # 10 minutes
}

# Redirect with code
query = {"code": code}
if params.state:
query["state"] = params.state

redirect_url = f"{params.redirect_uri}?" + "&".join([f"{k}={v}" for k, v in query.items()])
response.headers["location"] = redirect_url

return code


async def challenge_for_authorization_code(self,
client: OAuthClientInformationFull,
Expand Down