Files
khb_microservices/packages/khbuild_assistant_prep/src/mcp-agents.ts
Yuri Yaryshev 595e69d57f
All checks were successful
ci / test (push) Successful in 1m18s
ci / deploy (push) Successful in 3m33s
MCP: у каждого коннектора KH Build своя иконка и название (serverInfo.icons/title)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-06 17:01:07 +03:00

249 lines
13 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 { createPublicKey, createVerify, timingSafeEqual, type JsonWebKey } from "node:crypto";
import type { FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
/** Иконка коннектора (MCP serverInfo.icons): у каждого MCP KH Build свой цвет и знак, чтобы не путать их в списке коннекторов. */
const MCP_ICON = "data:image/svg+xml," + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#7a3fd1"/><text x="32" y="43" font-size="30" font-weight="700" text-anchor="middle" fill="#fff" font-family="Arial">AI</text></svg>');
const MCP_ICONS = [{ src: MCP_ICON, mimeType: "image/svg+xml", sizes: ["any"] }];
import { chunkOf, fullTextStore, type FullTextStore } from "./fulltext.js";
/**
* mcp_for_agents: постоянный MCP-сервер для Claude сервиса агентов (Streamable HTTP, JSON-RPC без сессий), по образцу MCP бухгалтерии.
* Публикуется через nginx как https://services.khbuild.freeddns.org/api/agents/mcp, подключается как коннектор claude.ai из-под agents@khbuild.pro.
* Аутентификация: статический токен или JWT Keycloak (RS256, JWKS издателя), email должен быть в agentsMcp.allowedEmails.
* Инструменты читают данные без ограничений по размеру (политика размеров, fulltext.ts).
*/
export interface AgentsMcpSettings {
enabled: boolean;
publicUrl?: string;
issuer?: string;
allowedEmails: string[];
staticTokens: string[];
}
export class McpAuthError extends Error {
constructor(message: string, readonly status: 401 | 403 = 401) {
super(message);
}
}
const safeEqual = (a: string, b: string): boolean => {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
};
export const bearerOf = (h: string | undefined): string | null => (h && /^Bearer\s/i.test(h) ? h.slice(7).trim() || null : null);
interface Jwks {
keys: (JsonWebKey & { kid?: string })[];
}
export interface JwtClaims {
email?: string;
email_verified?: boolean;
iss?: string;
exp?: number;
}
/** Проверка JWT RS256 по JWKS издателя (без внешних библиотек): подпись, issuer, срок. getJwks внедряется в тестах. */
export function jwtVerifier(issuer: string, getJwks?: () => Promise<Jwks>, now: () => number = () => Date.now() / 1000): (token: string) => Promise<JwtClaims> {
const iss = issuer.replace(/\/$/, "");
let cache: { at: number; jwks: Jwks } | undefined;
const load =
getJwks ??
(async () => {
if (cache && Date.now() - cache.at < 10 * 60_000) return cache.jwks;
const r = await fetch(`${iss}/protocol/openid-connect/certs`);
if (!r.ok) throw new Error(`JWKS: HTTP ${r.status}`);
cache = { at: Date.now(), jwks: (await r.json()) as Jwks };
return cache.jwks;
});
const b64 = (s: string) => Buffer.from(s, "base64url");
return async (token) => {
const parts = token.split(".");
if (parts.length !== 3) throw new Error("не JWT");
const header = JSON.parse(b64(parts[0]!).toString("utf8")) as { alg?: string; kid?: string };
if (header.alg !== "RS256") throw new Error("алгоритм не RS256");
const jwk = (await load()).keys.find((k) => k.kid === header.kid);
if (!jwk) throw new Error("ключ не найден");
const ok = createVerify("RSA-SHA256").update(`${parts[0]}.${parts[1]}`).verify(createPublicKey({ key: jwk, format: "jwk" }), b64(parts[2]!));
if (!ok) throw new Error("подпись не верна");
const claims = JSON.parse(b64(parts[1]!).toString("utf8")) as JwtClaims;
if (claims.iss !== iss && claims.iss !== `${iss}/`) throw new Error("issuer не совпадает");
if (typeof claims.exp !== "number" || claims.exp < now()) throw new Error("токен просрочен");
return claims;
};
}
export type AgentsMcpAuth = (authorization: string | undefined) => Promise<{ who: string }>;
export function createAgentsMcpAuth(s: AgentsMcpSettings, verify?: (t: string) => Promise<JwtClaims>): AgentsMcpAuth {
const v = verify ?? (s.issuer ? jwtVerifier(s.issuer) : undefined);
const allowed = new Set(s.allowedEmails.map((e) => e.toLowerCase()));
return async (authorization) => {
const t = bearerOf(authorization);
if (!t) throw new McpAuthError("нужен заголовок Authorization: Bearer <токен>", 401);
if (s.staticTokens.some((x) => safeEqual(t, x))) return { who: "static-token" };
if (!v) throw new McpAuthError("токен не принят", 401);
let claims: JwtClaims;
try {
claims = await v(t);
} catch {
throw new McpAuthError("токен не принят", 401);
}
if (claims.email_verified === false) throw new McpAuthError("email не подтверждён", 401);
if (!claims.email) throw new McpAuthError("в токене нет email", 401);
if (!allowed.has(claims.email.toLowerCase())) throw new McpAuthError("этому пользователю доступ к mcp_for_agents не выдан", 403);
return { who: claims.email.toLowerCase() };
};
}
// ---------------------------------------------------------------------------------------------------------------------
// Инструменты
export interface McpTool {
name: string;
description: string;
inputSchema: Record<string, unknown>;
call(args: Record<string, unknown>): Promise<string>;
}
export interface AgentsMcpDeps {
pool: Pool;
store?: FullTextStore;
/** Полный текст сообщения Slack (любой длины) по каналу и ts; null - не найдено. */
slackMessage?: (channel: string, ts: string) => Promise<string | null>;
}
export function agentsTools(d: AgentsMcpDeps): McpTool[] {
const store = d.store ?? fullTextStore;
const tools: McpTool[] = [
{
name: "read_full_text",
description: "Читает полный текст (любой длины) по ссылке ref из пометки «ОБРЕЗАНО … ref=…». Длинный текст читается частями: offset и length (символы), в ответе указан следующий offset.",
inputSchema: {
type: "object",
properties: {
ref: { type: "string", description: "Ссылка из пометки ОБРЕЗАНО" },
offset: { type: "integer", minimum: 0 },
length: { type: "integer", minimum: 1, maximum: 100000 },
},
required: ["ref"],
},
async call(a) {
const ref = String(a.ref ?? "");
const text = store.get(ref);
if (text === undefined) throw new Error(`ref ${ref || "(пусто)"} не найден или устарел (хранится 48 часов)`);
return chunkOf(text, Number(a.offset ?? 0) || 0, Number(a.length ?? 20000) || 20000);
},
},
{
name: "agent_issues",
description: "Последние записи журнала проблем агентов (agent_problem_log): обращения в ИТ и минорные проблемы. Фильтры: severity (it_request или log), days (по умолчанию 3), manager_person_id. Текст записей возвращается полностью.",
inputSchema: {
type: "object",
properties: { severity: { type: "string", enum: ["it_request", "log"] }, days: { type: "integer", minimum: 1, maximum: 90 }, manager_person_id: { type: "string" }, limit: { type: "integer", minimum: 1, maximum: 100 } },
},
async call(a) {
const days = Math.min(90, Math.max(1, Number(a.days ?? 3) || 3));
const limit = Math.min(100, Math.max(1, Number(a.limit ?? 30) || 30));
const { rows } = await d.pool.query(
`select created_at, manager_person_id, step, severity, body from agent_problem_log
where created_at > now() - make_interval(days => $1) and ($2::text is null or severity = $2) and ($3::uuid is null or manager_person_id = $3)
order by created_at desc limit $4`,
[days, a.severity ? String(a.severity) : null, a.manager_person_id ? String(a.manager_person_id) : null, limit],
);
return rows.length
? rows.map((r) => `### ${new Date(r.created_at as string).toISOString()} | ${r.step} | ${r.severity} | менеджер ${r.manager_person_id}\n${r.body}`).join("\n\n")
: "записей нет";
},
},
];
if (d.slackMessage) {
const read = d.slackMessage;
tools.push({
name: "read_slack_message",
description: "Читает сообщение Slack целиком (любой длины) по id канала и ts.",
inputSchema: { type: "object", properties: { channel: { type: "string" }, ts: { type: "string" } }, required: ["channel", "ts"] },
async call(a) {
const text = await read(String(a.channel ?? ""), String(a.ts ?? ""));
if (text === null) throw new Error("сообщение не найдено или нет доступа к каналу");
return text;
},
});
}
return tools;
}
// ---------------------------------------------------------------------------------------------------------------------
// Протокол
interface RpcReq {
jsonrpc?: string;
id?: number | string | null;
method?: string;
params?: Record<string, unknown>;
}
/** Обработчик одного запроса MCP; null - уведомление без ответа. */
export async function handleMcpRequest(req: RpcReq, tools: McpTool[], serverName: string): Promise<Record<string, unknown> | 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: serverName, title: "KH Build: агенты (mcp_for_agents)", version: "1.0.0", icons: MCP_ICONS },
instructions: "Чтение данных сервиса агентов без ограничений по размеру: read_full_text (полный текст по ref из пометки ОБРЕЗАНО), read_slack_message, agent_issues.",
});
case "ping":
return ok({});
case "tools/list":
return ok({ tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
case "tools/call": {
const p = req.params ?? {};
const t = tools.find((x) => x.name === p.name);
if (!t) return err(-32602, `неизвестный инструмент: ${String(p.name)}`);
try {
return ok({ content: [{ type: "text", text: await t.call((p.arguments ?? {}) as Record<string, unknown>) }] });
} catch (e) {
return ok({ isError: true, content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }] });
}
}
default:
if (req.method?.startsWith("notifications/")) return null;
return err(-32601, `метод не поддерживается: ${String(req.method)}`);
}
}
/** POST /mcp/agents (внутренний путь; наружу через nginx /api/agents/mcp) и метаданные OAuth protected resource. Собственная аутентификация (см. onRequest в http-api). */
export function registerAgentsMcp(app: FastifyInstance, s: AgentsMcpSettings, deps: AgentsMcpDeps, auth: AgentsMcpAuth = createAgentsMcpAuth(s)): void {
const tools = agentsTools(deps);
const base = s.publicUrl?.replace(/\/$/, "");
app.get("/.well-known/oauth-protected-resource", async (_req, reply) => {
if (!base) return reply.code(404).send({ error: "not configured" });
return { resource: `${base}/mcp`, ...(s.issuer ? { authorization_servers: [s.issuer] } : {}), bearer_methods_supported: ["header"], scopes_supported: ["openid", "email", "profile"] };
});
app.post("/mcp/agents", async (req, reply) => {
try {
await auth(req.headers.authorization);
} catch (e) {
const status = e instanceof McpAuthError ? e.status : 401;
// MCP-клиенту нужна подсказка, где взять токен (OAuth)
if (status === 401 && base) reply.header("WWW-Authenticate", `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`);
return reply.code(status).send({ error: e instanceof Error ? e.message : "unauthorized" });
}
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 = (await Promise.all(body.map((b) => handleMcpRequest(b, tools, "mcp_for_agents")))).filter((x): x is Record<string, unknown> => x !== null);
return out.length ? out : reply.code(202).send();
}
const res = await handleMcpRequest(body, tools, "mcp_for_agents");
return res ?? reply.code(202).send();
});
app.get("/mcp/agents", async (_req, reply) => reply.code(405).send({ error: "только POST" }));
}