Skip to content

Fix/bearer token usage #97

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 6 commits into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.3.2]

### Fixed
- 🐛 Fix a bug preventing simple setup of [basic token passthrough](docs/03_authentication_and_authorization.md#basic-token-passthrough)

## [0.3.1]

🚀 FastApiMCP now supports MCP Authorization!
Expand Down
4 changes: 3 additions & 1 deletion docs/03_authentication_and_authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ mcp = FastApiMCP(
mcp.mount()
```

For a complete working example of authorization header, check out the [auth_example_token_passthrough.py](/examples/08_auth_example_token_passthrough.py) in the examples folder.

## OAuth Flow

FastAPI-MCP supports the full OAuth 2 flow, compliant with [MCP Spec 2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization).
Expand Down Expand Up @@ -138,7 +140,7 @@ For this to work, you have to make sure mcp-remote is running [on a fixed port](

## Working Example with Auth0

For a complete working example of OAuth integration with Auth0, check out the [auth_example_auth0.py](/examples/08_auth_example_auth0.py) in the examples folder. This example demonstrates the simple case of using Auth0 as an OAuth provider, with a working example of the OAuth flow.
For a complete working example of OAuth integration with Auth0, check out the [auth_example_auth0.py](/examples/09_auth_example_auth0.py) in the examples folder. This example demonstrates the simple case of using Auth0 as an OAuth provider, with a working example of the OAuth flow.

For it to work, you need an .env file in the root of the project with the following variables:

Expand Down
58 changes: 58 additions & 0 deletions examples/08_auth_example_token_passthrough.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
This example shows how to reject any request without a valid token passed in the Authorization header.

In order to configure the auth header, the config file for the MCP server should looks like this:
```json
{
"mcpServers": {
"remote-example": {
"command": "npx",
"args": [
"mcp-remote",
"http://localhost:8000/mcp",
"--header",
"Authorization:${AUTH_HEADER}"
]
},
"env": {
"AUTH_HEADER": "Bearer <your-token>"
}
}
}
```
"""
from examples.shared.apps.items import app # The FastAPI app
from examples.shared.setup import setup_logging

from fastapi import Depends
from fastapi.security import HTTPBearer

from fastapi_mcp import FastApiMCP, AuthConfig

setup_logging()

# Scheme for the Authorization header
token_auth_scheme = HTTPBearer()

# Create a private endpoint
@app.get("/private")
async def private(token = Depends(token_auth_scheme)):
return token.credentials

# Create the MCP server with the token auth scheme
mcp = FastApiMCP(
app,
name="Protected MCP",
auth_config=AuthConfig(
dependencies=[Depends(token_auth_scheme)],
),
)

# Mount the MCP server
mcp.mount()


if __name__ == "__main__":
import uvicorn

uvicorn.run(app, host="0.0.0.0", port=8000)
File renamed without changes.
15 changes: 6 additions & 9 deletions fastapi_mcp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ class OAuthMetadata(BaseType):
]

authorization_endpoint: Annotated[
StrHttpUrl,
Optional[StrHttpUrl],
Doc(
"""
URL of the authorization server's authorization endpoint.
"""
),
]
] = None

token_endpoint: Annotated[
StrHttpUrl,
Expand Down Expand Up @@ -353,18 +353,15 @@ async def authenticate_request(request: Request, token: str = Depends(oauth2_sch

@model_validator(mode="after")
def validate_required_fields(self):
if self.custom_oauth_metadata is None and self.issuer is None:
raise ValueError("'issuer' is required when 'custom_oauth_metadata' is not provided")
if self.custom_oauth_metadata is None and self.issuer is None and not self.dependencies:
raise ValueError("at least one of 'issuer', 'custom_oauth_metadata' or 'dependencies' is required")

if self.setup_proxies:
if self.client_id is None:
raise ValueError("'client_id' is required when 'setup_proxies' is True")

if self.setup_fake_dynamic_registration and not self.client_secret:
raise ValueError("'client_secret' is required when 'setup_fake_dynamic_registration' is True")

if self.setup_fake_dynamic_registration and not self.setup_proxies:
raise ValueError("'setup_fake_dynamic_registration' can only be True when 'setup_proxies' is True")
if self.setup_fake_dynamic_registration and not self.client_secret:
raise ValueError("'client_secret' is required when 'setup_fake_dynamic_registration' is True")

return self

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "fastapi-mcp"
version = "0.3.1"
version = "0.3.2"
description = "Automatic MCP server generator for FastAPI applications - converts FastAPI endpoints to MCP tools for LLM integration"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
111 changes: 111 additions & 0 deletions tests/test_types_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import pytest
from pydantic import ValidationError
from fastapi import Depends

from fastapi_mcp.types import (
OAuthMetadata,
AuthConfig,
)


class TestOAuthMetadata:
def test_non_empty_lists_validation(self):
for field in [
"scopes_supported",
"response_types_supported",
"grant_types_supported",
"token_endpoint_auth_methods_supported",
"code_challenge_methods_supported",
]:
with pytest.raises(ValidationError, match=f"{field} cannot be empty"):
OAuthMetadata(
issuer="https://example.com",
authorization_endpoint="https://example.com/auth",
token_endpoint="https://example.com/token",
**{field: []},
)

def test_authorization_endpoint_required_for_authorization_code(self):
with pytest.raises(ValidationError) as exc_info:
OAuthMetadata(
issuer="https://example.com",
token_endpoint="https://example.com/token",
grant_types_supported=["authorization_code", "client_credentials"],
)
assert "authorization_endpoint is required when authorization_code grant type is supported" in str(
exc_info.value
)

OAuthMetadata(
issuer="https://example.com",
token_endpoint="https://example.com/token",
authorization_endpoint="https://example.com/auth",
grant_types_supported=["client_credentials"],
)

def test_model_dump_excludes_none(self):
metadata = OAuthMetadata(
issuer="https://example.com",
authorization_endpoint="https://example.com/auth",
token_endpoint="https://example.com/token",
)

dumped = metadata.model_dump()

assert "registration_endpoint" not in dumped


class TestAuthConfig:
def test_required_fields_validation(self):
with pytest.raises(
ValidationError, match="at least one of 'issuer', 'custom_oauth_metadata' or 'dependencies' is required"
):
AuthConfig()

AuthConfig(issuer="https://example.com")

AuthConfig(
custom_oauth_metadata={
"issuer": "https://example.com",
"authorization_endpoint": "https://example.com/auth",
"token_endpoint": "https://example.com/token",
},
)

def dummy_dependency():
pass

AuthConfig(dependencies=[Depends(dummy_dependency)])

def test_client_id_required_for_setup_proxies(self):
with pytest.raises(ValidationError, match="'client_id' is required when 'setup_proxies' is True"):
AuthConfig(
issuer="https://example.com",
setup_proxies=True,
)

AuthConfig(
issuer="https://example.com",
setup_proxies=True,
client_id="test-client-id",
client_secret="test-client-secret",
)

def test_client_secret_required_for_fake_registration(self):
with pytest.raises(
ValidationError, match="'client_secret' is required when 'setup_fake_dynamic_registration' is True"
):
AuthConfig(
issuer="https://example.com",
setup_proxies=True,
client_id="test-client-id",
setup_fake_dynamic_registration=True,
)

AuthConfig(
issuer="https://example.com",
setup_proxies=True,
client_id="test-client-id",
client_secret="test-client-secret",
setup_fake_dynamic_registration=True,
)
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.