deapi-mcp 0.7.0__py3-none-any.whl

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.
@@ -0,0 +1,466 @@
1
+ """HTTP client for deAPI with authentication forwarding and retry logic."""
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from typing import IO, Any, Dict, Optional, Tuple, Union, cast
5
+
6
+ import httpx
7
+
8
+ # Low-level request client from the deAPI SDK. These are SDK-internal modules for
9
+ # now; promote them to the SDK's public API in a later SDK release. The MCP keeps
10
+ # its own client surface (below) and delegates only transport, retry and auth
11
+ # forwarding to the SDK, so tool code is unchanged.
12
+ from deapi_sdk._client import AsyncHTTPClient
13
+ from deapi_sdk._config import ClientConfig
14
+ from deapi_sdk._exceptions import DeapiError as SdkError
15
+ from deapi_sdk._exceptions import NetworkError as SdkNetworkError
16
+
17
+ from .config import settings
18
+ from .observability import note_api_error, note_network_error
19
+ from .schemas import (
20
+ BalanceResponse,
21
+ JobRequestResponse,
22
+ JobStatusResponse,
23
+ ModelsResponse,
24
+ )
25
+ from .webhooks import get_job_registry, internal_webhooks_enabled
26
+
27
+ # The models endpoint caps `limit` at 50 server-side and defaults to 25.
28
+ # Requesting the cap keeps the number of round trips low; the page loop in
29
+ # get_models() is what guarantees completeness.
30
+ MODELS_PAGE_SIZE = 50
31
+
32
+ # Multipart uploads in either shape httpx accepts: a mapping of field name to
33
+ # (filename, content, mime type), or a sequence of (field name, that tuple) pairs,
34
+ # which allows a repeated field. Content is raw bytes or a binary file object.
35
+ UploadPart = Tuple[str, Union[bytes, IO[bytes]], str]
36
+ UploadFiles = Union[Mapping[str, UploadPart], Sequence[Tuple[str, UploadPart]]]
37
+
38
+ # Mirrors the deAPI API's webhook validation rules:
39
+ # webhook_url nullable|url:https|max:2048|required_with:webhook_secret
40
+ # webhook_secret sometimes|nullable|string|min:32|max:255
41
+ WEBHOOK_SECRET_MIN_LENGTH = 32
42
+ WEBHOOK_SECRET_MAX_LENGTH = 255
43
+ WEBHOOK_URL_MAX_LENGTH = 2048
44
+
45
+ # Appended to a 401 from deAPI: the key was refused, and reconnecting is the fix.
46
+ KEY_REFUSED_HINT = (
47
+ "deAPI did not accept the API key (revoked, deleted or mistyped). Reconnect with a valid "
48
+ "key from https://app.deapi.ai/settings/api-keys."
49
+ )
50
+
51
+
52
+ def _error_message(body: Dict[str, Any], fallback: str) -> str:
53
+ """The most specific reason an error body gives.
54
+
55
+ Laravel's own 422 summary only repeats the first field error ("... (and 1
56
+ more error)"), and some endpoints answer "The given data was invalid." or a
57
+ bare `{"error": ...}`, leaving the actual cause in `errors`. The caller can
58
+ only fix what it is told, so every field message is included.
59
+ """
60
+ message = body.get("message") or body.get("error")
61
+ if not isinstance(message, str) or not message:
62
+ message = fallback
63
+
64
+ details = []
65
+ errors = body.get("errors")
66
+ if isinstance(errors, dict):
67
+ for field, msgs in errors.items():
68
+ for msg in msgs if isinstance(msgs, list) else [msgs]:
69
+ details.append(f"{field}: {msg}")
70
+ if not details or len(details) == 1 and details[0].endswith(message):
71
+ return message
72
+ return f"{message} [{'; '.join(details)}]"
73
+
74
+
75
+ class DeapiAPIError(Exception):
76
+ """Custom exception for deAPI errors."""
77
+
78
+ def __init__(
79
+ self,
80
+ message: str,
81
+ status_code: Optional[int] = None,
82
+ response: Optional[Dict[str, Any]] = None,
83
+ ):
84
+ super().__init__(message)
85
+ self.status_code = status_code
86
+ self.response = response
87
+ note_api_error(status_code, response)
88
+
89
+
90
+ class DeapiRequestError(DeapiAPIError):
91
+ """A request rejected on this side before it was sent.
92
+
93
+ Raised by the checks that mirror the API's own validation rules, so the
94
+ caller sees the same 422-style message it would have got from the server,
95
+ without the round trip. Being a DeapiAPIError, every tool already reports
96
+ it as an API error rather than an unexpected one.
97
+ """
98
+
99
+ def __init__(self, message: str):
100
+ super().__init__(message, status_code=422)
101
+
102
+
103
+ def webhook_payload_fields(
104
+ webhook_url: Optional[str], webhook_secret: Optional[str]
105
+ ) -> Dict[str, str]:
106
+ """Return the webhook fields to add to a job payload, validated locally.
107
+
108
+ The API enforces these rules itself, but a 422 arriving after the caller
109
+ has assembled a whole request is a poor way to learn a secret is too short.
110
+ Checking here gives one clear message and no wasted round trip.
111
+
112
+ Returns an empty dict when neither value is given.
113
+ """
114
+ if not webhook_url and not webhook_secret:
115
+ return {}
116
+
117
+ if webhook_secret and not webhook_url:
118
+ raise DeapiRequestError("webhook_secret requires webhook_url")
119
+
120
+ assert webhook_url # both early exits above leave a non-empty URL here
121
+ if not webhook_url.lower().startswith("https://"):
122
+ raise DeapiRequestError("webhook_url must use https")
123
+ if len(webhook_url) > WEBHOOK_URL_MAX_LENGTH:
124
+ raise DeapiRequestError(f"webhook_url must be at most {WEBHOOK_URL_MAX_LENGTH} characters")
125
+
126
+ fields = {"webhook_url": webhook_url}
127
+ if webhook_secret:
128
+ if not WEBHOOK_SECRET_MIN_LENGTH <= len(webhook_secret) <= WEBHOOK_SECRET_MAX_LENGTH:
129
+ raise DeapiRequestError(
130
+ f"webhook_secret must be {WEBHOOK_SECRET_MIN_LENGTH}-"
131
+ f"{WEBHOOK_SECRET_MAX_LENGTH} characters"
132
+ )
133
+ fields["webhook_secret"] = webhook_secret
134
+ return fields
135
+
136
+
137
+ # One shared httpx.AsyncClient (connection pool) for the whole process, injected
138
+ # into every per-request SDK client so users share a single transport instead of
139
+ # each request opening its own pool. Auth is sent per request by the SDK client,
140
+ # so one transport safely serves every user.
141
+ _shared_http: Optional[httpx.AsyncClient] = None
142
+
143
+
144
+ def _shared_http_client() -> httpx.AsyncClient:
145
+ global _shared_http
146
+ if _shared_http is None or _shared_http.is_closed:
147
+ _shared_http = httpx.AsyncClient(timeout=httpx.Timeout(settings.http_timeout))
148
+ return _shared_http
149
+
150
+
151
+ async def aclose_shared_http_client() -> None:
152
+ """Close the shared transport. Call once on server shutdown."""
153
+ global _shared_http
154
+ if _shared_http is not None and not _shared_http.is_closed:
155
+ await _shared_http.aclose()
156
+ _shared_http = None
157
+
158
+
159
+ class DeapiClient:
160
+ """Async client for the deAPI REST API.
161
+
162
+ Keeps the MCP's own request surface (submit_job, get_job_status, ...) and
163
+ delegates transport to the deAPI SDK's HTTP client over a shared connection
164
+ pool, with per-request auth, safe retries and a capped Retry-After.
165
+ """
166
+
167
+ def __init__(self, api_token: str):
168
+ """Initialize deAPI client with user's API token.
169
+
170
+ Args:
171
+ api_token: User's deAPI Bearer token
172
+ """
173
+ self.api_token = api_token
174
+ self.base_url = settings.deapi_api_base_url
175
+ self.api_version = settings.deapi_api_version
176
+ self._http: Optional[AsyncHTTPClient] = None
177
+
178
+ async def __aenter__(self) -> "DeapiClient":
179
+ """Async context manager entry."""
180
+ config = ClientConfig(
181
+ api_key=self.api_token,
182
+ base_url=self.base_url,
183
+ timeout=settings.http_timeout,
184
+ max_retries=settings.max_retries,
185
+ api_version=self.api_version,
186
+ )
187
+ # Share the process-wide transport; auth rides each request, so the pool
188
+ # is safe to reuse across users. We don't own it, so our close is a no-op.
189
+ self._http = AsyncHTTPClient(config, _shared_http_client(), owns_http_client=False)
190
+ return self
191
+
192
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
193
+ """Async context manager exit. The transport is shared, so nothing to close."""
194
+ self._http = None
195
+
196
+ async def _send(
197
+ self,
198
+ method: str,
199
+ endpoint: str,
200
+ data: Optional[Dict[str, Any]] = None,
201
+ json_data: Optional[Dict[str, Any]] = None,
202
+ files: Optional[UploadFiles] = None,
203
+ params: Optional[Dict[str, Any]] = None,
204
+ ) -> Dict[str, Any]:
205
+ """Send one request over the shared SDK transport.
206
+
207
+ The SDK client forwards auth per request, retries only what is safe to
208
+ resend (never a POST that may have reached the server) and caps the
209
+ honoured Retry-After. A non-2xx response arrives as a typed SDK error,
210
+ translated here to DeapiAPIError (preserving the message the tools show);
211
+ a transport failure propagates for _request to note and re-raise.
212
+ """
213
+ if self._http is None:
214
+ raise RuntimeError("Client not initialized. Use async context manager.")
215
+
216
+ url = f"{self.base_url}/api/{self.api_version}/{endpoint}"
217
+ try:
218
+ return cast(
219
+ Dict[str, Any],
220
+ await self._http.request(
221
+ method,
222
+ url,
223
+ json=json_data,
224
+ data=data,
225
+ files=files,
226
+ params=params,
227
+ ),
228
+ )
229
+ except SdkNetworkError:
230
+ raise
231
+ except SdkError as exc:
232
+ body = exc.body if isinstance(exc.body, dict) else None
233
+ status = exc.status_code
234
+ if body is not None:
235
+ message = _error_message(body, f"HTTP {status}" if status else str(exc))
236
+ else:
237
+ message = exc.message or (f"HTTP {status}" if status else str(exc))
238
+ if status == 401:
239
+ # The key itself is refused (revoked, deleted or wrong). Remember it, so the
240
+ # client's next request fails authentication and it signs in again, and
241
+ # say what to do instead of a bare "Unauthenticated.".
242
+ from .key_verifier import note_key_refused
243
+
244
+ note_key_refused(self.api_token)
245
+ message = f"{message} {KEY_REFUSED_HINT}"
246
+ raise DeapiAPIError(message=message, status_code=status, response=body) from exc
247
+
248
+ async def _request(
249
+ self,
250
+ method: str,
251
+ endpoint: str,
252
+ data: Optional[Dict[str, Any]] = None,
253
+ json_data: Optional[Dict[str, Any]] = None,
254
+ files: Optional[UploadFiles] = None,
255
+ params: Optional[Dict[str, Any]] = None,
256
+ ) -> Dict[str, Any]:
257
+ """Send a request, noting a transport failure for the call's outcome."""
258
+ try:
259
+ return await self._send(
260
+ method, endpoint, data=data, json_data=json_data, files=files, params=params
261
+ )
262
+ except SdkNetworkError:
263
+ note_network_error()
264
+ raise
265
+
266
+ async def submit_job(
267
+ self,
268
+ endpoint: str,
269
+ data: Optional[Dict[str, Any]] = None,
270
+ json_data: Optional[Dict[str, Any]] = None,
271
+ files: Optional[UploadFiles] = None,
272
+ webhook_url: Optional[str] = None,
273
+ webhook_secret: Optional[str] = None,
274
+ ) -> JobRequestResponse:
275
+ """Submit a job to deAPI.
276
+
277
+ Args:
278
+ endpoint: API endpoint (e.g., 'audio/transcriptions', 'images/generations')
279
+ data: Form data
280
+ json_data: JSON data
281
+ files: Files for upload
282
+ webhook_url: HTTPS URL the API calls when the job finishes. Belongs to
283
+ the caller, not to this server: the tool still polls and returns
284
+ the result as usual, and the webhook is a side effect for the
285
+ caller's own systems.
286
+ webhook_secret: Key the API uses to sign the callback
287
+ (HMAC-SHA256 over timestamp + "." + body). Requires webhook_url.
288
+
289
+ Returns:
290
+ JobRequestResponse with request_id
291
+
292
+ Raises:
293
+ DeapiRequestError: If the webhook fields break a rule the API would
294
+ reject with a 422 (e.g. webhook_secret without webhook_url).
295
+ Failing here keeps the message readable and saves the round trip.
296
+ """
297
+ webhook_fields: Mapping[str, Optional[str]] = webhook_payload_fields(
298
+ webhook_url, webhook_secret
299
+ )
300
+
301
+ # The API takes one webhook per job. A caller's own URL always wins;
302
+ # only when they gave none do we register ourselves, so the tool can
303
+ # wait on the callback instead of polling.
304
+ use_internal = not webhook_fields and internal_webhooks_enabled()
305
+ if use_internal:
306
+ webhook_fields = {
307
+ "webhook_url": settings.webhook_receiver_url,
308
+ "webhook_secret": settings.webhook_secret,
309
+ }
310
+
311
+ if webhook_fields:
312
+ # Whichever body the tool built is the one the API will read; add the
313
+ # webhook fields to that one rather than introducing a second body.
314
+ if json_data is not None:
315
+ json_data = {**json_data, **webhook_fields}
316
+ else:
317
+ data = {**(data or {}), **webhook_fields}
318
+
319
+ response_data = await self._request(
320
+ method="POST",
321
+ endpoint=endpoint,
322
+ data=data,
323
+ json_data=json_data,
324
+ files=files,
325
+ )
326
+ response = JobRequestResponse(**response_data)
327
+
328
+ if use_internal:
329
+ # Tracking after submit is safe: a callback that beats us here is
330
+ # kept by the registry and found already set.
331
+ get_job_registry().track(response.data.request_id)
332
+
333
+ return response
334
+
335
+ async def get_job_status(self, job_id: str) -> JobStatusResponse:
336
+ """Get status of a submitted job.
337
+
338
+ Args:
339
+ job_id: Job request ID (UUID)
340
+
341
+ Returns:
342
+ JobStatusResponse with current status and result
343
+ """
344
+ response_data = await self._request(
345
+ method="GET",
346
+ endpoint=f"jobs/{job_id}",
347
+ )
348
+ return JobStatusResponse(**response_data)
349
+
350
+ async def get_balance(self) -> BalanceResponse:
351
+ """Get user's account balance.
352
+
353
+ Returns:
354
+ BalanceResponse with current balance
355
+ """
356
+ response_data = await self._request(
357
+ method="GET",
358
+ endpoint="account/balance",
359
+ )
360
+ return BalanceResponse(**response_data)
361
+
362
+ async def get_models(self) -> ModelsResponse:
363
+ """Get list of available models, following pagination to the last page.
364
+
365
+ The endpoint is paginated and defaults to 25 items per page, while the API
366
+ caps `limit` at 50 server-side (`min($request->input('limit', 25), 50)`).
367
+ Requesting a large limit is therefore not sufficient on its own — once the
368
+ catalogue exceeds the cap, a single request silently truncates again. The
369
+ page loop is what actually makes this correct.
370
+
371
+ Returns:
372
+ ModelsResponse whose `data` holds every model across all pages, and
373
+ whose `meta` is the first page's — `total` and `last_page` describe
374
+ the whole catalogue, so they stay accurate after the pages are joined.
375
+ """
376
+ first_page = await self._request(
377
+ method="GET",
378
+ endpoint="models",
379
+ params={"limit": MODELS_PAGE_SIZE},
380
+ )
381
+ response = ModelsResponse(**first_page)
382
+
383
+ last_page = response.meta.last_page if response.meta else None
384
+ if not last_page or last_page <= 1:
385
+ return response
386
+
387
+ for page in range(2, last_page + 1):
388
+ page_data = await self._request(
389
+ method="GET",
390
+ endpoint="models",
391
+ params={"limit": MODELS_PAGE_SIZE, "page": page},
392
+ )
393
+ response.data.extend(ModelsResponse(**page_data).data)
394
+
395
+ return response
396
+
397
+ async def calculate_price(
398
+ self,
399
+ endpoint: str,
400
+ data: Optional[Dict[str, Any]] = None,
401
+ json_data: Optional[Dict[str, Any]] = None,
402
+ files: Optional[UploadFiles] = None,
403
+ ) -> Dict[str, Any]:
404
+ """Calculate price for an operation.
405
+
406
+ Args:
407
+ endpoint: Price calculation endpoint (e.g., 'images/generations/price')
408
+ data: Form data
409
+ json_data: JSON data
410
+ files: Files for upload
411
+
412
+ Returns:
413
+ Price calculation response
414
+ """
415
+ return await self._request(
416
+ method="POST",
417
+ endpoint=endpoint,
418
+ data=data,
419
+ json_data=json_data,
420
+ files=files,
421
+ )
422
+
423
+ async def post_sync(
424
+ self,
425
+ endpoint: str,
426
+ data: Optional[Dict[str, Any]] = None,
427
+ json_data: Optional[Dict[str, Any]] = None,
428
+ files: Optional[UploadFiles] = None,
429
+ ) -> Dict[str, Any]:
430
+ """POST to a synchronous (non-job) endpoint and return the raw response.
431
+
432
+ For endpoints that return a result directly instead of a job_id (e.g.,
433
+ prompt enhancements). Same retry/error semantics as submit_job.
434
+ """
435
+ return await self._request(
436
+ method="POST",
437
+ endpoint=endpoint,
438
+ data=data,
439
+ json_data=json_data,
440
+ files=files,
441
+ )
442
+
443
+
444
+ def get_client(api_token: Optional[str] = None) -> DeapiClient:
445
+ """Get a new deAPI client instance.
446
+
447
+ If no api_token is provided, attempts to get it from the request context
448
+ (set by authentication middleware).
449
+
450
+ Args:
451
+ api_token: Optional deAPI Bearer token. If not provided,
452
+ uses token from authentication context.
453
+
454
+ Returns:
455
+ DeapiClient instance ready for use with async context manager
456
+
457
+ Raises:
458
+ ValueError: If no token available in context and none provided
459
+ """
460
+ if api_token is None:
461
+ # Try to get token from auth context
462
+ from .auth import get_current_token
463
+
464
+ api_token = get_current_token()
465
+
466
+ return DeapiClient(api_token)
@@ -0,0 +1,227 @@
1
+ """FastMCP-compatible authentication provider for deAPI MCP Server.
2
+
3
+ This module implements FastMCP's AuthProvider interface to properly integrate
4
+ JWT/Bearer token authentication into the MCP server.
5
+ """
6
+
7
+ import json
8
+ import re
9
+ from typing import Any
10
+
11
+ from fastmcp.server.auth import AccessToken, AuthProvider
12
+ from starlette.routing import Route
13
+
14
+ from .auth import current_deapi_token
15
+ from .key_verifier import is_api_key_rejected, is_key_known_invalid
16
+ from .oauth_endpoints import (
17
+ decode_jwt,
18
+ decrypt_token,
19
+ is_jwt,
20
+ oauth_protected_resource_metadata,
21
+ )
22
+
23
+ API_KEY_HEADER = b"x-api-key"
24
+
25
+
26
+ class ApiKeyHeaderMiddleware:
27
+ """Accept the deAPI key in ``X-API-Key`` as well as ``Authorization: Bearer``.
28
+
29
+ Some clients only let a user set one named header for a key. When a request
30
+ carries ``X-API-Key`` and no ``Authorization``, this rewrites it to
31
+ ``Authorization: Bearer <key>`` before authentication runs, so the key goes
32
+ through exactly the same checks (``DeapiAuthProvider.verify_token``). A request
33
+ that carries both keeps its ``Authorization`` header untouched.
34
+ """
35
+
36
+ def __init__(self, app: Any) -> None:
37
+ self.app = app
38
+
39
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
40
+ if scope["type"] == "http" and scope.get("path", "").startswith("/mcp"):
41
+ headers = scope.get("headers") or []
42
+ if not any(name == b"authorization" for name, _ in headers):
43
+ key = next((value for name, value in headers if name == API_KEY_HEADER), b"")
44
+ key = key.strip()
45
+ if key:
46
+ scope = dict(scope)
47
+ scope["headers"] = [*headers, (b"authorization", b"Bearer " + key)]
48
+ await self.app(scope, receive, send)
49
+
50
+
51
+ # Shown to the user by clients that surface error_description. No double quotes: it sits
52
+ # inside a quoted WWW-Authenticate parameter.
53
+ INVALID_TOKEN_DESCRIPTION = (
54
+ "The deAPI API key or access token was not accepted. Check the key at "
55
+ "https://app.deapi.ai/settings/api-keys, or sign in again if you connected with OAuth."
56
+ )
57
+ _DESCRIPTION_PARAM = re.compile(rb'error_description="[^"]*"')
58
+
59
+
60
+ class InvalidTokenDescriptionMiddleware:
61
+ """Replace FastMCP's text in a 401 ``invalid_token`` answer on /mcp with ours.
62
+
63
+ FastMCP tells the client to "re-register and obtain new tokens", which suits a
64
+ server with dynamic client registration. This one has none: the fix is a working
65
+ API key, or signing in again with the pre-registered client. Status, error code
66
+ and ``resource_metadata`` are kept; only ``error_description`` changes, in the
67
+ ``WWW-Authenticate`` header and in the JSON body.
68
+ """
69
+
70
+ def __init__(self, app: Any) -> None:
71
+ self.app = app
72
+
73
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
74
+ if scope["type"] != "http" or not scope.get("path", "").startswith("/mcp"):
75
+ await self.app(scope, receive, send)
76
+ return
77
+
78
+ replaced = False
79
+
80
+ async def rewriting_send(message: Any) -> None:
81
+ nonlocal replaced
82
+ if replaced:
83
+ return # the original body; ours has been sent already
84
+ if message["type"] == "http.response.start" and message["status"] == 401:
85
+ headers = list(message.get("headers") or [])
86
+ challenge = next((v for k, v in headers if k.lower() == b"www-authenticate"), b"")
87
+ if b'error="invalid_token"' in challenge:
88
+ body = json.dumps(
89
+ {"error": "invalid_token", "error_description": INVALID_TOKEN_DESCRIPTION}
90
+ ).encode()
91
+ description = f'error_description="{INVALID_TOKEN_DESCRIPTION}"'.encode()
92
+ rewritten = []
93
+ for name, value in headers:
94
+ lower = name.lower()
95
+ if lower == b"www-authenticate":
96
+ value = _DESCRIPTION_PARAM.sub(lambda _: description, value)
97
+ elif lower == b"content-length":
98
+ value = str(len(body)).encode()
99
+ rewritten.append((name, value))
100
+ replaced = True
101
+ await send({**message, "headers": rewritten})
102
+ await send({"type": "http.response.body", "body": body})
103
+ return
104
+ await send(message)
105
+
106
+ await self.app(scope, receive, rewriting_send)
107
+
108
+
109
+ class DeapiAuthProvider(AuthProvider):
110
+ """FastMCP AuthProvider for deAPI token passthrough.
111
+
112
+ This provider:
113
+ 1. Accepts Bearer tokens (JWT or plain deAPI tokens)
114
+ 2. Extracts deAPI token from JWT if applicable
115
+ 3. Stores it in context for tools to use
116
+ 4. Validates a JWT by its signature, and a plain key by asking the API once
117
+ (cached; see key_verifier.py). An API outage lets a plain key through.
118
+ """
119
+
120
+ def __init__(self, base_url: str | None = None):
121
+ """Initialize the deAPI auth provider.
122
+
123
+ Args:
124
+ base_url: Base URL of the server (optional)
125
+ """
126
+ super().__init__(base_url=base_url)
127
+
128
+ def get_routes(self, mcp_path: str | None = None) -> list[Route]:
129
+ # fastmcp >= 4.1 puts resource_metadata in the 401 challenge only when the
130
+ # provider itself serves the RFC 9728 metadata route.
131
+ return [
132
+ Route(
133
+ "/.well-known/oauth-protected-resource",
134
+ oauth_protected_resource_metadata,
135
+ methods=["GET"],
136
+ ),
137
+ Route(
138
+ "/.well-known/oauth-protected-resource/mcp",
139
+ oauth_protected_resource_metadata,
140
+ methods=["GET"],
141
+ ),
142
+ *super().get_routes(mcp_path),
143
+ ]
144
+
145
+ async def verify_token(self, token: str | None) -> AccessToken | None:
146
+ """Verify a bearer token and return access info if valid.
147
+
148
+ This method is called by FastMCP for every authenticated request.
149
+
150
+ Args:
151
+ token: The token string to validate (without "Bearer " prefix)
152
+
153
+ Returns:
154
+ AccessToken object if valid, None if invalid
155
+ """
156
+ import logging
157
+
158
+ from .observability import record_auth_rejected
159
+
160
+ logger = logging.getLogger(__name__)
161
+
162
+ if token is None:
163
+ logger.error("No Authorization token provided")
164
+ return None
165
+
166
+ try:
167
+ deapi_token = token # Default: use token directly
168
+
169
+ if is_jwt(token):
170
+ # Decode JWT to extract embedded deAPI token
171
+ payload = decode_jwt(token)
172
+ if payload is None:
173
+ logger.error("Invalid or expired JWT token")
174
+ record_auth_rejected("invalid_or_expired")
175
+ return None
176
+
177
+ # Extract and decrypt deAPI token from JWT payload
178
+ encrypted_token = payload.get("deapi_token_enc")
179
+ if not encrypted_token:
180
+ logger.error("JWT missing 'deapi_token_enc' claim")
181
+ record_auth_rejected("bad_claims")
182
+ return None
183
+
184
+ try:
185
+ deapi_token = decrypt_token(encrypted_token)
186
+ except Exception:
187
+ logger.error("Failed to decrypt deapi token from JWT")
188
+ record_auth_rejected("bad_claims")
189
+ return None
190
+
191
+ # deAPI refused this key on a recent call (revoked or deleted): end the
192
+ # session now, so the client refreshes, is refused, and signs in again.
193
+ # A memory read only: no request to deAPI on this path.
194
+ if is_key_known_invalid(deapi_token):
195
+ logger.warning("Access token for an API key deAPI refuses")
196
+ record_auth_rejected("invalid_key")
197
+ return None
198
+ elif await is_api_key_rejected(token):
199
+ # A plain key carries no signature, so the API is asked once whether
200
+ # it knows the key. A refusal here makes the client prompt for a new
201
+ # key now, instead of every tool call failing later.
202
+ logger.warning("Plain API key rejected by deAPI")
203
+ record_auth_rejected("invalid_key")
204
+ return None
205
+
206
+ # Store deAPI token in context for tools to access
207
+ current_deapi_token.set(deapi_token)
208
+
209
+ return AccessToken(
210
+ client_id="deapi-mcp",
211
+ token=deapi_token,
212
+ scopes=[],
213
+ )
214
+
215
+ except Exception as e:
216
+ logger.error(f"Token verification failed: {str(e)}")
217
+ record_auth_rejected("error")
218
+ return None
219
+
220
+ def get_middleware(self) -> list[Any]:
221
+ """Get HTTP middleware for this auth provider.
222
+
223
+ Returns:
224
+ List of Starlette Middleware instances
225
+ """
226
+ # Return FastMCP's default middleware which uses our verify_token method
227
+ return super().get_middleware()