mcpField
N
n8n-mcp-orchestrator

n8n-mcp-orchestrator

github.com/manutejAgent 工作流179 次安装48 周前更新
代码仓库

关于 n8n-mcp-orchestrator

n8n-mcp-orchestrator 是一项技能,介绍如何借助 n8n 的 MCP 集成设计 AI 自动化与 Agent 工作流。内容涵盖将 n8n 工作流作为工具公开,以及从工作流调用外部 MCP 服务。

主要功能

  1. 01将 n8n 工作流公开为 MCP 工具
  2. 02从工作流调用外部 MCP 服务工具
  3. 03配置身份验证与工具参数
  4. 04在自动化工作流中串联 MCP 调用
  5. 05协调多 Agent 工作流模式

适用场景

  1. 01让 AI Agent 触发业务工作流
  2. 02在定时自动化中使用外部 MCP 工具
  3. 03协调多步骤或多 Agent 流程

MCP 相关

介绍 MCP 的双向用法:n8n 工作流可作为 MCP 服务公开工具,也可作为客户端调用外部 MCP 服务的工具;还说明了工作流中的资源与提示词。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/manutej/crush-mcp-server --skill n8n-mcp-orchestrator

安装后在 Claude Code 中输入/n8n-mcp-orchestrator确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

EXAMPLES.md
mcp-client-patterns.md
mcp-server-setup.md
README.md
SUMMARY.txt

详细介绍

n8n MCP 编排器

一项全面的技能,用于通过 n8n 的 Model Context Protocol(MCP)集成来编排 AI Agent 和工作流。此技能支持双向 MCP 模式、Agent 式工作流自动化,以及与 Claude Code 集成的生产就绪型 AI 系统。

何时使用此技能

在以下情况下使用此技能:

  • 使用 n8n 构建 AI 驱动的自动化工作流
  • 将 n8n 工作流作为工具提供给 AI Agent(Claude Code、Claude Desktop)
  • 从 n8n 工作流调用外部 MCP 服务
  • 编排多 Agent 系统和 Agent 式工作流
  • 使用 n8n 后端创建可调用工具的 AI Agent
  • 将 Claude Code 与业务流程自动化集成
  • 使用 MCP 资源构建上下文感知型自动化
  • 协调多个 AI Agent 之间的复杂工作流
  • 开发生产就绪型 AI 编排流水线
  • 实现双向 MCP 通信模式
  • 创建具有工作流编排能力的自主 Agent 系统
  • 通过 400 多种服务集成构建 AI 优先的自动化

核心概念

Model Context Protocol(MCP)

Model Context Protocol 是一项开放标准,用于将 AI 助手连接到外部系统:

  • 双向通信:客户端和服务端都可以发起请求
  • 资源管理:将数据和上下文作为资源提供
  • 工具调用:AI Agent 可以执行工具(函数/工作流)
  • 提示词模板:为 AI 系统提供结构化提示词
  • 安全性:内置身份验证和授权模式
  • 可扩展性:专为生产级 AI 编排而设计
MCP 架构组件

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 的双向 MCP 能力

n8n 作为 MCP 服务(将工作流作为工具提供):

  • MCP Server Trigger 节点会在 AI 调用工作流时将其激活
  • 工作流会成为 Claude Code 可以调用的工具
  • 让 AI Agent 能够自动执行复杂业务流程
  • 向 AI 客户端返回结构化数据

n8n 作为 MCP 客户端(调用外部 MCP 服务):

  • MCP Client Tool 节点会调用外部 MCP 服务
  • 调用其他兼容 MCP 的服务中的工具
  • 在单个工作流中编排多个 MCP 服务
  • 构建复杂的自动化链
n8n 中的关键 MCP 节点

1. MCP Server Trigger

  • MCP 工具调用的工作流入口点
  • 接收来自 AI Agent 的参数
  • 向调用的 AI 客户端返回结果
  • 支持身份验证和验证

2. MCP Client Tool

  • 调用外部 MCP 服务的工具
  • 向远程工具传递参数
  • 处理响应和错误
  • 链式调用多个 MCP

n8n 作为 MCP 服务

将工作流作为 AI Agent 工具提供

