n8n-ops-mcp 0.10.0 → 0.11.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.
package/README.md CHANGED
@@ -40,6 +40,8 @@ For a catalog/docs tool that indexes n8n's node library, see [n8n-mcp](https://w
40
40
  | `n8n_retry_execution` | Retry a failed execution by id (returns a new execution) | ✓ |
41
41
  | `n8n_delete_execution` | Permanently delete an execution record (confirm-gated, irreversible) | ✓ |
42
42
  | `n8n_delete_executions` | Batch form of delete (client-side fan-out, confirm-gated, irreversible, max 50 ids) | ✓ |
43
+ | `n8n_pin_node_data` | Pin sample data to a node so downstream nodes use it during testing (confirm-gated, replace-or-merge) | ✓ |
44
+ | `n8n_unpin_node_data` | Clear pinned data on one node or the whole workflow (confirm-gated, idempotent) | ✓ |
43
45
 
44
46
  Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
45
47
 
@@ -88,6 +90,10 @@ Write tools are hidden unless `N8N_ENABLE_EDIT=true`.
88
90
 
89
91
  **`n8n_delete_execution`** - `DELETE /executions/{id}`. Permanently removes an execution record: logs, per-node run data, and error payloads are erased from n8n. Requires `confirm: true` to actually delete; calling with `confirm: false` returns `ok: false` and never touches the API (omitting `confirm` is rejected at the MCP schema layer). Returns `ok: false` with `reason: "not_found"` on 404; all other API errors rethrow. Not idempotent from an agent's perspective: the record is gone after the first successful call, so fetch `n8n_get_execution` first if you may need it later.
90
92
 
93
+ **`n8n_pin_node_data`** - pin sample data to a node so downstream nodes use it during testing/development without re-running the upstream node. Pairs naturally with `n8n_scaffold_browser_bridge_node`: scaffold a browser-bridge call, run it once, capture the output, pin it, then iterate on downstream nodes without re-spawning the browser. Inputs: `id`, `nodeName` (case-sensitive, must match an existing node), `data` (1-50 items; raw objects are auto-wrapped into `{json: <object>}`, items already shaped as `{json: ..., binary?: ...}` pass through unchanged), optional `merge: true` to append to existing pinned data instead of replacing (combined still capped at 50), `confirm: true`. Issues PUT `/workflows/{id}` with merged `pinData` plus the existing nodes/connections/settings/staticData (so the PUT does not blank them). Pinned data persists across executions until cleared — easy to forget; the response includes an `unpinHint`.
94
+
95
+ **`n8n_unpin_node_data`** - clear pinned data on one node (when `nodeName` is supplied) or the whole workflow (when omitted). Idempotent: clearing a node that wasn't pinned returns `ok: true` with `noop: true` and never touches the API. When clearing actually happens, the PUT includes the rest of the workflow body so other fields are not blanked. Requires `confirm: true`.
96
+
91
97
  **`n8n_delete_executions`** - batch form. Client-side fan-out over `DELETE /executions/{id}` with bounded concurrency (default 3, max 10). Takes an `ids` array (deduped before fan-out, capped at 50), requires `confirm: true`. Response surfaces `requested`/`attempted`/`deleted`/`alreadyDeleted`/`failed`/`skipped`/`aborted` counters plus a `results: Array<{id, ok, reason?, message?}>` - order is completion order, not input order, so look up by id. 404 per id is treated as `already_deleted` (idempotent). A 5xx on any id aborts the batch via an `AbortController`: no new ids are claimed and any already-in-flight `fetch`es are cancelled client-side. Under concurrency N, up to N-1 deletes may have already reached the server before the 5xx is observed, so the batch is best-effort, not transactional - clear signal the server is sick; don't retry blindly. Per-id error messages are passed through the API-key redactor. Compose with `n8n_search_executions` to purge a known set of noisy runs in one call.
92
98
 
93
99
  </details>
@@ -271,6 +277,10 @@ Calls `n8n_audit_browser_bridge_usage` with `platform: "linktree"` to list every
271
277
 
