MCP: поток GET /mcp (SSE) с notifications/tools/list_changed при подключении, capabilities.tools.listChanged
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -367,6 +367,25 @@ d("MCP бухгалтерии (временная БД)", () => {
|
||||
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: {} };
|
||||
|
||||
@@ -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: {}, 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: {} }, serverInfo: { name: "accounting_automation", version: "0.1.0" }, instructions } };
|
||||
}
|
||||
case "ping":
|
||||
return { jsonrpc: "2.0", id, result: {} };
|
||||
@@ -629,6 +629,33 @@ export function registerMcp(app: FastifyInstance, deps: McpDeps): ReviewTools {
|
||||
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" }));
|
||||
// Поток сервер->клиент (Streamable HTTP, GET + SSE): при каждом подключении шлём tools/list_changed.
|
||||
// После деплоя сервис перезапускается, клиент переподключает поток, получает уведомление и сам перечитывает список инструментов.
|
||||
const streams = new Set<() => void>();
|
||||
app.addHook("onClose", async () => {
|
||||
for (const close of [...streams]) close();
|
||||
});
|
||||
app.get("/mcp", async (req, reply) => {
|
||||
if (!String(req.headers.accept ?? "").includes("text/event-stream")) return reply.code(405).header("Allow", "POST").send({ error: "используйте POST (или GET с Accept: text/event-stream)" });
|
||||
try {
|
||||
await authenticate(req.headers.authorization);
|
||||
} catch (e) {
|
||||
const status = e instanceof McpAuthError ? e.status : 401;
|
||||
if (status === 401) void reply.header("WWW-Authenticate", challenge);
|
||||
return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" });
|
||||
}
|
||||
reply.hijack();
|
||||
const raw = reply.raw;
|
||||
raw.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive", "X-Accel-Buffering": "no" });
|
||||
raw.write(`event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })}\n\n`);
|
||||
const ping = setInterval(() => raw.write(": ping\n\n"), 20000);
|
||||
const close = (): void => {
|
||||
clearInterval(ping);
|
||||
streams.delete(close);
|
||||
if (!raw.writableEnded) raw.end();
|
||||
};
|
||||
streams.add(close);
|
||||
raw.on("close", close);
|
||||
});
|
||||
return tools;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user