Skip to main content
Yanked

This release has been yanked by its maintainers, and will be ignored by installers, except when explicitly specified.
Consider using release 0.1.1 instead.
Reason given by maintainers: Renamed package, use 0.1.1

mcp-guard

ASGI authentication middleware for FastMCP servers.

PyPI version Python 3.15+ License: 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

uv add mcp-guard

With Redis support:

uv add mcp-guard[redis]

Quick start

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

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.

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:

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.

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.

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.

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.

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.

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.

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

Development

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 for details.

Metadata

Release files for fastmcp-token-guard 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastmcp-token-guard 0.1.0
File Size Uploaded Provenance Actions
fastmcp_token_guard-0.1.0.tar.gz 9.7 kB Without provenance Details for fastmcp_token_guard-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastmcp-token-guard 0.1.0
File Interpreter ABI Platform Actions
fastmcp_token_guard-0.1.0-py3-none-any.whl Python 3 none any Details for fastmcp_token_guard-0.1.0-py3-none-any.whl

Total release size: 25.1 kB

Release files / fastmcp_token_guard-0.1.0.tar.gz

Download URL fastmcp_token_guard-0.1.0.tar.gz
Size 9.7 kB
Tags Source
SHA-256 checksum
How to use checksums
fd885a97bf2a6f55ce77b6271e660f827e363db37c2513befec7d8e96d326583
BLAKE2b-256 checksum
How to use checksums
318b00403dbb64f0a414bdfc29ab989ebfe3e4d0478e94c4d753c7c77dc8d77a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / fastmcp_token_guard-0.1.0-py3-none-any.whl

Download URL fastmcp_token_guard-0.1.0-py3-none-any.whl
Size 15.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c387242d5ebb0f178ca3636d26dbe327ec81da052978913daff107bf9561a6bb
BLAKE2b-256 checksum
How to use checksums
547eb81a4c8774f82fad03f5c6496fc2d2a3b80bfd8bf8622a97fb4d9138ab3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for fastmcp-token-guard 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page