> ## Documentation Index
> Fetch the complete documentation index at: https://learn.orbexa.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 电商MCP Server设计模式与实现

> 电商场景MCP Server设计模式与完整实现方案，包含商品搜索、库存查询、订单管理、退货处理与物流追踪等核心业务工具的TypeScript代码示例。深入讲解单一职责的工具设计原则、inputSchema参数验证规范及面向AI模型友好的工具描述与结构化响应编写方法

# 商务 MCP Server

## 5.1 电商MCP Server的工具设计

一个完整的电商MCP Server通常包含以下工具：

| 工具名               | 功能     | 输入                                 | 输出       |
| ----------------- | ------ | ---------------------------------- | -------- |
| `search_products` | 搜索商品   | query, category, priceRange, limit | 商品列表     |
| `get_product`     | 获取商品详情 | productId或sku                      | 单个商品完整信息 |
| `check_inventory` | 查询库存   | sku, warehouse(可选)                 | 库存数量和位置  |
| `get_price`       | 获取价格   | sku, quantity, couponCode(可选)      | 实时价格含折扣  |
| `get_order`       | 查询订单   | orderId                            | 订单状态和明细  |
| `list_orders`     | 订单列表   | userId, status(可选), limit          | 用户订单列表   |
| `create_return`   | 发起退货   | orderId, items, reason             | 退货单号     |
| `get_shipping`    | 查询物流   | orderId或trackingNumber             | 物流状态和轨迹  |
| `get_categories`  | 获取分类   | parentId(可选)                       | 分类树      |
| `get_promotions`  | 查询促销   | category(可选)                       | 当前活动列表   |

## 5.2 工具设计原则

### 单一职责

每个工具做一件事。不要把搜索和下单放在同一个工具里。AI模型会根据上下文自动组合多个工具。

### 清晰的描述

工具的 `description` 直接影响AI模型何时选择使用它。写清楚：

* 这个工具做什么
* 什么场景下应该使用
* 返回什么类型的数据

```typescript theme={null}
// 好的描述
"搜索商品目录，支持按关键词、分类、价格范围筛选。返回商品名称、价格、库存状态。"

// 不好的描述
"搜索商品"
```

### 合理的参数设计

* 必填参数要少（降低使用门槛）
* 可选参数提供默认值
* 参数描述要具体

### 善用structuredContent

对于需要程序化处理的返回数据（如价格计算、库存对比），同时提供 `content`（给LLM阅读）和 `structuredContent`（给程序处理）：

```typescript theme={null}
return {
  content: [{
    type: "text",
    text: "Nike Air Max (SHOE-001): 899元, 库存充足\nAdidas Ultra Boost (SHOE-002): 1299元, 无库存"
  }],
  structuredContent: {
    products: [
      { name: "Nike Air Max", sku: "SHOE-001", price: 899, inStock: true },
      { name: "Adidas Ultra Boost", sku: "SHOE-002", price: 1299, inStock: false }
    ],
    total: 42,
    page: 1
  }
};
```

### 善用isError区分业务错误

工具执行中遇到的业务问题（如商品不存在、库存不足），使用 `isError: true` 而不是抛出异常：

```typescript theme={null}
if (!product) {
  return {
    content: [{ type: "text", text: `SKU ${sku} 不存在，请检查编号` }],
    isError: true
  };
}
```

## 5.3 完整电商MCP Server示例

```typescript theme={null}
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new McpServer({
  name: "my-store-server",
  version: "1.0.0"
});

// ---- 商品搜索 ----
server.tool(
  "search_products",
  "搜索商品。支持关键词、分类筛选。返回商品名、价格、库存状态。",
  {
    query: { type: "string", description: "搜索关键词" },
    category: { type: "string", description: "分类名（可选）" },
    minPrice: { type: "number", description: "最低价格（可选）" },
    maxPrice: { type: "number", description: "最高价格（可选）" },
    limit: { type: "number", description: "返回数量，默认10，最大50" }
  },
  async ({ query, category, minPrice, maxPrice, limit = 10 }) => {
    const filters: any = {};
    if (category) filters.category = category;
    if (minPrice) filters.price = { $gte: minPrice };
    if (maxPrice) filters.price = { ...filters.price, $lte: maxPrice };

    const results = await db.products.search(query, filters, Math.min(limit, 50));

    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          results: results.map(p => ({
            name: p.name,
            sku: p.sku,
            price: p.price,
            currency: "CNY",
            inStock: p.inventory > 0,
            category: p.category,
            url: `https://mystore.com/product/${p.slug}`
          })),
          total: results.totalCount,
          query
        }, null, 2)
      }]
    };
  }
);

