Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254---title: GitHub OAuth 🤝 FastMCPsidebarTitle: GitHubdescription: Secure your FastMCP server with GitHub OAuthicon: githubtag: NEW---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.12.0" />
This guide shows you how to secure your FastMCP server using **GitHub OAuth**. Since GitHub doesn't support Dynamic Client Registration, this integration uses the [**OAuth Proxy**](/v2/servers/auth/oauth-proxy) pattern to bridge GitHub's traditional OAuth with MCP's authentication requirements.
## Configuration
### Prerequisites
Before you begin, you will need:1. A **[GitHub Account](https://github.com/)** with access to create OAuth Apps2. Your FastMCP server's URL (can be localhost for development, e.g., `http://localhost:8000`)
### Step 1: Create a GitHub OAuth App
Create an OAuth App in your GitHub settings to get the credentials needed for authentication:
<Steps><Step title="Navigate to OAuth Apps"> Go to **Settings → Developer settings → OAuth Apps** in your GitHub account, or visit [github.com/settings/developers](https://github.com/settings/developers). Click **"New OAuth App"** to create a new application.</Step>
<Step title="Configure Your OAuth App"> Fill in the application details: - **Application name**: Choose a name users will recognize (e.g., "My FastMCP Server") - **Homepage URL**: Your application's homepage or documentation URL - **Authorization callback URL**: Your server URL + `/auth/callback` (e.g., `http://localhost:8000/auth/callback`) <Warning> The callback URL must match exactly. The default path is `/auth/callback`, but you can customize it using the `redirect_path` parameter. For local development, GitHub allows `http://localhost` URLs. For production, you must use HTTPS. </Warning> <Tip> If you want to use a custom callback path (e.g., `/auth/github/callback`), make sure to set the same path in both your GitHub OAuth App settings and the `redirect_path` parameter when configuring the GitHubProvider. </Tip></Step>
<Step title="Save Your Credentials"> After creating the app, you'll see: - **Client ID**: A public identifier like `Ov23liAbcDefGhiJkLmN` - **Client Secret**: Click "Generate a new client secret" and save the value securely <Tip> Store these credentials securely. Never commit them to version control. Use environment variables or a secrets manager in production. </Tip></Step></Steps>
### Step 2: FastMCP Configuration
Create your FastMCP server using the `GitHubProvider`, which handles GitHub's OAuth quirks automatically:
```python server.pyfrom fastmcp import FastMCPfrom fastmcp.server.auth.providers.github import GitHubProvider
# The GitHubProvider handles GitHub's token format and validationauth_provider = GitHubProvider( client_id="Ov23liAbcDefGhiJkLmN", # Your GitHub OAuth App Client ID client_secret="github_pat_...", # Your GitHub OAuth App Client Secret base_url="http://localhost:8000", # Must match your OAuth App configuration # redirect_path="/auth/callback" # Default value, customize if needed)
mcp = FastMCP(name="GitHub Secured App", auth=auth_provider)
# Add a protected tool to test authentication@mcp.toolasync def get_user_info() -> dict: """Returns information about the authenticated GitHub user.""" from fastmcp.server.dependencies import get_access_token token = get_access_token() # The GitHubProvider stores user data in token claims return { "github_user": token.claims.get("login"), "name": token.claims.get("name"), "email": token.claims.get("email") }```
## Testing
### Running the Server
Start your FastMCP server with HTTP transport to enable OAuth flows:
```bashfastmcp run server.py --transport http --port 8000```
Your server is now running and protected by GitHub OAuth authentication.
### Testing with a Client
Create a test client that authenticates with your GitHub-protected server:
```python test_client.pyfrom fastmcp import Clientimport asyncio
async def main(): # The client will automatically handle GitHub OAuth async with Client("http://localhost:8000/mcp", auth="oauth") as client: # First-time connection will open GitHub login in your browser print("✓ Authenticated with GitHub!") # Test the protected tool result = await client.call_tool("get_user_info") print(f"GitHub user: {result['github_user']}")
if __name__ == "__main__": asyncio.run(main())```
When you run the client for the first time:1. Your browser will open to GitHub's authorization page2. After you authorize the app, you'll be redirected back3. The client receives the token and can make authenticated requests
<Info>The client caches tokens locally, so you won't need to re-authenticate for subsequent runs unless the token expires or you explicitly clear the cache.</Info>
## Production Configuration
<VersionBadge version="2.13.0" />
For production deployments with persistent token management across server restarts, configure `jwt_signing_key` and `client_storage`:
```python server.pyimport osfrom fastmcp import FastMCPfrom fastmcp.server.auth.providers.github import GitHubProviderfrom key_value.aio.stores.redis import RedisStorefrom key_value.aio.wrappers.encryption import FernetEncryptionWrapperfrom cryptography.fernet import Fernet
# Production setup with encrypted persistent token storageauth_provider = GitHubProvider( client_id="Ov23liAbcDefGhiJkLmN", client_secret="github_pat_...", base_url="https://your-production-domain.com",
# Production token management jwt_signing_key=os.environ["JWT_SIGNING_KEY"], client_storage=FernetEncryptionWrapper( key_value=RedisStore( host=os.environ["REDIS_HOST"], port=int(os.environ["REDIS_PORT"]) ), fernet=Fernet(os.environ["STORAGE_ENCRYPTION_KEY"]) ))
mcp = FastMCP(name="Production GitHub App", auth=auth_provider)```
<Note>Parameters (`jwt_signing_key` and `client_storage`) work together to ensure tokens and client registrations survive server restarts. **Wrap your storage in `FernetEncryptionWrapper` to encrypt sensitive OAuth tokens at rest** - without it, tokens are stored in plaintext. Store secrets in environment variables and use a persistent storage backend like Redis for distributed deployments.
For complete details on these parameters, see the [OAuth Proxy documentation](/v2/servers/auth/oauth-proxy#configuration-parameters).</Note>
## Environment Variables
<VersionBadge version="2.12.1" />
For production deployments, use environment variables instead of hardcoding credentials.
### Provider Selection
Setting this environment variable allows the GitHub provider to be used automatically without explicitly instantiating it in code.
<Card><ParamField path="FASTMCP_SERVER_AUTH" default="Not set">Set to `fastmcp.server.auth.providers.github.GitHubProvider` to use GitHub authentication.</ParamField></Card>
### GitHub-Specific Configuration
These environment variables provide default values for the GitHub provider, whether it's instantiated manually or configured via `FASTMCP_SERVER_AUTH`.
<Card><ParamField path="FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID" required>Your GitHub OAuth App Client ID (e.g., `Ov23liAbcDefGhiJkLmN`)</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET" required>Your GitHub OAuth App Client Secret</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_BASE_URL" default="http://localhost:8000">Public URL where OAuth endpoints will be accessible (includes any mount path)</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_ISSUER_URL" default="Uses BASE_URL">Issuer URL for OAuth metadata (defaults to `BASE_URL`). Set to root-level URL when mounting under a path prefix to avoid 404 logs. See [HTTP Deployment guide](/v2/deployment/http#mounting-authenticated-servers) for details.</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_REDIRECT_PATH" default="/auth/callback">Redirect path configured in your GitHub OAuth App</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_REQUIRED_SCOPES" default='["user"]'>Comma-, space-, or JSON-separated list of required GitHub scopes (e.g., `user repo` or `["user","repo"]`)</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_TIMEOUT_SECONDS" default="10">HTTP request timeout for GitHub API calls</ParamField></Card>
Example `.env` file:```bash# Use the GitHub providerFASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.github.GitHubProvider
# GitHub OAuth credentialsFASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID=Ov23liAbcDefGhiJkLmNFASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET=github_pat_...FASTMCP_SERVER_AUTH_GITHUB_BASE_URL=https://your-server.comFASTMCP_SERVER_AUTH_GITHUB_REQUIRED_SCOPES=user,repo```
With environment variables set, your server code simplifies to:
```python server.pyfrom fastmcp import FastMCP
# Authentication is automatically configured from environmentmcp = FastMCP(name="GitHub Secured App")
@mcp.toolasync def list_repos() -> list[str]: """List the authenticated user's repositories.""" # Your tool implementation here pass```