Document MCP tool contracts and structured results
This commit is contained in:
+76
-4
@@ -16,10 +16,82 @@ from starlette.responses import Response
|
||||
|
||||
import db
|
||||
from mcp_context import ToolContext
|
||||
from stove_contract import StoveRequest
|
||||
|
||||
|
||||
_PARAM_DESCRIPTIONS = {
|
||||
"budget_rub": "Максимальный расход на проверку в рублях; задаётся пользователем после оценки стоимости.",
|
||||
"confirmed": "true после явного согласия пользователя с оценкой расхода.",
|
||||
"content_base64": "Байты файла в стандартной кодировке base64; файл не более 512 КБ.",
|
||||
"date": "Дата расчёта YYYY-MM-DD; null сбрасывает на текущую дату.",
|
||||
"filename": "Имя файла в собственной вкладке пользователя.",
|
||||
"items": "Список замечаний для оценки или запуска проверки.",
|
||||
"job_id": "Идентификатор задания, возвращённый chat_ask.",
|
||||
"limit": "Максимальное число последних сообщений; по умолчанию 100.",
|
||||
"message": "Текст вопроса для Инфосметы.",
|
||||
"review_id": "Идентификатор собственной проверки замечаний.",
|
||||
"stove": "Параметры печи по контракту StoveRequest; оценка ориентировочная.",
|
||||
"tab_id": "Идентификатор собственной вкладки; если не указан, используется вкладка MCP-клиента.",
|
||||
"ticket": "Одноразовый код из браузерного подтверждения prepare_clear_files.",
|
||||
"title": "Название диалога или проверки.",
|
||||
"tz": "Смещение локального времени от UTC в минутах; по умолчанию 0.",
|
||||
}
|
||||
|
||||
|
||||
_REVIEW_ITEM = {"type": "object", "description": "Одно замечание экспертизы и необязательная привязка к строке файла.",
|
||||
"properties": {
|
||||
"ord": {"type": "integer", "minimum": 1, "description": "Порядковый номер; по умолчанию позиция в списке."},
|
||||
"text": {"type": "string", "minLength": 1, "maxLength": 10000, "description": "Текст замечания."},
|
||||
"target_path": {"type": ["string", "null"], "description": "Файл результата, к которому относится замечание."},
|
||||
"target_sheet": {"type": ["string", "null"], "description": "Лист файла результата."},
|
||||
"target_row": {"type": ["integer", "null"], "minimum": 1, "description": "Строка файла результата."},
|
||||
"target_path_before": {"type": ["string", "null"], "description": "Исходный файл до исправления."},
|
||||
"target_sheet_before": {"type": ["string", "null"], "description": "Исходный лист до исправления."},
|
||||
"target_row_before": {"type": ["integer", "null"], "minimum": 1, "description": "Исходная строка до исправления."},
|
||||
}, "required": ["text"], "additionalProperties": False}
|
||||
|
||||
|
||||
def _stove_schema() -> dict:
|
||||
# The REST endpoint validates with this model. Convert pydantic-core's two
|
||||
# numeric keywords to standard JSON Schema so MCP clients can validate too.
|
||||
schema = StoveRequest.model_json_schema()
|
||||
def standardize(value):
|
||||
if isinstance(value, dict):
|
||||
return {("exclusiveMinimum" if key == "gt" else "maximum" if key == "le" else key): standardize(item)
|
||||
for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [standardize(item) for item in value]
|
||||
return value
|
||||
schema = standardize(schema)
|
||||
stove_fields = schema["$defs"]["Stove"]["properties"]
|
||||
for field, description in {
|
||||
"kind": "Тип печи: отопительная, отопительно-варочная, кухонная, хлебная, банная или камин.",
|
||||
"bricks": "Число керамических и шамотных кирпичей.",
|
||||
"region": "Регион расчёта цен.",
|
||||
"zone": "Ценовая зона региона, если известна.",
|
||||
"mass_kg": "Масса печи в килограммах, если известна.",
|
||||
"bucket_volume_l": "Объём ведра в литрах для расхода материалов.",
|
||||
"materials": "Дополнительные материалы с количеством и единицей измерения.",
|
||||
"context": "Свободное пояснение к печи для подбора аналогов.",
|
||||
}.items():
|
||||
stove_fields[field]["description"] = description
|
||||
for field, description in {"ceramic": "Количество керамических кирпичей.",
|
||||
"fireclay": "Количество шамотных кирпичей."}.items():
|
||||
schema["$defs"]["Bricks"]["properties"][field]["description"] = description
|
||||
for field, description in {"name": "Наименование материала.",
|
||||
"qty": "Положительное количество.",
|
||||
"unit": "Единица измерения количества."}.items():
|
||||
schema["$defs"]["MaterialLine"]["properties"][field]["description"] = description
|
||||
schema["properties"]["tab_id"] = {"type": "string", "maxLength": 128,
|
||||
"description": _PARAM_DESCRIPTIONS["tab_id"]}
|
||||
schema["properties"]["stove"]["description"] = _PARAM_DESCRIPTIONS["stove"]
|
||||
return schema
|
||||
|
||||
|
||||
def _schema(properties: dict, required: tuple[str, ...] = ()) -> dict:
|
||||
return {"type": "object", "properties": properties, "required": list(required),
|
||||
described = {key: {**value, "description": value.get("description", _PARAM_DESCRIPTIONS[key])}
|
||||
for key, value in properties.items()}
|
||||
return {"type": "object", "properties": described, "required": list(required),
|
||||
"additionalProperties": False}
|
||||
|
||||
|
||||
@@ -54,10 +126,10 @@ CATALOG: dict[str, dict] = {
|
||||
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||
"ticket": {"type": "string", "maxLength": 100}}, ("ticket",))},
|
||||
"review_estimate_cost": {"scope": {"reviews:run"}, "description": "Оценка бюджета проверки замечаний.",
|
||||
"schema": _schema({"items": {"type": "array", "maxItems": 1000}}, ("items",))},
|
||||
"schema": _schema({"items": {"type": "array", "maxItems": 1000, "items": _REVIEW_ITEM}}, ("items",))},
|
||||
"review_create": {"scope": {"reviews:run"}, "description": "Создать проверку замечаний с явным потолком расходов.",
|
||||
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||
"items": {"type": "array", "minItems": 1, "maxItems": 1000},
|
||||
"items": {"type": "array", "minItems": 1, "maxItems": 1000, "items": _REVIEW_ITEM},
|
||||
"title": {"type": "string", "maxLength": 120},
|
||||
"budget_rub": {"type": "number", "minimum": 0},
|
||||
"confirmed": {"type": "boolean", "const": True}},
|
||||
@@ -80,7 +152,7 @@ CATALOG: dict[str, dict] = {
|
||||
"chat_job_cancel": {"scope": {"chat:run"}, "description": "Остановить своё задание.",
|
||||
"schema": _schema({"job_id": {"type": "integer", "minimum": 1}}, ("job_id",))},
|
||||
"stove_estimate": {"scope": {"stove:estimate"}, "description": "Ориентировочная оценка кладки печи с аналогами и пропусками, по тем же лимитам и бюджету, что REST API.",
|
||||
"schema": _schema({"stove": {"type": "object"}}, ("stove",))},
|
||||
"schema": _stove_schema()},
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user