feat(agents): the pipeline as a platform — API keys, MCP server, webhooks

Agents don't forget to come back; humans do. Make the whole pipeline
drivable without the dashboard:

- API keys (osk_...): sha256-stored tokens minted from the account page.
  get_current_user_optional resolves them like a session, so metering,
  entitlement, priority and job ownership apply to agents with zero
  endpoint changes. Key management refuses API-key auth (a leaked key
  cannot mint replacements).
- MCP server at /mcp: stateless Streamable-HTTP JSON-RPC, no SDK
  dependency. Six tools (process_video, get_job_status, list_clips,
  get_quota, add_subtitles, publish_clip) that call back into this same
  app in-process via ASGITransport with the caller's auth headers, so
  MCP can never drift from REST behavior. Cloud requires a key;
  self-host stays BYOK-open.
- Completion webhooks: webhook_url (+ optional HMAC webhook_secret) on
  /api/process, SSRF-checked at submit AND delivery, fired once after
  the R2 archive so payloads carry durable links, survives redeploys
  via the resume manifest.
- Dashboard: API keys card in the account page (create once-shown key,
  list, revoke).
- Tests pin BILLING_ENABLED=0 in conftest so the suite no longer
  depends on the developer's personal .env.
This commit is contained in:
juancarlos.cavero 2026-08-03 22:12:46 +02:00
parent 18f2cf4dbd
commit f10655fd1c
14 changed files with 1237 additions and 7 deletions

View file

@ -173,6 +173,28 @@ se desactiva porque el modelo diga `none`.
| POST | `/api/translate` | AI voice dubbing via ElevenLabs |
| GET | `/api/translate/languages` | List supported dubbing languages |
| POST | `/api/social/post` | Post to social media (async upload) |
| POST | `/mcp` | MCP server (JSON-RPC): the pipeline as agent tools |
| POST/GET/DELETE | `/api/keys` | User API keys (cloud mode, session JWT only) |
### Agent access (MCP, API keys, webhooks)
- **API keys** (`cloud/api_keys.py`): `osk_...` tokens, sha256-stored, created in
the dashboard account page. `cloud/auth.get_current_user_optional` accepts
them (`Bearer osk_...` or `X-API-Key`) and resolves the owner, so metering,
entitlement, plan priority and job ownership apply to agents with zero
endpoint changes. Key management itself refuses API-key auth: a leaked key
cannot mint replacements.
- **MCP server** (`mcp_server.py`, mounted always): stateless Streamable-HTTP
JSON-RPC at `/mcp` — no SDK dependency, ~3 methods + 6 tools. Each tool calls
back into this same app in-process (`httpx.ASGITransport`) forwarding the
caller's auth headers, so it can never drift from the REST behavior. Cloud
mode 401s without a resolvable user; self-host stays BYOK-open.
- **Webhooks**: `POST /api/process` takes `webhook_url` + optional
`webhook_secret` (HMAC-SHA256, `X-OpenShorts-Signature`). Validated with
`security_utils.assert_public_url` at submit AND at delivery (DNS rebinding).
Fired once per job from `run_job_wrapper` after the R2 archive so the payload
can carry durable download links; survives redeploys via the resume manifest.
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
### Concurrency Model
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.

View file

