Files
assistant/mcp_servers/product_mcp/server.py
wangliang 74c28eb838 fix: 添加工具注册表和 HTTP 路由,修复 MCP 工具调用 404 错误
## 问题
Product MCP 工具调用返回 404:
```
POST /tools/search_products HTTP/1.1 404 Not Found
```

## 根本原因
1. Product MCP 缺少 `/tools/{tool_name}` HTTP 路由
2. FastMCP 的 `mcp.http_app()` 默认不暴露此路由
3. Order MCP 有自定义路由处理,Product MCP 没有

## 解决方案

### 1. 添加工具注册表
**位置**: 第 32-41 行

```python
# Tool registry for HTTP access
_tools: Dict[str, Any] = {}

def register_tool(name: str):
    """Decorator to register tool in _tools dict"""
    def decorator(func):
        _tools[name] = func
        return func
    return decorator
```

### 2. 为所有工具添加注册装饰器
**修改的工具**:
- `get_product_detail`
- `recommend_products`
- `get_quote`
- `check_inventory`
- `get_categories`
- `search_products`
- `health_check`

**示例**:
```python
@register_tool("search_products")
@mcp.tool()
async def search_products(...):
```

### 3. 添加 HTTP 路由处理
**位置**: 第 352-401 行

参考 Order MCP 实现,添加:
- `/tools/{tool_name}` POST 路由
- 工具调用逻辑:`tool_obj.run(arguments)`
- 结果提取和 JSON 解析
- 错误处理(404, 400, 500)

### 4. 配置路由列表
**位置**: 第 407-415 行

```python
routes = [
    Route('/health', health_check, methods=['GET']),
    Route('/tools/{tool_name}', execute_tool, methods=['POST'])
]
```

## 测试结果

```bash
curl -X POST http://localhost:8004/tools/search_products \
  -H "Content-Type: application/json" \
  -d '{"keyword": "ring"}'
```

返回:
```json
{
  "success": true,
  "result": {
    "success": false,
    "error": "用户未登录,请先登录账户以搜索商品",
    "products": [],
    "total": 0,
    "require_login": true
  }
}
```

 工具调用成功(user_token 缺失是预期行为)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-26 18:32:16 +08:00

11 KiB