fastmcp-token-guard 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. fastmcp_token_guard-0.1.0/PKG-INFO +270 -0
  2. fastmcp_token_guard-0.1.0/README.md +245 -0
  3. fastmcp_token_guard-0.1.0/pyproject.toml +53 -0
  4. fastmcp_token_guard-0.1.0/pyproject.toml.orig +48 -0
  5. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/__init__.py +28 -0
  6. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/__init__.py +0 -0
  7. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/input/__init__.py +0 -0
  8. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/input/middleware.py +74 -0
  9. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/__init__.py +0 -0
  10. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/in_memory_rate_limiter.py +40 -0
  11. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/jwe_validator.py +40 -0
  12. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/jwks_validator.py +92 -0
  13. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/jwt_validator.py +30 -0
  14. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/proxy_validator.py +45 -0
  15. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/adapters/output/redis_rate_limiter.py +44 -0
  16. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/config/__init__.py +0 -0
  17. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/config/settings.py +31 -0
  18. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/core/__init__.py +0 -0
  19. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/core/domain/__init__.py +0 -0
  20. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/core/domain/auth_service.py +14 -0
  21. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/core/ports/__init__.py +0 -0
  22. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/core/ports/rate_limiter_port.py +8 -0
  23. fastmcp_token_guard-0.1.0/src/fastmcp_token_guard/core/ports/token_validator_port.py +7 -0
