n8n-mcp-orchestrator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

n8n MCP Orchestrator

n8n MCP 编排器

A comprehensive skill for orchestrating AI agents and workflows using n8n's Model Context Protocol (MCP) integration. This skill enables bidirectional MCP patterns, agentic workflow automation, and production-ready AI-powered systems with Claude Code integration.
这是一个利用n8n的Model Context Protocol(MCP)集成来编排AI Agent和工作流的综合技能。该技能支持双向MCP模式、智能代理工作流自动化,并结合Claude Code集成构建可投入生产的AI驱动系统。

When to Use This Skill

何时使用此技能

Use this skill when:
  • Building AI-powered automation workflows with n8n
  • Exposing n8n workflows as tools for AI agents (Claude Code, Claude Desktop)
  • Consuming external MCP servers from n8n workflows
  • Orchestrating multi-agent systems and agentic workflows
  • Creating tool-using AI agents with n8n backend
  • Integrating Claude Code with business process automation
  • Building context-aware automation with MCP resources
  • Coordinating complex workflows across multiple AI agents
  • Developing production-ready AI orchestration pipelines
  • Implementing bidirectional MCP communication patterns
  • Creating autonomous agent systems with workflow orchestration
  • Building AI-first automation with 400+ service integrations
在以下场景中使用此技能:
  • 使用n8n构建AI驱动的自动化工作流
  • 将n8n工作流暴露为AI Agent(Claude Code、Claude Desktop)可调用的工具
  • 在n8n工作流中调用外部MCP服务器
  • 编排多Agent系统和智能代理工作流
  • 基于n8n后端构建可调用工具的AI Agent
  • 将Claude Code与业务流程自动化集成
  • 利用MCP资源构建上下文感知的自动化
  • 协调跨多个AI Agent的复杂工作流
  • 开发可投入生产的AI编排流水线
  • 实现双向MCP通信模式
  • 构建带工作流编排的自主Agent系统
  • 结合400+服务集成构建AI优先的自动化

Core Concepts

核心概念

Model Context Protocol (MCP)

Model Context Protocol (MCP)

The Model Context Protocol is an open standard for connecting AI assistants to external systems:
  • Bidirectional Communication: Clients and servers can both initiate requests
  • Resource Management: Expose data and context as resources
  • Tool Invocation: AI agents can execute tools (functions/workflows)
  • Prompt Templates: Provide structured prompts to AI systems
  • Security: Built-in authentication and authorization patterns
  • Scalability: Designed for production AI orchestration
Model Context Protocol是一个用于连接AI助手与外部系统的开放标准:
  • 双向通信:客户端和服务器均可发起请求
  • 资源管理:将数据和上下文作为资源暴露
  • 工具调用:AI Agent可以执行工具(函数/工作流)
  • 提示模板:为AI系统提供结构化提示
  • 安全性:内置身份验证和授权模式
  • 可扩展性:专为生产级AI编排设计

MCP Architecture Components

MCP架构组件

1. MCP Servers
  • Expose capabilities (tools, resources, prompts) to AI clients
  • Can be standalone services or embedded in applications
  • Handle authentication, rate limiting, and security
  • n8n workflows can act as MCP servers
2. MCP Clients
  • Connect to MCP servers and invoke their capabilities
  • AI assistants like Claude Code and Claude Desktop
  • n8n workflows can act as MCP clients
3. Resources
  • Data sources and context exposed by MCP servers
  • Examples: documents, database records, API responses
  • AI agents can read resources for context
4. Tools
  • Functions/workflows that AI agents can invoke
  • Accept parameters and return results
  • n8n workflows become AI-callable tools
5. Prompts
  • Structured prompt templates for AI interactions
  • Include context, instructions, and variables
  • Guide AI behavior in specific scenarios
1. MCP服务器
  • 向AI客户端暴露功能(工具、资源、提示)
  • 可以是独立服务或嵌入应用中
  • 处理身份验证、速率限制和安全相关事宜
  • n8n工作流可作为MCP服务器
2. MCP客户端
  • 连接到MCP服务器并调用其功能
  • 如Claude Code和Claude Desktop等AI助手
  • n8n工作流可作为MCP客户端
3. 资源
  • MCP服务器暴露的数据源和上下文
  • 示例:文档、数据库记录、API响应
  • AI Agent可读取资源获取上下文
4. 工具
  • AI Agent可调用的函数/工作流
  • 接受参数并返回结果
  • n8n工作流可成为AI可调用的工具
5. 提示
  • 用于AI交互的结构化提示模板
  • 包含上下文、指令和变量
  • 在特定场景中引导AI行为

n8n's Bidirectional MCP Capability

n8n的双向MCP能力

n8n as MCP Server (Expose workflows as tools):
  • MCP Server Trigger node activates workflow when called by AI
  • Workflows become tools that Claude Code can invoke
  • Enable AI agents to automate complex business processes
  • Return structured data to AI clients
n8n as MCP Client (Call external MCP servers):
  • MCP Client Tool node invokes external MCP servers
  • Call tools from other MCP-compatible services
  • Orchestrate multiple MCP servers in single workflow
  • Build complex automation chains
n8n作为MCP服务器(将工作流暴露为工具):
  • MCP Server Trigger节点在被AI调用时激活工作流
  • 工作流成为Claude Code可调用的工具
  • 使AI Agent能够自动化复杂的业务流程
  • 向AI客户端返回结构化数据
n8n作为MCP客户端(调用外部MCP服务器):
  • MCP Client Tool节点调用外部MCP服务器
  • 调用其他兼容MCP的服务中的工具
  • 在单个工作流中编排多个MCP服务器
  • 构建复杂的自动化链

Key MCP Nodes in n8n

n8n中的关键MCP节点

1. MCP Server Trigger
  • Workflow entry point for MCP tool invocations
  • Receives parameters from AI agents
  • Returns results to calling AI client
  • Supports authentication and validation
2. MCP Client Tool
  • Call external MCP server tools
  • Pass parameters to remote tools
  • Handle responses and errors
  • Chain multiple MCP calls
1. MCP Server Trigger
  • MCP工具调用的工作流入口点
  • 接收来自AI Agent的参数
  • 向调用的AI客户端返回结果
  • 支持身份验证和验证
2. MCP Client Tool
  • 调用外部MCP服务器的工具
  • 向远程工具传递参数
  • 处理响应和错误
  • 链式调用多个MCP请求

n8n as MCP Server

n8n作为MCP服务器

Exposing Workflows as AI Agent Tools

将工作流暴露为AI Agent工具

