vidleaf-mcp 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """Vidleaf MCP Server & CLI — timestamped transcripts for YouTube, Bilibili, TikTok, Vimeo, Douyin, Xiaohongshu, Facebook, and X."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "1.1.0"
6
+ DEFAULT_BASE_URL = "https://vidleaf.app"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
vidleaf_mcp/cli.py ADDED
@@ -0,0 +1,131 @@
1
+ """Unified CLI and MCP stdio entrypoint for vidleaf-mcp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .client import VidleafClient, VidleafError
11
+ from .server import McpStdioServer
12
+ from .urls import ALLOWED_GOALS, ALLOWED_LOCALES, build_open_url
13
+
14
+
15
+ def build_parser() -> argparse.ArgumentParser:
16
+ parser = argparse.ArgumentParser(
17
+ prog="vidleaf-mcp",
18
+ description=(
19
+ "Vidleaf MCP Server & CLI — read timestamped YouTube, Bilibili, TikTok, Vimeo, Facebook, "
20
+ "Douyin, Xiaohongshu, and X (Twitter) transcripts or generate https://vidleaf.app/open links."
21
+ ),
22
+ )
23
+ parser.add_argument("--version", action="version", version=f"vidleaf-mcp {__version__}")
24
+ parser.add_argument("--stdio", action="store_true", help="Run MCP server over stdio (default when no subcommand is given).")
25
+ parser.add_argument("--base-url", default=None, help="Override Vidleaf base URL (default: https://vidleaf.app).")
26
+
27
+ sub = parser.add_subparsers(dest="command")
28
+
29
+ sub.add_parser("serve", help="Run Model Context Protocol (MCP) server over stdio.")
30
+
31
+ p_read = sub.add_parser("read", help="Fetch timestamped transcript for a public video URL.")
32
+ p_read.add_argument("url", help="Video URL, Bilibili BV ID, or mobile share text.")
33
+ p_read.add_argument("--lang", action="append", dest="langs", help="Preferred subtitle language (repeatable, max 3).")
34
+ p_read.add_argument("--offset", type=int, default=0, help="Starting cue offset (default: 0).")
35
+ p_read.add_argument("--limit", type=int, default=300, help="Max cues per page (1–500, default: 300).")
36
+ p_read.add_argument(
37
+ "--format",
38
+ choices=["timestamped", "markdown", "srt", "plain", "json"],
39
+ default="timestamped",
40
+ help="Output format (default: timestamped).",
41
+ )
42
+ p_read.add_argument("--locale", choices=["", *ALLOWED_LOCALES], default="", help="Locale for Vidleaf open link.")
43
+
44
+ p_search = sub.add_parser("search", help="Search keywords or exact phrases inside video captions.")
45
+ p_search.add_argument("url", help="Video URL, Bilibili BV ID, or mobile share text.")
46
+ p_search.add_argument("keywords", nargs="+", help="1–10 keywords or phrases to match.")
47
+ p_search.add_argument("--lang", default="", help="Subtitle track language.")
48
+ p_search.add_argument("--context", type=int, default=1, help="Context lines around each hit (0–3).")
49
+ p_search.add_argument("--limit", type=int, default=25, help="Maximum hits (1–100).")
50
+ p_search.add_argument("--json", action="store_true", help="Emit full JSON output.")
51
+
52
+ p_open = sub.add_parser("open", help="Build normalized https://vidleaf.app/open?... deep-reading link offline.")
53
+ p_open.add_argument("url", help="Video URL or mobile share snippet.")
54
+ p_open.add_argument("--goal", choices=list(ALLOWED_GOALS), default="transcript", help="Reader goal (transcript or summary).")
55
+ p_open.add_argument("--locale", choices=["", *ALLOWED_LOCALES], default="", help="UI locale.")
56
+ p_open.add_argument("--start", type=int, default=None, help="Optional start timestamp in seconds.")
57
+ p_open.add_argument("--json", action="store_true", help="Emit full JSON output.")
58
+
59
+ return parser
60
+
61
+
62
+ def main(argv: list[str] | None = None) -> int:
63
+ if hasattr(sys.stdout, "reconfigure"):
64
+ sys.stdout.reconfigure(encoding="utf-8")
65
+ if hasattr(sys.stderr, "reconfigure"):
66
+ sys.stderr.reconfigure(encoding="utf-8")
67
+
68
+ args = build_parser().parse_args(argv)
69
+ client = VidleafClient(base_url=args.base_url)
70
+
71
+ if args.stdio or args.command in (None, "serve"):
72
+ McpStdioServer(client=client).serve_forever()
73
+ return 0
74
+
75
+ try:
76
+ if args.command == "open":
77
+ res = build_open_url(
78
+ args.url,
79
+ goal=args.goal,
80
+ locale=args.locale,
81
+ start_seconds=args.start,
82
+ base_url=client.base_url,
83
+ )
84
+ if args.json:
85
+ print(json.dumps(res, ensure_ascii=False, indent=2))
86
+ else:
87
+ print(res["open_url"])
88
+ return 0
89
+
90
+ if args.command == "read":
91
+ fmt = "timestamped" if args.format == "json" else args.format
92
+ res = client.read_transcript(
93
+ args.url,
94
+ langs=args.langs,
95
+ offset=args.offset,
96
+ limit=args.limit,
97
+ output_format=fmt,
98
+ locale=args.locale,
99
+ )
100
+ if args.format == "json":
101
+ print(json.dumps(res, ensure_ascii=False, indent=2))
102
+ elif res["status"] == "ok":
103
+ print(res["formatted_transcript"])
104
+ else:
105
+ print(f"[{res['status']}] {res.get('message', '')}\nOpen in Vidleaf: {res['open_url']}", file=sys.stderr)
106
+ return 2 if res["status"] == "asr_confirmation_required" else 1
107
+ return 0
108
+
109
+ if args.command == "search":
110
+ res = client.search_transcript(
111
+ args.url,
112
+ args.keywords,
113
+ lang=args.lang,
114
+ context=args.context,
115
+ limit=args.limit,
116
+ )
117
+ if args.json:
118
+ print(json.dumps(res, ensure_ascii=False, indent=2))
119
+ elif res["status"] != "ok":
120
+ print(f"[{res['status']}] {res.get('message', '')}\nOpen in Vidleaf: {res['open_url']}", file=sys.stderr)
121
+ return 2 if res["status"] == "asr_confirmation_required" else 1
122
+ else:
123
+ print(f"Title: {res['title']} ({res['total_hits']} hits) — {res['open_url']}")
124
+ for hit in res["hits"]:
125
+ print(f"[{hit['time']}] {hit['text']}")
126
+ return 0
127
+ except (ValueError, VidleafError) as exc:
128
+ print(f"Error: {exc}", file=sys.stderr)
129
+ return 1
130
+
131
+ return 0
vidleaf_mcp/client.py ADDED
@@ -0,0 +1,332 @@
1
+ """Zero-dependency HTTP client for Vidleaf public & anonymous caption endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.cookiejar
6
+ import json
7
+ import os
8
+ import time
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from typing import Any
13
+
14
+ from . import DEFAULT_BASE_URL, __version__
15
+ from .urls import build_open_url, format_srt_timestamp, format_timestamp
16
+
17
+
18
+ class VidleafError(RuntimeError):
19
+ def __init__(self, message: str, *, status_code: int = 0, code: str = "") -> None:
20
+ super().__init__(message)
21
+ self.status_code = status_code
22
+ self.code = code
23
+
24
+
25
+ class VidleafClient:
26
+ """Session-aware client for https://vidleaf.app anonymous caption & search APIs."""
27
+
28
+ def __init__(
29
+ self,
30
+ base_url: str | None = None,
31
+ session_cookie: str | None = None,
32
+ timeout: float = 25.0,
33
+ ) -> None:
34
+ self.base_url = (base_url or os.environ.get("VIDLEAF_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
35
+ self.session_cookie = (session_cookie or os.environ.get("VIDLEAF_SESSION_COOKIE") or "").strip()
36
+ self.timeout = timeout
37
+ self._jar = http.cookiejar.CookieJar()
38
+ self._opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self._jar))
39
+ self._bootstrapped = False
40
+ self._ua = f"vidleaf-mcp/{__version__} (+https://github.com/blackmirror69/vidleaf-mcp)"
41
+
42
+ def _request_json(self, method: str, path: str, payload: dict | None = None) -> Any:
43
+ url = f"{self.base_url}{path}"
44
+ headers = {
45
+ "User-Agent": self._ua,
46
+ "Accept": "application/json",
47
+ }
48
+ if self.session_cookie:
49
+ headers["Cookie"] = (
50
+ self.session_cookie
51
+ if "=" in self.session_cookie
52
+ else f"vsub_session={self.session_cookie}"
53
+ )
54
+ data: bytes | None = None
55
+ if method != "GET":
56
+ headers["Origin"] = self.base_url
57
+ headers["Content-Type"] = "application/json"
58
+ data = json.dumps(payload or {}, ensure_ascii=False).encode("utf-8")
59
+
60
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
61
+ try:
62
+ with self._opener.open(req, timeout=self.timeout) as resp:
63
+ raw = resp.read().decode("utf-8")
64
+ return json.loads(raw) if raw else {}
65
+ except urllib.error.HTTPError as exc:
66
+ body = exc.read().decode("utf-8", errors="replace")
67
+ detail_msg = f"HTTP {exc.code}"
68
+ err_code = ""
69
+ try:
70
+ parsed = json.loads(body)
71
+ detail = parsed.get("detail")
72
+ if isinstance(detail, dict):
73
+ detail_msg = detail.get("message") or detail.get("code") or detail_msg
74
+ err_code = detail.get("code") or ""
75
+ elif isinstance(detail, str):
76
+ detail_msg = detail
77
+ except json.JSONDecodeError:
78
+ if body.strip():
79
+ detail_msg = body.strip()[:200]
80
+ raise VidleafError(detail_msg, status_code=exc.code, code=err_code) from None
81
+ except urllib.error.URLError as exc:
82
+ raise VidleafError(f"Network error contacting {self.base_url}: {exc.reason}") from None
83
+
84
+ def ensure_session(self) -> None:
85
+ if self._bootstrapped or self.session_cookie:
86
+ self._bootstrapped = True
87
+ return
88
+ self._request_json("GET", "/api/auth/me")
89
+ self._bootstrapped = True
90
+
91
+ def resolve_job(self, raw_input: str, langs: list[str] | None = None, max_wait_seconds: float = 28.0) -> dict:
92
+ """Submit or reuse a caption-fetch job and wait until terminal state."""
93
+ self.ensure_session()
94
+ links = build_open_url(raw_input, base_url=self.base_url)
95
+ clean_langs = [x.strip() for x in (langs or ["zh", "en"]) if x and x.strip()][:3] or ["zh", "en"]
96
+ job = self._request_json(
97
+ "POST",
98
+ "/api/jobs",
99
+ {"url": links["extracted_url"], "langs": clean_langs, "use_cache": True},
100
+ )
101
+ job_id = job["job_id"]
102
+ state = job
103
+ if state.get("status") not in ("done", "error", "canceled"):
104
+ deadline = time.monotonic() + max(3.0, min(max_wait_seconds, 60.0))
105
+ delay = 0.6
106
+ while time.monotonic() < deadline:
107
+ time.sleep(delay)
108
+ state = self._request_json("GET", f"/api/jobs/{urllib.parse.quote(job_id)}")
109
+ if state.get("status") in ("done", "error", "canceled"):
110
+ break
111
+ delay = min(1.8, delay * 1.35)
112
+ return {"job": state, "links": links}
113
+
114
+ def read_transcript(
115
+ self,
116
+ raw_input: str,
117
+ *,
118
+ langs: list[str] | None = None,
119
+ offset: int = 0,
120
+ limit: int = 300,
121
+ output_format: str = "timestamped",
122
+ locale: str = "",
123
+ ) -> dict:
124
+ resolved = self.resolve_job(raw_input, langs=langs)
125
+ state = resolved["job"]
126
+ links = build_open_url(raw_input, locale=locale, base_url=self.base_url)
127
+ video_key = state.get("video_key") or ""
128
+ status = state.get("status") or "unknown"
129
+
130
+ if status not in ("done",):
131
+ return {
132
+ "status": "error" if status in ("error", "canceled") else "processing",
133
+ "video_key": video_key,
134
+ "title": (state.get("preflight") or {}).get("title") or "",
135
+ "platform": links["platform"],
136
+ "source_url": links["extracted_url"],
137
+ "open_url": links["open_url"],
138
+ "summary_open_url": links["summary_open_url"],
139
+ "message": state.get("error") or state.get("stage") or f"Job ended in status: {status}",
140
+ "total_cues": 0,
141
+ "returned_cues": 0,
142
+ "has_more": False,
143
+ "cues": [],
144
+ "formatted_transcript": "",
145
+ }
146
+
147
+ video_info = self._request_json("GET", f"/api/videos/{urllib.parse.quote(video_key)}")
148
+ meta = video_info.get("meta") or {}
149
+ tracks = video_info.get("tracks") or []
150
+ if not tracks:
151
+ return {
152
+ "status": "asr_confirmation_required",
153
+ "video_key": video_key,
154
+ "title": meta.get("title") or "",
155
+ "duration_seconds": meta.get("duration"),
156
+ "platform": links["platform"],
157
+ "source_url": meta.get("url") or links["extracted_url"],
158
+ "open_url": links["open_url"],
159
+ "summary_open_url": links["summary_open_url"],
160
+ "message": (
161
+ "This video has no existing platform captions. To avoid unexpected audio billing, "
162
+ "open the Vidleaf link to inspect duration/free allowance and confirm speech-to-text transcription."
163
+ ),
164
+ "total_cues": 0,
165
+ "returned_cues": 0,
166
+ "has_more": False,
167
+ "cues": [],
168
+ "formatted_transcript": "",
169
+ }
170
+
171
+ preferred_lang = ""
172
+ if langs:
173
+ for wanted in langs:
174
+ for tr in tracks:
175
+ if (tr.get("lang") or "").lower().startswith(wanted.lower()):
176
+ preferred_lang = tr.get("lang") or ""
177
+ break
178
+ if preferred_lang:
179
+ break
180
+
181
+ bounded_limit = max(1, min(int(limit), 500))
182
+ bounded_offset = max(0, int(offset))
183
+ qs = urllib.parse.urlencode(
184
+ {"offset": bounded_offset, "limit": bounded_limit, **({"lang": preferred_lang} if preferred_lang else {})}
185
+ )
186
+ cues_resp = self._request_json("GET", f"/api/videos/{urllib.parse.quote(video_key)}/cues?{qs}")
187
+ raw_cues = cues_resp.get("cues") or []
188
+ total = int(cues_resp.get("total") or len(raw_cues))
189
+ next_offset = cues_resp.get("next_offset")
190
+ formatted = _format_cues(
191
+ raw_cues,
192
+ output_format=output_format,
193
+ title=cues_resp.get("title") or meta.get("title") or "",
194
+ source_url=cues_resp.get("url") or links["extracted_url"],
195
+ open_url=links["open_url"],
196
+ offset=bounded_offset,
197
+ )
198
+ return {
199
+ "status": "ok",
200
+ "video_key": video_key,
201
+ "title": cues_resp.get("title") or meta.get("title") or "",
202
+ "duration_seconds": cues_resp.get("duration_seconds") or meta.get("duration"),
203
+ "platform": links["platform"],
204
+ "lang": cues_resp.get("lang") or "",
205
+ "track_source": cues_resp.get("source") or "",
206
+ "available_tracks": [
207
+ {"lang": t.get("lang", ""), "source": t.get("source", ""), "count": int(t.get("count") or 0)}
208
+ for t in tracks
209
+ ],
210
+ "source_url": cues_resp.get("url") or links["extracted_url"],
211
+ "open_url": links["open_url"],
212
+ "summary_open_url": links["summary_open_url"],
213
+ "total_cues": total,
214
+ "offset": bounded_offset,
215
+ "returned_cues": len(raw_cues),
216
+ "next_offset": next_offset,
217
+ "has_more": next_offset is not None,
218
+ "cues": [
219
+ {"start": float(c["start"]), "end": float(c["end"]), "time": format_timestamp(c["start"]), "text": c["text"]}
220
+ for c in raw_cues
221
+ ],
222
+ "formatted_transcript": formatted,
223
+ }
224
+
225
+ def search_transcript(
226
+ self,
227
+ raw_input: str,
228
+ keywords: list[str],
229
+ *,
230
+ lang: str = "",
231
+ context: int = 1,
232
+ limit: int = 25,
233
+ offset: int = 0,
234
+ locale: str = "",
235
+ ) -> dict:
236
+ clean_kws = [k.strip() for k in keywords if k and k.strip()][:10]
237
+ if not clean_kws:
238
+ raise ValueError("At least one non-empty keyword is required.")
239
+ resolved = self.resolve_job(raw_input, langs=[lang] if lang else None)
240
+ state = resolved["job"]
241
+ links = build_open_url(raw_input, locale=locale, base_url=self.base_url)
242
+ video_key = state.get("video_key") or ""
243
+ if state.get("status") != "done":
244
+ return {
245
+ "status": "error",
246
+ "video_key": video_key,
247
+ "title": "",
248
+ "open_url": links["open_url"],
249
+ "total_hits": 0,
250
+ "has_more": False,
251
+ "hits": [],
252
+ "message": state.get("error") or f"Caption fetch not ready: {state.get('status')}",
253
+ }
254
+ try:
255
+ resp = self._request_json(
256
+ "POST",
257
+ "/api/search",
258
+ {
259
+ "video_key": video_key,
260
+ "keywords": clean_kws,
261
+ "lang": lang,
262
+ "context": max(0, min(int(context), 3)),
263
+ "limit": max(1, min(int(limit), 100)),
264
+ "offset": max(0, int(offset)),
265
+ },
266
+ )
267
+ except VidleafError as exc:
268
+ if exc.status_code == 404 and exc.code == "search_no_tracks":
269
+ return {
270
+ "status": "asr_confirmation_required",
271
+ "video_key": video_key,
272
+ "title": "",
273
+ "open_url": links["open_url"],
274
+ "total_hits": 0,
275
+ "has_more": False,
276
+ "hits": [],
277
+ "message": (
278
+ "This video has no existing platform captions. Open the Vidleaf link to confirm "
279
+ "speech-to-text transcription first."
280
+ ),
281
+ }
282
+ raise
283
+
284
+ hits = [
285
+ {
286
+ "keyword": h.get("keyword", ""),
287
+ "time": h.get("time") or format_timestamp(h.get("start", 0.0)),
288
+ "start": float(h.get("start", 0.0)),
289
+ "end": float(h.get("end", 0.0)),
290
+ "text": h.get("text", ""),
291
+ "context": h.get("context", ""),
292
+ "jump_url": h.get("url") or links["open_url"],
293
+ }
294
+ for h in (resp.get("hits") or [])
295
+ ]
296
+ return {
297
+ "status": "ok",
298
+ "video_key": video_key,
299
+ "title": resp.get("title") or "",
300
+ "lang": resp.get("lang") or "",
301
+ "open_url": links["open_url"],
302
+ "total_hits": int(resp.get("total") or 0),
303
+ "has_more": bool(resp.get("has_more")),
304
+ "matched_keywords": resp.get("matched") or [],
305
+ "missing_keywords": resp.get("missing") or [],
306
+ "hits": hits,
307
+ }
308
+
309
+
310
+ def _format_cues(
311
+ cues: list[dict],
312
+ *,
313
+ output_format: str,
314
+ title: str,
315
+ source_url: str,
316
+ open_url: str,
317
+ offset: int = 0,
318
+ ) -> str:
319
+ if output_format == "plain":
320
+ return "\n".join(c["text"] for c in cues)
321
+ if output_format == "srt":
322
+ blocks = []
323
+ for idx, c in enumerate(cues, start=offset + 1):
324
+ blocks.append(
325
+ f"{idx}\n{format_srt_timestamp(c['start'])} --> {format_srt_timestamp(c['end'])}\n{c['text']}"
326
+ )
327
+ return "\n\n".join(blocks)
328
+ lines = [f"[{format_timestamp(c['start'])}] {c['text']}" for c in cues]
329
+ if output_format == "markdown":
330
+ header = f"# {title or 'Video Transcript'}\n\n- Source: {source_url}\n- Deep Reader: {open_url}\n\n"
331
+ return header + "\n".join(f"- `{format_timestamp(c['start'])}` {c['text']}" for c in cues)
332
+ return "\n".join(lines)
vidleaf_mcp/server.py ADDED
@@ -0,0 +1,196 @@
1
+ """Standard MCP JSON-RPC 2.0 stdio server (2024-11-05 / 2025-03-26 / 2025-06-18)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from typing import Any, TextIO
8
+
9
+ from . import __version__
10
+ from .client import VidleafClient, VidleafError
11
+ from .tools import TOOLS
12
+ from .urls import build_open_url
13
+
14
+ SUPPORTED_PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05")
15
+
16
+ PROMPTS = [
17
+ {
18
+ "name": "summarize-video-with-citations",
19
+ "title": "Summarize Video with Timestamp Citations",
20
+ "description": "Read a video's transcript via Vidleaf and produce chapter takeaways with verifiable timestamps.",
21
+ "arguments": [
22
+ {"name": "url", "description": "Public YouTube, Bilibili, TikTok, Vimeo, Douyin, Xiaohongshu, Facebook, or X video URL.", "required": True},
23
+ ],
24
+ },
25
+ ]
26
+
27
+ RESOURCES = [
28
+ {
29
+ "uri": "vidleaf://capabilities",
30
+ "name": "Vidleaf Platform & Allowance Capabilities",
31
+ "description": "Supported platforms, 6 UI locales, free caption reading vs confirmation-gated ASR rules.",
32
+ "mimeType": "application/json",
33
+ },
34
+ ]
35
+
36
+
37
+ class McpStdioServer:
38
+ def __init__(self, client: VidleafClient | None = None) -> None:
39
+ self.client = client or VidleafClient()
40
+ self.negotiated_protocol = "2025-06-18"
41
+
42
+ def handle_message(self, msg: dict[str, Any]) -> dict[str, Any] | None:
43
+ method = msg.get("method")
44
+ msg_id = msg.get("id")
45
+ params = msg.get("params") or {}
46
+
47
+ if msg_id is None:
48
+ return None
49
+
50
+ try:
51
+ if method == "initialize":
52
+ requested = str(params.get("protocolVersion") or "2025-06-18")
53
+ self.negotiated_protocol = requested if requested in SUPPORTED_PROTOCOLS else SUPPORTED_PROTOCOLS[0]
54
+ return self._ok(
55
+ msg_id,
56
+ {
57
+ "protocolVersion": self.negotiated_protocol,
58
+ "capabilities": {
59
+ "tools": {"listChanged": False},
60
+ "prompts": {"listChanged": False},
61
+ "resources": {"subscribe": False, "listChanged": False},
62
+ },
63
+ "serverInfo": {"name": "vidleaf-mcp", "version": __version__},
64
+ "instructions": (
65
+ "Use Vidleaf tools to fetch timestamped transcripts, search exact quotes, "
66
+ "or build https://vidleaf.app/open?url=... deep-reading links for YouTube, "
67
+ "Bilibili, TikTok, Vimeo, Facebook, Douyin, Xiaohongshu, and X (Twitter) videos."
68
+ ),
69
+ },
70
+ )
71
+ if method == "ping":
72
+ return self._ok(msg_id, {})
73
+ if method == "tools/list":
74
+ return self._ok(msg_id, {"tools": TOOLS})
75
+ if method == "tools/call":
76
+ return self._ok(msg_id, self._call_tool(params.get("name", ""), params.get("arguments") or {}))
77
+ if method == "prompts/list":
78
+ return self._ok(msg_id, {"prompts": PROMPTS})
79
+ if method == "prompts/get":
80
+ return self._ok(msg_id, self._get_prompt(params.get("name", ""), params.get("arguments") or {}))
81
+ if method == "resources/list":
82
+ return self._ok(msg_id, {"resources": RESOURCES})
83
+ if method == "resources/read":
84
+ return self._ok(msg_id, self._read_resource(params.get("uri", "")))
85
+ return self._err(msg_id, -32601, f"Method not found: {method}")
86
+ except ValueError as exc:
87
+ return self._err(msg_id, -32602, str(exc))
88
+ except Exception as exc:
89
+ return self._err(msg_id, -32603, str(exc))
90
+
91
+ def _call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
92
+ try:
93
+ if name == "build_vidleaf_open_link":
94
+ data = build_open_url(
95
+ args.get("url", ""),
96
+ goal=args.get("goal") or "transcript",
97
+ locale=args.get("locale") or "",
98
+ start_seconds=args.get("start_seconds"),
99
+ base_url=self.client.base_url,
100
+ )
101
+ elif name == "read_video_transcript":
102
+ data = self.client.read_transcript(
103
+ args.get("url", ""),
104
+ langs=args.get("langs"),
105
+ offset=int(args.get("offset", 0)),
106
+ limit=int(args.get("limit", 300)),
107
+ output_format=args.get("format") or "timestamped",
108
+ locale=args.get("locale") or "",
109
+ )
110
+ elif name == "search_video_transcript":
111
+ data = self.client.search_transcript(
112
+ args.get("url", ""),
113
+ args.get("keywords") or [],
114
+ lang=args.get("lang") or "",
115
+ context=int(args.get("context", 1)),
116
+ limit=int(args.get("limit", 25)),
117
+ offset=int(args.get("offset", 0)),
118
+ locale=args.get("locale") or "",
119
+ )
120
+ else:
121
+ raise ValueError(f"Unknown tool: {name}")
122
+ except (ValueError, VidleafError) as exc:
123
+ return {
124
+ "content": [{"type": "text", "text": json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)}],
125
+ "isError": True,
126
+ }
127
+
128
+ res: dict[str, Any] = {
129
+ "content": [{"type": "text", "text": json.dumps(data, ensure_ascii=False, indent=2)}],
130
+ "isError": data.get("status") == "error",
131
+ }
132
+ if self.negotiated_protocol >= "2025-06-18":
133
+ res["structuredContent"] = data
134
+ return res
135
+
136
+ def _get_prompt(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
137
+ if name != "summarize-video-with-citations":
138
+ raise ValueError(f"Unknown prompt: {name}")
139
+ url = args.get("url") or "<VIDEO_URL>"
140
+ return {
141
+ "description": "Summarize video transcript with timestamp citations and Vidleaf deep-reader link.",
142
+ "messages": [
143
+ {
144
+ "role": "user",
145
+ "content": {
146
+ "type": "text",
147
+ "text": (
148
+ f"Call `read_video_transcript` on {url}. Summarize the core chapters and arguments "
149
+ "with exact `[MM:SS]` timestamps, and include the `open_url` link at the end so I "
150
+ "can verify quotes or trigger speech-to-text if the video has no captions."
151
+ ),
152
+ },
153
+ }
154
+ ],
155
+ }
156
+
157
+ def _read_resource(self, uri: str) -> dict[str, Any]:
158
+ if uri != "vidleaf://capabilities":
159
+ raise ValueError(f"Unknown resource URI: {uri}")
160
+ payload = {
161
+ "service": "Vidleaf",
162
+ "website": self.client.base_url,
163
+ "platforms": ["youtube", "bilibili", "tiktok", "vimeo", "facebook", "douyin", "xiaohongshu", "x"],
164
+ "locales": ["zh", "zh-Hant", "en", "es", "ja", "pt-BR"],
165
+ "free_caption_reading": True,
166
+ "confirmation_gated_asr": True,
167
+ "companion_repo": "https://github.com/blackmirror69/vidleaf-open",
168
+ }
169
+ return {"contents": [{"uri": uri, "mimeType": "application/json", "text": json.dumps(payload, indent=2)}]}
170
+
171
+ @staticmethod
172
+ def _ok(msg_id: Any, result: dict[str, Any]) -> dict[str, Any]:
173
+ return {"jsonrpc": "2.0", "id": msg_id, "result": result}
174
+
175
+ @staticmethod
176
+ def _err(msg_id: Any, code: int, message: str) -> dict[str, Any]:
177
+ return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}
178
+
179
+ def serve_forever(self, stdin: TextIO | None = None, stdout: TextIO | None = None) -> None:
180
+ inp = stdin or sys.stdin
181
+ out = stdout or sys.stdout
182
+ for raw_line in inp:
183
+ line = raw_line.strip()
184
+ if not line:
185
+ continue
186
+ try:
187
+ msg = json.loads(line)
188
+ except json.JSONDecodeError:
189
+ resp = self._err(None, -32700, "Parse error")
190
+ out.write(json.dumps(resp, ensure_ascii=False) + "\n")
191
+ out.flush()
192
+ continue
193
+ resp = self.handle_message(msg)
194
+ if resp is not None:
195
+ out.write(json.dumps(resp, ensure_ascii=False) + "\n")
196
+ out.flush()