Initial commit of n8n MCP Server

A Model Context Protocol (MCP) server that integrates with n8n, providing tools for workflow and execution management via the n8n API.
This commit is contained in:
leonardsellem
2025-03-12 17:12:35 +01:00
commit 2cd565cfa6
79 changed files with 19654 additions and 0 deletions

0
docs/.gitkeep Normal file
View File

View File

@@ -0,0 +1,250 @@
# Dynamic Resources
This page documents the dynamic resources available in the n8n MCP Server.
## Overview
Dynamic resources are parameterized URIs that allow access to specific n8n data based on identifiers such as workflow IDs or execution IDs. These resources follow the URI template format defined in RFC 6570, with parameters enclosed in curly braces.
## Available Resource Templates
### n8n://workflow/{id}
Provides detailed information about a specific workflow.
**URI Template:** `n8n://workflow/{id}`
**Parameters:**
- `id` (required): The ID of the workflow to retrieve
**Description:** Returns comprehensive information about a specific workflow, including its nodes, connections, and settings.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://workflow/1234abc');
```
**Response:**
```javascript
{
"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"
}
}
}
```
### n8n://executions/{workflowId}
Provides a list of executions for a specific workflow.
**URI Template:** `n8n://executions/{workflowId}`
**Parameters:**
- `workflowId` (required): The ID of the workflow whose executions to retrieve
**Description:** Returns a list of execution records for the specified workflow, sorted by most recent first.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://executions/1234abc');
```
**Response:**
```javascript
{
"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
}
}
```
### n8n://execution/{id}
Provides detailed information about a specific execution.
**URI Template:** `n8n://execution/{id}`
**Parameters:**
- `id` (required): The ID of the execution to retrieve
**Description:** Returns comprehensive information about a specific execution, including its status, inputs, outputs, and execution path.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://execution/exec789');
```
**Response:**
```javascript
{
"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": []
}
}
}
}
```
### n8n://workflow/{id}/active
Provides information about whether a specific workflow is active.
**URI Template:** `n8n://workflow/{id}/active`
**Parameters:**
- `id` (required): The ID of the workflow to check
**Description:** Returns the active status of a specific workflow.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://workflow/1234abc/active');
```
**Response:**
```javascript
{
"workflowId": "1234abc",
"active": true
}
```
## Content Types
All dynamic resources return JSON content with the MIME type `application/json`.
## Error Handling
Dynamic resources can return the following errors:
| HTTP Status | Description |
|-------------|-------------|
| 400 | Bad Request - Invalid parameter in URI |
| 401 | Unauthorized - Invalid or missing API key |
| 403 | Forbidden - API key does not have permission to access this resource |
| 404 | Not Found - The requested resource does not exist |
| 500 | Internal Server Error - An unexpected error occurred on the n8n server |
## Parameter Format
When using dynamic resources, parameters must be properly formatted:
1. **Workflow IDs**: Must be valid n8n workflow IDs (typically alphanumeric)
2. **Execution IDs**: Must be valid n8n execution IDs (typically alphanumeric)
## Best Practices
- Validate resource URIs before accessing them
- Handle possible 404 errors when accessing resources by ID
- Cache resource data when appropriate to reduce API calls
- Use specific resources (like `n8n://workflow/{id}/active`) for single properties when you don't need the entire resource
- Check workflow status before performing operations that require an active workflow

315
docs/api/execution-tools.md Normal file
View File

@@ -0,0 +1,315 @@
# Execution Tools
This page documents the tools available for managing n8n workflow executions.
## Overview
Execution tools allow AI assistants to execute n8n workflows and manage execution records. These tools provide a natural language interface to n8n's execution capabilities, allowing workflows to be run, monitored, and their results accessed.
## Available Tools
### execution_run
Executes a workflow with optional input data.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"workflowId": {
"type": "string",
"description": "ID of the workflow to execute"
},
"data": {
"type": "object",
"description": "Input data to pass to the workflow"
},
"waitForCompletion": {
"type": "boolean",
"description": "Whether to wait for the workflow to complete before returning",
"default": false
}
},
"required": ["workflowId"]
}
```
**Example Usage:**
```javascript
// Execute without waiting
const execution = await useExecutionRun({
workflowId: "1234abc"
});
// Execute with input data
const executionWithData = await useExecutionRun({
workflowId: "1234abc",
data: {
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com"
}
});
// Execute and wait for completion
const completedExecution = await useExecutionRun({
workflowId: "1234abc",
waitForCompletion: true
});
```
**Response (when waitForCompletion: false):**
```javascript
{
"executionId": "exec789",
"status": "running",
"startedAt": "2025-03-12T16:30:00.000Z"
}
```
**Response (when waitForCompletion: true):**
```javascript
{
"executionId": "exec789",
"status": "success", // Or "error" if execution failed
"startedAt": "2025-03-12T16:30:00.000Z",
"finishedAt": "2025-03-12T16:30:05.000Z",
"data": {
// Output data from the workflow execution
}
}
```
### execution_get
Retrieves details of a specific execution.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"executionId": {
"type": "string",
"description": "ID of the execution to retrieve"
}
},
"required": ["executionId"]
}
```
**Example Usage:**
```javascript
const execution = await useExecutionGet({
executionId: "exec789"
});
```
**Response:**
```javascript
{
"id": "exec789",
"workflowId": "1234abc",
"workflowName": "Test Workflow 1",
"status": "success", // Or "error", "running", "waiting", etc.
"startedAt": "2025-03-12T16:30:00.000Z",
"finishedAt": "2025-03-12T16:30:05.000Z",
"mode": "manual",
"data": {
"resultData": {
// Output data from the workflow execution
},
"executionData": {
// Detailed execution data including node inputs/outputs
},
"metadata": {
// Execution metadata
}
}
}
```
### execution_list
Lists executions for a specific workflow.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"workflowId": {
"type": "string",
"description": "ID of the workflow to get executions for"
},
"limit": {
"type": "number",
"description": "Maximum number of executions to return",
"default": 20
},
"status": {
"type": "string",
"description": "Filter by execution status",
"enum": ["success", "error", "running", "waiting"]
}
},
"required": ["workflowId"]
}
```
**Example Usage:**
```javascript
// List all executions for a workflow
const executions = await useExecutionList({
workflowId: "1234abc"
});
// List with limit
const limitedExecutions = await useExecutionList({
workflowId: "1234abc",
limit: 5
});
// List only successful executions
const successfulExecutions = await useExecutionList({
workflowId: "1234abc",
status: "success"
});
```
**Response:**
```javascript
[
{
"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"
}
]
```
### execution_delete
Deletes an execution record.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"executionId": {
"type": "string",
"description": "ID of the execution to delete"
}
},
"required": ["executionId"]
}
```
**Example Usage:**
```javascript
await useExecutionDelete({
executionId: "exec789"
});
```
**Response:**
```javascript
{
"success": true
}
```
### execution_stop
Stops a running execution.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"executionId": {
"type": "string",
"description": "ID of the execution to stop"
}
},
"required": ["executionId"]
}
```
**Example Usage:**
```javascript
await useExecutionStop({
executionId: "exec789"
});
```
**Response:**
```javascript
{
"success": true,
"status": "cancelled",
"stoppedAt": "2025-03-12T16:32:00.000Z"
}
```
## Execution Status Codes
Executions can have the following status codes:
| Status | Description |
|--------|-------------|
| `running` | The execution is currently in progress |
| `success` | The execution completed successfully |
| `error` | The execution failed with an error |
| `waiting` | The execution is waiting for a webhook or other event |
| `cancelled` | The execution was manually stopped |
## Error Handling
All execution tools can return the following errors:
| Error | Description |
|-------|-------------|
| Authentication Error | The provided API key is invalid or missing |
| Not Found Error | The requested workflow or execution does not exist |
| Validation Error | The input parameters are invalid or incomplete |
| Permission Error | The API key does not have permission to perform the operation |
| Server Error | An unexpected error occurred on the n8n server |
## Best Practices
- Check if a workflow is active before attempting to execute it
- Use `waitForCompletion: true` for short-running workflows, but be cautious with long-running workflows
- Always handle potential errors when executing workflows
- Filter executions by status to find problematic runs
- Use execution IDs from `execution_run` responses to track workflow progress

74
docs/api/index.md Normal file
View File

@@ -0,0 +1,74 @@
# API Reference
This section provides a comprehensive reference for the n8n MCP Server API, including all available tools and resources.
## Overview
The n8n MCP Server implements the Model Context Protocol (MCP) to provide AI assistants with access to n8n workflows and executions. The API is divided into two main categories:
1. **Tools**: Executable functions that can perform operations on n8n, such as creating workflows or starting executions.
2. **Resources**: Data sources that provide information about workflows and executions.
## API Architecture
The n8n MCP Server follows a clean separation of concerns:
- **Client Layer**: Handles communication with the n8n API
- **Transport Layer**: Implements the MCP protocol for communication with AI assistants
- **Tools Layer**: Exposes executable operations to AI assistants
- **Resources Layer**: Provides data access through URI-based resources
All API interactions are authenticated using the n8n API key configured in your environment.
## Available Tools
The server provides tools for managing workflows and executions:
- [Workflow Tools](./workflow-tools.md): Create, list, update, and delete workflows
- [Execution Tools](./execution-tools.md): Execute workflows and manage workflow executions
## Available Resources
The server provides resources for accessing workflow and execution data:
- [Static Resources](./static-resources.md): Fixed resources like workflow listings or execution statistics
- [Dynamic Resources](./dynamic-resources.md): Parameterized resources for specific workflows or executions
## Understanding Input Schemas
Each tool has an input schema that defines the expected parameters. These schemas follow the JSON Schema format and are automatically provided to AI assistants to enable proper parameter validation and suggestion.
Example input schema for the `workflow_get` tool:
```json
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "The ID of the workflow to retrieve"
}
},
"required": ["id"]
}
```
## Error Handling
All API operations can return errors in a standardized format. Common error scenarios include:
- Authentication failures (invalid or missing API key)
- Resource not found (workflow or execution doesn't exist)
- Permission issues (API key doesn't have required permissions)
- Input validation errors (missing or invalid parameters)
Error responses include detailed messages to help troubleshoot issues.
## Next Steps
Explore the detailed documentation for each category:
- [Workflow Tools](./workflow-tools.md)
- [Execution Tools](./execution-tools.md)
- [Static Resources](./static-resources.md)
- [Dynamic Resources](./dynamic-resources.md)

View File

@@ -0,0 +1,154 @@
# Static Resources
This page documents the static resources available in the n8n MCP Server.
## Overview
Static resources provide access to fixed n8n data sources without requiring parameters in the URI. These resources are ideal for retrieving collections of data or summary information.
## Available Resources
### n8n://workflows/list
Provides a list of all workflows in the n8n instance.
**URI:** `n8n://workflows/list`
**Description:** Returns a comprehensive list of all workflows with their basic metadata.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://workflows/list');
```
**Response:**
```javascript
{
"workflows": [
{
"id": "1234abc",
"name": "Email Processing Workflow",
"active": true,
"createdAt": "2025-03-01T12:00:00.000Z",
"updatedAt": "2025-03-02T14:30:00.000Z"
},
{
"id": "5678def",
"name": "Data Sync Workflow",
"active": false,
"createdAt": "2025-03-01T12:00:00.000Z",
"updatedAt": "2025-03-12T10:15:00.000Z"
}
],
"count": 2,
"pagination": {
"hasMore": false
}
}
```
### n8n://execution-stats
Provides aggregated statistics about workflow executions.
**URI:** `n8n://execution-stats`
**Description:** Returns summary statistics about workflow executions, including counts by status, average execution times, and recent trends.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://execution-stats');
```
**Response:**
```javascript
{
"totalExecutions": 1250,
"statusCounts": {
"success": 1050,
"error": 180,
"cancelled": 20
},
"averageExecutionTime": 3.5, // seconds
"recentActivity": {
"last24Hours": 125,
"last7Days": 450
},
"topWorkflows": [
{
"id": "1234abc",
"name": "Email Processing Workflow",
"executionCount": 256
},
{
"id": "5678def",
"name": "Data Sync Workflow",
"executionCount": 198
}
]
}
```
### n8n://health
Provides health information about the n8n instance.
**URI:** `n8n://health`
**Description:** Returns health status information about the n8n instance including connection status, version, and basic metrics.
**Example Usage:**
```javascript
const resource = await accessMcpResource('n8n-mcp-server', 'n8n://health');
```
**Response:**
```javascript
{
"status": "healthy",
"n8nVersion": "1.5.0",
"uptime": 259200, // seconds (3 days)
"databaseStatus": "connected",
"apiStatus": "operational",
"memoryUsage": {
"rss": "156MB",
"heapTotal": "85MB",
"heapUsed": "72MB"
}
}
```
## Content Types
All static resources return JSON content with the MIME type `application/json`.
## Authentication
Access to static resources requires the same authentication as tools, using the configured n8n API key. If authentication fails, the resource will return an error.
## Error Handling
Static resources can return the following errors:
| HTTP Status | Description |
|-------------|-------------|
| 401 | Unauthorized - Invalid or missing API key |
| 403 | Forbidden - API key does not have permission to access this resource |
| 500 | Internal Server Error - An unexpected error occurred on the n8n server |
## Pagination
Some resources that return large collections (like `n8n://workflows/list`) support pagination. The response includes a `pagination` object with information about whether more results are available.
## Best Practices
- Use static resources for getting an overview of what's available in the n8n instance
- Prefer static resources over tools when you only need to read data
- Check the health resource before performing operations to ensure the n8n instance is operational
- Use execution statistics to monitor the performance and reliability of your workflows

