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.
- deapi_mcp/__init__.py +24 -0
- deapi_mcp/auth.py +33 -0
- deapi_mcp/auth_code_store.py +226 -0
- deapi_mcp/config.py +297 -0
- deapi_mcp/consent.py +549 -0
- deapi_mcp/deapi_client.py +466 -0
- deapi_mcp/fastmcp_auth.py +227 -0
- deapi_mcp/key_verifier.py +225 -0
- deapi_mcp/landing.py +431 -0
- deapi_mcp/middleware.py +756 -0
- deapi_mcp/oauth_clients.py +443 -0
- deapi_mcp/oauth_endpoints.py +973 -0
- deapi_mcp/observability.py +199 -0
- deapi_mcp/polling_manager.py +319 -0
- deapi_mcp/py.typed +0 -0
- deapi_mcp/schemas.py +397 -0
- deapi_mcp/server_remote.py +416 -0
- deapi_mcp/tools/__init__.py +0 -0
- deapi_mcp/tools/_price_helpers.py +167 -0
- deapi_mcp/tools/_responses.py +157 -0
- deapi_mcp/tools/audio.py +1195 -0
- deapi_mcp/tools/embedding.py +102 -0
- deapi_mcp/tools/image.py +884 -0
- deapi_mcp/tools/prompt.py +155 -0
- deapi_mcp/tools/utility.py +230 -0
- deapi_mcp/tools/video.py +1117 -0
- deapi_mcp/utils.py +666 -0
- deapi_mcp/webhooks.py +349 -0
- deapi_mcp-0.7.0.dist-info/METADATA +642 -0
- deapi_mcp-0.7.0.dist-info/RECORD +33 -0
- deapi_mcp-0.7.0.dist-info/WHEEL +4 -0
- deapi_mcp-0.7.0.dist-info/entry_points.txt +2 -0
- deapi_mcp-0.7.0.dist-info/licenses/LICENSE +21 -0
deapi_mcp/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""deapi-mcp: the importable, SDK-consuming core of the deAPI MCP server.
|
|
2
|
+
|
|
3
|
+
The package is importable: a deployment can build its own server from this core
|
|
4
|
+
and layer a metrics/observability overlay on top via
|
|
5
|
+
``create_app(server, metrics=...)``. The stock server injects no overlay.
|
|
6
|
+
|
|
7
|
+
Entry points (see :mod:`deapi_mcp.server_remote`):
|
|
8
|
+
- ``register_core_tools(server)`` — register every deAPI tool on a FastMCP instance
|
|
9
|
+
- ``create_app(server=None, *, metrics=None)`` — build the Starlette app; ``metrics``
|
|
10
|
+
is an optional overlay the core never requires
|
|
11
|
+
- ``build_app()`` — the stock server app: the core with no overlay
|
|
12
|
+
- ``main()`` — uvicorn entry point
|
|
13
|
+
|
|
14
|
+
The import package is ``deapi_mcp`` and the distribution is ``deapi-mcp``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
__version__ = version("deapi-mcp")
|
|
21
|
+
except PackageNotFoundError: # running from a source tree that was never installed
|
|
22
|
+
__version__ = "0.0.0+unknown"
|
|
23
|
+
|
|
24
|
+
__all__ = ["__version__"]
|
deapi_mcp/auth.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Authentication context for deAPI MCP Server.
|
|
2
|
+
|
|
3
|
+
Provides a context variable to store and retrieve the deAPI token
|
|
4
|
+
for the current request. The token is set by DeapiAuthProvider during
|
|
5
|
+
authentication and retrieved by tools when calling the deAPI.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from contextvars import ContextVar
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
# Context variable to store the current request's deAPI token
|
|
12
|
+
current_deapi_token: ContextVar[Optional[str]] = ContextVar("deapi_token", default=None)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_current_token() -> str:
|
|
16
|
+
"""Get the deAPI token for the current request.
|
|
17
|
+
|
|
18
|
+
This function retrieves the token from the request context that was
|
|
19
|
+
set by the authentication middleware.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
The deAPI Bearer token
|
|
23
|
+
|
|
24
|
+
Raises:
|
|
25
|
+
ValueError: If no token is available (not authenticated)
|
|
26
|
+
"""
|
|
27
|
+
token = current_deapi_token.get()
|
|
28
|
+
if not token:
|
|
29
|
+
raise ValueError(
|
|
30
|
+
"No deAPI token available. "
|
|
31
|
+
"Please authenticate with 'Authorization: Bearer <your-deapi-token>' header."
|
|
32
|
+
)
|
|
33
|
+
return token
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Single-use OAuth authorization code storage.
|
|
2
|
+
|
|
3
|
+
Codes issued by /authorize must be redeemable on any replica, so the production
|
|
4
|
+
backend is Redis. The in-memory backend keeps single-replica deployments and local
|
|
5
|
+
development working without it.
|
|
6
|
+
|
|
7
|
+
The Redis instance is shared with other applications and runs with noeviction, so
|
|
8
|
+
every key carries a TTL, lives under the configured prefix, and the global cap is
|
|
9
|
+
enforced atomically by a Lua script. Raw codes never appear in key names.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any, Protocol, cast
|
|
17
|
+
|
|
18
|
+
import redis.asyncio as aioredis
|
|
19
|
+
from redis.asyncio.retry import Retry
|
|
20
|
+
from redis.backoff import NoBackoff
|
|
21
|
+
from redis.exceptions import RedisError
|
|
22
|
+
|
|
23
|
+
from .config import Settings, settings
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
# KEYS: code key, index key. ARGV: value, ttl seconds, cap, digest, code key prefix.
|
|
28
|
+
# The index scores each digest with its expiry time, read from the Redis clock (TIME), so
|
|
29
|
+
# pruning lines up with the keys' own TTLs whatever the application host's clock says.
|
|
30
|
+
# The index TTL is only ever extended, so a short-lived code never shortens it below a
|
|
31
|
+
# longer-lived one. This compares PTTL instead of using EXPIRE GT, which needs Redis 7 (GETDEL
|
|
32
|
+
# needs only 6.2) and never sets a TTL on a key that has none; here a missing TTL is restored.
|
|
33
|
+
_PUT_SCRIPT = """
|
|
34
|
+
local ttl = tonumber(ARGV[2])
|
|
35
|
+
local cap = tonumber(ARGV[3])
|
|
36
|
+
if cap <= 0 then return 0 end
|
|
37
|
+
local t = redis.call('TIME')
|
|
38
|
+
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
|
|
39
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now)
|
|
40
|
+
while redis.call('ZCARD', KEYS[2]) >= cap do
|
|
41
|
+
local oldest = redis.call('ZPOPMIN', KEYS[2])
|
|
42
|
+
redis.call('DEL', ARGV[5] .. oldest[1])
|
|
43
|
+
end
|
|
44
|
+
redis.call('SET', KEYS[1], ARGV[1], 'EX', ttl)
|
|
45
|
+
redis.call('ZADD', KEYS[2], now + ttl, ARGV[4])
|
|
46
|
+
if redis.call('PTTL', KEYS[2]) < ttl * 1000 then
|
|
47
|
+
redis.call('EXPIRE', KEYS[2], ttl)
|
|
48
|
+
end
|
|
49
|
+
return 1
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class AuthCodeStoreUnavailable(Exception): # noqa: N818
|
|
54
|
+
"""The backing store could not be reached or rejected the operation."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class AuthCodeStore(Protocol):
|
|
58
|
+
async def put(self, code: str, data: dict[str, Any], ttl_seconds: int) -> bool:
|
|
59
|
+
"""Store a code, evicting the oldest live code when the store is full.
|
|
60
|
+
|
|
61
|
+
The cap bounds memory; eviction keeps a burst of unauthenticated /authorize calls
|
|
62
|
+
from locking real users out. The per-IP ingress rate limit is tracked separately
|
|
63
|
+
for DevOps. Returns False only if the code could not be stored.
|
|
64
|
+
"""
|
|
65
|
+
...
|
|
66
|
+
|
|
67
|
+
async def consume(self, code: str) -> dict[str, Any] | None:
|
|
68
|
+
"""Atomically fetch and delete a code. None if unknown, used or expired."""
|
|
69
|
+
...
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class InMemoryAuthCodeStore:
|
|
73
|
+
def __init__(self, max_entries: int) -> None:
|
|
74
|
+
self._max_entries = max_entries
|
|
75
|
+
self._codes: dict[str, tuple[dict[str, Any], float]] = {}
|
|
76
|
+
|
|
77
|
+
def _prune(self, now: float) -> None:
|
|
78
|
+
for key in [k for k, (_, exp) in self._codes.items() if exp <= now]:
|
|
79
|
+
del self._codes[key]
|
|
80
|
+
|
|
81
|
+
async def put(self, code: str, data: dict[str, Any], ttl_seconds: int) -> bool:
|
|
82
|
+
now = time.time()
|
|
83
|
+
self._prune(now)
|
|
84
|
+
if self._max_entries <= 0:
|
|
85
|
+
return False
|
|
86
|
+
while len(self._codes) >= self._max_entries:
|
|
87
|
+
del self._codes[next(iter(self._codes))] # dicts keep insertion order: oldest first
|
|
88
|
+
self._codes[code] = (data, now + ttl_seconds)
|
|
89
|
+
return True
|
|
90
|
+
|
|
91
|
+
async def consume(self, code: str) -> dict[str, Any] | None:
|
|
92
|
+
entry = self._codes.pop(code, None)
|
|
93
|
+
if entry is None:
|
|
94
|
+
return None
|
|
95
|
+
data, expires = entry
|
|
96
|
+
if expires <= time.time():
|
|
97
|
+
return None
|
|
98
|
+
return data
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class RedisAuthCodeStore:
|
|
102
|
+
def __init__(self, client: aioredis.Redis, prefix: str, max_entries: int) -> None:
|
|
103
|
+
self._client = client
|
|
104
|
+
self._prefix = prefix
|
|
105
|
+
self._max_entries = max_entries
|
|
106
|
+
self._index_key = f"{prefix}oauth_codes_live"
|
|
107
|
+
self._put_script = client.register_script(_PUT_SCRIPT)
|
|
108
|
+
|
|
109
|
+
def _code_key(self, digest: str) -> str:
|
|
110
|
+
return f"{self._prefix}oauth_code:{digest}"
|
|
111
|
+
|
|
112
|
+
@staticmethod
|
|
113
|
+
def _digest(code: str) -> str:
|
|
114
|
+
return hashlib.sha256(code.encode()).hexdigest()
|
|
115
|
+
|
|
116
|
+
async def put(self, code: str, data: dict[str, Any], ttl_seconds: int) -> bool:
|
|
117
|
+
digest = self._digest(code)
|
|
118
|
+
try:
|
|
119
|
+
result = await self._put_script(
|
|
120
|
+
keys=[self._code_key(digest), self._index_key],
|
|
121
|
+
args=[
|
|
122
|
+
json.dumps(data),
|
|
123
|
+
ttl_seconds,
|
|
124
|
+
self._max_entries,
|
|
125
|
+
digest,
|
|
126
|
+
self._code_key(""),
|
|
127
|
+
],
|
|
128
|
+
)
|
|
129
|
+
except RedisError as exc:
|
|
130
|
+
raise AuthCodeStoreUnavailable("Redis auth code store unavailable") from exc
|
|
131
|
+
return int(result) == 1
|
|
132
|
+
|
|
133
|
+
async def consume(self, code: str) -> dict[str, Any] | None:
|
|
134
|
+
digest = self._digest(code)
|
|
135
|
+
try:
|
|
136
|
+
async with self._client.pipeline(transaction=True) as pipe:
|
|
137
|
+
pipe.getdel(self._code_key(digest))
|
|
138
|
+
pipe.zrem(self._index_key, digest)
|
|
139
|
+
raw, _ = await pipe.execute()
|
|
140
|
+
except UnicodeDecodeError:
|
|
141
|
+
# The transaction ran, so the code is already burnt; only its value is unreadable
|
|
142
|
+
return self._corrupt()
|
|
143
|
+
except RedisError as exc:
|
|
144
|
+
raise AuthCodeStoreUnavailable("Redis auth code store unavailable") from exc
|
|
145
|
+
if raw is None:
|
|
146
|
+
return None
|
|
147
|
+
try:
|
|
148
|
+
data = json.loads(raw)
|
|
149
|
+
except ValueError:
|
|
150
|
+
return self._corrupt()
|
|
151
|
+
if not isinstance(data, dict):
|
|
152
|
+
return self._corrupt()
|
|
153
|
+
return cast(dict[str, Any], data)
|
|
154
|
+
|
|
155
|
+
@staticmethod
|
|
156
|
+
def _corrupt() -> None:
|
|
157
|
+
# Neither the code nor the stored value is logged: both are credentials
|
|
158
|
+
logger.warning("Discarded an unreadable authorization code entry; treating it as unknown")
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def build_redis_client(
|
|
163
|
+
s: Settings,
|
|
164
|
+
*,
|
|
165
|
+
db: int | None = None,
|
|
166
|
+
timeout: float = 2.0,
|
|
167
|
+
retries: int = 1,
|
|
168
|
+
max_connections: int | None = None,
|
|
169
|
+
) -> aioredis.Redis:
|
|
170
|
+
kwargs: dict[str, Any] = {
|
|
171
|
+
"host": s.redis_host,
|
|
172
|
+
"port": s.redis_port,
|
|
173
|
+
"db": s.redis_db if db is None else db,
|
|
174
|
+
"username": s.redis_username,
|
|
175
|
+
"password": s.redis_password.get_secret_value() if s.redis_password else None,
|
|
176
|
+
"socket_connect_timeout": timeout,
|
|
177
|
+
"socket_timeout": timeout,
|
|
178
|
+
# redis-py >= 6 defaults to 3 retries with exponential backoff, which makes a login
|
|
179
|
+
# against an unreachable Redis hang 9-19 s. One immediate retry still survives a
|
|
180
|
+
# stale pooled connection after a managed-Redis restart.
|
|
181
|
+
"retry": Retry(NoBackoff(), retries),
|
|
182
|
+
"decode_responses": True,
|
|
183
|
+
}
|
|
184
|
+
if max_connections is not None:
|
|
185
|
+
kwargs["max_connections"] = max_connections
|
|
186
|
+
if s.redis_scheme == "tls":
|
|
187
|
+
kwargs.update(
|
|
188
|
+
ssl=True,
|
|
189
|
+
ssl_ca_certs=s.redis_ca_file,
|
|
190
|
+
ssl_cert_reqs="required",
|
|
191
|
+
ssl_check_hostname=True,
|
|
192
|
+
)
|
|
193
|
+
return aioredis.Redis(**kwargs)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
_store: AuthCodeStore | None = None
|
|
197
|
+
|
|
198
|
+
AUTHORIZATION_CODE_MAX_ENTRIES = 1000
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def get_auth_code_store() -> AuthCodeStore:
|
|
202
|
+
global _store
|
|
203
|
+
if _store is None:
|
|
204
|
+
if settings.redis_host:
|
|
205
|
+
logger.info(
|
|
206
|
+
"OAuth code store: Redis %s:%s db=%s prefix=%s",
|
|
207
|
+
settings.redis_host,
|
|
208
|
+
settings.redis_port,
|
|
209
|
+
settings.redis_db,
|
|
210
|
+
settings.redis_prefix,
|
|
211
|
+
)
|
|
212
|
+
_store = RedisAuthCodeStore(
|
|
213
|
+
build_redis_client(settings), settings.redis_prefix, AUTHORIZATION_CODE_MAX_ENTRIES
|
|
214
|
+
)
|
|
215
|
+
else:
|
|
216
|
+
logger.warning(
|
|
217
|
+
"OAuth code store: in-memory (DEAPI_REDIS_HOST unset). Authorization codes are "
|
|
218
|
+
"per-process, so this is only safe for a single-replica deployment"
|
|
219
|
+
)
|
|
220
|
+
_store = InMemoryAuthCodeStore(AUTHORIZATION_CODE_MAX_ENTRIES)
|
|
221
|
+
return _store
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def reset_auth_code_store(store: AuthCodeStore | None = None) -> None:
|
|
225
|
+
global _store
|
|
226
|
+
_store = store
|
deapi_mcp/config.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""Configuration management for deAPI MCP Server."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
|
|
6
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PollingConfig(BaseModel):
|
|
10
|
+
"""Configuration for smart adaptive polling based on job type."""
|
|
11
|
+
|
|
12
|
+
initial_delay: float = Field(description="Initial polling delay in seconds")
|
|
13
|
+
max_delay: float = Field(description="Maximum polling delay in seconds")
|
|
14
|
+
timeout: float = Field(description="Maximum time to wait for job completion in seconds")
|
|
15
|
+
backoff_factor: float = Field(default=1.5, description="Multiplier for exponential backoff")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Settings(BaseSettings):
|
|
19
|
+
"""Global settings for deAPI MCP Server."""
|
|
20
|
+
|
|
21
|
+
# deAPI Configuration
|
|
22
|
+
#
|
|
23
|
+
# These two fields already carry the `deapi_` prefix in their name, so the
|
|
24
|
+
# `DEAPI_` env_prefix below would resolve them to DEAPI_DEAPI_API_BASE_URL /
|
|
25
|
+
# DEAPI_DEAPI_API_VERSION. Every doc (.env.example, CLAUDE.md, deployment
|
|
26
|
+
# manifests) advertises the single-prefix names, which were silently ignored:
|
|
27
|
+
# the server kept talking to the production default no matter what was set.
|
|
28
|
+
# The explicit aliases make the documented names authoritative and keep the
|
|
29
|
+
# accidental double-prefix form working for anything already using it.
|
|
30
|
+
deapi_api_base_url: str = Field(
|
|
31
|
+
default="https://api.deapi.ai",
|
|
32
|
+
validation_alias=AliasChoices("DEAPI_API_BASE_URL", "DEAPI_DEAPI_API_BASE_URL"),
|
|
33
|
+
description="Base URL for deAPI REST API",
|
|
34
|
+
)
|
|
35
|
+
deapi_api_version: str = Field(
|
|
36
|
+
default="v2",
|
|
37
|
+
validation_alias=AliasChoices("DEAPI_API_VERSION", "DEAPI_DEAPI_API_VERSION"),
|
|
38
|
+
description="API version",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# HTTP Client Configuration
|
|
42
|
+
http_timeout: float = Field(default=30.0, description="HTTP request timeout in seconds")
|
|
43
|
+
max_retries: int = Field(
|
|
44
|
+
default=3, description="Maximum number of retry attempts for failed requests"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Polling Configuration by Job Type
|
|
48
|
+
polling_audio: PollingConfig = Field(
|
|
49
|
+
default=PollingConfig(initial_delay=1.0, max_delay=5.0, timeout=300.0), # 5 minutes
|
|
50
|
+
description="Polling config for audio transcription jobs",
|
|
51
|
+
)
|
|
52
|
+
polling_image: PollingConfig = Field(
|
|
53
|
+
default=PollingConfig(initial_delay=2.0, max_delay=8.0, timeout=300.0), # 5 minutes
|
|
54
|
+
description="Polling config for image generation jobs",
|
|
55
|
+
)
|
|
56
|
+
polling_video: PollingConfig = Field(
|
|
57
|
+
default=PollingConfig(initial_delay=5.0, max_delay=30.0, timeout=900.0), # 15 minutes
|
|
58
|
+
description="Polling config for video generation jobs",
|
|
59
|
+
)
|
|
60
|
+
polling_embedding: PollingConfig = Field(
|
|
61
|
+
default=PollingConfig(initial_delay=0.5, max_delay=3.0, timeout=120.0), # 2 minutes
|
|
62
|
+
description="Polling config for embedding jobs",
|
|
63
|
+
)
|
|
64
|
+
polling_default: PollingConfig = Field(
|
|
65
|
+
default=PollingConfig(initial_delay=2.0, max_delay=10.0, timeout=300.0), # 5 minutes
|
|
66
|
+
description="Default polling config for other job types",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# How long one tool call waits for its job before handing back the job_id.
|
|
70
|
+
#
|
|
71
|
+
# A job can run for an hour (a long video description, a long VOD transcript),
|
|
72
|
+
# but a tool call cannot stay open that long: a proxy or CDN in front of the
|
|
73
|
+
# server may end a response it has waited ~100s for (a 524 on some CDNs), and
|
|
74
|
+
# MCP clients have their own call timeouts: 60s is common (the MCP SDK default,
|
|
75
|
+
# and the bridge a cloud chat uses to reach a connector on the user's desktop).
|
|
76
|
+
# Past that the client drops the call and never sees the job_id, so the job
|
|
77
|
+
# runs, is charged, and a retry pays twice. 45s leaves room for the upload
|
|
78
|
+
# before the wait starts. So a call waits at most this long, then returns
|
|
79
|
+
# status "processing" with the job_id, and check_job_status(job_id,
|
|
80
|
+
# wait_seconds=...) picks the wait up again. The per-type `timeout` above
|
|
81
|
+
# still caps a single wait if it is lower.
|
|
82
|
+
tool_max_wait: float = Field(
|
|
83
|
+
default=45.0,
|
|
84
|
+
gt=0,
|
|
85
|
+
description="Seconds one tool call waits for its job before returning the job_id to resume with",
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# Plain API key check (deapi_mcp/key_verifier.py). A key sent as a bearer token
|
|
89
|
+
# or as the OAuth client_secret is checked once against the API (cached), so a
|
|
90
|
+
# wrong key is refused with 401 at connect instead of failing every tool call.
|
|
91
|
+
# An API outage lets keys through, as without the check.
|
|
92
|
+
verify_api_keys: bool = Field(
|
|
93
|
+
default=True,
|
|
94
|
+
description="Check plain deAPI API keys against the API before accepting them",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# OAuth for clients that register themselves (RFC 7591) or identify by a client ID
|
|
98
|
+
# metadata document: they get a sign-in screen at /authorize where the user enters an
|
|
99
|
+
# API key. The pre-registered deapi-mcp client works either way.
|
|
100
|
+
oauth_public_clients: bool = Field(
|
|
101
|
+
default=True,
|
|
102
|
+
description="Offer dynamic client registration, CIMD and the sign-in screen",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# The header that carries the real client address, set by the edge and impossible for a
|
|
106
|
+
# client to forge (for example CF-Connecting-IP when all traffic comes through
|
|
107
|
+
# Cloudflare). Used to count wrong keys on the sign-in screen. Unset: the connection's
|
|
108
|
+
# address, which a proxy trusting X-Forwarded-For blindly lets the client choose.
|
|
109
|
+
client_ip_header: str | None = Field(
|
|
110
|
+
default=None,
|
|
111
|
+
description="Header with the real client IP, set by a trusted edge proxy",
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Tool Description Enrichment
|
|
115
|
+
enrich_tool_descriptions: bool = Field(
|
|
116
|
+
default=True,
|
|
117
|
+
description="Enrich tool descriptions with available model info (set to false to disable)",
|
|
118
|
+
)
|
|
119
|
+
model_cache_ttl: float = Field(
|
|
120
|
+
default=300.0,
|
|
121
|
+
description="TTL in seconds for cached model info used in description enrichment",
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# Internal webhooks: the API calls this server back when a job finishes, so
|
|
125
|
+
# a tool waits on that callback instead of polling the status endpoint every
|
|
126
|
+
# few seconds. Polling stays as a safety net at a much lower rate.
|
|
127
|
+
#
|
|
128
|
+
# Field names deliberately carry no `deapi_` prefix — see the note above on
|
|
129
|
+
# deapi_api_base_url for why. Env vars: DEAPI_WEBHOOKS_INTERNAL,
|
|
130
|
+
# DEAPI_WEBHOOK_RECEIVER_URL, DEAPI_WEBHOOK_SECRET, DEAPI_WEBHOOK_FALLBACK_POLL_INTERVAL.
|
|
131
|
+
webhooks_internal: bool = Field(
|
|
132
|
+
default=False,
|
|
133
|
+
description="Register this server as the completion webhook for jobs it submits",
|
|
134
|
+
)
|
|
135
|
+
webhook_receiver_url: str | None = Field(
|
|
136
|
+
default=None,
|
|
137
|
+
description="Public HTTPS URL of this server's /webhooks/deapi route, as the API must reach it",
|
|
138
|
+
)
|
|
139
|
+
webhook_secret: str | None = Field(
|
|
140
|
+
default=None,
|
|
141
|
+
description="Key the API signs callbacks with (HMAC-SHA256). 32-255 characters",
|
|
142
|
+
)
|
|
143
|
+
webhook_fallback_poll_interval: float = Field(
|
|
144
|
+
default=15.0,
|
|
145
|
+
description="Seconds between safety-net status polls while waiting on a callback",
|
|
146
|
+
)
|
|
147
|
+
webhook_timestamp_tolerance: float = Field(
|
|
148
|
+
default=300.0,
|
|
149
|
+
description="Reject callbacks whose X-DeAPI-Timestamp is older than this many seconds",
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
# Redis: shared store for OAuth authorization codes, so a code issued by one
|
|
153
|
+
# replica can be redeemed on another. Unset host means no Redis (single
|
|
154
|
+
# replica, in-memory store).
|
|
155
|
+
#
|
|
156
|
+
# Field names carry no `deapi_` prefix for the same reason as the webhook
|
|
157
|
+
# block above. Env vars: DEAPI_REDIS_HOST, DEAPI_REDIS_PORT,
|
|
158
|
+
# DEAPI_REDIS_USERNAME, DEAPI_REDIS_PASSWORD, DEAPI_REDIS_DB,
|
|
159
|
+
# DEAPI_REDIS_SCHEME, DEAPI_REDIS_CA_FILE, DEAPI_REDIS_PREFIX,
|
|
160
|
+
# DEAPI_REDIS_REQUIRED.
|
|
161
|
+
redis_host: str | None = Field(
|
|
162
|
+
default=None, description="Redis host. Unset disables the shared store"
|
|
163
|
+
)
|
|
164
|
+
redis_port: int = Field(default=6379, description="Redis port")
|
|
165
|
+
redis_username: str | None = Field(default=None, description="Redis ACL username")
|
|
166
|
+
redis_password: SecretStr | None = Field(
|
|
167
|
+
default=None,
|
|
168
|
+
repr=False,
|
|
169
|
+
description="Redis password. A SecretStr so it never reaches a repr or an error message",
|
|
170
|
+
)
|
|
171
|
+
redis_db: int = Field(default=0, description="Redis logical database number")
|
|
172
|
+
redis_scheme: Literal["plain", "tls"] = Field(
|
|
173
|
+
default="plain", description="Connection scheme: plain TCP or TLS"
|
|
174
|
+
)
|
|
175
|
+
redis_ca_file: str | None = Field(
|
|
176
|
+
default=None, description="CA bundle used to verify the Redis server certificate (tls)"
|
|
177
|
+
)
|
|
178
|
+
redis_prefix: str = Field(
|
|
179
|
+
default="deapi_mcp_database_",
|
|
180
|
+
description="Prefix prepended to every key this server writes",
|
|
181
|
+
)
|
|
182
|
+
redis_required: bool = Field(
|
|
183
|
+
default=False,
|
|
184
|
+
description="Refuse to start when Redis is not configured, instead of falling back to memory",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Settings for an optional metrics overlay (create_app(server, metrics=...)). The core
|
|
188
|
+
# never reads them; they live here so an overlay shares this env prefix, validation and
|
|
189
|
+
# the Redis host above. Env vars: DEAPI_METRICS_TOKEN, DEAPI_METRICS_REDIS_DB,
|
|
190
|
+
# DEAPI_METRICS_PREFIX.
|
|
191
|
+
metrics_token: SecretStr | None = Field(
|
|
192
|
+
default=None,
|
|
193
|
+
repr=False,
|
|
194
|
+
description="Bearer token Prometheus presents to /metrics. Unset disables the endpoint",
|
|
195
|
+
)
|
|
196
|
+
metrics_redis_db: int = Field(default=1, description="Redis logical database for metrics")
|
|
197
|
+
metrics_prefix: str = Field(
|
|
198
|
+
default="deapi_mcp_metrics_",
|
|
199
|
+
description="Prefix prepended to every metrics key",
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
@field_validator("metrics_token", mode="before")
|
|
203
|
+
@classmethod
|
|
204
|
+
def _clean_metrics_token(cls, value: Any) -> str | None:
|
|
205
|
+
if value is None:
|
|
206
|
+
return None
|
|
207
|
+
raw = value.get_secret_value() if isinstance(value, SecretStr) else str(value)
|
|
208
|
+
raw = raw.strip()
|
|
209
|
+
if not raw:
|
|
210
|
+
return None
|
|
211
|
+
if len(raw) < 32:
|
|
212
|
+
raise ValueError("DEAPI_METRICS_TOKEN must be at least 32 characters")
|
|
213
|
+
return raw
|
|
214
|
+
|
|
215
|
+
@model_validator(mode="after")
|
|
216
|
+
def _validate_internal_webhooks(self) -> "Settings":
|
|
217
|
+
"""A half-configured receiver must fail at startup, not silently poll.
|
|
218
|
+
|
|
219
|
+
With the flag on and no URL the server would submit jobs without a
|
|
220
|
+
webhook and simply poll at the slow fallback rate — every job slower,
|
|
221
|
+
nothing logged. Refusing to start is the only outcome the operator
|
|
222
|
+
will notice.
|
|
223
|
+
"""
|
|
224
|
+
if not self.webhooks_internal:
|
|
225
|
+
return self
|
|
226
|
+
|
|
227
|
+
if not self.webhook_receiver_url:
|
|
228
|
+
raise ValueError("DEAPI_WEBHOOKS_INTERNAL is set but DEAPI_WEBHOOK_RECEIVER_URL is not")
|
|
229
|
+
if not self.webhook_receiver_url.lower().startswith("https://"):
|
|
230
|
+
raise ValueError("DEAPI_WEBHOOK_RECEIVER_URL must use https (the API requires it)")
|
|
231
|
+
if not self.webhook_secret:
|
|
232
|
+
raise ValueError("DEAPI_WEBHOOKS_INTERNAL is set but DEAPI_WEBHOOK_SECRET is not")
|
|
233
|
+
if not 32 <= len(self.webhook_secret) <= 255:
|
|
234
|
+
raise ValueError("DEAPI_WEBHOOK_SECRET must be 32-255 characters (API rule)")
|
|
235
|
+
return self
|
|
236
|
+
|
|
237
|
+
@model_validator(mode="after")
|
|
238
|
+
def _validate_redis(self) -> "Settings":
|
|
239
|
+
"""A half-configured Redis must fail at startup, not degrade silently.
|
|
240
|
+
|
|
241
|
+
With the flag on and no host the server would quietly fall back to the
|
|
242
|
+
per-process store, and every code issued by one replica would be
|
|
243
|
+
unknown to the next — OAuth logins fail intermittently with nothing
|
|
244
|
+
logged. TLS without a CA bundle would either fail on the first
|
|
245
|
+
connection under load or tempt someone to disable verification. The
|
|
246
|
+
bundle is mandatory so the server certificate is always verified, a
|
|
247
|
+
private or self-signed one included.
|
|
248
|
+
"""
|
|
249
|
+
if self.redis_required and not self.redis_host:
|
|
250
|
+
raise ValueError("DEAPI_REDIS_REQUIRED is set but DEAPI_REDIS_HOST is not")
|
|
251
|
+
if self.redis_host and self.redis_scheme == "tls" and not self.redis_ca_file:
|
|
252
|
+
raise ValueError(
|
|
253
|
+
"DEAPI_REDIS_SCHEME=tls needs DEAPI_REDIS_CA_FILE "
|
|
254
|
+
"(the CA bundle that verifies the server certificate)"
|
|
255
|
+
)
|
|
256
|
+
return self
|
|
257
|
+
|
|
258
|
+
model_config = SettingsConfigDict(
|
|
259
|
+
env_file=".env",
|
|
260
|
+
env_file_encoding="utf-8",
|
|
261
|
+
env_prefix="DEAPI_",
|
|
262
|
+
extra="ignore", # Ignore env vars not defined in Settings (e.g., MCP_HOST, DEAPI_JWT_SECRET_KEY)
|
|
263
|
+
# A blank value (`DEAPI_REDIS_PORT=`, as a secrets env or a pasted example often
|
|
264
|
+
# carries) means the default, not a parse error naming a field instead of the
|
|
265
|
+
# variable. Same rule as env_int() applies to MCP_*. No setting gives an empty
|
|
266
|
+
# string a meaning of its own.
|
|
267
|
+
env_ignore_empty=True,
|
|
268
|
+
# A rejected value (a short DEAPI_METRICS_TOKEN) must not reach the logs of a pod that
|
|
269
|
+
# fails to start; the messages name the variable instead.
|
|
270
|
+
hide_input_in_errors=True,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
def get_polling_config(self, job_type: str) -> PollingConfig:
|
|
274
|
+
"""Get appropriate polling configuration based on job type.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
job_type: Type of job (audio, image, video, or other)
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
PollingConfig for the specified job type
|
|
281
|
+
"""
|
|
282
|
+
job_type_lower = job_type.lower()
|
|
283
|
+
|
|
284
|
+
if "audio" in job_type_lower or "speech" in job_type_lower:
|
|
285
|
+
return self.polling_audio
|
|
286
|
+
elif "image" in job_type_lower or "img" in job_type_lower:
|
|
287
|
+
return self.polling_image
|
|
288
|
+
elif "video" in job_type_lower:
|
|
289
|
+
return self.polling_video
|
|
290
|
+
elif "embedding" in job_type_lower:
|
|
291
|
+
return self.polling_embedding
|
|
292
|
+
else:
|
|
293
|
+
return self.polling_default
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
# Global settings instance
|
|
297
|
+
settings = Settings()
|