peppa/packages/core/src/connection-mcp.ts

231 lines
12 KiB
TypeScript

// 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)) : [];
}