From 7a6c91829a3c67d9c78e9fd8b0cf1576fff5913b Mon Sep 17 00:00:00 2001 From: anor Date: Wed, 6 May 2026 18:37:21 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20smeta=5Fmcp=20=E2=80=94=20stdio=20MCP-?= =?UTF-8?q?=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=B4=D0=BE=D0=BC=D0=B5=D0=BD=D0=B0=20=D1=81=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=20(=D0=AD=D1=82=D0=B0=D0=BF=201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Цель: дать 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) --- TODO.md | 125 ++++++++++++++++++++++++++ smeta_mcp.py | 244 +++++++++++++++++++++++++++++++++++++++++++++++++++ tools_glm.py | 186 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 555 insertions(+) create mode 100644 TODO.md create mode 100644 smeta_mcp.py create mode 100644 tools_glm.py diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..70c410a --- /dev/null +++ b/TODO.md @@ -0,0 +1,125 @@ +# TODO — переезд задач из отдельных страниц в чат + +Цель: чат становится единым интерфейсом. Гибридный роутинг: +- **DeepSeek** (через ZAI/`AI_BACKEND=glm`) — для нормативных вопросов и Q&A + без файлов (95% запросов из логов: «какой НР», «приказ 421», расценки). + Дёшево, быстро. +- **Claude CLI** (через **подписку Pro/Max**, не Anthropic API) — для + агентских задач (открыть/проанализировать/заполнить/сгенерировать + xlsx, ssr, генерация смет, batch-обработка). Использует уже + существующий `claude_bridge.py` (Docker + `claude -p + --output-format stream-json`), модернизированный под domain MCP. + +**Anthropic API не используем** — слишком дорого для MVP. Подписки +достаточно. При росте нагрузки — добавляем 2-ю подписку или +рейт-лимит per-user. + +Источник анализа: 1104 user-сообщения из прод-БД + инвентаризация +`static/*.html` и endpoints. + +## Этап 1 — Domain MCP server (`smeta_mcp.py`) + +Статус: ✅ done (skeleton, без интеграции с CLI) + +Один MCP-сервер, переиспользуемый и DeepSeek-tools веткой, и +Claude-CLI веткой. stdio-транспорт (стандартный для MCP). + +- [x] Skeleton `smeta_mcp.py`: stdio MCP server (без зависимостей — + newline-delimited JSON-RPC 2.0; на pypi `mcp` мигрировать при + необходимости) +- [x] Tools (обёртки над уже существующими функциями): + - [x] `read_xlsx_sheet(filename, sheet?, max_rows=50)` ← `tools_glm.py` + - [x] `find_in_normative(query, top_k=3)` ← `claude_bridge_glm._search_normative` + - [x] `list_files()` ← `list_user_files` + - [x] `extract_complaints_pairs(filename)` ← `complaints.extract_pairs` + - [x] `apply_pukts_to_registry(filename)` ← `complaints.apply_to_registry` +- [x] Контекст user/tab — через env vars (`SMETA_USER`, `SMETA_TAB`) +- [x] Standalone-тест: tools/list и tools/call через stdio JSON-RPC + +## Этап 2 — Реанимация `claude_bridge.py` (Claude CLI + MCP) + +Статус: ⬜ planned + +- [ ] Подключить `smeta_mcp` к claude CLI: `--mcp-config ` или + добавить блок `mcpServers` в `~/.claude.json` (mounted в Docker) +- [ ] Бамп ресурсов: `--memory=2g`, `--cpus=2` — для больших xlsm +- [ ] Убрать глобальный `_semaphore` → per-(user,tab) lock +- [ ] Сохранение `session_id` per-(user,tab) для multi-turn +- [ ] Разрешённые tools: `mcp__smeta__*, Read, Glob, Grep` (Bash/Write + по умолчанию запрещены) +- [ ] Обработка stream-json events: парсить `tool_use_block`, + `tool_result_block`, генерировать SSE `event: tool_call.start/result` +- [ ] Per-user rate limit: 5 агентских запросов в час на юзера + (просто счётчик в памяти + UI-сообщение если превышен) + +## Этап 3 — Гибридный роутер `AI_BACKEND=hybrid` + +Статус: ⬜ planned + +- [ ] Новый ветка `AI_BACKEND=hybrid` в `main.py` (рядом с `glm`/`auto`/`claude`) +- [ ] Логика: keyword-эвристика (как в `auto`-ветке сейчас): + - есть упоминание файла из work_dir / file action keyword → Claude CLI + - норматив-keyword (НР, СП, приказ, индекс, ГЭСН, методика) → DeepSeek + - default → DeepSeek +- [ ] DeepSeek-ветка остаётся как сейчас + (опционально) function calling + с теми же MCP-tools (через своих API клиентов) +- [ ] E2E на dev: + - [ ] «Какой НР для ж/д работ?» → DeepSeek + - [ ] «Заполни пункты замечаний в этом реестре» → Claude CLI → + возвращает скачиваемый xlsx + - [ ] «Сколько строк на листе 15.СМ?» → Claude CLI с tool `read_xlsx_sheet` + +## Этап 4 — UI tool-cards (общий протокол) + +Статус: ⬜ planned + +- [ ] SSE-протокол: новые events `tool_call.start`, `tool_call.delta`, + `tool_call.result`, `step.complete`, `usage` +- [ ] В `chat.html`: рендер карточек (pending/running/success/error), + раскрытие диффов, ссылки на скачивание +- [ ] Approval-кнопки для опасных операций (apply, write_cell) +- [ ] Прогресс-индикатор для batch (вместо отдельной страницы) + +## Этап 5 — Депрекация отдельных страниц + +Статус: ⬜ planned + +- [ ] `/wizard` → редирект на чат с подсказкой +- [ ] `/ssr` → tool `generate_ssr` в MCP, страница опционально +- [ ] `/generate`, `/check`, `/reference` → MCP tools +- [ ] Удалить `/batch.html`, `/batch2.html` (legacy) +- [ ] `/admin`, `/register`, `/security` — оставить (не задачи) + +## Связанные правки, которые уже сделаны (не повторять) + +- ✅ DeepSeek V4 как основной backend (`AI_BACKEND=glm`) +- ✅ Расширение xlsm/xlsb/ods, стрим-чтение xlsm с per-sheet budget +- ✅ Гибкий system prompt: модель не отказывает в анализе файлов; + запрет на выдумывание содержимого по имени +- ✅ Чтение листинга zip-архивов (cp866 для Windows-имён) +- ✅ Endpoints `/api/extract_complaints` + `/api/apply_matches` + (учтены: many-to-many, дубли строк, скрытые строки, .xlsx как формат) +- ✅ Dev-сервер на 8103 (`smeta-web-dev.service`, ветка `dev`) +- ✅ Fallback `crypto.randomUUID` для HTTP origin +- ✅ Лимит загрузки 50 → 100 МБ +- ✅ Админка: раздел «Файлы» — просмотр и скачивание файлов любого + юзера (включая env-only `smeta` и удалённых аккаунтов) + +## Решения / отложенные опции + +- ❌ Anthropic API (Claude Agent SDK через `ANTHROPIC_API_KEY`) — отложено, + слишком дорого для MVP. Возможно в будущем для production-scale. +- 🟡 Docker-VM per session — сейчас Docker per-request с per-(user,tab) + `cwd`. При росте до 50+ одновременных юзеров — мигрировать на + long-lived containers с queue. +- 🟡 Tool-calling на стороне DeepSeek (function calling в OpenAI-формате) — + опционально, для случая когда юзер просит лёгкий tool без эскалации + до Claude. Не приоритет. + +## Ссылки + +- Прод: `https://infosmeta.ru` → `127.0.0.1:8101` → `~/smeta-web/` (`main`) +- Dev: `http://192.168.87.76:8103` → `~/smeta-web-dev/` (`dev`) +- Repo: `https://git.kazin.ru/anor/smeta-web.git` +- claude-agent-sdk docs: https://code.claude.com/docs/en/agent-sdk/overview +- MCP custom tools: https://code.claude.com/docs/en/agent-sdk/custom-tools diff --git a/smeta_mcp.py b/smeta_mcp.py new file mode 100644 index 0000000..a0e13da --- /dev/null +++ b/smeta_mcp.py @@ -0,0 +1,244 @@ +"""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, дубли строк " + "(пишем только в первую), скрытые строки (приоритет видимым). " + "Создаёт новый файл _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() diff --git a/tools_glm.py b/tools_glm.py new file mode 100644 index 0000000..c278d9d --- /dev/null +++ b/tools_glm.py @@ -0,0 +1,186 @@ +"""DeepSeek function-calling tools. + +Каждый tool — это пара (callable, JSON-Schema). callable принимает +(user, tab_id, **args) и возвращает dict, сериализуемый в JSON; +ошибки возвращаются как `{"error": "..."}`, чтобы модель могла на них +отреагировать в следующем шаге диалога. +""" +from __future__ import annotations + +from pathlib import Path + +import openpyxl + + +def read_xlsx_sheet( + user: str, + tab_id: str, + *, + filename: str, + sheet: str | None = None, + max_rows: int = 50, +) -> dict: + """Прочитать первые непустые строки конкретного листа xlsx.""" + from claude_bridge_glm import get_work_dir + + work_dir = get_work_dir(user, tab_id) + safe_name = Path(filename).name + fpath = work_dir / safe_name + if not fpath.exists(): + return {"error": f"Файл «{safe_name}» не найден в рабочей директории"} + 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 = [] + 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": safe_name, + "sheet": sheet_name, + "all_sheets": wb.sheetnames, + "rows_with_data_total": real_count, + "rows_returned": len(rows), + "rows": rows, + } + + +def find_in_normative( + user: str, + tab_id: str, + *, + query: str, + top_k: int = 3, +) -> dict: + """Семантический поиск по нормативной базе.""" + from claude_bridge_glm import _search_normative + + text = _search_normative(query, top_k=top_k) + return { + "query": query, + "result": text or "(нет совпадений)", + } + + +def list_files(user: str, tab_id: str) -> dict: + """Список загруженных файлов в текущей вкладке.""" + from claude_bridge_glm import list_user_files + + files = list_user_files(user, tab_id) + return {"tab_id": tab_id, "files": files} + + +# ---------- Registry + JSON-Schema for the API ---------- + +TOOL_REGISTRY = { + "read_xlsx_sheet": read_xlsx_sheet, + "find_in_normative": find_in_normative, + "list_files": list_files, +} + +TOOLS_SCHEMA = [ + { + "type": "function", + "function": { + "name": "read_xlsx_sheet", + "description": ( + "Прочитать первые непустые строки конкретного листа xlsx-файла из " + "рабочей директории пользователя. Используй когда нужно понять " + "структуру файла или процитировать ячейки по точным координатам." + ), + "parameters": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "description": "Имя файла, например 'РеестрСМ.xlsm'", + }, + "sheet": { + "type": "string", + "description": "Имя листа. Если не указано — первый лист", + }, + "max_rows": { + "type": "integer", + "description": "Сколько строк вернуть максимум (default 50)", + }, + }, + "required": ["filename"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "find_in_normative", + "description": ( + "Семантический поиск по нормативной базе (ГЭСН, ФСНБ, приказы " + "Минстроя, методики). Используй для конкретных нормативных ссылок." + ), + "parameters": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Поисковый запрос"}, + "top_k": {"type": "integer", "description": "Кол-во совпадений (default 3)"}, + }, + "required": ["query"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "list_files", + "description": "Список файлов, загруженных пользователем в текущей вкладке.", + "parameters": {"type": "object", "properties": {}}, + }, + }, +] + + +def summarize_result(name: str, result: dict) -> str: + """Короткий человекочитаемый summary для UI.""" + if "error" in result: + return f"❌ {name}: {result['error']}" + if name == "read_xlsx_sheet": + return ( + f"✓ {name}: лист «{result.get('sheet')}» из «{result.get('filename')}» " + f"({result.get('rows_with_data_total')} строк с данными, " + f"показано {result.get('rows_returned')})" + ) + if name == "find_in_normative": + return f"✓ {name}: запрос «{result.get('query')}»" + if name == "list_files": + n = len(result.get("files", [])) + return f"✓ {name}: {n} файлов" + return f"✓ {name}"