bugfix:修复一些bug
This commit is contained in:
+21
-1
@@ -8,6 +8,7 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -29,18 +30,37 @@ CONFIG_PATH = PROJECT_ROOT / "mcp_servers.json"
|
||||
# 物料服务返回的目录版本须与主进程一致,否则模型查到的字段和校验依据不同
|
||||
MATERIAL_SERVER = "materials"
|
||||
LOCAL_HOSTS = {"localhost", "127.0.0.1"}
|
||||
# 配置中引用环境变量的写法
|
||||
ENV_REFERENCE = re.compile(r"\$\{(\w+)\}")
|
||||
|
||||
|
||||
class MCPServiceError(RuntimeError):
|
||||
"""MCP 配置错误、服务不可用,或物料目录版本不一致"""
|
||||
|
||||
|
||||
def _expand_env(value):
|
||||
"""只展开字符串值里的 ${NAME};变量未设置时报错,不把字面量当成地址或密钥"""
|
||||
if isinstance(value, dict):
|
||||
return {key: _expand_env(item) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_expand_env(item) for item in value]
|
||||
if not isinstance(value, str):
|
||||
return value
|
||||
|
||||
def lookup(match: re.Match) -> str:
|
||||
if (found := os.environ.get(match[1])) is None:
|
||||
raise MCPServiceError(f"MCP 服务配置引用的环境变量 {match[1]} 未设置")
|
||||
return found
|
||||
|
||||
return ENV_REFERENCE.sub(lookup, value)
|
||||
|
||||
|
||||
def load_mcp_config(path: Path = CONFIG_PATH) -> dict[str, dict]:
|
||||
"""读取服务列表并展开环境变量;文件缺失或格式不对时报错"""
|
||||
if not path.exists():
|
||||
raise MCPServiceError(f"未找到 MCP 服务配置: {path}")
|
||||
try:
|
||||
config = json.loads(os.path.expandvars(path.read_text(encoding="utf-8")))
|
||||
config = _expand_env(json.loads(path.read_text(encoding="utf-8")))
|
||||
except json.JSONDecodeError as error:
|
||||
raise MCPServiceError(f"MCP 服务配置不是合法 JSON: {error}") from error
|
||||
if not isinstance(config, dict) or not all(
|
||||
|
||||
Reference in New Issue
Block a user