Files
khb_microservices/packages/todo_service/src/mcp.ts
2026-10-29 11:08:54 +03:00

113 lines
8.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { HttpError, type TodoCore } from "./core.js";
import type { Caller } from "./access.js";
/** MCP (Streamable HTTP, без сессий): тонкий адаптер над тем же ядром, что и REST. Реализация JSON-RPC 2.0 вручную. */
type Json = Record<string, unknown>;
interface Tool {
name: string;
description: string;
inputSchema: Json;
run: (core: TodoCore, caller: Caller, a: Json) => Promise<unknown>;
}
const str = { type: "string" };
const strArr = { type: "array", items: { type: "string" } };
const kind = { type: "string", enum: ["todo", "reminder", "control"] };
const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false });
const s = (a: Json, k: string): string | undefined => (typeof a[k] === "string" ? (a[k] as string) : undefined);
const need = (a: Json, k: string): string => {
const v = s(a, k);
if (!v) throw new HttpError(400, `нужно поле ${k}`);
return v;
};
export const TOOLS: Tool[] = [
{
name: "todo_search",
description: "Найти todo: фильтры по исполнителю (membership id или me), проекту, виду, сроку, review_date<=сегодня, статусу, текст по названию и описанию.",
inputSchema: obj({ q: str, assignee: str, job: str, kind, status: { type: "string", enum: ["open", "done", "all"] }, dueBefore: str, reviewDue: { type: "boolean" }, limit: { type: "number" } }),
run: (c, caller, a) =>
c.list(caller, { q: s(a, "q"), assignee: s(a, "assignee"), job: s(a, "job"), kind: s(a, "kind") as never, status: s(a, "status") as never, dueBefore: s(a, "dueBefore"), reviewDue: a.reviewDue === true, limit: typeof a.limit === "number" ? a.limit : undefined }),
},
{ name: "todo_get", description: "Одно todo со связями и флагами надстройки.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.get(caller, need(a, "id")) },
{
name: "todo_create",
description: "Создать todo в проекте JobTread (срок по умолчанию - 3 рабочих дня). kind=control добавляет префикс 'Control:'.",
inputSchema: obj({ jobId: str, name: str, description: str, due: str, assigneeMembershipIds: strArr, assigneePersonIds: strArr, kind, reviewDate: str, idempotencyKey: str }, ["jobId", "name"]),
run: (c, caller, a) =>
c.create(caller, { jobId: need(a, "jobId"), name: need(a, "name"), description: s(a, "description"), due: s(a, "due"), assigneeMembershipIds: a.assigneeMembershipIds as string[] | undefined, assigneePersonIds: a.assigneePersonIds as string[] | undefined, kind: s(a, "kind") as never, reviewDate: s(a, "reviewDate") }, s(a, "idempotencyKey")),
},
{
name: "todo_update",
description: "Изменить todo: название, описание, срок (due), исполнителей, вид, review_date (null снимает).",
inputSchema: obj({ id: str, name: str, description: str, due: str, assigneeMembershipIds: strArr, assigneePersonIds: strArr, kind, reviewDate: { type: ["string", "null"] } }, ["id"]),
run: (c, caller, a) =>
c.update(caller, need(a, "id"), { name: s(a, "name"), description: s(a, "description"), due: s(a, "due"), assigneeMembershipIds: a.assigneeMembershipIds as string[] | undefined, assigneePersonIds: a.assigneePersonIds as string[] | undefined, kind: s(a, "kind") as never, reviewDate: "reviewDate" in a ? (a.reviewDate as string | null) : undefined }),
},
{ name: "todo_close", description: "Закрыть todo.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.close(caller, need(a, "id")) },
{ name: "todo_reopen", description: "Вернуть закрытое todo в работу.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.reopen(caller, need(a, "id")) },
{ name: "todo_delete", description: "Удалить todo.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.remove(caller, need(a, "id")) },
{
name: "todo_snooze",
description: "Отложить todo: review_date = until (YYYY-MM-DD) или сегодня + days.",
inputSchema: obj({ id: str, until: str, days: { type: "number" } }, ["id"]),
run: (c, caller, a) => c.snooze(caller, need(a, "id"), { until: s(a, "until"), days: typeof a.days === "number" ? a.days : undefined }),
},
{ name: "todo_keep", description: "Отметить 'Keep confirmed': todo больше не попадает в проверку устаревания.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.keep(caller, need(a, "id")) },
{
name: "todo_control_create",
description: "Создать пару Control: todo исполнителю и Control todo контролёру (срок +2 дня, префикс 'Control:').",
inputSchema: obj(
{
jobId: str, controllerPersonId: str, idempotencyKey: str,
executor: obj({ name: str, description: str, due: str, assigneeMembershipIds: strArr, assigneePersonIds: strArr }, ["name"]),
control: obj({ name: str, description: str }, ["name"]),
},
["jobId", "controllerPersonId", "executor", "control"],
),
run: (c, caller, a) => c.createControl(caller, { jobId: need(a, "jobId"), controllerPersonId: need(a, "controllerPersonId"), executor: a.executor as never, control: a.control as never }, s(a, "idempotencyKey")),
},
{ name: "todo_stale", description: "Открытые напоминания и Control старше 3 недель без 'Keep confirmed' (для пакетного вопроса).", inputSchema: obj({ personId: str, days: { type: "number" } }), run: (c, caller, a) => c.stale(caller, { personId: s(a, "personId"), days: typeof a.days === "number" ? a.days : undefined }) },
{
name: "todo_events",
description: "Лента событий (control_done, control_overdue, review_due, write_failed).",
inputSchema: obj({ personId: str, afterId: { type: "number" }, pending: { type: "boolean" } }),
run: (c, caller, a) => c.events(caller, { personId: s(a, "personId"), afterId: typeof a.afterId === "number" ? a.afterId : undefined, pending: a.pending === true }),
},
];
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(core: TodoCore, caller: Caller, msg: Json): Promise<Json | null> {
const id = msg.id;
const method = msg.method;
if (typeof method !== "string") return rpcError(id, -32600, "invalid request");
if (id === undefined) return null; // notifications/*
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: {} }, serverInfo: { name: "khb-todo", version: "0.1.0" } } };
}
case "ping":
return { jsonrpc: "2.0", id, result: {} };
case "tools/list":
return { jsonrpc: "2.0", id, result: { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) } };
case "tools/call": {
const p = (msg.params ?? {}) as { name?: string; arguments?: Json };
const tool = TOOLS.find((t) => t.name === p.name);
if (!tool) return rpcError(id, -32602, `неизвестный инструмент ${p.name}`);
try {
const out = await tool.run(core, caller, p.arguments ?? {});
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(out) }] } };
} catch (e) {
return { jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }] } };
}
}
default:
return rpcError(id, -32601, `метод не поддерживается: ${method}`);
}
}