MCP: короткий id во всех инструментах, журнал вызовов acc_mcp_log и представление acc_mcp_error_rate, расширены instructions
Some checks failed
ci / test (push) Failing after 39s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 11:36:17 +03:00
parent 6c061929a1
commit de20e0400f
4 changed files with 111 additions and 17 deletions

View File

@@ -145,10 +145,9 @@ export class ReviewTools {
return [...roles];
}
private id(a: Json): string {
const v = a.id;
if (typeof v !== "string" || !UUID.test(v)) throw new McpToolError("нужно поле id (uuid задачи из acc_review_list)");
return v;
/** id задачи: полный uuid или первые 8+ символов из таблицы списка. */
private async id(a: Json): Promise<string> {
return this.resolveId(a.id);
}
/** Задача под блокировкой + проверка роли. */
@@ -206,7 +205,7 @@ export class ReviewTools {
/** acc_review_get */
async get(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = this.id(a);
const id = await this.id(a);
const t = (await this.d.pool.query("select * from acc_manual_review where id = $1", [id])).rows[0] as Task | undefined;
if (!t) throw new McpToolError("Задача не найдена (возможно, уже завершена и удалена из очереди).");
if (!roles.includes(t.assignee_role as ReviewRole)) throw new McpToolError(`Задача назначена роли ${t.assignee_role}: у вас нет этой роли.`);
@@ -226,7 +225,7 @@ export class ReviewTools {
/** acc_review_update */
async update(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = this.id(a);
const id = await this.id(a);
const fields = a.fields;
if (!fields || typeof fields !== "object" || Array.isArray(fields) || Object.keys(fields).length === 0) throw new McpToolError("fields: непустой объект {поле: значение}");
return withTx(this.d.pool, async (c) => {
@@ -258,7 +257,7 @@ export class ReviewTools {
/** acc_review_done */
async done(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = this.id(a);
const id = await this.id(a);
return withTx(this.d.pool, async (c) => {
const t = await this.lockTask(c, roles, id, "закрытия");
const m = metaOf(t);
@@ -280,7 +279,7 @@ export class ReviewTools {
/** acc_review_handoff */
async handoff(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = this.id(a);
const id = await this.id(a);
if (!ROLES.includes(a.role as ReviewRole)) throw new McpToolError("role: accountant или cfo");
if (a.comment !== undefined && typeof a.comment !== "string") throw new McpToolError("comment: строка");
return withTx(this.d.pool, async (c) => {
@@ -299,7 +298,7 @@ export class ReviewTools {
/** acc_review_return */
async return(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = this.id(a);
const id = await this.id(a);
if (typeof a.reason !== "string" || !a.reason.trim()) throw new McpToolError("reason: нужна причина возврата");
const reason: string = a.reason.trim();
return withTx(this.d.pool, async (c) => {
@@ -314,7 +313,7 @@ export class ReviewTools {
/** acc_review_snooze */
async snooze(personId: string, a: Json): Promise<Json> {
const roles = this.rolesOf(personId);
const id = this.id(a);
const id = await this.id(a);
const until = typeof a.until === "string" ? new Date(a.until) : null;
if (!until || Number.isNaN(until.getTime())) throw new McpToolError("until: дата или время в формате ISO (2026-11-20 или 2026-11-20T09:00:00Z)");
if (until <= this.now()) throw new McpToolError("until должно быть в будущем.");
@@ -328,9 +327,9 @@ export class ReviewTools {
/** Полный uuid или префикс (от 8 символов) id задачи, как в таблице списка. */
private async resolveId(v: unknown): Promise<string> {
if (typeof v !== "string") throw new McpToolError("id: строка");
if (typeof v !== "string") throw new McpToolError("нужно поле id: первые 8 символов (или полный uuid) задачи из таблицы acc_review_list");
if (UUID.test(v)) return v;
if (!/^[0-9a-f]{8,}$/i.test(v)) throw new McpToolError("id: uuid или первые 8+ символов uuid из таблицы");
if (!/^[0-9a-f]{8,}$/i.test(v)) throw new McpToolError("id: первые 8 символов (или полный uuid) задачи из таблицы acc_review_list");
const { rows } = await this.d.pool.query("select id from acc_manual_review where id::text like $1 limit 2", [`${v.toLowerCase()}%`]);
if (rows.length === 0) throw new McpToolError("Задача не найдена (возможно, уже завершена).");
if (rows.length > 1) throw new McpToolError("Префикс id неоднозначен: укажите больше символов.");
@@ -384,7 +383,7 @@ export class ReviewTools {
const str = { type: "string" };
const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false });
const idP = { type: "string", description: "id задачи (uuid из acc_review_list)" };
const idP = { type: "string", description: "id задачи: первые 8 символов из таблицы acc_review_list (или полный uuid), как есть" };
export const TOOLS: { name: string; description: string; inputSchema: Json; annotations?: Json; _meta?: Json }[] = [
{
@@ -468,7 +467,7 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno
/** Встроенный текст инструкций (копия: docs/.../p-mcp-instructions.md; сервис подставляет файл, если он доступен). */
export const DEFAULT_INSTRUCTIONS =
"Коннектор очереди ручного разбора бухгалтерии KH Build. На вопросы вроде «что у нас на сегодня», «что по делам», «что горит» кроме календаря и других источников обязательно вызови acc_review_list и покажи таблицу очереди как есть; затем дай общую сводку. Действия над несколькими задачами - одним вызовом acc_review_batch. acc_review_done - только после подтверждения пользователя и проводки в QuickBooks.";
"Коннектор очереди ручного разбора бухгалтерии KH Build. На вопросы вроде «что у нас на сегодня», «что по делам», «что горит» кроме календаря и других источников обязательно вызови acc_review_list и покажи таблицу очереди как есть; затем дай общую сводку. Действия над несколькими задачами - одним вызовом acc_review_batch. acc_review_done - только после подтверждения пользователя и проводки в QuickBooks. В любых инструментах id задачи - 8 символов из таблицы, как есть, полный uuid не нужен и в других источниках (SQL, Supabase) его искать не надо.";
/** Блок «## Инструкции» из файла p-mcp-instructions.md. */
export function instructionsFromFile(text: string): string {
@@ -539,6 +538,43 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
}
}
/** Классификация текста ошибки инструмента для журнала. */
function errorKind(text: string): string {
if (text.startsWith("Доступ запрещён") || text.includes("нужна роль") || text.includes("Нужна роль") || text.includes("У вас нет роли")) return "forbidden";
if (text.startsWith("Внутренняя ошибка")) return "internal";
if (text.includes("не найдена")) return "not_found";
return "invalid_args";
}
const clip = (v: unknown, n = 2000): unknown => {
const t = JSON.stringify(v ?? null);
return t.length > n ? { truncated: t.slice(0, n) } : v ?? null;
};
/** Пишет строку журнала вызова MCP; сбой журнала никогда не ломает ответ. */
async function logCall(pool: McpDeps["pool"], personId: string, msg: Json, res: Json | null, ms: number): Promise<void> {
try {
const method = String(msg?.method ?? "?");
if (method.startsWith("notifications/") || method === "ping") return;
const p = (msg.params ?? {}) as { name?: string; arguments?: Json };
const r = (res?.result ?? {}) as Json;
const sc = (r.structuredContent ?? {}) as Json;
const errText = res?.error ? String((res.error as Json).message) : r.isError ? String(((r.content as Json[] | undefined)?.[0] as Json | undefined)?.text ?? "") : null;
const failed = typeof sc.error_count === "number" ? sc.error_count : null;
const ok = !errText;
const kind = !errText ? (failed ? "partial" : null) : res?.error ? (method === "tools/call" ? "unknown_tool" : "rpc") : errorKind(errText);
const errs = failed ? ((sc.results as Json[]) ?? []).filter((x) => !x.ok).map((x) => String(x.error)).slice(0, 5).join(" | ") : errText;
await pool.query(
`insert into acc_mcp_log (person_id, method, tool, args, ok, error_kind, error, items_total, items_failed, duration_ms, result_bytes)
values ($1,$2,$3,$4::jsonb,$5,$6,$7,$8,$9,$10,$11)`,
[personId, method, method === "tools/call" ? (p.name ?? null) : null, JSON.stringify(method === "tools/call" ? clip(p.arguments) : clip(msg.params, 500)), ok, kind, errs ? errs.slice(0, 1000) : null,
Array.isArray(p.arguments?.actions) ? (p.arguments?.actions as unknown[]).length : null, failed, Math.round(ms), res ? JSON.stringify(res).length : 0],
);
} catch {
/* журнал не критичен */
}
}
export interface McpDeps extends ReviewDeps {
/** Текст инструкций для Claude (поле instructions при initialize). */
instructions?: string;
@@ -568,12 +604,18 @@ export function registerMcp(app: FastifyInstance, deps: McpDeps): ReviewTools {
return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" });
}
const body = req.body as unknown;
const handle = async (m: Json): Promise<Json | null> => {
const t0 = Date.now();
const res = await handleMcpMessage(tools, personId, m, deps.instructions);
await logCall(deps.pool, personId, m, res, Date.now() - t0);
return res;
};
if (Array.isArray(body)) {
const out = (await Promise.all(body.map((m) => handleMcpMessage(tools, personId, m as Json, deps.instructions)))).filter((x): x is Json => x !== null);
const out = (await Promise.all(body.map((m) => handle(m as Json)))).filter((x): x is Json => x !== null);
return out.length ? reply.send(out) : reply.code(202).send();
}
if (!body || typeof body !== "object") return reply.code(400).send(rpcError(null, -32700, "parse error"));
const res = await handleMcpMessage(tools, personId, body as Json, deps.instructions);
const res = await handle(body as Json);
return res ? reply.send(res) : reply.code(202).send();
});
app.get("/mcp", async (_req, reply) => reply.code(405).header("Allow", "POST").send({ error: "используйте POST" }));