first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled

This commit is contained in:
2026-03-17 16:22:57 +03:30
commit 3d5eaf9445
15349 changed files with 2847338 additions and 0 deletions
@@ -0,0 +1,462 @@
import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
import { StructuredToolkit } from 'n8n-core';
import {
type IDataObject,
type IExecuteFunctions,
type INodeExecutionData,
NodeConnectionTypes,
NodeOperationError,
type INodeType,
type INodeTypeDescription,
type ISupplyDataFunctions,
type SupplyData,
} from 'n8n-workflow';
import { logWrapper, getConnectionHintNoticeField } from '@n8n/ai-utilities';
import { getTools } from './loadOptions';
import type { McpToolIncludeMode } from './types';
import { createCallTool, getSelectedTools, mcpToolToDynamicTool } from './utils';
import { credentials, transportSelect } from '../shared/descriptions';
import type { McpAuthenticationOption, McpServerTransport } from '../shared/types';
import {
connectMcpClient,
getAllTools,
getAuthHeaders,
mapToNodeOperationError,
tryRefreshOAuth2Token,
} from '../shared/utils';
import type { JSONSchema7 } from 'json-schema';
import pick from 'lodash/pick';
/**
* Get node parameters for MCP client configuration
*/
function getNodeConfig(
ctx: ISupplyDataFunctions | IExecuteFunctions,
itemIndex: number,
): {
authentication: McpAuthenticationOption;
timeout: number;
serverTransport: McpServerTransport;
endpointUrl: string;
mode: McpToolIncludeMode;
includeTools: string[];
excludeTools: string[];
} {
const node = ctx.getNode();
const authentication = ctx.getNodeParameter(
'authentication',
itemIndex,
) as McpAuthenticationOption;
const timeout = ctx.getNodeParameter('options.timeout', itemIndex, 60000) as number;
let serverTransport: McpServerTransport;
let endpointUrl: string;
if (node.typeVersion === 1) {
serverTransport = 'sse';
endpointUrl = ctx.getNodeParameter('sseEndpoint', itemIndex) as string;
} else {
serverTransport = ctx.getNodeParameter('serverTransport', itemIndex) as McpServerTransport;
endpointUrl = ctx.getNodeParameter('endpointUrl', itemIndex) as string;
}
const mode = ctx.getNodeParameter('include', itemIndex) as McpToolIncludeMode;
const includeTools = ctx.getNodeParameter('includeTools', itemIndex, []) as string[];
const excludeTools = ctx.getNodeParameter('excludeTools', itemIndex, []) as string[];
return {
authentication,
timeout,
serverTransport,
endpointUrl,
mode,
includeTools,
excludeTools,
};
}
/**
* Connect to MCP server and get filtered tools
*/
async function connectAndGetTools(
ctx: ISupplyDataFunctions | IExecuteFunctions,
config: ReturnType<typeof getNodeConfig>,
) {
const node = ctx.getNode();
const { headers } = await getAuthHeaders(ctx, config.authentication);
const client = await connectMcpClient({
serverTransport: config.serverTransport,
endpointUrl: config.endpointUrl,
headers,
name: node.type,
version: node.typeVersion,
onUnauthorized: async (headers) =>
await tryRefreshOAuth2Token(ctx, config.authentication, headers),
});
if (!client.ok) {
return { client, mcpTools: null, error: client.error };
}
const allTools = await getAllTools(client.result);
const mcpTools = getSelectedTools({
tools: allTools,
mode: config.mode,
includeTools: config.includeTools,
excludeTools: config.excludeTools,
});
return { client: client.result, mcpTools, error: null };
}
export class McpClientTool implements INodeType {
description: INodeTypeDescription = {
displayName: 'MCP Client Tool',
name: 'mcpClientTool',
icon: {
light: 'file:../mcp.svg',
dark: 'file:../mcp.dark.svg',
},
group: ['output'],
version: [1, 1.1, 1.2],
description: 'Connect tools from an MCP Server',
defaults: {
name: 'MCP Client',
},
codex: {
categories: ['AI'],
subcategories: {
AI: ['Tools'],
Tools: ['Recommended Tools'],
},
alias: ['Model Context Protocol', 'MCP Client'],
resources: {
primaryDocumentation: [
{
url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolmcp/',
},
],
},
},
inputs: [],
outputs: [{ type: NodeConnectionTypes.AiTool, displayName: 'Tools' }],
credentials,
properties: [
getConnectionHintNoticeField([NodeConnectionTypes.AiAgent]),
{
displayName: 'SSE Endpoint',
name: 'sseEndpoint',
type: 'string',
description: 'SSE Endpoint of your MCP server',
placeholder: 'e.g. https://my-mcp-server.ai/sse',
default: '',
required: true,
displayOptions: {
show: {
'@version': [1],
},
},
},
{
displayName: 'Endpoint',
name: 'endpointUrl',
type: 'string',
description: 'Endpoint of your MCP server',
placeholder: 'e.g. https://my-mcp-server.ai/mcp',
default: '',
required: true,
displayOptions: {
show: {
'@version': [{ _cnd: { gte: 1.1 } }],
},
},
},
transportSelect({
defaultOption: 'sse',
displayOptions: {
show: {
'@version': [1.1],
},
},
}),
transportSelect({
defaultOption: 'httpStreamable',
displayOptions: {
show: {
'@version': [{ _cnd: { gte: 1.2 } }],
},
},
}),
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
name: 'Bearer Auth',
value: 'bearerAuth',
},
{
name: 'Header Auth',
value: 'headerAuth',
},
{
name: 'None',
value: 'none',
},
],
default: 'none',
description: 'The way to authenticate with your endpoint',
displayOptions: {
show: {
'@version': [{ _cnd: { lt: 1.2 } }],
},
},
},
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
name: 'Bearer Auth',
value: 'bearerAuth',
},
{
name: 'Header Auth',
value: 'headerAuth',
},
{
name: 'MCP OAuth2',
value: 'mcpOAuth2Api',
},
{
name: 'Multiple Headers Auth',
value: 'multipleHeadersAuth',
},
{
name: 'None',
value: 'none',
},
],
default: 'none',
description: 'The way to authenticate with your endpoint',
displayOptions: {
show: {
'@version': [{ _cnd: { gte: 1.2 } }],
},
},
},
{
displayName: 'Credentials',
name: 'credentials',
type: 'credentials',
default: '',
displayOptions: {
show: {
authentication: ['headerAuth', 'bearerAuth', 'mcpOAuth2Api', 'multipleHeadersAuth'],
},
},
},
{
displayName: 'Tools to Include',
name: 'include',
type: 'options',
description: 'How to select the tools you want to be exposed to the AI Agent',
default: 'all',
options: [
{
name: 'All',
value: 'all',
description: 'Also include all unchanged fields from the input',
},
{
name: 'Selected',
value: 'selected',
description: 'Also include the tools listed in the parameter "Tools to Include"',
},
{
name: 'All Except',
value: 'except',
description: 'Exclude the tools listed in the parameter "Tools to Exclude"',
},
],
},
{
displayName: 'Tools to Include',
name: 'includeTools',
type: 'multiOptions',
default: [],
description:
'Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
typeOptions: {
loadOptionsMethod: 'getTools',
loadOptionsDependsOn: ['sseEndpoint'],
},
displayOptions: {
show: {
include: ['selected'],
},
},
},
{
displayName: 'Tools to Exclude',
name: 'excludeTools',
type: 'multiOptions',
default: [],
description:
'Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code/expressions/">expression</a>',
typeOptions: {
loadOptionsMethod: 'getTools',
},
displayOptions: {
show: {
include: ['except'],
},
},
},
{
displayName: 'Options',
name: 'options',
placeholder: 'Add Option',
description: 'Additional options to add',
type: 'collection',
default: {},
options: [
{
displayName: 'Timeout',
name: 'timeout',
type: 'number',
typeOptions: {
minValue: 1,
},
default: 60000,
description: 'Time in ms to wait for tool calls to finish',
},
],
},
],
};
methods = {
loadOptions: {
getTools,
},
};
async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {
const node = this.getNode();
const config = getNodeConfig(this, itemIndex);
const setError = (error: NodeOperationError): SupplyData => {
this.addOutputData(NodeConnectionTypes.AiTool, itemIndex, error);
throw error;
};
const { client, mcpTools, error } = await connectAndGetTools(this, config);
if (error) {
this.logger.error('McpClientTool: Failed to connect to MCP Server', { error });
return setError(mapToNodeOperationError(node, error));
}
this.logger.debug('McpClientTool: Successfully connected to MCP Server');
if (!mcpTools?.length) {
return setError(
new NodeOperationError(node, 'MCP Server returned no tools', {
itemIndex,
description:
'Connected successfully to your MCP server but it returned an empty list of tools.',
}),
);
}
const tools = mcpTools.map((tool) =>
logWrapper(
mcpToolToDynamicTool(
tool,
createCallTool(tool.name, client, config.timeout, (errorMessage) => {
const error = new NodeOperationError(node, errorMessage, { itemIndex });
void this.addOutputData(NodeConnectionTypes.AiTool, itemIndex, error);
this.logger.error(`McpClientTool: Tool "${tool.name}" failed to execute`, { error });
}),
),
this,
),
);
this.logger.debug(`McpClientTool: Connected to MCP Server with ${tools.length} tools`);
const toolkit = new StructuredToolkit(tools);
return { response: toolkit, closeFunction: async () => await client.close() };
}
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const node = this.getNode();
const items = this.getInputData();
const returnData: INodeExecutionData[] = [];
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
const item = items[itemIndex];
const config = getNodeConfig(this, itemIndex);
const { client, mcpTools, error } = await connectAndGetTools(this, config);
if (error) {
throw new NodeOperationError(node, error.error, { itemIndex });
}
if (!mcpTools?.length) {
throw new NodeOperationError(node, 'MCP Server returned no tools', { itemIndex });
}
for (const tool of mcpTools) {
// Check for tool name in item.json.tool (for toolkit execution from agent)
// or item.tool (for direct execution)
if (!item.json.tool || typeof item.json.tool !== 'string') {
throw new NodeOperationError(node, 'Tool name not found in item.json.tool or item.tool', {
itemIndex,
});
}
const toolName = item.json.tool;
if (toolName === tool.name) {
// Extract the tool name from arguments before passing to MCP
const { tool: _, ...toolArguments } = item.json;
const schema: JSONSchema7 = tool.inputSchema;
// When additionalProperties is not explicitly true, filter to schema-defined properties.
// Otherwise, pass all arguments through
const sanitizedToolArguments: IDataObject =
schema.additionalProperties !== true
? pick(toolArguments, Object.keys(schema.properties ?? {}))
: toolArguments;
const params: {
name: string;
arguments: IDataObject;
} = {
name: tool.name,
arguments: sanitizedToolArguments,
};
const result = await client.callTool(params, CallToolResultSchema, {
timeout: config.timeout,
});
returnData.push({
json: {
response: result.content as IDataObject,
},
pairedItem: {
item: itemIndex,
},
});
}
}
}
return [returnData];
}
}
@@ -0,0 +1,856 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
import { McpError, ErrorCode, CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
import { mock, mockDeep } from 'jest-mock-extended';
import { StructuredToolkit } from 'n8n-core';
import {
type IExecuteFunctions,
NodeConnectionTypes,
NodeOperationError,
type ILoadOptionsFunctions,
type INode,
type ISupplyDataFunctions,
} from 'n8n-workflow';
import { getTools } from '../loadOptions';
import { McpClientTool } from '../McpClientTool.node';
jest.mock('@modelcontextprotocol/sdk/client/sse.js');
jest.mock('@modelcontextprotocol/sdk/client/index.js');
describe('McpClientTool', () => {
describe('loadOptions: getTools', () => {
it('should return a list of tools', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'MyTool',
description: 'MyTool does something',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
],
});
const result = await getTools.call(
mock<ILoadOptionsFunctions>({ getNode: jest.fn(() => mock<INode>({ typeVersion: 1 })) }),
);
expect(result).toEqual([
{
description: 'MyTool does something',
name: 'MyTool',
value: 'MyTool',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
]);
});
it('should handle errors', async () => {
jest.spyOn(Client.prototype, 'connect').mockRejectedValue(new Error('Fail!'));
const node = mock<INode>({ typeVersion: 1 });
await expect(
getTools.call(mock<ILoadOptionsFunctions>({ getNode: jest.fn(() => node) })),
).rejects.toEqual(new NodeOperationError(node, 'Could not connect to your MCP server'));
});
});
describe('supplyData', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('should return a valid toolkit with usable tools (that returns a string)', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest
.spyOn(Client.prototype, 'callTool')
.mockResolvedValue({ content: [{ type: 'text', text: 'result from tool' }] });
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'MyTool1',
description: 'MyTool1 does something',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
{
name: 'MyTool2',
description: 'MyTool2 does something',
inputSchema: { type: 'object', properties: { input2: { type: 'string' } } },
},
],
});
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() => mock<INode>({ typeVersion: 1 })),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
}),
0,
);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const tools = (supplyDataResult.response as StructuredToolkit).getTools();
expect(tools).toHaveLength(2);
const toolCallResult = await tools[0].invoke({ input: 'foo' });
expect(toolCallResult).toEqual(JSON.stringify([{ type: 'text', text: 'result from tool' }]));
});
it('should support selecting tools to expose', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'MyTool1',
description: 'MyTool1 does something',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
{
name: 'MyTool2',
description: 'MyTool2 does something',
inputSchema: { type: 'object', properties: { input2: { type: 'string' } } },
},
],
});
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() =>
mock<INode>({
typeVersion: 1,
}),
),
getNodeParameter: jest.fn((key, _index) => {
const parameters: Record<string, any> = {
include: 'selected',
includeTools: ['MyTool2'],
};
return parameters[key];
}),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
}),
0,
);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const tools = (supplyDataResult.response as StructuredToolkit).getTools();
expect(tools).toHaveLength(1);
expect(tools[0].name).toBe('MyTool2');
});
it('should support selecting tools to exclude', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'MyTool1',
description: 'MyTool1 does something',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
{
name: 'MyTool2',
description: 'MyTool2 does something',
inputSchema: { type: 'object', properties: { input2: { type: 'string' } } },
},
],
});
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() =>
mock<INode>({
typeVersion: 1,
}),
),
getNodeParameter: jest.fn((key, _index) => {
const parameters: Record<string, any> = {
include: 'except',
excludeTools: ['MyTool2'],
};
return parameters[key];
}),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
}),
0,
);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const tools = (supplyDataResult.response as StructuredToolkit).getTools();
expect(tools).toHaveLength(1);
expect(tools[0].name).toBe('MyTool1');
});
it('should support header auth', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'MyTool1',
description: 'MyTool1 does something',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
],
});
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() => mock<INode>({ typeVersion: 1 })),
getNodeParameter: jest.fn((key, _index) => {
const parameters: Record<string, any> = {
include: 'except',
excludeTools: ['MyTool2'],
authentication: 'headerAuth',
sseEndpoint: 'https://my-mcp-endpoint.ai/sse',
};
return parameters[key];
}),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
getCredentials: jest.fn().mockResolvedValue({ name: 'my-header', value: 'header-value' }),
}),
0,
);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue(mock());
const url = new URL('https://my-mcp-endpoint.ai/sse');
expect(SSEClientTransport).toHaveBeenCalledTimes(1);
expect(SSEClientTransport).toHaveBeenCalledWith(url, {
eventSourceInit: { fetch: expect.any(Function) },
fetch: expect.any(Function),
requestInit: { headers: { 'my-header': 'header-value' } },
});
const customFetch = jest.mocked(SSEClientTransport).mock.calls[0][1]?.eventSourceInit?.fetch;
await customFetch?.(url, {} as any);
expect(fetchSpy).toHaveBeenCalledWith(url, {
headers: { Accept: 'text/event-stream', 'my-header': 'header-value' },
});
});
it('should support bearer auth', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'MyTool1',
description: 'MyTool1 does something',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
],
});
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() => mock<INode>({ typeVersion: 1 })),
getNodeParameter: jest.fn((key, _index) => {
const parameters: Record<string, any> = {
include: 'except',
excludeTools: ['MyTool2'],
authentication: 'bearerAuth',
sseEndpoint: 'https://my-mcp-endpoint.ai/sse',
};
return parameters[key];
}),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
getCredentials: jest.fn().mockResolvedValue({ token: 'my-token' }),
}),
0,
);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue(mock());
const url = new URL('https://my-mcp-endpoint.ai/sse');
expect(SSEClientTransport).toHaveBeenCalledTimes(1);
expect(SSEClientTransport).toHaveBeenCalledWith(url, {
eventSourceInit: { fetch: expect.any(Function) },
fetch: expect.any(Function),
requestInit: { headers: { Authorization: 'Bearer my-token' } },
});
const customFetch = jest.mocked(SSEClientTransport).mock.calls[0][1]?.eventSourceInit?.fetch;
await customFetch?.(url, {} as any);
expect(fetchSpy).toHaveBeenCalledWith(url, {
headers: { Accept: 'text/event-stream', Authorization: 'Bearer my-token' },
});
});
it('should successfully execute a tool', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest
.spyOn(Client.prototype, 'callTool')
.mockResolvedValue({ toolResult: 'Sunny', content: [] });
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'Weather Tool',
description: 'Gets the current weather',
inputSchema: { type: 'object', properties: { location: { type: 'string' } } },
},
],
});
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() =>
mock<INode>({
typeVersion: 1,
}),
),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
}),
0,
);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const tools = (supplyDataResult.response as StructuredToolkit).getTools();
const toolResult = await tools[0].invoke({ location: 'Berlin' });
expect(toolResult).toEqual('Sunny');
});
it('should handle tool errors', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
isError: true,
toolResult: 'Weather unknown at location',
content: [{ text: 'Weather unknown at location' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'Weather Tool',
description: 'Gets the current weather',
inputSchema: { type: 'object', properties: { location: { type: 'string' } } },
},
],
});
const supplyDataFunctions = mock<ISupplyDataFunctions>({
getNode: jest.fn(() =>
mock<INode>({
typeVersion: 1,
}),
),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
});
const supplyDataResult = await new McpClientTool().supplyData.call(supplyDataFunctions, 0);
expect(supplyDataResult.closeFunction).toBeInstanceOf(Function);
expect(supplyDataResult.response).toBeInstanceOf(StructuredToolkit);
const tools = (supplyDataResult.response as StructuredToolkit).getTools();
const toolResult = await tools[0].invoke({ location: 'Berlin' });
expect(toolResult).toEqual('Weather unknown at location');
expect(supplyDataFunctions.addOutputData).toHaveBeenCalledWith(
NodeConnectionTypes.AiTool,
0,
new NodeOperationError(supplyDataFunctions.getNode(), 'Weather unknown at location'),
);
});
it('should support setting a timeout', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
const callToolSpy = jest
.spyOn(Client.prototype, 'callTool')
.mockRejectedValue(
new McpError(ErrorCode.RequestTimeout, 'Request timed out', { timeout: 200 }),
);
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'SlowTool',
description: 'SlowTool throws a timeout',
inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
},
],
});
const mockNode = mock<INode>({ typeVersion: 1 });
const supplyDataResult = await new McpClientTool().supplyData.call(
mock<ISupplyDataFunctions>({
getNode: jest.fn(() => mockNode),
getNodeParameter: jest.fn((key, _index) => {
const parameters: Record<string, any> = {
'options.timeout': 200,
};
return parameters[key];
}),
logger: { debug: jest.fn(), error: jest.fn() },
addInputData: jest.fn(() => ({ index: 0 })),
}),
0,
);
const tools = (supplyDataResult.response as StructuredToolkit).getTools();
await expect(tools[0].invoke({ input: 'foo' })).resolves.toEqual(
'MCP error -32001: Request timed out',
);
expect(callToolSpy).toHaveBeenCalledWith(
expect.any(Object), // params
expect.any(Object), // schema
expect.objectContaining({ timeout: 200 }),
); // options
});
});
describe('execute', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('should execute tool when tool name is in item.json.tool (from agent)', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
content: [{ type: 'text', text: 'Weather is sunny' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'get_weather',
description: 'Gets the weather',
inputSchema: {
type: 'object',
properties: { location: { type: 'string' } },
},
},
],
});
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'get_weather',
location: 'Berlin',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'all',
includeTools: [],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
const result = await new McpClientTool().execute.call(mockExecuteFunctions);
expect(result).toEqual([
[
{
json: {
response: [{ type: 'text', text: 'Weather is sunny' }],
},
pairedItem: { item: 0 },
},
],
]);
expect(Client.prototype.callTool).toHaveBeenCalledWith(
{
name: 'get_weather',
arguments: { location: 'Berlin' },
},
expect.anything(),
expect.anything(),
);
});
it.each([false, undefined])(
'should filter out tool arguments when additionalProperties is %s',
async (additionalProperties) => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
content: [{ type: 'text', text: 'Weather is sunny' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'get_weather',
description: 'Gets the weather',
inputSchema: {
type: 'object',
properties: { location: { type: 'string' } },
additionalProperties,
},
},
],
});
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'get_weather',
location: 'Berlin',
foo: 'bar',
sessionId: '123',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'all',
includeTools: [],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
const result = await new McpClientTool().execute.call(mockExecuteFunctions);
expect(result).toEqual([
[
{
json: {
response: [{ type: 'text', text: 'Weather is sunny' }],
},
pairedItem: { item: 0 },
},
],
]);
expect(Client.prototype.callTool).toHaveBeenCalledWith(
{
name: 'get_weather',
arguments: { location: 'Berlin' },
},
expect.anything(),
expect.anything(),
);
},
);
it('should pass all arguments when schema has additionalProperties: true', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
content: [{ type: 'text', text: 'Success' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'flexible_tool',
description: 'Accepts any arguments',
inputSchema: { type: 'object', additionalProperties: true },
},
],
});
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'flexible_tool',
foo: 'bar',
extra: 'data',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'all',
includeTools: [],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
await new McpClientTool().execute.call(mockExecuteFunctions);
expect(Client.prototype.callTool).toHaveBeenCalledWith(
{
name: 'flexible_tool',
arguments: { foo: 'bar', extra: 'data' },
},
expect.anything(),
expect.anything(),
);
});
it('should not execute if tool name does not match', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
content: [{ type: 'text', text: 'Should not be called' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'get_weather',
description: 'Gets the weather',
inputSchema: { type: 'object', properties: { location: { type: 'string' } } },
},
],
});
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'different_tool',
location: 'Berlin',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'all',
includeTools: [],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
const result = await new McpClientTool().execute.call(mockExecuteFunctions);
expect(result).toEqual([[]]);
expect(Client.prototype.callTool).not.toHaveBeenCalled();
});
it('should throw error when MCP server connection fails', async () => {
jest.spyOn(Client.prototype, 'connect').mockRejectedValue(new Error('Connection failed'));
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'get_weather',
location: 'Berlin',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'all',
includeTools: [],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
await expect(new McpClientTool().execute.call(mockExecuteFunctions)).rejects.toThrow(
NodeOperationError,
);
});
it('should handle multiple items', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest
.spyOn(Client.prototype, 'callTool')
.mockResolvedValueOnce({
content: [{ type: 'text', text: 'Weather in Berlin is sunny' }],
})
.mockResolvedValueOnce({
content: [{ type: 'text', text: 'Weather in London is rainy' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'get_weather',
description: 'Gets the weather',
inputSchema: { type: 'object', properties: { location: { type: 'string' } } },
},
],
});
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'get_weather',
location: 'Berlin',
},
},
{
json: {
tool: 'get_weather',
location: 'London',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'all',
includeTools: [],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
const result = await new McpClientTool().execute.call(mockExecuteFunctions);
expect(result).toEqual([
[
{
json: {
response: [{ type: 'text', text: 'Weather in Berlin is sunny' }],
},
pairedItem: { item: 0 },
},
{
json: {
response: [{ type: 'text', text: 'Weather in London is rainy' }],
},
pairedItem: { item: 1 },
},
],
]);
expect(Client.prototype.callTool).toHaveBeenCalledTimes(2);
});
it('should respect tool filtering (selected tools)', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
content: [{ type: 'text', text: 'Weather is sunny' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'get_weather',
description: 'Gets the weather',
inputSchema: { type: 'object', properties: { location: { type: 'string' } } },
},
{
name: 'get_time',
description: 'Gets the time',
inputSchema: { type: 'object', properties: {} },
},
],
});
const mockNode = mock<INode>({ typeVersion: 1, type: 'mcpClientTool' });
const mockExecuteFunctions = mock<any>({
getNode: jest.fn(() => mockNode),
getInputData: jest.fn(() => [
{
json: {
tool: 'get_weather',
location: 'Berlin',
},
},
]),
getNodeParameter: jest.fn((key) => {
const params: Record<string, any> = {
include: 'selected',
includeTools: ['get_weather'],
excludeTools: [],
authentication: 'none',
sseEndpoint: 'https://test.com/sse',
'options.timeout': 60000,
};
return params[key];
}),
});
const result = await new McpClientTool().execute.call(mockExecuteFunctions);
expect(result[0]).toHaveLength(1);
expect(result[0][0].json.response).toEqual([{ type: 'text', text: 'Weather is sunny' }]);
});
it('should execute tool with timeout', async () => {
jest.spyOn(Client.prototype, 'connect').mockResolvedValue();
jest.spyOn(Client.prototype, 'callTool').mockResolvedValue({
content: [{ type: 'text', text: 'Weather is sunny' }],
});
jest.spyOn(Client.prototype, 'listTools').mockResolvedValue({
tools: [
{
name: 'get_weather',
description: 'Gets the weather',
inputSchema: { type: 'object', properties: { location: { type: 'string' } } },
},
],
});
const mockNode = mock<INode>({ typeVersion: 1.2, type: 'mcpClientTool' });
const mockExecuteFunctions = mockDeep<IExecuteFunctions>();
mockExecuteFunctions.getNode.mockReturnValue(mockNode);
mockExecuteFunctions.getInputData.mockReturnValue([
{
json: {
tool: 'get_weather',
location: 'Berlin',
},
},
]);
mockExecuteFunctions.getNodeParameter.mockImplementation((key, _idx, defaultValue) => {
const params = {
include: 'all',
authentication: 'none',
serverTransport: 'httpStreamable',
endpointUrl: 'https://test.com/mcp',
'options.timeout': 12345,
};
return params[key as keyof typeof params] ?? defaultValue;
});
await new McpClientTool().execute.call(mockExecuteFunctions);
expect(Client.prototype.callTool).toHaveBeenCalledWith(
{
name: 'get_weather',
arguments: { location: 'Berlin' },
},
CallToolResultSchema,
{ timeout: 12345 },
);
});
});
});
@@ -0,0 +1,45 @@
import { type ILoadOptionsFunctions, type INodePropertyOptions } from 'n8n-workflow';
import type { McpAuthenticationOption, McpServerTransport } from '../shared/types';
import {
connectMcpClient,
getAllTools,
getAuthHeaders,
mapToNodeOperationError,
tryRefreshOAuth2Token,
} from '../shared/utils';
export async function getTools(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const authentication = this.getNodeParameter('authentication') as McpAuthenticationOption;
const node = this.getNode();
let serverTransport: McpServerTransport;
let endpointUrl: string;
if (node.typeVersion === 1) {
serverTransport = 'sse';
endpointUrl = this.getNodeParameter('sseEndpoint') as string;
} else {
serverTransport = this.getNodeParameter('serverTransport') as McpServerTransport;
endpointUrl = this.getNodeParameter('endpointUrl') as string;
}
const { headers } = await getAuthHeaders(this, authentication);
const client = await connectMcpClient({
serverTransport,
endpointUrl,
headers,
name: node.type,
version: node.typeVersion,
onUnauthorized: async (headers) => await tryRefreshOAuth2Token(this, authentication, headers),
});
if (!client.ok) {
throw mapToNodeOperationError(node, client.error);
}
const tools = await getAllTools(client.result);
return tools.map((tool) => ({
name: tool.name,
value: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
}));
}
@@ -0,0 +1 @@
export type McpToolIncludeMode = 'all' | 'selected' | 'except';
@@ -0,0 +1,109 @@
import { DynamicStructuredTool, type DynamicStructuredToolInput } from '@langchain/core/tools';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { CompatibilityCallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
import { type IDataObject } from 'n8n-workflow';
import { z } from 'zod';
import { convertJsonSchemaToZod } from '@utils/schemaParsing';
import type { McpToolIncludeMode } from './types';
import type { McpTool } from '../shared/types';
export function getSelectedTools({
mode,
includeTools,
excludeTools,
tools,
}: {
mode: McpToolIncludeMode;
includeTools?: string[];
excludeTools?: string[];
tools: McpTool[];
}) {
switch (mode) {
case 'selected': {
if (!includeTools?.length) return tools;
const include = new Set(includeTools);
return tools.filter((tool) => include.has(tool.name));
}
case 'except': {
const except = new Set(excludeTools ?? []);
return tools.filter((tool) => !except.has(tool.name));
}
case 'all':
default:
return tools;
}
}
export const getErrorDescriptionFromToolCall = (result: unknown): string | undefined => {
if (result && typeof result === 'object') {
if ('content' in result && Array.isArray(result.content)) {
const errorMessage = (result.content as Array<{ type: 'text'; text: string }>).find(
(content) => content && typeof content === 'object' && typeof content.text === 'string',
)?.text;
return errorMessage;
} else if ('toolResult' in result && typeof result.toolResult === 'string') {
return result.toolResult;
}
if ('message' in result && typeof result.message === 'string') {
return result.message;
}
}
return undefined;
};
export const createCallTool =
(name: string, client: Client, timeout: number, onError: (error: string) => void) =>
async (args: IDataObject) => {
let result: Awaited<ReturnType<Client['callTool']>>;
function handleError(error: unknown) {
const errorDescription =
getErrorDescriptionFromToolCall(error) ?? `Failed to execute tool "${name}"`;
onError(errorDescription);
return errorDescription;
}
try {
result = await client.callTool({ name, arguments: args }, CompatibilityCallToolResultSchema, {
timeout,
});
} catch (error) {
return handleError(error);
}
if (result.isError) {
return handleError(result);
}
if (result.toolResult !== undefined) {
return result.toolResult;
}
if (result.content !== undefined) {
return result.content;
}
return result;
};
export function mcpToolToDynamicTool(
tool: McpTool,
onCallTool: DynamicStructuredToolInput['func'],
): DynamicStructuredTool {
const rawSchema = convertJsonSchemaToZod(tool.inputSchema);
// Ensure we always have an object schema for structured tools
const objectSchema =
rawSchema instanceof z.ZodObject ? rawSchema : z.object({ value: rawSchema });
return new DynamicStructuredTool({
name: tool.name,
description: tool.description ?? '',
schema: objectSchema,
func: onCallTool,
metadata: { isFromToolkit: true },
});
}