accounting_automation: этап 1 бухгалтерской автоматизации (инвойсы из почты, категоризация, ручной разбор, MCP), интервальные задания scheduler, миграции 033/034/038
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
455
packages/accounting_automation/src/mcp.ts
Normal file
455
packages/accounting_automation/src/mcp.ts
Normal file
@@ -0,0 +1,455 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { withTx, type Pool } from "khb_common";
|
||||
import { createMcpAuth, McpAuthError, type JwtVerifier } from "./mcp-auth.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<string, unknown>;
|
||||
export type ReviewRole = "accountant" | "cfo";
|
||||
type PoolClient = Parameters<Parameters<typeof withTx>[1]>[0];
|
||||
const ROLES: ReviewRole[] = ["accountant", "cfo"];
|
||||
|
||||
/** Ошибка инструмента: показывается пользователю как isError с текстом по-русски. */
|
||||
export class McpToolError extends Error {}
|
||||
|
||||
export interface ReviewDeps {
|
||||
pool: Pool;
|
||||
settings: Pick<AccountingSettings, "reviewers">;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
interface KindMeta {
|
||||
table: string;
|
||||
key: string;
|
||||
/** Поля, которые можно править: имя -> проверка и приведение (возвращает значение и SQL-приведение типа). */
|
||||
fields: Record<string, FieldSpec>;
|
||||
}
|
||||
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<string, KindMeta> = {
|
||||
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<Task, "kind">): 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<ReviewRole>();
|
||||
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];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Задача под блокировкой + проверка роли. */
|
||||
private async lockTask(c: PoolClient, roles: ReviewRole[], id: string, forWhat = "работы с задачей"): Promise<Task> {
|
||||
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<PoolClient, "query">, t: Task, suffix = "", lock = false): Promise<Json | null> {
|
||||
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<Json> {
|
||||
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)) 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
|
||||
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" && row ? { file_url: driveUrl(row.drive_file_id) } : {}) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** acc_review_get */
|
||||
async get(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = 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 review = await this.reviewRow(this.d.pool, t);
|
||||
const original = await this.reviewRow(this.d.pool, t, "_original");
|
||||
let fileId: unknown = t.kind === "invoice" ? 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"].includes(k) && JSON.stringify(review[k]) !== JSON.stringify(original[k]))
|
||||
: [];
|
||||
return { task: taskOut(t), review, original, changed_fields: changed, file_url: driveUrl(fileId) };
|
||||
}
|
||||
|
||||
/** acc_review_update */
|
||||
async update(personId: string, a: Json): Promise<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = 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<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = 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<void> {
|
||||
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<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = 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<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = 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<Json> {
|
||||
const roles = this.rolesOf(personId);
|
||||
const id = 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) };
|
||||
});
|
||||
}
|
||||
|
||||
call(personId: string, name: string, a: Json): Promise<Json> {
|
||||
switch (name) {
|
||||
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);
|
||||
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 задачи (uuid из acc_review_list)" };
|
||||
|
||||
export const TOOLS: { name: string; description: string; inputSchema: Json }[] = [
|
||||
{
|
||||
name: "acc_review_list",
|
||||
description:
|
||||
"Список задач ручного разбора бухгалтерии (очередь 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",
|
||||
description: "Одна задача ручного разбора: сама задача, строка разбора (review), как её записал автомат (original), список изменённых полей и ссылка на файл в Google Drive (для инвойса и сертификата).",
|
||||
inputSchema: obj({ id: idP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_update",
|
||||
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",
|
||||
description: "Отметить задачу выполненной (после подтверждения пользователем; для банковской операции - после проводки в QuickBooks). Дальше запись переносит в историю процесс «Завершение ручного разбора». Задачу роли cfo может закрыть только пользователь с ролью cfo.",
|
||||
inputSchema: obj({ id: idP }, ["id"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_handoff",
|
||||
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",
|
||||
description: "Вернуть задачу в общую очередь (роль accountant) с причиной; причина записывается в problem_highlight, отложенность снимается.",
|
||||
inputSchema: obj({ id: idP, reason: { type: "string", description: "причина возврата" } }, ["id", "reason"]),
|
||||
},
|
||||
{
|
||||
name: "acc_review_snooze",
|
||||
description: "Отложить задачу («подождать»): она не показывается в списке до указанного момента.",
|
||||
inputSchema: obj({ id: idP, until: { ...str, description: "дата или время ISO, в будущем: 2026-11-20 или 2026-11-20T09:00:00Z" } }, ["id", "until"]),
|
||||
},
|
||||
];
|
||||
|
||||
const rpcError = (id: unknown, code: number, message: string): Json => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
|
||||
|
||||
/** Обрабатывает одно JSON-RPC сообщение от аутентифицированного человека; null - уведомление (ответа нет). */
|
||||
export async function handleMcpMessage(tools: ReviewTools, personId: string, msg: Json): Promise<Json | null> {
|
||||
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: { tools: {} }, serverInfo: { name: "khb-accounting", version: "0.1.0" } } };
|
||||
}
|
||||
case "ping":
|
||||
return { jsonrpc: "2.0", id, result: {} };
|
||||
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 ?? {});
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
|
||||
export interface McpDeps extends ReviewDeps {
|
||||
settings: Pick<AccountingSettings, "reviewers" | "mcp">;
|
||||
/** Проверка 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);
|
||||
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", "Bearer");
|
||||
return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" });
|
||||
}
|
||||
const body = req.body as unknown;
|
||||
if (Array.isArray(body)) {
|
||||
const out = (await Promise.all(body.map((m) => handleMcpMessage(tools, personId, 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);
|
||||
return res ? reply.send(res) : reply.code(202).send();
|
||||
});
|
||||
app.get("/mcp", async (_req, reply) => reply.code(405).header("Allow", "POST").send({ error: "используйте POST" }));
|
||||
return tools;
|
||||
}
|
||||
Reference in New Issue
Block a user