-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathhandlers-n8n-manager.ts
More file actions
5032 lines (4558 loc) · 174 KB
/
Copy pathhandlers-n8n-manager.ts
File metadata and controls
5032 lines (4558 loc) · 174 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
import { randomUUID } from 'crypto';
import { N8nApiClient } from '../services/n8n-api-client';
import { scanWorkflows, type CustomCheckType } from '../services/workflow-security-scanner';
import { buildAuditReport } from '../services/audit-report-builder';
import { getN8nApiConfig, getN8nApiConfigFromContext } from '../config/n8n-api';
import {
Workflow,
WorkflowNode,
WorkflowConnection,
ExecutionStatus,
WebhookRequest,
McpToolResponse,
ExecutionFilterOptions,
ExecutionMode,
Credential,
TestRunStatus,
} from '../types/n8n-api';
import type { TriggerType, TestWorkflowInput } from '../triggers/types';
import {
validateWorkflowStructure,
hasWebhookTrigger,
getWebhookUrl
} from '../services/n8n-validation';
import { nodeGroupsField, parseNodeGroupsInput } from '../services/node-groups';
import { versionAtLeast, N8N_VERSION_UNAVAILABLE_NOTE } from '../services/n8n-version';
import {
N8nApiError,
N8nNotFoundError,
getUserFriendlyErrorMessage,
formatExecutionError,
formatNoExecutionError
} from '../utils/n8n-errors';
import { logger } from '../utils/logger';
import { z } from 'zod';
import { WorkflowValidator } from '../services/workflow-validator';
import { EnhancedConfigValidator } from '../services/enhanced-config-validator';
import { NodeRepository } from '../database/node-repository';
import { InstanceContext, validateInstanceContext, getInstanceScopeId } from '../types/instance-context';
import { NodeTypeNormalizer } from '../utils/node-type-normalizer';
import { WorkflowAutoFixer, AutoFixConfig } from '../services/workflow-auto-fixer';
import { ExpressionFormatValidator, ExpressionFormatIssue } from '../services/expression-format-validator';
import { WorkflowVersioningService, VERSION_OWNERSHIP_ERROR_PREFIX } from '../services/workflow-versioning-service';
import { handleUpdatePartialWorkflow } from './handlers-workflow-diff';
import { telemetry } from '../telemetry';
import { TemplateService } from '../templates/template-service';
import {
createCacheKey,
createInstanceCache,
CacheMutex,
cacheMetrics,
withRetry,
getCacheStatistics
} from '../utils/cache-utils';
import { processExecution } from '../services/execution-processor';
import { checkNpmVersion, formatVersionMessage } from '../utils/npm-version-checker';
import {
normalizeMcpJsonValue,
normalizeMcpWorkflowConnections,
normalizeMcpWorkflowNodes,
} from '../utils/mcp-input-normalizer';
import { buildOfficialMcpHealth, OfficialMcpHealth } from './official-mcp-access';
import { callOfficialTool, resolveProjectChoices } from './handlers-official-tools';
import { withMcpExposure, publicApiMatchesContext, PUBLIC_API_CONTEXT_HINT } from '../services/mcp-exposure';
import { isOperationDisabled } from './tool-policy';
import {
DEFAULT_TIMEOUT_MS,
MIN_TIMEOUT_MS,
MAX_TIMEOUT_MS,
PINNED_TIMEOUT_MS,
} from './agents-action-map';
// ========================================================================
// TypeScript Interfaces for Type Safety
// ========================================================================
/**
* Health Check Response Data Structure
*/
interface HealthCheckResponseData {
status: string;
instanceId?: string;
n8nVersion?: string;
/** Present only when the instance did not report a version - see N8N_VERSION_UNAVAILABLE_NOTE. */
n8nVersionNote?: string;
features?: Record<string, unknown>;
apiUrl?: string;
mcpVersion: string;
supportedN8nVersion?: string;
versionCheck: {
current: string;
latest: string | null;
upToDate: boolean;
message: string;
updateCommand?: string;
};
performance: {
responseTimeMs: number;
cacheHitRate: string;
cachedInstances: number;
};
officialMcp?: OfficialMcpHealth;
nextSteps?: string[];
updateWarning?: string;
}
/**
* Cloud Platform Guide Structure
*/
interface CloudPlatformGuide {
name: string;
troubleshooting: string[];
}
/**
* Applied Fix from Auto-Fix Operation
*/
interface AppliedFix {
node: string;
field: string;
type: string;
before: string;
after: string;
confidence: string;
}
/**
* Auto-Fix Result Data from handleAutofixWorkflow
*/
interface AutofixResultData {
fixesApplied?: number;
fixes?: AppliedFix[];
workflowId?: string;
workflowName?: string;
message?: string;
summary?: string;
stats?: Record<string, number>;
}
/**
* Workflow Validation Response Data
*/
interface WorkflowValidationResponse {
valid: boolean;
workflowId?: string;
workflowName?: string;
summary: {
totalNodes: number;
enabledNodes: number;
triggerNodes: number;
validConnections: number;
invalidConnections: number;
expressionsValidated: number;
errorCount: number;
warningCount: number;
};
errors?: Array<{
node: string;
nodeName?: string;
message: string;
details?: Record<string, unknown>;
}>;
warnings?: Array<{
node: string;
nodeName?: string;
message: string;
details?: Record<string, unknown>;
}>;
suggestions?: unknown[];
}
/**
* Diagnostic Response Data Structure
*/
interface DiagnosticResponseData {
timestamp: string;
environment: {
N8N_API_URL: string | null;
N8N_API_KEY: string | null;
NODE_ENV: string;
MCP_MODE: string;
isDocker: boolean;
cloudPlatform: string | null;
nodeVersion: string;
platform: string;
};
apiConfiguration: {
configured: boolean;
status: {
configured: boolean;
connected: boolean;
error: string | null;
version: string | null;
};
config: {
baseUrl: string;
timeout: number;
maxRetries: number;
} | null;
};
versionInfo: {
current: string;
latest: string | null;
upToDate: boolean;
message: string;
updateCommand?: string;
};
toolsAvailability: {
documentationTools: {
count: number;
enabled: boolean;
description: string;
};
managementTools: {
count: number;
enabled: boolean;
description: string;
};
totalAvailable: number;
};
performance: {
diagnosticResponseTimeMs: number;
cacheHitRate: string;
cachedInstances: number;
};
officialMcp?: OfficialMcpHealth;
modeSpecificDebug: Record<string, unknown>;
dockerDebug?: Record<string, unknown>;
cloudPlatformDebug?: CloudPlatformGuide;
nextSteps?: Record<string, unknown>;
troubleshooting?: Record<string, unknown>;
setupGuide?: Record<string, unknown>;
updateWarning?: Record<string, unknown>;
debug?: Record<string, unknown>;
[key: string]: unknown; // Allow dynamic property access for optional fields
}
// ========================================================================
// Singleton n8n API client instance (backward compatibility)
let defaultApiClient: N8nApiClient | null = null;
let lastDefaultConfigUrl: string | null = null;
// Mutex for cache operations to prevent race conditions
const cacheMutex = new CacheMutex();
// Instance-specific API clients cache with LRU eviction and TTL
const instanceClients = createInstanceCache<N8nApiClient>((client, key) => {
// Clean up when evicting from cache
logger.debug('Evicting API client from cache', {
cacheKey: key.substring(0, 8) + '...' // Only log partial key for security
});
});
/**
* Get or create API client with flexible instance support
* Supports both singleton mode (using environment variables) and instance-specific mode.
* Uses LRU cache with mutex protection for thread-safe operations.
*
* @param context - Optional instance context for instance-specific configuration
* @returns API client configured for the instance or environment, or null if not configured
*
* @example
* // Using environment variables (singleton mode)
* const client = getN8nApiClient();
*
* @example
* // Using instance context
* const client = getN8nApiClient({
* n8nApiUrl: 'https://customer.n8n.cloud',
* n8nApiKey: 'api-key-123',
* instanceId: 'customer-1'
* });
*/
/**
* Get cache statistics for monitoring
* @returns Formatted cache statistics string
*/
export function getInstanceCacheStatistics(): string {
return getCacheStatistics();
}
/**
* Get raw cache metrics for detailed monitoring
* @returns Raw cache metrics object
*/
export function getInstanceCacheMetrics() {
return cacheMetrics.getMetrics();
}
/**
* Clear the instance cache for testing or maintenance
*/
export function clearInstanceCache(): void {
instanceClients.clear();
cacheMetrics.recordClear();
cacheMetrics.updateSize(0, instanceClients.max);
}
export function getN8nApiClient(context?: InstanceContext): N8nApiClient | null {
// If context provided with n8n config, use instance-specific client
if (context?.n8nApiUrl && context?.n8nApiKey) {
// Validate context before using
const validation = validateInstanceContext(context);
if (!validation.valid) {
logger.warn('Invalid instance context provided', {
instanceId: context.instanceId,
errors: validation.errors
});
return null;
}
// Create secure hash of credentials for cache key using memoization
const cacheKey = createCacheKey(
`${context.n8nApiUrl}:${context.n8nApiKey}:${context.instanceId || ''}`
);
// Check cache first
if (instanceClients.has(cacheKey)) {
cacheMetrics.recordHit();
return instanceClients.get(cacheKey) || null;
}
cacheMetrics.recordMiss();
// Check if already being created (simple lock check)
if (cacheMutex.isLocked(cacheKey)) {
// Wait briefly and check again
const waitTime = 100; // 100ms
const start = Date.now();
while (cacheMutex.isLocked(cacheKey) && (Date.now() - start) < 1000) {
// Busy wait for up to 1 second
}
// Check if it was created while waiting
if (instanceClients.has(cacheKey)) {
cacheMetrics.recordHit();
return instanceClients.get(cacheKey) || null;
}
}
const config = getN8nApiConfigFromContext(context);
if (config) {
// Sanitized logging - never log API keys
logger.info('Creating instance-specific n8n API client', {
url: config.baseUrl.replace(/^(https?:\/\/[^\/]+).*/, '$1'), // Only log domain
instanceId: context.instanceId,
cacheKey: cacheKey.substring(0, 8) + '...' // Only log partial hash
});
const client = new N8nApiClient(config);
instanceClients.set(cacheKey, client);
cacheMetrics.recordSet();
cacheMetrics.updateSize(instanceClients.size, instanceClients.max);
return client;
}
return null;
}
// SECURITY (GHSA-jxx9-px88-pj69): never fall back to process-level credentials
// when multi-tenant mode is enabled. A missing or incomplete tenant context
// must result in no client, not the operator's N8N_API_KEY.
if (process.env.ENABLE_MULTI_TENANT === 'true') {
logger.warn('Refusing env-credential fallback in multi-tenant mode');
return null;
}
// Fall back to default singleton from environment
logger.info('Falling back to environment configuration for n8n API client');
const config = getN8nApiConfig();
if (!config) {
if (defaultApiClient) {
logger.info('n8n API configuration removed, clearing default client');
defaultApiClient = null;
lastDefaultConfigUrl = null;
}
return null;
}
// Check if config has changed
if (!defaultApiClient || lastDefaultConfigUrl !== config.baseUrl) {
logger.info('n8n API client initialized from environment', { url: config.baseUrl });
defaultApiClient = new N8nApiClient(config);
lastDefaultConfigUrl = config.baseUrl;
}
return defaultApiClient;
}
/**
* Helper to ensure API is configured
* @param context - Optional instance context
* @returns Configured API client
* @throws Error if API is not configured
*/
function ensureApiConfigured(context?: InstanceContext): N8nApiClient {
const client = getN8nApiClient(context);
if (!client) {
if (context?.instanceId) {
throw new Error(`n8n API not configured for instance ${context.instanceId}. Please provide n8nApiUrl and n8nApiKey in the instance context.`);
}
throw new Error('n8n API not configured. Please set N8N_API_URL and N8N_API_KEY environment variables.');
}
return client;
}
/**
* Resolve the n8n API config to surface in a tool response (apiUrl,
* baseUrl for workflow links, etc.). Prefers the per-request tenant
* context; falls back to the process-env config only in single-tenant
* mode.
*
* SECURITY (GHSA-jxx9-px88-pj69): in multi-tenant mode this never returns
* the operator's env config, so handler responses cannot disclose the
* operator's apiUrl to a tenant whose context was missing or incomplete.
*/
function resolveN8nApiConfigForResponse(context?: InstanceContext) {
const fromContext = context ? getN8nApiConfigFromContext(context) : null;
if (fromContext) {
return fromContext;
}
if (process.env.ENABLE_MULTI_TENANT === 'true') {
return null;
}
return getN8nApiConfig();
}
// MCP transports may serialize JSON objects/arrays as strings.
// Parse them back, but return the original value on failure so Zod reports a proper type error.
export function tryParseJson(val: unknown): unknown {
if (typeof val !== 'string') return val;
try { return JSON.parse(val); } catch { return val; }
}
// n8n's draft/publish model returns a full `activeVersion` object on every workflow GET,
// duplicating the live graph's nodes/connections alongside the draft. That payload roughly
// doubles the response size and pushes large workflows past MCP host caps. Strip the
// heavy object here while preserving `activeVersionId` as a lightweight pointer. Callers
// that need the published graph should use mode='active' (handleGetWorkflowActive).
function stripActiveVersion(workflow: Workflow): Workflow {
const { activeVersion, ...rest } = workflow;
return rest;
}
// Some MCP clients (e.g. opencode) serialize all schema fields including optional ones,
// sending '' instead of omitting them. Coerce blank strings to undefined so the n8n API
// doesn't receive `?cursor=&projectId=` and reject the request. See issue #774.
const emptyToUndefined = (v: unknown) =>
typeof v === 'string' && v.trim() === '' ? undefined : v;
const optionalEmptyAware = <T extends z.ZodTypeAny>(schema: T) =>
z.preprocess(emptyToUndefined, schema.optional());
// Zod schemas for input validation
const createWorkflowSchema = z.object({
name: z.string(),
nodes: z.preprocess(normalizeMcpWorkflowNodes, z.array(z.any())),
// Two-arg z.record(keySchema, valueSchema) — see services/n8n-validation.ts for the
// Zod 3/4 compatibility rationale (#744).
connections: z.preprocess(normalizeMcpWorkflowConnections, z.record(z.string(), z.any())),
// The typed keys are validated; every other key is forwarded, as on the update path.
// A closed object here silently dropped `availableInMCP`, `callerPolicy` and the other
// settings added since n8n 1.119 before they reached the cleaner (issue #1026).
settings: z.preprocess(normalizeMcpJsonValue, z.object({
executionOrder: z.enum(['v0', 'v1']).optional(),
timezone: z.string().optional(),
saveDataErrorExecution: z.enum(['all', 'none']).optional(),
saveDataSuccessExecution: z.enum(['all', 'none']).optional(),
saveManualExecutions: z.boolean().optional(),
saveExecutionProgress: z.boolean().optional(),
executionTimeout: z.number().optional(),
errorWorkflow: z.string().optional(),
}).passthrough()).optional(),
// Validated by parseNodeGroupsInput() — see services/node-groups.ts
nodeGroups: z.any().optional(),
projectId: z.string().optional(),
// Folder placement (n8n 2.32+). Omit for the project root; blank strings from
// lossy MCP clients are treated as omitted (issue #774 pattern). Trimmed to match
// the folder handlers and the moveToFolder diff operation.
parentFolderId: optionalEmptyAware(z.string().trim().min(1)),
});
const updateWorkflowSchema = z.object({
id: z.string(),
name: z.string().optional(),
nodes: z.preprocess(normalizeMcpWorkflowNodes, z.array(z.any())).optional(),
connections: z.preprocess(normalizeMcpWorkflowConnections, z.record(z.string(), z.any())).optional(),
settings: z.preprocess(normalizeMcpJsonValue, z.any()).optional(),
// Validated by parseNodeGroupsInput() — see services/node-groups.ts
nodeGroups: z.any().optional(),
// Folder move (n8n 2.32+): a folder ID moves the workflow there, null moves it to the
// project root, omitting the field leaves the current folder unchanged. Write-only in
// n8n's schema, so the merged GET response can never re-send a stale value. Trimmed to
// match the folder handlers and the moveToFolder diff operation.
parentFolderId: optionalEmptyAware(z.string().trim().min(1).nullable()),
createBackup: z.boolean().optional(),
intent: z.string().optional(),
});
const listWorkflowsSchema = z.object({
limit: z.number().min(1).max(100).optional(),
cursor: optionalEmptyAware(z.string()),
active: z.boolean().optional(),
tags: z.preprocess(normalizeMcpJsonValue, z.array(z.string())).optional(),
projectId: optionalEmptyAware(z.string()),
excludePinnedData: z.boolean().optional(),
});
const validateWorkflowSchema = z.object({
id: z.string(),
options: z.object({
validateNodes: z.boolean().optional(),
validateConnections: z.boolean().optional(),
validateExpressions: z.boolean().optional(),
profile: z.enum(['minimal', 'runtime', 'ai-friendly', 'strict']).optional(),
}).optional(),
});
const autofixWorkflowSchema = z.object({
id: z.string(),
applyFixes: z.boolean().optional().default(false),
fixTypes: z.array(z.enum([
'expression-format',
'typeversion-correction',
'error-output-config',
'node-type-correction',
'webhook-missing-path',
'typeversion-upgrade',
'version-migration',
'tool-variant-correction',
'connection-numeric-keys',
'connection-invalid-type',
'connection-id-to-name',
'connection-duplicate-removal',
'connection-input-index'
])).optional(),
confidenceThreshold: z.enum(['high', 'medium', 'low']).optional().default('medium'),
maxFixes: z.number().optional().default(50)
});
// Schema for n8n_test_workflow tool
const testWorkflowSchema = z.object({
workflowId: z.string(),
method: optionalEmptyAware(z.enum(['auto', 'trigger', 'prepare', 'pinned', 'direct'])),
triggerType: optionalEmptyAware(z.enum(['webhook', 'form', 'chat'])),
httpMethod: optionalEmptyAware(z.enum(['GET', 'POST', 'PUT', 'DELETE'])),
webhookPath: optionalEmptyAware(z.string()),
message: optionalEmptyAware(z.string()),
sessionId: optionalEmptyAware(z.string()),
data: z.record(z.unknown()).optional(),
headers: z.record(z.string()).optional(),
timeout: z.number().optional(),
waitForResponse: z.boolean().optional(),
// Official-MCP methods only.
exposeToMcp: z.boolean().optional(),
timeoutMs: z.number().int().min(MIN_TIMEOUT_MS).max(MAX_TIMEOUT_MS).optional(),
pinData: z.record(z.array(z.unknown())).optional(),
triggerNodeName: optionalEmptyAware(z.string()),
executionMode: optionalEmptyAware(z.enum(['manual', 'production'])),
});
const listExecutionsSchema = z.object({
limit: z.number().min(1).max(100).optional(),
cursor: optionalEmptyAware(z.string()),
workflowId: optionalEmptyAware(z.string()),
projectId: optionalEmptyAware(z.string()),
status: optionalEmptyAware(z.enum(['success', 'error', 'waiting'])),
includeData: z.boolean().optional(),
});
// Evaluation ids become API path segments; trim and require content so a blank
// or whitespace-only value fails here as "Invalid input" rather than surfacing
// later as a transport-layer error.
const testRunPathId = z.string().trim().min(1);
const listTestRunsSchema = z.object({
workflowId: testRunPathId,
status: optionalEmptyAware(z.enum(['new', 'running', 'completed', 'error', 'cancelled'])),
limit: z.number().min(1).max(250).optional(),
cursor: optionalEmptyAware(z.string()),
});
const getTestRunSchema = z.object({
workflowId: testRunPathId,
runId: testRunPathId,
});
const listTestCasesSchema = z.object({
workflowId: testRunPathId,
runId: testRunPathId,
limit: z.number().min(1).max(250).optional(),
cursor: optionalEmptyAware(z.string()),
});
const triggerTestRunSchema = z.object({
workflowId: testRunPathId,
});
const cancelTestRunSchema = z.object({
workflowId: testRunPathId,
runId: testRunPathId,
});
/**
* A version id from either store. Local snapshots are numbered integers; n8n's
* own history uses opaque string ids. The MCP inputSchema deliberately leaves
* these two properties untyped so the server's argument coercion
* (`coerceStringifiedJsonParams`, which only touches properties declaring a
* scalar `type`) lets both shapes through to this union.
*/
const versionIdValue = z.union([z.number().int(), z.string().min(1)]);
const workflowVersionsSchema = z.object({
mode: z.enum(['list', 'get', 'rollback', 'delete', 'prune', 'diff']),
source: z.enum(['local', 'native']).optional(),
workflowId: z.string().optional(),
versionId: versionIdValue.optional(),
toVersionId: versionIdValue.optional(),
limit: z.number().default(10).optional(),
offset: z.number().int().min(0).optional(),
validateBefore: z.boolean().default(true).optional(),
deleteAll: z.boolean().default(false).optional(),
maxVersions: z.number().default(10).optional(),
exposeToMcp: z.boolean().optional(),
timeoutMs: z.number().int().min(5000).max(600000).optional(),
});
// Workflow Management Handlers
export async function handleCreateWorkflow(args: unknown, context?: InstanceContext): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const input = createWorkflowSchema.parse(args);
// Proactively detect SHORT form node types (common mistake)
const shortFormErrors: string[] = [];
input.nodes?.forEach((node: any, index: number) => {
if (node.type?.startsWith('nodes-base.') || node.type?.startsWith('nodes-langchain.')) {
const fullForm = node.type.startsWith('nodes-base.')
? node.type.replace('nodes-base.', 'n8n-nodes-base.')
: node.type.replace('nodes-langchain.', '@n8n/n8n-nodes-langchain.');
shortFormErrors.push(
`Node ${index} ("${node.name}") uses SHORT form "${node.type}". ` +
`The n8n API requires FULL form. Change to "${fullForm}"`
);
}
});
if (shortFormErrors.length > 0) {
telemetry.trackWorkflowCreation(input, false);
return {
success: false,
error: 'Node type format error: n8n API requires FULL form node types',
details: {
errors: shortFormErrors,
hint: 'Use n8n-nodes-base.* instead of nodes-base.* for standard nodes'
}
};
}
// Validate workflow structure (n8n API expects FULL form: n8n-nodes-base.*)
const errors = validateWorkflowStructure(input);
if (errors.length > 0) {
// Track validation failure
telemetry.trackWorkflowCreation(input, false);
return {
success: false,
error: 'Workflow validation failed',
details: { errors }
};
}
// Canvas groups are kept out of the spread so an ungrouped create sends no `nodeGroups` key
// at all: Zod emits an own `nodeGroups: undefined` for a caller that sent null.
const { nodeGroups: rawNodeGroups, ...createPayload } = input;
const nodeGroups = parseNodeGroupsInput(rawNodeGroups);
const groupWarnings: string[] = [];
// Create workflow (n8n API expects node types in FULL form)
const workflow = await client.createWorkflow(
nodeGroups !== undefined ? { ...createPayload, nodeGroups } : createPayload,
{
authoredGroups: new Set((nodeGroups ?? []).map(group => group.name)),
onWarning: message => groupWarnings.push(message),
}
);
// Defensive check: ensure the API returned a valid workflow with an ID
if (!workflow || !workflow.id) {
return {
success: false,
error: 'Workflow creation failed: n8n API returned an empty or invalid response. Verify your N8N_API_URL points to the correct /api/v1 endpoint and that the n8n instance supports workflow creation.',
details: {
response: workflow ? { keys: Object.keys(workflow) } : null
}
};
}
// Track successful workflow creation
telemetry.trackWorkflowCreation(workflow, true);
return {
success: true,
data: {
id: workflow.id,
name: workflow.name,
active: workflow.active,
nodeCount: workflow.nodes?.length || 0
},
message: `Workflow "${workflow.name}" created successfully with ID: ${workflow.id}. Use n8n_get_workflow with mode 'structure' to verify current state.`,
...(groupWarnings.length > 0 ? { details: { warnings: groupWarnings } } : {})
};
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: 'Invalid input',
details: { errors: error.errors }
};
}
if (error instanceof N8nApiError) {
return {
success: false,
error: getUserFriendlyErrorMessage(error),
code: error.code,
details: error.details as Record<string, unknown> | undefined
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
export async function handleGetWorkflow(args: unknown, context?: InstanceContext): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const { id } = z.object({ id: z.string() }).parse(args);
const workflow = await client.getWorkflow(id);
return {
success: true,
data: stripActiveVersion(workflow)
};
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: 'Invalid input',
details: { errors: error.errors }
};
}
if (error instanceof N8nApiError) {
return {
success: false,
error: getUserFriendlyErrorMessage(error),
code: error.code
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
export async function handleGetWorkflowDetails(args: unknown, context?: InstanceContext): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const { id } = z.object({ id: z.string() }).parse(args);
const workflow = await client.getWorkflow(id);
// Get recent executions for this workflow
const executions = await client.listExecutions({
workflowId: id,
limit: 10
});
// Calculate execution statistics
const stats = {
totalExecutions: executions.data.length,
successCount: executions.data.filter(e => e.status === ExecutionStatus.SUCCESS).length,
errorCount: executions.data.filter(e => e.status === ExecutionStatus.ERROR).length,
lastExecutionTime: executions.data[0]?.startedAt || null
};
return {
success: true,
data: {
workflow: stripActiveVersion(workflow),
executionStats: stats,
hasWebhookTrigger: hasWebhookTrigger(workflow),
webhookPath: getWebhookUrl(workflow)
}
};
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: 'Invalid input',
details: { errors: error.errors }
};
}
if (error instanceof N8nApiError) {
return {
success: false,
error: getUserFriendlyErrorMessage(error),
code: error.code
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
export async function handleGetWorkflowStructure(args: unknown, context?: InstanceContext): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const { id } = z.object({ id: z.string() }).parse(args);
const workflow = await client.getWorkflow(id);
// Simplify nodes to just essential structure
const simplifiedNodes = workflow.nodes.map(node => ({
id: node.id,
name: node.name,
type: node.type,
position: node.position,
disabled: node.disabled || false
}));
return {
success: true,
data: {
id: workflow.id,
name: workflow.name,
active: workflow.active,
isArchived: workflow.isArchived,
nodes: simplifiedNodes,
connections: workflow.connections,
// Canvas groups are part of the topology an editor sees, so structure mode reports them.
...nodeGroupsField(workflow.nodeGroups),
nodeCount: workflow.nodes.length,
connectionCount: Object.keys(workflow.connections).length
}
};
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: 'Invalid input',
details: { errors: error.errors }
};
}
if (error instanceof N8nApiError) {
return {
success: false,
error: getUserFriendlyErrorMessage(error),
code: error.code
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
export async function handleGetWorkflowMinimal(args: unknown, context?: InstanceContext): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const { id } = z.object({ id: z.string() }).parse(args);
const workflow = await client.getWorkflow(id);
return {
success: true,
data: {
id: workflow.id,
name: workflow.name,
active: workflow.active,
isArchived: workflow.isArchived,
tags: workflow.tags || [],
createdAt: workflow.createdAt,
updatedAt: workflow.updatedAt
}
};
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: 'Invalid input',
details: { errors: error.errors }
};
}
if (error instanceof N8nApiError) {
return {
success: false,
error: getUserFriendlyErrorMessage(error),
code: error.code
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
/**
* Returns the full config of only the requested nodes, identified by node name or node ID.
* Large workflows with long Code-node source can exceed client-side response limits when
* fetched whole (issue #101); this mode lets a caller pull one heavy node's `parameters`
* without the rest of the graph. Discover node names cheaply with mode='structure' first.
*
* `nodeNames` accepts both node names and node IDs; any entries that match nothing are
* reported back in `notFound` so the caller knows the lookup was partial.
*/
export async function handleGetWorkflowFiltered(args: unknown, context?: InstanceContext): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const { id, nodeNames } = z.object({
id: z.string(),
nodeNames: z.array(z.string()).min(1)
}).parse(args);
const workflow = await client.getWorkflow(id);
const requested = new Set(nodeNames);
const matchedNodes = workflow.nodes.filter(
node => requested.has(node.name) || requested.has(node.id)
);
// Report any requested keys that resolved to no node so partial requests are transparent.
const matchedKeys = new Set(matchedNodes.flatMap(node => [node.name, node.id]));
const notFound = nodeNames.filter(key => !matchedKeys.has(key));
// Only groups touching the requested nodes. Their nodeIds may reference nodes outside this
// response — filtered mode returns a slice of the workflow, not a valid whole.
const matchedIds = new Set(matchedNodes.map(node => node.id));
const touchedGroups = (workflow.nodeGroups ?? []).filter(group =>
Array.isArray(group?.nodeIds) && group.nodeIds.some(nodeId => matchedIds.has(nodeId))
);
return {
success: true,
data: {
id: workflow.id,
name: workflow.name,
active: workflow.active,
isArchived: workflow.isArchived,
nodes: matchedNodes,
...nodeGroupsField(touchedGroups),
nodeCount: workflow.nodes.length,
returnedCount: matchedNodes.length,
...(notFound.length > 0 ? { notFound } : {})
}
};
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
error: 'Invalid input',
details: { errors: error.errors }
};
}
if (error instanceof N8nApiError) {
return {
success: false,
error: getUserFriendlyErrorMessage(error),
code: error.code
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}
/**
* Returns the workflow's published (active) graph. n8n's draft/publish model exposes
* the live version under `activeVersion`; this handler surfaces that as a single-shaped
* response with `nodes`/`connections` populated from the published version. Use this when
* you need to see what is actually running in production rather than the latest editor draft.