// PEP-236 Access Hub: a remote MCP server as a connection — creating it, the test // (initialize + tools/list, the list is kept in `config`), the owner's message about tools whose // description looks like an instruction to an agent, and what the agent of a session may call. // The call itself goes through the common gateway `useConnection` (connection-gateway.ts). import { asIs, m as tr } from "@peppa/shared/i18n"; import { connectionGrants, connections, users, type Db } from "@peppa/db"; import { and, asc, eq, inArray } from "drizzle-orm"; import { logEvent } from "./audit.ts"; import { addMasterMessage } from "./chats.ts"; import { appendJournal } from "./connection-journal.ts"; import { listMcpTools, McpError, mcpToolMode, mcpTools, type McpTarget, type McpTool, type McpToolMode } from "./connection-mcp.ts"; import { agentIsolated, connectionSlug, defaultConnectionFetch, FORBIDDEN_HEADERS, freeSlug, grantState, HEADER_RE, internalHosts, keyShapeError, listConnections, nameError, openConnectionSecret, parseBaseUrl, sealConnectionSecret, secretError, sessionCtx, slugify, widest, type ConnectionCheckOptions, type ConnectionCheckResult, type ConnectionCheckStatus, type ConnectionFetch, type ConnectionInput, type ConnectionView, } from "./connections.ts"; import { PeppaError } from "./errors.ts"; import { deliverToUser } from "./notifications.ts"; import { getSetting, setSetting } from "./settings.ts"; import { INJECTION_EVENT } from "./untrusted.ts"; type Conn = typeof connections.$inferSelect; let defaultFetch: ConnectionFetch | null = null; /** Tests and the dev stand: the MCP servers' transport for calls that pass none (web form, MCP). */ export function setMcpFetch(f: ConnectionFetch | null): void { defaultFetch = f; } export const mcpFetch = (f?: ConnectionFetch): ConnectionFetch => f ?? defaultFetch ?? defaultConnectionFetch; /** The address and auth header of a connection's server (the key goes only into this header). */ export async function mcpTarget(db: Db, conn: Pick, secret: string, fetch?: ConnectionFetch): Promise { const url = new URL(conn.baseUrl); const auth: Record = {}; if (conn.authKind === "bearer" && secret) auth.authorization = `Bearer ${secret}`; else if (conn.authKind === "header" && conn.authHeader && secret) auth[conn.authHeader.toLowerCase()] = secret; const internal = await internalHosts(db); return { url, auth, fetch: mcpFetch(fetch), allowInternal: internal.includes(url.hostname.toLowerCase()) }; } /** «Подключить MCP-сервер»: address, key in a header (or none), then the test right away. */ export async function createMcpConnection(db: Db, userId: number, i: ConnectionInput): Promise { const name = (i.name ?? "").trim(); const authKind = i.authKind === "header" || i.authKind === "none" ? i.authKind : "bearer"; const secret = authKind === "none" ? "" : i.secret; const err = nameError(name) ?? (authKind === "none" ? null : (secretError(secret) ?? keyShapeError(authKind, secret))); if (err) throw new PeppaError(err); const raw = (i.baseUrl ?? "").trim(); if (!raw) throw new PeppaError(tr("Укажите адрес MCP-сервера")); const baseUrl = parseBaseUrl(raw); const authHeader = authKind === "header" ? (i.authHeader ?? "").trim() : null; if (authKind === "header" && (!HEADER_RE.test(authHeader!) || FORBIDDEN_HEADERS.has(authHeader!.toLowerCase()))) throw new PeppaError(tr("Имя заголовка для ключа: латинские буквы, цифры и дефис, например X-Api-Key")); const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name))); if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name })); const slug = await freeSlug(db, userId, slugify(name) || "mcp"); const [row] = await db .insert(connections) .values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: null, slug, protocol: "mcp", config: { tools: [] }, ...sealConnectionSecret(secret) }) .returning(); await mcpCheck(db, row!, { fetch: i.fetch }); return (await listConnections(db, userId)).find((c) => c.id === row!.id)!; } /** * The test of an MCP connection (also «Обновить список инструментов» and the daily check): * initialize + tools/list through the gateway's address guards. A working server's list replaces * the stored one; new suspicious tools tell the owner once. */ export async function mcpCheck(db: Db, conn: Conn, o: ConnectionCheckOptions = {}): Promise { const now = o.now ?? new Date(); const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method: "MCP", path: "/tools/list", createdAt: now }; const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null }); const started = Date.now(); let status: ConnectionCheckStatus = "down"; let httpStatus: number | undefined; try { const secret = openConnectionSecret(conn) ?? ""; const info = await listMcpTools(await mcpTarget(db, conn, secret, o.fetch), now); status = "ok"; const before = new Set(mcpTools(conn.config).filter((t) => t.suspicious?.length).map((t) => t.name)); const config = { ...(conn.config ?? {}), tools: info.tools, toolsAt: info.toolsAt, serverName: info.serverName, protocolVersion: info.protocolVersion }; await db.update(connections).set({ config }).where(eq(connections.id, conn.id)); conn.config = config; const added = info.tools.filter((t) => t.suspicious?.length && !before.has(t.name)); if (added.length) await tellSuspiciousTools(db, conn, added); } catch (e) { // Anything else (no answer, a blocked address, not an MCP server) — «не отвечает». if (e instanceof McpError) { httpStatus = e.status ?? undefined; if (e.code === "auth") status = "bad_key"; } } const durationMs = Date.now() - started; appendJournal(db, { ...entry, kind: "result", parentId: callId, decision: status === "ok" ? "allowed" : "failed", reason: "owner_check", statusCode: httpStatus ?? null, durationMs, createdAt: new Date(now.getTime() + durationMs) }); const patch: Partial = { checkStatus: status, checkedAt: now }; if (status === "ok") patch.checkAlertedAt = null; await db.update(connections).set(patch).where(eq(connections.id, conn.id)); return { status, checkedAt: now, ...(httpStatus ? { httpStatus } : {}) }; } /** «Обновить список инструментов» (owner only). */ export async function refreshMcpTools(db: Db, userId: number, connectionId: number, o: ConnectionCheckOptions = {}): Promise { const [c] = await db.select().from(connections).where(eq(connections.id, connectionId)); if (!c || c.ownerId !== userId) throw new PeppaError(tr("Подключение не найдено")); if (c.protocol !== "mcp") throw new PeppaError(tr("Это подключение не MCP-сервер")); if (c.status !== "active" || !c.secretEnc) throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа")); return mcpCheck(db, c, o); } /** One message per new suspicious tool: it is not given to agents until the owner turns it on. */ export async function tellSuspiciousTools(db: Db, conn: Pick, tools: McpTool[]): Promise { const key = `connection.mcp.suspicious:${conn.id}`; const told = new Set((await getSetting(db, key)) ?? []); const fresh = tools.filter((t) => !told.has(t.name)); if (!fresh.length) return false; await setSetting(db, key, [...told, ...fresh.map((t) => t.name)].slice(-500)); const names = fresh.map((t) => `«${t.name}»`).join(", "); const text = tr("Описание инструментов {names} MCP-сервера «{name}» похоже на указание для агента. Агентам они не выдаются, пока вы сами не включите их в разрешении в разделе «Подключения».", { names: asIs(names), name: asIs(conn.name) }); const dedupe = `${key}:${fresh.map((t) => t.name).join(",")}`.slice(0, 300); await addMasterMessage(db, conn.ownerId, { kind: "event", important: true, text, dedupeKey: `master:${dedupe}`, url: `/connections#c${conn.id}` }).catch(() => null); const [u] = await db.select().from(users).where(eq(users.id, conn.ownerId)); if (u) { await deliverToUser(db, u, { event: "failures", dedupeKey: `${dedupe}:${u.telegramChatId}`, pushKey: `${dedupe}:u${u.id}`, telegram: { params: { text } }, push: { title: tr("FORGE"), body: text, url: "/connections", tag: key }, }).catch(() => null); } const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, conn.id)); for (const projectId of new Set(grants.map((g) => g.projectId))) { await logEvent(db, { projectId, type: INJECTION_EVENT, payload: { source: `MCP-сервер ${conn.name}`, tools: fresh.map((t) => t.name), signs: [...new Set(fresh.flatMap((t) => t.suspicious ?? []))] } }); } return true; } /** A tool the agent of a session may call, with the connection's short name. */ export interface AgentMcpTool { connectionId: number; connectionName: string; slug: string; tool: McpTool; mode: McpToolMode; } /** * Tools of MCP connections this session's agent may call (mode ≠ off) — like the gateway decides: * an active connection granted to the project (and the agent or any agent), a live grant. */ export async function agentMcpTools(db: Db, sessionId: number | null | undefined, o: { now?: Date; env?: NodeJS.ProcessEnv } = {}): Promise { const now = o.now ?? new Date(); const s = await sessionCtx(db, sessionId); if (!s || !agentIsolated(s, o.env)) return []; const rows = await db .select({ c: connections, g: connectionGrants }) .from(connectionGrants) .innerJoin(connections, eq(connections.id, connectionGrants.connectionId)) .where(and(eq(connectionGrants.projectId, s.projectId), eq(connections.protocol, "mcp"), inArray(connections.status, ["active"]))) .orderBy(asc(connections.name), asc(connectionGrants.id)); const by = new Map(); for (const r of rows) { if (r.g.agentId != null && r.g.agentId !== s.agentId) continue; if (grantState(r.g, now) !== "active" || !r.c.secretEnc) continue; for (const tool of mcpTools(r.c.config)) { const mode = mcpToolMode(tool, { readMode: r.g.readMode, writeMode: r.g.writeMode, tools: r.g.tools }); if (mode === "off") continue; const k = `${r.c.id}:${tool.name}`; const prev = by.get(k); by.set(k, { connectionId: r.c.id, connectionName: r.c.name, slug: connectionSlug(r.c), tool, mode: prev ? widest(prev.mode, mode) : mode }); } } return [...by.values()]; }