feat(mcp): create_upload for local files, captions switch per job
process_video now takes captions:false for sources that already carry burned-in subtitles (maps to AUTO_CAPTIONS=0 for that job only) and accepts upload_id as an alternative to source_url. create_upload reserves a slot (POST /api/uploads) and returns a PUT URL the agent streams the raw bytes to (curl -T works from any runtime); the owner recorded at reserve time is checked at process time, files sit in UPLOAD_DIR under the usual sweep, slots expire after 24 h. Tool count is 8 everywhere it is quoted.
This commit is contained in:
parent
ecf9b0bfec
commit
0a21de29a2
7 changed files with 298 additions and 16 deletions
|
|
@ -225,7 +225,7 @@ creator instead of a stranger; an uploaded face photo still wins.
|
||||||
endpoint changes. Key management itself refuses API-key auth: a leaked key
|
endpoint changes. Key management itself refuses API-key auth: a leaked key
|
||||||
cannot mint replacements.
|
cannot mint replacements.
|
||||||
- **MCP server** (`mcp_server.py`, mounted always): stateless Streamable-HTTP
|
- **MCP server** (`mcp_server.py`, mounted always): stateless Streamable-HTTP
|
||||||
JSON-RPC at `/mcp` — no SDK dependency, ~3 methods + 7 tools. Each tool calls
|
JSON-RPC at `/mcp` — no SDK dependency, ~3 methods + 8 tools. Each tool calls
|
||||||
back into this same app in-process (`httpx.ASGITransport`) forwarding the
|
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
|
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.
|
mode 401s without a resolvable user; self-host stays BYOK-open.
|
||||||
|
|
|
||||||
|
|
@ -314,7 +314,7 @@ claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
|
||||||
claude mcp add --transport http openshorts http://localhost:8000/mcp
|
claude mcp add --transport http openshorts http://localhost:8000/mcp
|
||||||
```
|
```
|
||||||
|
|
||||||
Tools: `process_video`, `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `recut_clip`, `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.
|
Tools: `process_video` (URL or `upload_id`, `captions: false` when the source already has subtitles), `create_upload` (hand the agent a local file: PUT the bytes, then process), `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `recut_clip`, `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
|
### REST API + API keys
|
||||||
|
|
||||||
|
|
|
||||||
136
app.py
136
app.py
|
|
@ -1032,6 +1032,16 @@ async def cleanup_jobs():
|
||||||
except NameError:
|
except NameError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# Agent upload slots: expire with their file (the file sweep below
|
||||||
|
# removes it; a slot whose file is gone or too old is dropped).
|
||||||
|
for uid, slot in list(pending_uploads.items()):
|
||||||
|
if now - slot["created"] > UPLOAD_TTL_SECONDS:
|
||||||
|
pending_uploads.pop(uid, None)
|
||||||
|
try:
|
||||||
|
os.remove(slot["path"])
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
# Cleanup Uploads
|
# Cleanup Uploads
|
||||||
for filename in os.listdir(UPLOAD_DIR):
|
for filename in os.listdir(UPLOAD_DIR):
|
||||||
file_path = os.path.join(UPLOAD_DIR, filename)
|
file_path = os.path.join(UPLOAD_DIR, filename)
|
||||||
|
|
@ -1893,6 +1903,95 @@ LAYOUT_IMPLIES = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Agent uploads: a two-step path for callers that hold a video FILE, not a URL
|
||||||
|
# (an MCP client handed the file by the user). POST reserves an id and returns
|
||||||
|
# a PUT URL; the client streams the raw bytes there with no auth beyond the
|
||||||
|
# unguessable id (so `curl -T` works from any agent runtime); /api/process then
|
||||||
|
# takes the upload_id. Files live in UPLOAD_DIR under the same retention sweep
|
||||||
|
# as every other source upload, and the owner recorded at POST is checked at
|
||||||
|
# process time so a leaked id cannot start a job on someone else's account.
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
pending_uploads: Dict[str, Dict] = {}
|
||||||
|
UPLOAD_TTL_SECONDS = int(os.environ.get("UPLOAD_TTL_SECONDS", str(24 * 3600)))
|
||||||
|
|
||||||
|
|
||||||
|
def _upload_url_base(request):
|
||||||
|
return os.environ.get("PUBLIC_API_URL", "").rstrip("/") or str(request.base_url).rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/uploads")
|
||||||
|
async def create_upload(request: Request):
|
||||||
|
"""Reserve an upload slot. Body (JSON, optional): {"filename": "..."}."""
|
||||||
|
user_id = await _owner_id(request)
|
||||||
|
if BILLING_ENABLED and user_id is None:
|
||||||
|
raise HTTPException(status_code=401, detail="Sign in or use an API key to upload")
|
||||||
|
try:
|
||||||
|
body = await request.json()
|
||||||
|
except Exception:
|
||||||
|
body = {}
|
||||||
|
filename = os.path.basename(str((body or {}).get("filename") or "video.mp4")) or "video.mp4"
|
||||||
|
upload_id = str(uuid.uuid4())
|
||||||
|
pending_uploads[upload_id] = {
|
||||||
|
"user_id": user_id,
|
||||||
|
"filename": filename,
|
||||||
|
"path": os.path.join(UPLOAD_DIR, f"pending_{upload_id}_{filename}"),
|
||||||
|
"created": time.time(),
|
||||||
|
"bytes": 0,
|
||||||
|
"complete": False,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"upload_id": upload_id,
|
||||||
|
"upload_url": f"{_upload_url_base(request)}/api/uploads/{upload_id}",
|
||||||
|
"method": "PUT",
|
||||||
|
"max_mb": MAX_FILE_SIZE_MB,
|
||||||
|
"expires_in": UPLOAD_TTL_SECONDS,
|
||||||
|
"hint": "PUT the raw video bytes to upload_url (e.g. curl -T video.mp4 <upload_url>), "
|
||||||
|
"then call /api/process (or the process_video tool) with this upload_id.",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.put("/api/uploads/{upload_id}")
|
||||||
|
async def put_upload(upload_id: str, request: Request):
|
||||||
|
"""Receive the raw video body for a reserved slot. Streams to disk, capped
|
||||||
|
at MAX_FILE_SIZE_MB; a second PUT replaces the first."""
|
||||||
|
slot = pending_uploads.get(upload_id)
|
||||||
|
if not slot or time.time() - slot["created"] > UPLOAD_TTL_SECONDS:
|
||||||
|
pending_uploads.pop(upload_id, None)
|
||||||
|
raise HTTPException(status_code=404, detail="Unknown or expired upload_id")
|
||||||
|
limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024
|
||||||
|
size = 0
|
||||||
|
with open(slot["path"], "wb") as out:
|
||||||
|
async for chunk in request.stream():
|
||||||
|
size += len(chunk)
|
||||||
|
if size > limit_bytes:
|
||||||
|
out.close()
|
||||||
|
os.remove(slot["path"])
|
||||||
|
raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB")
|
||||||
|
out.write(chunk)
|
||||||
|
if size == 0:
|
||||||
|
os.remove(slot["path"])
|
||||||
|
raise HTTPException(status_code=400, detail="Empty body")
|
||||||
|
slot.update({"bytes": size, "complete": True})
|
||||||
|
duration = await asyncio.get_event_loop().run_in_executor(None, _media_duration_seconds, slot["path"])
|
||||||
|
if duration <= 0:
|
||||||
|
os.remove(slot["path"])
|
||||||
|
slot["complete"] = False
|
||||||
|
raise HTTPException(status_code=400, detail="The body is not a readable video file")
|
||||||
|
return {"upload_id": upload_id, "bytes": size, "duration_seconds": round(duration, 1),
|
||||||
|
"hint": "Now call /api/process with upload_id."}
|
||||||
|
|
||||||
|
|
||||||
|
def _take_pending_upload(upload_id, user_id):
|
||||||
|
"""The completed upload for this caller, or an HTTPException."""
|
||||||
|
slot = pending_uploads.get(upload_id)
|
||||||
|
if not slot or (BILLING_ENABLED and slot.get("user_id") != user_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Unknown or expired upload_id")
|
||||||
|
if not slot.get("complete") or not os.path.exists(slot["path"]):
|
||||||
|
raise HTTPException(status_code=409, detail="Upload not received yet: PUT the video to upload_url first")
|
||||||
|
return slot
|
||||||
|
|
||||||
|
|
||||||
def layout_env(requested):
|
def layout_env(requested):
|
||||||
"""Env overrides for the layouts this job allows. Unknown names are ignored
|
"""Env overrides for the layouts this job allows. Unknown names are ignored
|
||||||
rather than rejected: a newer dashboard must not break an older API.
|
rather than rejected: a newer dashboard must not break an older API.
|
||||||
|
|
@ -1938,7 +2037,9 @@ async def process_endpoint(
|
||||||
clip_max_seconds: Optional[str] = Form(None),
|
clip_max_seconds: Optional[str] = Form(None),
|
||||||
auto_hook: Optional[str] = Form(None),
|
auto_hook: Optional[str] = Form(None),
|
||||||
auto_hook_style: Optional[str] = Form(None),
|
auto_hook_style: Optional[str] = Form(None),
|
||||||
thumbnail_session_id: Optional[str] = Form(None)
|
thumbnail_session_id: Optional[str] = Form(None),
|
||||||
|
captions: Optional[str] = Form(None),
|
||||||
|
upload_id: Optional[str] = Form(None),
|
||||||
):
|
):
|
||||||
api_key = await resolve_gemini(request)
|
api_key = await resolve_gemini(request)
|
||||||
if not api_key:
|
if not api_key:
|
||||||
|
|
@ -1964,6 +2065,8 @@ async def process_endpoint(
|
||||||
auto_hook = body.get("auto_hook")
|
auto_hook = body.get("auto_hook")
|
||||||
auto_hook_style = body.get("auto_hook_style")
|
auto_hook_style = body.get("auto_hook_style")
|
||||||
thumbnail_session_id = body.get("thumbnail_session_id")
|
thumbnail_session_id = body.get("thumbnail_session_id")
|
||||||
|
captions = body.get("captions")
|
||||||
|
upload_id = body.get("upload_id")
|
||||||
|
|
||||||
# Normalize output format (auto = keep pipeline default).
|
# Normalize output format (auto = keep pipeline default).
|
||||||
if output_format not in ("vertical", "horizontal", "square"):
|
if output_format not in ("vertical", "horizontal", "square"):
|
||||||
|
|
@ -1988,8 +2091,13 @@ async def process_endpoint(
|
||||||
if not src or not os.path.exists(src):
|
if not src or not os.path.exists(src):
|
||||||
raise HTTPException(status_code=404, detail="Source video for this session is no longer on disk")
|
raise HTTPException(status_code=404, detail="Source video for this session is no longer on disk")
|
||||||
|
|
||||||
if not url and not file and not thumb_session:
|
# Agent upload (POST /api/uploads + PUT): the file is already on disk.
|
||||||
raise HTTPException(status_code=400, detail="Must provide URL or File")
|
upload_slot = None
|
||||||
|
if upload_id and not url and not file and not thumb_session:
|
||||||
|
upload_slot = _take_pending_upload(upload_id, await _owner_id(request))
|
||||||
|
|
||||||
|
if not url and not file and not thumb_session and not upload_slot:
|
||||||
|
raise HTTPException(status_code=400, detail="Must provide URL, File or upload_id")
|
||||||
|
|
||||||
# Completion callback: reject unsafe targets NOW (clear 400) — delivery
|
# Completion callback: reject unsafe targets NOW (clear 400) — delivery
|
||||||
# re-validates anyway, but failing at submit is the debuggable behavior.
|
# re-validates anyway, but failing at submit is the debuggable behavior.
|
||||||
|
|
@ -2043,7 +2151,8 @@ async def process_endpoint(
|
||||||
"ip": client_ip,
|
"ip": client_ip,
|
||||||
"user_agent": user_agent,
|
"user_agent": user_agent,
|
||||||
"timestamp": time.time(),
|
"timestamp": time.time(),
|
||||||
"source": "thumbnail_session" if thumb_session else ("url" if url else "file"),
|
"source": ("thumbnail_session" if thumb_session else "upload_id" if upload_slot
|
||||||
|
else "url" if url else "file"),
|
||||||
}
|
}
|
||||||
|
|
||||||
job_id = str(uuid.uuid4())
|
job_id = str(uuid.uuid4())
|
||||||
|
|
@ -2117,6 +2226,13 @@ async def process_endpoint(
|
||||||
if n_clips is not None or min_secs is not None or max_secs is not None:
|
if n_clips is not None or min_secs is not None or max_secs is not None:
|
||||||
print(f"[gen-controls] job={job_id} clips={n_clips} band={min_secs}-{max_secs}")
|
print(f"[gen-controls] job={job_id} clips={n_clips} band={min_secs}-{max_secs}")
|
||||||
|
|
||||||
|
# captions=false: the source already carries burned-in subtitles (or the
|
||||||
|
# caller adds its own later), so skip the free auto-caption pass instead
|
||||||
|
# of stacking a second layer. Absent → the deployment default (on).
|
||||||
|
if captions is not None and str(captions).lower() in ("0", "false", "no"):
|
||||||
|
env["AUTO_CAPTIONS"] = "0"
|
||||||
|
print(f"[captions] job={job_id} auto-captions off")
|
||||||
|
|
||||||
input_path = None
|
input_path = None
|
||||||
if url:
|
if url:
|
||||||
# Keep the downloaded source inside the job dir: the clip editor's
|
# Keep the downloaded source inside the job dir: the clip editor's
|
||||||
|
|
@ -2145,6 +2261,18 @@ async def process_endpoint(
|
||||||
with open(transcript_path, "w") as f:
|
with open(transcript_path, "w") as f:
|
||||||
json.dump(thumb_session["transcript"], f)
|
json.dump(thumb_session["transcript"], f)
|
||||||
cmd.extend(["--transcript", transcript_path])
|
cmd.extend(["--transcript", transcript_path])
|
||||||
|
elif upload_slot:
|
||||||
|
# Move the pre-uploaded file under the job's name so it is cleaned up
|
||||||
|
# with the job like any other upload; the slot is consumed.
|
||||||
|
src = upload_slot["path"]
|
||||||
|
src_duration = _media_duration_seconds(src)
|
||||||
|
if MIN_SOURCE_SECONDS > 0 and 0 < src_duration < MIN_SOURCE_SECONDS:
|
||||||
|
shutil.rmtree(job_output_dir, ignore_errors=True)
|
||||||
|
_reject_short_source(src_duration)
|
||||||
|
input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{upload_slot['filename']}")
|
||||||
|
os.replace(src, input_path)
|
||||||
|
pending_uploads.pop(upload_id, None)
|
||||||
|
cmd.extend(["-i", input_path])
|
||||||
else:
|
else:
|
||||||
# Save uploaded file with size limit check.
|
# Save uploaded file with size limit check.
|
||||||
# basename() strips any path components from the client-supplied
|
# basename() strips any path components from the client-supplied
|
||||||
|
|
|
||||||
|
|
@ -1033,7 +1033,7 @@ const mcpAgentsPage = () => ({
|
||||||
breadcrumb: [{ name: 'MCP server and API' }],
|
breadcrumb: [{ name: 'MCP server and API' }],
|
||||||
tldr: [
|
tldr: [
|
||||||
'OpenShorts has a native MCP server at mcp.openshorts.app/mcp. Connect any MCP client, Claude, ChatGPT, Cursor or a custom agent, and a prompt like "clip this podcast and schedule the best three to TikTok" becomes one instruction instead of an afternoon in an editor.',
|
'OpenShorts has a native MCP server at mcp.openshorts.app/mcp. Connect any MCP client, Claude, ChatGPT, Cursor or a custom agent, and a prompt like "clip this podcast and schedule the best three to TikTok" becomes one instruction instead of an afternoon in an editor.',
|
||||||
'Six tools cover the whole pipeline: process_video, get_job_status, list_clips, get_quota, add_subtitles and publish_clip. There is also a plain REST API with per-user keys, and completion webhooks so pipelines never poll.',
|
'Eight tools cover the whole pipeline: process_video, create_upload, get_job_status, list_clips, get_quota, add_subtitles, recut_clip and publish_clip. There is also a plain REST API with per-user keys, and completion webhooks so pipelines never poll.',
|
||||||
'The difference that survives comparison shopping is the meter. Most clipping tools now have an API, and Opus Clip added an MCP server in July 2026, but they meter agent calls per source minute or per operation. OpenShorts API calls draw from the same flat minute balance as the dashboard, and the self-hosted edition, free and MIT-licensed, serves the same MCP endpoint with no meter at all.',
|
'The difference that survives comparison shopping is the meter. Most clipping tools now have an API, and Opus Clip added an MCP server in July 2026, but they meter agent calls per source minute or per operation. OpenShorts API calls draw from the same flat minute balance as the dashboard, and the self-hosted edition, free and MIT-licensed, serves the same MCP endpoint with no meter at all.',
|
||||||
],
|
],
|
||||||
body: `
|
body: `
|
||||||
|
|
@ -1052,7 +1052,7 @@ server, so there is no key to copy:</p>
|
||||||
<ol>
|
<ol>
|
||||||
<li><strong>claude.ai:</strong> Settings, Connectors, Add custom connector, paste <code>https://mcp.openshorts.app/mcp</code>, Connect.</li>
|
<li><strong>claude.ai:</strong> Settings, Connectors, Add custom connector, paste <code>https://mcp.openshorts.app/mcp</code>, Connect.</li>
|
||||||
<li><strong>ChatGPT:</strong> Settings, Connectors, Create, paste the same URL, choose OAuth.</li>
|
<li><strong>ChatGPT:</strong> Settings, Connectors, Create, paste the same URL, choose OAuth.</li>
|
||||||
<li>Approve the access on openshorts.app (sign in if you are not). The 7 tools appear in every chat, and the connection is listed under Account, API keys, where revoking it disconnects the app.</li>
|
<li>Approve the access on openshorts.app (sign in if you are not). The 8 tools appear in every chat, and the connection is listed under Account, API keys, where revoking it disconnects the app.</li>
|
||||||
</ol>
|
</ol>
|
||||||
<h2>How do I connect Claude Code, Cursor or n8n?</h2>
|
<h2>How do I connect Claude Code, Cursor or n8n?</h2>
|
||||||
<p>CLI and workflow clients take an API key instead: create one in your account
|
<p>CLI and workflow clients take an API key instead: create one in your account
|
||||||
|
|
@ -1069,7 +1069,8 @@ snippets for Claude Desktop, Cursor, n8n and curl.</p>
|
||||||
<table>
|
<table>
|
||||||
<thead><tr><th>Tool</th><th>What it does</th></tr></thead>
|
<thead><tr><th>Tool</th><th>What it does</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr><td><code>process_video</code></td><td>Starts clipping a video from a URL. Returns a job id immediately; processing takes minutes.</td></tr>
|
<tr><td><code>process_video</code></td><td>Starts clipping a video from a URL or an upload_id. Returns a job id immediately; processing takes minutes. Pass captions: false when the source already has subtitles burned in.</td></tr>
|
||||||
|
<tr><td><code>create_upload</code></td><td>Reserves an upload slot for a local file: the agent PUTs the bytes to the returned URL, then processes it by upload_id.</td></tr>
|
||||||
<tr><td><code>get_job_status</code></td><td>Progress, recent log lines, and the clips once the job completes.</td></tr>
|
<tr><td><code>get_job_status</code></td><td>Progress, recent log lines, and the clips once the job completes.</td></tr>
|
||||||
<tr><td><code>list_clips</code></td><td>Titles, durations, platform-ready descriptions and download URLs for a finished job.</td></tr>
|
<tr><td><code>list_clips</code></td><td>Titles, durations, platform-ready descriptions and download URLs for a finished job.</td></tr>
|
||||||
<tr><td><code>get_quota</code></td><td>Plan and remaining minutes, so an agent can check before starting a large job.</td></tr>
|
<tr><td><code>get_quota</code></td><td>Plan and remaining minutes, so an agent can check before starting a large job.</td></tr>
|
||||||
|
|
@ -1154,7 +1155,7 @@ balance as the dashboard, so automation does not change the price of anything.</
|
||||||
${faqBlock([
|
${faqBlock([
|
||||||
{
|
{
|
||||||
q: 'Does OpenShorts have an MCP server?',
|
q: 'Does OpenShorts have an MCP server?',
|
||||||
a: 'Yes, a native one at mcp.openshorts.app/mcp using the Streamable HTTP transport. It exposes six tools covering the full pipeline: process_video, get_job_status, list_clips, get_quota, add_subtitles and publish_clip. Authentication is an API key created in the dashboard, sent as a Bearer token.',
|
a: 'Yes, a native one at mcp.openshorts.app/mcp using the Streamable HTTP transport. It exposes eight tools covering the full pipeline: process_video, create_upload, get_job_status, list_clips, get_quota, add_subtitles, recut_clip and publish_clip. Authentication is an API key created in the dashboard, sent as a Bearer token.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
q: 'Can Claude or ChatGPT create video clips with OpenShorts?',
|
q: 'Can Claude or ChatGPT create video clips with OpenShorts?',
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,7 @@ function buildClients({ cloud, url }) {
|
||||||
steps: [
|
steps: [
|
||||||
'Open claude.ai → Settings → Connectors → Add custom connector.',
|
'Open claude.ai → Settings → Connectors → Add custom connector.',
|
||||||
`Paste this URL and save: ${url}`,
|
`Paste this URL and save: ${url}`,
|
||||||
'Click Connect: you will land on OpenShorts to approve the access, then the 7 tools appear in every chat.',
|
'Click Connect: you will land on OpenShorts to approve the access, then the 8 tools appear in every chat.',
|
||||||
],
|
],
|
||||||
snippet: url,
|
snippet: url,
|
||||||
},
|
},
|
||||||
|
|
@ -99,7 +99,7 @@ export default function McpConnectCard({ cloud = true, compact = false }) {
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-muted text-sm mb-4">
|
<p className="text-muted text-sm mb-4">
|
||||||
Let Claude, ChatGPT, Cursor or n8n clip and publish for you through the built-in MCP server:
|
Let Claude, ChatGPT, Cursor or n8n clip and publish for you through the built-in MCP server:
|
||||||
7 tools (process a video, check a job, list clips, add subtitles, recut, publish, quota).
|
8 tools (process a video or upload one, check a job, list clips, add subtitles, recut, publish, quota).
|
||||||
{cloud
|
{cloud
|
||||||
? ' claude.ai and ChatGPT connect with one URL and a sign-in; CLI clients use an API key.'
|
? ' claude.ai and ChatGPT connect with one URL and a sign-in; CLI clients use an API key.'
|
||||||
: ' This install runs without accounts, so no key is needed.'}
|
: ' This install runs without accounts, so no key is needed.'}
|
||||||
|
|
|
||||||
|
|
@ -77,7 +77,20 @@ TOOLS = [
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Public video URL, passed through exactly as the user gave it "
|
"description": "Public video URL, passed through exactly as the user gave it "
|
||||||
"(YouTube watch/short/live URL, or a direct video file URL). "
|
"(YouTube watch/short/live URL, or a direct video file URL). "
|
||||||
"The server does the downloading.",
|
"The server does the downloading. Omit when using upload_id.",
|
||||||
|
},
|
||||||
|
"upload_id": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Instead of source_url: the id from create_upload after the "
|
||||||
|
"file was PUT to its upload_url. Use when the user gave you a "
|
||||||
|
"video file rather than a link.",
|
||||||
|
},
|
||||||
|
"captions": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "Default true: burn word-level captions on every clip. Set false "
|
||||||
|
"when the source already has subtitles burned in (they would "
|
||||||
|
"stack) or the user wants clean clips; add_subtitles can still "
|
||||||
|
"caption a clip later.",
|
||||||
},
|
},
|
||||||
"confirm_rights": {
|
"confirm_rights": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
|
|
@ -121,7 +134,26 @@ TOOLS = [
|
||||||
"description": "Maximum clip length in seconds (default 60). Must be ≥ 5s above the minimum.",
|
"description": "Maximum clip length in seconds (default 60). Must be ≥ 5s above the minimum.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"required": ["source_url", "confirm_rights"],
|
"required": ["confirm_rights"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "create_upload",
|
||||||
|
"title": "Reserve an upload slot for a local video file",
|
||||||
|
"description": (
|
||||||
|
"Use when the user hands you a video FILE instead of a link. Returns "
|
||||||
|
"an upload_url: send the file's raw bytes to it with an HTTP PUT "
|
||||||
|
"(for example `curl -T video.mp4 <upload_url>`), then call "
|
||||||
|
"process_video with the returned upload_id. The slot expires after "
|
||||||
|
"24 hours; max size is returned as max_mb. If you cannot make HTTP "
|
||||||
|
"requests from your environment, ask the user to run the curl "
|
||||||
|
"command or to share a public link instead."
|
||||||
|
),
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"filename": {"type": "string", "description": "Original file name (optional, for the extension)."},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -294,8 +326,11 @@ async def _tool_process_video(client, args):
|
||||||
if not args.get("confirm_rights"):
|
if not args.get("confirm_rights"):
|
||||||
return {"error": "confirm_rights must be true: the user must own the "
|
return {"error": "confirm_rights must be true: the user must own the "
|
||||||
"content or hold the rights to process it."}, True
|
"content or hold the rights to process it."}, True
|
||||||
|
if not args.get("source_url") and not args.get("upload_id"):
|
||||||
|
return {"error": "Give source_url (a public video link) or upload_id (from create_upload)."}, True
|
||||||
body = {
|
body = {
|
||||||
"url": args["source_url"],
|
"url": args.get("source_url"),
|
||||||
|
"upload_id": args.get("upload_id"),
|
||||||
"acknowledged": True,
|
"acknowledged": True,
|
||||||
"layouts": args.get("layouts") or [],
|
"layouts": args.get("layouts") or [],
|
||||||
"output_format": args.get("output_format"),
|
"output_format": args.get("output_format"),
|
||||||
|
|
@ -303,7 +338,7 @@ async def _tool_process_video(client, args):
|
||||||
"webhook_url": args.get("webhook_url"),
|
"webhook_url": args.get("webhook_url"),
|
||||||
"webhook_secret": args.get("webhook_secret"),
|
"webhook_secret": args.get("webhook_secret"),
|
||||||
}
|
}
|
||||||
for k in ("target_clips", "clip_min_seconds", "clip_max_seconds"):
|
for k in ("target_clips", "clip_min_seconds", "clip_max_seconds", "captions"):
|
||||||
if args.get(k) is not None:
|
if args.get(k) is not None:
|
||||||
body[k] = args[k]
|
body[k] = args[k]
|
||||||
resp = await client.post("/api/process", json=body)
|
resp = await client.post("/api/process", json=body)
|
||||||
|
|
@ -319,6 +354,13 @@ async def _tool_process_video(client, args):
|
||||||
return data, False
|
return data, False
|
||||||
|
|
||||||
|
|
||||||
|
async def _tool_create_upload(client, args):
|
||||||
|
resp = await client.post("/api/uploads", json={"filename": args.get("filename") or "video.mp4"})
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
return _api_error(resp), True
|
||||||
|
return resp.json(), False
|
||||||
|
|
||||||
|
|
||||||
async def _tool_get_job_status(client, args):
|
async def _tool_get_job_status(client, args):
|
||||||
resp = await client.get(f"/api/status/{args['job_id']}")
|
resp = await client.get(f"/api/status/{args['job_id']}")
|
||||||
if resp.status_code >= 400:
|
if resp.status_code >= 400:
|
||||||
|
|
@ -415,6 +457,7 @@ async def _tool_publish_clip(client, args):
|
||||||
|
|
||||||
_TOOL_IMPLS = {
|
_TOOL_IMPLS = {
|
||||||
"process_video": _tool_process_video,
|
"process_video": _tool_process_video,
|
||||||
|
"create_upload": _tool_create_upload,
|
||||||
"get_job_status": _tool_get_job_status,
|
"get_job_status": _tool_get_job_status,
|
||||||
"list_clips": _tool_list_clips,
|
"list_clips": _tool_list_clips,
|
||||||
"get_quota": _tool_get_quota,
|
"get_quota": _tool_get_quota,
|
||||||
|
|
|
||||||
110
tests/test_agent_uploads.py
Normal file
110
tests/test_agent_uploads.py
Normal file
|
|
@ -0,0 +1,110 @@
|
||||||
|
"""Agent uploads (POST/PUT /api/uploads -> process with upload_id) and the
|
||||||
|
per-job captions switch, through the MCP transport where the agent uses them."""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
app_module = pytest.importorskip("app")
|
||||||
|
|
||||||
|
|
||||||
|
def _client():
|
||||||
|
transport = httpx.ASGITransport(app=app_module.app)
|
||||||
|
return httpx.AsyncClient(transport=transport, base_url="http://testserver",
|
||||||
|
headers={"X-Gemini-Key": "test-key"})
|
||||||
|
|
||||||
|
|
||||||
|
def _mcp(tool, arguments):
|
||||||
|
async def _do():
|
||||||
|
async with _client() as c:
|
||||||
|
return await c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call",
|
||||||
|
"params": {"name": tool, "arguments": arguments}})
|
||||||
|
return asyncio.run(_do())
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_payload(resp):
|
||||||
|
import json
|
||||||
|
return json.loads(resp.json()["result"]["content"][0]["text"])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def dirs(tmp_path, monkeypatch):
|
||||||
|
out_root = tmp_path / "output"; up_root = tmp_path / "uploads"
|
||||||
|
out_root.mkdir(); up_root.mkdir()
|
||||||
|
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||||
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
|
||||||
|
# Never spawn main.py: capture the job instead.
|
||||||
|
captured = {}
|
||||||
|
async def fake_enqueue(*a, **k):
|
||||||
|
captured["args"] = a; captured["kwargs"] = k
|
||||||
|
monkeypatch.setattr(app_module, "_media_duration_seconds", lambda p: 120.0)
|
||||||
|
return out_root, up_root, captured
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_upload_is_an_mcp_tool():
|
||||||
|
names = [t["name"] for t in __import__("mcp_server").TOOLS]
|
||||||
|
assert "create_upload" in names
|
||||||
|
pv = next(t for t in __import__("mcp_server").TOOLS if t["name"] == "process_video")
|
||||||
|
assert "upload_id" in pv["inputSchema"]["properties"]
|
||||||
|
assert "captions" in pv["inputSchema"]["properties"]
|
||||||
|
assert "source_url" not in pv["inputSchema"]["required"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_video_needs_a_source():
|
||||||
|
payload = _tool_payload(_mcp("process_video", {"confirm_rights": True}))
|
||||||
|
assert "source_url" in payload["error"] and "upload_id" in payload["error"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_put_then_process_with_upload_id_and_captions_off(dirs, monkeypatch):
|
||||||
|
out_root, up_root, _ = dirs
|
||||||
|
slot = _tool_payload(_mcp("create_upload", {"filename": "../talk.mp4"}))
|
||||||
|
assert slot["upload_url"].endswith(f"/api/uploads/{slot['upload_id']}")
|
||||||
|
assert "talk.mp4" in app_module.pending_uploads[slot["upload_id"]]["path"]
|
||||||
|
assert ".." not in os.path.basename(app_module.pending_uploads[slot["upload_id"]]["path"])
|
||||||
|
|
||||||
|
async def _put(body):
|
||||||
|
async with _client() as c:
|
||||||
|
return await c.put(f"/api/uploads/{slot['upload_id']}", content=body)
|
||||||
|
assert asyncio.run(_put(b"")).status_code == 400
|
||||||
|
resp = asyncio.run(_put(b"\x00" * 5000))
|
||||||
|
assert resp.status_code == 200 and resp.json()["bytes"] == 5000
|
||||||
|
|
||||||
|
# Intercept the job instead of running main.py.
|
||||||
|
started = {}
|
||||||
|
async def fake_put(item):
|
||||||
|
started["job"] = item
|
||||||
|
monkeypatch.setattr(app_module.job_queue, "put", fake_put)
|
||||||
|
|
||||||
|
payload = _tool_payload(_mcp("process_video", {
|
||||||
|
"upload_id": slot["upload_id"], "confirm_rights": True, "captions": False}))
|
||||||
|
assert "job_id" in payload, payload
|
||||||
|
job = app_module.jobs[payload["job_id"]]
|
||||||
|
assert job["env"]["AUTO_CAPTIONS"] == "0"
|
||||||
|
assert slot["upload_id"] not in app_module.pending_uploads
|
||||||
|
input_path = job["cmd"][job["cmd"].index("-i") + 1]
|
||||||
|
assert os.path.exists(input_path) and input_path.startswith(str(up_root))
|
||||||
|
|
||||||
|
|
||||||
|
def test_captions_default_leaves_env_alone(dirs, monkeypatch):
|
||||||
|
slot = _tool_payload(_mcp("create_upload", {}))
|
||||||
|
async def _put():
|
||||||
|
async with _client() as c:
|
||||||
|
return await c.put(f"/api/uploads/{slot['upload_id']}", content=b"x" * 100)
|
||||||
|
assert asyncio.run(_put()).status_code == 200
|
||||||
|
async def fake_put(item): pass
|
||||||
|
monkeypatch.setattr(app_module.job_queue, "put", fake_put)
|
||||||
|
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True}))
|
||||||
|
assert "AUTO_CAPTIONS" not in app_module.jobs[payload["job_id"]]["env"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_or_unfinished_upload_id(dirs):
|
||||||
|
async def _put():
|
||||||
|
async with _client() as c:
|
||||||
|
return await c.put("/api/uploads/nope", content=b"x")
|
||||||
|
assert asyncio.run(_put()).status_code == 404
|
||||||
|
slot = _tool_payload(_mcp("create_upload", {}))
|
||||||
|
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True}))
|
||||||
|
assert "PUT" in payload["error"]
|
||||||
Loading…
Reference in a new issue