MCP: пакетный acc_review_batch, компактная таблица очереди, интерактивное приложение (ui://) с кнопками Done/Delegate/Snooze, подсказки readOnly/destructive
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { withTx, type Pool } from "khb_common";
|
||||
import { createMcpAuth, McpAuthError, type JwtVerifier } from "./mcp-auth.js";
|
||||
import { REVIEW_UI_HTML, REVIEW_UI_MIME, REVIEW_UI_URI, rowsToMarkdown, toRow } from "./mcp-ui.js";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
|
||||
/**
|
||||
@@ -325,8 +326,50 @@ export class ReviewTools {
|
||||
});
|
||||
}
|
||||
|
||||
/** Полный uuid или префикс (от 8 символов) id задачи, как в таблице списка. */
|
||||
private async resolveId(v: unknown): Promise<string> {
|
||||
if (typeof v !== "string") throw new McpToolError("id: строка");
|
||||
if (UUID.test(v)) return v;
|
||||
if (!/^[0-9a-f]{8,}$/i.test(v)) throw new McpToolError("id: uuid или первые 8+ символов uuid из таблицы");
|
||||
const { rows } = await this.d.pool.query("select id from acc_manual_review where id::text like $1 limit 2", [`${v.toLowerCase()}%`]);
|
||||
if (rows.length === 0) throw new McpToolError("Задача не найдена (возможно, уже завершена).");
|
||||
if (rows.length > 1) throw new McpToolError("Префикс id неоднозначен: укажите больше символов.");
|
||||
return rows[0].id as string;
|
||||
}
|
||||
|
||||
/** acc_review_batch: несколько действий одним вызовом; ошибка одного действия не останавливает остальные. */
|
||||
async batch(personId: string, a: Json): Promise<Json> {
|
||||
this.rolesOf(personId);
|
||||
const actions = a.actions;
|
||||
if (!Array.isArray(actions) || actions.length === 0 || actions.length > 50) throw new McpToolError("actions: массив из 1..50 действий");
|
||||
const results: Json[] = [];
|
||||
for (const raw of actions) {
|
||||
const x = (raw ?? {}) as Json;
|
||||
const act = String(x.action);
|
||||
try {
|
||||
const id = await this.resolveId(x.id);
|
||||
const args: Json = { ...x, id };
|
||||
switch (act) {
|
||||
case "update": await this.update(personId, args); break;
|
||||
case "done": await this.done(personId, args); break;
|
||||
case "snooze": await this.snooze(personId, args); break;
|
||||
case "handoff": await this.handoff(personId, args); break;
|
||||
case "return": await this.return(personId, args); break;
|
||||
default: throw new McpToolError("action: update, done, snooze, handoff или return");
|
||||
}
|
||||
results.push({ id, action: act, ok: true });
|
||||
} catch (e) {
|
||||
if (!(e instanceof McpToolError)) throw e;
|
||||
results.push({ id: typeof x.id === "string" ? x.id : null, action: act, ok: false, error: e.message });
|
||||
}
|
||||
}
|
||||
const okCount = results.filter((r) => r.ok).length;
|
||||
return { results, ok_count: okCount, error_count: results.length - okCount };
|
||||
}
|
||||
|
||||
call(personId: string, name: string, a: Json): Promise<Json> {
|
||||
switch (name) {
|
||||
case "acc_review_batch": return this.batch(personId, a);
|
||||
case "acc_review_list": return this.list(personId, a);
|
||||
case "acc_review_get": return this.get(personId, a);
|
||||
case "acc_review_update": return this.update(personId, a);
|
||||
@@ -343,11 +386,13 @@ const str = { type: "string" };
|
||||
const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false });
|
||||
const idP = { type: "string", description: "id задачи (uuid из acc_review_list)" };
|
||||
|
||||
export const TOOLS: { name: string; description: string; inputSchema: Json }[] = [
|
||||
export const TOOLS: { name: string; description: string; inputSchema: Json; annotations?: Json; _meta?: Json }[] = [
|
||||
{
|
||||
name: "acc_review_list",
|
||||
annotations: { readOnlyHint: true, openWorldHint: false, title: "Очередь разбора бухгалтерии" },
|
||||
_meta: { ui: { resourceUri: REVIEW_UI_URI }, "ui/resourceUri": REVIEW_UI_URI },
|
||||
description:
|
||||
"Список задач ручного разбора бухгалтерии (очередь acc_manual_review) для ролей текущего пользователя. Сначала идут задачи с проблемой (problem_highlight). В каждой задаче - данные строки разбора: инвойс (поля инвойса и ссылка на PDF), категоризация банковской операции (feed_txn_id, run_id, предложение, уверенность), сертификат страхования. Отложенные задачи скрыты, если не указан include_snoozed.",
|
||||
"Список задач (до 20 по умолчанию, можно до 100) показывается компактной таблицей: id (8 символов), вид, дата, сумма, кто, что, %, проблема, роль. В клиентах с поддержкой интерактивных приложений таблица кнопочная (Done / Delegate / Snooze); в остальных - markdown. Не пересказывай таблицу построчно, покажи её как есть. Исходное описание: список задач ручного разбора бухгалтерии (очередь acc_manual_review) для ролей текущего пользователя. Сначала идут задачи с проблемой (problem_highlight). В каждой задаче - данные строки разбора: инвойс (поля инвойса и ссылка на PDF), категоризация банковской операции (feed_txn_id, run_id, предложение, уверенность), сертификат страхования. Отложенные задачи скрыты, если не указан include_snoozed.",
|
||||
inputSchema: obj({
|
||||
kind: { type: "string", description: "вид задачи: invoice, categorization, certificate", enum: ["invoice", "categorization", "certificate", "discrepancy", "receipt_search", "chargeback", "invoice_approval"] },
|
||||
role: { type: "string", enum: ROLES, description: "показать задачи только этой роли (по умолчанию - все ваши роли)" },
|
||||
@@ -357,32 +402,65 @@ export const TOOLS: { name: string; description: string; inputSchema: Json }[] =
|
||||
},
|
||||
{
|
||||
name: "acc_review_get",
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
description: "Одна задача ручного разбора: сама задача, строка разбора (review), как её записал автомат (original), список изменённых полей и ссылка на файл в Google Drive (для инвойса и сертификата).",
|
||||
inputSchema: obj({ id: idP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_update",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
description:
|
||||
"Исправить поля строки разбора по задаче. Инвойс: vendor_name, vendor_qbo_id, invoice_number, invoice_date (YYYY-MM-DD), amount, lines (JSON), project_customer_id, jt_job_id, contract_id, problem_highlight. Категоризация: suggestion (JSON), confidence (0..100), problem_highlight. Сертификат: expires_on (YYYY-MM-DD), vendor_qbo_id, problem_highlight. Значение null очищает поле. Другие поля менять нельзя.",
|
||||
inputSchema: obj({ id: idP, fields: { type: "object", description: "{имя поля: новое значение}" } }, ["id", "fields"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_done",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
description: "Отметить задачу выполненной (после подтверждения пользователем; для банковской операции - после проводки в QuickBooks). Дальше запись переносит в историю процесс «Завершение ручного разбора». Задачу роли cfo может закрыть только пользователь с ролью cfo.",
|
||||
inputSchema: obj({ id: idP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_handoff",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
description: "Передать задачу другой роли (accountant или cfo), например операцию от $5 000 или первую оплату новому вендору - роли cfo. Комментарий добавляется к проблеме задачи.",
|
||||
inputSchema: obj({ id: idP, role: { type: "string", enum: ROLES }, comment: { type: "string", description: "зачем передаётся" } }, ["id", "role"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_return",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
description: "Вернуть задачу в общую очередь (роль accountant) с причиной; причина записывается в problem_highlight, отложенность снимается.",
|
||||
inputSchema: obj({ id: idP, reason: { type: "string", description: "причина возврата" } }, ["id", "reason"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_batch",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
description:
|
||||
"Несколько действий над задачами одним вызовом (до 50): после списка выполняй пакетом, а не по одной задаче. Каждое действие: {id, action, ...}. action: update (fields), done, snooze (until), handoff (role, comment), return (reason). id - из таблицы (первые 8 символов или полный). Ошибка одного действия не останавливает остальные; результат по каждой задаче отдельно. Done ставь только после подтверждения пользователя.",
|
||||
inputSchema: obj(
|
||||
{
|
||||
actions: {
|
||||
type: "array",
|
||||
description: "действия над задачами",
|
||||
items: obj(
|
||||
{
|
||||
id: { type: "string", description: "id задачи (8+ символов или полный uuid)" },
|
||||
action: { type: "string", enum: ["update", "done", "snooze", "handoff", "return"] },
|
||||
fields: { type: "object", description: "для update: {поле: значение}" },
|
||||
until: { type: "string", description: "для snooze: ISO дата или время в будущем" },
|
||||
role: { type: "string", enum: ROLES, description: "для handoff: кому передать" },
|
||||
comment: { type: "string", description: "для handoff: зачем" },
|
||||
reason: { type: "string", description: "для return: причина" },
|
||||
},
|
||||
["id", "action"],
|
||||
),
|
||||
},
|
||||
},
|
||||
["actions"],
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "acc_review_snooze",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
description: "Отложить задачу («подождать»): она не показывается в списке до указанного момента.",
|
||||
inputSchema: obj({ id: idP, until: { ...str, description: "дата или время ISO, в будущем: 2026-11-20 или 2026-11-20T09:00:00Z" } }, ["id", "until"]),
|
||||
},
|
||||
@@ -399,10 +477,17 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
|
||||
switch (method) {
|
||||
case "initialize": {
|
||||
const asked = (msg.params as Json | undefined)?.protocolVersion;
|
||||
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "accounting_automation", version: "0.1.0" } } };
|
||||
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: { tools: {}, resources: {} }, serverInfo: { name: "accounting_automation", version: "0.1.0" } } };
|
||||
}
|
||||
case "ping":
|
||||
return { jsonrpc: "2.0", id, result: {} };
|
||||
case "resources/list":
|
||||
return { jsonrpc: "2.0", id, result: { resources: [{ uri: REVIEW_UI_URI, name: "Таблица очереди разбора", mimeType: REVIEW_UI_MIME }] } };
|
||||
case "resources/read": {
|
||||
const uri = (msg.params as Json | undefined)?.uri;
|
||||
if (uri !== REVIEW_UI_URI) return rpcError(id, -32002, `ресурс не найден: ${String(uri)}`);
|
||||
return { jsonrpc: "2.0", id, result: { contents: [{ uri: REVIEW_UI_URI, mimeType: REVIEW_UI_MIME, text: REVIEW_UI_HTML, _meta: { ui: { prefersBorder: true } } }] } };
|
||||
}
|
||||
case "tools/list":
|
||||
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
|
||||
case "tools/call": {
|
||||
@@ -410,6 +495,15 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
|
||||
if (!TOOLS.some((t) => t.name === p.name)) return rpcError(id, -32602, `неизвестный инструмент ${p.name}`);
|
||||
try {
|
||||
const out = await tools.call(personId, p.name as string, p.arguments ?? {});
|
||||
if (p.name === "acc_review_list") {
|
||||
const rows = ((out.tasks as Json[] | undefined) ?? []).map(toRow);
|
||||
const total = Number(out.total ?? rows.length);
|
||||
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: rowsToMarkdown(rows, total) }], structuredContent: { total, shown: rows.length, rows } } };
|
||||
}
|
||||
if (p.name === "acc_review_batch") {
|
||||
const lines = ((out.results as Json[]) ?? []).map((r) => `${r.ok ? "ok" : "ОШИБКА"} ${String(r.id).slice(0, 8)} ${String(r.action)}${r.ok ? "" : `: ${String(r.error)}`}`);
|
||||
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `${lines.join("\n")}\nвыполнено ${String(out.ok_count)}, ошибок ${String(out.error_count)}` }], structuredContent: out } };
|
||||
}
|
||||
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(out) }] } };
|
||||
} catch (e) {
|
||||
const text = e instanceof McpToolError ? e.message : `Внутренняя ошибка: ${e instanceof Error ? e.message : String(e)}`;
|
||||
|
||||
Reference in New Issue
Block a user