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,225 @@
1
+ """Check a plain deAPI API key against the API before a connection is accepted.
2
+
3
+ A JWT issued by ``/token`` is checked by its signature. A plain key sent as
4
+ ``Authorization: Bearer <key>`` has no signature to check, so without this module
5
+ any string is accepted: ``initialize`` and ``tools/list`` succeed and the first
6
+ tool call fails with a generic API error. A client cannot tell from that that its
7
+ key is wrong, and so never asks the user for a new one.
8
+
9
+ The check is one ``GET /account/balance`` with the key, an endpoint that costs
10
+ nothing. The verdict is cached per key, under an HMAC of the key with a
11
+ per-process random secret, so the raw key is never held as a cache key:
12
+
13
+ - 2xx, or 403 (the key authenticated but is not allowed this endpoint): valid,
14
+ cached for ``VALID_TTL``;
15
+ - 401: invalid, cached for ``INVALID_TTL``;
16
+ - anything else (5xx, 429, a timeout, a network error): unknown. The key is let
17
+ through, as before this check existed, so an API outage never locks users out
18
+ of the server; the verdict is cached for ``UNKNOWN_TTL`` so an outage does not
19
+ add a probe to every request.
20
+
21
+ Concurrent requests carrying the same key share one probe. Turn the whole check
22
+ off with ``DEAPI_VERIFY_API_KEYS=false``.
23
+ """
24
+
25
+ import asyncio
26
+ import enum
27
+ import hashlib
28
+ import hmac
29
+ import logging
30
+ import secrets
31
+ import time
32
+ from collections import OrderedDict
33
+ from dataclasses import dataclass
34
+ from typing import Optional
35
+
36
+ import httpx
37
+
38
+ from . import __version__
39
+ from .config import settings
40
+ from .deapi_client import _shared_http_client
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ VALID_TTL = 600.0
45
+ INVALID_TTL = 60.0
46
+ UNKNOWN_TTL = 15.0
47
+ # A refusal seen on a real API call (tool or job status), not on a probe.
48
+ OBSERVED_INVALID_TTL = 600.0
49
+ # Seconds one probe may take. The probe runs before the request is served, so it
50
+ # is never retried and must not stall a connection the way a tool's own call may.
51
+ PROBE_TIMEOUT = 5.0
52
+ # Distinct keys remembered at once, least recently used evicted first.
53
+ MAX_ENTRIES = 10_000
54
+ # Probes in flight at once. A flood of random keys beyond this is let through unchecked
55
+ # (the API then refuses each tool call), as before this check existed, instead of
56
+ # turning the server into an amplifier of requests to the API.
57
+ MAX_CONCURRENT_PROBES = 32
58
+
59
+ # Monotonic clock for verdict expiry; a seam the tests replace.
60
+ _clock = time.monotonic
61
+
62
+ # The endpoint the probe reads, relative to /api/<version>/. Same one get_balance uses.
63
+ PROBE_ENDPOINT = "account/balance"
64
+
65
+
66
+ class KeyStatus(enum.Enum):
67
+ VALID = "valid"
68
+ INVALID = "invalid"
69
+ UNKNOWN = "unknown"
70
+
71
+
72
+ _TTL = {
73
+ KeyStatus.VALID: VALID_TTL,
74
+ KeyStatus.INVALID: INVALID_TTL,
75
+ KeyStatus.UNKNOWN: UNKNOWN_TTL,
76
+ }
77
+
78
+
79
+ @dataclass
80
+ class _Verdict:
81
+ status: KeyStatus
82
+ expires_at: float
83
+
84
+
85
+ class KeyVerifier:
86
+ """Verdict cache plus single-flight probe, one per process."""
87
+
88
+ def __init__(self, max_entries: int = MAX_ENTRIES) -> None:
89
+ self.max_entries = max_entries
90
+ self._hmac_key = secrets.token_bytes(32)
91
+ self._verdicts: "OrderedDict[str, _Verdict]" = OrderedDict()
92
+ self._inflight: dict[str, "asyncio.Future[KeyStatus]"] = {}
93
+
94
+ def _cache_key(self, api_key: str) -> str:
95
+ return hmac.new(self._hmac_key, api_key.encode(), hashlib.sha256).hexdigest()
96
+
97
+ def __len__(self) -> int:
98
+ return len(self._verdicts)
99
+
100
+ def clear(self) -> None:
101
+ self._verdicts.clear()
102
+ self._inflight.clear()
103
+
104
+ def _cached(self, cache_key: str) -> Optional[KeyStatus]:
105
+ verdict = self._verdicts.get(cache_key)
106
+ if verdict is None:
107
+ return None
108
+ if verdict.expires_at <= _clock():
109
+ del self._verdicts[cache_key]
110
+ return None
111
+ self._verdicts.move_to_end(cache_key)
112
+ return verdict.status
113
+
114
+ def _store(self, cache_key: str, status: KeyStatus, ttl: Optional[float] = None) -> None:
115
+ self._verdicts[cache_key] = _Verdict(status, _clock() + (ttl or _TTL[status]))
116
+ self._verdicts.move_to_end(cache_key)
117
+ while len(self._verdicts) > self.max_entries:
118
+ self._verdicts.popitem(last=False)
119
+
120
+ def mark_invalid(self, api_key: str) -> None:
121
+ """Record that deAPI just refused ``api_key`` (a 401 on a real call).
122
+
123
+ Kept for ``OBSERVED_INVALID_TTL``: long enough that the client's next request is
124
+ refused at authentication, which makes it sign in again, and refreshed by every
125
+ further 401 for the same key.
126
+ """
127
+ self._store(self._cache_key(api_key), KeyStatus.INVALID, OBSERVED_INVALID_TTL)
128
+
129
+ def known_invalid(self, api_key: str) -> bool:
130
+ """True when a recent verdict says deAPI refuses ``api_key``. Never probes."""
131
+ return self._cached(self._cache_key(api_key)) is KeyStatus.INVALID
132
+
133
+ async def verify(self, api_key: str) -> KeyStatus:
134
+ """The key's status, from the cache or from one probe shared by every caller."""
135
+ cache_key = self._cache_key(api_key)
136
+ cached = self._cached(cache_key)
137
+ if cached is not None:
138
+ return cached
139
+
140
+ probe = self._inflight.get(cache_key)
141
+ if probe is None:
142
+ if len(self._inflight) >= MAX_CONCURRENT_PROBES:
143
+ logger.warning("API key check: too many checks in flight; letting a key through")
144
+ return KeyStatus.UNKNOWN
145
+ probe = asyncio.ensure_future(self._probe_and_store(cache_key, api_key))
146
+ self._inflight[cache_key] = probe
147
+
148
+ def _done(future: "asyncio.Future[KeyStatus]") -> None:
149
+ if self._inflight.get(cache_key) is future:
150
+ del self._inflight[cache_key]
151
+
152
+ probe.add_done_callback(_done)
153
+
154
+ # A caller that goes away (client disconnect) must not cancel the probe the
155
+ # other callers are waiting on.
156
+ return await asyncio.shield(probe)
157
+
158
+ async def _probe_and_store(self, cache_key: str, api_key: str) -> KeyStatus:
159
+ try:
160
+ status = await probe_api_key(api_key)
161
+ except Exception as exc: # never let the check itself refuse a connection
162
+ logger.warning("API key check failed unexpectedly: %s", type(exc).__name__)
163
+ status = KeyStatus.UNKNOWN
164
+ self._store(cache_key, status)
165
+ return status
166
+
167
+
168
+ async def probe_api_key(api_key: str) -> KeyStatus:
169
+ """Ask the API whether it accepts this key. Never raises for an HTTP or network error."""
170
+ url = f"{settings.deapi_api_base_url}/api/{settings.deapi_api_version}/{PROBE_ENDPOINT}"
171
+ headers = {
172
+ "Authorization": f"Bearer {api_key}",
173
+ "Accept": "application/json",
174
+ "User-Agent": f"deapi-mcp/{__version__}",
175
+ }
176
+ try:
177
+ response = await _shared_http_client().get(url, headers=headers, timeout=PROBE_TIMEOUT)
178
+ except httpx.HTTPError as exc:
179
+ logger.warning(
180
+ "API key check: deAPI unreachable (%s), letting the key through", type(exc).__name__
181
+ )
182
+ return KeyStatus.UNKNOWN
183
+
184
+ code = response.status_code
185
+ if 200 <= code < 300 or code == 403:
186
+ return KeyStatus.VALID
187
+ if code == 401:
188
+ logger.info("API key check: deAPI rejected the key (401)")
189
+ return KeyStatus.INVALID
190
+ logger.warning("API key check: deAPI answered %d, letting the key through", code)
191
+ return KeyStatus.UNKNOWN
192
+
193
+
194
+ _verifier: Optional[KeyVerifier] = None
195
+
196
+
197
+ def get_key_verifier() -> KeyVerifier:
198
+ global _verifier
199
+ if _verifier is None:
200
+ _verifier = KeyVerifier()
201
+ return _verifier
202
+
203
+
204
+ def set_key_verifier(verifier: Optional[KeyVerifier]) -> None:
205
+ """Replace the process-wide verifier (``None`` resets it to a fresh default)."""
206
+ global _verifier
207
+ _verifier = verifier
208
+
209
+
210
+ async def is_api_key_rejected(api_key: str) -> bool:
211
+ """True only when the check is on and the API positively refused the key."""
212
+ if not settings.verify_api_keys:
213
+ return False
214
+ return await get_key_verifier().verify(api_key) is KeyStatus.INVALID
215
+
216
+
217
+ def note_key_refused(api_key: str) -> None:
218
+ """A call with ``api_key`` got 401 from deAPI: remember it, so the session ends."""
219
+ if settings.verify_api_keys:
220
+ get_key_verifier().mark_invalid(api_key)
221
+
222
+
223
+ def is_key_known_invalid(api_key: str) -> bool:
224
+ """True when deAPI recently refused ``api_key``. A cache read only, never a probe."""
225
+ return settings.verify_api_keys and get_key_verifier().known_invalid(api_key)
deapi_mcp/landing.py ADDED
@@ -0,0 +1,431 @@
1
+ """The page served at ``GET /``: how to connect an MCP client to this server.
2
+
3
+ One static HTML document: inline CSS, no script, no external resource, so a strict
4
+ Content-Security-Policy holds (the stylesheet is allowed by its hash, nothing else
5
+ loads). Client sections are ``<details>`` blocks, which open and close without
6
+ JavaScript. The endpoint URL comes from ``PUBLIC_BASE_URL`` (or the request), and
7
+ the tool list from the server's own registry, so the page never drifts from what
8
+ the server actually serves.
9
+ """
10
+
11
+ import base64
12
+ import hashlib
13
+ import os
14
+ from html import escape
15
+ from typing import Any, Optional, Sequence
16
+
17
+ from starlette.requests import Request
18
+ from starlette.responses import HTMLResponse, Response
19
+
20
+ from . import __version__
21
+
22
+ KEYS_URL = "https://app.deapi.ai/settings/api-keys"
23
+ DOCS_URL = "https://docs.deapi.ai/"
24
+ MCP_DOCS_URL = "https://docs.deapi.ai/execution-modes-and-integrations/mcp-server"
25
+ REPO_URL = "https://github.com/deapi-ai/mcp-server-deapi"
26
+ SECURITY_URL = "https://github.com/deapi-ai/mcp-server-deapi/blob/main/SECURITY.md"
27
+ OAUTH_CLIENT_ID = "deapi-mcp"
28
+ HOME_URL = "https://deapi.ai/"
29
+
30
+ # The deAPI logo (as in the deAPI docs), inline so the page loads nothing.
31
+ LOGO_SVG = '<svg class=logo xmlns="http://www.w3.org/2000/svg" viewBox="0 0 81.585 30.472" role=img aria-label=deAPI><g><path d="M34.149,19.256v-4.547l1.615-1.631h3.105l.925.8v-4.187h2.07v11.196h-1.944v-1.207l-1.208,1.207h-2.948l-1.615-1.631ZM38.525,19.131l1.27-1.302v-2.038l-1.066-.957h-1.913l-.596.611v3.074l.596.611h1.709Z" fill="#ffba00"/><path d="M43.59,19.288v-4.579l1.615-1.631h4.407l1.631,1.631v2.963h-5.583v1.004l.502.517h2.556l.47-.486v-.407h2.039v1.018l-1.553,1.568h-4.501l-1.584-1.599ZM49.173,16.231v-.91l-.533-.549h-2.447l-.533.549v.91h3.513Z" fill="#ffba00"/><path d="M55.884,9.911h1.945l4.014,10.977h-2.164l-.894-2.43h-3.858l-.894,2.43h-2.164l4.014-10.977ZM58.315,16.7l-1.459-4.171h-.031l-1.411,4.171h2.901Z" fill="#ffba00"/><path d="M62.941,9.911h6.885l1.678,1.694v3.841l-1.694,1.71h-4.736v3.732h-2.133v-10.977ZM68.854,15.368l.549-.549v-2.572l-.549-.55h-3.78v3.67h3.78Z" fill="#ffba00"/><path d="M73.15,9.911h2.133v10.977h-2.133v-10.977Z" fill="#ffba00"/></g><g><path d="M27.865,11.713v-2h-3.511v-2.595l-1-1h-2.595v-2.276l-2-1.155v3.43h-2.523V1.231l-.25-.144h-1.5l-.25.144v4.887h-2.523v-3.431l-2,1.155v2.276h-2.595l-1,1v2.595h-3.511v2h3.511v2.523h-3.511v2h3.511v2.522h-3.511v2h3.511v2.596l1,1h2.595v2.275l2,1.155v-3.43h2.523v4.887l.25.144h1.5l.25-.144v-4.887h2.523v3.43l2-1.155v-2.275h2.595l1-1v-2.596h3.511v-2h-3.511v-2.522h3.511v-2h-3.511v-2.523h3.511ZM22.354,22.355h-14.236v-14.236h14.236v14.236Z" fill="#ffba00"/><polygon points="20.742 9.691 18.222 9.691 9.727 20.781 12.247 20.781 20.742 9.691" fill="#ffba00"/></g></svg>'
32
+
33
+ # Tool modules (deapi_mcp.tools.<name>) in page order, with their heading.
34
+ CATEGORIES = (
35
+ ("image", "Image"),
36
+ ("video", "Video"),
37
+ ("audio", "Audio and speech"),
38
+ ("embedding", "Embeddings"),
39
+ ("prompt", "Prompts"),
40
+ ("utility", "Account and jobs"),
41
+ )
42
+
43
+ CSS = """
44
+ :root{--bg:#11100d;--bg-deep:#0e0d0b;--card:#1a1710;--line:#363021;--line-soft:#262217;
45
+ --fg:#f2f0ea;--muted:#bcbcbc;--dim:#938367;--amber:#ffba00;--amber-hi:#feca00;
46
+ --sans:Switzer,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
47
+ --mono:"IBM Plex Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color-scheme:dark}
48
+ *{box-sizing:border-box}
49
+ body{margin:0;background:var(--bg);color:var(--muted);font:15px/1.7 var(--mono)}
50
+ .bar{height:4px;background:linear-gradient(90deg,#5c4a12,var(--amber),#5c4a12)}
51
+ header{max-width:58rem;margin:1.25rem auto 0;padding:.9rem 1.25rem;display:flex;
52
+ align-items:center;gap:1rem;border:1px solid var(--line-soft);border-radius:10px;
53
+ background:var(--bg-deep)}
54
+ header .home{display:flex;align-items:center;text-decoration:none}
55
+ .logo{height:2.4rem;width:auto;display:block}
56
+ .pill{font-size:.75rem;color:var(--amber);border:1px solid var(--line);border-radius:999px;
57
+ padding:.1rem .6rem;letter-spacing:.04em}
58
+ header nav{margin-left:auto;display:flex;gap:.6rem;flex-wrap:wrap}
59
+ .btn{display:inline-block;font:700 .85rem/1 var(--mono);text-decoration:none;
60
+ padding:.8rem 1.1rem;border-radius:4px;border:1px solid var(--amber);color:var(--amber)}
61
+ .btn.solid{background:var(--amber);color:#11100d}
62
+ .btn:hover{background:var(--amber-hi);border-color:var(--amber-hi);color:#11100d}
63
+ main{max-width:52rem;margin:0 auto;padding:3.5rem 1.25rem 4rem}
64
+ .facts{text-align:center;color:var(--fg);font-size:.9rem;margin:0}
65
+ .facts span{margin:0 .7rem;white-space:nowrap}
66
+ .facts span::before{content:"•";margin-right:.5rem}
67
+ h1{font:600 clamp(2.4rem,7vw,4.2rem)/1.05 var(--sans);color:#fff;text-align:center;
68
+ margin:.9rem 0 1rem;letter-spacing:-.01em}
69
+ h1 em{font-style:normal;color:var(--amber)}
70
+ .lead{text-align:center;font-size:1.05rem;max-width:40rem;margin:0 auto 2rem}
71
+ .cta{display:flex;justify-content:center;gap:.8rem;flex-wrap:wrap;margin-bottom:2.5rem}
72
+ h2{font:600 1.6rem/1.2 var(--sans);color:#fff;margin:3.5rem 0 1rem}
73
+ h2 small{display:block;font:500 .8rem var(--mono);color:var(--amber);letter-spacing:.08em;
74
+ text-transform:uppercase;margin-bottom:.4rem}
75
+ h3{font:600 1.05rem var(--sans);color:var(--fg);margin:1.8rem 0 .6rem}
76
+ p{margin:.6rem 0}
77
+ a{color:var(--amber)}
78
+ b,strong,i{color:var(--fg)}
79
+ .endpoint{background:var(--card);border:1px solid var(--line);border-left:3px solid var(--amber);
80
+ border-radius:8px;padding:1rem 1.25rem}
81
+ .endpoint .label{color:var(--dim);font-size:.8rem;margin:0;letter-spacing:.04em}
82
+ .endpoint code{font-size:1.1rem;background:none;padding:0;color:var(--amber)}
83
+ code{font:.92em var(--mono);color:var(--fg);background:var(--line-soft);padding:.1em .35em;
84
+ border-radius:4px;overflow-wrap:anywhere}
85
+ pre{background:var(--bg-deep);border:1px solid var(--line-soft);border-radius:8px;
86
+ padding:.9rem 1rem;overflow-x:auto;margin:.6rem 0}
87
+ pre code{background:none;padding:0;user-select:all;overflow-wrap:normal;color:#e9e4d6}
88
+ .endpoint code,td code{user-select:all}
89
+ details{background:var(--card);border:1px solid var(--line);border-radius:8px;
90
+ padding:.2rem 1.25rem;margin:.6rem 0}
91
+ details[open]{padding-bottom:1rem;border-color:#4a4029}
92
+ summary{cursor:pointer;font:600 1rem var(--sans);color:var(--fg);padding:.75rem 0}
93
+ summary::marker{color:var(--amber)}
94
+ .note{color:var(--dim);font-size:.85rem}
95
+ ol,ul{padding-left:1.4rem}
96
+ li{margin:.3rem 0}
97
+ li::marker{color:var(--amber)}
98
+ table{border-collapse:collapse;width:100%;font-size:.9rem}
99
+ td{border-top:1px solid var(--line-soft);padding:.5rem .5rem .5rem 0;vertical-align:top}
100
+ td:first-child{white-space:nowrap;padding-right:1rem}
101
+ td code{color:var(--amber);background:none;padding:0}
102
+ @media (max-width:640px){header{flex-wrap:wrap}header nav{margin-left:0;width:100%}
103
+ .facts span{display:inline-block;margin:.1rem .5rem}
104
+ td{display:block;border-top:0;padding:0}
105
+ td:first-child{border-top:1px solid var(--line-soft);padding-top:.5rem}
106
+ td:last-child{padding-bottom:.5rem}}
107
+ footer{margin-top:4rem;padding-top:1.25rem;border-top:1px solid var(--line-soft);
108
+ color:var(--dim);font-size:.85rem;display:flex;flex-wrap:wrap;gap:.5rem 1.25rem;
109
+ align-items:center}
110
+ footer .logo{height:1.5rem}
111
+ footer a{color:var(--muted);text-decoration:none}
112
+ footer a:hover{color:var(--amber)}
113
+ footer .version{margin-left:auto}
114
+ """
115
+
116
+ _STYLE_HASH = base64.b64encode(hashlib.sha256(CSS.encode()).digest()).decode()
117
+
118
+ SECURITY_HEADERS = {
119
+ "Content-Security-Policy": (
120
+ "default-src 'none'; "
121
+ f"style-src 'sha256-{_STYLE_HASH}'; "
122
+ "base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
123
+ ),
124
+ "X-Content-Type-Options": "nosniff",
125
+ "X-Frame-Options": "DENY",
126
+ "Referrer-Policy": "no-referrer",
127
+ "Cross-Origin-Opener-Policy": "same-origin",
128
+ # The page names the host it was reached on, so a shared cache must not keep it.
129
+ "Cache-Control": "no-cache",
130
+ }
131
+
132
+
133
+ def _first_sentence(description: Optional[str]) -> str:
134
+ lines = (description or "").strip().splitlines()
135
+ return lines[0].strip() if lines else ""
136
+
137
+
138
+ def _tool_category(tool: Any) -> str:
139
+ module = getattr(getattr(tool, "fn", None), "__module__", "") or ""
140
+ return module.rsplit(".", 1)[-1]
141
+
142
+
143
+ def _code(text: str) -> str:
144
+ return f"<pre><code>{escape(text)}</code></pre>"
145
+
146
+
147
+ def _tools_html(tools: Sequence[Any]) -> str:
148
+ """The tool list, grouped by category. Price tools are counted, not listed."""
149
+ generators = [t for t in tools if not t.name.endswith("_price")]
150
+ price_count = len(tools) - len(generators)
151
+ known = {key for key, _ in CATEGORIES}
152
+ groups = [(key, title) for key, title in CATEGORIES]
153
+ if any(_tool_category(t) not in known for t in generators):
154
+ groups.append(("", "Other"))
155
+
156
+ parts = []
157
+ for key, title in groups:
158
+ members = [
159
+ t
160
+ for t in generators
161
+ if (_tool_category(t) == key if key else _tool_category(t) not in known)
162
+ ]
163
+ if not members:
164
+ continue
165
+ rows = "".join(
166
+ f"<tr><td><code>{escape(t.name)}</code></td>"
167
+ f"<td>{escape(_first_sentence(t.description))}</td></tr>"
168
+ for t in members
169
+ )
170
+ parts.append(f"<h3>{escape(title)}</h3><table>{rows}</table>")
171
+ if price_count:
172
+ parts.append(
173
+ f"<p class=note>Plus {price_count} <code>*_price</code> tools that quote "
174
+ "the cost of a job before it runs.</p>"
175
+ )
176
+ return "".join(parts)
177
+
178
+
179
+ def render_landing(base_url: str, tools: Sequence[Any]) -> str:
180
+ """The whole page for a server reachable at ``base_url``."""
181
+ base = base_url.rstrip("/")
182
+ mcp_url = f"{base}/mcp"
183
+ e_url = escape(mcp_url)
184
+
185
+ claude_code = (
186
+ f"claude mcp add --transport http deapi {mcp_url} \\\n"
187
+ ' --header "Authorization: Bearer $DEAPI_API_KEY"'
188
+ )
189
+ claude_code_json = (
190
+ "{\n"
191
+ ' "mcpServers": {\n'
192
+ ' "deapi": {\n'
193
+ ' "type": "http",\n'
194
+ f' "url": "{mcp_url}",\n'
195
+ ' "headers": { "Authorization": "Bearer ${DEAPI_API_KEY}" }\n'
196
+ " }\n"
197
+ " }\n"
198
+ "}"
199
+ )
200
+ cursor_json = (
201
+ "{\n"
202
+ ' "mcpServers": {\n'
203
+ ' "deapi": {\n'
204
+ f' "url": "{mcp_url}",\n'
205
+ ' "headers": { "Authorization": "Bearer ${env:DEAPI_API_KEY}" }\n'
206
+ " }\n"
207
+ " }\n"
208
+ "}"
209
+ )
210
+ cursor_oauth_json = (
211
+ "{\n"
212
+ ' "mcpServers": {\n'
213
+ ' "deapi": {\n'
214
+ f' "url": "{mcp_url}",\n'
215
+ ' "auth": {\n'
216
+ f' "CLIENT_ID": "{OAUTH_CLIENT_ID}",\n'
217
+ ' "CLIENT_SECRET": "${env:DEAPI_API_KEY}"\n'
218
+ " }\n"
219
+ " }\n"
220
+ " }\n"
221
+ "}"
222
+ )
223
+ vscode_json = (
224
+ "{\n"
225
+ ' "inputs": [\n'
226
+ ' { "type": "promptString", "id": "deapi-key",\n'
227
+ ' "description": "deAPI API key", "password": true }\n'
228
+ " ],\n"
229
+ ' "servers": {\n'
230
+ ' "deapi": {\n'
231
+ ' "type": "http",\n'
232
+ f' "url": "{mcp_url}",\n'
233
+ ' "headers": { "Authorization": "Bearer ${input:deapi-key}" }\n'
234
+ " }\n"
235
+ " }\n"
236
+ "}"
237
+ )
238
+ codex_toml = (
239
+ "[mcp_servers.deapi]\n" f'url = "{mcp_url}"\n' 'bearer_token_env_var = "DEAPI_API_KEY"'
240
+ )
241
+ gemini_json = (
242
+ "{\n"
243
+ ' "mcpServers": {\n'
244
+ ' "deapi": {\n'
245
+ f' "httpUrl": "{mcp_url}",\n'
246
+ ' "headers": { "Authorization": "Bearer <YOUR_DEAPI_API_KEY>" }\n'
247
+ " }\n"
248
+ " }\n"
249
+ "}"
250
+ )
251
+ curl = (
252
+ f"curl -s {mcp_url} \\\n"
253
+ ' -H "Authorization: Bearer $DEAPI_API_KEY" \\\n'
254
+ ' -H "Content-Type: application/json" \\\n'
255
+ ' -H "Accept: application/json, text/event-stream" \\\n'
256
+ """ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'"""
257
+ )
258
+
259
+ tool_count = len(tools)
260
+ return f"""<!doctype html>
261
+ <html lang=en>
262
+ <head>
263
+ <meta charset=utf-8>
264
+ <meta name=viewport content="width=device-width, initial-scale=1">
265
+ <meta name=referrer content=no-referrer>
266
+ <title>deAPI MCP Server</title>
267
+ <meta name=description content="Connect Claude, ChatGPT, Cursor, VS Code, Codex and other MCP clients to deAPI: image, video, audio, transcription, OCR and embedding models.">
268
+ <style>{CSS}</style>
269
+ </head>
270
+ <body>
271
+ <div class=bar></div>
272
+ <header>
273
+ <a class=home href="{HOME_URL}">{LOGO_SVG}</a>
274
+ <span class=pill>MCP SERVER</span>
275
+ <nav><a class=btn href="{MCP_DOCS_URL}">Docs</a><a class="btn solid"
276
+ href="{KEYS_URL}">Get API key</a></nav>
277
+ </header>
278
+ <main>
279
+ <p class=facts><span>{tool_count} tools</span><span>Streamable HTTP</span><span>Pay per
280
+ use</span></p>
281
+ <h1>deAPI <em>MCP Server</em></h1>
282
+ <p class=lead>Generate images, video, speech and music, transcribe audio and video, read text
283
+ from images and create embeddings, all from your AI assistant. {tool_count} tools over one
284
+ endpoint, billed to your deAPI balance.</p>
285
+ <div class=cta><a class="btn solid" href="#connect">Connect your client</a><a class=btn
286
+ href="#tools">See the tools</a></div>
287
+
288
+ <div class=endpoint>
289
+ <p class=label>MCP endpoint · Streamable HTTP</p>
290
+ <code>{e_url}</code>
291
+ </div>
292
+ <p class=note>This server speaks Streamable HTTP only. There is no SSE endpoint; a client
293
+ that can only use SSE needs an update.</p>
294
+
295
+ <h2><small>Step 1</small>Get an API key</h2>
296
+ <p>Create a key at <a href="{KEYS_URL}">app.deapi.ai/settings/api-keys</a>. Jobs run on your
297
+ deAPI balance, so treat the key like a password. The examples below read it from the
298
+ <code>DEAPI_API_KEY</code> environment variable where the client allows that, which keeps it
299
+ out of config files and shell history.</p>
300
+
301
+ <h2 id=connect><small>Step 2</small>Connect your client</h2>
302
+
303
+ <details open>
304
+ <summary>Claude (claude.ai and Claude Desktop)</summary>
305
+ <ol>
306
+ <li>Open <b>Customize → Connectors</b> and choose <b>Add custom connector</b>.</li>
307
+ <li>Name it <code>deAPI</code> and paste the endpoint <code>{e_url}</code>.</li>
308
+ <li>Click <b>Add</b>, then <b>Connect</b>. A deAPI sign-in window opens: paste your API key
309
+ and choose <b>Allow access</b>.</li>
310
+ </ol>
311
+ <p class=note>You can also skip the sign-in window: under <b>Advanced settings</b> choose
312
+ <b>Use your own OAuth client</b> with Client ID <code>{OAUTH_CLIENT_ID}</code> and your API key as
313
+ Client Secret, or, where your plan offers <b>Request headers</b>, add
314
+ <code>Authorization: Bearer &lt;your key&gt;</code>. On Team and Enterprise plans an owner adds
315
+ connectors under Organization settings.</p>
316
+ </details>
317
+
318
+ <details>
319
+ <summary>ChatGPT</summary>
320
+ <ol>
321
+ <li>On chatgpt.com, open <b>Settings → Apps &amp; Connectors → Advanced settings</b> and turn on
322
+ <b>Developer mode</b>.</li>
323
+ <li>Choose <b>Create</b>, name the app <code>deAPI</code> and enter the MCP server URL
324
+ <code>{e_url}</code>.</li>
325
+ <li>Set <b>Authentication</b> to <b>OAuth</b>. Leave the client fields empty: ChatGPT
326
+ registers itself, and a deAPI sign-in window asks for your API key.</li>
327
+ <li>Confirm and create the app, then enable it in a chat.</li>
328
+ </ol>
329
+ <p class=note>If ChatGPT asks for client credentials, enter Client ID
330
+ <code>{OAUTH_CLIENT_ID}</code> and your API key as Client Secret.</p>
331
+ <p class=note>Developer mode depends on your ChatGPT plan and is set up on the web.</p>
332
+ </details>
333
+
334
+ <details>
335
+ <summary>Claude Code</summary>
336
+ {_code(claude_code)}
337
+ <p>Without <code>--header</code>, run <code>/mcp</code> in Claude Code and choose
338
+ <b>Authenticate</b>: the deAPI sign-in window opens in your browser.</p>
339
+ <p>Or share it with a project in <code>.mcp.json</code>:</p>
340
+ {_code(claude_code_json)}
341
+ </details>
342
+
343
+ <details>
344
+ <summary>Cursor</summary>
345
+ <p>In <code>~/.cursor/mcp.json</code> (or <code>.cursor/mcp.json</code> in a project):</p>
346
+ {_code(cursor_json)}
347
+ <p>Or leave out <code>headers</code>: Cursor then opens the deAPI sign-in window, where you
348
+ paste your key. To skip that window with OAuth, use the pre-registered client:</p>
349
+ {_code(cursor_oauth_json)}
350
+ </details>
351
+
352
+ <details>
353
+ <summary>VS Code (GitHub Copilot)</summary>
354
+ <p>In <code>.vscode/mcp.json</code>. VS Code asks for the key once and stores it securely:</p>
355
+ {_code(vscode_json)}
356
+ </details>
357
+
358
+ <details>
359
+ <summary>Codex CLI</summary>
360
+ <p>In <code>~/.codex/config.toml</code>. Codex sends the variable's value as a Bearer token:</p>
361
+ {_code(codex_toml)}
362
+ </details>
363
+
364
+ <details>
365
+ <summary>Gemini CLI</summary>
366
+ <p>In <code>~/.gemini/settings.json</code>. Use <code>httpUrl</code>: in Gemini CLI
367
+ <code>url</code> means SSE.</p>
368
+ {_code(gemini_json)}
369
+ <p class=note>This file holds the key in plain text; keep it private.</p>
370
+ </details>
371
+
372
+ <details>
373
+ <summary>Any other MCP client</summary>
374
+ <p>Use the endpoint <code>{e_url}</code> with transport Streamable HTTP (sometimes called
375
+ just "HTTP") and send your key in one of these headers:</p>
376
+ <ul>
377
+ <li><code>Authorization: Bearer &lt;your key&gt;</code></li>
378
+ <li><code>X-API-Key: &lt;your key&gt;</code></li>
379
+ </ul>
380
+ <p>A client that uses OAuth needs no setup: it registers itself (dynamic client
381
+ registration or a client ID metadata document) and opens the deAPI sign-in window, where you
382
+ paste your API key. A client with fixed OAuth credentials can use Client ID
383
+ <code>{OAUTH_CLIENT_ID}</code> with your API key as Client Secret. Both use the Authorization
384
+ Code flow with PKCE (S256).</p>
385
+ </details>
386
+
387
+ <h2><small>Step 3</small>Check that it works</h2>
388
+ <p>Ask your assistant to <i>"check my deAPI balance"</i>, or list the tools from a terminal:</p>
389
+ {_code(curl)}
390
+ <p>A key deAPI does not accept is refused with <code>401</code> as soon as the client
391
+ connects, so a client that reports an authentication error is telling you to fix the key.
392
+ Never put the key in the URL; it is only read from the headers above.</p>
393
+
394
+ <h2>Things to try</h2>
395
+ <ul>
396
+ <li>"Generate a 1024×1024 image of a lighthouse at dusk, watercolor style."</li>
397
+ <li>"Transcribe this video and give me timestamps: &lt;link&gt;"</li>
398
+ <li>"Read the text in this screenshot."</li>
399
+ <li>"Remove the background from this photo, then upscale it."</li>
400
+ <li>"Turn this image into a five-second clip."</li>
401
+ <li>"How much would that cost before you run it?"</li>
402
+ </ul>
403
+
404
+ <h2>Long jobs</h2>
405
+ <p>Video and long transcriptions can take minutes. A tool call waits up to 45 seconds; if
406
+ the job is still running it returns <code>done: false</code> with a <code>job_id</code>, and
407
+ <code>check_job_status</code> picks the wait up again. Your assistant does this for you.</p>
408
+
409
+ <h2 id=tools>Tools</h2>
410
+ {_tools_html(tools)}
411
+
412
+ <footer>
413
+ <a href="{HOME_URL}">{LOGO_SVG}</a>
414
+ <a href="{MCP_DOCS_URL}">MCP server docs</a><a href="{DOCS_URL}">deAPI docs</a><a
415
+ href="{KEYS_URL}">API keys</a><a href="{REPO_URL}">Source</a><a
416
+ href="{SECURITY_URL}">Security</a>
417
+ <span class=version>MCP Server {escape(__version__)}</span>
418
+ </footer>
419
+ </main>
420
+ </body>
421
+ </html>
422
+ """
423
+
424
+
425
+ def public_base_url(request: Request) -> str:
426
+ """The URL clients reach this server on: PUBLIC_BASE_URL, else the request's own."""
427
+ return os.getenv("PUBLIC_BASE_URL") or f"{request.url.scheme}://{request.url.netloc}"
428
+
429
+
430
+ def landing_response(base_url: str, tools: Sequence[Any]) -> Response:
431
+ return HTMLResponse(render_landing(base_url, tools), headers=SECURITY_HEADERS)