Files
smeta-web/smeta_mcp.py
T
anorandClaude Opus 4.7 0153cb761b feat: smeta_mcp self-contained + интеграция в claude_bridge.py (Этап 2 prep)
— smeta_mcp.py больше не зависит от claude_bridge_glm: read_xlsx_sheet,
  list_files реализованы локально через openpyxl и iterdir; find_in_normative
  fault-tolerant к отсутствию sentence_transformers/pymorphy2. Проверено в
  smeta-claude-sandbox image: extract_complaints_pairs внутри Docker
  отрабатывает корректно (231/145/339 на реальном файле).
— claude_bridge.py: mount smeta_mcp.py/complaints.py/mcp_config.json в /app/,
  передача SMETA_USER/SMETA_TAB/SMETA_WORK_DIR в env, --mcp-config к claude
  args, mcp__smeta__* в allowedTools, бамп ресурсов до 2g/2cpus.
— sandbox/mcp_config.json — конфиг MCP-сервера для claude CLI.
— SMETA_WORK_DIR override: в Docker /data смонтирован как work_dir вкладки,
  и MCP идёт прямо туда без сборки пути из user/tab.

Что осталось до полной интеграции (Этап 2/3):
  — переключить dev backend на claude/hybrid и сделать E2E
  — per-(user,tab) lock вместо глобального semaphore
  — rate limit per-user

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 18:42:24 +10:00

