Skip to main content

A lightweight, plug-and-play security middleware for FastAPI applications with comprehensive audit trail logging, 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
  • 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:

  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

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 authorized
  • authentication_failed: Invalid or missing JWT token
  • authorization_failed: Valid token but insufficient permissions
  • rate_limit_exceeded: User exceeded rate limit
  • security_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.

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.1.0.tar.gz (18.8 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.1.0-py3-none-any.whl (9.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: mcp_guardian_auth-1.1.0.tar.gz
  • Upload date:
  • Size: 18.8 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.1.0.tar.gz
Algorithm Hash digest
SHA256 f41fc446223df6869bae73f4cf81abc4fadf7c69a6cbfd0912296c064874f052
MD5 ecdd811e86b9b9b142ea7a8367e28892
BLAKE2b-256 4dc584d19c57bfd07ac563681a0c024a24e16d3f216b2ef0ee6ea551fd708bd9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for mcp_guardian_auth-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b4da1dea16ba23512a8aaa9a0851d6153b2f2c0340c5913563928e7f40fe3382
MD5 686a318f0482f6059a9b1be04707f2f6
BLAKE2b-256 a595d5a50a90a91dc58e33a18d5e999e60144e9111d3b76e47f26bc7234b673b

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