n8n-ops-mcp 0.1.2 → 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.
package/README.md CHANGED
@@ -20,6 +20,8 @@ This is an **ops** tool — focused on listing, triggering, validating, and edit
20
20
 
21
21
  **`n8n_get_execution`** - fetch one execution by id. Includes per-node run log (truncated to `maxExecutionLogBytes`, default 64 KB, with a tail hint when it exceeds) and the raw error object verbatim when status is `error`. Pass `includeRunData: false` to skip the run log and get just status + error.
22
22
 
23
+ **`n8n_search_executions`** - text-search recent executions without paging through them. Defaults to scanning executions with `status=error` for a `query` fragment (e.g. `ECONNREFUSED`) and returning matches with workflow context + a snippet around each hit. `scope: "error"` (default) greps the error payload only. `scope: "all"` also greps the full per-node run log — slower and may return node output data, so treat snippets as sensitive. Optional `workflowId`, `status` (override default `error`), `limit` (default 50, max 250), `maxMatches` (default 20), `snippetChars` (default 160). Returns `matches`, plus `skipped` entries for any execution that failed to fetch.
24
+
23
25
  **`n8n_list_webhooks`** - scan workflows for webhook and form-trigger nodes and return their paths + fully-formed `triggerUrl`. Pairs with `n8n_trigger` mode='webhook' so agents can discover and call webhooks without opening n8n. Optional `workflowId` for a single workflow, `activeOnly` (default true), `limit` (default 50).
24
26
 
25
27
  **`n8n_validate_workflow`** - static checks on a workflow: deprecated node types (function → code), legacy Code-node API (`$node[]`, `items` global, `require()`), orphan nodes, disabled nodes, missing trigger. Returns issues with severity (error/warning/info) and a summary count.
@@ -218,7 +220,7 @@ npm start # node dist/mcp-server.js (post-build)
218
220
  - [x] `n8n_activate` / `n8n_deactivate` (behind `enableEdit`)
219
221
  - [x] `n8n_save_workflow` with auto-backup + validation gate (behind `enableEdit`)
220
222
  - [x] MCP wrapper (stdio)
221
- - [ ] `n8n_search_executions` (text search across run logs)
223
+ - [x] `n8n_search_executions` (text search across run logs)
222
224
 
223
225
  ## License
224
226
 
@@ -25,6 +25,9 @@ var N8nClient = class {
25
25
  this.apiKey = opts.apiKey;
26
26
  this.timeoutMs = opts.timeoutMs ?? 15e3;
27
27
  }
28
+ redact(text) {
29
+ return redactKey(text, this.apiKey);
30
+ }
28
31
  async listWorkflows(params = {}) {
29
32
  const qs = new URLSearchParams();
30
33
  if (params.active !== void 0) qs.set("active", String(params.active));
@@ -468,35 +471,234 @@ function truncateRunData(runData, maxBytes) {
468
471
  };
469
472
  }
470
473
 
471
- // src/tools/trigger.ts
474
+ // src/tools/search-executions.ts
472
475
  import { Type as Type5 } from "@sinclair/typebox";
