feat: универсальные MCP-tools для .gge архивов + clarification-first алгоритм

Перенос алгоритма обработки смет из чат-сессии в dev-чат smeta-web:
агент сам уточняет задачу у пользователя и собирает решение из
универсальных tools, без специальных скриптов под конкретный сценарий.

- gge_tools.py: парсер архивов .gge (extract_archive с cp866-decoding и
  path-traversal guard, parse_gge_file для XML смет ГГЭ, index_gge_directory
  с записью полного индекса в JSON, update_xlsx_cells для массовой записи).
- smeta_mcp.py: 3 новых tool — parse_gge_archive, parse_gge_file,
  update_xlsx_cells. Универсальные, не привязаны к конкретной задаче
  (ИГИ/ТС, сводная таблица и т.д.).
- claude_project_instructions.md: явный алгоритм «понимание → уточнения
  → подтверждение → выполнение → проверка» вместо одной строки
  «уточняй». Описание новых tools для агента.
- claude_bridge.py: монтирование gge_tools.py в /app, новые tools в
  --allowedTools.

Тест: JSON-RPC stdio + прямой вызов tool-функций на 1989 .gge
(1750 уникальных кодов, 1082 с «разработка грунта», 821 с
EstimatePrice/Summary/Transport > 0). Эталон ЛСР-04-01-0-00-01:
has_excavation=True, has_transport_summary=True. update_xlsx_cells
записал E=ИГИ, F=ТС в первую строку кода. Regression: read_xlsx_sheet
не сломан.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-05-06 21:01:37 +10:00
co-authored by Claude Opus 4.7
parent f763d22263
commit 855e2f2eef
4 changed files with 459 additions and 2 deletions
+176
View File
@@ -154,6 +154,108 @@ def tool_apply_pukts_to_registry(*, filename: str) -> dict:
}
def tool_parse_gge_archive(*, filename: str, save_index: bool = True,
include_codes: bool = False) -> dict:
"""Распаковать zip с .gge и проиндексировать. Универсальный tool —
под любую задачу с архивом смет ГГЭ. Если zip уже распакован
(filename — папка), просто индексирует.
save_index=True пишет полный индекс с positions в <stem>_index.json
в work_dir — Claude может читать его через Bash python для глубокого
анализа без перепарсинга.
Возвращает: summary (счётчики, схемы), и first 20 codes как пример.
Если include_codes=True — возвращает все коды (но без positions).
"""
user, tab = _user_tab()
work_dir = _work_dir(user, tab)
src = work_dir / Path(filename).name
if not src.exists():
return {"error": f"«{filename}» не найден в {user}/{tab}"}
from gge_tools import extract_archive, index_gge_directory
if src.is_dir():
target = src
extract_info = None
elif src.suffix.lower() == '.zip':
target = work_dir / src.stem
extract_info = extract_archive(src, target)
else:
return {"error": f"Неподдерживаемый формат: {src.suffix}. Ожидается .zip или папка."}
index_path = work_dir / f"{Path(filename).stem}_index.json" if save_index else None
idx = index_gge_directory(target, save_index_to=index_path)
by_code = idx['by_code']
summary = idx['summary']
codes = sorted(by_code.keys())
out = {
"extracted_to": str(target),
"extract_info": extract_info,
"summary": summary,
"index_file": str(index_path) if index_path else None,
"sample_codes": codes[:20],
}
if include_codes:
out["all_codes"] = codes
return out
def tool_parse_gge_file(*, filename: str, max_positions: int = 30) -> dict:
"""Распарсить одну .gge смету (XML). filename — относительный путь
в work_dir или внутри ранее распакованной папки.
Возвращает: code, name, schema_kind, has_excavation,
has_transport_summary, totals (полностью), первые max_positions
позиций. Удобно посмотреть структуру конкретной сметы.
"""
user, tab = _user_tab()
work_dir = _work_dir(user, tab)
candidate = work_dir / filename
if not candidate.exists():
# fall back: search by basename
matches = list(work_dir.rglob(Path(filename).name))
if not matches:
return {"error": f"«{filename}» не найден в {user}/{tab}"}
candidate = matches[0]
from gge_tools import parse_gge_file
data = parse_gge_file(candidate)
if 'error' in data:
return data
if len(data['positions']) > max_positions:
data['positions_total'] = len(data['positions'])
data['positions'] = data['positions'][:max_positions]
data['positions_truncated'] = True
return data
def tool_update_xlsx_cells(*, filename: str, sheet: str,
updates: list, out_filename: str | None = None) -> dict:
"""Массовая запись ячеек в xlsx. Универсальный tool — годится для
любой задачи (заполнение реестра, добавление сводных строк).
updates: [{"row": int, "col": "E"|int, "value": <строка|число>}, ...]
out_filename: если не задан — <stem>_updated.xlsx.
Не модифицирует исходник; результат в work_dir.
"""
user, tab = _user_tab()
work_dir = _work_dir(user, tab)
src = work_dir / Path(filename).name
if not src.exists():
return {"error": f"«{filename}» не найден"}
if not isinstance(updates, list):
return {"error": "updates должен быть списком {row, col, value}"}
out_name = out_filename or f"{Path(filename).stem}_updated.xlsx"
out_path = work_dir / out_name
from gge_tools import update_xlsx_cells
res = update_xlsx_cells(src, out_path, sheet, updates)
if 'error' in res:
return res
return {
**res,
"output_filename": out_name,
"download_url": f"/api/files/{out_name}",
}
# ---------- Registry + JSON-Schema ----------
TOOLS: dict[str, dict] = {
@@ -228,6 +330,80 @@ TOOLS: dict[str, dict] = {
"required": ["filename"],
},
},
"parse_gge_archive": {
"fn": tool_parse_gge_archive,
"description": (
"Распаковать .zip с .gge файлами (сметы ГГЭ, XML) и построить "
"индекс по коду сметы (Estimate/Num). Для каждой сметы возвращает: "
"schema_kind (local|object|unknown), has_excavation (есть ли в "
"Cost.Name подстрока «разработка грунта»), has_transport_summary "
"(EstimatePrice/Summary/Transport > 0), total_rub, transport_rub, "
"name, path. Полный индекс с позициями сохраняется в "
"<stem>_index.json — читай его через Bash python для глубокого "
"анализа. Если filename — уже распакованная папка, просто "
"индексирует. Универсальный tool: используй для любой задачи, где "
"нужно агрегировать данные по архиву смет."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Имя .zip или папки в work_dir"},
"save_index": {"type": "boolean", "description": "Сохранить полный индекс в JSON (default true)"},
"include_codes": {"type": "boolean", "description": "Вернуть все коды смет (default false — только первые 20)"},
},
"required": ["filename"],
},
},
"parse_gge_file": {
"fn": tool_parse_gge_file,
"description": (
"Распарсить одну .gge смету (XML формата ГГЭ). Возвращает: "
"code, name, schema_kind, has_excavation, has_transport_summary, "
"totals (все поля EstimatePrice/Summary), positions (список "
"Cost/Transport позиций с name/code/quantity/unit/price). "
"Полезно для уточнения структуры конкретной сметы."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Путь к .gge файлу относительно work_dir (или просто basename — будет найден)"},
"max_positions": {"type": "integer", "description": "Лимит позиций в ответе (default 30)"},
},
"required": ["filename"],
},
},
"update_xlsx_cells": {
"fn": tool_update_xlsx_cells,
"description": (
"Массовая запись ячеек в xlsx файл. Универсальный tool: годится "
"для заполнения колонок (E=ИГИ, F=ТС), добавления сводных строк, "
"правок отдельных ячеек. Создаёт копию <stem>_updated.xlsx, "
"не трогает исходник. Возвращает download_url. "
"ВАЖНО: если исходник .xlsm — VBA не сохранится, выход всегда .xlsx."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Имя xlsx/xlsm файла"},
"sheet": {"type": "string", "description": "Имя листа"},
"updates": {
"type": "array",
"items": {
"type": "object",
"properties": {
"row": {"type": "integer"},
"col": {"description": "Буква (E) или индекс (5)"},
"value": {},
},
"required": ["row", "col"],
},
"description": "Список {row, col, value} для записи",
},
"out_filename": {"type": "string", "description": "Имя выходного файла (default <stem>_updated.xlsx)"},
},
"required": ["filename", "sheet", "updates"],
},
},
}