feat(mcp): integrate netx via netx_mcp and improve MCP install

- Gate builtin netx tools; ops docs/skills use mcp__netx__*

- Import Cursor mcpServers JSON; pass env_schema defaults to subprocess

- Allow source_type=local; UTF-8 MCP stdio on Windows

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
oliver 2026-05-30 15:44:34 +08:00
parent bbd7b0300f
commit a0a3f4b65f
17 changed files with 408 additions and 536 deletions

View file

@ -3,6 +3,7 @@ from __future__ import annotations
import importlib.util
import inspect
import logging
import os
from collections.abc import Callable
from pathlib import Path
from typing import Any
@ -21,6 +22,22 @@ _DEPRECATED_TOOL_NAMES: set[str] = {
}
def netx_builtin_tools_enabled() -> bool:
"""When false, skip ``network_ops/netx_tools.py`` factories (use MCP ``mcp__netx__*`` instead)."""
return str(os.getenv("OCLAW_NETX_BUILTIN_TOOLS") or "0").strip().lower() not in {
"0",
"false",
"no",
"off",
}
def _skip_expert_module(module_path: Path) -> bool:
if module_path.stem == "netx_tools" and not netx_builtin_tools_enabled():
return True
return False
def _load_module_from_path(module_path: Path, module_name: str) -> Any | None:
try:
spec = importlib.util.spec_from_file_location(module_name, module_path)
@ -52,12 +69,14 @@ def discover_expert_tool_factories() -> dict[str, list[ToolFactory]]:
for module_path in sorted(expert_dir.glob("*.py")):
if module_path.name == "__init__.py":
continue
if _skip_expert_module(module_path):
continue
mod_name = f"runtime.tools.experts.{expert}.{module_path.stem}"
module = _load_module_from_path(module_path, mod_name)
if module is None:
continue
exported = getattr(module, "__all__", None)
if isinstance(exported, list) and exported:
if isinstance(exported, list):
for name in sorted(exported):
value = getattr(module, name, None)
if callable(value) and name.endswith("_tool"):

View file