When you create a workflow with an MCP Server Trigger, that workflow becomes a tool that AI agents can invoke.
Architecture Pattern:
┌─────────────────────────────────────────────────────────────────┐
│                    Claude Code / Claude Desktop                 │
│                                                                 │
│  Agent decides to use tool:                                     │
│  "I need to create a support ticket for this bug"              │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Tool Invocation
┌─────────────────────────────────────────────────────────────────┐
│                    n8n Workflow (MCP Server)                    │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ MCP Server Trigger                                        │  │
│  │ Tool: "create_support_ticket"                             │  │
│  │ Receives: {title, description, priority}                  │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ HTTP Request: Call Jira API                               │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Slack Notification: Notify team                           │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Respond to MCP: Return ticket ID                          │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Response
┌─────────────────────────────────────────────────────────────────┐
│                    Claude Code                                  │
│                                                                 │
│  Receives: {ticketId: "JIRA-12345", status: "created"}        │
│  Continues conversation with user                              │
└─────────────────────────────────────────────────────────────────┘
当你使用MCP Server Trigger创建工作流时,该工作流将成为AI Agent可调用的工具。
架构模式:
┌─────────────────────────────────────────────────────────────────┐
│                    Claude Code / Claude Desktop                 │
│                                                                 │
│  Agent decides to use tool:                                     │
│  "I need to create a support ticket for this bug"              │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Tool Invocation
┌─────────────────────────────────────────────────────────────────┐
│                    n8n Workflow (MCP Server)                    │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ MCP Server Trigger                                        │  │
│  │ Tool: "create_support_ticket"                             │  │
│  │ Receives: {title, description, priority}                  │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ HTTP Request: Call Jira API                               │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Slack Notification: Notify team                           │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Respond to MCP: Return ticket ID                          │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Response
┌─────────────────────────────────────────────────────────────────┐
│                    Claude Code                                  │
│                                                                 │
│  Receives: {ticketId: "JIRA-12345", status: "created"}        │
│  Continues conversation with user                              │
└─────────────────────────────────────────────────────────────────┘

MCP Server Trigger Configuration

MCP Server Trigger配置

Basic Setup:
  1. Create New Workflow in n8n
  2. Add MCP Server Trigger node as entry point
  3. Configure Tool Definition:
    • Tool Name: Unique identifier (e.g., "create_support_ticket")
    • Description: Clear description for AI to understand when to use
    • Parameters: Define input schema (JSON Schema format)
    • Authentication: Optional authentication settings
  4. Build Workflow Logic: Add nodes to process the request
  5. Return Response: Last node output becomes MCP response
MCP Server Trigger Parameters:
json
{
  "toolName": "create_support_ticket",
  "description": "Create a support ticket in Jira with automatic team notification",
  "parameters": {
    "type": "object",
    "properties": {
      "title": {
        "type": "string",
        "description": "Brief ticket title"
      },
      "description": {
        "type": "string",
        "description": "Detailed problem description"
      },
      "priority": {
        "type": "string",
        "enum": ["low", "medium", "high", "critical"],
        "description": "Ticket priority level"
      },
      "component": {
        "type": "string",
        "description": "System component affected"
      }
    },
    "required": ["title", "description"]
  }
}
基础设置:
  1. 在n8n中创建新工作流
  2. 添加MCP Server Trigger节点作为入口点
  3. 配置工具定义
    • 工具名称:唯一标识符(例如"create_support_ticket")
    • 描述:清晰说明AI何时应使用此工具
    • 参数:定义输入模式(JSON Schema格式)
    • 身份验证:可选的身份验证设置
  4. 构建工作流逻辑:添加节点处理请求
  5. 返回响应:最后一个节点的输出将作为MCP响应返回
MCP Server Trigger参数:
json
{
  "toolName": "create_support_ticket",
  "description": "Create a support ticket in Jira with automatic team notification",
  "parameters": {
    "type": "object",
    "properties": {
      "title": {
        "type": "string",
        "description": "Brief ticket title"
      },
      "description": {
        "type": "string",
        "description": "Detailed problem description"
      },
      "priority": {
        "type": "string",
        "enum": ["low", "medium", "high", "critical"],
        "description": "Ticket priority level"
      },
      "component": {
        "type": "string",
        "description": "System component affected"
      }
    },
    "required": ["title", "description"]
  }
}

Response Format

响应格式

The final node output in your workflow is returned to the AI agent:
json
{
  "success": true,
  "ticketId": "JIRA-12345",
  "url": "https://company.atlassian.net/browse/JIRA-12345",
  "assignee": "john.doe@company.com",
  "createdAt": "2025-10-20T10:30:00Z"
}
工作流中最后一个节点的输出将返回给AI Agent:
json
{
  "success": true,
  "ticketId": "JIRA-12345",
  "url": "https://company.atlassian.net/browse/JIRA-12345",
  "assignee": "john.doe@company.com",
  "createdAt": "2025-10-20T10:30:00Z"
}

Authentication Patterns

身份验证模式

1. API Key Authentication
json
{
  "authenticationType": "apiKey",
  "apiKeyHeader": "X-API-Key",
  "requiredScopes": ["workflows:execute"]
}
2. OAuth 2.0
json
{
  "authenticationType": "oauth2",
  "authorizationUrl": "https://auth.company.com/oauth/authorize",
  "tokenUrl": "https://auth.company.com/oauth/token",
  "scopes": ["workflows:read", "workflows:execute"]
}
3. No Authentication (internal use only)
json
{
  "authenticationType": "none"
}
1. API密钥身份验证
json
{
  "authenticationType": "apiKey",
  "apiKeyHeader": "X-API-Key",
  "requiredScopes": ["workflows:execute"]
}
2. OAuth 2.0
json
{
  "authenticationType": "oauth2",
  "authorizationUrl": "https://auth.company.com/oauth/authorize",
  "tokenUrl": "https://auth.company.com/oauth/token",
  "scopes": ["workflows:read", "workflows:execute"]
}
3. 无身份验证(仅限内部使用)
json
{
  "authenticationType": "none"
}

n8n as MCP Client

n8n作为MCP客户端

Consuming External MCP Servers

调用外部MCP服务器

The MCP Client Tool node allows n8n workflows to call external MCP servers and use their tools.
Architecture Pattern:
┌─────────────────────────────────────────────────────────────────┐
│                    n8n Workflow                                 │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Schedule Trigger: Every day at 9am                        │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ MCP Client Tool                                           │  │
│  │ Server: "analytics-mcp-server"                            │  │
│  │ Tool: "generate_daily_report"                             │  │
│  │ Params: {date: "today"}                                   │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Request
┌─────────────────────────────────────────────────────────────────┐
│                    External MCP Server                          │
│                    (Analytics Service)                          │
│                                                                 │
│  Processes request, generates report, returns data             │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Response
┌─────────────────────────────────────────────────────────────────┐
│                    n8n Workflow (continued)                     │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Email: Send report to stakeholders                        │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
MCP Client Tool节点允许n8n工作流调用外部MCP服务器并使用其工具。
架构模式:
┌─────────────────────────────────────────────────────────────────┐
│                    n8n Workflow                                 │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Schedule Trigger: Every day at 9am                        │  │
│  └──────────────────────────────────────────────────────────┘  │
│                          │                                      │
│                          ↓                                      │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ MCP Client Tool                                           │  │
│  │ Server: "analytics-mcp-server"                            │  │
│  │ Tool: "generate_daily_report"                             │  │
│  │ Params: {date: "today"}                                   │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Request
┌─────────────────────────────────────────────────────────────────┐
│                    External MCP Server                          │
│                    (Analytics Service)                          │
│                                                                 │
│  Processes request, generates report, returns data             │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Response
┌─────────────────────────────────────────────────────────────────┐
│                    n8n Workflow (continued)                     │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │ Email: Send report to stakeholders                        │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘

