// THE CORPUS TOOLS IN PROCESS (release 27 S3, D2) — the MCP's own read tools // for an agent a generation job runs, so it sees exactly what Claude Code // sees, with no MCP process and no stdio. // // A Client and the server (createServer) linked over the SDK's in-memory // transport: the tool handlers are module-private, and going through // `tools/call` keeps the dispatch wrapper (the corpus note on every result, // the error shapes) in the path. // // The rules, in code: // - `source` is FORCED: every call reads the run's corpus. An argument naming // another source is overwritten, and `source` is not in the schemas the // agent sees. // - A READ-ONLY allowlist (CORPUS_TOOL_NAMES): the listing, search, // enumerate, get_* corpus reads, channel coverage, the sources, and the // sweep and ask plans. `notes` is in it for `list` and `read` only (a // reply writes in umtool). `fetch_clip` and `enqueue` cause work in the // editor, `get_job` reads the editor's jobs and `open_link` reads OTHER // corpora by URL: none of them is in it. // // The tools come in the agent loop's AgentTool shape (common/lib/llm, lane A // of release 27); the type is declared here until S5 unifies the import. import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; import type { FetchClipDeps } from "./fetchClip"; import type { ListArgs, RecordingListing } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta"; import type { CountPhrasesArgs, PhraseCounts } from "yt-dlp-transcript-common/lib/report/draft/triage/confirm"; import { countPhrases, listRecordings } from "./enumerate"; import { createServer, TOOLS } from "./server"; import { SourceRegistry } from "./sourceRegistry"; import type { ShardSource } from "./source"; import type { SourceSpec } from "./sources"; export type AgentTool = { name: string; description: string; inputSchema: Record; run(input: any, ctx: { signal?: AbortSignal }): Promise; // eslint-disable-line @typescript-eslint/no-explicit-any }; export const CORPUS_TOOL_NAMES = [ "list_channels", "list_tags", "list_reports", "get_report", "search_transcripts", "enumerate_matches", "get_transcript", "get_post", "get_thread", "get_transcripts", "get_video_metadata", "channel_coverage", "notes", "list_sources", "resolve_source", "sweep_plan", "ask_plan", ] as const; export type CorpusToolName = (typeof CORPUS_TOOL_NAMES)[number]; // What `notes` may do in process. export const NOTES_ACTIONS = ["list", "read"] as const; export class CorpusToolError extends Error {} export type CorpusTools = { // The source handle every call reads. source: string; tools: AgentTool[]; // Call one allowed tool; its text. A tool error is thrown as a // CorpusToolError carrying the tool's own words. call(name: string, args?: Record): Promise; // R6.1: every recording in a scope, uncapped (the build's manifests), as // data — what a triage's tier 0 lists the scope with. Not an agent tool. listRecordings(args: ListArgs): Promise; // R6.3: phrases counted over a scope, uncapped, in one scan (a learned // spelling's confirmation). Not an agent tool. countPhrases(args: CountPhrasesArgs): Promise; close(): Promise; }; export type CorpusToolsOptions = { // The corpus: a handle (`local:`, `remote:`, `hub:`), a // spec, or a built ShardSource (tests). source: string | SourceSpec | ShardSource; // Only these of CORPUS_TOOL_NAMES (default: all of them). only?: readonly CorpusToolName[]; // The editor and umtool the editor-backed reads (channel_coverage, notes) // reach: env, fetch, clock. Default: the process's. editorDeps?: Partial; }; function specOf(handle: string): SourceSpec { const m = /^(local|remote|hub):(.+)$/s.exec(handle.trim()); if (!m) throw new Error(`createCorpusTools: "${handle}" is not a source handle (local:, remote:, hub:)`); const rest = m[2]!.trim(); if (m[1] === "local") return { kind: "local", dir: rest }; if (m[1] === "remote") return { kind: "remote", url: rest.replace(/\/+$/, "") }; const hash = rest.indexOf("#"); if (hash < 0) return { kind: "hub", url: rest.replace(/\/+$/, "") }; const sites = rest .slice(hash + 1) .split(",") .map((s) => s.trim()) .filter(Boolean); return { kind: "hub", url: rest.slice(0, hash).replace(/\/+$/, ""), ...(sites.length ? { sites } : {}) }; } const isSource = (s: unknown): s is ShardSource => typeof s === "object" && s !== null && typeof (s as ShardSource).listChannels === "function"; type JsonSchema = { properties?: Record; required?: string[] } & Record; // A tool's schema as the agent sees it: no `source`; `notes` list/read only. function agentSchema(name: string, schema: unknown): Record { const s = structuredClone(schema) as JsonSchema; if (s.properties) delete s.properties.source; if (Array.isArray(s.required)) { s.required = s.required.filter((r) => r !== "source"); if (s.required.length === 0) delete s.required; } if (name === "notes" && s.properties) { s.properties.action = { type: "string", enum: [...NOTES_ACTIONS], description: 'Default "list".' }; for (const k of ["note_id", "text", "resolve"]) delete s.properties[k]; } return s; } const NOTES_DESCRIPTION = "The operator's notes in umtool on articles and report-video projects (read only here). action " + '"list": every open note, grouped by target. action "read" with target (as list names it: ' + '"sites//" for an article, else a project id): each note with its anchor resolved ' + "(status: open, resolved or all)."; export async function createCorpusTools(opts: CorpusToolsOptions): Promise { let registry: SourceRegistry; if (isSource(opts.source)) registry = SourceRegistry.forSource(opts.source); else registry = new SourceRegistry(typeof opts.source === "string" ? specOf(opts.source) : opts.source); const source = registry.defaultHandle; const allowed = new Set(opts.only ?? CORPUS_TOOL_NAMES); for (const n of allowed) { if (!(CORPUS_TOOL_NAMES as readonly string[]).includes(n)) { throw new Error(`createCorpusTools: "${n}" is not a read-only corpus tool`); } } const server = createServer(registry, opts.editorDeps ? { fetchClipDeps: opts.editorDeps } : {}); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "archilyzer-generation", version: "0" }, { capabilities: {} }); await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); const call = async (name: string, args: Record = {}, signal?: AbortSignal): Promise => { if (!allowed.has(name)) { throw new CorpusToolError(`${name}: not one of this run's read-only corpus tools (${[...allowed].join(", ")})`); } const a: Record = { ...(args ?? {}), source }; if (name === "notes") { const action = a.action ?? "list"; if (!(NOTES_ACTIONS as readonly unknown[]).includes(action)) { throw new CorpusToolError(`notes: ${NOTES_ACTIONS.join(" and ")} only here (a reply is the operator's)`); } a.action = action; for (const k of ["note_id", "text", "resolve"]) delete a[k]; } signal?.throwIfAborted(); const res = (await client.callTool({ name, arguments: a }, signal ? { signal } : undefined)) as { content?: { type: string; text?: string }[]; isError?: boolean; }; const text = (res.content ?? []) .filter((c) => c.type === "text") .map((c) => c.text ?? "") .join("\n"); if (res.isError) throw new CorpusToolError(text); return text; }; const tools: AgentTool[] = TOOLS.filter((t) => allowed.has(t.name)).map((t) => ({ name: t.name, description: t.name === "notes" ? NOTES_DESCRIPTION : (t.description ?? ""), inputSchema: agentSchema(t.name, t.inputSchema), run: (input: Record, ctx: { signal?: AbortSignal }) => call(t.name, input, ctx?.signal), })); return { source, tools, call: (name, args) => call(name, args), listRecordings: async (args) => listRecordings((await registry.resolve()).source, args), countPhrases: async (args) => countPhrases((await registry.resolve()).source, args), close: async () => { await client.close(); await server.close(); }, }; }