mcp_for_agents: постоянный MCP-сервер агентов (read_full_text, read_slack_message, agent_issues)
All checks were successful
ci / test (push) Successful in 54s
ci / deploy (push) Successful in 3m11s

- mcp-agents.ts: JSON-RPC MCP, аутентификация статическим токеном или JWT Keycloak (RS256 по JWKS, без новых зависимостей), allowedEmails
- маршрут POST /mcp/agents и метаданные OAuth; http-api пропускает их мимо токена сервиса
- SlackApi.message: сообщение целиком; настройки agentsMcp; тесты; документ mcp-for-agents.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 22:30:12 +03:00
parent 6e777bca94
commit fef474232c
8 changed files with 368 additions and 2 deletions

View File

@@ -3,6 +3,7 @@ import Fastify, { type FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
import { registerAgentRoutes } from "./agents-api.js";
import { registerFullTextMcp } from "./fulltext.js";
import { registerAgentsMcp, type AgentsMcpSettings } from "./mcp-agents.js";
import { usageSummary, type UsageLog } from "./usage.js";
import type { PrepJob, PrepResult } from "./jobs.js";
import { checkMailAuth } from "./mail/auth.js";
@@ -29,6 +30,8 @@ export interface PrepApiDeps {
mail?: { deps: MailDeps; secret: string };
/** chargeback к контракту (команда khb-chargeback): токен менеджера, вызов уходит в accounting_automation. */
chargeback?: ChargebackConfig;
/** mcp_for_agents (постоянный MCP для Claude, наружу через nginx): настройки и чтение сообщений Slack. */
agentsMcp?: { settings: AgentsMcpSettings; slackMessage?: (channel: string, ts: string) => Promise<string | null> };
}
interface RunState {
@@ -46,6 +49,8 @@ export function buildApi(deps: PrepApiDeps): FastifyInstance {
const runs = new Map<string, RunState>(); // состояние последних запусков в памяти; постоянный след - ap_*, sched_run
app.addHook("onRequest", async (req, reply) => {
if (req.url === "/healthz") return;
// mcp_for_agents: своя аутентификация (токен/JWT Keycloak) внутри маршрута; метаданные OAuth публичны
if (req.url.startsWith("/mcp/agents") || req.url.startsWith("/.well-known/")) return;
if (req.url.startsWith("/mail/")) {
if (!deps.mail || !checkMailAuth(deps.mail.secret, String(req.headers["x-khb-caller"] ?? ""), req.headers.authorization)) return reply.code(401).send({ error: "unauthorized" });
return;
@@ -63,6 +68,7 @@ export function buildApi(deps: PrepApiDeps): FastifyInstance {
registerAgentRoutes(app, deps.pool);
registerFullTextMcp(app);
if (deps.agentsMcp?.settings.enabled) registerAgentsMcp(app, deps.agentsMcp.settings, { pool: deps.pool, slackMessage: deps.agentsMcp.slackMessage });
if (deps.mail) {
const mail = deps.mail.deps;

View File

@@ -134,6 +134,7 @@ const app = buildApi({
mail: mailApi,
chargeback: service.accounting ? { url: service.accounting.url, token: service.accounting.token, secret: service.accounting.tokenSecret } : undefined,
token: service.http.token,
agentsMcp: service.agentsMcp ? { settings: service.agentsMcp, slackMessage: slackApi?.message ? (c, t) => slackApi.message!(c, t) : undefined } : undefined,
chat,
run: (job, opts) =>
runPrepJob(

View File

@@ -0,0 +1,69 @@
import { createSign, generateKeyPairSync } from "node:crypto";
import Fastify from "fastify";
import { describe, expect, it } from "vitest";
import { FullTextStore } from "./fulltext.js";
import { agentsTools, createAgentsMcpAuth, handleMcpRequest, jwtVerifier, McpAuthError, registerAgentsMcp, type AgentsMcpSettings } from "./mcp-agents.js";
const ISS = "https://keycloak.example/realms/khbuild";
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const jwk = { ...publicKey.export({ format: "jwk" }), kid: "k1", alg: "RS256", use: "sig" };
const b64 = (o: unknown) => Buffer.from(typeof o === "string" ? o : JSON.stringify(o)).toString("base64url");
function jwt(claims: Record<string, unknown>, key = privateKey): string {
const head = b64({ alg: "RS256", kid: "k1", typ: "JWT" });
const body = b64({ iss: ISS, exp: Math.floor(Date.now() / 1000) + 600, ...claims });
const sig = createSign("RSA-SHA256").update(`${head}.${body}`).sign(key).toString("base64url");
return `${head}.${body}.${sig}`;
}
const settings: AgentsMcpSettings = { enabled: true, publicUrl: "https://x/api/agents", issuer: ISS, allowedEmails: ["Agents@khbuild.pro"], staticTokens: ["static-token-0123456789abcdef"] };
const verify = jwtVerifier(ISS, async () => ({ keys: [jwk as never] }));
describe("mcp_for_agents: аутентификация", () => {
const auth = createAgentsMcpAuth(settings, verify);
it("статический токен и JWT разрешённого email проходят", async () => {
await expect(auth("Bearer static-token-0123456789abcdef")).resolves.toMatchObject({ who: "static-token" });
await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro", email_verified: true })}`)).resolves.toMatchObject({ who: "agents@khbuild.pro" });
});
it("чужой email - 403, нет токена / плохая подпись / просрочен - 401", async () => {
await expect(auth(`Bearer ${jwt({ email: "other@khbuild.pro" })}`)).rejects.toMatchObject({ status: 403 });
await expect(auth(undefined)).rejects.toBeInstanceOf(McpAuthError);
const other = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey;
await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro" }, other)}`)).rejects.toMatchObject({ status: 401 });
await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro", exp: 1 })}`)).rejects.toMatchObject({ status: 401 });
await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro", iss: "https://evil" })}`)).rejects.toMatchObject({ status: 401 });
});
});
describe("mcp_for_agents: инструменты и маршрут", () => {
it("read_full_text читает любой длины частями, read_slack_message отдаёт текст целиком", async () => {
const store = new FullTextStore();
store.put("a".repeat(30000), "slack:C1:1.1");
const tools = agentsTools({ pool: {} as never, store, slackMessage: async (c, t) => (c === "C1" && t === "1.1" ? "полный текст".repeat(1000) : null) });
expect(tools.map((t) => t.name)).toEqual(["read_full_text", "agent_issues", "read_slack_message"]);
const r1 = (await handleMcpRequest({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "read_full_text", arguments: { ref: "slack:C1:1.1", offset: 20000 } } }, tools, "t")) as { result: { content: { text: string }[] } };
expect(r1.result.content[0]!.text).toContain("символы 20000..30000 из 30000");
const r2 = (await handleMcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "read_slack_message", arguments: { channel: "C1", ts: "1.1" } } }, tools, "t")) as { result: { content: { text: string }[] } };
expect(r2.result.content[0]!.text.length).toBe(12000);
const r3 = (await handleMcpRequest({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "read_slack_message", arguments: { channel: "C9", ts: "9" } } }, tools, "t")) as { result: { isError: boolean } };
expect(r3.result.isError).toBe(true);
});
it("POST /mcp/agents: 401 с подсказкой OAuth без токена, 200 с токеном", async () => {
const app = Fastify();
registerAgentsMcp(app, settings, { pool: {} as never, store: new FullTextStore() }, createAgentsMcpAuth(settings, verify));
await app.listen({ port: 0, host: "127.0.0.1" });
try {
const base = `http://127.0.0.1:${(app.server.address() as { port: number }).port}`;
const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" });
const no = await fetch(base + "/mcp/agents", { method: "POST", headers: { "content-type": "application/json" }, body });
expect(no.status).toBe(401);
expect(no.headers.get("www-authenticate")).toContain("resource_metadata=");
const ok = await fetch(base + "/mcp/agents", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer static-token-0123456789abcdef" }, body });
expect(ok.status).toBe(200);
expect(((await ok.json()) as { result: { tools: unknown[] } }).result.tools.length).toBeGreaterThan(0);
const meta = await fetch(base + "/.well-known/oauth-protected-resource");
expect(await meta.json()).toMatchObject({ resource: "https://x/api/agents/mcp", authorization_servers: [ISS] });
} finally {
await app.close();
}
});
});

View File

@@ -0,0 +1,244 @@
import { createPublicKey, createVerify, timingSafeEqual, type JsonWebKey } from "node:crypto";
import type { FastifyInstance } from "fastify";
import type { Pool } from "khb_common";
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, version: "1.0.0" },
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" }));
}

View File

@@ -135,6 +135,19 @@ export const meetingsSchema = z.object({
glossary: z.array(z.string()).default([]),
});
/** mcp_for_agents: постоянный MCP-сервер для Claude (коннектор claude.ai под agents@khbuild.pro), см. mcp-agents.ts. */
export const agentsMcpSchema = z.object({
enabled: z.boolean().default(true),
/** Публичный адрес (nginx), например https://services.khbuild.freeddns.org/api/agents; MCP - <publicUrl>/mcp. */
publicUrl: z.string().optional(),
/** Издатель Keycloak (OAuth): токены проверяются по его JWKS. */
issuer: z.string().optional(),
/** Email, которым разрешён доступ (agents@khbuild.pro и т.п.). */
allowedEmails: z.array(z.string()).default([]),
/** Статические токены для тестов и служебного доступа. */
staticTokens: z.array(z.string().min(24)).default([]),
});
export const assistantPrepSchema = z.object({
http: z.object({ host: z.string().default("127.0.0.1"), port: z.number(), token: z.string().min(1) }),
lookaheadWorkDays: z.number().default(10),
@@ -145,6 +158,7 @@ export const assistantPrepSchema = z.object({
slack: slackSchema.optional(),
drive: driveSchema.optional(),
meetings: meetingsSchema.optional(),
agentsMcp: agentsMcpSchema.optional(),
tts: ttsSchema.optional(),
mail: mailSchema.optional(),
accounting: accountingSchema.optional(),

View File

@@ -31,6 +31,8 @@ export interface SlackApi {
userName?(userId: string): Promise<string | null>;
/** Ставит эмодзи-реакцию на сообщение (нужен scope reactions:write); ошибка already_reacted не считается сбоем. */
addReaction?(channel: string, ts: string, emoji: string): Promise<boolean>;
/** Полный текст одного сообщения (любой длины) по каналу и ts; null - не найдено (для mcp_for_agents). */
message?(channel: string, ts: string): Promise<string | null>;
/** Slack id самого бота (чтобы пометить его сообщения в истории). */
botUserId?(): Promise<string | null>;
/** Загружает файл в канал (нужен scope files:write). */
@@ -68,6 +70,12 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
let botId: string | null | undefined;
return {
postMessageTs: postTs,
async message(channel, ts) {
const r = await get("conversations.history", { channel, latest: ts, oldest: ts, inclusive: "true", limit: "1" });
if (!r.ok) throw new Error(`Slack conversations.history: ${r.error}`);
const m = (r.messages ?? []).find((x: { ts?: string }) => String(x.ts) === ts);
return m ? String((m as { text?: string }).text ?? "") : null;
},
async history(channel, oldest) {
const out = new Map<string, SlackHistoryMessage>();
let cursor = "";