### Install Dependencies and Build Project from Source Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/installation.md After cloning the repository, install project dependencies and build the project. This is part of the source installation process. ```bash # Install dependencies npm install # Build the project npm run build ``` -------------------------------- ### Install and Register MCP Server Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/configuration.md Commands to install the MCP Installer and then register the n8n-mcp-server, either globally or from a local path. ```bash # Install the MCP Installer npx @anaisbetts/mcp-installer # Register the server (if installed globally) install_repo_mcp_server n8n-mcp-server # Or register from a local installation install_local_mcp_server path/to/n8n-mcp-server ``` -------------------------------- ### Run n8n MCP Server Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/index.md Execute this command to start the n8n MCP Server after installation and configuration. Ensure your .env file is set up correctly. ```bash n8n-mcp-server ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/configuration.md This is an example of a .env file showing required and optional environment variables for the n8n MCP Server. ```env # n8n MCP Server Environment Variables # Required: URL of the n8n API N8N_API_URL=http://localhost:5678/api/v1 # Required: API key for authenticating with n8n N8N_API_KEY=your_n8n_api_key_here # Optional: Set to 'true' to enable debug logging DEBUG=false ``` -------------------------------- ### Install Dependencies Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/index.md Install the necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Copy .env.example to .env Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/README.md Use this command to create a .env file for server configuration, based on the provided example. ```bash cp .env.example .env ``` -------------------------------- ### Install n8n MCP Server from Source Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/README.md Installs the n8n MCP Server from its source code repository. This involves cloning the repo, installing dependencies, and building the project. ```bash # Clone the repository git clone https://github.com/leonardsellem/n8n-mcp-server.git cd n8n-mcp-server # Install dependencies npm install # Build the project npm run build # Optional: Install globally npm install -g . ``` -------------------------------- ### Start Development Server Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/index.md Start the development server to compile TypeScript in watch mode, enabling hot reloading. ```bash npm run dev ``` -------------------------------- ### Create and Edit .env File Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/configuration.md Use these commands to copy the example .env file and then edit it with your specific server settings. ```bash cp .env.example .env # Edit the .env file with your settings nano .env # or use any text editor ``` -------------------------------- ### Optional: Install n8n MCP Server Globally from Source Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/installation.md After building from source, you can optionally install the server globally. This makes the command-line interface available system-wide. ```bash # Optional: Install globally npm install -g . ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/index.md Copy the example environment file and edit it with your n8n API credentials for local development. ```bash cp .env.example .env # Edit the .env file with your n8n API credentials ``` -------------------------------- ### Verify n8n MCP Server Installation Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/installation.md Run this command to verify that the n8n MCP Server has been installed correctly. It will display the installed version number. ```bash n8n-mcp-server --version ``` -------------------------------- ### Install n8n MCP Server Globally Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/index.md Use this command to install the n8n MCP Server globally on your system. This makes the `n8n-mcp-server` command available in your terminal. ```bash npm install -g @leonardsellem/n8n-mcp-server ``` -------------------------------- ### Example Workflow Get Input Schema Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/index.md This JSON schema defines the expected input for the `workflow_get` tool, specifying a required 'id' parameter of type string. ```json { "type": "object", "properties": { "id": { "type": "string", "description": "The ID of the workflow to retrieve" } }, "required": ["id"] } ``` -------------------------------- ### n8n to Slack Notification Setup Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/integration-examples.md This code block outlines the setup process for n8n to send notifications to Slack. It includes workflow IDs and the necessary webhook URL for configuration. ```javascript const notificationWorkflow = { id: "notificationWorkflowId", name: "n8n Execution Notifications to Slack" }; const setupWorkflow = { id: "setupWorkflowId", name: "Configure n8n Execution Notifications" }; // Execute the workflow to get the webhook URL const execution = await useMcpTool('n8n-mcp-server', 'execution_run', { workflowId: notificationWorkflow.id, waitForCompletion: true }); // Extract webhook URL from the execution let webhookUrl = "undefined"; if (execution.status === "success" && execution.data?.resultData?.runData?.Webhook?.[0]?.data?.webhookUrl) { webhookUrl = execution.data.resultData.runData.Webhook[0].data.webhookUrl; } return ` # n8n to Slack Notification Setup I've created two workflows: 1. **n8n Execution Notifications to Slack** - This workflow receives execution notifications from n8n and sends them to Slack - ID: ${notificationWorkflow.id} - Webhook URL: ${webhookUrl} 2. **Configure n8n Execution Notifications** - This workflow configures n8n settings to send notifications - ID: ${setupWorkflow.id} ## Next Steps: 1. Create a Slack app and obtain a token with the following permissions: - chat:write - chat:write.public 2. Set the environment variable `SLACK_TOKEN` with your Slack token 3. Run the "Configure n8n Execution Notifications" workflow after setting the `webhookUrl` parameter to: ${webhookUrl} 4. Activate the "n8n Execution Notifications to Slack" workflow 5. Customize the channel in the "Format Slack Message" node if needed (default is #n8n-notifications) Once completed, you'll receive Slack notifications whenever a workflow execution completes! `; ``` -------------------------------- ### Upgrade n8n MCP Server from Source Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/installation.md To upgrade an installation from source, navigate to the repository, pull the latest changes, and then reinstall dependencies and rebuild the project. ```bash # Navigate to the repository directory cd n8n-mcp-server # Pull the latest changes git pull # Install dependencies and rebuild npm install npm run build # If installed globally, reinstall npm install -g . ``` -------------------------------- ### Axios Mock Setup Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/testing.md Sets up the axios-mock-adapter to intercept HTTP requests. Use the reset function before each test to ensure a clean state. ```typescript // tests/mocks/axios-mock.ts import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; // Create a new instance of the mock adapter export const axiosMock = new MockAdapter(axios); // Helper function to reset the mock adapter before each test export function resetAxiosMock() { axiosMock.reset(); } ``` -------------------------------- ### AI Assistant Integration Configuration Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/README.md Example JSON configuration for integrating the n8n-mcp-server with AI assistants. Ensure you replace placeholder paths and API keys with your actual values. ```json { "mcpServers": { // Give your server a unique name "n8n-local": { // Use 'node' to execute the built JavaScript file "command": "node", // Provide the *absolute path* to the built index.js file "args": [ "/path/to/your/cloned/n8n-mcp-server/build/index.js" // On Windows, use double backslashes: // "C:\\path\\to\\your\\cloned\\n8n-mcp-server\\build\\index.js" ], // Environment variables needed by the server "env": { "N8N_API_URL": "http://your-n8n-instance:5678/api/v1", // Replace with your n8n URL "N8N_API_KEY": "YOUR_N8N_API_KEY", // Replace with your key // Add webhook credentials only if you plan to use webhook tools // "N8N_WEBHOOK_USERNAME": "your_webhook_user", // "N8N_WEBHOOK_PASSWORD": "your_webhook_password" }, // Ensure the server is enabled "disabled": false, // Default autoApprove settings "autoApprove": [] } // ... other servers might be configured here } } ``` -------------------------------- ### Connect n8n MCP Server to OpenAI Assistant Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/integration-examples.md Conceptual example of how an OpenAI Assistant can interact with the n8n MCP Server. It defines a function for listing workflows and shows how the assistant would call the n8n MCP Server API. ```javascript // This is a conceptual example of how an OpenAI Assistant might interact with the n8n MCP Server // In an OpenAI Assistant Function definition: { "name": "n8n_workflow_list", "description": "List all workflows in n8n", "parameters": { "type": "object", "properties": { "active": { "type": "boolean", "description": "Filter by active status (optional)" } } } } // The function would call the n8n MCP Server: async function n8n_workflow_list(params) { // Call the n8n MCP Server API const response = await fetch('http://localhost:3000/n8n-mcp/tools/workflow_list', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_AUTH_TOKEN' }, body: JSON.stringify(params) }); return await response.json(); } // The OpenAI Assistant would then use this function when asked about n8n workflows ``` -------------------------------- ### Create HubSpot Two-Way Sync Workflow Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/integration-examples.md This example demonstrates the creation of a two-way synchronization workflow between HubSpot and an internal system using n8n. It outlines the workflow's ID, configuration steps, and operational logic. ```javascript return ` # HubSpot Two-Way Sync Workflow Created I've created a new workflow that will synchronize contacts between HubSpot and your internal system. **Workflow ID:** ${syncWorkflow.id} ## Configuration Needed: 1. The workflow is currently **inactive** - activate it once configured 2. ${credentialsMessage} 3. You'll need to customize the "Get n8n Contacts", "Update Internal Contact", and "Create Internal Contact" nodes to work with your specific database or storage system ## How It Works: - Runs every 2 hours (configurable) - Retrieves contacts from both HubSpot and your internal system - Compares the data to identify new or updated contacts in either system - Creates or updates contacts to keep both systems in sync - Generates a sync report with statistics ## Customization: You may need to modify the field mappings in the function nodes to match your specific data structure and add any additional fields that need to be synchronized between the systems. `; ``` -------------------------------- ### Unit Tests for Static Resource Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/extending.md Write unit tests for your new static resource handler. This example uses Jest and mocks the client to verify the resource data and error handling. ```typescript // tests/unit/resources/static/my-resource.test.ts // or // tests/unit/resources/dynamic/my-resource.test.ts import { describe, it, expect, jest } from '@jest/globals'; import { MY_RESOURCE_URI, handleMyResourceRequest } from '../../../../src/resources/static/my-resource.js'; describe('My Resource', () => { it('should return resource data', async () => { const mockClient = { // Mock the necessary client methods }; const response = await handleMyResourceRequest(mockClient as any); expect(response.contents).toHaveLength(1); expect(response.contents[0].uri).toBe(MY_RESOURCE_URI); expect(response.contents[0].mimeType).toBe('application/json'); const data = JSON.parse(response.contents[0].text); expect(data).toHaveProperty('property1'); expect(data).toHaveProperty('property2'); }); it('should handle errors properly', async () => { const mockClient = { // Mock client that throws an error someMethod: jest.fn().mockRejectedValue(new Error('Test error')) }; await expect(handleMyResourceRequest(mockClient as any)) .rejects .toThrow('Failed to retrieve resource'); }); }); ``` -------------------------------- ### List Workflows with n8n MCP Server Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/basic-examples.md Use the `workflow_list` tool to retrieve all workflows from your n8n instance. This is useful for getting an overview of available workflows. ```javascript // The assistant uses the workflow_list tool const result = await useMcpTool('n8n-mcp-server', 'workflow_list', {}); // The assistant formats and presents the results if (result.length === 0) { return "You don't have any workflows in your n8n instance yet."; } else { let response = "Here are your workflows:\n\n"; result.forEach(workflow => { response += `- ${workflow.name} (ID: ${workflow.id}) - ${workflow.active ? 'Active' : 'Inactive'}\n`; }); return response; } ``` -------------------------------- ### Unit Test Example for Workflow List Tool Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/testing.md This snippet demonstrates a comprehensive unit test for the workflow list tool, covering its definition and handling of workflow retrieval and filtering. It uses Jest for testing and mocks the N8nClient to isolate the tool's logic. ```typescript // tests/unit/tools/workflow/list.test.ts import { describe, it, expect, jest } from '@jest/globals'; import { getListWorkflowsToolDefinition, handleListWorkflows } from '../../../../src/tools/workflow/list.js'; import { N8nClient } from '../../../../src/api/n8n-client.js'; // Mock data const mockWorkflows = [ { id: '1234abc', name: 'Test Workflow 1', active: true, createdAt: '2025-03-01T12:00:00.000Z', updatedAt: '2025-03-02T14:30:00.000Z' }, { id: '5678def', name: 'Test Workflow 2', active: false, createdAt: '2025-03-01T12:00:00.000Z', updatedAt: '2025-03-12T10:15:00.000Z' } ]; describe('Workflow List Tool', () => { describe('getListWorkflowsToolDefinition', () => { it('should return the correct tool definition', () => { const definition = getListWorkflowsToolDefinition(); expect(definition.name).toBe('workflow_list'); expect(definition.description).toBeTruthy(); expect(definition.inputSchema).toBeDefined(); expect(definition.inputSchema.properties).toHaveProperty('active'); expect(definition.inputSchema.required).toEqual([]); }); }); describe('handleListWorkflows', () => { it('should return all workflows when no filter is provided', async () => { // Mock the API client const mockClient = { getWorkflows: jest.fn().mockResolvedValue(mockWorkflows) }; const result = await handleListWorkflows(mockClient as unknown as N8nClient, {}); expect(mockClient.getWorkflows).toHaveBeenCalledWith(undefined); expect(result.isError).toBeFalsy(); // Parse the JSON text to check the content const content = JSON.parse(result.content[0].text); expect(content).toHaveLength(2); expect(content[0].id).toBe('1234abc'); expect(content[1].id).toBe('5678def'); }); it('should filter workflows by active status', async () => { // Mock the API client const mockClient = { getWorkflows: jest.fn().mockResolvedValue(mockWorkflows) }; const result = await handleListWorkflows(mockClient as unknown as N8nClient, { active: true }); expect(mockClient.getWorkflows).toHaveBeenCalledWith(true); expect(result.isError).toBeFalsy(); // Parse the JSON text to check the content const content = JSON.parse(result.content[0].text); expect(content).toHaveLength(2); }); it('should handle API errors', async () => { // Mock the API client to throw an error const mockClient = { getWorkflows: jest.fn().mockRejectedValue(new Error('API error')) }; const result = await handleListWorkflows(mockClient as unknown as N8nClient, {}); expect(result.isError).toBeTruthy(); expect(result.content[0].text).toContain('API error'); }); }); }); ``` -------------------------------- ### Extend Claude's Capabilities with n8n Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/integration-examples.md Uses n8n as a bridge to external systems, allowing Claude to access data like databases. This example shows how Claude can query a database through an n8n workflow. ```javascript // Using n8n as a bridge to external systems // This example shows how Claude can access a database through n8n // User: "Show me the top 5 customers from my database" // Claude would: // 1. Find the appropriate workflow const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {}); const dbQueryWorkflow = workflows.find(w => w.name.toLowerCase().includes('database query') || w.name.toLowerCase().includes('db query') ); if (!dbQueryWorkflow) { return "I couldn't find a database query workflow. Would you like me to help you create one?"; } // 2. Execute the workflow with the appropriate parameters const execution = await useMcpTool('n8n-mcp-server', 'execution_run', { workflowId: dbQueryWorkflow.id, data: { query: "SELECT * FROM customers ORDER BY total_purchases DESC LIMIT 5", format: "table" }, waitForCompletion: true }); // 3. Present the results to the user if (execution.status !== "success") { return "There was an error querying the database. Error: " + (execution.error || "Unknown error"); } // Format the results as a table const customers = execution.data.resultData.runData.lastNode[0].data.json; let response = "# Top 5 Customers\n\n"; response += "| Customer Name | Email | Total Purchases |\n"; response += "|--------------|-------|----------------|\n"; customers.forEach(customer => { response += `| ${customer.name} | ${customer.email} | $${customer.total_purchases.toFixed(2)} | `; }); return response; ``` -------------------------------- ### Extend Claude's Capabilities with n8n Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/integration-examples.md Use n8n as a bridge to external systems, allowing Claude to access data like databases. This example shows how Claude can query customer data through an n8n workflow. ```javascript // Using n8n as a bridge to external systems // This example shows how Claude can access a database through n8n // User: "Show me the top 5 customers from my database" // Claude would: // 1. Find the appropriate workflow const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {}); const dbQueryWorkflow = workflows.find(w => w.name.toLowerCase().includes('database query') || w.name.toLowerCase().includes('db query') ); if (!dbQueryWorkflow) { return "I couldn't find a database query workflow. Would you like me to help you create one?"; } // 2. Execute the workflow with the appropriate parameters const execution = await useMcpTool('n8n-mcp-server', 'execution_run', { workflowId: dbQueryWorkflow.id, data: { query: "SELECT * FROM customers ORDER BY total_purchases DESC LIMIT 5", format: "table" }, waitForCompletion: true }); // 3. Present the results to the user if (execution.status !== "success") { return "There was an error querying the database. Error: " + (execution.error || "Unknown error"); } // Format the results as a table const customers = execution.data.resultData.runData.lastNode[0].data.json; let response = "# Top 5 Customers\n\n"; response += "| Customer Name | Email | Total Purchases |\n"; response += "|--------------|-------|----------------|\n"; customers.forEach(customer => { response += `| ${customer.name} | ${customer.email} | $${customer.total_purchases.toFixed(2)} |\n`; }); return response; ``` -------------------------------- ### Create Workflow Error Notification System Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/advanced-scenarios.md This scenario demonstrates creating a monitoring workflow that checks for failures and sends notifications. It first checks for an existing monitor and then creates a new one if none is found. Requires email configuration in n8n settings and recipient email address setup. ```javascript // This scenario demonstrates creating a monitoring workflow that checks for failures // and sends notifications // First, check if a monitoring workflow already exists const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {}); const existingMonitor = workflows.find(workflow => workflow.name.toLowerCase().includes('workflow monitor') || workflow.name.toLowerCase().includes('error notification') ); if (existingMonitor) { return `You already have a monitoring workflow: "${existingMonitor.name}" (ID: ${existingMonitor.id}). Would you like me to update it instead?`; } // Create a new monitoring workflow const monitorWorkflow = await useMcpTool('n8n-mcp-server', 'workflow_create', { name: "Workflow Error Notification System", active: false, // Start inactive until configured nodes: [ { name: "Schedule Trigger", type: "n8n-nodes-base.scheduleTrigger", position: [100, 300], parameters: { cronExpression: "*/15 * * * *" // Run every 15 minutes } }, { name: "Get Failed Executions", type: "n8n-nodes-base.n8n", position: [300, 300], parameters: { resource: "execution", operation: "getAll", filters: { status: "error", // Look for executions in the last 15 minutes finished: { $gt: "={{$now.minus({ minutes: 15 }).toISOString()}}" } } } }, { name: "Filter Empty", type: "n8n-nodes-base.filter", position: [500, 300], parameters: { conditions: { boolean: [ { value1: "={{ $json.length > 0 }}", operation: "equal", value2: true } ] } } }, { name: "Format Notification", type: "n8n-nodes-base.function", position: [700, 300], parameters: { functionCode: ` // Function to format error notifications const executions = items; const now = new Date(); // Group by workflow const workflowErrors = {}; for (const execution of executions) { const workflowId = execution.workflowId; const workflowName = execution.workflowData.name; if (!workflowErrors[workflowId]) { workflowErrors[workflowId] = { name: workflowName, errors: [] }; } workflowErrors[workflowId].errors.push({ id: execution.id, time: execution.finished, error: execution.error?.message || "Unknown error" }); } // Create notification text let notificationText = "⚠️ Workflow Error Alert ⚠️\n\n"; notificationText += "The following workflows have failed:\n\n"; for (const [workflowId, data] of Object.entries(workflowErrors)) { notificationText += `👉 ${data.name} (ID: ${workflowId})\n`; notificationText += ` Failed executions: ${data.errors.length}\n`; // Add details about each failure data.errors.forEach(error => { const time = new Date(error.time).toLocaleString(); notificationText += ` - ${time}: ${error.error}\n`; }); notificationText += "\n"; } notificationText += "Check your n8n dashboard for more details."; return [{ json: { text: notificationText, subject: `n8n Alert: ${Object.keys(workflowErrors).length} Workflow(s) Failed`, timestamp: now.toISOString() } }]; ` } }, { name: "Send Email", type: "n8n-nodes-base.emailSend", position: [900, 300], parameters: { to: "{{$env.EMAIL_RECIPIENT}}", // Will need to be configured subject: "{{$json.subject}}", text: "{{$json.text}}" } } ], connections: { "Schedule Trigger": { main: [ [ { node: "Get Failed Executions", type: "main", index: 0 } ] ] }, "Get Failed Executions": { main: [ [ { node: "Filter Empty", type: "main", index: 0 } ] ] }, "Filter Empty": { main: [ [ { node: "Format Notification", type: "main", index: 0 } ] ] }, "Format Notification": { main: [ [ { node: "Send Email", type: "main", index: 0 } ] ] } } }); return ` # Workflow Error Notification System Created I've created a new workflow that will monitor for failed executions and send email notifications. **Workflow ID:** ${monitorWorkflow.id} ## Configuration Needed: 1. The workflow is currently **inactive** - you'll need to activate it once configured 2. Set up the email configuration in n8n settings 3. Configure the "Send Email" node with your recipient email address `; ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/index.md Clone the n8n-mcp-server repository and navigate into the project directory. ```bash git clone https://github.com/yourusername/n8n-mcp-server.git cd n8n-mcp-server ``` -------------------------------- ### Get Workflow Active Status Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/dynamic-resources.md Provides information about whether a specific workflow is active. ```APIDOC ## GET n8n://workflow/{id}/active ### Description Returns the active status of a specific workflow. ### Method GET ### Endpoint n8n://workflow/{id}/active ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the workflow to check ### Response #### Success Response (200) - **workflowId** (string) - The ID of the workflow. - **active** (boolean) - The active status of the workflow. ### Response Example ```json { "workflowId": "1234abc", "active": true } ``` ``` -------------------------------- ### Get Workflow Executions Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/dynamic-resources.md Provides a list of executions for a specific workflow, sorted by most recent first. ```APIDOC ## GET n8n://executions/{workflowId} ### Description Provides a list of executions for a specific workflow. ### Method GET ### Endpoint n8n://executions/{workflowId} ### Parameters #### Path Parameters - **workflowId** (string) - Required - The ID of the workflow whose executions to retrieve ### Response #### Success Response (200) - **executions** (array) - A list of execution records. - **id** (string) - **workflowId** (string) - **status** (string) - **startedAt** (string) - **finishedAt** (string) - **mode** (string) - **count** (integer) - The total number of executions. - **pagination** (object) - **hasMore** (boolean) ### Response Example ```json { "executions": [ { "id": "exec789", "workflowId": "1234abc", "status": "success", "startedAt": "2025-03-12T16:30:00.000Z", "finishedAt": "2025-03-12T16:30:05.000Z", "mode": "manual" }, { "id": "exec456", "workflowId": "1234abc", "status": "error", "startedAt": "2025-03-11T14:20:00.000Z", "finishedAt": "2025-03-11T14:20:10.000Z", "mode": "manual" } ], "count": 2, "pagination": { "hasMore": false } } ``` ``` -------------------------------- ### Get Workflow Details Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/dynamic-resources.md Provides detailed information about a specific workflow, including its nodes, connections, and settings. ```APIDOC ## GET n8n://workflow/{id} ### Description Provides detailed information about a specific workflow. ### Method GET ### Endpoint n8n://workflow/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the workflow to retrieve ### Response #### Success Response (200) - **workflow** (object) - Comprehensive information about the workflow. - **id** (string) - **name** (string) - **active** (boolean) - **createdAt** (string) - **updatedAt** (string) - **nodes** (array) - **connections** (object) - **settings** (object) ### Response Example ```json { "workflow": { "id": "1234abc", "name": "Email Processing Workflow", "active": true, "createdAt": "2025-03-01T12:00:00.000Z", "updatedAt": "2025-03-02T14:30:00.000Z", "nodes": [ { "id": "node1", "name": "Start", "type": "n8n-nodes-base.start", "position": [100, 200], "parameters": {} }, { "id": "node2", "name": "Email Trigger", "type": "n8n-nodes-base.emailTrigger", "position": [300, 200], "parameters": { "inbox": "support", "domain": "example.com" } } ], "connections": { "node1": { "main": [ [ { "node": "node2", "type": "main", "index": 0 } ] ] } }, "settings": { "saveExecutionProgress": true, "saveManualExecutions": true, "timezone": "America/New_York" } } } ``` ``` -------------------------------- ### Get Execution Details Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/dynamic-resources.md Provides detailed information about a specific execution, including its status, inputs, outputs, and execution path. ```APIDOC ## GET n8n://execution/{id} ### Description Provides detailed information about a specific execution. ### Method GET ### Endpoint n8n://execution/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the execution to retrieve ### Response #### Success Response (200) - **execution** (object) - Comprehensive information about the execution. - **id** (string) - **workflowId** (string) - **workflowName** (string) - **status** (string) - **startedAt** (string) - **finishedAt** (string) - **mode** (string) - **data** (object) ### Response Example ```json { "execution": { "id": "exec789", "workflowId": "1234abc", "workflowName": "Email Processing Workflow", "status": "success", "startedAt": "2025-03-12T16:30:00.000Z", "finishedAt": "2025-03-12T16:30:05.000Z", "mode": "manual", "data": { "resultData": { "runData": { "node1": [ { "startTime": "2025-03-12T16:30:00.000Z", "endTime": "2025-03-12T16:30:01.000Z", "executionStatus": "success", "data": { "json": { "started": true } } } ], "node2": [ { "startTime": "2025-03-12T16:30:01.000Z", "endTime": "2025-03-12T16:30:05.000Z", "executionStatus": "success", "data": { "json": { "subject": "Test Email", "body": "This is a test", "from": "sender@example.com" } } } ] } }, "executionData": { "nodeExecutionOrder": ["node1", "node2"], "waitingNodes": [], "waitingExecutionData": [] } } } } ``` ``` -------------------------------- ### Access n8n Workflow List Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/static-resources.md Retrieves a list of all workflows in the n8n instance. Use this to get basic metadata for each workflow. ```javascript const resource = await accessMcpResource('n8n-mcp-server', 'n8n://workflows/list'); ``` -------------------------------- ### Build Project for Distribution Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/index.md Compile the TypeScript code to JavaScript in the build directory for distribution. ```bash npm run build ``` -------------------------------- ### Test n8n MCP Server Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/README.md Execute this command to run the test suite for the n8n MCP Server. This helps ensure the stability and correctness of your changes. ```bash npm test ``` -------------------------------- ### Get Workflow Details Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/dynamic-resources.md Retrieve comprehensive information about a specific n8n workflow using its ID. This includes nodes, connections, and settings. ```javascript const resource = await accessMcpResource('n8n-mcp-server', 'n8n://workflow/1234abc'); ``` ```json { "workflow": { "id": "1234abc", "name": "Email Processing Workflow", "active": true, "createdAt": "2025-03-01T12:00:00.000Z", "updatedAt": "2025-03-02T14:30:00.000Z", "nodes": [ { "id": "node1", "name": "Start", "type": "n8n-nodes-base.start", "position": [100, 200], "parameters": {} }, { "id": "node2", "name": "Email Trigger", "type": "n8n-nodes-base.emailTrigger", "position": [300, 200], "parameters": { "inbox": "support", "domain": "example.com" } } ], "connections": { "node1": { "main": [ [ { "node": "node2", "type": "main", "index": 0 } ] ] } }, "settings": { "saveExecutionProgress": true, "saveManualExecutions": true, "timezone": "America/New_York" } } } ``` -------------------------------- ### Get Workflow Executions Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/api/dynamic-resources.md Retrieve a list of execution records for a specific n8n workflow, sorted by most recent first. Requires the workflow ID. ```javascript const resource = await accessMcpResource('n8n-mcp-server', 'n8n://executions/1234abc'); ``` ```json { "executions": [ { "id": "exec789", "workflowId": "1234abc", "status": "success", "startedAt": "2025-03-12T16:30:00.000Z", "finishedAt": "2025-03-12T16:30:05.000Z", "mode": "manual" }, { "id": "exec456", "workflowId": "1234abc", "status": "error", "startedAt": "2025-03-11T14:20:00.000Z", "finishedAt": "2025-03-11T14:20:10.000Z", "mode": "manual" } ], "count": 2, "pagination": { "hasMore": false } } ``` -------------------------------- ### Create Data Migration Workflow Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/advanced-scenarios.md This script automates the creation of an n8n workflow for data migration between two existing workflows. It finds source and target workflows by name, defines the migration steps (trigger, execute legacy, transform, execute new, summarize), and sets up connections between nodes. The transformation logic is a placeholder and requires customization. ```javascript // Get all workflows const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {}); // Find the source and target workflows const legacyWorkflow = workflows.find(w => w.name.toLowerCase().includes('legacy crm')); const newWorkflow = workflows.find(w => w.name.toLowerCase().includes('new crm')); if (!legacyWorkflow) { return "I couldn't find a workflow with 'Legacy CRM' in the name. Please check the exact name of your source workflow."; } if (!newWorkflow) { return "I couldn't find a workflow with 'New CRM' in the name. Please check the exact name of your target workflow."; } // Create a data migration workflow const migrationWorkflow = await useMcpTool('n8n-mcp-server', 'workflow_create', { name: "Data Migration: Legacy CRM to New CRM", active: false, // Start inactive until confirmed nodes: [ { name: "Manual Trigger", type: "n8n-nodes-base.manualTrigger", position: [100, 300], parameters: {} }, { name: "Execute Legacy Workflow", type: "n8n-nodes-base.executeWorkflow", position: [300, 300], parameters: { workflowId: legacyWorkflow.id, options: { includeData: true } } }, { name: "Transform Data", type: "n8n-nodes-base.function", position: [500, 300], parameters: { functionCode: " // This is a placeholder transformation function that you'll need to customize // based on the actual data structure of your workflows const legacyData = items; const transformedItems = []; // Example transformation (modify based on your data structures) for (const item of legacyData) { transformedItems.push({ json: { // Map legacy fields to new fields customer_id: item.json.id, customer_name: item.json.fullName || ` ${item.json.firstName || ''} ${item.json.lastName || ''}`.trim(), email: item.json.emailAddress || item.json.email, phone: item.json.phoneNumber || item.json.phone, notes: item.json.comments || item.json.notes || '', // Add migration metadata migrated_from_legacy: true, migration_date: new Date().toISOString() } }); } return transformedItems; " } }, { name: "Execute New Workflow", type: "n8n-nodes-base.executeWorkflow", position: [700, 300], parameters: { workflowId: newWorkflow.id, options: { includeData: true } } }, { name: "Migration Summary", type: "n8n-nodes-base.function", position: [900, 300], parameters: { functionCode: " // Create a summary of the migration const results = items; const totalItems = items.length; const successItems = items.filter(item => !item.json.error).length; const errorItems = totalItems - successItems; return [ { json: { summary: "Migration Complete", total_records: totalItems, successful_records: successItems, failed_records: errorItems, completion_time: new Date().toISOString() } } ]; " } } ], connections: { "Manual Trigger": { main: [ [ { node: "Execute Legacy Workflow", type: "main", index: 0 } ] ] }, "Execute Legacy Workflow": { main: [ [ { node: "Transform Data", type: "main", index: 0 } ] ] }, "Transform Data": { main: [ [ { node: "Execute New Workflow", type: "main", index: 0 } ] ] }, "Execute New Workflow": { main: [ [ { node: "Migration Summary", type: "main", index: 0 } ] ] } } }); return "\n# Data Migration Workflow Created I've created a new workflow to migrate data from "${legacyWorkflow.name}" to "${newWorkflow.name}". **Migration Workflow ID:** ${migrationWorkflow.id} ## Important Notes: 1. The workflow is currently **inactive** - activate it only when you're ready to perform the migration 2. The data transformation is a placeholder - you'll need to edit the "Transform Data" function node to map fields correctly based on your specific data structures 3. This is a one-time migration workflow - run it manually when you're ready to migrate the data ## Next Steps: 1. Open the workflow in the n8n interface 2. Edit the "Transform Data" function to correctly map your data fields 3. Test the workflow with a small sample if possible 4. Activate and run the workflow to perform the migration 5. Check the migration summary for results Would you like me to help you customize the data transformation based on the specific fields in your CRM workflows? "; ``` -------------------------------- ### Running Tests with npm Scripts Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/tests/README.md These commands are used to execute tests within the project. They include options for running all tests, watching for changes, generating coverage reports, and targeting specific files or patterns. ```bash # Run all tests npm test # Run tests in watch mode (useful during development) npm run test:watch # Run tests with coverage report npm run test:coverage # Run specific test file(s) npm test -- tests/unit/api/client.test.ts # Run tests matching a specific pattern npm test -- -t "should format and return workflows" ``` -------------------------------- ### Upgrade n8n MCP Server from npm Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/installation.md To upgrade a globally installed n8n MCP Server to the latest version available on npm, use this command. ```bash npm update -g n8n-mcp-server ``` -------------------------------- ### Clone n8n MCP Server Repository Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/setup/installation.md Clone the n8n MCP Server repository to install from source. This is useful for development or using the latest features. ```bash # Clone the repository git clone https://github.com/yourusername/n8n-mcp-server.git cd n8n-mcp-server ``` -------------------------------- ### Create a Static Resource Handler Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/extending.md Implement logic for a static resource that does not require parameters. Use the N8nClient for interactions. ```typescript // src/resources/static/my-resource.ts import { McpError, ReadResourceResponse } from '@modelcontextprotocol/sdk/types.js'; import { ErrorCode } from '../../errors/error-codes.js'; import { N8nClient } from '../../api/n8n-client.js'; export const MY_RESOURCE_URI = 'n8n://my-resource'; export async function handleMyResourceRequest( client: N8nClient ): Promise { try { // Implement the resource logic // Use the N8nClient to interact with n8n // Return the response return { contents: [ { uri: MY_RESOURCE_URI, mimeType: 'application/json', text: JSON.stringify( { // Resource data property1: 'value1', property2: 'value2' }, null, 2 ) } ] }; } catch (error) { throw new McpError( ErrorCode.InternalError, `Failed to retrieve resource: ${error.message}` ); } } ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/development/testing.md Execute all tests and generate code coverage reports, including HTML reports viewable in a browser. ```bash npm run test:coverage ``` -------------------------------- ### Register n8n MCP Server with Claude Source: https://github.com/leonardsellem/n8n-mcp-server/blob/main/docs/examples/integration-examples.md Registers the n8n MCP Server with Claude using the MCP Installer. After registration, Claude can interact with n8n workflows. ```javascript // Register the n8n MCP Server with Claude using the MCP Installer const installationResult = await useMcpTool('mcp-installer', 'install_repo_mcp_server', { name: 'n8n-mcp-server', env: [ "N8N_API_URL=http://localhost:5678/api/v1", "N8N_API_KEY=your_n8n_api_key_here", "DEBUG=false" ] }); // Once registered, Claude can interact with n8n // Here's an example conversation: // User: "Show me my active workflows in n8n" // Claude: (uses workflow_list tool to retrieve and display active workflows) // User: "Execute my 'Daily Report' workflow" // Claude: (uses execution_run tool to start the workflow and provide status) ```