diff --git a/packages/accounting_automation/src/mcp-ui.ts b/packages/accounting_automation/src/mcp-ui.ts new file mode 100644 index 0000000..c84134a --- /dev/null +++ b/packages/accounting_automation/src/mcp-ui.ts @@ -0,0 +1,161 @@ +/** Представление очереди разбора: компактные строки, markdown-таблица для текста и HTML-приложение (MCP Apps) с кнопками. */ + +type Json = Record; + +export const REVIEW_UI_URI = "ui://accounting_automation/review-table"; +export const REVIEW_UI_MIME = "text/html;profile=mcp-app"; + +export interface ReviewRow { + id: string; + kind: string; + role: string; + date: string | null; + amount: string | null; + who: string | null; + what: string | null; + confidence: number | null; + problem: string | null; + snoozed: boolean; + file_url: string | null; +} + +const s = (v: unknown): string | null => (v === null || v === undefined || v === "" ? null : String(v)); +const day = (v: unknown): string | null => { + const x = s(v); + return x ? x.slice(0, 10) : null; +}; + +/** Одна строка таблицы из задачи списка (task + review). */ +export function toRow(t: Json): ReviewRow { + const review = (t.review ?? {}) as Json; + const kind = String(t.kind); + let date: string | null = null; + let amount: string | null = null; + let who: string | null = null; + let what: string | null = null; + let confidence: number | null = typeof review.confidence === "number" ? review.confidence : null; + if (kind === "categorization") { + const sg = (review.suggestion ?? {}) as Json; + date = day(sg.date); + amount = s(sg.amount); + who = s(sg.vendor); + what = [s(sg.account), sg.project_customer_id ? `проект ${String(sg.project_customer_id)}` : null].filter(Boolean).join(", ") || s(review.feed_txn_id); + } else if (kind === "invoice") { + date = day(review.invoice_date); + amount = s(review.amount); + who = s(review.vendor_name); + what = + [s(review.invoice_number) ? `№ ${String(review.invoice_number)}` : null, review.project_customer_id ? `проект ${String(review.project_customer_id)}` : null].filter(Boolean).join(", ") || null; + confidence = null; + } else if (kind === "certificate") { + date = day(review.expires_on); + who = s(review.vendor_name); + what = "сертификат страхования"; + confidence = null; + } + return { + id: String(t.id), + kind, + role: String(t.assignee_role), + date, + amount, + who, + what, + confidence, + problem: s(t.problem_highlight), + snoozed: t.snoozed_until != null, + file_url: s(t.file_url), + }; +} + +const cell = (v: string | number | null, max = 60): string => { + const x = v === null ? "" : String(v).replace(/\s+/g, " ").replace(/\|/g, "/"); + return x.length > max ? `${x.slice(0, max - 1)}…` : x; +}; + +/** Текстовая таблица для хостов без поддержки интерактивных приложений и для самой модели. */ +export function rowsToMarkdown(rows: ReviewRow[], total: number): string { + if (rows.length === 0) return "Очередь разбора пуста."; + const head = "| id | вид | дата | сумма | кто | что | % | проблема | роль |\n|---|---|---|---|---|---|---|---|---|"; + const body = rows.map( + (r) => `| ${r.id.slice(0, 8)} | ${r.kind} | ${cell(r.date)} | ${cell(r.amount)} | ${cell(r.who, 30)} | ${cell(r.what, 40)} | ${cell(r.confidence)} | ${cell(r.problem, 80)} | ${r.role} |`, + ); + return `${head}\n${body.join("\n")}\n\nПоказано ${rows.length} из ${total}. Действия по нескольким задачам - одним вызовом acc_review_batch (id - первые 8 символов из таблицы).`; +} + +/** HTML-приложение (MCP Apps): таблица очереди с кнопками Done / Delegate / Snooze. Данные приходят в ui/notifications/tool-result. */ +export const REVIEW_UI_HTML = String.raw` + +Очередь разбора бухгалтерии +
+
+
Загрузка…
+`; diff --git a/packages/accounting_automation/src/mcp.int.test.ts b/packages/accounting_automation/src/mcp.int.test.ts index c64bad5..74a9aff 100644 --- a/packages/accounting_automation/src/mcp.int.test.ts +++ b/packages/accounting_automation/src/mcp.int.test.ts @@ -217,6 +217,28 @@ d("MCP бухгалтерии (временная БД)", () => { }); }); + describe("пакетные действия", () => { + it("валидация: пусто, больше 50, неоднозначный/короткий префикс; роли не обходятся", async () => { + expect(await errOf(call(accountant, "acc_review_batch", { actions: [] }))).toContain("1..50"); + expect(await errOf(call(accountant, "acc_review_batch", { actions: Array.from({ length: 51 }, () => ({ id: "x", action: "done" })) }))).toContain("1..50"); + expect(await errOf(call(stranger, "acc_review_batch", { actions: [{ id: "abcdef12", action: "done" }] }))).toContain("Доступ запрещён"); + const t = await addCat("p1"); + const res = (await call(accountant, "acc_review_batch", { actions: [{ id: "abc", action: "done" }, { id: t, action: "handoff", role: "cfo" }, { id: t, action: "done" }] })) as { results: Array> }; + expect(res.results[0].ok).toBe(false); + expect(res.results[1].ok).toBe(true); + // после передачи cfo задача уже не закрывается accountant-ом + expect(res.results[2].ok).toBe(false); + expect(res.results[2].error).toContain("cfo"); + }); + + it("update в пакете меняет поля, как отдельный вызов", async () => { + const t = await addCat("u1"); + const res = (await call(accountant, "acc_review_batch", { actions: [{ id: t, action: "update", fields: { confidence: 55 } }] })) as { ok_count: number }; + expect(res.ok_count).toBe(1); + expect((await db.pool.query("select confidence from acc_categorization_review where feed_txn_id = 'u1'")).rows[0].confidence).toBe(55); + }); + }); + describe("HTTP", () => { const post = async (headers: Record, payload: unknown, deps: Partial = {}) => { const app = Fastify(); @@ -246,8 +268,13 @@ d("MCP бухгалтерии (временная БД)", () => { expect(((await post(bearer(TOKEN_A), rpc("ping"))).json()).result).toEqual({}); const l = (await post(bearer(TOKEN_A), rpc("tools/list"))).json(); expect(l.result.tools.map((t: { name: string }) => t.name)).toEqual([ - "acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_snooze", + "acc_review_list", "acc_review_get", "acc_review_update", "acc_review_done", "acc_review_handoff", "acc_review_return", "acc_review_batch", "acc_review_snooze", ]); + const tl = l.result.tools as Array<{ name: string; annotations?: { readOnlyHint?: boolean }; _meta?: { ui?: { resourceUri?: string } } }>; + expect(tl.find((t) => t.name === "acc_review_list")?.annotations?.readOnlyHint).toBe(true); + expect(tl.find((t) => t.name === "acc_review_done")?.annotations?.readOnlyHint).toBe(false); + expect(tl.find((t) => t.name === "acc_review_list")?._meta?.ui?.resourceUri).toBe("ui://accounting_automation/review-table"); + expect(i.json().result.capabilities.resources).toBeDefined(); expect((await post(bearer(TOKEN_A), rpc("nope"))).json().error.code).toBe(-32601); }); @@ -255,7 +282,9 @@ d("MCP бухгалтерии (временная БД)", () => { await addInvoice(); const ok = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json(); expect(ok.result.isError).toBeUndefined(); - expect(JSON.parse(ok.result.content[0].text).total).toBe(1); + expect(ok.result.structuredContent.total).toBe(1); + expect(ok.result.structuredContent.rows[0]).toMatchObject({ kind: "invoice", who: "Vendor A", role: "accountant" }); + expect(ok.result.content[0].text).toContain("| id | вид |"); const denied = (await post(bearer("token-stranger-0123456789"), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json(); expect(denied.result.isError).toBe(true); expect(denied.result.content[0].text).toContain("Доступ запрещён"); @@ -263,13 +292,53 @@ d("MCP бухгалтерии (временная БД)", () => { expect(bad.result.isError).toBe(true); }); + it("resources: интерактивная таблица очереди отдаётся как ui:// ресурс", async () => { + const list = (await post(bearer(TOKEN_A), rpc("resources/list"))).json(); + expect(list.result.resources[0]).toMatchObject({ uri: "ui://accounting_automation/review-table", mimeType: "text/html;profile=mcp-app" }); + const read = (await post(bearer(TOKEN_A), rpc("resources/read", { uri: "ui://accounting_automation/review-table" }))).json(); + expect(read.result.contents[0].mimeType).toBe("text/html;profile=mcp-app"); + expect(read.result.contents[0].text).toContain("acc_review_batch"); + expect((await post(bearer(TOKEN_A), rpc("resources/read", { uri: "ui://nope" }))).json().error.code).toBe(-32002); + expect((await post({}, rpc("resources/list"))).statusCode).toBe(401); + }); + + it("acc_review_batch через HTTP: пакет с частичной ошибкой, id по префиксу", async () => { + const a = await addCat("b1"); + const b = await addCat("b2"); + const c = await addCat("b3"); + const r = ( + await post( + bearer(TOKEN_A), + rpc("tools/call", { + name: "acc_review_batch", + arguments: { + actions: [ + { id: a.slice(0, 8), action: "done" }, + { id: b, action: "snooze", until: "2026-12-01" }, + { id: c, action: "handoff", role: "cfo", comment: "сумма" }, + { id: "00000000-0000-4000-8000-000000000000", action: "done" }, + { id: b, action: "bogus" }, + ], + }, + }), + ) + ).json(); + expect(r.result.isError).toBeUndefined(); + expect(r.result.structuredContent.ok_count).toBe(3); + expect(r.result.structuredContent.error_count).toBe(2); + expect(r.result.content[0].text).toContain("ОШИБКА"); + expect((await db.pool.query("select done from acc_categorization_review where feed_txn_id = 'b1'")).rows[0].done).toBe(true); + expect((await db.pool.query("select snoozed_until from acc_manual_review where id = $1", [b])).rows[0].snoozed_until).not.toBeNull(); + expect((await db.pool.query("select assignee_role from acc_manual_review where id = $1", [c])).rows[0].assignee_role).toBe("cfo"); + }); + it("JWT Keycloak: person по основной и дополнительной почте; чужой email - 403; плохие токены - 401", async () => { await addInvoice(); const call = { name: "acc_review_list", arguments: {} }; for (const email of ["kc@khbuild.pro", "KC.Alias@gmail.com", "other@gmail.com"]) { const r = await post(bearer(await jwt({ email, email_verified: true })), rpc("tools/call", call)); expect(r.statusCode, email).toBe(200); - expect(JSON.parse(r.json().result.content[0].text).total).toBe(1); + expect(r.json().result.structuredContent.total).toBe(1); } expect((await post(bearer(await jwt({ email: "nobody@x.com" })), rpc("tools/call", call))).statusCode).toBe(403); expect((await post(bearer(await jwt({ email: "off@khbuild.pro" })), rpc("tools/call", call))).statusCode).toBe(403); diff --git a/packages/accounting_automation/src/mcp.ts b/packages/accounting_automation/src/mcp.ts index 20c5707..d5e6a0f 100644 --- a/packages/accounting_automation/src/mcp.ts +++ b/packages/accounting_automation/src/mcp.ts @@ -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 { + 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 { + 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 { 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)}`;