147 lines
5.2 KiB
Python
147 lines
5.2 KiB
Python
"""Менеджер встроенного MCP-сервера и политики разрешений."""
|
|
|
|
import json
|
|
import os
|
|
from typing import Callable, Optional
|
|
|
|
from ..mcp.client import start_fs_server
|
|
|
|
|
|
READ_ONLY_TOOLS = {"list_dir", "stat", "read_file", "search"}
|
|
|
|
|
|
class MCPManager:
|
|
def __init__(self, app):
|
|
self.app = app
|
|
self._client = None
|
|
self._tools = []
|
|
self._roots = []
|
|
self._last_error = ""
|
|
|
|
# ---------- конфиг ----------
|
|
def _conf(self):
|
|
try:
|
|
return self.app.engine.config.setdefault("mcp", {})
|
|
except Exception:
|
|
return {}
|
|
|
|
def roots(self):
|
|
conf = self._conf()
|
|
out = []
|
|
for p in conf.get("roots") or []:
|
|
try:
|
|
ap = os.path.abspath(os.path.expanduser(str(p)))
|
|
except Exception:
|
|
continue
|
|
if os.path.isdir(ap):
|
|
out.append(ap)
|
|
return out
|
|
|
|
def mode(self):
|
|
mode = self._conf().get("mode", "smart")
|
|
return mode if mode in ("smart", "full", "restricted") else "smart"
|
|
|
|
def enabled(self) -> bool:
|
|
return bool(self.roots())
|
|
|
|
# ---------- lifecycle ----------
|
|
def _ensure(self):
|
|
roots = self.roots()
|
|
if not roots:
|
|
raise RuntimeError("Укажите разрешённые папки в настройках MCP")
|
|
if self._client is not None and roots == self._roots:
|
|
return self._client
|
|
self.close()
|
|
client = start_fs_server(roots)
|
|
client.start()
|
|
self._client = client
|
|
self._roots = roots
|
|
self._tools = client.list_tools()
|
|
return client
|
|
|
|
def close(self):
|
|
if self._client is not None:
|
|
try:
|
|
self._client.stop()
|
|
except Exception:
|
|
pass
|
|
self._client = None
|
|
self._tools = []
|
|
self._roots = []
|
|
|
|
def list_tools(self):
|
|
client = self._ensure()
|
|
if not self._tools:
|
|
self._tools = client.list_tools()
|
|
return self._tools
|
|
|
|
def tool_prompt(self) -> str:
|
|
try:
|
|
tools = self.list_tools()
|
|
except Exception as e:
|
|
return ""
|
|
lines = []
|
|
for tool in tools:
|
|
name = tool.get("name", "")
|
|
desc = tool.get("description", "")
|
|
schema = tool.get("inputSchema") or {}
|
|
props = list((schema.get("properties") or {}).keys())
|
|
lines.append(f"- {name}: {desc} Аргументы: {', '.join(props)}")
|
|
roots = "\n".join(f"- {r}" for r in self.roots())
|
|
return (
|
|
"Доступные файловые инструменты:\n" + "\n".join(lines) +
|
|
"\n\nРазрешённые папки:\n" + roots +
|
|
"\n\nЧтобы вызвать инструмент, ответь только одним блоком:\n"
|
|
"```tool\n{\"tool\": \"имя\", \"arguments\": {...}}\n```\n"
|
|
"После результата инструмента продолжи ответ пользователю. "
|
|
"Не выходи за пределы разрешённых папок."
|
|
)
|
|
|
|
# ---------- вызов ----------
|
|
def call_tool(self, name: str, arguments: dict,
|
|
ask: Optional[Callable[[str, dict], bool]] = None):
|
|
client = self._ensure()
|
|
mode = self.mode()
|
|
readonly = name in READ_ONLY_TOOLS
|
|
need_ask = mode == "restricted" or (mode == "smart" and not readonly)
|
|
if need_ask and ask is not None:
|
|
if not ask(name, dict(arguments or {})):
|
|
msg = "Пользователь отклонил вызов инструмента"
|
|
self._audit(name, arguments, False, msg)
|
|
return False, msg
|
|
try:
|
|
raw = client.call_tool(name, dict(arguments or {}))
|
|
ok = True
|
|
text = self._extract_text(raw)
|
|
if isinstance(raw, dict) and raw.get("isError"):
|
|
ok = False
|
|
self._audit(name, arguments, ok, text)
|
|
return ok, text
|
|
except Exception as e:
|
|
self._audit(name, arguments, False, str(e))
|
|
return False, str(e)
|
|
|
|
def _extract_text(self, raw) -> str:
|
|
if isinstance(raw, dict):
|
|
content = raw.get("content")
|
|
if isinstance(content, list):
|
|
parts = []
|
|
for item in content:
|
|
if isinstance(item, dict) and item.get("type") == "text":
|
|
parts.append(str(item.get("text", "")))
|
|
if parts:
|
|
return "\n".join(parts)
|
|
return json.dumps(raw, ensure_ascii=False)
|
|
return str(raw)
|
|
|
|
def _audit(self, name, arguments, ok, text):
|
|
try:
|
|
self.app.app_state.add_interaction(
|
|
"mcp", input_text=json.dumps({"tool": name, "arguments": arguments},
|
|
ensure_ascii=False)[:4000],
|
|
output_text=str(text)[:4000], ok=ok, error="" if ok else str(text)[:1000],
|
|
meta={"tool": name, "mode": self.mode()},
|
|
)
|
|
except Exception:
|
|
pass
|