272
278
  Calls `n8n_scaffold_browser_bridge_node` with `platform: "coderlegion"`, `action: "scan-comments"`, `input: {limit: 5}` to get a Code node JSON, then pastes it into n8n.
273
279
 
280
+ > Pin a sample browser-bridge response on the "BB call" node so I can iterate on downstream parsing without re-spawning the browser *(requires `N8N_ENABLE_EDIT=true`)*
281
+
282
+ Calls `n8n_get_execution` to grab the most recent successful output of the node, then `n8n_pin_node_data` with `nodeName: "BB call"`, `data: <captured items>`, `confirm: true`. Clear later via `n8n_unpin_node_data`.
283
+
274
284
  > Audit my workflows for deprecated Code-node API usage
275
285
 
276
286
  Calls `n8n_list_workflows` then `n8n_validate_workflow` per id, filters for `code-node-old-node-ref` and `code-node-items-global` warnings.
@@ -2670,8 +2670,255 @@ function deepEqual(a, b) {
2670
2670
  return true;
2671
2671
  }
2672
2672
 
2673
+ // src/tools/pin-node-data.ts
2674
+ import { Type as Type22 } from "@sinclair/typebox";
2675
+ var Schema22 = Type22.Object(
2676
+ {
2677
+ id: Type22.String({ description: "Workflow id (from n8n_list_workflows)." }),
2678
+ nodeName: Type22.String({
2679
+ minLength: 1,
2680
+ description: "Name of the node to pin data on (case-sensitive). Must be the n8n node 'name' field, not the type. Use n8n_get_workflow(includeDefinition=true) to look up exact names."
2681
+ }),
2682
+ data: Type22.Array(
2683
+ Type22.Record(Type22.String(), Type22.Unknown()),
2684
+ {
2685
+ minItems: 1,
2686
+ maxItems: 50,
2687
+ description: "Items to pin (max 50). Each item may be a fully-shaped n8n run item (`{json: {...}, binary?: {...}}`) or a raw object \u2014 raw objects are auto-wrapped into `{json: <object>}`."
2688
+ }
2689
+ ),
2690
+ merge: Type22.Optional(
2691
+ Type22.Boolean({
2692
+ description: "If true, append to existing pinned data on the node instead of replacing it (combined total still capped at 50). Default false (replace)."
2693
+ })
2694
+ ),
2695
+ confirm: Type22.Boolean({
2696
+ description: "Must be true to actually write. Pinned data persists across executions and overrides node output until cleared via n8n_unpin_node_data \u2014 easy to forget about."
2697
+ })
2698
+ },
2699
+ { additionalProperties: false }
2700
+ );
2701
+ var MAX_TOTAL_ITEMS = 50;
2702
+ function createPinNodeDataTool(getClient) {
2703
+ return {
2704
+ name: "n8n_pin_node_data",
2705
+ label: "n8n: pin node data",
2706
+ description: "Pin sample data to a node so downstream nodes use it during testing/development without re-running the upstream node. Useful after scaffolding a browser-bridge call: run it once, capture the output, pin it, then iterate on downstream nodes without re-spawning the browser. Issues PUT /workflows/{id} with merged pinData. Pinned data overrides actual node output on subsequent executions until cleared with n8n_unpin_node_data \u2014 easy to forget. Requires enableEdit and explicit confirm=true.",
2707
+ parameters: Schema22,
2708
+ execute: async (_toolCallId, rawParams) => {
2709
+ const params = rawParams;
2710
+ if (!params.confirm) {
2711
+ return jsonToolResult({
2712
+ ok: false,
2713
+ error: "confirm must be true to pin data"
2714
+ });
2715
+ }
2716
+ const client = getClient();
2717
+ let current;
2718
+ try {
2719
+ current = await client.getWorkflow(params.id);
2720
+ } catch (err) {
2721
+ const msg = err instanceof Error ? err.message : String(err);
2722
+ return jsonToolResult({
2723
+ ok: false,
2724
+ error: `failed to fetch workflow: ${client.redact(msg)}`
2725
+ });
2726
+ }
2727
+ const nodeExists = nodeNameExists(current.nodes, params.nodeName);
2728
+ if (!nodeExists) {
2729
+ return jsonToolResult({
2730
+ ok: false,
2731
+ error: `node "${params.nodeName}" not found in workflow ${params.id}. Use n8n_get_workflow(includeDefinition=true) to look up exact names.`
2732
+ });
2733
+ }
2734
+ const incoming = params.data.map(normalizeItem);
2735
+ const existingForNode = readNodePinData(current.pinData, params.nodeName);
2736
+ const merged = params.merge ? [...existingForNode, ...incoming] : incoming;
2737
+ if (merged.length > MAX_TOTAL_ITEMS) {
2738
+ return jsonToolResult({
2739
+ ok: false,
2740
+ error: `combined pinned items (${merged.length}) exceeds cap of ${MAX_TOTAL_ITEMS}. Reduce the input or unpin existing data first.`
2741
+ });
2742
+ }
2743
+ const newPinData = {
2744
+ ...current.pinData ?? {},
2745
+ [params.nodeName]: merged
2746
+ };
2747
+ const body = buildBody(current, { pinData: newPinData });
2748
+ try {
2749
+ const saved = await client.saveWorkflow(params.id, body);
2750
+ return jsonToolResult({
2751
+ ok: true,
2752
+ action: "pin",
2753
+ workflowId: saved.id,
2754
+ nodeName: params.nodeName,
2755
+ pinnedItemCount: merged.length,
2756
+ replaced: !params.merge && existingForNode.length > 0,
2757
+ appended: params.merge ? incoming.length : 0,
2758
+ versionId: saved.versionId ?? null,
2759
+ updatedAt: saved.updatedAt,
2760
+ unpinHint: `To clear: n8n_unpin_node_data(id=${saved.id}, nodeName=${JSON.stringify(params.nodeName)}, confirm=true).`
2761
+ });
2762
+ } catch (err) {
2763
+ const msg = err instanceof Error ? err.message : String(err);
2764
+ return jsonToolResult({
2765
+ ok: false,
2766
+ error: `pin failed: ${client.redact(msg)}`
2767
+ });
2768
+ }
2769
+ }
2770
+ };
2771
+ }
2772
+ function nodeNameExists(nodes, nodeName) {
2773
+ if (!Array.isArray(nodes)) return false;
2774
+ return nodes.some(
2775
+ (n) => n && typeof n === "object" && typeof n.name === "string" && n.name === nodeName
2776
+ );
2777
+ }
2778
+ function readNodePinData(pinData, nodeName) {
2779
+ if (!pinData) return [];
2780
+ const existing = pinData[nodeName];
2781
+ return Array.isArray(existing) ? existing : [];
2782
+ }
2783
+ function normalizeItem(item) {
2784
+ if ("json" in item) return item;
2785
+ return { json: item };
2786
+ }
2787
+ function buildBody(current, patch) {
2788
+ const body = {
2789
+ name: current.name,
2790
+ nodes: current.nodes,
2791
+ connections: current.connections,
2792
+ settings: current.settings ?? {}
2793
+ };
2794
+ if (patch.staticData !== void 0) {
2795
+ body.staticData = patch.staticData;
2796
+ } else if (current.staticData !== void 0) {
2797
+ body.staticData = current.staticData;
2798
+ }
2799
+ if (patch.pinData !== void 0) {
2800
+ body.pinData = patch.pinData;
2801
+ } else if (current.pinData !== void 0) {
2802
+ body.pinData = current.pinData;
2803
+ }
2804
+ return body;
2805
+ }
2806
+
2807
+ // src/tools/unpin-node-data.ts
2808
+ import { Type as Type23 } from "@sinclair/typebox";
2809
+ var Schema23 = Type23.Object(
2810
+ {
2811
+ id: Type23.String({ description: "Workflow id (from n8n_list_workflows)." }),
2812
+ nodeName: Type23.Optional(
2813
+ Type23.String({
2814
+ minLength: 1,
2815
+ description: "Name of the node to unpin (case-sensitive). Omit to clear ALL pinned data on the workflow."
2816
+ })
2817
+ ),
2818
+ confirm: Type23.Boolean({
2819
+ description: "Must be true to actually clear the pinned data. Idempotent: nodes with no pinned data are a no-op (returns ok=true with noop=true)."
2820
+ })
2821
+ },
2822
+ { additionalProperties: false }
2823
+ );
2824
+ function createUnpinNodeDataTool(getClient) {
2825
+ return {
2826
+ name: "n8n_unpin_node_data",
2827
+ label: "n8n: unpin node data",
2828
+ description: "Clear pinned data on one node (or the whole workflow when nodeName is omitted) so executions return to using live node output. Idempotent \u2014 clearing a node that wasn't pinned returns ok=true with noop=true. Issues PUT /workflows/{id} with the modified pinData. Requires enableEdit and explicit confirm=true.",
2829
+ parameters: Schema23,
2830
+ execute: async (_toolCallId, rawParams) => {
2831
+ const params = rawParams;
2832
+ if (!params.confirm) {
2833
+ return jsonToolResult({
2834
+ ok: false,
2835
+ error: "confirm must be true to unpin data"
2836
+ });
2837
+ }
2838
+ const client = getClient();
2839
+ let current;
2840
+ try {
2841
+ current = await client.getWorkflow(params.id);
2842
+ } catch (err) {
2843
+ const msg = err instanceof Error ? err.message : String(err);
2844
+ return jsonToolResult({
2845
+ ok: false,
2846
+ error: `failed to fetch workflow: ${client.redact(msg)}`
2847
+ });
2848
+ }
2849
+ const existing = current.pinData ?? {};
2850
+ const existingKeys = Object.keys(existing);
2851
+ if (!params.nodeName) {
2852
+ if (existingKeys.length === 0) {
2853
+ return jsonToolResult({
2854
+ ok: true,
2855
+ action: "unpin",
2856
+ workflowId: current.id,
2857
+ scope: "workflow",
2858
+ noop: true,
2859
+ clearedNodes: []
2860
+ });
2861
+ }
2862
+ const body2 = buildBody(current, { pinData: {} });
2863
+ try {
2864
+ const saved = await client.saveWorkflow(params.id, body2);
2865
+ return jsonToolResult({
2866
+ ok: true,
2867
+ action: "unpin",
2868
+ workflowId: saved.id,
2869
+ scope: "workflow",
2870
+ noop: false,
2871
+ clearedNodes: existingKeys,
2872
+ versionId: saved.versionId ?? null,
2873
+ updatedAt: saved.updatedAt
2874
+ });
2875
+ } catch (err) {
2876
+ const msg = err instanceof Error ? err.message : String(err);
2877
+ return jsonToolResult({
2878
+ ok: false,
2879
+ error: `unpin failed: ${client.redact(msg)}`
2880
+ });
2881
+ }
2882
+ }
2883
+ const nodeName = params.nodeName;
2884
+ if (!(nodeName in existing)) {
2885
+ return jsonToolResult({
2886
+ ok: true,
2887
+ action: "unpin",
2888
+ workflowId: current.id,
2889
+ scope: "node",
2890
+ nodeName,
2891
+ noop: true
2892
+ });
2893
+ }
2894
+ const newPinData = { ...existing };
2895
+ delete newPinData[nodeName];
2896
+ const body = buildBody(current, { pinData: newPinData });
2897
+ try {
2898
+ const saved = await client.saveWorkflow(params.id, body);
2899
+ return jsonToolResult({
2900
+ ok: true,
2901
+ action: "unpin",
2902
+ workflowId: saved.id,
2903
+ scope: "node",
2904
+ nodeName,
2905
+ noop: false,
2906
+ versionId: saved.versionId ?? null,
2907
+ updatedAt: saved.updatedAt
2908
+ });
2909
+ } catch (err) {
2910
+ const msg = err instanceof Error ? err.message : String(err);
2911
+ return jsonToolResult({
2912
+ ok: false,
2913
+ error: `unpin failed: ${client.redact(msg)}`
2914
+ });
2915
+ }
2916
+ }
2917
+ };
2918
+ }
2919
+
2673
2920
  // mcp-server.ts
2674
- var VERSION = "0.10.0";
2921
+ var VERSION = "0.11.0";
2675
2922
  function readConfigFromEnv() {
2676
2923
  const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
2677
2924
  if (!baseUrl) {
@@ -2929,6 +3176,30 @@ async function main() {
2929
3176
  ),
2930
3177
  skipValidation: z.boolean().optional().describe("Skip the validate-workflow pre-check. Default false.")
2931
3178
  });
3179
+ bind(server, createPinNodeDataTool(getClient), {
3180
+ id: z.string().describe("Workflow id (from n8n_list_workflows)."),
3181
+ nodeName: z.string().min(1).describe(
3182
+ "Name of the node to pin data on (case-sensitive). Must be the n8n node 'name' field, not the type."
3183
+ ),
3184
+ data: z.array(z.record(z.string(), z.unknown())).min(1).max(50).describe(
3185
+ "Items to pin (max 50). Each item may be a fully-shaped n8n run item (`{json: {...}}`) or a raw object \u2014 raw objects are auto-wrapped into `{json: <object>}`."
3186
+ ),
3187
+ merge: z.boolean().optional().describe(
3188
+ "If true, append to existing pinned data on the node instead of replacing (combined total still capped at 50). Default false."
3189
+ ),
3190
+ confirm: z.boolean().describe(
3191
+ "Must be true to actually write. Pinned data persists across executions and overrides node output until cleared."
3192
+ )
3193
+ });
3194
+ bind(server, createUnpinNodeDataTool(getClient), {
3195
+ id: z.string().describe("Workflow id (from n8n_list_workflows)."),
3196
+ nodeName: z.string().min(1).optional().describe(
3197
+ "Name of the node to unpin (case-sensitive). Omit to clear ALL pinned data on the workflow."
3198
+ ),
3199
+ confirm: z.boolean().describe(
3200
+ "Must be true to actually clear pinned data. Idempotent: clearing a node that wasn't pinned returns ok=true with noop=true."
3201
+ )
3202
+ });
2932
3203
  }
2933
3204
  const transport = new StdioServerTransport();
2934
3205
  await server.connect(transport);
package/index.ts CHANGED
@@ -25,6 +25,8 @@ import { createCreateWorkflowTool } from "./src/tools/create-workflow.ts";
25
25
  import { createAuditBrowserBridgeUsageTool } from "./src/tools/audit-browser-bridge-usage.ts";
26
26
  import { createScaffoldBrowserBridgeNodeTool } from "./src/tools/scaffold-browser-bridge-node.ts";
27
27
  import { createDiffWorkflowTool } from "./src/tools/diff-workflow.ts";
28
+ import { createPinNodeDataTool } from "./src/tools/pin-node-data.ts";
29
+ import { createUnpinNodeDataTool } from "./src/tools/unpin-node-data.ts";
28
30
 
29
31
  export default definePluginEntry({
30
32
  id: "n8n",
@@ -82,6 +84,8 @@ export default definePluginEntry({
82
84
  }) as AnyAgentTool,
83
85
  );
84
86
  api.registerTool(createCreateWorkflowTool({ getClient }) as AnyAgentTool);
87
+ api.registerTool(createPinNodeDataTool(getClient) as AnyAgentTool);
88
+ api.registerTool(createUnpinNodeDataTool(getClient) as AnyAgentTool);
85
89
  }