MCP Client Tool Configuration

MCP Client Tool配置

Basic Setup:
  1. Add MCP Client Tool node to workflow
  2. Configure MCP Server Connection:
    • Server URL: MCP server endpoint
    • Authentication: API key, OAuth, or none
    • Timeout: Request timeout (default: 30s)
  3. Select Tool: Choose from available tools on MCP server
  4. Provide Parameters: Map workflow data to tool parameters
  5. Handle Response: Process returned data in subsequent nodes
MCP Client Tool Configuration:
json
{
  "serverUrl": "https://mcp.analytics-service.com",
  "authentication": {
    "type": "apiKey",
    "apiKey": "{{$credentials.analyticsApiKey}}"
  },
  "tool": "generate_daily_report",
  "parameters": {
    "date": "{{DateTime.now().toISODate()}}",
    "metrics": ["revenue", "users", "engagement"],
    "format": "json"
  },
  "timeout": 60000
}
基础设置:
  1. 向工作流中添加MCP Client Tool节点
  2. 配置MCP服务器连接
    • 服务器URL:MCP服务器端点
    • 身份验证:API密钥、OAuth或无身份验证
    • 超时:请求超时时间(默认:30秒)
  3. 选择工具:从MCP服务器的可用工具中选择
  4. 提供参数:将工作流数据映射到工具参数
  5. 处理响应:在后续节点中处理返回的数据
MCP Client Tool配置:
json
{
  "serverUrl": "https://mcp.analytics-service.com",
  "authentication": {
    "type": "apiKey",
    "apiKey": "{{$credentials.analyticsApiKey}}"
  },
  "tool": "generate_daily_report",
  "parameters": {
    "date": "{{DateTime.now().toISODate()}}",
    "metrics": ["revenue", "users", "engagement"],
    "format": "json"
  },
  "timeout": 60000
}

Discovering Available Tools

发现可用工具

MCP servers expose their available tools through the protocol:
json
{
  "tools": [
    {
      "name": "generate_daily_report",
      "description": "Generate daily analytics report",
      "parameters": {
        "type": "object",
        "properties": {
          "date": {"type": "string"},
          "metrics": {"type": "array"},
          "format": {"type": "string"}
        }
      }
    },
    {
      "name": "query_metrics",
      "description": "Query specific metrics",
      "parameters": {
        "type": "object",
        "properties": {
          "metric": {"type": "string"},
          "startDate": {"type": "string"},
          "endDate": {"type": "string"}
        }
      }
    }
  ]
}
MCP服务器通过协议暴露其可用工具:
json
{
  "tools": [
    {
      "name": "generate_daily_report",
      "description": "Generate daily analytics report",
      "parameters": {
        "type": "object",
        "properties": {
          "date": {"type": "string"},
          "metrics": {"type": "array"},
          "format": {"type": "string"}
        }
      }
    },
    {
      "name": "query_metrics",
      "description": "Query specific metrics",
      "parameters": {
        "type": "object",
        "properties": {
          "metric": {"type": "string"},
          "startDate": {"type": "string"},
          "endDate": {"type": "string"}
        }
      }
    }
  ]
}

Claude Code Integration

Claude Code集成

Connecting Claude Code to n8n Workflows

将Claude Code连接到n8n工作流

Prerequisites:
  1. n8n instance running (self-hosted or cloud)
  2. n8n workflow with MCP Server Trigger configured
  3. Claude Code with MCP client capability
Configuration Steps:
1. Create n8n MCP Server Workflow
Workflow: "create_task"
┌──────────────────────────────────────┐
│ MCP Server Trigger                   │
│ Tool: create_task                    │
│ Params: title, description, due_date │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ HTTP Request: POST to Todoist API    │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ Return: Task created confirmation    │
└──────────────────────────────────────┘
2. Get n8n MCP Server URL
n8n exposes MCP servers at:
https://your-n8n-instance.com/mcp
3. Configure Claude Code MCP Client
Add to
mcp_config.json
:
json
{
  "mcpServers": {
    "n8n-workflows": {
      "url": "https://your-n8n-instance.com/mcp",
      "apiKey": "your-n8n-api-key",
      "description": "n8n workflow automation tools",
      "tools": [
        "create_task",
        "send_email",
        "create_support_ticket",
        "generate_report"
      ]
    }
  }
}
4. Use in Claude Code
Claude Code automatically discovers and uses n8n tools:
User: "Create a task to review the PR tomorrow at 2pm"

Claude Code:
- Recognizes create_task tool from n8n
- Invokes: create_task(
    title="Review PR",
    description="Code review for authentication feature",
    due_date="2025-10-21T14:00:00Z"
  )
- n8n workflow executes
- Returns task confirmation
- Claude responds: "Task created in Todoist: Review PR (tomorrow at 2pm)"
前提条件:
  1. n8n实例正在运行(自托管或云版本)
  2. 已配置MCP Server Trigger的n8n工作流
  3. 具备MCP客户端能力的Claude Code
配置步骤:
1. 创建n8n MCP服务器工作流
Workflow: "create_task"
┌──────────────────────────────────────┐
│ MCP Server Trigger                   │
│ Tool: create_task                    │
│ Params: title, description, due_date │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ HTTP Request: POST to Todoist API    │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ Return: Task created confirmation    │
└──────────────────────────────────────┘
2. 获取n8n MCP服务器URL
n8n在以下地址暴露MCP服务器:
https://your-n8n-instance.com/mcp
3. 配置Claude Code MCP客户端
添加到
mcp_config.json
json
{
  "mcpServers": {
    "n8n-workflows": {
      "url": "https://your-n8n-instance.com/mcp",
      "apiKey": "your-n8n-api-key",
      "description": "n8n workflow automation tools",
      "tools": [
        "create_task",
        "send_email",
        "create_support_ticket",
        "generate_report"
      ]
    }
  }
}
4. 在Claude Code中使用
Claude Code会自动发现并使用n8n工具:
User: "Create a task to review the PR tomorrow at 2pm"

