Три обезличенных индекса из базы реального проекта (gge_deep — глубокий разбор всех схем): расценки с полным ресурсным составом + ценой/накладными/обоснованиями, КА-цены (winner + офферы поставщиков «Поставщик N»), ВОР-объёмы с формулами расчёта. Поиск (find_in_real_estimates / find_ka_price / find_in_vor) заведён в smeta_mcp и tools_glm (активный прод-бэкенд glm). Обезличивание verify_corpus: exit 0. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
590 lines
27 KiB
Python
590 lines
27 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",
|
||
)
|
||
|
||
|
||
def _work_dir(user: str, tab: str) -> Path:
|
||
"""Где лежат файлы пользователя.
|
||
|
||
SMETA_WORK_DIR (если задан) — прямой override абсолютным путём.
|
||
Используется в Docker, где host-путь `~/smeta-web-data/<user>/<tab>`
|
||
смонтирован в `/data`, и MCP должен идти туда напрямую.
|
||
|
||
Иначе — DATA_DIR/user/tab (как на хосте main-приложения).
|
||
"""
|
||
direct = os.environ.get("SMETA_WORK_DIR")
|
||
if direct:
|
||
return Path(direct)
|
||
base = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||
d = base / user / tab
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
return d
|
||
|
||
|
||
# ---------- Tool implementations (обёртки над существующими функциями) ----------
|
||
|
||
def tool_read_xlsx_sheet(*, filename: str, sheet: str | None = None, max_rows: int = 50) -> dict:
|
||
"""Локальная реализация — не зависит от tools_glm/claude_bridge_glm,
|
||
которые в Docker-sandbox-окружении могут отсутствовать."""
|
||
import openpyxl
|
||
user, tab = _user_tab()
|
||
fpath = _work_dir(user, tab) / Path(filename).name
|
||
if not fpath.exists():
|
||
return {"error": f"Файл «{filename}» не найден"}
|
||
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: list[dict] = []
|
||
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": fpath.name,
|
||
"sheet": sheet_name,
|
||
"all_sheets": wb.sheetnames,
|
||
"rows_with_data_total": real_count,
|
||
"rows_returned": len(rows),
|
||
"rows": rows,
|
||
}
|
||
|
||
|
||
def tool_find_in_normative(*, query: str, top_k: int = 3) -> dict:
|
||
"""В Docker-sandbox обычно нет sentence_transformers — деградирует
|
||
в `error`, не ломая MCP."""
|
||
try:
|
||
from claude_bridge_glm import _search_normative
|
||
except Exception as e:
|
||
return {"query": query, "error": f"RAG недоступен: {type(e).__name__}: {e}"}
|
||
try:
|
||
text = _search_normative(query, top_k=top_k)
|
||
except Exception as e:
|
||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||
return {"query": query, "result": text or "(нет совпадений)"}
|
||
|
||
|
||
def tool_find_in_real_estimates(*, query: str, top_k: int = 5) -> dict:
|
||
"""Поиск по обезличенному корпусу РЕАЛЬНЫХ применённых смет (ЛСР/ОСР).
|
||
Деградирует в error, если индекс не задеплоен."""
|
||
try:
|
||
from real_corpus import find_in_real_estimates
|
||
except Exception as e:
|
||
return {"query": query, "error": f"Корпус недоступен: {type(e).__name__}: {e}"}
|
||
try:
|
||
hits = find_in_real_estimates(query, top_k=top_k)
|
||
except Exception as e:
|
||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||
return {"query": query, "count": len(hits), "results": hits}
|
||
|
||
|
||
def tool_find_ka_price(*, query: str, top_k: int = 5) -> dict:
|
||
"""Поиск реальных цен материала (КА-рынок + прямые материалы смет), обезличено."""
|
||
try:
|
||
from real_corpus import find_ka_price
|
||
except Exception as e:
|
||
return {"query": query, "error": f"КА-индекс недоступен: {type(e).__name__}: {e}"}
|
||
try:
|
||
hits = find_ka_price(query, top_k=top_k)
|
||
except Exception as e:
|
||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||
return {"query": query, "count": len(hits), "results": hits}
|
||
|
||
|
||
def tool_find_in_vor(*, query: str, top_k: int = 5) -> dict:
|
||
"""Поиск по ведомостям объёмов работ — как реально считали объём."""
|
||
try:
|
||
from real_corpus import find_in_vor
|
||
except Exception as e:
|
||
return {"query": query, "error": f"ВОР-индекс недоступен: {type(e).__name__}: {e}"}
|
||
try:
|
||
hits = find_in_vor(query, top_k=top_k)
|
||
except Exception as e:
|
||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||
return {"query": query, "count": len(hits), "results": hits}
|
||
|
||
|
||
def tool_list_files() -> dict:
|
||
user, tab = _user_tab()
|
||
work_dir = _work_dir(user, tab)
|
||
files = []
|
||
for f in sorted(work_dir.iterdir()):
|
||
if f.is_file() and not f.name.startswith("."):
|
||
files.append({"name": f.name, "size": f.stat().st_size})
|
||
return {"tab_id": tab, "files": files}
|
||
|
||
|
||
def tool_extract_complaints_pairs(*, filename: str) -> dict:
|
||
user, tab = _user_tab()
|
||
from complaints import extract_pairs
|
||
fpath = _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 complaints import apply_to_registry
|
||
work_dir = _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}",
|
||
}
|
||
|
||
|
||
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] = {
|
||
"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"],
|
||
},
|
||
},
|
||
"find_in_real_estimates": {
|
||
"fn": tool_find_in_real_estimates,
|
||
"description": (
|
||
"Поиск по корпусу РЕАЛЬНЫХ применённых смет сданного проекта "
|
||
"(обезличено). По описанию работы возвращает: какую расценку "
|
||
"реально применяли эксперты, ед.изм, как часто (freq), типовой "
|
||
"объём (qty min/median/max), регионы. Дополняет find_in_normative: "
|
||
"тот говорит «какие расценки существуют», этот — «какие реально "
|
||
"применяли под эту работу». Используй когда нужно подсказать "
|
||
"расценку под работу или показать реальную практику применения."
|
||
),
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"query": {"type": "string", "description": "Описание работы на русском (напр. «армирование монолитной плиты»)"},
|
||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||
},
|
||
"required": ["query"],
|
||
},
|
||
},
|
||
"find_ka_price": {
|
||
"fn": tool_find_ka_price,
|
||
"description": (
|
||
"Поиск реальных рыночных цен на материал/оборудование из "
|
||
"конъюнктурного анализа (КА) сданного проекта (обезличено: "
|
||
"поставщики → «Поставщик N»). Возвращает: цену min/median/max, "
|
||
"цену победителя, разброс по обезличенным офферам, регион, "
|
||
"квартал/год. Используй для обоснования цены материала или когда "
|
||
"нужен реальный рыночный ориентир, а не нормативная цена ФССЦ."
|
||
),
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"query": {"type": "string", "description": "Название материала/оборудования (напр. «датчик температуры накладной»)"},
|
||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||
},
|
||
"required": ["query"],
|
||
},
|
||
},
|
||
"find_in_vor": {
|
||
"fn": tool_find_in_vor,
|
||
"description": (
|
||
"Поиск по ведомостям объёмов работ (ВОР) сданного проекта "
|
||
"(обезличено). По описанию работы возвращает: как реально считали "
|
||
"ОБЪЁМ — ед.изм, типовое кол-во (min/median/max), формулы расчёта "
|
||
"объёма, ссылки на листы обоснования. Используй когда вопрос про "
|
||
"объём работ, методику его подсчёта или ведомость объёмов."
|
||
),
|
||
"inputSchema": {
|
||
"type": "object",
|
||
"properties": {
|
||
"query": {"type": "string", "description": "Описание работы (напр. «разработка грунта экскаватором»)"},
|
||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||
},
|
||
"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"],
|
||
},
|
||
},
|
||
"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"],
|
||
},
|
||
},
|
||
}
|
||
|
||
|
||
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()
|