第 21 期:MCP Server — 将 Dify 应用发布为工具

Updated on 4/6/2026

[Translation Pending]\n\n## MCP 协议概述

MCP (Model Context Protocol) 是 Anthropic 提出的开放协议,允许 AI 应用之间互相调用工具和共享上下文。Dify 原生支持将应用发布为 MCP Server。

graph LR
    subgraph "MCP 生态"
        Client1[Claude Desktop] --> |MCP| Server1[Dify App A]
        Client2[其他 Agent] --> |MCP| Server1
        Client1 --> |MCP| Server2[Dify App B]
        Client3[自定义客户端] --> |MCP| Server2
    end

将 Dify App 发布为 MCP Server

在 Dify 后台,选择某个 App → Publish → MCP Server:

# MCP Server 配置
server:
  name: "company-knowledge-qa"
  description: "企业知识库问答服务"
  version: "1.0.0"
  
tools:
  - name: ask_knowledge
    description: "查询企业知识库中的信息"
    input_schema:
      type: object
      properties:
        question:
          type: string
          description: "要查询的问题"
      required: ["question"]

在 Claude Desktop 中调用

// claude_desktop_config.json
{
  "mcpServers": {
    "dify-knowledge": {
      "url": "http://localhost/api/mcp/your-app-token",
      "description": "Dify 企业知识库"
    }
  }
}

编程方式调用 MCP Server

# 使用 MCP SDK 调用 Dify MCP Server
from mcp import ClientSession
from mcp.client.stdio import stdio_client

async def query_dify_mcp():
    async with stdio_client(
        server_url="http://localhost/api/mcp/your-app-token"
    ) as (read, write):
        async with ClientSession(read, write) as session:
            # 列出可用工具
            tools = await session.list_tools()
            print(f"可用工具: {[t.name for t in tools]}")
            
            # 调用工具
            result = await session.call_tool(
                "ask_knowledge",
                arguments={"question": "公司的年假政策是什么?"}
            )
            print(f"回答: {result}")

MCP Server 架构

sequenceDiagram
    participant Client as MCP Client
    participant Server as Dify MCP Server
    participant App as Dify App
    participant KB as 知识库
    participant LLM as LLM

    Client->>Server: list_tools()
    Server->>Client: [ask_knowledge, ...]
    Client->>Server: call_tool("ask_knowledge", {question: "..."})
    Server->>App: 触发 Workflow/Chatflow
    App->>KB: 知识库检索
    KB->>App: 相关段落
    App->>LLM: 上下文 + 问题
    LLM->>App: 回答
    App->>Server: 返回结果
    Server->>Client: tool_result