Claude Code:
- Recognizes create_task tool from n8n
- Invokes: create_task(
    title="Review PR",
    description="Code review for authentication feature",
    due_date="2025-10-21T14:00:00Z"
  )
- n8n workflow executes
- Returns task confirmation
- Claude responds: "Task created in Todoist: Review PR (tomorrow at 2pm)"

Bidirectional Claude Code ↔ n8n Integration

Claude Code ↔ n8n双向集成

Pattern 1: Claude triggers n8n workflow
Claude Code → MCP Tool Call → n8n MCP Server → Workflow executes
Pattern 2: n8n calls Claude via MCP
n8n Workflow → MCP Client Tool → Claude API → AI processing → Response
Combined Pattern: Agentic Workflow
1. User asks Claude to analyze sales data
2. Claude calls n8n tool: get_sales_data()
3. n8n retrieves data from database
4. Claude analyzes data
5. Claude calls n8n tool: generate_report(analysis)
6. n8n creates PDF report and emails stakeholders
7. Claude confirms completion to user
模式1:Claude触发n8n工作流
Claude Code → MCP Tool Call → n8n MCP Server → Workflow executes
模式2:n8n通过MCP调用Claude
n8n Workflow → MCP Client Tool → Claude API → AI processing → Response
组合模式:智能代理工作流
1. 用户请求Claude分析销售数据
2. Claude调用n8n工具:get_sales_data()
3. n8n从数据库中检索数据
4. Claude分析数据
5. Claude调用n8n工具:generate_report(analysis)
6. n8n创建PDF报告并发送给相关人员
7. Claude向用户确认完成

Agentic Workflow Patterns

智能代理工作流模式

Pattern 1: Multi-Step Agent Workflow

模式1:多步骤代理工作流

Scenario: Customer support ticket processing
┌─────────────────────────────────────────────────────────────────┐
│ User: "Customer reports login issue"                            │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Agent)                                             │
│ 1. Calls: create_support_ticket(issue_type="login")            │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n Workflow 1: Create Ticket                                   │
│ - Create Jira ticket                                            │
│ - Notify support team in Slack                                  │
│ - Return ticket ID                                              │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Agent)                                             │
│ 2. Calls: search_knowledge_base(query="login issues")          │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n Workflow 2: Knowledge Search                                │
│ - Query internal docs                                           │
│ - Search past tickets                                           │
│ - Return relevant solutions                                     │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Agent)                                             │
│ 3. Analyzes solutions                                           │
│ 4. Calls: update_ticket(id, suggested_solution)                │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n Workflow 3: Update Ticket                                   │
│ - Update Jira with solution                                     │
│ - Auto-assign to engineer if complex                            │
│ - Send email to customer with workaround                        │
└─────────────────────────────────────────────────────────────────┘
场景:客户支持工单处理
┌─────────────────────────────────────────────────────────────────┐
│ User: "Customer reports login issue"                            │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Agent)                                             │
│ 1. Calls: create_support_ticket(issue_type="login")            │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n Workflow 1: Create Ticket                                   │
│ - Create Jira ticket                                            │
│ - Notify support team in Slack                                  │
│ - Return ticket ID                                              │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Agent)                                             │
│ 2. Calls: search_knowledge_base(query="login issues")          │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n Workflow 2: Knowledge Search                                │
│ - Query internal docs                                           │
│ - Search past tickets                                           │
│ - Return relevant solutions                                     │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Agent)                                             │
│ 3. Analyzes solutions                                           │
│ 4. Calls: update_ticket(id, suggested_solution)                │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n Workflow 3: Update Ticket                                   │
│ - Update Jira with solution                                     │
│ - Auto-assign to engineer if complex                            │
│ - Send email to customer with workaround                        │
└─────────────────────────────────────────────────────────────────┘

Pattern 2: Multi-Agent Orchestration

模式2:多代理编排

Scenario: Content creation pipeline with multiple specialized agents
┌─────────────────────────────────────────────────────────────────┐
│ Orchestrator Agent (Claude Code)                                │
│ "Create a blog post about our new feature"                      │
└─────────────────────────────────────────────────────────────────┘
        ┌─────────────────┼─────────────────┐
        ↓                 ↓                 ↓
┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│ Research     │  │ Writing      │  │ SEO          │
│ Agent        │  │ Agent        │  │ Agent        │
└──────────────┘  └──────────────┘  └──────────────┘
        │                 │                 │
        ↓ MCP             ↓ MCP             ↓ MCP
┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│ n8n: Gather  │  │ n8n: Generate│  │ n8n: Optimize│
│ data         │  │ content      │  │ for search   │
└──────────────┘  └──────────────┘  └──────────────┘
        │                 │                 │
        └─────────────────┼─────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Publishing Workflow                                        │
│ - Format content                                                │
│ - Upload images to CDN                                          │
│ - Publish to CMS                                                │
│ - Share on social media                                         │
│ - Notify marketing team                                         │
└─────────────────────────────────────────────────────────────────┘
场景:多专业代理的内容创建流水线
┌─────────────────────────────────────────────────────────────────┐
│ Orchestrator Agent (Claude Code)                                │
│ "Create a blog post about our new feature"                      │
└─────────────────────────────────────────────────────────────────┘
        ┌─────────────────┼─────────────────┐
        ↓                 ↓                 ↓
┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│ Research     │  │ Writing      │  │ SEO          │
│ Agent        │  │ Agent        │  │ Agent        │
└──────────────┘  └──────────────┘  └──────────────┘
        │                 │                 │
        ↓ MCP             ↓ MCP             ↓ MCP
┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│ n8n: Gather  │  │ n8n: Generate│  │ n8n: Optimize│
│ data         │  │ content      │  │ for search   │
└──────────────┘  └──────────────┘  └──────────────┘
        │                 │                 │
        └─────────────────┼─────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Publishing Workflow                                        │
│ - Format content                                                │
│ - Upload images to CDN                                          │
│ - Publish to CMS                                                │
│ - Share on social media                                         │
│ - Notify marketing team                                         │
└─────────────────────────────────────────────────────────────────┘

Pattern 3: Autonomous Agent Loop

模式3:自主代理循环

