forked from tcmartin/flowrunner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcpexample
More file actions
658 lines (605 loc) · 18.5 KB
/
mcpexample
File metadata and controls
658 lines (605 loc) · 18.5 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
import {
IExecuteFunctions,
INodeExecutionData,
INodeType,
INodeTypeDescription,
NodeConnectionType,
NodeOperationError,
} from 'n8n-workflow';
import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
// Add Node.js process type declaration
declare const process: {
env: Record<string, string | undefined>;
};
export class McpClient implements INodeType {
description: INodeTypeDescription = {
displayName: 'MCP Client',
name: 'mcpClient',
icon: 'file:mcpClient.svg',
group: ['transform'],
version: 1,
subtitle: '={{$parameter["operation"]}}',
description: 'Use MCP client',
defaults: {
name: 'MCP Client',
},
// @ts-ignore - node-class-description-outputs-wrong
inputs: [{ type: NodeConnectionType.Main }],
// @ts-ignore - node-class-description-outputs-wrong
outputs: [{ type: NodeConnectionType.Main }],
usableAsTool: true,
credentials: [
{
name: 'mcpClientApi',
required: false,
displayOptions: {
show: {
connectionType: ['cmd'],
},
},
},
{
name: 'mcpClientSseApi',
required: false,
displayOptions: {
show: {
connectionType: ['sse'],
},
},
},
{
name: 'mcpClientHttpApi',
required: false,
displayOptions: {
show: {
connectionType: ['http'],
},
},
},
],
properties: [
{
displayName: 'Connection Type',
name: 'connectionType',
type: 'options',
options: [
{
name: 'Command Line (STDIO)',
value: 'cmd',
},
{
name: 'Server-Sent Events (SSE)',
value: 'sse',
description: 'Deprecated: Use HTTP Streamable instead',
},
{
name: 'HTTP Streamable',
value: 'http',
description: 'Use HTTP streamable protocol for real-time communication',
},
],
default: 'cmd',
description: 'Choose the transport type to connect to MCP server',
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
noDataExpression: true,
options: [
{
name: 'Execute Tool',
value: 'executeTool',
description: 'Execute a specific tool',
action: 'Execute a tool',
},
{
name: 'Get Prompt',
value: 'getPrompt',
description: 'Get a specific prompt template',
action: 'Get a prompt template',
},
{
name: 'List Prompts',
value: 'listPrompts',
description: 'Get available prompts',
action: 'List available prompts',
},
{
name: 'List Resource Templates',
value: 'listResourceTemplates',
description: 'Get a list of available resource templates',
action: 'List available resource templates',
},
{
name: 'List Resources',
value: 'listResources',
description: 'Get a list of available resources',
action: 'List available resources',
},
{
name: 'List Tools',
value: 'listTools',
description: 'Get available tools',
action: 'List available tools',
},
{
name: 'Read Resource',
value: 'readResource',
description: 'Read a specific resource by URI',
action: 'Read a resource',
},
],
default: 'listTools',
required: true,
},
{
displayName: 'Resource URI',
name: 'resourceUri',
type: 'string',
required: true,
displayOptions: {
show: {
operation: ['readResource'],
},
},
default: '',
description: 'URI of the resource to read',
},
{
displayName: 'Tool Name',
name: 'toolName',
type: 'string',
required: true,
displayOptions: {
show: {
operation: ['executeTool'],
},
},
default: '',
description: 'Name of the tool to execute',
},
{
displayName: 'Tool Parameters',
name: 'toolParameters',
type: 'json',
required: true,
displayOptions: {
show: {
operation: ['executeTool'],
},
},
default: '{}',
description: 'Parameters to pass to the tool in JSON format',
},
{
displayName: 'Prompt Name',
name: 'promptName',
type: 'string',
required: true,
displayOptions: {
show: {
operation: ['getPrompt'],
},
},
default: '',
description: 'Name of the prompt template to get',
},
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const returnData: INodeExecutionData[] = [];
const operation = this.getNodeParameter('operation', 0) as string;
let transport: Transport | undefined;
// For backward compatibility - if connectionType isn't set, default to 'cmd'
let connectionType = 'cmd';
try {
connectionType = this.getNodeParameter('connectionType', 0) as string;
} catch (error) {
// If connectionType parameter doesn't exist, keep default 'cmd'
this.logger.debug('ConnectionType parameter not found, using default "cmd" transport');
}
let timeout = 600000;
try {
if (connectionType === 'http') {
// Use HTTP Streamable transport
const httpCredentials = await this.getCredentials('mcpClientHttpApi');
// Dynamically import the HTTP client
const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js');
const httpStreamUrl = httpCredentials.httpStreamUrl as string;
const messagesPostEndpoint = (httpCredentials.messagesPostEndpoint as string) || '';
timeout = httpCredentials.httpTimeout as number || 60000;
// Parse headers
let headers: Record<string, string> = {};
if (httpCredentials.headers) {
const headerLines = (httpCredentials.headers as string).split('\n');
for (const line of headerLines) {
const equalsIndex = line.indexOf('=');
// Ensure '=' is present and not the first character of the line
if (equalsIndex > 0) {
const name = line.substring(0, equalsIndex).trim();
const value = line.substring(equalsIndex + 1).trim();
// Add to headers object if key is not empty and value is defined
if (name && value !== undefined) {
headers[name] = value;
}
}
}
}
const requestInit: RequestInit = { headers };
if (messagesPostEndpoint) {
(requestInit as any).endpoint = new URL(messagesPostEndpoint);
}
transport = new StreamableHTTPClientTransport(
new URL(httpStreamUrl),
{ requestInit }
);
} else if (connectionType === 'sse') {
// Use SSE transport
const sseCredentials = await this.getCredentials('mcpClientSseApi');
// Dynamically import the SSE client to avoid TypeScript errors
const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js');
const sseUrl = sseCredentials.sseUrl as string;
const messagesPostEndpoint = (sseCredentials.messagesPostEndpoint as string) || '';
timeout = sseCredentials.sseTimeout as number || 60000;
// Parse headers
let headers: Record<string, string> = {};
if (sseCredentials.headers) {
const headerLines = (sseCredentials.headers as string).split('\n');
for (const line of headerLines) {
const equalsIndex = line.indexOf('=');
// Ensure '=' is present and not the first character of the line
if (equalsIndex > 0) {
const name = line.substring(0, equalsIndex).trim();
const value = line.substring(equalsIndex + 1).trim();
// Add to headers object if key is not empty and value is defined
if (name && value !== undefined) {
headers[name] = value;
}
}
}
}
// Create SSE transport with dynamic import to avoid TypeScript errors
transport = new SSEClientTransport(
// @ts-ignore
new URL(sseUrl),
{
// @ts-ignore
eventSourceInit: { headers },
// @ts-ignore
requestInit: {
headers,
...(messagesPostEndpoint
? {
// @ts-ignore
endpoint: new URL(messagesPostEndpoint),
}
: {}),
},
},
);
this.logger.debug(`Created SSE transport for MCP client URL: ${sseUrl}`);
if (messagesPostEndpoint) {
this.logger.debug(`Using custom POST endpoint: ${messagesPostEndpoint}`);
}
} else {
// Use stdio transport (default)
const cmdCredentials = await this.getCredentials('mcpClientApi');
// Build environment variables object for MCP servers
const env: Record<string, string> = {
// Preserve the PATH environment variable to ensure commands can be found
PATH: process.env.PATH || '',
};
this.logger.debug(`Original PATH: ${process.env.PATH}`);
// Parse newline-separated environment variables from credentials
if (cmdCredentials.environments) {
const envLines = (cmdCredentials.environments as string).split('\n');
for (const line of envLines) {
const equalsIndex = line.indexOf('=');
// Ensure '=' is present and not the first character of the line
if (equalsIndex > 0) {
const name = line.substring(0, equalsIndex).trim();
const value = line.substring(equalsIndex + 1).trim();
// Add to env object if key is not empty and value is defined
if (name && value !== undefined) {
env[name] = value;
}
}
}
}
// Process environment variables from Node.js
// This allows Docker environment variables to override credentials
for (const key in process.env) {
// Only pass through MCP-related environment variables
if (key.startsWith('MCP_') && process.env[key]) {
// Strip off the MCP_ prefix when passing to the MCP server
const envName = key.substring(4); // Remove 'MCP_'
env[envName] = process.env[key] as string;
}
}
transport = new StdioClientTransport({
command: cmdCredentials.command as string,
args: (cmdCredentials.args as string)?.split(' ') || [],
env: env, // Always pass the env with PATH preserved
});
// Use n8n's logger instead of console.log
this.logger.debug(
`Transport created for MCP client command: ${cmdCredentials.command}, PATH: ${env.PATH}`,
);
}
// Add error handling to transport
if (transport) {
transport.onerror = (error: Error) => {
throw new NodeOperationError(this.getNode(), `Transport error: ${error.message}`);
};
}
const client = new Client(
{
name: `${McpClient.name}-client`,
version: '1.0.0',
},
{
capabilities: {
prompts: {},
resources: {},
tools: {},
},
},
);
try {
if (!transport) {
throw new NodeOperationError(this.getNode(), 'No transport available');
}
await client.connect(transport);
this.logger.debug('Client connected to MCP server');
} catch (connectionError) {
this.logger.error(`MCP client connection error: ${(connectionError as Error).message}`);
throw new NodeOperationError(
this.getNode(),
`Failed to connect to MCP server: ${(connectionError as Error).message}`,
);
}
// Create a RequestOptions object from environment variables
const requestOptions: RequestOptions = {};
requestOptions.timeout = timeout;
switch (operation) {
case 'listResources': {
const resources = await client.listResources();
returnData.push({
json: { resources },
});
break;
}
case 'listResourceTemplates': {
const resourceTemplates = await client.listResourceTemplates();
returnData.push({
json: { resourceTemplates },
});
break;
}
case 'readResource': {
const uri = this.getNodeParameter('resourceUri', 0) as string;
const resource = await client.readResource({
uri,
});
returnData.push({
json: { resource },
});
break;
}
case 'listTools': {
const rawTools = await client.listTools();
const tools = Array.isArray(rawTools)
? rawTools
: Array.isArray(rawTools?.tools)
? rawTools.tools
: typeof rawTools?.tools === 'object' && rawTools.tools !== null
? Object.values(rawTools.tools)
: [];
if (!tools.length) {
this.logger.warn('No tools found from MCP client response.');
throw new NodeOperationError(this.getNode(), 'No tools found from MCP client');
}
const aiTools = tools.map((tool: any) => {
const paramSchema = tool.inputSchema?.properties
? z.object(
Object.entries(tool.inputSchema.properties).reduce(
(acc: any, [key, prop]: [string, any]) => {
let zodType: z.ZodType;
switch (prop.type) {
case 'string':
zodType = z.string();
break;
case 'number':
zodType = z.number();
break;
case 'integer':
zodType = z.number().int();
break;
case 'boolean':
zodType = z.boolean();
break;
case 'array':
if (prop.items?.type === 'string') {
zodType = z.array(z.string());
} else if (prop.items?.type === 'number') {
zodType = z.array(z.number());
} else if (prop.items?.type === 'boolean') {
zodType = z.array(z.boolean());
} else {
zodType = z.array(z.any());
}
break;
case 'object':
zodType = z.record(z.string(), z.any());
break;
default:
zodType = z.any();
}
if (prop.description) {
zodType = zodType.describe(prop.description);
}
if (!tool.inputSchema?.required?.includes(key)) {
zodType = zodType.optional();
}
return {
...acc,
[key]: zodType,
};
},
{},
),
)
: z.object({});
return new DynamicStructuredTool({
name: tool.name,
description: tool.description || `Execute the ${tool.name} tool`,
schema: paramSchema,
func: async (params) => {
try {
const result = await client.callTool({
name: tool.name,
arguments: params,
}, CallToolResultSchema, requestOptions);
return typeof result === 'object' ? JSON.stringify(result) : String(result);
} catch (error) {
throw new NodeOperationError(
this.getNode(),
`Failed to execute ${tool.name}: ${(error as Error).message}`,
);
}
},
});
});
returnData.push({
json: {
tools: aiTools.map((t: DynamicStructuredTool) => ({
name: t.name,
description: t.description,
schema: zodToJsonSchema(t.schema as z.ZodTypeAny || z.object({})),
})),
},
});
break;
}
case 'executeTool': {
const toolName = this.getNodeParameter('toolName', 0) as string;
let toolParams;
try {
const rawParams = this.getNodeParameter('toolParameters', 0);
this.logger.debug(`Raw tool parameters: ${JSON.stringify(rawParams)}`);
// Handle different parameter types
if (rawParams === undefined || rawParams === null) {
// Handle null/undefined case
toolParams = {};
} else if (typeof rawParams === 'string') {
// Handle string input (typical direct node usage)
if (!rawParams || rawParams.trim() === '') {
toolParams = {};
} else {
toolParams = JSON.parse(rawParams);
}
} else if (typeof rawParams === 'object') {
// Handle object input (when used as a tool in AI Agent)
toolParams = rawParams;
} else {
// Try to convert other types to object
try {
toolParams = JSON.parse(JSON.stringify(rawParams));
} catch (parseError) {
throw new NodeOperationError(
this.getNode(),
`Invalid parameter type: ${typeof rawParams}`,
);
}
}
// Ensure toolParams is an object
if (
typeof toolParams !== 'object' ||
toolParams === null ||
Array.isArray(toolParams)
) {
throw new NodeOperationError(this.getNode(), 'Tool parameters must be a JSON object');
}
} catch (error) {
throw new NodeOperationError(
this.getNode(),
`Failed to parse tool parameters: ${(error as Error).message
}. Make sure the parameters are valid JSON.`,
);
}
// Validate tool exists before executing
try {
const availableTools = await client.listTools();
const toolsList = Array.isArray(availableTools)
? availableTools
: Array.isArray(availableTools?.tools)
? availableTools.tools
: Object.values(availableTools?.tools || {});
const toolExists = toolsList.some((tool: any) => tool.name === toolName);
if (!toolExists) {
const availableToolNames = toolsList.map((t: any) => t.name).join(', ');
throw new NodeOperationError(
this.getNode(),
`Tool '${toolName}' does not exist. Available tools: ${availableToolNames}`,
);
}
this.logger.debug(
`Executing tool: ${toolName} with params: ${JSON.stringify(toolParams)}`,
);
const result = await client.callTool({
name: toolName,
arguments: toolParams,
}, CallToolResultSchema, requestOptions);
this.logger.debug(`Tool executed successfully: ${JSON.stringify(result)}`);
returnData.push({
json: { result },
});
} catch (error) {
throw new NodeOperationError(
this.getNode(),
`Failed to execute tool '${toolName}': ${(error as Error).message}`,
);
}
break;
}
case 'listPrompts': {
const prompts = await client.listPrompts();
returnData.push({
json: { prompts },
});
break;
}
case 'getPrompt': {
const promptName = this.getNodeParameter('promptName', 0) as string;
const prompt = await client.getPrompt({
name: promptName,
});
returnData.push({
json: { prompt },
});
break;
}
default:
throw new NodeOperationError(this.getNode(), `Operation ${operation} not supported`);
}
return [returnData];
} catch (error) {
throw new NodeOperationError(
this.getNode(),
`Failed to execute operation: ${(error as Error).message}`,
);
} finally {
if (transport) {
await transport.close();
}
}
}
}