From fef474232ccc249eae8611f400244934f37dfffb Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Fri, 4 Dec 2026 22:30:12 +0300 Subject: [PATCH] =?UTF-8?q?mcp=5Ffor=5Fagents:=20=D0=BF=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D0=BE=D1=8F=D0=BD=D0=BD=D1=8B=D0=B9=20MCP-=D1=81=D0=B5=D1=80?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=BE=D0=B2?= =?UTF-8?q?=20(read=5Ffull=5Ftext,=20read=5Fslack=5Fmessage,=20agent=5Fiss?= =?UTF-8?q?ues)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../khbuild_assistant_prep/known-issues.md | 4 +- .../khbuild_assistant_prep/mcp-for-agents.md | 24 ++ .../khbuild_assistant_prep/src/http-api.ts | 6 + packages/khbuild_assistant_prep/src/main.ts | 1 + .../src/mcp-agents.test.ts | 69 +++++ .../khbuild_assistant_prep/src/mcp-agents.ts | 244 ++++++++++++++++++ .../khbuild_assistant_prep/src/settings.ts | 14 + .../khbuild_assistant_prep/src/slack/api.ts | 8 + 8 files changed, 368 insertions(+), 2 deletions(-) create mode 100644 docs/proposed/modules/khbuild_assistant_prep/mcp-for-agents.md create mode 100644 packages/khbuild_assistant_prep/src/mcp-agents.test.ts create mode 100644 packages/khbuild_assistant_prep/src/mcp-agents.ts diff --git a/docs/proposed/modules/khbuild_assistant_prep/known-issues.md b/docs/proposed/modules/khbuild_assistant_prep/known-issues.md index 7fb91a4..546e7a6 100644 --- a/docs/proposed/modules/khbuild_assistant_prep/known-issues.md +++ b/docs/proposed/modules/khbuild_assistant_prep/known-issues.md @@ -1,6 +1,6 @@ # Реестр проблем агентов-ассистентов (khbuild_assistant_prep) -Ведётся с 04.12.2026. Источники: обращения агентов в ИТ (`agent_problem_log`), ночной аудит сообщений (`message_audit_run`), разбор Юрия Ярышева. Риски безопасности ведутся отдельно: Google Drive, «30. IT / IT security», файл «Реестр рисков IT Security». +Ведётся с 04.12.2026. Источники: обращения агентов в ИТ (`agent_problem_log`), ночной аудит сообщений (`message_audit_run`), разбор Юрия Ярышева. Риски безопасности ведутся отдельно: Google Drive, «30. IT / IT security», файл «critical security problems.md». Статусы: `открыта`, `исправлено в коде (ждёт деплоя/проверки)`, `решение принято`, `закрыта`. @@ -11,7 +11,7 @@ | P3 | Ночной аудит сообщений ставит `low_confidence` по длинным Daily-сводкам (1807 Pass a Grille 03.12, 734 Placido 30.11, 256 Bayside 02.12). | `audit.ts` отдавал классификатору только первые 700 символов сообщения. | исправлено в коде: 3000 символов, пачки по 20 | | P4 | Сводки Maria Shevchenko и Nastia Kuranova (1807, 734 Placido, 256 Bayside) не записаны в Daily Log. | Журнал отмечал часть как `done`, запись не создавалась. Три найденных сообщения требуют проверки человеком. | открыта: проверить и дописать Daily Log вручную | | P5 | Зеркало Supabase (`jt_task`) отстаёт от JobTread по 734 Placido (Stucco, Thickness, Prime/1st Coat Exterior, Garage Door, Screw Inspection). | Не выяснена (интервал синхронизации или сбой отдельных таблиц). | открыта | -| P6 | Менеджеры (в первую очередь Greg Paris, молчит с 13.11) не отвечают на сообщения. | Организационная проблема компании: нет Execution-менеджера. Не техническая. | решение принято: агенты игнорируют молчание, не эскалируют в ИТ и не усиливают напоминания; вместо этого разбор записей встреч и Daily Log. Правило добавлено в proposed-промты `p-manager-dialog.md` и `p-step2-prepare.md`; пересмотреть, когда появится исполнительный директор (Execution-менеджер); задача заведена | +| P6 | Менеджеры (в первую очередь Greg Paris, молчит с 13.11) не отвечают на сообщения. | Организационная проблема компании: нет Execution-менеджера. Не техническая. | решение принято: агенты игнорируют молчание, не эскалируют в ИТ и не усиливают напоминания; вместо этого разбор записей встреч и Daily Log. Правило добавлено в proposed-промты `p-manager-dialog.md` и `p-step2-prepare.md`; пересмотреть, когда появится исполнительный директор (Execution-менеджер); открытая задача: найти исполнительного директора (Execution-менеджера), ответственные - владелец компании и Юрий (в todo_service не заведена: сервис требует проект JobTread, внутреннего проекта «компания» нет) | | P7 | Запуск агента в 09:00 пропущен 03.12 (первый запуск дня в 12:00). | Не выяснена. | открыта | | P8 | Доступ сервисного аккаунта к папкам Drive потерян после переноса папок в «30. IT» (приём файлов, бэкапы, записи встреч). | Права наследуются от нового родителя. | закрыта 04.12: `khb-drive-agent` выданы права на «Meeting recordings», «Tech data and logs», «Backups», «IT security» | | P9 | Канал алертов `#it-support-for-agents` засорён обработанными обращениями и служебными сообщениями монитора. | Все алерты (монитор, обращения агентов, аудит) идут в один канал, а старые не чистятся. | в работе: чистка обработанных сообщений ассистентов | diff --git a/docs/proposed/modules/khbuild_assistant_prep/mcp-for-agents.md b/docs/proposed/modules/khbuild_assistant_prep/mcp-for-agents.md new file mode 100644 index 0000000..23794fb --- /dev/null +++ b/docs/proposed/modules/khbuild_assistant_prep/mcp-for-agents.md @@ -0,0 +1,24 @@ +# mcp_for_agents: постоянный MCP-сервер сервиса агентов + +Предложение и реализация (04.12.2026, решение Юрия Ярышева): единый MCP-сервер для Claude сервиса агентов, по образцу MCP бухгалтерии (`/api/acc/mcp`). Подключается как коннектор claude.ai под аккаунтом `agents@khbuild.pro`. + +## Адрес и доступ + +- Внутри: `POST /mcp/agents` сервиса `khb-assistant-prep` (127.0.0.1:8085). Снаружи через nginx: `https://services.khbuild.freeddns.org/api/agents/mcp`; метаданные OAuth: `/api/agents/.well-known/oauth-protected-resource` и `/.well-known/oauth-protected-resource/api/agents/mcp`. +- Протокол: MCP Streamable HTTP, JSON-RPC 2.0 без сессий, ответ `application/json`. +- Аутентификация (внутри сервиса, `src/mcp-agents.ts`): JWT Keycloak (RS256, подпись по JWKS издателя, issuer, срок) с email из `agentsMcp.allowedEmails` (по умолчанию `agents@khbuild.pro`) либо статический токен из `agentsMcp.staticTokens` (служебный доступ и тесты). Без токена: 401 с подсказкой `WWW-Authenticate: Bearer resource_metadata=...`. +- Настройки: секция `khbuild_assistant_prep.agentsMcp` в `settings.json5` (`enabled`, `publicUrl`, `issuer`, `allowedEmails`, `staticTokens`). + +## Инструменты + +| Инструмент | Что делает | +|---|---| +| `read_full_text(ref, offset?, length?)` | Полный текст любой длины по ссылке `ref` из пометки «ОБРЕЗАНО … ref=…» (политика размеров, `fulltext.ts`); читается частями, в ответе следующий offset. | +| `read_slack_message(channel, ts)` | Сообщение Slack целиком по каналу и ts. | +| `agent_issues(severity?, days?, manager_person_id?, limit?)` | Журнал проблем агентов (`agent_problem_log`), тексты полностью. | + +Новые инструменты для агентов добавляются сюда (`agentsTools`), а не отдельными MCP-серверами. + +## Как подключить (делает Юрий) + +В claude.ai под `agents@khbuild.pro`: Settings, Connectors, Add custom connector, URL `https://services.khbuild.freeddns.org/api/agents/mcp`; вход через Keycloak. Внутренний MCP `POST /mcp/fulltext` (токен сервиса, `--mcp-config` для запусков аудита) остаётся для запусков самого сервиса. diff --git a/packages/khbuild_assistant_prep/src/http-api.ts b/packages/khbuild_assistant_prep/src/http-api.ts index f7c11df..25db6d9 100644 --- a/packages/khbuild_assistant_prep/src/http-api.ts +++ b/packages/khbuild_assistant_prep/src/http-api.ts @@ -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 }; } interface RunState { @@ -46,6 +49,8 @@ export function buildApi(deps: PrepApiDeps): FastifyInstance { const runs = new Map(); // состояние последних запусков в памяти; постоянный след - 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; diff --git a/packages/khbuild_assistant_prep/src/main.ts b/packages/khbuild_assistant_prep/src/main.ts index 61f3d48..5babff1 100644 --- a/packages/khbuild_assistant_prep/src/main.ts +++ b/packages/khbuild_assistant_prep/src/main.ts @@ -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( diff --git a/packages/khbuild_assistant_prep/src/mcp-agents.test.ts b/packages/khbuild_assistant_prep/src/mcp-agents.test.ts new file mode 100644 index 0000000..9d8002e --- /dev/null +++ b/packages/khbuild_assistant_prep/src/mcp-agents.test.ts @@ -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, 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(); + } + }); +}); diff --git a/packages/khbuild_assistant_prep/src/mcp-agents.ts b/packages/khbuild_assistant_prep/src/mcp-agents.ts new file mode 100644 index 0000000..6e942f1 --- /dev/null +++ b/packages/khbuild_assistant_prep/src/mcp-agents.ts @@ -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, now: () => number = () => Date.now() / 1000): (token: string) => Promise { + 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): 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; + call(args: Record): Promise; +} + +export interface AgentsMcpDeps { + pool: Pool; + store?: FullTextStore; + /** Полный текст сообщения Slack (любой длины) по каналу и ts; null - не найдено. */ + slackMessage?: (channel: string, ts: string) => Promise; +} + +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; +} + +/** Обработчик одного запроса MCP; null - уведомление без ответа. */ +export async function handleMcpRequest(req: RpcReq, tools: McpTool[], serverName: string): Promise | 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) }] }); + } 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 => 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" })); +} diff --git a/packages/khbuild_assistant_prep/src/settings.ts b/packages/khbuild_assistant_prep/src/settings.ts index 1034c9c..419cd8d 100644 --- a/packages/khbuild_assistant_prep/src/settings.ts +++ b/packages/khbuild_assistant_prep/src/settings.ts @@ -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 - /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(), diff --git a/packages/khbuild_assistant_prep/src/slack/api.ts b/packages/khbuild_assistant_prep/src/slack/api.ts index cfd2573..a383f1f 100644 --- a/packages/khbuild_assistant_prep/src/slack/api.ts +++ b/packages/khbuild_assistant_prep/src/slack/api.ts @@ -31,6 +31,8 @@ export interface SlackApi { userName?(userId: string): Promise; /** Ставит эмодзи-реакцию на сообщение (нужен scope reactions:write); ошибка already_reacted не считается сбоем. */ addReaction?(channel: string, ts: string, emoji: string): Promise; + /** Полный текст одного сообщения (любой длины) по каналу и ts; null - не найдено (для mcp_for_agents). */ + message?(channel: string, ts: string): Promise; /** Slack id самого бота (чтобы пометить его сообщения в истории). */ botUserId?(): Promise; /** Загружает файл в канал (нужен 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(); let cursor = "";