@pagelines/n8n-mcp 0.3.0 → 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,295 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { N8nClient } from './n8n-client.js';
3
- // Mock fetch globally
4
- const mockFetch = vi.fn();
5
- global.fetch = mockFetch;
6
- describe('N8nClient', () => {
7
- let client;
8
- beforeEach(() => {
9
- client = new N8nClient({
10
- apiUrl: 'https://n8n.example.com',
11
- apiKey: 'test-api-key',
12
- });
13
- mockFetch.mockReset();
14
- });
15
- describe('constructor', () => {
16
- it('normalizes URL by removing trailing slash', () => {
17
- const clientWithSlash = new N8nClient({
18
- apiUrl: 'https://n8n.example.com/',
19
- apiKey: 'key',
20
- });
21
- // Access private property for testing
22
- expect(clientWithSlash.baseUrl).toBe('https://n8n.example.com');
23
- });
24
- });
25
- describe('listWorkflows', () => {
26
- it('calls correct endpoint', async () => {
27
- mockFetch.mockResolvedValueOnce({
28
- ok: true,
29
- text: async () => JSON.stringify({ data: [] }),
30
- });
31
- await client.listWorkflows();
32
- expect(mockFetch).toHaveBeenCalledWith('https://n8n.example.com/api/v1/workflows', expect.objectContaining({
33
- method: 'GET',
34
- headers: expect.objectContaining({
35
- 'X-N8N-API-KEY': 'test-api-key',
36
- }),
37
- }));
38
- });
39
- it('includes query params when provided', async () => {
40
- mockFetch.mockResolvedValueOnce({
41
- ok: true,
42
- text: async () => JSON.stringify({ data: [] }),
43
- });
44
- await client.listWorkflows({ active: true, limit: 10 });
45
- expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('active=true'), expect.any(Object));
46
- expect(mockFetch).toHaveBeenCalledWith(expect.stringContaining('limit=10'), expect.any(Object));
47
- });
48
- });
49
- describe('patchWorkflow', () => {
50
- const mockWorkflow = {
51
- id: '1',
52
- name: 'test_workflow',
53
- active: false,
54
- nodes: [
55
- {
56
- id: 'node1',
57
- name: 'existing_node',
58
- type: 'n8n-nodes-base.set',
59
- typeVersion: 1,
60
- position: [0, 0],
61
- parameters: { param1: 'value1', param2: 'value2' },
62
- },
63
- ],
64
- connections: {},
65
- createdAt: '2024-01-01',
66
- updatedAt: '2024-01-01',
67
- };
68
- beforeEach(() => {
69
- // Mock GET workflow
70
- mockFetch.mockResolvedValueOnce({
71
- ok: true,
72
- text: async () => JSON.stringify(mockWorkflow),
73
- });
74
- // Mock PUT workflow
75
- mockFetch.mockResolvedValueOnce({
76
- ok: true,
77
- text: async () => JSON.stringify(mockWorkflow),
78
- });
79
- });
80
- it('warns when updateNode would remove parameters', async () => {
81
- const { warnings } = await client.patchWorkflow('1', [
82
- {
83
- type: 'updateNode',
84
- nodeName: 'existing_node',
85
- properties: {
86
- parameters: { newParam: 'newValue' }, // Missing param1, param2
87
- },
88
- },
89
- ]);
90
- expect(warnings).toContainEqual(expect.stringContaining('remove parameters'));
91
- expect(warnings).toContainEqual(expect.stringContaining('param1'));
92
- });
93
- it('warns when removing non-existent node', async () => {
94
- const { warnings } = await client.patchWorkflow('1', [
95
- {
96
- type: 'removeNode',
97
- nodeName: 'nonexistent_node',
98
- },
99
- ]);
100
- expect(warnings).toContainEqual(expect.stringContaining('not found'));
101
- });
102
- it('adds node correctly', async () => {
103
- mockFetch.mockReset();
104
- mockFetch.mockResolvedValueOnce({
105
- ok: true,
106
- text: async () => JSON.stringify(mockWorkflow),
107
- });
108
- const updatedWorkflow = {
109
- ...mockWorkflow,
110
- nodes: [
111
- ...mockWorkflow.nodes,
112
- {
113
- id: 'new-id',
114
- name: 'new_node',
115
- type: 'n8n-nodes-base.code',
116
- typeVersion: 1,
117
- position: [100, 100],
118
- parameters: {},
119
- },
120
- ],
121
- };
122
- mockFetch.mockResolvedValueOnce({
123
- ok: true,
124
- text: async () => JSON.stringify(updatedWorkflow),
125
- });
126
- const { workflow } = await client.patchWorkflow('1', [
127
- {
128
- type: 'addNode',
129
- node: {
130
- name: 'new_node',
131
- type: 'n8n-nodes-base.code',
132
- typeVersion: 1,
133
- position: [100, 100],
134
- parameters: {},
135
- },
136
- },
137
- ]);
138
- // Verify PUT was called with the new node
139
- const putCall = mockFetch.mock.calls[1];
140
- const putBody = JSON.parse(putCall[1].body);
141
- expect(putBody.nodes).toHaveLength(2);
142
- expect(putBody.nodes[1].name).toBe('new_node');
143
- });
144
- it('adds connection correctly', async () => {
145
- mockFetch.mockReset();
146
- mockFetch.mockResolvedValueOnce({
147
- ok: true,
148
- text: async () => JSON.stringify(mockWorkflow),
149
- });
150
- const updatedWorkflow = {
151
- ...mockWorkflow,
152
- connections: {
153
- existing_node: {
154
- main: [[{ node: 'target_node', type: 'main', index: 0 }]],
155
- },
156
- },
157
- };
158
- mockFetch.mockResolvedValueOnce({
159
- ok: true,
160
- text: async () => JSON.stringify(updatedWorkflow),
161
- });
162
- await client.patchWorkflow('1', [
163
- {
164
- type: 'addConnection',
165
- from: 'existing_node',
166
- to: 'target_node',
167
- },
168
- ]);
169
- const putCall = mockFetch.mock.calls[1];
170
- const putBody = JSON.parse(putCall[1].body);
171
- expect(putBody.connections.existing_node.main[0][0].node).toBe('target_node');
172
- });
173
- });
174
- describe('error handling', () => {
175
- it('throws on non-ok response', async () => {
176
- mockFetch.mockResolvedValueOnce({
177
- ok: false,
178
- status: 404,
179
- text: async () => 'Not found',
180
- });
181
- await expect(client.getWorkflow('999')).rejects.toThrow('n8n API error (404)');
182
- });
183
- });
184
- describe('listNodeTypes', () => {
185
- it('calls correct endpoint', async () => {
186
- const mockNodeTypes = [
187
- {
188
- name: 'n8n-nodes-base.webhook',
189
- displayName: 'Webhook',
190
- description: 'Starts workflow on webhook call',
191
- group: ['trigger'],
192
- version: 2,
193
- },
194
- {
195
- name: 'n8n-nodes-base.set',
196
- displayName: 'Set',
197
- description: 'Set values',
198
- group: ['transform'],
199
- version: 3,
200
- },
201
- ];
202
- mockFetch.mockResolvedValueOnce({
203
- ok: true,
204
- text: async () => JSON.stringify(mockNodeTypes),
205
- });
206
- const result = await client.listNodeTypes();
207
- expect(mockFetch).toHaveBeenCalledWith('https://n8n.example.com/api/v1/nodes', expect.objectContaining({
208
- method: 'GET',
209
- headers: expect.objectContaining({
210
- 'X-N8N-API-KEY': 'test-api-key',
211
- }),
212
- }));
213
- expect(result).toHaveLength(2);
214
- expect(result[0].name).toBe('n8n-nodes-base.webhook');
215
- expect(result[1].name).toBe('n8n-nodes-base.set');
216
- });
217
- });
218
- describe('updateWorkflow', () => {
219
- it('strips disallowed properties before sending to API', async () => {
220
- const fullWorkflow = {
221
- id: '123',
222
- name: 'test_workflow',
223
- active: true,
224
- nodes: [{ id: 'n1', name: 'node1', type: 'test', typeVersion: 1, position: [0, 0], parameters: {} }],
225
- connections: {},
226
- settings: { timezone: 'UTC' },
227
- createdAt: '2024-01-01T00:00:00.000Z',
228
- updatedAt: '2024-01-02T00:00:00.000Z',
229
- versionId: 'v1',
230
- staticData: undefined,
231
- tags: [{ id: 't1', name: 'tag1' }],
232
- };
233
- mockFetch.mockResolvedValueOnce({
234
- ok: true,
235
- text: async () => JSON.stringify(fullWorkflow),
236
- });
237
- await client.updateWorkflow('123', fullWorkflow);
238
- // Verify the request body does NOT contain disallowed properties
239
- const putCall = mockFetch.mock.calls[0];
240
- const putBody = JSON.parse(putCall[1].body);
241
- // These should be stripped
242
- expect(putBody.id).toBeUndefined();
243
- expect(putBody.createdAt).toBeUndefined();
244
- expect(putBody.updatedAt).toBeUndefined();
245
- expect(putBody.active).toBeUndefined();
246
- expect(putBody.versionId).toBeUndefined();
247
- // These should be preserved
248
- expect(putBody.name).toBe('test_workflow');
249
- expect(putBody.nodes).toHaveLength(1);
250
- expect(putBody.connections).toEqual({});
251
- expect(putBody.settings).toEqual({ timezone: 'UTC' });
252
- expect(putBody.staticData).toBeUndefined();
253
- expect(putBody.tags).toEqual([{ id: 't1', name: 'tag1' }]);
254
- });
255
- it('works with partial workflow (only some fields)', async () => {
256
- mockFetch.mockResolvedValueOnce({
257
- ok: true,
258
- text: async () => JSON.stringify({ id: '123', name: 'updated' }),
259
- });
260
- await client.updateWorkflow('123', { name: 'updated', nodes: [] });
261
- const putCall = mockFetch.mock.calls[0];
262
- const putBody = JSON.parse(putCall[1].body);
263
- expect(putBody.name).toBe('updated');
264
- expect(putBody.nodes).toEqual([]);
265
- });
266
- it('handles workflow from formatWorkflow (simulating workflow_format apply)', async () => {
267
- // This simulates the exact scenario that caused the bug:
268
- // workflow_format returns a full N8nWorkflow object with id, createdAt, etc.
269
- const formattedWorkflow = {
270
- id: 'zbB1fCxWgZXgpjB1',
271
- name: 'my_workflow',
272
- active: false,
273
- nodes: [],
274
- connections: {},
275
- createdAt: '2024-01-01T00:00:00.000Z',
276
- updatedAt: '2024-01-02T00:00:00.000Z',
277
- };
278
- mockFetch.mockResolvedValueOnce({
279
- ok: true,
280
- text: async () => JSON.stringify(formattedWorkflow),
281
- });
282
- // This should NOT throw "must NOT have additional properties"
283
- await client.updateWorkflow('zbB1fCxWgZXgpjB1', formattedWorkflow);
284
- const putCall = mockFetch.mock.calls[0];
285
- const putBody = JSON.parse(putCall[1].body);
286
- // Critical: these must NOT be in the request body
287
- expect(putBody.id).toBeUndefined();
288
- expect(putBody.createdAt).toBeUndefined();
289
- expect(putBody.updatedAt).toBeUndefined();
290
- expect(putBody.active).toBeUndefined();
291
- // Only allowed properties should be sent
292
- expect(Object.keys(putBody).sort()).toEqual(['connections', 'name', 'nodes']);
293
- });
294
- });
295
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,291 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { formatWorkflowResponse, formatExecutionResponse, formatExecutionListResponse, cleanResponse, stringifyResponse, } from './response-format.js';
3
- const createWorkflow = (overrides = {}) => ({
4
- id: '1',
5
- name: 'test_workflow',
6
- active: false,
7
- nodes: [
8
- {
9
- id: 'node1',
10
- name: 'webhook_trigger',
11
- type: 'n8n-nodes-base.webhook',
12
- typeVersion: 1,
13
- position: [0, 0],
14
- parameters: { path: 'test', httpMethod: 'POST' },
15
- },
16
- {
17
- id: 'node2',
18
- name: 'set_data',
19
- type: 'n8n-nodes-base.set',
20
- typeVersion: 1,
21
- position: [200, 0],
22
- parameters: { values: { string: [{ name: 'key', value: 'value' }] } },
23
- credentials: { httpBasicAuth: { id: '1', name: 'My Auth' } },
24
- },
25
- ],
26
- connections: {
27
- webhook_trigger: {
28
- main: [[{ node: 'set_data', type: 'main', index: 0 }]],
29
- },
30
- },
31
- createdAt: '2024-01-01T00:00:00.000Z',
32
- updatedAt: '2024-01-02T00:00:00.000Z',
33
- ...overrides,
34
- });
35
- const createExecution = (overrides = {}) => ({
36
- id: 'exec1',
37
- workflowId: '1',
38
- finished: true,
39
- mode: 'manual',
40
- startedAt: '2024-01-01T00:00:00.000Z',
41
- stoppedAt: '2024-01-01T00:00:05.000Z',
42
- status: 'success',
43
- data: {
44
- resultData: {
45
- runData: {
46
- webhook_trigger: [{ data: { main: [[{ json: { test: 'data' } }]] } }],
47
- set_data: [{ data: { main: [[{ json: { key: 'value' } }]] } }],
48
- },
49
- },
50
- },
51
- ...overrides,
52
- });
53
- describe('formatWorkflowResponse', () => {
54
- describe('summary format', () => {
55
- it('returns minimal workflow info', () => {
56
- const workflow = createWorkflow();
57
- const result = formatWorkflowResponse(workflow, 'summary');
58
- expect(result.id).toBe('1');
59
- expect(result.name).toBe('test_workflow');
60
- expect(result.active).toBe(false);
61
- expect(result.nodeCount).toBe(2);
62
- expect(result.connectionCount).toBe(1);
63
- expect(result.updatedAt).toBe('2024-01-02T00:00:00.000Z');
64
- expect(result.nodeTypes).toContain('n8n-nodes-base.webhook');
65
- expect(result.nodeTypes).toContain('n8n-nodes-base.set');
66
- // Should not have full nodes or connections
67
- expect(result.nodes).toBeUndefined();
68
- expect(result.connections).toBeUndefined();
69
- });
70
- });
71
- describe('compact format', () => {
72
- it('returns nodes without parameters', () => {
73
- const workflow = createWorkflow();
74
- const result = formatWorkflowResponse(workflow, 'compact');
75
- expect(result.id).toBe('1');
76
- expect(result.name).toBe('test_workflow');
77
- expect(result.nodes).toHaveLength(2);
78
- // Nodes should have name, type, position but no parameters
79
- expect(result.nodes[0].name).toBe('webhook_trigger');
80
- expect(result.nodes[0].type).toBe('n8n-nodes-base.webhook');
81
- expect(result.nodes[0].position).toEqual([0, 0]);
82
- expect(result.nodes[0].hasCredentials).toBe(false);
83
- expect(result.nodes[0].parameters).toBeUndefined();
84
- // Second node has credentials
85
- expect(result.nodes[1].hasCredentials).toBe(true);
86
- });
87
- it('simplifies connections to node -> [targets] map', () => {
88
- const workflow = createWorkflow();
89
- const result = formatWorkflowResponse(workflow, 'compact');
90
- expect(result.connections).toEqual({
91
- webhook_trigger: ['set_data'],
92
- });
93
- });
94
- it('marks disabled nodes', () => {
95
- const workflow = createWorkflow({
96
- nodes: [
97
- {
98
- id: 'node1',
99
- name: 'disabled_node',
100
- type: 'n8n-nodes-base.set',
101
- typeVersion: 1,
102
- position: [0, 0],
103
- parameters: {},
104
- disabled: true,
105
- },
106
- ],
107
- });
108
- const result = formatWorkflowResponse(workflow, 'compact');
109
- expect(result.nodes[0].disabled).toBe(true);
110
- });
111
- });
112
- describe('full format', () => {
113
- it('returns complete workflow', () => {
114
- const workflow = createWorkflow();
115
- const result = formatWorkflowResponse(workflow, 'full');
116
- expect(result).toEqual(workflow);
117
- expect(result.nodes[0].parameters).toEqual({ path: 'test', httpMethod: 'POST' });
118
- });
119
- });
120
- describe('default format', () => {
121
- it('defaults to compact', () => {
122
- const workflow = createWorkflow();
123
- const result = formatWorkflowResponse(workflow);
124
- // Should be compact (no parameters)
125
- expect(result.nodes[0].parameters).toBeUndefined();
126
- });
127
- });
128
- });
129
- describe('formatExecutionResponse', () => {
130
- describe('summary format', () => {
131
- it('returns minimal execution info', () => {
132
- const execution = createExecution();
133
- const result = formatExecutionResponse(execution, 'summary');
134
- expect(result.id).toBe('exec1');
135
- expect(result.workflowId).toBe('1');
136
- expect(result.status).toBe('success');
137
- expect(result.mode).toBe('manual');
138
- expect(result.durationMs).toBe(5000);
139
- expect(result.hasError).toBe(false);
140
- // Should not have runData
141
- expect(result.data).toBeUndefined();
142
- });
143
- it('includes error message when present', () => {
144
- const execution = createExecution({
145
- status: 'error',
146
- data: {
147
- resultData: {
148
- error: { message: 'Something went wrong' },
149
- },
150
- },
151
- });
152
- const result = formatExecutionResponse(execution, 'summary');
153
- expect(result.hasError).toBe(true);
154
- expect(result.errorMessage).toBe('Something went wrong');
155
- });
156
- });
157
- describe('compact format', () => {
158
- it('returns execution without runData but with node summaries', () => {
159
- const execution = createExecution();
160
- const result = formatExecutionResponse(execution, 'compact');
161
- expect(result.id).toBe('exec1');
162
- expect(result.status).toBe('success');
163
- expect(result.finished).toBe(true);
164
- // Should have node result summaries
165
- expect(result.nodeResults).toHaveLength(2);
166
- expect(result.nodeResults[0].nodeName).toBe('webhook_trigger');
167
- expect(result.nodeResults[0].itemCount).toBe(1);
168
- // Should not have full runData
169
- expect(result.data).toBeUndefined();
170
- });
171
- it('includes error in compact format', () => {
172
- const execution = createExecution({
173
- status: 'error',
174
- data: {
175
- resultData: {
176
- error: { message: 'Failed' },
177
- },
178
- },
179
- });
180
- const result = formatExecutionResponse(execution, 'compact');
181
- expect(result.error).toEqual({ message: 'Failed' });
182
- });
183
- });
184
- describe('full format', () => {
185
- it('returns complete execution with runData', () => {
186
- const execution = createExecution();
187
- const result = formatExecutionResponse(execution, 'full');
188
- expect(result).toEqual(execution);
189
- expect(result.data?.resultData?.runData).toBeDefined();
190
- });
191
- });
192
- });
193
- describe('formatExecutionListResponse', () => {
194
- const executions = [
195
- { id: '1', workflowId: 'w1', status: 'success', startedAt: '2024-01-01', mode: 'manual' },
196
- { id: '2', workflowId: 'w1', status: 'error', startedAt: '2024-01-02', mode: 'webhook' },
197
- ];
198
- it('summary returns id, status, startedAt only', () => {
199
- const result = formatExecutionListResponse(executions, 'summary');
200
- expect(result).toHaveLength(2);
201
- expect(result[0]).toEqual({ id: '1', status: 'success', startedAt: '2024-01-01' });
202
- expect(result[0].workflowId).toBeUndefined();
203
- expect(result[0].mode).toBeUndefined();
204
- });
205
- it('compact and full return same as input', () => {
206
- const compactResult = formatExecutionListResponse(executions, 'compact');
207
- const fullResult = formatExecutionListResponse(executions, 'full');
208
- expect(compactResult).toEqual(executions);
209
- expect(fullResult).toEqual(executions);
210
- });
211
- });
212
- describe('cleanResponse', () => {
213
- it('removes null values', () => {
214
- const obj = { a: 1, b: null, c: 'test' };
215
- const result = cleanResponse(obj);
216
- expect(result).toEqual({ a: 1, c: 'test' });
217
- });
218
- it('removes undefined values', () => {
219
- const obj = { a: 1, b: undefined, c: 'test' };
220
- const result = cleanResponse(obj);
221
- expect(result).toEqual({ a: 1, c: 'test' });
222
- });
223
- it('removes empty objects', () => {
224
- const obj = { a: 1, b: {}, c: 'test' };
225
- const result = cleanResponse(obj);
226
- expect(result).toEqual({ a: 1, c: 'test' });
227
- });
228
- it('removes empty arrays', () => {
229
- const obj = { a: 1, b: [], c: 'test' };
230
- const result = cleanResponse(obj);
231
- expect(result).toEqual({ a: 1, c: 'test' });
232
- });
233
- it('handles nested objects', () => {
234
- const obj = { a: { b: null, c: 1 }, d: { e: {} } };
235
- const result = cleanResponse(obj);
236
- expect(result).toEqual({ a: { c: 1 } });
237
- });
238
- it('handles arrays', () => {
239
- const arr = [{ a: 1, b: null }, { c: 2 }];
240
- const result = cleanResponse(arr);
241
- expect(result).toEqual([{ a: 1 }, { c: 2 }]);
242
- });
243
- });
244
- describe('stringifyResponse', () => {
245
- it('minifies by default', () => {
246
- const obj = { a: 1, b: 'test' };
247
- const result = stringifyResponse(obj);
248
- expect(result).toBe('{"a":1,"b":"test"}');
249
- expect(result).not.toContain('\n');
250
- });
251
- it('can pretty print when minify=false', () => {
252
- const obj = { a: 1 };
253
- const result = stringifyResponse(obj, false);
254
- expect(result).toContain('\n');
255
- });
256
- it('cleans null values before stringifying', () => {
257
- const obj = { a: 1, b: null };
258
- const result = stringifyResponse(obj);
259
- expect(result).toBe('{"a":1}');
260
- });
261
- });
262
- describe('token reduction estimates', () => {
263
- it('compact format significantly reduces workflow size', () => {
264
- const workflow = createWorkflow({
265
- nodes: Array.from({ length: 10 }, (_, i) => ({
266
- id: `node${i}`,
267
- name: `node_${i}`,
268
- type: 'n8n-nodes-base.set',
269
- typeVersion: 1,
270
- position: [i * 200, 0],
271
- parameters: {
272
- values: {
273
- string: Array.from({ length: 10 }, (_, j) => ({
274
- name: `param_${j}`,
275
- value: `This is a long value that takes up tokens ${j}`,
276
- })),
277
- },
278
- },
279
- })),
280
- });
281
- const fullJson = JSON.stringify(workflow);
282
- const compactJson = stringifyResponse(formatWorkflowResponse(workflow, 'compact'));
283
- const summaryJson = stringifyResponse(formatWorkflowResponse(workflow, 'summary'));
284
- // Compact should be significantly smaller than full
285
- expect(compactJson.length).toBeLessThan(fullJson.length * 0.5);
286
- // Summary should be smallest
287
- expect(summaryJson.length).toBeLessThan(compactJson.length);
288
- console.log(`Full: ${fullJson.length} chars, Compact: ${compactJson.length} chars, Summary: ${summaryJson.length} chars`);
289
- console.log(`Reduction: ${Math.round((1 - compactJson.length / fullJson.length) * 100)}% (compact), ${Math.round((1 - summaryJson.length / fullJson.length) * 100)}% (summary)`);
290
- });
291
- });
@@ -1 +0,0 @@
1
- export {};