跳转到主要内容

实战案例

10.1 案例1:电商客服MCP Server

场景: 让Claude/ChatGPT成为你的客服助手,回答客户关于订单、物流、退货的问题。 工具设计:
工具功能
get_order_status根据订单号查询状态
track_shipment查询物流轨迹
check_return_eligibility检查是否满足退货条件
create_return_request创建退货申请
get_faq获取常见问题答案
Resources设计:
资源URI内容Annotations
store://policies/return退货政策audience: ["assistant"], priority: 0.9
store://policies/shipping配送说明audience: ["assistant"], priority: 0.8
store://faq/common高频问题audience: ["assistant", "user"], priority: 0.7
Prompts设计:
server.prompt(
  "customer_service_mode",
  "启动客服助手模式,加载店铺政策和常见问题",
  [],
  async () => ({
    messages: [{
      role: "assistant",
      content: {
        type: "text",
        text: "你是一个专业的客服助手。基于店铺政策回答问题,遇到无法处理的投诉请建议转人工。"
      }
    }]
  })
);
Elicitation应用: 退货申请时,通过Elicitation向用户确认退货原因和退款方式:
server.tool("create_return_request", "创建退货申请", {
  orderId: { type: "string" }
}, async ({ orderId }, { requestElicitation }) => {
  // 通过Elicitation请求用户确认
  const confirmation = await requestElicitation({
    message: "请确认退货信息",
    requestedSchema: {
      type: "object",
      properties: {
        reason: { type: "string", enum: ["质量问题", "尺码不合", "不想要了", "其他"] },
        refundMethod: { type: "string", enum: ["原路退回", "账户余额"] }
      },
      required: ["reason", "refundMethod"]
    }
  });
  // 创建退货...
  return {
    content: [{ type: "text", text: `退货申请已创建,退款方式:${confirmation.refundMethod}` }]
  };
});
用户对话示例:
用户: 我的订单 ORD-20260410-001 到哪了?
AI: [调用get_order_status] 您的订单已发货,快递单号SF1234567890。
    [调用track_shipment] 最新状态:4月10日 15:23 已到达北京分拨中心,
    预计明天送达。
价值: 7x24小时自动回复,减少客服工作量60%以上。

10.2 案例2:B2B供应链查询

场景: 让采购人员通过AI助手快速查询供应商的库存和报价。 工具设计:
server.tool("query_supplier_inventory", "查询供应商库存和报价", {
  productCode: { type: "string", description: "产品编号" },
  quantity: { type: "number", description: "需求数量" },
  supplierId: { type: "string", description: "供应商ID" }
}, async ({ productCode, quantity, supplierId }) => {
  const quote = await supplierApi.getQuote(supplierId, productCode, quantity);
  const data = {
    supplier: quote.supplierName,
    product: quote.productName,
    unitPrice: quote.unitPrice,
    totalPrice: quote.totalPrice,
    currency: quote.currency,
    leadTime: quote.leadTimeDays,
    moq: quote.minimumOrderQuantity,
    inStock: quote.availableQuantity
  };
  return {
    content: [{
      type: "text",
      text: JSON.stringify(data, null, 2)
    }],
    structuredContent: data
  };
});

server.tool("compare_suppliers", "对比多个供应商的报价", {
  productCode: { type: "string", description: "产品编号" },
  quantity: { type: "number", description: "需求数量" },
  supplierIds: { type: "string", description: "供应商ID列表,逗号分隔" }
}, async ({ productCode, quantity, supplierIds }) => {
  const ids = supplierIds.split(",").map(s => s.trim());
  const quotes = await Promise.all(
    ids.map(id => supplierApi.getQuote(id, productCode, quantity))
  );
  const comparison = quotes
    .sort((a, b) => a.unitPrice - b.unitPrice)
    .map((q, i) => ({
      rank: i + 1,
      supplier: q.supplierName,
      unitPrice: q.unitPrice,
      leadTime: q.leadTimeDays,
      moq: q.minimumOrderQuantity
    }));
  return {
    content: [{
      type: "text",
      text: JSON.stringify(comparison, null, 2)
    }]
  };
});
Sampling应用: 利用Sampling请求Host的LLM生成采购建议:
server.tool("procurement_advice", "基于报价数据生成采购建议", {
  productCode: { type: "string" },
  quantity: { type: "number" }
}, async ({ productCode, quantity }, { requestSampling }) => {
  const quotes = await supplierApi.getAllQuotes(productCode, quantity);
  // 通过Sampling请求LLM分析
  const analysis = await requestSampling({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `分析以下供应商报价,推荐最优采购方案:\n${JSON.stringify(quotes, null, 2)}`
      }
    }],
    maxTokens: 500,
    modelPreferences: {
      intelligencePriority: 0.8,
      costPriority: 0.2
    }
  });
  return {
    content: [{ type: "text", text: analysis.content.text }]
  };
});

10.3 案例3:多店铺管理

