import { createHash } from "node:crypto"; import type { FastifyInstance } from "fastify"; /** * Политика размеров (04.12.2026): любое сокращение текста, который видит агент, обязано (1) явно помечаться в самом тексте * («ОБРЕЗАНО … ref=…») и (2) оставлять агенту способ прочитать полный текст любой длины - MCP-инструмент `read_full_text` * (эндпоинт POST /mcp/fulltext этого сервиса, подключается к агенту через --mcp-config, см. cli-runner.ts, ToolSet "fulltext"). * В промте агента, которому доступен инструмент, это упоминается (FULLTEXT_PROMPT_NOTE). */ export const FULLTEXT_TOOL = "mcp__khb_fulltext__read_full_text"; export const FULLTEXT_PROMPT_NOTE = "Тебе доступен MCP-инструмент `read_full_text` (сервер khb_fulltext): параметры `ref`, необязательные `offset` и `length`. " + "Если в тексте стоит пометка «ОБРЕЗАНО … ref=…», показан только фрагмент: прочитай полный текст этим инструментом по ref " + "(текст любой длины читается частями: следующий `offset` указан в ответе) и только потом делай вывод. Не делай выводов по обрезанному фрагменту."; const TTL_MS = 48 * 3600_000; const MAX_ENTRIES = 5000; const DEFAULT_CHUNK = 20_000; const MAX_CHUNK = 100_000; interface Entry { text: string; at: number; } /** Хранилище полных текстов в памяти сервиса (ref -> текст), живёт TTL; читается MCP-инструментом. */ export class FullTextStore { private map = new Map(); /** Сохраняет полный текст; ref - явный (например `slack:C0123:1700000000.000100`) или хэш текста. */ put(text: string, ref?: string): string { const key = ref ?? `t:${createHash("sha256").update(text).digest("hex").slice(0, 16)}`; this.map.set(key, { text, at: Date.now() }); if (this.map.size > MAX_ENTRIES) this.sweep(); return key; } get(ref: string): string | undefined { const e = this.map.get(ref); if (!e) return undefined; if (Date.now() - e.at > TTL_MS) { this.map.delete(ref); return undefined; } return e.text; } private sweep(): void { const now = Date.now(); for (const [k, e] of this.map) if (now - e.at > TTL_MS) this.map.delete(k); // всё ещё много: убираем самые старые if (this.map.size > MAX_ENTRIES) for (const k of [...this.map.keys()].slice(0, this.map.size - MAX_ENTRIES)) this.map.delete(k); } get size(): number { return this.map.size; } } /** Общее хранилище сервиса. */ export const fullTextStore = new FullTextStore(); /** * Сокращает текст для агента до max символов, если он длиннее; полный текст кладёт в хранилище, в конец сокращённого добавляет пометку с ref. * Текст короче max возвращается как есть. */ export function clipForAgent(text: string, max: number, opts: { ref?: string; store?: FullTextStore } = {}): string { if (text.length <= max) return text; const ref = (opts.store ?? fullTextStore).put(text, opts.ref); return `${text.slice(0, max)} …[ОБРЕЗАНО: показано ${max} из ${text.length} символов, полный текст: read_full_text ref=${ref}]`; } /** Часть текста по offset/length с пометкой положения и следующим offset. */ export function chunkOf(text: string, offset: number, length: number): string { const off = Math.max(0, Math.floor(offset)); const len = Math.min(MAX_CHUNK, Math.max(1, Math.floor(length))); if (off >= text.length) return `[offset ${off} за концом текста: всего ${text.length} символов]`; const part = text.slice(off, off + len); const end = off + part.length; const tail = end < text.length ? `следующий offset: ${end}` : "конец текста"; return `[символы ${off}..${end} из ${text.length}; ${tail}]\n${part}`; } interface RpcReq { jsonrpc?: string; id?: number | string | null; method?: string; params?: Record; } const TOOL_DEF = { name: "read_full_text", description: "Читает полный текст (любой длины) по ссылке ref из пометки «ОБРЕЗАНО … ref=…». Длинный текст читается частями: offset и length (символы), в ответе указан следующий offset.", inputSchema: { type: "object", properties: { ref: { type: "string", description: "Ссылка из пометки ОБРЕЗАНО" }, offset: { type: "integer", minimum: 0, description: "С какого символа читать (по умолчанию 0)" }, length: { type: "integer", minimum: 1, maximum: MAX_CHUNK, description: `Сколько символов (по умолчанию ${DEFAULT_CHUNK}, максимум ${MAX_CHUNK})` }, }, required: ["ref"], }, }; /** Обработчик одного запроса MCP (JSON-RPC 2.0, Streamable HTTP, ответ application/json); null - уведомление без ответа. */ export function handleMcp(req: RpcReq, store: FullTextStore = fullTextStore): Record | null { const id = req.id ?? null; const ok = (result: unknown) => ({ jsonrpc: "2.0", id, result }); const err = (code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } }); switch (req.method) { case "initialize": return ok({ protocolVersion: typeof req.params?.protocolVersion === "string" ? req.params.protocolVersion : "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "khb_fulltext", version: "1.0.0" }, }); case "ping": return ok({}); case "tools/list": return ok({ tools: [TOOL_DEF] }); case "tools/call": { const p = req.params ?? {}; if (p.name !== "read_full_text") return err(-32602, `неизвестный инструмент: ${String(p.name)}`); const a = (p.arguments ?? {}) as { ref?: unknown; offset?: unknown; length?: unknown }; if (typeof a.ref !== "string" || !a.ref) return ok({ isError: true, content: [{ type: "text", text: "не указан ref" }] }); const text = store.get(a.ref); if (text === undefined) return ok({ isError: true, content: [{ type: "text", text: `ref ${a.ref} не найден или устарел (хранится 48 часов); полный текст недоступен` }] }); const out = chunkOf(text, Number(a.offset ?? 0) || 0, Number(a.length ?? DEFAULT_CHUNK) || DEFAULT_CHUNK); return ok({ content: [{ type: "text", text: out }] }); } default: if (req.method?.startsWith("notifications/")) return null; return err(-32601, `метод не поддерживается: ${String(req.method)}`); } } /** POST /mcp/fulltext: MCP-сервер «полный текст» (авторизация - общий токен сервиса, хук onRequest в http-api). */ export function registerFullTextMcp(app: FastifyInstance, store: FullTextStore = fullTextStore): void { app.post("/mcp/fulltext", async (req, reply) => { const body = req.body as RpcReq | RpcReq[] | undefined; if (!body) return reply.code(400).send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "пустое тело" } }); if (Array.isArray(body)) { const out = body.map((b) => handleMcp(b, store)).filter((x): x is Record => x !== null); return out.length ? out : reply.code(202).send(); } const res = handleMcp(body, store); return res ?? reply.code(202).send(); }); app.get("/mcp/fulltext", async (_req, reply) => reply.code(405).send({ error: "только POST" })); }