MCP: instructions для Claude (что у нас на сегодня -> очередь бухгалтерии) и промпт today; текст в p-mcp-instructions.md
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
# Инструкции MCP accounting_automation для Claude сотрудника
|
||||
|
||||
Подключается как поле `instructions` при инициализации MCP: Claude получает их вместе с описанием инструментов, как только коннектор подключён.
|
||||
|
||||
## Инструкции
|
||||
|
||||
Это коннектор очереди ручного разбора бухгалтерии KH Build (операции банка, инвойсы, сертификаты, которые автомат не смог или не должен закрывать сам).
|
||||
|
||||
Когда пользователь спрашивает «что у нас на сегодня», «что по делам», «что нового», «чем заняться», «что горит», «планы на день» и подобное:
|
||||
- сначала посмотри календарь и остальные доступные источники, как обычно;
|
||||
- затем обязательно вызови acc_review_list и покажи очередь разбора бухгалтерии таблицей как есть, без пересказа построчно;
|
||||
- в итоге дай общую сводку: события дня, в очереди столько-то задач, из них столько с проблемой, самые срочные.
|
||||
|
||||
Когда пользователь просит показать очередь, задачи бухгалтерии или разбор:
|
||||
- вызови acc_review_list (по умолчанию до 20 задач); не вызывай acc_review_get по каждой задаче, только когда нужны подробности по одной;
|
||||
- действия над несколькими задачами выполняй одним вызовом acc_review_batch, а не по одной задаче;
|
||||
- acc_review_done ставь только после явного подтверждения пользователя и, для банковской операции, после проводки в QuickBooks;
|
||||
- id задач в таблице короткие (8 символов), в acc_review_batch можно передавать их как есть.
|
||||
|
||||
Если у пользователя нет доступа к очереди (ошибка «Доступ запрещён»), не пытайся обойти: скажи об этом одной фразой.
|
||||
@@ -16,6 +16,8 @@ export interface ApiDeps {
|
||||
pool: Pool;
|
||||
settings: Pick<AccountingSettings, "http" | "reviewers" | "mcp">;
|
||||
jobs: JobHandlers;
|
||||
/** Текст instructions для MCP (из p-mcp-instructions.md); не задан - встроенный. */
|
||||
mcpInstructions?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,7 +80,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
scopes_supported: ["openid", "email", "profile"],
|
||||
};
|
||||
});
|
||||
registerMcp(app, { pool: deps.pool, settings: deps.settings });
|
||||
registerMcp(app, { pool: deps.pool, settings: deps.settings, instructions: deps.mcpInstructions });
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createLogger, createPool, itNotify, loadServiceSettings } from "khb_common";
|
||||
import { runCategorization } from "./categorize.js";
|
||||
import { makeClaudeRunner } from "./claude-runner.js";
|
||||
@@ -6,6 +7,7 @@ import { runFinalize } from "./finalize.js";
|
||||
import { GmailClient } from "./gmail.js";
|
||||
import { GoogleAuth } from "./google.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { instructionsFromFile } from "./mcp.js";
|
||||
import { runInvoiceIngest } from "./invoices-mail.js";
|
||||
import { makePromptLoader } from "./prompt-loader.js";
|
||||
import { accountingSchema } from "./settings.js";
|
||||
@@ -44,9 +46,17 @@ async function nonWorkdays(): Promise<ReadonlySet<string>> {
|
||||
return new Set(rows.map((r) => r.d as string));
|
||||
}
|
||||
|
||||
let mcpInstructions: string | undefined;
|
||||
try {
|
||||
mcpInstructions = instructionsFromFile(readFileSync(`${process.env.KHB_REPO_ROOT ?? process.cwd()}/docs/proposed/modules/quickbooks_bookkeeper/p-mcp-instructions.md`, "utf8"));
|
||||
} catch (e) {
|
||||
log.warn({ err: String(e) }, "p-mcp-instructions.md недоступен, используются встроенные инструкции MCP");
|
||||
}
|
||||
|
||||
const app = buildApi({
|
||||
pool,
|
||||
settings: s,
|
||||
mcpInstructions,
|
||||
jobs: {
|
||||
"invoices-mail": async () => {
|
||||
if (!auth || !drive || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта, rootFolderId)");
|
||||
|
||||
@@ -275,6 +275,12 @@ d("MCP бухгалтерии (временная БД)", () => {
|
||||
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("ui://accounting_automation/review-table");
|
||||
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);
|
||||
});
|
||||
|
||||
|
||||
@@ -466,10 +466,20 @@ 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.";
|
||||
|
||||
/** Блок «## Инструкции» из файла 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 - уведомление (ответа нет). */
|
||||
export async function handleMcpMessage(tools: ReviewTools, personId: string, msg: Json): Promise<Json | null> {
|
||||
export async function handleMcpMessage(tools: ReviewTools, personId: string, msg: Json, instructions: string = DEFAULT_INSTRUCTIONS): Promise<Json | null> {
|
||||
const id = msg?.id;
|
||||
const method = msg?.method;
|
||||
if (typeof method !== "string") return rpcError(id, -32600, "invalid request");
|
||||
@@ -477,10 +487,24 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
|
||||
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: {}, resources: {} }, serverInfo: { name: "accounting_automation", version: "0.1.0" } } };
|
||||
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: { tools: {}, resources: {}, prompts: {} }, serverInfo: { name: "accounting_automation", version: "0.1.0" }, 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": {
|
||||
@@ -516,6 +540,8 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
|
||||
}
|
||||
|
||||
export interface McpDeps extends ReviewDeps {
|
||||
/** Текст инструкций для Claude (поле instructions при initialize). */
|
||||
instructions?: string;
|
||||
settings: Pick<AccountingSettings, "reviewers" | "mcp">;
|
||||
/** Проверка JWT Keycloak (для тестов - с локальным JWKS). */
|
||||
verifyJwt?: JwtVerifier;
|
||||
@@ -543,11 +569,11 @@ export function registerMcp(app: FastifyInstance, deps: McpDeps): ReviewTools {
|
||||
}
|
||||
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);
|
||||
const out = (await Promise.all(body.map((m) => handleMcpMessage(tools, personId, m as Json, deps.instructions)))).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);
|
||||
const res = await handleMcpMessage(tools, personId, body as Json, deps.instructions);
|
||||
return res ? reply.send(res) : reply.code(202).send();
|
||||
});
|
||||
app.get("/mcp", async (_req, reply) => reply.code(405).header("Allow", "POST").send({ error: "используйте POST" }));
|
||||
|
||||
Reference in New Issue
Block a user