// ---- 商品详情 ----
server.tool(
  "get_product",
  "获取单个商品的完整详情，包括描述、规格、评分、库存。",
  {
    sku: { type: "string", description: "商品SKU编号" }
  },
  async ({ sku }) => {
    const product = await db.products.findBySku(sku);
    if (!product) {
      return {
        content: [{ type: "text", text: `未找到SKU: ${sku}` }],
        isError: true
      };
    }

    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          name: product.name,
          sku: product.sku,
          description: product.description,
          price: product.price,
          currency: "CNY",
          brand: product.brand,
          category: product.category,
          inStock: product.inventory > 0,
          inventory: product.inventory,
          rating: product.averageRating,
          reviewCount: product.reviewCount,
          specs: product.specifications,
          images: product.images,
          url: `https://mystore.com/product/${product.slug}`
        }, null, 2)
      }]
    };
  }
);

// ---- 订单查询 ----
server.tool(
  "get_order",
  "查询订单状态和明细。需要订单号。",
  {
    orderId: { type: "string", description: "订单号" }
  },
  async ({ orderId }) => {
    const order = await db.orders.findById(orderId);
    if (!order) {
      return {
        content: [{ type: "text", text: `未找到订单: ${orderId}` }],
        isError: true
      };
    }

    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          id: order.id,
          status: order.status,
          createdAt: order.createdAt,
          items: order.items.map(i => ({
            name: i.name, quantity: i.quantity, price: i.price
          })),
          total: order.total,
          shipping: {
            method: order.shippingMethod,
            trackingNumber: order.trackingNumber,
            estimatedDelivery: order.estimatedDelivery
          }
        }, null, 2)
      }]
    };
  }
);

// ---- OTR信任查询（ORBEXA集成）----
server.tool(
  "otr_verify",
  "查询商家网站的OTR信任评分。返回六维信任评估结果。",
  {
    domain: { type: "string", description: "商家域名，如 example.com" }
  },
  async ({ domain }) => {
    const response = await fetch(
      `https://${domain}/.well-known/otr/verify`
    );
    if (!response.ok) {
      return {
        content: [{ type: "text", text: `${domain} 未部署OTR协议` }],
        isError: true
      };
    }
    const otr = await response.json();
    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          domain: otr.domain,
          trustScore: otr.trustScore,
          dimensions: otr.dimensions,
          badges: otr.badges,
          lastScan: otr.lastScan
        }, null, 2)
      }]
    };
  }
);

// 启动
const transport = new StdioServerTransport();
await server.connect(transport);
```

## 5.4 商务Resources设计

除了工具，电商Server还可以暴露静态上下文作为Resources，让AI代理理解你的业务：

```typescript theme={null}
// 退货政策
server.resource(
  "commerce://policies/return",
  "退货政策",
  "text/markdown",
  async () => {
    return "## 退货政策\n\n- 7天无理由退货\n- 需保持原包装完好\n- 定制商品不可退";
  }
);

// 配送区域
server.resource(
  "commerce://shipping/zones",
  "配送区域",
  "application/json",
  async () => {
    const zones = await db.shippingZones.getAll();
    return JSON.stringify(zones, null, 2);
  }
);
```

AI代理在回答"你们支持退货吗"这类问题时，会自动读取相关资源作为上下文。

## 5.5 权限和安全

商务Server需要特别注意权限控制：

| 工具                | 权限要求 | 说明             |
| ----------------- | ---- | -------------- |
| `search_products` | 无需认证 | 公开信息           |
| `get_product`     | 无需认证 | 公开信息           |
| `check_inventory` | 可选认证 | 粗略库存公开，精确库存需认证 |
| `get_order`       | 必须认证 | 用户只能查自己的订单     |
| `create_return`   | 必须认证 | 涉及退款操作         |
| `otr_verify`      | 无需认证 | OTR是公开协议       |

远程部署时，使用OAuth 2.1认证，确保用户身份和权限正确。对于需要认证的工具，可以通过Elicitation请求用户登录，或依赖Host应用已有的OAuth集成。

## 5.6 商务MCP Server与其他协议的关系

| 协议      | 用途       | 与MCP的关系                       |
| ------- | -------- | ----------------------------- |
| **UCP** | AI代理发现商品 | MCP Server可以暴露UCP数据作为Resource |
| **ACP** | AI代理下单支付 | MCP Server可以封装ACP流程为Tool      |
| **OTR** | 商家信任评估   | MCP Server可以集成OTR查询为Tool      |

一个完整的Agentic Commerce系统中，MCP作为AI应用与你的商务系统之间的"连接层"，而UCP/ACP/OTR处理具体的商务协议逻辑。

***

**下一章**: [资源与提示词](/zh/book-5/ch6-resources-prompts) — Resources和Prompts的深入使用