场景: 经营多个电商店铺(Shopify+WooCommerce+自营站),通过MCP统一管理。 工具设计:
工具功能
list_stores列出所有店铺
get_store_stats获取指定店铺的销售数据
sync_inventory跨店铺同步库存
compare_performance对比多店铺的业绩指标
Resources: 各平台API配置作为资源暴露
server.resource(
  "stores://platforms",
  "已连接的电商平台",
  "application/json",
  async () => {
    return JSON.stringify([
      { id: "shopify-main", platform: "Shopify", name: "主站", status: "active" },
      { id: "woo-1", platform: "WooCommerce", name: "副站", status: "active" },
      { id: "self-hosted", platform: "Custom", name: "自营站", status: "active" }
    ], null, 2);
  }
);
用户对话示例:
用户: 对比一下我三个店铺这周的销售情况
AI: [调用get_store_stats x 3]

    本周销售对比:
    | 店铺 | 订单数 | 销售额 | 转化率 |
    |------|--------|--------|--------|
    | Shopify主站 | 142 | 89,400元 | 3.2% |
    | WooCommerce | 68 | 42,100元 | 2.8% |
    | 自营站 | 35 | 28,600元 | 4.1% |

    自营站的转化率最高,但流量最少。
    建议把Shopify的流量引流策略应用到自营站。

10.4 案例4:OTR信任评估集成

场景: AI代理在推荐商家前,先查询其OTR信任评分,确保推荐的是可信商家。 工具设计:
server.tool("verify_merchant", "验证商家信任度", {
  domain: { type: "string", description: "商家域名" }
}, async ({ domain }) => {
  const otrResponse = await fetch(
    `https://${domain}/.well-known/otr/verify`
  );

  if (!otrResponse.ok) {
    return {
      content: [{
        type: "text",
        text: `${domain} 未部署OTR协议,无法验证信任度。建议谨慎交易。`
      }],
      isError: false  // 这不是错误,只是缺少OTR数据
    };
  }

  const otr = await otrResponse.json();
  return {
    content: [{
      type: "text",
      text: JSON.stringify({
        domain: otr.domain,
        trustScore: otr.trustScore,
        badges: otr.badges,
        dimensions: {
          identity: otr.dimensions?.I,
          security: otr.dimensions?.S,
          transparency: otr.dimensions?.T,
          reputation: otr.dimensions?.R,
          durability: otr.dimensions?.D,
          financial: otr.dimensions?.F
        },
        recommendation: otr.trustScore >= 70
          ? "信任评分良好,可以放心交易"
          : otr.trustScore >= 40
          ? "信任评分一般,建议进一步了解后决定"
          : "信任评分较低,建议谨慎"
      }, null, 2)
    }]
  };
});
使用场景: AI购物助手在推荐商品时自动验证商家信任度:
用户: 帮我找一个靠谱的户外装备店
AI: [调用search_products 搜索户外装备]
    [调用verify_merchant 验证 outdoorgear.com]
    [调用verify_merchant 验证 hikestore.cn]

    推荐两家经过OTR信任验证的户外装备店:

    1. outdoorgear.com — OTR信任评分 82/100
       六维评估: 身份A / 安全A / 透明B / 声誉B / 耐久A / 财务B

    2. hikestore.cn — OTR信任评分 71/100
       六维评估: 身份B / 安全B / 透明B / 声誉C / 耐久B / 财务C

    两家都通过了基本信任验证。outdoorgear.com的整体评分更高。

10.5 快速上手路径

如果你是第一次构建MCP Server:
  1. 第1小时: 读完本书第1-4章,理解MCP架构和开发流程
  2. 第2小时: 用MCP Inspector跑通第4章的示例代码
  3. 第3-4小时: 基于第5章的模板,构建你自己的商务Server
  4. 第5小时: 在Claude Desktop中测试,确认工具正常工作
  5. 后续: 根据需要扩展工具、添加Resources和Prompts、部署到远程

AI提示词:快速构建MCP Server

请帮我构建一个MCP Server。

我已经阅读了MCP协议文档(modelcontextprotocol.io),
现在需要你帮我实现。

需求:
- 语言:TypeScript
- 协议版本:2025-11-25
- 工具列表:
  1. 【工具名】: 【功能描述】,输入【参数】,返回【数据】
  2. 【工具名】: 【功能描述】,输入【参数】,返回【数据】
- Resources: 【需要暴露的数据资源】
- Prompts: 【需要预定义的提示词模板】
- 数据源:【数据库连接信息 / API地址】
- 传输方式:【stdio / Streamable HTTP】

请提供:
1. 完整的可运行代码(含outputSchema和structuredContent)
2. package.json
3. tsconfig.json
4. Claude Desktop配置文件
5. 测试命令

恭喜你读完了Book 5。现在你掌握了MCP协议的完整知识,可以构建自己的MCP Server让AI代理与你的系统交互。 接下来推荐:
下一步推荐: SEO for AI — 让AI代理发现你的站点和商品 其他实战案例: OTR案例 | UCP案例 | SEO案例