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
+7 -1
View File
@@ -141,8 +141,10 @@ async def stream_claude(
# Build claude args
smeta_mcp_path = APP_DIR / "smeta_mcp.py"
smeta_complaints_path = APP_DIR / "complaints.py"
smeta_gge_tools_path = APP_DIR / "gge_tools.py"
smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json"
mcp_available = (smeta_mcp_path.exists() and smeta_complaints_path.exists()
and smeta_gge_tools_path.exists()
and smeta_mcp_config.exists())
claude_args = [
@@ -154,7 +156,10 @@ async def stream_claude(
"mcp__smeta__read_xlsx_sheet,"
"mcp__smeta__list_files,"
"mcp__smeta__extract_complaints_pairs,"
"mcp__smeta__apply_pukts_to_registry"),
"mcp__smeta__apply_pukts_to_registry,"
"mcp__smeta__parse_gge_archive,"
"mcp__smeta__parse_gge_file,"
"mcp__smeta__update_xlsx_cells"),
]
if mcp_available:
claude_args.extend(["--mcp-config", "/app/mcp_config.json"])
@@ -184,6 +189,7 @@ async def stream_claude(
cmd.extend([
"-v", f"{smeta_mcp_path.resolve()}:/app/smeta_mcp.py:ro",
"-v", f"{smeta_complaints_path.resolve()}:/app/complaints.py:ro",
"-v", f"{smeta_gge_tools_path.resolve()}:/app/gge_tools.py:ro",
"-v", f"{smeta_mcp_config.resolve()}:/app/mcp_config.json:ro",
])
if instructions.exists():
+18 -1
View File
@@ -458,13 +458,30 @@ for row in sheet.findall('.//s:row', ns):
- ВСЕГДА показывай результат: первые строки, итоги
- После создания файла — скажи что файл готов и можно скачать
## ⚡ Алгоритм работы со сложными задачами с файлами
При любой задаче на ОБРАБОТКУ файлов пользователя (заполнить, проанализировать, преобразовать, агрегировать) — **обязательно** соблюдай этот цикл:
1. **Понимание** — сформулируй СВОИМИ СЛОВАМИ, что понял из задачи: какой файл-источник, какая операция, какой результат, по каким правилам.
2. **Уточнения** — если есть НЕОДНОЗНАЧНОСТИ — задай вопросы ПЕРЕД выполнением. Типичные неоднозначности: что считать триггером? откуда брать значение? куда писать (колонка, лист)? как обрабатывать дубли? перезаписать или создать новый файл?
3. **Подтверждение** — дождись явного «да, делай» от пользователя. Не приступай по молчаливому согласию.
4. **Выполнение** — реализуй задачу. Если по дороге появилось новое уточнение — спроси, не предполагай.
5. **Проверка** — после выполнения покажи результат на эталонном примере (если он есть в задаче) и попроси пользователя подтвердить.
Этот цикл ВАЖНЕЕ скорости. Лучше задать 5 уточнений и сделать правильно с первого раза, чем сделать «как понял» и переделывать. Уточнения — это **признак понимания**, а не неуверенности.
## Правила поведения
1. **Уточняй** — если запрос неясен, задай вопрос ПЕРЕД выполнением
1. **Уточняй** — следуй алгоритму выше
2. **Превью** — показывай предпросмотр результата
3. **Подтверждение** — для удаления/перезаписи спрашивай
4. **Ошибки** — объясни простым языком, предложи альтернативу
5. **Не выполняй** сетевых запросов, не устанавливай пакеты
## Tools для работы со сметными архивами .gge
- `mcp__smeta__parse_gge_archive(filename)` — распаковать .zip с .gge и проиндексировать. Для каждой сметы получишь has_excavation (есть «разработка грунта»), has_transport_summary, total_rub, schema_kind. Полный индекс с позициями сохраняется в `<stem>_index.json` — читай его через Bash python для глубокой аналитики (фильтры по Cost.Name, агрегаты).
- `mcp__smeta__parse_gge_file(filename)` — распарсить одну смету: получишь все позиции (Cost+Transport), totals, флаги.
- `mcp__smeta__update_xlsx_cells(filename, sheet, updates)` — массовая запись ячеек. updates: `[{row, col, value}, ...]`. Создаёт `<stem>_updated.xlsx`.
## Автоматические приёмы (применяй без запроса)
- Перед работой с файлом — покажи структуру
- Грязные данные — предупреди
+258
View File
@@ -0,0 +1,258 @@
"""gge_tools — работа с архивами .gge (XML смет ГГЭ) и xlsx-реестрами.
Универсальный, без привязки к конкретной задаче (ИГИ/ТС). Чат-агент
сам комбинирует tools для нужного сценария.
Зависимости: openpyxl + stdlib (zipfile, xml.etree, json). Без plotly,
sentence-transformers и т.п. — работает в sandbox-контейнере.
"""
from __future__ import annotations
import json
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
def _decode_zip_name(info: zipfile.ZipInfo) -> str:
"""Python 3 zipfile авто-декодирует cp437 если флаг UTF-8 (0x800) не задан.
Для имён от Windows-архиваторов нужно re-encode→re-decode как cp866."""
if info.flag_bits & 0x800:
return info.filename
try:
return info.filename.encode('cp437').decode('cp866')
except UnicodeError:
return info.filename
def extract_archive(zip_path: Path, target_dir: Path) -> dict:
"""Распаковать zip с .gge файлами в target_dir. Сохраняет древовидную
структуру внутри архива. Корректно декодирует cp866-имена.
Возвращает: {target: <abs path>, total_files: N, gge_files: M, skipped: K}
"""
import os
target_dir.mkdir(parents=True, exist_ok=True)
target_resolved = target_dir.resolve()
total = gge = skipped = 0
with zipfile.ZipFile(zip_path) as z:
for info in z.infolist():
if info.is_dir():
continue
total += 1
name = _decode_zip_name(info).replace('\\', '/')
# path traversal guard
out = (target_dir / name).resolve()
try:
out.relative_to(target_resolved)
except ValueError:
skipped += 1
continue
out.parent.mkdir(parents=True, exist_ok=True)
try:
with z.open(info) as src, open(out, 'wb') as dst:
while chunk := src.read(64 * 1024):
dst.write(chunk)
if name.lower().endswith('.gge'):
gge += 1
except Exception:
skipped += 1
return {
'target': str(target_dir),
'total_files': total,
'gge_files': gge,
'skipped': skipped,
}
def parse_gge_file(path: Path) -> dict:
"""Извлечь данные одной сметы из .gge XML.
Возвращает: code, name, schema_kind ('local' | 'object' | 'unknown'),
has_excavation, has_transport_summary, totals (всё что есть в
EstimatePrice/Summary), positions (список dict с name/code/quantity/
unit/price_total из <Cost>; для перевозочных позиций <Transport>
тоже включаем).
"""
try:
tree = ET.parse(str(path))
except (ET.ParseError, OSError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
root = tree.getroot()
schema_loc = root.attrib.get(
'{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation', '')
if 'LocalEstimate' in schema_loc:
schema_kind = 'local'
elif 'ObjectEstimate' in schema_loc:
schema_kind = 'object'
else:
schema_kind = 'unknown'
code = (root.findtext('.//Estimate/Num') or '').strip()
name = (root.findtext('.//Estimate/Name') or '').strip()
# Totals: EstimatePrice/Summary
totals: dict[str, float] = {}
summary = root.find('.//EstimatePrice/Summary')
if summary is not None:
for child in summary:
if len(list(child)) > 0:
# Materials/Total etc.
for sub in child:
if sub.text:
try:
totals[f'{child.tag}.{sub.tag}'] = float(sub.text.strip())
except ValueError:
pass
elif child.text:
try:
totals[child.tag] = float(child.text.strip())
except ValueError:
pass
# Positions: Item/Cost (work) + Item/Transport (carrier line)
positions: list[dict] = []
has_excavation = False
for it in root.iter('Item'):
for kind_tag in ('Cost', 'Transport'):
node = it.find(kind_tag)
if node is None:
continue
pname = (node.findtext('Name') or '').strip()
if not pname:
continue
pcode = (node.findtext('Code') or '').strip()
qty = node.findtext('Quantity') or ''
unit = (node.findtext('Unit') or '').strip()
ptcur = node.findtext('PriceTotalCur') or ''
direct = node.findtext('.//Totals/Current/Direct') or ''
try: qty_f = float(qty) if qty else 0.0
except ValueError: qty_f = 0.0
try: pt_f = float(ptcur) if ptcur else 0.0
except ValueError: pt_f = 0.0
try: dir_f = float(direct) if direct else 0.0
except ValueError: dir_f = 0.0
positions.append({
'kind': kind_tag.lower(), # 'cost' | 'transport'
'name': pname,
'code': pcode,
'quantity': qty_f,
'unit': unit,
'price_total_cur': pt_f,
'direct': dir_f,
})
if 'разработка грунта' in pname.lower():
has_excavation = True
has_transport_summary = (totals.get('Transport', 0.0) > 0)
return {
'path': str(path),
'code': code,
'name': name,
'schema_kind': schema_kind,
'has_excavation': has_excavation,
'has_transport_summary': has_transport_summary,
'totals': totals,
'positions': positions,
}
def index_gge_directory(dir_path: Path, save_index_to: Path | None = None) -> dict:
"""Пройти все .gge в dir_path рекурсивно, распарсить.
Returns: {by_code: {code: {has_excavation, has_transport_summary,
name, total_rub, schema_kind, path}}, summary: {...}, parse_errors: N}.
Если save_index_to задан — пишет полный индекс (с positions) в JSON.
Возврат компактнее (без positions), чтобы влез в MCP-ответ.
"""
files = sorted(p for p in dir_path.rglob('*.gge'))
by_code: dict[str, dict] = {}
full_index: dict[str, dict] = {}
parse_errors = 0
schemas: dict[str, int] = {}
excav = transp = 0
rub_sum = 0.0
for f in files:
data = parse_gge_file(f)
if 'error' in data:
parse_errors += 1
continue
code = data['code']
if not code:
continue
# Сводный (компактный) вид без positions для MCP-ответа.
compact = {
'name': data['name'],
'schema_kind': data['schema_kind'],
'has_excavation': data['has_excavation'],
'has_transport_summary': data['has_transport_summary'],
'total_rub': data['totals'].get('Total') or data['totals'].get('Price') or 0.0,
'transport_rub': data['totals'].get('Transport', 0.0),
'path': data['path'],
}
prev = by_code.get(code)
if prev is None or compact['total_rub'] > prev['total_rub']:
by_code[code] = compact
full_index[code] = data
schemas[data['schema_kind']] = schemas.get(data['schema_kind'], 0) + 1
if data['has_excavation']:
excav += 1
if data['has_transport_summary']:
transp += 1
rub_sum += compact['total_rub']
summary = {
'files_total': len(files),
'parse_errors': parse_errors,
'unique_codes': len(by_code),
'schemas': schemas,
'with_excavation': excav,
'with_transport_summary': transp,
'sum_total_rub': rub_sum,
}
if save_index_to is not None:
save_index_to.write_text(
json.dumps({'by_code': full_index, 'summary': summary},
ensure_ascii=False),
encoding='utf-8',
)
return {'by_code': by_code, 'summary': summary}
def update_xlsx_cells(src_path: Path, out_path: Path, sheet: str,
updates: list[dict]) -> dict:
"""Записать список ячеек в xlsx.
updates: [{"row": 5, "col": "E" | 5, "value": "ИГИ"}, ...]
Сохраняет копию в out_path. Не трогает остальной контент книги.
"""
import openpyxl
wb = openpyxl.load_workbook(str(src_path))
if sheet not in wb.sheetnames:
return {'error': f'Лист «{sheet}» не найден',
'available_sheets': wb.sheetnames}
ws = wb[sheet]
written = 0
skipped = 0
for u in updates:
try:
row = int(u['row'])
col = u['col']
if isinstance(col, str):
col_idx = openpyxl.utils.column_index_from_string(col)
else:
col_idx = int(col)
ws.cell(row, col_idx).value = u.get('value')
written += 1
except (KeyError, ValueError, TypeError):
skipped += 1
wb.save(str(out_path))
return {
'output_path': str(out_path),
'sheet': sheet,
'cells_written': written,
'cells_skipped': skipped,
}
+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"],
},
},
}