diff --git a/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md b/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md index 46afc4d..54972b5 100644 --- a/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md +++ b/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md @@ -15,6 +15,7 @@ - вызови acc_review_list (по умолчанию до 20 задач); не вызывай acc_review_get по каждой задаче, только когда нужны подробности по одной; - действия над несколькими задачами выполняй одним вызовом acc_review_batch, а не по одной задаче; - acc_review_done ставь только после явного подтверждения пользователя и, для банковской операции, после проводки в QuickBooks; -- id задач в таблице короткие (8 символов), в acc_review_batch можно передавать их как есть. +- id задач в таблице короткие (8 символов); во всех инструментах (done, handoff, snooze, batch и др.) передавай их как есть, полный uuid не нужен. Не ищи id в других источниках (SQL, Supabase): очередь доступна только через этот коннектор; +- если нужного инструмента нет в списке, найди его по имени (acc_review_batch, acc_review_done, acc_review_handoff, acc_review_snooze) в инструментах коннектора accounting_automation, прежде чем сообщать, что действие невозможно. Если у пользователя нет доступа к очереди (ошибка «Доступ запрещён»), не пытайся обойти: скажи об этом одной фразой. diff --git a/packages/accounting_automation/src/mcp.int.test.ts b/packages/accounting_automation/src/mcp.int.test.ts index 0a95c49..389675b 100644 --- a/packages/accounting_automation/src/mcp.int.test.ts +++ b/packages/accounting_automation/src/mcp.int.test.ts @@ -231,6 +231,14 @@ d("MCP бухгалтерии (временная БД)", () => { expect(res.results[2].error).toContain("cfo"); }); + it("одиночные инструменты принимают короткий id из таблицы", async () => { + const t = await addCat("s1"); + await call(accountant, "acc_review_handoff", { id: t.slice(0, 8), role: "cfo", comment: "c" }); + expect((await db.pool.query("select assignee_role from acc_manual_review where id = $1", [t])).rows[0].assignee_role).toBe("cfo"); + await call(accountant, "acc_review_snooze", { id: t.slice(0, 8), until: "2026-12-01" }).catch(() => undefined); + expect(await errOf(call(accountant, "acc_review_done", { id: "zz" }))).toContain("8 символов"); + }); + 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 }; @@ -338,6 +346,18 @@ d("MCP бухгалтерии (временная БД)", () => { expect((await db.pool.query("select assignee_role from acc_manual_review where id = $1", [c])).rows[0].assignee_role).toBe("cfo"); }); + it("журнал MCP: успешные и неудачные вызовы, пакет с частичной ошибкой, представление доли ошибок", async () => { + await db.pool.query("delete from acc_mcp_log"); + await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_list", arguments: {} })); + await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_done", arguments: { id: "zz" } })); + await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_batch", arguments: { actions: [{ id: "00000000", action: "done" }] } })); + const { rows } = await db.pool.query("select tool, ok, error_kind, items_total, items_failed from acc_mcp_log where method = 'tools/call' order by id"); + expect(rows[0]).toMatchObject({ tool: "acc_review_list", ok: true, error_kind: null }); + expect(rows[1]).toMatchObject({ tool: "acc_review_done", ok: false, error_kind: "invalid_args" }); + expect(rows[2]).toMatchObject({ tool: "acc_review_batch", ok: true, error_kind: "partial", items_total: 1, items_failed: 1 }); + expect((await db.pool.query("select sum(bad_calls)::int as b from acc_mcp_error_rate")).rows[0].b).toBe(2); + }); + it("JWT Keycloak: person по основной и дополнительной почте; чужой email - 403; плохие токены - 401", async () => { await addInvoice(); const call = { name: "acc_review_list", arguments: {} }; diff --git a/packages/accounting_automation/src/mcp.ts b/packages/accounting_automation/src/mcp.ts index cbe1611..8ec830b 100644 --- a/packages/accounting_automation/src/mcp.ts +++ b/packages/accounting_automation/src/mcp.ts @@ -145,10 +145,9 @@ export class ReviewTools { return [...roles]; } - private id(a: Json): string { - const v = a.id; - if (typeof v !== "string" || !UUID.test(v)) throw new McpToolError("нужно поле id (uuid задачи из acc_review_list)"); - return v; + /** id задачи: полный uuid или первые 8+ символов из таблицы списка. */ + private async id(a: Json): Promise { + return this.resolveId(a.id); } /** Задача под блокировкой + проверка роли. */ @@ -206,7 +205,7 @@ export class ReviewTools { /** acc_review_get */ async get(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); - const id = this.id(a); + const id = await this.id(a); const t = (await this.d.pool.query("select * from acc_manual_review where id = $1", [id])).rows[0] as Task | undefined; if (!t) throw new McpToolError("Задача не найдена (возможно, уже завершена и удалена из очереди)."); if (!roles.includes(t.assignee_role as ReviewRole)) throw new McpToolError(`Задача назначена роли ${t.assignee_role}: у вас нет этой роли.`); @@ -226,7 +225,7 @@ export class ReviewTools { /** acc_review_update */ async update(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); - const id = this.id(a); + const id = await this.id(a); const fields = a.fields; if (!fields || typeof fields !== "object" || Array.isArray(fields) || Object.keys(fields).length === 0) throw new McpToolError("fields: непустой объект {поле: значение}"); return withTx(this.d.pool, async (c) => { @@ -258,7 +257,7 @@ export class ReviewTools { /** acc_review_done */ async done(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); - const id = this.id(a); + const id = await this.id(a); return withTx(this.d.pool, async (c) => { const t = await this.lockTask(c, roles, id, "закрытия"); const m = metaOf(t); @@ -280,7 +279,7 @@ export class ReviewTools { /** acc_review_handoff */ async handoff(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); - const id = this.id(a); + const id = await this.id(a); if (!ROLES.includes(a.role as ReviewRole)) throw new McpToolError("role: accountant или cfo"); if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка"); return withTx(this.d.pool, async (c) => { @@ -299,7 +298,7 @@ export class ReviewTools { /** acc_review_return */ async return(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); - const id = this.id(a); + const id = await this.id(a); if (typeof a.reason !== "string" || !a.reason.trim()) throw new McpToolError("reason: нужна причина возврата"); const reason: string = a.reason.trim(); return withTx(this.d.pool, async (c) => { @@ -314,7 +313,7 @@ export class ReviewTools { /** acc_review_snooze */ async snooze(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); - const id = this.id(a); + const id = await this.id(a); const until = typeof a.until === "string" ? new Date(a.until) : null; if (!until || Number.isNaN(until.getTime())) throw new McpToolError("until: дата или время в формате ISO (2026-11-20 или 2026-11-20T09:00:00Z)"); if (until <= this.now()) throw new McpToolError("until должно быть в будущем."); @@ -328,9 +327,9 @@ export class ReviewTools { /** Полный uuid или префикс (от 8 символов) id задачи, как в таблице списка. */ private async resolveId(v: unknown): Promise { - if (typeof v !== "string") throw new McpToolError("id: строка"); + if (typeof v !== "string") throw new McpToolError("нужно поле id: первые 8 символов (или полный uuid) задачи из таблицы acc_review_list"); if (UUID.test(v)) return v; - if (!/^[0-9a-f]{8,}$/i.test(v)) throw new McpToolError("id: uuid или первые 8+ символов uuid из таблицы"); + if (!/^[0-9a-f]{8,}$/i.test(v)) throw new McpToolError("id: первые 8 символов (или полный uuid) задачи из таблицы acc_review_list"); 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 неоднозначен: укажите больше символов."); @@ -384,7 +383,7 @@ export class ReviewTools { 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)" }; +const idP = { type: "string", description: "id задачи: первые 8 символов из таблицы acc_review_list (или полный uuid), как есть" }; export const TOOLS: { name: string; description: string; inputSchema: Json; annotations?: Json; _meta?: Json }[] = [ { @@ -468,7 +467,7 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno /** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */ export const DEFAULT_INSTRUCTIONS = - "Коннектор очереди ручного разбора бухгалтерии KH Build. На вопросы вроде «что у нас на сегодня», «что по делам», «что горит» кроме календаря и других источников обязательно вызови acc_review_list и покажи таблицу очереди как есть; затем дай общую сводку. Действия над несколькими задачами - одним вызовом acc_review_batch. acc_review_done - только после подтверждения пользователя и проводки в QuickBooks."; + "Коннектор очереди ручного разбора бухгалтерии KH Build. На вопросы вроде «что у нас на сегодня», «что по делам», «что горит» кроме календаря и других источников обязательно вызови acc_review_list и покажи таблицу очереди как есть; затем дай общую сводку. Действия над несколькими задачами - одним вызовом acc_review_batch. acc_review_done - только после подтверждения пользователя и проводки в QuickBooks. В любых инструментах id задачи - 8 символов из таблицы, как есть, полный uuid не нужен и в других источниках (SQL, Supabase) его искать не надо."; /** Блок «## Инструкции» из файла p-mcp-instructions.md. */ export function instructionsFromFile(text: string): string { @@ -539,6 +538,43 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg } } +/** Классификация текста ошибки инструмента для журнала. */ +function errorKind(text: string): string { + if (text.startsWith("Доступ запрещён") || text.includes("нужна роль") || text.includes("Нужна роль") || text.includes("У вас нет роли")) return "forbidden"; + if (text.startsWith("Внутренняя ошибка")) return "internal"; + if (text.includes("не найдена")) return "not_found"; + return "invalid_args"; +} + +const clip = (v: unknown, n = 2000): unknown => { + const t = JSON.stringify(v ?? null); + return t.length > n ? { truncated: t.slice(0, n) } : v ?? null; +}; + +/** Пишет строку журнала вызова MCP; сбой журнала никогда не ломает ответ. */ +async function logCall(pool: McpDeps["pool"], personId: string, msg: Json, res: Json | null, ms: number): Promise { + try { + const method = String(msg?.method ?? "?"); + if (method.startsWith("notifications/") || method === "ping") return; + const p = (msg.params ?? {}) as { name?: string; arguments?: Json }; + const r = (res?.result ?? {}) as Json; + const sc = (r.structuredContent ?? {}) as Json; + const errText = res?.error ? String((res.error as Json).message) : r.isError ? String(((r.content as Json[] | undefined)?.[0] as Json | undefined)?.text ?? "") : null; + const failed = typeof sc.error_count === "number" ? sc.error_count : null; + const ok = !errText; + const kind = !errText ? (failed ? "partial" : null) : res?.error ? (method === "tools/call" ? "unknown_tool" : "rpc") : errorKind(errText); + const errs = failed ? ((sc.results as Json[]) ?? []).filter((x) => !x.ok).map((x) => String(x.error)).slice(0, 5).join(" | ") : errText; + await pool.query( + `insert into acc_mcp_log (person_id, method, tool, args, ok, error_kind, error, items_total, items_failed, duration_ms, result_bytes) + values ($1,$2,$3,$4::jsonb,$5,$6,$7,$8,$9,$10,$11)`, + [personId, method, method === "tools/call" ? (p.name ?? null) : null, JSON.stringify(method === "tools/call" ? clip(p.arguments) : clip(msg.params, 500)), ok, kind, errs ? errs.slice(0, 1000) : null, + Array.isArray(p.arguments?.actions) ? (p.arguments?.actions as unknown[]).length : null, failed, Math.round(ms), res ? JSON.stringify(res).length : 0], + ); + } catch { + /* журнал не критичен */ + } +} + export interface McpDeps extends ReviewDeps { /** Текст инструкций для Claude (поле instructions при initialize). */ instructions?: string; @@ -568,12 +604,18 @@ export function registerMcp(app: FastifyInstance, deps: McpDeps): ReviewTools { return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" }); } const body = req.body as unknown; + const handle = async (m: Json): Promise => { + const t0 = Date.now(); + const res = await handleMcpMessage(tools, personId, m, deps.instructions); + await logCall(deps.pool, personId, m, res, Date.now() - t0); + return res; + }; if (Array.isArray(body)) { - const out = (await Promise.all(body.map((m) => handleMcpMessage(tools, personId, m as Json, deps.instructions)))).filter((x): x is Json => x !== null); + const out = (await Promise.all(body.map((m) => handle(m as Json)))).filter((x): x is Json => x !== null); return out.length ? reply.send(out) : reply.code(202).send(); } if (!body || typeof body !== "object") return reply.code(400).send(rpcError(null, -32700, "parse error")); - const res = await handleMcpMessage(tools, personId, body as Json, deps.instructions); + const res = await handle(body as Json); return res ? reply.send(res) : reply.code(202).send(); }); app.get("/mcp", async (_req, reply) => reply.code(405).header("Allow", "POST").send({ error: "используйте POST" })); diff --git a/packages/khb_common/migrations/040_acc_mcp_log.sql b/packages/khb_common/migrations/040_acc_mcp_log.sql new file mode 100644 index 0000000..cfded3b --- /dev/null +++ b/packages/khb_common/migrations/040_acc_mcp_log.sql @@ -0,0 +1,31 @@ +-- Журнал вызовов MCP accounting_automation: разбор ошибок и доли неудачных запросов, когда чата сотрудника не видно. +create table if not exists acc_mcp_log ( + id bigserial primary key, + at timestamptz not null default now(), + person_id text, + method text not null, -- tools/call, tools/list, initialize, resources/read ... + tool text, -- имя инструмента для tools/call + args jsonb, -- аргументы (усечённые) + ok boolean not null, + error_kind text, -- invalid_args | not_found | forbidden | internal | unknown_tool | rpc | partial + error text, + items_total int, -- для acc_review_batch: действий в пакете + items_failed int, -- для acc_review_batch: неудачных действий + duration_ms int, + result_bytes int +); +create index if not exists acc_mcp_log_at_idx on acc_mcp_log (at desc); +create index if not exists acc_mcp_log_tool_idx on acc_mcp_log (tool, at desc); + +-- Доля ошибок по инструментам и дням: >3-5% = баг инструмента или мало инструкций. +create or replace view acc_mcp_error_rate as +select date_trunc('day', at)::date as day, tool, + count(*) as calls, + count(*) filter (where not ok or coalesce(items_failed, 0) > 0) as bad_calls, + round(100.0 * count(*) filter (where not ok or coalesce(items_failed, 0) > 0) / count(*), 1) as bad_pct, + coalesce(sum(items_total), 0) as batch_items, + coalesce(sum(items_failed), 0) as batch_items_failed + from acc_mcp_log + where method = 'tools/call' + group by 1, 2 + order by 1 desc, 2;