Scenario: Continuous monitoring and remediation
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Monitoring Workflow (runs every 5 minutes)                 │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ 1. Check system health metrics                              │ │
│ │ 2. If anomaly detected → Trigger MCP call to Claude        │ │
│ └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Anomaly detected
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Remediation Agent)                                 │
│ 1. Analyze metrics and logs                                     │
│ 2. Determine root cause                                         │
│ 3. Call: execute_remediation(action)                           │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Remediation Workflow                                       │
│ - Restart service if needed                                     │
│ - Scale resources                                               │
│ - Clear cache                                                   │
│ - Create incident ticket                                        │
│ - Alert on-call engineer                                        │
│ - Return results                                                │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code                                                     │
│ - Verify remediation successful                                 │
│ - Document incident                                             │
│ - Call: update_incident_log()                                  │
└─────────────────────────────────────────────────────────────────┘
场景:持续监控与修复
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Monitoring Workflow (runs every 5 minutes)                 │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ 1. Check system health metrics                              │ │
│ │ 2. If anomaly detected → Trigger MCP call to Claude        │ │
│ └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Anomaly detected
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Remediation Agent)                                 │
│ 1. Analyze metrics and logs                                     │
│ 2. Determine root cause                                         │
│ 3. Call: execute_remediation(action)                           │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Remediation Workflow                                       │
│ - Restart service if needed                                     │
│ - Scale resources                                               │
│ - Clear cache                                                   │
│ - Create incident ticket                                        │
│ - Alert on-call engineer                                        │
│ - Return results                                                │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code                                                     │
│ - Verify remediation successful                                 │
│ - Document incident                                             │
│ - Call: update_incident_log()                                  │
└─────────────────────────────────────────────────────────────────┘

Tool Composition and Chaining

工具组合与链式调用

Pattern: Sequential Tool Calls

模式:顺序工具调用

Build complex automations by chaining multiple MCP tool calls:
javascript
// Claude Code orchestrates sequence
async function processCustomerOrder(orderId) {
  // Step 1: Get order details
  const order = await mcpCall('n8n', 'get_order', { orderId });

  // Step 2: Validate inventory
  const inventory = await mcpCall('n8n', 'check_inventory', {
    items: order.items
  });

  if (!inventory.available) {
    // Step 3a: Order out of stock items
    await mcpCall('n8n', 'create_purchase_order', {
      items: inventory.missing
    });

    // Step 3b: Notify customer of delay
    await mcpCall('n8n', 'send_email', {
      to: order.customerEmail,
      template: 'order_delayed',
      data: { estimatedDate: inventory.restockDate }
    });
  } else {
    // Step 3: Process payment
    const payment = await mcpCall('n8n', 'process_payment', {
      orderId,
      amount: order.total
    });

    // Step 4: Create shipment
    await mcpCall('n8n', 'create_shipment', {
      orderId,
      address: order.shippingAddress
    });

    // Step 5: Send confirmation
    await mcpCall('n8n', 'send_email', {
      to: order.customerEmail,
      template: 'order_confirmed',
      data: { trackingNumber: payment.trackingNumber }
    });
  }
}
通过链式调用多个MCP工具构建复杂自动化:
javascript
// Claude Code orchestrates sequence
async function processCustomerOrder(orderId) {
  // Step 1: Get order details
  const order = await mcpCall('n8n', 'get_order', { orderId });

  // Step 2: Validate inventory
  const inventory = await mcpCall('n8n', 'check_inventory', {
    items: order.items
  });

  if (!inventory.available) {
    // Step 3a: Order out of stock items
    await mcpCall('n8n', 'create_purchase_order', {
      items: inventory.missing
    });

    // Step 3b: Notify customer of delay
    await mcpCall('n8n', 'send_email', {
      to: order.customerEmail,
      template: 'order_delayed',
      data: { estimatedDate: inventory.restockDate }
    });
  } else {
    // Step 3: Process payment
    const payment = await mcpCall('n8n', 'process_payment', {
      orderId,
      amount: order.total
    });

    // Step 4: Create shipment
    await mcpCall('n8n', 'create_shipment', {
      orderId,
      address: order.shippingAddress
    });

    // Step 5: Send confirmation
    await mcpCall('n8n', 'send_email', {
      to: order.customerEmail,
      template: 'order_confirmed',
      data: { trackingNumber: payment.trackingNumber }
    });
  }
}

Pattern: Parallel Tool Execution

模式:并行工具执行

Execute multiple tools simultaneously for efficiency:
javascript
// Claude Code executes in parallel
async function enrichCustomerProfile(customerId) {
  const [
    orders,
    supportTickets,
    socialData,
    emailEngagement
  ] = await Promise.all([
    mcpCall('n8n', 'get_customer_orders', { customerId }),
    mcpCall('n8n', 'get_support_history', { customerId }),
    mcpCall('n8n', 'get_social_data', { customerId }),
    mcpCall('n8n', 'get_email_metrics', { customerId })
  ]);

  // Combine all data
  const profile = {
    totalSpent: orders.reduce((sum, o) => sum + o.total, 0),
    supportIssues: supportTickets.length,
    sentimentScore: socialData.sentiment,
    emailEngagement: emailEngagement.averageClickRate
  };

  // Update CRM
  await mcpCall('n8n', 'update_crm', {
    customerId,
    profile
  });
}
同时执行多个工具以提高效率:
javascript
// Claude Code executes in parallel
async function enrichCustomerProfile(customerId) {
  const [
    orders,
    supportTickets,
    socialData,
    emailEngagement
  ] = await Promise.all([
    mcpCall('n8n', 'get_customer_orders', { customerId }),
    mcpCall('n8n', 'get_support_history', { customerId }),
    mcpCall('n8n', 'get_social_data', { customerId }),
    mcpCall('n8n', 'get_email_metrics', { customerId })
  ]);

  // Combine all data
  const profile = {
    totalSpent: orders.reduce((sum, o) => sum + o.total, 0),
    supportIssues: supportTickets.length,
    sentimentScore: socialData.sentiment,
    emailEngagement: emailEngagement.averageClickRate
  };

  // Update CRM
  await mcpCall('n8n', 'update_crm', {
    customerId,
    profile
  });
}

Resource Management

资源管理

Exposing Resources via MCP

通过MCP暴露资源

Resources provide context to AI agents without requiring tool invocation.
Resource Types:
  1. Documents: Markdown, text, PDFs
  2. Data: JSON, CSV, structured data
  3. Context: Configuration, metadata
  4. Templates: Prompt templates, code snippets