@@ -0,0 +1,270 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastmcp-token-guard
3
+ Version: 0.1.0
4
+ Summary: ASGI authentication middleware for FastMCP servers
5
+ Keywords: mcp,fastmcp,authentication,middleware,asgi
6
+ Author: CamiloDevPy
7
+ License-Expression: MIT
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.15
13
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
14
+ Classifier: Topic :: Security
15
+ Requires-Dist: fastmcp>=4.0.0
16
+ Requires-Dist: httpx>=0.28.0
17
+ Requires-Dist: pydantic-settings>=2.0.0
18
+ Requires-Dist: python-jose[cryptography]>=3.5.0
19
+ Requires-Dist: redis>=8.0.0 ; extra == 'redis'
20
+ Requires-Python: >=3.15
21
+ Project-URL: Homepage, https://github.com/camilo-dev-py/fastmcp-token-guard
22
+ Project-URL: Bug Tracker, https://github.com/camilo-dev-py/fastmcp-token-guard/issues
23
+ Provides-Extra: redis
24
+ Description-Content-Type: text/markdown
25
+
26
+ # mcp-guard
27
+
28
+ ASGI authentication middleware for [FastMCP](https://github.com/jlowin/fastmcp) servers.
29
+
30
+ [![PyPI version](https://badge.fury.io/py/mcp-guard.svg)](https://badge.fury.io/py/mcp-guard)
31
+ [![Python 3.15+](https://img.shields.io/badge/python-3.15+-blue.svg)](https://www.python.org/downloads/)
32
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
33
+
34
+ ## What is mcp-guard?
35
+
36
+ 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.
37
+
38
+ **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.
39
+
40
+ ```
41
+ Client → [McpGuardMiddleware] → FastMCP Server
42
+ ↓
43
+ Token validation
44
+ Rate limiting
45
+ ```
46
+
47
+ ### When should I use it?
48
+
49
+ - You are exposing a FastMCP server over HTTP and need to protect it
50
+ - Your team uses JWT, JWE or JWKS tokens for authentication
51
+ - You already have an auth service and want to validate tokens against it
52
+ - You want to prevent brute force attacks with rate limiting
53
+
54
+ ## Features
55
+
56
+ - **JWT** validation — verify signed tokens using a secret key or public key
57
+ - **JWE** token decryption and validation — verify encrypted tokens
58
+ - **JWKS** validation — fetch and cache public keys from an identity provider automatically
59
+ - **Proxy** validation — delegate token validation to an external auth service
60
+ - **Rate limiting** — block brute force and spam attacks by IP using in-memory or Redis storage
61
+ - **Hexagonal architecture** — bring your own validator by implementing a simple interface
62
+ - **ASGI native** — works with FastMCP, FastAPI, Starlette and any ASGI framework
63
+
64
+ ## Installation
65
+
66
+ ```bash
67
+ uv add mcp-guard
68
+ ```
69
+
70
+ With Redis support:
71
+ ```bash
72
+ uv add mcp-guard[redis]
73
+ ```
74
+
75
+ ## Quick start
76
+
77
+ ```python
78
+ from fastmcp import FastMCP
79
+ from mcp_guard import McpGuardMiddleware, JWTValidator
80
+
81
+ mcp = FastMCP("My Server")
82
+
83
+ app = McpGuardMiddleware(
84
+ mcp.streamable_http_app(),
85
+ token_validator=JWTValidator(secret_key="your-secret-key"),
86
+ )
87
+ ```
88
+
89
+ Every request must include an `Authorization` header:
90
+ ```
91
+ Authorization: Bearer <your-token>
92
+ ```
93
+
94
+ Requests without a valid token receive a `401 Unauthorized` response.
95
+
96
+ ## Validators
97
+
98
+ Validators are responsible for checking whether a token is valid. mcp-guard ships with four built-in validators.
99
+
100
+ ### JWT
101
+
102
+ Validates tokens signed with a secret key (HS256) or a public/private key pair (RS256, ES256).
103
+
104
+ ```python
105
+ from mcp_guard import JWTValidator
106
+
107
+ validator = JWTValidator(
108
+ secret_key="your-secret-key",
109
+ algorithm="HS256", # default — also supports RS256, ES256, HS384, ES384, ES512
110
+ )
111
+ ```
112
+
113
+ ### JWE
114
+
115
+ Validates encrypted tokens. Unlike JWT (which is only signed), JWE tokens are fully encrypted — the payload cannot be read without the key.
116
+
117
+ ```python
118
+ from mcp_guard import JWEValidator
119
+
120
+ validator = JWEValidator(
121
+ key=b"your-32-byte-key-here-padded-123", # must be bytes, 32 bytes for A256KW
122
+ algorithm="A256KW", # how the encryption key is wrapped
123
+ encryption="A256GCM", # how the content is encrypted
124
+ )
125
+ ```
126
+
127
+ If you need to read the decrypted payload (for example, to extract user claims), use `decrypt()` directly:
128
+
129
+ ```python
130
+ payload = await validator.decrypt(token)
131
+ if payload:
132
+ print(payload) # the decrypted content as a string
133
+ ```
134
+
135
+ ### JWKS
136
+
137
+ Validates JWT tokens using public keys downloaded automatically from a JWKS endpoint. Ideal for identity providers like Auth0, Keycloak, Google or Microsoft Azure AD.
138
+
139
+ 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.
140
+
141
+ ```python
142
+ from mcp_guard import JWKSValidator
143
+
144
+ validator = JWKSValidator(
145
+ jwks_url="https://your-domain.auth0.com/.well-known/jwks.json",
146
+ timeout=5.0,
147
+ cache_ttl_seconds=3600.0, # refresh keys every hour (default)
148
+ refresh_cooldown_seconds=30.0, # minimum wait between forced refreshes (default)
149
+ max_refresh_attempts=3, # max retries before blocking further refreshes (default)
150
+ )
151
+ ```
152
+
153
+ **How it works:**
154
+
155
+ 1. The first request downloads the public keys from the JWKS endpoint and caches them.
156
+ 2. Every subsequent request validates the token against the cached keys — no network call.
157
+ 3. If a token fails and the cache has not expired, the keys are refreshed once to handle key rotation.
158
+ 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.
159
+
160
+ ### Proxy
161
+
162
+ Delegates token validation to an external authentication service. Useful when your team already has a centralized auth service.
163
+
164
+ The middleware sends the token to your auth service via HTTP POST. If the service responds with `200 OK`, the token is considered valid.
165
+
166
+ ```python
167
+ from mcp_guard import ProxyValidator
168
+
169
+ validator = ProxyValidator(
170
+ validation_url="https://your-auth-service.com/validate",
171
+ timeout=5.0,
172
+ extra_headers={"X-Service": "mcp-guard"}, # optional additional headers
173
+ verify_ssl=True, # set to False for self-signed certs
174
+ success_status_codes=[200], # codes considered as valid
175
+ )
176
+ ```
177
+
178
+ ## Rate Limiting
179
+
180
+ 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.
181
+
182
+ 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.
183
+
184
+ ### In-Memory (development / single instance)
185
+
186
+ Simple and dependency-free. Not shared across multiple server instances.
187
+
188
+ ```python
189
+ from mcp_guard import McpGuardMiddleware, JWTValidator, InMemoryRateLimiter
190
+
191
+ app = McpGuardMiddleware(
192
+ mcp.streamable_http_app(),
193
+ token_validator=JWTValidator(secret_key="your-secret-key"),
194
+ rate_limiter=InMemoryRateLimiter(
195
+ max_requests=10, # maximum requests allowed
196
+ window_seconds=60.0, # in this time window (seconds)
197
+ whitelist={"127.0.0.1", "localhost"}, # IPs that bypass rate limiting
198
+ ),
199
+ )
200
+ ```
201
+
202
+ ### Redis (production / multiple instances)
203
+
204
+ Shared across all server instances. Requires the `redis` extra.
205
+
206
+ ```python
207
+ import redis.asyncio as redis
208
+ from mcp_guard import McpGuardMiddleware, JWTValidator, RedisRateLimiter
209
+
210
+ redis_client = redis.from_url("redis://localhost:6379")
211
+
212
+ app = McpGuardMiddleware(
213
+ mcp.streamable_http_app(),
214
+ token_validator=JWTValidator(secret_key="your-secret-key"),
215
+ rate_limiter=RedisRateLimiter(
216
+ redis_client=redis_client,
217
+ max_requests=100,
218
+ window_seconds=60.0,
219
+ fail_open=True, # if Redis is unavailable, allow requests instead of blocking all traffic
220
+ ),
221
+ )
222
+ ```
223
+
224
+ ## Custom Validator
225
+
226
+ 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.
227
+
228
+ ```python
229
+ from mcp_guard import McpGuardMiddleware, TokenValidatorPort
230
+
231
+ class MyValidator(TokenValidatorPort):
232
+ async def validate(self, token: str) -> bool:
233
+ # your logic here
234
+ return token == "my-valid-token"
235
+
236
+ app = McpGuardMiddleware(
237
+ mcp.streamable_http_app(),
238
+ token_validator=MyValidator(),
239
+ )
240
+ ```
241
+
242
+ ## Exclude Paths
243
+
244
+ Some paths like health checks should be accessible without authentication. Use `exclude_paths` to bypass the middleware for specific routes.
245
+
246
+ ```python
247
+ app = McpGuardMiddleware(
248
+ mcp.streamable_http_app(),
249
+ token_validator=JWTValidator(secret_key="your-secret-key"),
250
+ exclude_paths={"/healthcheck", "/metrics"},
251
+ )
252
+ ```
253
+
254
+ ## Development
255
+
256
+ ```bash
257
+ git clone https://github.com/camilo-dev-py/mcp-guard.git
258
+ cd mcp-guard
259
+ uv sync
260
+ uv run pytest
261
+ ```
262
+
263
+ ## Roadmap
264
+
265
+ - [ ] OAuth2 validator
266
+ - [ ] CLI for token inspection
267
+
268
+ ## License
269
+
270
+ MIT — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,245 @@
1
+ # mcp-guard
2
+
3
+ ASGI authentication middleware for [FastMCP](https://github.com/jlowin/fastmcp) servers.
4
+
5
+ [![PyPI version](https://badge.fury.io/py/mcp-guard.svg)](https://badge.fury.io/py/mcp-guard)
6
+ [![Python 3.15+](https://img.shields.io/badge/python-3.15+-blue.svg)](https://www.python.org/downloads/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ ## What is mcp-guard?
10
+
11
+ 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.
12
+
13
+ **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.
14
+
15
+ ```
16
+ Client → [McpGuardMiddleware] → FastMCP Server
17
+ ↓
18
+ Token validation
19
+ Rate limiting
20
+ ```
21
+
22
+ ### When should I use it?
23
+
24
+ - You are exposing a FastMCP server over HTTP and need to protect it
25
+ - Your team uses JWT, JWE or JWKS tokens for authentication
26
+ - You already have an auth service and want to validate tokens against it
27
+ - You want to prevent brute force attacks with rate limiting
28
+
29
+ ## Features
30
+
31
+ - **JWT** validation — verify signed tokens using a secret key or public key
32
+ - **JWE** token decryption and validation — verify encrypted tokens
33
+ - **JWKS** validation — fetch and cache public keys from an identity provider automatically
34
+ - **Proxy** validation — delegate token validation to an external auth service
35
+ - **Rate limiting** — block brute force and spam attacks by IP using in-memory or Redis storage
36
+ - **Hexagonal architecture** — bring your own validator by implementing a simple interface
37
+ - **ASGI native** — works with FastMCP, FastAPI, Starlette and any ASGI framework
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ uv add mcp-guard
43
+ ```
44
+
45
+ With Redis support:
46
+ ```bash
47
+ uv add mcp-guard[redis]
48
+ ```
49
+
50
+ ## Quick start
51
+
52
+ ```python
53
+ from fastmcp import FastMCP
54
+ from mcp_guard import McpGuardMiddleware, JWTValidator
55
+
56
+ mcp = FastMCP("My Server")
57
+
58
+ app = McpGuardMiddleware(
59
+ mcp.streamable_http_app(),
60
+ token_validator=JWTValidator(secret_key="your-secret-key"),
61
+ )
62
+ ```
63
+
64
+ Every request must include an `Authorization` header:
65
+ ```
66
+ Authorization: Bearer <your-token>
67
+ ```
68
+
69
+ Requests without a valid token receive a `401 Unauthorized` response.
70
+
71
+ ## Validators
72
+
73
+ Validators are responsible for checking whether a token is valid. mcp-guard ships with four built-in validators.
74
+
75
+ ### JWT
76
+
77
+ Validates tokens signed with a secret key (HS256) or a public/private key pair (RS256, ES256).
78
+
79
+ ```python
80
+ from mcp_guard import JWTValidator
81
+
82
+ validator = JWTValidator(
83
+ secret_key="your-secret-key",
84
+ algorithm="HS256", # default — also supports RS256, ES256, HS384, ES384, ES512
85
+ )
86
+ ```
87
+
88
+ ### JWE
89
+
90
+ Validates encrypted tokens. Unlike JWT (which is only signed), JWE tokens are fully encrypted — the payload cannot be read without the key.
91
+
92
+ ```python
93
+ from mcp_guard import JWEValidator
94
+
95
+ validator = JWEValidator(
96
+ key=b"your-32-byte-key-here-padded-123", # must be bytes, 32 bytes for A256KW
97
+ algorithm="A256KW", # how the encryption key is wrapped
98
+ encryption="A256GCM", # how the content is encrypted
99
+ )
100
+ ```
101
+
102
+ If you need to read the decrypted payload (for example, to extract user claims), use `decrypt()` directly:
103
+
104
+ ```python
105
+ payload = await validator.decrypt(token)
106
+ if payload:
107
+ print(payload) # the decrypted content as a string
108
+ ```
109
+
110
+ ### JWKS
111
+
112
+ Validates JWT tokens using public keys downloaded automatically from a JWKS endpoint. Ideal for identity providers like Auth0, Keycloak, Google or Microsoft Azure AD.
113
+
114
+ 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.
115
+
116
+ ```python
117
+ from mcp_guard import JWKSValidator
118
+
119
+ validator = JWKSValidator(
120
+ jwks_url="https://your-domain.auth0.com/.well-known/jwks.json",
121
+ timeout=5.0,
122
+ cache_ttl_seconds=3600.0, # refresh keys every hour (default)
123
+ refresh_cooldown_seconds=30.0, # minimum wait between forced refreshes (default)
124
+ max_refresh_attempts=3, # max retries before blocking further refreshes (default)
125
+ )
126
+ ```
127
+
128
+ **How it works:**
129
+
130
+ 1. The first request downloads the public keys from the JWKS endpoint and caches them.
131
+ 2. Every subsequent request validates the token against the cached keys — no network call.
132
+ 3. If a token fails and the cache has not expired, the keys are refreshed once to handle key rotation.
133
+ 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.
134
+
135
+ ### Proxy
136
+
137
+ Delegates token validation to an external authentication service. Useful when your team already has a centralized auth service.
138
+
139
+ The middleware sends the token to your auth service via HTTP POST. If the service responds with `200 OK`, the token is considered valid.
140
+
141
+ ```python
142
+ from mcp_guard import ProxyValidator
143
+
144
+ validator = ProxyValidator(
145
+ validation_url="https://your-auth-service.com/validate",
146
+ timeout=5.0,
147
+ extra_headers={"X-Service": "mcp-guard"}, # optional additional headers
148
+ verify_ssl=True, # set to False for self-signed certs
149
+ success_status_codes=[200], # codes considered as valid
150
+ )
151
+ ```
152
+
153
+ ## Rate Limiting
154
+
155
+ 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.
156
+
157
+ 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.
158
+
159
+ ### In-Memory (development / single instance)
160
+
161
+ Simple and dependency-free. Not shared across multiple server instances.
162
+
163
+ ```python
164
+ from mcp_guard import McpGuardMiddleware, JWTValidator, InMemoryRateLimiter
165
+
166
+ app = McpGuardMiddleware(
167
+ mcp.streamable_http_app(),
168
+ token_validator=JWTValidator(secret_key="your-secret-key"),
169
+ rate_limiter=InMemoryRateLimiter(
170
+ max_requests=10, # maximum requests allowed
171
+ window_seconds=60.0, # in this time window (seconds)
172
+ whitelist={"127.0.0.1", "localhost"}, # IPs that bypass rate limiting
173
+ ),
174
+ )
175
+ ```
176
+
177
+ ### Redis (production / multiple instances)
178
+
179
+ Shared across all server instances. Requires the `redis` extra.
180
+
181
+ ```python
182
+ import redis.asyncio as redis
183
+ from mcp_guard import McpGuardMiddleware, JWTValidator, RedisRateLimiter
184
+
185
+ redis_client = redis.from_url("redis://localhost:6379")
186
+
187
+ app = McpGuardMiddleware(
188
+ mcp.streamable_http_app(),
189
+ token_validator=JWTValidator(secret_key="your-secret-key"),
190
+ rate_limiter=RedisRateLimiter(
191
+ redis_client=redis_client,
192
+ max_requests=100,
193
+ window_seconds=60.0,
194
+ fail_open=True, # if Redis is unavailable, allow requests instead of blocking all traffic
195
+ ),
196
+ )
197
+ ```
198
+
199
+ ## Custom Validator
200
+
201
+ 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.
202
+
203
+ ```python
204
+ from mcp_guard import McpGuardMiddleware, TokenValidatorPort
205
+
206
+ class MyValidator(TokenValidatorPort):
207
+ async def validate(self, token: str) -> bool:
208
+ # your logic here
209
+ return token == "my-valid-token"
210
+
211
+ app = McpGuardMiddleware(
212
+ mcp.streamable_http_app(),
213
+ token_validator=MyValidator(),
214
+ )
215
+ ```
216
+
217
+ ## Exclude Paths
218
+
219
+ Some paths like health checks should be accessible without authentication. Use `exclude_paths` to bypass the middleware for specific routes.
220
+
221
+ ```python
222
+ app = McpGuardMiddleware(
223
+ mcp.streamable_http_app(),
224
+ token_validator=JWTValidator(secret_key="your-secret-key"),
225
+ exclude_paths={"/healthcheck", "/metrics"},
226
+ )
227
+ ```
228
+
229
+ ## Development
230
+
231
+ ```bash
232
+ git clone https://github.com/camilo-dev-py/mcp-guard.git
233
+ cd mcp-guard
234
+ uv sync
235
+ uv run pytest
236
+ ```
237
+
238
+ ## Roadmap
239
+
240
+ - [ ] OAuth2 validator
241
+ - [ ] CLI for token inspection
242
+
243
+ ## License
244
+
245
+ MIT — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "fastmcp-token-guard"
3
+ version = "0.1.0"
4
+ description = "ASGI authentication middleware for FastMCP servers"
5
+ readme = "README.md"
6
+ requires-python = ">=3.15"
7
+ license = "MIT"
8
+ keywords = [
9
+ "mcp",
10
+ "fastmcp",
11
+ "authentication",
12
+ "middleware",
13
+ "asgi",
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.15",
21
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
22
+ "Topic :: Security",
23
+ ]
24
+ dependencies = [
25
+ "fastmcp>=4.0.0",
26
+ "httpx>=0.28.0",
27
+ "pydantic-settings>=2.0.0",
28
+ "python-jose[cryptography]>=3.5.0",
29
+ ]
30
+
31
+ [[project.authors]]
32
+ name = "CamiloDevPy"
33
+
34
+ [project.optional-dependencies]
35
+ redis = ["redis>=8.0.0"]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/camilo-dev-py/fastmcp-token-guard"
39
+ "Bug Tracker" = "https://github.com/camilo-dev-py/fastmcp-token-guard/issues"
40
+
41
+ [dependency-groups]
42
+ dev = [
43
+ "pytest>=9.0.0",
44
+ "pytest-asyncio>=1.5.0",
45
+ ]
46
+
47
+ [build-system]
48
+ requires = ["uv_build>=0.13.10,<0.14.0"]
49
+ build-backend = "uv_build"
50
+
51
+ [tool.pytest.ini_options]
52
+ asyncio_mode = "auto"
53
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "fastmcp-token-guard"
3
+ version = "0.1.0"
4
+ description = "ASGI authentication middleware for FastMCP servers"
5
+ readme = "README.md"
6
+ requires-python = ">=3.15"
7
+ license = "MIT"
8
+ authors = [
9
+ { name = "CamiloDevPy" }
10
+ ]
11
+ keywords = ["mcp", "fastmcp", "authentication", "middleware", "asgi"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.15",
18
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
19
+ "Topic :: Security",
20
+ ]
21
+
22
+ dependencies = [
23
+ "fastmcp>=4.0.0",
24
+ "httpx>=0.28.0",
25
+ "pydantic-settings>=2.0.0",
26
+ "python-jose[cryptography]>=3.5.0",
27
+ ]
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "pytest>=9.0.0",
32
+ "pytest-asyncio>=1.5.0",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ redis = ["redis>=8.0.0"]
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.13.10,<0.14.0"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.pytest.ini_options]
43
+ asyncio_mode = "auto"
44
+ asyncio_default_fixture_loop_scope = "function"
45
+
46
+ [project.urls]
47
+ "Homepage" = "https://github.com/camilo-dev-py/fastmcp-token-guard"
48
+ "Bug Tracker" = "https://github.com/camilo-dev-py/fastmcp-token-guard/issues"
@@ -0,0 +1,28 @@
1
+ from importlib.metadata import version, PackageNotFoundError
2
+
3
+ from fastmcp_token_guard.adapters.input.middleware import McpGuardMiddleware
4
+ from fastmcp_token_guard.adapters.output.jwt_validator import JWTValidator
5
+ from fastmcp_token_guard.adapters.output.jwe_validator import JWEValidator
6
+ from fastmcp_token_guard.adapters.output.jwks_validator import JWKSValidator
7
+ from fastmcp_token_guard.adapters.output.proxy_validator import ProxyValidator
8
+ from fastmcp_token_guard.adapters.output.in_memory_rate_limiter import InMemoryRateLimiter
9
+ from fastmcp_token_guard.adapters.output.redis_rate_limiter import RedisRateLimiter
10
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
11
+ from fastmcp_token_guard.core.ports.rate_limiter_port import RateLimiterPort
12
+
13
+ try:
14
+ __version__ = version("fastmcp-token-guard")
15
+ except PackageNotFoundError:
16
+ __version__ = "unknown"
17
+
18
+ __all__ = [
19
+ "McpGuardMiddleware",
20
+ "JWTValidator",
21
+ "JWEValidator",
22
+ "JWKSValidator",
23
+ "ProxyValidator",
24
+ "InMemoryRateLimiter",
25
+ "RedisRateLimiter",
26
+ "TokenValidatorPort",
27
+ "RateLimiterPort",
28
+ ]
@@ -0,0 +1,74 @@
1
+ import logging
2
+ import json
3
+
4
+ from fastmcp_token_guard.config.settings import get_settings
5
+ from fastmcp_token_guard.core.domain.auth_service import AuthService
6
+ from fastmcp_token_guard.core.ports.rate_limiter_port import RateLimiterPort
7
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ settings = get_settings()
12
+
13
+
14
+ class McpGuardMiddleware:
15
+
16
+ def __init__(self, app, token_validator: TokenValidatorPort, rate_limiter: RateLimiterPort | None = None,
17
+ exclude_paths: set[str] | None = None):
18
+ self.app = app
19
+ self.auth_service = AuthService(token_validator, rate_limiter)
20
+ self.exclude_paths = exclude_paths or set(settings.MCP_GUARD_EXCLUDE_PATHS)
21
+
22
+ async def __call__(self, scope, receive, send) -> None:
23
+ is_passthrough = scope.get("type") not in {"http", "websocket"} or scope.get("path") in self.exclude_paths
24
+ if is_passthrough:
25
+ return await self.app(scope, receive, send)
26
+ headers = self._get_headers(scope)
27
+
28
+ token = self._extract_token(headers=headers)
29
+ if not token:
30
+ return await self._send_error(send, 401, "Unauthorized", "Missing token")
31
+
32
+ key = self._extract_key(headers=headers, scope=scope)
33
+ if not await self.auth_service.authenticate(token, key):
34
+ await self._send_error(send, 401, "Unauthorized", "Invalid token or rate limit exceeded")
35
+ return
36
+
37
+ await self.app(scope, receive, send)
38
+
39
+ @staticmethod
40
+ def _get_headers(scope: dict[str, str]) -> dict:
41
+ return {k.lower(): v for k, v in scope.get("headers", [])}
42
+
43
+ @staticmethod
44
+ def _extract_token(headers: dict) -> str | None:
45
+ auth_bytes = headers.get(b"authorization")
46
+ if not auth_bytes:
47
+ return None
48
+ return auth_bytes.decode()
49
+
50
+ @staticmethod
51
+ def _extract_key(headers: dict, scope: dict) -> str:
52
+ client = scope.get("client")
53
+ ip = client[0] if client else "unknown"
54
+ forwarded = headers.get(b"x-forwarded-for")
55
+ if forwarded:
56
+ ip = forwarded.decode().split(",")[0].strip()
57
+ return ip
58
+
59
+ @staticmethod
60
+ async def _send_error(send, status_code: int, error: str, detail: str):
61
+ body = json.dumps({"error": error, "detail": detail}).encode()
62
+ await send({
63
+ "type": "http.response.start",
64
+ "status": status_code,
65
+ "headers": [
66
+ (b"content-type", b"application/json"),
67
+ (b"content-length", str(len(body)).encode()),
68
+ ],
69
+ })
70
+ await send({
71
+ "type": "http.response.body",
72
+ "body": body,
73
+ "more_body": False,
74
+ })
@@ -0,0 +1,40 @@
1
+ import logging
2
+ import time
3
+ from collections import defaultdict
4
+
5
+ from fastmcp_token_guard.core.ports.rate_limiter_port import RateLimiterPort
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class InMemoryRateLimiter(RateLimiterPort):
11
+
12
+ def __init__(self, max_requests: int = 10, window_seconds: float = 60.0, whitelist: set[str] | None = None):
13
+ self.max_requests = max_requests
14
+ self.window_seconds = window_seconds
15
+ self.whitelist = whitelist or set()
16
+ self._requests: dict[str, list[float]] = defaultdict(list)
17
+
18
+ async def is_allowed(self, key: str) -> bool:
19
+ if key in self.whitelist:
20
+ return True
21
+
22
+ now = time.time()
23
+ window_start = now - self.window_seconds
24
+
25
+ self._requests[key] = [
26
+ timestamp for timestamp in self._requests[key]
27
+ if timestamp > window_start
28
+ ]
29
+
30
+ if not self._requests[key]:
31
+ del self._requests[key]
32
+ self._requests[key].append(now)
33
+ return True
34
+
35
+ if len(self._requests[key]) >= self.max_requests:
36
+ logger.warning(f"[ Rate limit exceeded ]: key={key}")
37
+ return False
38
+
39
+ self._requests[key].append(now)
40
+ return True
@@ -0,0 +1,40 @@
1
+ import logging
2
+
3
+ from jose import jwe
4
+ from jose.exceptions import JWEError
5
+
6
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class JWEValidator(TokenValidatorPort):
12
+ SUPPORTED_ALGORITHMS = {"A128KW", "A256KW", "RSA-OAEP", "RSA-OAEP-256"}
13
+ SUPPORTED_ENCRYPTIONS = {"A128GCM", "A256GCM", "A128CBC-HS256", "A256CBC-HS512"}
14
+
15
+ def __init__(self, key: bytes, algorithm: str = "A256KW", encryption: str = "A256GCM"):
16
+ if algorithm not in self.SUPPORTED_ALGORITHMS:
17
+ logger.error(f"Algorithm {algorithm} is not supported")
18
+ raise ValueError(f"Algorithm '{algorithm}' not supported. Use one of {self.SUPPORTED_ALGORITHMS}")
19
+
20
+ if encryption not in self.SUPPORTED_ENCRYPTIONS:
21
+ logger.error(f"Encryption {encryption} is not supported")
22
+ raise ValueError(f"Encryption '{encryption}' not supported. Use one of {self.SUPPORTED_ENCRYPTIONS}")
23
+
24
+ self.key = key
25
+ self.algorithm = algorithm
26
+ self.encryption = encryption
27
+
28
+ async def validate(self, token: str) -> bool:
29
+ return await self.decrypt(token) is not None
30
+
31
+ async def decrypt(self, token: str) -> str | None:
32
+ try:
33
+ payload = jwe.decrypt(token, self.key)
34
+ return payload.decode()
35
+ except JWEError as e:
36
+ logger.warning(f"[ Invalid JWE token received ]: {e}")
37
+ return None
38
+ except Exception as e:
39
+ logger.error(f"[ Unexpected error validating JWE token ]: {e}")
40
+ return None
@@ -0,0 +1,92 @@
1
+ import logging
2
+ import time
3
+
4
+ import httpx
5
+ from jose import jwt, JWTError
6
+
7
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class JWKSValidator(TokenValidatorPort):
13
+
14
+ def __init__(
15
+ self,
16
+ jwks_url: str,
17
+ timeout: float = 5.0,
18
+ cache_ttl_seconds: float = 3600.0,
19
+ refresh_cooldown_seconds: float = 30.0,
20
+ max_refresh_attempts: int = 3,
21
+ ):
22
+ self.jwks_url = jwks_url
23
+ self.timeout = timeout
24
+ self.cache_ttl_seconds = cache_ttl_seconds
25
+ self.refresh_cooldown_seconds = refresh_cooldown_seconds
26
+ self.max_refresh_attempts = max_refresh_attempts
27
+ self._jwks_cache: dict | None = None
28
+ self._cache_expiry: float = 0.0
29
+ self._last_refresh_attempt: float = 0.0
30
+ self._failed_refresh_count: int = 0
31
+
32
+ async def _get_jwks(self, force_refresh: bool = False) -> dict | None:
33
+ now = time.time()
34
+
35
+ if not force_refresh and self._jwks_cache and now < self._cache_expiry:
36
+ return self._jwks_cache
37
+
38
+ if force_refresh and (now - self._last_refresh_attempt) < self.refresh_cooldown_seconds:
39
+ logger.warning("[ JWKS refresh cooldown active ]: using cached keys")
40
+ return self._jwks_cache
41
+
42
+ self._last_refresh_attempt = now
43
+
44
+ try:
45
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
46
+ response = await client.get(self.jwks_url)
47
+ if response.status_code != 200:
48
+ logger.error(f"[ Failed to fetch JWKS ]: status={response.status_code}")
49
+ return self._jwks_cache
50
+ self._jwks_cache = response.json()
51
+ self._cache_expiry = now + self.cache_ttl_seconds
52
+ return self._jwks_cache
53
+ except httpx.TimeoutException:
54
+ logger.warning(f"[ JWKS fetch timeout ]: {self.jwks_url}")
55
+ return self._jwks_cache
56
+ except Exception as e:
57
+ logger.error(f"[ Unexpected error fetching JWKS ]: {e}")
58
+ return self._jwks_cache
59
+
60
+ async def validate(self, token: str) -> bool:
61
+ parts = token.split(" ", 1)
62
+ raw_token = parts[1] if len(parts) == 2 else token
63
+
64
+ jwks = await self._get_jwks()
65
+ if not jwks:
66
+ return False
67
+
68
+ try:
69
+ jwt.decode(raw_token, jwks, options={"verify_aud": False})
70
+ self._failed_refresh_count = 0
71
+ return True
72
+ except JWTError:
73
+ if self._failed_refresh_count >= self.max_refresh_attempts:
74
+ logger.warning("[ Max JWKS refresh attempts reached ]: blocking further refreshes")
75
+ return False
76
+
77
+ jwks = await self._get_jwks(force_refresh=True)
78
+ self._failed_refresh_count += 1
79
+
80
+ if not jwks:
81
+ return False
82
+
83
+ try:
84
+ jwt.decode(raw_token, jwks, options={"verify_aud": False})
85
+ self._failed_refresh_count = 0
86
+ return True
87
+ except JWTError as e:
88
+ logger.warning(f"[ Invalid JWKS token ]: {e}")
89
+ return False
90
+ except Exception as e:
91
+ logger.error(f"[ Unexpected error validating JWKS token ]: {e}")
92
+ return False
@@ -0,0 +1,30 @@
1
+ import logging
2
+
3
+ from jose import jwt, JWTError
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
8
+
9
+
10
+ class JWTValidator(TokenValidatorPort):
11
+ SUPPORTED_ALGORITHMS = {"HS256", "RS256", "ES256", "HS384", "ES384", "ES512"}
12
+
13
+ def __init__(self, secret_key: str, algorithm: str = "HS256"):
14
+ self.secret_key = secret_key
15
+ self.algorithm = algorithm
16
+
17
+ if self.algorithm not in self.SUPPORTED_ALGORITHMS:
18
+ logger.error(f"Algorithm {self.algorithm} is not supported")
19
+ raise ValueError(f"Algorithm {self.algorithm} is not supported. Use one of {self.SUPPORTED_ALGORITHMS}")
20
+
21
+ async def validate(self, token: str) -> bool:
22
+ try:
23
+ jwt.decode(token, key=self.secret_key, algorithms=list(self.SUPPORTED_ALGORITHMS))
24
+ return True
25
+ except JWTError:
26
+ logger.warning("[ Invalid JWT token received ]")
27
+ return False
28
+ except Exception as e:
29
+ logger.error(f"[ Unexpected error validating JWT token ]: {e}")
30
+ return False
@@ -0,0 +1,45 @@
1
+ import logging
2
+
3
+ import httpx
4
+
5
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class ProxyValidator(TokenValidatorPort):
11
+
12
+ def __init__(self, validation_url: str, timeout: float = 5.0, extra_headers: dict | None = None,
13
+ verify_ssl: bool = True, success_status_codes: list[int] | None = None):
14
+ self.validation_url = validation_url
15
+ self.timeout = timeout
16
+ self.extra_headers = extra_headers or {}
17
+ self.verify_ssl = verify_ssl
18
+ self.success_status_codes = success_status_codes or [200]
19
+
20
+ async def validate(self, token: str) -> bool:
21
+ try:
22
+ headers = {"Authorization": token, **self.extra_headers}
23
+ async with httpx.AsyncClient(
24
+ timeout=self.timeout,
25
+ verify=self.verify_ssl,
26
+ ) as client:
27
+ response = await client.post(
28
+ self.validation_url,
29
+ headers=headers,
30
+ )
31
+ is_valid = response.status_code in self.success_status_codes
32
+ if not is_valid:
33
+ logger.warning(
34
+ f"[ Proxy rejected token ]: status={response.status_code}"
35
+ )
36
+ return is_valid
37
+ except httpx.TimeoutException:
38
+ logger.warning(f"[ Proxy validation timeout ]: {self.validation_url}")
39
+ return False
40
+ except httpx.RequestError as e:
41
+ logger.error(f"[ Proxy validation request error ]: {e}")
42
+ return False
43
+ except Exception as e:
44
+ logger.error(f"[ Unexpected error validating token via proxy ]: {e}")
45
+ return False
@@ -0,0 +1,44 @@
1
+ import logging
2
+ import time
3
+
4
+ from fastmcp_token_guard.core.ports.rate_limiter_port import RateLimiterPort
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class RedisRateLimiter(RateLimiterPort):
10
+
11
+ def __init__(self, redis_client, max_requests: int = 10, window_seconds: float = 60.0,
12
+ whitelist: set[str] | None = None, key_prefix: str = "mcp_guard:rate_limit:", fail_open: bool = True):
13
+ self.redis_client = redis_client
14
+ self.max_requests = max_requests
15
+ self.window_seconds = window_seconds
16
+ self.whitelist = whitelist or set()
17
+ self.key_prefix = key_prefix
18
+ self.fail_open = fail_open
19
+
20
+ async def is_allowed(self, key: str) -> bool:
21
+ if key in self.whitelist:
22
+ return True
23
+
24
+ redis_key = f"{self.key_prefix}{key}"
25
+ now = time.time()
26
+ window_start = now - self.window_seconds
27
+
28
+ try:
29
+ async with self.redis_client.pipeline() as pipe:
30
+ await pipe.zremrangebyscore(redis_key, 0, window_start)
31
+ await pipe.zcard(redis_key)
32
+ await pipe.zadd(redis_key, {str(now): now})
33
+ await pipe.expire(redis_key, int(self.window_seconds))
34
+ results = await pipe.execute()
35
+
36
+ count = results[1]
37
+ if count >= self.max_requests:
38
+ logger.warning(f"[ Rate limit exceeded ]: key={key}")
39
+ return False
40
+
41
+ return True
42
+ except Exception as e:
43
+ logger.error(f"[ Redis rate limiter error ]: {e}")
44
+ return self.fail_open
@@ -0,0 +1,31 @@
1
+ import logging
2
+ from functools import lru_cache
3
+
4
+ from pydantic_settings import BaseSettings, SettingsConfigDict
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class Settings(BaseSettings):
10
+ MCP_GUARD_SECRET_KEY: str = ""
11
+ MCP_GUARD_ALGORITHM: str = "HS256"
12
+ MCP_GUARD_PROXY_URL: str = ""
13
+ MCP_GUARD_JWKS_URL: str = ""
14
+ MCP_GUARD_JWKS_CACHE_TTL_SECONDS: float = 3600.0
15
+ MCP_GUARD_JWKS_REFRESH_COOLDOWN_SECONDS: float = 30.0
16
+ MCP_GUARD_JWKS_MAX_REFRESH_ATTEMPTS: int = 3
17
+ MCP_GUARD_MAX_REQUESTS: int = 10
18
+ MCP_GUARD_WINDOW_SECONDS: float = 60.0
19
+ MCP_GUARD_EXCLUDE_PATHS: list[str] = ["/healthcheck"]
20
+
21
+ model_config = SettingsConfigDict(
22
+ env_prefix="",
23
+ env_file=".env",
24
+ env_file_encoding="utf-8",
25
+ extra="ignore",
26
+ )
27
+
28
+
29
+ @lru_cache()
30
+ def get_settings() -> Settings:
31
+ return Settings()
@@ -0,0 +1,14 @@
1
+ from fastmcp_token_guard.core.ports.rate_limiter_port import RateLimiterPort
2
+ from fastmcp_token_guard.core.ports.token_validator_port import TokenValidatorPort
3
+
4
+
5
+ class AuthService:
6
+
7
+ def __init__(self, token_validator: TokenValidatorPort, rate_limiter: RateLimiterPort | None):
8
+ self.token_validator = token_validator
9
+ self.rate_limiter = rate_limiter
10
+
11
+ async def authenticate(self, token: str, key: str) -> bool:
12
+ if self.rate_limiter and not await self.rate_limiter.is_allowed(key=key):
13
+ return False
14
+ return await self.token_validator.validate(token=token)
@@ -0,0 +1,8 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class RateLimiterPort(ABC):
5
+
6
+ @abstractmethod
7
+ async def is_allowed(self, key: str) -> bool: ...
8
+
@@ -0,0 +1,7 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class TokenValidatorPort(ABC):
5
+
6
+ @abstractmethod
7
+ async def validate(self, token: str) -> bool: ...