commit d178b80d2c2cffb472877fc3eed25e2bd909607a
parent cb8ba813156c6e35de9314ea5919519a35ffedb9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 02:17:11 -0400
mcp: enumerate_matches' scan as data (enumerate.ts), clip-target mapping shared, a research export for umtool
The tool now renders enumerate()'s result, so a structured caller covers the
same set by construction. searchTranscripts gains onRecord (every record read,
before filters); fetchClip takes requestedBy. umtool depends on the mcp package.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 483 insertions(+), 220 deletions(-)
diff --git a/mcp/package.json b/mcp/package.json
@@ -5,7 +5,8 @@
"type": "module",
"exports": {
"./package.json": "./package.json",
- "./callTool": "./src/callTool.ts"
+ "./callTool": "./src/callTool.ts",
+ "./research": "./src/research.ts"
},
"description": "MCP server exposing a yt-dlp transcript archive (or a federated hub) to Claude Code and other MCP clients \u2014 reads the site's static JSON shards.",
"bin": {
diff --git a/mcp/src/clipTarget.ts b/mcp/src/clipTarget.ts
@@ -0,0 +1,34 @@
+// A cited moment mapped to the editor's directory (fetch_clip's first step),
+// shared by the tool and umtool's Research page so both ask the editor for the
+// same thing.
+//
+// Rumble: the cited id is the EMBED id (the record's `id`); the editor's
+// directory is the URL slug, read off the record's webpageUrl. The channel is
+// the one the record lives in, which is the editor's directory even when the
+// citation spelled it by name or in another case. A video the source does not
+// hold is passed as cited, with a note saying so.
+import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { isVideoId, notFoundNote, type FetchClipRequest } from "./fetchClip";
+import { findVideo } from "./search";
+import type { ShardSource } from "./source";
+
+export async function resolveClipTarget(
+ source: ShardSource,
+ handle: string,
+ request: FetchClipRequest,
+): Promise<{ note: string; ctx: { channel?: string; video?: string } }> {
+ if (!("target" in request)) return { note: "", ctx: {} };
+ const target = request.target;
+ let note = "";
+ const found = await findVideo(source, target.video, target.channel);
+ if (found) {
+ const webpageUrl = found.record.webpageUrl;
+ const mapped = webpageUrl ? extractVideoId(webpageUrl) : null;
+ target.video = mapped && isVideoId(mapped) ? mapped : target.video;
+ target.channel = found.ch.slug;
+ if (target.kind === "window" && webpageUrl) target.webpageUrl = webpageUrl;
+ } else {
+ note = `${notFoundNote(target.video, handle)}\n\n`;
+ }
+ return { note, ctx: { channel: target.channel, video: target.video } };
+}
diff --git a/mcp/src/enumerate.test.ts b/mcp/src/enumerate.test.ts
@@ -0,0 +1,125 @@
+// enumerate(): the scan behind enumerate_matches, as data. The tool and a
+// caller of enumerate() cover exactly the same set, because the tool renders
+// enumerate()'s result -- these pin that, and the two options a structured
+// caller adds (snippets, onRecord) change nothing about which recordings match.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { CHANNELS, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { createCorpusTools, type CorpusTools } from "./callTool";
+import { enumerate, type Enumerated } from "./enumerate";
+import { resolveClipTarget } from "./clipTarget";
+import { fetchClip, validateFetchClipArgs, type FetchClipDeps } from "./fetchClip";
+import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { LocalSource } from "./source";
+
+let dir: string;
+let corpus: CorpusTools;
+
+before(async () => {
+ dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "mcp-enumerate-")));
+ corpus = await createCorpusTools({ source: `local:${dir}` });
+});
+
+after(async () => {
+ await corpus.close();
+ await rm(dir, { recursive: true, force: true });
+});
+
+// The ids a worklist row names: `- <id> | video | …`.
+const toolIds = (text: string) => [...text.matchAll(/^- ([^ |]+) \| /gm)].map((m) => m[1]);
+const ok = (e: Enumerated | { error: string }): Enumerated => {
+ if ("error" in e) throw new Error(e.error);
+ return e;
+};
+
+for (const args of [
+ { query: "the" },
+ { query: "sourdough" },
+ { query: "contest", channels: ["synth-kitchen"] },
+ { query: "o.en", regex: true },
+ { query: "the", date_from: "2026-02-01" },
+ { query: "the", exclude: ["oven"] },
+]) {
+ test(`enumerate() and the tool cover the same set: ${JSON.stringify(args)}`, async () => {
+ const text = await corpus.call("enumerate_matches", args);
+ const e = ok(await enumerate(new LocalSource(dir), args, { includeSnippets: true, snippetsPerVideo: 12 }));
+ const total = Number(/(\d+) match\(es\);/.exec(text)?.[1] ?? "0");
+ assert.equal(e.result.total, total);
+ assert.deepEqual(
+ e.result.hits.map((h) => h.videoId),
+ toolIds(text),
+ );
+ assert.equal(e.result.truncated, /COVERAGE PARTIAL/.test(text));
+ });
+}
+
+test("snippets are the caller's choice and never change the set", async () => {
+ const src = new LocalSource(dir);
+ const bare = ok(await enumerate(src, { query: "the" }));
+ const rich = ok(await enumerate(src, { query: "the" }, { includeSnippets: true, snippetsPerVideo: 2 }));
+ assert.deepEqual(rich.result.hits.map((h) => h.videoId), bare.result.hits.map((h) => h.videoId));
+ assert.ok(bare.result.hits.every((h) => h.snippets.length === 0));
+ assert.ok(rich.result.hits.every((h) => h.snippets.length > 0 && h.snippets.length <= 2));
+ // matches still counts every hit, past the snippets kept.
+ const qa = rich.result.hits.find((h) => h.videoId === "qa-long-03")!;
+ assert.ok(qa.matches > qa.snippets.length);
+});
+
+test("onRecord sees every record the scan reads, before any filter or match", async () => {
+ const seen: string[] = [];
+ const e = ok(
+ await enumerate(new LocalSource(dir), { query: "contest", date_from: "2026-02-01" }, {
+ onRecord: (rec, ch) => seen.push(`${ch.slug}/${rec.id}`),
+ }),
+ );
+ const all = CHANNELS.flatMap((c: { slug: string; records: { id: string }[] }) => c.records.map((r) => `${c.slug}/${r.id}`));
+ assert.deepEqual([...seen].sort(), [...all].sort());
+ assert.deepEqual(e.result.hits.map((h) => h.videoId), ["pie-stream-02"]);
+});
+
+test("a bad argument is the tool's error, and nothing is searched", async () => {
+ assert.deepEqual(await enumerate(new LocalSource(dir), { query: " " }), { error: "query is required" });
+ const bad = await enumerate(new LocalSource(dir), { query: "x", date_from: "yesterday" });
+ assert.ok("error" in bad && /not a date/.test(bad.error));
+});
+
+test("resolveClipTarget: the record's channel and its URL's id, as fetch_clip sends them", async () => {
+ const v = validateFetchClipArgs({ channel: "Synth Kitchen", video: "bread-day-01", start: 15, end: 20, reason: "r" });
+ assert.ok(v.ok);
+ const { note, ctx } = await resolveClipTarget(new LocalSource(dir), `local:${dir}`, v.request);
+ assert.equal(note, "");
+ // The channel the record lives in, and the id the editor names its directory
+ // with: extractVideoId of the record's URL (on Rumble, not the embed id).
+ const url = "https://video.example/watch?v=bread-day-01";
+ const dirId = extractVideoId(url);
+ assert.deepEqual(ctx, { channel: "synth-kitchen", video: dirId && /^[\w.-]+$/.test(dirId) ? dirId : "bread-day-01" });
+ assert.ok("target" in v.request && v.request.target.kind === "window");
+ assert.equal((v.request.target as { webpageUrl?: string }).webpageUrl, "https://video.example/watch?v=bread-day-01");
+
+ const gone = validateFetchClipArgs({ channel: "synth-kitchen", video: "nope-99", start: 1, end: 2, reason: "r" });
+ assert.ok(gone.ok);
+ const r = await resolveClipTarget(new LocalSource(dir), `local:${dir}`, gone.request);
+ assert.match(r.note, /nope-99/);
+});
+
+test("fetchClip says who asked: mcp by default, the caller's name when given", async () => {
+ const bodies: unknown[] = [];
+ const deps: FetchClipDeps = {
+ env: { WORKER_TOKEN: "tok", ARCHILYZER_EDITOR_URL: "http://editor.test" },
+ fetch: async (_url, init) => {
+ bodies.push(JSON.parse(init?.body ?? "{}"));
+ return { status: 200, json: async () => ({ file: "/x/clips/1.00-2.00.mp4", from: 1, to: 2, bytes: 1 }) };
+ },
+ sleep: async () => {},
+ now: () => 0,
+ };
+ const v = validateFetchClipArgs({ channel: "c", video: "v", start: 5, end: 6, reason: "r" });
+ assert.ok(v.ok);
+ await fetchClip(v.request, deps);
+ await fetchClip(v.request, deps, { requestedBy: "umtool" });
+ assert.deepEqual(bodies.map((b) => (b as { requestedBy: string }).requestedBy), ["mcp", "umtool"]);
+});
diff --git a/mcp/src/enumerate.ts b/mcp/src/enumerate.ts
@@ -0,0 +1,247 @@
+// THE ENUMERATE, AS DATA (umtool redesign R1): the one scan behind
+// `enumerate_matches`, callable in process.
+//
+// `enumerate_matches` renders its result as text for an agent. umtool's
+// Research page needs the same scan as structured data -- the ids, the
+// timecodes, the coverage -- and must not parse the text to get it. So the
+// scan lives here, and the tool is a renderer over it: the scoping, the
+// filters, the exclusions, the alias expansion, the mirror collapsing and the
+// caps (MCP_POLICY) are one code path for both by construction.
+//
+// The argument parsing for both search tools moved here from server.ts
+// unchanged (`parseSearchArgs`, `strArray`): it is the half of the contract a
+// caller passing the tool's own arguments needs.
+import { normalizeDateArg } from "./dateArg";
+import { isTagId } from "yt-dlp-transcript-common/lib/curatedTags";
+import {
+ VIDEO_STATES,
+ isVideoState,
+ type VideoState,
+} from "yt-dlp-transcript-common/lib/availability";
+import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery";
+import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts";
+import type { ChannelRef, ShardSource } from "./source";
+import {
+ parseContentTypes,
+ searchTranscripts,
+ type SearchFilters,
+ type SearchResult,
+} from "./search";
+
+// The parsed form of SEARCH_FILTER_ARGS, plus any tokens that were not
+// understood. Unknown tokens are REPORTED rather than dropped silently: a
+// typo'd state ("removed" for "deleted") would otherwise widen the search back
+// to the whole corpus and look like a legitimate empty result.
+export type ParsedSearchArgs = {
+ filters: SearchFilters | null;
+ exclude?: string[];
+ scopes?: LayerScope[];
+ collapseDuplicates: boolean;
+ warnings: string[];
+ // Set when an argument must stop the call rather than be dropped (a date
+ // bound that is not a date). Callers return it as an error and search nothing.
+ error?: string;
+};
+
+export const SCOPE_TOKENS: ReadonlyArray<LayerScope> = [
+ "transcripts",
+ "chat",
+ "description",
+ "tags",
+ "metadata",
+ "posts",
+];
+
+export function parseSearchArgs(args: Record<string, unknown>): ParsedSearchArgs {
+ const warnings: string[] = [];
+
+ const rawStates = strArray(args.states);
+ let states: VideoState[] | undefined;
+ if (rawStates) {
+ states = rawStates.filter((s): s is VideoState => isVideoState(s));
+ const bad = rawStates.filter((s) => !isVideoState(s));
+ if (bad.length > 0) {
+ warnings.push(
+ `unknown state(s) ignored: ${bad.join(", ")} (valid: ${VIDEO_STATES.join(", ")})`,
+ );
+ }
+ if (states.length === 0) {
+ states = undefined;
+ warnings.push("no valid states given — the state filter was NOT applied");
+ }
+ }
+
+ const mediaType =
+ args.media_type === "video" || args.media_type === "livestream"
+ ? args.media_type
+ : undefined;
+ if (args.media_type !== undefined && mediaType === undefined) {
+ warnings.push(`unknown media_type ignored: ${String(args.media_type)}`);
+ }
+ const age =
+ args.age === "all_ages" || args.age === "restricted" ? args.age : undefined;
+ if (args.age !== undefined && age === undefined) {
+ warnings.push(`unknown age ignored: ${String(args.age)}`);
+ }
+
+ // A date bound the caller cannot have meant is an ERROR, not a warning: an
+ // ignored bound widens the search to the whole corpus and the count reads as
+ // the bounded one (see dateArg.ts). The common spellings are normalised.
+ const from = normalizeDateArg(args.date_from);
+ const to = normalizeDateArg(args.date_to);
+ const badDates = [
+ ["date_from", args.date_from, from],
+ ["date_to", args.date_to, to],
+ ]
+ .filter(([, , v]) => v === null)
+ .map(([name, raw]) => `${name}=${JSON.stringify(raw)}`);
+ const error = badDates.length
+ ? `not a date: ${badDates.join(", ")} — use YYYYMMDD or YYYY-MM-DD. Nothing was searched.`
+ : undefined;
+
+ // Curated tags. A malformed id is REPORTED, never silently dropped: dropping
+ // the only tag in the list would widen the search back to the whole corpus
+ // and read as a legitimate result, which is the same failure a typo'd state
+ // would cause.
+ const rawTags = strArray(args.tags);
+ let tags: string[] | undefined;
+ if (rawTags) {
+ const normalized = rawTags.map((t) => t.trim().toLowerCase());
+ tags = normalized.filter((t) => isTagId(t));
+ const bad = normalized.filter((t) => !isTagId(t));
+ if (bad.length > 0) {
+ warnings.push(
+ `not a tag id, ignored: ${bad.join(", ")} (ids are lowercase, ` +
+ `[a-z0-9._-]; call list_tags)`,
+ );
+ }
+ if (tags.length === 0) {
+ tags = undefined;
+ warnings.push("no valid tags given — the tag filter was NOT applied");
+ }
+ }
+
+ const anyFilter =
+ states !== undefined ||
+ mediaType !== undefined ||
+ age !== undefined ||
+ Boolean(from) ||
+ Boolean(to) ||
+ tags !== undefined;
+
+ const filters: SearchFilters | null = anyFilter
+ ? {
+ videos: mediaType === undefined || mediaType === "video",
+ livestreams: mediaType === undefined || mediaType === "livestream",
+ allAges: age === undefined || age === "all_ages",
+ restricted: age === undefined || age === "restricted",
+ states: new Set<VideoState>(states ?? VIDEO_STATES),
+ ...(from ? { dateFrom: from } : {}),
+ ...(to ? { dateTo: to } : {}),
+ ...(tags ? { curatedTags: tags } : {}),
+ }
+ : null;
+
+ const rawScopes = strArray(args.scopes);
+ let scopes: LayerScope[] | undefined;
+ if (rawScopes) {
+ scopes = rawScopes.filter((s): s is LayerScope =>
+ (SCOPE_TOKENS as readonly string[]).includes(s),
+ );
+ const bad = rawScopes.filter(
+ (s) => !(SCOPE_TOKENS as readonly string[]).includes(s),
+ );
+ if (bad.length > 0) {
+ warnings.push(`unknown scope(s) ignored: ${bad.join(", ")}`);
+ }
+ if (scopes.length === 0) {
+ scopes = undefined;
+ warnings.push("no valid scopes given — searching captions + title");
+ }
+ }
+
+ return {
+ filters,
+ exclude: strArray(args.exclude),
+ scopes,
+ collapseDuplicates: args.collapse_duplicates !== false,
+ warnings,
+ ...(error ? { error } : {}),
+ };
+}
+
+// Coerce a tool arg to a trimmed non-empty string[] (drops non-strings/blanks).
+export function strArray(v: unknown): string[] | undefined {
+ if (!Array.isArray(v)) return undefined;
+ const out = v
+ .filter((x): x is string => typeof x === "string")
+ .map((x) => x.trim())
+ .filter((x) => x !== "");
+ return out.length > 0 ? out : undefined;
+}
+
+// Videos per batch when a call names none: the sweep's own batch.
+export const DEFAULT_BATCH_SIZE = 8;
+
+export type EnumerateOptions = {
+ // The worklist carries no cue text by default, exactly as the tool's. A
+ // caller that shows the hits asks for snippets; WHICH recordings match does
+ // not change (snippets are collected after a record has matched).
+ includeSnippets?: boolean;
+ // Snippets kept per recording when they are included (the engine's default,
+ // 4, otherwise). `matches` still counts every hit.
+ snippetsPerVideo?: number;
+ // Every transcript record the scan reads, before any filter: what a caller
+ // learns about the scope for free (umtool counts transcripts vs captions).
+ onRecord?: (rec: TranscriptDetail, ch: ChannelRef) => void;
+};
+
+export type Enumerated = {
+ query: string;
+ parsed: ParsedSearchArgs;
+ result: SearchResult;
+ batchSize: number;
+};
+
+// `enumerate_matches`' scan: the tool's own arguments in, the whole match set
+// out (never a page of it -- the coverage rule). `{ error }` is the text the
+// tool answers with as an error, and nothing was searched.
+export async function enumerate(
+ source: ShardSource,
+ args: Record<string, unknown>,
+ opts: EnumerateOptions = {},
+): Promise<Enumerated | { error: string }> {
+ const query = String(args.query ?? "").trim();
+ if (!query) return { error: "query is required" };
+
+ const batchSizeArg =
+ typeof args.batch_size === "number" ? Math.floor(args.batch_size) : DEFAULT_BATCH_SIZE;
+ const batchSize = batchSizeArg >= 1 ? batchSizeArg : DEFAULT_BATCH_SIZE;
+
+ const parsed = parseSearchArgs(args);
+ if (parsed.error) return { error: parsed.error };
+ const result = await searchTranscripts(source, {
+ query,
+ filters: parsed.filters,
+ exclude: parsed.exclude,
+ scopes: parsed.scopes,
+ collapseDuplicates: parsed.collapseDuplicates,
+ // The singulars stay parsed even though they are no longer advertised.
+ channel: typeof args.channel === "string" ? args.channel : undefined,
+ channels: strArray(args.channels),
+ group: typeof args.group === "string" ? args.group : undefined,
+ groups: strArray(args.groups),
+ regex: args.regex === true,
+ useAliases: args.use_aliases !== false,
+ maxPages: typeof args.max_pages === "number" ? args.max_pages : undefined,
+ contentTypes: parseContentTypes(args.content_types),
+ includeSnippets: opts.includeSnippets === true,
+ ...(opts.snippetsPerVideo !== undefined ? { snippetsPerVideo: opts.snippetsPerVideo } : {}),
+ ...(opts.onRecord ? { onRecord: opts.onRecord } : {}),
+ offset: 0,
+ // The whole set: searchTranscripts collects up to HARD_VIDEO_CAP and then
+ // slices, so asking for every collected match costs nothing extra.
+ limit: Number.MAX_SAFE_INTEGER,
+ });
+ return { query, parsed, result, batchSize };
+}
diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts
@@ -398,7 +398,12 @@ export type PollProgress = {
export async function fetchClip(
request: FetchClipRequest,
deps: FetchClipDeps,
- hooks: { onPoll?: (p: PollProgress) => void | Promise<void> } = {},
+ hooks: {
+ onPoll?: (p: PollProgress) => void | Promise<void>;
+ // Who asked, as the editor records it beside the file (default "mcp"):
+ // umtool's Research page says "umtool".
+ requestedBy?: string;
+ } = {},
): Promise<FetchClipOutcome> {
const editor = editorFromEnv(deps.env);
if (!editor) return { kind: "no_editor" };
@@ -499,7 +504,7 @@ export async function fetchClip(
const { target } = request;
const provenance = {
- requestedBy: REQUESTED_BY,
+ requestedBy: hooks.requestedBy ?? REQUESTED_BY,
manifest: request.report,
reason: request.reason.slice(0, MAX_REASON_CHARS),
};
diff --git a/mcp/src/research.ts b/mcp/src/research.ts
@@ -0,0 +1,44 @@
+// What umtool's Research page reads the corpus through, in process
+// (plans/umtool-redesign.md, R1): the SAME engine the tools wrap, as data.
+//
+// enumerate enumerate_matches' scan (enumerate.ts) -- the ids,
+// hits and coverage, never a page of them
+// SourceRegistry a handle (local:/remote:/hub:) to a live source,
+// cached per handle, as the server resolves `source`
+// findVideo / findPost one record, as get_transcript / get_post find it
+// fetch_clip's client validate, map the cite to the editor's directory,
+// ask the editor (never yt-dlp)
+//
+// Read-only, like every corpus tool; the only write is the editor's, through
+// its fetch-window route.
+export {
+ enumerate,
+ parseSearchArgs,
+ strArray,
+ DEFAULT_BATCH_SIZE,
+ type Enumerated,
+ type EnumerateOptions,
+ type ParsedSearchArgs,
+} from "./enumerate";
+export { SourceRegistry, handleFor, type ResolvedSource } from "./sourceRegistry";
+export type { SourceSpec } from "./sources";
+export {
+ findVideo,
+ findPost,
+ MCP_POLICY,
+ type SearchHit,
+ type SearchResult,
+ type Snippet,
+} from "./search";
+export type { ChannelRef, ShardSource } from "./source";
+export {
+ fetchClip,
+ validateFetchClipArgs,
+ editorFromEnv,
+ describeFetchError,
+ NO_EDITOR_TEXT,
+ type FetchClipDeps,
+ type FetchClipOutcome,
+ type FetchClipRequest,
+} from "./fetchClip";
+export { resolveClipTarget } from "./clipTarget";
diff --git a/mcp/src/search.ts b/mcp/src/search.ts
@@ -486,6 +486,11 @@ export async function searchTranscripts(
// existing caller reads exactly the same pages and parses exactly the same
// bytes. A caller with a different budget passes its own.
policy?: SearchPolicy;
+ // Told every transcript record the video pass reads, BEFORE any filter or
+ // match: what the scan saw of the scope, for a caller that wants to learn
+ // about it for free (umtool counts transcripts vs captions per channel).
+ // Changes nothing about what matches.
+ onRecord?: (rec: TranscriptDetail, ch: ChannelRef) => void;
},
): Promise<SearchResult> {
const policy = opts.policy ?? MCP_POLICY;
@@ -603,6 +608,7 @@ export async function searchTranscripts(
if (records === null) continue; // failed page — skipped, as before
pagesScanned++;
for (const rec of records) {
+ opts.onRecord?.(rec, ch);
if (
filters &&
!passesFilters(rec, filters, availability?.get(rec.slug))
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -1,4 +1,3 @@
-import { normalizeDateArg } from "./dateArg";
import {
Server,
type Prompt,
@@ -12,7 +11,7 @@ import type { VideoStat } from "yt-dlp-transcript-common/lib/stats";
import { momentUrl, momentBaseUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl";
import type { Platform } from "yt-dlp-transcript-common/lib/platform";
import type { SearchAlias } from "yt-dlp-transcript-common/lib/searchAliases";
-import { isTagId, type PublishedTag } from "yt-dlp-transcript-common/lib/curatedTags";
+import type { PublishedTag } from "yt-dlp-transcript-common/lib/curatedTags";
import { groupPublishedTags } from "yt-dlp-transcript-common/lib/publishedTags";
import {
cuesOfTrack,
@@ -22,12 +21,7 @@ import {
trackLabel,
} from "yt-dlp-transcript-common/lib/captionTracks";
import { windowedTranscript } from "yt-dlp-transcript-common/lib/search/window";
-import {
- VIDEO_STATES,
- isVideoState,
- type VideoState,
-} from "yt-dlp-transcript-common/lib/availability";
-import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery";
+import { VIDEO_STATES } from "yt-dlp-transcript-common/lib/availability";
import {
sortGroups,
resolveChannelGroupId,
@@ -82,8 +76,6 @@ import {
renderFetchClip,
validateFetchClipArgs,
editorFromEnv,
- notFoundNote,
- isVideoId,
NO_EDITOR_TEXT,
type FetchClipDeps,
type PollProgress,
@@ -103,7 +95,8 @@ import {
generationPolicyTool,
planGeneration,
} from "./generation";
-import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { enumerate, parseSearchArgs, strArray, type ParsedSearchArgs } from "./enumerate";
+import { resolveClipTarget } from "./clipTarget";
import {
decodeShareLink,
applyLinkOverrides,
@@ -1144,9 +1137,9 @@ const DEFAULT_FETCH_CLIP_DEPS: FetchClipDeps = {
// from the URL slug (`v1007ay`). Passing the embed id would make the editor
// create a NEW data/vxe1ae/ and fetch rumble.com/vxe1ae. The record's
// `webpageUrl` is the slug URL, so the canonical id comes from it — the same
-// `extractVideoId` the editor names its directories with. On YouTube the two
-// are equal. A video the corpus does not hold goes through as cited, with a
-// note saying what that risks.
+// `extractVideoId` the editor names its directories with (clipTarget.ts). On
+// YouTube the two are equal. A video the corpus does not hold goes through as
+// cited, with a note saying what that risks.
async function handleFetchClip(
source: ShardSource,
resolved: ResolvedSource,
@@ -1161,24 +1154,7 @@ async function handleFetchClip(
if (!v.ok) return errorText(v.error);
const request = v.request;
- let note = "";
- let ctx: { channel?: string; video?: string } = {};
- if ("target" in request) {
- const target = request.target;
- const found = await findVideo(source, target.video, target.channel);
- if (found) {
- const webpageUrl = found.record.webpageUrl;
- const mapped = webpageUrl ? extractVideoId(webpageUrl) : null;
- target.video = mapped && isVideoId(mapped) ? mapped : target.video;
- // The channel the record lives in, which is the editor's directory even
- // when the citation spelled it by name or in another case.
- target.channel = found.ch.slug;
- if (target.kind === "window" && webpageUrl) target.webpageUrl = webpageUrl;
- } else {
- note = `${notFoundNote(target.video, resolved.handle)}\n\n`;
- }
- ctx = { channel: target.channel, video: target.video };
- }
+ const { note, ctx } = await resolveClipTarget(source, resolved.handle, request);
const outcome = await fetchClip(request, deps, { onPoll });
const rendered = renderFetchClip(outcome, ctx);
@@ -1786,36 +1762,11 @@ async function handleEnumerateMatches(
source: ShardSource,
args: Record<string, unknown>,
): Promise<ToolResult> {
- const query = String(args.query ?? "").trim();
- if (!query) return errorText("query is required");
-
- const batchSizeArg =
- typeof args.batch_size === "number" ? Math.floor(args.batch_size) : 8;
- const batchSize = batchSizeArg >= 1 ? batchSizeArg : 8;
-
- const parsed = parseSearchArgs(args);
- if (parsed.error) return errorText(parsed.error);
- const result = await searchTranscripts(source, {
- query,
- filters: parsed.filters,
- exclude: parsed.exclude,
- scopes: parsed.scopes,
- collapseDuplicates: parsed.collapseDuplicates,
- // The singulars stay parsed even though they are no longer advertised.
- channel: typeof args.channel === "string" ? args.channel : undefined,
- channels: strArray(args.channels),
- group: typeof args.group === "string" ? args.group : undefined,
- groups: strArray(args.groups),
- regex: args.regex === true,
- useAliases: args.use_aliases !== false,
- maxPages: typeof args.max_pages === "number" ? args.max_pages : undefined,
- contentTypes: parseContentTypes(args.content_types),
- includeSnippets: false,
- offset: 0,
- // The whole set: searchTranscripts collects up to HARD_VIDEO_CAP and then
- // slices, so asking for every collected match costs nothing extra.
- limit: Number.MAX_SAFE_INTEGER,
- });
+ // The scan is enumerate.ts's, shared with umtool's Research page: this tool
+ // only renders it.
+ const e = await enumerate(source, args);
+ if ("error" in e) return errorText(e.error);
+ const { query, parsed, result, batchSize } = e;
const partial = result.truncated;
const capNote = describeCapCoverage(result);
@@ -1889,150 +1840,6 @@ function describeFiredAliases(fired: SearchAlias[]): string {
return `expanded via alias ${parts.join(", ")}`;
}
-// ─── the shared filter/scope parsing for both search tools ───
-
-// The parsed form of SEARCH_FILTER_ARGS, plus any tokens that were not
-// understood. Unknown tokens are REPORTED rather than dropped silently: a
-// typo'd state ("removed" for "deleted") would otherwise widen the search back
-// to the whole corpus and look like a legitimate empty result.
-type ParsedSearchArgs = {
- filters: SearchFilters | null;
- exclude?: string[];
- scopes?: LayerScope[];
- collapseDuplicates: boolean;
- warnings: string[];
- // Set when an argument must stop the call rather than be dropped (a date
- // bound that is not a date). Callers return it as an error and search nothing.
- error?: string;
-};
-
-const SCOPE_TOKENS: ReadonlyArray<LayerScope> = [
- "transcripts",
- "chat",
- "description",
- "tags",
- "metadata",
- "posts",
-];
-
-function parseSearchArgs(args: Record<string, unknown>): ParsedSearchArgs {
- const warnings: string[] = [];
-
- const rawStates = strArray(args.states);
- let states: VideoState[] | undefined;
- if (rawStates) {
- states = rawStates.filter((s): s is VideoState => isVideoState(s));
- const bad = rawStates.filter((s) => !isVideoState(s));
- if (bad.length > 0) {
- warnings.push(
- `unknown state(s) ignored: ${bad.join(", ")} (valid: ${VIDEO_STATES.join(", ")})`,
- );
- }
- if (states.length === 0) {
- states = undefined;
- warnings.push("no valid states given — the state filter was NOT applied");
- }
- }
-
- const mediaType =
- args.media_type === "video" || args.media_type === "livestream"
- ? args.media_type
- : undefined;
- if (args.media_type !== undefined && mediaType === undefined) {
- warnings.push(`unknown media_type ignored: ${String(args.media_type)}`);
- }
- const age =
- args.age === "all_ages" || args.age === "restricted" ? args.age : undefined;
- if (args.age !== undefined && age === undefined) {
- warnings.push(`unknown age ignored: ${String(args.age)}`);
- }
-
- // A date bound the caller cannot have meant is an ERROR, not a warning: an
- // ignored bound widens the search to the whole corpus and the count reads as
- // the bounded one (see dateArg.ts). The common spellings are normalised.
- const from = normalizeDateArg(args.date_from);
- const to = normalizeDateArg(args.date_to);
- const badDates = [
- ["date_from", args.date_from, from],
- ["date_to", args.date_to, to],
- ]
- .filter(([, , v]) => v === null)
- .map(([name, raw]) => `${name}=${JSON.stringify(raw)}`);
- const error = badDates.length
- ? `not a date: ${badDates.join(", ")} — use YYYYMMDD or YYYY-MM-DD. Nothing was searched.`
- : undefined;
-
- // Curated tags. A malformed id is REPORTED, never silently dropped: dropping
- // the only tag in the list would widen the search back to the whole corpus
- // and read as a legitimate result, which is the same failure a typo'd state
- // would cause.
- const rawTags = strArray(args.tags);
- let tags: string[] | undefined;
- if (rawTags) {
- const normalized = rawTags.map((t) => t.trim().toLowerCase());
- tags = normalized.filter((t) => isTagId(t));
- const bad = normalized.filter((t) => !isTagId(t));
- if (bad.length > 0) {
- warnings.push(
- `not a tag id, ignored: ${bad.join(", ")} (ids are lowercase, ` +
- `[a-z0-9._-]; call list_tags)`,
- );
- }
- if (tags.length === 0) {
- tags = undefined;
- warnings.push("no valid tags given — the tag filter was NOT applied");
- }
- }
-
- const anyFilter =
- states !== undefined ||
- mediaType !== undefined ||
- age !== undefined ||
- Boolean(from) ||
- Boolean(to) ||
- tags !== undefined;
-
- const filters: SearchFilters | null = anyFilter
- ? {
- videos: mediaType === undefined || mediaType === "video",
- livestreams: mediaType === undefined || mediaType === "livestream",
- allAges: age === undefined || age === "all_ages",
- restricted: age === undefined || age === "restricted",
- states: new Set<VideoState>(states ?? VIDEO_STATES),
- ...(from ? { dateFrom: from } : {}),
- ...(to ? { dateTo: to } : {}),
- ...(tags ? { curatedTags: tags } : {}),
- }
- : null;
-
- const rawScopes = strArray(args.scopes);
- let scopes: LayerScope[] | undefined;
- if (rawScopes) {
- scopes = rawScopes.filter((s): s is LayerScope =>
- (SCOPE_TOKENS as readonly string[]).includes(s),
- );
- const bad = rawScopes.filter(
- (s) => !(SCOPE_TOKENS as readonly string[]).includes(s),
- );
- if (bad.length > 0) {
- warnings.push(`unknown scope(s) ignored: ${bad.join(", ")}`);
- }
- if (scopes.length === 0) {
- scopes = undefined;
- warnings.push("no valid scopes given — searching captions + title");
- }
- }
-
- return {
- filters,
- exclude: strArray(args.exclude),
- scopes,
- collapseDuplicates: args.collapse_duplicates !== false,
- warnings,
- ...(error ? { error } : {}),
- };
-}
-
// A human note for the footer describing the filters actually applied, so a
// result can never be read as unfiltered when it wasn't.
function describeSearchFilters(p: ParsedSearchArgs): string {
@@ -2121,16 +1928,6 @@ function describeCoverage(result: SearchResult): string {
);
}
-// Coerce a tool arg to a trimmed non-empty string[] (drops non-strings/blanks).
-function strArray(v: unknown): string[] | undefined {
- if (!Array.isArray(v)) return undefined;
- const out = v
- .filter((x): x is string => typeof x === "string")
- .map((x) => x.trim())
- .filter((x) => x !== "");
- return out.length > 0 ? out : undefined;
-}
-
// A human scope note for the search footer: names the resolved scope (whole
// corpus, a named group + channel count, or an N-channel set) and warns about
// any channel/group token that matched nothing — so a typo is surfaced, not
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
@@ -355,6 +355,9 @@ importers:
yt-dlp-transcript-common:
specifier: workspace:*
version: link:../common
+ yt-dlp-transcript-mcp:
+ specifier: workspace:*
+ version: link:../mcp
devDependencies:
'@playwright/test':
specifier: ^1.59.1
diff --git a/umtool/package.json b/umtool/package.json
@@ -19,7 +19,8 @@
"react-dom": "19.2.4",
"umtool-report-to-video": "workspace:*",
"tailwind-merge": "^3.6.0",
- "yt-dlp-transcript-common": "workspace:*"
+ "yt-dlp-transcript-common": "workspace:*",
+ "yt-dlp-transcript-mcp": "workspace:*"
},
"devDependencies": {
"@playwright/test": "^1.59.1",