PEP-236: MCP-сервер как подключение — клиент, проверка, разрешение по инструментам, вызов через шлюз

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-12-01 16:34:09 +00:00
parent e33e1381be
commit d231a86788
12 changed files with 6504 additions and 24 deletions

View File

@ -21,7 +21,8 @@ export type ApprovalStatus = Row["status"];
/** The exact call that runs after «Разрешить». */
export type ApprovalRequest =
| { kind: "http"; method: string; path: string; body: string | null; contentType: string | null }
| { kind: "use"; operation: string; args: Record<string, unknown> };
/** mcp (PEP-236): `operation` is a remote MCP server's tool. */
| { kind: "use"; operation: string; args: Record<string, unknown>; mcp?: boolean };
export const APPROVAL_TTL_MS = () => Math.max(1, Number(process.env.PEPPA_APPROVAL_TTL_HOURS ?? 24)) * 3600_000;
/** How long the agent's call waits for the answer before «ждёт подтверждения, id …». */
@ -77,6 +78,7 @@ export function approvalSummary(req: ApprovalRequest): { method: string; logPath
return { method: req.method.toUpperCase().slice(0, 10), logPath, summary: lines.join("\n") };
}
const args = JSON.stringify(canonical(req.args));
if (req.mcp) return { method: "MCP", logPath: `/${req.operation}`.slice(0, 300), summary: [`MCP /${req.operation}`, args === "{}" ? "" : shorten(maskKeyLike(args))].filter(Boolean).join("\n") };
return { method: req.operation.toUpperCase().slice(0, 10), logPath: "/", summary: [req.operation, args === "{}" ? "" : shorten(maskKeyLike(args))].filter(Boolean).join("\n") };
}

View File

@ -9,7 +9,8 @@
// open API with a plain key — not in the catalog, use «Свой сервис» if a partner gives one.
import { m as tr } from "@peppa/shared/i18n";
export type CatalogAuth = "bearer" | "header" | "basic" | "query" | "path" | "oauth";
// none (PEP-236): a public MCP server without a key.
export type CatalogAuth = "bearer" | "header" | "basic" | "query" | "path" | "oauth" | "none";
export type CatalogKind = "payments" | "code" | "mail" | "messaging" | "ai" | "cloud" | "errors" | "data" | "docs" | "maps" | "commerce";
export const CATALOG_KINDS: CatalogKind[] = ["payments", "code", "mail", "messaging", "ai", "cloud", "errors", "data", "docs", "maps", "commerce"];

View File

