mcp-guardian-auth 1.1.0
A lightweight, plug-and-play security middleware for FastAPI applications with comprehensive audit trail logging, specifically designed for MCP (Model Context Protocol) servers.
Requires Python: >=3.10
Keywords: fastapi, jwt, authentication, authorization, rate-limiting, mcp, ai-agents, security, middleware

# 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

```bash
# 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**:

```python
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**:

```bash
# 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

```yaml
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

```yaml
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:

```json
{
  "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:

```python
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

```bash
python test_tokens.py
```

This script generates:
- Valid tokens for testing protected endpoints
- Invalid tokens for testing error handling

### Example Test Requests

**Public Endpoint:**
```bash
curl http://localhost:8000/
```

**Protected Endpoint:**
```bash
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](LICENSE) file for details.