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, REVIEW_UI_URI_LEGACY, rowsToMarkdown, toRow } from "./mcp-ui.js"; import { allowWithoutReceipt } from "./receipt-search.js"; import type { AccountingSettings } from "./settings.js"; /** * MCP для Claude сотрудника: разбор очереди acc_manual_review («Review проблем в Claude»). * JSON-RPC 2.0 вручную, Streamable HTTP без сессий. Чистый слой (ReviewTools) не знает про HTTP. */ type Json = Record; export type ReviewRole = "accountant" | "cfo"; type PoolClient = Parameters[1]>[0]; const ROLES: ReviewRole[] = ["accountant", "cfo"]; /** Ошибка инструмента: показывается пользователю как isError с текстом по-русски. */ export class McpToolError extends Error {} export interface ReviewDeps { pool: Pool; settings: Pick; /** Лимит расхода без чека (USD), по умолчанию 500. */ noReceiptLimitUsd?: number; now?: () => Date; } interface KindMeta { table: string; key: string; /** Поля, которые можно править: имя -> проверка и приведение (возвращает значение и SQL-приведение типа). */ fields: Record; } interface FieldSpec { cast: string; check: (v: unknown) => unknown; } const isNull = (v: unknown): boolean => v === null; const text = (nullable: boolean) => (v: unknown): unknown => { if (v === null && nullable) return null; if (typeof v !== "string") throw new McpToolError("ожидалась строка"); return v; }; const dateF = (v: unknown): unknown => { if (isNull(v)) return null; if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v) || Number.isNaN(Date.parse(v)) || new Date(v).toISOString().slice(0, 10) !== v) throw new McpToolError("ожидалась дата YYYY-MM-DD"); return v; }; const amountF = (v: unknown): unknown => { if (isNull(v)) return null; const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v; if (typeof n !== "number" || !Number.isFinite(n) || Math.abs(n) >= 1e12) throw new McpToolError("ожидалось число"); return Math.round(n * 100) / 100; }; const jsonF = (v: unknown): unknown => { if (v !== null && typeof v !== "object") throw new McpToolError("ожидался JSON (объект или массив)"); return JSON.stringify(v); }; const uuidF = (v: unknown): unknown => { if (isNull(v)) return null; if (typeof v !== "string" || !UUID.test(v)) throw new McpToolError("ожидался uuid"); return v; }; const confidenceF = (v: unknown): unknown => { if (isNull(v)) return null; if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > 100) throw new McpToolError("ожидалось целое 0..100"); return v; }; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const problem: FieldSpec = { cast: "text", check: text(true) }; export const KINDS: Record = { invoice: { table: "acc_invoices_review", key: "id", fields: { vendor_name: { cast: "text", check: text(true) }, vendor_qbo_id: { cast: "text", check: text(true) }, invoice_number: { cast: "text", check: text(true) }, invoice_date: { cast: "date", check: dateF }, amount: { cast: "numeric", check: amountF }, lines: { cast: "jsonb", check: jsonF }, project_customer_id: { cast: "text", check: text(true) }, jt_job_id: { cast: "text", check: text(true) }, contract_id: { cast: "uuid", check: uuidF }, problem_highlight: problem, }, }, categorization: { table: "acc_categorization_review", key: "feed_txn_id", fields: { suggestion: { cast: "jsonb", check: jsonF }, confidence: { cast: "smallint", check: confidenceF }, problem_highlight: problem, }, }, certificate: { table: "acc_certificates_review", key: "id", fields: { expires_on: { cast: "date", check: dateF }, vendor_qbo_id: { cast: "text", check: text(true) }, problem_highlight: problem, }, }, }; const driveUrl = (id: unknown): string | null => (typeof id === "string" && id ? `https://drive.google.com/file/d/${id}/view` : null); interface Task { id: string; kind: string; ref_table: string; ref_id: string; assignee_role: string; problem_highlight: string | null; snoozed_until: Date | null; created_at: Date; } const taskOut = (t: Task): Json => ({ id: t.id, kind: t.kind, assignee_role: t.assignee_role, problem_highlight: t.problem_highlight, snoozed_until: t.snoozed_until, created_at: t.created_at, }); const metaOf = (t: Pick): KindMeta | undefined => KINDS[t.kind]; /** Чистый слой инструментов: person_id вызывающего передаётся первым аргументом. */ export class ReviewTools { private readonly now: () => Date; constructor(private readonly d: ReviewDeps) { this.now = d.now ?? (() => new Date()); } /** Роли человека по settings.reviewers; пусто - доступ запрещён. */ rolesOf(personId: string): ReviewRole[] { const roles = new Set(); for (const r of this.d.settings.reviewers) if (r.personId.toLowerCase() === personId.toLowerCase()) r.roles.forEach((x) => roles.add(x)); if (roles.size === 0) throw new McpToolError("Доступ запрещён: вы не назначены на разбор очереди бухгалтерии (settings.reviewers)."); return [...roles]; } /** id задачи: полный uuid или первые 8+ символов из таблицы списка. */ private async id(a: Json): Promise { return this.resolveId(a.id); } /** Задача под блокировкой + проверка роли. */ private async lockTask(c: PoolClient, roles: ReviewRole[], id: string, forWhat = "работы с задачей"): Promise { const t = (await c.query("select * from acc_manual_review where id = $1 for update", [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}: для ${forWhat} нужна роль ${t.assignee_role}.`); return t; } private async reviewRow(c: Pick, t: Task, suffix = "", lock = false): Promise { const m = metaOf(t); if (!m) return null; const r = await c.query(`select to_jsonb(r) as row from ${m.table}${suffix} r where r.${m.key}::text = $1 ${lock ? "for update" : ""}`.trim(), [t.ref_id]); return (r.rows[0]?.row as Json | undefined) ?? null; } /** acc_review_list */ async list(personId: string, a: Json): Promise { const mine = this.rolesOf(personId); let roles = mine; if (a.role !== undefined) { if (!ROLES.includes(a.role as ReviewRole)) throw new McpToolError("role: accountant или cfo"); if (!mine.includes(a.role as ReviewRole)) throw new McpToolError(`У вас нет роли ${String(a.role)}.`); roles = [a.role as ReviewRole]; } if (a.kind !== undefined && typeof a.kind !== "string") throw new McpToolError("kind: строка"); const limit = a.limit === undefined ? 20 : a.limit; if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new McpToolError("limit: целое 1..100"); const { rows } = await this.d.pool.query( `select m.*, coalesce(to_jsonb(i), to_jsonb(c), to_jsonb(s), to_jsonb(v)) as row, count(*) over()::int as total from acc_manual_review m left join acc_invoices_review i on m.ref_table = 'acc_invoices_review' and i.id::text = m.ref_id left join acc_categorization_review c on m.ref_table = 'acc_categorization_review' and c.feed_txn_id = m.ref_id left join acc_certificates_review s on m.ref_table = 'acc_certificates_review' and s.id::text = m.ref_id left join acc_invoices v on m.ref_table = 'acc_invoices' and v.id::text = m.ref_id where m.assignee_role = any($1::text[]) and ($2::text is null or m.kind = $2) and ($3::boolean or m.snoozed_until is null or m.snoozed_until <= $4) and not coalesce(i.done, c.done, s.done, false) order by (nullif(btrim(m.problem_highlight), '') is null), m.created_at, m.id limit $5`, [roles, (a.kind as string | undefined) ?? null, a.include_snoozed === true, this.now(), limit], ); return { total: rows[0]?.total ?? 0, shown: rows.length, tasks: rows.map((r) => { const row = r.row as Json | null; return { ...taskOut(r as Task), review: row, ...((r.kind === "invoice" || r.kind === "invoice_approval") && row ? { file_url: driveUrl(row.drive_file_id) } : {}) }; }), }; } /** acc_review_get */ async get(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); 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}: у вас нет этой роли.`); const isApproval = t.kind === "invoice_approval"; const review = isApproval ? await this.invoiceRow(this.d.pool, t.ref_id) : await this.reviewRow(this.d.pool, t); const original = isApproval ? null : await this.reviewRow(this.d.pool, t, "_original"); let fileId: unknown = t.kind === "invoice" || isApproval ? review?.drive_file_id : undefined; if (t.kind === "certificate" && review?.certificate_id) { fileId = (await this.d.pool.query("select drive_file_id from acc_insurance_certificates where id = $1", [review.certificate_id])).rows[0]?.drive_file_id; } const changed = review && original ? Object.keys(review).filter((k) => !["updated_at", "done", "done_by", "fraud_checked_at"].includes(k) && JSON.stringify(review[k]) !== JSON.stringify(original[k])) : []; return { task: taskOut(t), review, original, changed_fields: changed, file_url: driveUrl(fileId) }; } private async invoiceRow(c: Pick, id: string, lock = false): Promise { const r = await c.query(`select to_jsonb(v) as row from acc_invoices v where v.id::text = $1 ${lock ? "for update" : ""}`.trim(), [id]); return (r.rows[0]?.row as Json | undefined) ?? null; } /** Задача проверки инвойса (invoice_approval) под блокировкой вместе со строкой acc_invoices. */ private async lockInvoiceTask(c: PoolClient, roles: ReviewRole[], id: string, forWhat: string): Promise<{ t: Task; inv: Json }> { const t = await this.lockTask(c, roles, id, forWhat); if (t.kind !== "invoice_approval") throw new McpToolError(`Это задача вида ${t.kind}, а не согласования инвойса (invoice_approval).`); const inv = await this.invoiceRow(c, t.ref_id, true); if (!inv) throw new McpToolError("Инвойс не найден."); return { t, inv }; } /** acc_invoice_to_approve: Юля проверила инвойс и переводит его «на согласование» (задача уходит роли cfo). */ async invoiceToApprove(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); const id = await this.id(a); if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка"); return withTx(this.d.pool, async (c) => { const { t, inv } = await this.lockInvoiceTask(c, roles, id, "перевода на согласование"); if (inv.stage !== "checking") throw new McpToolError(`Инвойс в стадии ${String(inv.stage)}: на согласование переводится только инвойс на проверке (checking).`); if (inv.conclusion == null) throw new McpToolError("У инвойса ещё нет заключения проверки: дождитесь задания invoice-check."); await c.query("update acc_invoices set stage = 'to_approve' where id = $1", [inv.id]); await c.query("update acc_manual_review set assignee_role = 'cfo', snoozed_until = null where id = $1", [t.id]); if (typeof a.comment === "string" && a.comment.trim()) { const base = t.problem_highlight ? `${t.problem_highlight} | ` : ""; await c.query("update acc_manual_review set problem_highlight = $2 where id = $1", [t.id, `${base}Юля: ${a.comment.trim()}`]); } const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task; return { ok: true, stage: "to_approve", task: taskOut(now) }; }); } /** acc_invoice_decide: решение Анастасии (роль cfo): approved, rejected или wait (с датой повторного показа). */ async invoiceDecide(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); if (!roles.includes("cfo")) throw new McpToolError("Решение по инвойсу принимает роль cfo."); const id = await this.id(a); const decision = a.decision; if (decision !== "approved" && decision !== "rejected" && decision !== "wait") throw new McpToolError("decision: approved, rejected или wait"); if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка"); let until: Date | null = null; if (decision === "wait") { until = typeof a.until === "string" ? new Date(a.until) : null; if (!until || Number.isNaN(until.getTime())) throw new McpToolError("until: для wait нужна дата повторного показа (2026-11-20 или ISO-время)"); if (until <= this.now()) throw new McpToolError("until должно быть в будущем."); } const now = this.now(); return withTx(this.d.pool, async (c) => { const { t, inv } = await this.lockInvoiceTask(c, roles, id, "решения по инвойсу"); if (t.assignee_role !== "cfo") throw new McpToolError("Инвойс ещё не переведён на согласование (задача у accountant)."); if (inv.stage !== "to_approve" && inv.stage !== "wait") throw new McpToolError(`Инвойс в стадии ${String(inv.stage)}: решение возможно для to_approve и wait.`); const note = { decision, by: personId, at: now.toISOString(), ...(typeof a.comment === "string" && a.comment.trim() ? { comment: a.comment.trim() } : {}), ...(until ? { until: until.toISOString() } : {}) }; await c.query( `update acc_invoices set stage = $2, decided_by = $3, decided_at = $4, conclusion = coalesce(conclusion, '{}'::jsonb) || jsonb_build_object('last_decision', $5::jsonb) where id = $1`, [inv.id, decision, personId, now, JSON.stringify(note)], ); if (decision === "wait") await c.query("update acc_manual_review set snoozed_until = $2 where id = $1", [t.id, until]); else await c.query("delete from acc_manual_review where id = $1", [t.id]); return { ok: true, stage: decision, decided_by: personId, decided_at: now.toISOString(), ...(until ? { snoozed_until: until.toISOString() } : {}) }; }); } /** acc_review_update */ async update(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); 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) => { const t = await this.lockTask(c, roles, id, "правки"); const m = metaOf(t); if (!m) throw new McpToolError(`Для задач вида ${t.kind} правка полей через MCP не предусмотрена.`); const sets: string[] = []; const vals: unknown[] = []; for (const [k, v] of Object.entries(fields as Json)) { const spec = m.fields[k]; if (!spec) throw new McpToolError(`Поле ${k} править нельзя. Допустимые для вида ${t.kind}: ${Object.keys(m.fields).join(", ")}.`); let val: unknown; try { val = spec.check(v); } catch (e) { throw new McpToolError(`Поле ${k}: ${e instanceof Error ? e.message : String(e)}`); } vals.push(val); sets.push(`${k} = $${vals.length + 1}::${spec.cast}`); } const row = await this.reviewRow(c, t, "", true); if (!row) throw new McpToolError("Строка разбора не найдена."); if (row.done === true) throw new McpToolError("Запись уже отмечена выполненной, править нельзя."); await c.query(`update ${m.table} set ${sets.join(", ")} where ${m.key}::text = $1`, [t.ref_id, ...vals]); return { ok: true, review: await this.reviewRow(c, t) }; }); } /** acc_review_done */ async done(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); 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); if (!m) throw new McpToolError(`Задачи вида ${t.kind} через MCP закрыть нельзя.`); if (t.kind === "categorization" && t.assignee_role === "cfo" && !roles.includes("cfo")) throw new McpToolError("Нужна роль cfo."); const r = await c.query(`update ${m.table} set done = true, done_by = $2 where ${m.key}::text = $1 and not done`, [t.ref_id, personId]); if (r.rowCount === 0) throw new McpToolError("Запись уже отмечена выполненной или не найдена."); return { ok: true, message: "Отмечено выполненным; запись будет перенесена в историю процессом «Завершение ручного разбора».", task: taskOut(t) }; }); } /** Записывает текст проблемы туда же, где её видит человек: в review-строку (триггер синхронизирует очередь) или в саму очередь. */ private async setProblem(c: PoolClient, t: Task, textValue: string | null): Promise { const m = metaOf(t); if (m) await c.query(`update ${m.table} set problem_highlight = $2 where ${m.key}::text = $1`, [t.ref_id, textValue]); else await c.query("update acc_manual_review set problem_highlight = $2 where id = $1", [t.id, textValue]); } /** acc_review_handoff */ async handoff(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); 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) => { const t = await this.lockTask(c, roles, id, "передачи"); if (t.assignee_role === a.role) throw new McpToolError(`Задача уже назначена роли ${String(a.role)}.`); await c.query("update acc_manual_review set assignee_role = $2 where id = $1", [t.id, a.role]); if (typeof a.comment === "string" && a.comment.trim()) { const base = t.problem_highlight ? `${t.problem_highlight} | ` : ""; await this.setProblem(c, t, `${base}Передано ${t.assignee_role} -> ${String(a.role)}: ${a.comment.trim()}`); } const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task; return { ok: true, task: taskOut(now) }; }); } /** acc_review_return */ async return(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); 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) => { const t = await this.lockTask(c, roles, id, "возврата"); await c.query("update acc_manual_review set assignee_role = 'accountant', snoozed_until = null where id = $1", [t.id]); await this.setProblem(c, t, `Возвращено: ${reason}`); const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task; return { ok: true, task: taskOut(now) }; }); } /** acc_review_snooze */ async snooze(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); 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 должно быть в будущем."); return withTx(this.d.pool, async (c) => { const t = await this.lockTask(c, roles, id, "откладывания"); await c.query("update acc_manual_review set snoozed_until = $2 where id = $1", [t.id, until]); const now = (await c.query("select * from acc_manual_review where id = $1", [t.id])).rows[0] as Task; return { ok: true, task: taskOut(now) }; }); } /** acc_receipt_allow_without: Анастасия разрешает провести расход без чека (процесс «Поиск чека», шаг 8). */ async allowWithoutReceipt(personId: string, a: Json): Promise { const roles = this.rolesOf(personId); if (!roles.includes("cfo")) throw new McpToolError("Разрешить расход без чека может только роль cfo (Анастасия)."); const id = await this.id(a); if (typeof a.reason !== "string" || !a.reason.trim()) throw new McpToolError("reason: нужна причина (почему чек не найден)"); 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("Задача не найдена (возможно, уже завершена и удалена из очереди)."); let feed: string | null = null; if (t.ref_table === "acc_categorization_review") feed = t.ref_id; else if (t.ref_table === "acc_receipt_search") feed = ((await this.d.pool.query("select feed_txn_id from acc_receipt_search where id::text = $1", [t.ref_id])).rows[0]?.feed_txn_id as string | undefined) ?? null; if (!feed) throw new McpToolError("Задача не относится к операции банка (нужна задача вида categorization или receipt_search)."); try { const r = await allowWithoutReceipt(this.d.pool, personId, feed, a.reason, this.d.noReceiptLimitUsd ?? 500, this.now()); return { ok: true, amount: r.amount, message: "Разрешено провести без чека. Проведите операцию в QuickBooks с пометкой «чек не найден, причина» в Private note, затем отметьте задачу выполненной." }; } catch (e) { throw new McpToolError(e instanceof Error ? e.message : String(e)); } } /** Полный uuid или префикс (от 8 символов) id задачи, как в таблице списка. */ private async resolveId(v: unknown): Promise { 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: первые 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 неоднозначен: укажите больше символов."); 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); case "acc_review_done": return this.done(personId, a); case "acc_review_handoff": return this.handoff(personId, a); case "acc_review_return": return this.return(personId, a); case "acc_review_snooze": return this.snooze(personId, a); case "acc_invoice_to_approve": return this.invoiceToApprove(personId, a); case "acc_invoice_decide": return this.invoiceDecide(personId, a); case "acc_receipt_allow_without": return this.allowWithoutReceipt(personId, a); default: throw new McpToolError(`Неизвестный инструмент ${name}`); } } } const str = { type: "string" }; const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false }); const idP = { type: "string", description: "id задачи: первые 8 символов из таблицы acc_review_list (или полный uuid), как есть" }; 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, visibility: ["model", "app"] }, "ui/resourceUri": REVIEW_UI_URI }, description: "ВЫЗЫВАЙ СРАЗУ, без вопросов и без просьб разрешения (только чтение, безопасно) на любые вопросы про бухгалтерию, дела, задачи, «что на сегодня», «что горит». Не спрашивай «использовать ли коннектор?», просто вызови. ВЫЗЫВАЙ СРАЗУ, без вопросов и без просьб разрешения (только чтение, безопасно) на любые вопросы про бухгалтерию, дела, задачи, «что на сегодня», «что горит»; не спрашивай «использовать ли коннектор?». Дела и задачи бухгалтерии на сегодня: очередь ручного разбора (банковские операции, инвойсы, сертификаты). Вызывай и на общие вопросы «что у нас на сегодня», «что по делам», «что горит», вместе с календарём. Список задач (до 20 по умолчанию, можно до 100) показывается компактной таблицей: id (8 символов), вид, дата, сумма, кто, что, %, проблема, роль. ОБЯЗАТЕЛЬНО выведи эту 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: "показать задачи только этой роли (по умолчанию - все ваши роли)" }, include_snoozed: { type: "boolean", description: "показать и отложенные задачи" }, limit: { type: "number", description: "сколько задач вернуть (1..100, по умолчанию 20)" }, }), }, { 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_receipt_allow_without", annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, description: "Только роль cfo (Анастасия). Разрешить провести расход без чека, когда чек так и не найден (процесс «Поиск чека», шаг 8): только на сумму до $500 и по каждому расходу отдельно; больше $500 без чека не проводится. id - задача операции (categorization или receipt_search). Дальше проведи операцию в QuickBooks с пометкой «чек не найден, причина» в Private note и отметь задачу выполненной.", 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"]), }, { name: "acc_invoice_to_approve", annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, description: "Проверка инвойса закончена: перевести инвойс (задача вида invoice_approval) в «на согласование»; задача уходит роли cfo (Анастасия). Вызывать после того, как бухгалтер прочитал заключение и решил вопросы с подрядчиком; только по просьбе пользователя.", inputSchema: obj({ id: idP, comment: { ...str, description: "заметка для Анастасии (добавится к проблеме задачи)" } }, ["id"]), }, { name: "acc_invoice_decide", annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, description: "Решение по инвойсу на согласовании (только роль cfo): approved (согласован), rejected (отклонён) или wait (подождать: нужна дата until, до неё задача скрыта). Записывает, кто и когда решил. Деньги система не двигает: оплату делает человек в банке. Вызывать только после явного решения пользователя.", inputSchema: obj( { id: idP, decision: { type: "string", enum: ["approved", "rejected", "wait"] }, until: { ...str, description: "для wait: дата или время ISO в будущем, когда показать инвойс снова" }, comment: { ...str, description: "причина или заметка (сохраняется в заключении инвойса)" }, }, ["id", "decision"], ), }, ]; /** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */ export const DEFAULT_INSTRUCTIONS = "Коннектор очереди ручного разбора бухгалтерии KH Build. Инструменты только читают или меняют очередь по явной просьбе: на вопросы про бухгалтерию вызывай acc_review_list сразу, не спрашивая разрешения и не уточняя, использовать ли коннектор. Таблицу очереди, если она показана приложением, не дублируй текстом: дай короткую сводку и предложи пакетное действие. Пользователь не видит результаты инструментов: таблицу очереди из ответа acc_review_list всегда выводи в ответ целиком как markdown, затем короткая сводка. На вопросы про бухгалтерию вызывай acc_review_list сразу, не спрашивая разрешения и не уточняя, использовать ли коннектор. На вопросы вроде «что у нас на сегодня», «что по делам», «что горит» кроме календаря и других источников обязательно вызови 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 { const m = text.split(/\n## Инструкции\s*\n/)[1]; return (m ?? text).trim(); } const rpcError = (id: unknown, code: number, message: string): Json => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } }); /** Обрабатывает одно JSON-RPC сообщение от аутентифицированного человека; null - уведомление (ответа нет). */ const SUPPORTED_VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"]; const SERVER_INFO = { name: "accounting_automation", version: "0.1.0" }; const CAPABILITIES = { tools: { listChanged: true }, resources: {}, prompts: {}, extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [REVIEW_UI_MIME] } } }; /** Подсказки кэширования (2026-07-28) для списков, discover и ресурсов; во всех результатах resultType: "complete". */ const CACHE_HINTS: Record = { "server/discover": { ttlMs: 60_000, cacheScope: "public" }, "tools/list": { ttlMs: 60_000, cacheScope: "public" }, "prompts/list": { ttlMs: 60_000, cacheScope: "public" }, "resources/list": { ttlMs: 60_000, cacheScope: "public" }, "resources/read": { ttlMs: 3_600_000, cacheScope: "public" }, // URI с хэшем содержимого }; export async function handleMcpMessage(tools: ReviewTools, personId: string, msg: Json, instructions: string = DEFAULT_INSTRUCTIONS): Promise { const res = await handleMcpInner(tools, personId, msg, instructions); if (res && res.result && typeof res.result === "object") { const hint = CACHE_HINTS[String(msg?.method)]; res.result = { resultType: "complete", ...(res.result as Json), ...(hint ?? {}) }; } return res; } async function handleMcpInner(tools: ReviewTools, personId: string, msg: Json, instructions: string): Promise { const id = msg?.id; const method = msg?.method; if (typeof method !== "string") return rpcError(id, -32600, "invalid request"); if (id === undefined) return null; // notifications/* 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: CAPABILITIES, serverInfo: SERVER_INFO, instructions } }; } case "ping": return { jsonrpc: "2.0", id, result: {} }; case "prompts/list": return { jsonrpc: "2.0", id, result: { prompts: [{ name: "today", description: "Что у нас на сегодня: календарь и очередь разбора бухгалтерии" }] } }; case "prompts/get": { const name = (msg.params as Json | undefined)?.name; if (name !== "today") return rpcError(id, -32602, `неизвестный промпт ${String(name)}`); return { jsonrpc: "2.0", id, result: { description: "Что у нас на сегодня", messages: [{ role: "user", content: { type: "text", text: "Что у нас на сегодня? Посмотри календарь и очередь разбора бухгалтерии (acc_review_list), покажи таблицу очереди и дай общую сводку." } }], }, }; } 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 && uri !== REVIEW_UI_URI_LEGACY) return rpcError(id, -32002, `ресурс не найден: ${String(uri)}`); return { jsonrpc: "2.0", id, result: { contents: [{ uri, mimeType: REVIEW_UI_MIME, text: REVIEW_UI_HTML, _meta: { ui: { prefersBorder: true, csp: { connectDomains: [], resourceDomains: [], frameDomains: [], baseUriDomains: [] } } } }] } }; } case "server/discover": // версия 2026-07-28 (без initialize): Claude вызывает именно его return { jsonrpc: "2.0", id, result: { supportedVersions: SUPPORTED_VERSIONS, capabilities: CAPABILITIES, _meta: { "io.modelcontextprotocol/serverInfo": SERVER_INFO }, instructions } }; case "tools/list": return { jsonrpc: "2.0", id, result: { tools: TOOLS } }; case "tools/call": { const p = (msg.params ?? {}) as { name?: string; arguments?: Json }; 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 }, _meta: { ui: { resourceUri: REVIEW_UI_URI }, "ui/resourceUri": REVIEW_UI_URI } } }; } 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)}`; return { jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text }] } }; } } default: return rpcError(id, -32601, `метод не поддерживается: ${method}`); } } /** Классификация текста ошибки инструмента для журнала. */ 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; }; export const MCP_LOG_KEEP = 100000; let logWrites = 0; /** Автоочистка журнала: оставляет последние keep записей, давние удаляет. Возвращает число удалённых. */ export async function pruneMcpLog(pool: McpDeps["pool"], keep = MCP_LOG_KEEP): Promise { const r = await pool.query("delete from acc_mcp_log where id in (select id from acc_mcp_log order by id desc offset $1)", [keep]); return r.rowCount ?? 0; } /** Пишет строку журнала вызова 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], ); // очистка при первой записи после старта и затем раз в 500 записей if (logWrites++ % 500 === 0) await pruneMcpLog(pool); } catch { /* журнал не критичен */ } } export interface McpDeps extends ReviewDeps { /** Текст инструкций для Claude (поле instructions при initialize). */ instructions?: string; settings: Pick; /** Проверка JWT Keycloak (для тестов - с локальным JWKS). */ verifyJwt?: JwtVerifier; } /** Вешает POST /mcp на Fastify. Аутентификация (Bearer) - только для /mcp. Если mcp.enabled=false - ничего не регистрирует. */ export function registerMcp(app: FastifyInstance, deps: McpDeps): ReviewTools { const tools = new ReviewTools(deps); if (!deps.settings.mcp.enabled) return tools; const authenticate = createMcpAuth(deps); // подсказка клиенту (Claude), где искать описание защищённого ресурса (RFC 9728) let challenge = "Bearer"; if (deps.settings.mcp.publicUrl) { const u = new URL(deps.settings.mcp.publicUrl); challenge = `Bearer resource_metadata="${u.origin}/.well-known/oauth-protected-resource${u.pathname.replace(/\/$/, "")}/mcp"`; } app.post("/mcp", async (req, reply) => { let personId: string; try { personId = (await authenticate(req.headers.authorization)).personId; } catch (e) { const status = e instanceof McpAuthError ? e.status : 401; if (status === 401) void reply.header("WWW-Authenticate", challenge); 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) => 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 handle(body as Json); return res ? reply.send(res) : reply.code(202).send(); }); // Поток сервер->клиент (Streamable HTTP, GET + SSE): при каждом подключении шлём tools/list_changed. // После деплоя сервис перезапускается, клиент переподключает поток, получает уведомление и сам перечитывает список инструментов. const streams = new Set<() => void>(); app.addHook("onClose", async () => { for (const close of [...streams]) close(); }); app.get("/mcp", async (req, reply) => { if (!String(req.headers.accept ?? "").includes("text/event-stream")) return reply.code(405).header("Allow", "POST").send({ error: "используйте POST (или GET с Accept: text/event-stream)" }); try { await authenticate(req.headers.authorization); } catch (e) { const status = e instanceof McpAuthError ? e.status : 401; if (status === 401) void reply.header("WWW-Authenticate", challenge); return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" }); } reply.hijack(); const raw = reply.raw; raw.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive", "X-Accel-Buffering": "no" }); raw.write(`event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })}\n\n`); const ping = setInterval(() => raw.write(": ping\n\n"), 20000); const close = (): void => { clearInterval(ping); streams.delete(close); if (!raw.writableEnded) raw.end(); }; streams.add(close); raw.on("close", close); }); return tools; }