317 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""smeta_mcp — stdio MCP-сервер для домена смет.
Подключается к Claude CLI через `--mcp-config`. Принимает JSON-RPC 2.0 со
stdin, ответы пишет на stdout (одно JSON-сообщение на строку).
Контекст пользователя приходит через env vars: SMETA_USER, SMETA_TAB.
Запуск (вручную для теста):
SMETA_USER=smeta SMETA_TAB=default python3 smeta_mcp.py < requests.jsonl
В будущем удобнее переехать на pypi `mcp` (FastMCP), но MVP — без
зависимостей: stdio MCP это просто newline-delimited JSON-RPC 2.0.
"""
from __future__ import annotations
import json
import os
import sys
import traceback
from pathlib import Path
PROTOCOL_VERSION = "2025-06-18"
def _user_tab() -> tuple[str, str]:
return (
os.environ.get("SMETA_USER", "").strip(),
os.environ.get("SMETA_TAB", "default").strip() or "default",
)
def _work_dir(user: str, tab: str) -> Path:
"""Где лежат файлы пользователя.
SMETA_WORK_DIR (если задан) — прямой override абсолютным путём.
Используется в Docker, где host-путь `~/smeta-web-data/<user>/<tab>`
смонтирован в `/data`, и MCP должен идти туда напрямую.
Иначе — DATA_DIR/user/tab (как на хосте main-приложения).
"""
direct = os.environ.get("SMETA_WORK_DIR")
if direct:
return Path(direct)
base = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
d = base / user / tab
d.mkdir(parents=True, exist_ok=True)
return d
# ---------- Tool implementations (обёртки над существующими функциями) ----------
def tool_read_xlsx_sheet(*, filename: str, sheet: str | None = None, max_rows: int = 50) -> dict:
"""Локальная реализация — не зависит от tools_glm/claude_bridge_glm,
которые в Docker-sandbox-окружении могут отсутствовать."""
import openpyxl
user, tab = _user_tab()
fpath = _work_dir(user, tab) / Path(filename).name
if not fpath.exists():
return {"error": f"Файл «{filename}» не найден"}
if fpath.suffix.lower() not in {".xlsx", ".xlsm", ".xls"}:
return {"error": f"Неподдерживаемый формат: {fpath.suffix}"}
try:
wb = openpyxl.load_workbook(str(fpath), data_only=True)
except Exception as e:
return {"error": f"Не удалось открыть файл: {e}"}
if sheet is None:
ws = wb.worksheets[0]
sheet_name = ws.title
elif sheet in wb.sheetnames:
ws = wb[sheet]
sheet_name = sheet
else:
return {"error": f"Лист «{sheet}» не найден", "available_sheets": wb.sheetnames}
rows: list[dict] = []
real_count = 0
empty_streak = 0
for r_idx, row in enumerate(ws.iter_rows(), 1):
cells = {
c.column_letter: str(c.value)[:300]
for c in row
if c.value is not None and str(c.value).strip()
}
if not cells:
empty_streak += 1
if empty_streak >= 30:
break
continue
empty_streak = 0
real_count += 1
if len(rows) < max_rows:
rows.append({"row": r_idx, "cells": cells})
return {
"filename": fpath.name,
"sheet": sheet_name,
"all_sheets": wb.sheetnames,
"rows_with_data_total": real_count,
"rows_returned": len(rows),
"rows": rows,
}
def tool_find_in_normative(*, query: str, top_k: int = 3) -> dict:
"""В Docker-sandbox обычно нет sentence_transformers — деградирует
в `error`, не ломая MCP."""
try:
from claude_bridge_glm import _search_normative
except Exception as e:
return {"query": query, "error": f"RAG недоступен: {type(e).__name__}: {e}"}
try:
text = _search_normative(query, top_k=top_k)
except Exception as e:
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
return {"query": query, "result": text or "(нет совпадений)"}
def tool_list_files() -> dict:
user, tab = _user_tab()
work_dir = _work_dir(user, tab)
files = []
for f in sorted(work_dir.iterdir()):
if f.is_file() and not f.name.startswith("."):
files.append({"name": f.name, "size": f.stat().st_size})
return {"tab_id": tab, "files": files}
def tool_extract_complaints_pairs(*, filename: str) -> dict:
user, tab = _user_tab()
from complaints import extract_pairs
fpath = _work_dir(user, tab) / Path(filename).name
if not fpath.exists():
return {"error": f"Файл «{filename}» не найден в рабочей директории {user}/{tab}"}
try:
return extract_pairs(fpath)
except ValueError as e:
return {"error": str(e)}
def tool_apply_pukts_to_registry(*, filename: str) -> dict:
user, tab = _user_tab()
from complaints import apply_to_registry
work_dir = _work_dir(user, tab)
fpath = work_dir / Path(filename).name
if not fpath.exists():
return {"error": f"Файл «{filename}» не найден"}
out_name = f"{Path(filename).stem}_filled.xlsx"
out_path = work_dir / out_name
try:
result = apply_to_registry(fpath, out_path)
except ValueError as e:
return {"error": str(e)}
return {
**result,
"output_filename": out_name,
"download_url": f"/api/files/{out_name}",
}
# ---------- Registry + JSON-Schema ----------
TOOLS: dict[str, dict] = {
"read_xlsx_sheet": {
"fn": tool_read_xlsx_sheet,
"description": (
"Прочитать первые непустые строки конкретного листа xlsx-файла "
"из рабочей директории пользователя. Возвращает реальные значения "
"ячеек по координатам. Используй когда нужно процитировать ячейки "
"или понять структуру файла."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Имя файла как загружено (например 'РеестрСМ.xlsm')"},
"sheet": {"type": "string", "description": "Имя листа. Если не указано — первый лист"},
"max_rows": {"type": "integer", "description": "Сколько строк максимум (default 50)"},
},
"required": ["filename"],
},
},
"find_in_normative": {
"fn": tool_find_in_normative,
"description": (
"Семантический поиск по нормативной базе сметчика (ГЭСН, ФСНБ, "
"приказы Минстроя, методики). Возвращает релевантные фрагменты "
"с указанием источника."
),
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Поисковый запрос на русском"},
"top_k": {"type": "integer", "description": "Кол-во совпадений (default 3)"},
},
"required": ["query"],
},
},
"list_files": {
"fn": tool_list_files,
"description": "Список файлов, загруженных пользователем в текущей вкладке чата.",
"inputSchema": {"type": "object", "properties": {}},
},
"extract_complaints_pairs": {
"fn": tool_extract_complaints_pairs,
"description": (
"Извлечь из реестра РеестрСМ.xlsm все пары (пункт замечания, "
"код сметы) с листа «15.СМ». Regex-парсер, без галлюцинаций. "
"Возвращает stats и список pairs. Не модифицирует файл."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Имя xlsm-файла реестра"},
},
"required": ["filename"],
},
},
"apply_pukts_to_registry": {
"fn": tool_apply_pukts_to_registry,
"description": (
"Заполнить столбец D листа РеестрСМ номерами пунктов замечаний, "
"извлечёнными с листа 15.СМ. Учитывает: many-to-many, дубли строк "
"(пишем только в первую), скрытые строки (приоритет видимым). "
"Создаёт новый файл <stem>_filled.xlsx, не трогает исходник. "
"Возвращает download_url для скачивания через /api/files/."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Имя xlsm-файла реестра"},
},
"required": ["filename"],
},
},
}
def _tools_list_payload() -> list[dict]:
return [
{
"name": name,
"description": meta["description"],
"inputSchema": meta["inputSchema"],
}
for name, meta in TOOLS.items()
]
# ---------- JSON-RPC 2.0 ----------
def _rpc_result(rpc_id, result: dict) -> dict:
return {"jsonrpc": "2.0", "id": rpc_id, "result": result}
def _rpc_error(rpc_id, code: int, message: str) -> dict:
return {"jsonrpc": "2.0", "id": rpc_id, "error": {"code": code, "message": message}}
def handle(msg: dict) -> dict | None:
method = msg.get("method")
rpc_id = msg.get("id")
if method == "initialize":
return _rpc_result(rpc_id, {
"protocolVersion": PROTOCOL_VERSION,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "smeta", "version": "0.1.0"},
})
if method in ("notifications/initialized", "notifications/cancelled"):
return None # notification — без ответа
if method == "tools/list":
return _rpc_result(rpc_id, {"tools": _tools_list_payload()})
if method == "tools/call":
params = msg.get("params") or {}
name = params.get("name")
args = params.get("arguments") or {}
if name not in TOOLS:
return _rpc_error(rpc_id, -32601, f"Unknown tool: {name}")
try:
result = TOOLS[name]["fn"](**args)
except TypeError as e:
return _rpc_error(rpc_id, -32602, f"Bad arguments: {e}")
except Exception as e:
return _rpc_error(rpc_id, -32000, f"{type(e).__name__}: {e}")
is_error = isinstance(result, dict) and "error" in result
text = json.dumps(result, ensure_ascii=False, indent=2)
return _rpc_result(rpc_id, {
"content": [{"type": "text", "text": text}],
"isError": is_error,
})
if rpc_id is not None:
return _rpc_error(rpc_id, -32601, f"Method not found: {method}")
return None
def main() -> None:
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
msg = json.loads(line)
except json.JSONDecodeError:
continue
try:
resp = handle(msg)
except Exception:
traceback.print_exc(file=sys.stderr)
resp = _rpc_error(msg.get("id"), -32000, "Internal server error")
if resp is not None:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()