Skip to main content

A lightweight, plug-and-play security middleware for FastAPI applications, specifically designed for MCP (Model Context Protocol) servers.

Project description

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
  • Developer-Friendly: Simple decorator-based API with minimal configuration
  • Production-Ready: Comprehensive error handling and security best practices

Quick Start

Installation

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:

  1. Token Extraction: Validates Authorization header format
  2. JWT Validation: Verifies signature, expiration, and audience
  3. Scope Authorization: Ensures required scope is present
  4. 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

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcp_guardian_auth-1.0.0.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_guardian_auth-1.0.0-py3-none-any.whl (7.5 kB view details)

Uploaded Python 3

File details

Details for the file mcp_guardian_auth-1.0.0.tar.gz.

File metadata

  • Download URL: mcp_guardian_auth-1.0.0.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for mcp_guardian_auth-1.0.0.tar.gz
Algorithm Hash digest
SHA256 48f8d6e9bf8a421839909a97a7a6c430ae4b29b2be4ba52fe14bdd06263e97a5
MD5 6f774071e2515a332bbf93744b63b439
BLAKE2b-256 5a4e127d94148d30e8232e205d83b799212edcf4c540733dd24f3abbf66000f7

See more details on using hashes here.

File details

Details for the file mcp_guardian_auth-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mcp_guardian_auth-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 142a7a0391b1aa1853169fca29f611b902e4bdf8514a15655950f854eeed4812
MD5 eb82207d220879c200c6cee34a104709
BLAKE2b-256 f51375842a69a811cdc52bcacf14cdff89cf1340a40bbcbf9511739f65406dcf

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page