feat: smeta_mcp — stdio MCP-сервер для домена смет (Этап 1)
Цель: дать 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>
This commit is contained in:
+186
@@ -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}"
|
||||
Reference in New Issue
Block a user