@pagelines/n8n-mcp 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,355 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import {
3
- formatWorkflowResponse,
4
- formatExecutionResponse,
5
- formatExecutionListResponse,
6
- cleanResponse,
7
- stringifyResponse,
8
- type WorkflowSummary,
9
- type WorkflowCompact,
10
- type ExecutionSummary,
11
- type ExecutionCompact,
12
- } from './response-format.js';
13
- import type { N8nWorkflow, N8nExecution, N8nExecutionListItem } from './types.js';
14
-
15
- const createWorkflow = (overrides: Partial<N8nWorkflow> = {}): N8nWorkflow => ({
16
- id: '1',
17
- name: 'test_workflow',
18
- active: false,
19
- nodes: [
20
- {
21
- id: 'node1',
22
- name: 'webhook_trigger',
23
- type: 'n8n-nodes-base.webhook',
24
- typeVersion: 1,
25
- position: [0, 0],
26
- parameters: { path: 'test', httpMethod: 'POST' },
27
- },
28
- {
29
- id: 'node2',
30
- name: 'set_data',
31
- type: 'n8n-nodes-base.set',
32
- typeVersion: 1,
33
- position: [200, 0],
34
- parameters: { values: { string: [{ name: 'key', value: 'value' }] } },
35
- credentials: { httpBasicAuth: { id: '1', name: 'My Auth' } },
36
- },
37
- ],
38
- connections: {
39
- webhook_trigger: {
40
- main: [[{ node: 'set_data', type: 'main', index: 0 }]],
41
- },
42
- },
43
- createdAt: '2024-01-01T00:00:00.000Z',
44
- updatedAt: '2024-01-02T00:00:00.000Z',
45
- ...overrides,
46
- });
47
-
48
- const createExecution = (overrides: Partial<N8nExecution> = {}): N8nExecution => ({
49
- id: 'exec1',
50
- workflowId: '1',
51
- finished: true,
52
- mode: 'manual',
53
- startedAt: '2024-01-01T00:00:00.000Z',
54
- stoppedAt: '2024-01-01T00:00:05.000Z',
55
- status: 'success',
56
- data: {
57
- resultData: {
58
- runData: {
59
- webhook_trigger: [{ data: { main: [[{ json: { test: 'data' } }]] } }],
60
- set_data: [{ data: { main: [[{ json: { key: 'value' } }]] } }],
61
- },
62
- },
63
- },
64
- ...overrides,
65
- });
66
-
67
- describe('formatWorkflowResponse', () => {
68
- describe('summary format', () => {
69
- it('returns minimal workflow info', () => {
70
- const workflow = createWorkflow();
71
- const result = formatWorkflowResponse(workflow, 'summary') as WorkflowSummary;
72
-
73
- expect(result.id).toBe('1');
74
- expect(result.name).toBe('test_workflow');
75
- expect(result.active).toBe(false);
76
- expect(result.nodeCount).toBe(2);
77
- expect(result.connectionCount).toBe(1);
78
- expect(result.updatedAt).toBe('2024-01-02T00:00:00.000Z');
79
- expect(result.nodeTypes).toContain('n8n-nodes-base.webhook');
80
- expect(result.nodeTypes).toContain('n8n-nodes-base.set');
81
- // Should not have full nodes or connections
82
- expect((result as any).nodes).toBeUndefined();
83
- expect((result as any).connections).toBeUndefined();
84
- });
85
- });
86
-
87
- describe('compact format', () => {
88
- it('returns nodes without parameters', () => {
89
- const workflow = createWorkflow();
90
- const result = formatWorkflowResponse(workflow, 'compact') as WorkflowCompact;
91
-
92
- expect(result.id).toBe('1');
93
- expect(result.name).toBe('test_workflow');
94
- expect(result.nodes).toHaveLength(2);
95
-
96
- // Nodes should have name, type, position but no parameters
97
- expect(result.nodes[0].name).toBe('webhook_trigger');
98
- expect(result.nodes[0].type).toBe('n8n-nodes-base.webhook');
99
- expect(result.nodes[0].position).toEqual([0, 0]);
100
- expect(result.nodes[0].hasCredentials).toBe(false);
101
- expect((result.nodes[0] as any).parameters).toBeUndefined();
102
-
103
- // Second node has credentials
104
- expect(result.nodes[1].hasCredentials).toBe(true);
105
- });
106
-
107
- it('simplifies connections to node -> [targets] map', () => {
108
- const workflow = createWorkflow();
109
- const result = formatWorkflowResponse(workflow, 'compact') as WorkflowCompact;
110
-
111
- expect(result.connections).toEqual({
112
- webhook_trigger: ['set_data'],
113
- });
114
- });
115
-
116
- it('marks disabled nodes', () => {
117
- const workflow = createWorkflow({
118
- nodes: [
119
- {
120
- id: 'node1',
121
- name: 'disabled_node',
122
- type: 'n8n-nodes-base.set',
123
- typeVersion: 1,
124
- position: [0, 0],
125
- parameters: {},
126
- disabled: true,
127
- },
128
- ],
129
- });
130
- const result = formatWorkflowResponse(workflow, 'compact') as WorkflowCompact;
131
-
132
- expect(result.nodes[0].disabled).toBe(true);
133
- });
134
- });
135
-
136
- describe('full format', () => {
137
- it('returns complete workflow', () => {
138
- const workflow = createWorkflow();
139
- const result = formatWorkflowResponse(workflow, 'full') as N8nWorkflow;
140
-
141
- expect(result).toEqual(workflow);
142
- expect(result.nodes[0].parameters).toEqual({ path: 'test', httpMethod: 'POST' });
143
- });
144
- });
145
-
146
- describe('default format', () => {
147
- it('defaults to compact', () => {
148
- const workflow = createWorkflow();
149
- const result = formatWorkflowResponse(workflow);
150
-
151
- // Should be compact (no parameters)
152
- expect((result as any).nodes[0].parameters).toBeUndefined();
153
- });
154
- });
155
- });
156
-
157
- describe('formatExecutionResponse', () => {
158
- describe('summary format', () => {
159
- it('returns minimal execution info', () => {
160
- const execution = createExecution();
161
- const result = formatExecutionResponse(execution, 'summary') as ExecutionSummary;
162
-
163
- expect(result.id).toBe('exec1');
164
- expect(result.workflowId).toBe('1');
165
- expect(result.status).toBe('success');
166
- expect(result.mode).toBe('manual');
167
- expect(result.durationMs).toBe(5000);
168
- expect(result.hasError).toBe(false);
169
- // Should not have runData
170
- expect((result as any).data).toBeUndefined();
171
- });
172
-
173
- it('includes error message when present', () => {
174
- const execution = createExecution({
175
- status: 'error',
176
- data: {
177
- resultData: {
178
- error: { message: 'Something went wrong' },
179
- },
180
- },
181
- });
182
- const result = formatExecutionResponse(execution, 'summary') as ExecutionSummary;
183
-
184
- expect(result.hasError).toBe(true);
185
- expect(result.errorMessage).toBe('Something went wrong');
186
- });
187
- });
188
-
189
- describe('compact format', () => {
190
- it('returns execution without runData but with node summaries', () => {
191
- const execution = createExecution();
192
- const result = formatExecutionResponse(execution, 'compact') as ExecutionCompact;
193
-
194
- expect(result.id).toBe('exec1');
195
- expect(result.status).toBe('success');
196
- expect(result.finished).toBe(true);
197
- // Should have node result summaries
198
- expect(result.nodeResults).toHaveLength(2);
199
- expect(result.nodeResults![0].nodeName).toBe('webhook_trigger');
200
- expect(result.nodeResults![0].itemCount).toBe(1);
201
- // Should not have full runData
202
- expect((result as any).data).toBeUndefined();
203
- });
204
-
205
- it('includes error in compact format', () => {
206
- const execution = createExecution({
207
- status: 'error',
208
- data: {
209
- resultData: {
210
- error: { message: 'Failed' },
211
- },
212
- },
213
- });
214
- const result = formatExecutionResponse(execution, 'compact') as ExecutionCompact;
215
-
216
- expect(result.error).toEqual({ message: 'Failed' });
217
- });
218
- });
219
-
220
- describe('full format', () => {
221
- it('returns complete execution with runData', () => {
222
- const execution = createExecution();
223
- const result = formatExecutionResponse(execution, 'full') as N8nExecution;
224
-
225
- expect(result).toEqual(execution);
226
- expect(result.data?.resultData?.runData).toBeDefined();
227
- });
228
- });
229
- });
230
-
231
- describe('formatExecutionListResponse', () => {
232
- const executions: N8nExecutionListItem[] = [
233
- { id: '1', workflowId: 'w1', status: 'success', startedAt: '2024-01-01', mode: 'manual' },
234
- { id: '2', workflowId: 'w1', status: 'error', startedAt: '2024-01-02', mode: 'webhook' },
235
- ];
236
-
237
- it('summary returns id, status, startedAt only', () => {
238
- const result = formatExecutionListResponse(executions, 'summary');
239
-
240
- expect(result).toHaveLength(2);
241
- expect(result[0]).toEqual({ id: '1', status: 'success', startedAt: '2024-01-01' });
242
- expect((result[0] as any).workflowId).toBeUndefined();
243
- expect((result[0] as any).mode).toBeUndefined();
244
- });
245
-
246
- it('compact and full return same as input', () => {
247
- const compactResult = formatExecutionListResponse(executions, 'compact');
248
- const fullResult = formatExecutionListResponse(executions, 'full');
249
-
250
- expect(compactResult).toEqual(executions);
251
- expect(fullResult).toEqual(executions);
252
- });
253
- });
254
-
255
- describe('cleanResponse', () => {
256
- it('removes null values', () => {
257
- const obj = { a: 1, b: null, c: 'test' };
258
- const result = cleanResponse(obj);
259
-
260
- expect(result).toEqual({ a: 1, c: 'test' });
261
- });
262
-
263
- it('removes undefined values', () => {
264
- const obj = { a: 1, b: undefined, c: 'test' };
265
- const result = cleanResponse(obj);
266
-
267
- expect(result).toEqual({ a: 1, c: 'test' });
268
- });
269
-
270
- it('removes empty objects', () => {
271
- const obj = { a: 1, b: {}, c: 'test' };
272
- const result = cleanResponse(obj);
273
-
274
- expect(result).toEqual({ a: 1, c: 'test' });
275
- });
276
-
277
- it('removes empty arrays', () => {
278
- const obj = { a: 1, b: [], c: 'test' };
279
- const result = cleanResponse(obj);
280
-
281
- expect(result).toEqual({ a: 1, c: 'test' });
282
- });
283
-
284
- it('handles nested objects', () => {
285
- const obj = { a: { b: null, c: 1 }, d: { e: {} } };
286
- const result = cleanResponse(obj);
287
-
288
- expect(result).toEqual({ a: { c: 1 } });
289
- });
290
-
291
- it('handles arrays', () => {
292
- const arr = [{ a: 1, b: null }, { c: 2 }];
293
- const result = cleanResponse(arr);
294
-
295
- expect(result).toEqual([{ a: 1 }, { c: 2 }]);
296
- });
297
- });
298
-
299
- describe('stringifyResponse', () => {
300
- it('minifies by default', () => {
301
- const obj = { a: 1, b: 'test' };
302
- const result = stringifyResponse(obj);
303
-
304
- expect(result).toBe('{"a":1,"b":"test"}');
305
- expect(result).not.toContain('\n');
306
- });
307
-
308
- it('can pretty print when minify=false', () => {
309
- const obj = { a: 1 };
310
- const result = stringifyResponse(obj, false);
311
-
312
- expect(result).toContain('\n');
313
- });
314
-
315
- it('cleans null values before stringifying', () => {
316
- const obj = { a: 1, b: null };
317
- const result = stringifyResponse(obj);
318
-
319
- expect(result).toBe('{"a":1}');
320
- });
321
- });
322
-
323
- describe('token reduction estimates', () => {
324
- it('compact format significantly reduces workflow size', () => {
325
- const workflow = createWorkflow({
326
- nodes: Array.from({ length: 10 }, (_, i) => ({
327
- id: `node${i}`,
328
- name: `node_${i}`,
329
- type: 'n8n-nodes-base.set',
330
- typeVersion: 1,
331
- position: [i * 200, 0] as [number, number],
332
- parameters: {
333
- values: {
334
- string: Array.from({ length: 10 }, (_, j) => ({
335
- name: `param_${j}`,
336
- value: `This is a long value that takes up tokens ${j}`,
337
- })),
338
- },
339
- },
340
- })),
341
- });
342
-
343
- const fullJson = JSON.stringify(workflow);
344
- const compactJson = stringifyResponse(formatWorkflowResponse(workflow, 'compact'));
345
- const summaryJson = stringifyResponse(formatWorkflowResponse(workflow, 'summary'));
346
-
347
- // Compact should be significantly smaller than full
348
- expect(compactJson.length).toBeLessThan(fullJson.length * 0.5);
349
- // Summary should be smallest
350
- expect(summaryJson.length).toBeLessThan(compactJson.length);
351
-
352
- console.log(`Full: ${fullJson.length} chars, Compact: ${compactJson.length} chars, Summary: ${summaryJson.length} chars`);
353
- console.log(`Reduction: ${Math.round((1 - compactJson.length / fullJson.length) * 100)}% (compact), ${Math.round((1 - summaryJson.length / fullJson.length) * 100)}% (summary)`);
354
- });
355
- });
@@ -1,278 +0,0 @@
1
- /**
2
- * Response Format Transformers
3
- * Reduces response size for MCP to prevent context overflow
4
- */
5
-
6
- import type { N8nWorkflow, N8nNode, N8nExecution, N8nExecutionListItem } from './types.js';
7
-
8
- export type ResponseFormat = 'full' | 'compact' | 'summary';
9
-
10
- // ─────────────────────────────────────────────────────────────
11
- // Workflow Formatting
12
- // ─────────────────────────────────────────────────────────────
13
-
14
- export interface WorkflowSummary {
15
- id: string;
16
- name: string;
17
- active: boolean;
18
- nodeCount: number;
19
- connectionCount: number;
20
- updatedAt: string;
21
- nodeTypes: string[];
22
- }
23
-
24
- export interface WorkflowCompact {
25
- id: string;
26
- name: string;
27
- active: boolean;
28
- updatedAt: string;
29
- nodes: CompactNode[];
30
- connections: Record<string, string[]>; // simplified: nodeName -> [targetNodes]
31
- settings?: Record<string, unknown>;
32
- }
33
-
34
- export interface CompactNode {
35
- name: string;
36
- type: string;
37
- position: [number, number];
38
- hasCredentials: boolean;
39
- disabled?: boolean;
40
- // Parameters omitted to save tokens
41
- }
42
-
43
- /**
44
- * Format a workflow based on the requested format level
45
- */
46
- export function formatWorkflowResponse(
47
- workflow: N8nWorkflow,
48
- format: ResponseFormat = 'compact'
49
- ): N8nWorkflow | WorkflowCompact | WorkflowSummary {
50
- switch (format) {
51
- case 'summary':
52
- return toWorkflowSummary(workflow);
53
- case 'compact':
54
- return toWorkflowCompact(workflow);
55
- case 'full':
56
- default:
57
- return workflow;
58
- }
59
- }
60
-
61
- function toWorkflowSummary(workflow: N8nWorkflow): WorkflowSummary {
62
- const connectionCount = Object.values(workflow.connections).reduce((acc, outputs) => {
63
- return acc + Object.values(outputs).reduce((a, conns) => {
64
- return a + conns.reduce((b, c) => b + c.length, 0);
65
- }, 0);
66
- }, 0);
67
-
68
- return {
69
- id: workflow.id,
70
- name: workflow.name,
71
- active: workflow.active,
72
- nodeCount: workflow.nodes.length,
73
- connectionCount,
74
- updatedAt: workflow.updatedAt,
75
- nodeTypes: [...new Set(workflow.nodes.map((n) => n.type))],
76
- };
77
- }
78
-
79
- function toWorkflowCompact(workflow: N8nWorkflow): WorkflowCompact {
80
- // Simplify connections to just show flow: nodeName -> [targetNodeNames]
81
- const simpleConnections: Record<string, string[]> = {};
82
- for (const [nodeName, outputs] of Object.entries(workflow.connections)) {
83
- const targets: string[] = [];
84
- for (const conns of Object.values(outputs)) {
85
- for (const connList of conns) {
86
- for (const conn of connList) {
87
- if (!targets.includes(conn.node)) {
88
- targets.push(conn.node);
89
- }
90
- }
91
- }
92
- }
93
- if (targets.length > 0) {
94
- simpleConnections[nodeName] = targets;
95
- }
96
- }
97
-
98
- return {
99
- id: workflow.id,
100
- name: workflow.name,
101
- active: workflow.active,
102
- updatedAt: workflow.updatedAt,
103
- nodes: workflow.nodes.map(toCompactNode),
104
- connections: simpleConnections,
105
- ...(workflow.settings && Object.keys(workflow.settings).length > 0 && { settings: workflow.settings }),
106
- };
107
- }
108
-
109
- function toCompactNode(node: N8nNode): CompactNode {
110
- return {
111
- name: node.name,
112
- type: node.type,
113
- position: node.position,
114
- hasCredentials: !!node.credentials && Object.keys(node.credentials).length > 0,
115
- ...(node.disabled && { disabled: true }),
116
- };
117
- }
118
-
119
- // ─────────────────────────────────────────────────────────────
120
- // Execution Formatting
121
- // ─────────────────────────────────────────────────────────────
122
-
123
- export interface ExecutionSummary {
124
- id: string;
125
- workflowId: string;
126
- status: string;
127
- mode: string;
128
- startedAt: string;
129
- stoppedAt?: string;
130
- durationMs?: number;
131
- hasError: boolean;
132
- errorMessage?: string;
133
- }
134
-
135
- export interface ExecutionCompact {
136
- id: string;
137
- workflowId: string;
138
- status: string;
139
- mode: string;
140
- startedAt: string;
141
- stoppedAt?: string;
142
- finished: boolean;
143
- error?: { message: string };
144
- // runData omitted - often huge
145
- nodeResults?: NodeResultSummary[];
146
- }
147
-
148
- export interface NodeResultSummary {
149
- nodeName: string;
150
- itemCount: number;
151
- success: boolean;
152
- }
153
-
154
- /**
155
- * Format an execution based on the requested format level
156
- */
157
- export function formatExecutionResponse(
158
- execution: N8nExecution,
159
- format: ResponseFormat = 'compact'
160
- ): N8nExecution | ExecutionCompact | ExecutionSummary {
161
- switch (format) {
162
- case 'summary':
163
- return toExecutionSummary(execution);
164
- case 'compact':
165
- return toExecutionCompact(execution);
166
- case 'full':
167
- default:
168
- return execution;
169
- }
170
- }
171
-
172
- function toExecutionSummary(execution: N8nExecution): ExecutionSummary {
173
- const durationMs = execution.stoppedAt && execution.startedAt
174
- ? new Date(execution.stoppedAt).getTime() - new Date(execution.startedAt).getTime()
175
- : undefined;
176
-
177
- return {
178
- id: execution.id,
179
- workflowId: execution.workflowId,
180
- status: execution.status,
181
- mode: execution.mode,
182
- startedAt: execution.startedAt,
183
- stoppedAt: execution.stoppedAt,
184
- durationMs,
185
- hasError: execution.status === 'error',
186
- errorMessage: execution.data?.resultData?.error?.message,
187
- };
188
- }
189
-
190
- function toExecutionCompact(execution: N8nExecution): ExecutionCompact {
191
- const nodeResults: NodeResultSummary[] = [];
192
-
193
- if (execution.data?.resultData?.runData) {
194
- for (const [nodeName, runs] of Object.entries(execution.data.resultData.runData)) {
195
- // runData is Record<string, unknown>, so we need to handle it carefully
196
- const runArray = runs as Array<{ data?: { main?: Array<Array<unknown>> } }>;
197
- if (Array.isArray(runArray) && runArray.length > 0) {
198
- const lastRun = runArray[runArray.length - 1];
199
- const itemCount = lastRun?.data?.main?.[0]?.length ?? 0;
200
- nodeResults.push({
201
- nodeName,
202
- itemCount,
203
- success: true,
204
- });
205
- }
206
- }
207
- }
208
-
209
- return {
210
- id: execution.id,
211
- workflowId: execution.workflowId,
212
- status: execution.status,
213
- mode: execution.mode,
214
- startedAt: execution.startedAt,
215
- stoppedAt: execution.stoppedAt,
216
- finished: execution.finished,
217
- ...(execution.data?.resultData?.error && { error: { message: execution.data.resultData.error.message } }),
218
- ...(nodeResults.length > 0 && { nodeResults }),
219
- };
220
- }
221
-
222
- /**
223
- * Format execution list items
224
- */
225
- export function formatExecutionListResponse(
226
- executions: N8nExecutionListItem[],
227
- format: ResponseFormat = 'compact'
228
- ): N8nExecutionListItem[] | Array<{ id: string; status: string; startedAt: string }> {
229
- if (format === 'summary') {
230
- return executions.map((e) => ({
231
- id: e.id,
232
- status: e.status,
233
- startedAt: e.startedAt,
234
- }));
235
- }
236
- // compact and full are the same for list items (already minimal)
237
- return executions;
238
- }
239
-
240
- // ─────────────────────────────────────────────────────────────
241
- // Generic Response Utilities
242
- // ─────────────────────────────────────────────────────────────
243
-
244
- /**
245
- * Remove null/undefined values and empty objects to reduce size
246
- */
247
- export function cleanResponse<T>(obj: T): T {
248
- if (obj === null || obj === undefined) {
249
- return obj;
250
- }
251
- if (Array.isArray(obj)) {
252
- return obj.map(cleanResponse) as T;
253
- }
254
- if (typeof obj === 'object') {
255
- const cleaned: Record<string, unknown> = {};
256
- for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
257
- if (value !== null && value !== undefined) {
258
- const cleanedValue = cleanResponse(value);
259
- // Skip empty objects and arrays
260
- if (typeof cleanedValue === 'object' && cleanedValue !== null) {
261
- if (Array.isArray(cleanedValue) && cleanedValue.length === 0) continue;
262
- if (!Array.isArray(cleanedValue) && Object.keys(cleanedValue).length === 0) continue;
263
- }
264
- cleaned[key] = cleanedValue;
265
- }
266
- }
267
- return cleaned as T;
268
- }
269
- return obj;
270
- }
271
-
272
- /**
273
- * Stringify with optional minification
274
- */
275
- export function stringifyResponse(obj: unknown, minify = true): string {
276
- const cleaned = cleanResponse(obj);
277
- return minify ? JSON.stringify(cleaned) : JSON.stringify(cleaned, null, 2);
278
- }