ai4mats-mcp-tools/tools/bayesian_mcp_server.py

117 lines
3.1 KiB
Python

import os
import json
import httpx
from mcp.server.fastmcp import FastMCP
# ============================================
# 配置
# ============================================
def load_config():
"""加载配置"""
config_path = os.path.join(os.path.dirname(__file__), "config.json")
default_config = {
"API_BASE_URL": "http://218.77.58.19:22222"
}
try:
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
default_config.update(json.load(f))
except Exception:
pass
return default_config
config = load_config()
API_BASE_URL = config["API_BASE_URL"]
# ============================================
# MCP 服务定义
# ============================================
mcp = FastMCP("Bayesian-Analysis")
# ============================================
# 工具:贝叶斯预测
# ============================================
@mcp.tool()
async def predict_next_five_rounds(
Concentration: float,
T_S: int,
T_Mo: int,
growth_time: int,
Ar: int,
CO2: int,
H2: int,
Density: float,
Width: float,
R_stacking_ratio: float,
rounds: int = 5,
suggestions_per_round: int = 1,
) -> str:
"""
调用贝叶斯分析模型,预测未来几轮的工艺参数建议。
参数说明:
- Concentration: 浓度
- T_S: 温度 S
- T_Mo: 温度 Mo
- growth_time: 生长时间
- Ar: 氩气流量
- CO2: 二氧化碳流量
- H2: 氢气流量
- Density: 密度
- Width: 宽度
- R_stacking_ratio: 堆叠比
- rounds: 预测轮数
- suggestions_per_round: 每轮建议数
"""
# ---------- 参数校验 ----------
if Concentration <= 0 or Density <= 0 or Width <= 0:
return "❌ 参数错误:浓度 / 密度 / 宽度必须大于 0"
if not (0 < R_stacking_ratio < 1):
return "❌ 参数错误:堆叠比应在 0~1 之间"
# ---------- 构造请求 ----------
url = f"{API_BASE_URL}/next-five-rounds"
payload = {
"Concentration": Concentration,
"T_S": T_S,
"T_Mo": T_Mo,
"growth_time": growth_time,
"Ar": Ar,
"CO2": CO2,
"H2": H2,
"Density": Density,
"Width": Width,
"R_stacking_ratio": R_stacking_ratio,
"rounds": rounds,
"suggestions_per_round": suggestions_per_round,
}
# ---------- 调用 API ----------
try:
async with httpx.AsyncClient(timeout=120.0) as client:
response = await client.post(url, json=payload)
response.raise_for_status()
return json.dumps(
response.json(),
indent=2,
ensure_ascii=False
)
except httpx.HTTPStatusError as e:
return f"❌ 贝叶斯接口错误 ({e.response.status_code})"
except httpx.TimeoutException:
return "❌ 贝叶斯接口超时"
except Exception as e:
return f"❌ 调用失败:{e}"
# ============================================
# ⚠️ 注意:这里不写 mcp.run()
# 由主网关统一启动
# ============================================