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
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:
@@ -0,0 +1,327 @@
|
||||
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
|
||||
import type {
|
||||
IBinaryKeyData,
|
||||
IDataObject,
|
||||
IExecuteFunctions,
|
||||
INodeExecutionData,
|
||||
INodeType,
|
||||
INodeTypeDescription,
|
||||
NodeExecutionWithMetadata,
|
||||
} from 'n8n-workflow';
|
||||
import { jsonParse, NodeConnectionTypes, NodeOperationError } from 'n8n-workflow';
|
||||
import { ZodError } from 'zod';
|
||||
import { prettifyError } from 'zod/v4/core';
|
||||
|
||||
import * as listSearch from './listSearch';
|
||||
import * as resourceMapping from './resourceMapping';
|
||||
import { credentials, transportSelect } from '../shared/descriptions';
|
||||
import type { McpAuthenticationOption, McpServerTransport } from '../shared/types';
|
||||
import {
|
||||
getAuthHeaders,
|
||||
tryRefreshOAuth2Token,
|
||||
connectMcpClient,
|
||||
mapToNodeOperationError,
|
||||
} from '../shared/utils';
|
||||
|
||||
export class McpClient implements INodeType {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'MCP Client',
|
||||
description: 'Standalone MCP Client',
|
||||
name: 'mcpClient',
|
||||
icon: {
|
||||
light: 'file:../mcp.svg',
|
||||
dark: 'file:../mcp.dark.svg',
|
||||
},
|
||||
group: ['transform'],
|
||||
version: 1,
|
||||
defaults: {
|
||||
name: 'MCP Client',
|
||||
},
|
||||
credentials,
|
||||
inputs: [NodeConnectionTypes.Main],
|
||||
outputs: [NodeConnectionTypes.Main],
|
||||
properties: [
|
||||
transportSelect({
|
||||
defaultOption: 'httpStreamable',
|
||||
}),
|
||||
{
|
||||
displayName: 'MCP Endpoint URL',
|
||||
name: 'endpointUrl',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'e.g. https://my-mcp-server.ai/mcp',
|
||||
required: true,
|
||||
description: 'The URL of the MCP server to connect to',
|
||||
},
|
||||
{
|
||||
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',
|
||||
},
|
||||
{
|
||||
displayName: 'Credentials',
|
||||
name: 'credentials',
|
||||
type: 'credentials',
|
||||
default: '',
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: ['headerAuth', 'bearerAuth', 'mcpOAuth2Api', 'multipleHeadersAuth'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Tool',
|
||||
name: 'tool',
|
||||
type: 'resourceLocator',
|
||||
default: { mode: 'list', value: '' },
|
||||
required: true,
|
||||
description: 'The tool to use',
|
||||
modes: [
|
||||
{
|
||||
displayName: 'From List',
|
||||
name: 'list',
|
||||
type: 'list',
|
||||
typeOptions: {
|
||||
searchListMethod: 'getTools',
|
||||
searchable: true,
|
||||
skipCredentialsCheckInRLC: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'ID',
|
||||
name: 'id',
|
||||
type: 'string',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
displayName: 'Input Mode',
|
||||
name: 'inputMode',
|
||||
type: 'options',
|
||||
default: 'manual',
|
||||
noDataExpression: true,
|
||||
options: [
|
||||
{
|
||||
name: 'Manual',
|
||||
value: 'manual',
|
||||
description: 'Manually specify the input data for each tool parameter',
|
||||
},
|
||||
{
|
||||
name: 'JSON',
|
||||
value: 'json',
|
||||
description: 'Specify the input data as a JSON object',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
displayName: 'Parameters',
|
||||
name: 'parameters',
|
||||
type: 'resourceMapper',
|
||||
default: {
|
||||
mappingMode: 'defineBelow',
|
||||
value: null,
|
||||
},
|
||||
noDataExpression: true,
|
||||
required: true,
|
||||
typeOptions: {
|
||||
loadOptionsDependsOn: ['tool.value'],
|
||||
resourceMapper: {
|
||||
resourceMapperMethod: 'getToolParameters',
|
||||
hideNoDataError: true,
|
||||
addAllFields: false,
|
||||
supportAutoMap: false,
|
||||
mode: 'add',
|
||||
fieldWords: {
|
||||
singular: 'parameter',
|
||||
plural: 'parameters',
|
||||
},
|
||||
},
|
||||
},
|
||||
displayOptions: {
|
||||
show: {
|
||||
inputMode: ['manual'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'JSON',
|
||||
name: 'jsonInput',
|
||||
type: 'json',
|
||||
typeOptions: {
|
||||
rows: 5,
|
||||
},
|
||||
default: '{\n "my_field_1": "value",\n "my_field_2": 1\n}\n',
|
||||
validateType: 'object',
|
||||
displayOptions: {
|
||||
show: {
|
||||
inputMode: ['json'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
placeholder: 'Add Option',
|
||||
description: 'Additional options to add',
|
||||
type: 'collection',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Convert to Binary',
|
||||
name: 'convertToBinary',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
description:
|
||||
'Whether to convert images and audio to binary data. If false, images and audio will be returned as base64 encoded strings.',
|
||||
},
|
||||
{
|
||||
displayName: 'Timeout',
|
||||
name: 'timeout',
|
||||
type: 'number',
|
||||
typeOptions: {
|
||||
minValue: 1,
|
||||
},
|
||||
default: 60000,
|
||||
description: 'Time in ms to wait for tool calls to finish',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
methods = {
|
||||
listSearch,
|
||||
resourceMapping,
|
||||
};
|
||||
|
||||
async execute(
|
||||
this: IExecuteFunctions,
|
||||
): Promise<INodeExecutionData[][] | NodeExecutionWithMetadata[][] | null> {
|
||||
const authentication = this.getNodeParameter('authentication', 0) as McpAuthenticationOption;
|
||||
const serverTransport = this.getNodeParameter('serverTransport', 0) as McpServerTransport;
|
||||
const endpointUrl = this.getNodeParameter('endpointUrl', 0) as string;
|
||||
const node = this.getNode();
|
||||
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 inputMode = this.getNodeParameter('inputMode', 0, 'manual') as 'manual' | 'json';
|
||||
const items = this.getInputData();
|
||||
const returnData: INodeExecutionData[] = [];
|
||||
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
|
||||
try {
|
||||
const tool = this.getNodeParameter('tool.value', itemIndex) as string;
|
||||
const options = this.getNodeParameter('options', itemIndex);
|
||||
let parameters: IDataObject = {};
|
||||
if (inputMode === 'manual') {
|
||||
parameters = this.getNodeParameter('parameters.value', itemIndex) as IDataObject;
|
||||
} else {
|
||||
parameters = this.getNodeParameter('jsonInput', itemIndex) as IDataObject;
|
||||
}
|
||||
|
||||
const result = (await client.result.callTool(
|
||||
{
|
||||
name: tool,
|
||||
arguments: parameters,
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
timeout: options.timeout ? Number(options.timeout) : undefined,
|
||||
},
|
||||
)) as CallToolResult;
|
||||
|
||||
let binaryIndex = 0;
|
||||
const binary: IBinaryKeyData = {};
|
||||
const content: IDataObject[] = [];
|
||||
const convertToBinary = options.convertToBinary ?? true;
|
||||
for (const contentItem of result.content) {
|
||||
if (contentItem.type === 'text') {
|
||||
content.push({
|
||||
...contentItem,
|
||||
text: jsonParse(contentItem.text, { fallbackValue: contentItem.text }),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (convertToBinary && (contentItem.type === 'image' || contentItem.type === 'audio')) {
|
||||
binary[`data_${binaryIndex}`] = await this.helpers.prepareBinaryData(
|
||||
Buffer.from(contentItem.data, 'base64'),
|
||||
undefined,
|
||||
contentItem.mimeType,
|
||||
);
|
||||
binaryIndex++;
|
||||
continue;
|
||||
}
|
||||
|
||||
content.push(contentItem as IDataObject);
|
||||
}
|
||||
|
||||
returnData.push({
|
||||
json: {
|
||||
content: content.length > 0 ? content : undefined,
|
||||
},
|
||||
binary: Object.keys(binary).length > 0 ? binary : undefined,
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
const errorMessage =
|
||||
e instanceof ZodError ? prettifyError(e) : e instanceof Error ? e.message : String(e);
|
||||
if (this.continueOnFail()) {
|
||||
returnData.push({
|
||||
json: {
|
||||
error: {
|
||||
message: errorMessage,
|
||||
issues: e instanceof ZodError ? e.issues : undefined,
|
||||
},
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new NodeOperationError(node, errorMessage, {
|
||||
itemIndex,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [returnData];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
||||
import { mockDeep } from 'jest-mock-extended';
|
||||
import type { IExecuteFunctions } from 'n8n-workflow';
|
||||
|
||||
import * as sharedUtils from '../../shared/utils';
|
||||
import { McpClient } from '../McpClient.node';
|
||||
|
||||
describe('McpClient', () => {
|
||||
const getAuthHeaders = jest.spyOn(sharedUtils, 'getAuthHeaders');
|
||||
const connectMcpClient = jest.spyOn(sharedUtils, 'connectMcpClient');
|
||||
const executeFunctions = mockDeep<IExecuteFunctions>();
|
||||
const client = mockDeep<Client>();
|
||||
const defaultParams = {
|
||||
authentication: 'none',
|
||||
serverTransport: 'httpStreamable',
|
||||
endpointUrl: 'https://test.com/mcp',
|
||||
inputMode: 'json',
|
||||
jsonInput: { location: 'Berlin' },
|
||||
'tool.value': 'get_weather',
|
||||
options: { timeout: 10000, convertToBinary: false },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
|
||||
executeFunctions.getNode.mockReturnValue({
|
||||
id: '123',
|
||||
name: 'MCP Client',
|
||||
type: '@n8n/n8n-nodes-langchain.mcpClient',
|
||||
typeVersion: 1,
|
||||
position: [0, 0],
|
||||
parameters: {},
|
||||
});
|
||||
executeFunctions.getInputData.mockReturnValue([{ json: {} }]);
|
||||
getAuthHeaders.mockResolvedValue({ headers: {} });
|
||||
connectMcpClient.mockResolvedValue({
|
||||
ok: true,
|
||||
result: client,
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle json input mode', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation(
|
||||
(key, _idx, defaultValue) => defaultParams[key as keyof typeof defaultParams] ?? defaultValue,
|
||||
);
|
||||
client.callTool.mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Weather in Berlin is sunny' }],
|
||||
});
|
||||
|
||||
const result = await new McpClient().execute.call(executeFunctions);
|
||||
|
||||
expect(result).toEqual([
|
||||
[
|
||||
{
|
||||
json: { content: [{ type: 'text', text: 'Weather in Berlin is sunny' }] },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
expect(client.callTool).toHaveBeenCalledWith(
|
||||
{ name: 'get_weather', arguments: { location: 'Berlin' } },
|
||||
undefined,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle manual input mode', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation((key, _idx, defaultValue) => {
|
||||
const params = {
|
||||
...defaultParams,
|
||||
jsonInput: undefined,
|
||||
inputMode: 'manual',
|
||||
'parameters.value': { location: 'Berlin' },
|
||||
};
|
||||
return params[key as keyof typeof params] ?? defaultValue;
|
||||
});
|
||||
client.callTool.mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Weather in Berlin is sunny' }],
|
||||
});
|
||||
|
||||
const result = await new McpClient().execute.call(executeFunctions);
|
||||
|
||||
expect(result).toEqual([
|
||||
[
|
||||
{
|
||||
json: { content: [{ type: 'text', text: 'Weather in Berlin is sunny' }] },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
expect(client.callTool).toHaveBeenCalledWith(
|
||||
{ name: 'get_weather', arguments: { location: 'Berlin' } },
|
||||
undefined,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
});
|
||||
|
||||
it('should try to parse text content as json', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation(
|
||||
(key, _idx, defaultValue) => defaultParams[key as keyof typeof defaultParams] ?? defaultValue,
|
||||
);
|
||||
client.callTool.mockResolvedValue({
|
||||
content: [{ type: 'text', text: '{"answer": "Weather in Berlin is sunny"}' }],
|
||||
});
|
||||
|
||||
const result = await new McpClient().execute.call(executeFunctions);
|
||||
|
||||
expect(result).toEqual([
|
||||
[
|
||||
{
|
||||
json: { content: [{ type: 'text', text: { answer: 'Weather in Berlin is sunny' } }] },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should convert images and audio to binary data when convertToBinary is true', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation(
|
||||
(key, _idx, defaultValue) =>
|
||||
({
|
||||
...defaultParams,
|
||||
jsonInput: { foo: 'bar' },
|
||||
options: { ...defaultParams.options, convertToBinary: true },
|
||||
})[key as keyof typeof defaultParams] ?? defaultValue,
|
||||
);
|
||||
client.callTool.mockResolvedValue({
|
||||
content: [
|
||||
{ type: 'image', data: 'abcdef', mimeType: 'image/jpeg' },
|
||||
{ type: 'audio', data: 'ghijkl', mimeType: 'audio/mpeg' },
|
||||
],
|
||||
});
|
||||
executeFunctions.helpers.prepareBinaryData.mockResolvedValueOnce({
|
||||
data: 'abcdef',
|
||||
mimeType: 'image/jpeg',
|
||||
});
|
||||
executeFunctions.helpers.prepareBinaryData.mockResolvedValueOnce({
|
||||
data: 'ghijkl',
|
||||
mimeType: 'audio/mpeg',
|
||||
});
|
||||
|
||||
const result = await new McpClient().execute.call(executeFunctions);
|
||||
|
||||
expect(result).toEqual([
|
||||
[
|
||||
{
|
||||
json: {},
|
||||
binary: {
|
||||
data_0: {
|
||||
mimeType: 'image/jpeg',
|
||||
data: 'abcdef',
|
||||
},
|
||||
data_1: {
|
||||
mimeType: 'audio/mpeg',
|
||||
data: 'ghijkl',
|
||||
},
|
||||
},
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should keep images and audio as json when convertToBinary is false', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation(
|
||||
(key, _idx, defaultValue) =>
|
||||
({
|
||||
...defaultParams,
|
||||
jsonInput: { foo: 'bar' },
|
||||
options: { ...defaultParams.options, convertToBinary: false },
|
||||
})[key as keyof typeof defaultParams] ?? defaultValue,
|
||||
);
|
||||
client.callTool.mockResolvedValue({
|
||||
content: [
|
||||
{ type: 'image', data: 'abcdef', mimeType: 'image/jpeg' },
|
||||
{ type: 'audio', data: 'ghijkl', mimeType: 'audio/mpeg' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await new McpClient().execute.call(executeFunctions);
|
||||
|
||||
expect(result).toEqual([
|
||||
[
|
||||
{
|
||||
json: {
|
||||
content: [
|
||||
{ type: 'image', data: 'abcdef', mimeType: 'image/jpeg' },
|
||||
{ type: 'audio', data: 'ghijkl', mimeType: 'audio/mpeg' },
|
||||
],
|
||||
},
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should throw an error if the tool call fails', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation(
|
||||
(key, _idx, defaultValue) => defaultParams[key as keyof typeof defaultParams] ?? defaultValue,
|
||||
);
|
||||
client.callTool.mockRejectedValue(new Error('Tool call failed'));
|
||||
|
||||
await expect(new McpClient().execute.call(executeFunctions)).rejects.toThrow(
|
||||
'Tool call failed',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return an error as json if the tool call fails and continueOnFail is true', async () => {
|
||||
executeFunctions.getNodeParameter.mockImplementation(
|
||||
(key, _idx, defaultValue) => defaultParams[key as keyof typeof defaultParams] ?? defaultValue,
|
||||
);
|
||||
client.callTool.mockRejectedValue(new Error('Tool call failed'));
|
||||
executeFunctions.continueOnFail.mockReturnValue(true);
|
||||
|
||||
const result = await new McpClient().execute.call(executeFunctions);
|
||||
|
||||
expect(result).toEqual([
|
||||
[{ json: { error: { message: 'Tool call failed' } }, pairedItem: { item: 0 } }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
import type { JSONSchema7Definition, JSONSchema7 } from 'json-schema';
|
||||
|
||||
import {
|
||||
convertJsonSchemaToResourceMapperFields,
|
||||
jsonSchemaTypeToDefaultValue,
|
||||
jsonSchemaTypeToFieldType,
|
||||
} from '../utils';
|
||||
|
||||
describe('utils', () => {
|
||||
describe('jsonSchemaTypeToFieldType', () => {
|
||||
it.each([
|
||||
[{ schema: { type: 'string', format: 'date-time' } as JSONSchema7, expected: 'dateTime' }],
|
||||
[{ schema: { type: 'string' } as JSONSchema7, expected: 'string' }],
|
||||
[{ schema: { type: 'number' } as JSONSchema7, expected: 'number' }],
|
||||
[{ schema: { type: 'integer' } as JSONSchema7, expected: 'number' }],
|
||||
[{ schema: { type: 'boolean' } as JSONSchema7, expected: 'boolean' }],
|
||||
[{ schema: { type: 'array' } as JSONSchema7, expected: 'array' }],
|
||||
[{ schema: { type: 'object' } as JSONSchema7, expected: 'object' }],
|
||||
])('should return the correct field type for the schema', ({ schema, expected }) => {
|
||||
expect(jsonSchemaTypeToFieldType(schema)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsonSchemaTypeToDefaultValue', () => {
|
||||
it.each([
|
||||
[{ schema: false as JSONSchema7Definition, expected: null }],
|
||||
[{ schema: true as JSONSchema7Definition, expected: 'any' }],
|
||||
[{ schema: { type: 'string' } as JSONSchema7Definition, expected: 'string' }],
|
||||
[{ schema: { type: 'number' } as JSONSchema7Definition, expected: 0 }],
|
||||
[{ schema: { type: 'integer' } as JSONSchema7Definition, expected: 0 }],
|
||||
[{ schema: { type: 'number', minimum: -1 } as JSONSchema7Definition, expected: -1 }],
|
||||
[{ schema: { type: 'number', maximum: 1 } as JSONSchema7Definition, expected: 1 }],
|
||||
[{ schema: { type: 'boolean' } as JSONSchema7Definition, expected: false }],
|
||||
[
|
||||
{
|
||||
schema: { type: 'string', format: 'date-time' } as JSONSchema7Definition,
|
||||
expected: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: { type: 'string', format: 'uri' } as JSONSchema7Definition,
|
||||
expected: 'https://example.com',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: { type: 'string', format: 'url' } as JSONSchema7Definition,
|
||||
expected: 'https://example.com',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: { type: 'string', format: 'date' } as JSONSchema7Definition,
|
||||
expected: '2025-01-01',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: { type: 'string', format: 'time' } as JSONSchema7Definition,
|
||||
expected: '00:00:00',
|
||||
},
|
||||
],
|
||||
[{ schema: { type: 'array' } as JSONSchema7Definition, expected: [] }],
|
||||
[
|
||||
{
|
||||
schema: { type: 'array', items: { type: 'string' } } as JSONSchema7Definition,
|
||||
expected: ['string'],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'array',
|
||||
items: [{ type: 'number' }, { type: 'string' }],
|
||||
} as JSONSchema7Definition,
|
||||
expected: [0, 'string'],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
age: { type: 'number' },
|
||||
},
|
||||
required: ['name', 'age'],
|
||||
additionalProperties: false,
|
||||
} as JSONSchema7Definition,
|
||||
expected: { name: 'string', age: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
age: { type: 'number' },
|
||||
},
|
||||
required: ['name', 'age'],
|
||||
additionalProperties: { type: 'string' },
|
||||
} as JSONSchema7Definition,
|
||||
expected: { name: 'string', age: 0, '<additionalProperty>': 'string' },
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'string',
|
||||
enum: ['foo', 'bar'],
|
||||
} as JSONSchema7Definition,
|
||||
expected: 'foo',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
oneOf: [{ type: 'string' }, { type: 'number' }],
|
||||
} as JSONSchema7Definition,
|
||||
expected: 'string',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
anyOf: [{ type: 'string' }, { type: 'number' }],
|
||||
} as JSONSchema7Definition,
|
||||
expected: 'string',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
allOf: [
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
age: { type: 'number' },
|
||||
},
|
||||
required: ['age'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
},
|
||||
required: ['name'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
} as JSONSchema7Definition,
|
||||
expected: { age: 0, name: 'string' },
|
||||
},
|
||||
],
|
||||
])('should return the correct default value for the schema', ({ schema, expected }) => {
|
||||
expect(jsonSchemaTypeToDefaultValue(schema)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertJsonSchemaToResourceMapperFields', () => {
|
||||
it.each([
|
||||
[
|
||||
{
|
||||
schema: { type: 'string' } as JSONSchema7,
|
||||
expected: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: { type: 'object' } as JSONSchema7,
|
||||
expected: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string' }, age: { type: 'number' } },
|
||||
required: ['name'],
|
||||
} as JSONSchema7,
|
||||
expected: [
|
||||
{
|
||||
id: 'name',
|
||||
displayName: 'name',
|
||||
defaultMatch: false,
|
||||
required: true,
|
||||
display: true,
|
||||
type: 'string',
|
||||
},
|
||||
{
|
||||
id: 'age',
|
||||
displayName: 'age',
|
||||
defaultMatch: false,
|
||||
required: false,
|
||||
display: true,
|
||||
type: 'number',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: { type: 'object', properties: { name: true, age: false } } as JSONSchema7,
|
||||
expected: [
|
||||
{
|
||||
id: 'name',
|
||||
displayName: 'name',
|
||||
defaultMatch: false,
|
||||
required: false,
|
||||
display: true,
|
||||
type: 'string',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
])(
|
||||
'should return the correct resource mapper fields for the schema',
|
||||
({ schema, expected }) => {
|
||||
expect(convertJsonSchemaToResourceMapperFields(schema)).toEqual(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: { names: { type: 'array', items: { type: 'string' } } },
|
||||
required: ['names'],
|
||||
} as JSONSchema7,
|
||||
expected: [
|
||||
{
|
||||
id: 'names',
|
||||
displayName: 'names',
|
||||
defaultMatch: false,
|
||||
required: true,
|
||||
display: true,
|
||||
type: 'array',
|
||||
defaultValue: JSON.stringify(['string'], null, 2),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
user: {
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string' }, age: { type: 'number' } },
|
||||
},
|
||||
},
|
||||
required: ['user'],
|
||||
} as JSONSchema7,
|
||||
expected: [
|
||||
{
|
||||
id: 'user',
|
||||
displayName: 'user',
|
||||
defaultMatch: false,
|
||||
required: true,
|
||||
display: true,
|
||||
type: 'object',
|
||||
defaultValue: JSON.stringify({ name: 'string', age: 0 }, null, 2),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
])('should add defaultValue for arrays and objects', ({ schema, expected }) => {
|
||||
expect(convertJsonSchemaToResourceMapperFields(schema)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('should add options for enums', () => {
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: { color: { type: 'string', enum: ['red', 'green', 'blue'] } },
|
||||
} as JSONSchema7;
|
||||
const expected = [
|
||||
{
|
||||
id: 'color',
|
||||
displayName: 'color',
|
||||
defaultMatch: false,
|
||||
required: false,
|
||||
display: true,
|
||||
type: 'options',
|
||||
options: [
|
||||
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
|
||||
{ name: 'red', value: 'red' },
|
||||
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
|
||||
{ name: 'green', value: 'green' },
|
||||
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
|
||||
{ name: 'blue', value: 'blue' },
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(convertJsonSchemaToResourceMapperFields(schema)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { ILoadOptionsFunctions, INodeListSearchResult } from 'n8n-workflow';
|
||||
|
||||
import type { McpAuthenticationOption, McpServerTransport } from '../shared/types';
|
||||
import {
|
||||
connectMcpClient,
|
||||
getAuthHeaders,
|
||||
mapToNodeOperationError,
|
||||
tryRefreshOAuth2Token,
|
||||
} from '../shared/utils';
|
||||
|
||||
export async function getTools(
|
||||
this: ILoadOptionsFunctions,
|
||||
filter?: string,
|
||||
paginationToken?: string,
|
||||
): Promise<INodeListSearchResult> {
|
||||
const authentication = this.getNodeParameter('authentication') as McpAuthenticationOption;
|
||||
const serverTransport = this.getNodeParameter('serverTransport') as McpServerTransport;
|
||||
const endpointUrl = this.getNodeParameter('endpointUrl') as string;
|
||||
const node = this.getNode();
|
||||
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 result = await client.result.listTools({ cursor: paginationToken });
|
||||
const tools = filter
|
||||
? result.tools.filter((tool) => tool.name.toLowerCase().includes(filter.toLowerCase()))
|
||||
: result.tools;
|
||||
|
||||
return {
|
||||
results: tools.map((tool) => ({
|
||||
name: tool.name,
|
||||
value: tool.name,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
})),
|
||||
paginationToken: result.nextCursor,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { ILoadOptionsFunctions, ResourceMapperFields } from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import { convertJsonSchemaToResourceMapperFields } from './utils';
|
||||
import type { McpAuthenticationOption, McpServerTransport } from '../shared/types';
|
||||
import {
|
||||
getAuthHeaders,
|
||||
connectMcpClient,
|
||||
getAllTools,
|
||||
tryRefreshOAuth2Token,
|
||||
mapToNodeOperationError,
|
||||
} from '../shared/utils';
|
||||
|
||||
export async function getToolParameters(
|
||||
this: ILoadOptionsFunctions,
|
||||
): Promise<ResourceMapperFields> {
|
||||
const toolId = this.getNodeParameter('tool', 0, {
|
||||
extractValue: true,
|
||||
}) as string;
|
||||
const authentication = this.getNodeParameter('authentication') as McpAuthenticationOption;
|
||||
const serverTransport = this.getNodeParameter('serverTransport') as McpServerTransport;
|
||||
const endpointUrl = this.getNodeParameter('endpointUrl') as string;
|
||||
const node = this.getNode();
|
||||
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 result = await getAllTools(client.result);
|
||||
const tool = result.find((tool) => tool.name === toolId);
|
||||
if (!tool) {
|
||||
throw new NodeOperationError(this.getNode(), 'Tool not found');
|
||||
}
|
||||
|
||||
const fields = convertJsonSchemaToResourceMapperFields(tool.inputSchema);
|
||||
return {
|
||||
fields,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import type { JSONSchema7, JSONSchema7Definition } from 'json-schema';
|
||||
import type {
|
||||
ResourceMapperField,
|
||||
FieldType,
|
||||
INodePropertyOptions,
|
||||
IDataObject,
|
||||
} from 'n8n-workflow';
|
||||
|
||||
function pickFirstSchema(schema: JSONSchema7Definition): JSONSchema7Definition {
|
||||
if (typeof schema === 'object' && (schema?.anyOf || schema?.oneOf)) {
|
||||
if (Array.isArray(schema.anyOf) && schema.anyOf[0] !== undefined) {
|
||||
return schema.anyOf[0];
|
||||
}
|
||||
|
||||
if (Array.isArray(schema.oneOf) && schema.oneOf[0] !== undefined) {
|
||||
return schema.oneOf[0];
|
||||
}
|
||||
}
|
||||
|
||||
return schema;
|
||||
}
|
||||
|
||||
function mergeTwoSchemas(
|
||||
a?: JSONSchema7Definition,
|
||||
b?: JSONSchema7Definition,
|
||||
): JSONSchema7Definition | undefined {
|
||||
if (a === undefined) {
|
||||
return b;
|
||||
}
|
||||
|
||||
if (b === undefined) {
|
||||
return a;
|
||||
}
|
||||
|
||||
a = pickFirstSchema(a);
|
||||
b = pickFirstSchema(b);
|
||||
if (a === false || b === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a === true || b === true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.type === 'object' && b.type === 'object') {
|
||||
const properties = { ...(a.properties ?? {}), ...(b.properties ?? {}) };
|
||||
const required = [...(a.required ?? []), ...(b.required ?? [])];
|
||||
const additionalProperties = mergeTwoSchemas(a.additionalProperties, b.additionalProperties);
|
||||
return { ...a, ...b, properties, required, additionalProperties };
|
||||
}
|
||||
|
||||
if (a.type === 'array' && b.type === 'array') {
|
||||
if (Array.isArray(a.items) && Array.isArray(b.items)) {
|
||||
// Two tuples -> pick the longer one
|
||||
return a.items.length > b.items.length ? a : b;
|
||||
}
|
||||
|
||||
if (Array.isArray(a.items) || Array.isArray(b.items)) {
|
||||
// One tuple -> pick the tuple
|
||||
return Array.isArray(a.items) ? a : b;
|
||||
}
|
||||
|
||||
const items = mergeTwoSchemas(a.items, b.items);
|
||||
return { ...a, ...b, items };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function mergeAllOfSchemas(schemas: JSONSchema7Definition[]): JSONSchema7Definition | undefined {
|
||||
if (schemas.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (schemas.length === 1) {
|
||||
return schemas[0];
|
||||
}
|
||||
|
||||
return schemas.reduce(
|
||||
(acc, schema) => mergeTwoSchemas(acc, schema),
|
||||
undefined as JSONSchema7Definition | undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function jsonSchemaTypeToDefaultValue(
|
||||
schema: JSONSchema7Definition,
|
||||
): string | number | boolean | object | null {
|
||||
if (schema === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (schema === true) {
|
||||
return 'any';
|
||||
}
|
||||
|
||||
if (schema.allOf) {
|
||||
const mergedSchema = mergeAllOfSchemas(schema.allOf);
|
||||
if (mergedSchema !== undefined) {
|
||||
return jsonSchemaTypeToDefaultValue(mergedSchema);
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.anyOf) {
|
||||
const anyOfSchemas = schema.anyOf;
|
||||
for (const anyOfSchema of anyOfSchemas) {
|
||||
const defaultValue = jsonSchemaTypeToDefaultValue(anyOfSchema);
|
||||
if (defaultValue !== null) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.oneOf) {
|
||||
const oneOfSchemas = schema.oneOf;
|
||||
for (const oneOfSchema of oneOfSchemas) {
|
||||
const defaultValue = jsonSchemaTypeToDefaultValue(oneOfSchema);
|
||||
if (defaultValue !== null) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.enum && Array.isArray(schema.enum)) {
|
||||
return schema.enum[0];
|
||||
}
|
||||
|
||||
if (Array.isArray(schema.type)) {
|
||||
const types = schema.type;
|
||||
for (const type of types) {
|
||||
const defaultValue = jsonSchemaTypeToDefaultValue({ type });
|
||||
if (defaultValue !== null) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.type === 'number' || schema.type === 'integer') {
|
||||
if (schema.minimum !== undefined) {
|
||||
return schema.minimum;
|
||||
}
|
||||
|
||||
if (schema.maximum !== undefined) {
|
||||
return schema.maximum;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (schema.type === 'boolean') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (schema.type === 'string') {
|
||||
if (schema.format === 'date-time') {
|
||||
return '2025-01-01T00:00:00Z';
|
||||
}
|
||||
|
||||
if (schema.format === 'uri' || schema.format === 'url') {
|
||||
return 'https://example.com';
|
||||
}
|
||||
|
||||
if (schema.format === 'date') {
|
||||
return '2025-01-01';
|
||||
}
|
||||
|
||||
if (schema.format === 'time') {
|
||||
return '00:00:00';
|
||||
}
|
||||
|
||||
return 'string';
|
||||
}
|
||||
|
||||
if (schema.type === 'array') {
|
||||
if (!schema.items) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(schema.items)) {
|
||||
return schema.items.map((item) => jsonSchemaTypeToDefaultValue(item));
|
||||
}
|
||||
|
||||
return [jsonSchemaTypeToDefaultValue(schema.items)];
|
||||
}
|
||||
|
||||
if (schema.type === 'object') {
|
||||
const properties = schema.properties ?? {};
|
||||
const exampleObject: IDataObject = {};
|
||||
for (const [key, propertySchema] of Object.entries(properties)) {
|
||||
const propertyValue = jsonSchemaTypeToDefaultValue(propertySchema);
|
||||
if (propertyValue !== null) {
|
||||
exampleObject[key] = propertyValue;
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.additionalProperties) {
|
||||
const additionalProperties = jsonSchemaTypeToDefaultValue(schema.additionalProperties);
|
||||
if (additionalProperties !== null) {
|
||||
exampleObject['<additionalProperty>'] = additionalProperties;
|
||||
}
|
||||
}
|
||||
|
||||
return exampleObject;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function jsonSchemaTypeToFieldType(schema: JSONSchema7): FieldType {
|
||||
if (schema.type === 'string' && schema.format === 'date-time') {
|
||||
return 'dateTime';
|
||||
}
|
||||
|
||||
if (schema.type === 'number' || schema.type === 'integer') {
|
||||
return 'number';
|
||||
}
|
||||
|
||||
if (schema.type === 'boolean' || schema.type === 'array' || schema.type === 'object') {
|
||||
return schema.type;
|
||||
}
|
||||
|
||||
return 'string';
|
||||
}
|
||||
|
||||
export function convertJsonSchemaToResourceMapperFields(
|
||||
schema: JSONSchema7,
|
||||
): ResourceMapperField[] {
|
||||
const fields: ResourceMapperField[] = [];
|
||||
if (schema.type !== 'object' || !schema.properties) {
|
||||
return fields;
|
||||
}
|
||||
|
||||
const required = Array.isArray(schema.required) ? schema.required : [];
|
||||
for (const [key, propertySchema] of Object.entries(schema.properties)) {
|
||||
if (propertySchema === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (propertySchema === true) {
|
||||
fields.push({
|
||||
id: key,
|
||||
displayName: key,
|
||||
defaultMatch: false,
|
||||
required: required.includes(key),
|
||||
display: true,
|
||||
type: 'string', // use string as a "catch all" for any values
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const schemaType = jsonSchemaTypeToFieldType(propertySchema);
|
||||
let defaultValue: string | undefined;
|
||||
if (schemaType === 'object' || schemaType === 'array') {
|
||||
const result = jsonSchemaTypeToDefaultValue(propertySchema);
|
||||
if (result !== null) {
|
||||
defaultValue = JSON.stringify(result, null, 2);
|
||||
}
|
||||
}
|
||||
|
||||
const field: ResourceMapperField = {
|
||||
id: key,
|
||||
displayName: propertySchema.title ?? key,
|
||||
defaultMatch: false,
|
||||
required: required.includes(key),
|
||||
display: true,
|
||||
type: schemaType,
|
||||
defaultValue,
|
||||
};
|
||||
|
||||
if (propertySchema.enum && Array.isArray(propertySchema.enum)) {
|
||||
field.type = 'options';
|
||||
field.options = propertySchema.enum.map((value) => ({
|
||||
name: value,
|
||||
value,
|
||||
})) as INodePropertyOptions[];
|
||||
}
|
||||
|
||||
fields.push(field);
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
Reference in New Issue
Block a user