375
docs/api/workflow-tools.md Normal file
View File

@@ -0,0 +1,375 @@
# Workflow Tools
This page documents the tools available for managing n8n workflows.
## Overview
Workflow tools allow AI assistants to manage n8n workflows, including creating, retrieving, updating, deleting, activating, and deactivating workflows. These tools provide a natural language interface to n8n's workflow management capabilities.
## Available Tools
### workflow_list
Lists all workflows with optional filtering.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"active": {
"type": "boolean",
"description": "Filter workflows by active status"
}
},
"required": []
}
```
**Example Usage:**
```javascript
// List all workflows
const result = await useWorkflowList({});
// List only active workflows
const activeWorkflows = await useWorkflowList({ active: true });
// List only inactive workflows
const inactiveWorkflows = await useWorkflowList({ active: false });
```
**Response:**
```javascript
[
{
"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"
}
]
```
### workflow_get
Retrieves a specific workflow by ID.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "The ID of the workflow to retrieve"
}
},
"required": ["id"]
}
```
**Example Usage:**
```javascript
const workflow = await useWorkflowGet({ id: "1234abc" });
```
**Response:**
```javascript
{
"id": "1234abc",
"name": "Test Workflow 1",
"active": true,
"createdAt": "2025-03-01T12:00:00.000Z",
"updatedAt": "2025-03-02T14:30:00.000Z",
"nodes": [
// Detailed node configuration
],
"connections": {
// Connection configuration
},
"settings": {
// Workflow settings
}
}
```
### workflow_create
Creates a new workflow.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the workflow"
},
"nodes": {
"type": "array",
"description": "Array of node configurations"
},
"connections": {
"type": "object",
"description": "Connection configuration"
},
"active": {
"type": "boolean",
"description": "Whether the workflow should be active"
},
"settings": {
"type": "object",
"description": "Workflow settings"
}
},
"required": ["name"]
}
```
**Example Usage:**
```javascript
const newWorkflow = await useWorkflowCreate({
name: "New Workflow",
active: true,
nodes: [
{
"name": "Start",
"type": "n8n-nodes-base.start",
"position": [100, 200],
"parameters": {}
}
],
connections: {}
});
```
**Response:**
```javascript
{
"id": "new123",
"name": "New Workflow",
"active": true,
"createdAt": "2025-03-12T15:30:00.000Z",
"updatedAt": "2025-03-12T15:30:00.000Z",
"nodes": [
{
"name": "Start",
"type": "n8n-nodes-base.start",
"position": [100, 200],
"parameters": {}
}
],
"connections": {}
}
```
### workflow_update
Updates an existing workflow.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "ID of the workflow to update"
},
"name": {
"type": "string",
"description": "New name for the workflow"
},
"nodes": {
"type": "array",
"description": "Updated array of node configurations"
},
"connections": {
"type": "object",
"description": "Updated connection configuration"
},
"active": {
"type": "boolean",
"description": "Whether the workflow should be active"
},
"settings": {
"type": "object",
"description": "Updated workflow settings"
}
},
"required": ["id"]
}
```
**Example Usage:**
```javascript
const updatedWorkflow = await useWorkflowUpdate({
id: "1234abc",
name: "Updated Workflow Name",
active: false
});
```
**Response:**
```javascript
{
"id": "1234abc",
"name": "Updated Workflow Name",
"active": false,
"createdAt": "2025-03-01T12:00:00.000Z",
"updatedAt": "2025-03-12T15:45:00.000Z",
"nodes": [
// Existing node configuration
],
"connections": {
// Existing connection configuration
}
}
```
### workflow_delete
Deletes a workflow.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "ID of the workflow to delete"
}
},
"required": ["id"]
}
```
**Example Usage:**
```javascript
await useWorkflowDelete({ id: "1234abc" });
```
**Response:**
```javascript
{
"success": true
}
```
### workflow_activate
Activates a workflow.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "ID of the workflow to activate"
}
},
"required": ["id"]
}
```
**Example Usage:**
```javascript
const activatedWorkflow = await useWorkflowActivate({ id: "1234abc" });
```
**Response:**
```javascript
{
"id": "1234abc",
"name": "Test Workflow 1",
"active": true,
"createdAt": "2025-03-01T12:00:00.000Z",
"updatedAt": "2025-03-12T16:00:00.000Z"
}
```
### workflow_deactivate
Deactivates a workflow.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "ID of the workflow to deactivate"
}
},
"required": ["id"]
}
```
**Example Usage:**
```javascript
const deactivatedWorkflow = await useWorkflowDeactivate({ id: "1234abc" });
```
**Response:**
```javascript
{
"id": "1234abc",
"name": "Test Workflow 1",
"active": false,
"createdAt": "2025-03-01T12:00:00.000Z",
"updatedAt": "2025-03-12T16:15:00.000Z"
}
```
## Error Handling
All workflow tools can return the following errors:
| Error | Description |
|-------|-------------|
| Authentication Error | The provided API key is invalid or missing |
| Not Found Error | The requested workflow does not exist |
| Validation Error | The input parameters are invalid or incomplete |
| Permission Error | The API key does not have permission to perform the operation |
| Server Error | An unexpected error occurred on the n8n server |
## Best Practices
- Use `workflow_list` to discover available workflows before performing operations
- Validate workflow IDs before attempting to update or delete workflows
- Check workflow status (active/inactive) before attempting activation/deactivation
- Include only the necessary fields when updating workflows to avoid unintended changes

View File

@@ -0,0 +1,158 @@
# Architecture
This document describes the architectural design of the n8n MCP Server.
## Overview
The n8n MCP Server follows a layered architecture pattern that separates concerns and promotes maintainability. The main architectural layers are:
1. **Transport Layer**: Handles communication with AI assistants via the Model Context Protocol
2. **API Client Layer**: Interacts with the n8n API
3. **Tools Layer**: Implements executable operations as MCP tools
4. **Resources Layer**: Provides data access through URI-based resources
5. **Configuration Layer**: Manages environment variables and server settings
6. **Error Handling Layer**: Provides consistent error management and reporting
## System Components
![Architecture Diagram](../images/architecture.png.placeholder)
### Entry Point
The server entry point is defined in `src/index.ts`. This file:
1. Initializes the configuration from environment variables
2. Creates and configures the MCP server instance
3. Registers tool and resource handlers
4. Connects to the transport layer (typically stdio)
### Configuration
The configuration layer (`src/config/`) handles:
- Loading environment variables
- Validating required configuration
- Providing typed access to configuration values
The main configuration component is the `Environment` class, which validates and manages environment variables like `N8N_API_URL` and `N8N_API_KEY`.
### API Client
The API client layer (`src/api/`) provides a clean interface for interacting with the n8n API. It includes:
- `N8nClient`: The main client that encapsulates communication with n8n
- API-specific functionality divided by resource type (workflows, executions)
- Authentication handling using the n8n API key
The client uses Axios for HTTP requests and includes error handling specific to the n8n API responses.
### MCP Tools
The tools layer (`src/tools/`) implements the executable operations exposed to AI assistants. Each tool follows a common pattern:
1. A tool definition that specifies name, description, and input schema
2. A handler function that processes input parameters and executes the operation
3. Error handling for validation and execution errors
Tools are categorized by resource type:
- Workflow tools: Create, list, update, delete, activate, and deactivate workflows
- Execution tools: Run, list, and manage workflow executions
Each tool is designed to be independently testable and maintains a clean separation of concerns.
### MCP Resources
The resources layer (`src/resources/`) provides data access through URI-based templates. Resources are divided into two categories:
1. **Static Resources** (`src/resources/static/`): Fixed resources like workflow listings
2. **Dynamic Resources** (`src/resources/dynamic/`): Parameterized resources like specific workflow details
Each resource implements:
- URI pattern matching
- Content retrieval
- Error handling
- Response formatting
### Error Handling
The error handling layer (`src/errors/`) provides consistent error management across the server. It includes:
- Custom error types that map to MCP error codes
- Error translation functions to convert n8n API errors to MCP errors
- Common error patterns and handling strategies
## Data Flow
A typical data flow through the system:
1. AI assistant sends a request via stdin to the MCP server
2. Server routes the request to the appropriate handler based on the request type
3. Handler validates input and delegates to the appropriate tool or resource
4. Tool/resource uses the n8n API client to interact with n8n
5. Response is processed, formatted, and returned via stdout
6. AI assistant receives and processes the response
## Key Design Principles
### 1. Separation of Concerns
Each component has a single responsibility, making the codebase easier to understand, test, and extend.
### 2. Type Safety
TypeScript interfaces and types are used extensively to ensure type safety and provide better developer experience.
### 3. Error Handling
Comprehensive error handling ensures that errors are caught at the appropriate level and translated into meaningful messages for AI assistants.
### 4. Testability
The architecture supports unit testing by keeping components loosely coupled and maintaining clear boundaries between layers.
### 5. Extensibility
New tools and resources can be added without modifying existing code, following the open-closed principle.
## Implementation Patterns
### Factory Pattern
Used for creating client instances and tool handlers based on configuration.
### Adapter Pattern
The n8n API client adapts the n8n API to the internal representation used by the server.
### Strategy Pattern
Different resource handlers implement a common interface but provide different strategies for retrieving and formatting data.
### Decorator Pattern
Used to add cross-cutting concerns like logging and error handling to base functionality.
## Core Files and Their Purposes
| File | Purpose |
|------|---------|
| `src/index.ts` | Main entry point, initializes and configures the server |
| `src/config/environment.ts` | Manages environment variables and configuration |
| `src/api/n8n-client.ts` | Main client for interacting with the n8n API |
| `src/tools/workflow/handler.ts` | Handles workflow-related tool requests |
| `src/tools/execution/handler.ts` | Handles execution-related tool requests |
| `src/resources/index.ts` | Registers and manages resource handlers |
| `src/resources/dynamic/workflow.ts` | Provides access to specific workflow resources |
| `src/resources/static/workflows.ts` | Provides access to workflow listings |
| `src/errors/index.ts` | Defines and manages error types and handling |
## Extension Points
To extend the server with new capabilities:
1. **Adding a new tool**: Create a new handler in the appropriate category under `src/tools/` and register it in the main server setup
2. **Adding a new resource**: Create a new resource handler in `src/resources/` and register it in the resource manager
3. **Supporting new n8n API features**: Extend the API client in `src/api/` to support new API endpoints or features
For detailed instructions on extending the server, see [Extending the Server](./extending.md).

View File

@@ -0,0 +1,653 @@
# Extending the Server
This guide explains how to extend the n8n MCP Server with new functionality.
## Overview
The n8n MCP Server is designed to be extensible, allowing developers to add new tools and resources without modifying existing code. This extensibility makes it easy to support new n8n features or customize the server for specific use cases.
## Adding a New Tool
Tools in the MCP server represent executable operations that AI assistants can use. To add a new tool, follow these steps:
### 1. Define the Tool Interface
Create a new TypeScript interface that defines the input parameters for your tool:
```typescript
// src/types/tools/my-tool.ts
export interface MyToolParams {
param1: string;
param2?: number; // Optional parameter
}
```
### 2. Create the Tool Handler
Create a new file for your tool in the appropriate category under `src/tools/`:
```typescript
// src/tools/category/my-tool.ts
import { ToolCallResponse, ToolDefinition } from '@modelcontextprotocol/sdk/types.js';
import { N8nClient } from '../../api/n8n-client.js';
import { MyToolParams } from '../../types/tools/my-tool.js';
// Define the tool
export function getMyToolDefinition(): ToolDefinition {
return {
name: 'my_tool',
description: 'Description of what my tool does',
inputSchema: {
type: 'object',
properties: {
param1: {
type: 'string',
description: 'Description of param1'
},
param2: {
type: 'number',
description: 'Description of param2'
}
},
required: ['param1']
}
};
}
// Implement the tool handler
export async function handleMyTool(
client: N8nClient,
params: MyToolParams
): Promise<ToolCallResponse> {
try {
// Implement the tool logic here
// Use the N8nClient to interact with n8n
// Return the response
return {
content: [
{
type: 'text',
text: 'Result of the operation'
}
]
};
} catch (error) {
// Handle errors
return {
content: [
{
type: 'text',
text: `Error: ${error.message}`
}
],
isError: true
};
}
}
```
### 3. Register the Tool in the Handler
Update the main handler file for your tool category (e.g., `src/tools/category/handler.ts`):
```typescript
// src/tools/category/handler.ts
import { getMyToolDefinition, handleMyTool } from './my-tool.js';
// Add your tool to the tools object
export const categoryTools = {
// ... existing tools
my_tool: {
definition: getMyToolDefinition,
handler: handleMyTool
}
};
```
### 4. Add Handler to Main Server
Update the main tool handler registration in `src/index.ts`:
```typescript
// src/index.ts
import { categoryTools } from './tools/category/handler.js';
// In the server initialization
const server = new Server(
{
name: 'n8n-mcp-server',
version: '0.1.0'
},
{
capabilities: {
tools: {
// ... existing categories
category: true
}
}
}
);
// Register tool handlers
Object.entries(categoryTools).forEach(([name, { definition, handler }]) => {
server.setToolHandler(definition(), async (request) => {
return await handler(client, request.params.arguments as any);
});
});
```
### 5. Add Unit Tests
Create unit tests for your new tool:
```typescript
// tests/unit/tools/category/my-tool.test.ts
import { describe, it, expect, jest } from '@jest/globals';
import { getMyToolDefinition, handleMyTool } from '../../../../src/tools/category/my-tool.js';
describe('My Tool', () => {
describe('getMyToolDefinition', () => {
it('should return the correct tool definition', () => {
const definition = getMyToolDefinition();
expect(definition.name).toBe('my_tool');
expect(definition.description).toBeTruthy();
expect(definition.inputSchema).toBeDefined();
expect(definition.inputSchema.properties).toHaveProperty('param1');
expect(definition.inputSchema.required).toEqual(['param1']);
});
});
describe('handleMyTool', () => {
it('should handle valid parameters', async () => {
const mockClient = {
// Mock the necessary client methods
};
const result = await handleMyTool(mockClient as any, {
param1: 'test value'
});
expect(result.isError).toBeFalsy();
expect(result.content[0].text).toBeTruthy();
});
it('should handle errors properly', async () => {
const mockClient = {
// Mock client that throws an error
someMethod: jest.fn().mockRejectedValue(new Error('Test error'))
};
const result = await handleMyTool(mockClient as any, {
param1: 'test value'
});
expect(result.isError).toBeTruthy();
expect(result.content[0].text).toContain('Error');
});
});
});
```
## Adding a New Resource
Resources in the MCP server provide data access through URI-based templates. To add a new resource, follow these steps:
### 1. Create a Static Resource (No Parameters)
For a resource that doesn't require parameters:
```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<ReadResourceResponse> {
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}`
);
}
}
```
### 2. Create a Dynamic Resource (With Parameters)
For a resource that requires parameters:
```typescript
// src/resources/dynamic/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_TEMPLATE = 'n8n://my-resource/{id}';
export function matchMyResourceUri(uri: string): { id: string } | null {
const match = uri.match(/^n8n:\/\/my-resource\/([^/]+)$/);
if (!match) return null;
return {
id: decodeURIComponent(match[1])
};
}
export async function handleMyResourceRequest(
client: N8nClient,
uri: string
): Promise<ReadResourceResponse> {
const params = matchMyResourceUri(uri);
if (!params) {
throw new McpError(
ErrorCode.InvalidRequest,
`Invalid URI format: ${uri}`
);
}
try {
// Implement the resource logic using params.id
// Use the N8nClient to interact with n8n
// Return the response
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify(
{
// Resource data with the specific ID
id: params.id,
property1: 'value1',
property2: 'value2'
},
null,
2
)
}
]
};
} catch (error) {
throw new McpError(
ErrorCode.InternalError,
`Failed to retrieve resource: ${error.message}`
);
}
}
```
### 3. Register Resources in the Handler Files
Update the resource handler registration:
#### For Static Resources
```typescript
// src/resources/static/index.ts
import { MY_RESOURCE_URI, handleMyResourceRequest } from './my-resource.js';
export const staticResources = {
// ... existing static resources
[MY_RESOURCE_URI]: handleMyResourceRequest
};
```
#### For Dynamic Resources
```typescript
// src/resources/dynamic/index.ts
import { MY_RESOURCE_URI_TEMPLATE, matchMyResourceUri, handleMyResourceRequest } from './my-resource.js';
export const dynamicResourceMatchers = [
// ... existing dynamic resource matchers
{
uriTemplate: MY_RESOURCE_URI_TEMPLATE,
match: matchMyResourceUri,
handler: handleMyResourceRequest
}
];
```
### 4. Add Resource Listings
Update the resource listing functions:
```typescript
// src/resources/index.ts
// Update the resource templates listing
export function getResourceTemplates() {
return [
// ... existing templates
{
uriTemplate: MY_RESOURCE_URI_TEMPLATE,
name: 'My Resource',
description: 'Description of my resource'
}
];
}
// Update the static resources listing
export function getStaticResources() {
return [
// ... existing resources
{
uri: MY_RESOURCE_URI,
name: 'My Resource List',
description: 'List of all my resources'
}
];
}
```
### 5. Add Unit Tests
Create tests for your new resource:
```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');
});
});
```
## Extending the API Client
If you need to add support for new n8n API features, extend the N8nClient class:
### 1. Add New Methods to the Client
```typescript
// src/api/n8n-client.ts
export class N8nClient {
// ... existing methods
// Add new methods
async myNewApiMethod(param1: string): Promise<any> {
try {
const response = await this.httpClient.get(`/endpoint/${param1}`);
return response.data;
} catch (error) {
this.handleApiError(error);
}
}
}
```
### 2. Add Type Definitions
```typescript
// src/types/api.ts
// Add types for API responses and requests
export interface MyApiResponse {
id: string;
name: string;
// Other properties
}
export interface MyApiRequest {
param1: string;
param2?: number;
}
```
### 3. Add Tests for the New API Methods
```typescript
// tests/unit/api/n8n-client.test.ts
describe('N8nClient', () => {
// ... existing tests
describe('myNewApiMethod', () => {
it('should call the correct API endpoint', async () => {
// Set up mock Axios
axiosMock.onGet('/endpoint/test').reply(200, {
id: '123',
name: 'Test'
});
const client = new N8nClient({
apiUrl: 'http://localhost:5678/api/v1',
apiKey: 'test-api-key'
});
const result = await client.myNewApiMethod('test');
expect(result).toEqual({
id: '123',
name: 'Test'
});
});
it('should handle errors correctly', async () => {
// Set up mock Axios
axiosMock.onGet('/endpoint/test').reply(404, {
message: 'Not found'
});
const client = new N8nClient({
apiUrl: 'http://localhost:5678/api/v1',
apiKey: 'test-api-key'
});
await expect(client.myNewApiMethod('test'))
.rejects
.toThrow('Resource not found');
});
});
});
```
## Best Practices for Extensions
1. **Follow the Existing Patterns**: Try to follow the patterns already established in the codebase.
2. **Type Safety**: Use TypeScript types and interfaces to ensure type safety.
3. **Error Handling**: Implement comprehensive error handling in all extensions.
4. **Testing**: Write thorough tests for all new functionality.
5. **Documentation**: Document your extensions, including JSDoc comments for all public methods.
6. **Backward Compatibility**: Ensure that your extensions don't break existing functionality.
## Example: Adding Support for n8n Tags
Here's a complete example of adding support for n8n tags:
### API Client Extension
```typescript
// src/api/n8n-client.ts
export class N8nClient {
// ... existing methods
// Add tag methods
async getTags(): Promise<Tag[]> {
try {
const response = await this.httpClient.get('/tags');
return response.data;
} catch (error) {
this.handleApiError(error);
}
}
async createTag(data: CreateTagRequest): Promise<Tag> {
try {
const response = await this.httpClient.post('/tags', data);
return response.data;
} catch (error) {
this.handleApiError(error);
}
}
async deleteTag(id: string): Promise<void> {
try {
await this.httpClient.delete(`/tags/${id}`);
} catch (error) {
this.handleApiError(error);
}
}
}
```
### Type Definitions
```typescript
// src/types/api.ts
export interface Tag {
id: string;
name: string;
createdAt: string;
updatedAt: string;
}
export interface CreateTagRequest {
name: string;
}
```
### Tool Implementations
```typescript
// src/tools/tag/list.ts
export function getTagListToolDefinition(): ToolDefinition {
return {
name: 'tag_list',
description: 'List all tags in n8n',
inputSchema: {
type: 'object',
properties: {},
required: []
}
};
}
export async function handleTagList(
client: N8nClient,
params: any
): Promise<ToolCallResponse> {
try {
const tags = await client.getTags();
return {
content: [
{
type: 'text',
text: JSON.stringify(tags, null, 2)
}
]
};
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error listing tags: ${error.message}`
}
],
isError: true
};
}
}
```
### Resource Implementation
```typescript
// src/resources/static/tags.ts
export const TAGS_URI = 'n8n://tags';
export async function handleTagsRequest(
client: N8nClient
): Promise<ReadResourceResponse> {
try {
const tags = await client.getTags();
return {
contents: [
{
uri: TAGS_URI,
mimeType: 'application/json',
text: JSON.stringify(
{
tags,
count: tags.length
},
null,
2
)
}
]
};
} catch (error) {
throw new McpError(
ErrorCode.InternalError,
`Failed to retrieve tags: ${error.message}`
);
}
}
```
### Integration
Register the new tools and resources in the appropriate handler files, and update the main server initialization to include them.
By following these patterns, you can extend the n8n MCP Server to support any n8n feature or add custom functionality tailored to your specific needs.

85
docs/development/index.md Normal file
View File

@@ -0,0 +1,85 @@
# Development Guide
This section provides information for developers who want to understand, maintain, or extend the n8n MCP Server.
## Overview
The n8n MCP Server is built with TypeScript and implements the Model Context Protocol (MCP) to provide AI assistants with access to n8n workflows and executions. This development guide covers the architecture, extension points, and testing procedures.
## Topics
- [Architecture](./architecture.md): Overview of the codebase organization and design patterns
- [Extending the Server](./extending.md): Guide to adding new tools and resources
- [Testing](./testing.md): Information on testing procedures and writing tests
## Development Setup
To set up a development environment:
1. Clone the repository:
```bash
git clone https://github.com/yourusername/n8n-mcp-server.git
cd n8n-mcp-server
```
2. Install dependencies:
```bash
npm install
```
3. Create a `.env` file for local development:
```bash
cp .env.example .env
# Edit the .env file with your n8n API credentials
```
4. Start the development server:
```bash
npm run dev
```
This will compile the TypeScript code in watch mode, allowing you to make changes and see them take effect immediately.
## Project Structure
The project follows a modular structure:
```
n8n-mcp-server/
├── src/ # Source code
│ ├── api/ # API client for n8n
│ ├── config/ # Configuration and environment settings
│ ├── errors/ # Error handling
│ ├── resources/ # MCP resources implementation
│ │ ├── static/ # Static resources
│ │ └── dynamic/ # Dynamic (parameterized) resources
│ ├── tools/ # MCP tools implementation
│ │ ├── workflow/ # Workflow management tools
│ │ └── execution/ # Execution management tools
│ ├── types/ # TypeScript type definitions
│ └── utils/ # Utility functions
├── tests/ # Test files
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
└── build/ # Compiled output
```
## Build and Distribution
To build the project for distribution:
```bash
npm run build
```
This will compile the TypeScript code to JavaScript in the `build` directory and make the executable script file.
## Development Workflow
1. Create a feature branch for your changes
2. Make your changes and ensure tests pass
3. Update documentation as needed
4. Submit a pull request
For more detailed instructions on specific development tasks, see the linked guides.

486
docs/development/testing.md Normal file
View File

@@ -0,0 +1,486 @@
# Testing
This document describes the testing approach for the n8n MCP Server and provides guidelines for writing effective tests.
## Overview
The n8n MCP Server uses Jest as its testing framework and follows a multi-level testing approach:
1. **Unit Tests**: Test individual components in isolation
2. **Integration Tests**: Test interactions between components
3. **End-to-End Tests**: Test the entire system as a whole
Tests are organized in the `tests/` directory, with a structure that mirrors the `src/` directory.
## Running Tests
### Running All Tests
To run all tests:
```bash
npm test
```
This command runs all tests and outputs a summary of the results.
### Running Tests with Coverage
To run tests with coverage reporting:
```bash
npm run test:coverage
```
This generates coverage reports in the `coverage/` directory, including HTML reports that you can view in a browser.
### Running Tests in Watch Mode
During development, you can run tests in watch mode, which will automatically rerun tests when files change:
```bash
npm run test:watch
```
### Running Specific Tests
To run tests in a specific file or directory:
```bash
npx jest path/to/test-file.test.ts
```
Or to run tests matching a specific pattern:
```bash
npx jest -t "test pattern"
```
## Test Structure
Tests are organized into the following directories:
- `tests/unit/`: Unit tests for individual components
- `tests/integration/`: Integration tests that test interactions between components
- `tests/e2e/`: End-to-end tests that test the entire system
- `tests/mocks/`: Shared test fixtures and mocks
### Unit Tests
Unit tests are organized in a structure that mirrors the `src/` directory. For example:
- `src/api/n8n-client.ts` has a corresponding test at `tests/unit/api/n8n-client.test.ts`
- `src/tools/workflow/list.ts` has a corresponding test at `tests/unit/tools/workflow/list.test.ts`
### Integration Tests
Integration tests focus on testing interactions between components, such as:
- Testing that tools correctly use the API client
- Testing that resources correctly format data from the API
### End-to-End Tests
End-to-end tests test the entire system, from the transport layer to the API client and back.
## Writing Effective Tests
### Unit Test Example
Here's an example of a unit test for a workflow tool:
```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');
});
});
});
```
### Integration Test Example
Here's an example of an integration test that tests the interaction between a resource handler and the API client:
```typescript
// tests/integration/resources/static/workflows.test.ts
import { describe, it, expect, jest } from '@jest/globals';
import { handleWorkflowsRequest, WORKFLOWS_URI } from '../../../../src/resources/static/workflows.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('Workflows Resource Handler', () => {
it('should return a properly formatted response', async () => {
// Mock the API client
const mockClient = {
getWorkflows: jest.fn().mockResolvedValue(mockWorkflows)
};
const response = await handleWorkflowsRequest(mockClient as unknown as N8nClient);
expect(mockClient.getWorkflows).toHaveBeenCalled();
expect(response.contents).toHaveLength(1);
expect(response.contents[0].uri).toBe(WORKFLOWS_URI);
expect(response.contents[0].mimeType).toBe('application/json');
// Parse the JSON text to check the content
const content = JSON.parse(response.contents[0].text);
expect(content).toHaveProperty('workflows');
expect(content.workflows).toHaveLength(2);
expect(content.count).toBe(2);
expect(content.workflows[0].id).toBe('1234abc');
});
it('should handle API errors', async () => {
// Mock the API client to throw an error
const mockClient = {
getWorkflows: jest.fn().mockRejectedValue(new Error('API error'))
};
await expect(handleWorkflowsRequest(mockClient as unknown as N8nClient))
.rejects
.toThrow('Failed to retrieve workflows');
});
});
```
### End-to-End Test Example
Here's an example of an end-to-end test that tests the entire system:
```typescript
// tests/e2e/workflow-operations.test.ts
import { describe, it, expect, beforeAll, afterAll } from '@jest/globals';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { MemoryServerTransport } from '@modelcontextprotocol/sdk/server/memory.js';
import { createServer } from '../../src/index.js';
describe('End-to-End Workflow Operations', () => {
let server: Server;
let transport: MemoryServerTransport;
beforeAll(async () => {
// Mock the environment
process.env.N8N_API_URL = 'http://localhost:5678/api/v1';
process.env.N8N_API_KEY = 'test-api-key';
// Create the server with a memory transport
transport = new MemoryServerTransport();
server = await createServer(transport);
});
afterAll(async () => {
await server.close();
});
it('should list workflows', async () => {
// Send a request to list workflows
const response = await transport.sendRequest({
jsonrpc: '2.0',
id: '1',
method: 'callTool',
params: {
name: 'workflow_list',
arguments: {}
}
});
expect(response.result).toBeDefined();
expect(response.result.content).toHaveLength(1);
expect(response.result.content[0].type).toBe('text');
// Parse the JSON text to check the content
const content = JSON.parse(response.result.content[0].text);
expect(Array.isArray(content)).toBe(true);
});
it('should retrieve a workflow by ID', async () => {
// Send a request to get a workflow
const response = await transport.sendRequest({
jsonrpc: '2.0',
id: '2',
method: 'callTool',
params: {
name: 'workflow_get',
arguments: {
id: '1234abc'
}
}
});
expect(response.result).toBeDefined();
expect(response.result.content).toHaveLength(1);
expect(response.result.content[0].type).toBe('text');
// Parse the JSON text to check the content
const content = JSON.parse(response.result.content[0].text);
expect(content).toHaveProperty('id');
expect(content.id).toBe('1234abc');
});
});
```
## Test Fixtures and Mocks
To avoid duplication and improve test maintainability, common test fixtures and mocks are stored in the `tests/mocks/` directory.
### Axios Mock
The Axios HTTP client is mocked using `axios-mock-adapter` to simulate HTTP responses without making actual API calls:
```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();
}
```
### n8n API Fixtures
Common fixtures for n8n API responses are stored in a shared file:
```typescript
// tests/mocks/n8n-fixtures.ts
export const mockWorkflows = [
{
id: '1234abc',
name: 'Test Workflow 1',
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: {}
}
],
connections: {}
},
{
id: '5678def',
name: 'Test Workflow 2',
active: false,
createdAt: '2025-03-01T12:00:00.000Z',
updatedAt: '2025-03-12T10:15:00.000Z',
nodes: [],
connections: {}
}
];
export const mockExecutions = [
{
id: 'exec123',
workflowId: '1234abc',
workflowName: 'Test Workflow 1',
status: 'success',
startedAt: '2025-03-10T15:00:00.000Z',
finishedAt: '2025-03-10T15:01:00.000Z',
mode: 'manual'
},
{
id: 'exec456',
workflowId: '1234abc',
workflowName: 'Test Workflow 1',
status: 'error',
startedAt: '2025-03-09T12:00:00.000Z',
finishedAt: '2025-03-09T12:00:10.000Z',
mode: 'manual'
}
];
```
## Test Environment
The test environment is configured in `jest.config.js` and `babel.config.js`. Key configurations include:
- TypeScript support via Babel
- ES module support
- Coverage reporting
The `tests/test-setup.ts` file contains global setup code that runs before tests:
```typescript
// tests/test-setup.ts
import { jest } from '@jest/globals';
import { resetAxiosMock } from './mocks/axios-mock';
// Reset mocks before each test
beforeEach(() => {
jest.clearAllMocks();
resetAxiosMock();
});
```
## Best Practices
### General Testing Guidelines
1. **Write tests first**: Follow a test-driven development (TDD) approach when possible.
2. **Test behavior, not implementation**: Focus on what a component does, not how it's implemented.
3. **Keep tests simple**: Each test should test one behavior or aspect of functionality.
4. **Use descriptive test names**: Test names should describe the expected behavior.
5. **Follow the AAA pattern**: Arrange, Act, Assert (setup, execute, verify).
### Mocking Best Practices
1. **Mock dependencies, not the unit under test**: Only mock external dependencies, not the code you're testing.
2. **Use the minimum viable mock**: Only mock the methods and behavior needed for the test.
3. **Ensure mock behavior is realistic**: Mocks should behave similarly to the real implementation.
4. **Verify interactions with mocks**: Use `expect(mock).toHaveBeenCalled()` to verify interactions.
### Error Testing Best Practices
1. **Test error cases**: Don't just test the happy path; test error handling too.
2. **Simulate errors with mocks**: Use mocks to simulate error scenarios.
3. **Verify error messages**: Ensure error messages are helpful and descriptive.
### Performance Testing Considerations
1. **Monitor test performance**: Slow tests can slow down development.
2. **Use test timeout values wisely**: Set appropriate timeout values for async tests.
3. **Minimize redundant setup**: Use `beforeEach` and `beforeAll` to avoid redundant setup.
## Continuous Integration
Tests are run automatically in CI environments on pull requests and commits to the main branch. The CI configuration ensures tests pass before code can be merged.
### CI Test Requirements
- All tests must pass
- Test coverage must not decrease
- Linting checks must pass
## Debugging Tests
### Console Output
You can use `console.log()` statements in your tests to debug issues:
```typescript
it('should do something', () => {
const result = doSomething();
console.log('Result:', result);
expect(result).toBe(expectedValue);
});
```
When running tests with Jest, console output will be displayed for failing tests by default.
### Using the Debugger
You can also use the Node.js debugger with Jest:
```bash
node --inspect-brk node_modules/.bin/jest --runInBand path/to/test
```
Then connect to the debugger with Chrome DevTools or VS Code.
## Conclusion
Thorough testing is essential for maintaining a reliable and robust n8n MCP Server. By following these guidelines and examples, you can write effective tests that help ensure your code works as expected and catches issues early.

View File

@@ -0,0 +1,617 @@
# Advanced Scenarios
This page demonstrates more complex examples of using the n8n MCP Server with AI assistants.
## Workflow Analysis and Optimization
### User Prompt
"Analyze my workflows and suggest optimizations."
### Assistant Actions
```javascript
// Get all workflows
const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {});
// Get execution statistics
const stats = await accessMcpResource('n8n-mcp-server', 'n8n://execution-stats');
// Analyze each workflow in detail
const analysisResults = [];
for (const workflow of workflows) {
// Get detailed workflow information
const details = await useMcpTool('n8n-mcp-server', 'workflow_get', {
id: workflow.id
});
// Get recent executions
const executions = await useMcpTool('n8n-mcp-server', 'execution_list', {
workflowId: workflow.id,
limit: 10
});
// Analyze workflow structure
const nodeCount = details.nodes.length;
const nodeTypes = new Set(details.nodes.map(node => node.type));
// Check for error patterns in executions
const errorRate = executions.length > 0
? executions.filter(e => e.status === "error").length / executions.length
: 0;
// Check execution times
const executionTimes = executions
.filter(e => e.status === "success" && e.finishedAt && e.startedAt)
.map(e => new Date(e.finishedAt) - new Date(e.startedAt));
const avgExecutionTime = executionTimes.length > 0
? executionTimes.reduce((sum, time) => sum + time, 0) / executionTimes.length / 1000
: 0;
// Generate optimization suggestions
const suggestions = [];
if (nodeCount > 15) {
suggestions.push("Consider splitting into multiple workflows for better maintainability");
}
if (errorRate > 0.2) {
suggestions.push("High error rate detected - review error handling and input validation");
}
if (avgExecutionTime > 30) {
suggestions.push("Long execution time - check for bottlenecks or inefficient operations");
}
if (nodeTypes.has("n8n-nodes-base.httpRequest") && !nodeTypes.has("n8n-nodes-base.errorTrigger")) {
suggestions.push("HTTP requests without error handling - consider adding error triggers");
}
analysisResults.push({
id: workflow.id,
name: workflow.name,
nodeCount,
errorRate,
avgExecutionTime,
suggestions
});
}
// Format and present the analysis
let response = "# Workflow Analysis and Optimization Suggestions\n\n";
analysisResults.forEach(result => {
response += `## ${result.name}\n\n`;
response += `**Nodes:** ${result.nodeCount}\n`;
response += `**Error Rate:** ${(result.errorRate * 100).toFixed(1)}%\n`;
response += `**Avg. Execution Time:** ${result.avgExecutionTime.toFixed(1)} seconds\n\n`;
if (result.suggestions.length > 0) {
response += "**Optimization Suggestions:**\n";
result.suggestions.forEach(suggestion => {
response += `- ${suggestion}\n`;
});
} else {
response += "No specific optimization suggestions for this workflow.\n";
}
response += "\n";
});
return response;
```
## Scheduled Workflow Management
### User Prompt
"Update all my scheduled workflows to run one hour later."
### Assistant Actions
```javascript
// Get all workflows
const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {});
// Filter for scheduled workflows (those with a Schedule node)
const scheduledWorkflows = [];
for (const workflow of workflows) {
// Get detailed workflow information
const details = await useMcpTool('n8n-mcp-server', 'workflow_get', {
id: workflow.id
});
// Look for Schedule Trigger nodes
const scheduleNodes = details.nodes.filter(node =>
node.type === "n8n-nodes-base.scheduleTrigger" ||
node.type === "n8n-nodes-base.cron"
);
if (scheduleNodes.length > 0) {
scheduledWorkflows.push({
workflow: details,
scheduleNodes
});
}
}
if (scheduledWorkflows.length === 0) {
return "I couldn't find any workflows with scheduled triggers.";
}
// Process each scheduled workflow
const results = [];
for (const { workflow, scheduleNodes } of scheduledWorkflows) {
// Create a copy of the workflow for modification
const updatedWorkflow = { ...workflow };
// Update each schedule node
for (const scheduleNode of scheduleNodes) {
const nodeIndex = updatedWorkflow.nodes.findIndex(n => n.id === scheduleNode.id);
if (nodeIndex === -1) continue;
// Copy the node for modification
const updatedNode = { ...updatedWorkflow.nodes[nodeIndex] };
// Handle different types of schedule configurations
if (updatedNode.type === "n8n-nodes-base.scheduleTrigger") {
if (updatedNode.parameters.cronExpression) {
// Modify cron expression to run 1 hour later
const cronParts = updatedNode.parameters.cronExpression.split(' ');
if (cronParts.length === 5) {
// Standard cron format: minute hour day month dayOfWeek
const hour = parseInt(cronParts[1], 10);
cronParts[1] = ((hour + 1) % 24).toString();
updatedNode.parameters.cronExpression = cronParts.join(' ');
}
} else if (updatedNode.parameters.timeToRepeat) {
// Handle specific time scheduling
const time = updatedNode.parameters.timeToRepeat;
if (time && time.split(':').length === 2) {
const [hours, minutes] = time.split(':').map(part => parseInt(part, 10));
const newHours = (hours + 1) % 24;
updatedNode.parameters.timeToRepeat = `${newHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
}
}
} else if (updatedNode.type === "n8n-nodes-base.cron") {
// Similar handling for cron node
if (updatedNode.parameters.cronExpression) {
const cronParts = updatedNode.parameters.cronExpression.split(' ');
if (cronParts.length === 5) {
const hour = parseInt(cronParts[1], 10);
cronParts[1] = ((hour + 1) % 24).toString();
updatedNode.parameters.cronExpression = cronParts.join(' ');
}
}
}
// Update the node in the workflow
updatedWorkflow.nodes[nodeIndex] = updatedNode;
}
// Save the updated workflow
const result = await useMcpTool('n8n-mcp-server', 'workflow_update', {
id: workflow.id,
nodes: updatedWorkflow.nodes,
connections: updatedWorkflow.connections
});
results.push({
name: workflow.name,
updated: result.updatedAt
});
}
// Format and present the results
let response = "# Updated Scheduled Workflows\n\n";
response += "I've updated the following workflows to run one hour later:\n\n";
results.forEach(result => {
response += `- **${result.name}** (Updated: ${new Date(result.updated).toLocaleString()})\n`;
});
return response;
```
## Error Handling and Notification System
### User Prompt
"Set up a notification system for any workflow that fails."
### Assistant Actions
```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
## How It Works:
- Runs every 15 minutes
- Checks for any workflows that failed in the last 15 minutes
- Groups failures by workflow and formats a notification
- Sends an email with details about the failures
You can customize the notification format, schedule, and notification method by editing the workflow in the n8n interface.
`;
```
## Data Migration Between Workflows
### User Prompt
"Help me move data from my 'Legacy CRM' workflow to my 'New CRM' workflow."
### Assistant Actions
```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 `
# 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?
`;
```
These examples demonstrate more advanced usage patterns for the n8n MCP Server. For integration with other systems, see the [Integration Examples](./integration-examples.md) page.

View File

@@ -0,0 +1,258 @@
# Basic Examples
This page provides basic examples of using the n8n MCP Server with AI assistants.
## Listing Workflows
### User Prompt
"Show me all the workflows in my n8n instance."
### Assistant Actions
```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;
}
```
## Getting Workflow Details
### User Prompt
"Tell me about my 'Email Processing' workflow."
### Assistant Actions
```javascript
// First list all workflows to find the one with matching name
const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {});
// Find the workflow with a name containing "Email Processing"
const emailWorkflow = workflows.find(workflow =>
workflow.name.toLowerCase().includes('email processing')
);
if (!emailWorkflow) {
return "I couldn't find a workflow named 'Email Processing'. Would you like to see a list of all your workflows?";
}
// Get detailed information about the workflow
const details = await useMcpTool('n8n-mcp-server', 'workflow_get', {
id: emailWorkflow.id
});
// Format and present the workflow details
return `
# Email Processing Workflow
**Status:** ${details.active ? 'Active' : 'Inactive'}
**Created:** ${new Date(details.createdAt).toLocaleString()}
**Last Updated:** ${new Date(details.updatedAt).toLocaleString()}
## Nodes (${details.nodes.length})
${details.nodes.map(node => `- ${node.name} (${node.type})`).join('\n')}
## Settings
${Object.entries(details.settings || {}).map(([key, value]) => `- ${key}: ${value}`).join('\n')}
`;
```
## Executing a Workflow
### User Prompt
"Run my 'Data Sync' workflow."
### Assistant Actions
```javascript
// First list all workflows to find the one with matching name
const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {});
// Find the workflow with a name containing "Data Sync"
const syncWorkflow = workflows.find(workflow =>
workflow.name.toLowerCase().includes('data sync')
);
if (!syncWorkflow) {
return "I couldn't find a workflow named 'Data Sync'. Would you like to see a list of all your workflows?";
}
// Check if the workflow is active
if (!syncWorkflow.active) {
return "The 'Data Sync' workflow is currently inactive. Would you like me to activate it before running it?";
}
// Execute the workflow
const execution = await useMcpTool('n8n-mcp-server', 'execution_run', {
workflowId: syncWorkflow.id
});
return `
I've started the 'Data Sync' workflow.
**Execution ID:** ${execution.executionId}
**Status:** ${execution.status}
**Started At:** ${new Date(execution.startedAt).toLocaleString()}
You can check the execution status later by asking me about it.
`;
```
## Checking Execution Status
### User Prompt
"Check the status of my last workflow execution."
### Assistant Actions
```javascript
// Get recent executions (this example assumes we've stored the last execution ID in context)
// In a real scenario, you might need to list recent executions first
const lastExecutionId = "exec123"; // In practice, this would come from context or a previous response
// Get execution details
const execution = await useMcpTool('n8n-mcp-server', 'execution_get', {
executionId: lastExecutionId
});
// Format and present the execution status
let response = `
# Execution Status for ${execution.workflowName}
**Status:** ${execution.status}
**Started:** ${new Date(execution.startedAt).toLocaleString()}
`;
if (execution.finishedAt) {
response += `**Finished:** ${new Date(execution.finishedAt).toLocaleString()}\n`;
response += `**Duration:** ${Math.round((new Date(execution.finishedAt) - new Date(execution.startedAt)) / 1000)} seconds\n`;
}
response += "\n## Execution Path\n";
execution.data.executionData.nodeExecutionOrder.forEach(nodeName => {
response += `- ${nodeName}\n`;
});
return response;
```
## Activating/Deactivating a Workflow
### User Prompt
"Deactivate my 'Daily Report' workflow."
### Assistant Actions
```javascript
// First list all workflows to find the one with matching name
const workflows = await useMcpTool('n8n-mcp-server', 'workflow_list', {});
// Find the workflow with a name containing "Daily Report"
const reportWorkflow = workflows.find(workflow =>
workflow.name.toLowerCase().includes('daily report')
);
if (!reportWorkflow) {
return "I couldn't find a workflow named 'Daily Report'. Would you like to see a list of all your workflows?";
}
// Check if the workflow is already inactive
if (!reportWorkflow.active) {
return "The 'Daily Report' workflow is already inactive.";
}
// Deactivate the workflow
const result = await useMcpTool('n8n-mcp-server', 'workflow_deactivate', {
id: reportWorkflow.id
});
return `
I've deactivated the 'Daily Report' workflow.
It was last updated on ${new Date(result.updatedAt).toLocaleString()}.
You can reactivate it at any time by asking me to activate it.
`;
```
## Creating a Simple Workflow
### User Prompt
"Create a new workflow that sends me a daily email reminder."
### Assistant Actions
```javascript
// Create a new workflow
const newWorkflow = await useMcpTool('n8n-mcp-server', 'workflow_create', {
name: "Daily Email Reminder",
active: false, // Start inactive until it's configured properly
nodes: [
{
name: "Schedule Trigger",
type: "n8n-nodes-base.scheduleTrigger",
position: [100, 300],
parameters: {
rule: {
interval: [
{
field: "hours",
minuteInterval: 24
}
]
}
}
},
{
name: "Send Email",
type: "n8n-nodes-base.emailSend",
position: [300, 300],
parameters: {
to: "{{$json.email}}",
subject: "Daily Reminder",
text: "This is your daily reminder!"
}
}
],
connections: {
"Schedule Trigger": {
main: [
[
{
node: "Send Email",
type: "main",
index: 0
}
]
]
}
}
});
return `
I've created a new workflow called "Daily Email Reminder".
This workflow is currently **inactive** and needs configuration:
1. You'll need to enter your email address in the "Send Email" node
2. You might want to customize the schedule and email content
You can view and edit this workflow in the n8n interface (ID: ${newWorkflow.id}), and then ask me to activate it when you're ready.
`;
```
These examples demonstrate the basic operations you can perform with the n8n MCP Server. For more complex scenarios, see the [Advanced Scenarios](./advanced-scenarios.md) page.

22
docs/examples/index.md Normal file
View File

@@ -0,0 +1,22 @@
# Usage Examples
This section provides practical examples of using the n8n MCP Server with AI assistants.
## Overview
The examples in this section demonstrate how AI assistants can interact with n8n workflows through the MCP server. They range from basic operations to complex integration scenarios.
## Examples Categories
- [Basic Examples](./basic-examples.md): Simple examples covering fundamental operations like listing workflows, retrieving workflow details, and executing workflows.
- [Advanced Scenarios](./advanced-scenarios.md): More complex examples showing how to chain operations, handle errors, and implement common workflow patterns.
- [Integration Examples](./integration-examples.md): Examples of integrating the n8n MCP Server with different AI assistant platforms and other tools.
## How to Use These Examples
The examples in this section show both:
1. **User Prompts**: What a user might ask an AI assistant to do
2. **Assistant Actions**: How the assistant would use the MCP tools and resources to accomplish the task
You can use these examples as inspiration for your own interactions with the n8n MCP Server or as templates for building more complex workflows.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
This is a placeholder for an architecture diagram.
Replace this with an actual diagram showing the layered architecture of the n8n MCP Server,
including the Transport Layer, API Client Layer, Tools Layer, Resources Layer,
Configuration Layer, and Error Handling Layer.

View File

@@ -0,0 +1,2 @@
This is a placeholder for a screenshot showing the n8n API Key creation process.
When documenting the actual project, replace this with a real screenshot.

34
docs/index.md Normal file
View File

@@ -0,0 +1,34 @@
# n8n MCP Server Documentation
Welcome to the n8n MCP Server documentation. This documentation provides comprehensive information about setting up, configuring, and using the n8n MCP Server.
## Table of Contents
- [Setup and Configuration](./setup/index.md)
- [Installation](./setup/installation.md)
- [Configuration](./setup/configuration.md)
- [Troubleshooting](./setup/troubleshooting.md)
- [API Reference](./api/index.md)
- [Tools](./api/tools.md)
- [Workflow Tools](./api/workflow-tools.md)
- [Execution Tools](./api/execution-tools.md)
- [Resources](./api/resources.md)
- [Static Resources](./api/static-resources.md)
- [Dynamic Resources](./api/dynamic-resources.md)
- [Usage Examples](./examples/index.md)
- [Basic Examples](./examples/basic-examples.md)
- [Advanced Scenarios](./examples/advanced-scenarios.md)
- [Integration Examples](./examples/integration-examples.md)
- [Development](./development/index.md)
- [Architecture](./development/architecture.md)
- [Extending the Server](./development/extending.md)
- [Testing](./development/testing.md)
## Quick Links
- [GitHub Repository](https://github.com/yourusername/n8n-mcp-server)
- [n8n Documentation](https://docs.n8n.io/)
- [Model Context Protocol Documentation](https://modelcontextprotocol.github.io/)

111
docs/setup/configuration.md Normal file
View File

@@ -0,0 +1,111 @@
# Configuration Guide
This guide provides detailed information on configuring the n8n MCP Server.
## Environment Variables
The n8n MCP Server is configured using environment variables, which can be set in a `.env` file or directly in your environment.
### Required Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `N8N_API_URL` | URL of the n8n API | `http://localhost:5678/api/v1` |
| `N8N_API_KEY` | API key for authenticating with n8n | `n8n_api_...` |
### Optional Variables
| Variable | Description | Default | Example |
|----------|-------------|---------|---------|
| `DEBUG` | Enable debug logging | `false` | `true` or `false` |
## Creating a .env File
The simplest way to configure the server is to create a `.env` file in the directory where you'll run the server:
```bash
# Copy the example .env file
cp .env.example .env
# Edit the .env file with your settings
nano .env # or use any text editor
```
Example `.env` file:
```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
```
## Generating an n8n API Key
To use the n8n MCP Server, you need an API key from your n8n instance:
1. Open your n8n instance in a browser
2. Go to **Settings** > **API** > **API Keys**
3. Click **Create** to create a new API key
4. Set appropriate **Scope** (recommended: `workflow:read workflow:write workflow:execute`)
5. Copy the key to your `.env` file
![Creating an n8n API Key](../images/n8n-api-key.png)
## Server Connection Options
By default, the n8n MCP Server listens on `stdin` and `stdout` for Model Context Protocol communications. This is the format expected by AI assistants using the MCP protocol.
## Configuring AI Assistants
To use the n8n MCP Server with AI assistants, you need to register it with your AI assistant platform. The exact method depends on the platform you're using.
### Using the MCP Installer
If you're using Claude or another assistant that supports the MCP Installer, you can register the server with:
```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
```
### Manual Configuration
For platforms without an installer, you'll need to configure the connection according to the platform's documentation. Typically, this involves:
1. Specifying the path to the executable
2. Setting environment variables for the server
3. Configuring response formatting
## Verifying Configuration
To verify your configuration:
1. Start the server
2. Open your AI assistant
3. Try a simple command like "List all workflows in n8n"
If configured correctly, the assistant should be able to retrieve and display your workflows.
## Troubleshooting
If you encounter issues with your configuration, check:
- The `.env` file is in the correct location
- The n8n API URL is accessible from where the server is running
- The API key has the correct permissions
- Any firewalls or network restrictions that might block connections
For more specific issues, see the [Troubleshooting](./troubleshooting.md) guide.

18
docs/setup/index.md Normal file
View File

@@ -0,0 +1,18 @@
# Setup and Configuration
This section covers everything you need to know to set up and configure the n8n MCP Server.
## Topics
- [Installation](./installation.md): Instructions for installing the n8n MCP Server from npm or from source.
- [Configuration](./configuration.md): Information on configuring the server, including environment variables and n8n API setup.
- [Troubleshooting](./troubleshooting.md): Solutions to common issues you might encounter.
## Quick Start
For a quick start, follow these steps:
1. Install the server: `npm install -g n8n-mcp-server`
2. Create a `.env` file with your n8n API URL and API key
3. Run the server: `n8n-mcp-server`
4. Register the server with your AI assistant platform

View File

@@ -0,0 +1,83 @@
# Installation Guide
This guide covers the installation process for the n8n MCP Server.
## Prerequisites
Before installing the n8n MCP Server, ensure you have:
- Node.js 18 or later installed
- An n8n instance running and accessible via HTTP/HTTPS
- API access enabled on your n8n instance
- An API key with appropriate permissions (see [Configuration](./configuration.md))
## Option 1: Install from npm (Recommended)
The easiest way to install the n8n MCP Server is from npm:
```bash
npm install -g n8n-mcp-server
```
This will install the server globally, making the `n8n-mcp-server` command available in your terminal.
## Option 2: Install from Source
For development purposes or to use the latest features, you can install from source:
```bash
# Clone the repository
git clone https://github.com/yourusername/n8n-mcp-server.git
cd n8n-mcp-server
# Install dependencies
npm install
# Build the project
npm run build
# Optional: Install globally
npm install -g .
```
## Verifying Installation
Once installed, you can verify the installation by running:
```bash
n8n-mcp-server --version
```
This should display the version number of the installed n8n MCP Server.
## Next Steps
After installation, you'll need to:
1. [Configure the server](./configuration.md) by setting up environment variables
2. Run the server
3. Register the server with your AI assistant platform
## Upgrading
To upgrade a global installation from npm:
```bash
npm update -g n8n-mcp-server
```
To upgrade a source installation:
```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 .

View File

@@ -0,0 +1,149 @@
# Troubleshooting Guide
This guide addresses common issues you might encounter when setting up and using the n8n MCP Server.
## Connection Issues
### Cannot Connect to n8n API
**Symptoms:**
- Error messages mentioning "Connection refused" or "Cannot connect to n8n API"
- Timeout errors when trying to use MCP tools
**Possible Solutions:**
1. **Verify n8n is running:**
- Ensure your n8n instance is running and accessible
- Try accessing the n8n URL in a browser
2. **Check n8n API URL:**
- Verify the `N8N_API_URL` in your `.env` file
- Make sure it includes the full path (e.g., `http://localhost:5678/api/v1`)
- Check for typos or incorrect protocol (http vs https)
3. **Network Configuration:**
- If running on a different machine, ensure there are no firewall rules blocking access
- Check if n8n is configured to allow remote connections
4. **HTTPS/SSL Issues:**
- If using HTTPS, ensure certificates are valid
- For self-signed certificates, you may need to set up additional configuration
### Authentication Failures
**Symptoms:**
- "Authentication failed" or "Invalid API key" messages
- 401 or 403 HTTP status codes
**Possible Solutions:**
1. **Verify API Key:**
- Check that the `N8N_API_KEY` in your `.env` file matches the one in n8n
- Create a new API key if necessary
2. **Check API Key Permissions:**
- Ensure the API key has appropriate scopes/permissions
- Required scopes: `workflow:read workflow:write workflow:execute`
3. **n8n API Settings:**
- Verify that API access is enabled in n8n settings
- Check if there are IP restrictions on API access
## MCP Server Issues
### Server Crashes or Exits Unexpectedly
**Symptoms:**
- The MCP server stops running unexpectedly
- Error messages in logs or console output
**Possible Solutions:**
1. **Check Node.js Version:**
- Ensure you're using Node.js 18 or later
- Check with `node --version`
2. **Check Environment Variables:**
- Ensure all required environment variables are set
- Verify the format of the environment variables
3. **View Debug Logs:**
- Set `DEBUG=true` in your `.env` file
- Check the console output for detailed error messages
4. **Memory Issues:**
- If running on a system with limited memory, increase available memory
- Check for memory leaks or high consumption patterns
### AI Assistant Cannot Communicate with MCP Server
**Symptoms:**
- AI assistant reports it cannot connect to the MCP server
- Tools are not available in the assistant interface
**Possible Solutions:**
1. **Verify Server Registration:**
- Ensure the server is properly registered with your AI assistant platform
- Check the configuration settings for the MCP server in your assistant
2. **Server Running Check:**
- Verify the MCP server is running
- Check that it was started with the correct environment
3. **Restart Components:**
- Restart the MCP server
- Refresh the AI assistant interface
- If using a managed AI assistant, check platform status
## Tool-Specific Issues
### Workflow Operations Fail
**Symptoms:**
- Cannot list, create, or update workflows
- Error messages about missing permissions
**Possible Solutions:**
1. **API Key Scope:**
- Ensure your API key has `workflow:read` and `workflow:write` permissions
- Create a new key with appropriate permissions if needed
2. **n8n Version:**
- Check if your n8n version supports all the API endpoints being used
- Update n8n to the latest version if possible
3. **Workflow Complexity:**
- Complex workflows with custom nodes may not work correctly
- Try with simpler workflows to isolate the issue
### Execution Operations Fail
**Symptoms:**
- Cannot execute workflows or retrieve execution data
- Execution starts but fails to complete
**Possible Solutions:**
1. **API Key Scope:**
- Ensure your API key has the `workflow:execute` permission
- Create a new key with appropriate permissions if needed
2. **Workflow Status:**
- Check if the target workflow is active
- Verify the workflow executes correctly in the n8n interface
3. **Workflow Inputs:**
- Ensure all required inputs for workflow execution are provided
- Check the format of input data
## Getting More Help
If you're still experiencing issues after trying these troubleshooting steps:
1. **Check GitHub Issues:**
- Look for similar issues in the [GitHub repository](https://github.com/yourusername/n8n-mcp-server/issues)
- Create a new issue with detailed information about your problem
2. **Submit Logs:**
- Enable debug logging with `DEBUG=true`
- Include relevant logs when seeking help
3. **Community Support:**
- Ask in the n8n community forums
- Check MCP-related discussion groups