@ -244,6 +244,51 @@ Navigate to **`http://localhost:5175`**
---
## Automate It: MCP Server, REST API and Webhooks
You don't need the dashboard. The whole pipeline is callable by AI agents and scripts.
### MCP server (`/mcp`)
OpenShorts ships a built-in [MCP](https://modelcontextprotocol.io) server, so Claude, ChatGPT, Cursor or any MCP client can clip and publish videos for you:
```bash
# Hosted (create an API key in your account page at openshorts.app):
claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
--header "Authorization: Bearer osk_..."
# Self-hosted (no key needed, BYOK rules apply):
claude mcp add --transport http openshorts http://localhost:8000/mcp
```
Tools: `process_video`, `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `publish_clip`. A prompt like *"clip this podcast and schedule the best 3 to TikTok"* is now a one-liner in your agent of choice.
### REST API + API keys
Hosted accounts can mint `osk_...` API keys (account page). A key authenticates as you everywhere — same plan, same minutes, same job ownership:
```bash
curl -X POST https://api.openshorts.app/api/process \
-H "Authorization: Bearer osk_..." -H "Content-Type: application/json" \
-d '{"url": "https://youtube.com/watch?v=...", "acknowledged": true,
"webhook_url": "https://your-server.com/hooks/openshorts"}'
```
Interactive docs at `/docs` (OpenAPI) on any instance.
### Completion webhooks
Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and you get exactly one `POST` when the job reaches a terminal state — no polling loops in your n8n / Zapier / cron pipelines:
```json
{"event": "job.completed", "job_id": "…",
"clips": [{"index": 0, "title": "…", "video_url": "…", "download_url": "…"}]}
```
With a secret, the body is signed: `X-OpenShorts-Signature: sha256=<hmac-sha256(body)>`.
---
## Tech Stack
| Layer | Technology |

146
app.py
View file

@ -492,7 +492,8 @@ _RESUME_FILE = ".resume.json"
MAX_RESUME_ATTEMPTS = 2
def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark):
def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark,
webhook_url=None, webhook_secret=None, base_url=None):
try:
path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE)
with open(path, "w") as f:
@ -501,6 +502,14 @@ def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, water
"user_id": None if user_id is None else str(user_id),
"reservation_id": reservation_id,
"watermark": bool(watermark), "attempts": 0,
# The caller's webhook must survive a redeploy: a pipeline that
# relies on the callback would otherwise hang forever on a job
# that resumed fine. The secret is the caller's own HMAC value,
# stored next to their video on the same disk — not a server
# credential (those are rebuilt from os.environ on resume).
"webhook_url": webhook_url,
"webhook_secret": webhook_secret,
"base_url": base_url,
}, f)
except Exception as e:
print(f"⚠️ Could not write resume manifest for {job_id}: {e}")
@ -591,6 +600,9 @@ def _resume_interrupted_jobs() -> set:
'user_id': None if user_id is None else user_id,
'reservation_id': reservation_id,
'watermark': bool(m.get("watermark")),
'webhook_url': m.get("webhook_url"),
'webhook_secret': m.get("webhook_secret"),
'base_url': m.get("base_url"),
}
if reservation_id:
keep_reservations.add(str(reservation_id))
@ -797,6 +809,8 @@ async def run_job_wrapper(job_id):
await _settle_reservation(job_id)
# Archive the completed clips to the user's durable R2 library (history).
await _archive_managed_job(job_id)
# Fire the caller's webhook (after archive, so durable links exist).
await _notify_job_webhook(job_id)
# Operational alerting for managed jobs (proxy out of credits / failures).
await _record_job_alert(job_id)
# Accumulate proxy bandwidth for the monthly cost alert.
@ -995,6 +1009,103 @@ async def _track_job_outcome(job, ok, err):
print(f"⚠️ Analytics error: {e}")
# --- Job completion webhooks --------------------------------------------------
# Agents and pipelines (n8n, cron, MCP clients) need push, not poll: a caller
# passes webhook_url on /api/process and gets one POST when the job reaches a
# terminal state. The URL goes through assert_public_url both at submit and at
# delivery time — the second check is what defeats DNS rebinding between them.
WEBHOOK_TIMEOUT = 10.0
WEBHOOK_RETRY_DELAYS = (0, 10, 60) # seconds before each attempt
def _sign_webhook(body: bytes, secret: str) -> str:
import hmac as _hmac
import hashlib as _hashlib
return "sha256=" + _hmac.new(secret.encode(), body, _hashlib.sha256).hexdigest()
async def _webhook_clip_entries(job_id, job):
"""The payload's clip list: absolute URLs, plus durable R2 links when the
job was archived (a webhook consumer usually fetches later, after the
1-hour local retention would have expired the /videos path)."""
base = (job.get('base_url') or os.environ.get("PUBLIC_API_URL", "")).rstrip("/")
clips = (job.get('result') or {}).get('clips') or []
entries = []
for i, clip in enumerate(clips):
rel = clip.get('video_url') or ""
entries.append({
"index": i,
"title": clip.get('title') or clip.get('video_title_for_youtube_short'),
"video_url": f"{base}{rel}" if rel.startswith("/") and base else rel,
})
if BILLING_ENABLED and job.get('user_id'):
try:
from sqlalchemy import select as _select
from cloud.database import session as cloud_session
from cloud.models import UserVideo
from cloud import storage as _storage
async with cloud_session() as s:
vids = list((await s.execute(
_select(UserVideo).where(UserVideo.job_id == job_id)
)).scalars())
for v in vids:
if v.clip_index is not None and v.clip_index < len(entries):
entries[v.clip_index]["download_url"] = _storage.presigned_get(
v.r2_key, expires=24 * 3600)
except Exception as e:
print(f"⚠️ Webhook R2 links failed for {job_id}: {e}")
return entries
async def _deliver_webhook(url, body: bytes, secret):
headers = {"Content-Type": "application/json", "User-Agent": "OpenShorts-Webhook/1.0"}
if secret:
headers["X-OpenShorts-Signature"] = _sign_webhook(body, secret)
from security_utils import assert_public_url, UnsafeURLError
loop = asyncio.get_event_loop()
for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1):
if delay:
await asyncio.sleep(delay)
try:
# Re-resolve on every attempt: the submit-time check is stale by now.
await loop.run_in_executor(None, assert_public_url, url)
async with httpx.AsyncClient(timeout=WEBHOOK_TIMEOUT,
follow_redirects=False) as client:
resp = await client.post(url, content=body, headers=headers)
if resp.status_code < 300:
print(f"🪝 Webhook delivered to {url} (attempt {attempt})")
return
print(f"⚠️ Webhook attempt {attempt} to {url}: HTTP {resp.status_code}")
except UnsafeURLError as e:
print(f"🛑 Webhook URL no longer safe, dropping: {e}")
return
except Exception as e:
print(f"⚠️ Webhook attempt {attempt} to {url} failed: {e}")
print(f"❌ Webhook to {url} gave up after {len(WEBHOOK_RETRY_DELAYS)} attempts.")
async def _notify_job_webhook(job_id):
"""Fire the caller's webhook for a terminal job. Runs inside run_job_wrapper's
finally AFTER the R2 archive, so durable links exist; the actual delivery
(with its retry sleeps) is detached so the worker slot frees immediately."""
job = jobs.get(job_id) or {}
url = job.get('webhook_url')
if not url or job.get('webhook_sent'):
return
job['webhook_sent'] = True
completed = job.get('status') == 'completed'
payload = {
"event": "job.completed" if completed else "job.failed",
"job_id": job_id,
"status": job.get('status'),
"clips": (await _webhook_clip_entries(job_id, job)) if completed else [],
}
if not completed:
payload["error"] = _job_error_text(job.get('logs', []))[-500:]
body = json.dumps(payload).encode()
asyncio.create_task(_deliver_webhook(url, body, job.get('webhook_secret')))
async def _settle_reservation(job_id):
if not BILLING_ENABLED:
return
@ -1031,6 +1142,11 @@ app = FastAPI(lifespan=lifespan)
if BILLING_ENABLED:
cloud.setup_sync(app)
# MCP server (/mcp): the pipeline as agent-callable tools. Works in both modes —
# cloud requires an osk_ API key, self-host keeps BYOK (see mcp_server.py).
import mcp_server as _mcp_server
app.include_router(_mcp_server.router)
# Enable CORS for frontend. Cloud mode locks this down to the configured origins;
# self-host keeps the permissive wildcard it has always used.
app.add_middleware(
@ -1328,7 +1444,9 @@ async def process_endpoint(
acknowledged: Optional[str] = Form(None),
output_format: Optional[str] = Form(None),
layouts: Optional[str] = Form(None),
force_low_quality: Optional[str] = Form(None)
force_low_quality: Optional[str] = Form(None),
webhook_url: Optional[str] = Form(None),
webhook_secret: Optional[str] = Form(None)
):
api_key = await resolve_gemini(request)
if not api_key:
@ -1346,6 +1464,8 @@ async def process_endpoint(
force_low = bool(body.get("force_low_quality"))
output_format = body.get("output_format")
layouts = body.get("layouts")
webhook_url = body.get("webhook_url")
webhook_secret = body.get("webhook_secret")
# Normalize output format (auto = keep pipeline default).
if output_format not in ("vertical", "horizontal", "square"):
@ -1360,6 +1480,16 @@ async def process_endpoint(
if not url and not file:
raise HTTPException(status_code=400, detail="Must provide URL or File")
# Completion callback: reject unsafe targets NOW (clear 400) — delivery
# re-validates anyway, but failing at submit is the debuggable behavior.
if webhook_url:
from security_utils import assert_public_url, UnsafeURLError
try:
await asyncio.get_event_loop().run_in_executor(
None, assert_public_url, webhook_url)
except UnsafeURLError as e:
raise HTTPException(status_code=400, detail=f"Invalid webhook_url: {e}")
if not ack_flag:
raise HTTPException(status_code=400, detail="You must confirm you own the content or have rights to process it.")
@ -1452,6 +1582,11 @@ async def process_endpoint(
# subprocess after each clip renders).
env["WATERMARK"] = "1"
# Absolute-URL base for the webhook payload: explicit env wins (the API may
# sit behind a proxy whose forwarded headers we can't trust), else what the
# caller connected to.
api_base = os.environ.get("PUBLIC_API_URL", "").rstrip("/") or str(request.base_url).rstrip("/")
# Enqueue Job
jobs[job_id] = {
'status': 'queued',
@ -1463,6 +1598,9 @@ async def process_endpoint(
'user_id': user_id,
'reservation_id': reservation_id,
'watermark': env.get("WATERMARK") == "1",
'webhook_url': webhook_url,
'webhook_secret': webhook_secret,
'base_url': api_base,
}
# Persist the owner so recovered jobs keep their multi-tenant guard after a
@ -1478,7 +1616,9 @@ async def process_endpoint(
# Resume manifest: enough to re-run this job if the container dies mid-flight
# (a redeploy). No secrets — the env is rebuilt from os.environ on resume.
_write_resume_manifest(job_id, cmd, priority, user_id, reservation_id,
watermark=jobs[job_id]['watermark'])
watermark=jobs[job_id]['watermark'],
webhook_url=webhook_url, webhook_secret=webhook_secret,
base_url=api_base)
_enqueue_job(job_id, priority)

View file

@ -26,7 +26,7 @@ def setup_sync(app):
from starlette.middleware.sessions import SessionMiddleware
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
from . import auth, oauth, billing, social_profiles, videos
from . import auth, oauth, billing, social_profiles, videos, api_keys
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
@ -34,6 +34,7 @@ def setup_sync(app):
app.include_router(billing.router)
app.include_router(social_profiles.router)
app.include_router(videos.router)
app.include_router(api_keys.router)
async def setup_async(app, keep_reservation_ids=None):

147
cloud/api_keys.py Normal file
View file

@ -0,0 +1,147 @@
"""User API keys (``osk_...``) for programmatic access: MCP clients, scripts, CI.
Two halves:
- Management endpoints (create / list / revoke). These require a SESSION JWT,
never an API key — a leaked key must not be able to mint replacement keys
for the same account.
- ``user_id_for_key``: the resolver cloud/auth.py calls so a Bearer
``osk_...`` (or ``X-API-Key``) authenticates like a session everywhere else.
Quota, entitlement and job ownership then apply unchanged.
"""
import hashlib
import secrets
from datetime import datetime, timezone, timedelta
from typing import Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select, func, and_
from . import database
from .models import ApiKey
router = APIRouter()
KEY_PREFIX = "osk_"
MAX_ACTIVE_KEYS = 10
# last_used_at is informational; refreshing it on every /api/status poll would
# write the row hundreds of times per job for no extra signal.
LAST_USED_REFRESH = timedelta(minutes=5)
def _now():
return datetime.now(timezone.utc)
def hash_key(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
def generate_key() -> tuple[str, str, str]:
"""Return (raw, sha256, display_prefix) for a fresh key."""
raw = KEY_PREFIX + secrets.token_urlsafe(32)
return raw, hash_key(raw), raw[: len(KEY_PREFIX) + 6]
def looks_like_key(token: str) -> bool:
return isinstance(token, str) and token.startswith(KEY_PREFIX)
async def user_id_for_key(raw: str) -> Optional[object]:
"""Resolve a raw ``osk_`` token to its owner's user id, or None.
Refreshes ``last_used_at`` at most every LAST_USED_REFRESH so status polls
don't turn every request into a DB write.
"""
if not looks_like_key(raw):
return None
token_hash = hash_key(raw)
async with database.session() as session:
async with session.begin():
row = (await session.execute(
select(ApiKey).where(ApiKey.key_hash == token_hash)
)).scalar_one_or_none()
if row is None or row.revoked_at is not None:
return None
if row.last_used_at is None or _now() - row.last_used_at > LAST_USED_REFRESH:
row.last_used_at = _now()
return row.user_id
# --------------------------------------------------------------------------- #
# Management endpoints (session JWT only)
# --------------------------------------------------------------------------- #
async def _session_user(request: Request):
"""The signed-in user, refusing API-key auth for key management."""
from .auth import get_current_user_required
auth = request.headers.get("Authorization", "")
if looks_like_key(auth[7:].strip()) or looks_like_key(request.headers.get("X-API-Key", "")):
raise HTTPException(status_code=403,
detail="API keys cannot manage API keys. Sign in to the dashboard.")
return await get_current_user_required(request)
class CreateKeyRequest(BaseModel):
name: Optional[str] = None
@router.post("/api/keys")
async def create_key(payload: CreateKeyRequest, request: Request):
user = await _session_user(request)
raw, token_hash, prefix = generate_key()
name = (payload.name or "").strip()[:60] or "API key"
async with database.session() as session:
async with session.begin():
active = (await session.execute(
select(func.count(ApiKey.id)).where(and_(
ApiKey.user_id == user.id, ApiKey.revoked_at.is_(None),
))
)).scalar_one()
if active >= MAX_ACTIVE_KEYS:
raise HTTPException(status_code=400,
detail=f"Limit of {MAX_ACTIVE_KEYS} active keys reached. Revoke one first.")
row = ApiKey(user_id=user.id, name=name, key_hash=token_hash, prefix=prefix)
session.add(row)
await session.flush()
key_id = row.id
# The raw key appears here once and is never retrievable again.
return {"id": str(key_id), "name": name, "prefix": prefix, "key": raw}
@router.get("/api/keys")
async def list_keys(request: Request):
user = await _session_user(request)
async with database.session() as session:
rows = list((await session.execute(
select(ApiKey).where(ApiKey.user_id == user.id)
.order_by(ApiKey.created_at.desc()).limit(100)
)).scalars())
return {"keys": [{
"id": str(k.id),
"name": k.name,
"prefix": k.prefix,
"created_at": k.created_at.isoformat() if k.created_at else None,
"last_used_at": k.last_used_at.isoformat() if k.last_used_at else None,
"revoked": k.revoked_at is not None,
} for k in rows]}
@router.delete("/api/keys/{key_id}")
async def revoke_key(key_id: str, request: Request):
user = await _session_user(request)
import uuid
try:
key_uuid = uuid.UUID(key_id)
except ValueError:
raise HTTPException(status_code=404, detail="Key not found")
async with database.session() as session:
async with session.begin():
row = (await session.execute(
select(ApiKey).where(ApiKey.id == key_uuid)
)).scalar_one_or_none()
if row is None or str(row.user_id) != str(user.id):
raise HTTPException(status_code=404, detail="Key not found")
if row.revoked_at is None:
row.revoked_at = _now()
return {"ok": True}

View file

@ -98,11 +98,29 @@ async def _load_current_user(session, user_id) -> Optional["CurrentUser"]:
async def get_current_user_optional(request: Request) -> Optional[CurrentUser]:
"""Return the authenticated user, or None for anonymous / BYOK requests."""
"""Return the authenticated user, or None for anonymous / BYOK requests.
Accepts either a session JWT (``Bearer <jwt>``) or a user API key
(``Bearer osk_...`` / ``X-API-Key``). A key authenticates as its owner, so
quota, entitlement and job ownership apply to agents exactly as to the
dashboard — no parallel auth path to keep in sync.
"""
from . import api_keys
auth = request.headers.get("Authorization", "")
if not auth.lower().startswith("bearer "):
token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
api_token = token if api_keys.looks_like_key(token) else request.headers.get("X-API-Key", "")
if api_keys.looks_like_key(api_token):
user_id = await api_keys.user_id_for_key(api_token)
if user_id is None:
return None
payload = _decode_jwt(auth[7:].strip())
async with database.session() as session:
return await _load_current_user(session, user_id)
if not token:
return None
payload = _decode_jwt(token)
if not payload:
return None
try:

View file

@ -117,6 +117,29 @@ class SignupAttribution(Base):
)
class ApiKey(Base):
"""A user-issued ``osk_...`` token for programmatic access (MCP, scripts, CI).
Only the sha256 of the raw token is stored — the raw value is shown once at
creation and never again. ``prefix`` keeps the first characters so the UI
can tell keys apart. Revocation is a timestamp rather than a delete so a
leaked-then-revoked key stays visible in the user's list with its history.
Its own table (not columns on ``users``) because the schema bootstrap is
``create_all`` — see [SignupAttribution] above for the same reasoning.
"""
__tablename__ = "api_keys"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
name = Column(Text, nullable=False)
key_hash = Column(Text, unique=True, nullable=False) # sha256 of the raw osk_ token
prefix = Column(Text, nullable=False) # e.g. "osk_a1b2c3" (display only)
created_at = Column(DateTime(timezone=True), server_default=func.now())
last_used_at = Column(DateTime(timezone=True), nullable=True)
revoked_at = Column(DateTime(timezone=True), nullable=True)
class UploadPostProfile(Base):
__tablename__ = "upload_post_profiles"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),

View file

@ -3,6 +3,7 @@ import { Loader2, CreditCard, LogOut, Plus } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import ApiKeysCard from './ApiKeysCard';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
@ -197,6 +198,8 @@ export default function AccountPage() {
</div>
</div>
)}
<ApiKeysCard />
</div>
);
}

View file

@ -0,0 +1,117 @@
import React, { useState, useEffect, useCallback } from 'react';
import { KeyRound, Plus, Trash2, Copy, Check, Loader2 } from 'lucide-react';
import { apiJson } from '../lib/api';
// API keys for programmatic access (MCP clients, scripts, n8n). The raw key is
// returned exactly once by POST /api/keys, so it is surfaced in a one-time
// banner the user must copy before it disappears.
export default function ApiKeysCard() {
const [keys, setKeys] = useState(null);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const [freshKey, setFreshKey] = useState(null); // { key, name } shown once
const [copied, setCopied] = useState(false);
const load = useCallback(() => {
apiJson('/api/keys').then((d) => setKeys(d.keys || [])).catch(() => setKeys([]));
}, []);
useEffect(() => { load(); }, [load]);
const createKey = useCallback(async () => {
setBusy(true);
try {
const d = await apiJson('/api/keys', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name.trim() || undefined }),
});
setFreshKey(d);
setCopied(false);
setName('');
load();
} catch (e) { alert(e?.detail || 'Could not create the key.'); }
setBusy(false);
}, [name, load]);
const revoke = useCallback(async (k) => {
if (!window.confirm(`Revoke "${k.name}"? Anything using it stops working immediately.`)) return;
try {
await apiJson(`/api/keys/${k.id}`, { method: 'DELETE' });
load();
} catch (e) { alert(e?.detail || 'Could not revoke the key.'); }
}, [load]);
const copyKey = useCallback(() => {
navigator.clipboard?.writeText(freshKey.key).then(() => setCopied(true)).catch(() => {});
}, [freshKey]);
const active = (keys || []).filter((k) => !k.revoked);
return (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<KeyRound size={16} className="text-brass" /> API keys
</h3>
<p className="text-muted text-sm mb-4">
Automate OpenShorts from agents and scripts. Connect any MCP client to{' '}
<code className="readout">https://mcp.openshorts.app/mcp</code> with{' '}
<code className="readout">Authorization: Bearer &lt;key&gt;</code>, or call the REST API
directly. Keys use your plan's minutes.
</p>
{freshKey && (
<div className="mb-4 rounded-card border border-brass/40 bg-brass/5 p-3 text-sm">
<p className="text-ink mb-2">
<b>Copy your new key now.</b> For security it will never be shown again.
</p>
<div className="flex items-center gap-2">
<code className="readout flex-1 break-all select-all">{freshKey.key}</code>
<button onClick={copyKey} className="btn-ghost px-3 py-1.5 shrink-0">
{copied ? <Check size={14} /> : <Copy size={14} />} {copied ? 'Copied' : 'Copy'}
</button>
</div>
</div>
)}
{keys === null ? (
<div className="flex justify-center py-4"><Loader2 className="animate-spin text-brass" size={18} /></div>
) : (
<>
{active.length > 0 && (
<div className="space-y-2 mb-4">
{active.map((k) => (
<div key={k.id} className="flex items-center justify-between gap-3 border border-rule rounded-card px-3 py-2 text-sm">
<div className="min-w-0">
<span className="text-ink">{k.name}</span>{' '}
<code className="readout">{k.prefix}…</code>
</div>
<div className="flex items-center gap-3 shrink-0">
<span className="text-muted text-xs lowercase">
{k.last_used_at ? `used ${new Date(k.last_used_at).toLocaleDateString()}` : 'never used'}
</span>
<button onClick={() => revoke(k)} title="Revoke key"
className="text-muted hover:text-warn transition-colors">
<Trash2 size={15} />
</button>
</div>
</div>
))}
</div>
)}
<div className="flex gap-2">
<input
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') createKey(); }}
placeholder="Key name (e.g. n8n, claude)"
className="input-field flex-1 text-sm"
maxLength={60}
/>
<button onClick={createKey} disabled={busy} className="btn-ghost px-4 py-2 shrink-0">
{busy ? <Loader2 size={16} className="animate-spin" /> : <Plus size={16} />} Create key
</button>
</div>
</>
)}
</div>
);
}

441
mcp_server.py Normal file
View file

@ -0,0 +1,441 @@
"""Remote MCP server: the whole pipeline as agent-callable tools at ``/mcp``.
Stateless Streamable-HTTP transport (plain JSON responses, no SSE, no session
ids) implemented directly over FastAPI — the protocol surface an MCP client
actually needs for tools is three methods (initialize / tools/list / tools/call)
plus notifications, and owning those ~200 lines beats carrying the full SDK as
a dependency for them.
Tools don't reimplement anything: each one is an in-process HTTP call back into
this same app (httpx ASGITransport) with the caller's auth headers forwarded.
Cloud mode therefore meters, gates and scopes agent calls exactly like
dashboard calls — an ``osk_`` API key IS the user (see cloud/api_keys.py).
Self-host keeps its BYOK semantics: no key required, ``X-Gemini-Key`` /
env fallbacks apply unchanged.
Connect with any MCP client, e.g.:
claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
--header "Authorization: Bearer osk_..."
(mcp.openshorts.app is a domain alias of the API app; api.openshorts.app/mcp
serves the identical endpoint.)
"""
import json
import os
from typing import Optional
import httpx
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, Response
router = APIRouter()
PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
SERVER_INFO = {"name": "openshorts", "title": "OpenShorts", "version": "1.0.0"}
INSTRUCTIONS = (
"OpenShorts turns long videos (YouTube URLs) into viral-ready vertical "
"clips. Typical flow: process_video -> poll get_job_status until "
"'completed' (a job takes minutes; poll every 30-60s or pass webhook_url) "
"-> list_clips -> optionally add_subtitles / publish_clip. Check "
"get_quota before large jobs."
)
# Headers an MCP caller may use to authenticate / bring their own keys; they are
# forwarded verbatim to the internal endpoints so every existing auth path works.
_FORWARD_HEADERS = ("authorization", "x-api-key", "x-gemini-key", "x-upload-post-key")
_LOG_TAIL = 10 # status logs are for humans; agents only need the tail
TOOLS = [
{
"name": "process_video",
"title": "Process a video into short clips",
"description": (
"Start clipping a video: downloads the source, transcribes it, finds "
"the most viral moments with AI and renders vertical (9:16) clips "
"with captions. Returns a job_id immediately — the work takes "
"minutes; poll get_job_status or pass webhook_url to be called back. "
"The caller must own the content or hold the rights to process it "
"(confirm_rights)."
),
"inputSchema": {
"type": "object",
"properties": {
"source_url": {
"type": "string",
"description": "Public video URL (YouTube or a direct video file URL).",
},
"confirm_rights": {
"type": "boolean",
"description": "Must be true: the user owns the content or has rights to process it.",
},
"layouts": {
"type": "array",
"items": {"type": "string",
"enum": ["auto", "split", "screencast", "speaker_cut", "punch_in"]},
"description": "Optional extra reframe layouts. 'auto' lets AI pick per video.",
},
"output_format": {
"type": "string",
"enum": ["auto", "vertical", "horizontal", "square"],
"description": "Clip aspect. Default auto (vertical).",
},
"webhook_url": {
"type": "string",
"description": "Optional public HTTPS URL POSTed once when the job finishes or fails.",
},
"webhook_secret": {
"type": "string",
"description": "Optional secret; the webhook body is then HMAC-SHA256 signed (X-OpenShorts-Signature).",
},
"force_low_quality": {
"type": "boolean",
"description": "Set true to proceed after a needs_confirmation low-resolution warning.",
},
},
"required": ["source_url", "confirm_rights"],
},
},
{
"name": "get_job_status",
"title": "Get processing job status",
"description": (
"Status of a processing job: 'queued', 'processing', 'completed' or "
"'failed', with recent log lines and, once completed, the clips."
),
"inputSchema": {
"type": "object",
"properties": {"job_id": {"type": "string"}},
"required": ["job_id"],
},
},
{
"name": "list_clips",
"title": "List a job's clips",
"description": (
"The clips of a completed job, with titles, platform-ready "
"descriptions and download URLs."
),
"inputSchema": {
"type": "object",
"properties": {"job_id": {"type": "string"}},
"required": ["job_id"],
},
},
{
"name": "get_quota",
"title": "Get plan and remaining minutes",
"description": (
"The authenticated user's plan and remaining processing minutes. "
"Call before large jobs; process_video fails with quota_exceeded "
"when the balance is insufficient."
),
"inputSchema": {"type": "object", "properties": {}},
},
{
"name": "add_subtitles",
"title": "Burn styled captions onto a clip",
"description": (
"Re-style the captions of one clip (clips already ship with default "
"captions). style 'karaoke' highlights the active word."
),
"inputSchema": {
"type": "object",
"properties": {
"job_id": {"type": "string"},
"clip_index": {"type": "integer", "description": "0-based index from list_clips."},
"style": {"type": "string", "enum": ["classic", "karaoke"]},
"position": {"type": "string", "enum": ["top", "middle", "bottom"]},
"font_size": {"type": "integer"},
"font_name": {"type": "string"},
"font_color": {"type": "string", "description": "Hex color, e.g. #FFFFFF."},
"highlight_color": {"type": "string", "description": "Karaoke active-word color."},
"uppercase": {"type": "boolean"},
},
"required": ["job_id", "clip_index"],
},
},
{
"name": "publish_clip",
"title": "Publish a clip to social platforms",
"description": (
"Post one clip to the user's connected accounts (TikTok lands as a "
"draft in the app; Instagram and YouTube publish directly). Requires "
"a connected social profile (cloud) or an Upload-Post key (self-host). "
"Optionally schedule with an ISO-8601 scheduled_date."
),
"inputSchema": {
"type": "object",
"properties": {
"job_id": {"type": "string"},
"clip_index": {"type": "integer"},
"platforms": {
"type": "array",
"items": {"type": "string", "enum": ["tiktok", "instagram", "youtube"]},
},
"title": {"type": "string"},
"description": {"type": "string"},
"scheduled_date": {"type": "string", "description": "ISO-8601; omit to post now."},
"timezone": {"type": "string"},
},
"required": ["job_id", "clip_index", "platforms"],
},
},
]
# --------------------------------------------------------------------------- #
# Internal dispatch: each tool is an in-process call to the existing REST API.
# --------------------------------------------------------------------------- #
def _client(request: Request) -> httpx.AsyncClient:
headers = {k: v for k, v in request.headers.items() if k.lower() in _FORWARD_HEADERS}
return httpx.AsyncClient(
transport=httpx.ASGITransport(app=request.app, raise_app_exceptions=False),
base_url="http://openshorts.internal",
headers=headers,
timeout=300.0,
)
def _api_error(resp: httpx.Response) -> dict:
try:
detail = resp.json().get("detail")
except Exception:
detail = resp.text[:300]
return {"error": detail or f"HTTP {resp.status_code}", "http_status": resp.status_code}
async def _tool_process_video(client, args):
if not args.get("confirm_rights"):
return {"error": "confirm_rights must be true: the user must own the "
"content or hold the rights to process it."}, True
body = {
"url": args["source_url"],
"acknowledged": True,
"layouts": args.get("layouts") or [],
"output_format": args.get("output_format"),
"force_low_quality": bool(args.get("force_low_quality")),
"webhook_url": args.get("webhook_url"),
"webhook_secret": args.get("webhook_secret"),
}
resp = await client.post("/api/process", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
data = resp.json()
if data.get("needs_confirmation"):
data["hint"] = ("Source resolution is below the quality gate. Ask the "
"user, then retry with force_low_quality=true to proceed.")
return data, False
data["hint"] = ("Processing takes minutes. Poll get_job_status every 30-60s"
+ ("" if body["webhook_url"] else " (or re-run with webhook_url for a callback)") + ".")
return data, False
async def _tool_get_job_status(client, args):
resp = await client.get(f"/api/status/{args['job_id']}")
if resp.status_code >= 400:
return _api_error(resp), True
data = resp.json()
out = {"job_id": args["job_id"], "status": data.get("status"),
"recent_logs": (data.get("logs") or [])[-_LOG_TAIL:]}
if data.get("status") == "completed":
out["clips"] = _clip_summaries(args["job_id"], data.get("result") or {})
return out, data.get("status") == "failed"
def _clip_summaries(job_id, result):
base = os.environ.get("PUBLIC_API_URL", "").rstrip("/")
out = []
for i, clip in enumerate(result.get("clips") or []):
rel = clip.get("video_url") or ""
out.append({
"index": i,
"title": clip.get("title") or clip.get("video_title_for_youtube_short"),
"duration_seconds": (round(clip["end"] - clip["start"], 1)
if isinstance(clip.get("start"), (int, float))
and isinstance(clip.get("end"), (int, float)) else None),
"video_url": f"{base}{rel}" if base and rel.startswith("/") else rel,
"youtube_title": clip.get("video_title_for_youtube_short"),
"tiktok_description": clip.get("video_description_for_tiktok"),
"instagram_description": clip.get("video_description_for_instagram"),
})
return out
async def _tool_list_clips(client, args):
out, is_error = await _tool_get_job_status(client, args)
if is_error:
return out, True
if out.get("status") != "completed":
return {"error": f"Job is {out.get('status')}, clips are not ready yet.",
"status": out.get("status")}, True
return {"job_id": args["job_id"], "clips": out.get("clips") or []}, False
async def _tool_get_quota(client, args):
resp = await client.get("/api/me")
# 401: anonymous. 404: self-host, where /api/me isn't even mounted (the
# cloud router only registers under BILLING_ENABLED). Neither is an error
# from the agent's point of view — there is simply no quota to report.
if resp.status_code in (401, 404):
return {"self_host_or_anonymous": True,
"note": "No authenticated cloud user; if this is a self-hosted "
"instance there is no minute quota."}, False
if resp.status_code >= 400:
return _api_error(resp), True
data = resp.json()
return {"plan": data.get("plan"), "entitled": data.get("entitled"),
"minutes": data.get("minutes"),
"upload_post_profile": data.get("upload_post_profile")}, False
async def _tool_add_subtitles(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"]}
for k in ("style", "position", "font_size", "font_name", "font_color",
"highlight_color", "uppercase"):
if args.get(k) is not None:
body[k] = args[k]
resp = await client.post("/api/subtitle", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
return resp.json(), False
async def _tool_publish_clip(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"],
"platforms": args["platforms"]}
for k in ("title", "description", "scheduled_date", "timezone"):
if args.get(k) is not None:
body[k] = args[k]
resp = await client.post("/api/social/post", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
return resp.json(), False
_TOOL_IMPLS = {
"process_video": _tool_process_video,
"get_job_status": _tool_get_job_status,
"list_clips": _tool_list_clips,
"get_quota": _tool_get_quota,
"add_subtitles": _tool_add_subtitles,
"publish_clip": _tool_publish_clip,
}
async def call_tool(request: Request, name: str, args: dict) -> tuple[dict, bool]:
impl = _TOOL_IMPLS.get(name)
if impl is None:
return {"error": f"Unknown tool: {name}"}, True
try:
async with _client(request) as client:
return await impl(client, args or {})
except KeyError as e:
return {"error": f"Missing required argument: {e}"}, True
except Exception as e:
return {"error": f"Tool failed: {e}"}, True
# --------------------------------------------------------------------------- #
# JSON-RPC / MCP protocol layer (pure: testable without the app)
# --------------------------------------------------------------------------- #
def _rpc_error(msg_id, code, message):
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}
def _rpc_result(msg_id, result):
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
async def handle_message(msg, tool_caller) -> Optional[dict]:
"""One JSON-RPC message in, one response dict out (None for notifications).
``tool_caller(name, args) -> (result_dict, is_error)`` is injected so this
layer stays free of HTTP and app state.
"""
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
return _rpc_error(None, -32600, "Expected a JSON-RPC 2.0 message")
method = msg.get("method")
msg_id = msg.get("id")
if method is None:
# A response from the client (has 'result'/'error') — nothing to do.
return None
if msg_id is None:
return None # notification (e.g. notifications/initialized): accept silently
if method == "initialize":
client_version = (msg.get("params") or {}).get("protocolVersion")
version = client_version if client_version in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
return _rpc_result(msg_id, {
"protocolVersion": version,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": SERVER_INFO,
"instructions": INSTRUCTIONS,
})
if method == "ping":
return _rpc_result(msg_id, {})
if method == "tools/list":
return _rpc_result(msg_id, {"tools": TOOLS})
if method == "tools/call":
params = msg.get("params") or {}
name = params.get("name")
result, is_error = await tool_caller(name, params.get("arguments") or {})
return _rpc_result(msg_id, {
"content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}],
"structuredContent": result,
"isError": is_error,
})
return _rpc_error(msg_id, -32601, f"Method not found: {method}")
# --------------------------------------------------------------------------- #
# Transport endpoints
# --------------------------------------------------------------------------- #
def _billing_enabled() -> bool:
return os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", "yes")
async def _authorized(request: Request) -> bool:
"""Cloud mode requires a resolvable user (API key or JWT) before any RPC.
The internal endpoints would each reject anonymous calls anyway; failing
once here with a clear 401 is what lets MCP clients surface 'add your API
key' instead of a per-tool 402. Self-host stays open (BYOK)."""
if not _billing_enabled():
return True
from cloud.auth import get_current_user_optional
return (await get_current_user_optional(request)) is not None
@router.post("/mcp")
async def mcp_endpoint(request: Request):
if not await _authorized(request):
return JSONResponse(
{"error": "Authentication required. Pass an OpenShorts API key: "
"Authorization: Bearer osk_... (create one in the dashboard)."},
status_code=401,
headers={"WWW-Authenticate": "Bearer"},
)
try:
msg = json.loads(await request.body())
except Exception:
return JSONResponse(_rpc_error(None, -32700, "Parse error"), status_code=400)
if isinstance(msg, list):
return JSONResponse(_rpc_error(None, -32600, "Batching is not supported"),
status_code=400)
async def tool_caller(name, args):
return await call_tool(request, name, args)
response = await handle_message(msg, tool_caller)
if response is None:
return Response(status_code=202)
return JSONResponse(response)
@router.get("/mcp")
async def mcp_get():
# Stateless server: no server-initiated SSE stream to offer.
return Response(status_code=405, headers={"Allow": "POST"})

View file

@ -3,3 +3,9 @@ import sys
# Make the repo root importable so tests can import the app modules directly.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Tests always run the app in self-host (BYOK) mode. app.py freezes
# BILLING_ENABLED at import time and load_dotenv never overrides an existing
# variable, so this must be set here — before any test module imports app — or
# the suite's behavior would depend on the developer's personal .env.
os.environ["BILLING_ENABLED"] = "0"

42
tests/test_api_keys.py Normal file
View file

@ -0,0 +1,42 @@
"""API-key token semantics (cloud/api_keys.py).
The raw ``osk_`` value is shown once and only its sha256 is stored, so the
format and hashing rules are load-bearing: a drifting prefix would break
``looks_like_key`` routing in cloud/auth.py, and a non-deterministic hash would
lock every issued key out of the resolver.
"""
from cloud.api_keys import KEY_PREFIX, generate_key, hash_key, looks_like_key
class TestKeyGeneration:
def test_raw_key_carries_the_prefix(self):
raw, _hash, _prefix = generate_key()
assert raw.startswith(KEY_PREFIX)
def test_hash_matches_rehashing_the_raw_value(self):
raw, token_hash, _prefix = generate_key()
assert hash_key(raw) == token_hash
def test_display_prefix_is_a_prefix_of_the_raw_key(self):
raw, _hash, prefix = generate_key()
assert raw.startswith(prefix)
# Long enough to tell keys apart, short enough to be useless to guess.
assert len(prefix) < len(raw) / 3
def test_keys_are_unique(self):
assert generate_key()[0] != generate_key()[0]
def test_raw_key_has_enough_entropy(self):
raw, _hash, _prefix = generate_key()
assert len(raw) >= len(KEY_PREFIX) + 40 # token_urlsafe(32) ≈ 43 chars
class TestLooksLikeKey:
def test_accepts_generated_keys(self):
assert looks_like_key(generate_key()[0])
def test_rejects_jwts_and_junk(self):
assert not looks_like_key("eyJhbGciOiJIUzI1NiJ9.e30.abc")
assert not looks_like_key("")
assert not looks_like_key(None)
assert not looks_like_key(123)

142
tests/test_mcp_endpoint.py Normal file
View file

@ -0,0 +1,142 @@
"""End-to-end MCP transport against the real app (self-host mode, no DB).
Exercises the exact path an agent takes: HTTP POST /mcp -> JSON-RPC -> tool ->
in-process call back into the REST API -> real jobs dict. BILLING is off in the
test environment, so no cloud auth or database is involved — which is itself
the contract being tested: self-host must serve MCP without any of that.
"""
import asyncio
# Self-host mode is guaranteed by tests/conftest.py (BILLING_ENABLED=0), which
# runs before any test module can import app.
import httpx
import app as app_module
from app import app
def _post(payload):
async def _run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:
return await client.post("/mcp", json=payload)
return asyncio.run(_run())
def _call(tool, arguments, msg_id=1):
return _post({"jsonrpc": "2.0", "id": msg_id, "method": "tools/call",
"params": {"name": tool, "arguments": arguments}})
class TestTransport:
def test_initialize_over_http(self):
resp = _post({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2025-06-18"}})
assert resp.status_code == 200
assert resp.json()["result"]["serverInfo"]["name"] == "openshorts"
def test_notification_gets_202(self):
resp = _post({"jsonrpc": "2.0", "method": "notifications/initialized"})
assert resp.status_code == 202
def test_batch_is_rejected(self):
resp = _post([{"jsonrpc": "2.0", "id": 1, "method": "ping"}])
assert resp.status_code == 400
def test_get_is_405(self):
async def _run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:
return await client.get("/mcp")
assert asyncio.run(_run()).status_code == 405
class TestToolsThroughRealEndpoints:
def test_get_job_status_of_a_real_in_memory_job(self):
app_module.jobs["mcp-test-job"] = {
"status": "completed",
"logs": ["line"] * 30,
"result": {"clips": [{"title": "A clip", "video_url": "/videos/mcp-test-job/c1.mp4",
"start": 10.0, "end": 25.5}]},
}
try:
resp = _call("get_job_status", {"job_id": "mcp-test-job"})
result = resp.json()["result"]
assert result["isError"] is False
data = result["structuredContent"]
assert data["status"] == "completed"
assert len(data["recent_logs"]) == 10 # agents get the tail, not 30 lines
assert data["clips"][0]["duration_seconds"] == 15.5
finally:
app_module.jobs.pop("mcp-test-job", None)
def test_unknown_job_is_a_tool_error_not_a_crash(self):
resp = _call("get_job_status", {"job_id": "no-such-job"})
result = resp.json()["result"]
assert result["isError"] is True
assert result["structuredContent"]["http_status"] == 404
def test_process_video_requires_rights_confirmation(self):
resp = _call("process_video",
{"source_url": "https://example.com/v.mp4", "confirm_rights": False})
result = resp.json()["result"]
assert result["isError"] is True
assert "confirm_rights" in result["structuredContent"]["error"]
def test_unknown_tool_is_a_tool_error(self):
resp = _call("make_coffee", {})
assert resp.json()["result"]["isError"] is True
class TestSelfHostQuota:
def test_get_quota_reports_no_quota_instead_of_erroring(self):
# /api/me only exists in cloud mode; self-host must get the friendly
# "no quota here" answer, not a 404 tool error.
resp = _call("get_quota", {})
result = resp.json()["result"]
assert result["isError"] is False
assert result["structuredContent"]["self_host_or_anonymous"] is True
class TestCloudModeAuth:
"""mcp_server reads BILLING_ENABLED per request (unlike app.py, which
freezes it at import), so cloud-mode gating is testable by env patch."""
def test_401_without_credentials(self, monkeypatch):
monkeypatch.setenv("BILLING_ENABLED", "1")
resp = _post({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
assert resp.status_code == 401
assert resp.headers.get("www-authenticate") == "Bearer"
assert "osk_" in resp.json()["error"] # the fix is named in the message
def test_resolvable_user_passes(self, monkeypatch):
monkeypatch.setenv("BILLING_ENABLED", "1")
import cloud.auth as cloud_auth
async def fake_user(request):
return object()
monkeypatch.setattr(cloud_auth, "get_current_user_optional", fake_user)
resp = _post({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
assert resp.status_code == 200
assert resp.json()["result"]["serverInfo"]["name"] == "openshorts"
class TestWebhookSigning:
def test_signature_is_deterministic_hmac(self):
import hashlib
import hmac
body = b'{"event":"job.completed"}'
expected = "sha256=" + hmac.new(b"s3cret", body, hashlib.sha256).hexdigest()
assert app_module._sign_webhook(body, "s3cret") == expected
def test_process_rejects_private_webhook_targets(self):
async def _run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:
return await client.post("/api/process", json={
"url": "https://example.com/v.mp4", "acknowledged": True,
"webhook_url": "http://169.254.169.254/latest/meta-data/",
})
resp = asyncio.run(_run())
assert resp.status_code == 400
assert "webhook_url" in resp.json()["detail"]

View file

@ -0,0 +1,83 @@
"""MCP protocol layer (mcp_server.handle_message).
The handler is deliberately pure — tool execution is injected — so the whole
JSON-RPC surface an MCP client depends on (initialize negotiation, silent
notifications, tools/list, tools/call wrapping, error codes) is testable
without the FastAPI app or a database.
"""
import asyncio
from mcp_server import PROTOCOL_VERSIONS, TOOLS, _TOOL_IMPLS, handle_message
async def _ok_tool(name, args):
return {"echo": {"name": name, "args": args}}, False
async def _err_tool(name, args):
return {"error": "boom"}, True
def _run(msg, tool_caller=_ok_tool):
return asyncio.run(handle_message(msg, tool_caller))
class TestInitialize:
def test_echoes_a_supported_client_version(self):
resp = _run({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": PROTOCOL_VERSIONS[-1]}})
assert resp["result"]["protocolVersion"] == PROTOCOL_VERSIONS[-1]
def test_falls_back_to_latest_for_unknown_versions(self):
resp = _run({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "1999-01-01"}})
assert resp["result"]["protocolVersion"] == PROTOCOL_VERSIONS[0]
def test_advertises_tools_capability(self):
resp = _run({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
assert "tools" in resp["result"]["capabilities"]
assert resp["result"]["serverInfo"]["name"] == "openshorts"
class TestNotificationsAndErrors:
def test_notification_returns_none(self):
assert _run({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None
def test_unknown_method_is_32601(self):
resp = _run({"jsonrpc": "2.0", "id": 7, "method": "resources/list"})
assert resp["error"]["code"] == -32601
assert resp["id"] == 7
def test_non_jsonrpc_message_is_32600(self):
resp = _run({"not": "jsonrpc"})
assert resp["error"]["code"] == -32600
def test_ping_answers_empty_result(self):
assert _run({"jsonrpc": "2.0", "id": 2, "method": "ping"})["result"] == {}
class TestTools:
def test_list_matches_the_implementations(self):
resp = _run({"jsonrpc": "2.0", "id": 3, "method": "tools/list"})
listed = {t["name"] for t in resp["result"]["tools"]}
assert listed == set(_TOOL_IMPLS)
def test_every_tool_declares_an_object_schema(self):
for tool in TOOLS:
assert tool["inputSchema"]["type"] == "object", tool["name"]
for req in tool["inputSchema"].get("required", []):
assert req in tool["inputSchema"]["properties"], tool["name"]
def test_call_wraps_result_as_text_and_structured(self):
resp = _run({"jsonrpc": "2.0", "id": 4, "method": "tools/call",
"params": {"name": "get_quota", "arguments": {"a": 1}}})
result = resp["result"]
assert result["isError"] is False
assert result["structuredContent"]["echo"]["args"] == {"a": 1}
assert result["content"][0]["type"] == "text"
def test_call_marks_tool_failures_as_is_error(self):
resp = _run({"jsonrpc": "2.0", "id": 5, "method": "tools/call",
"params": {"name": "get_quota", "arguments": {}}},
tool_caller=_err_tool)
assert resp["result"]["isError"] is True