mirror of
https://github.com/Abdulazizzn/n8n-enterprise-unlocked.git
synced 2025-12-17 01:56:46 +00:00
feat(MCP Server Trigger Node): Add MCP Server Trigger node to expose tools to MCP clients (#14403)
Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
|
||||
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
||||
import type { Response } from 'express';
|
||||
|
||||
export type CompressionResponse = Response & {
|
||||
/**
|
||||
* `flush()` is defined in the compression middleware.
|
||||
* This is necessary because the compression middleware sometimes waits
|
||||
* for a certain amount of data before sending the data to the client
|
||||
*/
|
||||
flush: () => void;
|
||||
};
|
||||
|
||||
export class FlushingSSEServerTransport extends SSEServerTransport {
|
||||
constructor(
|
||||
_endpoint: string,
|
||||
private response: CompressionResponse,
|
||||
) {
|
||||
super(_endpoint, response);
|
||||
}
|
||||
|
||||
async send(message: JSONRPCMessage): Promise<void> {
|
||||
await super.send(message);
|
||||
this.response.flush();
|
||||
}
|
||||
}
|
||||
195
packages/@n8n/nodes-langchain/nodes/Mcp/McpServer.ts
Normal file
195
packages/@n8n/nodes-langchain/nodes/Mcp/McpServer.ts
Normal file
@@ -0,0 +1,195 @@
|
||||
import type { Tool } from '@langchain/core/tools';
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
|
||||
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
||||
import {
|
||||
JSONRPCMessageSchema,
|
||||
ListToolsRequestSchema,
|
||||
CallToolRequestSchema,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import type * as express from 'express';
|
||||
import { OperationalError, type Logger } from 'n8n-workflow';
|
||||
import { zodToJsonSchema } from 'zod-to-json-schema';
|
||||
|
||||
import { FlushingSSEServerTransport } from './FlushingSSEServerTransport';
|
||||
import type { CompressionResponse } from './FlushingSSEServerTransport';
|
||||
|
||||
/**
|
||||
* Parses the JSONRPC message and checks whether the method used was a tool
|
||||
* call. This is necessary in order to not have executions for listing tools
|
||||
* and other commands sent by the MCP client
|
||||
*/
|
||||
function wasToolCall(body: string) {
|
||||
try {
|
||||
const message: unknown = JSON.parse(body);
|
||||
const parsedMessage: JSONRPCMessage = JSONRPCMessageSchema.parse(message);
|
||||
return (
|
||||
'method' in parsedMessage &&
|
||||
'id' in parsedMessage &&
|
||||
parsedMessage?.method === CallToolRequestSchema.shape.method.value
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export class McpServer {
|
||||
servers: { [sessionId: string]: Server } = {};
|
||||
|
||||
transports: { [sessionId: string]: FlushingSSEServerTransport } = {};
|
||||
|
||||
logger: Logger;
|
||||
|
||||
private tools: { [sessionId: string]: Tool[] } = {};
|
||||
|
||||
private resolveFunctions: { [sessionId: string]: CallableFunction } = {};
|
||||
|
||||
constructor(logger: Logger) {
|
||||
this.logger = logger;
|
||||
this.logger.debug('MCP Server created');
|
||||
}
|
||||
|
||||
async connectTransport(postUrl: string, resp: CompressionResponse): Promise<void> {
|
||||
const transport = new FlushingSSEServerTransport(postUrl, resp);
|
||||
const server = this.setUpServer();
|
||||
const { sessionId } = transport;
|
||||
this.transports[sessionId] = transport;
|
||||
this.servers[sessionId] = server;
|
||||
|
||||
resp.on('close', async () => {
|
||||
this.logger.debug(`Deleting transport for ${sessionId}`);
|
||||
delete this.tools[sessionId];
|
||||
delete this.resolveFunctions[sessionId];
|
||||
delete this.transports[sessionId];
|
||||
delete this.servers[sessionId];
|
||||
});
|
||||
|
||||
await server.connect(transport);
|
||||
|
||||
// Make sure we flush the compression middleware, so that it's not waiting for more content to be added to the buffer
|
||||
if (resp.flush) {
|
||||
resp.flush();
|
||||
}
|
||||
}
|
||||
|
||||
async handlePostMessage(req: express.Request, resp: CompressionResponse, connectedTools: Tool[]) {
|
||||
const sessionId = req.query.sessionId as string;
|
||||
const transport = this.transports[sessionId];
|
||||
this.tools[sessionId] = connectedTools;
|
||||
if (transport) {
|
||||
// We need to add a promise here because the `handlePostMessage` will send something to the
|
||||
// MCP Server, that will run in a different context. This means that the return will happen
|
||||
// almost immediately, and will lead to marking the sub-node as "running" in the final execution
|
||||
await new Promise(async (resolve) => {
|
||||
this.resolveFunctions[sessionId] = resolve;
|
||||
await transport.handlePostMessage(req, resp, req.rawBody.toString());
|
||||
});
|
||||
delete this.resolveFunctions[sessionId];
|
||||
} else {
|
||||
this.logger.warn(`No transport found for session ${sessionId}`);
|
||||
resp.status(401).send('No transport found for sessionId');
|
||||
}
|
||||
|
||||
if (resp.flush) {
|
||||
resp.flush();
|
||||
}
|
||||
|
||||
delete this.tools[sessionId]; // Clean up to avoid keeping all tools in memory
|
||||
|
||||
return wasToolCall(req.rawBody.toString());
|
||||
}
|
||||
|
||||
setUpServer(): Server {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'n8n-mcp-server',
|
||||
version: '0.1.0',
|
||||
},
|
||||
{
|
||||
capabilities: { tools: {} },
|
||||
},
|
||||
);
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, async (_, extra: RequestHandlerExtra) => {
|
||||
if (!extra.sessionId) {
|
||||
throw new OperationalError('Require a sessionId for the listing of tools');
|
||||
}
|
||||
|
||||
return {
|
||||
tools: this.tools[extra.sessionId].map((tool) => {
|
||||
return {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
inputSchema: zodToJsonSchema(tool.schema),
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request, extra: RequestHandlerExtra) => {
|
||||
if (!request.params?.name || !request.params?.arguments) {
|
||||
throw new OperationalError('Require a name and arguments for the tool call');
|
||||
}
|
||||
if (!extra.sessionId) {
|
||||
throw new OperationalError('Require a sessionId for the tool call');
|
||||
}
|
||||
|
||||
const requestedTool: Tool | undefined = this.tools[extra.sessionId].find(
|
||||
(tool) => tool.name === request.params.name,
|
||||
);
|
||||
if (!requestedTool) {
|
||||
throw new OperationalError('Tool not found');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await requestedTool.invoke(request.params.arguments);
|
||||
|
||||
this.resolveFunctions[extra.sessionId]();
|
||||
|
||||
this.logger.debug(`Got request for ${requestedTool.name}, and executed it.`);
|
||||
|
||||
// TODO: Refactor this to no longer use the legacy tool result, but
|
||||
return { toolResult: result };
|
||||
} catch (error) {
|
||||
this.logger.error(`Error while executing Tool ${requestedTool.name}: ${error}`);
|
||||
return { isError: true, content: [{ type: 'text', text: `Error: ${error.message}` }] };
|
||||
}
|
||||
});
|
||||
|
||||
server.onclose = () => {
|
||||
this.logger.debug('Closing MCP Server');
|
||||
};
|
||||
server.onerror = (error: unknown) => {
|
||||
this.logger.error(`MCP Error: ${error}`);
|
||||
};
|
||||
return server;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This singleton is shared across the instance, making sure we only have one server to worry about.
|
||||
* It needs to stay in memory to keep track of the long-lived connections.
|
||||
* It requires a logger at first creation to set everything up.
|
||||
*/
|
||||
export class McpServerSingleton {
|
||||
static #instance: McpServerSingleton;
|
||||
|
||||
private _serverData: McpServer;
|
||||
|
||||
private constructor(logger: Logger) {
|
||||
this._serverData = new McpServer(logger);
|
||||
}
|
||||
|
||||
static instance(logger: Logger): McpServer {
|
||||
if (!McpServerSingleton.#instance) {
|
||||
McpServerSingleton.#instance = new McpServerSingleton(logger);
|
||||
logger.debug('Created singleton for MCP Servers');
|
||||
}
|
||||
|
||||
return McpServerSingleton.#instance.serverData;
|
||||
}
|
||||
|
||||
get serverData() {
|
||||
return this._serverData;
|
||||
}
|
||||
}
|
||||
168
packages/@n8n/nodes-langchain/nodes/Mcp/McpTrigger.node.ts
Normal file
168
packages/@n8n/nodes-langchain/nodes/Mcp/McpTrigger.node.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { WebhookAuthorizationError } from 'n8n-nodes-base/dist/nodes/Webhook/error';
|
||||
import { validateWebhookAuthentication } from 'n8n-nodes-base/dist/nodes/Webhook/utils';
|
||||
import type { INodeTypeDescription, IWebhookFunctions, IWebhookResponseData } from 'n8n-workflow';
|
||||
import { NodeConnectionTypes, Node } from 'n8n-workflow';
|
||||
|
||||
import { getConnectedTools } from '@utils/helpers';
|
||||
|
||||
import type { CompressionResponse } from './FlushingSSEServerTransport';
|
||||
import { McpServerSingleton } from './McpServer';
|
||||
import type { McpServer } from './McpServer';
|
||||
|
||||
const MCP_SSE_SETUP_PATH = 'sse';
|
||||
const MCP_SSE_MESSAGES_PATH = 'messages';
|
||||
|
||||
export class McpTrigger extends Node {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'MCP Server Trigger',
|
||||
name: 'mcpTrigger',
|
||||
icon: {
|
||||
light: 'file:mcp.svg',
|
||||
dark: 'file:mcp.dark.svg',
|
||||
},
|
||||
group: ['trigger'],
|
||||
version: 1,
|
||||
description: 'Expose n8n tools as an MCP Server endpoint',
|
||||
activationMessage: 'You can now connect your MCP Clients to the SSE URL.',
|
||||
defaults: {
|
||||
name: 'MCP Server Trigger',
|
||||
},
|
||||
triggerPanel: {
|
||||
header: 'Listen for MCP events',
|
||||
executionsHelp: {
|
||||
inactive:
|
||||
"This trigger has two modes: test and production.<br /><br /><b>Use test mode while you build your workflow</b>. Click the 'test step' button, then make an MCP request to the test URL. The executions will show up in the editor.<br /><br /><b>Use production mode to run your workflow automatically</b>. <a data-key='activate'>Activate</a> the workflow, then make requests to the production URL. These executions will show up in the <a data-key='executions'>executions list</a>, but not the editor.",
|
||||
active:
|
||||
"This trigger has two modes: test and production.<br /><br /><b>Use test mode while you build your workflow</b>. Click the 'test step' button, then make an MCP request to the test URL. The executions will show up in the editor.<br /><br /><b>Use production mode to run your workflow automatically</b>. Since your workflow is activated, you can make requests to the production URL. These executions will show up in the <a data-key='executions'>executions list</a>, but not the editor.",
|
||||
},
|
||||
activationHint:
|
||||
'Once you’ve finished building your workflow, run it without having to click this button by using the production URL.',
|
||||
},
|
||||
inputs: [
|
||||
{
|
||||
type: NodeConnectionTypes.AiTool,
|
||||
displayName: 'Tools',
|
||||
},
|
||||
],
|
||||
outputs: [],
|
||||
credentials: [
|
||||
{
|
||||
// eslint-disable-next-line n8n-nodes-base/node-class-description-credentials-name-unsuffixed
|
||||
name: 'httpBearerAuth',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: ['bearerAuth'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'httpHeaderAuth',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: ['headerAuth'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'httpCustomAuth',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: ['customAuth'],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
properties: [
|
||||
{
|
||||
displayName: 'Authentication',
|
||||
name: 'authentication',
|
||||
type: 'options',
|
||||
options: [
|
||||
{ name: 'None', value: 'none' },
|
||||
{ name: 'Bearer Auth', value: 'bearerAuth' },
|
||||
{ name: 'Header Auth', value: 'headerAuth' },
|
||||
{ name: 'Custom Auth', value: 'customAuth' },
|
||||
],
|
||||
default: 'none',
|
||||
description: 'The way to authenticate',
|
||||
},
|
||||
{
|
||||
displayName: 'Path',
|
||||
name: 'path',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'webhook',
|
||||
required: true,
|
||||
description: 'The base path for this MCP server',
|
||||
},
|
||||
],
|
||||
webhooks: [
|
||||
{
|
||||
name: 'setup',
|
||||
httpMethod: 'GET',
|
||||
responseMode: 'onReceived',
|
||||
isFullPath: true,
|
||||
path: `={{$parameter["path"]}}/${MCP_SSE_SETUP_PATH}`,
|
||||
nodeType: 'mcp',
|
||||
ndvHideMethod: true,
|
||||
ndvHideUrl: false,
|
||||
},
|
||||
{
|
||||
name: 'default',
|
||||
httpMethod: 'POST',
|
||||
responseMode: 'onReceived',
|
||||
isFullPath: true,
|
||||
path: `={{$parameter["path"]}}/${MCP_SSE_MESSAGES_PATH}`,
|
||||
nodeType: 'mcp',
|
||||
ndvHideMethod: true,
|
||||
ndvHideUrl: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
async webhook(context: IWebhookFunctions): Promise<IWebhookResponseData> {
|
||||
const webhookName = context.getWebhookName();
|
||||
const req = context.getRequestObject();
|
||||
const resp = context.getResponseObject() as unknown as CompressionResponse;
|
||||
|
||||
try {
|
||||
await validateWebhookAuthentication(context, 'authentication');
|
||||
} catch (error) {
|
||||
if (error instanceof WebhookAuthorizationError) {
|
||||
resp.writeHead(error.responseCode);
|
||||
resp.end(error.message);
|
||||
return { noWebhookResponse: true };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const mcpServer: McpServer = McpServerSingleton.instance(context.logger);
|
||||
|
||||
if (webhookName === 'setup') {
|
||||
// Sets up the transport and opens the long-lived connection. This resp
|
||||
// will stay streaming, and is the channel that sends the events
|
||||
const postUrl = req.path.replace(
|
||||
new RegExp(`/${MCP_SSE_SETUP_PATH}$`),
|
||||
`/${MCP_SSE_MESSAGES_PATH}`,
|
||||
);
|
||||
await mcpServer.connectTransport(postUrl, resp);
|
||||
|
||||
return { noWebhookResponse: true };
|
||||
} else if (webhookName === 'default') {
|
||||
// This is the command-channel, and is actually executing the tools. This
|
||||
// sends the response back through the long-lived connection setup in the
|
||||
// 'setup' call
|
||||
const connectedTools = await getConnectedTools(context, true);
|
||||
|
||||
const wasToolCall = await mcpServer.handlePostMessage(req, resp, connectedTools);
|
||||
|
||||
if (wasToolCall) return { noWebhookResponse: true, workflowData: [[{ json: {} }]] };
|
||||
return { noWebhookResponse: true };
|
||||
}
|
||||
|
||||
return { workflowData: [[{ json: {} }]] };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { jest } from '@jest/globals';
|
||||
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { mock } from 'jest-mock-extended';
|
||||
|
||||
import { FlushingSSEServerTransport } from '../FlushingSSEServerTransport';
|
||||
import type { CompressionResponse } from '../FlushingSSEServerTransport';
|
||||
|
||||
describe('FlushingSSEServerTransport', () => {
|
||||
const mockResponse = mock<CompressionResponse>();
|
||||
let transport: FlushingSSEServerTransport;
|
||||
const endpoint = '/test/endpoint';
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
mockResponse.status.mockReturnThis();
|
||||
transport = new FlushingSSEServerTransport(endpoint, mockResponse);
|
||||
});
|
||||
|
||||
it('should call flush after sending a message', async () => {
|
||||
// Create a sample JSONRPC message
|
||||
const message: JSONRPCMessage = {
|
||||
jsonrpc: '2.0',
|
||||
id: '123',
|
||||
result: { success: true },
|
||||
};
|
||||
|
||||
// Send a message through the transport
|
||||
await transport.start();
|
||||
await transport.send(message);
|
||||
|
||||
expect(mockResponse.writeHead).toHaveBeenCalledWith(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
});
|
||||
expect(mockResponse.write).toHaveBeenCalledWith(
|
||||
// @ts-expect-error `_sessionId` is private
|
||||
`event: endpoint\ndata: /test/endpoint?sessionId=${transport._sessionId}\n\n`,
|
||||
);
|
||||
expect(mockResponse.write).toHaveBeenCalledWith(
|
||||
`event: message\ndata: ${JSON.stringify(message)}\n\n`,
|
||||
);
|
||||
expect(mockResponse.flush).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { jest } from '@jest/globals';
|
||||
import type { Tool } from '@langchain/core/tools';
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import type { Request } from 'express';
|
||||
import { captor, mock } from 'jest-mock-extended';
|
||||
|
||||
import type { CompressionResponse } from '../FlushingSSEServerTransport';
|
||||
import { FlushingSSEServerTransport } from '../FlushingSSEServerTransport';
|
||||
import { McpServer } from '../McpServer';
|
||||
|
||||
const sessionId = 'mock-session-id';
|
||||
const mockServer = mock<Server>();
|
||||
jest.mock('@modelcontextprotocol/sdk/server/index.js', () => {
|
||||
return {
|
||||
Server: jest.fn().mockImplementation(() => mockServer),
|
||||
};
|
||||
});
|
||||
|
||||
const mockTransport = mock<FlushingSSEServerTransport>({ sessionId });
|
||||
jest.mock('../FlushingSSEServerTransport', () => {
|
||||
return {
|
||||
FlushingSSEServerTransport: jest.fn().mockImplementation(() => mockTransport),
|
||||
};
|
||||
});
|
||||
|
||||
describe('McpServer', () => {
|
||||
const mockRequest = mock<Request>({ query: { sessionId }, path: '/sse' });
|
||||
const mockResponse = mock<CompressionResponse>();
|
||||
const mockTool = mock<Tool>({ name: 'mockTool' });
|
||||
|
||||
let mcpServer: McpServer;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockResponse.status.mockReturnThis();
|
||||
|
||||
mcpServer = new McpServer(mock());
|
||||
});
|
||||
|
||||
describe('connectTransport', () => {
|
||||
const postUrl = '/post-url';
|
||||
|
||||
it('should set up a transport and server', async () => {
|
||||
await mcpServer.connectTransport(postUrl, mockResponse);
|
||||
|
||||
// Check that FlushingSSEServerTransport was initialized with correct params
|
||||
expect(FlushingSSEServerTransport).toHaveBeenCalledWith(postUrl, mockResponse);
|
||||
|
||||
// Check that Server was initialized
|
||||
expect(Server).toHaveBeenCalled();
|
||||
|
||||
// Check that transport and server are stored
|
||||
expect(mcpServer.transports[sessionId]).toBeDefined();
|
||||
expect(mcpServer.servers[sessionId]).toBeDefined();
|
||||
|
||||
// Check that connect was called on the server
|
||||
expect(mcpServer.servers[sessionId].connect).toHaveBeenCalled();
|
||||
|
||||
// Check that flush was called if available
|
||||
expect(mockResponse.flush).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should set up close handler that cleans up resources', async () => {
|
||||
await mcpServer.connectTransport(postUrl, mockResponse);
|
||||
|
||||
// Get the close callback and execute it
|
||||
const closeCallbackCaptor = captor<() => Promise<void>>();
|
||||
expect(mockResponse.on).toHaveBeenCalledWith('close', closeCallbackCaptor);
|
||||
await closeCallbackCaptor.value();
|
||||
|
||||
// Check that resources were cleaned up
|
||||
expect(mcpServer.transports[sessionId]).toBeUndefined();
|
||||
expect(mcpServer.servers[sessionId]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('handlePostMessage', () => {
|
||||
it('should call transport.handlePostMessage when transport exists', async () => {
|
||||
mockTransport.handlePostMessage.mockImplementation(async () => {
|
||||
// @ts-expect-error private property `resolveFunctions`
|
||||
mcpServer.resolveFunctions[sessionId]();
|
||||
});
|
||||
|
||||
// Add the transport directly
|
||||
mcpServer.transports[sessionId] = mockTransport;
|
||||
|
||||
mockRequest.rawBody = Buffer.from(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
method: 'tools/call',
|
||||
id: 123,
|
||||
params: { name: 'mockTool' },
|
||||
}),
|
||||
);
|
||||
|
||||
// Call the method
|
||||
const result = await mcpServer.handlePostMessage(mockRequest, mockResponse, [mockTool]);
|
||||
|
||||
// Verify that transport's handlePostMessage was called
|
||||
expect(mockTransport.handlePostMessage).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
mockResponse,
|
||||
expect.any(String),
|
||||
);
|
||||
|
||||
// Verify that we check if it was a tool call
|
||||
expect(result).toBe(true);
|
||||
|
||||
// Verify flush was called
|
||||
expect(mockResponse.flush).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return 401 when transport does not exist', async () => {
|
||||
// Call without setting up transport
|
||||
await mcpServer.handlePostMessage(mockRequest, mockResponse, [mockTool]);
|
||||
|
||||
// Verify error status was set
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(401);
|
||||
expect(mockResponse.send).toHaveBeenCalledWith(expect.stringContaining('No transport found'));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { jest } from '@jest/globals';
|
||||
import type { Tool } from '@langchain/core/tools';
|
||||
import type { Request, Response } from 'express';
|
||||
import { mock } from 'jest-mock-extended';
|
||||
import type { IWebhookFunctions } from 'n8n-workflow';
|
||||
|
||||
import type { McpServer } from '../McpServer';
|
||||
import { McpTrigger } from '../McpTrigger.node';
|
||||
|
||||
const mockTool = mock<Tool>({ name: 'mockTool' });
|
||||
jest.mock('@utils/helpers', () => ({
|
||||
getConnectedTools: jest.fn().mockImplementation(() => [mockTool]),
|
||||
}));
|
||||
|
||||
const mockServer = mock<McpServer>();
|
||||
jest.mock('../McpServer', () => ({
|
||||
McpServerSingleton: {
|
||||
instance: jest.fn().mockImplementation(() => mockServer),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('McpTrigger Node', () => {
|
||||
const sessionId = 'mock-session-id';
|
||||
const mockContext = mock<IWebhookFunctions>();
|
||||
const mockRequest = mock<Request>({ query: { sessionId }, path: '/custom-path/sse' });
|
||||
const mockResponse = mock<Response>();
|
||||
let mcpTrigger: McpTrigger;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
mcpTrigger = new McpTrigger();
|
||||
|
||||
mockContext.getRequestObject.mockReturnValue(mockRequest);
|
||||
mockContext.getResponseObject.mockReturnValue(mockResponse);
|
||||
});
|
||||
|
||||
describe('webhook method', () => {
|
||||
it('should handle setup webhook', async () => {
|
||||
// Configure the context for setup webhook
|
||||
mockContext.getWebhookName.mockReturnValue('setup');
|
||||
|
||||
// Call the webhook method
|
||||
const result = await mcpTrigger.webhook(mockContext);
|
||||
|
||||
// Verify that the connectTransport method was called with correct URL
|
||||
expect(mockServer.connectTransport).toHaveBeenCalledWith(
|
||||
'/custom-path/messages',
|
||||
mockResponse,
|
||||
);
|
||||
|
||||
// Verify the returned result has noWebhookResponse: true
|
||||
expect(result).toEqual({ noWebhookResponse: true });
|
||||
});
|
||||
|
||||
it('should handle default webhook for tool execution', async () => {
|
||||
// Configure the context for default webhook (tool execution)
|
||||
mockContext.getWebhookName.mockReturnValue('default');
|
||||
|
||||
// Mock that the server executes a tool and returns true
|
||||
mockServer.handlePostMessage.mockResolvedValueOnce(true);
|
||||
|
||||
// Call the webhook method
|
||||
const result = await mcpTrigger.webhook(mockContext);
|
||||
|
||||
// Verify that handlePostMessage was called with request, response and tools
|
||||
expect(mockServer.handlePostMessage).toHaveBeenCalledWith(mockRequest, mockResponse, [
|
||||
mockTool,
|
||||
]);
|
||||
|
||||
// Verify the returned result when a tool was called
|
||||
expect(result).toEqual({
|
||||
noWebhookResponse: true,
|
||||
workflowData: [[{ json: {} }]],
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle default webhook when no tool was executed', async () => {
|
||||
// Configure the context for default webhook
|
||||
mockContext.getWebhookName.mockReturnValue('default');
|
||||
|
||||
// Mock that the server doesn't execute a tool and returns false
|
||||
mockServer.handlePostMessage.mockResolvedValueOnce(false);
|
||||
|
||||
// Call the webhook method
|
||||
const result = await mcpTrigger.webhook(mockContext);
|
||||
|
||||
// Verify the returned result when no tool was called
|
||||
expect(result).toEqual({ noWebhookResponse: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
7
packages/@n8n/nodes-langchain/nodes/Mcp/mcp.dark.svg
Normal file
7
packages/@n8n/nodes-langchain/nodes/Mcp/mcp.dark.svg
Normal file
@@ -0,0 +1,7 @@
|
||||
<svg width="180" height="180" viewBox="0 0 195 195" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g stroke="#fff" stroke-width="12" stroke-linecap="round">
|
||||
<path d="M25 97.8528L92.8823 29.9706C102.255 20.598 117.451 20.598 126.823 29.9706V29.9706C136.196 39.3431 136.196 54.5391 126.823 63.9117L75.5581 115.177"/>
|
||||
<path d="M76.2653 114.47L126.823 63.9117C136.196 54.5391 151.392 54.5391 160.765 63.9117L161.118 64.2652C170.491 73.6378 170.491 88.8338 161.118 98.2063L99.7248 159.6C96.6006 162.724 96.6006 167.789 99.7248 170.913L112.331 183.52"/>
|
||||
<path d="M109.853 46.9411L59.6482 97.1457C50.2757 106.518 50.2757 121.714 59.6482 131.087V131.087C69.0208 140.459 84.2168 140.459 93.5894 131.087L143.794 80.8822"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 735 B |
7
packages/@n8n/nodes-langchain/nodes/Mcp/mcp.svg
Normal file
7
packages/@n8n/nodes-langchain/nodes/Mcp/mcp.svg
Normal file
@@ -0,0 +1,7 @@
|
||||
<svg width="180" height="180" viewBox="0 0 195 195" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g stroke="#000" stroke-width="12" stroke-linecap="round">
|
||||
<path d="M25 97.8528L92.8823 29.9706C102.255 20.598 117.451 20.598 126.823 29.9706V29.9706C136.196 39.3431 136.196 54.5391 126.823 63.9117L75.5581 115.177"/>
|
||||
<path d="M76.2653 114.47L126.823 63.9117C136.196 54.5391 151.392 54.5391 160.765 63.9117L161.118 64.2652C170.491 73.6378 170.491 88.8338 161.118 98.2063L99.7248 159.6C96.6006 162.724 96.6006 167.789 99.7248 170.913L112.331 183.52"/>
|
||||
<path d="M109.853 46.9411L59.6482 97.1457C50.2757 106.518 50.2757 121.714 59.6482 131.087V131.087C69.0208 140.459 84.2168 140.459 93.5894 131.087L143.794 80.8822"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 735 B |
@@ -1,19 +1,16 @@
|
||||
// ToolsAgent.test.ts
|
||||
import type { BaseChatMemory } from '@langchain/community/memory/chat_memory';
|
||||
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
import { HumanMessage } from '@langchain/core/messages';
|
||||
import type { BaseMessagePromptTemplateLike } from '@langchain/core/prompts';
|
||||
import { FakeTool } from '@langchain/core/utils/testing';
|
||||
import { Buffer } from 'buffer';
|
||||
import { mock } from 'jest-mock-extended';
|
||||
import type { ToolsAgentAction } from 'langchain/dist/agents/tool_calling/output_parser';
|
||||
import type { Tool } from 'langchain/tools';
|
||||
import type { IExecuteFunctions } from 'n8n-workflow';
|
||||
import { NodeOperationError, BINARY_ENCODING } from 'n8n-workflow';
|
||||
import { NodeOperationError, BINARY_ENCODING, NodeConnectionTypes } from 'n8n-workflow';
|
||||
import type { ZodType } from 'zod';
|
||||
import { z } from 'zod';
|
||||
|
||||
import * as helpersModule from '@utils/helpers';
|
||||
import type { N8nOutputParser } from '@utils/output_parsers/N8nOutputParser';
|
||||
|
||||
import {
|
||||
@@ -28,31 +25,16 @@ import {
|
||||
getTools,
|
||||
} from '../agents/ToolsAgent/execute';
|
||||
|
||||
// We need to override the imported getConnectedTools so that we control its output.
|
||||
jest.spyOn(helpersModule, 'getConnectedTools').mockResolvedValue([FakeTool as unknown as Tool]);
|
||||
|
||||
function getFakeOutputParser(returnSchema?: ZodType): N8nOutputParser {
|
||||
const fakeOutputParser = mock<N8nOutputParser>();
|
||||
(fakeOutputParser.getSchema as jest.Mock).mockReturnValue(returnSchema);
|
||||
return fakeOutputParser;
|
||||
}
|
||||
|
||||
function createFakeExecuteFunctions(overrides: Partial<IExecuteFunctions> = {}): IExecuteFunctions {
|
||||
return {
|
||||
getNodeParameter: jest
|
||||
.fn()
|
||||
.mockImplementation((_arg1: string, _arg2: number, defaultValue?: unknown) => {
|
||||
return defaultValue;
|
||||
}),
|
||||
getNode: jest.fn().mockReturnValue({}),
|
||||
getInputConnectionData: jest.fn().mockResolvedValue({}),
|
||||
getInputData: jest.fn().mockReturnValue([]),
|
||||
continueOnFail: jest.fn().mockReturnValue(false),
|
||||
logger: { debug: jest.fn() },
|
||||
helpers: {},
|
||||
...overrides,
|
||||
} as unknown as IExecuteFunctions;
|
||||
}
|
||||
const mockHelpers = mock<IExecuteFunctions['helpers']>();
|
||||
const mockContext = mock<IExecuteFunctions>({ helpers: mockHelpers });
|
||||
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
describe('getOutputParserSchema', () => {
|
||||
it('should return a default schema if getSchema returns undefined', () => {
|
||||
@@ -74,6 +56,7 @@ describe('getOutputParserSchema', () => {
|
||||
describe('extractBinaryMessages', () => {
|
||||
it('should extract a binary message from the input data when no id is provided', async () => {
|
||||
const fakeItem = {
|
||||
json: {},
|
||||
binary: {
|
||||
img1: {
|
||||
mimeType: 'image/png',
|
||||
@@ -82,11 +65,9 @@ describe('extractBinaryMessages', () => {
|
||||
},
|
||||
},
|
||||
};
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputData: jest.fn().mockReturnValue([fakeItem]),
|
||||
});
|
||||
mockContext.getInputData.mockReturnValue([fakeItem]);
|
||||
|
||||
const humanMsg: HumanMessage = await extractBinaryMessages(ctx, 0);
|
||||
const humanMsg: HumanMessage = await extractBinaryMessages(mockContext, 0);
|
||||
// Expect the HumanMessage's content to be an array containing one binary message.
|
||||
expect(Array.isArray(humanMsg.content)).toBe(true);
|
||||
expect(humanMsg.content[0]).toEqual({
|
||||
@@ -97,6 +78,7 @@ describe('extractBinaryMessages', () => {
|
||||
|
||||
it('should extract a binary message using binary stream if id is provided', async () => {
|
||||
const fakeItem = {
|
||||
json: {},
|
||||
binary: {
|
||||
img2: {
|
||||
mimeType: 'image/jpeg',
|
||||
@@ -105,21 +87,16 @@ describe('extractBinaryMessages', () => {
|
||||
},
|
||||
},
|
||||
};
|
||||
// Cast fakeHelpers as any to satisfy type requirements.
|
||||
const fakeHelpers = {
|
||||
getBinaryStream: jest.fn().mockResolvedValue('stream'),
|
||||
binaryToBuffer: jest.fn().mockResolvedValue(Buffer.from('fakebufferdata')),
|
||||
} as unknown as IExecuteFunctions['helpers'];
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputData: jest.fn().mockReturnValue([fakeItem]),
|
||||
helpers: fakeHelpers,
|
||||
});
|
||||
|
||||
const humanMsg: HumanMessage = await extractBinaryMessages(ctx, 0);
|
||||
mockHelpers.getBinaryStream.mockResolvedValue(mock());
|
||||
mockHelpers.binaryToBuffer.mockResolvedValue(Buffer.from('fakebufferdata'));
|
||||
mockContext.getInputData.mockReturnValue([fakeItem]);
|
||||
|
||||
const humanMsg: HumanMessage = await extractBinaryMessages(mockContext, 0);
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
expect(fakeHelpers.getBinaryStream).toHaveBeenCalledWith('1234');
|
||||
expect(mockHelpers.getBinaryStream).toHaveBeenCalledWith('1234');
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
expect(fakeHelpers.binaryToBuffer).toHaveBeenCalled();
|
||||
expect(mockHelpers.binaryToBuffer).toHaveBeenCalled();
|
||||
const expectedUrl = `data:image/jpeg;base64,${Buffer.from('fakebufferdata').toString(
|
||||
BINARY_ENCODING,
|
||||
)}`;
|
||||
@@ -173,48 +150,48 @@ describe('getChatModel', () => {
|
||||
const fakeChatModel = mock<BaseChatModel>();
|
||||
fakeChatModel.bindTools = jest.fn();
|
||||
fakeChatModel.lc_namespace = ['chat_models'];
|
||||
mockContext.getInputConnectionData.mockResolvedValue(fakeChatModel);
|
||||
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputConnectionData: jest.fn().mockResolvedValue(fakeChatModel),
|
||||
});
|
||||
const model = await getChatModel(ctx);
|
||||
const model = await getChatModel(mockContext);
|
||||
expect(model).toEqual(fakeChatModel);
|
||||
});
|
||||
|
||||
it('should throw if the model is not a valid chat model', async () => {
|
||||
const fakeInvalidModel = mock<BaseChatModel>(); // missing bindTools & lc_namespace
|
||||
fakeInvalidModel.lc_namespace = [];
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputConnectionData: jest.fn().mockResolvedValue(fakeInvalidModel),
|
||||
getNode: jest.fn().mockReturnValue({}),
|
||||
});
|
||||
await expect(getChatModel(ctx)).rejects.toThrow(NodeOperationError);
|
||||
mockContext.getInputConnectionData.mockResolvedValue(fakeInvalidModel);
|
||||
mockContext.getNode.mockReturnValue(mock());
|
||||
await expect(getChatModel(mockContext)).rejects.toThrow(NodeOperationError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOptionalMemory', () => {
|
||||
it('should return the memory if available', async () => {
|
||||
const fakeMemory = { some: 'memory' };
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputConnectionData: jest.fn().mockResolvedValue(fakeMemory),
|
||||
});
|
||||
const memory = await getOptionalMemory(ctx);
|
||||
mockContext.getInputConnectionData.mockResolvedValue(fakeMemory);
|
||||
|
||||
const memory = await getOptionalMemory(mockContext);
|
||||
expect(memory).toEqual(fakeMemory);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTools', () => {
|
||||
beforeEach(() => {
|
||||
const fakeTool = mock<Tool>();
|
||||
mockContext.getInputConnectionData
|
||||
.calledWith(NodeConnectionTypes.AiTool, 0)
|
||||
.mockResolvedValue([fakeTool]);
|
||||
});
|
||||
|
||||
it('should retrieve tools without appending if outputParser is not provided', async () => {
|
||||
const ctx = createFakeExecuteFunctions();
|
||||
const tools = await getTools(ctx);
|
||||
const tools = await getTools(mockContext);
|
||||
|
||||
expect(tools.length).toEqual(1);
|
||||
});
|
||||
|
||||
it('should retrieve tools and append the structured output parser tool if outputParser is provided', async () => {
|
||||
const fakeOutputParser = getFakeOutputParser(z.object({ text: z.string() }));
|
||||
const ctx = createFakeExecuteFunctions();
|
||||
const tools = await getTools(ctx, fakeOutputParser);
|
||||
const tools = await getTools(mockContext, fakeOutputParser);
|
||||
// Our fake getConnectedTools returns one tool; with outputParser, one extra is appended.
|
||||
expect(tools.length).toEqual(2);
|
||||
const dynamicTool = tools.find((t) => t.name === 'format_final_json_response');
|
||||
@@ -225,6 +202,7 @@ describe('getTools', () => {
|
||||
describe('prepareMessages', () => {
|
||||
it('should include a binary message if binary data is present and passthroughBinaryImages is true', async () => {
|
||||
const fakeItem = {
|
||||
json: {},
|
||||
binary: {
|
||||
img1: {
|
||||
mimeType: 'image/png',
|
||||
@@ -232,10 +210,8 @@ describe('prepareMessages', () => {
|
||||
},
|
||||
},
|
||||
};
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputData: jest.fn().mockReturnValue([fakeItem]),
|
||||
});
|
||||
const messages = await prepareMessages(ctx, 0, {
|
||||
mockContext.getInputData.mockReturnValue([fakeItem]);
|
||||
const messages = await prepareMessages(mockContext, 0, {
|
||||
systemMessage: 'Test system',
|
||||
passthroughBinaryImages: true,
|
||||
});
|
||||
@@ -248,10 +224,8 @@ describe('prepareMessages', () => {
|
||||
|
||||
it('should not include a binary message if no binary data is present', async () => {
|
||||
const fakeItem = { json: {} }; // no binary key
|
||||
const ctx = createFakeExecuteFunctions({
|
||||
getInputData: jest.fn().mockReturnValue([fakeItem]),
|
||||
});
|
||||
const messages = await prepareMessages(ctx, 0, {
|
||||
mockContext.getInputData.mockReturnValue([fakeItem]);
|
||||
const messages = await prepareMessages(mockContext, 0, {
|
||||
systemMessage: 'Test system',
|
||||
passthroughBinaryImages: true,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user