feat(mcp): list_clips renders as an MCP App clip picker in UI-capable clients

New mcp_ui module holds the template: preview each 9:16 clip inline,
select the keepers and publish them via publish_clip from inside the
conversation. One template, three data paths, because the ecosystem has
not converged: baked-in JSON on the per-call embedded resource, the
ChatGPT Apps window.openai bridge, and the MCP Apps ready/render-data
postMessage handshake. Titles are JSON-escaped so a clip name cannot
break out of the script tag, and the template is fully inline because
host CSPs block external fetches.

The server grows resources/list, resources/read and the resources
capability; list_clips declares the template under both _meta.ui
.resourceUri and openai/outputTemplate. Non-UI clients see the same
text and structured content as before; the extra content entry is
spec-tolerated. The unknown-method protocol test moves off
resources/list, which is now a real method.
This commit is contained in:
juancarlos.cavero 2026-08-05 23:59:02 +02:00
parent 40f530f9aa
commit 46c61e407b
5 changed files with 340 additions and 4 deletions

View file

@ -927,6 +927,10 @@ there is nothing else to configure.</p>
<tr><td><code>publish_clip</code></td><td>Posts or schedules one clip to TikTok, Instagram or YouTube through the connected account.</td></tr> <tr><td><code>publish_clip</code></td><td>Posts or schedules one clip to TikTok, Instagram or YouTube through the connected account.</td></tr>
</tbody> </tbody>
</table> </table>
<p>In clients that support the MCP Apps extension (ChatGPT apps, mcp-ui hosts),
<code>list_clips</code> also renders as an interactive clip picker: preview each
9:16 clip inline, select the keepers and publish them without leaving the
conversation. Clients without UI support see the same data as plain results.</p>
<h2>How does this compare to the other clipping tools' agent access?</h2> <h2>How does this compare to the other clipping tools' agent access?</h2>
<p class="checked">Checked 2026-08-04 on vendor developer documentation and pricing pages. This market is moving fast; verify before committing a pipeline.</p> <p class="checked">Checked 2026-08-04 on vendor developer documentation and pricing pages. This market is moving fast; verify before committing a pipeline.</p>

View file

@ -28,6 +28,8 @@ import httpx
from fastapi import APIRouter, Request from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, Response from fastapi.responses import JSONResponse, Response
import mcp_ui
router = APIRouter() router = APIRouter()
PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05") PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
@ -115,13 +117,20 @@ TOOLS = [
"title": "List a job's clips", "title": "List a job's clips",
"description": ( "description": (
"The clips of a completed job, with titles, platform-ready " "The clips of a completed job, with titles, platform-ready "
"descriptions and download URLs." "descriptions and download URLs. In MCP Apps-capable clients the "
"result also renders as an interactive clip picker."
), ),
"inputSchema": { "inputSchema": {
"type": "object", "type": "object",
"properties": {"job_id": {"type": "string"}}, "properties": {"job_id": {"type": "string"}},
"required": ["job_id"], "required": ["job_id"],
}, },
# Both spellings of the tool->template link: MCP Apps hosts read
# _meta.ui.resourceUri, the ChatGPT Apps SDK reads openai/outputTemplate.
"_meta": {
"ui": {"resourceUri": mcp_ui.CLIP_PICKER_URI},
"openai/outputTemplate": mcp_ui.CLIP_PICKER_URI,
},
}, },
{ {
"name": "get_quota", "name": "get_quota",
@ -370,7 +379,8 @@ async def handle_message(msg, tool_caller) -> Optional[dict]:
version = client_version if client_version in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0] version = client_version if client_version in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
return _rpc_result(msg_id, { return _rpc_result(msg_id, {
"protocolVersion": version, "protocolVersion": version,
"capabilities": {"tools": {"listChanged": False}}, "capabilities": {"tools": {"listChanged": False},
"resources": {"listChanged": False}},
"serverInfo": SERVER_INFO, "serverInfo": SERVER_INFO,
"instructions": INSTRUCTIONS, "instructions": INSTRUCTIONS,
}) })
@ -378,12 +388,37 @@ async def handle_message(msg, tool_caller) -> Optional[dict]:
return _rpc_result(msg_id, {}) return _rpc_result(msg_id, {})
if method == "tools/list": if method == "tools/list":
return _rpc_result(msg_id, {"tools": TOOLS}) return _rpc_result(msg_id, {"tools": TOOLS})
if method == "resources/list":
return _rpc_result(msg_id, {"resources": mcp_ui.RESOURCES})
if method == "resources/templates/list":
return _rpc_result(msg_id, {"resourceTemplates": []})
if method == "resources/read":
uri = (msg.get("params") or {}).get("uri") or ""
# Per-call URIs (ui://openshorts/clip-picker/<job>) resolve to the same
# template; the data those carried was baked into the tool result.
if uri == mcp_ui.CLIP_PICKER_URI or uri.startswith(mcp_ui.CLIP_PICKER_URI + "/"):
return _rpc_result(msg_id, {"contents": [{
"uri": uri,
"mimeType": mcp_ui.MIME_TYPE,
"text": mcp_ui.clip_picker_html(),
}]})
return _rpc_error(msg_id, -32002, f"Resource not found: {uri}")
if method == "tools/call": if method == "tools/call":
params = msg.get("params") or {} params = msg.get("params") or {}
name = params.get("name") name = params.get("name")
result, is_error = await tool_caller(name, params.get("arguments") or {}) result, is_error = await tool_caller(name, params.get("arguments") or {})
content = [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}]
# A successful list_clips additionally ships the picker with its data
# baked in, so hosts that render embedded resources need no bridge.
# Non-UI clients ignore extra content entries.
if name == "list_clips" and not is_error and result.get("clips"):
content.append({"type": "resource", "resource": {
"uri": f"{mcp_ui.CLIP_PICKER_URI}/{result.get('job_id', 'result')}",
"mimeType": mcp_ui.MIME_TYPE,
"text": mcp_ui.clip_picker_html(result),
}})
return _rpc_result(msg_id, { return _rpc_result(msg_id, {
"content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}], "content": content,
"structuredContent": result, "structuredContent": result,
"isError": is_error, "isError": is_error,
}) })