创建包含 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 服务触发器配置

基本设置:

  1. 创建新工作流(在 n8n 中)

  2. 添加 MCP 服务触发器节点作为入口点

  3. 配置工具定义:

    • 工具名称:唯一标识符(例如,“create_support_ticket”)
    • 描述:清晰描述工具用途,便于 AI 理解何时使用
    • 参数:定义输入架构(JSON Schema 格式)
    • 身份验证:可选的身份验证设置
  4. 构建工作流逻辑:添加用于处理请求的节点

  5. 返回响应:最后一个节点的输出将成为 MCP 响应

MCP 服务触发器参数:

{
  "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"]
  }
}
响应格式

工作流中最后一个节点的输出会返回给 AI Agent:

{
  "success": true,
  "ticketId": "JIRA-12345",
  "url": "https://company.atlassian.net/browse/JIRA-12345",
  "assignee": "[email protected]",
  "createdAt": "2025-10-20T10:30:00Z"
}
身份验证模式

1. API Key 身份验证

{
  "authenticationType": "apiKey",
  "apiKeyHeader": "X-API-Key",
  "requiredScopes": ["workflows:execute"]
}

2. OAuth 2.0

{
  "authenticationType": "oauth2",
  "authorizationUrl": "https://auth.company.com/oauth/authorize",
  "tokenUrl": "https://auth.company.com/oauth/token",
  "scopes": ["workflows:read", "workflows:execute"]
}

3. 无需身份验证(仅供内部使用)

{
  "authenticationType": "none"
}

将 n8n 用作 MCP 客户端

使用外部 MCP 服务

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 配置

基本设置:

  1. 将 MCP Client Tool 节点添加到工作流

  2. 配置 MCP 服务连接:

    • 服务 URL:MCP 服务端点
    • 身份验证:API key、OAuth 或无
    • 超时:请求超时时间(默认:30s)
  3. 选择工具:从 MCP 服务提供的工具中选择

  4. 提供参数:将工作流数据映射到工具参数

  5. 处理响应:在后续节点中处理返回的数据

MCP Client Tool 配置:

{
  "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
}
发现可用工具

MCP 服务通过协议公开其可用工具:

{
  "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 集成

将 Claude Code 连接到 n8n 工作流

前提条件:

  1. n8n 实例正在运行(可自托管或使用云服务)
  2. 已配置 MCP 服务触发器的 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:

{
  "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)"
双向 Claude Code ↔ n8n 集成

模式 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

组合模式:Agent 工作流

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

Agent 工作流模式

模式 1:多步骤 Agent 工作流

场景: 客户支持工单处理

┌─────────────────────────────────────────────────────────────────┐
│ 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                        │
└─────────────────────────────────────────────────────────────────┘
模式 2:多 Agent 编排

场景: 由多个专业 Agent 组成的内容创作流程

┌─────────────────────────────────────────────────────────────────┐
│ 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                                         │
└─────────────────────────────────────────────────────────────────┘
模式 3:自主 Agent 循环

场景: 持续监控和修复

┌─────────────────────────────────────────────────────────────────┐
│ 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()                                  │
└─────────────────────────────────────────────────────────────────┘

工具组合与串联

模式:顺序调用工具

通过串联多个 MCP 工具调用来构建复杂自动化流程:

// 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 }
    });
  }
}
模式:并行执行工具

同时执行多个工具以提高效率:

// 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
  });
}

资源管理

通过 MCP 公开资源

资源可以为 AI Agent 提供上下文,而无需调用工具。

资源类型:

  1. 文档:Markdown、文本、PDF
  2. 数据:JSON、CSV、结构化数据
  3. 上下文:配置、元数据
  4. 模板:提示词模板、代码片段

示例:将 API 文档作为资源公开