@ -13,6 +13,8 @@ import { addMasterMessage } from "./chats.ts";
import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts";
import { DriverError, defaultDrivers, type GatewayDrivers, type MailRequest, type SshRequest } from "./connection-drivers.ts";
import { approvalGate, type ApprovalPending } from "./connection-approvals.ts";
import { callMcpTool, MCP_ARGS_MAX_BYTES, McpError, mcpToolMode, mcpTools } from "./connection-mcp.ts";
import { mcpTarget } from "./connection-mcp-hub.ts";
import {
ANSWER_MAX_BYTES,
FILE_MAX_BYTES,
@ -199,6 +201,8 @@ function prepare(protocol: GatewayProtocol, cfg: Record<string, unknown>, op: st
return { kind: "mail", req: { op: "send", from: c.from, to, subject, text }, logPath: "/" };
}
const MCP_REASON: Record<McpError["code"], ConnectionReason> = { auth: "auth_failed", down: "upstream_error", protocol: "upstream_error", too_large: "too_large", redirect: "redirect" };
const DRIVER_REASON: Record<DriverError["code"], ConnectionReason> = {
auth: "auth_failed",
down: "upstream_error",
@ -312,7 +316,8 @@ export async function tellHostKeyChanged(db: Db, conn: Pick<Conn, "id" | "ownerI
export async function useConnection(db: Db, call: UseConnectionCall, opts: GatewayOptions & ApprovalOptions = {}): Promise<UseConnectionResult> {
const o = { ...defaults, ...opts };
const now = o.now ?? new Date();
const operation = String(call.operation ?? "").trim().toLowerCase();
const rawOperation = String(call.operation ?? "").trim();
const operation = rawOperation.toLowerCase();
const args = call.args && typeof call.args === "object" ? call.args : {};
const s = await sessionCtx(db, call.sessionId);
if (!s) return { ok: false, reason: "no_session" };
@ -320,8 +325,10 @@ export async function useConnection(db: Db, call: UseConnectionCall, opts: Gatew
if ("reason" in found) return { ok: false, reason: found.reason };
const conn = found.matches[0]!.c;
let logPath = "/";
// PEP-236: an MCP server's tool is journaled as «MCP /<tool>».
const journalMethod = conn.protocol === "mcp" ? "MCP" : operation.toUpperCase().slice(0, 10) || "?";
const record = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number } = {}) =>
const record = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number; statusCode?: number | null } = {}) =>
appendJournal(db, {
ownerId: conn.ownerId,
kind: extra.kind ?? "call",
@ -332,11 +339,11 @@ export async function useConnection(db: Db, call: UseConnectionCall, opts: Gatew
sessionId: s.id,
agentId: s.agentId,
agentName: s.agentName,
method: operation.toUpperCase().slice(0, 10) || "?",
method: journalMethod,
path: logPath.slice(0, 300),
decision,
reason,
statusCode: null,
statusCode: extra.statusCode ?? null,
durationMs: extra.durationMs ?? null,
createdAt: extra.kind === "result" ? new Date(now.getTime() + (extra.durationMs ?? 0)) : now,
});
@ -348,6 +355,51 @@ export async function useConnection(db: Db, call: UseConnectionCall, opts: Gatew
if (!agentIsolated(s, o.env)) return deny("not_isolated");
if (conn.status !== "active" || !conn.secretEnc) return deny("revoked");
const protocol = conn.protocol;
if (protocol === "mcp") {
// PEP-236: the operation is the server's tool, by its exact name.
const live = liveGrants(found.matches, s.agentId, now);
if ("reason" in live) return deny(live.reason);
const tool = mcpTools(conn.config).find((t) => t.name === rawOperation);
if (!tool) return deny("operation_denied");
logPath = `/${tool.name}`;
const mode = live.mine.reduce<GrantMode>((acc, g) => widest(acc, mcpToolMode(tool, { readMode: g.readMode, writeMode: g.writeMode, tools: g.g.tools })), "off");
if (mode === "off") return deny("operation_denied");
if (Buffer.byteLength(JSON.stringify(args)) > MCP_ARGS_MAX_BYTES) return deny("bad_request");
if ((await recentCalls(db, s.id, now)) >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
if (mode === "ask" && !o.approved) {
const { drivers, fetch, resolve, env } = o;
return (await approvalGate(db, { conn, session: s, request: { kind: "use", operation: tool.name, args, mcp: true }, idemKey: call.idempotencyKey, now }, () => record("denied", "needs_approval"), { waitMs: o.approvalWaitMs, gateway: { drivers, fetch, resolve, env } })) as UseConnectionResult;
}
let secret: string;
try {
secret = openConnectionSecret(conn) ?? "";
} catch {
await record("failed", "upstream_error");
return { ok: false, reason: "upstream_error" };
}
const callId = record("allowed", null);
await touchGrants(db, live.mine, now);
const started = Date.now();
const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null = null) => record(decision, reason, { kind: "result", parentId: callId, durationMs: Date.now() - started, statusCode });
const forms = connectionKeyForms(secret);
const mask = (t: string) => maskConnectionKey(t, forms);
try {
const a = await callMcpTool(await mcpTarget(db, conn, secret, o.fetch), tool.name, args);
await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id));
if (!a.ok) {
result("failed", "query_error", a.status);
return { ok: false, reason: "query_error", message: mask(a.text).slice(0, 2000) };
}
const truncated = Buffer.byteLength(a.text) > ANSWER_MAX_BYTES;
result("allowed", truncated ? "too_large" : null, a.status);
const text = mask(truncated ? Buffer.from(a.text).subarray(0, ANSWER_MAX_BYTES).toString("utf8") : a.text);
return { ok: true, text: truncated ? `${text}\n…[cut at 64 KB]` : text, truncated };
} catch (e) {
const reason: ConnectionReason = e instanceof Refused ? e.reason : e instanceof McpError ? MCP_REASON[e.code] : "upstream_error";
result(reason === "blocked_address" ? "denied" : "failed", reason, e instanceof McpError ? e.status : null);
return { ok: false, reason };
}
}
if (!isGatewayProtocol(protocol)) return deny("wrong_protocol");
// PEP-259: only live grants (term not over, not revoked for no use).
const live = liveGrants(found.matches, s.agentId, now);

View File

@ -0,0 +1,195 @@
// 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<Conn, "baseUrl" | "authKind" | "authHeader">, secret: string, fetch?: ConnectionFetch): Promise<McpTarget> {
const url = new URL(conn.baseUrl);
const auth: Record<string, string> = {};
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<ConnectionView> {
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<ConnectionCheckResult> {
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<typeof connections.$inferInsert> = { 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<ConnectionCheckResult> {
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<Conn, "id" | "ownerId" | "name">, tools: McpTool[]): Promise<boolean> {
const key = `connection.mcp.suspicious:${conn.id}`;
const told = new Set((await getSetting<string[]>(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<AgentMcpTool[]> {
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<string, AgentMcpTool>();
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()];
}

View File

@ -0,0 +1,230 @@
// PEP-236 Access Hub: a remote MCP server (Streamable HTTP) as a connection. This module is the
// client side of the protocol — JSON-RPC over POST, answers as JSON or as an SSE stream, the
// session header — and the parsing of the server's tool list (limits, read/write class, signs of
// an instruction to an agent in a description). The gateway (connection-gateway.ts) decides who
// may call what; the key is added here, in the request headers only, and never leaves the server.
import { detectInjection } from "./untrusted.ts";
import type { ConnectionFetch } from "./connections.ts";
export const MCP_PROTOCOL_VERSION = "2025-06-18";
export const MCP_TOOLS_MAX = 200;
export const MCP_TOOL_NAME_MAX = 128;
export const MCP_DESCRIPTION_MAX = 2000;
export const MCP_SCHEMA_MAX_BYTES = 8 * 1024;
export const MCP_ARGS_MAX_BYTES = 64 * 1024;
const LIST_PAGES_MAX = 5;
/** A tool of a remote MCP server as FORGE keeps it (never a secret). */
export interface McpTool {
name: string;
title?: string;
description: string;
/** `annotations.readOnlyHint === true` — reading; anything else — writing. */
readOnly: boolean;
destructive: boolean;
inputSchema: Record<string, unknown>;
/** Signs of an instruction to an agent in its description (PEP-187); empty/absent — clean. */
suspicious?: string[];
}
export interface McpServerInfo {
tools: McpTool[];
toolsAt: string;
serverName: string | null;
protocolVersion: string | null;
}
export const isMcpToolName = (s: unknown): s is string => typeof s === "string" && s.length > 0 && s.length <= MCP_TOOL_NAME_MAX && /^[A-Za-z0-9_.\-/]+$/.test(s);
/** Where and how to talk to the server: the address and the auth header (with the key) if any. */
export interface McpTarget {
url: URL;
/** Header name → value; the key lives only here. */
auth: Record<string, string>;
fetch: ConnectionFetch;
allowInternal?: boolean;
}
/** Why a conversation with the server failed. */
export class McpError extends Error {
code: "auth" | "down" | "protocol" | "too_large" | "redirect";
status: number | null;
constructor(code: McpError["code"], message: string = code, status: number | null = null) {
super(message);
this.code = code;
this.status = status;
}
}
interface RpcAnswer {
result?: Record<string, unknown>;
error?: { code?: number; message?: string };
status: number;
sessionId: string | null;
}
/** The JSON-RPC message with this id in an SSE stream (`data:` lines of events). */
export function sseMessage(text: string, id: number): Record<string, unknown> | null {
for (const block of text.split(/\r?\n\r?\n/)) {
const data = block.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
if (!data) continue;
try {
const msg = JSON.parse(data) as Record<string, unknown> | Array<Record<string, unknown>>;
for (const m of Array.isArray(msg) ? msg : [msg]) if (m && m.id === id) return m;
} catch {}
}
return null;
}
let rpcSeq = 0;
async function rpc(t: McpTarget, method: string, params: Record<string, unknown> | undefined, s: { sessionId: string | null; version: string | null }, notify = false): Promise<RpcAnswer> {
const id = ++rpcSeq;
const body = Buffer.from(JSON.stringify(notify ? { jsonrpc: "2.0", method, ...(params ? { params } : {}) } : { jsonrpc: "2.0", id, method, ...(params ? { params } : {}) }));
const headers: Record<string, string> = {
"user-agent": "PeppaFactory-AccessHub/1",
accept: "application/json, text/event-stream",
"content-type": "application/json",
"content-length": String(body.length),
...t.auth,
};
if (s.sessionId) headers["mcp-session-id"] = s.sessionId;
if (s.version) headers["mcp-protocol-version"] = s.version;
const res = await t.fetch({ url: t.url, method: "POST", headers, body, allowInternal: t.allowInternal });
const sessionId = res.mcpSessionId ?? s.sessionId;
if (res.status >= 300 && res.status < 400) throw new McpError("redirect", "redirect", res.status);
if (res.status === 401 || res.status === 403) throw new McpError("auth", "auth", res.status);
if (notify) return { status: res.status, sessionId };
if (res.status >= 400) throw new McpError("down", `server answered ${res.status}`, res.status);
if (res.truncated) throw new McpError("too_large", "too_large", res.status);
const enc = (res.contentEncoding ?? "").trim().toLowerCase();
if (enc && enc !== "identity") throw new McpError("protocol", "compressed answer", res.status);
const text = res.body.toString("utf8");
let msg: Record<string, unknown> | null = null;
if ((res.contentType ?? "").toLowerCase().startsWith("text/event-stream")) msg = sseMessage(text, id);
else {
try {
const parsed = JSON.parse(text) as Record<string, unknown> | Array<Record<string, unknown>>;
msg = (Array.isArray(parsed) ? parsed.find((m) => m?.id === id) : parsed) ?? null;
} catch {
msg = null;
}
}
if (!msg || typeof msg !== "object") throw new McpError("protocol", "not a JSON-RPC answer", res.status);
return { result: msg.result as Record<string, unknown> | undefined, error: msg.error as RpcAnswer["error"], status: res.status, sessionId };
}
/** `initialize` + `notifications/initialized`: a fresh session for one piece of work. */
async function openSession(t: McpTarget): Promise<{ sessionId: string | null; version: string | null; serverName: string | null }> {
const init = await rpc(t, "initialize", { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "forge-access-hub", version: "1.0.0" } }, { sessionId: null, version: null });
if (init.error || !init.result) throw new McpError("protocol", init.error?.message ?? "initialize failed", init.status);
const version = typeof init.result.protocolVersion === "string" ? init.result.protocolVersion : MCP_PROTOCOL_VERSION;
const info = init.result.serverInfo as { name?: unknown } | undefined;
const s = { sessionId: init.sessionId, version };
await rpc(t, "notifications/initialized", undefined, s, true).catch(() => null);
return { ...s, serverName: typeof info?.name === "string" ? info.name.slice(0, 120) : null };
}
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
/** Descriptions inside a tool's input schema (an injection may hide in a parameter's text too). */
function schemaTexts(schema: unknown, out: string[] = [], depth = 0): string[] {
if (!schema || typeof schema !== "object" || depth > 6) return out;
for (const [k, v] of Object.entries(schema as Record<string, unknown>)) {
if ((k === "description" || k === "title") && typeof v === "string") out.push(v);
else if (v && typeof v === "object") schemaTexts(v, out, depth + 1);
}
return out;
}
/** One raw tool of `tools/list` → what FORGE keeps; null — not a usable tool. */
export function parseMcpTool(raw: unknown): McpTool | null {
if (!raw || typeof raw !== "object") return null;
const r = raw as Record<string, unknown>;
if (!isMcpToolName(r.name)) return null;
const ann = (r.annotations && typeof r.annotations === "object" ? r.annotations : {}) as Record<string, unknown>;
const description = clip(typeof r.description === "string" ? r.description : "", MCP_DESCRIPTION_MAX);
const title = typeof r.title === "string" ? clip(r.title, 200) : typeof ann.title === "string" ? clip(ann.title, 200) : undefined;
let inputSchema: Record<string, unknown> = { type: "object" };
if (r.inputSchema && typeof r.inputSchema === "object" && Buffer.byteLength(JSON.stringify(r.inputSchema)) <= MCP_SCHEMA_MAX_BYTES) inputSchema = r.inputSchema as Record<string, unknown>;
const hits = detectInjection([r.name, title ?? "", description, ...schemaTexts(r.inputSchema)].join("\n"));
return {
name: r.name,
...(title ? { title } : {}),
description,
readOnly: ann.readOnlyHint === true,
destructive: ann.destructiveHint === true,
inputSchema,
...(hits.length ? { suspicious: hits.map((h) => h.id) } : {}),
};
}
/** The test of a connection and «Обновить список»: initialize + tools/list (a few pages). */
export async function listMcpTools(t: McpTarget, now = new Date()): Promise<McpServerInfo> {
const s = await openSession(t);
const tools: McpTool[] = [];
const seen = new Set<string>();
let cursor: string | undefined;
for (let page = 0; page < LIST_PAGES_MAX; page++) {
const a = await rpc(t, "tools/list", cursor ? { cursor } : undefined, s);
if (a.error || !a.result) throw new McpError("protocol", a.error?.message ?? "tools/list failed", a.status);
for (const raw of Array.isArray(a.result.tools) ? a.result.tools : []) {
const tool = parseMcpTool(raw);
if (tool && !seen.has(tool.name) && tools.length < MCP_TOOLS_MAX) {
seen.add(tool.name);
tools.push(tool);
}
}
cursor = typeof a.result.nextCursor === "string" && a.result.nextCursor ? a.result.nextCursor : undefined;
if (!cursor || tools.length >= MCP_TOOLS_MAX) break;
}
return { tools, toolsAt: now.toISOString(), serverName: s.serverName, protocolVersion: s.version };
}
export type McpCallAnswer = { ok: true; text: string; status: number } | { ok: false; toolError: true; text: string; status: number } | { ok: false; toolError: false; text: string; status: number };
/** Content of a `tools/call` result → text for the agent: text parts as is, others as a note. */
export function mcpResultText(result: Record<string, unknown>): string {
const parts: string[] = [];
for (const c of Array.isArray(result.content) ? result.content : []) {
const item = c as Record<string, unknown>;
if (item?.type === "text" && typeof item.text === "string") parts.push(item.text);
else if (item?.type === "resource" && item.resource && typeof (item.resource as Record<string, unknown>).text === "string") parts.push(String((item.resource as Record<string, unknown>).text));
else if (item?.type === "resource_link") parts.push(`[resource link: ${String(item.uri ?? "")}]`);
else parts.push(`[${String(item?.type ?? "content")} omitted]`);
}
if (!parts.length && result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent));
return parts.join("\n") || "(empty answer)";
}
/** One tool call in a fresh session. A tool error (`isError`) is the server's text, not ours. */
export async function callMcpTool(t: McpTarget, tool: string, args: Record<string, unknown>): Promise<McpCallAnswer> {
const s = await openSession(t);
const a = await rpc(t, "tools/call", { name: tool, arguments: args }, s);
if (a.error) return { ok: false, toolError: false, text: clip(String(a.error.message ?? "error"), 2000), status: a.status };
if (!a.result) throw new McpError("protocol", "tools/call without result", a.status);
const text = mcpResultText(a.result);
return a.result.isError === true ? { ok: false, toolError: true, text, status: a.status } : { ok: true, text, status: a.status };
}
// ---------- grants per tool ----------
export type McpToolMode = "off" | "auto" | "ask";
/**
* The mode of one tool under one grant: the owner's own mode of the tool wins; otherwise the class
* mode (read for `readOnlyHint`, write for the rest). A suspicious tool gets nothing from the class:
* only the owner's explicit choice turns it on.
*/
export function mcpToolMode(tool: McpTool, g: { readMode: McpToolMode; writeMode: McpToolMode; tools?: Record<string, McpToolMode> | null }): McpToolMode {
const own = g.tools?.[tool.name];
if (own === "off" || own === "auto" || own === "ask") return own;
if (tool.suspicious?.length) return "off";
return tool.readOnly ? g.readMode : g.writeMode;
}
/** The stored list of a connection's config. */
export function mcpTools(config: Record<string, unknown> | null | undefined): McpTool[] {
const list = (config as { tools?: unknown } | null)?.tools;
return Array.isArray(list) ? (list as McpTool[]).filter((t) => t && isMcpToolName(t.name)) : [];
}

View File

@ -8,8 +8,9 @@ import { isIP } from "node:net";
import { posix } from "node:path";
import { m as tr } from "@peppa/shared/i18n";
export type ConnectionProtocol = "http" | "postgres" | "mysql" | "ssh" | "s3" | "mail";
export type GatewayProtocol = Exclude<ConnectionProtocol, "http">;
// PEP-236: mcp — a remote MCP server; its operations are the server's own tools (connection-mcp.ts).
export type ConnectionProtocol = "http" | "postgres" | "mysql" | "ssh" | "s3" | "mail" | "mcp";
export type GatewayProtocol = Exclude<ConnectionProtocol, "http" | "mcp">;
export const GATEWAY_PROTOCOLS: GatewayProtocol[] = ["postgres", "mysql", "ssh", "s3", "mail"];
export const isGatewayProtocol = (p: unknown): p is GatewayProtocol => GATEWAY_PROTOCOLS.includes(p as GatewayProtocol);

View File

@ -26,6 +26,7 @@ import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts";
import { projectForUser } from "./users.ts";
import { pausedProjectIds } from "./project-pause.ts";
import { approvalGate, type ApprovalPending, type ApprovalRequest } from "./connection-approvals.ts";
import { mcpToolMode, mcpTools } from "./connection-mcp.ts";
export { isBlockedAddress } from "./connection-protocols.ts";
@ -156,6 +157,8 @@ export interface ConnectionGrantView {
operations: string[];
readMode: GrantMode;
writeMode: GrantMode;
/** PEP-236: an MCP server's own modes per tool (null — none). */
tools: Record<string, GrantMode> | null;
createdAt: Date;
/** PEP-259: the term chosen; «Продлить» gives the same again. */
term: GrantTerm;
@ -334,21 +337,21 @@ export async function ownConnection(db: Db, userId: number, connectionId: number
return c;
}
function nameError(name: string): string | null {
export function nameError(name: string): string | null {
if (!name || name.length > CONNECTION_NAME_MAX) return tr("Название подключения: от 1 до {n} символов", { n: CONNECTION_NAME_MAX });
if (/[\u0000-\u001f\u007f]/.test(name)) return tr("Название подключения содержит недопустимые символы");
return null;
}
function secretError(secret: string): string | null {
export function secretError(secret: string): string | null {
if (!secret) return tr("Ключ доступа пустой");
if (Buffer.byteLength(secret) > CONNECTION_SECRET_MAX_BYTES) return tr("Ключ доступа больше 8 КБ");
if (/[\r\n\u0000]/.test(secret)) return tr("Ключ доступа должен быть одной строкой");
return null;
}
const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]);
export const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
export const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]);
// ---------- PEP-254: one data key per connection (envelope) ----------
@ -407,6 +410,8 @@ export interface ConnectionInput {
protocol?: ConnectionProtocol;
/** PEP-251: the form fields of that protocol (host, port, user…). */
config?: Record<string, unknown>;
/** PEP-236: tests / dev stand — the MCP server's transport. */
fetch?: ConnectionFetch;
}
const QUERY_PARAM_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
@ -429,7 +434,7 @@ export async function freeSlug(db: Db, userId: number, base: string, exceptId?:
/** PEP-260: a header value Node sends as is — visible ASCII, spaces only inside. */
const HEADER_KEY_RE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/;
function keyShapeError(authKind: CatalogAuth, secret: string): string | null {
export function keyShapeError(authKind: CatalogAuth, secret: string): string | null {
if ((authKind === "bearer" || authKind === "header") && !HEADER_KEY_RE.test(secret)) return tr("Ключ доступа может содержать только латинские буквы, цифры и знаки — проверьте, что вставили его целиком");
if (authKind === "basic" && !/^[^:]+:.+$/.test(secret)) return tr("Для этого сервиса вставьте ключ как «логин:пароль» через двоеточие");
if (authKind === "path" && !PATH_KEY_RE.test(secret)) return tr("Ключ доступа содержит недопустимые символы");
@ -437,6 +442,8 @@ function keyShapeError(authKind: CatalogAuth, secret: string): string | null {
}
export async function createConnection(db: Db, userId: number, i: ConnectionInput): Promise<ConnectionView> {
// PEP-236: a remote MCP server — the test (initialize + tools/list) runs right away.
if (i.protocol === "mcp") return (await import("./connection-mcp-hub.ts")).createMcpConnection(db, userId, i);
if (i.protocol && i.protocol !== "http") return createProtocolConnection(db, userId, i);
const card = i.catalogId ? catalogService(i.catalogId) : null;
if (i.catalogId && !card) throw new PeppaError(tr("Такого сервиса нет в каталоге"));
@ -520,7 +527,9 @@ export async function resetHostKey(db: Db, userId: number, connectionId: number)
export async function replaceConnectionSecret(db: Db, userId: number, connectionId: number, secret: string): Promise<void> {
const c = await ownConnection(db, userId, connectionId);
if (c.authKind === "oauth") throw new PeppaError(tr("Это подключение работает через вход в сервис: нажмите «Войти заново»"));
const err = isGatewayProtocol(c.protocol) ? protocolSecretError(c.protocol, secret) : (secretError(secret) ?? keyShapeError(c.authKind, secret));
// PEP-236: a public MCP server has no key — «включить снова» needs none.
if (c.protocol === "mcp" && c.authKind === "none") secret = "";
const err = c.protocol === "mcp" && c.authKind === "none" ? null : isGatewayProtocol(c.protocol) ? protocolSecretError(c.protocol, secret) : (secretError(secret) ?? keyShapeError(c.authKind, secret));
if (err) throw new PeppaError(err);
// A new key: the old check result and the «key stopped working» message no longer apply.
await db.update(connections).set({ ...sealConnectionSecret(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId));
@ -569,11 +578,22 @@ export interface GrantInput {
term?: GrantTerm;
/** «Дать: чтение / полные права» — sets both modes. */
rights?: GrantRights;
/** PEP-236: an MCP server's own mode per tool (wins over read / write). */
tools?: Record<string, GrantMode> | null;
now?: Date;
}
const mode = (m: unknown): GrantMode => (GRANT_MODES.includes(m as GrantMode) ? (m as GrantMode) : "off");
/** PEP-236: own modes only for tools the server listed; «as the class» entries are dropped. */
function normalizeToolModes(config: Record<string, unknown> | null, raw: Record<string, GrantMode> | null | undefined): Record<string, GrantMode> | null {
if (!raw) return null;
const known = new Set(mcpTools(config).map((t) => t.name));
const out: Record<string, GrantMode> = {};
for (const [name, m] of Object.entries(raw)) if (known.has(name) && GRANT_MODES.includes(m)) out[name] = m;
return Object.keys(out).length ? out : null;
}
export async function grantConnection(db: Db, userId: number, connectionId: number, g: GrantInput): Promise<ConnectionGrantView> {
const c = await ownConnection(db, userId, connectionId);
if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа"));
@ -588,19 +608,20 @@ export async function grantConnection(db: Db, userId: number, connectionId: numb
const term: GrantTerm = isGrantTerm(g.term) ? g.term : "forever";
const now = g.now ?? new Date();
const life = { term, expiresAt: GRANT_TERM_MS[term] == null ? null : new Date(now.getTime() + GRANT_TERM_MS[term]!), grantedAt: now, endedAt: null, endReason: null };
const anyMode = readMode !== "off" || writeMode !== "off";
const operations = normalizeOperations(g.operations ?? [], { allowEmpty: true });
const tools = c.protocol === "mcp" ? normalizeToolModes(c.config, g.tools) : null;
const anyMode = readMode !== "off" || writeMode !== "off" || Object.values(tools ?? {}).some((m) => m !== "off");
const operations = c.protocol === "http" ? normalizeOperations(g.operations ?? [], { allowEmpty: true }) : [];
if (!anyMode && !operations.length) throw new PeppaError(tr("Разрешите чтение, запись или хотя бы одну операцию"));
const existing = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, c.id), eq(connectionGrants.projectId, g.projectId)))).find((x) => x.agentId === agentId);
let id: number;
if (existing) {
await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId, ...life }).where(eq(connectionGrants.id, existing.id));
await db.update(connectionGrants).set({ operations, readMode, writeMode, tools, createdBy: userId, ...life }).where(eq(connectionGrants.id, existing.id));
id = existing.id;
} else {
const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId, ...life }).returning({ id: connectionGrants.id });
const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, tools, createdBy: userId, ...life }).returning({ id: connectionGrants.id });
id = row!.id;
}
await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode, term } });
await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode, term, ...(tools ? { tools } : {}) } });
return (await grantViews(db, [c.id], now)).find((x) => x.id === id)!;
}
@ -646,6 +667,7 @@ async function grantViews(db: Db, connectionIds: number[], now: Date = new Date(
operations: connectionGrants.operations,
readMode: connectionGrants.readMode,
writeMode: connectionGrants.writeMode,
tools: connectionGrants.tools,
createdAt: connectionGrants.createdAt,
term: connectionGrants.term,
expiresAt: connectionGrants.expiresAt,
@ -815,11 +837,12 @@ export async function agentConnections(db: Db, sessionId: number, o: { now?: Dat
if (grantState(r.g, now) !== "active") continue;
const card = catalogService(r.c.catalogId);
const proto = r.c.protocol;
const protocolOperations = isGatewayProtocol(proto) ? Object.entries(PROTOCOL_OPERATIONS[proto]).map(([name, op]) => ({ name, ...op })) : [];
const protocolOperations = isGatewayProtocol(proto) ? Object.entries(PROTOCOL_OPERATIONS[proto]).map(([name, op]) => ({ name, ...op })) : proto === "mcp" ? mcpTools(r.c.config).filter((t) => mcpToolMode(t, { readMode: r.readMode, writeMode: r.writeMode, tools: r.g.tools }) !== "off").map((t) => ({ name: t.name, kind: t.readOnly ? ("read" as const) : ("write" as const), args: Object.keys(((t.inputSchema as { properties?: object }).properties ?? {}) as object), help: t.description.slice(0, 300) })) : [];
const first = !by.has(r.c.id);
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, catalogId: card?.id ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.status === "relogin" ? "bad_key" : r.c.checkStatus, protocol: proto, protocolOperations, expiresAt: null };
c.expiresAt = first ? r.g.expiresAt : c.expiresAt && r.g.expiresAt ? (r.g.expiresAt > c.expiresAt ? r.g.expiresAt : c.expiresAt) : null;
c.operations = [...new Set([...c.operations, ...r.operations])];
if (!first) for (const op of protocolOperations) if (!c.protocolOperations.some((x) => x.name === op.name)) c.protocolOperations.push(op);
c.readMode = widest(c.readMode, r.readMode);
c.writeMode = widest(c.writeMode, r.writeMode);
by.set(r.c.id, c);
@ -1006,7 +1029,7 @@ export interface ApprovalOptions {
}
/** One outbound request, injectable in tests. */
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record<string, string>; body: Buffer | null; allowInternal?: boolean }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean; contentEncoding?: string | null }>;
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record<string, string>; body: Buffer | null; allowInternal?: boolean }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean; contentEncoding?: string | null; mcpSessionId?: string | null }>;
export class Refused extends Error {
reason: ConnectionReason;
@ -1048,7 +1071,7 @@ export const defaultConnectionFetch: ConnectionFetch = ({ url, method, headers,
}
chunks.push(c);
});
const done = () => resolve({ status: res.statusCode ?? 0, contentType: (res.headers["content-type"] as string | undefined) ?? null, body: Buffer.concat(chunks), truncated, location: !!res.headers.location, contentEncoding: (res.headers["content-encoding"] as string | undefined) ?? null });
const done = () => resolve({ status: res.statusCode ?? 0, contentType: (res.headers["content-type"] as string | undefined) ?? null, body: Buffer.concat(chunks), truncated, location: !!res.headers.location, contentEncoding: (res.headers["content-encoding"] as string | undefined) ?? null, mcpSessionId: (res.headers["mcp-session-id"] as string | undefined) ?? null });
res.on("end", done);
res.on("close", done);
res.on("error", () => (truncated ? done() : reject(new Refused("upstream_error"))));
@ -1288,6 +1311,7 @@ export interface ConnectionCheckOptions {
}
async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: ConnectionCheckOptions): Promise<ConnectionCheckResult & { relogin?: boolean }> {
if (conn.protocol === "mcp") return (await import("./connection-mcp-hub.ts")).mcpCheck(db, conn, o);
if (conn.protocol !== "http") return (await import("./connection-gateway.ts")).protocolCheck(db, conn, o);
const now = o.now ?? new Date();
const check = catalogService(conn.catalogId)?.check ?? null;

View File

@ -122,6 +122,8 @@ export * from "./access-requests.ts";
export * from "./connection-protocols.ts";
export * from "./connection-gateway.ts";
export * from "./connection-approvals.ts";
export * from "./connection-mcp.ts";
export * from "./connection-mcp-hub.ts";
export { DriverError, type GatewayDrivers, type SqlTarget, type SqlRequest, type SshTarget, type SshRequest, type SshAnswer, type MailTarget, type MailRequest, type MailAnswer, type TlsMode } from "./connection-drivers.ts";
export * from "./connection-mask.ts";
export * from "./connection-oauth.ts";

View File

@ -0,0 +1 @@
ALTER TABLE `connection_grants` ADD `tools` text;

File diff suppressed because it is too large Load Diff

View File

@ -260,6 +260,13 @@
"when": 1796036638399,
"tag": "0036_connection_approvals",
"breakpoints": true
},
{
"idx": 37,
"version": "6",
"when": 1796142700134,
"tag": "0037_access_hub_mcp",
"breakpoints": true
}
]
}