86
90
  },
87
91
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-ops-mcp",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Ops-focused n8n tools for any MCP-compatible client: list, inspect, trigger, validate, plus full workflow + execution lifecycle (create, save, archive, delete, cancel, retry). MCP server + first-class OpenClaw plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,176 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { N8nClient, N8nWorkflow } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+
5
+ const Schema = Type.Object(
6
+ {
7
+ id: Type.String({ description: "Workflow id (from n8n_list_workflows)." }),
8
+ nodeName: Type.String({
9
+ minLength: 1,
10
+ description:
11
+ "Name of the node to pin data on (case-sensitive). Must be the n8n node 'name' field, not the type. Use n8n_get_workflow(includeDefinition=true) to look up exact names.",
12
+ }),
13
+ data: Type.Array(
14
+ Type.Record(Type.String(), Type.Unknown()),
15
+ {
16
+ minItems: 1,
17
+ maxItems: 50,
18
+ description:
19
+ "Items to pin (max 50). Each item may be a fully-shaped n8n run item (`{json: {...}, binary?: {...}}`) or a raw object — raw objects are auto-wrapped into `{json: <object>}`.",
20
+ },
21
+ ),
22
+ merge: Type.Optional(
23
+ Type.Boolean({
24
+ description:
25
+ "If true, append to existing pinned data on the node instead of replacing it (combined total still capped at 50). Default false (replace).",
26
+ }),
27
+ ),
28
+ confirm: Type.Boolean({
29
+ description:
30
+ "Must be true to actually write. Pinned data persists across executions and overrides node output until cleared via n8n_unpin_node_data — easy to forget about.",
31
+ }),
32
+ },
33
+ { additionalProperties: false },
34
+ );
35
+
36
+ const MAX_TOTAL_ITEMS = 50;
37
+
38
+ export function createPinNodeDataTool(getClient: () => N8nClient) {
39
+ return {
40
+ name: "n8n_pin_node_data",
41
+ label: "n8n: pin node data",
42
+ description:
43
+ "Pin sample data to a node so downstream nodes use it during testing/development without re-running the upstream node. Useful after scaffolding a browser-bridge call: run it once, capture the output, pin it, then iterate on downstream nodes without re-spawning the browser. Issues PUT /workflows/{id} with merged pinData. Pinned data overrides actual node output on subsequent executions until cleared with n8n_unpin_node_data — easy to forget. Requires enableEdit and explicit confirm=true.",
44
+ parameters: Schema,
45
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
46
+ const params = rawParams as {
47
+ id: string;
48
+ nodeName: string;
49
+ data: Array<Record<string, unknown>>;
50
+ merge?: boolean;
51
+ confirm: boolean;
52
+ };
53
+ if (!params.confirm) {
54
+ return jsonToolResult({
55
+ ok: false,
56
+ error: "confirm must be true to pin data",
57
+ });
58
+ }
59
+
60
+ const client = getClient();
61
+
62
+ let current: N8nWorkflow;
63
+ try {
64
+ current = await client.getWorkflow(params.id);
65
+ } catch (err) {
66
+ const msg = err instanceof Error ? err.message : String(err);
67
+ return jsonToolResult({
68
+ ok: false,
69
+ error: `failed to fetch workflow: ${client.redact(msg)}`,
70
+ });
71
+ }
72
+
73
+ const nodeExists = nodeNameExists(current.nodes, params.nodeName);
74
+ if (!nodeExists) {
75
+ return jsonToolResult({
76
+ ok: false,
77
+ error: `node "${params.nodeName}" not found in workflow ${params.id}. Use n8n_get_workflow(includeDefinition=true) to look up exact names.`,
78
+ });
79
+ }
80
+
81
+ const incoming = params.data.map(normalizeItem);
82
+ const existingForNode = readNodePinData(current.pinData, params.nodeName);
83
+ const merged = params.merge
84
+ ? [...existingForNode, ...incoming]
85
+ : incoming;
86
+
87
+ if (merged.length > MAX_TOTAL_ITEMS) {
88
+ return jsonToolResult({
89
+ ok: false,
90
+ error: `combined pinned items (${merged.length}) exceeds cap of ${MAX_TOTAL_ITEMS}. Reduce the input or unpin existing data first.`,
91
+ });
92
+ }
93
+
94
+ const newPinData: Record<string, unknown> = {
95
+ ...(current.pinData ?? {}),
96
+ [params.nodeName]: merged,
97
+ };
98
+ const body = buildBody(current, { pinData: newPinData });
99
+
100
+ try {
101
+ const saved = await client.saveWorkflow(params.id, body);
102
+ return jsonToolResult({
103
+ ok: true,
104
+ action: "pin",
105
+ workflowId: saved.id,
106
+ nodeName: params.nodeName,
107
+ pinnedItemCount: merged.length,
108
+ replaced: !params.merge && existingForNode.length > 0,
109
+ appended: params.merge ? incoming.length : 0,
110
+ versionId: saved.versionId ?? null,
111
+ updatedAt: saved.updatedAt,
112
+ unpinHint: `To clear: n8n_unpin_node_data(id=${saved.id}, nodeName=${JSON.stringify(params.nodeName)}, confirm=true).`,
113
+ });
114
+ } catch (err) {
115
+ const msg = err instanceof Error ? err.message : String(err);
116
+ return jsonToolResult({
117
+ ok: false,
118
+ error: `pin failed: ${client.redact(msg)}`,
119
+ });
120
+ }
121
+ },
122
+ };
123
+ }
124
+
125
+ function nodeNameExists(nodes: unknown, nodeName: string): boolean {
126
+ if (!Array.isArray(nodes)) return false;
127
+ return nodes.some(
128
+ (n) =>
129
+ n &&
130
+ typeof n === "object" &&
131
+ typeof (n as Record<string, unknown>).name === "string" &&
132
+ (n as Record<string, unknown>).name === nodeName,
133
+ );
134
+ }
135
+
136
+ function readNodePinData(
137
+ pinData: Record<string, unknown> | undefined,
138
+ nodeName: string,
139
+ ): Array<Record<string, unknown>> {
140
+ if (!pinData) return [];
141
+ const existing = pinData[nodeName];
142
+ return Array.isArray(existing)
143
+ ? (existing as Array<Record<string, unknown>>)
144
+ : [];
145
+ }
146
+
147
+ function normalizeItem(item: Record<string, unknown>): Record<string, unknown> {
148
+ // Accept both shapes: full run-item (`{json: ..., binary?: ...}`) or raw
149
+ // payload — raw wraps into `{json: item}` so callers don't have to remember
150
+ // n8n's internal item shape.
151
+ if ("json" in item) return item;
152
+ return { json: item };
153
+ }
154
+
155
+ export function buildBody(
156
+ current: N8nWorkflow,
157
+ patch: { pinData?: Record<string, unknown>; staticData?: unknown },
158
+ ): Record<string, unknown> {
159
+ const body: Record<string, unknown> = {
160
+ name: current.name,
161
+ nodes: current.nodes,
162
+ connections: current.connections,
163
+ settings: current.settings ?? {},
164
+ };
165
+ if (patch.staticData !== undefined) {
166
+ body.staticData = patch.staticData;
167
+ } else if (current.staticData !== undefined) {
168
+ body.staticData = current.staticData;
169
+ }
170
+ if (patch.pinData !== undefined) {
171
+ body.pinData = patch.pinData;
172
+ } else if (current.pinData !== undefined) {
173
+ body.pinData = current.pinData;
174
+ }
175
+ return body;
176
+ }
@@ -0,0 +1,129 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { N8nClient, N8nWorkflow } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+ import { buildBody } from "./pin-node-data.ts";
5
+
6
+ const Schema = Type.Object(
7
+ {
8
+ id: Type.String({ description: "Workflow id (from n8n_list_workflows)." }),
9
+ nodeName: Type.Optional(
10
+ Type.String({
11
+ minLength: 1,
12
+ description:
13
+ "Name of the node to unpin (case-sensitive). Omit to clear ALL pinned data on the workflow.",
14
+ }),
15
+ ),
16
+ confirm: Type.Boolean({
17
+ description:
18
+ "Must be true to actually clear the pinned data. Idempotent: nodes with no pinned data are a no-op (returns ok=true with noop=true).",
19
+ }),
20
+ },
21
+ { additionalProperties: false },
22
+ );
23
+
24
+ export function createUnpinNodeDataTool(getClient: () => N8nClient) {
25
+ return {
26
+ name: "n8n_unpin_node_data",
27
+ label: "n8n: unpin node data",
28
+ description:
29
+ "Clear pinned data on one node (or the whole workflow when nodeName is omitted) so executions return to using live node output. Idempotent — clearing a node that wasn't pinned returns ok=true with noop=true. Issues PUT /workflows/{id} with the modified pinData. Requires enableEdit and explicit confirm=true.",
30
+ parameters: Schema,
31
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
32
+ const params = rawParams as {
33
+ id: string;
34
+ nodeName?: string;
35
+ confirm: boolean;
36
+ };
37
+ if (!params.confirm) {
38
+ return jsonToolResult({
39
+ ok: false,
40
+ error: "confirm must be true to unpin data",
41
+ });
42
+ }
43
+ const client = getClient();
44
+
45
+ let current: N8nWorkflow;
46
+ try {
47
+ current = await client.getWorkflow(params.id);
48
+ } catch (err) {
49
+ const msg = err instanceof Error ? err.message : String(err);
50
+ return jsonToolResult({
51
+ ok: false,
52
+ error: `failed to fetch workflow: ${client.redact(msg)}`,
53
+ });
54
+ }
55
+
56
+ const existing = current.pinData ?? {};
57
+ const existingKeys = Object.keys(existing);
58
+
59
+ // Whole-workflow unpin path.
60
+ if (!params.nodeName) {
61
+ if (existingKeys.length === 0) {
62
+ return jsonToolResult({
63
+ ok: true,
64
+ action: "unpin",
65
+ workflowId: current.id,
66
+ scope: "workflow",
67
+ noop: true,
68
+ clearedNodes: [],
69
+ });
70
+ }
71
+ const body = buildBody(current, { pinData: {} });
72
+ try {
73
+ const saved = await client.saveWorkflow(params.id, body);
74
+ return jsonToolResult({
75
+ ok: true,
76
+ action: "unpin",
77
+ workflowId: saved.id,
78
+ scope: "workflow",
79
+ noop: false,
80
+ clearedNodes: existingKeys,
81
+ versionId: saved.versionId ?? null,
82
+ updatedAt: saved.updatedAt,
83
+ });
84
+ } catch (err) {
85
+ const msg = err instanceof Error ? err.message : String(err);
86
+ return jsonToolResult({
87
+ ok: false,
88
+ error: `unpin failed: ${client.redact(msg)}`,
89
+ });
90
+ }
91
+ }
92
+
93
+ // Single-node unpin path.
94
+ const nodeName = params.nodeName;
95
+ if (!(nodeName in existing)) {
96
+ return jsonToolResult({
97
+ ok: true,
98
+ action: "unpin",
99
+ workflowId: current.id,
100
+ scope: "node",
101
+ nodeName,
102
+ noop: true,
103
+ });
104
+ }
105
+ const newPinData: Record<string, unknown> = { ...existing };
106
+ delete newPinData[nodeName];
107
+ const body = buildBody(current, { pinData: newPinData });
108
+ try {
109
+ const saved = await client.saveWorkflow(params.id, body);
110
+ return jsonToolResult({
111
+ ok: true,
112
+ action: "unpin",
113
+ workflowId: saved.id,
114
+ scope: "node",
115
+ nodeName,
116
+ noop: false,
117
+ versionId: saved.versionId ?? null,
118
+ updatedAt: saved.updatedAt,
119
+ });
120
+ } catch (err) {
121
+ const msg = err instanceof Error ? err.message : String(err);
122
+ return jsonToolResult({
123
+ ok: false,
124
+ error: `unpin failed: ${client.redact(msg)}`,
125
+ });
126
+ }
127
+ },
128
+ };
129
+ }