MCP: server/discover (2026-07-28), resultType и кэш-подсказки; таблица передаёт выделение в контекст Claude (ui/update-model-context) и кнопка «Спросить Claude про выбранные» (ui/message)
All checks were successful
ci / deploy (push) Successful in 2m42s
ci / test (push) Successful in 40s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 19:44:53 +03:00
parent 4b5e0444b9
commit 053b5018c0
3 changed files with 60 additions and 6 deletions

View File

@@ -105,7 +105,7 @@ td.n,th.n{text-align:right;white-space:nowrap} tr.p td{background:var(--hl)}
.prob{color:var(--bad)} .acts{white-space:nowrap;display:flex;gap:4px}
.empty{color:var(--mut);padding:14px 4px}
</style></head><body><div class="wrap">
<div class="bar"><button id="done" class="pri" disabled>Done выбранные</button><button id="deleg" disabled>Delegate выбранные</button><button id="snz" disabled>Snooze 1д</button><span class="st" id="st"></span></div>
<div class="bar"><button id="done" class="pri" disabled>Done выбранные</button><button id="deleg" disabled>Delegate выбранные</button><button id="snz" disabled>Snooze 1д</button><button id="ask" disabled>Спросить Claude про выбранные</button><span class="st" id="st"></span></div>
<div id="root"><div class="empty">Загрузка…</div></div></div>
<script>
(function(){
@@ -129,7 +129,17 @@ function render(){
});
root.innerHTML=h+'</tbody></table>';updBtns();size();
}
function updBtns(){var n=selIds().length;["done","deleg","snz"].forEach(function(i){document.getElementById(i).disabled=!n;});}
function selText(){
var byId={};rows.forEach(function(r){byId[r.id]=r;});
var ids=selIds().filter(function(i){return byId[i];});
if(!ids.length)return "В таблице очереди бухгалтерии ничего не выбрано.";
return "Пользователь отметил в таблице очереди бухгалтерии "+ids.length+" задач: "+ids.map(function(i){var r=byId[i];return i.slice(0,8)+" ("+[r.kind,r.who,r.amount,r.what].filter(Boolean).join(", ")+")";}).join("; ")+".";
}
function pushCtx(){
var ids=selIds();
req("ui/update-model-context",{content:[{type:"text",text:selText()}],structuredContent:{selected_ids:ids.map(function(i){return i.slice(0,8);})}}).catch(function(){});
}
function updBtns(){var n=selIds().length;["done","deleg","snz","ask"].forEach(function(i){document.getElementById(i).disabled=!n;});}
function size(){send({method:"ui/notifications/size-changed",params:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}});}
function tomorrow(){return new Date(Date.now()+24*3600*1000).toISOString();}
function run(ids,action){
@@ -140,7 +150,7 @@ function run(ids,action){
var sc=(r&&r.structuredContent)||{};var okIds={};(sc.results||[]).forEach(function(x){if(x.ok)okIds[x.id]=1;});
var bad=(sc.results||[]).filter(function(x){return !x.ok;});
rows=rows.filter(function(x){return !okIds[x.id];});ids.forEach(function(i){delete sel[i];});
render();status(Object.keys(okIds).length+" выполнено"+(bad.length?", ошибок: "+bad.length+" ("+bad[0].error+")":""));
render();pushCtx();status(Object.keys(okIds).length+" выполнено"+(bad.length?", ошибок: "+bad.length+" ("+bad[0].error+")":""));
}).catch(function(e){status("Ошибка: "+((e&&e.message)||e));});
}
document.addEventListener("click",function(e){
@@ -149,8 +159,9 @@ document.addEventListener("click",function(e){
if(t.id==="done")run(selIds(),"done");
if(t.id==="deleg")run(selIds(),"handoff");
if(t.id==="snz")run(selIds(),"snooze");
if(t.id==="ask")req("ui/message",{role:"user",content:{type:"text",text:selText()+" Расскажи подробнее про эти задачи и предложи, что с ними сделать."}}).catch(function(e){status("Не удалось отправить в чат: "+((e&&e.message)||e));});
});
document.addEventListener("change",function(e){var t=e.target;if(t&&t.dataset&&t.dataset.sel){sel[t.dataset.sel]=t.checked;updBtns();}});
document.addEventListener("change",function(e){var t=e.target;if(t&&t.dataset&&t.dataset.sel){sel[t.dataset.sel]=t.checked;updBtns();pushCtx();}});
window.addEventListener("message",function(e){
var m=e.data;if(!m||m.jsonrpc!=="2.0")return;
if(m.id!=null&&pending[m.id]){var p=pending[m.id];delete pending[m.id];if(m.error)p.rej(new Error(m.error.message||"error"));else p.res(m.result);return;}

View File

@@ -269,12 +269,30 @@ d("MCP бухгалтерии (временная БД)", () => {
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({});
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",

View File

@@ -478,7 +478,29 @@ export function instructionsFromFile(text: string): string {
const rpcError = (id: unknown, code: number, message: string): Json => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
/** Обрабатывает одно JSON-RPC сообщение от аутентифицированного человека; null - уведомление (ответа нет). */
const SUPPORTED_VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"];
const SERVER_INFO = { name: "accounting_automation", version: "0.1.0" };
const CAPABILITIES = { tools: { listChanged: true }, resources: {}, prompts: {}, extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [REVIEW_UI_MIME] } } };
/** Подсказки кэширования (2026-07-28) для списков, discover и ресурсов; во всех результатах resultType: "complete". */
const CACHE_HINTS: Record<string, { ttlMs: number; cacheScope: "public" | "private" }> = {
"server/discover": { ttlMs: 60_000, cacheScope: "public" },
"tools/list": { ttlMs: 60_000, cacheScope: "public" },
"prompts/list": { ttlMs: 60_000, cacheScope: "public" },
"resources/list": { ttlMs: 60_000, cacheScope: "public" },
"resources/read": { ttlMs: 3_600_000, cacheScope: "public" }, // URI с хэшем содержимого
};
export async function handleMcpMessage(tools: ReviewTools, personId: string, msg: Json, instructions: string = DEFAULT_INSTRUCTIONS): Promise<Json | null> {
const res = await handleMcpInner(tools, personId, msg, instructions);
if (res && res.result && typeof res.result === "object") {
const hint = CACHE_HINTS[String(msg?.method)];
res.result = { resultType: "complete", ...(res.result as Json), ...(hint ?? {}) };
}
return res;
}
async function handleMcpInner(tools: ReviewTools, personId: string, msg: Json, instructions: string): Promise<Json | null> {
const id = msg?.id;
const method = msg?.method;
if (typeof method !== "string") return rpcError(id, -32600, "invalid request");
@@ -486,7 +508,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: {}, extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [REVIEW_UI_MIME] } } }, serverInfo: { name: "accounting_automation", version: "0.1.0" }, instructions } };
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: CAPABILITIES, serverInfo: SERVER_INFO, instructions } };
}
case "ping":
return { jsonrpc: "2.0", id, result: {} };
@@ -511,6 +533,9 @@ export async function handleMcpMessage(tools: ReviewTools, personId: string, msg
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 "server/discover":
// версия 2026-07-28 (без initialize): Claude вызывает именно его
return { jsonrpc: "2.0", id, result: { supportedVersions: SUPPORTED_VERSIONS, capabilities: CAPABILITIES, _meta: { "io.modelcontextprotocol/serverInfo": SERVER_INFO }, instructions } };
case "tools/list":
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
case "tools/call": {