MCP Guardian
A lightweight, plug-and-play security middleware for FastAPI applications, specifically designed for MCP (Model Context Protocol) servers in the AI Agent ecosystem.
Features
- JWT Authentication: Secure token-based authentication using RS256 signatures
- Scope-based Authorization: Fine-grained access control using JWT scopes
- Rate Limiting: Configurable request rate limiting per user
- Security Audit Trail: Comprehensive JSON logging of all security events for monitoring and forensics
- Developer-Friendly: Simple decorator-based API with minimal configuration
- Production-Ready: Comprehensive error handling and security best practices
Quick Start
Installation
# Install from PyPI (recommended)
pip install mcp-guardian-auth
# Or install from source
git clone https://github.com/zhengchen/mcp-guardian.git
cd mcp-guardian
pip install -r requirements.txt
Quick Setup
Protect your FastAPI endpoints:
from fastapi import FastAPI, Request
from mcp_guardian import Guardian
app = FastAPI()
guardian = Guardian(config_path="config.example.yaml")
@app.post("/protected-endpoint")
@guardian.protect(scope="tools:calculator:execute")
async def protected_function(request: Request):
# Access validated token payload
user_info = request.state.token
return {"message": "Access granted!", "user": user_info["sub"]}
Run the demo application:
# Simple demo
python tools/main.py
# Or comprehensive example
python examples/real_world_example.py
API Reference
Guardian Class
The main security middleware class that provides endpoint protection.
Guardian(config_path: str)
Initialize the Guardian with configuration from a YAML file.
Parameters:
config_path: Path to the YAML configuration file
@guardian.protect(scope: str)
Decorator to protect FastAPI endpoints with comprehensive security checks.
Parameters:
scope: Required scope for accessing the endpoint
Security Checks Performed:
- Token Extraction: Validates Authorization header format
- JWT Validation: Verifies signature, expiration, and audience
- Scope Authorization: Ensures required scope is present
- Rate Limiting: Tracks and enforces request limits per user
Returns:
- Decorated function with security middleware applied
Configuration
JWT Configuration
jwt:
public_key: | # RS256 public key for token verification
-----BEGIN PUBLIC KEY-----
# Your public key content
-----END PUBLIC KEY-----
algorithm: "RS256" # JWT signing algorithm
audience: "your-api-audience" # Expected JWT audience
Rate Limiting Configuration
rate_limit:
requests: 100 # Maximum requests per period
period_minutes: 60 # Time period in minutes
Security Audit Trail
MCP Guardian provides comprehensive security event logging in structured JSON format for monitoring, debugging, and forensic analysis.
Log Format
All security events are logged as JSON with the following structure:
{
"timestamp": "2024-01-15T10:30:45.123456+00:00",
"event_action": "authentication_success",
"event_status": "SUCCESS",
"user_id": "user-12345",
"source_ip": "192.168.1.100",
"detail": "User user-12345 successfully authenticated and authorized for scope 'tools:calculator:execute'",
"service": "mcp_guardian",
"scope": "tools:calculator:execute",
"endpoint": "POST /tools/calculator",
"user_agent": "Mozilla/5.0..."
}
Event Types
authentication_success: User successfully authenticated and authorizedauthentication_failed: Invalid or missing JWT tokenauthorization_failed: Valid token but insufficient permissionsrate_limit_exceeded: User exceeded rate limitsecurity_error: Other security-related errors
Logger Configuration
The Guardian uses a dedicated logger named mcp_guardian.security that outputs raw JSON to stdout. You can configure this logger in your application:
import logging
# Configure the security logger
security_logger = logging.getLogger('mcp_guardian.security')
security_logger.setLevel(logging.INFO)
# Add file handler for persistent logging
file_handler = logging.FileHandler('security_audit.log')
security_logger.addHandler(file_handler)
Error Handling
MCP Guardian provides clear, secure error messages:
- 401 Unauthorized: Missing, malformed, or invalid JWT tokens
- 403 Forbidden: Insufficient permissions (missing required scope)
- 429 Too Many Requests: Rate limit exceeded
Testing
Generate Test Tokens
python test_tokens.py
This script generates:
- Valid tokens for testing protected endpoints
- Invalid tokens for testing error handling
Example Test Requests
Public Endpoint:
curl http://localhost:8000/
Protected Endpoint:
curl -X POST http://localhost:8000/tools/calculate \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"expression": "5 * 3"}'
Security Considerations
- Token Storage: Never store JWT tokens in localStorage or cookies in production
- Key Management: Use secure key management practices for your private keys
- Rate Limiting: Adjust rate limits based on your application's needs
- Audience Validation: Always validate the JWT audience to prevent token reuse
- Scope Design: Design your scopes following the principle of least privilege
License
MIT License - see LICENSE file for details.
Metadata
Release files for mcp-guardian-auth 1.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| mcp_guardian_auth-1.1.0.tar.gz | 18.8 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mcp_guardian_auth-1.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 28.1 kB
Release files / mcp_guardian_auth-1.1.0.tar.gz
| Download URL | mcp_guardian_auth-1.1.0.tar.gz |
|---|---|
| Size | 18.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f41fc446223df6869bae73f4cf81abc4fadf7c69a6cbfd0912296c064874f052
|
|
BLAKE2b-256 checksum How to use checksums |
4dc584d19c57bfd07ac563681a0c024a24e16d3f216b2ef0ee6ea551fd708bd9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.7
|
Release files / mcp_guardian_auth-1.1.0-py3-none-any.whl
| Download URL | mcp_guardian_auth-1.1.0-py3-none-any.whl |
|---|---|
| Size | 9.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b4da1dea16ba23512a8aaa9a0851d6153b2f2c0340c5913563928e7f40fe3382
|
|
BLAKE2b-256 checksum How to use checksums |
a595d5a50a90a91dc58e33a18d5e999e60144e9111d3b76e47f26bc7234b673b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.7
|
Security for mcp-guardian-auth 1.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.