473
476
  var Schema5 = Type5.Object(
474
477
  {
475
- mode: Type5.Union([Type5.Literal("workflow"), Type5.Literal("webhook")], {
476
- description: "'workflow' triggers by workflow id (manual-style). 'webhook' POSTs to a webhook path."
478
+ query: Type5.String({
479
+ minLength: 1,
480
+ description: "Case-insensitive text to search for. Typical: an error fragment like 'ECONNREFUSED' or a node name."
477
481
  }),
478
482
  workflowId: Type5.Optional(
479
483
  Type5.String({
484
+ description: "Filter to a single workflow id. Omit to scan across all workflows."
485
+ })
486
+ ),
487
+ status: Type5.Optional(
488
+ Type5.Union(
489
+ [
490
+ Type5.Literal("success"),
491
+ Type5.Literal("error"),
492
+ Type5.Literal("running"),
493
+ Type5.Literal("waiting"),
494
+ Type5.Literal("canceled")
495
+ ],
496
+ {
497
+ description: "Filter executions by status before searching. Default 'error' \u2014 matches the main use case ('which workflow errored with X?')."
498
+ }
499
+ )
500
+ ),
501
+ scope: Type5.Optional(
502
+ Type5.Union(
503
+ [Type5.Literal("error"), Type5.Literal("all")],
504
+ {
505
+ description: "'error' (default) searches only the execution error payload. 'all' additionally greps the full per-node run log \u2014 slower and returns more raw data."
506
+ }
507
+ )
508
+ ),
509
+ limit: Type5.Optional(
510
+ Type5.Integer({
511
+ minimum: 1,
512
+ maximum: 250,
513
+ description: "Max executions to scan (default 50)."
514
+ })
515
+ ),
516
+ maxMatches: Type5.Optional(
517
+ Type5.Integer({
518
+ minimum: 1,
519
+ maximum: 100,
520
+ description: "Stop after this many matches (default 20)."
521
+ })
522
+ ),
523
+ snippetChars: Type5.Optional(
524
+ Type5.Integer({
525
+ minimum: 40,
526
+ maximum: 600,
527
+ description: "Context window around each match (default 160)."
528
+ })
529
+ )
530
+ },
531
+ { additionalProperties: false }
532
+ );
533
+ var DEFAULT_LIMIT = 50;
534
+ var DEFAULT_MAX_MATCHES = 20;
535
+ var DEFAULT_SNIPPET_CHARS = 160;
536
+ function createSearchExecutionsTool(getClient) {
537
+ return {
538
+ name: "n8n_search_executions",
539
+ label: "n8n: search executions",
540
+ description: "Text-search recent n8n executions without paging through them one by one. Fetches each candidate with includeData=true, then greps the error payload (scope='error', default) or the full per-node run log (scope='all'). Returns matched executions with workflow context and a snippet around each hit. Snippets are raw run data with the API key redacted \u2014 with scope='all' they may still contain credentials or payload data from node outputs, so treat as sensitive.",
541
+ parameters: Schema5,
542
+ execute: async (_toolCallId, rawParams) => {
543
+ const params = rawParams;
544
+ const client = getClient();
545
+ const query = params.query;
546
+ const needle = query.toLowerCase();
547
+ const scope = params.scope ?? "error";
548
+ const limit = params.limit ?? DEFAULT_LIMIT;
549
+ const maxMatches = params.maxMatches ?? DEFAULT_MAX_MATCHES;
550
+ const snippetChars = params.snippetChars ?? DEFAULT_SNIPPET_CHARS;
551
+ const status = params.status ?? "error";
552
+ const [executions, workflowIndex] = await Promise.all([
553
+ client.listExecutions({
554
+ workflowId: params.workflowId,
555
+ status,
556
+ limit
557
+ }),
558
+ loadWorkflowNames2(client)
559
+ ]);
560
+ const matches = [];
561
+ const skipped = [];
562
+ let scannedCount = 0;
563
+ let truncated = false;
564
+ for (const summary of executions.data) {
565
+ scannedCount++;
566
+ let detail;
567
+ try {
568
+ detail = await client.getExecution(String(summary.id), {
569
+ includeData: true
570
+ });
571
+ } catch (err) {
572
+ const msg = err instanceof Error ? err.message : String(err);
573
+ skipped.push({
574
+ executionId: String(summary.id),
575
+ error: client.redact(msg)
576
+ });
577
+ continue;
578
+ }
579
+ const hits = findHits(detail, needle, scope, snippetChars);
580
+ if (hits.length === 0) continue;
581
+ const workflowId = String(detail.workflowId ?? summary.workflowId ?? "");
582
+ const errorMessage = extractErrorMessage(detail);
583
+ matches.push({
584
+ executionId: String(detail.id),
585
+ workflowId,
586
+ workflowName: detail.workflowData?.name ?? workflowIndex.get(workflowId) ?? null,
587
+ status: detail.status ?? (detail.finished ? "success" : "running"),
588
+ mode: detail.mode,
589
+ startedAt: detail.startedAt ?? null,
590
+ stoppedAt: detail.stoppedAt ?? null,
591
+ errorMessage: errorMessage ? client.redact(errorMessage) : null,
592
+ matchedIn: hits.map((h) => h.where),
593
+ snippets: hits.map((h) => ({
594
+ where: h.where,
595
+ text: client.redact(h.snippet)
596
+ }))
597
+ });
598
+ if (matches.length >= maxMatches) {
599
+ truncated = true;
600
+ break;
601
+ }
602
+ }
603
+ return jsonToolResult({
604
+ query,
605
+ scope,
606
+ status,
607
+ scannedCount,
608
+ matchCount: matches.length,
609
+ skippedCount: skipped.length,
610
+ truncated,
611
+ matches,
612
+ skipped,
613
+ nextCursor: truncated ? null : executions.nextCursor ?? null
614
+ });
615
+ }
616
+ };
617
+ }
618
+ function findHits(detail, needle, scope, snippetChars) {
619
+ const hits = [];
620
+ const error = detail.data?.resultData?.error;
621
+ if (error !== void 0) {
622
+ const errText = JSON.stringify(error);
623
+ const idx = errText.toLowerCase().indexOf(needle);
624
+ if (idx !== -1) {
625
+ hits.push({
626
+ where: "error",
627
+ snippet: snippet(errText, idx, needle.length, snippetChars)
628
+ });
629
+ }
630
+ }
631
+ if (scope === "all") {
632
+ const runData = detail.data?.resultData?.runData;
633
+ if (runData && typeof runData === "object") {
634
+ for (const [nodeName, nodeRuns] of Object.entries(runData)) {
635
+ const text = JSON.stringify(nodeRuns);
636
+ const idx = text.toLowerCase().indexOf(needle);
637
+ if (idx !== -1) {
638
+ hits.push({
639
+ where: `node:${nodeName}`,
640
+ snippet: snippet(text, idx, needle.length, snippetChars)
641
+ });
642
+ }
643
+ }
644
+ }
645
+ }
646
+ return hits;
647
+ }
648
+ function snippet(text, matchStart, matchLen, window) {
649
+ const half = Math.floor(window / 2);
650
+ const start = Math.max(0, matchStart - half);
651
+ const end = Math.min(text.length, matchStart + matchLen + half);
652
+ const prefix = start > 0 ? "\u2026" : "";
653
+ const suffix = end < text.length ? "\u2026" : "";
654
+ return `${prefix}${text.slice(start, end)}${suffix}`;
655
+ }
656
+ function extractErrorMessage(ex) {
657
+ const err = ex.data?.resultData?.error;
658
+ if (err && typeof err.message === "string") return err.message;
659
+ return null;
660
+ }
661
+ async function loadWorkflowNames2(client) {
662
+ const index = /* @__PURE__ */ new Map();
663
+ try {
664
+ const res = await client.listWorkflows({ limit: 250 });
665
+ for (const w of res.data) {
666
+ index.set(String(w.id), w.name);
667
+ }
668
+ } catch {
669
+ }
670
+ return index;
671
+ }
672
+
673
+ // src/tools/trigger.ts
674
+ import { Type as Type6 } from "@sinclair/typebox";
675
+ var Schema6 = Type6.Object(
676
+ {
677
+ mode: Type6.Union([Type6.Literal("workflow"), Type6.Literal("webhook")], {
678
+ description: "'workflow' triggers by workflow id (manual-style). 'webhook' POSTs to a webhook path."
679
+ }),
680
+ workflowId: Type6.Optional(
681
+ Type6.String({
480
682
  description: "Required when mode=workflow. Id from n8n_list_workflows."
481
683
  })
482
684
  ),
483
- webhookPath: Type5.Optional(
484
- Type5.String({
685
+ webhookPath: Type6.Optional(
686
+ Type6.String({
485
687
  description: "Required when mode=webhook. Path portion after the base URL, e.g. /webhook/my-hook."
486
688
  })
487
689
  ),
488
- payload: Type5.Optional(
489
- Type5.Record(Type5.String(), Type5.Unknown(), {
690
+ payload: Type6.Optional(
691
+ Type6.Record(Type6.String(), Type6.Unknown(), {
490
692
  description: "Optional JSON body. Sent as request body for either mode."
491
693
  })
492
694
  ),
493
- method: Type5.Optional(
494
- Type5.Union(
695
+ method: Type6.Optional(
696
+ Type6.Union(
495
697
  [
496
- Type5.Literal("POST"),
497
- Type5.Literal("GET"),
498
- Type5.Literal("PUT"),
499
- Type5.Literal("DELETE")
698
+ Type6.Literal("POST"),
699
+ Type6.Literal("GET"),
700
+ Type6.Literal("PUT"),
701
+ Type6.Literal("DELETE")
500
702
  ],
501
703
  {
502
704
  description: "HTTP method for webhook mode. Default POST."
@@ -517,7 +719,7 @@ function createTriggerTool(getClient) {
517
719
  name: "n8n_trigger",
518
720
  label: "n8n: trigger workflow",
519
721
  description: "Run an n8n workflow. mode='webhook' POSTs to a webhook path with an optional JSON payload \u2014 this is the supported path on n8n's Public API. mode='workflow' tries POST /api/v1/workflows/:id/execute with an active/manual/webhook/form pre-check; most n8n builds do NOT expose this endpoint and return 405 \u2014 prefer mode='webhook' for reliable triggers.",
520
- parameters: Schema5,
722
+ parameters: Schema6,
521
723
  execute: async (_toolCallId, rawParams) => {
522
724
  const params = rawParams;
523
725
  const client = getClient();
@@ -627,21 +829,21 @@ function findTriggerNode(wf) {
627
829
  }
628
830
 
629
831
  // src/tools/list-webhooks.ts
630
- import { Type as Type6 } from "@sinclair/typebox";
631
- var Schema6 = Type6.Object(
832
+ import { Type as Type7 } from "@sinclair/typebox";
833
+ var Schema7 = Type7.Object(
632
834
  {
633
- workflowId: Type6.Optional(
634
- Type6.String({
835
+ workflowId: Type7.Optional(
836
+ Type7.String({
635
837
  description: "Restrict to a single workflow. Omit to scan recent workflows."
636
838
  })
637
839
  ),
638
- activeOnly: Type6.Optional(
639
- Type6.Boolean({
840
+ activeOnly: Type7.Optional(
841
+ Type7.Boolean({
640
842
  description: "Only include active workflows. Default true."
641
843
  })
642
844
  ),
643
- limit: Type6.Optional(
644
- Type6.Number({
845
+ limit: Type7.Optional(
846
+ Type7.Number({
645
847
  minimum: 1,
646
848
  maximum: 100,
647
849
  description: "When workflowId is omitted, max workflows to fetch and scan (default 50)."
@@ -655,7 +857,7 @@ function createListWebhooksTool(deps) {
655
857
  name: "n8n_list_webhooks",
656
858
  label: "n8n: list webhooks",
657
859
  description: "Surface webhook and form-trigger paths from n8n workflows so agents can call n8n_trigger with mode='webhook' without opening the n8n UI. Returns workflowId, workflowName, nodeName, method, path, and a fully-formed triggerUrl.",
658
- parameters: Schema6,
860
+ parameters: Schema7,
659
861
  execute: async (_toolCallId, rawParams) => {
660
862
  const params = rawParams;
661
863
  const activeOnly = params.activeOnly !== false;
@@ -734,10 +936,10 @@ function extractWebhook(rawNode, wf, baseUrl) {
734
936
  }
735
937
 
736
938
  // src/tools/validate-workflow.ts
737
- import { Type as Type7 } from "@sinclair/typebox";
738
- var Schema7 = Type7.Object(
939
+ import { Type as Type8 } from "@sinclair/typebox";
940
+ var Schema8 = Type8.Object(
739
941
  {
740
- id: Type7.String({
942
+ id: Type8.String({
741
943
  description: "Workflow id (from n8n_list_workflows)."
742
944
  })
743
945
  },
@@ -757,7 +959,7 @@ function createValidateWorkflowTool(getClient) {
757
959
  name: "n8n_validate_workflow",
758
960
  label: "n8n: validate workflow",
759
961
  description: "Static checks on a workflow: deprecated node types (function \u2192 code), old Code-node API usage ($node[], items global, require()), orphan nodes, disabled nodes, and missing trigger. Returns a list of issues with severity.",
760
- parameters: Schema7,
962
+ parameters: Schema8,
761
963
  execute: async (_toolCallId, rawParams) => {
762
964
  const { id } = rawParams;
763
965
  const wf = await getClient().getWorkflow(id);
@@ -909,10 +1111,10 @@ function summarize(issues) {
909
1111
  }
910
1112
 
911
1113
  // src/tools/activate.ts
912
- import { Type as Type8 } from "@sinclair/typebox";
913
- var Schema8 = Type8.Object(
1114
+ import { Type as Type9 } from "@sinclair/typebox";
1115
+ var Schema9 = Type9.Object(
914
1116
  {
915
- id: Type8.String({ description: "Workflow id to activate." })
1117
+ id: Type9.String({ description: "Workflow id to activate." })
916
1118
  },
917
1119
  { additionalProperties: false }
918
1120
  );
@@ -921,7 +1123,7 @@ function createActivateTool(getClient) {
921
1123
  name: "n8n_activate",
922
1124
  label: "n8n: activate workflow",
923
1125
  description: "Activate an n8n workflow so its triggers (webhooks, schedules, polling) start running. Idempotent - activating an already-active workflow returns the current state. Requires enableEdit.",
924
- parameters: Schema8,
1126
+ parameters: Schema9,
925
1127
  execute: async (_toolCallId, rawParams) => {
926
1128
  const { id } = rawParams;
927
1129
  const wf = await getClient().activateWorkflow(id);
@@ -938,10 +1140,10 @@ function createActivateTool(getClient) {
938
1140
  }
939
1141
 
940
1142
  // src/tools/deactivate.ts
941
- import { Type as Type9 } from "@sinclair/typebox";
942
- var Schema9 = Type9.Object(
1143
+ import { Type as Type10 } from "@sinclair/typebox";
1144
+ var Schema10 = Type10.Object(
943
1145
  {
944
- id: Type9.String({ description: "Workflow id to deactivate." })
1146
+ id: Type10.String({ description: "Workflow id to deactivate." })
945
1147
  },
946
1148
  { additionalProperties: false }
947
1149
  );
@@ -950,7 +1152,7 @@ function createDeactivateTool(getClient) {
950
1152
  name: "n8n_deactivate",
951
1153
  label: "n8n: deactivate workflow",
952
1154
  description: "Deactivate an n8n workflow so its triggers stop firing. Running executions are not cancelled. Idempotent. Requires enableEdit.",
953
- parameters: Schema9,
1155
+ parameters: Schema10,
954
1156
  execute: async (_toolCallId, rawParams) => {
955
1157
  const { id } = rawParams;
956
1158
  const wf = await getClient().deactivateWorkflow(id);
@@ -967,32 +1169,32 @@ function createDeactivateTool(getClient) {
967
1169
  }
968
1170
 
969
1171
  // src/tools/save-workflow.ts
970
- import { Type as Type10 } from "@sinclair/typebox";
1172
+ import { Type as Type11 } from "@sinclair/typebox";
971
1173
  import { promises as fs } from "fs";
972
1174
  import { homedir } from "os";
973
1175
  import path from "path";
974
- var Schema10 = Type10.Object(
1176
+ var Schema11 = Type11.Object(
975
1177
  {
976
- id: Type10.String({ description: "Workflow id to overwrite." }),
977
- definition: Type10.Object(
1178
+ id: Type11.String({ description: "Workflow id to overwrite." }),
1179
+ definition: Type11.Object(
978
1180
  {
979
- name: Type10.Optional(Type10.String()),
980
- nodes: Type10.Array(Type10.Record(Type10.String(), Type10.Unknown())),
981
- connections: Type10.Record(Type10.String(), Type10.Unknown()),
982
- settings: Type10.Optional(Type10.Record(Type10.String(), Type10.Unknown())),
983
- staticData: Type10.Optional(Type10.Unknown())
1181
+ name: Type11.Optional(Type11.String()),
1182
+ nodes: Type11.Array(Type11.Record(Type11.String(), Type11.Unknown())),
1183
+ connections: Type11.Record(Type11.String(), Type11.Unknown()),
1184
+ settings: Type11.Optional(Type11.Record(Type11.String(), Type11.Unknown())),
1185
+ staticData: Type11.Optional(Type11.Unknown())
984
1186
  },
985
1187
  {
986
1188
  additionalProperties: true,
987
1189
  description: "Full new workflow body. Copy from n8n_get_workflow with includeDefinition=true, modify, then pass the nodes + connections (+ optional settings/staticData/name) here."
988
1190
  }
989
1191
  ),
990
- skipValidation: Type10.Optional(
991
- Type10.Boolean({
1192
+ skipValidation: Type11.Optional(
1193
+ Type11.Boolean({
992
1194
  description: "Skip the n8n_validate_workflow pre-check. Default false. Validation errors (not warnings) block the save by default."
993
1195
  })
994
1196
  ),
995
- confirm: Type10.Boolean({
1197
+ confirm: Type11.Boolean({
996
1198
  description: "Must be true to actually write. A snapshot of the current workflow is saved to backupDir regardless."
997
1199
  })
998
1200
  },
@@ -1003,7 +1205,7 @@ function createSaveWorkflowTool(deps) {
1003
1205
  name: "n8n_save_workflow",
1004
1206
  label: "n8n: save workflow",
1005
1207
  description: "Overwrite an n8n workflow. Snapshots the current version to backupDir first, runs n8n_validate_workflow on the proposed new state (errors block, warnings pass through), then PUTs the new body. Requires enableEdit and explicit confirm=true.",
1006
- parameters: Schema10,
1208
+ parameters: Schema11,
1007
1209
  execute: async (_toolCallId, rawParams) => {
1008
1210
  const params = rawParams;
1009
1211
  if (!params.confirm) {
@@ -1089,7 +1291,7 @@ async function writeBackup(dir, wf) {
1089
1291
  }
1090
1292
 
1091
1293
  // mcp-server.ts
1092
- var VERSION = "0.1.0";
1294
+ var VERSION = "0.2.0";
1093
1295
  function readConfigFromEnv() {
1094
1296
  const baseUrl = (process.env.N8N_BASE_URL ?? "").trim();
1095
1297
  if (!baseUrl) {
@@ -1184,6 +1386,21 @@ async function main() {
1184
1386
  )
1185
1387
  }
1186
1388
  );
1389
+ bind(server, createSearchExecutionsTool(getClient), {
1390
+ query: z.string().min(1).describe(
1391
+ "Case-insensitive text to search for (e.g. 'ECONNREFUSED')."
1392
+ ),
1393
+ workflowId: z.string().optional().describe("Filter to a single workflow id. Omit to scan across all workflows."),
1394
+ status: z.enum(["success", "error", "running", "waiting", "canceled"]).optional().describe(
1395
+ "Filter executions by status before searching. Default 'error'."
1396
+ ),
1397
+ scope: z.enum(["error", "all"]).optional().describe(
1398
+ "'error' (default) searches only the execution error payload. 'all' also greps the full per-node run log \u2014 slower and may return raw node output in snippets."
1399
+ ),
1400
+ limit: z.number().int().min(1).max(250).optional().describe("Max executions to scan (default 50)."),
1401
+ maxMatches: z.number().int().min(1).max(100).optional().describe("Stop after this many matches (default 20)."),
1402
+ snippetChars: z.number().int().min(40).max(600).optional().describe("Context window around each match (default 160).")
1403
+ });
1187
1404
  bind(server, createTriggerTool(getClient), {
1188
1405
  mode: z.enum(["workflow", "webhook"]).describe(
1189
1406
  "'workflow' triggers by workflow id (manual-style; most builds 405). 'webhook' POSTs to a webhook path."
package/index.ts CHANGED
@@ -5,6 +5,7 @@ import { createListWorkflowsTool } from "./src/tools/list-workflows.ts";
5
5
  import { createGetWorkflowTool } from "./src/tools/get-workflow.ts";
6
6
  import { createListExecutionsTool } from "./src/tools/list-executions.ts";
7
7
  import { createGetExecutionTool } from "./src/tools/get-execution.ts";
8
+ import { createSearchExecutionsTool } from "./src/tools/search-executions.ts";
8
9
  import { createTriggerTool } from "./src/tools/trigger.ts";
9
10
  import { createListWebhooksTool } from "./src/tools/list-webhooks.ts";
10
11
  import { createValidateWorkflowTool } from "./src/tools/validate-workflow.ts";
@@ -32,6 +33,7 @@ export default definePluginEntry({
32
33
  maxLogBytes: config.maxExecutionLogBytes,
33
34
  }) as AnyAgentTool,
34
35
  );
36
+ api.registerTool(createSearchExecutionsTool(getClient) as AnyAgentTool);
35
37
  api.registerTool(createTriggerTool(getClient) as AnyAgentTool);
36
38
  api.registerTool(
37
39
  createListWebhooksTool({ getClient, baseUrl: config.baseUrl }) as AnyAgentTool,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-ops-mcp",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Ops-focused n8n tools (list, inspect, trigger, validate, save) for Claude-compatible clients. MCP server + first-class OpenClaw plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.ts CHANGED
@@ -90,6 +90,10 @@ export class N8nClient {
90
90
  this.timeoutMs = opts.timeoutMs ?? 15_000;
91
91
  }
92
92
 
93
+ redact(text: string): string {
94
+ return redactKey(text, this.apiKey);
95
+ }
96
+
93
97
  async listWorkflows(params: {
94
98
  active?: boolean;
95
99
  tags?: string;
@@ -0,0 +1,249 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { N8nClient, N8nExecution } from "../client.ts";
3
+ import { jsonToolResult } from "./result.ts";
4
+
5
+ const Schema = Type.Object(
6
+ {
7
+ query: Type.String({
8
+ minLength: 1,
9
+ description:
10
+ "Case-insensitive text to search for. Typical: an error fragment like 'ECONNREFUSED' or a node name.",
11
+ }),
12
+ workflowId: Type.Optional(
13
+ Type.String({
14
+ description: "Filter to a single workflow id. Omit to scan across all workflows.",
15
+ }),
16
+ ),
17
+ status: Type.Optional(
18
+ Type.Union(
19
+ [
20
+ Type.Literal("success"),
21
+ Type.Literal("error"),
22
+ Type.Literal("running"),
23
+ Type.Literal("waiting"),
24
+ Type.Literal("canceled"),
25
+ ],
26
+ {
27
+ description:
28
+ "Filter executions by status before searching. Default 'error' — matches the main use case ('which workflow errored with X?').",
29
+ },
30
+ ),
31
+ ),
32
+ scope: Type.Optional(
33
+ Type.Union(
34
+ [Type.Literal("error"), Type.Literal("all")],
35
+ {
36
+ description:
37
+ "'error' (default) searches only the execution error payload. 'all' additionally greps the full per-node run log — slower and returns more raw data.",
38
+ },
39
+ ),
40
+ ),
41
+ limit: Type.Optional(
42
+ Type.Integer({
43
+ minimum: 1,
44
+ maximum: 250,
45
+ description: "Max executions to scan (default 50).",
46
+ }),
47
+ ),
48
+ maxMatches: Type.Optional(
49
+ Type.Integer({
50
+ minimum: 1,
51
+ maximum: 100,
52
+ description: "Stop after this many matches (default 20).",
53
+ }),
54
+ ),
55
+ snippetChars: Type.Optional(
56
+ Type.Integer({
57
+ minimum: 40,
58
+ maximum: 600,
59
+ description: "Context window around each match (default 160).",
60
+ }),
61
+ ),
62
+ },
63
+ { additionalProperties: false },
64
+ );
65
+
66
+ const DEFAULT_LIMIT = 50;
67
+ const DEFAULT_MAX_MATCHES = 20;
68
+ const DEFAULT_SNIPPET_CHARS = 160;
69
+
70
+ export function createSearchExecutionsTool(getClient: () => N8nClient) {
71
+ return {
72
+ name: "n8n_search_executions",
73
+ label: "n8n: search executions",
74
+ description:
75
+ "Text-search recent n8n executions without paging through them one by one. Fetches each candidate with includeData=true, then greps the error payload (scope='error', default) or the full per-node run log (scope='all'). Returns matched executions with workflow context and a snippet around each hit. Snippets are raw run data with the API key redacted — with scope='all' they may still contain credentials or payload data from node outputs, so treat as sensitive.",
76
+ parameters: Schema,
77
+ execute: async (_toolCallId: string, rawParams: Record<string, unknown>) => {
78
+ const params = rawParams as {
79
+ query: string;
80
+ workflowId?: string;
81
+ status?: string;
82
+ scope?: "error" | "all";
83
+ limit?: number;
84
+ maxMatches?: number;
85
+ snippetChars?: number;
86
+ };
87
+ const client = getClient();
88
+ const query = params.query;
89
+ const needle = query.toLowerCase();
90
+ const scope = params.scope ?? "error";
91
+ const limit = params.limit ?? DEFAULT_LIMIT;
92
+ const maxMatches = params.maxMatches ?? DEFAULT_MAX_MATCHES;
93
+ const snippetChars = params.snippetChars ?? DEFAULT_SNIPPET_CHARS;
94
+ const status = params.status ?? "error";
95
+
96
+ const [executions, workflowIndex] = await Promise.all([
97
+ client.listExecutions({
98
+ workflowId: params.workflowId,
99
+ status,
100
+ limit,
101
+ }),
102
+ loadWorkflowNames(client),
103
+ ]);
104
+
105
+ const matches: Array<Record<string, unknown>> = [];
106
+ const skipped: Array<{ executionId: string; error: string }> = [];
107
+ let scannedCount = 0;
108
+ let truncated = false;
109
+
110
+ for (const summary of executions.data) {
111
+ scannedCount++;
112
+ let detail: N8nExecution;
113
+ try {
114
+ detail = await client.getExecution(String(summary.id), {
115
+ includeData: true,
116
+ });
117
+ } catch (err) {
118
+ const msg = err instanceof Error ? err.message : String(err);
119
+ skipped.push({
120
+ executionId: String(summary.id),
121
+ error: client.redact(msg),
122
+ });
123
+ continue;
124
+ }
125
+
126
+ const hits = findHits(detail, needle, scope, snippetChars);
127
+ if (hits.length === 0) continue;
128
+
129
+ const workflowId = String(detail.workflowId ?? summary.workflowId ?? "");
130
+ const errorMessage = extractErrorMessage(detail);
131
+ matches.push({
132
+ executionId: String(detail.id),
133
+ workflowId,
134
+ workflowName:
135
+ detail.workflowData?.name ?? workflowIndex.get(workflowId) ?? null,
136
+ status: detail.status ?? (detail.finished ? "success" : "running"),
137
+ mode: detail.mode,
138
+ startedAt: detail.startedAt ?? null,
139
+ stoppedAt: detail.stoppedAt ?? null,
140
+ errorMessage: errorMessage ? client.redact(errorMessage) : null,
141
+ matchedIn: hits.map((h) => h.where),
142
+ snippets: hits.map((h) => ({
143
+ where: h.where,
144
+ text: client.redact(h.snippet),
145
+ })),
146
+ });
147
+
148
+ if (matches.length >= maxMatches) {
149
+ truncated = true;
150
+ break;
151
+ }
152
+ }
153
+
154
+ return jsonToolResult({
155
+ query,
156
+ scope,
157
+ status,
158
+ scannedCount,
159
+ matchCount: matches.length,
160
+ skippedCount: skipped.length,
161
+ truncated,
162
+ matches,
163
+ skipped,
164
+ nextCursor: truncated ? null : executions.nextCursor ?? null,
165
+ });
166
+ },
167
+ };
168
+ }
169
+
170
+ interface Hit {
171
+ where: string;
172
+ snippet: string;
173
+ }
174
+
175
+ function findHits(
176
+ detail: N8nExecution,
177
+ needle: string,
178
+ scope: "error" | "all",
179
+ snippetChars: number,
180
+ ): Hit[] {
181
+ const hits: Hit[] = [];
182
+
183
+ const error = detail.data?.resultData?.error;
184
+ if (error !== undefined) {
185
+ const errText = JSON.stringify(error);
186
+ const idx = errText.toLowerCase().indexOf(needle);
187
+ if (idx !== -1) {
188
+ hits.push({
189
+ where: "error",
190
+ snippet: snippet(errText, idx, needle.length, snippetChars),
191
+ });
192
+ }
193
+ }
194
+
195
+ if (scope === "all") {
196
+ const runData = detail.data?.resultData?.runData;
197
+ if (runData && typeof runData === "object") {
198
+ for (const [nodeName, nodeRuns] of Object.entries(runData)) {
199
+ const text = JSON.stringify(nodeRuns);
200
+ const idx = text.toLowerCase().indexOf(needle);
201
+ if (idx !== -1) {
202
+ hits.push({
203
+ where: `node:${nodeName}`,
204
+ snippet: snippet(text, idx, needle.length, snippetChars),
205
+ });
206
+ }
207
+ }
208
+ }
209
+ }
210
+
211
+ return hits;
212
+ }
213
+
214
+ function snippet(
215
+ text: string,
216
+ matchStart: number,
217
+ matchLen: number,
218
+ window: number,
219
+ ): string {
220
+ const half = Math.floor(window / 2);
221
+ const start = Math.max(0, matchStart - half);
222
+ const end = Math.min(text.length, matchStart + matchLen + half);
223
+ const prefix = start > 0 ? "…" : "";
224
+ const suffix = end < text.length ? "…" : "";
225
+ return `${prefix}${text.slice(start, end)}${suffix}`;
226
+ }
227
+
228
+ function extractErrorMessage(ex: N8nExecution): string | null {
229
+ const err = ex.data?.resultData?.error as
230
+ | { message?: unknown }
231
+ | undefined;
232
+ if (err && typeof err.message === "string") return err.message;
233
+ return null;
234
+ }
235
+
236
+ async function loadWorkflowNames(
237
+ client: N8nClient,
238
+ ): Promise<Map<string, string>> {
239
+ const index = new Map<string, string>();
240
+ try {
241
+ const res = await client.listWorkflows({ limit: 250 });
242
+ for (const w of res.data) {
243
+ index.set(String(w.id), w.name);
244
+ }
245
+ } catch {
246
+ // best-effort
247
+ }
248
+ return index;
249
+ }