@ -1,7 +1,10 @@
"""Internal read-only tools: query netx REST API (PostgreSQL backend on netx side).
"""netx ops helpers: runtime context inject + optional legacy inline HTTP tools.
Default: tools are exposed via stdio MCP (``pip install -e packages/netx-mcp`` then ``python -m netx_mcp``).
Set ``OCLAW_NETX_BUILTIN_TOOLS=1`` to re-register inline ``netx_*`` expert tools.
Configure via environment:
- ``OCLAW_NETX_BASE_URL`` (default ``http://127.0.0.1:8890``)
- ``OCLAW_NETX_BASE_URL`` (default ``http://127.0.0.1:8890``) — runtime anchor HTTP probe
- ``OCLAW_NETX_API_TOKEN`` (optional) → sent as ``Authorization: Bearer …`` if set.
"""
@ -27,6 +30,7 @@ _PROTOCOL_KEY_ZH_TO_EN: dict[str, str] = {
"电源": "Power",
}
_UME_RAW_GROUP_FIELDS = [
"alarm_alarm_key",
"alarm_host_name",
@ -136,24 +140,6 @@ def _http_json(method: str, path: str, *, params: dict[str, Any] | None = None)
return {"ok": False, "error": "netx_request_failed", "detail": str(exc)[:800]}
def _resolve_latest_import_batch_id() -> dict[str, Any]:
"""``GET /v1/batches`` 按 created_at 降序;取第一条为当前最新导入批次。"""
r = _http_json("GET", "/v1/batches", params={"limit": 1})
if not r.get("ok"):
return {"ok": False, "error": "netx_list_batches_failed", "detail": r.get("detail"), "upstream": r}
data = r.get("data") or {}
items = data.get("items")
if not isinstance(items, list) or not items:
return {"ok": False, "error": "no_import_batches", "detail": "netx 中尚无导入批次,请先导入或显式提供 batch_id"}
first = items[0]
if not isinstance(first, dict):
return {"ok": False, "error": "no_import_batches", "detail": "batch 列表格式异常"}
bid = str(first.get("batch_id") or "").strip()
if not bid:
return {"ok": False, "error": "no_import_batches", "detail": "batch 列表中无 batch_id"}
return {"ok": True, "batch_id": bid, "batch_row": first}
def _resolve_ume_anchor() -> dict[str, Any]:
"""Resolve current UME alarm anchor from netx sync status."""
r = _http_json("GET", "/v1/ume/sync/status", params={"page": 1, "page_size": 20})
@ -219,48 +205,42 @@ def _format_ops_netx_system_extension(r: dict[str, Any], *, lang_en: bool) -> st
f"- last_error: {err[:200]}" if lang_en else f"- 最近错误: {err[:200]}"
)
tail_en = (
"- tools: netx_query_ume_alarms, netx_aggregate_ume_alarms, netx_run_ume_diagnostics, "
"netx_query_ume_ne_inventory, netx_get_ume_ne\n"
"- MCP tools (server_id=netx): mcp__netx__queryUmeAlarms, mcp__netx__aggregateUmeAlarms, "
"mcp__netx__runUmeDiagnostics, mcp__netx__queryUmeNeInventory, mcp__netx__getUmeNe, "
"mcp__netx__queryUmeAlarmsRaw, mcp__netx__aggregateUmeAlarmsRaw, mcp__netx__listUmeAlarmFields, "
"mcp__netx__sqlQueryUme, mcp__netx__listManagedNe, mcp__netx__getManagedNe, mcp__netx__execManagedNe\n"
"- note: this is only runtime anchor; use tools for alarm/ne evidence.\n"
"- English session: user-visible reply must contain NO Chinese/CJK; translate alarm text fields."
)
tail_zh = (
"- 工具: netx_query_ume_alarms、netx_aggregate_ume_alarms、netx_run_ume_diagnostics、"
"netx_query_ume_ne_inventory、netx_get_ume_ne\n"
"- MCP 工具(server_id=netx):mcp__netx__queryUmeAlarms、mcp__netx__aggregateUmeAlarms、"
"mcp__netx__runUmeDiagnostics、mcp__netx__queryUmeNeInventory、mcp__netx__getUmeNe、"
"mcp__netx__queryUmeAlarmsRaw、mcp__netx__aggregateUmeAlarmsRaw、mcp__netx__listUmeAlarmFields、"
"mcp__netx__sqlQueryUme、mcp__netx__listManagedNe、mcp__netx__getManagedNe、mcp__netx__execManagedNe\n"
"- 说明: 此处仅为运行锚点;具体告警/网元信息必须以工具返回为准,勿臆测。"
)
return "\n".join(lines_en + [tail_en]) if lang_en else "\n".join(lines_zh + [tail_zh])
err = str(r.get("error") or "")
detail = str(r.get("detail") or "")[:240]
if err == "no_import_batches":
if lang_en:
return (
"[Netx alarm import anchor]\n"
"- batch_id: (none)\n"
"- note: no import batches in netx yet—import alarms or pass batch_id in chat."
)
return (
"[当前 netx 告警导入锚点]\n"
"- batch_id: (暂无)\n"
"- 说明: netx 中尚无导入批次;请先导入告警或在对话中提供 batch_id。"
)
if lang_en:
return (
"[Netx UME current-alarms anchor]\n"
f"- error: {err}\n"
f"- detail: {detail}\n"
"- fix: check OCLAW_NETX_BASE_URL and that netx API is reachable."
"- fix: check NETX_API_URL (or OCLAW_NETX_BASE_URL) and that netx API is reachable; "
"ensure MCP server_id=netx is bound and synced."
)
return (
"[当前 netx UME告警锚点]\n"
f"- 错误: {err}\n"
f"- 详情: {detail}\n"
"- 处理: 检查 OCLAW_NETX_BASE_URL 与 netx 服务是否可达。"
"- 处理: 检查 NETX_API_URL(或 OCLAW_NETX_BASE_URL)与 netx 服务是否可达;"
"确认 Admin 已安装并绑定 MCP server_id=netx。"
)
def ops_netx_system_context_extension(*, lang: str = "zh") -> str:
"""Append to ops specialist system prompt: latest batch_id anchor (direct_loop injection).
"""Append to ops specialist system prompt: UME sync anchor (direct_loop injection).
Cached briefly to reduce duplicate HTTP calls across tool rounds.
"""
@ -281,310 +261,6 @@ def ops_netx_system_context_extension(*, lang: str = "zh") -> str:
return text
def netx_query_alarms_tool() -> ToolSpec:
"""Paginated alarm rows from netx (same filters as netx UI REST)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
resolution = "explicit"
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
resolution = "latest_import"
page = max(1, int(args.get("page") or 1))
page_size = min(200, max(1, int(args.get("page_size") or 50)))
params: dict[str, Any] = {
"batch_id": batch_id,
"page": page,
"page_size": page_size,
}
if str(args.get("alarm_code") or "").strip():
params["alarm_code"] = str(args.get("alarm_code")).strip()
if str(args.get("ne_name") or "").strip():
params["ne_name"] = str(args.get("ne_name")).strip()
if str(args.get("severity") or "").strip():
params["severity"] = str(args.get("severity")).strip()
out = _http_json("GET", "/v1/alarms", params=params)
if out.get("ok") and resolution == "latest_import":
out = {**out, "batch_id_used": batch_id, "batch_resolution": resolution}
return out
return ToolSpec(
name="netx_query_alarms",
description=(
"从独立运维工具 netx 读取告警明细(PostgreSQL 侧由 netx 托管)。"
"batch_id 可选:不传表示使用 netx 当前「最新」导入批次(/v1/batches 第一条)。"
"可选 alarm_code / ne_name / severity(与 netx 告警列表过滤语义一致);支持分页。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string", "description": "导入批次 ID;省略则用最新导入批次"},
"alarm_code": {"type": "string", "description": "告警码包含匹配(可选)"},
"ne_name": {"type": "string", "description": "网元名包含匹配(可选)"},
"severity": {"type": "string", "description": "规范化级别 critical/major/minor/warning/..."},
"page": {"type": "integer", "minimum": 1, "default": 1},
"page_size": {"type": "integer", "minimum": 1, "maximum": 200, "default": 50},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_aggregate_alarms_tool() -> ToolSpec:
"""Aggregate buckets from netx."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
resolution = "explicit"
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
resolution = "latest_import"
group_by = str(args.get("group_by") or "severity_norm").strip()
if group_by not in {"severity_norm", "alarm_code", "ne_name"}:
return {"ok": False, "error": "invalid_group_by"}
params: dict[str, Any] = {"group_by": group_by, "batch_id": batch_id}
out = _http_json("GET", "/v1/alarms/aggregate", params=params)
if out.get("ok") and resolution == "latest_import":
out = {**out, "batch_id_used": batch_id, "batch_resolution": resolution}
return out
return ToolSpec(
name="netx_aggregate_alarms",
description=(
"按 severity_norm / alarm_code / ne_name 对 netx 告警做聚合统计(读 netx API,不落直连 PG)。"
"batch_id 可选:不传则限定为 netx 当前最新导入批次(与告警查询默认语义一致)。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string"},
"group_by": {
"type": "string",
"enum": ["severity_norm", "alarm_code", "ne_name"],
"default": "severity_norm",
},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "aggregate", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_run_diagnostics_tool() -> ToolSpec:
"""Diagnostics summary (same stats netx uses for dashboard slices)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
resolution = "explicit"
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
resolution = "latest_import"
out = _http_json("GET", "/v1/diagnostics", params={"batch_id": batch_id})
if out.get("ok") and resolution == "latest_import":
out = {**out, "batch_id_used": batch_id, "batch_resolution": resolution}
return out
return ToolSpec(
name="netx_run_diagnostics",
description=(
"读取 netx /v1/diagnostics 统计摘要(批次维度:级别分布、Top 告警码/网元、协议归类等)。"
"batch_id 可选:不传则使用 netx 当前最新导入批次。"
),
parameters={
"type": "object",
"properties": {"batch_id": {"type": "string", "description": "批次 ID;省略则用最新导入批次"}},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "diagnostics", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_list_import_batches_tool() -> ToolSpec:
"""List recent import batches (newest first)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
limit = max(1, min(100, int(args.get("limit") or 20)))
return _http_json("GET", "/v1/batches", params={"limit": limit})
return ToolSpec(
name="netx_list_import_batches",
description="列出 netx 最近导入批次(与 UI 一致,按创建时间降序)。用于核对 batch_id 或确认「最新」批次。",
parameters={
"type": "object",
"properties": {
"limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "batches", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_list_alarm_fields_tool() -> ToolSpec:
"""List alarms_norm columns from netx."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
_ = args
return _http_json("GET", "/v1/alarms/fields", params=None)
return ToolSpec(
name="netx_list_alarm_fields",
description="列出 netx alarms_norm 表所有字段名(供自由查询时选择字段/确认可用字段)。",
parameters={
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "schema", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_query_alarms_raw_tool() -> ToolSpec:
"""Power query alarms_norm with all fields."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
page = max(1, int(args.get("page") or 1))
page_size = min(200, max(1, int(args.get("page_size") or 50)))
params: dict[str, Any] = {
"batch_id": batch_id,
"page": page,
"page_size": page_size,
}
if str(args.get("alarm_code") or "").strip():
params["alarm_code"] = str(args.get("alarm_code")).strip()
if str(args.get("ne_name") or "").strip():
params["ne_name"] = str(args.get("ne_name")).strip()
if str(args.get("severity") or "").strip():
params["severity"] = str(args.get("severity")).strip()
if str(args.get("q") or "").strip():
params["q"] = str(args.get("q")).strip()
if str(args.get("order_by") or "").strip():
params["order_by"] = str(args.get("order_by")).strip()
if str(args.get("order") or "").strip():
params["order"] = str(args.get("order")).strip()
return _http_json("GET", "/v1/alarms/raw", params=params)
return ToolSpec(
name="netx_query_alarms_raw",
description=(
"自由查询 netx alarms_norm:返回所有字段。"
"batch_id 可选(省略则使用最新导入批次);支持 severity/alarm_code/ne_name/q 过滤与分页;"
"order_by 仅允许 id/alarm_time/severity_norm/ne_name/alarm_code。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string", "description": "批次 ID;省略则用最新导入批次"},
"severity": {"type": "string"},
"alarm_code": {"type": "string"},
"ne_name": {"type": "string"},
"q": {"type": "string", "description": "自由文本 contains(alarm_code/ne_name/description/service)"},
"order_by": {"type": "string", "enum": ["id", "alarm_time", "severity_norm", "ne_name", "alarm_code"]},
"order": {"type": "string", "enum": ["asc", "desc"]},
"page": {"type": "integer", "minimum": 1, "default": 1},
"page_size": {"type": "integer", "minimum": 1, "maximum": 200, "default": 50},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "power_query", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_sql_query_tool() -> ToolSpec:
"""Execute read-only SQL on netx (server enforced SELECT-only)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
batch_id = str(args.get("batch_id") or "").strip()
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
sql = str(args.get("sql") or "").strip()
limit = max(1, min(2000, int(args.get("limit") or 200)))
if not sql:
return {"ok": False, "error": "sql_required"}
base = _netx_base_url()
url = f"{base}/v1/sql/query"
try:
# Do not inherit system proxy settings for local netx calls.
with httpx.Client(timeout=60.0, trust_env=False) as client:
resp = client.post(url, json={"sql": sql, "batch_id": batch_id, "limit": limit}, headers=_netx_headers())
text = resp.text
if not resp.is_success:
return {"ok": False, "error": f"netx_http_{resp.status_code}", "detail": text[:800]}
data = resp.json() if text else {}
return {"ok": True, "data": data if isinstance(data, dict) else {"raw": data}}
except Exception as exc:
return {"ok": False, "error": "netx_request_failed", "detail": str(exc)[:800]}
return ToolSpec(
name="netx_sql_query",
description=(
"在 netx 上执行只读 SQL(服务端强制 SELECT-only、单语句、必须包含 :batch_id 参数,并强制 limit)。"
"用于自由组合查询;建议先用 netx_list_alarm_fields 确认可用字段。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string", "description": "批次 ID;省略则用最新导入批次"},
"sql": {"type": "string", "description": "必须是 SELECT,且包含 :batch_id 占位符"},
"limit": {"type": "integer", "minimum": 1, "maximum": 2000, "default": 200},
},
"required": ["sql"],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "sql", "power_query", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_query_ume_alarms_tool() -> ToolSpec:
"""Paginated UME current alarms from netx."""
@ -612,7 +288,6 @@ def netx_query_ume_alarms_tool() -> ToolSpec:
description=(
"读取 netx UME 当前告警明细(实时表);每条含 host_name(网元主展示键,同步时已写入告警表)。"
"支持 severity/ne_id/keyword 与分页。"
"当需要字段级控制或复杂分析时,优先 netx_list_ume_alarm_fields + netx_query_ume_alarms_raw/netx_sql_query_ume。"
),
parameters={
"type": "object",
@ -915,7 +590,7 @@ def netx_sql_query_ume_tool() -> ToolSpec:
"minimum": 0,
"maximum": 30000,
"default": 0,
"description": "可选查询超时(ms),0表示使用数据库默认超时",
"description": "可选查询超时(ms);0 表示使用数据库默认超时",
},
},
"required": ["sql"],
@ -1127,14 +802,9 @@ def netx_exec_managed_ne_tool() -> ToolSpec:
)
__all__ = [
# "netx_query_alarms_tool",
# "netx_aggregate_alarms_tool",
# "netx_run_diagnostics_tool",
# "netx_list_import_batches_tool",
# "netx_list_alarm_fields_tool",
# "netx_query_alarms_raw_tool",
# "netx_sql_query_tool",
__all__: list[str] = []
_LEGACY_EXPORTS = [
"netx_query_ume_alarms_tool",
"netx_aggregate_ume_alarms_tool",
"netx_run_ume_diagnostics_tool",
@ -1148,3 +818,14 @@ __all__ = [
"netx_get_managed_ne_tool",
"netx_exec_managed_ne_tool",
]
def _apply_legacy_exports() -> None:
import os as _os
if str(_os.getenv("OCLAW_NETX_BUILTIN_TOOLS") or "0").strip().lower() in {"0", "false", "no", "off"}:
return
globals()["__all__"] = list(_LEGACY_EXPORTS)
_apply_legacy_exports()

View file

@ -5,7 +5,6 @@ import json
import os
from typing import Any
from runtime.operations.mcp_env import mcp_env_allowlist_keys
from runtime.skills import SkillSpec, materialize_skills_from_tool_specs
from runtime.tools.base import ToolSpec
from runtime.tools.mcp.filesystem_argv import build_mcp_process_command
@ -13,6 +12,31 @@ from runtime.tools.mcp.runtime import McpProcessRuntime
from runtime.tools.public.bailian_webparser_tool import bailian_webparser_tool
def _mcp_row_env_config(row: dict[str, Any]) -> tuple[list[str], dict[str, str]]:
"""Per-server env allowlist + defaults from registry ``env_schema`` (e.g. Cursor ``mcpServers.env``)."""
from runtime.operations.mcp_env import mcp_env_allowlist_keys
schema = row.get("env_schema") if isinstance(row.get("env_schema"), dict) else {}
defaults: dict[str, str] = {}
schema_keys: list[str] = []
for k, spec in schema.items():
key = str(k or "").strip()
if not key:
continue
schema_keys.append(key)
if isinstance(spec, dict) and spec.get("default") is not None:
dv = str(spec.get("default") or "").strip()
if dv:
defaults[key] = dv
seen: set[str] = set()
allowlist: list[str] = []
for k in [*mcp_env_allowlist_keys(), *schema_keys]:
if k and k not in seen:
seen.add(k)
allowlist.append(k)
return allowlist, defaults
@dataclass
class _McpBoundTool:
server_id: str
@ -23,9 +47,15 @@ class _McpBoundTool:
timeout_s: float = 30.0
required_permissions: frozenset[str] = frozenset()
env_allowlist: list[str] | None = None
env_defaults: dict[str, str] | None = None
def to_spec(self) -> ToolSpec:
rt = McpProcessRuntime(command=self.command, timeout_s=self.timeout_s, env_allowlist=self.env_allowlist)
rt = McpProcessRuntime(
command=self.command,
timeout_s=self.timeout_s,
env_allowlist=self.env_allowlist,
env_defaults=self.env_defaults,
)
def _handler(args: dict[str, Any]) -> dict[str, Any]:
res = rt.call_tool(tool_name=self.tool_name, arguments=args or {})
@ -112,7 +142,6 @@ def materialize_mcp_tools_for_specialist(
return []
out: list[ToolSpec] = []
rows = store.list_mcp_servers(enabled_only=True) if store else []
env_allowlist = mcp_env_allowlist_keys()
for row in rows:
server_id = str(row.get("server_id") or "").strip()
cmd = str(row.get("entry_command") or "").strip()
@ -120,6 +149,7 @@ def materialize_mcp_tools_for_specialist(
continue
if binding_server_ids is not None and sp and server_id not in binding_server_ids:
continue
env_allowlist, env_defaults = _mcp_row_env_config(row)
raw_args = [x for x in (row.get("entry_args") or []) if isinstance(x, str)]
command = build_mcp_process_command(
cmd,
@ -161,6 +191,7 @@ def materialize_mcp_tools_for_specialist(
timeout_s=float(row.get("timeout_s") or 30.0),
required_permissions=frozenset(str(x) for x in (row.get("required_permissions") or [])),
env_allowlist=env_allowlist,
env_defaults=env_defaults,
).to_spec()
out.append(spec)
return out

View file

@ -61,6 +61,8 @@ def _install_command(manifest: McpServerManifest) -> list[str]:
if manifest.source_type == "pypi":
pkg = manifest.source_ref + (f"=={manifest.version}" if manifest.version else "")
return [sys.executable, "-m", "pip", "install", pkg]
if manifest.source_type == "local":
return []
raise ValueError(f"unsupported_source_type:{manifest.source_type}")
@ -85,6 +87,8 @@ def _uninstall_command(manifest: McpServerManifest) -> list[str]:
return [sys.executable, "-m", "pip", "uninstall", "-y", str(manifest.source_ref or "").strip()]
if manifest.source_type == "github":
return []
if manifest.source_type == "local":
return []
raise ValueError(f"unsupported_source_type:{manifest.source_type}")
@ -93,6 +97,12 @@ def install_mcp_server(manifest: McpServerManifest, *, dry_run: bool = False) ->
cmd = _install_command(manifest)
except Exception as exc:
return McpInstallResult(ok=False, error_code="mcp_invalid_source", error=str(exc))
if manifest.source_type == "local" and not cmd:
return McpInstallResult(
ok=True,
install_command="",
details={"skipped": True, "reason": "local_source_no_package_install"},
)
cmd_text = " ".join(cmd)
if dry_run:
return McpInstallResult(ok=True, install_command=cmd_text, details={"dry_run": True})

View file

@ -16,13 +16,17 @@ class McpProcessRuntime:
command: list[str]
timeout_s: float = 30.0
env_allowlist: list[str] | None = None
env_defaults: dict[str, str] | None = None
_proc: subprocess.Popen[str] | None = None
_lock: threading.Lock = field(default_factory=threading.Lock)
_initialized: bool = False
_request_id: int = 0
@staticmethod
def _build_runtime_env(env_allowlist: list[str] | None) -> dict[str, str] | None:
def _build_runtime_env(
env_allowlist: list[str] | None,
env_defaults: dict[str, str] | None = None,
) -> dict[str, str] | None:
if env_allowlist is None:
return None
from runtime.operations.mcp_env import mcp_local_env_merged
@ -46,6 +50,16 @@ class McpProcessRuntime:
key = str(k or "").strip()
if key and key in os.environ and str(os.environ[key] or "").strip():
env[key] = os.environ[key]
for k, v in (env_defaults or {}).items():
key = str(k or "").strip()
val = str(v or "").strip()
if not key or not val:
continue
if key not in env or not str(env.get(key) or "").strip():
env[key] = val
# MCP JSON-RPC on stdio is UTF-8; force child Python off Windows GBK console encoding.
env.setdefault("PYTHONIOENCODING", "utf-8")
env.setdefault("PYTHONUTF8", "1")
return env
@staticmethod
@ -68,11 +82,19 @@ class McpProcessRuntime:
def start(self) -> None:
if self._proc and self._proc.poll() is None:
return
env = self._build_runtime_env(self.env_allowlist)
env = self._build_runtime_env(self.env_allowlist, self.env_defaults)
cmd = list(self.command or [])
if cmd:
cmd[0] = self._resolve_command(str(cmd[0]), env)
popen_kwargs: dict[str, Any] = {"stdin": subprocess.PIPE, "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "text": True, "encoding": "utf-8", "env": env}
popen_kwargs: dict[str, Any] = {
"stdin": subprocess.PIPE,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"text": True,
"encoding": "utf-8",
"errors": "replace",
"env": env,
}
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW