feat(агент): инструмент regional_rate — региональная расценка с провенансом
Отдельный MCP-инструмент читает regional_ref.sqlite только на чтение; отвечает «региональная база», различает найдено / кода нет / вид не загружен / регион не загружен / база недоступна; федеральную не подставляет. База и модуль монтируются в контейнер по образцу fgis_ref. Четыре проверки. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -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']}"])
|
||||
# Ограничение правовой проверки — отдельный файл допуска, без него флага мало
|
||||
|
||||
@@ -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())
|
||||
@@ -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": (
|
||||
|
||||
@@ -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"]
|
||||
Reference in New Issue
Block a user