- approval.ts: роль подтверждающего при создании задачи категоризации (порог approvalThresholdUsd, первая оплата вендору) - fraud.ts: красные флажки по картам (первая оплата, рост суммы от медианы), задание fraud-flags - invoice-check.ts: заключение по инвойсу и задача invoice_approval; задание invoice-check - invoice-paid.ts: markPaid и задание invoice-paid (paid_on, paid_amount контракта) - MCP: acc_invoice_to_approve, acc_invoice_decide; миграция 041; документы proposed Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
439 lines
31 KiB
TypeScript
439 lines
31 KiB
TypeScript
import Fastify from "fastify";
|
||
import { exportJWK, generateKeyPair, SignJWT, createLocalJWKSet } from "jose";
|
||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||
import { keycloakVerifier } from "./mcp-auth.js";
|
||
import { REVIEW_UI_URI } from "./mcp-ui.js";
|
||
import { ReviewTools, pruneMcpLog, registerMcp, type McpDeps } from "./mcp.js";
|
||
|
||
const url = testDatabaseUrl();
|
||
const d = url ? describe : describe.skip;
|
||
|
||
const ISSUER = "https://sso.example.test/realms/khb";
|
||
const TOKEN_A = "token-accountant-0123456789";
|
||
const TOKEN_CFO = "token-cfo-0123456789abcd";
|
||
const NOW = new Date("2026-11-17T12:00:00Z");
|
||
|
||
d("MCP бухгалтерии (временная БД)", () => {
|
||
let db: TestDb;
|
||
let accountant: string; // только роль accountant
|
||
let cfo: string; // accountant + cfo
|
||
let stranger: string; // не в reviewers
|
||
let kc: string; // person с email из Keycloak, роль accountant
|
||
let settings: McpDeps["settings"];
|
||
let tools: ReviewTools;
|
||
let signer: Awaited<ReturnType<typeof generateKeyPair>>["privateKey"];
|
||
let verifyJwt: McpDeps["verifyJwt"];
|
||
|
||
const call = (who: string, name: string, args: Record<string, unknown> = {}) => tools.call(who, name, args);
|
||
const errOf = async (p: Promise<unknown>): Promise<string> => {
|
||
try {
|
||
await p;
|
||
} catch (e) {
|
||
return (e as Error).message;
|
||
}
|
||
return "NO ERROR";
|
||
};
|
||
const addInvoice = async (extra: Record<string, unknown> = {}) => {
|
||
const r = await db.pool.query(
|
||
`insert into acc_invoices_review (source_message_id, drive_file_id, vendor_name, amount, problem_highlight)
|
||
values ('m1', 'drv1', $1, 100, $2) returning id`,
|
||
[extra.vendor ?? "Vendor A", extra.problem ?? null],
|
||
);
|
||
return (await db.pool.query("select id from acc_manual_review where ref_id = $1", [r.rows[0].id])).rows[0].id as string;
|
||
};
|
||
const addCat = async (feed: string, problem: string | null = null) => {
|
||
await db.pool.query(
|
||
`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, confidence, problem_highlight)
|
||
values ($1, 'run1', now(), '{"account":"Materials"}', 80, $2)`,
|
||
[feed, problem],
|
||
);
|
||
return (await db.pool.query("select id from acc_manual_review where ref_id = $1", [feed])).rows[0].id as string;
|
||
};
|
||
|
||
beforeAll(async () => {
|
||
db = await createTestDb(url!);
|
||
const mk = async (name: string, email: string, extra = "null", active = true) =>
|
||
(await db.pool.query("insert into person (display_name, email, additional_emails, is_active) values ($1, $2, $3, $4) returning id", [name, email, extra === "null" ? null : extra, active])).rows[0].id as string;
|
||
accountant = await mk("Юля", "yulia@khbuild.pro");
|
||
cfo = await mk("Анастасия", "anastasia@khbuild.pro");
|
||
stranger = await mk("Чужой", "x@khbuild.pro");
|
||
kc = await mk("KC", "kc@khbuild.pro", "other@gmail.com; kc.alias@gmail.com");
|
||
await mk("Неактивный", "off@khbuild.pro", "null", false);
|
||
settings = {
|
||
reviewers: [
|
||
{ personId: accountant, roles: ["accountant"] },
|
||
{ personId: cfo, roles: ["accountant", "cfo"] },
|
||
{ personId: kc, roles: ["accountant"] },
|
||
],
|
||
mcp: { enabled: true, issuer: ISSUER, staticTokens: [{ token: TOKEN_A, personId: accountant }, { token: TOKEN_CFO, personId: cfo }, { token: "token-stranger-0123456789", personId: stranger }] },
|
||
};
|
||
tools = new ReviewTools({ pool: db.pool, settings, now: () => NOW });
|
||
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
||
signer = privateKey;
|
||
const jwk = { ...(await exportJWK(publicKey)), kid: "k1", alg: "RS256", use: "sig" };
|
||
verifyJwt = keycloakVerifier(ISSUER, createLocalJWKSet({ keys: [jwk] }));
|
||
});
|
||
afterAll(async () => {
|
||
await db?.drop();
|
||
});
|
||
beforeEach(async () => {
|
||
await db.pool.query("truncate acc_manual_review, acc_invoices_review, acc_invoices_review_original, acc_categorization_review, acc_categorization_review_original, acc_certificates_review, acc_certificates_review_original cascade");
|
||
});
|
||
|
||
describe("чистый слой", () => {
|
||
it("без записи в reviewers доступ запрещён, пустые reviewers - тоже", async () => {
|
||
expect(await errOf(call(stranger, "acc_review_list"))).toContain("Доступ запрещён");
|
||
const empty = new ReviewTools({ pool: db.pool, settings: { reviewers: [] }, now: () => NOW });
|
||
expect(await errOf(empty.call(cfo, "acc_review_list", {}))).toContain("Доступ запрещён");
|
||
});
|
||
|
||
it("список: видимость по ролям, сортировка с проблемой вперёд, данные строк, ссылка на файл", async () => {
|
||
await addInvoice();
|
||
const withProblem = await addCat("f1", "ждёт документ");
|
||
const cfoTask = await addCat("f2");
|
||
await db.pool.query("update acc_manual_review set assignee_role = 'cfo' where id = $1", [cfoTask]);
|
||
const y = (await call(accountant, "acc_review_list")) as { total: number; tasks: Array<Record<string, any>> };
|
||
expect(y.total).toBe(2);
|
||
expect(y.tasks[0].id).toBe(withProblem);
|
||
expect(y.tasks[0].review.feed_txn_id).toBe("f1");
|
||
expect(y.tasks[0].review.run_id).toBe("run1");
|
||
expect(y.tasks[0].review.confidence).toBe(80);
|
||
expect(y.tasks[0].problem_highlight).toBe("ждёт документ");
|
||
expect(y.tasks[1].kind).toBe("invoice");
|
||
expect(y.tasks[1].file_url).toBe("https://drive.google.com/file/d/drv1/view");
|
||
expect(y.tasks.map((t) => t.id)).not.toContain(cfoTask);
|
||
const a = (await call(cfo, "acc_review_list")) as { total: number };
|
||
expect(a.total).toBe(3);
|
||
const onlyCfo = (await call(cfo, "acc_review_list", { role: "cfo" })) as { tasks: Array<{ id: string }> };
|
||
expect(onlyCfo.tasks.map((t) => t.id)).toEqual([cfoTask]);
|
||
expect(await errOf(call(accountant, "acc_review_list", { role: "cfo" }))).toContain("нет роли cfo");
|
||
const k = (await call(cfo, "acc_review_list", { kind: "invoice" })) as { total: number };
|
||
expect(k.total).toBe(1);
|
||
});
|
||
|
||
it("отложенные скрыты, include_snoozed их показывает; выполненные скрыты", async () => {
|
||
const t1 = await addInvoice();
|
||
const t2 = await addInvoice();
|
||
await call(accountant, "acc_review_snooze", { id: t1, until: "2026-11-20" });
|
||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(1);
|
||
expect(((await call(accountant, "acc_review_list", { include_snoozed: true })) as { total: number }).total).toBe(2);
|
||
await call(accountant, "acc_review_done", { id: t2 });
|
||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(0);
|
||
expect(await errOf(call(accountant, "acc_review_snooze", { id: t1, until: "2026-11-01" }))).toContain("в будущем");
|
||
expect(await errOf(call(accountant, "acc_review_snooze", { id: t1, until: "завтра" }))).toContain("until");
|
||
});
|
||
|
||
it("get: задача, строка, original, изменённые поля, ссылка", async () => {
|
||
const t = await addInvoice();
|
||
await call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "Vendor B" } });
|
||
const g = (await call(accountant, "acc_review_get", { id: t })) as Record<string, any>;
|
||
expect(g.review.vendor_name).toBe("Vendor B");
|
||
expect(g.original.vendor_name).toBe("Vendor A");
|
||
expect(g.changed_fields).toEqual(["vendor_name"]);
|
||
expect(g.file_url).toBe("https://drive.google.com/file/d/drv1/view");
|
||
expect(await errOf(call(accountant, "acc_review_get", { id: "not-uuid" }))).toContain("uuid");
|
||
});
|
||
|
||
it("update: белый список, типы, null, запрет чужих колонок", async () => {
|
||
const t = await addInvoice();
|
||
const r = (await call(accountant, "acc_review_update", {
|
||
id: t,
|
||
fields: { invoice_number: "INV-7", invoice_date: "2026-11-01", amount: "250.5", lines: [{ what: "work", sum: 250.5 }], problem_highlight: null },
|
||
})) as { review: Record<string, any> };
|
||
expect(r.review.invoice_number).toBe("INV-7");
|
||
expect(r.review.invoice_date).toBe("2026-11-01");
|
||
expect(r.review.amount).toBe(250.5);
|
||
expect(r.review.lines).toEqual([{ what: "work", sum: 250.5 }]);
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { done: true } }))).toContain("править нельзя");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { drive_file_id: "x" } }))).toContain("править нельзя");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { invoice_date: "01.11.2026" } }))).toContain("YYYY-MM-DD");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { amount: "abc" } }))).toContain("число");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: {} }))).toContain("fields");
|
||
// отказ откатывает всю правку целиком
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "ZZ", amount: "bad" } }))).toContain("amount");
|
||
expect((await db.pool.query("select vendor_name from acc_invoices_review")).rows[0].vendor_name).toBe("Vendor A");
|
||
// категоризация и сертификат
|
||
const c = await addCat("f9");
|
||
const cr = (await call(accountant, "acc_review_update", { id: c, fields: { suggestion: { account: "Tools" }, confidence: 55, problem_highlight: "проверить" } })) as { review: Record<string, any> };
|
||
expect(cr.review.suggestion).toEqual({ account: "Tools" });
|
||
expect(cr.review.confidence).toBe(55);
|
||
expect((await db.pool.query("select problem_highlight from acc_manual_review where id = $1", [c])).rows[0].problem_highlight).toBe("проверить");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: c, fields: { confidence: 101 } }))).toContain("0..100");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: c, fields: { run_id: "x" } }))).toContain("править нельзя");
|
||
await db.pool.query("insert into acc_certificates_review (vendor_name) values ('V')");
|
||
const cert = (await db.pool.query("select id from acc_manual_review where kind = 'certificate'")).rows[0].id;
|
||
const ce = (await call(accountant, "acc_review_update", { id: cert, fields: { expires_on: "2027-01-31", vendor_qbo_id: "q1" } })) as { review: Record<string, any> };
|
||
expect(ce.review.expires_on).toBe("2027-01-31");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: cert, fields: { amount: 1 } }))).toContain("править нельзя");
|
||
});
|
||
|
||
it("чужая роль: нельзя читать, править, закрывать; cfo-задачу категоризации закрывает только cfo", async () => {
|
||
const t = await addCat("f3");
|
||
await db.pool.query("update acc_manual_review set assignee_role = 'cfo' where id = $1", [t]);
|
||
for (const n of ["acc_review_get", "acc_review_done", "acc_review_return", "acc_review_snooze", "acc_review_handoff", "acc_review_update"]) {
|
||
const m = await errOf(call(accountant, n, { id: t, until: "2026-12-01", reason: "r", role: "accountant", fields: { confidence: 1 } }));
|
||
expect(m, n).toContain("роли cfo");
|
||
}
|
||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toMatch(/cfo/);
|
||
await call(cfo, "acc_review_done", { id: t });
|
||
const row = (await db.pool.query("select done, done_by from acc_categorization_review")).rows[0];
|
||
expect(row).toEqual({ done: true, done_by: cfo });
|
||
});
|
||
|
||
it("done: отмечает done и done_by, повтор - ошибка; нет задачи - ошибка", async () => {
|
||
const t = await addInvoice();
|
||
await call(accountant, "acc_review_done", { id: t });
|
||
expect((await db.pool.query("select done, done_by from acc_invoices_review")).rows[0]).toEqual({ done: true, done_by: accountant });
|
||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toContain("уже отмечена");
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { vendor_name: "Q" } }))).toContain("уже отмечена");
|
||
expect(await errOf(call(accountant, "acc_review_done", { id: "00000000-0000-4000-8000-000000000000" }))).toContain("не найдена");
|
||
});
|
||
|
||
it("handoff меняет роль и дописывает комментарий; return возвращает accountant с причиной и снимает snooze", async () => {
|
||
const t = await addCat("f4", "крупная сумма");
|
||
const h = (await call(accountant, "acc_review_handoff", { id: t, role: "cfo", comment: "сумма $6000" })) as { task: Record<string, any> };
|
||
expect(h.task.assignee_role).toBe("cfo");
|
||
expect(h.task.problem_highlight).toBe("крупная сумма | Передано accountant -> cfo: сумма $6000");
|
||
expect((await db.pool.query("select problem_highlight from acc_categorization_review")).rows[0].problem_highlight).toContain("сумма $6000");
|
||
// после передачи accountant задачу больше не видит
|
||
expect(await errOf(call(accountant, "acc_review_get", { id: t }))).toContain("роли cfo");
|
||
expect(await errOf(call(cfo, "acc_review_handoff", { id: t, role: "cfo" }))).toContain("уже назначена");
|
||
expect(await errOf(call(cfo, "acc_review_handoff", { id: t, role: "boss" }))).toContain("role");
|
||
await call(cfo, "acc_review_snooze", { id: t, until: "2026-12-01" });
|
||
const r = (await call(cfo, "acc_review_return", { id: t, reason: "нет документа" })) as { task: Record<string, any> };
|
||
expect(r.task.assignee_role).toBe("accountant");
|
||
expect(r.task.snoozed_until).toBeNull();
|
||
expect(r.task.problem_highlight).toBe("Возвращено: нет документа");
|
||
expect(await errOf(call(cfo, "acc_review_return", { id: t, reason: " " }))).toContain("причина");
|
||
});
|
||
|
||
it("вид без review-таблицы: виден, но правка и закрытие запрещены; handoff/return работают", async () => {
|
||
const t = (await db.pool.query("insert into acc_manual_review (kind, ref_table, ref_id) values ('chargeback', 'acc_chargeback', 'x1') returning id")).rows[0].id;
|
||
expect(((await call(accountant, "acc_review_list")) as { total: number }).total).toBe(1);
|
||
expect(await errOf(call(accountant, "acc_review_update", { id: t, fields: { a: 1 } }))).toContain("не предусмотрена");
|
||
expect(await errOf(call(accountant, "acc_review_done", { id: t }))).toContain("нельзя");
|
||
await call(accountant, "acc_review_return", { id: t, reason: "уточнить" });
|
||
expect((await db.pool.query("select problem_highlight from acc_manual_review where id = $1", [t])).rows[0].problem_highlight).toBe("Возвращено: уточнить");
|
||
});
|
||
});
|
||
|
||
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("одиночные инструменты принимают короткий 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 };
|
||
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();
|
||
registerMcp(app, { pool: db.pool, settings, now: () => NOW, verifyJwt, ...deps });
|
||
const res = await app.inject({ method: "POST", url: "/mcp", headers, payload: payload as object });
|
||
await app.close();
|
||
return res;
|
||
};
|
||
const rpc = (method: string, params?: unknown, id: number | undefined = 1) => ({ jsonrpc: "2.0", id, method, params });
|
||
const bearer = (t: string) => ({ authorization: `Bearer ${t}` });
|
||
const jwt = (claims: Record<string, unknown>, opts: { iss?: string; exp?: string } = {}) =>
|
||
new SignJWT(claims).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(opts.iss ?? ISSUER).setIssuedAt().setExpirationTime(opts.exp ?? "5m").sign(signer);
|
||
|
||
it("без токена и с неверным токеном - 401", async () => {
|
||
const a = await post({}, rpc("initialize"));
|
||
expect(a.statusCode).toBe(401);
|
||
expect(a.headers["www-authenticate"]).toBe("Bearer");
|
||
expect((await post(bearer("wrong-token-wrong-token"), rpc("initialize"))).statusCode).toBe(401);
|
||
expect((await post({ authorization: "Basic abc" }, rpc("initialize"))).statusCode).toBe(401);
|
||
});
|
||
|
||
it("server/discover (2026-07-28): версии, capabilities с расширением UI, serverInfo в _meta, instructions, кэш-подсказки; resultType у всех результатов", async () => {
|
||
const d = (await post(bearer(TOKEN_A), rpc("server/discover", { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }))).json().result;
|
||
expect(d.resultType).toBe("complete");
|
||
expect(d.supportedVersions).toContain("2026-07-28");
|
||
expect(d.capabilities.extensions["io.modelcontextprotocol/ui"].mimeTypes).toContain("text/html;profile=mcp-app");
|
||
expect(d.capabilities.tools.listChanged).toBe(true);
|
||
expect(d._meta["io.modelcontextprotocol/serverInfo"].name).toBe("accounting_automation");
|
||
expect(d.instructions).toContain("acc_review_list");
|
||
expect(d.ttlMs).toBeGreaterThan(0);
|
||
expect(["public", "private"]).toContain(d.cacheScope);
|
||
const l = (await post(bearer(TOKEN_A), rpc("tools/list"))).json().result;
|
||
expect(l).toMatchObject({ resultType: "complete", ttlMs: 60000, cacheScope: "public" });
|
||
const c = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json().result;
|
||
expect(c.resultType).toBe("complete");
|
||
expect(c.ttlMs).toBeUndefined();
|
||
expect((await post({}, rpc("server/discover"))).statusCode).toBe(401);
|
||
});
|
||
|
||
it("initialize, notifications/initialized, ping, tools/list", async () => {
|
||
const i = await post(bearer(TOKEN_A), rpc("initialize", { protocolVersion: "2025-03-26" }));
|
||
expect(i.statusCode).toBe(200);
|
||
expect(i.json().result.serverInfo.name).toBe("accounting_automation");
|
||
expect((await post(bearer(TOKEN_A), { jsonrpc: "2.0", method: "notifications/initialized" })).statusCode).toBe(202);
|
||
expect(((await post(bearer(TOKEN_A), rpc("ping"))).json()).result).toEqual({ resultType: "complete" });
|
||
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_batch", "acc_review_snooze", "acc_invoice_to_approve", "acc_invoice_decide",
|
||
]);
|
||
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(REVIEW_UI_URI);
|
||
expect(REVIEW_UI_URI).toMatch(/^ui:\/\/accounting_automation\/review-table-[0-9a-f]{8}$/);
|
||
expect(i.json().result.capabilities.extensions["io.modelcontextprotocol/ui"].mimeTypes).toContain("text/html;profile=mcp-app");
|
||
expect(i.json().result.capabilities.resources).toBeDefined();
|
||
expect(i.json().result.instructions).toContain("acc_review_list");
|
||
const pr = (await post(bearer(TOKEN_A), rpc("prompts/list"))).json();
|
||
expect(pr.result.prompts[0].name).toBe("today");
|
||
expect((await post(bearer(TOKEN_A), rpc("prompts/get", { name: "today" }))).json().result.messages[0].content.text).toContain("acc_review_list");
|
||
const custom = (await post(bearer(TOKEN_A), rpc("initialize", {}), { instructions: "СВОИ ИНСТРУКЦИИ" })).json();
|
||
expect(custom.result.instructions).toBe("СВОИ ИНСТРУКЦИИ");
|
||
expect((await post(bearer(TOKEN_A), rpc("nope"))).json().error.code).toBe(-32601);
|
||
});
|
||
|
||
it("tools/call со статическим токеном: список, ошибка доступа - isError", async () => {
|
||
await addInvoice();
|
||
const ok = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_list", arguments: {} }))).json();
|
||
expect(ok.result.isError).toBeUndefined();
|
||
expect(ok.result.structuredContent.total).toBe(1);
|
||
expect(ok.result._meta.ui.resourceUri).toBe(REVIEW_UI_URI);
|
||
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("Доступ запрещён");
|
||
const bad = (await post(bearer(TOKEN_A), rpc("tools/call", { name: "acc_review_get", arguments: { id: "x" } }))).json();
|
||
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: REVIEW_UI_URI, mimeType: "text/html;profile=mcp-app" });
|
||
const read = (await post(bearer(TOKEN_A), rpc("resources/read", { uri: REVIEW_UI_URI }))).json();
|
||
expect(read.result.contents[0].mimeType).toBe("text/html;profile=mcp-app");
|
||
expect(read.result.contents[0].text).toContain("acc_review_batch");
|
||
expect(read.result.contents[0]._meta.ui.csp).toBeDefined();
|
||
expect(read.result.contents[0].text).toContain("ui/notifications/initialized");
|
||
expect((await post(bearer(TOKEN_A), rpc("resources/read", { uri: "ui://accounting_automation/review-table" }))).json().result.contents[0].mimeType).toBe("text/html;profile=mcp-app");
|
||
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("журнал 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("автоочистка журнала: остаются последние N записей", async () => {
|
||
await db.pool.query("delete from acc_mcp_log");
|
||
await db.pool.query("insert into acc_mcp_log (method, ok) select 'tools/call', true from generate_series(1, 25)");
|
||
expect(await pruneMcpLog(db.pool, 10)).toBe(15);
|
||
const { rows } = await db.pool.query("select count(*)::int as n, min(id)::int as lo, max(id)::int as hi from acc_mcp_log");
|
||
expect(rows[0].n).toBe(10);
|
||
expect(rows[0].hi - rows[0].lo).toBe(9);
|
||
});
|
||
|
||
it("GET /mcp: поток SSE шлёт tools/list_changed при подключении; без токена 401, без SSE-Accept 405", async () => {
|
||
const app = Fastify();
|
||
registerMcp(app, { pool: db.pool, settings, now: () => NOW, verifyJwt });
|
||
expect((await app.inject({ method: "GET", url: "/mcp" })).statusCode).toBe(405);
|
||
expect((await app.inject({ method: "GET", url: "/mcp", headers: { accept: "text/event-stream" } })).statusCode).toBe(401);
|
||
await app.listen({ port: 0, host: "127.0.0.1" });
|
||
const port = (app.server.address() as { port: number }).port;
|
||
const ac = new AbortController();
|
||
const r = await fetch(`http://127.0.0.1:${port}/mcp`, { headers: { accept: "text/event-stream", ...bearer(TOKEN_A) }, signal: ac.signal });
|
||
expect(r.status).toBe(200);
|
||
expect(r.headers.get("content-type")).toContain("text/event-stream");
|
||
const chunk = new TextDecoder().decode((await r.body!.getReader().read()).value);
|
||
expect(chunk).toContain("notifications/tools/list_changed");
|
||
ac.abort();
|
||
await app.close();
|
||
expect((await post({}, rpc("initialize"))).statusCode).toBe(401);
|
||
expect((await post(bearer(TOKEN_A), rpc("initialize"))).json().result.capabilities.tools.listChanged).toBe(true);
|
||
});
|
||
|
||
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(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);
|
||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro", email_verified: false })), rpc("tools/call", call))).statusCode).toBe(401);
|
||
expect((await post(bearer(await jwt({})), rpc("tools/call", call))).statusCode).toBe(401);
|
||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro" }, { iss: "https://evil.test/realms/x" })), rpc("tools/call", call))).statusCode).toBe(401);
|
||
expect((await post(bearer(await jwt({ email: "kc@khbuild.pro" }, { exp: "-1m" })), rpc("tools/call", call))).statusCode).toBe(401);
|
||
const other = await generateKeyPair("RS256");
|
||
const forged = await new SignJWT({ email: "kc@khbuild.pro" }).setProtectedHeader({ alg: "RS256", kid: "k1" }).setIssuer(ISSUER).setExpirationTime("5m").sign(other.privateKey);
|
||
expect((await post(bearer(forged), rpc("tools/call", call))).statusCode).toBe(401);
|
||
});
|
||
|
||
it("mcp.enabled=false: маршрут не регистрируется", async () => {
|
||
const r = await post(bearer(TOKEN_A), rpc("ping"), { settings: { ...settings, mcp: { ...settings.mcp, enabled: false } } });
|
||
expect(r.statusCode).toBe(404);
|
||
});
|
||
});
|
||
});
|