Example: Expose API Documentation as Resource
json
{
  "resources": [
    {
      "uri": "resource://api-docs/authentication",
      "name": "Authentication API Docs",
      "description": "Complete authentication API documentation",
      "mimeType": "text/markdown",
      "content": "# Authentication API\n\n## Endpoints\n\n### POST /auth/login..."
    },
    {
      "uri": "resource://api-docs/users",
      "name": "Users API Docs",
      "description": "User management API documentation",
      "mimeType": "text/markdown",
      "content": "# Users API\n\n## Endpoints\n\n### GET /users..."
    }
  ]
}
n8n Workflow to Serve Resources:
┌──────────────────────────────────────┐
│ MCP Server Trigger                   │
│ Resource: api-docs/*                 │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ Switch: Route by resource URI        │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ HTTP Request: Fetch from docs repo   │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ Format and return markdown           │
└──────────────────────────────────────┘
资源可为AI Agent提供上下文,无需调用工具。
资源类型:
  1. 文档:Markdown、文本、PDF
  2. 数据:JSON、CSV、结构化数据
  3. 上下文:配置、元数据
  4. 模板:提示模板、代码片段
示例:将API文档作为资源暴露
json
{
  "resources": [
    {
      "uri": "resource://api-docs/authentication",
      "name": "Authentication API Docs",
      "description": "Complete authentication API documentation",
      "mimeType": "text/markdown",
      "content": "# Authentication API\n\n## Endpoints\n\n### POST /auth/login..."
    },
    {
      "uri": "resource://api-docs/users",
      "name": "Users API Docs",
      "description": "User management API documentation",
      "mimeType": "text/markdown",
      "content": "# Users API\n\n## Endpoints\n\n### GET /users..."
    }
  ]
}
用于提供资源的n8n工作流:
┌──────────────────────────────────────┐
│ MCP Server Trigger                   │
│ Resource: api-docs/*                 │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ Switch: Route by resource URI        │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ HTTP Request: Fetch from docs repo   │
└──────────────────────────────────────┘
┌──────────────────────────────────────┐
│ Format and return markdown           │
└──────────────────────────────────────┘

Using Resources in AI Workflows

在AI工作流中使用资源

Claude Code can read resources for context:
User: "How do I authenticate with the API?"

Claude Code:
1. Reads resource: resource://api-docs/authentication
2. Analyzes documentation
3. Provides answer with code examples
Claude Code可读取资源获取上下文:
User: "How do I authenticate with the API?"

Claude Code:
1. Reads resource: resource://api-docs/authentication
2. Analyzes documentation
3. Provides answer with code examples

Production Deployment

生产部署

Hosting n8n MCP Servers

托管n8n MCP服务器

Deployment Options:
1. Self-Hosted n8n
yaml
undefined
部署选项:
1. 自托管n8n
yaml
undefined

docker-compose.yml

docker-compose.yml

version: '3.8' services: n8n: image: n8nio/n8n:latest ports: - "5678:5678" environment: - N8N_BASIC_AUTH_ACTIVE=true - N8N_BASIC_AUTH_USER=admin - N8N_BASIC_AUTH_PASSWORD=${N8N_PASSWORD} - N8N_MCP_ENABLED=true - N8N_MCP_PORT=8080 volumes: - n8n_data:/home/node/.n8n restart: unless-stopped
volumes: n8n_data:

**2. n8n Cloud**
- Fully managed n8n hosting
- Built-in MCP support
- Automatic scaling
- SSL/TLS included

**3. Kubernetes Deployment**
```yaml
version: '3.8' services: n8n: image: n8nio/n8n:latest ports: - "5678:5678" environment: - N8N_BASIC_AUTH_ACTIVE=true - N8N_BASIC_AUTH_USER=admin - N8N_BASIC_AUTH_PASSWORD=${N8N_PASSWORD} - N8N_MCP_ENABLED=true - N8N_MCP_PORT=8080 volumes: - n8n_data:/home/node/.n8n restart: unless-stopped
volumes: n8n_data:

**2. n8n云版本**
- 全托管n8n服务
- 内置MCP支持
- 自动扩容
- 包含SSL/TLS

**3. Kubernetes部署**
```yaml

n8n-deployment.yaml

n8n-deployment.yaml

apiVersion: apps/v1 kind: Deployment metadata: name: n8n-mcp-server spec: replicas: 3 selector: matchLabels: app: n8n template: metadata: labels: app: n8n spec: containers: - name: n8n image: n8nio/n8n:latest ports: - containerPort: 5678 name: http - containerPort: 8080 name: mcp env: - name: N8N_MCP_ENABLED value: "true" resources: requests: memory: "512Mi" cpu: "500m" limits: memory: "1Gi" cpu: "1000m"
undefined
apiVersion: apps/v1 kind: Deployment metadata: name: n8n-mcp-server spec: replicas: 3 selector: matchLabels: app: n8n template: metadata: labels: app: n8n spec: containers: - name: n8n image: n8nio/n8n:latest ports: - containerPort: 5678 name: http - containerPort: 8080 name: mcp env: - name: N8N_MCP_ENABLED value: "true" resources: requests: memory: "512Mi" cpu: "500m" limits: memory: "1Gi" cpu: "1000m"
undefined

Security Best Practices

安全最佳实践

1. Authentication
json
{
  "mcp": {
    "authentication": {
      "type": "oauth2",
      "provider": "okta",
      "clientId": "${OAUTH_CLIENT_ID}",
      "clientSecret": "${OAUTH_CLIENT_SECRET}",
      "authorizationUrl": "https://company.okta.com/oauth2/v1/authorize",
      "tokenUrl": "https://company.okta.com/oauth2/v1/token"
    }
  }
}
2. Rate Limiting
json
{
  "mcp": {
    "rateLimiting": {
      "enabled": true,
      "maxRequests": 100,
      "windowMs": 60000,
      "message": "Too many requests, please try again later"
    }
  }
}
3. IP Whitelisting
json
{
  "mcp": {
    "ipWhitelist": [
      "10.0.0.0/8",
      "172.16.0.0/12",
      "192.168.1.100"
    ]
  }
}
4. HTTPS Only
nginx
undefined
1. 身份验证
json
{
  "mcp": {
    "authentication": {
      "type": "oauth2",
      "provider": "okta",
      "clientId": "${OAUTH_CLIENT_ID}",
      "clientSecret": "${OAUTH_CLIENT_SECRET}",
      "authorizationUrl": "https://company.okta.com/oauth2/v1/authorize",
      "tokenUrl": "https://company.okta.com/oauth2/v1/token"
    }
  }
}
2. 速率限制
json
{
  "mcp": {
    "rateLimiting": {
      "enabled": true,
      "maxRequests": 100,
      "windowMs": 60000,
      "message": "Too many requests, please try again later"
    }
  }
}
3. IP白名单
json
{
  "mcp": {
    "ipWhitelist": [
      "10.0.0.0/8",
      "172.16.0.0/12",
      "192.168.1.100"
    ]
  }
}
4. 仅使用HTTPS
nginx
undefined

nginx.conf

nginx.conf

server { listen 443 ssl http2; server_name mcp.company.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;

location / {
    proxy_pass http://n8n:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}
}
undefined
server { listen 443 ssl http2; server_name mcp.company.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;

location / {
    proxy_pass http://n8n:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}
}
undefined

Monitoring and Debugging

监控与调试

Workflow Execution Logging:
javascript
// Add to n8n workflow
{
  "nodes": [
    {
      "name": "Log MCP Request",
      "type": "n8n-nodes-base.function",
      "parameters": {
        "functionCode": `
          const mcpRequest = $input.item.json;

          console.log('MCP Tool Invoked:', {
            tool: mcpRequest.tool,
            parameters: mcpRequest.parameters,
            timestamp: new Date().toISOString(),
            clientId: mcpRequest.clientId
          });

          return { json: mcpRequest };
        `
      }
    }
  ]
}
Error Handling:
javascript
// MCP error response format
{
  "error": {
    "code": "INVALID_PARAMETERS",
    "message": "Missing required parameter: customerId",
    "details": {
      "parameter": "customerId",
      "expected": "string",
      "received": "undefined"
    }
  }
}
Monitoring Metrics:
yaml
undefined
工作流执行日志:
javascript
// Add to n8n workflow
{
  "nodes": [
    {
      "name": "Log MCP Request",
      "type": "n8n-nodes-base.function",
      "parameters": {
        "functionCode": `
          const mcpRequest = $input.item.json;

          console.log('MCP Tool Invoked:', {
            tool: mcpRequest.tool,
            parameters: mcpRequest.parameters,
            timestamp: new Date().toISOString(),
            clientId: mcpRequest.clientId
          });

          return { json: mcpRequest };
        `
      }
    }
  ]
}
错误处理:
javascript
// MCP error response format
{
  "error": {
    "code": "INVALID_PARAMETERS",
    "message": "Missing required parameter: customerId",
    "details": {
      "parameter": "customerId",
      "expected": "string",
      "received": "undefined"
    }
  }
}
监控指标:
yaml
undefined

Prometheus metrics for n8n MCP

Prometheus metrics for n8n MCP

metrics:
  • mcp_tool_invocations_total
  • mcp_tool_execution_duration_seconds
  • mcp_tool_errors_total
  • mcp_active_connections
  • mcp_requests_per_second
undefined
metrics:
  • mcp_tool_invocations_total
  • mcp_tool_execution_duration_seconds
  • mcp_tool_errors_total
  • mcp_active_connections
  • mcp_requests_per_second
undefined

Best Practices

最佳实践

MCP Server Design

MCP服务器设计

  1. Clear Tool Names: Use verb-noun format (create_ticket, get_user)
  2. Comprehensive Descriptions: Help AI understand when to use each tool
  3. Validate Parameters: Always validate input parameters
  4. Return Structured Data: Use consistent JSON response formats
  5. Handle Errors Gracefully: Return meaningful error messages
  6. Version Your Tools: Support versioning for breaking changes
  7. Document Everything: Provide examples and usage guides
  1. 清晰的工具名称:使用动词-名词格式(create_ticket, get_user)
  2. 全面的描述:帮助AI理解何时使用每个工具
  3. 验证参数:始终验证输入参数
  4. 返回结构化数据:使用一致的JSON响应格式
  5. 优雅处理错误:返回有意义的错误信息
  6. 工具版本化:支持版本化以应对破坏性变更
  7. 完整文档:提供示例和使用指南

MCP Client Usage

MCP客户端使用

  1. Connection Pooling: Reuse MCP client connections
  2. Timeout Configuration: Set appropriate timeouts
  3. Retry Logic: Implement exponential backoff
  4. Error Handling: Catch and handle MCP errors
  5. Cache Responses: Cache expensive tool calls when appropriate
  6. Parallel Execution: Use Promise.all for independent calls
  7. Logging: Log all MCP interactions for debugging
  1. 连接池:复用MCP客户端连接
  2. 超时配置:设置合适的超时时间
  3. 重试逻辑:实现指数退避重试
  4. 错误处理:捕获并处理MCP错误
  5. 响应缓存:在合适时缓存昂贵的工具调用结果
  6. 并行执行:对独立调用使用Promise.all
  7. 日志记录:记录所有MCP交互以便调试

Workflow Optimization

工作流优化

  1. Minimize Tool Calls: Batch operations when possible
  2. Use Webhooks: For long-running operations
  3. Async Patterns: Don't block on slow operations
  4. Resource Limits: Set memory and CPU limits
  5. Monitoring: Track execution times and errors
  6. Testing: Test MCP tools independently
  7. Documentation: Keep tool documentation up-to-date
  1. 减少工具调用:尽可能批量操作
  2. 使用Webhook:处理长时间运行的操作
  3. 异步模式:不要阻塞在慢速操作上
  4. 资源限制:设置内存和CPU限制
  5. 监控:跟踪执行时间和错误
  6. 测试:独立测试MCP工具
  7. 文档:保持工具文档更新

Security Guidelines

安全指南

  1. Authentication: Always require authentication in production
  2. Authorization: Implement role-based access control
  3. Input Validation: Sanitize all inputs
  4. Rate Limiting: Prevent abuse
  5. Audit Logging: Log all tool invocations
  6. Secrets Management: Use environment variables
  7. HTTPS: Always use TLS in production
  1. 身份验证:生产环境中始终要求身份验证
  2. 授权:实现基于角色的访问控制
  3. 输入验证:清理所有输入
  4. 速率限制:防止滥用
  5. 审计日志:记录所有工具调用
  6. 密钥管理:使用环境变量存储密钥
  7. HTTPS:生产环境中始终使用TLS

Troubleshooting

故障排除

Common Issues

常见问题

Tool Not Appearing in Claude Code
Possible causes:
  • MCP server not registered in mcp_config.json
  • Tool description missing or unclear
  • Authentication failure
  • n8n workflow not activated
Solution:
  1. Verify MCP server URL is correct
  2. Check authentication credentials
  3. Ensure workflow is active in n8n
  4. Restart Claude Code to refresh tool list
MCP Tool Invocation Fails
Possible causes:
  • Invalid parameters
  • Timeout
  • n8n workflow error
  • Authentication expired
Solution:
  1. Check parameter types match schema
  2. Increase timeout in configuration
  3. Review n8n workflow execution logs
  4. Refresh authentication token
Slow Tool Execution
Possible causes:
  • Complex workflow
  • External API delays
  • Database queries
  • Network latency
Solution:
  1. Optimize workflow logic
  2. Add caching for repeated queries
  3. Use async patterns
  4. Scale n8n instances
Authentication Errors
Possible causes:
  • Expired API key
  • Wrong credentials
  • IP not whitelisted
  • OAuth token expired
Solution:
  1. Regenerate API key
  2. Verify credentials in configuration
  3. Add IP to whitelist
  4. Refresh OAuth token
工具未在Claude Code中显示
可能原因:
  • MCP服务器未在mcp_config.json中注册
  • 工具描述缺失或不清晰
  • 身份验证失败
  • n8n工作流未激活
解决方案:
  1. 验证MCP服务器URL是否正确
  2. 检查身份验证凭据
  3. 确保n8n工作流已激活
  4. 重启Claude Code刷新工具列表
MCP工具调用失败
可能原因:
  • 参数无效
  • 超时
  • n8n工作流错误
  • 身份验证过期
解决方案:
  1. 检查参数类型是否匹配模式
  2. 在配置中增加超时时间
  3. 查看n8n工作流执行日志
  4. 刷新身份验证令牌
工具执行缓慢
可能原因:
  • 工作流复杂
  • 外部API延迟
  • 数据库查询缓慢
  • 网络延迟
解决方案:
  1. 优化工作流逻辑
  2. 为重复查询添加缓存
  3. 使用异步模式
  4. 扩容n8n实例
身份验证错误
可能原因:
  • API密钥过期
  • 凭据错误
  • IP未在白名单中
  • OAuth令牌过期
解决方案:
  1. 重新生成API密钥
  2. 验证配置中的凭据
  3. 将IP添加到白名单
  4. 刷新OAuth令牌

Advanced Patterns

高级模式

Pattern: Event-Driven Architecture

模式:事件驱动架构

┌─────────────────────────────────────────────────────────────────┐
│ External System (e.g., Stripe)                                  │
│ Event: payment_succeeded                                        │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Webhook
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Webhook Trigger                                            │
│ 1. Receive payment event                                        │
│ 2. Call MCP: analyze_payment_risk()                            │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Call
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Risk Analysis Agent)                               │
│ - Analyze transaction pattern                                   │
│ - Check customer history                                        │
│ - Assess fraud risk                                             │
│ - Return risk score                                             │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Risk-Based Routing                                         │
│ IF risk_score > 0.7:                                            │
│   - Flag for manual review                                      │
│   - Notify fraud team                                           │
│ ELSE:                                                           │
│   - Auto-approve                                                │
│   - Trigger fulfillment                                         │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ External System (e.g., Stripe)                                  │
│ Event: payment_succeeded                                        │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Webhook
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Webhook Trigger                                            │
│ 1. Receive payment event                                        │
│ 2. Call MCP: analyze_payment_risk()                            │
└─────────────────────────────────────────────────────────────────┘
                          ↓ MCP Call
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code (Risk Analysis Agent)                               │
│ - Analyze transaction pattern                                   │
│ - Check customer history                                        │
│ - Assess fraud risk                                             │
│ - Return risk score                                             │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ n8n: Risk-Based Routing                                         │
│ IF risk_score > 0.7:                                            │
│   - Flag for manual review                                      │
│   - Notify fraud team                                           │
│ ELSE:                                                           │
│   - Auto-approve                                                │
│   - Trigger fulfillment                                         │
└─────────────────────────────────────────────────────────────────┘

Pattern: Human-in-the-Loop

模式:人工介入循环

┌─────────────────────────────────────────────────────────────────┐
│ Claude Code: Draft email response                               │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Call MCP tool
┌─────────────────────────────────────────────────────────────────┐
│ n8n: request_human_approval(draft)                              │
│ 1. Send draft to manager via Slack                              │
│ 2. Wait for approval (webhook)                                  │
│ 3. Return approval status                                       │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Approval received
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code: Send approved email                                │
│ Call: send_email(approved_draft)                               │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code: Draft email response                               │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Call MCP tool
┌─────────────────────────────────────────────────────────────────┐
│ n8n: request_human_approval(draft)                              │
│ 1. Send draft to manager via Slack                              │
│ 2. Wait for approval (webhook)                                  │
│ 3. Return approval status                                       │
└─────────────────────────────────────────────────────────────────┘
                          ↓ Approval received
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code: Send approved email                                │
│ Call: send_email(approved_draft)                               │
└─────────────────────────────────────────────────────────────────┘

Pattern: Multi-Modal Processing

模式:多模态处理

┌─────────────────────────────────────────────────────────────────┐
│ User uploads image to chat                                      │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code: Analyze image                                      │
│ - Extract text (OCR)                                            │
│ - Detect objects                                                │
│ - Identify action items                                         │
└─────────────────────────────────────────────────────────────────┘
                          ↓ For each action item
┌─────────────────────────────────────────────────────────────────┐
│ n8n MCP Tools:                                                  │
│ - create_task(item)                                             │
│ - send_notification(team)                                       │
│ - update_dashboard(metrics)                                     │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ User uploads image to chat                                      │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code: Analyze image                                      │
│ - Extract text (OCR)                                            │
│ - Detect objects                                                │
│ - Identify action items                                         │
└─────────────────────────────────────────────────────────────────┘
                          ↓ For each action item
┌─────────────────────────────────────────────────────────────────┐
│ n8n MCP Tools:                                                  │
│ - create_task(item)                                             │
│ - send_notification(team)                                       │
│ - update_dashboard(metrics)                                     │
└─────────────────────────────────────────────────────────────────┘

Quick Reference

快速参考

Essential n8n MCP Nodes

核心n8n MCP节点

MCP Server Trigger
  • Exposes workflow as AI-callable tool
  • Define tool name, description, parameters
  • Returns workflow output to AI client
MCP Client Tool
  • Calls external MCP servers
  • Specify server URL and tool name
  • Pass parameters and handle response
MCP Server Trigger
  • 将工作流暴露为AI可调用工具
  • 定义工具名称、描述和参数
  • 将工作流输出返回给AI客户端
MCP Client Tool
  • 调用外部MCP服务器
  • 指定服务器URL和工具名称
  • 传递参数并处理响应

Common Tool Patterns

常见工具模式

Create Resource
json
{
  "tool": "create_resource",
  "parameters": {
    "type": "string",
    "data": "object"
  },
  "returns": {
    "id": "string",
    "status": "string"
  }
}
Update Resource
json
{
  "tool": "update_resource",
  "parameters": {
    "id": "string",
    "updates": "object"
  },
  "returns": {
    "success": "boolean",
    "resource": "object"
  }
}
Query Data
json
{
  "tool": "query_data",
  "parameters": {
    "filters": "object",
    "limit": "number"
  },
  "returns": {
    "data": "array",
    "total": "number"
  }
}
创建资源
json
{
  "tool": "create_resource",
  "parameters": {
    "type": "string",
    "data": "object"
  },
  "returns": {
    "id": "string",
    "status": "string"
  }
}
更新资源
json
{
  "tool": "update_resource",
  "parameters": {
    "id": "string",
    "updates": "object"
  },
  "returns": {
    "success": "boolean",
    "resource": "object"
  }
}
查询数据
json
{
  "tool": "query_data",
  "parameters": {
    "filters": "object",
    "limit": "number"
  },
  "returns": {
    "data": "array",
    "total": "number"
  }
}

Resources

资源


Skill Version: 1.0.0 Last Updated: October 2025 Skill Category: AI Orchestration, Workflow Automation, MCP Integration Compatible With: n8n, Claude Code, Claude Desktop, MCP Protocol

技能版本:1.0.0 最后更新:2025年10月 技能分类:AI编排、工作流自动化、MCP集成 兼容对象:n8n、Claude Code、Claude Desktop、MCP协议