diff --git a/TODO.md b/TODO.md index 70c410a..ea8476f 100644 --- a/TODO.md +++ b/TODO.md @@ -38,19 +38,25 @@ Claude-CLI веткой. stdio-транспорт (стандартный для ## Этап 2 — Реанимация `claude_bridge.py` (Claude CLI + MCP) -Статус: ⬜ planned +Статус: 🟡 in-progress (подключение готово, остались оптимизации и E2E) -- [ ] Подключить `smeta_mcp` к claude CLI: `--mcp-config ` или - добавить блок `mcpServers` в `~/.claude.json` (mounted в Docker) -- [ ] Бамп ресурсов: `--memory=2g`, `--cpus=2` — для больших xlsm +- [x] `sandbox/mcp_config.json` — MCP-конфиг для claude CLI +- [x] Mount `smeta_mcp.py` + `complaints.py` + `mcp_config.json` в `/app/` +- [x] `--mcp-config /app/mcp_config.json` к claude args +- [x] `mcp__smeta__*` в `--allowedTools` (read_xlsx_sheet, list_files, + extract_complaints_pairs, apply_pukts_to_registry) +- [x] env vars в Docker: SMETA_USER, SMETA_TAB, SMETA_WORK_DIR=/data +- [x] Бамп ресурсов: `--memory=2g`, `--cpus=2` +- [x] `smeta_mcp.py` self-contained — не зависит от claude_bridge_glm, + работает в minimal Docker-окружении (проверено в smeta-claude-sandbox) +- [x] `find_in_normative` fault-tolerant — не падает, если нет RAG-стека - [ ] Убрать глобальный `_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-сообщение если превышен) +- [ ] E2E на dev с `AI_BACKEND=claude` или `hybrid`: + - [ ] «прочитай файл X.xlsm и скажи сколько строк» → Claude вызывает + mcp__smeta__read_xlsx_sheet → отвечает реальным числом + - [ ] «заполни пункты замечаний в реестре» → Claude вызывает + mcp__smeta__apply_pukts_to_registry → возвращает download URL ## Этап 3 — Гибридный роутер `AI_BACKEND=hybrid` diff --git a/claude_bridge.py b/claude_bridge.py index 559e6a5..b3eec68 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -139,14 +139,26 @@ async def stream_claude( instructions = APP_DIR / "claude_project_instructions.md" # Build claude args + smeta_mcp_path = APP_DIR / "smeta_mcp.py" + smeta_complaints_path = APP_DIR / "complaints.py" + smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json" + mcp_available = (smeta_mcp_path.exists() and smeta_complaints_path.exists() + and smeta_mcp_config.exists()) + claude_args = [ "-p", message, "--output-format", "stream-json", "--verbose", - "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep", + "--allowedTools", + ("Bash,Read,Write,Edit,Glob,Grep," + "mcp__smeta__read_xlsx_sheet," + "mcp__smeta__list_files," + "mcp__smeta__extract_complaints_pairs," + "mcp__smeta__apply_pukts_to_registry"), ] + if mcp_available: + claude_args.extend(["--mcp-config", "/app/mcp_config.json"]) if instructions.exists(): - # Mount instructions file into container claude_args.extend([ "--append-system-prompt-file", "/instructions.md" ]) @@ -156,9 +168,9 @@ async def stream_claude( # Docker command cmd = [ "docker", "run", "--rm", - # Resource limits - "--memory=512m", - "--cpus=1", + # Resource limits — bumped for xlsm parsing + "--memory=2g", + "--cpus=2", "--network=host", # access xray on host # Mount work directory as /data "-v", f"{work_dir.resolve()}:/data", @@ -167,8 +179,13 @@ async def stream_claude( "-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json", # Mount smeta-railway project (read-only) "-v", f"{SMETA_PROJECT_DIR}:/smeta:ro", - # Mount instructions ] + if mcp_available: + 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_mcp_config.resolve()}:/app/mcp_config.json:ro", + ]) if instructions.exists(): cmd.extend(["-v", f"{instructions.resolve()}:/instructions.md:ro"]) @@ -177,6 +194,16 @@ async def stream_claude( "-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", "-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", "-e", "HOME=/home/worker", + ]) + if mcp_available: + # MCP видит файлы текущей вкладки прямо по /data — этот + # путь смонтирован выше как work_dir пользователя + cmd.extend([ + "-e", f"SMETA_USER={username}", + "-e", f"SMETA_TAB={tab_id}", + "-e", "SMETA_WORK_DIR=/data", + ]) + cmd.extend([ # Working directory "-w", "/data", # Image + claude args diff --git a/sandbox/mcp_config.json b/sandbox/mcp_config.json new file mode 100644 index 0000000..f4d26a5 --- /dev/null +++ b/sandbox/mcp_config.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "smeta": { + "command": "python3", + "args": ["/app/smeta_mcp.py"] + } + } +} diff --git a/smeta_mcp.py b/smeta_mcp.py index a0e13da..0e11cb9 100644 --- a/smeta_mcp.py +++ b/smeta_mcp.py @@ -28,31 +28,104 @@ def _user_tab() -> tuple[str, str]: ) +def _work_dir(user: str, tab: str) -> Path: + """Где лежат файлы пользователя. + + SMETA_WORK_DIR (если задан) — прямой override абсолютным путём. + Используется в Docker, где host-путь `~/smeta-web-data//` + смонтирован в `/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() - from tools_glm import read_xlsx_sheet - return read_xlsx_sheet(user, tab, filename=filename, sheet=sheet, max_rows=max_rows) + 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: - user, tab = _user_tab() - from tools_glm import find_in_normative - return find_in_normative(user, tab, query=query, top_k=top_k) + """В 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_list_files() -> dict: user, tab = _user_tab() - from tools_glm import list_files - return list_files(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 claude_bridge_glm import get_work_dir from complaints import extract_pairs - fpath = get_work_dir(user, tab) / Path(filename).name + fpath = _work_dir(user, tab) / Path(filename).name if not fpath.exists(): return {"error": f"Файл «{filename}» не найден в рабочей директории {user}/{tab}"} try: @@ -63,9 +136,8 @@ def tool_extract_complaints_pairs(*, filename: str) -> dict: 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) + work_dir = _work_dir(user, tab) fpath = work_dir / Path(filename).name if not fpath.exists(): return {"error": f"Файл «{filename}» не найден"} diff --git a/tools_glm.py b/tools_glm.py index c278d9d..a0902a8 100644 --- a/tools_glm.py +++ b/tools_glm.py @@ -83,10 +83,22 @@ def find_in_normative( query: str, top_k: int = 3, ) -> dict: - """Семантический поиск по нормативной базе.""" - from claude_bridge_glm import _search_normative + """Семантический поиск по нормативной базе. + + Импорт claude_bridge_glm/sentence_transformers вынесен в try-блок: + в minimal-окружениях (например, Claude-sandbox Docker без RAG-стека) + отсутствие зависимостей не должно ронять весь 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}"} - text = _search_normative(query, top_k=top_k) return { "query": query, "result": text or "(нет совпадений)",