-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathmcp-tools.ts
More file actions
1436 lines (1318 loc) · 44.3 KB
/
Copy pathmcp-tools.ts
File metadata and controls
1436 lines (1318 loc) · 44.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MCP Tool wrappers for the Agent system.
*
* These tools give the agent "omnipotent" control over nodetool:
* workflows, nodes, jobs, assets, and models via REST API calls.
*
* Port of src/nodetool/agents/tools/mcp_tools.py
*/
import type { BaseProvider, ProcessingContext } from "@nodetool-ai/runtime";
import type { NodeMetadata, NodeRegistry } from "@nodetool-ai/node-sdk";
import { validateGraph } from "@nodetool-ai/node-sdk";
import { Tool } from "./base-tool.js";
import { LocalListNodesTool } from "./local-list-nodes-tool.js";
import { LocalSearchNodesTool } from "./local-search-nodes-tool.js";
import { LocalGetNodeInfoTool } from "./local-get-node-info-tool.js";
import { FindModelTool } from "./find-model-tool.js";
import {
GenerateImageTool,
EditImageTool,
GenerateVideoTool,
AnimateImageTool,
GenerateSpeechTool,
TranscribeAudioTool,
EmbedTextTool
} from "./media-tools.js";
import { SaveAssetTool, ReadAssetTool } from "./asset-tools.js";
import type { ProcessingMessage } from "@nodetool-ai/protocol";
import { uiToolSchemas } from "@nodetool-ai/protocol";
import { graph as workflowGraphSchema } from "@nodetool-ai/protocol/api-schemas/workflows.js";
import {
applyWorkflowDocumentTool,
WORKFLOW_DOCUMENT_TOOL_NAMES,
type WorkflowDocumentToolName
} from "@nodetool-ai/node-sdk";
import { z } from "zod";
import { GraphPlanner } from "../graph-planner.js";
import { TOOL_CALL_ID_FIELD } from "./subtask-fields.js";
const DEFAULT_API_URL = "http://localhost:7777";
function getApiUrl(context: ProcessingContext): string {
return context.environment?.["NODETOOL_API_URL"] ?? DEFAULT_API_URL;
}
function getHeaders(context: ProcessingContext): Record<string, string> {
const headers: Record<string, string> = {
"Content-Type": "application/json"
};
if (context.userId) {
headers["X-User-Id"] = context.userId;
}
if (context.authToken) {
headers["Authorization"] = `Bearer ${context.authToken}`;
}
return headers;
}
// Column/row spacing for the auto-layout. 280 is NodeTool's default node
// width, so a 320 column gap leaves ~40px between stages.
const LAYOUT_COL_GAP = 320;
const LAYOUT_ROW_GAP = 220;
/**
* Assign a grid position to every node from the graph's dataflow: columns are
* topological depth (longest path from a root), rows are order within a
* column. A left-to-right layered layout — the same shape NodeTool graphs are
* authored in — without a full layout engine (no `elkjs` in the backend).
*/
function computeAutoLayout(
nodeIds: string[],
edges: Array<Record<string, unknown>>
): Map<string, { x: number; y: number }> {
const ids = new Set(nodeIds);
const outgoing = new Map<string, string[]>();
const indegree = new Map<string, number>();
for (const id of nodeIds) {
outgoing.set(id, []);
indegree.set(id, 0);
}
for (const edge of edges) {
const source = edge["source"] == null ? "" : String(edge["source"]);
const target = edge["target"] == null ? "" : String(edge["target"]);
if (source === target || !ids.has(source) || !ids.has(target)) continue;
outgoing.get(source)!.push(target);
indegree.set(target, (indegree.get(target) ?? 0) + 1);
}
// Longest-path layering via Kahn's topological order: each node lands one
// column past its deepest upstream. Roots (no incoming edge) sit in column 0.
const column = new Map<string, number>();
const remaining = new Map(indegree);
const queue: string[] = [];
for (const id of nodeIds) {
column.set(id, 0);
if ((indegree.get(id) ?? 0) === 0) queue.push(id);
}
const ordered: string[] = [];
for (let head = 0; head < queue.length; head++) {
const id = queue[head];
ordered.push(id);
for (const target of outgoing.get(id) ?? []) {
column.set(target, Math.max(column.get(target)!, column.get(id)! + 1));
remaining.set(target, remaining.get(target)! - 1);
if (remaining.get(target) === 0) queue.push(target);
}
}
// A cycle leaves nodes that never reach indegree 0; keep them in column 0 and
// append in original order so they still get a slot.
const placed = new Set(ordered);
for (const id of nodeIds) if (!placed.has(id)) ordered.push(id);
const rowByColumn = new Map<number, number>();
const positions = new Map<string, { x: number; y: number }>();
for (const id of ordered) {
const col = column.get(id) ?? 0;
const row = rowByColumn.get(col) ?? 0;
rowByColumn.set(col, row + 1);
positions.set(id, { x: col * LAYOUT_COL_GAP, y: row * LAYOUT_ROW_GAP });
}
return positions;
}
/**
* Set `ui_properties.position` on every node from {@link computeAutoLayout},
* overriding any caller-supplied coordinates (create_workflow always
* auto-lays-out) while preserving other `ui_properties` fields (title, color).
*/
function withAutoLayout(nodes: unknown, edges: unknown): unknown {
if (!Array.isArray(nodes)) return nodes;
const isRecord = (v: unknown): v is Record<string, unknown> =>
!!v && typeof v === "object" && !Array.isArray(v);
const edgeList = Array.isArray(edges) ? edges.filter(isRecord) : [];
const ids = nodes.filter(isRecord).map((node) => String(node["id"] ?? ""));
const positions = computeAutoLayout(ids, edgeList);
return nodes.map((node) => {
if (!isRecord(node)) return node;
const id = String(node["id"] ?? "");
const ui = isRecord(node["ui_properties"]) ? node["ui_properties"] : {};
return {
...node,
ui_properties: {
zIndex: 0,
width: 280,
selectable: true,
...ui,
position: positions.get(id) ?? { x: 0, y: 0 }
}
};
});
}
/**
* Normalize an agent-authored graph into the *stored* workflow shape.
*
* Two representations exist. The kernel (and `GraphPlanner`/`GraphBuilder`)
* puts a node's property bag under `properties`; the persisted/editor shape
* puts it flat under `data`, with layout under `ui_properties`. Saving kernel
* shape runs fine — `normalizeGraph` in the websocket runner maps `data` →
* `properties` on the way to the kernel and leaves an existing `properties`
* alone — but the editor reads `node.data`, so such a workflow opens with
* every node blank. The planner emits no layout at all, so the nodes would
* also pile at the origin.
*
* This is the boundary where both conversions happen — `create_workflow` is
* the only tool that persists a graph, so it maps `properties` → `data` and
* always auto-lays-out the result.
*/
function normalizeWorkflowGraph(graph: unknown): unknown {
if (!graph || typeof graph !== "object" || Array.isArray(graph)) return graph;
const record = graph as Record<string, unknown>;
const rawNodes = record["nodes"];
const rawEdges = record["edges"];
const normalizeNode = (value: unknown, fallbackId?: string): unknown => {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return value;
}
const node = value as Record<string, unknown>;
// `properties` and `parameters` are dropped from the spread so the stored
// node carries the bag once, under `data`. `ui_properties` stays in `rest`
// and is filled in by `withAutoLayout` below.
const { node_type, parameters, properties, ...rest } = node;
const data = properties ?? parameters ?? node["data"];
return {
...rest,
id: node["id"] ?? fallbackId,
type: node["type"] ?? node_type,
...(data === undefined ? {} : { data })
};
};
const nodes = Array.isArray(rawNodes)
? rawNodes.map((node) => normalizeNode(node))
: rawNodes && typeof rawNodes === "object"
? Object.entries(rawNodes as Record<string, unknown>).map(([id, node]) =>
normalizeNode(node, id)
)
: rawNodes;
const edges = Array.isArray(rawEdges)
? rawEdges.map((value, index) => {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return value;
}
const edge = value as Record<string, unknown>;
const { source_output, target_input, ...rest } = edge;
return {
...rest,
id: edge["id"] ?? `edge-${index}`,
sourceHandle: edge["sourceHandle"] ?? source_output ?? "output",
targetHandle: edge["targetHandle"] ?? target_input
};
})
: rawEdges;
return { ...record, nodes: withAutoLayout(nodes, edges), edges };
}
async function apiGet(
context: ProcessingContext,
path: string,
query?: Record<string, string | number | boolean | undefined>
): Promise<unknown> {
const base = getApiUrl(context);
const url = new URL(path, base);
if (query) {
for (const [k, v] of Object.entries(query)) {
if (v !== undefined) url.searchParams.set(k, String(v));
}
}
const res = await fetch(url.toString(), { headers: getHeaders(context) });
if (!res.ok) {
const text = await res.text();
return { error: `API error ${res.status}: ${text}` };
}
return res.json();
}
async function apiPost(
context: ProcessingContext,
path: string,
body?: unknown
): Promise<unknown> {
const base = getApiUrl(context);
const url = new URL(path, base);
const res = await fetch(url.toString(), {
method: "POST",
headers: getHeaders(context),
body: body !== undefined ? JSON.stringify(body) : undefined
});
if (!res.ok) {
const text = await res.text();
return { error: `API error ${res.status}: ${text}` };
}
return res.json();
}
async function apiPut(
context: ProcessingContext,
path: string,
body: unknown
): Promise<unknown> {
const url = new URL(path, getApiUrl(context));
const res = await fetch(url.toString(), {
method: "PUT",
headers: getHeaders(context),
body: JSON.stringify(body)
});
if (!res.ok) {
const text = await res.text();
return { error: `API error ${res.status}: ${text}` };
}
return res.json();
}
// ============================================================================
// Workflow Tools
// ============================================================================
/** Project a workflow record to a light summary — never the full graph. */
function lightWorkflow(w: unknown): unknown {
if (!w || typeof w !== "object") return w;
const r = w as Record<string, unknown>;
return {
id: r["id"],
name: r["name"],
description: r["description"] ?? null,
tags: r["tags"] ?? null
};
}
/** Strip embedded graphs from a `/api/workflows` list response (array or
* `{ workflows: [...] }`), keeping pagination fields intact. */
function lightWorkflowList(resp: unknown): unknown {
if (Array.isArray(resp)) return resp.map(lightWorkflow);
if (resp && typeof resp === "object") {
const r = resp as Record<string, unknown>;
if (Array.isArray(r["workflows"])) {
return { ...r, workflows: r["workflows"].map(lightWorkflow) };
}
}
return resp;
}
export class ListWorkflowsTool extends Tool {
readonly name = "list_workflows";
readonly description =
"List workflows (id, name, description, tags only — no graph). Returns user workflows, example workflows, or both. Use get_workflow for the full graph of a specific workflow.";
readonly jsonSchema = {
type: "object" as const,
properties: {
workflow_type: {
type: "string" as const,
description: "Type of workflows to list",
enum: ["user", "example", "all"],
default: "user"
},
query: {
type: "string" as const,
description: "Optional search query to filter workflows"
},
limit: {
type: "number" as const,
description: "Maximum number of workflows to return",
default: 100
}
},
required: [] as string[]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
const workflowType = String(params["workflow_type"] ?? "user");
const query = params["query"] as string | undefined;
const limit = Number(params["limit"] ?? 100);
if (workflowType === "example" || workflowType === "all") {
const examples = lightWorkflowList(
await apiGet(context, "/api/workflows/examples", { limit, query })
);
if (workflowType === "example") return examples;
const user = lightWorkflowList(
await apiGet(context, "/api/workflows/", { limit })
);
return { examples, user };
}
return lightWorkflowList(
await apiGet(context, "/api/workflows/", { limit })
);
}
userMessage(params: Record<string, unknown>): string {
const wt = params["workflow_type"] ?? "user";
const q = params["query"];
if (q) return `Listing ${wt} workflows matching '${q}'`;
return `Listing ${wt} workflows`;
}
}
export class GetWorkflowTool extends Tool {
readonly name = "get_workflow";
readonly description =
"Get detailed information about a specific workflow including its graph structure.";
readonly jsonSchema = {
type: "object" as const,
properties: {
workflow_id: {
type: "string" as const,
description: "The ID of the workflow"
}
},
required: ["workflow_id"]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
return apiGet(context, `/api/workflows/${params["workflow_id"]}`);
}
userMessage(params: Record<string, unknown>): string {
return `Getting workflow ${params["workflow_id"]}`;
}
}
export class WorkflowDocumentTool extends Tool {
readonly description: string;
constructor(
readonly name: WorkflowDocumentToolName,
private readonly registry?: NodeRegistry
) {
super();
this.description = uiToolSchemas[name].description;
}
override get schema(): z.ZodType {
return z.object(uiToolSchemas[this.name].parameters);
}
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
const workflowId =
typeof params["workflow_id"] === "string"
? params["workflow_id"]
: context.workflowId;
if (!workflowId) {
return {
error: "workflow_id_required",
message: "workflow_id is required when no workflow is active."
};
}
const response = await apiGet(context, `/api/workflows/${workflowId}`);
if (!response || typeof response !== "object" || Array.isArray(response)) {
return { error: "Invalid workflow response" };
}
const workflow = response as Record<string, unknown>;
if ("error" in workflow) return workflow;
const parsedGraph = workflowGraphSchema.safeParse(workflow["graph"]);
if (!parsedGraph.success) {
return { error: "Workflow has an invalid graph" };
}
const metadataByType = new Map<string, NodeMetadata>();
const loadMetadata = async (nodeType: string): Promise<void> => {
const local = this.registry?.resolveMetadata(nodeType);
if (local) {
metadataByType.set(nodeType, local);
return;
}
const remote = await apiGet(context, "/api/nodes/metadata", {
node_type: nodeType
});
if (
remote &&
typeof remote === "object" &&
!Array.isArray(remote) &&
!("error" in remote)
) {
metadataByType.set(nodeType, remote as NodeMetadata);
}
};
if (this.name === "ui_add_node" && typeof params["type"] === "string") {
await loadMetadata(params["type"]);
} else if (this.name === "ui_connect_nodes") {
const sourceId = String(params["source_node_id"]);
const targetId = String(params["target_node_id"]);
const source = parsedGraph.data.nodes.find(
(node) => node.id === sourceId
);
const target = parsedGraph.data.nodes.find(
(node) => node.id === targetId
);
await Promise.all(
[source?.type, target?.type]
.filter((type): type is string => typeof type === "string")
.map(loadMetadata)
);
}
const applied = applyWorkflowDocumentTool(
parsedGraph.data,
this.name,
params,
{
workflowId,
resolveMetadata: (nodeType) => metadataByType.get(nodeType)
}
);
if (!applied.changed) return applied.result;
const updated = await apiPut(context, `/api/workflows/${workflowId}`, {
name: workflow["name"],
access: workflow["access"] ?? "private",
graph: applied.graph,
tool_name: workflow["tool_name"],
description: workflow["description"],
tags: workflow["tags"],
package_name: workflow["package_name"],
thumbnail: workflow["thumbnail"],
thumbnail_url: workflow["thumbnail_url"],
settings: workflow["settings"],
run_mode: workflow["run_mode"],
workspace_id: workflow["workspace_id"],
html_app: workflow["html_app"],
app_doc: workflow["app_doc"],
expected_updated_at: workflow["updated_at"]
});
if (!updated || typeof updated !== "object" || Array.isArray(updated)) {
return { error: "Invalid workflow update response" };
}
const persisted = updated as Record<string, unknown>;
if ("error" in persisted) return persisted;
return {
...applied.result,
updated_at: persisted["updated_at"],
etag: persisted["etag"]
};
}
}
export function createWorkflowDocumentTools(
registry?: NodeRegistry
): WorkflowDocumentTool[] {
return WORKFLOW_DOCUMENT_TOOL_NAMES.map(
(name) => new WorkflowDocumentTool(name, registry)
);
}
export class CreateWorkflowTool extends Tool {
readonly name = "create_workflow";
readonly description =
"Create a new workflow with a name, graph structure, and optional metadata.";
readonly jsonSchema = {
type: "object" as const,
properties: {
name: { type: "string" as const, description: "The workflow name" },
graph: {
type: "object" as const,
description:
"Workflow graph with nodes and edges. Nodes may be an array of {id, type, properties} or an object keyed by node id with {node_type, parameters}. Edges use source, target, targetHandle/target_input, and optional sourceHandle/source_output (defaults to output)."
},
description: {
type: "string" as const,
description: "Optional workflow description"
},
tags: {
type: "array" as const,
items: { type: "string" as const },
description: "Optional workflow tags"
},
access: {
type: "string" as const,
enum: ["private", "public"],
default: "private"
}
},
required: ["name", "graph"]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
return apiPost(context, "/api/workflows", {
name: params["name"],
graph: normalizeWorkflowGraph(params["graph"]),
description: params["description"],
tags: params["tags"],
access: params["access"] ?? "private"
});
}
userMessage(params: Record<string, unknown>): string {
return `Creating workflow '${params["name"]}'`;
}
}
export class RunWorkflowTool extends Tool {
readonly name = "run_workflow";
readonly description =
"Execute a workflow with given parameters and return results.";
readonly jsonSchema = {
type: "object" as const,
properties: {
workflow_id: {
type: "string" as const,
description: "The ID of the workflow to run"
},
params: {
type: "object" as const,
description: "Dictionary of input parameters for the workflow"
}
},
required: ["workflow_id"]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
return apiPost(context, `/api/workflows/${params["workflow_id"]}/run`, {
params: params["params"] ?? {}
});
}
userMessage(params: Record<string, unknown>): string {
return `Running workflow ${params["workflow_id"]}`;
}
}
/** Distill a workflow API record down to a graph overview for a debug report. */
function summarizeWorkflowGraph(workflow: unknown): unknown {
if (!workflow || typeof workflow !== "object") return workflow;
const wf = workflow as Record<string, unknown>;
const graph = (wf.graph ?? wf) as Record<string, unknown>;
const nodes = Array.isArray(graph.nodes)
? (graph.nodes as Array<Record<string, unknown>>)
: [];
const edges = Array.isArray(graph.edges)
? (graph.edges as Array<Record<string, unknown>>)
: [];
return {
id: wf.id,
name: wf.name,
node_count: nodes.length,
edge_count: edges.length,
node_types: [...new Set(nodes.map((n) => String(n.type ?? "unknown")))],
nodes: nodes.map((n) => ({ id: n.id, type: n.type })),
edges
};
}
export class DebugWorkflowTool extends Tool {
readonly name = "debug_workflow";
readonly description =
"Run a workflow end-to-end and return a consolidated debug report: final " +
"status, outputs, error, job logs, and the workflow graph overview. Use this " +
"to troubleshoot a failing or misbehaving workflow and iterate on a fix.";
readonly jsonSchema = {
type: "object" as const,
properties: {
workflow_id: {
type: "string" as const,
description: "The ID of the workflow to run and debug"
},
params: {
type: "object" as const,
description: "Input parameters keyed by input-node name"
},
include_graph: {
type: "boolean" as const,
description:
"Include the workflow graph overview in the report (default true)"
},
log_limit: {
type: "number" as const,
description: "Maximum job log entries to include (default 200)"
}
},
required: ["workflow_id"]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
const workflowId = String(params["workflow_id"]);
const includeGraph = params["include_graph"] !== false;
const logLimit = Number(params["log_limit"] ?? 200);
const run = await apiPost(context, `/api/workflows/${workflowId}/run`, {
params: params["params"] ?? {}
});
const report: Record<string, unknown> = { workflow_id: workflowId, run };
const jobId = (run as Record<string, unknown>)?.["job_id"];
if (typeof jobId === "string") {
report["job"] = await apiGet(context, `/api/jobs/${jobId}`, {
limit: logLimit
});
}
if (includeGraph) {
const wf = await apiGet(context, `/api/workflows/${workflowId}`);
report["workflow"] = summarizeWorkflowGraph(wf);
}
return report;
}
userMessage(params: Record<string, unknown>): string {
return `Debugging workflow ${params["workflow_id"]}`;
}
}
export class ValidateWorkflowTool extends Tool {
readonly name = "validate_workflow";
readonly description =
"Statically validate a workflow against the node registry WITHOUT running " +
"it: unknown node types, missing required properties, unselected models, " +
"and dangling or mis-typed edges. Pass an inline `graph` to check a graph " +
"you are building, or `workflow_id` to validate a saved one. Run this " +
"before saving or running to catch breakage in milliseconds.";
readonly jsonSchema = {
type: "object" as const,
properties: {
workflow_id: {
type: "string" as const,
description:
"The ID of a saved workflow to validate (fetched from the API)"
},
graph: {
type: "object" as const,
description:
"Inline graph to validate ({ nodes, edges }). Takes precedence over workflow_id."
}
}
};
// When a registry is available the tool validates locally; without one it
// falls back to fetching the workflow so the tool still returns something
// useful in registry-free contexts (e.g. the multi-task planner).
constructor(private readonly registry?: NodeRegistry) {
super();
}
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
let graph = params["graph"] as
| { nodes?: unknown[]; edges?: unknown[] }
| undefined;
const workflowId = params["workflow_id"] as string | undefined;
if (!graph && workflowId) {
const wf = (await apiGet(context, `/api/workflows/${workflowId}`)) as
| Record<string, unknown>
| undefined;
if (wf && "error" in wf) return wf;
graph = (wf?.["graph"] ?? wf) as typeof graph;
}
if (!graph || !Array.isArray(graph.nodes)) {
return {
error:
"No graph to validate — pass an inline `graph` ({nodes, edges}) or a valid `workflow_id`."
};
}
if (!this.registry) {
return {
note: "No in-process node registry available; returning the graph unvalidated. Run `nodetool validate` from the CLI for a full static check.",
graph
};
}
return validateGraph(
{ nodes: graph.nodes as never[], edges: (graph.edges ?? []) as never[] },
this.registry
);
}
userMessage(params: Record<string, unknown>): string {
return params["workflow_id"]
? `Validating workflow ${params["workflow_id"]}`
: "Validating workflow graph";
}
}
export interface PlanWorkflowGraphToolOptions {
provider: BaseProvider;
model: string;
registry: NodeRegistry;
/** Configured providers by id — enables the planner's `find_model` tool. */
providers?: Record<string, BaseProvider>;
/**
* Forwards planner progress events (planning_update, tool_call_update,
* chunk) to the client. Events arrive tagged with `parent_tool_call_id`
* so the UI can nest them under this tool's call card.
*/
forwardMessage?: (msg: ProcessingMessage) => Promise<void> | void;
/**
* Resolves the abort signal for the *current* chat turn. Read lazily on each
* call: the tool outlives a single turn, and each turn installs a fresh
* controller, so a captured signal would go stale after the first Stop.
*/
signal?: () => AbortSignal | undefined;
}
export class PlanWorkflowGraphTool extends Tool {
readonly name = "plan_workflow_graph";
readonly needsToolCallId = true;
readonly description =
"Build a complete workflow graph ({nodes, edges}) from a natural-language " +
"objective using the backend GraphPlanner: it searches the node registry, " +
"inspects node metadata, and wires a validated DAG node-by-node. Returns " +
"the graph without saving or running it — pass the result to " +
"`create_workflow` to save, then `run_workflow` to execute.";
readonly jsonSchema = {
type: "object" as const,
properties: {
objective: {
type: "string" as const,
description:
"Natural-language description of what the workflow should do."
},
inputs: {
type: "object" as const,
description:
"Runtime parameters the workflow should accept, keyed by input " +
"name with example values. Each becomes an input node in the graph."
}
},
required: ["objective"]
};
constructor(private readonly opts: PlanWorkflowGraphToolOptions) {
super();
}
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
const objective =
typeof params["objective"] === "string" ? params["objective"].trim() : "";
if (!objective) {
return {
error: "`objective` is required and must be a non-empty string."
};
}
const parentToolCallId =
typeof params[TOOL_CALL_ID_FIELD] === "string"
? (params[TOOL_CALL_ID_FIELD] as string)
: null;
const signal = this.opts.signal?.();
if (signal?.aborted) {
return { error: "Graph planning was cancelled." };
}
const planner = new GraphPlanner({
provider: this.opts.provider,
model: this.opts.model,
registry: this.opts.registry,
tools: [],
inputs: (params["inputs"] as Record<string, unknown>) ?? {},
providers: this.opts.providers,
signal
});
const gen = planner.plan(objective, context);
let next = await gen.next();
while (!next.done) {
// The planner's own abort stops its LLM loop, but a tool call already
// in flight still resolves — stop driving the generator so a Stop ends
// the turn promptly instead of after the current round.
if (signal?.aborted) {
await gen.return(null);
return { error: "Graph planning was cancelled." };
}
if (this.opts.forwardMessage) {
const tagged = {
...(next.value as unknown as Record<string, unknown>),
parent_tool_call_id: parentToolCallId
} as unknown as ProcessingMessage;
try {
await this.opts.forwardMessage(tagged);
} catch {
// A broken forwarder must not kill planning — the model still gets
// the graph via the tool return below.
}
}
next = await gen.next();
}
if (signal?.aborted) {
return { error: "Graph planning was cancelled." };
}
const graph = next.value;
if (!graph) {
return {
error:
"GraphPlanner failed to build a graph after multiple attempts. " +
"Refine the objective (name concrete inputs/outputs) and retry."
};
}
return {
graph,
node_count: graph.nodes.length,
edge_count: graph.edges.length
};
}
userMessage(params: Record<string, unknown>): string {
const objective =
typeof params["objective"] === "string"
? params["objective"].slice(0, 80)
: "workflow";
return `Planning workflow graph: ${objective}`;
}
}
export class GetExampleWorkflowTool extends Tool {
readonly name = "get_example_workflow";
readonly description =
"Load a specific example workflow from a package by name.";
readonly jsonSchema = {
type: "object" as const,
properties: {
package_name: {
type: "string" as const,
description: "The name of the package containing the example"
},
example_name: {
type: "string" as const,
description: "The name of the example workflow to load"
}
},
required: ["package_name", "example_name"]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
return apiGet(
context,
`/api/workflows/examples/${params["package_name"]}/${params["example_name"]}`
);
}
userMessage(params: Record<string, unknown>): string {
return `Loading example ${params["package_name"]}/${params["example_name"]}`;
}
}
export class ExportWorkflowDigraphTool extends Tool {
readonly name = "export_workflow_digraph";
readonly description =
"Export a workflow as a Graphviz Digraph (DOT format) for visualization.";
readonly jsonSchema = {
type: "object" as const,
properties: {
workflow_id: {
type: "string" as const,
description: "The ID of the workflow to export"
},
descriptive_names: {
type: "boolean" as const,
description: "Use descriptive node names instead of UUIDs",
default: true
}
},
required: ["workflow_id"]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
return apiGet(
context,
`/api/workflows/${params["workflow_id"]}/dsl-export`
);
}
userMessage(params: Record<string, unknown>): string {
return `Exporting workflow ${params["workflow_id"]} as digraph`;
}
}
// ============================================================================
// Node Tools
// ============================================================================
export class ListNodesTool extends Tool {
readonly name = "list_nodes";
readonly description =
"List available nodes from installed packages. Use this to discover nodes for building workflows.";
readonly jsonSchema = {
type: "object" as const,
properties: {
namespace: {
type: "string" as const,
description: "Optional namespace prefix filter (e.g. 'nodetool.text')"
},
limit: {
type: "number" as const,
description: "Maximum number of nodes to return",
default: 200
}
},
required: [] as string[]
};
async process(
context: ProcessingContext,
params: Record<string, unknown>
): Promise<unknown> {
return apiGet(context, "/api/nodes/metadata", {
namespace: params["namespace"] as string | undefined,
limit: Number(params["limit"] ?? 200)
});
}
userMessage(params: Record<string, unknown>): string {
const ns = params["namespace"];
return ns ? `Listing nodes in namespace ${ns}` : "Listing available nodes";