fastmcp-token-guard
ASGI authentication middleware for FastMCP servers.
What is fastmcp-token-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.
fastmcp-token-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 fastmcp-token-guard
With Redis support:
uv add fastmcp-token-guard[redis]
Quick start
from fastmcp import FastMCP
from fastmcp_token_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. fastmcp-token-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 fastmcp_token_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 fastmcp_token_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 fastmcp_token_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:
- The first request downloads the public keys from the JWKS endpoint and caches them.
- Every subsequent request validates the token against the cached keys — no network call.
- If a token fails and the cache has not expired, the keys are refreshed once to handle key rotation.
- After
max_refresh_attemptsconsecutive 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 fastmcp_token_guard import ProxyValidator
validator = ProxyValidator(
validation_url="https://your-auth-service.com/validate",
timeout=5.0,
extra_headers={"X-Service": "fastmcp-token-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 fastmcp_token_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 fastmcp_token_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 fastmcp_token_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/fastmcp-token-guard.git
cd fastmcp-token-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.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastmcp_token_guard-0.1.1.tar.gz | 9.7 kB | Without provenance | Details for fastmcp_token_guard-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastmcp_token_guard-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for fastmcp_token_guard-0.1.1-py3-none-any.whl |
Total release size: 25.1 kB
Release files / fastmcp_token_guard-0.1.1.tar.gz
| Download URL | fastmcp_token_guard-0.1.1.tar.gz |
|---|---|
| Size | 9.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
43318c1cada1dfdfc63dc9313a27b1e503627d21abdb25db82f593902fd2dfc5
|
|
BLAKE2b-256 checksum How to use checksums |
1d50f612475059d03f0352aac3243377f136b6905ba272fef557050b32c492a9
|
| 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.1-py3-none-any.whl
| Download URL | fastmcp_token_guard-0.1.1-py3-none-any.whl |
|---|---|
| Size | 15.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
924b876d7cce0bbc85dbd4bceb189532d69d3b4a35c1e8b5cb5a52796f0979f6
|
|
BLAKE2b-256 checksum How to use checksums |
3f238c4d8d14d8fba7fcf75a10c11cd720b1f5721e0ca76a47a682c4e97ea026
|
| 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.1
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.