@dpantani/tdmcp 0.1.0 → 0.2.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/agent.ts","../../src/knowledge/index.ts","../../src/utils/logger.ts","../../src/utils/paths.ts","../../src/knowledge/normalize.ts","../../src/recipes/loader.ts","../../src/recipes/schema.ts","../../src/td-client/types.ts","../../src/td-client/validators.ts","../../src/td-client/touchDesignerClient.ts","../../src/utils/config.ts","../../src/server/connectionManager.ts","../../src/server/context.ts","../../src/tools/layer3/compareTdNodes.ts","../../src/tools/result.ts","../../src/tools/layer3/createTdNode.ts","../../src/tools/layer3/deleteTdNode.ts","../../src/tools/layer3/execNodeMethod.ts","../../src/tools/layer3/executePythonScript.ts","../../src/tools/layer3/findTdNodes.ts","../../src/tools/layer3/nodeMatch.ts","../../src/tools/layer3/getModuleHelp.ts","../../src/tools/layer3/getTdClassDetails.ts","../../src/tools/layer3/getTdClasses.ts","../../src/tools/layer3/getTdInfo.ts","../../src/tools/layer3/getTdNodeErrors.ts","../../src/tools/layer3/getTdNodeParameters.ts","../../src/tools/layer3/getTdNodes.ts","../../src/tools/layer3/getTdPerformance.ts","../../src/feedback/performanceMonitor.ts","../../src/tools/layer3/getTdTopology.ts","../../src/feedback/networkVerifier.ts","../../src/tools/layer3/snapshotTdGraph.ts","../../src/tools/layer3/summarizeTdErrors.ts","../../src/tools/layer3/updateTdNodeParameters.ts"],"sourcesContent":["import { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { buildToolContext } from \"../server/context.js\";\nimport { compareTdNodesImpl, compareTdNodesSchema } from \"../tools/layer3/compareTdNodes.js\";\nimport { createTdNodeImpl, createTdNodeSchema } from \"../tools/layer3/createTdNode.js\";\nimport { deleteTdNodeImpl, deleteTdNodeSchema } from \"../tools/layer3/deleteTdNode.js\";\nimport { execNodeMethodImpl, execNodeMethodSchema } from \"../tools/layer3/execNodeMethod.js\";\nimport {\n executePythonScriptImpl,\n executePythonScriptSchema,\n} from \"../tools/layer3/executePythonScript.js\";\nimport { findTdNodesImpl, findTdNodesSchema } from \"../tools/layer3/findTdNodes.js\";\nimport { getModuleHelpImpl, getModuleHelpSchema } from \"../tools/layer3/getModuleHelp.js\";\nimport {\n getTdClassDetailsImpl,\n getTdClassDetailsSchema,\n} from \"../tools/layer3/getTdClassDetails.js\";\nimport { getTdClassesImpl, getTdClassesSchema } from \"../tools/layer3/getTdClasses.js\";\nimport { getTdInfoImpl } from \"../tools/layer3/getTdInfo.js\";\nimport { getTdNodeErrorsImpl, getTdNodeErrorsSchema } from \"../tools/layer3/getTdNodeErrors.js\";\nimport {\n getTdNodeParametersImpl,\n getTdNodeParametersSchema,\n} from \"../tools/layer3/getTdNodeParameters.js\";\nimport { getTdNodesImpl, getTdNodesSchema } from \"../tools/layer3/getTdNodes.js\";\nimport { getTdPerformanceImpl, getTdPerformanceSchema } from \"../tools/layer3/getTdPerformance.js\";\nimport { getTdTopologyImpl, getTdTopologySchema } from \"../tools/layer3/getTdTopology.js\";\nimport { snapshotTdGraphImpl, snapshotTdGraphSchema } from \"../tools/layer3/snapshotTdGraph.js\";\nimport {\n summarizeTdErrorsImpl,\n summarizeTdErrorsSchema,\n} from \"../tools/layer3/summarizeTdErrors.js\";\nimport {\n updateTdNodeParametersImpl,\n updateTdNodeParametersSchema,\n} from \"../tools/layer3/updateTdNodeParameters.js\";\nimport type { ToolContext } from \"../tools/types.js\";\nimport { loadConfig } from \"../utils/config.js\";\nimport { silentLogger } from \"../utils/logger.js\";\n\n// biome-ignore lint/suspicious/noExplicitAny: args are validated by each command's zod schema before use.\ntype Runner = (ctx: ToolContext, args: any) => CallToolResult | Promise<CallToolResult>;\n\ninterface Command {\n schema: z.ZodTypeAny;\n run: Runner;\n summary: string;\n mutates: boolean;\n unsafe: boolean;\n}\n\nconst r = (\n schema: z.ZodTypeAny,\n run: Runner,\n summary: string,\n opts: { mutates?: boolean; unsafe?: boolean } = {},\n): Command => ({ schema, run, summary, mutates: !!opts.mutates, unsafe: !!opts.unsafe });\n\n/** Static command tree — each entry maps 1:1 onto an existing MCP tool handler. */\nconst COMMANDS: Record<string, Command> = {\n info: r(z.object({}), (ctx) => getTdInfoImpl(ctx), \"Health check + TD/bridge info.\"),\n \"nodes list\": r(\n getTdNodesSchema,\n getTdNodesImpl,\n \"List a COMP's child nodes (summary by default).\",\n ),\n \"nodes find\": r(findTdNodesSchema, findTdNodesImpl, \"Search nodes by name pattern and/or type.\"),\n \"nodes get\": r(getTdNodeParametersSchema, getTdNodeParametersImpl, \"Read a node's parameters.\"),\n \"nodes errors\": r(getTdNodeErrorsSchema, getTdNodeErrorsImpl, \"Check a node/network for errors.\"),\n \"nodes compare\": r(compareTdNodesSchema, compareTdNodesImpl, \"Diff two nodes' parameters.\"),\n \"nodes snapshot\": r(snapshotTdGraphSchema, snapshotTdGraphImpl, \"Capture a network snapshot.\"),\n \"nodes topology\": r(getTdTopologySchema, getTdTopologyImpl, \"Map nodes + connections.\"),\n \"nodes performance\": r(getTdPerformanceSchema, getTdPerformanceImpl, \"Report cook times.\"),\n \"nodes update\": r(\n updateTdNodeParametersSchema,\n updateTdNodeParametersImpl,\n \"Set node parameters.\",\n { mutates: true },\n ),\n \"nodes create\": r(createTdNodeSchema, createTdNodeImpl, \"Create an operator.\", { mutates: true }),\n \"nodes delete\": r(deleteTdNodeSchema, deleteTdNodeImpl, \"Delete a node.\", { mutates: true }),\n \"errors summarize\": r(\n summarizeTdErrorsSchema,\n summarizeTdErrorsImpl,\n \"Cluster network errors by cause.\",\n ),\n \"classes list\": r(getTdClassesSchema, getTdClassesImpl, \"List TD Python API classes (offline).\"),\n \"classes get\": r(\n getTdClassDetailsSchema,\n getTdClassDetailsImpl,\n \"Get one Python class (offline).\",\n ),\n \"module help\": r(\n getModuleHelpSchema,\n getModuleHelpImpl,\n \"Human-readable help for a class (offline).\",\n ),\n \"exec python\": r(\n executePythonScriptSchema,\n executePythonScriptImpl,\n \"Escape hatch: run arbitrary Python in TD.\",\n { mutates: true, unsafe: true },\n ),\n \"exec node-method\": r(\n execNodeMethodSchema,\n execNodeMethodImpl,\n \"Escape hatch: call a Python method on a node.\",\n { mutates: true, unsafe: true },\n ),\n};\n\nexport interface CliResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\nfunction textOf(result: CallToolResult): string {\n return result.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n}\n\n/** Prefer the structured channel; fall back to a JSON code-fence, then to the raw text. */\nfunction extractData(result: CallToolResult): unknown {\n if (result.structuredContent !== undefined) return result.structuredContent;\n const text = textOf(result);\n const fence = text.match(/```json\\n([\\s\\S]*?)\\n```/);\n if (fence) {\n try {\n return JSON.parse(fence[1] as string);\n } catch {\n // fall through\n }\n }\n return { message: text };\n}\n\nfunction firstArray(data: unknown): unknown[] | null {\n if (Array.isArray(data)) return data;\n if (data && typeof data === \"object\") {\n for (const value of Object.values(data)) if (Array.isArray(value)) return value;\n }\n return null;\n}\n\nfunction resolveCommand(positionals: string[]): { key: string; cmd: Command } | undefined {\n const key2 = positionals.slice(0, 2).join(\" \");\n if (COMMANDS[key2]) return { key: key2, cmd: COMMANDS[key2] };\n const key1 = positionals[0] ?? \"\";\n if (COMMANDS[key1]) return { key: key1, cmd: COMMANDS[key1] };\n return undefined;\n}\n\nfunction usage(): string {\n const lines = [\"tdmcp-agent — drive TouchDesigner from a shell (machine-readable output).\", \"\"];\n lines.push(\"Usage: tdmcp-agent <command> [--params '<json>'] [--json '<json>'] [flags]\", \"\");\n lines.push(\"Flags:\");\n lines.push(\n \" --params <json> Arguments object (validated against the command's input schema).\",\n );\n lines.push(\" --json <json> Merged into --params (e.g. for request bodies).\");\n lines.push(\" --output <fmt> json (default) | ndjson | text.\");\n lines.push(\" --dry-run Validate and print the intended call without executing.\");\n lines.push(\" --allow-unsafe Required for `exec` escape-hatch commands.\");\n lines.push(\" -h, --help Show this help.\", \"\");\n lines.push(\"Commands:\");\n for (const [key, cmd] of Object.entries(COMMANDS)) {\n const tags = [cmd.mutates ? \"mutates\" : \"\", cmd.unsafe ? \"unsafe\" : \"\"]\n .filter(Boolean)\n .join(\",\");\n lines.push(` ${key.padEnd(20)} ${cmd.summary}${tags ? ` [${tags}]` : \"\"}`);\n }\n lines.push(\" schema <command> Print a command's JSON Schema and metadata.\");\n return lines.join(\"\\n\");\n}\n\nexport interface RunCliOptions {\n /** Inject a context (used by tests); production builds one from env config. */\n makeCtx?: () => ToolContext;\n}\n\nfunction parseCliArgs(argv: string[]) {\n return parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n params: { type: \"string\" },\n json: { type: \"string\" },\n output: { type: \"string\", default: \"json\" },\n \"dry-run\": { type: \"boolean\", default: false },\n \"allow-unsafe\": { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n });\n}\n\nexport async function runCli(argv: string[], opts: RunCliOptions = {}): Promise<CliResult> {\n let parsed: ReturnType<typeof parseCliArgs>;\n try {\n parsed = parseCliArgs(argv);\n } catch (err) {\n return { stdout: \"\", stderr: `${(err as Error).message}\\n`, code: 2 };\n }\n\n const { values, positionals } = parsed;\n if (values.help || positionals.length === 0) {\n return { stdout: `${usage()}\\n`, stderr: \"\", code: 0 };\n }\n\n // `schema <command>` — emit the input contract without touching TD.\n if (positionals[0] === \"schema\") {\n const target = positionals.slice(1).join(\" \");\n const cmd = COMMANDS[target];\n if (!cmd) return { stdout: \"\", stderr: `Unknown command for schema: \"${target}\".\\n`, code: 2 };\n const doc = {\n command: target,\n summary: cmd.summary,\n mutates: cmd.mutates,\n unsafe: cmd.unsafe,\n input: z.toJSONSchema(cmd.schema),\n };\n return { stdout: `${JSON.stringify(doc, null, 2)}\\n`, stderr: \"\", code: 0 };\n }\n\n const resolved = resolveCommand(positionals);\n if (!resolved) {\n return {\n stdout: \"\",\n stderr: `Unknown command: \"${positionals.join(\" \")}\". Run with --help.\\n`,\n code: 2,\n };\n }\n const { key, cmd } = resolved;\n\n const raw: Record<string, unknown> = {};\n try {\n if (typeof values.params === \"string\") Object.assign(raw, JSON.parse(values.params));\n if (typeof values.json === \"string\") Object.assign(raw, JSON.parse(values.json));\n } catch (err) {\n return {\n stdout: \"\",\n stderr: `Invalid JSON in --params/--json: ${(err as Error).message}\\n`,\n code: 2,\n };\n }\n\n const args = cmd.schema.safeParse(raw);\n if (!args.success) {\n return {\n stdout: \"\",\n stderr: `Invalid arguments for \"${key}\": ${args.error.message}\\n`,\n code: 2,\n };\n }\n\n if (values[\"dry-run\"]) {\n const doc = {\n dryRun: true,\n command: key,\n mutates: cmd.mutates,\n unsafe: cmd.unsafe,\n args: args.data,\n };\n return { stdout: `${JSON.stringify(doc, null, 2)}\\n`, stderr: \"\", code: 0 };\n }\n\n const ctx = opts.makeCtx\n ? opts.makeCtx()\n : buildToolContext(loadConfig(), { logger: silentLogger });\n\n if (cmd.unsafe) {\n if (ctx.allowRawPython === false) {\n return { stdout: \"\", stderr: `\"${key}\" is disabled (TDMCP_RAW_PYTHON=off).\\n`, code: 2 };\n }\n if (!values[\"allow-unsafe\"]) {\n return {\n stdout: \"\",\n stderr: `\"${key}\" is an escape hatch. Re-run with --allow-unsafe to execute.\\n`,\n code: 2,\n };\n }\n }\n\n const result = await cmd.run(ctx, args.data);\n const summary = textOf(result).split(\"\\n\")[0] ?? \"\";\n if (result.isError) return { stdout: \"\", stderr: `${textOf(result)}\\n`, code: 1 };\n\n const output = String(values.output);\n const data = extractData(result);\n if (output === \"text\") return { stdout: `${textOf(result)}\\n`, stderr: \"\", code: 0 };\n if (output === \"ndjson\") {\n const arr = firstArray(data);\n const body = arr ? arr.map((item) => JSON.stringify(item)).join(\"\\n\") : JSON.stringify(data);\n return { stdout: `${body}\\n`, stderr: summary ? `${summary}\\n` : \"\", code: 0 };\n }\n return {\n stdout: `${JSON.stringify(data, null, 2)}\\n`,\n stderr: summary ? `${summary}\\n` : \"\",\n code: 0,\n };\n}\n\nasync function main(): Promise<void> {\n const result = await runCli(process.argv.slice(2));\n if (result.stdout) process.stdout.write(result.stdout);\n if (result.stderr) process.stderr.write(result.stderr);\n process.exitCode = result.code;\n}\n\nconst invokedDirectly =\n process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;\nif (invokedDirectly) void main();\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { type Logger, silentLogger } from \"../utils/logger.js\";\nimport { bottobotPackageDir, knowledgeDataDir } from \"../utils/paths.js\";\nimport {\n compactKey,\n normalizeGlsl,\n normalizePatterns,\n slugify,\n toOperatorSummary,\n toPythonSummary,\n toTutorialSummary,\n} from \"./normalize.js\";\nimport type {\n GlslSummary,\n GlslTechnique,\n KnowledgeStats,\n OperatorDoc,\n OperatorSummary,\n Pattern,\n PatternSummary,\n PythonClass,\n PythonClassSummary,\n Tutorial,\n TutorialSummary,\n} from \"./types.js\";\n\nexport interface KnowledgeBaseOptions {\n dataDir?: string;\n logger?: Logger;\n}\n\ninterface ResolvedSource {\n kind: \"local\" | \"bottobot\" | \"empty\";\n operatorsDir: string;\n operatorsIndex?: string;\n pythonDir: string;\n tutorialsDir: string;\n patternsFile: string;\n glslFile: string;\n}\n\nconst EMPTY_SOURCE: ResolvedSource = {\n kind: \"empty\",\n operatorsDir: \"\",\n pythonDir: \"\",\n tutorialsDir: \"\",\n patternsFile: \"\",\n glslFile: \"\",\n};\n\n/**\n * Read-only accessor over the embedded TouchDesigner knowledge base. Prefers the\n * imported local data directory; falls back to reading directly from an installed\n * `@bottobot/td-mcp`; otherwise degrades to empty results (never throws on lookup).\n */\nexport class KnowledgeBase {\n private readonly logger: Logger;\n private readonly source: ResolvedSource;\n\n private opIndexCache?: OperatorSummary[];\n private opLookupCache?: Map<string, string>;\n private readonly opDocCache = new Map<string, OperatorDoc | null>();\n private pyIndexCache?: PythonClassSummary[];\n private pyLookupCache?: Map<string, string>;\n private readonly pyDocCache = new Map<string, PythonClass | null>();\n private tutIndexCache?: TutorialSummary[];\n private tutLookupCache?: Map<string, string>;\n private readonly tutDocCache = new Map<string, Tutorial | null>();\n private patternsCache?: Pattern[];\n private glslCache?: GlslTechnique[];\n\n constructor(options: KnowledgeBaseOptions = {}) {\n this.logger = options.logger ?? silentLogger;\n this.source = KnowledgeBase.resolveSource(options.dataDir ?? knowledgeDataDir());\n this.logger.debug(\"knowledge source resolved\", { kind: this.source.kind });\n }\n\n private static resolveSource(localDir: string): ResolvedSource {\n if (existsSync(join(localDir, \"operators\"))) {\n return {\n kind: \"local\",\n operatorsDir: join(localDir, \"operators\"),\n operatorsIndex: join(localDir, \"operators\", \"index.json\"),\n pythonDir: join(localDir, \"python-api\"),\n tutorialsDir: join(localDir, \"tutorials\"),\n patternsFile: join(localDir, \"patterns.json\"),\n glslFile: join(localDir, \"glsl.json\"),\n };\n }\n const bb = bottobotPackageDir();\n if (bb) {\n return {\n kind: \"bottobot\",\n operatorsDir: join(bb, \"wiki/data/processed\"),\n pythonDir: join(bb, \"wiki/data/python-api\"),\n tutorialsDir: join(bb, \"wiki/data/tutorials\"),\n patternsFile: join(bb, \"data/patterns.json\"),\n glslFile: join(bb, \"wiki/data/experimental/glsl.json\"),\n };\n }\n return EMPTY_SOURCE;\n }\n\n private readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch (err) {\n this.logger.debug(\"knowledge readJson failed\", { path, error: String(err) });\n return undefined;\n }\n }\n\n private listJsonFiles(dir: string): string[] {\n if (!dir || !existsSync(dir)) return [];\n try {\n return readdirSync(dir).filter((f) => f.endsWith(\".json\") && f !== \"index.json\");\n } catch {\n return [];\n }\n }\n\n // ---- Operators -----------------------------------------------------------\n\n private operatorIndex(): OperatorSummary[] {\n if (this.opIndexCache) return this.opIndexCache;\n if (this.source.kind === \"empty\") {\n this.opIndexCache = [];\n return this.opIndexCache;\n }\n if (this.source.operatorsIndex && existsSync(this.source.operatorsIndex)) {\n const data = this.readJson(this.source.operatorsIndex);\n if (Array.isArray(data)) {\n this.opIndexCache = data as OperatorSummary[];\n return this.opIndexCache;\n }\n }\n const summaries: OperatorSummary[] = [];\n for (const file of this.listJsonFiles(this.source.operatorsDir)) {\n const doc = this.readJson(join(this.source.operatorsDir, file)) as OperatorDoc | undefined;\n if (doc?.name) summaries.push(toOperatorSummary(file.replace(/\\.json$/, \"\"), doc));\n }\n this.opIndexCache = summaries;\n return this.opIndexCache;\n }\n\n private operatorLookup(): Map<string, string> {\n if (this.opLookupCache) return this.opLookupCache;\n const map = new Map<string, string>();\n for (const summary of this.operatorIndex()) {\n map.set(compactKey(summary.slug), summary.slug);\n map.set(compactKey(summary.name), summary.slug);\n map.set(compactKey(summary.displayName), summary.slug);\n }\n this.opLookupCache = map;\n return map;\n }\n\n listOperatorCategories(): string[] {\n const set = new Set<string>();\n for (const summary of this.operatorIndex()) set.add(summary.category);\n return [...set].sort();\n }\n\n listOperators(category?: string): OperatorSummary[] {\n const all = this.operatorIndex();\n if (!category) return all;\n const wanted = compactKey(category);\n return all.filter((s) => compactKey(s.category) === wanted);\n }\n\n getOperator(nameOrSlug: string): OperatorDoc | undefined {\n if (this.source.kind === \"empty\") return undefined;\n const slug = this.operatorLookup().get(compactKey(nameOrSlug)) ?? slugify(nameOrSlug);\n const cached = this.opDocCache.get(slug);\n if (cached !== undefined) return cached ?? undefined;\n const file = join(this.source.operatorsDir, `${slug}.json`);\n const doc = existsSync(file) ? (this.readJson(file) as OperatorDoc | undefined) : undefined;\n this.opDocCache.set(slug, doc ?? null);\n return doc;\n }\n\n /** Soft existence check (by operator type, display name, or slug). */\n operatorExists(typeOrName: string): boolean {\n return this.operatorLookup().has(compactKey(typeOrName));\n }\n\n searchOperators(query: string, limit = 25): OperatorSummary[] {\n const q = query.trim().toLowerCase();\n if (!q) return [];\n const terms = q.split(/\\s+/);\n const scored: Array<{ summary: OperatorSummary; score: number }> = [];\n for (const summary of this.operatorIndex()) {\n const haystack =\n `${summary.name} ${summary.displayName} ${summary.summary} ${summary.keywords.join(\" \")}`.toLowerCase();\n let score = 0;\n for (const term of terms) {\n if (haystack.includes(term)) score += 1;\n if (summary.name.toLowerCase().includes(term)) score += 1;\n }\n if (score > 0) scored.push({ summary, score });\n }\n scored.sort((a, b) => b.score - a.score);\n return scored.slice(0, limit).map((s) => s.summary);\n }\n\n // ---- Python API ----------------------------------------------------------\n\n private pythonIndex(): PythonClassSummary[] {\n if (this.pyIndexCache) return this.pyIndexCache;\n if (this.source.kind === \"empty\") {\n this.pyIndexCache = [];\n return this.pyIndexCache;\n }\n const indexPath = join(this.source.pythonDir, \"index.json\");\n if (existsSync(indexPath)) {\n const data = this.readJson(indexPath);\n if (Array.isArray(data)) {\n this.pyIndexCache = data as PythonClassSummary[];\n return this.pyIndexCache;\n }\n }\n const summaries: PythonClassSummary[] = [];\n for (const file of this.listJsonFiles(this.source.pythonDir)) {\n const cls = this.readJson(join(this.source.pythonDir, file)) as PythonClass | undefined;\n if (cls?.className) summaries.push(toPythonSummary(cls));\n }\n this.pyIndexCache = summaries;\n return this.pyIndexCache;\n }\n\n private pythonLookup(): Map<string, string> {\n if (this.pyLookupCache) return this.pyLookupCache;\n const map = new Map<string, string>();\n for (const summary of this.pythonIndex()) {\n map.set(compactKey(summary.className), summary.className);\n map.set(compactKey(summary.displayName), summary.className);\n }\n this.pyLookupCache = map;\n return map;\n }\n\n listPythonClasses(): PythonClassSummary[] {\n return this.pythonIndex();\n }\n\n getPythonClass(name: string): PythonClass | undefined {\n if (this.source.kind === \"empty\") return undefined;\n const className = this.pythonLookup().get(compactKey(name)) ?? name;\n const cached = this.pyDocCache.get(className);\n if (cached !== undefined) return cached ?? undefined;\n const file = join(this.source.pythonDir, `${className}.json`);\n const cls = existsSync(file) ? (this.readJson(file) as PythonClass | undefined) : undefined;\n this.pyDocCache.set(className, cls ?? null);\n return cls;\n }\n\n // ---- Patterns ------------------------------------------------------------\n\n private patterns(): Pattern[] {\n if (this.patternsCache) return this.patternsCache;\n if (this.source.kind === \"empty\") {\n this.patternsCache = [];\n return this.patternsCache;\n }\n const data = this.readJson(this.source.patternsFile);\n if (Array.isArray(data) && data.length > 0 && typeof (data[0] as Pattern).id === \"string\") {\n this.patternsCache = data as Pattern[];\n } else {\n this.patternsCache = normalizePatterns(data);\n }\n return this.patternsCache;\n }\n\n listPatterns(): PatternSummary[] {\n return this.patterns().map((p) => ({\n id: p.id,\n name: p.name,\n category: p.category ?? \"Unknown\",\n description: p.description ?? \"\",\n }));\n }\n\n getPattern(name: string): Pattern | undefined {\n const key = compactKey(name);\n return this.patterns().find((p) => compactKey(p.id) === key || compactKey(p.name) === key);\n }\n\n // ---- GLSL ----------------------------------------------------------------\n\n private glsl(): GlslTechnique[] {\n if (this.glslCache) return this.glslCache;\n if (this.source.kind === \"empty\") {\n this.glslCache = [];\n return this.glslCache;\n }\n const data = this.readJson(this.source.glslFile);\n this.glslCache = Array.isArray(data) ? (data as GlslTechnique[]) : normalizeGlsl(data);\n return this.glslCache;\n }\n\n listGlslPatterns(): GlslSummary[] {\n return this.glsl().map((g) => ({\n id: g.id,\n name: g.name,\n description: g.description ?? \"\",\n difficulty: g.difficulty ?? \"unknown\",\n }));\n }\n\n getGlslPattern(name: string): GlslTechnique | undefined {\n const key = compactKey(name);\n return this.glsl().find((g) => compactKey(g.id) === key || compactKey(g.name) === key);\n }\n\n // ---- Tutorials -----------------------------------------------------------\n\n private tutorialIndex(): TutorialSummary[] {\n if (this.tutIndexCache) return this.tutIndexCache;\n if (this.source.kind === \"empty\") {\n this.tutIndexCache = [];\n return this.tutIndexCache;\n }\n const indexPath = join(this.source.tutorialsDir, \"index.json\");\n if (existsSync(indexPath)) {\n const data = this.readJson(indexPath);\n if (Array.isArray(data)) {\n this.tutIndexCache = data as TutorialSummary[];\n return this.tutIndexCache;\n }\n }\n const summaries: TutorialSummary[] = [];\n for (const file of this.listJsonFiles(this.source.tutorialsDir)) {\n const tut = this.readJson(join(this.source.tutorialsDir, file)) as Tutorial | undefined;\n if (tut?.id || tut?.name) {\n const normalized: Tutorial = {\n ...tut,\n id: tut.id ?? file.replace(/\\.json$/, \"\"),\n name: tut.name ?? file,\n };\n summaries.push(toTutorialSummary(normalized));\n }\n }\n this.tutIndexCache = summaries;\n return this.tutIndexCache;\n }\n\n private tutorialLookup(): Map<string, string> {\n if (this.tutLookupCache) return this.tutLookupCache;\n const map = new Map<string, string>();\n for (const file of this.listJsonFiles(this.source.tutorialsDir)) {\n const slug = file.replace(/\\.json$/, \"\");\n map.set(compactKey(slug), slug);\n }\n for (const summary of this.tutorialIndex()) {\n map.set(compactKey(summary.id), summary.id);\n map.set(compactKey(summary.name), summary.id);\n }\n this.tutLookupCache = map;\n return map;\n }\n\n listTutorials(): TutorialSummary[] {\n return this.tutorialIndex();\n }\n\n getTutorial(name: string): Tutorial | undefined {\n if (this.source.kind === \"empty\") return undefined;\n const slug = this.tutorialLookup().get(compactKey(name)) ?? slugify(name);\n const cached = this.tutDocCache.get(slug);\n if (cached !== undefined) return cached ?? undefined;\n const file = join(this.source.tutorialsDir, `${slug}.json`);\n const tut = existsSync(file) ? (this.readJson(file) as Tutorial | undefined) : undefined;\n this.tutDocCache.set(slug, tut ?? null);\n return tut;\n }\n\n // ---- Meta ----------------------------------------------------------------\n\n get sourceKind(): KnowledgeStats[\"source\"] {\n return this.source.kind;\n }\n\n stats(): KnowledgeStats {\n return {\n source: this.source.kind,\n operators: this.operatorIndex().length,\n pythonClasses: this.pythonIndex().length,\n patterns: this.patterns().length,\n glsl: this.glsl().length,\n tutorials: this.tutorialIndex().length,\n };\n }\n}\n","export type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\nconst LEVELS: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n silent: 99,\n};\n\nexport interface Logger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Creates a leveled logger. All output goes to **stderr** so that stdout stays\n * reserved for the MCP stdio protocol stream.\n */\nexport function createLogger(level: LogLevel = \"info\"): Logger {\n const threshold = LEVELS[level];\n\n const emit = (\n lvl: Exclude<LogLevel, \"silent\">,\n message: string,\n meta?: Record<string, unknown>,\n ) => {\n if (LEVELS[lvl] < threshold) return;\n const stamp = new Date().toISOString();\n const suffix = meta && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : \"\";\n process.stderr.write(`[tdmcp] ${stamp} ${lvl.toUpperCase()} ${message}${suffix}\\n`);\n };\n\n return {\n debug: (message, meta) => emit(\"debug\", message, meta),\n info: (message, meta) => emit(\"info\", message, meta),\n warn: (message, meta) => emit(\"warn\", message, meta),\n error: (message, meta) => emit(\"error\", message, meta),\n };\n}\n\n/** A logger that discards everything — handy for tests. */\nexport const silentLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n","import { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst moduleDir = dirname(fileURLToPath(import.meta.url));\n\nfunction firstExisting(candidates: string[], fallback: string): string {\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate;\n }\n return fallback;\n}\n\n/**\n * Directory holding the imported knowledge base JSON.\n * - dev (tsx): `<root>/src/knowledge/data`\n * - build (node): `<root>/dist/knowledge/data` (copied by `copy-assets.mjs`)\n */\nexport function knowledgeDataDir(): string {\n return firstExisting(\n [resolve(moduleDir, \"../knowledge/data\"), resolve(moduleDir, \"knowledge/data\")],\n resolve(moduleDir, \"../knowledge/data\"),\n );\n}\n\n/**\n * Directory holding recipe JSON files.\n * - dev: `<root>/recipes`\n * - build: `<root>/dist/recipes`\n */\nexport function recipesDir(): string {\n return firstExisting(\n [resolve(moduleDir, \"../../recipes\"), resolve(moduleDir, \"recipes\")],\n resolve(moduleDir, \"../../recipes\"),\n );\n}\n\n/**\n * Directory holding the TouchDesigner-side Python bridge modules that ship with\n * the package (the `td/modules` tree). Used by the `install-bridge` CLI to copy\n * them somewhere TouchDesigner can import from.\n * - dev (tsx): `<root>/td/modules`\n * - installed package (node): `<pkgroot>/td/modules`\n */\nexport function bridgeModulesDir(): string {\n return firstExisting(\n [resolve(moduleDir, \"../td/modules\"), resolve(moduleDir, \"../../td/modules\")],\n resolve(moduleDir, \"../td/modules\"),\n );\n}\n\n/**\n * Resolves the installed `@bottobot/td-mcp` package root (the source of operator\n * data), if present. Used as a fallback when local knowledge data is missing.\n */\nexport function bottobotPackageDir(): string | undefined {\n const candidates = [\n resolve(moduleDir, \"../../node_modules/@bottobot/td-mcp\"),\n resolve(moduleDir, \"../node_modules/@bottobot/td-mcp\"),\n resolve(process.cwd(), \"node_modules/@bottobot/td-mcp\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(resolve(candidate, \"wiki/data/processed\"))) return candidate;\n }\n return undefined;\n}\n","import type {\n GlslTechnique,\n OperatorDoc,\n OperatorSummary,\n Pattern,\n PythonClass,\n PythonClassSummary,\n Tutorial,\n TutorialSummary,\n} from \"./types.js\";\n\n/** Filename-style slug: lowercase, non-alphanumerics collapse to underscores. */\nexport function slugify(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n}\n\n/** Lookup key that unifies \"Noise TOP\", \"noiseTOP\" and \"noise_top\" → \"noisetop\". */\nexport function compactKey(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function toOperatorSummary(slug: string, doc: OperatorDoc): OperatorSummary {\n return {\n slug,\n name: doc.name,\n displayName: doc.displayName ?? doc.name,\n category: doc.category ?? \"Unknown\",\n subcategory: doc.subcategory ?? \"\",\n summary: doc.summary ?? doc.description ?? \"\",\n keywords: doc.keywords ?? [],\n };\n}\n\nexport function toPythonSummary(cls: PythonClass): PythonClassSummary {\n return {\n className: cls.className,\n displayName: cls.displayName ?? cls.className,\n category: cls.category ?? \"Unknown\",\n methodCount: cls.methods?.length ?? 0,\n memberCount: cls.members?.length ?? 0,\n };\n}\n\nexport function toTutorialSummary(tut: Tutorial): TutorialSummary {\n return {\n id: tut.id,\n name: tut.name,\n category: tut.category ?? \"Unknown\",\n summary: tut.summary ?? tut.description ?? \"\",\n };\n}\n\ninterface RawPattern {\n name?: string;\n description?: string;\n category?: string;\n workflow?: string[];\n use_case?: string;\n}\n\n/**\n * The bottobot patterns file is an object with a `patterns` array (plus extra\n * metadata keys). Normalizes it into a flat, id-keyed array.\n */\nexport function normalizePatterns(raw: unknown): Pattern[] {\n let list: RawPattern[] = [];\n if (Array.isArray(raw)) {\n list = raw as RawPattern[];\n } else if (raw && typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>;\n if (Array.isArray(obj.patterns)) {\n list = obj.patterns as RawPattern[];\n } else {\n list = Object.values(obj).filter((v): v is RawPattern => !!v && typeof v === \"object\");\n }\n }\n return list\n .filter((p) => typeof p.name === \"string\")\n .map((p) => ({\n id: slugify(p.name as string),\n name: p.name as string,\n description: p.description,\n category: p.category,\n workflow: Array.isArray(p.workflow) ? p.workflow : undefined,\n use_case: p.use_case,\n }));\n}\n\ninterface RawGlslFile {\n techniques?: unknown;\n}\n\n/** Extracts GLSL techniques from bottobot's `experimental/glsl.json`. */\nexport function normalizeGlsl(raw: unknown): GlslTechnique[] {\n const file = (raw ?? {}) as RawGlslFile;\n const techniques = Array.isArray(file.techniques) ? file.techniques : [];\n return techniques\n .filter((t): t is Record<string, unknown> => !!t && typeof t === \"object\")\n .map((t) => {\n const name = typeof t.name === \"string\" ? t.name : \"Untitled\";\n const id = typeof t.id === \"string\" && t.id.length > 0 ? t.id : slugify(name);\n return {\n id,\n name,\n subcategory: typeof t.subcategory === \"string\" ? t.subcategory : undefined,\n description: typeof t.description === \"string\" ? t.description : undefined,\n difficulty: typeof t.difficulty === \"string\" ? t.difficulty : undefined,\n operators: Array.isArray(t.operators) ? (t.operators as string[]) : undefined,\n tags: Array.isArray(t.tags) ? (t.tags as string[]) : undefined,\n notes: typeof t.notes === \"string\" ? t.notes : undefined,\n code: (t.code ?? undefined) as GlslTechnique[\"code\"],\n setup: typeof t.setup === \"string\" ? t.setup : undefined,\n };\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { compactKey } from \"../knowledge/normalize.js\";\nimport { type Logger, silentLogger } from \"../utils/logger.js\";\nimport { recipesDir } from \"../utils/paths.js\";\nimport { type Recipe, RecipeSchema, type RecipeSummary } from \"./schema.js\";\n\nexport interface RecipeLibraryOptions {\n dir?: string;\n logger?: Logger;\n}\n\n/** Loads and validates recipe JSON files from the recipes directory. */\nexport class RecipeLibrary {\n private readonly dir: string;\n private readonly logger: Logger;\n private cache?: Recipe[];\n\n constructor(options: RecipeLibraryOptions = {}) {\n this.dir = options.dir ?? recipesDir();\n this.logger = options.logger ?? silentLogger;\n }\n\n private load(): Recipe[] {\n if (this.cache) return this.cache;\n const recipes: Recipe[] = [];\n if (existsSync(this.dir)) {\n for (const file of readdirSync(this.dir)) {\n if (!file.endsWith(\".json\")) continue;\n try {\n const raw = JSON.parse(readFileSync(join(this.dir, file), \"utf8\"));\n const parsed = RecipeSchema.safeParse(raw);\n if (parsed.success) {\n recipes.push(parsed.data);\n } else {\n this.logger.warn(`Invalid recipe ${file}`, { issues: parsed.error.issues.length });\n }\n } catch (err) {\n this.logger.warn(`Failed to read recipe ${file}`, { error: String(err) });\n }\n }\n }\n this.cache = recipes;\n return recipes;\n }\n\n all(): Recipe[] {\n return this.load();\n }\n\n list(): RecipeSummary[] {\n return this.load().map((r) => ({\n id: r.id,\n name: r.name,\n description: r.description,\n tags: r.tags,\n difficulty: r.difficulty,\n }));\n }\n\n get(id: string): Recipe | undefined {\n const key = compactKey(id);\n return this.load().find((r) => compactKey(r.id) === key || compactKey(r.name) === key);\n }\n\n /** Finds the best recipe whose tags/name/description match any of the given terms. */\n findByTags(terms: string[]): Recipe | undefined {\n const wanted = terms.map((t) => t.toLowerCase()).filter(Boolean);\n if (wanted.length === 0) return undefined;\n let best: { recipe: Recipe; score: number } | undefined;\n for (const recipe of this.load()) {\n const haystack =\n `${recipe.name} ${recipe.description} ${recipe.tags.join(\" \")}`.toLowerCase();\n let score = 0;\n for (const term of wanted) {\n if (recipe.tags.some((tag) => tag.toLowerCase() === term)) score += 2;\n else if (haystack.includes(term)) score += 1;\n }\n if (score > 0 && (!best || score > best.score)) best = { recipe, score };\n }\n return best?.recipe;\n }\n}\n","import { z } from \"zod\";\n\nexport const RecipeNodeSchema = z.object({\n name: z.string().describe(\"Unique node name within the recipe (used for wiring).\"),\n type: z.string().describe(\"Operator type, e.g. 'noiseTOP'.\"),\n parameters: z.record(z.string(), z.unknown()).default({}),\n parent: z\n .string()\n .optional()\n .describe(\n \"Name of another recipe node (a COMP, e.g. a geometryCOMP) to nest this node inside of. \" +\n \"The parent must appear earlier in `nodes`. Used to place SOPs inside a Geometry COMP.\",\n ),\n render: z\n .boolean()\n .optional()\n .describe(\n \"For a SOP nested in a geometryCOMP: make this the rendered geometry. Sets the render/display \" +\n \"flags on it and clears its siblings, so the COMP renders this instead of its default torus.\",\n ),\n comment: z.string().optional(),\n});\n\nexport const RecipeConnectionSchema = z.object({\n from: z.string().describe(\"Source node name.\"),\n to: z.string().describe(\"Target node name.\"),\n from_output: z.number().int().nonnegative().default(0),\n to_input: z.number().int().nonnegative().default(0),\n});\n\nexport const RecipeParameterSchema = z.object({\n name: z.string().describe(\"Friendly name of the exposed control.\"),\n node: z.string().describe(\"Recipe node name the parameter belongs to.\"),\n param: z.string().describe(\"TD parameter name on that node.\"),\n value: z.unknown().optional(),\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n description: z.string().optional(),\n});\n\n/**\n * A uniform exposed by a GLSL TOP. On the GLSL TOP these live in *parameter\n * sequences*, not normal parameters, so they cannot be set the usual way: the block\n * count (`op.seq.<seq>.numBlocks`) has to be raised first, after which the per-block\n * name/value sub-parameters exist. `float`/`vec` uniforms bind through the \"Vectors\"\n * page (the `vec` sequence); `color` binds through the \"Colors\" page (the `color`\n * sequence). The \"Constants\" page does NOT feed a runtime `uniform float`, so it is\n * not used here. `buildFromRecipe` handles the translation; authors just declare the\n * uniform.\n */\nexport const RecipeGlslUniformSchema = z.object({\n node: z.string().describe(\"Recipe node name of the GLSL TOP that declares the uniform.\"),\n name: z.string().describe(\"Uniform name as referenced in the shader, e.g. 'uFeed'.\"),\n kind: z\n .enum([\"float\", \"vec\", \"color\"])\n .default(\"float\")\n .describe(\n \"Uniform kind: float (uniform float), vec (uniform vec2/3/4), color (rgba). \" +\n \"float/vec use the Vectors page; color uses the Colors page.\",\n ),\n value: z\n .union([z.number(), z.array(z.number())])\n .optional()\n .describe(\"Initial value: a number for float, or an array of components for vec/color.\"),\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n description: z.string().optional(),\n});\nexport type RecipeGlslUniform = z.infer<typeof RecipeGlslUniformSchema>;\n\nexport const RecipeSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().default(\"\"),\n tags: z.array(z.string()).default([]),\n difficulty: z.enum([\"beginner\", \"intermediate\", \"advanced\"]).default(\"intermediate\"),\n td_version_min: z.string().default(\"2023\"),\n nodes: z.array(RecipeNodeSchema).min(1),\n connections: z.array(RecipeConnectionSchema).default([]),\n parameters: z.array(RecipeParameterSchema).default([]),\n glsl_uniforms: z.array(RecipeGlslUniformSchema).default([]),\n glsl_code: z.record(z.string(), z.string()).optional(),\n python_code: z.record(z.string(), z.string()).optional(),\n preview_description: z.string().default(\"\"),\n});\nexport type Recipe = z.infer<typeof RecipeSchema>;\n\nexport interface RecipeSummary {\n id: string;\n name: string;\n description: string;\n tags: string[];\n difficulty: Recipe[\"difficulty\"];\n}\n","/** Base error for all TouchDesigner bridge failures. */\nexport class TdError extends Error {\n readonly code: string;\n\n constructor(message: string, code: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"TdError\";\n this.code = code;\n }\n}\n\n/** The bridge could not be reached (TD not running, wrong host/port, etc.). */\nexport class TdConnectionError extends TdError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, \"TD_CONNECTION\", options);\n this.name = \"TdConnectionError\";\n }\n}\n\n/** The request exceeded the configured timeout. */\nexport class TdTimeoutError extends TdError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, \"TD_TIMEOUT\", options);\n this.name = \"TdTimeoutError\";\n }\n}\n\n/** The bridge responded but reported an error (HTTP non-2xx or `ok: false`). */\nexport class TdApiError extends TdError {\n readonly status: number | undefined;\n readonly apiCode: string | undefined;\n\n constructor(message: string, options?: { status?: number; apiCode?: string; cause?: unknown }) {\n super(message, \"TD_API\", options);\n this.name = \"TdApiError\";\n this.status = options?.status;\n this.apiCode = options?.apiCode;\n }\n}\n\n/** Produces a human-friendly, single-line description of any error. */\nexport function friendlyTdError(err: unknown): string {\n if (err instanceof TdError) return err.message;\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\nexport type {\n ApiEnvelope,\n CreateNodeInput,\n TdBatchOperation,\n TdBatchResult,\n TdConnection,\n TdDeleteResult,\n TdExecResult,\n TdInfo,\n TdMethodResult,\n TdNodeDetail,\n TdNodeError,\n TdNodeErrors,\n TdNodeList,\n TdNodeRef,\n TdPerformance,\n TdPreview,\n TdTopology,\n} from \"./validators.js\";\n","import { z } from \"zod\";\n\n/** Standard response envelope every bridge endpoint returns. */\nexport const ApiEnvelopeSchema = z.object({\n ok: z.boolean(),\n data: z.unknown().optional(),\n error: z.object({ code: z.string().optional(), message: z.string() }).optional(),\n});\nexport type ApiEnvelope = z.infer<typeof ApiEnvelopeSchema>;\n\nexport const NodeRefSchema = z.object({\n path: z.string(),\n type: z.string().default(\"\"),\n name: z.string().default(\"\"),\n});\nexport type TdNodeRef = z.infer<typeof NodeRefSchema>;\n\nexport const NodeDetailSchema = NodeRefSchema.extend({\n parameters: z.record(z.string(), z.unknown()).default({}),\n inputs: z.array(z.string()).optional(),\n outputs: z.array(z.string()).optional(),\n family: z.string().optional(),\n errors: z.array(z.string()).optional(),\n});\nexport type TdNodeDetail = z.infer<typeof NodeDetailSchema>;\n\nexport const NodeListSchema = z.object({ nodes: z.array(NodeRefSchema).default([]) });\nexport type TdNodeList = z.infer<typeof NodeListSchema>;\n\nexport const InfoSchema = z.object({\n td_version: z.string().optional(),\n python_version: z.string().optional(),\n build: z.string().optional(),\n bridge_version: z.string().optional(),\n project: z.string().optional(),\n});\nexport type TdInfo = z.infer<typeof InfoSchema>;\n\nexport const NodeErrorSchema = z.object({\n path: z.string(),\n message: z.string(),\n type: z.string().optional(),\n});\nexport type TdNodeError = z.infer<typeof NodeErrorSchema>;\n\nexport const NodeErrorsSchema = z.object({ errors: z.array(NodeErrorSchema).default([]) });\nexport type TdNodeErrors = z.infer<typeof NodeErrorsSchema>;\n\nexport const PreviewSchema = z.object({\n path: z.string(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.string().default(\"png\"),\n base64: z.string(),\n});\nexport type TdPreview = z.infer<typeof PreviewSchema>;\n\nexport const ExecResultSchema = z.object({\n result: z.unknown().optional(),\n stdout: z.string().optional(),\n printed: z.array(z.string()).optional(),\n});\nexport type TdExecResult = z.infer<typeof ExecResultSchema>;\n\nexport const MethodResultSchema = z.object({ result: z.unknown() });\nexport type TdMethodResult = z.infer<typeof MethodResultSchema>;\n\nexport const DeleteResultSchema = z.object({ deleted: z.string() });\nexport type TdDeleteResult = z.infer<typeof DeleteResultSchema>;\n\nexport const ConnectionSchema = z.object({\n source_path: z.string(),\n source_output: z.number().int().default(0),\n target_path: z.string(),\n target_input: z.number().int().default(0),\n});\nexport type TdConnection = z.infer<typeof ConnectionSchema>;\n\nexport const TopologySchema = z.object({\n nodes: z.array(NodeRefSchema).default([]),\n connections: z.array(ConnectionSchema).default([]),\n});\nexport type TdTopology = z.infer<typeof TopologySchema>;\n\nexport const PerformanceSchema = z.object({\n nodes: z\n .array(\n z.object({\n path: z.string(),\n cook_time_ms: z.number().default(0),\n cook_count: z.number().optional(),\n }),\n )\n .default([]),\n total_cook_time_ms: z.number().optional(),\n gpu_memory_mb: z.number().optional(),\n});\nexport type TdPerformance = z.infer<typeof PerformanceSchema>;\n\nexport const BatchOpResultSchema = z.object({\n action: z.string(),\n ok: z.boolean(),\n path: z.string().optional(),\n data: z.unknown().optional(),\n error: z.string().optional(),\n});\nexport const BatchResultSchema = z.object({ results: z.array(BatchOpResultSchema).default([]) });\nexport type TdBatchResult = z.infer<typeof BatchResultSchema>;\n\n/** Input shape for creating a node (used by the client and Layer 3 tool). */\nexport const CreateNodeInputSchema = z.object({\n parent_path: z.string(),\n type: z.string(),\n name: z.string().optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n});\nexport type CreateNodeInput = z.infer<typeof CreateNodeInputSchema>;\n\n/** A single atomic operation accepted by `POST /api/batch`. */\nexport const BatchOperationSchema = z.discriminatedUnion(\"action\", [\n z.object({\n action: z.literal(\"create\"),\n parent_path: z.string(),\n type: z.string(),\n name: z.string().optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n }),\n z.object({\n action: z.literal(\"update\"),\n path: z.string(),\n parameters: z.record(z.string(), z.unknown()),\n }),\n z.object({ action: z.literal(\"delete\"), path: z.string() }),\n z.object({\n action: z.literal(\"connect\"),\n source_path: z.string(),\n target_path: z.string(),\n source_output: z.number().int().default(0),\n target_input: z.number().int().default(0),\n }),\n]);\nexport type TdBatchOperation = z.infer<typeof BatchOperationSchema>;\n","import type { z } from \"zod\";\nimport { type Logger, silentLogger } from \"../utils/logger.js\";\nimport { TdApiError, TdConnectionError, TdTimeoutError } from \"./types.js\";\nimport {\n ApiEnvelopeSchema,\n BatchResultSchema,\n type CreateNodeInput,\n CreateNodeInputSchema,\n DeleteResultSchema,\n ExecResultSchema,\n InfoSchema,\n MethodResultSchema,\n NodeDetailSchema,\n NodeErrorsSchema,\n NodeListSchema,\n NodeRefSchema,\n PerformanceSchema,\n PreviewSchema,\n type TdBatchOperation,\n TopologySchema,\n} from \"./validators.js\";\n\nexport interface TouchDesignerClientOptions {\n baseUrl: string;\n timeoutMs?: number;\n logger?: Logger;\n /** Optional shared bearer token; sent as `Authorization: Bearer <token>` when set. */\n token?: string;\n /** Overridable for tests (defaults to global `fetch`). */\n fetchImpl?: typeof fetch;\n}\n\ntype QueryParams = Record<string, string | number | boolean | undefined>;\n\nfunction extractErrorMessage(json: unknown): string | undefined {\n if (json && typeof json === \"object\") {\n const obj = json as Record<string, unknown>;\n const error = obj.error;\n if (\n error &&\n typeof error === \"object\" &&\n typeof (error as Record<string, unknown>).message === \"string\"\n ) {\n return (error as Record<string, string>).message;\n }\n if (typeof obj.message === \"string\") return obj.message;\n }\n return undefined;\n}\n\n/** Encodes a TD node path (which contains slashes) into a single URL segment. */\nfunction segment(path: string): string {\n return encodeURIComponent(path);\n}\n\n/**\n * HTTP client for the TouchDesigner REST bridge. Every method maps to one of the\n * endpoints in the bridge spec. All failures surface as typed `TdError`s so MCP\n * tool handlers can convert them into friendly messages without crashing.\n */\nexport class TouchDesignerClient {\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly logger: Logger;\n private readonly token: string | undefined;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: TouchDesignerClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.timeoutMs = options.timeoutMs ?? 10000;\n this.logger = options.logger ?? silentLogger;\n this.token = options.token;\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n get endpoint(): string {\n return this.baseUrl;\n }\n\n private async request<T>(\n method: string,\n path: string,\n schema: z.ZodType<T>,\n body?: unknown,\n query?: QueryParams,\n ): Promise<T> {\n const url = new URL(`${this.baseUrl}${path}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n let response: Response;\n try {\n this.logger.debug(`TD ${method} ${path}`);\n const headers: Record<string, string> = {};\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (this.token) headers.authorization = `Bearer ${this.token}`;\n response = await this.fetchImpl(url, {\n method,\n signal: controller.signal,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new TdTimeoutError(\n `TouchDesigner request timed out after ${this.timeoutMs}ms (${method} ${path}).`,\n { cause: err },\n );\n }\n throw new TdConnectionError(\n `Cannot reach TouchDesigner at ${this.baseUrl}. Make sure TD is running with the tdmcp bridge (WebServer DAT) installed and listening on that port.`,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n }\n\n const text = await response.text();\n let json: unknown;\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n\n if (!response.ok) {\n const message =\n extractErrorMessage(json) ??\n `TouchDesigner bridge returned HTTP ${response.status} for ${method} ${path}.`;\n throw new TdApiError(message, { status: response.status });\n }\n\n const envelope = ApiEnvelopeSchema.safeParse(json);\n if (!envelope.success) {\n throw new TdApiError(`Malformed response from TouchDesigner bridge for ${method} ${path}.`, {\n status: response.status,\n });\n }\n if (!envelope.data.ok) {\n throw new TdApiError(\n envelope.data.error?.message ?? `TouchDesigner reported an error for ${method} ${path}.`,\n { status: response.status, apiCode: envelope.data.error?.code },\n );\n }\n\n const parsed = schema.safeParse(envelope.data.data);\n if (!parsed.success) {\n throw new TdApiError(\n `Unexpected data shape from TouchDesigner bridge for ${method} ${path}: ${parsed.error.message}`,\n { status: response.status },\n );\n }\n return parsed.data;\n }\n\n getInfo() {\n return this.request(\"GET\", \"/api/info\", InfoSchema);\n }\n\n createNode(input: CreateNodeInput) {\n return this.request(\"POST\", \"/api/nodes\", NodeRefSchema, CreateNodeInputSchema.parse(input));\n }\n\n deleteNode(path: string) {\n return this.request(\"DELETE\", `/api/nodes/${segment(path)}`, DeleteResultSchema);\n }\n\n getNodes(parentPath?: string) {\n return this.request(\"GET\", \"/api/nodes\", NodeListSchema, undefined, { parent: parentPath });\n }\n\n getNode(path: string) {\n return this.request(\"GET\", `/api/nodes/${segment(path)}`, NodeDetailSchema);\n }\n\n updateNodeParameters(path: string, parameters: Record<string, unknown>) {\n return this.request(\"PATCH\", `/api/nodes/${segment(path)}`, NodeDetailSchema, { parameters });\n }\n\n executePythonScript(script: string, returnOutput = true) {\n return this.request(\"POST\", \"/api/exec\", ExecResultSchema, {\n script,\n return_output: returnOutput,\n });\n }\n\n execNodeMethod(\n path: string,\n method: string,\n args: unknown[] = [],\n kwargs: Record<string, unknown> = {},\n ) {\n return this.request(\"POST\", `/api/nodes/${segment(path)}/method`, MethodResultSchema, {\n method,\n args,\n kwargs,\n });\n }\n\n getNodeErrors(path: string) {\n return this.request(\"GET\", `/api/nodes/${segment(path)}/errors`, NodeErrorsSchema);\n }\n\n getPreview(path: string, width = 640, height = 360) {\n return this.request(\"GET\", `/api/preview/${segment(path)}`, PreviewSchema, undefined, {\n width,\n height,\n });\n }\n\n batch(operations: TdBatchOperation[]) {\n return this.request(\"POST\", \"/api/batch\", BatchResultSchema, { operations });\n }\n\n getNetworkErrors(path: string) {\n return this.request(\"GET\", `/api/network/${segment(path)}/errors`, NodeErrorsSchema);\n }\n\n getNetworkTopology(path: string, recursive = false) {\n return this.request(\n \"GET\",\n `/api/network/${segment(path)}/topology`,\n TopologySchema,\n undefined,\n recursive ? { recursive: true } : undefined,\n );\n }\n\n getNetworkPerformance(path: string) {\n return this.request(\"GET\", `/api/network/${segment(path)}/performance`, PerformanceSchema);\n }\n}\n","import { z } from \"zod\";\n\nexport const ConfigSchema = z.object({\n /** TouchDesigner bridge host. */\n tdHost: z.string().min(1).default(\"127.0.0.1\"),\n /** TouchDesigner bridge port (WebServer DAT). */\n tdPort: z.coerce.number().int().positive().max(65535).default(9980),\n /** MCP transport: `stdio` (default, for local clients) or `http` (Streamable HTTP, loopback-only). */\n transport: z.enum([\"stdio\", \"http\"]).default(\"stdio\"),\n /** Log verbosity (written to stderr). */\n logLevel: z.enum([\"debug\", \"info\", \"warn\", \"error\", \"silent\"]).default(\"info\"),\n /** Per-request timeout against the TD bridge, in milliseconds. */\n requestTimeoutMs: z.coerce.number().int().positive().default(10000),\n /** HTTP transport port (only used when transport=http). */\n httpPort: z.coerce.number().int().positive().max(65535).default(3939),\n /** Subscribe to TD WebSocket events and forward them as MCP logging notifications. */\n events: z.enum([\"on\", \"off\"]).default(\"on\"),\n /**\n * Raw Python escape-hatch tools (`execute_python_script`, `exec_node_method`).\n * Set to \"off\" to lock them out for restricted setups; on by default.\n */\n rawPython: z.enum([\"on\", \"off\"]).default(\"on\"),\n /**\n * Optional shared bearer token for the TD bridge. When set, the server sends it\n * as `Authorization: Bearer <token>` and the bridge requires a match. Leave unset\n * (default) for the zero-config local flow. Set the SAME value in TouchDesigner's\n * environment (`TDMCP_BRIDGE_TOKEN`) to turn enforcement on.\n */\n bridgeToken: z.string().min(1).optional(),\n});\n\nexport type TdmcpConfig = z.infer<typeof ConfigSchema>;\n\n/**\n * Loads and validates configuration from environment variables. Missing values\n * fall back to sensible defaults; invalid values throw a descriptive ZodError.\n */\nexport function loadConfig(env: NodeJS.ProcessEnv = process.env): TdmcpConfig {\n return ConfigSchema.parse({\n tdHost: env.TDMCP_TD_HOST,\n tdPort: env.TDMCP_TD_PORT,\n transport: env.TDMCP_TRANSPORT,\n logLevel: env.TDMCP_LOG_LEVEL,\n requestTimeoutMs: env.TDMCP_REQUEST_TIMEOUT_MS,\n httpPort: env.TDMCP_HTTP_PORT,\n events: env.TDMCP_EVENTS,\n rawPython: env.TDMCP_RAW_PYTHON,\n bridgeToken: env.TDMCP_BRIDGE_TOKEN || undefined,\n });\n}\n\n/** Base URL for the TouchDesigner REST bridge. */\nexport function tdBaseUrl(config: Pick<TdmcpConfig, \"tdHost\" | \"tdPort\">): string {\n return `http://${config.tdHost}:${config.tdPort}`;\n}\n","import { TouchDesignerClient } from \"../td-client/touchDesignerClient.js\";\nimport { type TdmcpConfig, tdBaseUrl } from \"../utils/config.js\";\nimport type { Logger } from \"../utils/logger.js\";\n\n/**\n * Owns the TouchDesigner client and exposes a cheap health probe. The MCP server\n * stays alive whether or not TD is reachable.\n */\nexport class ConnectionManager {\n readonly client: TouchDesignerClient;\n\n constructor(config: TdmcpConfig, logger: Logger) {\n this.client = new TouchDesignerClient({\n baseUrl: tdBaseUrl(config),\n timeoutMs: config.requestTimeoutMs,\n token: config.bridgeToken,\n logger,\n });\n }\n\n async isReachable(): Promise<boolean> {\n try {\n await this.client.getInfo();\n return true;\n } catch {\n return false;\n }\n }\n}\n","import { KnowledgeBase } from \"../knowledge/index.js\";\nimport { RecipeLibrary } from \"../recipes/loader.js\";\nimport type { ToolContext } from \"../tools/types.js\";\nimport type { TdmcpConfig } from \"../utils/config.js\";\nimport { createLogger, type Logger } from \"../utils/logger.js\";\nimport { ConnectionManager } from \"./connectionManager.js\";\n\nexport interface ToolContextOverrides {\n logger?: Logger;\n knowledge?: KnowledgeBase;\n recipes?: RecipeLibrary;\n connection?: ConnectionManager;\n}\n\n/**\n * Assembles the shared {@link ToolContext} that backs every tool handler. Both\n * the MCP server and the agent CLI build their context here, so the two surfaces\n * stay on the same core (client + knowledge + recipes) without duplicating wiring.\n */\nexport function buildToolContext(\n config: TdmcpConfig,\n overrides: ToolContextOverrides = {},\n): ToolContext {\n const logger = overrides.logger ?? createLogger(config.logLevel);\n const connection = overrides.connection ?? new ConnectionManager(config, logger);\n const knowledge = overrides.knowledge ?? new KnowledgeBase({ logger });\n const recipes = overrides.recipes ?? new RecipeLibrary({ logger });\n return {\n client: connection.client,\n knowledge,\n recipes,\n logger,\n allowRawPython: config.rawPython !== \"off\",\n };\n}\n","import { z } from \"zod\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const compareTdNodesSchema = z.object({\n path_a: z.string().describe(\"First node path.\"),\n path_b: z.string().describe(\"Second node path.\"),\n only_diff: z\n .boolean()\n .default(true)\n .describe(\"Return only the parameters that differ (true) or also list the identical ones.\"),\n});\ntype CompareTdNodesArgs = z.infer<typeof compareTdNodesSchema>;\n\nexport const compareTdNodesOutputSchema = z.object({\n a: z.string(),\n b: z.string(),\n type_a: z.string(),\n type_b: z.string(),\n type_match: z.boolean(),\n differing_count: z.number(),\n same_count: z.number(),\n differing: z.array(z.object({ param: z.string(), a: z.unknown(), b: z.unknown() })),\n identical: z.array(z.string()).optional(),\n});\n\nexport async function compareTdNodesImpl(ctx: ToolContext, args: CompareTdNodesArgs) {\n return guardTd(\n async () => {\n const [a, b] = await Promise.all([\n ctx.client.getNode(args.path_a),\n ctx.client.getNode(args.path_b),\n ]);\n return { a, b };\n },\n ({ a, b }) => {\n const keys = new Set([...Object.keys(a.parameters), ...Object.keys(b.parameters)]);\n const differing: Array<{ param: string; a: unknown; b: unknown }> = [];\n const identical: string[] = [];\n for (const key of [...keys].sort()) {\n const va = a.parameters[key];\n const vb = b.parameters[key];\n if (JSON.stringify(va) === JSON.stringify(vb)) identical.push(key);\n else differing.push({ param: key, a: va, b: vb });\n }\n const data: Record<string, unknown> = {\n a: a.path,\n b: b.path,\n type_a: a.type,\n type_b: b.type,\n type_match: a.type === b.type,\n differing_count: differing.length,\n same_count: identical.length,\n differing,\n };\n if (!args.only_diff) data.identical = identical;\n return structuredResult(\n `${differing.length} differing parameter(s) between ${a.path} and ${b.path}${a.type === b.type ? \"\" : ` (types differ: ${a.type} vs ${b.type})`}.`,\n data,\n );\n },\n );\n}\n\nexport const registerCompareTdNodes: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"compare_td_nodes\",\n {\n title: \"Compare two nodes\",\n description:\n \"Diff the parameters of two nodes, returning only the values that differ (by default). Useful for aligning settings across similar operators.\",\n inputSchema: compareTdNodesSchema.shape,\n outputSchema: compareTdNodesOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => compareTdNodesImpl(ctx, args),\n );\n};\n","import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { friendlyTdError } from \"../td-client/types.js\";\n\ntype Content = CallToolResult[\"content\"];\n\nexport function textResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }] };\n}\n\nexport function errorResult(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** A text block followed by a pretty-printed JSON code fence. */\nexport function jsonResult(summary: string, data: unknown): CallToolResult {\n const text = `${summary}\\n\\n\\`\\`\\`json\\n${JSON.stringify(data, null, 2)}\\n\\`\\`\\``;\n return { content: [{ type: \"text\", text }] };\n}\n\n/**\n * A short text summary plus a machine-readable `structuredContent` payload.\n *\n * Use this (with an `outputSchema` on the tool) for read tools so agents can\n * process the data with code instead of re-parsing a JSON code fence out of the\n * conversation. The text block stays small on purpose — it is only a summary;\n * the full data travels on the `structuredContent` channel.\n */\nexport function structuredResult(summary: string, data: object): CallToolResult {\n return {\n content: [{ type: \"text\", text: summary }],\n structuredContent: data as { [key: string]: unknown },\n };\n}\n\n/** An image block (base64), optionally preceded by a caption. */\nexport function imageResult(\n base64: string,\n mimeType = \"image/png\",\n caption?: string,\n): CallToolResult {\n const content: Content = [];\n if (caption) content.push({ type: \"text\", text: caption });\n content.push({ type: \"image\", data: base64, mimeType });\n return { content };\n}\n\n/**\n * Runs a client call and formats the result, converting any TD error into a\n * friendly `isError` result instead of throwing out of the MCP handler.\n */\nexport async function guardTd<T>(\n fn: () => Promise<T>,\n onOk: (value: T) => CallToolResult,\n): Promise<CallToolResult> {\n try {\n return onOk(await fn());\n } catch (err) {\n return errorResult(friendlyTdError(err));\n }\n}\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const createTdNodeSchema = z.object({\n parent_path: z\n .string()\n .default(\"/project1\")\n .describe(\"Parent COMP path to create the node inside.\"),\n type: z\n .string()\n .describe(\"Operator type string, e.g. 'noiseTOP', 'feedbackTOP', 'nullTOP', 'constantCHOP'.\"),\n name: z.string().optional().describe(\"Optional node name (auto-generated if omitted).\"),\n parameters: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Optional initial parameter overrides as key→value pairs.\"),\n});\ntype CreateTdNodeArgs = z.infer<typeof createTdNodeSchema>;\n\nexport async function createTdNodeImpl(ctx: ToolContext, args: CreateTdNodeArgs) {\n const warnings: string[] = [];\n if (!ctx.knowledge.operatorExists(args.type)) {\n const suggestions = ctx.knowledge.searchOperators(args.type, 3).map((s) => s.name);\n warnings.push(\n `Operator type \"${args.type}\" was not found in the knowledge base.${\n suggestions.length ? ` Did you mean: ${suggestions.join(\", \")}?` : \"\"\n }`,\n );\n }\n return guardTd(\n () =>\n ctx.client.createNode({\n parent_path: args.parent_path,\n type: args.type,\n name: args.name,\n parameters: args.parameters,\n }),\n (node) => jsonResult(`Created ${node.type || args.type} at ${node.path}.`, { node, warnings }),\n );\n}\n\nexport const registerCreateTdNode: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"create_td_node\",\n {\n title: \"Create TouchDesigner node\",\n description:\n \"Create a single operator (node) inside a parent COMP. Validates the operator type against the knowledge base and warns (without blocking) on unknown types.\",\n inputSchema: createTdNodeSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },\n },\n (args) => createTdNodeImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const deleteTdNodeSchema = z.object({\n path: z.string().describe(\"Full path of the node to delete, e.g. '/project1/noise1'.\"),\n});\ntype DeleteTdNodeArgs = z.infer<typeof deleteTdNodeSchema>;\n\nexport async function deleteTdNodeImpl(ctx: ToolContext, args: DeleteTdNodeArgs) {\n return guardTd(\n () => ctx.client.deleteNode(args.path),\n (result) => jsonResult(`Deleted ${result.deleted}.`, result),\n );\n}\n\nexport const registerDeleteTdNode: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"delete_td_node\",\n {\n title: \"Delete TouchDesigner node\",\n description:\n \"Delete a single node by path. Destructive — only call this when the user explicitly asks to remove a node.\",\n inputSchema: deleteTdNodeSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },\n },\n (args) => deleteTdNodeImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const execNodeMethodSchema = z.object({\n path: z.string().describe(\"Full path of the node to call the method on.\"),\n method: z.string().describe(\"Method name to call, e.g. 'cook', 'par', 'destroy', 'copy'.\"),\n args: z.array(z.unknown()).default([]).describe(\"Positional arguments.\"),\n kwargs: z.record(z.string(), z.unknown()).default({}).describe(\"Keyword arguments.\"),\n});\ntype ExecNodeMethodArgs = z.infer<typeof execNodeMethodSchema>;\n\nexport async function execNodeMethodImpl(ctx: ToolContext, args: ExecNodeMethodArgs) {\n return guardTd(\n () => ctx.client.execNodeMethod(args.path, args.method, args.args, args.kwargs),\n (result) => jsonResult(`Called ${args.path}.${args.method}().`, result),\n );\n}\n\nexport const registerExecNodeMethod: ToolRegistrar = (server, ctx) => {\n if (ctx.allowRawPython === false) return;\n server.registerTool(\n \"exec_node_method\",\n {\n title: \"Call node method\",\n description:\n \"Escape hatch — invoke an arbitrary Python method on a node (operator). Prefer structured tools where one exists; use this for operations they don't cover (e.g. .cook(), .copy(), .destroy()).\",\n inputSchema: execNodeMethodSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },\n },\n (args) => execNodeMethodImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const executePythonScriptSchema = z.object({\n script: z\n .string()\n .min(1)\n .describe(\n \"Python source to execute inside TouchDesigner (runs in the TD process, not locally).\",\n ),\n return_output: z\n .boolean()\n .default(true)\n .describe(\"Capture stdout / the value of the last expression and return it.\"),\n});\ntype ExecutePythonScriptArgs = z.infer<typeof executePythonScriptSchema>;\n\nexport async function executePythonScriptImpl(ctx: ToolContext, args: ExecutePythonScriptArgs) {\n return guardTd(\n () => ctx.client.executePythonScript(args.script, args.return_output),\n (result) => jsonResult(\"Python executed in TouchDesigner.\", result),\n );\n}\n\nexport const registerExecutePythonScript: ToolRegistrar = (server, ctx) => {\n if (ctx.allowRawPython === false) return;\n server.registerTool(\n \"execute_python_script\",\n {\n title: \"Execute Python in TouchDesigner\",\n description:\n \"Escape hatch — run an arbitrary Python script inside the TouchDesigner process. Prefer the structured tools (find_td_nodes, get_td_node_parameters, update_td_node_parameters, summarize_td_errors, snapshot_td_graph, …); reach for this only when no structured tool can express the operation. Code runs in TD only, never on the local machine.\",\n inputSchema: executePythonScriptSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },\n },\n (args) => executePythonScriptImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { NodeRefSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\nimport { globToRegExp } from \"./nodeMatch.js\";\n\nexport const findTdNodesSchema = z.object({\n parent_path: z.string().default(\"/project1\").describe(\"Where to search from.\"),\n pattern: z\n .string()\n .optional()\n .describe(\"Case-insensitive name/path filter with '*' wildcards (e.g. 'text*', '*noise*').\"),\n type: z\n .string()\n .optional()\n .describe(\"Case-insensitive operator-type substring (e.g. 'TOP', 'noise').\"),\n recursive: z\n .boolean()\n .default(true)\n .describe(\"Search the whole sub-network (true) or only direct children (false).\"),\n path_only: z.boolean().default(false).describe(\"Return only matching paths.\"),\n limit: z.number().int().positive().default(50).describe(\"Max matches to return.\"),\n});\ntype FindTdNodesArgs = z.infer<typeof findTdNodesSchema>;\n\nexport const findTdNodesOutputSchema = z.object({\n parent_path: z.string(),\n recursive: z.boolean(),\n count: z.number(),\n truncated: z.boolean(),\n paths: z.array(z.string()).optional(),\n matches: z.array(NodeRefSchema).optional(),\n});\n\nexport async function findTdNodesImpl(ctx: ToolContext, args: FindTdNodesArgs) {\n const fetch = args.recursive\n ? async () => (await ctx.client.getNetworkTopology(args.parent_path, true)).nodes\n : async () => (await ctx.client.getNodes(args.parent_path)).nodes;\n\n return guardTd(fetch, (allNodes) => {\n let nodes = allNodes;\n if (args.pattern) {\n const re = globToRegExp(args.pattern);\n nodes = nodes.filter((n) => re.test(n.name) || re.test(n.path));\n }\n if (args.type) {\n const t = args.type.toLowerCase();\n nodes = nodes.filter((n) => n.type.toLowerCase().includes(t));\n }\n const count = nodes.length;\n const truncated = count > args.limit;\n nodes = nodes.slice(0, args.limit);\n const summary = `${count} match(es) under ${args.parent_path}${truncated ? ` (showing ${args.limit})` : \"\"}.`;\n const base = { parent_path: args.parent_path, recursive: args.recursive, count, truncated };\n return args.path_only\n ? structuredResult(summary, { ...base, paths: nodes.map((n) => n.path) })\n : structuredResult(summary, { ...base, matches: nodes });\n });\n}\n\nexport const registerFindTdNodes: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"find_td_nodes\",\n {\n title: \"Find TouchDesigner nodes\",\n description:\n \"Search a network for nodes by name pattern and/or operator type. Recursive by default; pass path_only:true for a compact path list. Prefer this over get_td_nodes when you are looking for specific nodes.\",\n inputSchema: findTdNodesSchema.shape,\n outputSchema: findTdNodesOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => findTdNodesImpl(ctx, args),\n );\n};\n","/** Turns a `*`-glob into a case-insensitive RegExp (other regex metachars are escaped). */\nexport function globToRegExp(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\");\n return new RegExp(escaped, \"i\");\n}\n\n/** The parent path of a TD node path, e.g. `/project1/moviein1` -> `/project1`. */\nexport function parentOf(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx <= 0 ? \"/\" : path.slice(0, idx);\n}\n","import { z } from \"zod\";\nimport { jsonResult, textResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getModuleHelpSchema = z.object({\n name: z.string().describe(\"Class or module name to get help for, e.g. 'OP', 'App', 'Project'.\"),\n});\ntype GetModuleHelpArgs = z.infer<typeof getModuleHelpSchema>;\n\nexport function getModuleHelpImpl(ctx: ToolContext, args: GetModuleHelpArgs) {\n const cls = ctx.knowledge.getPythonClass(args.name);\n if (!cls) {\n const suggestions = ctx.knowledge\n .listPythonClasses()\n .filter((c) => c.className.toLowerCase().includes(args.name.toLowerCase()))\n .slice(0, 5)\n .map((c) => c.className);\n return jsonResult(`No help found for \"${args.name}\".`, { found: false, suggestions });\n }\n\n const lines: string[] = [`# ${cls.displayName || cls.className}`, \"\"];\n if (cls.description) lines.push(cls.description, \"\");\n if (cls.members && cls.members.length > 0) {\n lines.push(\"## Members\");\n for (const m of cls.members) {\n const ro = m.readOnly ? \" (read-only)\" : \"\";\n lines.push(`- ${m.name}${m.returnType ? `: ${m.returnType}` : \"\"}${ro}`);\n }\n lines.push(\"\");\n }\n if (cls.methods && cls.methods.length > 0) {\n lines.push(\"## Methods\");\n for (const method of cls.methods) {\n const sig = method.signature || method.name || \"\";\n lines.push(`- ${sig}${method.returns ? ` -> ${method.returns}` : \"\"}`);\n }\n }\n return textResult(lines.join(\"\\n\"));\n}\n\nexport const registerGetModuleHelp: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_module_help\",\n {\n title: \"Get module/class help\",\n description:\n \"Human-readable help (description, members, method signatures) for a TouchDesigner Python class or module, from the knowledge base.\",\n inputSchema: getModuleHelpSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (args) => getModuleHelpImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdClassDetailsSchema = z.object({\n class_name: z.string().describe(\"Python class name, e.g. 'OP', 'TOP', 'App', 'CHOP'.\"),\n});\ntype GetTdClassDetailsArgs = z.infer<typeof getTdClassDetailsSchema>;\n\nexport function getTdClassDetailsImpl(ctx: ToolContext, args: GetTdClassDetailsArgs) {\n const cls = ctx.knowledge.getPythonClass(args.class_name);\n if (!cls) {\n const suggestions = ctx.knowledge\n .listPythonClasses()\n .filter((c) => c.className.toLowerCase().includes(args.class_name.toLowerCase()))\n .slice(0, 5)\n .map((c) => c.className);\n return structuredResult(`Python class \"${args.class_name}\" not found.`, {\n found: false,\n suggestions,\n });\n }\n return structuredResult(\n `${cls.className} — ${cls.methods?.length ?? 0} methods, ${cls.members?.length ?? 0} members.`,\n cls,\n );\n}\n\nexport const registerGetTdClassDetails: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_class_details\",\n {\n title: \"Get TD Python class details\",\n description:\n \"Full documentation for one TouchDesigner Python class (members + methods) from the knowledge base.\",\n inputSchema: getTdClassDetailsSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (args) => getTdClassDetailsImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdClassesSchema = z.object({\n filter: z\n .string()\n .optional()\n .describe(\"Optional case-insensitive substring to filter class names by.\"),\n});\ntype GetTdClassesArgs = z.infer<typeof getTdClassesSchema>;\n\nexport function getTdClassesImpl(ctx: ToolContext, args: GetTdClassesArgs) {\n let classes = ctx.knowledge.listPythonClasses();\n if (args.filter) {\n const needle = args.filter.toLowerCase();\n classes = classes.filter(\n (c) =>\n c.className.toLowerCase().includes(needle) || c.displayName.toLowerCase().includes(needle),\n );\n }\n return structuredResult(`Found ${classes.length} TouchDesigner Python API class(es).`, {\n classes,\n });\n}\n\nexport const registerGetTdClasses: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_classes\",\n {\n title: \"List TD Python classes\",\n description:\n \"List TouchDesigner Python API classes from the embedded knowledge base (works offline). Optionally filter by name.\",\n inputSchema: getTdClassesSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (args) => getTdClassesImpl(ctx, args),\n );\n};\n","import { friendlyTdError } from \"../../td-client/types.js\";\nimport { jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nconst DESCRIPTION =\n \"Health check + TouchDesigner server info. Returns TD/Python version and bridge status when connected, plus the embedded knowledge-base stats. Use this first to confirm the bridge is reachable.\";\n\nexport async function getTdInfoImpl(ctx: ToolContext) {\n const knowledge = ctx.knowledge.stats();\n try {\n const info = await ctx.client.getInfo();\n return jsonResult(\"TouchDesigner is connected.\", {\n connected: true,\n endpoint: ctx.client.endpoint,\n touchdesigner: info,\n knowledge,\n });\n } catch (err) {\n return jsonResult(\"TouchDesigner is not reachable (the server is still running).\", {\n connected: false,\n endpoint: ctx.client.endpoint,\n reason: friendlyTdError(err),\n knowledge,\n });\n }\n}\n\nexport const registerGetTdInfo: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_info\",\n {\n title: \"Get TouchDesigner info\",\n description: DESCRIPTION,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n () => getTdInfoImpl(ctx),\n );\n};\n","import { z } from \"zod\";\nimport { NodeErrorSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdNodeErrorsSchema = z.object({\n path: z.string().describe(\"Full path of the node (or network root) to check for errors.\"),\n recursive: z\n .boolean()\n .default(false)\n .describe(\"If true, check the whole network under `path`; otherwise just that node.\"),\n summary: z\n .boolean()\n .default(false)\n .describe(\"Return only counts grouped by error type instead of the full error list.\"),\n});\ntype GetTdNodeErrorsArgs = z.infer<typeof getTdNodeErrorsSchema>;\n\nexport const getTdNodeErrorsOutputSchema = z.object({\n path: z.string(),\n total: z.number(),\n errors: z.array(NodeErrorSchema).optional(),\n by_type: z.record(z.string(), z.number()).optional(),\n});\n\nexport async function getTdNodeErrorsImpl(ctx: ToolContext, args: GetTdNodeErrorsArgs) {\n return guardTd(\n () =>\n args.recursive ? ctx.client.getNetworkErrors(args.path) : ctx.client.getNodeErrors(args.path),\n (result) => {\n const errors = result.errors;\n const total = errors.length;\n const none = total === 0;\n if (args.summary) {\n const byType: Record<string, number> = {};\n for (const e of errors) {\n const key = e.type || \"error\";\n byType[key] = (byType[key] ?? 0) + 1;\n }\n return structuredResult(\n none ? `No errors found at ${args.path}.` : `${total} error(s) at ${args.path}.`,\n { path: args.path, total, by_type: byType },\n );\n }\n return structuredResult(\n none ? `No errors found at ${args.path}.` : `Found ${total} error(s) at ${args.path}.`,\n { path: args.path, total, errors },\n );\n },\n );\n}\n\nexport const registerGetTdNodeErrors: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_node_errors\",\n {\n title: \"Get node errors\",\n description:\n \"Check a node (or its whole sub-network) for cook/compile errors and warnings. Pass `summary:true` for grouped counts instead of the full list.\",\n inputSchema: getTdNodeErrorsSchema.shape,\n outputSchema: getTdNodeErrorsOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdNodeErrorsImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { NodeDetailSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdNodeParametersSchema = z.object({\n path: z.string().describe(\"Full path of the node to inspect.\"),\n keys: z\n .array(z.string())\n .optional()\n .describe(\"Only return these parameter names (case-sensitive). Omit to return all parameters.\"),\n omit_io: z\n .boolean()\n .default(false)\n .describe(\"Drop the inputs/outputs lists from the result to save context.\"),\n});\ntype GetTdNodeParametersArgs = z.infer<typeof getTdNodeParametersSchema>;\n\nexport async function getTdNodeParametersImpl(ctx: ToolContext, args: GetTdNodeParametersArgs) {\n return guardTd(\n () => ctx.client.getNode(args.path),\n (node) => {\n let parameters = node.parameters;\n if (args.keys && args.keys.length > 0) {\n const wanted = new Set(args.keys);\n parameters = Object.fromEntries(\n Object.entries(node.parameters).filter(([k]) => wanted.has(k)),\n );\n }\n const data: Record<string, unknown> = {\n path: node.path,\n type: node.type,\n name: node.name,\n parameters,\n };\n if (!args.omit_io) {\n data.inputs = node.inputs;\n data.outputs = node.outputs;\n }\n const count = Object.keys(parameters).length;\n return structuredResult(`${count} parameter(s) for ${node.path} (${node.type}).`, data);\n },\n );\n}\n\nexport const registerGetTdNodeParameters: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_node_parameters\",\n {\n title: \"Get node parameters\",\n description:\n \"Read the current parameters (and I/O) of a node. Pass `keys` to project specific parameters or `omit_io:true` to drop the inputs/outputs lists.\",\n inputSchema: getTdNodeParametersSchema.shape,\n outputSchema: NodeDetailSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdNodeParametersImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { NodeRefSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\nimport { globToRegExp } from \"./nodeMatch.js\";\n\nexport const getTdNodesSchema = z.object({\n parent_path: z\n .string()\n .default(\"/project1\")\n .describe(\"Parent COMP whose direct children should be listed.\"),\n pattern: z\n .string()\n .optional()\n .describe(\n \"Case-insensitive filter on node name/path. Supports '*' wildcards (e.g. 'text*', '*noise*').\",\n ),\n path_only: z\n .boolean()\n .default(false)\n .describe(\"Return only the list of node paths, dropping type/name.\"),\n limit: z.number().int().positive().optional().describe(\"Cap the number of nodes returned.\"),\n detail_level: z\n .enum([\"summary\", \"full\"])\n .default(\"summary\")\n .describe(\n \"'summary' (default) returns a count, a type breakdown and the first few paths; 'full' returns every node. Use 'full' (or path_only) when you need the complete list.\",\n ),\n});\ntype GetTdNodesArgs = z.infer<typeof getTdNodesSchema>;\n\nconst SAMPLE_SIZE = 10;\n\nexport const getTdNodesOutputSchema = z.object({\n parent_path: z.string(),\n count: z.number(),\n detail_level: z.enum([\"summary\", \"full\"]),\n truncated: z.boolean(),\n by_type: z.record(z.string(), z.number()).optional(),\n sample: z.array(z.string()).optional(),\n paths: z.array(z.string()).optional(),\n nodes: z.array(NodeRefSchema).optional(),\n hint: z.string().optional(),\n});\n\nexport async function getTdNodesImpl(ctx: ToolContext, args: GetTdNodesArgs) {\n return guardTd(\n () => ctx.client.getNodes(args.parent_path),\n (list) => {\n let nodes = list.nodes;\n if (args.pattern) {\n const re = globToRegExp(args.pattern);\n nodes = nodes.filter((n) => re.test(n.name) || re.test(n.path));\n }\n const matched = nodes.length;\n const truncated = args.limit !== undefined && matched > args.limit;\n if (args.limit !== undefined) nodes = nodes.slice(0, args.limit);\n const where = args.pattern ? ` matching \"${args.pattern}\"` : \"\";\n const base = {\n parent_path: args.parent_path,\n count: matched,\n detail_level: args.detail_level,\n truncated,\n };\n\n if (args.path_only) {\n return structuredResult(`${matched} node(s) under ${args.parent_path}${where}.`, {\n ...base,\n paths: nodes.map((n) => n.path),\n });\n }\n\n if (args.detail_level === \"summary\") {\n const byType: Record<string, number> = {};\n for (const n of nodes) {\n const key = n.type || \"unknown\";\n byType[key] = (byType[key] ?? 0) + 1;\n }\n const sample = nodes.slice(0, SAMPLE_SIZE).map((n) => n.path);\n return structuredResult(\n `${matched} node(s) under ${args.parent_path}${where}. Summary only — pass detail_level:\"full\" or path_only:true for the full list.`,\n {\n ...base,\n by_type: byType,\n sample,\n ...(matched > sample.length\n ? {\n hint: `Showing first ${sample.length} of ${matched}. Use detail_level:\"full\" for all.`,\n }\n : {}),\n },\n );\n }\n\n return structuredResult(`${matched} node(s) under ${args.parent_path}${where}.`, {\n ...base,\n nodes,\n });\n },\n );\n}\n\nexport const registerGetTdNodes: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_nodes\",\n {\n title: \"List TouchDesigner nodes\",\n description:\n 'List the direct child nodes of a COMP. Defaults to a compact summary (count + type breakdown + sample paths); pass detail_level:\"full\" or path_only:true for the complete list, and `pattern` to filter by name.',\n inputSchema: getTdNodesSchema.shape,\n outputSchema: getTdNodesOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdNodesImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { checkPerformance } from \"../../feedback/performanceMonitor.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdPerformanceSchema = z.object({\n root_path: z.string().default(\"/project1\").describe(\"Network root to measure cook times under.\"),\n target_fps: z\n .number()\n .positive()\n .default(60)\n .describe(\"Frame-rate target used to flag slow nodes.\"),\n});\ntype GetTdPerformanceArgs = z.infer<typeof getTdPerformanceSchema>;\n\nexport const getTdPerformanceOutputSchema = z.object({\n path: z.string(),\n targetFps: z.number(),\n frameBudgetMs: z.number(),\n totalCookMs: z.number(),\n nodes: z.array(\n z.object({\n path: z.string(),\n cook_time_ms: z.number(),\n cook_count: z.number().optional(),\n }),\n ),\n warnings: z.array(z.string()),\n});\n\nexport async function getTdPerformanceImpl(ctx: ToolContext, args: GetTdPerformanceArgs) {\n return guardTd(\n () => checkPerformance(ctx.client, args.root_path, args.target_fps),\n (report) =>\n structuredResult(\n report.warnings.length === 0\n ? `Within budget: ${report.totalCookMs.toFixed(2)}ms total under ${args.root_path} (${args.target_fps}fps).`\n : `${report.warnings.length} performance warning(s) under ${args.root_path}.`,\n report,\n ),\n );\n}\n\nexport const registerGetTdPerformance: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_performance\",\n {\n title: \"Get network performance\",\n description:\n \"Report cook times under a network and warn about nodes that exceed the frame budget.\",\n inputSchema: getTdPerformanceSchema.shape,\n outputSchema: getTdPerformanceOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdPerformanceImpl(ctx, args),\n );\n};\n","import type { TouchDesignerClient } from \"../td-client/touchDesignerClient.js\";\n\nexport interface PerformanceReport {\n path: string;\n targetFps: number;\n frameBudgetMs: number;\n totalCookMs: number;\n nodes: Array<{ path: string; cook_time_ms: number; cook_count?: number }>;\n warnings: string[];\n}\n\n/** Reports cook times against the frame budget implied by `targetFps`. */\nexport async function checkPerformance(\n client: TouchDesignerClient,\n path: string,\n targetFps = 60,\n): Promise<PerformanceReport> {\n const perf = await client.getNetworkPerformance(path);\n const frameBudgetMs = 1000 / targetFps;\n const warnings: string[] = [];\n\n for (const node of perf.nodes) {\n if (node.cook_time_ms > frameBudgetMs) {\n warnings.push(\n `${node.path} cooks in ${node.cook_time_ms.toFixed(2)}ms, exceeding the ${frameBudgetMs.toFixed(2)}ms budget at ${targetFps}fps.`,\n );\n }\n }\n\n const totalCookMs =\n perf.total_cook_time_ms ?? perf.nodes.reduce((sum, node) => sum + node.cook_time_ms, 0);\n if (totalCookMs > frameBudgetMs) {\n warnings.push(\n `Total cook time ${totalCookMs.toFixed(2)}ms exceeds the ${frameBudgetMs.toFixed(2)}ms budget at ${targetFps}fps.`,\n );\n }\n\n return { path, targetFps, frameBudgetMs, totalCookMs, nodes: perf.nodes, warnings };\n}\n","import { z } from \"zod\";\nimport { verifyNetwork } from \"../../feedback/networkVerifier.js\";\nimport { TopologySchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdTopologySchema = z.object({\n root_path: z.string().default(\"/project1\").describe(\"Network root to map.\"),\n});\ntype GetTdTopologyArgs = z.infer<typeof getTdTopologySchema>;\n\nexport const getTdTopologyOutputSchema = z.object({\n path: z.string(),\n nodeCount: z.number(),\n connectionCount: z.number(),\n issues: z.array(z.string()),\n topology: TopologySchema,\n});\n\nexport async function getTdTopologyImpl(ctx: ToolContext, args: GetTdTopologyArgs) {\n return guardTd(\n () => verifyNetwork(ctx.client, args.root_path),\n (report) =>\n structuredResult(\n `${report.nodeCount} node(s), ${report.connectionCount} connection(s) under ${args.root_path}.`,\n report,\n ),\n );\n}\n\nexport const registerGetTdTopology: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_topology\",\n {\n title: \"Get network topology\",\n description:\n \"Return the nodes and connections under a network root, flagging obvious structural issues.\",\n inputSchema: getTdTopologySchema.shape,\n outputSchema: getTdTopologyOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdTopologyImpl(ctx, args),\n );\n};\n","import type { TouchDesignerClient } from \"../td-client/touchDesignerClient.js\";\nimport type { TdTopology } from \"../td-client/types.js\";\n\nexport interface VerifyReport {\n path: string;\n nodeCount: number;\n connectionCount: number;\n issues: string[];\n topology: TdTopology;\n}\n\n/** Inspects the topology under `path` and flags obvious structural issues. */\nexport async function verifyNetwork(\n client: TouchDesignerClient,\n path: string,\n): Promise<VerifyReport> {\n const topology = await client.getNetworkTopology(path);\n const issues: string[] = [];\n if (topology.nodes.length === 0) {\n issues.push(`No nodes were found under ${path}.`);\n } else if (topology.nodes.length > 1 && topology.connections.length === 0) {\n issues.push(\"Multiple nodes exist but none are connected.\");\n }\n return {\n path,\n nodeCount: topology.nodes.length,\n connectionCount: topology.connections.length,\n issues,\n topology,\n };\n}\n","import { z } from \"zod\";\nimport { verifyNetwork } from \"../../feedback/networkVerifier.js\";\nimport { ConnectionSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\n/** Cap on per-node parameter fetches so a big graph can't fan out into hundreds of requests. */\nconst MAX_PARAM_NODES = 60;\n\nexport const snapshotTdGraphSchema = z.object({\n path: z.string().default(\"/project1\").describe(\"Network root to snapshot.\"),\n include_params: z\n .boolean()\n .default(false)\n .describe(\"Also fetch each node's parameters (one request per node; capped for large graphs).\"),\n});\ntype SnapshotTdGraphArgs = z.infer<typeof snapshotTdGraphSchema>;\n\nexport const snapshotTdGraphOutputSchema = z.object({\n path: z.string(),\n nodeCount: z.number(),\n connectionCount: z.number(),\n issues: z.array(z.string()),\n params_truncated: z.boolean(),\n nodes: z.array(\n z.object({\n path: z.string(),\n type: z.string(),\n name: z.string(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n }),\n ),\n connections: z.array(ConnectionSchema),\n});\n\nexport async function snapshotTdGraphImpl(ctx: ToolContext, args: SnapshotTdGraphArgs) {\n return guardTd(\n async () => {\n const report = await verifyNetwork(ctx.client, args.path);\n const refs = report.topology.nodes;\n let paramsTruncated = false;\n const params = new Map<string, Record<string, unknown>>();\n if (args.include_params) {\n const targets = refs.slice(0, MAX_PARAM_NODES);\n paramsTruncated = refs.length > MAX_PARAM_NODES;\n // Fail-forward: one unreadable node shouldn't sink the whole snapshot.\n const details = await Promise.allSettled(targets.map((n) => ctx.client.getNode(n.path)));\n for (const detail of details) {\n if (detail.status === \"fulfilled\") params.set(detail.value.path, detail.value.parameters);\n }\n }\n const nodes = refs.map((n) => ({\n path: n.path,\n type: n.type,\n name: n.name,\n ...(args.include_params ? { parameters: params.get(n.path) ?? {} } : {}),\n }));\n return { report, nodes, paramsTruncated };\n },\n ({ report, nodes, paramsTruncated }) =>\n structuredResult(\n `Snapshot of ${args.path}: ${report.nodeCount} node(s), ${report.connectionCount} connection(s)${report.issues.length ? `, ${report.issues.length} issue(s)` : \"\"}.`,\n {\n path: report.path,\n nodeCount: report.nodeCount,\n connectionCount: report.connectionCount,\n issues: report.issues,\n params_truncated: paramsTruncated,\n nodes,\n connections: report.topology.connections,\n },\n ),\n );\n}\n\nexport const registerSnapshotTdGraph: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"snapshot_td_graph\",\n {\n title: \"Snapshot network graph\",\n description:\n \"Capture a compact, serializable snapshot of a network — nodes, connections, structural issues, and optionally each node's parameters — for review, diffing, or documentation.\",\n inputSchema: snapshotTdGraphSchema.shape,\n outputSchema: snapshotTdGraphOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => snapshotTdGraphImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\nimport { parentOf } from \"./nodeMatch.js\";\n\nexport const summarizeTdErrorsSchema = z.object({\n path: z.string().default(\"/project1\").describe(\"Network root to collect errors under.\"),\n group_by: z\n .enum([\"message\", \"type\", \"parent\"])\n .default(\"message\")\n .describe(\n \"How to cluster errors: by exact message, by error type, or by parent container (to find a common upstream cause).\",\n ),\n});\ntype SummarizeTdErrorsArgs = z.infer<typeof summarizeTdErrorsSchema>;\n\nexport const summarizeTdErrorsOutputSchema = z.object({\n path: z.string(),\n total: z.number(),\n group_by: z.enum([\"message\", \"type\", \"parent\"]),\n groups: z.array(\n z.object({\n key: z.string(),\n count: z.number(),\n sample: z.object({ path: z.string(), message: z.string() }),\n }),\n ),\n suggestions: z.array(z.string()),\n});\n\nexport async function summarizeTdErrorsImpl(ctx: ToolContext, args: SummarizeTdErrorsArgs) {\n return guardTd(\n () => ctx.client.getNetworkErrors(args.path),\n (result) => {\n const errors = result.errors;\n const total = errors.length;\n if (total === 0) {\n return structuredResult(`No errors found under ${args.path}.`, {\n path: args.path,\n total: 0,\n group_by: args.group_by,\n groups: [],\n suggestions: [],\n });\n }\n\n const keyOf = (e: { path: string; message: string; type?: string }): string =>\n args.group_by === \"message\"\n ? e.message\n : args.group_by === \"type\"\n ? e.type || \"error\"\n : parentOf(e.path);\n\n const grouped = new Map<\n string,\n { count: number; sample: { path: string; message: string } }\n >();\n const byPath = new Map<string, number>();\n for (const e of errors) {\n const key = keyOf(e);\n const g = grouped.get(key);\n if (g) g.count += 1;\n else grouped.set(key, { count: 1, sample: { path: e.path, message: e.message } });\n byPath.set(e.path, (byPath.get(e.path) ?? 0) + 1);\n }\n\n const groups = [...grouped.entries()]\n .map(([key, g]) => ({ key, count: g.count, sample: g.sample }))\n .sort((a, b) => b.count - a.count);\n\n const worstNodes = [...byPath.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 3)\n .map(([p, c]) => `${p} (${c} error${c === 1 ? \"\" : \"s\"})`);\n\n const suggestions: string[] = [];\n if (groups[0] && groups[0].count > 1) {\n suggestions.push(\n `${groups[0].count} errors share ${args.group_by} \"${groups[0].key}\" — fixing the common cause clears them at once.`,\n );\n }\n if (worstNodes.length > 0) {\n suggestions.push(`Check first: ${worstNodes.join(\", \")}.`);\n }\n\n return structuredResult(\n `${total} error(s) under ${args.path} in ${groups.length} ${args.group_by} group(s).`,\n { path: args.path, total, group_by: args.group_by, groups, suggestions },\n );\n },\n );\n}\n\nexport const registerSummarizeTdErrors: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"summarize_td_errors\",\n {\n title: \"Summarize network errors\",\n description:\n \"Collect errors across a network and cluster them by message, type, or parent container, with the worst-offending nodes and a suggested order to investigate. Use this instead of reading every node's errors one by one.\",\n inputSchema: summarizeTdErrorsSchema.shape,\n outputSchema: summarizeTdErrorsOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => summarizeTdErrorsImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const updateTdNodeParametersSchema = z.object({\n path: z.string().describe(\"Full path of the node whose parameters to update.\"),\n parameters: z\n .record(z.string(), z.unknown())\n .describe(\"Parameter overrides as key→value pairs, e.g. { period: 4, amplitude: 0.5 }.\"),\n});\ntype UpdateTdNodeParametersArgs = z.infer<typeof updateTdNodeParametersSchema>;\n\nexport async function updateTdNodeParametersImpl(\n ctx: ToolContext,\n args: UpdateTdNodeParametersArgs,\n) {\n return guardTd(\n () => ctx.client.updateNodeParameters(args.path, args.parameters),\n (node) =>\n jsonResult(`Updated ${Object.keys(args.parameters).length} parameter(s) on ${node.path}.`, {\n node,\n }),\n );\n}\n\nexport const registerUpdateTdNodeParameters: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"update_td_node_parameters\",\n {\n title: \"Update node parameters\",\n description: \"Set one or more parameters on an existing node.\",\n inputSchema: updateTdNodeParametersSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },\n },\n (args) => updateTdNodeParametersImpl(ctx, args),\n );\n};\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAE1B,SAAS,KAAAA,WAAS;;;ACHlB,SAAS,cAAAC,aAAY,aAAa,oBAAoB;AACtD,SAAS,YAAY;;;ACCrB,IAAM,SAAmC;AAAA,EACvC,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AACV;AAaO,SAAS,aAAa,QAAkB,QAAgB;AAC7D,QAAM,YAAY,OAAO,KAAK;AAE9B,QAAM,OAAO,CACX,KACA,SACA,SACG;AACH,QAAI,OAAO,GAAG,IAAI,UAAW;AAC7B,UAAM,SAAQ,oBAAI,KAAK,GAAE,YAAY;AACrC,UAAM,SAAS,QAAQ,OAAO,KAAK,IAAI,EAAE,SAAS,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK;AACnF,YAAQ,OAAO,MAAM,WAAW,KAAK,IAAI,IAAI,YAAY,CAAC,IAAI,OAAO,GAAG,MAAM;AAAA,CAAI;AAAA,EACpF;AAEA,SAAO;AAAA,IACL,OAAO,CAAC,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI;AAAA,IACrD,MAAM,CAAC,SAAS,SAAS,KAAK,QAAQ,SAAS,IAAI;AAAA,IACnD,MAAM,CAAC,SAAS,SAAS,KAAK,QAAQ,SAAS,IAAI;AAAA,IACnD,OAAO,CAAC,SAAS,SAAS,KAAK,SAAS,SAAS,I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IAAM,kBACJ,QAAQ,KAAK,CAAC,MAAM,UAAa,YAAY,QAAQ,cAAc,QAAQ,KAAK,CAAC,CAAC,EAAE;AACtF,IAAI,gBAAiB,MAAK,KAAK;","names":["z","existsSync","existsSync","existsSync","readdirSync","readFileSync","join","existsSync","readdirSync","readFileSync","join","r","z","z","z","z","z","z","z","z","z","z","z","z","z","z","fetch","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","cmd"]}
1
+ {"version":3,"sources":["../../src/cli/agent.ts","../../src/knowledge/index.ts","../../src/utils/logger.ts","../../src/utils/paths.ts","../../src/knowledge/normalize.ts","../../src/recipes/loader.ts","../../src/recipes/schema.ts","../../src/tools/layer2/createControlPanel.ts","../../src/td-client/types.ts","../../src/tools/result.ts","../../src/td-client/validators.ts","../../src/td-client/touchDesignerClient.ts","../../src/utils/config.ts","../../src/server/connectionManager.ts","../../src/server/context.ts","../../src/tools/layer3/compareTdNodes.ts","../../src/tools/layer3/createTdNode.ts","../../src/tools/layer3/deleteTdNode.ts","../../src/tools/layer3/execNodeMethod.ts","../../src/tools/layer3/executePythonScript.ts","../../src/tools/layer3/findTdNodes.ts","../../src/tools/layer3/nodeMatch.ts","../../src/tools/layer3/getModuleHelp.ts","../../src/tools/layer3/getTdClassDetails.ts","../../src/tools/layer3/getTdClasses.ts","../../src/tools/layer3/getTdInfo.ts","../../src/tools/layer3/getTdNodeErrors.ts","../../src/tools/layer3/getTdNodeParameters.ts","../../src/tools/layer3/getTdNodes.ts","../../src/tools/layer3/getTdPerformance.ts","../../src/feedback/performanceMonitor.ts","../../src/tools/layer3/getTdTopology.ts","../../src/feedback/networkVerifier.ts","../../src/tools/layer3/snapshotTdGraph.ts","../../src/tools/layer3/summarizeTdErrors.ts","../../src/tools/layer3/updateTdNodeParameters.ts"],"sourcesContent":["import { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { buildToolContext } from \"../server/context.js\";\nimport { compareTdNodesImpl, compareTdNodesSchema } from \"../tools/layer3/compareTdNodes.js\";\nimport { createTdNodeImpl, createTdNodeSchema } from \"../tools/layer3/createTdNode.js\";\nimport { deleteTdNodeImpl, deleteTdNodeSchema } from \"../tools/layer3/deleteTdNode.js\";\nimport { execNodeMethodImpl, execNodeMethodSchema } from \"../tools/layer3/execNodeMethod.js\";\nimport {\n executePythonScriptImpl,\n executePythonScriptSchema,\n} from \"../tools/layer3/executePythonScript.js\";\nimport { findTdNodesImpl, findTdNodesSchema } from \"../tools/layer3/findTdNodes.js\";\nimport { getModuleHelpImpl, getModuleHelpSchema } from \"../tools/layer3/getModuleHelp.js\";\nimport {\n getTdClassDetailsImpl,\n getTdClassDetailsSchema,\n} from \"../tools/layer3/getTdClassDetails.js\";\nimport { getTdClassesImpl, getTdClassesSchema } from \"../tools/layer3/getTdClasses.js\";\nimport { getTdInfoImpl } from \"../tools/layer3/getTdInfo.js\";\nimport { getTdNodeErrorsImpl, getTdNodeErrorsSchema } from \"../tools/layer3/getTdNodeErrors.js\";\nimport {\n getTdNodeParametersImpl,\n getTdNodeParametersSchema,\n} from \"../tools/layer3/getTdNodeParameters.js\";\nimport { getTdNodesImpl, getTdNodesSchema } from \"../tools/layer3/getTdNodes.js\";\nimport { getTdPerformanceImpl, getTdPerformanceSchema } from \"../tools/layer3/getTdPerformance.js\";\nimport { getTdTopologyImpl, getTdTopologySchema } from \"../tools/layer3/getTdTopology.js\";\nimport { snapshotTdGraphImpl, snapshotTdGraphSchema } from \"../tools/layer3/snapshotTdGraph.js\";\nimport {\n summarizeTdErrorsImpl,\n summarizeTdErrorsSchema,\n} from \"../tools/layer3/summarizeTdErrors.js\";\nimport {\n updateTdNodeParametersImpl,\n updateTdNodeParametersSchema,\n} from \"../tools/layer3/updateTdNodeParameters.js\";\nimport type { ToolContext } from \"../tools/types.js\";\nimport { loadConfig } from \"../utils/config.js\";\nimport { silentLogger } from \"../utils/logger.js\";\n\n// biome-ignore lint/suspicious/noExplicitAny: args are validated by each command's zod schema before use.\ntype Runner = (ctx: ToolContext, args: any) => CallToolResult | Promise<CallToolResult>;\n\ninterface Command {\n schema: z.ZodTypeAny;\n run: Runner;\n summary: string;\n mutates: boolean;\n unsafe: boolean;\n}\n\nconst r = (\n schema: z.ZodTypeAny,\n run: Runner,\n summary: string,\n opts: { mutates?: boolean; unsafe?: boolean } = {},\n): Command => ({ schema, run, summary, mutates: !!opts.mutates, unsafe: !!opts.unsafe });\n\n/** Static command tree — each entry maps 1:1 onto an existing MCP tool handler. */\nconst COMMANDS: Record<string, Command> = {\n info: r(z.object({}), (ctx) => getTdInfoImpl(ctx), \"Health check + TD/bridge info.\"),\n \"nodes list\": r(\n getTdNodesSchema,\n getTdNodesImpl,\n \"List a COMP's child nodes (summary by default).\",\n ),\n \"nodes find\": r(findTdNodesSchema, findTdNodesImpl, \"Search nodes by name pattern and/or type.\"),\n \"nodes get\": r(getTdNodeParametersSchema, getTdNodeParametersImpl, \"Read a node's parameters.\"),\n \"nodes errors\": r(getTdNodeErrorsSchema, getTdNodeErrorsImpl, \"Check a node/network for errors.\"),\n \"nodes compare\": r(compareTdNodesSchema, compareTdNodesImpl, \"Diff two nodes' parameters.\"),\n \"nodes snapshot\": r(snapshotTdGraphSchema, snapshotTdGraphImpl, \"Capture a network snapshot.\"),\n \"nodes topology\": r(getTdTopologySchema, getTdTopologyImpl, \"Map nodes + connections.\"),\n \"nodes performance\": r(getTdPerformanceSchema, getTdPerformanceImpl, \"Report cook times.\"),\n \"nodes update\": r(\n updateTdNodeParametersSchema,\n updateTdNodeParametersImpl,\n \"Set node parameters.\",\n { mutates: true },\n ),\n \"nodes create\": r(createTdNodeSchema, createTdNodeImpl, \"Create an operator.\", { mutates: true }),\n \"nodes delete\": r(deleteTdNodeSchema, deleteTdNodeImpl, \"Delete a node.\", { mutates: true }),\n \"errors summarize\": r(\n summarizeTdErrorsSchema,\n summarizeTdErrorsImpl,\n \"Cluster network errors by cause.\",\n ),\n \"classes list\": r(getTdClassesSchema, getTdClassesImpl, \"List TD Python API classes (offline).\"),\n \"classes get\": r(\n getTdClassDetailsSchema,\n getTdClassDetailsImpl,\n \"Get one Python class (offline).\",\n ),\n \"module help\": r(\n getModuleHelpSchema,\n getModuleHelpImpl,\n \"Human-readable help for a class (offline).\",\n ),\n \"exec python\": r(\n executePythonScriptSchema,\n executePythonScriptImpl,\n \"Escape hatch: run arbitrary Python in TD.\",\n { mutates: true, unsafe: true },\n ),\n \"exec node-method\": r(\n execNodeMethodSchema,\n execNodeMethodImpl,\n \"Escape hatch: call a Python method on a node.\",\n { mutates: true, unsafe: true },\n ),\n};\n\nexport interface CliResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\nfunction textOf(result: CallToolResult): string {\n return result.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n}\n\n/** Prefer the structured channel; fall back to a JSON code-fence, then to the raw text. */\nfunction extractData(result: CallToolResult): unknown {\n if (result.structuredContent !== undefined) return result.structuredContent;\n const text = textOf(result);\n const fence = text.match(/```json\\n([\\s\\S]*?)\\n```/);\n if (fence) {\n try {\n return JSON.parse(fence[1] as string);\n } catch {\n // fall through\n }\n }\n return { message: text };\n}\n\nfunction firstArray(data: unknown): unknown[] | null {\n if (Array.isArray(data)) return data;\n if (data && typeof data === \"object\") {\n for (const value of Object.values(data)) if (Array.isArray(value)) return value;\n }\n return null;\n}\n\nfunction resolveCommand(positionals: string[]): { key: string; cmd: Command } | undefined {\n const key2 = positionals.slice(0, 2).join(\" \");\n if (COMMANDS[key2]) return { key: key2, cmd: COMMANDS[key2] };\n const key1 = positionals[0] ?? \"\";\n if (COMMANDS[key1]) return { key: key1, cmd: COMMANDS[key1] };\n return undefined;\n}\n\nfunction usage(): string {\n const lines = [\"tdmcp-agent — drive TouchDesigner from a shell (machine-readable output).\", \"\"];\n lines.push(\"Usage: tdmcp-agent <command> [--params '<json>'] [--json '<json>'] [flags]\", \"\");\n lines.push(\"Flags:\");\n lines.push(\n \" --params <json> Arguments object (validated against the command's input schema).\",\n );\n lines.push(\" --json <json> Merged into --params (e.g. for request bodies).\");\n lines.push(\" --output <fmt> json (default) | ndjson | text.\");\n lines.push(\" --dry-run Validate and print the intended call without executing.\");\n lines.push(\" --allow-unsafe Required for `exec` escape-hatch commands.\");\n lines.push(\" -h, --help Show this help.\", \"\");\n lines.push(\"Commands:\");\n for (const [key, cmd] of Object.entries(COMMANDS)) {\n const tags = [cmd.mutates ? \"mutates\" : \"\", cmd.unsafe ? \"unsafe\" : \"\"]\n .filter(Boolean)\n .join(\",\");\n lines.push(` ${key.padEnd(20)} ${cmd.summary}${tags ? ` [${tags}]` : \"\"}`);\n }\n lines.push(\" schema <command> Print a command's JSON Schema and metadata.\");\n return lines.join(\"\\n\");\n}\n\nexport interface RunCliOptions {\n /** Inject a context (used by tests); production builds one from env config. */\n makeCtx?: () => ToolContext;\n}\n\nfunction parseCliArgs(argv: string[]) {\n return parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n params: { type: \"string\" },\n json: { type: \"string\" },\n output: { type: \"string\", default: \"json\" },\n \"dry-run\": { type: \"boolean\", default: false },\n \"allow-unsafe\": { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n });\n}\n\nexport async function runCli(argv: string[], opts: RunCliOptions = {}): Promise<CliResult> {\n let parsed: ReturnType<typeof parseCliArgs>;\n try {\n parsed = parseCliArgs(argv);\n } catch (err) {\n return { stdout: \"\", stderr: `${(err as Error).message}\\n`, code: 2 };\n }\n\n const { values, positionals } = parsed;\n if (values.help || positionals.length === 0) {\n return { stdout: `${usage()}\\n`, stderr: \"\", code: 0 };\n }\n\n // `schema <command>` — emit the input contract without touching TD.\n if (positionals[0] === \"schema\") {\n const target = positionals.slice(1).join(\" \");\n const cmd = COMMANDS[target];\n if (!cmd) return { stdout: \"\", stderr: `Unknown command for schema: \"${target}\".\\n`, code: 2 };\n const doc = {\n command: target,\n summary: cmd.summary,\n mutates: cmd.mutates,\n unsafe: cmd.unsafe,\n input: z.toJSONSchema(cmd.schema),\n };\n return { stdout: `${JSON.stringify(doc, null, 2)}\\n`, stderr: \"\", code: 0 };\n }\n\n const resolved = resolveCommand(positionals);\n if (!resolved) {\n return {\n stdout: \"\",\n stderr: `Unknown command: \"${positionals.join(\" \")}\". Run with --help.\\n`,\n code: 2,\n };\n }\n const { key, cmd } = resolved;\n\n const raw: Record<string, unknown> = {};\n try {\n if (typeof values.params === \"string\") Object.assign(raw, JSON.parse(values.params));\n if (typeof values.json === \"string\") Object.assign(raw, JSON.parse(values.json));\n } catch (err) {\n return {\n stdout: \"\",\n stderr: `Invalid JSON in --params/--json: ${(err as Error).message}\\n`,\n code: 2,\n };\n }\n\n const args = cmd.schema.safeParse(raw);\n if (!args.success) {\n return {\n stdout: \"\",\n stderr: `Invalid arguments for \"${key}\": ${args.error.message}\\n`,\n code: 2,\n };\n }\n\n if (values[\"dry-run\"]) {\n const doc = {\n dryRun: true,\n command: key,\n mutates: cmd.mutates,\n unsafe: cmd.unsafe,\n args: args.data,\n };\n return { stdout: `${JSON.stringify(doc, null, 2)}\\n`, stderr: \"\", code: 0 };\n }\n\n const ctx = opts.makeCtx\n ? opts.makeCtx()\n : buildToolContext(loadConfig(), { logger: silentLogger });\n\n if (cmd.unsafe) {\n if (ctx.allowRawPython === false) {\n return { stdout: \"\", stderr: `\"${key}\" is disabled (TDMCP_RAW_PYTHON=off).\\n`, code: 2 };\n }\n if (!values[\"allow-unsafe\"]) {\n return {\n stdout: \"\",\n stderr: `\"${key}\" is an escape hatch. Re-run with --allow-unsafe to execute.\\n`,\n code: 2,\n };\n }\n }\n\n const result = await cmd.run(ctx, args.data);\n const summary = textOf(result).split(\"\\n\")[0] ?? \"\";\n if (result.isError) return { stdout: \"\", stderr: `${textOf(result)}\\n`, code: 1 };\n\n const output = String(values.output);\n const data = extractData(result);\n if (output === \"text\") return { stdout: `${textOf(result)}\\n`, stderr: \"\", code: 0 };\n if (output === \"ndjson\") {\n const arr = firstArray(data);\n const body = arr ? arr.map((item) => JSON.stringify(item)).join(\"\\n\") : JSON.stringify(data);\n return { stdout: `${body}\\n`, stderr: summary ? `${summary}\\n` : \"\", code: 0 };\n }\n return {\n stdout: `${JSON.stringify(data, null, 2)}\\n`,\n stderr: summary ? `${summary}\\n` : \"\",\n code: 0,\n };\n}\n\nasync function main(): Promise<void> {\n const result = await runCli(process.argv.slice(2));\n if (result.stdout) process.stdout.write(result.stdout);\n if (result.stderr) process.stderr.write(result.stderr);\n process.exitCode = result.code;\n}\n\nconst invokedDirectly =\n process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;\nif (invokedDirectly) void main();\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { type Logger, silentLogger } from \"../utils/logger.js\";\nimport { bottobotPackageDir, knowledgeDataDir } from \"../utils/paths.js\";\nimport {\n compactKey,\n normalizeGlsl,\n normalizePatterns,\n slugify,\n toOperatorSummary,\n toPythonSummary,\n toTutorialSummary,\n} from \"./normalize.js\";\nimport type {\n GlslSummary,\n GlslTechnique,\n KnowledgeStats,\n OperatorDoc,\n OperatorSummary,\n Pattern,\n PatternSummary,\n PythonClass,\n PythonClassSummary,\n Tutorial,\n TutorialSummary,\n} from \"./types.js\";\n\nexport interface KnowledgeBaseOptions {\n dataDir?: string;\n logger?: Logger;\n}\n\ninterface ResolvedSource {\n kind: \"local\" | \"bottobot\" | \"empty\";\n operatorsDir: string;\n operatorsIndex?: string;\n pythonDir: string;\n tutorialsDir: string;\n patternsFile: string;\n glslFile: string;\n}\n\nconst EMPTY_SOURCE: ResolvedSource = {\n kind: \"empty\",\n operatorsDir: \"\",\n pythonDir: \"\",\n tutorialsDir: \"\",\n patternsFile: \"\",\n glslFile: \"\",\n};\n\n/**\n * Read-only accessor over the embedded TouchDesigner knowledge base. Prefers the\n * imported local data directory; falls back to reading directly from an installed\n * `@bottobot/td-mcp`; otherwise degrades to empty results (never throws on lookup).\n */\nexport class KnowledgeBase {\n private readonly logger: Logger;\n private readonly source: ResolvedSource;\n\n private opIndexCache?: OperatorSummary[];\n private opLookupCache?: Map<string, string>;\n private readonly opDocCache = new Map<string, OperatorDoc | null>();\n private pyIndexCache?: PythonClassSummary[];\n private pyLookupCache?: Map<string, string>;\n private readonly pyDocCache = new Map<string, PythonClass | null>();\n private tutIndexCache?: TutorialSummary[];\n private tutLookupCache?: Map<string, string>;\n private readonly tutDocCache = new Map<string, Tutorial | null>();\n private patternsCache?: Pattern[];\n private glslCache?: GlslTechnique[];\n\n constructor(options: KnowledgeBaseOptions = {}) {\n this.logger = options.logger ?? silentLogger;\n this.source = KnowledgeBase.resolveSource(options.dataDir ?? knowledgeDataDir());\n this.logger.debug(\"knowledge source resolved\", { kind: this.source.kind });\n }\n\n private static resolveSource(localDir: string): ResolvedSource {\n if (existsSync(join(localDir, \"operators\"))) {\n return {\n kind: \"local\",\n operatorsDir: join(localDir, \"operators\"),\n operatorsIndex: join(localDir, \"operators\", \"index.json\"),\n pythonDir: join(localDir, \"python-api\"),\n tutorialsDir: join(localDir, \"tutorials\"),\n patternsFile: join(localDir, \"patterns.json\"),\n glslFile: join(localDir, \"glsl.json\"),\n };\n }\n const bb = bottobotPackageDir();\n if (bb) {\n return {\n kind: \"bottobot\",\n operatorsDir: join(bb, \"wiki/data/processed\"),\n pythonDir: join(bb, \"wiki/data/python-api\"),\n tutorialsDir: join(bb, \"wiki/data/tutorials\"),\n patternsFile: join(bb, \"data/patterns.json\"),\n glslFile: join(bb, \"wiki/data/experimental/glsl.json\"),\n };\n }\n return EMPTY_SOURCE;\n }\n\n private readJson(path: string): unknown {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch (err) {\n this.logger.debug(\"knowledge readJson failed\", { path, error: String(err) });\n return undefined;\n }\n }\n\n private listJsonFiles(dir: string): string[] {\n if (!dir || !existsSync(dir)) return [];\n try {\n return readdirSync(dir).filter((f) => f.endsWith(\".json\") && f !== \"index.json\");\n } catch {\n return [];\n }\n }\n\n // ---- Operators -----------------------------------------------------------\n\n private operatorIndex(): OperatorSummary[] {\n if (this.opIndexCache) return this.opIndexCache;\n if (this.source.kind === \"empty\") {\n this.opIndexCache = [];\n return this.opIndexCache;\n }\n if (this.source.operatorsIndex && existsSync(this.source.operatorsIndex)) {\n const data = this.readJson(this.source.operatorsIndex);\n if (Array.isArray(data)) {\n this.opIndexCache = data as OperatorSummary[];\n return this.opIndexCache;\n }\n }\n const summaries: OperatorSummary[] = [];\n for (const file of this.listJsonFiles(this.source.operatorsDir)) {\n const doc = this.readJson(join(this.source.operatorsDir, file)) as OperatorDoc | undefined;\n if (doc?.name) summaries.push(toOperatorSummary(file.replace(/\\.json$/, \"\"), doc));\n }\n this.opIndexCache = summaries;\n return this.opIndexCache;\n }\n\n private operatorLookup(): Map<string, string> {\n if (this.opLookupCache) return this.opLookupCache;\n const map = new Map<string, string>();\n for (const summary of this.operatorIndex()) {\n map.set(compactKey(summary.slug), summary.slug);\n map.set(compactKey(summary.name), summary.slug);\n map.set(compactKey(summary.displayName), summary.slug);\n }\n this.opLookupCache = map;\n return map;\n }\n\n listOperatorCategories(): string[] {\n const set = new Set<string>();\n for (const summary of this.operatorIndex()) set.add(summary.category);\n return [...set].sort();\n }\n\n listOperators(category?: string): OperatorSummary[] {\n const all = this.operatorIndex();\n if (!category) return all;\n const wanted = compactKey(category);\n return all.filter((s) => compactKey(s.category) === wanted);\n }\n\n getOperator(nameOrSlug: string): OperatorDoc | undefined {\n if (this.source.kind === \"empty\") return undefined;\n const slug = this.operatorLookup().get(compactKey(nameOrSlug)) ?? slugify(nameOrSlug);\n const cached = this.opDocCache.get(slug);\n if (cached !== undefined) return cached ?? undefined;\n const file = join(this.source.operatorsDir, `${slug}.json`);\n const doc = existsSync(file) ? (this.readJson(file) as OperatorDoc | undefined) : undefined;\n this.opDocCache.set(slug, doc ?? null);\n return doc;\n }\n\n /** Soft existence check (by operator type, display name, or slug). */\n operatorExists(typeOrName: string): boolean {\n return this.operatorLookup().has(compactKey(typeOrName));\n }\n\n searchOperators(query: string, limit = 25): OperatorSummary[] {\n const q = query.trim().toLowerCase();\n if (!q) return [];\n const terms = q.split(/\\s+/);\n const scored: Array<{ summary: OperatorSummary; score: number }> = [];\n for (const summary of this.operatorIndex()) {\n const haystack =\n `${summary.name} ${summary.displayName} ${summary.summary} ${summary.keywords.join(\" \")}`.toLowerCase();\n let score = 0;\n for (const term of terms) {\n if (haystack.includes(term)) score += 1;\n if (summary.name.toLowerCase().includes(term)) score += 1;\n }\n if (score > 0) scored.push({ summary, score });\n }\n scored.sort((a, b) => b.score - a.score);\n return scored.slice(0, limit).map((s) => s.summary);\n }\n\n // ---- Python API ----------------------------------------------------------\n\n private pythonIndex(): PythonClassSummary[] {\n if (this.pyIndexCache) return this.pyIndexCache;\n if (this.source.kind === \"empty\") {\n this.pyIndexCache = [];\n return this.pyIndexCache;\n }\n const indexPath = join(this.source.pythonDir, \"index.json\");\n if (existsSync(indexPath)) {\n const data = this.readJson(indexPath);\n if (Array.isArray(data)) {\n this.pyIndexCache = data as PythonClassSummary[];\n return this.pyIndexCache;\n }\n }\n const summaries: PythonClassSummary[] = [];\n for (const file of this.listJsonFiles(this.source.pythonDir)) {\n const cls = this.readJson(join(this.source.pythonDir, file)) as PythonClass | undefined;\n if (cls?.className) summaries.push(toPythonSummary(cls));\n }\n this.pyIndexCache = summaries;\n return this.pyIndexCache;\n }\n\n private pythonLookup(): Map<string, string> {\n if (this.pyLookupCache) return this.pyLookupCache;\n const map = new Map<string, string>();\n for (const summary of this.pythonIndex()) {\n map.set(compactKey(summary.className), summary.className);\n map.set(compactKey(summary.displayName), summary.className);\n }\n this.pyLookupCache = map;\n return map;\n }\n\n listPythonClasses(): PythonClassSummary[] {\n return this.pythonIndex();\n }\n\n getPythonClass(name: string): PythonClass | undefined {\n if (this.source.kind === \"empty\") return undefined;\n const className = this.pythonLookup().get(compactKey(name)) ?? name;\n const cached = this.pyDocCache.get(className);\n if (cached !== undefined) return cached ?? undefined;\n const file = join(this.source.pythonDir, `${className}.json`);\n const cls = existsSync(file) ? (this.readJson(file) as PythonClass | undefined) : undefined;\n this.pyDocCache.set(className, cls ?? null);\n return cls;\n }\n\n // ---- Patterns ------------------------------------------------------------\n\n private patterns(): Pattern[] {\n if (this.patternsCache) return this.patternsCache;\n if (this.source.kind === \"empty\") {\n this.patternsCache = [];\n return this.patternsCache;\n }\n const data = this.readJson(this.source.patternsFile);\n if (Array.isArray(data) && data.length > 0 && typeof (data[0] as Pattern).id === \"string\") {\n this.patternsCache = data as Pattern[];\n } else {\n this.patternsCache = normalizePatterns(data);\n }\n return this.patternsCache;\n }\n\n listPatterns(): PatternSummary[] {\n return this.patterns().map((p) => ({\n id: p.id,\n name: p.name,\n category: p.category ?? \"Unknown\",\n description: p.description ?? \"\",\n }));\n }\n\n getPattern(name: string): Pattern | undefined {\n const key = compactKey(name);\n return this.patterns().find((p) => compactKey(p.id) === key || compactKey(p.name) === key);\n }\n\n // ---- GLSL ----------------------------------------------------------------\n\n private glsl(): GlslTechnique[] {\n if (this.glslCache) return this.glslCache;\n if (this.source.kind === \"empty\") {\n this.glslCache = [];\n return this.glslCache;\n }\n const data = this.readJson(this.source.glslFile);\n this.glslCache = Array.isArray(data) ? (data as GlslTechnique[]) : normalizeGlsl(data);\n return this.glslCache;\n }\n\n listGlslPatterns(): GlslSummary[] {\n return this.glsl().map((g) => ({\n id: g.id,\n name: g.name,\n description: g.description ?? \"\",\n difficulty: g.difficulty ?? \"unknown\",\n }));\n }\n\n getGlslPattern(name: string): GlslTechnique | undefined {\n const key = compactKey(name);\n return this.glsl().find((g) => compactKey(g.id) === key || compactKey(g.name) === key);\n }\n\n // ---- Tutorials -----------------------------------------------------------\n\n private tutorialIndex(): TutorialSummary[] {\n if (this.tutIndexCache) return this.tutIndexCache;\n if (this.source.kind === \"empty\") {\n this.tutIndexCache = [];\n return this.tutIndexCache;\n }\n const indexPath = join(this.source.tutorialsDir, \"index.json\");\n if (existsSync(indexPath)) {\n const data = this.readJson(indexPath);\n if (Array.isArray(data)) {\n this.tutIndexCache = data as TutorialSummary[];\n return this.tutIndexCache;\n }\n }\n const summaries: TutorialSummary[] = [];\n for (const file of this.listJsonFiles(this.source.tutorialsDir)) {\n const tut = this.readJson(join(this.source.tutorialsDir, file)) as Tutorial | undefined;\n if (tut?.id || tut?.name) {\n const normalized: Tutorial = {\n ...tut,\n id: tut.id ?? file.replace(/\\.json$/, \"\"),\n name: tut.name ?? file,\n };\n summaries.push(toTutorialSummary(normalized));\n }\n }\n this.tutIndexCache = summaries;\n return this.tutIndexCache;\n }\n\n private tutorialLookup(): Map<string, string> {\n if (this.tutLookupCache) return this.tutLookupCache;\n const map = new Map<string, string>();\n for (const file of this.listJsonFiles(this.source.tutorialsDir)) {\n const slug = file.replace(/\\.json$/, \"\");\n map.set(compactKey(slug), slug);\n }\n for (const summary of this.tutorialIndex()) {\n map.set(compactKey(summary.id), summary.id);\n map.set(compactKey(summary.name), summary.id);\n }\n this.tutLookupCache = map;\n return map;\n }\n\n listTutorials(): TutorialSummary[] {\n return this.tutorialIndex();\n }\n\n getTutorial(name: string): Tutorial | undefined {\n if (this.source.kind === \"empty\") return undefined;\n const slug = this.tutorialLookup().get(compactKey(name)) ?? slugify(name);\n const cached = this.tutDocCache.get(slug);\n if (cached !== undefined) return cached ?? undefined;\n const file = join(this.source.tutorialsDir, `${slug}.json`);\n const tut = existsSync(file) ? (this.readJson(file) as Tutorial | undefined) : undefined;\n this.tutDocCache.set(slug, tut ?? null);\n return tut;\n }\n\n // ---- Meta ----------------------------------------------------------------\n\n get sourceKind(): KnowledgeStats[\"source\"] {\n return this.source.kind;\n }\n\n stats(): KnowledgeStats {\n return {\n source: this.source.kind,\n operators: this.operatorIndex().length,\n pythonClasses: this.pythonIndex().length,\n patterns: this.patterns().length,\n glsl: this.glsl().length,\n tutorials: this.tutorialIndex().length,\n };\n }\n}\n","export type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\nconst LEVELS: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n silent: 99,\n};\n\nexport interface Logger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Creates a leveled logger. All output goes to **stderr** so that stdout stays\n * reserved for the MCP stdio protocol stream.\n */\nexport function createLogger(level: LogLevel = \"info\"): Logger {\n const threshold = LEVELS[level];\n\n const emit = (\n lvl: Exclude<LogLevel, \"silent\">,\n message: string,\n meta?: Record<string, unknown>,\n ) => {\n if (LEVELS[lvl] < threshold) return;\n const stamp = new Date().toISOString();\n const suffix = meta && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : \"\";\n process.stderr.write(`[tdmcp] ${stamp} ${lvl.toUpperCase()} ${message}${suffix}\\n`);\n };\n\n return {\n debug: (message, meta) => emit(\"debug\", message, meta),\n info: (message, meta) => emit(\"info\", message, meta),\n warn: (message, meta) => emit(\"warn\", message, meta),\n error: (message, meta) => emit(\"error\", message, meta),\n };\n}\n\n/** A logger that discards everything — handy for tests. */\nexport const silentLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n","import { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst moduleDir = dirname(fileURLToPath(import.meta.url));\n\nfunction firstExisting(candidates: string[], fallback: string): string {\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate;\n }\n return fallback;\n}\n\n/**\n * Directory holding the imported knowledge base JSON.\n * - dev (tsx): `<root>/src/knowledge/data`\n * - build (node): `<root>/dist/knowledge/data` (copied by `copy-assets.mjs`)\n */\nexport function knowledgeDataDir(): string {\n return firstExisting(\n [resolve(moduleDir, \"../knowledge/data\"), resolve(moduleDir, \"knowledge/data\")],\n resolve(moduleDir, \"../knowledge/data\"),\n );\n}\n\n/**\n * Directory holding recipe JSON files.\n * - dev: `<root>/recipes`\n * - build: `<root>/dist/recipes`\n */\nexport function recipesDir(): string {\n return firstExisting(\n [resolve(moduleDir, \"../../recipes\"), resolve(moduleDir, \"recipes\")],\n resolve(moduleDir, \"../../recipes\"),\n );\n}\n\n/**\n * Directory holding the TouchDesigner-side Python bridge modules that ship with\n * the package (the `td/modules` tree). Used by the `install-bridge` CLI to copy\n * them somewhere TouchDesigner can import from.\n * - dev (tsx): `<root>/td/modules`\n * - installed package (node): `<pkgroot>/td/modules`\n */\nexport function bridgeModulesDir(): string {\n return firstExisting(\n [resolve(moduleDir, \"../td/modules\"), resolve(moduleDir, \"../../td/modules\")],\n resolve(moduleDir, \"../td/modules\"),\n );\n}\n\n/**\n * Resolves the installed `@bottobot/td-mcp` package root (the source of operator\n * data), if present. Used as a fallback when local knowledge data is missing.\n */\nexport function bottobotPackageDir(): string | undefined {\n const candidates = [\n resolve(moduleDir, \"../../node_modules/@bottobot/td-mcp\"),\n resolve(moduleDir, \"../node_modules/@bottobot/td-mcp\"),\n resolve(process.cwd(), \"node_modules/@bottobot/td-mcp\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(resolve(candidate, \"wiki/data/processed\"))) return candidate;\n }\n return undefined;\n}\n","import type {\n GlslTechnique,\n OperatorDoc,\n OperatorSummary,\n Pattern,\n PythonClass,\n PythonClassSummary,\n Tutorial,\n TutorialSummary,\n} from \"./types.js\";\n\n/** Filename-style slug: lowercase, non-alphanumerics collapse to underscores. */\nexport function slugify(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n}\n\n/** Lookup key that unifies \"Noise TOP\", \"noiseTOP\" and \"noise_top\" → \"noisetop\". */\nexport function compactKey(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function toOperatorSummary(slug: string, doc: OperatorDoc): OperatorSummary {\n return {\n slug,\n name: doc.name,\n displayName: doc.displayName ?? doc.name,\n category: doc.category ?? \"Unknown\",\n subcategory: doc.subcategory ?? \"\",\n summary: doc.summary ?? doc.description ?? \"\",\n keywords: doc.keywords ?? [],\n };\n}\n\nexport function toPythonSummary(cls: PythonClass): PythonClassSummary {\n return {\n className: cls.className,\n displayName: cls.displayName ?? cls.className,\n category: cls.category ?? \"Unknown\",\n methodCount: cls.methods?.length ?? 0,\n memberCount: cls.members?.length ?? 0,\n };\n}\n\nexport function toTutorialSummary(tut: Tutorial): TutorialSummary {\n return {\n id: tut.id,\n name: tut.name,\n category: tut.category ?? \"Unknown\",\n summary: tut.summary ?? tut.description ?? \"\",\n };\n}\n\ninterface RawPattern {\n name?: string;\n description?: string;\n category?: string;\n workflow?: string[];\n use_case?: string;\n}\n\n/**\n * The bottobot patterns file is an object with a `patterns` array (plus extra\n * metadata keys). Normalizes it into a flat, id-keyed array.\n */\nexport function normalizePatterns(raw: unknown): Pattern[] {\n let list: RawPattern[] = [];\n if (Array.isArray(raw)) {\n list = raw as RawPattern[];\n } else if (raw && typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>;\n if (Array.isArray(obj.patterns)) {\n list = obj.patterns as RawPattern[];\n } else {\n list = Object.values(obj).filter((v): v is RawPattern => !!v && typeof v === \"object\");\n }\n }\n return list\n .filter((p) => typeof p.name === \"string\")\n .map((p) => ({\n id: slugify(p.name as string),\n name: p.name as string,\n description: p.description,\n category: p.category,\n workflow: Array.isArray(p.workflow) ? p.workflow : undefined,\n use_case: p.use_case,\n }));\n}\n\ninterface RawGlslFile {\n techniques?: unknown;\n}\n\n/** Extracts GLSL techniques from bottobot's `experimental/glsl.json`. */\nexport function normalizeGlsl(raw: unknown): GlslTechnique[] {\n const file = (raw ?? {}) as RawGlslFile;\n const techniques = Array.isArray(file.techniques) ? file.techniques : [];\n return techniques\n .filter((t): t is Record<string, unknown> => !!t && typeof t === \"object\")\n .map((t) => {\n const name = typeof t.name === \"string\" ? t.name : \"Untitled\";\n const id = typeof t.id === \"string\" && t.id.length > 0 ? t.id : slugify(name);\n return {\n id,\n name,\n subcategory: typeof t.subcategory === \"string\" ? t.subcategory : undefined,\n description: typeof t.description === \"string\" ? t.description : undefined,\n difficulty: typeof t.difficulty === \"string\" ? t.difficulty : undefined,\n operators: Array.isArray(t.operators) ? (t.operators as string[]) : undefined,\n tags: Array.isArray(t.tags) ? (t.tags as string[]) : undefined,\n notes: typeof t.notes === \"string\" ? t.notes : undefined,\n code: (t.code ?? undefined) as GlslTechnique[\"code\"],\n setup: typeof t.setup === \"string\" ? t.setup : undefined,\n };\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { compactKey } from \"../knowledge/normalize.js\";\nimport { type Logger, silentLogger } from \"../utils/logger.js\";\nimport { recipesDir } from \"../utils/paths.js\";\nimport { type Recipe, RecipeSchema, type RecipeSummary } from \"./schema.js\";\n\nexport interface RecipeLibraryOptions {\n dir?: string;\n logger?: Logger;\n}\n\n/** Loads and validates recipe JSON files from the recipes directory. */\nexport class RecipeLibrary {\n private readonly dir: string;\n private readonly logger: Logger;\n private cache?: Recipe[];\n\n constructor(options: RecipeLibraryOptions = {}) {\n this.dir = options.dir ?? recipesDir();\n this.logger = options.logger ?? silentLogger;\n }\n\n private load(): Recipe[] {\n if (this.cache) return this.cache;\n const recipes: Recipe[] = [];\n if (existsSync(this.dir)) {\n for (const file of readdirSync(this.dir)) {\n if (!file.endsWith(\".json\")) continue;\n try {\n const raw = JSON.parse(readFileSync(join(this.dir, file), \"utf8\"));\n const parsed = RecipeSchema.safeParse(raw);\n if (parsed.success) {\n recipes.push(parsed.data);\n } else {\n this.logger.warn(`Invalid recipe ${file}`, { issues: parsed.error.issues.length });\n }\n } catch (err) {\n this.logger.warn(`Failed to read recipe ${file}`, { error: String(err) });\n }\n }\n }\n this.cache = recipes;\n return recipes;\n }\n\n all(): Recipe[] {\n return this.load();\n }\n\n list(): RecipeSummary[] {\n return this.load().map((r) => ({\n id: r.id,\n name: r.name,\n description: r.description,\n tags: r.tags,\n difficulty: r.difficulty,\n }));\n }\n\n get(id: string): Recipe | undefined {\n const key = compactKey(id);\n return this.load().find((r) => compactKey(r.id) === key || compactKey(r.name) === key);\n }\n\n /** Finds the best recipe whose tags/name/description match any of the given terms. */\n findByTags(terms: string[]): Recipe | undefined {\n const wanted = terms.map((t) => t.toLowerCase()).filter(Boolean);\n if (wanted.length === 0) return undefined;\n let best: { recipe: Recipe; score: number } | undefined;\n for (const recipe of this.load()) {\n const haystack =\n `${recipe.name} ${recipe.description} ${recipe.tags.join(\" \")}`.toLowerCase();\n let score = 0;\n for (const term of wanted) {\n if (recipe.tags.some((tag) => tag.toLowerCase() === term)) score += 2;\n else if (haystack.includes(term)) score += 1;\n }\n if (score > 0 && (!best || score > best.score)) best = { recipe, score };\n }\n return best?.recipe;\n }\n}\n","import { z } from \"zod\";\nimport { controlSchema } from \"../tools/layer2/createControlPanel.js\";\n\nexport const RecipeNodeSchema = z.object({\n name: z.string().describe(\"Unique node name within the recipe (used for wiring).\"),\n type: z.string().describe(\"Operator type, e.g. 'noiseTOP'.\"),\n parameters: z.record(z.string(), z.unknown()).default({}),\n parent: z\n .string()\n .optional()\n .describe(\n \"Name of another recipe node (a COMP, e.g. a geometryCOMP) to nest this node inside of. \" +\n \"The parent must appear earlier in `nodes`. Used to place SOPs inside a Geometry COMP.\",\n ),\n render: z\n .boolean()\n .optional()\n .describe(\n \"For a SOP nested in a geometryCOMP: make this the rendered geometry. Sets the render/display \" +\n \"flags on it and clears its siblings, so the COMP renders this instead of its default torus.\",\n ),\n comment: z.string().optional(),\n});\n\nexport const RecipeConnectionSchema = z.object({\n from: z.string().describe(\"Source node name.\"),\n to: z.string().describe(\"Target node name.\"),\n from_output: z.number().int().nonnegative().default(0),\n to_input: z.number().int().nonnegative().default(0),\n});\n\nexport const RecipeParameterSchema = z.object({\n name: z.string().describe(\"Friendly name of the exposed control.\"),\n node: z.string().describe(\"Recipe node name the parameter belongs to.\"),\n param: z.string().describe(\"TD parameter name on that node.\"),\n value: z.unknown().optional(),\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n description: z.string().optional(),\n});\n\n/**\n * A uniform exposed by a GLSL TOP. On the GLSL TOP these live in *parameter\n * sequences*, not normal parameters, so they cannot be set the usual way: the block\n * count (`op.seq.<seq>.numBlocks`) has to be raised first, after which the per-block\n * name/value sub-parameters exist. `float`/`vec` uniforms bind through the \"Vectors\"\n * page (the `vec` sequence); `color` binds through the \"Colors\" page (the `color`\n * sequence). The \"Constants\" page does NOT feed a runtime `uniform float`, so it is\n * not used here. `buildFromRecipe` handles the translation; authors just declare the\n * uniform.\n */\nexport const RecipeGlslUniformSchema = z.object({\n node: z.string().describe(\"Recipe node name of the GLSL TOP that declares the uniform.\"),\n name: z.string().describe(\"Uniform name as referenced in the shader, e.g. 'uFeed'.\"),\n kind: z\n .enum([\"float\", \"vec\", \"color\"])\n .default(\"float\")\n .describe(\n \"Uniform kind: float (uniform float), vec (uniform vec2/3/4), color (rgba). \" +\n \"float/vec use the Vectors page; color uses the Colors page.\",\n ),\n value: z\n .union([z.number(), z.array(z.number())])\n .optional()\n .describe(\"Initial value: a number for float, or an array of components for vec/color.\"),\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n description: z.string().optional(),\n});\nexport type RecipeGlslUniform = z.infer<typeof RecipeGlslUniformSchema>;\n\nexport const RecipeSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().default(\"\"),\n tags: z.array(z.string()).default([]),\n difficulty: z.enum([\"beginner\", \"intermediate\", \"advanced\"]).default(\"intermediate\"),\n td_version_min: z.string().default(\"2023\"),\n nodes: z.array(RecipeNodeSchema).min(1),\n connections: z.array(RecipeConnectionSchema).default([]),\n parameters: z.array(RecipeParameterSchema).default([]),\n glsl_uniforms: z.array(RecipeGlslUniformSchema).default([]),\n glsl_code: z.record(z.string(), z.string()).optional(),\n python_code: z.record(z.string(), z.string()).optional(),\n /**\n * Live controls to auto-expose on the system container: custom parameters (knobs/\n * sliders/toggles) bound to node parameters so the built system is immediately\n * playable. Each control's `bind_to` uses recipe node *names* (\"nodeName.parName\");\n * buildFromRecipe rewrites them to the real created paths.\n */\n controls: z.array(controlSchema).default([]),\n preview_description: z.string().default(\"\"),\n});\nexport type Recipe = z.infer<typeof RecipeSchema>;\n\nexport interface RecipeSummary {\n id: string;\n name: string;\n description: string;\n tags: string[];\n difficulty: Recipe[\"difficulty\"];\n}\n","import { z } from \"zod\";\nimport { buildPayloadScript, parsePythonReport } from \"../pythonReport.js\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const controlSchema = z.object({\n name: z\n .string()\n .describe(\n \"Control label; also sanitized into a valid TD custom-parameter name (e.g. 'blur amount' → 'Bluramount').\",\n ),\n type: z\n .enum([\"float\", \"int\", \"toggle\", \"menu\", \"rgb\", \"pulse\", \"string\"])\n .default(\"float\")\n .describe(\n \"Widget kind: float/int sliders, a toggle, a dropdown menu, an RGB swatch, a momentary pulse, or a text field.\",\n ),\n label: z.string().optional().describe(\"Display label (defaults to `name`).\"),\n min: z.coerce.number().optional().describe(\"Slider lower bound (float/int) — also hard-clamped.\"),\n max: z.coerce.number().optional().describe(\"Slider upper bound (float/int) — also hard-clamped.\"),\n default: z.union([z.number(), z.boolean(), z.string()]).optional().describe(\"Initial value.\"),\n menu_items: z.array(z.string()).optional().describe(\"Options for a 'menu' control.\"),\n bind_to: z\n .array(z.string())\n .optional()\n .describe(\n \"Parameters this control should drive, each written as 'nodePath.parName' (e.g. '/project1/sys/blur1.size'). Each target is switched to expression mode so moving the control moves the parameter live. Not supported for 'rgb'/'pulse'.\",\n ),\n});\n\n/** One control spec (knob/slider/toggle/menu/…), reused by Layer 1 tools that auto-expose a panel. */\nexport type ControlSpec = z.infer<typeof controlSchema>;\n\nexport const createControlPanelSchema = z.object({\n comp_path: z\n .string()\n .default(\"/project1\")\n .describe(\n \"COMP that will receive the custom parameters — usually a generated system's container.\",\n ),\n page: z\n .string()\n .default(\"Controls\")\n .describe(\"Name of the custom-parameter page to add the controls to.\"),\n controls: z\n .array(controlSchema)\n .min(1)\n .describe(\"The controls (knobs/sliders/toggles/menus) to expose.\"),\n});\ntype CreateControlPanelArgs = z.infer<typeof createControlPanelSchema>;\n\ninterface ControlReport {\n comp: string;\n page: string;\n created: Array<{ control: string; name: string; type: string; pars: string[]; value: unknown }>;\n bound: Array<{ control: string; target: string }>;\n warnings: string[];\n fatal?: string;\n}\n\n// The whole panel is built in one Python pass: appending custom parameters is an\n// attribute-level operation with no structured bridge endpoint, and doing it in a\n// single script keeps the page/parameter/binding work atomic. `ParMode` is *not*\n// injected into the bridge's exec globals, so the expression-mode enum is derived\n// from a live parameter (`type(par.mode)`) instead of imported.\nconst PANEL_SCRIPT = `\nimport json, base64, traceback\n_payload = json.loads(base64.b64decode(\"__PAYLOAD_B64__\").decode(\"utf-8\"))\n_comp = op(_payload[\"comp\"]); _page_name = _payload[\"page\"]; _controls = _payload[\"controls\"]\nreport = {\"comp\": _payload[\"comp\"], \"page\": _page_name, \"created\": [], \"bound\": [], \"warnings\": []}\n\ndef _parname(s):\n s = \"\".join(ch for ch in s if ch.isalnum())\n if not s:\n s = \"Par\"\n if not s[0].isalpha():\n s = \"P\" + s\n # TD custom-parameter names must be a leading uppercase letter followed by lowercase\n # letters/digits only, so lowercase the tail — otherwise camelCase input like \"CamZoom\"\n # keeps its internal capital and TouchDesigner rejects the name.\n return s[0].upper() + s[1:].lower()\n\nif _comp is None:\n report[\"fatal\"] = \"COMP not found: \" + _payload[\"comp\"]\nelif not hasattr(_comp, \"appendCustomPage\"):\n report[\"fatal\"] = _payload[\"comp\"] + \" is not a COMP, so it cannot hold custom parameters.\"\nelse:\n _page = None\n for _pg in _comp.customPages:\n if _pg.name == _page_name:\n _page = _pg\n break\n if _page is None:\n _page = _comp.appendCustomPage(_page_name)\n for _spec in _controls:\n try:\n _name = _parname(_spec[\"name\"]); _typ = _spec.get(\"type\", \"float\"); _label = _spec.get(\"label\") or _spec[\"name\"]\n if _typ == \"float\":\n _pg = _page.appendFloat(_name, label=_label)\n elif _typ == \"int\":\n _pg = _page.appendInt(_name, label=_label)\n elif _typ == \"toggle\":\n _pg = _page.appendToggle(_name, label=_label)\n elif _typ == \"menu\":\n _pg = _page.appendMenu(_name, label=_label)\n elif _typ == \"rgb\":\n _pg = _page.appendRGB(_name, label=_label)\n elif _typ == \"pulse\":\n _pg = _page.appendPulse(_name, label=_label)\n elif _typ in (\"string\", \"str\"):\n _pg = _page.appendStr(_name, label=_label)\n else:\n report[\"warnings\"].append(\"Unknown control type '%s' for '%s'.\" % (_typ, _spec[\"name\"]))\n continue\n _p0 = _pg[0]; _dflt = _spec.get(\"default\", None)\n if _typ in (\"float\", \"int\"):\n _mn = _spec.get(\"min\", None); _mx = _spec.get(\"max\", None)\n if _mn is not None:\n _p0.normMin = _mn; _p0.min = _mn; _p0.clampMin = True\n if _mx is not None:\n _p0.normMax = _mx; _p0.max = _mx; _p0.clampMax = True\n if _dflt is not None:\n _p0.default = _dflt; _p0.val = _dflt\n elif _typ == \"toggle\":\n if _dflt is not None:\n _p0.default = bool(_dflt); _p0.val = bool(_dflt)\n elif _typ == \"menu\":\n _items = _spec.get(\"menu_items\") or []\n if _items:\n _names = [str(x) for x in _items]\n _p0.menuNames = _names; _p0.menuLabels = _names\n if _dflt is not None and str(_dflt) in [str(x) for x in _items]:\n _p0.default = str(_dflt); _p0.val = str(_dflt)\n elif _typ in (\"string\", \"str\"):\n if _dflt is not None:\n _p0.default = str(_dflt); _p0.val = str(_dflt)\n report[\"created\"].append({\"control\": _spec[\"name\"], \"name\": _name, \"type\": _typ, \"pars\": [pp.name for pp in _pg], \"value\": _p0.eval()})\n _binds = _spec.get(\"bind_to\") or []\n if _binds and _typ in (\"rgb\", \"pulse\"):\n report[\"warnings\"].append(\"bind_to ignored for '%s' (a %s control cannot drive a single parameter).\" % (_spec[\"name\"], _typ))\n _binds = []\n for _t in _binds:\n try:\n _dot = _t.rfind(\".\")\n if _dot <= 0:\n report[\"warnings\"].append(\"Invalid bind target '%s' (expected 'nodePath.parName').\" % _t)\n continue\n _np = _t[:_dot]; _pn = _t[_dot + 1:]; _tn = op(_np)\n if _tn is None:\n report[\"warnings\"].append(\"Bind target node not found: %s\" % _np)\n continue\n _tp = getattr(_tn.par, _pn, None)\n if _tp is None:\n report[\"warnings\"].append(\"Bind target parameter not found: %s.%s\" % (_np, _pn))\n continue\n _PM = type(_tp.mode)\n _tp.expr = \"op(%s).par.%s\" % (repr(_payload[\"comp\"]), _name)\n _tp.mode = _PM.EXPRESSION\n report[\"bound\"].append({\"control\": _name, \"target\": _np + \".\" + _pn})\n except Exception:\n report[\"warnings\"].append(\"Failed to bind '%s' to '%s': %s\" % (_name, _t, traceback.format_exc().splitlines()[-1]))\n except Exception:\n report[\"warnings\"].append(\"Failed to create control '%s': %s\" % (_spec.get(\"name\", \"?\"), traceback.format_exc().splitlines()[-1]))\nprint(json.dumps(report))\n`;\n\nexport function buildPanelScript(payload: object): string {\n return buildPayloadScript(PANEL_SCRIPT, payload);\n}\n\nexport function parseReport(stdout: string | undefined): ControlReport {\n return parsePythonReport<ControlReport>(stdout);\n}\n\nexport async function createControlPanelImpl(ctx: ToolContext, args: CreateControlPanelArgs) {\n return guardTd(\n async () => {\n const script = buildPanelScript({\n comp: args.comp_path,\n page: args.page,\n controls: args.controls,\n });\n const exec = await ctx.client.executePythonScript(script, true);\n return parseReport(exec.stdout);\n },\n (report) => {\n if (report.fatal) {\n return jsonResult(`Could not build control panel: ${report.fatal}`, report);\n }\n const summary = `Added ${report.created.length} control(s) on page \"${report.page}\" of ${report.comp}, ${report.bound.length} bound to live parameter(s)${\n report.warnings.length ? `, ${report.warnings.length} warning(s)` : \"\"\n }.`;\n return jsonResult(summary, report);\n },\n );\n}\n\nexport const registerCreateControlPanel: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"create_control_panel\",\n {\n title: \"Create control panel\",\n description:\n \"Expose live controls on a COMP: append custom parameters (sliders, toggles, menus, RGB, pulse) and bind them to node parameters so the artist can drive a generated system in real time. Point `comp_path` at a system container and list the controls; use each control's `bind_to` to wire it to one or more 'nodePath.parName' targets.\",\n inputSchema: createControlPanelSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },\n },\n (args) => createControlPanelImpl(ctx, args),\n );\n};\n","/** Base error for all TouchDesigner bridge failures. */\nexport class TdError extends Error {\n readonly code: string;\n\n constructor(message: string, code: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"TdError\";\n this.code = code;\n }\n}\n\n/** The bridge could not be reached (TD not running, wrong host/port, etc.). */\nexport class TdConnectionError extends TdError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, \"TD_CONNECTION\", options);\n this.name = \"TdConnectionError\";\n }\n}\n\n/** The request exceeded the configured timeout. */\nexport class TdTimeoutError extends TdError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, \"TD_TIMEOUT\", options);\n this.name = \"TdTimeoutError\";\n }\n}\n\n/** The bridge responded but reported an error (HTTP non-2xx or `ok: false`). */\nexport class TdApiError extends TdError {\n readonly status: number | undefined;\n readonly apiCode: string | undefined;\n\n constructor(message: string, options?: { status?: number; apiCode?: string; cause?: unknown }) {\n super(message, \"TD_API\", options);\n this.name = \"TdApiError\";\n this.status = options?.status;\n this.apiCode = options?.apiCode;\n }\n}\n\n/** Produces a human-friendly, single-line description of any error. */\nexport function friendlyTdError(err: unknown): string {\n if (err instanceof TdError) return err.message;\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\nexport type {\n ApiEnvelope,\n CreateNodeInput,\n TdBatchOperation,\n TdBatchResult,\n TdConnection,\n TdDeleteResult,\n TdExecResult,\n TdInfo,\n TdMethodResult,\n TdNodeDetail,\n TdNodeError,\n TdNodeErrors,\n TdNodeList,\n TdNodeRef,\n TdPerformance,\n TdPreview,\n TdTopology,\n} from \"./validators.js\";\n","import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { friendlyTdError } from \"../td-client/types.js\";\n\ntype Content = CallToolResult[\"content\"];\n\nexport function textResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }] };\n}\n\nexport function errorResult(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** A text block followed by a pretty-printed JSON code fence. */\nexport function jsonResult(summary: string, data: unknown): CallToolResult {\n const text = `${summary}\\n\\n\\`\\`\\`json\\n${JSON.stringify(data, null, 2)}\\n\\`\\`\\``;\n return { content: [{ type: \"text\", text }] };\n}\n\n/**\n * A short text summary plus a machine-readable `structuredContent` payload.\n *\n * Use this (with an `outputSchema` on the tool) for read tools so agents can\n * process the data with code instead of re-parsing a JSON code fence out of the\n * conversation. The text block stays small on purpose — it is only a summary;\n * the full data travels on the `structuredContent` channel.\n */\nexport function structuredResult(summary: string, data: object): CallToolResult {\n return {\n content: [{ type: \"text\", text: summary }],\n structuredContent: data as { [key: string]: unknown },\n };\n}\n\n/** An image block (base64), optionally preceded by a caption. */\nexport function imageResult(\n base64: string,\n mimeType = \"image/png\",\n caption?: string,\n): CallToolResult {\n const content: Content = [];\n if (caption) content.push({ type: \"text\", text: caption });\n content.push({ type: \"image\", data: base64, mimeType });\n return { content };\n}\n\n/**\n * Runs a client call and formats the result, converting any TD error into a\n * friendly `isError` result instead of throwing out of the MCP handler.\n */\nexport async function guardTd<T>(\n fn: () => Promise<T>,\n onOk: (value: T) => CallToolResult,\n): Promise<CallToolResult> {\n try {\n return onOk(await fn());\n } catch (err) {\n return errorResult(friendlyTdError(err));\n }\n}\n","import { z } from \"zod\";\n\n/** Standard response envelope every bridge endpoint returns. */\nexport const ApiEnvelopeSchema = z.object({\n ok: z.boolean(),\n data: z.unknown().optional(),\n error: z.object({ code: z.string().optional(), message: z.string() }).optional(),\n});\nexport type ApiEnvelope = z.infer<typeof ApiEnvelopeSchema>;\n\nexport const NodeRefSchema = z.object({\n path: z.string(),\n type: z.string().default(\"\"),\n name: z.string().default(\"\"),\n /** Parameters that could not be applied at create time (unknown name or bad value). */\n parameter_warnings: z.array(z.string()).optional(),\n});\nexport type TdNodeRef = z.infer<typeof NodeRefSchema>;\n\nexport const NodeDetailSchema = NodeRefSchema.extend({\n parameters: z.record(z.string(), z.unknown()).default({}),\n inputs: z.array(z.string()).optional(),\n outputs: z.array(z.string()).optional(),\n family: z.string().optional(),\n errors: z.array(z.string()).optional(),\n});\nexport type TdNodeDetail = z.infer<typeof NodeDetailSchema>;\n\nexport const NodeListSchema = z.object({ nodes: z.array(NodeRefSchema).default([]) });\nexport type TdNodeList = z.infer<typeof NodeListSchema>;\n\nexport const InfoSchema = z.object({\n td_version: z.string().optional(),\n python_version: z.string().optional(),\n build: z.string().optional(),\n bridge_version: z.string().optional(),\n project: z.string().optional(),\n});\nexport type TdInfo = z.infer<typeof InfoSchema>;\n\nexport const NodeErrorSchema = z.object({\n path: z.string(),\n message: z.string(),\n type: z.string().optional(),\n});\nexport type TdNodeError = z.infer<typeof NodeErrorSchema>;\n\nexport const NodeErrorsSchema = z.object({ errors: z.array(NodeErrorSchema).default([]) });\nexport type TdNodeErrors = z.infer<typeof NodeErrorsSchema>;\n\nexport const PreviewSchema = z.object({\n path: z.string(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n format: z.string().default(\"png\"),\n base64: z.string(),\n});\nexport type TdPreview = z.infer<typeof PreviewSchema>;\n\nexport const ExecResultSchema = z.object({\n result: z.unknown().optional(),\n stdout: z.string().optional(),\n printed: z.array(z.string()).optional(),\n});\nexport type TdExecResult = z.infer<typeof ExecResultSchema>;\n\nexport const MethodResultSchema = z.object({ result: z.unknown() });\nexport type TdMethodResult = z.infer<typeof MethodResultSchema>;\n\nexport const DeleteResultSchema = z.object({ deleted: z.string() });\nexport type TdDeleteResult = z.infer<typeof DeleteResultSchema>;\n\nexport const ConnectionSchema = z.object({\n source_path: z.string(),\n source_output: z.number().int().default(0),\n target_path: z.string(),\n target_input: z.number().int().default(0),\n});\nexport type TdConnection = z.infer<typeof ConnectionSchema>;\n\nexport const TopologySchema = z.object({\n nodes: z.array(NodeRefSchema).default([]),\n connections: z.array(ConnectionSchema).default([]),\n});\nexport type TdTopology = z.infer<typeof TopologySchema>;\n\nexport const PerformanceSchema = z.object({\n nodes: z\n .array(\n z.object({\n path: z.string(),\n cook_time_ms: z.number().default(0),\n cook_count: z.number().optional(),\n }),\n )\n .default([]),\n total_cook_time_ms: z.number().optional(),\n gpu_memory_mb: z.number().optional(),\n});\nexport type TdPerformance = z.infer<typeof PerformanceSchema>;\n\nexport const BatchOpResultSchema = z.object({\n action: z.string(),\n ok: z.boolean(),\n path: z.string().optional(),\n data: z.unknown().optional(),\n error: z.string().optional(),\n});\nexport const BatchResultSchema = z.object({ results: z.array(BatchOpResultSchema).default([]) });\nexport type TdBatchResult = z.infer<typeof BatchResultSchema>;\n\n/** Input shape for creating a node (used by the client and Layer 3 tool). */\nexport const CreateNodeInputSchema = z.object({\n parent_path: z.string(),\n type: z.string(),\n name: z.string().optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n});\nexport type CreateNodeInput = z.infer<typeof CreateNodeInputSchema>;\n\n/** A single atomic operation accepted by `POST /api/batch`. */\nexport const BatchOperationSchema = z.discriminatedUnion(\"action\", [\n z.object({\n action: z.literal(\"create\"),\n parent_path: z.string(),\n type: z.string(),\n name: z.string().optional(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n }),\n z.object({\n action: z.literal(\"update\"),\n path: z.string(),\n parameters: z.record(z.string(), z.unknown()),\n }),\n z.object({ action: z.literal(\"delete\"), path: z.string() }),\n z.object({\n action: z.literal(\"connect\"),\n source_path: z.string(),\n target_path: z.string(),\n source_output: z.number().int().default(0),\n target_input: z.number().int().default(0),\n }),\n]);\nexport type TdBatchOperation = z.infer<typeof BatchOperationSchema>;\n","import type { z } from \"zod\";\nimport { type Logger, silentLogger } from \"../utils/logger.js\";\nimport { TdApiError, TdConnectionError, TdTimeoutError } from \"./types.js\";\nimport {\n ApiEnvelopeSchema,\n BatchResultSchema,\n type CreateNodeInput,\n CreateNodeInputSchema,\n DeleteResultSchema,\n ExecResultSchema,\n InfoSchema,\n MethodResultSchema,\n NodeDetailSchema,\n NodeErrorsSchema,\n NodeListSchema,\n NodeRefSchema,\n PerformanceSchema,\n PreviewSchema,\n type TdBatchOperation,\n TopologySchema,\n} from \"./validators.js\";\n\nexport interface TouchDesignerClientOptions {\n baseUrl: string;\n timeoutMs?: number;\n logger?: Logger;\n /** Optional shared bearer token; sent as `Authorization: Bearer <token>` when set. */\n token?: string;\n /** Overridable for tests (defaults to global `fetch`). */\n fetchImpl?: typeof fetch;\n}\n\ntype QueryParams = Record<string, string | number | boolean | undefined>;\n\nfunction extractErrorMessage(json: unknown): string | undefined {\n if (json && typeof json === \"object\") {\n const obj = json as Record<string, unknown>;\n const error = obj.error;\n if (\n error &&\n typeof error === \"object\" &&\n typeof (error as Record<string, unknown>).message === \"string\"\n ) {\n return (error as Record<string, string>).message;\n }\n if (typeof obj.message === \"string\") return obj.message;\n }\n return undefined;\n}\n\n/** Encodes a TD node path (which contains slashes) into a single URL segment. */\nfunction segment(path: string): string {\n return encodeURIComponent(path);\n}\n\n/**\n * HTTP client for the TouchDesigner REST bridge. Every method maps to one of the\n * endpoints in the bridge spec. All failures surface as typed `TdError`s so MCP\n * tool handlers can convert them into friendly messages without crashing.\n */\nexport class TouchDesignerClient {\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly logger: Logger;\n private readonly token: string | undefined;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: TouchDesignerClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.timeoutMs = options.timeoutMs ?? 10000;\n this.logger = options.logger ?? silentLogger;\n this.token = options.token;\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n get endpoint(): string {\n return this.baseUrl;\n }\n\n private async request<T>(\n method: string,\n path: string,\n schema: z.ZodType<T>,\n body?: unknown,\n query?: QueryParams,\n ): Promise<T> {\n const url = new URL(`${this.baseUrl}${path}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n let response: Response;\n try {\n this.logger.debug(`TD ${method} ${path}`);\n const headers: Record<string, string> = {};\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (this.token) headers.authorization = `Bearer ${this.token}`;\n response = await this.fetchImpl(url, {\n method,\n signal: controller.signal,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new TdTimeoutError(\n `TouchDesigner request timed out after ${this.timeoutMs}ms (${method} ${path}).`,\n { cause: err },\n );\n }\n throw new TdConnectionError(\n `Cannot reach TouchDesigner at ${this.baseUrl}. Make sure TD is running with the tdmcp bridge (WebServer DAT) installed and listening on that port.`,\n { cause: err },\n );\n } finally {\n clearTimeout(timer);\n }\n\n const text = await response.text();\n let json: unknown;\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n\n if (!response.ok) {\n const message =\n extractErrorMessage(json) ??\n `TouchDesigner bridge returned HTTP ${response.status} for ${method} ${path}.`;\n throw new TdApiError(message, { status: response.status });\n }\n\n const envelope = ApiEnvelopeSchema.safeParse(json);\n if (!envelope.success) {\n throw new TdApiError(`Malformed response from TouchDesigner bridge for ${method} ${path}.`, {\n status: response.status,\n });\n }\n if (!envelope.data.ok) {\n throw new TdApiError(\n envelope.data.error?.message ?? `TouchDesigner reported an error for ${method} ${path}.`,\n { status: response.status, apiCode: envelope.data.error?.code },\n );\n }\n\n const parsed = schema.safeParse(envelope.data.data);\n if (!parsed.success) {\n throw new TdApiError(\n `Unexpected data shape from TouchDesigner bridge for ${method} ${path}: ${parsed.error.message}`,\n { status: response.status },\n );\n }\n return parsed.data;\n }\n\n getInfo() {\n return this.request(\"GET\", \"/api/info\", InfoSchema);\n }\n\n createNode(input: CreateNodeInput) {\n return this.request(\"POST\", \"/api/nodes\", NodeRefSchema, CreateNodeInputSchema.parse(input));\n }\n\n deleteNode(path: string) {\n return this.request(\"DELETE\", `/api/nodes/${segment(path)}`, DeleteResultSchema);\n }\n\n getNodes(parentPath?: string) {\n return this.request(\"GET\", \"/api/nodes\", NodeListSchema, undefined, { parent: parentPath });\n }\n\n getNode(path: string) {\n return this.request(\"GET\", `/api/nodes/${segment(path)}`, NodeDetailSchema);\n }\n\n updateNodeParameters(path: string, parameters: Record<string, unknown>) {\n return this.request(\"PATCH\", `/api/nodes/${segment(path)}`, NodeDetailSchema, { parameters });\n }\n\n executePythonScript(script: string, returnOutput = true) {\n return this.request(\"POST\", \"/api/exec\", ExecResultSchema, {\n script,\n return_output: returnOutput,\n });\n }\n\n execNodeMethod(\n path: string,\n method: string,\n args: unknown[] = [],\n kwargs: Record<string, unknown> = {},\n ) {\n return this.request(\"POST\", `/api/nodes/${segment(path)}/method`, MethodResultSchema, {\n method,\n args,\n kwargs,\n });\n }\n\n getNodeErrors(path: string) {\n return this.request(\"GET\", `/api/nodes/${segment(path)}/errors`, NodeErrorsSchema);\n }\n\n getPreview(path: string, width = 640, height = 360) {\n return this.request(\"GET\", `/api/preview/${segment(path)}`, PreviewSchema, undefined, {\n width,\n height,\n });\n }\n\n batch(operations: TdBatchOperation[]) {\n return this.request(\"POST\", \"/api/batch\", BatchResultSchema, { operations });\n }\n\n getNetworkErrors(path: string) {\n return this.request(\"GET\", `/api/network/${segment(path)}/errors`, NodeErrorsSchema);\n }\n\n getNetworkTopology(path: string, recursive = false) {\n return this.request(\n \"GET\",\n `/api/network/${segment(path)}/topology`,\n TopologySchema,\n undefined,\n recursive ? { recursive: true } : undefined,\n );\n }\n\n getNetworkPerformance(path: string, recursive = false) {\n return this.request(\n \"GET\",\n `/api/network/${segment(path)}/performance`,\n PerformanceSchema,\n undefined,\n recursive ? { recursive: true } : undefined,\n );\n }\n}\n","import { z } from \"zod\";\n\nexport const ConfigSchema = z.object({\n /** TouchDesigner bridge host. */\n tdHost: z.string().min(1).default(\"127.0.0.1\"),\n /** TouchDesigner bridge port (WebServer DAT). */\n tdPort: z.coerce.number().int().positive().max(65535).default(9980),\n /** MCP transport: `stdio` (default, for local clients) or `http` (Streamable HTTP, loopback-only). */\n transport: z.enum([\"stdio\", \"http\"]).default(\"stdio\"),\n /** Log verbosity (written to stderr). */\n logLevel: z.enum([\"debug\", \"info\", \"warn\", \"error\", \"silent\"]).default(\"info\"),\n /** Per-request timeout against the TD bridge, in milliseconds. */\n requestTimeoutMs: z.coerce.number().int().positive().default(10000),\n /** HTTP transport port (only used when transport=http). */\n httpPort: z.coerce.number().int().positive().max(65535).default(3939),\n /** Subscribe to TD WebSocket events and forward them as MCP logging notifications. */\n events: z.enum([\"on\", \"off\"]).default(\"on\"),\n /**\n * Raw Python escape-hatch tools (`execute_python_script`, `exec_node_method`).\n * Set to \"off\" to lock them out for restricted setups; on by default.\n */\n rawPython: z.enum([\"on\", \"off\"]).default(\"on\"),\n /**\n * Optional shared bearer token for the TD bridge. When set, the server sends it\n * as `Authorization: Bearer <token>` and the bridge requires a match. Leave unset\n * (default) for the zero-config local flow. Set the SAME value in TouchDesigner's\n * environment (`TDMCP_BRIDGE_TOKEN`) to turn enforcement on.\n */\n bridgeToken: z.string().min(1).optional(),\n});\n\nexport type TdmcpConfig = z.infer<typeof ConfigSchema>;\n\n/**\n * Loads and validates configuration from environment variables. Missing values\n * fall back to sensible defaults; invalid values throw a descriptive ZodError.\n */\nexport function loadConfig(env: NodeJS.ProcessEnv = process.env): TdmcpConfig {\n return ConfigSchema.parse({\n tdHost: env.TDMCP_TD_HOST,\n tdPort: env.TDMCP_TD_PORT,\n transport: env.TDMCP_TRANSPORT,\n logLevel: env.TDMCP_LOG_LEVEL,\n requestTimeoutMs: env.TDMCP_REQUEST_TIMEOUT_MS,\n httpPort: env.TDMCP_HTTP_PORT,\n events: env.TDMCP_EVENTS,\n rawPython: env.TDMCP_RAW_PYTHON,\n bridgeToken: env.TDMCP_BRIDGE_TOKEN || undefined,\n });\n}\n\n/** Base URL for the TouchDesigner REST bridge. */\nexport function tdBaseUrl(config: Pick<TdmcpConfig, \"tdHost\" | \"tdPort\">): string {\n return `http://${config.tdHost}:${config.tdPort}`;\n}\n","import { TouchDesignerClient } from \"../td-client/touchDesignerClient.js\";\nimport { type TdmcpConfig, tdBaseUrl } from \"../utils/config.js\";\nimport type { Logger } from \"../utils/logger.js\";\n\n/**\n * Owns the TouchDesigner client and exposes a cheap health probe. The MCP server\n * stays alive whether or not TD is reachable.\n */\nexport class ConnectionManager {\n readonly client: TouchDesignerClient;\n\n constructor(config: TdmcpConfig, logger: Logger) {\n this.client = new TouchDesignerClient({\n baseUrl: tdBaseUrl(config),\n timeoutMs: config.requestTimeoutMs,\n token: config.bridgeToken,\n logger,\n });\n }\n\n async isReachable(): Promise<boolean> {\n try {\n await this.client.getInfo();\n return true;\n } catch {\n return false;\n }\n }\n}\n","import { KnowledgeBase } from \"../knowledge/index.js\";\nimport { RecipeLibrary } from \"../recipes/loader.js\";\nimport type { ToolContext } from \"../tools/types.js\";\nimport type { TdmcpConfig } from \"../utils/config.js\";\nimport { createLogger, type Logger } from \"../utils/logger.js\";\nimport { ConnectionManager } from \"./connectionManager.js\";\n\nexport interface ToolContextOverrides {\n logger?: Logger;\n knowledge?: KnowledgeBase;\n recipes?: RecipeLibrary;\n connection?: ConnectionManager;\n}\n\n/**\n * Assembles the shared {@link ToolContext} that backs every tool handler. Both\n * the MCP server and the agent CLI build their context here, so the two surfaces\n * stay on the same core (client + knowledge + recipes) without duplicating wiring.\n */\nexport function buildToolContext(\n config: TdmcpConfig,\n overrides: ToolContextOverrides = {},\n): ToolContext {\n const logger = overrides.logger ?? createLogger(config.logLevel);\n const connection = overrides.connection ?? new ConnectionManager(config, logger);\n const knowledge = overrides.knowledge ?? new KnowledgeBase({ logger });\n const recipes = overrides.recipes ?? new RecipeLibrary({ logger });\n return {\n client: connection.client,\n knowledge,\n recipes,\n logger,\n allowRawPython: config.rawPython !== \"off\",\n };\n}\n","import { z } from \"zod\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const compareTdNodesSchema = z.object({\n path_a: z.string().describe(\"First node path.\"),\n path_b: z.string().describe(\"Second node path.\"),\n only_diff: z\n .boolean()\n .default(true)\n .describe(\"Return only the parameters that differ (true) or also list the identical ones.\"),\n});\ntype CompareTdNodesArgs = z.infer<typeof compareTdNodesSchema>;\n\nexport const compareTdNodesOutputSchema = z.object({\n a: z.string(),\n b: z.string(),\n type_a: z.string(),\n type_b: z.string(),\n type_match: z.boolean(),\n differing_count: z.number(),\n same_count: z.number(),\n differing: z.array(z.object({ param: z.string(), a: z.unknown(), b: z.unknown() })),\n identical: z.array(z.string()).optional(),\n});\n\nexport async function compareTdNodesImpl(ctx: ToolContext, args: CompareTdNodesArgs) {\n return guardTd(\n async () => {\n const [a, b] = await Promise.all([\n ctx.client.getNode(args.path_a),\n ctx.client.getNode(args.path_b),\n ]);\n return { a, b };\n },\n ({ a, b }) => {\n const keys = new Set([...Object.keys(a.parameters), ...Object.keys(b.parameters)]);\n const differing: Array<{ param: string; a: unknown; b: unknown }> = [];\n const identical: string[] = [];\n for (const key of [...keys].sort()) {\n const va = a.parameters[key];\n const vb = b.parameters[key];\n if (JSON.stringify(va) === JSON.stringify(vb)) identical.push(key);\n else differing.push({ param: key, a: va, b: vb });\n }\n const data: Record<string, unknown> = {\n a: a.path,\n b: b.path,\n type_a: a.type,\n type_b: b.type,\n type_match: a.type === b.type,\n differing_count: differing.length,\n same_count: identical.length,\n differing,\n };\n if (!args.only_diff) data.identical = identical;\n return structuredResult(\n `${differing.length} differing parameter(s) between ${a.path} and ${b.path}${a.type === b.type ? \"\" : ` (types differ: ${a.type} vs ${b.type})`}.`,\n data,\n );\n },\n );\n}\n\nexport const registerCompareTdNodes: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"compare_td_nodes\",\n {\n title: \"Compare two nodes\",\n description:\n \"Diff the parameters of two nodes, returning only the values that differ (by default). Useful for aligning settings across similar operators.\",\n inputSchema: compareTdNodesSchema.shape,\n outputSchema: compareTdNodesOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => compareTdNodesImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const createTdNodeSchema = z.object({\n parent_path: z\n .string()\n .default(\"/project1\")\n .describe(\"Parent COMP path to create the node inside.\"),\n type: z\n .string()\n .describe(\"Operator type string, e.g. 'noiseTOP', 'feedbackTOP', 'nullTOP', 'constantCHOP'.\"),\n name: z.string().optional().describe(\"Optional node name (auto-generated if omitted).\"),\n parameters: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Optional initial parameter overrides as key→value pairs.\"),\n});\ntype CreateTdNodeArgs = z.infer<typeof createTdNodeSchema>;\n\nexport async function createTdNodeImpl(ctx: ToolContext, args: CreateTdNodeArgs) {\n const warnings: string[] = [];\n if (!ctx.knowledge.operatorExists(args.type)) {\n const suggestions = ctx.knowledge.searchOperators(args.type, 3).map((s) => s.name);\n warnings.push(\n `Operator type \"${args.type}\" was not found in the knowledge base.${\n suggestions.length ? ` Did you mean: ${suggestions.join(\", \")}?` : \"\"\n }`,\n );\n }\n return guardTd(\n () =>\n ctx.client.createNode({\n parent_path: args.parent_path,\n type: args.type,\n name: args.name,\n parameters: args.parameters,\n }),\n (node) => {\n const allWarnings = [...warnings];\n if (node.parameter_warnings?.length) {\n allWarnings.push(\n `These parameter(s) were not applied (unknown name or bad value): ${node.parameter_warnings.join(\", \")}.`,\n );\n }\n return jsonResult(`Created ${node.type || args.type} at ${node.path}.`, {\n node,\n warnings: allWarnings,\n });\n },\n );\n}\n\nexport const registerCreateTdNode: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"create_td_node\",\n {\n title: \"Create TouchDesigner node\",\n description:\n \"Create a single operator (node) inside a parent COMP. Validates the operator type against the knowledge base and warns (without blocking) on unknown types.\",\n inputSchema: createTdNodeSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },\n },\n (args) => createTdNodeImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const deleteTdNodeSchema = z.object({\n path: z.string().describe(\"Full path of the node to delete, e.g. '/project1/noise1'.\"),\n});\ntype DeleteTdNodeArgs = z.infer<typeof deleteTdNodeSchema>;\n\nexport async function deleteTdNodeImpl(ctx: ToolContext, args: DeleteTdNodeArgs) {\n return guardTd(\n () => ctx.client.deleteNode(args.path),\n (result) => jsonResult(`Deleted ${result.deleted}.`, result),\n );\n}\n\nexport const registerDeleteTdNode: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"delete_td_node\",\n {\n title: \"Delete TouchDesigner node\",\n description:\n \"Delete a single node by path. Destructive — only call this when the user explicitly asks to remove a node.\",\n inputSchema: deleteTdNodeSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },\n },\n (args) => deleteTdNodeImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const execNodeMethodSchema = z.object({\n path: z.string().describe(\"Full path of the node to call the method on.\"),\n method: z.string().describe(\"Method name to call, e.g. 'cook', 'par', 'destroy', 'copy'.\"),\n args: z.array(z.unknown()).default([]).describe(\"Positional arguments.\"),\n kwargs: z.record(z.string(), z.unknown()).default({}).describe(\"Keyword arguments.\"),\n});\ntype ExecNodeMethodArgs = z.infer<typeof execNodeMethodSchema>;\n\nexport async function execNodeMethodImpl(ctx: ToolContext, args: ExecNodeMethodArgs) {\n return guardTd(\n () => ctx.client.execNodeMethod(args.path, args.method, args.args, args.kwargs),\n (result) => jsonResult(`Called ${args.path}.${args.method}().`, result),\n );\n}\n\nexport const registerExecNodeMethod: ToolRegistrar = (server, ctx) => {\n if (ctx.allowRawPython === false) return;\n server.registerTool(\n \"exec_node_method\",\n {\n title: \"Call node method\",\n description:\n \"Escape hatch — invoke an arbitrary Python method on a node (operator). Prefer structured tools where one exists; use this for operations they don't cover (e.g. .cook(), .copy(), .destroy()).\",\n inputSchema: execNodeMethodSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },\n },\n (args) => execNodeMethodImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const executePythonScriptSchema = z.object({\n script: z\n .string()\n .min(1)\n .describe(\n \"Python source to execute inside TouchDesigner (runs in the TD process, not locally).\",\n ),\n return_output: z\n .boolean()\n .default(true)\n .describe(\"Capture stdout / the value of the last expression and return it.\"),\n});\ntype ExecutePythonScriptArgs = z.infer<typeof executePythonScriptSchema>;\n\nexport async function executePythonScriptImpl(ctx: ToolContext, args: ExecutePythonScriptArgs) {\n return guardTd(\n () => ctx.client.executePythonScript(args.script, args.return_output),\n (result) => jsonResult(\"Python executed in TouchDesigner.\", result),\n );\n}\n\nexport const registerExecutePythonScript: ToolRegistrar = (server, ctx) => {\n if (ctx.allowRawPython === false) return;\n server.registerTool(\n \"execute_python_script\",\n {\n title: \"Execute Python in TouchDesigner\",\n description:\n \"Escape hatch — run an arbitrary Python script inside the TouchDesigner process. Prefer the structured tools (find_td_nodes, get_td_node_parameters, update_td_node_parameters, summarize_td_errors, snapshot_td_graph, …); reach for this only when no structured tool can express the operation. Code runs in TD only, never on the local machine.\",\n inputSchema: executePythonScriptSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },\n },\n (args) => executePythonScriptImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { NodeRefSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\nimport { globToRegExp } from \"./nodeMatch.js\";\n\nexport const findTdNodesSchema = z.object({\n parent_path: z.string().default(\"/project1\").describe(\"Where to search from.\"),\n pattern: z\n .string()\n .optional()\n .describe(\"Case-insensitive name/path filter with '*' wildcards (e.g. 'text*', '*noise*').\"),\n type: z\n .string()\n .optional()\n .describe(\"Case-insensitive operator-type substring (e.g. 'TOP', 'noise').\"),\n recursive: z\n .boolean()\n .default(true)\n .describe(\"Search the whole sub-network (true) or only direct children (false).\"),\n path_only: z.boolean().default(false).describe(\"Return only matching paths.\"),\n limit: z.number().int().positive().default(50).describe(\"Max matches to return.\"),\n});\ntype FindTdNodesArgs = z.infer<typeof findTdNodesSchema>;\n\nexport const findTdNodesOutputSchema = z.object({\n parent_path: z.string(),\n recursive: z.boolean(),\n count: z.number(),\n truncated: z.boolean(),\n paths: z.array(z.string()).optional(),\n matches: z.array(NodeRefSchema).optional(),\n});\n\nexport async function findTdNodesImpl(ctx: ToolContext, args: FindTdNodesArgs) {\n const fetch = args.recursive\n ? async () => (await ctx.client.getNetworkTopology(args.parent_path, true)).nodes\n : async () => (await ctx.client.getNodes(args.parent_path)).nodes;\n\n return guardTd(fetch, (allNodes) => {\n let nodes = allNodes;\n if (args.pattern) {\n const re = globToRegExp(args.pattern);\n nodes = nodes.filter((n) => re.test(n.name) || re.test(n.path));\n }\n if (args.type) {\n const t = args.type.toLowerCase();\n nodes = nodes.filter((n) => n.type.toLowerCase().includes(t));\n }\n const count = nodes.length;\n const truncated = count > args.limit;\n nodes = nodes.slice(0, args.limit);\n const summary = `${count} match(es) under ${args.parent_path}${truncated ? ` (showing ${args.limit})` : \"\"}.`;\n const base = { parent_path: args.parent_path, recursive: args.recursive, count, truncated };\n return args.path_only\n ? structuredResult(summary, { ...base, paths: nodes.map((n) => n.path) })\n : structuredResult(summary, { ...base, matches: nodes });\n });\n}\n\nexport const registerFindTdNodes: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"find_td_nodes\",\n {\n title: \"Find TouchDesigner nodes\",\n description:\n \"Search a network for nodes by name pattern and/or operator type. Recursive by default; pass path_only:true for a compact path list. Prefer this over get_td_nodes when you are looking for specific nodes.\",\n inputSchema: findTdNodesSchema.shape,\n outputSchema: findTdNodesOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => findTdNodesImpl(ctx, args),\n );\n};\n","/** Turns a `*`-glob into a case-insensitive RegExp (other regex metachars are escaped). */\nexport function globToRegExp(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\");\n return new RegExp(escaped, \"i\");\n}\n\n/** The parent path of a TD node path, e.g. `/project1/moviein1` -> `/project1`. */\nexport function parentOf(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx <= 0 ? \"/\" : path.slice(0, idx);\n}\n","import { z } from \"zod\";\nimport { jsonResult, textResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getModuleHelpSchema = z.object({\n name: z.string().describe(\"Class or module name to get help for, e.g. 'OP', 'App', 'Project'.\"),\n});\ntype GetModuleHelpArgs = z.infer<typeof getModuleHelpSchema>;\n\nexport function getModuleHelpImpl(ctx: ToolContext, args: GetModuleHelpArgs) {\n const cls = ctx.knowledge.getPythonClass(args.name);\n if (!cls) {\n const suggestions = ctx.knowledge\n .listPythonClasses()\n .filter((c) => c.className.toLowerCase().includes(args.name.toLowerCase()))\n .slice(0, 5)\n .map((c) => c.className);\n return jsonResult(`No help found for \"${args.name}\".`, { found: false, suggestions });\n }\n\n const lines: string[] = [`# ${cls.displayName || cls.className}`, \"\"];\n if (cls.description) lines.push(cls.description, \"\");\n if (cls.members && cls.members.length > 0) {\n lines.push(\"## Members\");\n for (const m of cls.members) {\n const ro = m.readOnly ? \" (read-only)\" : \"\";\n lines.push(`- ${m.name}${m.returnType ? `: ${m.returnType}` : \"\"}${ro}`);\n }\n lines.push(\"\");\n }\n if (cls.methods && cls.methods.length > 0) {\n lines.push(\"## Methods\");\n for (const method of cls.methods) {\n const sig = method.signature || method.name || \"\";\n lines.push(`- ${sig}${method.returns ? ` -> ${method.returns}` : \"\"}`);\n }\n }\n return textResult(lines.join(\"\\n\"));\n}\n\nexport const registerGetModuleHelp: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_module_help\",\n {\n title: \"Get module/class help\",\n description:\n \"Human-readable help (description, members, method signatures) for a TouchDesigner Python class or module, from the knowledge base.\",\n inputSchema: getModuleHelpSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (args) => getModuleHelpImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdClassDetailsSchema = z.object({\n class_name: z.string().describe(\"Python class name, e.g. 'OP', 'TOP', 'App', 'CHOP'.\"),\n});\ntype GetTdClassDetailsArgs = z.infer<typeof getTdClassDetailsSchema>;\n\nexport function getTdClassDetailsImpl(ctx: ToolContext, args: GetTdClassDetailsArgs) {\n const cls = ctx.knowledge.getPythonClass(args.class_name);\n if (!cls) {\n const suggestions = ctx.knowledge\n .listPythonClasses()\n .filter((c) => c.className.toLowerCase().includes(args.class_name.toLowerCase()))\n .slice(0, 5)\n .map((c) => c.className);\n return structuredResult(`Python class \"${args.class_name}\" not found.`, {\n found: false,\n suggestions,\n });\n }\n return structuredResult(\n `${cls.className} — ${cls.methods?.length ?? 0} methods, ${cls.members?.length ?? 0} members.`,\n cls,\n );\n}\n\nexport const registerGetTdClassDetails: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_class_details\",\n {\n title: \"Get TD Python class details\",\n description:\n \"Full documentation for one TouchDesigner Python class (members + methods) from the knowledge base.\",\n inputSchema: getTdClassDetailsSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (args) => getTdClassDetailsImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdClassesSchema = z.object({\n filter: z\n .string()\n .optional()\n .describe(\"Optional case-insensitive substring to filter class names by.\"),\n});\ntype GetTdClassesArgs = z.infer<typeof getTdClassesSchema>;\n\nexport function getTdClassesImpl(ctx: ToolContext, args: GetTdClassesArgs) {\n let classes = ctx.knowledge.listPythonClasses();\n if (args.filter) {\n const needle = args.filter.toLowerCase();\n classes = classes.filter(\n (c) =>\n c.className.toLowerCase().includes(needle) || c.displayName.toLowerCase().includes(needle),\n );\n }\n return structuredResult(`Found ${classes.length} TouchDesigner Python API class(es).`, {\n classes,\n });\n}\n\nexport const registerGetTdClasses: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_classes\",\n {\n title: \"List TD Python classes\",\n description:\n \"List TouchDesigner Python API classes from the embedded knowledge base (works offline). Optionally filter by name.\",\n inputSchema: getTdClassesSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (args) => getTdClassesImpl(ctx, args),\n );\n};\n","import { friendlyTdError } from \"../../td-client/types.js\";\nimport { jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nconst DESCRIPTION =\n \"Health check + TouchDesigner server info. Returns TD/Python version and bridge status when connected, plus the embedded knowledge-base stats. Use this first to confirm the bridge is reachable.\";\n\nexport async function getTdInfoImpl(ctx: ToolContext) {\n const knowledge = ctx.knowledge.stats();\n try {\n const info = await ctx.client.getInfo();\n return jsonResult(\"TouchDesigner is connected.\", {\n connected: true,\n endpoint: ctx.client.endpoint,\n touchdesigner: info,\n knowledge,\n });\n } catch (err) {\n return jsonResult(\"TouchDesigner is not reachable (the server is still running).\", {\n connected: false,\n endpoint: ctx.client.endpoint,\n reason: friendlyTdError(err),\n knowledge,\n });\n }\n}\n\nexport const registerGetTdInfo: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_info\",\n {\n title: \"Get TouchDesigner info\",\n description: DESCRIPTION,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n () => getTdInfoImpl(ctx),\n );\n};\n","import { z } from \"zod\";\nimport { NodeErrorSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdNodeErrorsSchema = z.object({\n path: z.string().describe(\"Full path of the node (or network root) to check for errors.\"),\n recursive: z\n .boolean()\n .default(false)\n .describe(\"If true, check the whole network under `path`; otherwise just that node.\"),\n summary: z\n .boolean()\n .default(false)\n .describe(\"Return only counts grouped by error type instead of the full error list.\"),\n});\ntype GetTdNodeErrorsArgs = z.infer<typeof getTdNodeErrorsSchema>;\n\nexport const getTdNodeErrorsOutputSchema = z.object({\n path: z.string(),\n total: z.number(),\n errors: z.array(NodeErrorSchema).optional(),\n by_type: z.record(z.string(), z.number()).optional(),\n});\n\nexport async function getTdNodeErrorsImpl(ctx: ToolContext, args: GetTdNodeErrorsArgs) {\n return guardTd(\n () =>\n args.recursive ? ctx.client.getNetworkErrors(args.path) : ctx.client.getNodeErrors(args.path),\n (result) => {\n const errors = result.errors;\n const total = errors.length;\n const none = total === 0;\n if (args.summary) {\n const byType: Record<string, number> = {};\n for (const e of errors) {\n const key = e.type || \"error\";\n byType[key] = (byType[key] ?? 0) + 1;\n }\n return structuredResult(\n none ? `No errors found at ${args.path}.` : `${total} error(s) at ${args.path}.`,\n { path: args.path, total, by_type: byType },\n );\n }\n return structuredResult(\n none ? `No errors found at ${args.path}.` : `Found ${total} error(s) at ${args.path}.`,\n { path: args.path, total, errors },\n );\n },\n );\n}\n\nexport const registerGetTdNodeErrors: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_node_errors\",\n {\n title: \"Get node errors\",\n description:\n \"Check a node (or its whole sub-network) for cook/compile errors and warnings. Pass `summary:true` for grouped counts instead of the full list.\",\n inputSchema: getTdNodeErrorsSchema.shape,\n outputSchema: getTdNodeErrorsOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdNodeErrorsImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { NodeDetailSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdNodeParametersSchema = z.object({\n path: z.string().describe(\"Full path of the node to inspect.\"),\n keys: z\n .array(z.string())\n .optional()\n .describe(\"Only return these parameter names (case-sensitive). Omit to return all parameters.\"),\n omit_io: z\n .boolean()\n .default(false)\n .describe(\"Drop the inputs/outputs lists from the result to save context.\"),\n});\ntype GetTdNodeParametersArgs = z.infer<typeof getTdNodeParametersSchema>;\n\nexport async function getTdNodeParametersImpl(ctx: ToolContext, args: GetTdNodeParametersArgs) {\n return guardTd(\n () => ctx.client.getNode(args.path),\n (node) => {\n let parameters = node.parameters;\n if (args.keys && args.keys.length > 0) {\n const wanted = new Set(args.keys);\n parameters = Object.fromEntries(\n Object.entries(node.parameters).filter(([k]) => wanted.has(k)),\n );\n }\n const data: Record<string, unknown> = {\n path: node.path,\n type: node.type,\n name: node.name,\n parameters,\n };\n if (!args.omit_io) {\n data.inputs = node.inputs;\n data.outputs = node.outputs;\n }\n const count = Object.keys(parameters).length;\n return structuredResult(`${count} parameter(s) for ${node.path} (${node.type}).`, data);\n },\n );\n}\n\nexport const registerGetTdNodeParameters: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_node_parameters\",\n {\n title: \"Get node parameters\",\n description:\n \"Read the current parameters (and I/O) of a node. Pass `keys` to project specific parameters or `omit_io:true` to drop the inputs/outputs lists.\",\n inputSchema: getTdNodeParametersSchema.shape,\n outputSchema: NodeDetailSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdNodeParametersImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { NodeRefSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\nimport { globToRegExp } from \"./nodeMatch.js\";\n\nexport const getTdNodesSchema = z.object({\n parent_path: z\n .string()\n .default(\"/project1\")\n .describe(\"Parent COMP whose direct children should be listed.\"),\n pattern: z\n .string()\n .optional()\n .describe(\n \"Case-insensitive filter on node name/path. Supports '*' wildcards (e.g. 'text*', '*noise*').\",\n ),\n path_only: z\n .boolean()\n .default(false)\n .describe(\"Return only the list of node paths, dropping type/name.\"),\n limit: z.number().int().positive().optional().describe(\"Cap the number of nodes returned.\"),\n detail_level: z\n .enum([\"summary\", \"full\"])\n .default(\"summary\")\n .describe(\n \"'summary' (default) returns a count, a type breakdown and the first few paths; 'full' returns every node. Use 'full' (or path_only) when you need the complete list.\",\n ),\n});\ntype GetTdNodesArgs = z.infer<typeof getTdNodesSchema>;\n\nconst SAMPLE_SIZE = 10;\n\nexport const getTdNodesOutputSchema = z.object({\n parent_path: z.string(),\n count: z.number(),\n detail_level: z.enum([\"summary\", \"full\"]),\n truncated: z.boolean(),\n by_type: z.record(z.string(), z.number()).optional(),\n sample: z.array(z.string()).optional(),\n paths: z.array(z.string()).optional(),\n nodes: z.array(NodeRefSchema).optional(),\n hint: z.string().optional(),\n});\n\nexport async function getTdNodesImpl(ctx: ToolContext, args: GetTdNodesArgs) {\n return guardTd(\n () => ctx.client.getNodes(args.parent_path),\n (list) => {\n let nodes = list.nodes;\n if (args.pattern) {\n const re = globToRegExp(args.pattern);\n nodes = nodes.filter((n) => re.test(n.name) || re.test(n.path));\n }\n const matched = nodes.length;\n const truncated = args.limit !== undefined && matched > args.limit;\n if (args.limit !== undefined) nodes = nodes.slice(0, args.limit);\n const where = args.pattern ? ` matching \"${args.pattern}\"` : \"\";\n const base = {\n parent_path: args.parent_path,\n count: matched,\n detail_level: args.detail_level,\n truncated,\n };\n\n if (args.path_only) {\n return structuredResult(`${matched} node(s) under ${args.parent_path}${where}.`, {\n ...base,\n paths: nodes.map((n) => n.path),\n });\n }\n\n if (args.detail_level === \"summary\") {\n const byType: Record<string, number> = {};\n for (const n of nodes) {\n const key = n.type || \"unknown\";\n byType[key] = (byType[key] ?? 0) + 1;\n }\n const sample = nodes.slice(0, SAMPLE_SIZE).map((n) => n.path);\n return structuredResult(\n `${matched} node(s) under ${args.parent_path}${where}. Summary only — pass detail_level:\"full\" or path_only:true for the full list.`,\n {\n ...base,\n by_type: byType,\n sample,\n ...(matched > sample.length\n ? {\n hint: `Showing first ${sample.length} of ${matched}. Use detail_level:\"full\" for all.`,\n }\n : {}),\n },\n );\n }\n\n return structuredResult(`${matched} node(s) under ${args.parent_path}${where}.`, {\n ...base,\n nodes,\n });\n },\n );\n}\n\nexport const registerGetTdNodes: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_nodes\",\n {\n title: \"List TouchDesigner nodes\",\n description:\n 'List the direct child nodes of a COMP. Defaults to a compact summary (count + type breakdown + sample paths); pass detail_level:\"full\" or path_only:true for the complete list, and `pattern` to filter by name.',\n inputSchema: getTdNodesSchema.shape,\n outputSchema: getTdNodesOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdNodesImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { checkPerformance } from \"../../feedback/performanceMonitor.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdPerformanceSchema = z.object({\n root_path: z.string().default(\"/project1\").describe(\"Network root to measure cook times under.\"),\n target_fps: z\n .number()\n .positive()\n .default(60)\n .describe(\"Frame-rate target used to flag slow nodes.\"),\n recursive: z\n .boolean()\n .default(true)\n .describe(\n \"Measure every descendant (true, default) so cook time inside generated containers is counted, not just the root's direct children.\",\n ),\n});\ntype GetTdPerformanceArgs = z.infer<typeof getTdPerformanceSchema>;\n\nexport const getTdPerformanceOutputSchema = z.object({\n path: z.string(),\n targetFps: z.number(),\n frameBudgetMs: z.number(),\n totalCookMs: z.number(),\n nodes: z.array(\n z.object({\n path: z.string(),\n cook_time_ms: z.number(),\n cook_count: z.number().optional(),\n }),\n ),\n warnings: z.array(z.string()),\n});\n\nexport async function getTdPerformanceImpl(ctx: ToolContext, args: GetTdPerformanceArgs) {\n return guardTd(\n () => checkPerformance(ctx.client, args.root_path, args.target_fps, args.recursive),\n (report) =>\n structuredResult(\n report.warnings.length === 0\n ? `Within budget: ${report.totalCookMs.toFixed(2)}ms total under ${args.root_path} (${args.target_fps}fps).`\n : `${report.warnings.length} performance warning(s) under ${args.root_path}.`,\n report,\n ),\n );\n}\n\nexport const registerGetTdPerformance: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_performance\",\n {\n title: \"Get network performance\",\n description:\n \"Report cook times under a network (recursively by default, slowest node first) and warn about nodes that exceed the frame budget.\",\n inputSchema: getTdPerformanceSchema.shape,\n outputSchema: getTdPerformanceOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdPerformanceImpl(ctx, args),\n );\n};\n","import type { TouchDesignerClient } from \"../td-client/touchDesignerClient.js\";\n\nexport interface PerformanceReport {\n path: string;\n targetFps: number;\n frameBudgetMs: number;\n totalCookMs: number;\n nodes: Array<{ path: string; cook_time_ms: number; cook_count?: number }>;\n warnings: string[];\n}\n\n/**\n * Reports cook times against the frame budget implied by `targetFps`. `recursive`\n * measures every descendant (so cook time inside generated containers is counted, not\n * just the root's direct children). Nodes are returned slowest-first.\n */\nexport async function checkPerformance(\n client: TouchDesignerClient,\n path: string,\n targetFps = 60,\n recursive = true,\n): Promise<PerformanceReport> {\n const perf = await client.getNetworkPerformance(path, recursive);\n const frameBudgetMs = 1000 / targetFps;\n const warnings: string[] = [];\n\n for (const node of perf.nodes) {\n if (node.cook_time_ms > frameBudgetMs) {\n warnings.push(\n `${node.path} cooks in ${node.cook_time_ms.toFixed(2)}ms, exceeding the ${frameBudgetMs.toFixed(2)}ms budget at ${targetFps}fps.`,\n );\n }\n }\n\n const totalCookMs =\n perf.total_cook_time_ms ?? perf.nodes.reduce((sum, node) => sum + node.cook_time_ms, 0);\n if (totalCookMs > frameBudgetMs) {\n warnings.push(\n `Total cook time ${totalCookMs.toFixed(2)}ms exceeds the ${frameBudgetMs.toFixed(2)}ms budget at ${targetFps}fps.`,\n );\n }\n\n // Surface the slowest nodes first so the real bottlenecks are obvious.\n const nodes = [...perf.nodes].sort((a, b) => b.cook_time_ms - a.cook_time_ms);\n return { path, targetFps, frameBudgetMs, totalCookMs, nodes, warnings };\n}\n","import { z } from \"zod\";\nimport { verifyNetwork } from \"../../feedback/networkVerifier.js\";\nimport { TopologySchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const getTdTopologySchema = z.object({\n root_path: z.string().default(\"/project1\").describe(\"Network root to map.\"),\n});\ntype GetTdTopologyArgs = z.infer<typeof getTdTopologySchema>;\n\nexport const getTdTopologyOutputSchema = z.object({\n path: z.string(),\n nodeCount: z.number(),\n connectionCount: z.number(),\n issues: z.array(z.string()),\n topology: TopologySchema,\n});\n\nexport async function getTdTopologyImpl(ctx: ToolContext, args: GetTdTopologyArgs) {\n return guardTd(\n () => verifyNetwork(ctx.client, args.root_path),\n (report) =>\n structuredResult(\n `${report.nodeCount} node(s), ${report.connectionCount} connection(s) under ${args.root_path}.`,\n report,\n ),\n );\n}\n\nexport const registerGetTdTopology: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"get_td_topology\",\n {\n title: \"Get network topology\",\n description:\n \"Return the nodes and connections under a network root, flagging obvious structural issues.\",\n inputSchema: getTdTopologySchema.shape,\n outputSchema: getTdTopologyOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => getTdTopologyImpl(ctx, args),\n );\n};\n","import type { TouchDesignerClient } from \"../td-client/touchDesignerClient.js\";\nimport type { TdTopology } from \"../td-client/types.js\";\n\nexport interface VerifyReport {\n path: string;\n nodeCount: number;\n connectionCount: number;\n issues: string[];\n topology: TdTopology;\n}\n\n/** Inspects the topology under `path` and flags obvious structural issues. */\nexport async function verifyNetwork(\n client: TouchDesignerClient,\n path: string,\n): Promise<VerifyReport> {\n const topology = await client.getNetworkTopology(path);\n const issues: string[] = [];\n if (topology.nodes.length === 0) {\n issues.push(`No nodes were found under ${path}.`);\n } else if (topology.nodes.length > 1 && topology.connections.length === 0) {\n issues.push(\"Multiple nodes exist but none are connected.\");\n }\n return {\n path,\n nodeCount: topology.nodes.length,\n connectionCount: topology.connections.length,\n issues,\n topology,\n };\n}\n","import { z } from \"zod\";\nimport { verifyNetwork } from \"../../feedback/networkVerifier.js\";\nimport { ConnectionSchema } from \"../../td-client/validators.js\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\n/** Cap on per-node parameter fetches so a big graph can't fan out into hundreds of requests. */\nconst MAX_PARAM_NODES = 60;\n\nexport const snapshotTdGraphSchema = z.object({\n path: z.string().default(\"/project1\").describe(\"Network root to snapshot.\"),\n include_params: z\n .boolean()\n .default(false)\n .describe(\"Also fetch each node's parameters (one request per node; capped for large graphs).\"),\n});\ntype SnapshotTdGraphArgs = z.infer<typeof snapshotTdGraphSchema>;\n\nexport const snapshotTdGraphOutputSchema = z.object({\n path: z.string(),\n nodeCount: z.number(),\n connectionCount: z.number(),\n issues: z.array(z.string()),\n params_truncated: z.boolean(),\n nodes: z.array(\n z.object({\n path: z.string(),\n type: z.string(),\n name: z.string(),\n parameters: z.record(z.string(), z.unknown()).optional(),\n }),\n ),\n connections: z.array(ConnectionSchema),\n});\n\nexport async function snapshotTdGraphImpl(ctx: ToolContext, args: SnapshotTdGraphArgs) {\n return guardTd(\n async () => {\n const report = await verifyNetwork(ctx.client, args.path);\n const refs = report.topology.nodes;\n let paramsTruncated = false;\n const params = new Map<string, Record<string, unknown>>();\n if (args.include_params) {\n const targets = refs.slice(0, MAX_PARAM_NODES);\n paramsTruncated = refs.length > MAX_PARAM_NODES;\n // Fail-forward: one unreadable node shouldn't sink the whole snapshot.\n const details = await Promise.allSettled(targets.map((n) => ctx.client.getNode(n.path)));\n for (const detail of details) {\n if (detail.status === \"fulfilled\") params.set(detail.value.path, detail.value.parameters);\n }\n }\n const nodes = refs.map((n) => ({\n path: n.path,\n type: n.type,\n name: n.name,\n ...(args.include_params ? { parameters: params.get(n.path) ?? {} } : {}),\n }));\n return { report, nodes, paramsTruncated };\n },\n ({ report, nodes, paramsTruncated }) =>\n structuredResult(\n `Snapshot of ${args.path}: ${report.nodeCount} node(s), ${report.connectionCount} connection(s)${report.issues.length ? `, ${report.issues.length} issue(s)` : \"\"}.`,\n {\n path: report.path,\n nodeCount: report.nodeCount,\n connectionCount: report.connectionCount,\n issues: report.issues,\n params_truncated: paramsTruncated,\n nodes,\n connections: report.topology.connections,\n },\n ),\n );\n}\n\nexport const registerSnapshotTdGraph: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"snapshot_td_graph\",\n {\n title: \"Snapshot network graph\",\n description:\n \"Capture a compact, serializable snapshot of a network — nodes, connections, structural issues, and optionally each node's parameters — for review, diffing, or documentation.\",\n inputSchema: snapshotTdGraphSchema.shape,\n outputSchema: snapshotTdGraphOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => snapshotTdGraphImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, structuredResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\nimport { parentOf } from \"./nodeMatch.js\";\n\nexport const summarizeTdErrorsSchema = z.object({\n path: z.string().default(\"/project1\").describe(\"Network root to collect errors under.\"),\n group_by: z\n .enum([\"message\", \"type\", \"parent\"])\n .default(\"message\")\n .describe(\n \"How to cluster errors: by exact message, by error type, or by parent container (to find a common upstream cause).\",\n ),\n});\ntype SummarizeTdErrorsArgs = z.infer<typeof summarizeTdErrorsSchema>;\n\nexport const summarizeTdErrorsOutputSchema = z.object({\n path: z.string(),\n total: z.number(),\n group_by: z.enum([\"message\", \"type\", \"parent\"]),\n groups: z.array(\n z.object({\n key: z.string(),\n count: z.number(),\n sample: z.object({ path: z.string(), message: z.string() }),\n }),\n ),\n suggestions: z.array(z.string()),\n});\n\nexport async function summarizeTdErrorsImpl(ctx: ToolContext, args: SummarizeTdErrorsArgs) {\n return guardTd(\n () => ctx.client.getNetworkErrors(args.path),\n (result) => {\n const errors = result.errors;\n const total = errors.length;\n if (total === 0) {\n return structuredResult(`No errors found under ${args.path}.`, {\n path: args.path,\n total: 0,\n group_by: args.group_by,\n groups: [],\n suggestions: [],\n });\n }\n\n const keyOf = (e: { path: string; message: string; type?: string }): string =>\n args.group_by === \"message\"\n ? e.message\n : args.group_by === \"type\"\n ? e.type || \"error\"\n : parentOf(e.path);\n\n const grouped = new Map<\n string,\n { count: number; sample: { path: string; message: string } }\n >();\n const byPath = new Map<string, number>();\n for (const e of errors) {\n const key = keyOf(e);\n const g = grouped.get(key);\n if (g) g.count += 1;\n else grouped.set(key, { count: 1, sample: { path: e.path, message: e.message } });\n byPath.set(e.path, (byPath.get(e.path) ?? 0) + 1);\n }\n\n const groups = [...grouped.entries()]\n .map(([key, g]) => ({ key, count: g.count, sample: g.sample }))\n .sort((a, b) => b.count - a.count);\n\n const worstNodes = [...byPath.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 3)\n .map(([p, c]) => `${p} (${c} error${c === 1 ? \"\" : \"s\"})`);\n\n const suggestions: string[] = [];\n if (groups[0] && groups[0].count > 1) {\n suggestions.push(\n `${groups[0].count} errors share ${args.group_by} \"${groups[0].key}\" — fixing the common cause clears them at once.`,\n );\n }\n if (worstNodes.length > 0) {\n suggestions.push(`Check first: ${worstNodes.join(\", \")}.`);\n }\n\n return structuredResult(\n `${total} error(s) under ${args.path} in ${groups.length} ${args.group_by} group(s).`,\n { path: args.path, total, group_by: args.group_by, groups, suggestions },\n );\n },\n );\n}\n\nexport const registerSummarizeTdErrors: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"summarize_td_errors\",\n {\n title: \"Summarize network errors\",\n description:\n \"Collect errors across a network and cluster them by message, type, or parent container, with the worst-offending nodes and a suggested order to investigate. Use this instead of reading every node's errors one by one.\",\n inputSchema: summarizeTdErrorsSchema.shape,\n outputSchema: summarizeTdErrorsOutputSchema.shape,\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n (args) => summarizeTdErrorsImpl(ctx, args),\n );\n};\n","import { z } from \"zod\";\nimport { guardTd, jsonResult } from \"../result.js\";\nimport type { ToolContext, ToolRegistrar } from \"../types.js\";\n\nexport const updateTdNodeParametersSchema = z.object({\n path: z.string().describe(\"Full path of the node whose parameters to update.\"),\n parameters: z\n .record(z.string(), z.unknown())\n .describe(\"Parameter overrides as key→value pairs, e.g. { period: 4, amplitude: 0.5 }.\"),\n});\ntype UpdateTdNodeParametersArgs = z.infer<typeof updateTdNodeParametersSchema>;\n\nexport async function updateTdNodeParametersImpl(\n ctx: ToolContext,\n args: UpdateTdNodeParametersArgs,\n) {\n return guardTd(\n () => ctx.client.updateNodeParameters(args.path, args.parameters),\n (node) =>\n jsonResult(`Updated ${Object.keys(args.parameters).length} parameter(s) on ${node.path}.`, {\n node,\n }),\n );\n}\n\nexport const registerUpdateTdNodeParameters: ToolRegistrar = (server, ctx) => {\n server.registerTool(\n \"update_td_node_parameters\",\n {\n title: \"Update node parameters\",\n description: \"Set one or more parameters on an existing node.\",\n inputSchema: updateTdNodeParametersSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },\n },\n (args) => updateTdNodeParametersImpl(ctx, args),\n );\n};\n"],"mapp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D,MAAI,OAAO,OAAQ,SAAQ,OAAO,MAAM,OAAO,MAAM;AACrD,MAAI,OAAO,OAAQ,SAAQ,OAAO,MAAM,OAAO,MAAM;AACrD,UAAQ,WAAW,OAAO;AAC5B;AAEA,IAAM,kBACJ,QAAQ,KAAK,CAAC,MAAM,UAAa,YAAY,QAAQ,cAAc,QAAQ,KAAK,CAAC,CAAC,EAAE;AACtF,IAAI,gBAAiB,MAAK,KAAK;","names":["z","existsSync","existsSync","existsSync","readdirSync","readFileSync","join","z","z","existsSync","readdirSync","readFileSync","join","r","z","z","z","z","z","z","z","z","z","z","z","z","z","z","fetch","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","cmd"]}