@pipeworx/mcp-youtube 0.1.1 → 0.1.3

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.
package/README.md CHANGED
@@ -1,18 +1,95 @@
1
- # mcp-youtube
1
+ # @pipeworx/youtube
2
2
 
3
- YouTube MCP — wraps the YouTube Data API v3 (BYO API key)
3
+ YouTube videos, channels, comments and transcripts: search, video and channel
4
+ metadata with view/like counts, comment threads, and the caption text of a video.
4
5
 
5
- Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1679+ live data sources.
6
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1763+ live data sources. This is an independent, unofficial integration — not affiliated with, endorsed by, or published by the upstream provider.
6
7
 
7
8
  ## Tools
8
9
 
9
- | Tool | Description |
10
- |------|-------------|
11
- | `yt_search` | Search YouTube for videos, channels, or playlists. Returns snippet info including title, description, channel, thumbnails, and publish date. |
12
- | `yt_video_details` | Get detailed information about one or more YouTube videos including title, description, channel, duration, view/like/comment counts, and tags. |
13
- | `yt_channel_details` | Get YouTube channel information and statistics including subscriber count, video count, view count, description, and custom URL. |
14
- | `yt_channel_videos` | List recent videos from a YouTube channel, ordered by date. Returns video ID, title, description, and publish date. |
15
- | `yt_video_comments` | Get top-level comment threads on a YouTube video. Returns author, text, like count, and publish date. |
10
+ - `yt_search(query, type?, …)` — videos, channels or playlists matching a term.
11
+ - `yt_video_details(video_id)` — title, description, duration, view/like/comment counts, tags.
12
+ - `yt_channel_details(channel_id | username)` — subscriber, video and view counts.
13
+ - `yt_channel_videos(channel_id, …)` — a channel's recent uploads.
14
+ - `yt_video_comments(video_id, …)` — top-level comment threads.
15
+ - `yt_video_transcript(video_id, lang?, start_seconds?, max_chars?)` — the
16
+ video's captions as timestamped segments plus the joined text, the track
17
+ language, and whether it is auto-generated. Accepts a bare ID or a
18
+ youtube.com / youtu.be URL. Long videos are paged: the response carries
19
+ `truncated` and `next_start_seconds`; pass that back as `start_seconds`.
20
+
21
+ ## Auth
22
+
23
+ - `yt_video_transcript` — **keyless.**
24
+ - Everything else — **BYO only**: a YouTube Data API v3 key from Google Cloud
25
+ Console, passed as `_apiKey`. Pipeworx does not front a shared key.
26
+
27
+ ## Data sources
28
+
29
+ - <https://www.googleapis.com/youtube/v3> — the Data API (all tools except the transcript).
30
+ - <https://www.youtube.com/youtubei/v1/player> — YouTube's own player endpoint,
31
+ called with the ANDROID client context; its `captionTracks[].baseUrl` is then
32
+ fetched with `fmt=json3` for the transcript.
33
+
34
+ **The transcript upstream is fragile.** It is an undocumented endpoint, not a
35
+ published API, and YouTube can change it without notice. What we know as of
36
+ 2026-10-09 (edge-probed from a Worker, fleet #2846):
37
+
38
+ - The **WEB** watch page lists the same caption tracks, but their URLs carry
39
+ `exp=xpe` and need a PO token: fetched bare they answer **200 with a 0-byte
40
+ body**. That is a silent empty transcript, so the WEB route is not used.
41
+ The ANDROID client's track URLs fetch without one.
42
+ - YouTube **intermittently** answers datacenter IPs with `LOGIN_REQUIRED`
43
+ "Sign in to confirm you're not a bot". It lands per request rather than per
44
+ video: through the live gateway it hit 7 of 10 consecutive calls with a
45
+ single attempt, and then let the same videos through. So the tool tries the
46
+ ANDROID client, then IOS (both give caption URLs that need no PO token;
47
+ ANDROID_VR does not qualify, it was bot-checked on every probe). If both are
48
+ refused it opens the public watch page. If that page shows the video plays
49
+ and has no caption tracks, the answer is `captions_unavailable`. Otherwise
50
+ both clients are retried carrying the visitor ID and cookies the page handed
51
+ out. Only after all four are refused does the call fail `upstream_down`,
52
+ saying that YouTube is blocking our servers. It never returns an empty
53
+ transcript. The watch page itself answers 429 from some egress IPs, and in
54
+ that case it is skipped.
55
+ - Translation (`&tlang=`) answers **429** from a datacenter IP, so a language
56
+ the video has no track for is refused (`captions_unavailable`, listing the
57
+ tracks it does have) rather than machine-translated.
58
+ - A video with no caption tracks fails `captions_unavailable`. A private,
59
+ removed or region-blocked video fails `not_found` with YouTube's own reason.
60
+
61
+ If this starts failing for every video, check the ANDROID `clientVersion` in
62
+ `src/index.ts` first — YouTube retires old client versions.
63
+
64
+ **The egress relay is NOT the fallback after that. Measured and ruled out
65
+ 2026-10-09 (fleet #2877).** It was the obvious next move and it is strictly
66
+ worse than what we have. Probed from a throwaway function on the relay's own
67
+ Supabase edge infra, against `www.youtube.com`:
68
+
69
+ | Leg the transcript needs | Through the relay | Residential control |
70
+ |---|---|---|
71
+ | `POST /youtubei/v1/player` | **403, 10/10** — Google's "Sorry… your computer or network may be sending automated queries" page, an identical 1,103 bytes on every call, across 5 different videos | 200 `OK`, 3/3, 2 caption tracks |
72
+ | `GET /watch?v=` | 200, 5/5, visitor ID present | — |
73
+ | `GET /api/timedtext` (signed) | 200, 3/3, 79,833 bytes — byte-identical to residential | 200, 79,833 bytes |
74
+
75
+ So the block is scoped to **exactly one endpoint** — the innertube player call —
76
+ and that is the only leg that fails on Cloudflare today. The relay refuses it
77
+ **100%** of the time; Cloudflare egress refuses it **40%** (8 of 20 live
78
+ `yt_video_transcript` calls across 10 videos, 2026-10-09). Routing the player
79
+ call through the relay would take the tool from partly working to never working,
80
+ which is why `www.youtube.com` is deliberately absent from the relay's
81
+ `ALLOWED_HOSTS` (there is a note there saying so). The two legs that *do* pass
82
+ the relay are not the ones that need help.
83
+
84
+ Measuring the 40% needs care: the gateway caches tool responses, so a probe that
85
+ repeats identical arguments reads far too healthy. An un-busted run of the same
86
+ 10 videos scored 14/16; varying `max_chars` per call to defeat the cache gave
87
+ 12/20. Vary an argument or you will measure the cache.
88
+
89
+ What is actually left, none of it tried: a residential/mobile proxy (costs
90
+ money, so it is Bruce's call), a PO-token minter so the WEB route's `exp=xpe`
91
+ URLs stop answering 0 bytes, or accepting the 40% and making the retry advice in
92
+ the error message the answer.
16
93
 
17
94
  ## Quick Start
18
95
 
@@ -58,7 +135,7 @@ directly, instead of just this one's:
58
135
  }
59
136
  ```
60
137
 
61
- Both URLs reach the same gateway and the same 1679+ data sources. The
138
+ Both URLs reach the same gateway and the same 1763+ data sources. The
62
139
  only difference is which pack's tools are listed **directly**; `ask_pipeworx`
63
140
  reaches all of them from either one.
64
141
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pipeworx/mcp-youtube",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "YouTube MCP — wraps the YouTube Data API v3 (BYO API key)",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -26,7 +26,7 @@
26
26
  "@cloudflare/workers-types": "^4.20260405.1"
27
27
  },
28
28
  "pipeworx": {
29
- "sourceHash": "v1-952ad5e9037046037d62b850ed259dfb84a5a657376993fb284fb487781e8039",
30
- "sourceCommit": "b0fb3c31386cf0256dcf1e2f1b3440435a87ec35"
29
+ "sourceHash": "v1-3a9451cbeb4277203c701eda5f0f85e1bab523481c5a480d9605f8403bb8120b",
30
+ "sourceCommit": "051ee2039fc96224cb5b7358fd69d525bced13a6"
31
31
  }
32
32
  }
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.pipeworx-io/youtube",
4
4
  "title": "Youtube",
5
5
  "description": "YouTube MCP — wraps the YouTube Data API v3 (BYO API key)",
6
- "version": "0.1.1",
6
+ "version": "0.1.3",
7
7
  "websiteUrl": "https://pipeworx.io/packs/youtube",
8
8
  "repository": {
9
9
  "url": "https://github.com/pipeworx-io/mcp-youtube",
package/src/index.ts CHANGED
@@ -452,7 +452,42 @@ async function fetchWithTimeout(
452
452
  ),
453
453
  );
454
454
  }
455
- throw err;
455
+ // Fleet #2382. Everything that isn't a timeout/abort here is a genuine
456
+ // NETWORK-LEVEL failure — DNS resolution, connection refused, TLS handshake,
457
+ // Cloudflare's own "Network connection lost." — meaning `fetch()` itself
458
+ // threw and no HTTP response of any kind was ever received. Until this fix
459
+ // that raw exception was rethrown VERBATIM: a bare `TypeError: fetch failed`
460
+ // (or the Workers-runtime equivalent) names no upstream, carries no class
461
+ // token, and reads exactly like a defect in OUR code — because it says
462
+ // nothing about the call at all. It landed in `error`, the tier that means
463
+ // "Pipeworx has a defect", for every one of the (at the time of writing)
464
+ // ~470 packs that call this helper directly with no wrapper of their own.
465
+ //
466
+ // `dexscreener` hit this independently (fleet #1579) and fixed it with a
467
+ // bespoke per-pack try/catch around `fetchWithTimeout`. That fix is correct
468
+ // but only covers one pack; every other caller of this shared helper still
469
+ // leaked the raw exception. Moving the same fix HERE — the one place that
470
+ // already carries the timeout case — covers every pack that uses
471
+ // `fetchWithTimeout` without a wrapper, for free, and without widening
472
+ // `classifyToolError`'s regex list: the fix is giving the message a proper
473
+ // `upstream_down:` token at the point the two facts (no response was ever
474
+ // received, and which host we were trying to reach) are actually in hand,
475
+ // not teaching the classifier to guess from prose after the fact.
476
+ //
477
+ // Safe on the same grounds as the timeout branch above: no argument a
478
+ // caller passes can make `fetch()` itself throw a connection-level error,
479
+ // so this is always an availability failure, never a caller mistake. Same
480
+ // `markInternalOrigin` treatment — an origin we run that never answered is
481
+ // still ours, not a third party's outage.
482
+ const raw = err instanceof Error ? err.message : String(err);
483
+ throw new Error(
484
+ markInternalOrigin(
485
+ `upstream_down: could not reach ${name} at all (${raw.slice(0, 160)}). ` +
486
+ `No request reached ${name}, so this says NOTHING about whether the arguments you passed ` +
487
+ 'are valid — do not re-check them on the strength of this error. Retry shortly.',
488
+ url,
489
+ ),
490
+ );
456
491
  }
457
492
  }
458
493
 
@@ -644,6 +679,8 @@ function collapse(s: string): string {
644
679
  * - yt_channel_details: get channel info and stats
645
680
  * - yt_channel_videos: list videos from a channel
646
681
  * - yt_video_comments: get comments on a video
682
+ * - yt_video_transcript: caption track (timestamped segments + joined text) —
683
+ * KEYLESS, via YouTube's own player endpoint, not the Data API
647
684
  */
648
685
 
649
686
 
@@ -656,6 +693,32 @@ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response>
656
693
  }
657
694
 
658
695
  const BASE = 'https://www.googleapis.com/youtube/v3';
696
+ const PLAYER_URL = 'https://www.youtube.com/youtubei/v1/player?prettyPrint=false';
697
+ // The ANDROID / IOS innertube clients are the ones whose caption baseUrls fetch
698
+ // without a PO token. The WEB watch page lists the same tracks, but its URLs carry
699
+ // `exp=xpe` and answer 200 with a ZERO-byte body when fetched bare — a silent
700
+ // empty transcript, which is the exact failure this tool must never return.
701
+ // Edge-probed from a Worker 2026-10-09 (fleet #2846).
702
+ // YouTube's datacenter bot-check ("Sign in to confirm you're not a bot") lands
703
+ // per request, not per video: measured live through the gateway 2026-10-09 it
704
+ // hit 7 of 10 consecutive calls and then let the same videos through. So the
705
+ // player call rotates through two clients whose caption URLs need no PO token
706
+ // (ANDROID_VR does NOT qualify — it is bot-checked on every probe), then
707
+ // repeats both carrying the visitor id the public watch page hands out.
708
+ const PLAYER_CLIENTS: { context: Record<string, unknown>; ua: string }[] = [
709
+ {
710
+ context: { clientName: 'ANDROID', clientVersion: '20.10.38', androidSdkVersion: 34, hl: 'en' },
711
+ ua: 'com.google.android.youtube/20.10.38 (Linux; U; Android 14) gzip',
712
+ },
713
+ {
714
+ context: { clientName: 'IOS', clientVersion: '20.10.4', deviceMake: 'Apple', deviceModel: 'iPhone16,2', osName: 'iPhone', osVersion: '18.3.2.22D82', hl: 'en' },
715
+ ua: 'com.google.ios.youtube/20.10.4 (iPhone16,2; U; CPU iOS 18_3_2 like Mac OS X;)',
716
+ },
717
+ ];
718
+ const BROWSER_UA =
719
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36';
720
+ const TRANSCRIPT_MAX_CHARS_DEFAULT = 50_000;
721
+ const TRANSCRIPT_MAX_CHARS_CAP = 200_000;
659
722
 
660
723
  // ── Tool definitions ──────────────────────────────────────────────────
661
724
 
@@ -772,6 +835,34 @@ const tools: McpToolExport['tools'] = [
772
835
  required: ['_apiKey', 'video_id'],
773
836
  },
774
837
  },
838
+ {
839
+ name: 'yt_video_transcript',
840
+ description:
841
+ 'Get the transcript (captions) of a YouTube video: timestamped segments plus the joined text, the caption language, and whether the track is auto-generated. No API key needed. Use it to summarize, quote or search what is said in a video. Long videos are paged: pass the returned next_start_seconds as start_seconds to continue. A video with no captions returns a captions_unavailable error, never an empty transcript.',
842
+ inputSchema: {
843
+ type: 'object' as const,
844
+ properties: {
845
+ video_id: {
846
+ type: 'string',
847
+ description: 'YouTube video ID (e.g. "dQw4w9WgXcQ") or a full youtube.com / youtu.be URL',
848
+ },
849
+ lang: {
850
+ type: 'string',
851
+ description:
852
+ 'Caption language code (e.g. "en", "fr", "pt-BR"). "en" also matches "en-US". Default: the video\'s default caption track. If the video has no track in this language the error lists the ones it has.',
853
+ },
854
+ start_seconds: {
855
+ type: 'number',
856
+ description: 'Skip segments that start before this many seconds (for paging through long videos). Default 0.',
857
+ },
858
+ max_chars: {
859
+ type: 'number',
860
+ description: `Stop after this many characters of transcript text (default ${TRANSCRIPT_MAX_CHARS_DEFAULT}, max ${TRANSCRIPT_MAX_CHARS_CAP}).`,
861
+ },
862
+ },
863
+ required: ['video_id'],
864
+ },
865
+ },
775
866
  ];
776
867
 
777
868
  // ── Helpers ───────────────────────────────────────────────────────────
@@ -1049,9 +1140,233 @@ async function videoComments(key: string, videoId: string, maxResults?: number,
1049
1140
  };
1050
1141
  }
1051
1142
 
1143
+ // ── Transcript (keyless) ─────────────────────────────────────────────
1144
+
1145
+ interface CaptionTrack {
1146
+ baseUrl: string;
1147
+ languageCode: string;
1148
+ kind?: string;
1149
+ name?: { simpleText?: string; runs?: { text: string }[] };
1150
+ }
1151
+
1152
+ interface PlayerResponse {
1153
+ playabilityStatus?: { status?: string; reason?: string };
1154
+ videoDetails?: { videoId?: string; title?: string; author?: string; channelId?: string; lengthSeconds?: string };
1155
+ captions?: {
1156
+ playerCaptionsTracklistRenderer?: {
1157
+ captionTracks?: CaptionTrack[];
1158
+ audioTracks?: { captionTrackIndices?: number[]; defaultCaptionTrackIndex?: number }[];
1159
+ };
1160
+ };
1161
+ }
1162
+
1163
+ function parseVideoId(input: string): string {
1164
+ const raw = String(input ?? '').trim();
1165
+ if (/^[A-Za-z0-9_-]{11}$/.test(raw)) return raw;
1166
+ const m =
1167
+ raw.match(/[?&]v=([A-Za-z0-9_-]{11})/) ??
1168
+ raw.match(/youtu\.be\/([A-Za-z0-9_-]{11})/) ??
1169
+ raw.match(/\/(?:shorts|embed|live|v)\/([A-Za-z0-9_-]{11})/);
1170
+ if (m) return m[1];
1171
+ throw new Error(`user_error: "${raw}" is not a YouTube video ID or URL. A video ID is 11 characters, e.g. "dQw4w9WgXcQ".`);
1172
+ }
1173
+
1174
+ async function playerCall(
1175
+ videoId: string,
1176
+ client: (typeof PLAYER_CLIENTS)[number],
1177
+ visitor?: WatchPage,
1178
+ ): Promise<PlayerResponse> {
1179
+ const headers: Record<string, string> = { 'content-type': 'application/json', 'user-agent': client.ua };
1180
+ let context = client.context;
1181
+ if (visitor) {
1182
+ headers['x-goog-visitor-id'] = visitor.visitorData;
1183
+ if (visitor.cookie) headers.cookie = visitor.cookie;
1184
+ context = { ...context, visitorData: visitor.visitorData };
1185
+ }
1186
+ const res = await pwFetch(PLAYER_URL, { method: 'POST', headers, body: JSON.stringify({ context: { client: context }, videoId }) });
1187
+ if (res.status === 429) throw new Error('upstream_throttled: YouTube rate-limited the transcript lookup (HTTP 429). Retry in a minute.');
1188
+ if (!res.ok) throw new Error(`upstream_down: YouTube player endpoint returned HTTP ${res.status} for video ${videoId}.`);
1189
+ return (await res.json()) as PlayerResponse;
1190
+ }
1191
+
1192
+ interface WatchPage {
1193
+ visitorData: string;
1194
+ cookie: string;
1195
+ /** The page itself says the video plays and lists no caption tracks. */
1196
+ noCaptions: boolean;
1197
+ title: string | null;
1198
+ }
1199
+
1200
+ // The public watch page: no login, no forged identity — what any browser that
1201
+ // opened the video would get. It yields the visitor id + cookies a retry
1202
+ // carries, and it states on its own whether the video has caption tracks,
1203
+ // which settles captions_unavailable even when every player call is
1204
+ // bot-checked. Null when the page itself is refused (it answers 429 from some
1205
+ // egress IPs) — then it has told us nothing.
1206
+ async function fetchWatchPage(videoId: string): Promise<WatchPage | null> {
1207
+ const res = await pwFetch(`https://www.youtube.com/watch?v=${videoId}`, {
1208
+ headers: { 'user-agent': BROWSER_UA, 'accept-language': 'en' },
1209
+ });
1210
+ if (!res.ok) return null;
1211
+ const html = await res.text();
1212
+ const visitorData = html.match(/"VISITOR_DATA":"([^"]+)"/)?.[1];
1213
+ if (!visitorData) return null;
1214
+ const setCookies = (res.headers as Headers & { getSetCookie?: () => string[] }).getSetCookie?.() ?? [];
1215
+ const playable = html.match(/"playabilityStatus":\{"status":"([A-Z_]+)"/)?.[1] === 'OK';
1216
+ const rawTitle = html.match(/<meta name="title" content="([^"]*)"/)?.[1];
1217
+ const title = rawTitle
1218
+ ? rawTitle.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
1219
+ : null;
1220
+ return {
1221
+ visitorData,
1222
+ cookie: setCookies.map((c) => c.split(';')[0]).join('; '),
1223
+ noCaptions: playable && !html.includes('"captionTracks"'),
1224
+ title,
1225
+ };
1226
+ }
1227
+
1228
+ function isBotCheck(p: PlayerResponse): boolean {
1229
+ return p.playabilityStatus?.status === 'LOGIN_REQUIRED' && /bot/i.test(p.playabilityStatus?.reason ?? '');
1230
+ }
1231
+
1232
+ function captionsUnavailable(videoId: string, title: string | null | undefined): Error {
1233
+ return new Error(
1234
+ `not_found: captions_unavailable — video ${videoId}${title ? ` ("${title}")` : ''} has no captions: the uploader disabled them or YouTube generated none. There is no transcript to return.`,
1235
+ );
1236
+ }
1237
+
1238
+ async function resolvePlayer(videoId: string): Promise<PlayerResponse> {
1239
+ let last: PlayerResponse | undefined;
1240
+ for (const client of PLAYER_CLIENTS) {
1241
+ last = await playerCall(videoId, client);
1242
+ if (!isBotCheck(last)) return last;
1243
+ }
1244
+ const page = await fetchWatchPage(videoId);
1245
+ if (page?.noCaptions) throw captionsUnavailable(videoId, page.title);
1246
+ if (page) {
1247
+ for (const client of PLAYER_CLIENTS) {
1248
+ last = await playerCall(videoId, client, page);
1249
+ if (!isBotCheck(last)) return last;
1250
+ }
1251
+ }
1252
+ throw new Error(
1253
+ `upstream_down: YouTube refused the transcript lookup from our servers ("${last?.playabilityStatus?.reason ?? 'bot check'}") on ${page ? 4 : 2} attempts. This is YouTube blocking datacenter traffic, not a problem with video ${videoId} — retry shortly.`,
1254
+ );
1255
+ }
1256
+
1257
+ function trackLabel(t: CaptionTrack): string {
1258
+ return t.name?.simpleText ?? t.name?.runs?.map((r) => r.text).join('') ?? t.languageCode;
1259
+ }
1260
+
1261
+ function pickTrack(player: PlayerResponse, lang: string | undefined): CaptionTrack {
1262
+ const r = player.captions?.playerCaptionsTracklistRenderer;
1263
+ const tracks = r?.captionTracks ?? [];
1264
+ if (lang) {
1265
+ const want = lang.toLowerCase();
1266
+ const exact = tracks.filter((t) => t.languageCode.toLowerCase() === want);
1267
+ const prefix = tracks.filter((t) => t.languageCode.toLowerCase().split('-')[0] === want.split('-')[0]);
1268
+ const pool = exact.length ? exact : prefix;
1269
+ // A human-made track beats the auto-generated one in the same language.
1270
+ const hit = pool.find((t) => t.kind !== 'asr') ?? pool[0];
1271
+ if (hit) return hit;
1272
+ throw new Error(
1273
+ `not_found: captions_unavailable — video ${player.videoDetails?.videoId ?? ''} has no caption track in "${lang}". ` +
1274
+ `Available: ${tracks.map((t) => `${t.languageCode}${t.kind === 'asr' ? ' (auto-generated)' : ''}`).join(', ')}. Call again with one of those as lang.`,
1275
+ );
1276
+ }
1277
+ const audio = r?.audioTracks?.[0];
1278
+ const idx = audio?.defaultCaptionTrackIndex ?? audio?.captionTrackIndices?.[0];
1279
+ if (idx !== undefined && tracks[idx]) return tracks[idx];
1280
+ return tracks.find((t) => t.kind !== 'asr') ?? tracks[0];
1281
+ }
1282
+
1283
+ async function videoTranscript(input: string, lang?: string, startSeconds?: number, maxChars?: number) {
1284
+ const videoId = parseVideoId(input);
1285
+ const player = await resolvePlayer(videoId);
1286
+ const status = player.playabilityStatus?.status;
1287
+ const reason = player.playabilityStatus?.reason ?? '';
1288
+ if (status !== 'OK') {
1289
+ // Private, removed, age-gated or region-blocked — the caller named a video
1290
+ // whose captions nobody without a login can read.
1291
+ throw new Error(`not_found: YouTube video ${videoId} is not publicly playable (${status ?? 'no status'}${reason ? `: ${reason}` : ''}).`);
1292
+ }
1293
+ const tracks = player.captions?.playerCaptionsTracklistRenderer?.captionTracks ?? [];
1294
+ if (tracks.length === 0) throw captionsUnavailable(videoId, player.videoDetails?.title);
1295
+ const track = pickTrack(player, lang);
1296
+ const url = `${track.baseUrl.replace(/&fmt=[^&]*/, '')}&fmt=json3`;
1297
+ const res = await pwFetch(url, { headers: { 'user-agent': BROWSER_UA } });
1298
+ if (res.status === 429) throw new Error('upstream_throttled: YouTube rate-limited the caption download (HTTP 429). Retry in a minute.');
1299
+ if (!res.ok) throw new Error(`upstream_down: YouTube caption endpoint returned HTTP ${res.status} for video ${videoId}.`);
1300
+ const body = await res.text();
1301
+ if (!body.trim()) {
1302
+ throw new Error(`upstream_down: YouTube returned an empty caption file for video ${videoId} (${track.languageCode}) — the track exists but the download was refused.`);
1303
+ }
1304
+ const data = JSON.parse(body) as { events?: { tStartMs?: number; dDurationMs?: number; segs?: { utf8?: string }[] }[] };
1305
+
1306
+ const all = (data.events ?? [])
1307
+ .filter((e) => e.segs)
1308
+ .map((e) => ({
1309
+ start: (e.tStartMs ?? 0) / 1000,
1310
+ duration: (e.dDurationMs ?? 0) / 1000,
1311
+ text: (e.segs ?? []).map((g) => g.utf8 ?? '').join('').replace(/\s+/g, ' ').trim(),
1312
+ }))
1313
+ .filter((s) => s.text);
1314
+ if (all.length === 0) {
1315
+ throw new Error(`not_found: captions_unavailable — the ${track.languageCode} caption track of video ${videoId} contains no text.`);
1316
+ }
1317
+
1318
+ const from = Math.max(0, Number(startSeconds) || 0);
1319
+ const cap = Math.min(Math.max(1000, Number(maxChars) || TRANSCRIPT_MAX_CHARS_DEFAULT), TRANSCRIPT_MAX_CHARS_CAP);
1320
+ const segments: { start_seconds: number; duration_seconds: number; text: string }[] = [];
1321
+ let chars = 0;
1322
+ let nextStart: number | null = null;
1323
+ for (const s of all) {
1324
+ if (s.start < from) continue;
1325
+ if (chars + s.text.length > cap && segments.length > 0) {
1326
+ nextStart = s.start;
1327
+ break;
1328
+ }
1329
+ segments.push({ start_seconds: Math.round(s.start * 100) / 100, duration_seconds: Math.round(s.duration * 100) / 100, text: s.text });
1330
+ chars += s.text.length + 1;
1331
+ }
1332
+ if (segments.length === 0) {
1333
+ throw new Error(`user_error: start_seconds ${from} is past the end of the transcript (last segment starts at ${Math.floor(all[all.length - 1].start)}s).`);
1334
+ }
1335
+
1336
+ const v = player.videoDetails ?? {};
1337
+ return {
1338
+ video_id: videoId,
1339
+ title: v.title ?? null,
1340
+ channel: v.author ?? null,
1341
+ channel_id: v.channelId ?? null,
1342
+ length_seconds: v.lengthSeconds ? Number(v.lengthSeconds) : null,
1343
+ language: track.languageCode,
1344
+ language_name: trackLabel(track),
1345
+ auto_generated: track.kind === 'asr',
1346
+ available_tracks: tracks.map((t) => ({ language: t.languageCode, name: trackLabel(t), auto_generated: t.kind === 'asr' })),
1347
+ segment_count: segments.length,
1348
+ total_segments: all.length,
1349
+ truncated: nextStart !== null,
1350
+ next_start_seconds: nextStart,
1351
+ text: segments.map((s) => s.text).join(' '),
1352
+ segments,
1353
+ source: `https://www.youtube.com/watch?v=${videoId}`,
1354
+ };
1355
+ }
1356
+
1052
1357
  // ── callTool dispatcher ──────────────────────────────────────────────
1053
1358
 
1054
1359
  async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
1360
+ // Keyless: reads YouTube's public player + caption endpoints, not the Data API.
1361
+ if (name === 'yt_video_transcript') {
1362
+ return videoTranscript(
1363
+ args.video_id as string,
1364
+ args.lang as string | undefined,
1365
+ args.start_seconds as number | undefined,
1366
+ args.max_chars as number | undefined,
1367
+ );
1368
+ }
1369
+
1055
1370
  const apiKey = extractKey(args);
1056
1371
 
1057
1372
  switch (name) {
package/src/server.ts CHANGED
@@ -9,7 +9,7 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprot
9
9
  import pack from './index.js';
10
10
 
11
11
  const server = new Server(
12
- { name: '@pipeworx/mcp-youtube', version: '0.1.1' },
12
+ { name: '@pipeworx/mcp-youtube', version: '0.1.3' },
13
13
  { capabilities: { tools: {} } },
14
14
  );
15
15