119 lines
4.6 KiB
Python
119 lines
4.6 KiB
Python
import requests
|
||
import uvicorn
|
||
import logging
|
||
from mcp.server.fastmcp import FastMCP
|
||
from typing import List, Dict, Any
|
||
import json
|
||
import os
|
||
|
||
# --- 配置 ---
|
||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||
|
||
# --- MCP Server 定义 ---
|
||
mcp = FastMCP()
|
||
|
||
# 定义正确的DMS服务器基地址
|
||
DMS_BASE_URL = "http://127.0.0.1:5001"
|
||
MOCK_DMS_API_LIST_URL = f"{DMS_BASE_URL}/api/schema/manage/schema"
|
||
MOCK_DMS_SCHEMA_DETAIL_URL_TEMPLATE = f"{DMS_BASE_URL}/api/schema/manage/schema/{{model_id}}"
|
||
|
||
@mcp.tool()
|
||
def get_api_list() -> Dict[str, Any]:
|
||
"""
|
||
通过HTTP请求从模拟的DMS服务器获取所有可用API的列表,并返回一个干净的、包含records的字典。
|
||
"""
|
||
logging.info(f"DMSProviderServer: Attempting to fetch API list from {MOCK_DMS_API_LIST_URL}")
|
||
try:
|
||
response = requests.get(MOCK_DMS_API_LIST_URL, timeout=5)
|
||
response.raise_for_status()
|
||
|
||
raw_data = response.json()
|
||
|
||
# 核心修正:根据mock server的实际返回,深入到'data'键下提取'records'
|
||
records = raw_data.get("data", {}).get("records", [])
|
||
|
||
logging.info(f"DMSProviderServer: Successfully parsed response. Found {len(records)} records.")
|
||
|
||
# 返回一个干净、统一的结构,并加入版本号探针
|
||
return {"records": records, "version": "1.1"}
|
||
|
||
except requests.exceptions.RequestException as e:
|
||
error_message = f"Failed to connect to mock DMS server for API list: {e}"
|
||
logging.error(f"DMSProviderServer: {error_message}")
|
||
return {"records": [], "error": error_message}
|
||
except json.JSONDecodeError:
|
||
error_message = "Failed to decode JSON response for API list from mock DMS server."
|
||
logging.error(f"DMSProviderServer: {error_message}")
|
||
return {"records": [], "error": error_message}
|
||
|
||
@mcp.tool()
|
||
def get_schema_by_id(model_id: str) -> Dict[str, Any]:
|
||
"""
|
||
根据模型ID,通过HTTP请求从模拟的DMS服务器获取其JSON Schema。
|
||
"""
|
||
schema_url = MOCK_DMS_SCHEMA_DETAIL_URL_TEMPLATE.format(model_id=model_id)
|
||
logging.info(f"DMSProviderServer: Attempting to fetch schema for '{model_id}' from {schema_url}")
|
||
|
||
try:
|
||
response = requests.get(schema_url, timeout=5)
|
||
response.raise_for_status()
|
||
|
||
raw_data = response.json()
|
||
|
||
# 核心修正:提取'data'键下的schema对象
|
||
schema = raw_data.get("data")
|
||
|
||
if schema:
|
||
logging.info(f"DMSProviderServer: Successfully parsed schema for '{model_id}'.")
|
||
return {"schema": schema}
|
||
else:
|
||
error_message = f"Schema data for '{model_id}' is empty or missing in the response."
|
||
logging.warning(f"DMSProviderServer: {error_message}")
|
||
return {"error": error_message}
|
||
|
||
except requests.exceptions.RequestException as e:
|
||
error_message = f"Failed to connect to mock DMS server for schema '{model_id}': {e}"
|
||
logging.error(f"DMSProviderServer: {error_message}")
|
||
return {"error": error_message}
|
||
except json.JSONDecodeError:
|
||
error_message = f"Failed to decode JSON response for schema '{model_id}' from mock DMS server."
|
||
logging.error(f"DMSProviderServer: {error_message}")
|
||
return {"error": error_message}
|
||
|
||
|
||
@mcp.tool()
|
||
def get_dms_crud_endpoints(model_id: str) -> Dict[str, Any]:
|
||
"""
|
||
根据模型ID,生成并返回其所有标准的CRUD操作端点(create, list, read, update, delete)的完整定义。
|
||
"""
|
||
# 这个函数的逻辑是基于名称生成,暂时不需要对接mock服务,所以保持不变
|
||
base_path = model_id.split('.')[0]
|
||
|
||
endpoints = {
|
||
"create": {
|
||
"method": "POST",
|
||
"url": f"{DMS_BASE_URL}/api/dms/wb_ml/v1/{base_path}"
|
||
},
|
||
"list": {
|
||
"method": "POST", # 根据mock server,list是POST
|
||
"url": f"{DMS_BASE_URL}/api/dms/wb_ml/v1/{base_path}/1.0.0" # 根据mock server,需要版本号
|
||
},
|
||
"read": {
|
||
"method": "GET",
|
||
"url": f"{DMS_BASE_URL}/api/dms/wb_ml/v1/{base_path}/1.0.0/{{id}}" # 根据mock server,需要版本号
|
||
},
|
||
"update": {
|
||
"method": "PUT",
|
||
"url": f"{DMS_BASE_URL}/api/dms/wb_ml/v1/{base_path}"
|
||
},
|
||
"delete": {
|
||
"method": "DELETE",
|
||
"url": f"{DMS_BASE_URL}/api/dms/wb_ml/v1/{base_path}"
|
||
}
|
||
}
|
||
return endpoints
|
||
|
||
# --- 启动服务器 ---
|
||
if __name__ == "__main__":
|
||
import uvicorn
|
||
uvicorn.run(mcp.streamable_http_app(), host="127.0.0.1", port=8003) |