{
  "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           │
└──────────────────────────────────────┘
在 AI 工作流中使用资源

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

生产环境部署

托管 n8n MCP 服务

部署选项:

1. 自托管 n8n

# 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

  • 完全托管的 n8n 服务
  • 内置 MCP 支持
  • 自动扩展
  • 包含 SSL/TLS

3. Kubernetes 部署

# 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"
安全最佳实践

1. 身份验证

{
  "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. 速率限制

{
  "mcp": {
    "rateLimiting": {
      "enabled": true,
      "maxRequests": 100,
      "windowMs": 60000,
      "message": "Too many requests, please try again later"
    }
  }
}

3. IP 白名单

{
  "mcp": {
    "ipWhitelist": [
      "10.0.0.0/8",
      "172.16.0.0/12",
      "192.168.1.100"
    ]
  }
}

4. 仅使用 HTTPS

# 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;
    }
}
监控与调试

工作流执行日志:

// 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 };
        `
      }
    }
  ]
}

错误处理:

// MCP error response format
{
  "error": {
    "code": "INVALID_PARAMETERS",
    "message": "Missing required parameter: customerId",
    "details": {
      "parameter": "customerId",
      "expected": "string",
      "received": "undefined"
    }
  }
}

监控指标:

# 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

最佳实践

MCP 服务设计
  1. 清晰的工具名称:使用动词-名词格式(create_ticket、get_user)
  2. 全面的描述:帮助 AI 理解何时使用每个工具
  3. 验证参数:始终验证输入参数
  4. 返回结构化数据:使用一致的 JSON 响应格式
  5. 妥善处理错误:返回有意义的错误消息
  6. 为工具添加版本:支持针对破坏性变更进行版本管理
  7. 记录所有内容:提供示例和使用指南
MCP 客户端使用
  1. 连接池:复用 MCP 客户端连接
  2. 超时配置:设置适当的超时时间
  3. 重试逻辑:实现指数退避
  4. 错误处理:捕获并处理 MCP 错误
  5. 缓存响应:在适当情况下缓存开销较大的工具调用
  6. 并行执行:对相互独立的调用使用 Promise.all
  7. 日志记录:记录所有 MCP 交互,以便调试
工作流优化
  1. 尽量减少工具调用:尽可能批量执行操作
  2. 使用 Webhook:处理长时间运行的操作
  3. 异步模式:不要因缓慢的操作而阻塞
  4. 资源限制:设置内存和 CPU 限制
  5. 监控:跟踪执行时间和错误
  6. 测试:独立测试 MCP 工具
  7. 文档:及时更新工具文档
安全指南
  1. 身份验证:生产环境中始终要求身份验证
  2. 授权:实施基于角色的访问控制
  3. 输入验证:清理所有输入
  4. 速率限制:防止滥用
  5. 审计日志:记录所有工具调用
  6. 密钥管理:使用环境变量
  7. HTTPS:生产环境中始终使用 TLS

故障排除

常见问题

工具未显示在 Claude Code 中

可能原因:

  • 未在 mcp_config.json 中注册 MCP 服务
  • 工具描述缺失或不清晰
  • 身份验证失败
  • 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 令牌

高级模式

模式:事件驱动架构
┌─────────────────────────────────────────────────────────────────┐
│ 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                                         │
└─────────────────────────────────────────────────────────────────┘
模式:人在回路中
┌─────────────────────────────────────────────────────────────────┐
│ 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)                               │
└─────────────────────────────────────────────────────────────────┘
模式:多模态处理
┌─────────────────────────────────────────────────────────────────┐
│ 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)                                     │
└─────────────────────────────────────────────────────────────────┘

快速参考

必备 n8n MCP 节点

MCP 服务触发器

  • 将工作流公开为可由 AI 调用的工具
  • 定义工具名称、描述和参数
  • 将工作流输出返回给 AI 客户端

MCP 客户端工具

  • 调用外部 MCP 服务
  • 指定服务 URL 和工具名称
  • 传递参数并处理响应
常见工具模式

创建资源

{
  "tool": "create_resource",
  "parameters": {
    "type": "string",
    "data": "object"
  },
  "returns": {
    "id": "string",
    "status": "string"
  }
}

更新资源

{
  "tool": "update_resource",
  "parameters": {
    "id": "string",
    "updates": "object"
  },
  "returns": {
    "success": "boolean",
    "resource": "object"
  }
}

查询数据

{
  "tool": "query_data",
  "parameters": {
    "filters": "object",
    "limit": "number"
  },
  "returns": {
    "data": "array",
    "total": "number"
  }
}

资源


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

评论

支持 Markdown