195
mcp_ui.py Normal file
View file

@ -0,0 +1,195 @@
"""MCP Apps surface: an embedded clip picker for UI-capable MCP clients.
The pipeline returns 3-15 clips per job; choosing which ones to publish by
looking at them beats reading titles out of JSON. Clients that support the MCP
Apps extension (ChatGPT apps, mcp-ui hosts, Claude) render the HTML below in a
sandboxed iframe; every other client ignores it and keeps working from the
text/structured content exactly as before.
One template, three data paths, because the ecosystem hasn't converged:
1. Baked-in JSON — the per-call embedded resource appended to a successful
list_clips result carries its data inline and renders with no bridge.
2. window.openai.toolOutput — the ChatGPT Apps SDK injects the tool's
structuredContent there; the tool's _meta names this template.
3. postMessage handshake — MCP Apps / mcp-ui hosts that serve the template
from resources/read and push render data after the iframe reports ready.
The iframe cannot fetch anything (host CSP), so the video previews use the
clips' absolute URLs and everything else is inline.
"""
import json
CLIP_PICKER_URI = "ui://openshorts/clip-picker"
MIME_TYPE = "text/html;profile=mcp-app"
RESOURCES = [
{
"uri": CLIP_PICKER_URI,
"name": "clip-picker",
"title": "OpenShorts clip picker",
"description": (
"Interactive picker for a job's finished clips: preview each 9:16 "
"clip, select the keepers and publish them to TikTok, Instagram or "
"YouTube without leaving the conversation."
),
"mimeType": MIME_TYPE,
},
]
# Kept as a plain string with a token instead of an f-string: the JS is full of
# braces and escaping them all is how bugs get in.
_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root{--paper:oklch(13% 0.014 265);--paper2:oklch(16.5% 0.015 265);
--ink:oklch(96% 0.006 262);--ink2:oklch(86% 0.01 262);--muted:oklch(64% 0.012 262);
--rule:oklch(96% 0.006 262 / .12);--brass:oklch(76% 0.17 50);--ok:oklch(75% 0.11 150)}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink2);
font-family:ui-sans-serif,system-ui,-apple-system,sans-serif;font-size:14px;padding:12px}
h1{font-size:15px;font-weight:600;color:var(--ink);margin:0 0 10px}
.grid{display:grid;gap:10px;grid-template-columns:repeat(auto-fill,minmax(150px,1fr))}
.card{background:var(--paper2);border:1px solid var(--rule);border-radius:10px;
padding:8px;cursor:pointer}
.card.sel{border-color:var(--brass)}
.card video{width:100%;aspect-ratio:9/16;border-radius:6px;background:#000;display:block}
.card .t{margin-top:6px;font-size:12px;color:var(--ink);line-height:1.3;
display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.card .d{font-size:11px;color:var(--muted);margin-top:2px}
.bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}
.chip{border:1px solid var(--rule);border-radius:999px;padding:4px 12px;font-size:12px;
cursor:pointer;user-select:none;color:var(--muted)}
.chip.on{border-color:var(--brass);color:var(--ink)}
button{background:var(--brass);color:oklch(17% 0.03 50);border:0;border-radius:8px;
padding:7px 14px;font-size:13px;font-weight:600;cursor:pointer}
button:disabled{opacity:.4;cursor:default}
.msg{font-size:12px;color:var(--ok);margin-top:8px;min-height:16px}
.empty{color:var(--muted)}
</style>
</head>
<body>
<h1 id="hd">OpenShorts clips</h1>
<div class="grid" id="grid"><span class="empty">Waiting for clip data…</span></div>
<div class="bar" id="bar" hidden>
<span class="chip on" data-p="tiktok">TikTok</span>
<span class="chip on" data-p="instagram">Instagram</span>
<span class="chip" data-p="youtube">YouTube</span>
<button id="pub" disabled>Publish selected</button>
</div>
<div class="msg" id="msg"></div>
<script>
var inline = __OPENSHORTS_DATA__;
var state = null;
var selected = {};
function callTool(name, params) {
if (window.openai && window.openai.callTool) {
return window.openai.callTool(name, params);
}
window.parent.postMessage({type: 'tool', payload: {toolName: name, params: params}}, '*');
}
function platforms() {
var out = [];
document.querySelectorAll('.chip.on').forEach(function (c) { out.push(c.dataset.p); });
return out;
}
function refreshButton() {
var n = Object.keys(selected).length;
var btn = document.getElementById('pub');
btn.disabled = n === 0 || platforms().length === 0;
btn.textContent = n ? 'Publish ' + n + ' clip' + (n > 1 ? 's' : '') : 'Publish selected';
}
function render(data) {
state = data;
var clips = data.clips || [];
document.getElementById('hd').textContent =
clips.length + ' clip' + (clips.length !== 1 ? 's' : '') +
(data.job_id ? ' · job ' + data.job_id : '');
var grid = document.getElementById('grid');
grid.textContent = '';
clips.forEach(function (clip) {
var card = document.createElement('div');
card.className = 'card';
if (clip.video_url) {
var v = document.createElement('video');
v.src = clip.video_url;
v.muted = true; v.controls = true; v.playsInline = true; v.preload = 'metadata';
card.appendChild(v);
}
var t = document.createElement('div');
t.className = 't';
t.textContent = clip.title || ('Clip ' + clip.index);
card.appendChild(t);
var d = document.createElement('div');
d.className = 'd';
d.textContent = clip.duration_seconds ? clip.duration_seconds + 's' : '';
card.appendChild(d);
card.addEventListener('click', function (ev) {
if (ev.target.tagName === 'VIDEO') return; // let the player play
if (selected[clip.index]) { delete selected[clip.index]; card.classList.remove('sel'); }
else { selected[clip.index] = true; card.classList.add('sel'); }
refreshButton();
});
grid.appendChild(card);
});
document.getElementById('bar').hidden = clips.length === 0;
refreshButton();
}
document.querySelectorAll('.chip').forEach(function (c) {
c.addEventListener('click', function () { c.classList.toggle('on'); refreshButton(); });
});
document.getElementById('pub').addEventListener('click', function () {
var idxs = Object.keys(selected);
var ps = platforms();
idxs.forEach(function (i) {
callTool('publish_clip', {job_id: state.job_id, clip_index: parseInt(i, 10), platforms: ps});
});
document.getElementById('msg').textContent =
'Publish requested for ' + idxs.length + ' clip(s) to ' + ps.join(', ') +
'. Results arrive in the conversation.';
});
// Data path 2: ChatGPT Apps SDK injects structuredContent here.
function fromOpenai() {
var o = window.openai && (window.openai.toolOutput || window.openai.toolResponse);
if (o && o.clips) { render(o); return true; }
return false;
}
// Data path 3: MCP Apps / mcp-ui hosts push render data after we report ready.
window.addEventListener('message', function (ev) {
var m = ev.data || {};
var d = (m.payload && (m.payload.renderData || m.payload.toolOutput ||
m.payload.structuredContent)) ||
m.renderData || m.toolOutput || m.structuredContent;
if (d && d.clips) render(d);
});
window.addEventListener('openai:set_globals', fromOpenai);
if (inline && inline.clips) { render(inline); } // data path 1
else if (!fromOpenai()) {
try { window.parent.postMessage({type: 'ui-lifecycle-iframe-ready'}, '*'); } catch (e) {}
}
</script>
</body>
</html>
"""
def clip_picker_html(data=None) -> str:
"""The picker HTML; ``data`` baked in when rendering a per-call resource.
``<`` is escaped in the JSON so a clip title can never close the script
tag and inject markup.
"""
payload = "null" if data is None else json.dumps(
data, ensure_ascii=False).replace("<", "\\u003c")
return _TEMPLATE.replace("__OPENSHORTS_DATA__", payload)

View file

@ -44,7 +44,7 @@ class TestNotificationsAndErrors:
assert _run({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None assert _run({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None
def test_unknown_method_is_32601(self): def test_unknown_method_is_32601(self):
resp = _run({"jsonrpc": "2.0", "id": 7, "method": "resources/list"}) resp = _run({"jsonrpc": "2.0", "id": 7, "method": "does/not-exist"})
assert resp["error"]["code"] == -32601 assert resp["error"]["code"] == -32601
assert resp["id"] == 7 assert resp["id"] == 7

102
tests/test_mcp_ui.py Normal file
View file

@ -0,0 +1,102 @@
"""MCP Apps surface: the clip picker resource and its wiring.
Pure protocol-layer tests (handle_message with a fake tool_caller), same
pattern as test_mcp_protocol.py.
"""
import asyncio
import mcp_ui
from mcp_server import TOOLS, handle_message
def _run(msg, tool_caller=None):
async def _noop(name, args):
return {}, False
return asyncio.run(handle_message(msg, tool_caller or _noop))
def _req(method, params=None, msg_id=1):
m = {"jsonrpc": "2.0", "id": msg_id, "method": method}
if params is not None:
m["params"] = params
return m
class TestResourceSurface:
def test_initialize_advertises_resources(self):
resp = _run(_req("initialize", {"protocolVersion": "2025-06-18"}))
assert "resources" in resp["result"]["capabilities"]
def test_resources_list_contains_the_picker(self):
resp = _run(_req("resources/list"))
uris = [r["uri"] for r in resp["result"]["resources"]]
assert mcp_ui.CLIP_PICKER_URI in uris
def test_resources_read_serves_the_template(self):
resp = _run(_req("resources/read", {"uri": mcp_ui.CLIP_PICKER_URI}))
content = resp["result"]["contents"][0]
assert content["mimeType"] == mcp_ui.MIME_TYPE
# Template mode: no baked data, the bridge provides it.
assert "__OPENSHORTS_DATA__" not in content["text"]
assert "var inline = null;" in content["text"]
def test_resources_read_accepts_per_call_uris(self):
resp = _run(_req("resources/read", {"uri": mcp_ui.CLIP_PICKER_URI + "/job42"}))
assert resp["result"]["contents"][0]["uri"].endswith("/job42")
def test_unknown_resource_is_not_found(self):
resp = _run(_req("resources/read", {"uri": "ui://other/thing"}))
assert resp["error"]["code"] == -32002
class TestToolWiring:
def test_list_clips_declares_the_template_in_meta(self):
tool = next(t for t in TOOLS if t["name"] == "list_clips")
assert tool["_meta"]["ui"]["resourceUri"] == mcp_ui.CLIP_PICKER_URI
assert tool["_meta"]["openai/outputTemplate"] == mcp_ui.CLIP_PICKER_URI
def test_list_clips_result_embeds_the_picker_with_data(self):
clips = {"job_id": "j1", "clips": [{"index": 0, "title": "A", "video_url": "http://x/v.mp4"}]}
async def fake(name, args):
return clips, False
resp = _run(_req("tools/call", {"name": "list_clips",
"arguments": {"job_id": "j1"}}), fake)
content = resp["result"]["content"]
assert content[0]["type"] == "text"
embedded = content[1]
assert embedded["type"] == "resource"
assert embedded["resource"]["mimeType"] == mcp_ui.MIME_TYPE
assert embedded["resource"]["uri"] == mcp_ui.CLIP_PICKER_URI + "/j1"
assert '"job_id": "j1"' in embedded["resource"]["text"]
def test_other_tools_stay_text_only(self):
async def fake(name, args):
return {"clips": [{"index": 0}]}, False # even with clips in result
resp = _run(_req("tools/call", {"name": "get_quota", "arguments": {}}), fake)
assert len(resp["result"]["content"]) == 1
def test_failed_list_clips_embeds_nothing(self):
async def fake(name, args):
return {"error": "job is processing", "clips": []}, True
resp = _run(_req("tools/call", {"name": "list_clips",
"arguments": {"job_id": "j1"}}), fake)
assert len(resp["result"]["content"]) == 1
class TestTemplateSafety:
def test_titles_cannot_break_out_of_the_script_tag(self):
html = mcp_ui.clip_picker_html(
{"job_id": "j", "clips": [{"index": 0, "title": "</script><img onerror=x>"}]})
assert "</script><img" not in html
assert "\\u003c/script" in html
def test_template_is_self_contained(self):
html = mcp_ui.clip_picker_html()
for marker in ("http://", "https://"):
# No external fetches: host CSPs block them and the picker must
# render anyway. (Clip video URLs are data, not template.)
assert marker not in html