Fastmcp Oauth Simple
No description available
Ask AI about Fastmcp Oauth Simple
Powered by Claude Β· Grounded in docs
I know everything about Fastmcp Oauth Simple. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
FastMCP OAuth Simple
Production-ready MCP (Model Context Protocol) server skeleton with OAuth 2.1 authentication support.
Features
β Dual Transport Support
- stdio transport for local MCP clients (Claude Desktop, etc.)
- HTTP transport for remote/web access
β OAuth 2.1 Compliance
- PKCE (Proof Key for Code Exchange) enabled by default
- JWT token verification with JWKS
- Flexible audience validation
- Secure token handling
β Multiple Provider Support
- Okta (fully implemented)
- Extensible architecture for Auth0, Azure AD, Google (templates provided)
β Modern Architecture
- Type-safe configuration with Pydantic 2.0+
- Structured logging
- Application context pattern
- Clean separation of concerns
β Developer Experience
- Comprehensive CLI with argparse
- Environment-based configuration
- Detailed inline documentation
- Example tools, resources, and prompts
Quick Start
1. Installation
# Clone the repository
git clone <repository-url>
cd fastmcp-oauth-simple
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -e .
# Or using uv (recommended)
uv venv
source .venv/bin/activate
uv pip install -e .
2. Configuration
# Copy environment template
cp .env.example .env
# Edit .env with your configuration
nano .env
3. Run the Server
Stdio Transport (No Auth - for local clients)
python -m src.server
# or
python -m src.server --transport stdio
HTTP Transport with OAuth
# Set OAuth credentials in .env first
python -m src.server --transport http --host 0.0.0.0 --port 8000
HTTP Transport without OAuth
# Don't set OAuth credentials in .env
python -m src.server --transport http
Configuration
Environment Variables
The server is configured via environment variables. See .env.example for all available options.
Server Configuration:
MCP_SERVER_NAME="FastMCP OAuth Server"
MCP_TRANSPORT=stdio # stdio or http
MCP_HOST=localhost # HTTP host
MCP_PORT=8000 # HTTP port
MCP_PATH=/ # Base path
BASE_URL= # Base URL for OAuth (e.g., https://abc123.ngrok-free.app)
MCP_CORS_ORIGINS=* # CORS origins (comma-separated)
MCP_LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
Note: BASE_URL is useful when using ngrok, reverse proxies, or custom domains. If not set, it will be constructed from MCP_HOST and MCP_PORT.
OAuth Configuration (optional):
OAUTH_PROVIDER=okta # okta, auth0, azure, google
OAUTH_DOMAIN=https://dev-123456.okta.com # Provider domain
OAUTH_CLIENT_ID=your-client-id # Client ID
OAUTH_CLIENT_SECRET=your-client-secret # Client secret (optional for PKCE)
OAUTH_SCOPES=openid,profile,email # Comma-separated scopes
OAUTH_PKCE=true # Enable PKCE (required for OAuth 2.1)
OAUTH_AUDIENCE= # Token audience (optional)
Command-Line Arguments
All configuration can be overridden via command-line arguments:
python -m src.server \
--transport http \
--host 0.0.0.0 \
--port 8000 \
--path / \
--base-url https://abc123.ngrok-free.app \
--log-level DEBUG
Available Arguments:
--transport: Transport protocol (stdio or http)--host: Server host for HTTP transport--port: Server port for HTTP transport--path: Base path for HTTP endpoints--base-url: Base URL for OAuth callbacks (overrides host:port)--log-level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
Architecture
Project Structure
fastmcp-oauth-simple/
βββ src/
β βββ auth/ # Authentication providers
β β βββ __init__.py # Export auth components
β β βββ base.py # Abstract auth provider base class
β β βββ okta_provider.py # Okta OAuth 2.1 implementation
β β βββ auth_factory.py # Factory for creating providers
β β
β βββ mcp/ # MCP server components
β β βββ __init__.py # Export MCP components
β β βββ tools.py # Tool definitions
β β βββ resources.py # Resource definitions
β β βββ prompts.py # Prompt definitions
β β βββ registry.py # Component registration
β β
β βββ __init__.py # Package initialization
β βββ config.py # Configuration management
β βββ context.py # Application context
β βββ server.py # Main entry point
β
βββ .env.example # Environment template
βββ .gitignore # Enhanced gitignore
βββ README.md # This file
βββ pyproject.toml # Project configuration
βββ uv.lock # Dependency lock file
Core Concepts
1. Configuration Management (config.py)
- Type-safe configuration with Pydantic models
- Environment variable loading
- Validation and defaults
- Separation of server and OAuth config
2. Application Context (context.py)
- Shared state management
- Logger configuration
- Metadata storage
- Dependency injection support
3. Authentication (auth/)
- Abstract provider interface
- Provider-specific implementations
- Factory pattern for easy extension
- OAuth 2.1 compliance
4. MCP Components (mcp/)
- Tools: Callable operations
- Resources: Read-only data sources
- Prompts: LLM interaction guidance
- Registry: Central registration system
5. Server Entry Point (server.py)
- CLI argument parsing
- Transport selection
- Auth provider initialization
- Component registration
- Async execution
Usage Examples
Example 1: Local Development (No Auth)
# .env
MCP_TRANSPORT=stdio
MCP_LOG_LEVEL=DEBUG
# Run
python -m src.server
Example 2: HTTP with Okta OAuth
# .env
MCP_TRANSPORT=http
MCP_HOST=localhost
MCP_PORT=8000
OAUTH_PROVIDER=okta
OAUTH_DOMAIN=https://dev-123456.okta.com
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=your-client-secret
OAUTH_SCOPES=openid,profile,email,mcp:access
OAUTH_PKCE=true
# Run
python -m src.server
Example 3: Development with ngrok (OAuth Testing)
# Terminal 1: Start ngrok
ngrok http 8000
# Copy the ngrok URL (e.g., https://abc123.ngrok-free.app)
# Terminal 2: Configure and run server
# .env
MCP_TRANSPORT=http
MCP_HOST=localhost
MCP_PORT=8000
BASE_URL=https://abc123.ngrok-free.app # Your ngrok URL
OAUTH_PROVIDER=okta
OAUTH_DOMAIN=https://dev-123456.okta.com
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=your-client-secret
OAUTH_SCOPES=openid,profile,email,mcp:access
# Run server
python -m src.server --transport http
# Or with CLI argument
python -m src.server --transport http --base-url https://abc123.ngrok-free.app
Important: Add the ngrok URL to your OAuth provider's allowed redirect URIs:
https://abc123.ngrok-free.app/callback
Example 4: Production Deployment
# .env
MCP_TRANSPORT=http
MCP_HOST=0.0.0.0
MCP_PORT=443
MCP_CORS_ORIGINS=https://your-app.com,https://claude.ai
MCP_LOG_LEVEL=INFO
OAUTH_PROVIDER=okta
OAUTH_DOMAIN=https://your-org.okta.com
OAUTH_CLIENT_ID=prod-client-id
OAUTH_CLIENT_SECRET=prod-client-secret
OAUTH_AUDIENCE=api://default
# Run with gunicorn or uvicorn
# (See deployment section below)
Available Tools
The server includes example tools:
- search: Search for information
- get_user_info: Get authenticated user information
- echo: Echo a message back
- add: Add two numbers
- multiply: Multiply two numbers
- get_server_status: Get server health status
Available Resources
- fastmcp://welcome: Welcome message and server information
- fastmcp://api_docs: Complete API documentation
- fastmcp://config: Server configuration details
Available Prompts
- welcome: Introduction and getting started guide
- troubleshooting: Common issues and solutions
- api_usage: Best practices for using the API
OAuth Provider Setup
Okta Setup
-
Create Okta Account
- Sign up at https://developer.okta.com/signup/
-
Create Application
- Go to Applications β Create App Integration
- Choose "OIDC - OpenID Connect"
- Choose "Web Application"
-
Configure Application
- Grant Types: Enable Authorization Code and Client Credentials
- Sign-in redirect URIs:
https://claude.ai/api/mcp/auth_callback https://chatgpt.com/oauth/callback http://localhost:8000/callback - Sign-out redirect URIs: (optional)
- Assignments: Choose who can access
-
Enable PKCE
- In application settings, ensure PKCE is enabled
- This is required for OAuth 2.1 compliance
-
Copy Credentials
- Copy Client ID and Client Secret
- Note your Okta domain (e.g., https://dev-123456.okta.com)
- Add to
.envfile
-
Test Integration
python -m src.server --transport http --log-level DEBUG
Adding Other Providers
To add support for Auth0, Azure AD, Google, or other providers:
-
Create Provider Class
- Create
src/auth/<provider>_provider.py - Extend
AuthProviderbase class - Implement required methods
- Create
-
Update Factory
- Add provider case in
auth_factory.py - Import and instantiate your provider
- Add provider case in
-
Example Template:
# src/auth/auth0_provider.py from .base import AuthProvider from fastmcp.server.auth import OAuthProxy, JWTVerifier class Auth0Provider(AuthProvider): def __init__(self, domain, client_id, **kwargs): super().__init__("auth0", domain, client_id, **kwargs) def get_authorization_endpoint(self): return f"{self.domain}/authorize" def get_token_endpoint(self): return f"{self.domain}/oauth/token" def get_jwks_uri(self): return f"{self.domain}/.well-known/jwks.json" def get_issuer(self): return f"{self.domain}/" def create_oauth_proxy(self, base_url): # Implement OAuth proxy creation pass
Development
Running Tests
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
Code Quality
# Format code
black src/
# Lint code
ruff check src/
# Type check
mypy src/
Adding New Tools
-
Define Tool Function (
src/mcp/tools.py):def my_new_tool(param: str) -> str: """Tool description.""" return f"Result: {param}" -
Register Tool (
src/mcp/registry.py):def register_tools(self): # ... existing registrations self.mcp.tool()(tools.my_new_tool) -
Test Tool:
python -m src.server --log-level DEBUG
Adding New Resources
-
Define Resource Function (
src/mcp/resources.py):def get_my_resource() -> dict: """Resource description.""" return {"data": "value"} -
Register Resource (
src/mcp/registry.py):@self.mcp.resource("fastmcp://my_resource") def my_resource() -> str: import json return json.dumps(resources.get_my_resource(), indent=2)
Deployment
Docker Deployment
# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install -e .
EXPOSE 8000
CMD ["python", "-m", "src.server", "--transport", "http", "--host", "0.0.0.0", "--port", "8000"]
# Build and run
docker build -t fastmcp-oauth-server .
docker run -p 8000:8000 --env-file .env fastmcp-oauth-server
Production Recommendations
- Use HTTPS: Always use HTTPS in production (use reverse proxy like nginx)
- Environment Variables: Never commit secrets, use environment variables
- Logging: Set appropriate log levels (INFO or WARNING)
- CORS: Limit CORS origins to specific domains
- Monitoring: Implement health checks and monitoring
- Rate Limiting: Add rate limiting for public endpoints
- Secrets Management: Use secrets manager (AWS Secrets Manager, Vault, etc.)
Example nginx Configuration
server {
listen 443 ssl;
server_name your-domain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Troubleshooting
Common Issues
1. Authentication Failures
- Verify OAuth credentials are correct
- Check redirect URIs match in OAuth provider
- Ensure PKCE is enabled
- Check JWKS URI is accessible
2. Connection Issues
- Verify port is not in use:
lsof -i :8000 - Check firewall rules
- Verify host binding (0.0.0.0 for external access)
3. Import Errors
- Ensure you're in the virtual environment
- Install dependencies:
pip install -e . - Check Python version (3.10+)
4. Token Validation Errors
- Check token issuer matches configuration
- Verify audience if set
- Ensure token hasn't expired
Debug Mode
# Enable debug logging
python -m src.server --log-level DEBUG
# Check configuration
python -c "from src.config import load_config_from_env; print(load_config_from_env())"
# Test auth provider
python -c "from src.auth import OktaProvider; print(OktaProvider.__doc__)"
Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Run code quality checks
- Submit a pull request
License
MIT License - see LICENSE file for details
Support
For issues and questions:
- Open an issue on GitHub
- Check existing documentation
- Review troubleshooting section
Acknowledgments
- Built with FastMCP
- OAuth implementation based on OAuth 2.1 specification
- Inspired by modern Python best practices
Version History
See CHANGELOG.md for detailed version history.
Current Version: 0.2.0
Features:
- OAuth 2.1 with PKCE support
- Dual transport (stdio/http)
- Multiple provider architecture
- Type-safe configuration
- Comprehensive documentation
