MCP: пакетный acc_review_batch, компактная таблица очереди, интерактивное приложение (ui://) с кнопками Done/Delegate/Snooze, подсказки readOnly/destructive
All checks were successful
ci / test (push) Successful in 38s
ci / deploy (push) Successful in 2m37s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 09:21:34 +03:00
parent 7638242a51
commit aae7472010
3 changed files with 330 additions and 6 deletions

View File

@@ -0,0 +1,161 @@
/** Представление очереди разбора: компактные строки, markdown-таблица для текста и HTML-приложение (MCP Apps) с кнопками. */
type Json = Record<string, unknown>;
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`<!doctype html>
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Очередь разбора бухгалтерии</title>
<style>
:root{--bg:#fff;--fg:#1f2328;--mut:#6b7280;--line:#e5e7eb;--acc:#2563eb;--bad:#b42318;--hl:#fff7ed}
@media (prefers-color-scheme:dark){:root{--bg:#1c1c1e;--fg:#e8e8ea;--mut:#9ca3af;--line:#3a3a3e;--acc:#6ea0ff;--bad:#ff8a80;--hl:#3a2a1a}}
html,body{margin:0;background:var(--bg);color:var(--fg);font:13px/1.4 system-ui,sans-serif}
.wrap{padding:8px 10px}
.bar{display:flex;gap:8px;align-items:center;margin:0 0 8px;flex-wrap:wrap}
.bar .st{color:var(--mut);margin-left:auto}
button{font:inherit;border:1px solid var(--line);background:transparent;color:var(--fg);border-radius:6px;padding:3px 9px;cursor:pointer}
button:hover{border-color:var(--acc);color:var(--acc)} button:disabled{opacity:.45;cursor:default}
button.pri{background:var(--acc);border-color:var(--acc);color:#fff}
table{width:100%;border-collapse:collapse}
th,td{text-align:left;padding:5px 6px;border-bottom:1px solid var(--line);vertical-align:top}
th{color:var(--mut);font-weight:500;white-space:nowrap}
td.n,th.n{text-align:right;white-space:nowrap} tr.p td{background:var(--hl)}
.prob{color:var(--bad)} .acts{white-space:nowrap;display:flex;gap:4px}
.empty{color:var(--mut);padding:14px 4px}
</style></head><body><div class="wrap">
<div class="bar"><button id="done" class="pri" disabled>Done выбранные</button><button id="deleg" disabled>Delegate выбранные</button><button id="snz" disabled>Snooze 1д</button><span class="st" id="st"></span></div>
<div id="root"><div class="empty">Загрузка…</div></div></div>
<script>
(function(){
var rows=[],sel={},nextId=1,pending={};
function send(m){parent.postMessage(Object.assign({jsonrpc:"2.0"},m),"*");}
function req(method,params){return new Promise(function(res,rej){var id=nextId++;pending[id]={res:res,rej:rej};send({id:id,method:method,params:params});});}
function esc(x){return String(x==null?"":x).replace(/[&<>"]/g,function(c){return {"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c];});}
function status(t){document.getElementById("st").textContent=t||"";}
function other(r){return r==="accountant"?"cfo":"accountant";}
function selIds(){return Object.keys(sel).filter(function(k){return sel[k];});}
function render(){
var root=document.getElementById("root");
if(!rows.length){root.innerHTML='<div class="empty">Очередь разбора пуста.</div>';updBtns();size();return;}
var h='<table><thead><tr><th></th><th>вид</th><th>дата</th><th class="n">сумма</th><th>кто</th><th>что</th><th class="n">%</th><th>проблема</th><th>роль</th><th></th></tr></thead><tbody>';
rows.forEach(function(r){
h+='<tr'+(r.problem?' class="p"':'')+'><td><input type="checkbox" data-sel="'+esc(r.id)+'"'+(sel[r.id]?' checked':'')+'></td>'
+'<td>'+esc(r.kind)+'</td><td>'+esc(r.date)+'</td><td class="n">'+esc(r.amount)+'</td><td>'+esc(r.who)+'</td>'
+'<td>'+(r.file_url?'<a href="'+esc(r.file_url)+'" target="_blank" rel="noopener">':'')+esc(r.what)+(r.file_url?'</a>':'')+'</td>'
+'<td class="n">'+esc(r.confidence)+'</td><td class="prob">'+esc(r.problem)+'</td><td>'+esc(r.role)+'</td>'
+'<td><div class="acts"><button data-a="done" data-id="'+esc(r.id)+'">Done</button><button data-a="handoff" data-id="'+esc(r.id)+'">→ '+esc(other(r.role))+'</button><button data-a="snooze" data-id="'+esc(r.id)+'">1д</button></div></td></tr>';
});
root.innerHTML=h+'</tbody></table>';updBtns();size();
}
function updBtns(){var n=selIds().length;["done","deleg","snz"].forEach(function(i){document.getElementById(i).disabled=!n;});}
function size(){send({method:"ui/notifications/size-changed",params:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}});}
function tomorrow(){return new Date(Date.now()+24*3600*1000).toISOString();}
function run(ids,action){
var byId={};rows.forEach(function(r){byId[r.id]=r;});
var actions=ids.map(function(id){var a={id:id,action:action};if(action==="handoff"){a.role=other(byId[id].role);a.comment="из таблицы";}if(action==="snooze")a.until=tomorrow();return a;});
status("Выполняю…");
req("tools/call",{name:"acc_review_batch",arguments:{actions:actions}}).then(function(r){
var sc=(r&&r.structuredContent)||{};var okIds={};(sc.results||[]).forEach(function(x){if(x.ok)okIds[x.id]=1;});
var bad=(sc.results||[]).filter(function(x){return !x.ok;});
rows=rows.filter(function(x){return !okIds[x.id];});ids.forEach(function(i){delete sel[i];});
render();status(Object.keys(okIds).length+" выполнено"+(bad.length?", ошибок: "+bad.length+" ("+bad[0].error+")":""));
}).catch(function(e){status("Ошибка: "+((e&&e.message)||e));});
}
document.addEventListener("click",function(e){
var t=e.target;if(!t||!t.dataset)return;
if(t.dataset.a){run([t.dataset.id],t.dataset.a);return;}
if(t.id==="done")run(selIds(),"done");
if(t.id==="deleg")run(selIds(),"handoff");
if(t.id==="snz")run(selIds(),"snooze");
});
document.addEventListener("change",function(e){var t=e.target;if(t&&t.dataset&&t.dataset.sel){sel[t.dataset.sel]=t.checked;updBtns();}});
window.addEventListener("message",function(e){
var m=e.data;if(!m||m.jsonrpc!=="2.0")return;
if(m.id!=null&&pending[m.id]){var p=pending[m.id];delete pending[m.id];if(m.error)p.rej(new Error(m.error.message||"error"));else p.res(m.result);return;}
if(m.method==="ui/notifications/tool-result"){var sc=(m.params&&m.params.structuredContent)||{};rows=sc.rows||[];sel={};render();status("Всего в очереди: "+(sc.total!=null?sc.total:rows.length));}
if(m.id!=null&&m.method==="ui/resource-teardown"){send({id:m.id,result:{}});}
});
req("ui/initialize",{protocolVersion:"2026-01-26",capabilities:{},clientInfo:{name:"accounting_automation review table",version:"0.1.0"},appCapabilities:{}}).then(function(){send({method:"ui/notifications/initialized"});}).catch(function(){});
})();
</script></body></html>`;

View File

@@ -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<Record<string, any>> };
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<string, string>, payload: unknown, deps: Partial<McpDeps> = {}) => {
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);

View File

@@ -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)}`;