View File

@ -694,13 +694,13 @@ export const connections = sqliteTable(
// bearer: Authorization: Bearer <key>; header: <authHeader>: <key>; basic: «login:password»;
// query: ?<authHeader>=<key>; path: base URL + key (Telegram). PEP-249.
// oauth (PEP-252): Authorization: Bearer <access token>, refreshed by the gateway.
authKind: text("auth_kind").$type<"bearer" | "header" | "basic" | "query" | "path" | "oauth">().notNull().default("bearer"),
authKind: text("auth_kind").$type<"bearer" | "header" | "basic" | "query" | "path" | "oauth" | "none">().notNull().default("bearer"),
authHeader: text("auth_header"),
// PEP-249: the catalog card (core/connection-catalog.ts) or null = own service.
catalogId: text("catalog_id"),
// PEP-251: http (base_url + key) | postgres | mysql | ssh | s3 | mail; for the others
// base_url is only a display address and `config` holds host, port, user… (never the secret).
protocol: text("protocol").$type<"http" | "postgres" | "mysql" | "ssh" | "s3" | "mail">().notNull().default("http"),
protocol: text("protocol").$type<"http" | "postgres" | "mysql" | "ssh" | "s3" | "mail" | "mcp">().notNull().default("http"),
config: text("config", { mode: "json" }).$type<Record<string, unknown>>(),
// PEP-249: the agent's short name (`stripe`), unique per owner.
slug: text("slug"),
@ -742,6 +742,8 @@ export const connectionGrants = sqliteTable(
// PEP-249: read / write by the catalog's read rule; off | auto (at once) | ask (owner confirms, PEP-235).
readMode: text("read_mode").$type<"off" | "auto" | "ask">().notNull().default("off"),
writeMode: text("write_mode").$type<"off" | "auto" | "ask">().notNull().default("off"),
// PEP-236: an MCP server's own mode per tool (wins over read/write by `readOnlyHint`); null — none.
tools: text("tools", { mode: "json" }).$type<Record<string, "off" | "auto" | "ask">>(),
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
// PEP-259: the term chosen (extend gives the same again) and when it ends (null = until revoked).
term: text("term").$type<"1h" | "1d" | "7d" | "forever">().notNull().default("forever"),