Цель: дать Claude-CLI (и любому MCP-клиенту) единый набор инструментов
для работы со сметами, чтобы агент мог реально читать xlsx, искать
по нормативке и заполнять реестры — без кастомных bridge-кода.
Реализовано:
- newline-delimited JSON-RPC 2.0 через stdin/stdout, без зависимостей
(на pypi `mcp`/FastMCP мигрируем при необходимости)
- 5 tools, обёртки над уже работающим кодом:
read_xlsx_sheet, find_in_normative, list_files,
extract_complaints_pairs, apply_pukts_to_registry
- Контекст пользователь/вкладка через env vars SMETA_USER, SMETA_TAB,
DATA_DIR
- Errors внутри tool возвращаются как `{"error": ...}` + isError=true
в content — модель видит ошибку и реагирует
Standalone-тесты на dev:
- tools/list → 5 инструментов с JSON-Schema
- extract_complaints_pairs РеестрСМ.xlsm → 231 жалобы, 339 пар
- read_xlsx_sheet 15.СМ → 250 строк, первая ячейка
- list_files → корректный список
Также включает tools_glm.py (примитивы read_xlsx_sheet и пр.) —
ранее untracked.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
245 lines
9.3 KiB
Python
245 lines
9.3 KiB
Python
"""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",
|
|
)
|
|
|
|
|
|
# ---------- Tool implementations (обёртки над существующими функциями) ----------
|
|
|
|
def tool_read_xlsx_sheet(*, filename: str, sheet: str | None = None, max_rows: int = 50) -> dict:
|
|
user, tab = _user_tab()
|
|
from tools_glm import read_xlsx_sheet
|
|
return read_xlsx_sheet(user, tab, filename=filename, sheet=sheet, max_rows=max_rows)
|
|
|
|
|
|
def tool_find_in_normative(*, query: str, top_k: int = 3) -> dict:
|
|
user, tab = _user_tab()
|
|
from tools_glm import find_in_normative
|
|
return find_in_normative(user, tab, query=query, top_k=top_k)
|
|
|
|
|
|
def tool_list_files() -> dict:
|
|
user, tab = _user_tab()
|
|
from tools_glm import list_files
|
|
return list_files(user, tab)
|
|
|
|
|
|
def tool_extract_complaints_pairs(*, filename: str) -> dict:
|
|
user, tab = _user_tab()
|
|
from claude_bridge_glm import get_work_dir
|
|
from complaints import extract_pairs
|
|
fpath = get_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 claude_bridge_glm import get_work_dir
|
|
from complaints import apply_to_registry
|
|
work_dir = get_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()
|