Metadata-Version: 2.4
Name: fastmcp-token-guard
Version: 0.1.0
Summary: ASGI authentication middleware for FastMCP servers
Keywords: mcp,fastmcp,authentication,middleware,asgi
Author: CamiloDevPy
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Requires-Dist: fastmcp>=4.0.0
Requires-Dist: httpx>=0.28.0
Requires-Dist: pydantic-settings>=2.0.0
Requires-Dist: python-jose[cryptography]>=3.5.0
Requires-Dist: redis>=8.0.0 ; extra == 'redis'
Requires-Python: >=3.15
Project-URL: Homepage, https://github.com/camilo-dev-py/fastmcp-token-guard
Project-URL: Bug Tracker, https://github.com/camilo-dev-py/fastmcp-token-guard/issues
Provides-Extra: redis
Description-Content-Type: text/markdown

# mcp-guard

ASGI authentication middleware for [FastMCP](https://github.com/jlowin/fastmcp) servers.

[![PyPI version](https://badge.fury.io/py/mcp-guard.svg)](https://badge.fury.io/py/mcp-guard)
[![Python 3.15+](https://img.shields.io/badge/python-3.15+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## What is mcp-guard?

MCP (Model Context Protocol) servers expose tools and resources to AI models. By default, these servers have no authentication — anyone with the URL can access them.

**mcp-guard** is an ASGI middleware that sits in front of your FastMCP server and validates every incoming request before it reaches your tools. It supports multiple authentication strategies out of the box and is designed to be extended with your own validators.

```
Client → [McpGuardMiddleware] → FastMCP Server
              ↓
        Token validation
        Rate limiting
```

### When should I use it?

- You are exposing a FastMCP server over HTTP and need to protect it
- Your team uses JWT, JWE or JWKS tokens for authentication
- You already have an auth service and want to validate tokens against it
- You want to prevent brute force attacks with rate limiting

## Features

- **JWT** validation — verify signed tokens using a secret key or public key
- **JWE** token decryption and validation — verify encrypted tokens
- **JWKS** validation — fetch and cache public keys from an identity provider automatically
- **Proxy** validation — delegate token validation to an external auth service
- **Rate limiting** — block brute force and spam attacks by IP using in-memory or Redis storage
- **Hexagonal architecture** — bring your own validator by implementing a simple interface
- **ASGI native** — works with FastMCP, FastAPI, Starlette and any ASGI framework

## Installation

```bash
uv add mcp-guard
```

With Redis support:
```bash
uv add mcp-guard[redis]
```

## Quick start

```python
from fastmcp import FastMCP
from mcp_guard import McpGuardMiddleware, JWTValidator

mcp = FastMCP("My Server")

app = McpGuardMiddleware(
    mcp.streamable_http_app(),
    token_validator=JWTValidator(secret_key="your-secret-key"),
)
```

Every request must include an `Authorization` header:
```
Authorization: Bearer <your-token>
```

Requests without a valid token receive a `401 Unauthorized` response.

## Validators

Validators are responsible for checking whether a token is valid. mcp-guard ships with four built-in validators.

### JWT

Validates tokens signed with a secret key (HS256) or a public/private key pair (RS256, ES256).

```python
from mcp_guard import JWTValidator

validator = JWTValidator(
    secret_key="your-secret-key",
    algorithm="HS256",  # default — also supports RS256, ES256, HS384, ES384, ES512
)
```

### JWE

Validates encrypted tokens. Unlike JWT (which is only signed), JWE tokens are fully encrypted — the payload cannot be read without the key.

```python
from mcp_guard import JWEValidator

validator = JWEValidator(
    key=b"your-32-byte-key-here-padded-123",  # must be bytes, 32 bytes for A256KW
    algorithm="A256KW",   # how the encryption key is wrapped
    encryption="A256GCM", # how the content is encrypted
)
```

If you need to read the decrypted payload (for example, to extract user claims), use `decrypt()` directly:

```python
payload = await validator.decrypt(token)
if payload:
    print(payload)  # the decrypted content as a string
```

### JWKS

Validates JWT tokens using public keys downloaded automatically from a JWKS endpoint. Ideal for identity providers like Auth0, Keycloak, Google or Microsoft Azure AD.

The public keys are cached to avoid downloading them on every request. When a token fails validation, the keys are refreshed once in case the provider has rotated them. To prevent abuse, two safety limits apply: a cooldown between refreshes and a maximum number of refresh attempts per token.

```python
from mcp_guard import JWKSValidator

validator = JWKSValidator(
    jwks_url="https://your-domain.auth0.com/.well-known/jwks.json",
    timeout=5.0,
    cache_ttl_seconds=3600.0,          # refresh keys every hour (default)
    refresh_cooldown_seconds=30.0,     # minimum wait between forced refreshes (default)
    max_refresh_attempts=3,            # max retries before blocking further refreshes (default)
)
```

**How it works:**

1. The first request downloads the public keys from the JWKS endpoint and caches them.
2. Every subsequent request validates the token against the cached keys — no network call.
3. If a token fails and the cache has not expired, the keys are refreshed once to handle key rotation.
4. After `max_refresh_attempts` consecutive failures, no more refreshes are made until a valid token resets the counter. This prevents a flood of invalid tokens from hammering your identity provider.

### Proxy

Delegates token validation to an external authentication service. Useful when your team already has a centralized auth service.

The middleware sends the token to your auth service via HTTP POST. If the service responds with `200 OK`, the token is considered valid.

```python
from mcp_guard import ProxyValidator

validator = ProxyValidator(
    validation_url="https://your-auth-service.com/validate",
    timeout=5.0,
    extra_headers={"X-Service": "mcp-guard"},  # optional additional headers
    verify_ssl=True,                            # set to False for self-signed certs
    success_status_codes=[200],                 # codes considered as valid
)
```

## Rate Limiting

Rate limiting blocks requests from clients that exceed a configured number of requests in a time window. It protects against brute force attacks and spam.

The client is identified by its IP address. If a reverse proxy is in front of your server, the real IP is read from the `X-Forwarded-For` header automatically.

### In-Memory (development / single instance)

Simple and dependency-free. Not shared across multiple server instances.

```python
from mcp_guard import McpGuardMiddleware, JWTValidator, InMemoryRateLimiter

app = McpGuardMiddleware(
    mcp.streamable_http_app(),
    token_validator=JWTValidator(secret_key="your-secret-key"),
    rate_limiter=InMemoryRateLimiter(
        max_requests=10,       # maximum requests allowed
        window_seconds=60.0,   # in this time window (seconds)
        whitelist={"127.0.0.1", "localhost"},  # IPs that bypass rate limiting
    ),
)
```

### Redis (production / multiple instances)

Shared across all server instances. Requires the `redis` extra.

```python
import redis.asyncio as redis
from mcp_guard import McpGuardMiddleware, JWTValidator, RedisRateLimiter

redis_client = redis.from_url("redis://localhost:6379")

app = McpGuardMiddleware(
    mcp.streamable_http_app(),
    token_validator=JWTValidator(secret_key="your-secret-key"),
    rate_limiter=RedisRateLimiter(
        redis_client=redis_client,
        max_requests=100,
        window_seconds=60.0,
        fail_open=True,  # if Redis is unavailable, allow requests instead of blocking all traffic
    ),
)
```

## Custom Validator

You can implement your own validator by extending `TokenValidatorPort`. This is useful when you need custom validation logic that is not covered by the built-in validators.

```python
from mcp_guard import McpGuardMiddleware, TokenValidatorPort

class MyValidator(TokenValidatorPort):
    async def validate(self, token: str) -> bool:
        # your logic here
        return token == "my-valid-token"

app = McpGuardMiddleware(
    mcp.streamable_http_app(),
    token_validator=MyValidator(),
)
```

## Exclude Paths

Some paths like health checks should be accessible without authentication. Use `exclude_paths` to bypass the middleware for specific routes.

```python
app = McpGuardMiddleware(
    mcp.streamable_http_app(),
    token_validator=JWTValidator(secret_key="your-secret-key"),
    exclude_paths={"/healthcheck", "/metrics"},
)
```

## Development

```bash
git clone https://github.com/camilo-dev-py/mcp-guard.git
cd mcp-guard
uv sync
uv run pytest
```

## Roadmap

- [ ] OAuth2 validator
- [ ] CLI for token inspection

## License

MIT — see [LICENSE](LICENSE) for details.