MCP Apps: extensions в initialize, _meta.ui в результате вызова, CSP ресурса, URI с хэшем, надёжное рукопожатие ui/initialize (initialized с таймаутом)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,8 @@
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
export const REVIEW_UI_URI = "ui://accounting_automation/review-table";
|
||||
/** Прежний URI (оставлен рабочим: клиенты могут держать его в кэше). */
|
||||
export const REVIEW_UI_URI_LEGACY = "ui://accounting_automation/review-table";
|
||||
export const REVIEW_UI_MIME = "text/html;profile=mcp-app";
|
||||
|
||||
export interface ReviewRow {
|
||||
@@ -156,6 +157,15 @@ window.addEventListener("message",function(e){
|
||||
if(m.method==="ui/notifications/tool-result"){var sc=(m.params&&m.params.structuredContent)||{};rows=sc.rows||[];sel={};render();status("Всего в очереди: "+(sc.total!=null?sc.total:rows.length));}
|
||||
if(m.id!=null&&m.method==="ui/resource-teardown"){send({id:m.id,result:{}});}
|
||||
});
|
||||
req("ui/initialize",{protocolVersion:"2026-01-26",capabilities:{},clientInfo:{name:"accounting_automation review table",version:"0.1.0"},appCapabilities:{}}).then(function(){send({method:"ui/notifications/initialized"});}).catch(function(){});
|
||||
var inited=false;
|
||||
function ready(){if(inited)return;inited=true;send({method:"ui/notifications/initialized"});size();}
|
||||
var info={name:"accounting_automation review table",version:"0.1.0"};
|
||||
req("ui/initialize",{protocolVersion:"2026-01-26",appInfo:info,clientInfo:info,appCapabilities:{}}).then(ready).catch(ready);
|
||||
setTimeout(ready,1500);
|
||||
})();
|
||||
</script></body></html>`;
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/** URI с хэшем содержимого: изменённое приложение не подменяется устаревшей копией из кэша клиента. */
|
||||
export const REVIEW_UI_URI = `ui://accounting_automation/review-table-${createHash("sha256").update(REVIEW_UI_HTML).digest("hex").slice(0, 8)}`;
|
||||
|
||||
@@ -3,6 +3,7 @@ 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();
|
||||
@@ -281,7 +282,9 @@ d("MCP бухгалтерии (временная БД)", () => {
|
||||
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("ui://accounting_automation/review-table");
|
||||
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();
|
||||
@@ -297,6 +300,7 @@ d("MCP бухгалтерии (временная БД)", () => {
|
||||
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();
|
||||
@@ -308,10 +312,13 @@ d("MCP бухгалтерии (временная БД)", () => {
|
||||
|
||||
it("resources: интерактивная таблица очереди отдаётся как ui:// ресурс", async () => {
|
||||
const list = (await post(bearer(TOKEN_A), rpc("resources/list"))).json();
|
||||
expect(list.result.resources[0]).toMatchObject({ uri: "ui://accounting_automation/review-table", mimeType: "text/html;profile=mcp-app" });
|
||||
const read = (await post(bearer(TOKEN_A), rpc("resources/read", { uri: "ui://accounting_automation/review-table" }))).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);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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, rowsToMarkdown, toRow } from "./mcp-ui.js";
|
||||
import { REVIEW_UI_HTML, REVIEW_UI_MIME, REVIEW_UI_URI, REVIEW_UI_URI_LEGACY, rowsToMarkdown, toRow } from "./mcp-ui.js";
|
||||
import type { AccountingSettings } from "./settings.js";
|
||||
|
||||
/**
|
||||
@@ -389,7 +389,7 @@ export const TOOLS: { name: string; description: string; inputSchema: Json; anno
|
||||
{
|
||||
name: "acc_review_list",
|
||||
annotations: { readOnlyHint: true, openWorldHint: false, title: "Очередь разбора бухгалтерии" },
|
||||
_meta: { ui: { resourceUri: REVIEW_UI_URI }, "ui/resourceUri": REVIEW_UI_URI },
|
||||
_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({
|
||||
@@ -486,7 +486,7 @@ 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: { listChanged: true }, resources: {}, prompts: {} }, serverInfo: { name: "accounting_automation", version: "0.1.0" }, instructions } };
|
||||
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: { tools: { listChanged: true }, resources: {}, prompts: {}, extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [REVIEW_UI_MIME] } } }, serverInfo: { name: "accounting_automation", version: "0.1.0" }, instructions } };
|
||||
}
|
||||
case "ping":
|
||||
return { jsonrpc: "2.0", id, result: {} };
|
||||
@@ -508,8 +508,8 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
|
||||
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) return rpcError(id, -32002, `ресурс не найден: ${String(uri)}`);
|
||||
return { jsonrpc: "2.0", id, result: { contents: [{ uri: REVIEW_UI_URI, mimeType: REVIEW_UI_MIME, text: REVIEW_UI_HTML, _meta: { ui: { prefersBorder: true } } }] } };
|
||||
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 "tools/list":
|
||||
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
|
||||
@@ -521,7 +521,7 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
|
||||
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 } } };
|
||||
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)}`}`);
|
||||
|
||||
Reference in New Issue
Block a user