| """ |
| MCP工具文档生成器 - 从Pydantic模型自动生成工具文档 |
| """ |
|
|
| from pydantic import BaseModel |
| from typing import Dict, Any, Type, Optional |
|
|
|
|
| def generate_tool_docs( |
| input_model: Optional[Type[BaseModel]], |
| output_model: Optional[Type[BaseModel]] |
| ) -> Dict[str, Any]: |
| """从Pydantic模型生成工具文档。 |
| |
| Args: |
| input_model: 输入参数模型 |
| output_model: 输出结果模型 |
| |
| Returns: |
| 包含input和output schema的文档字典 |
| """ |
|
|
| def model_to_schema(model: Optional[Type[BaseModel]]) -> Dict: |
| if model is None: |
| return {} |
| schema = model.model_json_schema() |
| return { |
| "type": schema.get("type", "object"), |
| "properties": schema.get("properties", {}), |
| "required": schema.get("required", []), |
| } |
|
|
| return { |
| "input": model_to_schema(input_model), |
| "output": model_to_schema(output_model), |
| } |
|
|
|
|
| def generate_full_tool_doc(tool_info: Dict[str, Any]) -> Dict[str, Any]: |
| """生成完整的工具文档。 |
| |
| Args: |
| tool_info: 工具信息字典(来自 registered_tools) |
| |
| Returns: |
| 完整的工具文档,包含名称、描述、输入输出schema |
| """ |
| docs = generate_tool_docs( |
| tool_info.get('input_model'), |
| tool_info.get('output_model') |
| ) |
|
|
| return { |
| "name": tool_info.get('tool'), |
| "full_name": f"{tool_info['plugin']}_{tool_info['tool']}", |
| "title": tool_info.get('title'), |
| "description": tool_info.get('description'), |
| "input": docs['input'], |
| "output": docs['output'], |
| "annotations": tool_info.get('annotations', {}), |
| } |