From 9f6f38b6babe55345a0650d60bb52d49fe06c9e4 Mon Sep 17 00:00:00 2001 From: anor Date: Sun, 22 Nov 2026 16:21:51 +1000 Subject: [PATCH] =?UTF-8?q?feat(=D0=B0=D0=B3=D0=B5=D0=BD=D1=82):=20=D0=B8?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BC=D0=B5=D0=BD=D1=82=20region?= =?UTF-8?q?al=5Frate=20=E2=80=94=20=D1=80=D0=B5=D0=B3=D0=B8=D0=BE=D0=BD?= =?UTF-8?q?=D0=B0=D0=BB=D1=8C=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D1=81=D1=86?= =?UTF-8?q?=D0=B5=D0=BD=D0=BA=D0=B0=20=D1=81=20=D0=BF=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=D0=BD=D1=81=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Отдельный MCP-инструмент читает regional_ref.sqlite только на чтение; отвечает «региональная база», различает найдено / кода нет / вид не загружен / регион не загружен / база недоступна; федеральную не подставляет. База и модуль монтируются в контейнер по образцу fgis_ref. Четыре проверки. Co-Authored-By: Claude Code --- claude_bridge.py | 13 +++++ regional_ref.py | 88 +++++++++++++++++++++++++++++++++ smeta_mcp.py | 31 ++++++++++++ tests/test_regional_rate_mcp.py | 46 +++++++++++++++++ 4 files changed, 178 insertions(+) create mode 100644 regional_ref.py create mode 100644 tests/test_regional_rate_mcp.py diff --git a/claude_bridge.py b/claude_bridge.py index 2785847..25b0caa 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -863,6 +863,7 @@ async def _run_profile( "mcp__smeta__find_recalc_index," "mcp__smeta__find_direct_costs_index," "mcp__smeta__find_resource_price," + "mcp__smeta__regional_rate," "mcp__smeta__find_salary," "mcp__smeta__calc_rim_rate," "mcp__smeta__find_ksr," @@ -997,6 +998,18 @@ async def _run_profile( "-v", f"{Path(_tsn_db_file).resolve()}:/app/data/tsn_ref.sqlite:ro", "-e", "TSN_REF_PATH=/app/data/tsn_ref.sqlite", ]) + # Региональная база (ТЕР/ТССЦ): код монтируем всегда, файл — если существует. + cmd.extend(["-v", f"{(APP_DIR / 'regional_ref.py').resolve()}:/app/regional_ref.py:ro"]) + _regional_db = Path("/data_fast/smeta-web-data/_external/derived/regional_ref/regional_ref.sqlite") + if _regional_db.is_file(): + cmd.extend([ + "-v", f"{_regional_db}:/app/data/regional_ref.sqlite:ro", + "-e", "REGIONAL_REF_PATH=/app/data/regional_ref.sqlite", + ]) + _regional_registry = Path("/data_fast/smeta-web-data/_external/tools/reference_sources.json") + if _regional_registry.is_file(): + cmd.extend(["-v", f"{_regional_registry}:/app/reference_sources.json:ro", + "-e", "REGIONAL_REGISTRY=/app/reference_sources.json"]) if os.environ.get("TSN_ENABLED"): cmd.extend(["-e", f"TSN_ENABLED={os.environ['TSN_ENABLED']}"]) # Ограничение правовой проверки — отдельный файл допуска, без него флага мало diff --git a/regional_ref.py b/regional_ref.py new file mode 100644 index 0000000..9872569 --- /dev/null +++ b/regional_ref.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Запрос расценки/цены из региональной базы с провенансом. + +Три состояния: регион не загружен, регион загружен и кода нет, запись найдена. +Ответ всегда помечен как региональная база; федеральная ФСНБ не подставляется. +""" +from __future__ import annotations +import argparse, json, os, sqlite3 +from pathlib import Path + +DEFAULT_REGISTRY = Path(os.environ.get("REGIONAL_REGISTRY", "/app/reference_sources.json")) + +def _subject_name(con, subject_id, registry=None): + try: + row = con.execute("select name from subjects where code=?", (subject_id,)).fetchone() + if row and row["name"]: + return row["name"] + except sqlite3.Error: + pass + try: + data = json.loads(Path(registry or DEFAULT_REGISTRY).read_text(encoding="utf-8")) + for s in data.get("subjects", []): + if int(s["code"]) == int(subject_id): + return s.get("name") + except Exception: + pass + return None + +DEFAULT_DB = Path(os.environ.get("REGIONAL_REF_PATH", "/app/data/regional_ref.sqlite")) + +def lookup(code: str, subject_id: int, kind: str | None = None, + db: Path | str | None = None, registry: Path | str | None = None) -> dict: + db = Path(db or os.environ.get("REGIONAL_REF_PATH", str(DEFAULT_DB))) + if not Path(db).is_file(): + return {"status": "db_unavailable", "base": "региональная", + "message": "региональная база недоступна", "subject_id": subject_id} + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True); con.row_factory = sqlite3.Row + try: + loaded = [r["kind"] for r in con.execute( + "select distinct kind from sources where subject_id=?", (subject_id,))] + if not loaded: + return {"status": "region_not_loaded", "base": "региональная", + "message": "регион не загружен в региональную базу", + "subject_id": subject_id, "subject": _subject_name(con, subject_id, registry)} + if kind and kind not in loaded: + return {"status": "kind_not_loaded", "base": "региональная", + "message": f"регион загружен, но вид {kind} в региональной базе не загружен", + "subject_id": subject_id, "subject": _subject_name(con, subject_id, registry), + "loaded_kinds": loaded} + kinds = [kind] if kind else loaded + for k in kinds: + if k == "ТЕР": + row = con.execute( + "select w.code,w.name,w.unit,w.price,s.edition,s.act," + "s.file_sha,s.manifest_sha " + "from works w join sources s on s.id=w.source_id " + "where w.subject_id=? and w.kind=? and w.code=?", + (subject_id, k, code)).fetchone() + elif k == "ТССЦ": + row = con.execute( + "select p.code,p.name,p.unit,p.price_otp,p.price_smet," + "s.edition,s.act,s.file_sha,s.manifest_sha from prices p join sources s " + "on s.id=p.source_id where p.subject_id=? and p.kind=? and p.code=?", + (subject_id, k, code)).fetchone() + else: + row = None + if row: + return {"status": "ok", "base": "региональная", + "subject_id": subject_id, "subject": _subject_name(con, subject_id, registry), + "kind": k, **dict(row)} + return {"status": "code_not_found", "base": "региональная", + "message": "регион загружен, кода в региональной базе нет", + "subject_id": subject_id, "subject": _subject_name(con, subject_id, registry), + "code": code} + finally: + con.close() + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("code"); ap.add_argument("--subject", type=int, required=True) + ap.add_argument("--kind", choices=("ТЕР", "ТССЦ")) + ap.add_argument("--db", default=str(DEFAULT_DB)) + a = ap.parse_args() + print(json.dumps(lookup(a.code, a.subject, a.kind, a.db), ensure_ascii=False)) + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/smeta_mcp.py b/smeta_mcp.py index 6f238c9..f31020a 100644 --- a/smeta_mcp.py +++ b/smeta_mcp.py @@ -935,7 +935,38 @@ def tool_ocr_scans(*, предел_страниц: int = 40) -> dict: return итог +def tool_regional_rate(*, code: str, subject_id: int, kind: str | None = None) -> dict: + """Региональная расценка/цена с провенансом. Федеральную базу не подставляет.""" + try: + import regional_ref + return regional_ref.lookup(code, int(subject_id), kind) + except Exception as e: # noqa: BLE001 — отсутствие базы/модуля не должно ронять прогон + return {"status": "db_unavailable", "base": "региональная", + "message": "региональная база недоступна", "error": f"{type(e).__name__}: {e}"} + + TOOLS: dict[str, dict] = { + "regional_rate": { + "fn": tool_regional_rate, + "description": ( + "Расценка или цена из РЕГИОНАЛЬНОЙ базы (ТЕР/ТССЦ) с провенансом: регион, " + "редакция, акт, отпечатки. Ответ всегда помечен «региональная база». " + "Федеральную ФСНБ не подставляет: если кода нет или регион не загружен — " + "честный статус (code_not_found / kind_not_loaded / region_not_loaded)." + ), + "inputSchema": { + "type": "object", + "properties": { + "code": {"type": "string", "description": "Код расценки или ресурса"}, + "subject_id": {"type": "integer", "description": "Код субъекта ФГИС"}, + "kind": {"type": "string", "enum": ["ТЕР", "ТССЦ"], + "description": "Вид справочника; без него — поиск по загруженным"}, + }, + "required": ["code", "subject_id"], + }, + }, + + "find_in_tsn": { "fn": tool_find_in_tsn, "description": ( diff --git a/tests/test_regional_rate_mcp.py b/tests/test_regional_rate_mcp.py new file mode 100644 index 0000000..5f81eff --- /dev/null +++ b/tests/test_regional_rate_mcp.py @@ -0,0 +1,46 @@ +"""MCP-инструмент regional_rate: три состояния, отсутствие базы, регистрация.""" +import sqlite3, sys +from pathlib import Path +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) +import smeta_mcp # noqa: E402 +import regional_ref # noqa: E402 + +def _db(tmp_path: Path) -> Path: + db = tmp_path / "regional_ref.sqlite" + con = sqlite3.connect(db) + con.executescript(""" + create table subjects(code integer primary key, name text); + create table sources(id integer primary key, subject_id int, kind text, edition text, + act text, file_sha text, manifest_sha text, imported_at text); + create table works(id integer primary key, subject_id int, kind text, code text, + name text, unit text, price real, source_id int); + create table prices(id integer primary key, subject_id int, kind text, code text, + name text, unit text, price_otp real, price_smet real, source_id int); + """) + con.execute("insert into subjects values(337,'Оренбургская область')") + con.execute("insert into sources values(1,337,'ТЕР','ред. 2014','приказ','sha1','sha2','now')") + con.execute("insert into works values(1,337,'ТЕР','01-01-001-01','15 м³','м3',3270.04,1)") + con.commit(); con.close(); return db + +def test_tool_registered(): + assert "regional_rate" in smeta_mcp.TOOLS + assert smeta_mcp.TOOLS["regional_rate"]["fn"] is smeta_mcp.tool_regional_rate + +def test_found_regional_label_and_provenance(tmp_path, monkeypatch): + db = _db(tmp_path); monkeypatch.setenv("REGIONAL_REF_PATH", str(db)) + r = smeta_mcp.tool_regional_rate(code="01-01-001-01", subject_id=337, kind="ТЕР") + assert r["status"] == "ok" and r["base"] == "региональная" + assert r["subject"] == "Оренбургская область" and r["price"] == 3270.04 + assert r["file_sha"] == "sha1" and r["manifest_sha"] == "sha2" + +def test_code_missing_and_kind_missing(tmp_path, monkeypatch): + db = _db(tmp_path); monkeypatch.setenv("REGIONAL_REF_PATH", str(db)) + assert smeta_mcp.tool_regional_rate(code="99-99-999-99", subject_id=337)["status"] == "code_not_found" + r = smeta_mcp.tool_regional_rate(code="101-0001", subject_id=337, kind="ТССЦ") + assert r["status"] == "kind_not_loaded" + +def test_db_unavailable_not_silent(tmp_path, monkeypatch): + monkeypatch.setenv("REGIONAL_REF_PATH", str(tmp_path / "missing.sqlite")) + r = smeta_mcp.tool_regional_rate(code="01-01-001-01", subject_id=337) + assert r["status"] == "db_unavailable" and "недоступна" in r["message"]