# 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

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

## 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.