"""
MCP(Model Context Protocol) 数据模型
这个文件定义了 MCP 协议的请求和响应格式
"""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
# ============================================
# MCP Tools 相关模型
# ============================================
class ToolInputProperty(BaseModel):
"""
工具输入参数的属性
这个模型描述了工具的一个参数的详细信息
"""
type: str = Field(..., description="参数类型,如 'string', 'integer'")
description: str = Field(..., description="参数说明,让AI知道这个参数是做什么的")
enum: Optional[List[Any]] = Field(None, description="可选值列表(如果参数只能是特定值)")
default: Optional[Any] = Field(None, description="默认值")
class ToolInputSchema(BaseModel):
"""
工具的输入 Schema
这个模型定义了工具需要什么参数
使用 JSON Schema 格式
"""
type: str = Field("object", description="固定为 'object'")
# 这是整个模型的核心,就像 Go 里的 “Properies map[string]ToolInputProperty”
properties: Dict[str, ToolInputProperty] = Field(..., description="参数列表")
required: List[str] = Field(default_factory=list, description="必填参数")
class Tool(BaseModel):
"""
MCP 工具定义
这是 tools/list 接口返回的核心数据结构
AI 通过这个结构了解工具的功能和用户
"""
name: str = Field(..., description="工具名称,唯一标识")
description: str = Field(..., description="工具描述,让AI知道什么时候使用这个工具")
input_schema: ToolInputSchema = Field(..., description="输入参数的 Schema")
class ToolsListResponse(BaseModel):
"""
tools/list 接口的响应
"""
tools: List[Tool] = Field(..., description="可用工具列表")
# ============================================
# MCP Tool Call 相关模型
# ============================================
class ToolCallRequest(BaseModel):
"""
tool_call 接口的请求
AI 调用工具时发送这个格式的数据
"""
name: str = Field(..., description="要调用的工具名称")
arguments: Dict[str, Any] = Field(..., description="工具的输入参数")
class ToolCallContentItem(BaseModel):
"""
工具返回的单个内容项
MCP 支持多种内容类型(文本,图片等)
我们这里主要使用文本
"""
type: str = Field(..., description="内容类型,通常是 'text'")
text: Optional[str] = Field(None, description="文本内容")
class ToolCallResponse(BaseModel):
"""
tools/call 接口的响应
AI 调用工具后,MCP 返回这个格式的数据
"""
content: List[ToolCallContentItem] = Field(..., description="工具返回的内容")
is_error: bool = Field(..., description="是否是错误")
# ============================================
# MCP Resources 相关模型(可选)
# ============================================
class Resource(BaseModel):
"""
MCP 资源定义
用于提供参考文档、数据等给 AI
"""
uri: str = Field(..., description="资源的 URI")
name: str = Field(..., description="资源名称,唯一标识")
description: str = Field(..., description="资源描述,让AI知道这个资源是做什么的")
mime_type: str = Field(..., description="资源的 MIME 类型")
class ResourcesListResponse(BaseModel):
"""
resources/list 接口的响应
"""
resources: List[Resource] = Field(..., description="可用资源列表")