diff --git a/CLAUDE.md b/CLAUDE.md index 90ef93614..7ec66cf63 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,9 @@ for the area you are changing first. The parts most changes touch: - **Agents** — WebMCP tools `lib/webmcp.ts` / `app/lab/agent-tools.ts`; MCP server `mcp/tools.ts`. **Federation is not MCP**: peers talk through `lib/federation-api.ts` at `/api/federation/v1/`; never register a federation op as an MCP tool. **The chat sidebar is the app's only model call and - is just another WebMCP client** — never give it a private way in. **The campaign engine never + is just another WebMCP client** — never give it a private way in. (The one exception is a + *connector*: an external MCP server the reader switches on, every call approved first, that reaches + only what the model puts in the call — [`ARCHITECTURE.md`](docs/ARCHITECTURE.md).) **The campaign engine never calls a model**, and a locked campaign is immutable at the database level. Other docs: [`DOMAIN.md`](docs/DOMAIN.md) (what the domain's words mean), diff --git a/app/_agent/ChatSidebar.tsx b/app/_agent/ChatSidebar.tsx index 24761459f..face286f3 100644 --- a/app/_agent/ChatSidebar.tsx +++ b/app/_agent/ChatSidebar.tsx @@ -11,12 +11,17 @@ // conversation and whether the panel is open live in sessionStorage; a conversation whose last // step was a tool call carries on once the new page's tools are up. import { useChat } from "@ai-sdk/react"; -import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls, type UIMessage } from "ai"; -import { ArrowLeftIcon, ArrowUpIcon, CheckIcon, HistoryIcon, MessageSquareIcon, PencilIcon, RotateCcwIcon, SquareIcon, SquarePenIcon, Trash2Icon, XIcon } from "lucide-react"; +import { DefaultChatTransport, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, type UIMessage } from "ai"; +import { ArrowLeftIcon, ArrowUpIcon, CheckIcon, HistoryIcon, MessageSquareIcon, PencilIcon, PlugIcon, RotateCcwIcon, ShieldAlertIcon, SquareIcon, SquarePenIcon, Trash2Icon, XIcon } from "lucide-react"; import { useEffect, useMemo, useRef, useState } from "react"; import { Button } from "@/app/_ui/button"; import { Textarea } from "@/app/_ui/textarea"; import { Input } from "@/app/_ui/input"; +import { Checkbox } from "@/app/_ui/checkbox"; +import { fromToolName, type ConnectorStatus, type PublicConnector } from "../../lib/chat-connectors.ts"; +import { + CONNECTOR_NOTE_KEY, canSwitchOn, connectUrl, loadState, requestEntries, saveState, signedIn, withOn, withToken, type ConnectorState +} from "../../lib/chat-connector-state.ts"; import { Conversation, ConversationContent, ConversationScrollButton } from "@/app/_ui/ai/conversation"; import { Message, MessageContent, MessageResponse } from "@/app/_ui/ai/message"; import { Reasoning } from "@/app/_ui/ai/reasoning"; @@ -49,6 +54,10 @@ function store(key: string, v: unknown) { const local = (): Storage | null => { try { return window.localStorage; } catch { return null; } }; const newId = () => (globalThis.crypto?.randomUUID?.() ?? String(Date.now()) + Math.random().toString(36).slice(2)); type Meta = { tools?: string[]; earlier?: string } | undefined; +/** a message the connector sign-in left for this page (sessionStorage), shown once */ +function takeNote(): string | null { + try { const n = sessionStorage.getItem(CONNECTOR_NOTE_KEY); if (n) sessionStorage.removeItem(CONNECTOR_NOTE_KEY); return n; } catch { return null; } +} /** The page's tools, waiting briefly for a page that registers them after it mounts. */ async function waitForPage(ms = 10000): Promise { @@ -76,21 +85,46 @@ function ChatPanel({ info }: { info: ChatInfo }) { const [historyNote, setHistoryNote] = useState<{ dropped: number; failed: boolean }>({ dropped: 0, failed: false }); const [showHistory, setShowHistory] = useState(false); const initial = useMemo(() => stored(STORE, []), []); + // connectors (issue #128): the reader's switches and sign-ins, kept in this browser; off until switched on + const [conn, setConn] = useState(() => loadState(local())); + const [connSaveFailed, setConnSaveFailed] = useState(false); + const [connStatus, setConnStatus] = useState>({}); + const [connNote, setConnNote] = useState(() => takeNote()); + const [showConnectors, setShowConnectors] = useState(() => !!connNote); + const infoRef = useRef(info); + infoRef.current = info; + const statusSink = useRef<(s: ConnectorStatus[]) => void>(() => {}); + statusSink.current = (list) => setConnStatus(Object.fromEntries(list.map((s) => [s.id, s]))); + // a connector's last-turn status describes the settings it had then: any change to it clears the status + const saveConn = (next: ConnectorState, changed: string) => { + setConn(next); + setConnSaveFailed(!saveState(local(), next)); + setConnStatus((s) => Object.fromEntries(Object.entries(s).filter(([id]) => id !== changed))); + }; const transport = useMemo(() => new DefaultChatTransport({ api: "/api/chat", + // what is on is read when the request is made, so a switch applies to the very next message prepareSendMessagesRequest: ({ messages }) => { const p = pageApi(); - return { body: { messages, page: p?.page ?? location.pathname, tools: p?.tools ?? [] } }; + const connectors = requestEntries(loadState(local()), infoRef.current.connectors, Date.now()); + return { body: { messages, page: p?.page ?? location.pathname, tools: p?.tools ?? [], connectors } }; + }, + // what became of each connector this turn comes back in a header + fetch: async (input, init) => { + const r = await fetch(input, init); + try { const h = r.headers.get("x-chat-connectors"); if (h) statusSink.current(JSON.parse(decodeURIComponent(h)) as ConnectorStatus[]); } catch { /* a status is a convenience */ } + return r; } }), []); - const { messages, sendMessage, addToolOutput, status, error, stop, setMessages, regenerate, clearError } = useChat({ + const { messages, sendMessage, addToolOutput, addToolApprovalResponse, status, error, stop, setMessages, regenerate, clearError } = useChat({ id: "sidebar", messages: initial, transport, throttle: 50, - sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls, + // a page tool the browser has run, or a connector call the reader has approved or denied + sendAutomaticallyWhen: (o) => lastAssistantMessageIsCompleteWithToolCalls(o) || lastAssistantMessageIsCompleteWithApprovalResponses(o), onToolCall: async ({ toolCall }) => { const { toolName, toolCallId, input: args } = toolCall; try { @@ -185,7 +219,9 @@ function ChatPanel({ info }: { info: ChatInfo }) { Assistant {info.model} - + + @@ -194,7 +230,13 @@ function ChatPanel({ info }: { info: ChatInfo }) { onRename={(id, t) => { const h = renamed(history, id, t); setHistory(h); setHistoryNote((n) => ({ ...n, failed: !saveHistory(local(), h) })); }} onRemove={(id) => { const h = removed(history, id); setHistory(h); setHistoryNote((n) => ({ ...n, failed: !saveHistory(local(), h) })); if (id === convId) newChat(); }} onClear={() => { setHistory([]); setHistoryNote({ dropped: 0, failed: !saveHistory(local(), []) }); }} />} - + {showConnectors && setConnNote(null)} + onSwitch={(id, on) => saveConn(withOn(conn, id, on), id)} + onDisconnect={(id) => saveConn(withToken(conn, id, null), id)} + onSaveToken={(id, token) => saveConn(withToken(conn, id, { token }), id)} + onConnect={(id) => { location.assign(connectUrl(id, location.pathname + location.search)); }} />} + {reopened && (

@@ -221,6 +263,9 @@ function ChatPanel({ info }: { info: ChatInfo }) { if (part.type === "dynamic-tool" || part.type.startsWith("tool-")) { const t = part as ToolPart; const name = t.type === "dynamic-tool" ? t.toolName : t.type.slice(5); + if (t.state === "approval-requested" && t.approval) + return void addToolApprovalResponse({ id: t.approval!.id, approved })} />; return ( @@ -249,6 +294,11 @@ function ChatPanel({ info }: { info: ChatInfo }) { + {info.connectors.some((c) => conn.on.includes(c.id)) && ( +

+ Connectors on: {info.connectors.filter((c) => conn.on.includes(c.id)).map((c) => c.name).join(", ")}. The assistant can ask {info.connectors.filter((c) => conn.on.includes(c.id)).length === 1 ? "it" : "them"}, and you approve each call first. +

+ )}
{ e.preventDefault(); submit(); }}> {info.signInRequired ?

Sign in to use the assistant.

@@ -316,3 +366,102 @@ function TitleField({ initial, onDone }: { initial: string; onDone: (title: stri
); } + +/** A connector call waiting for the reader: where it goes, what it sends, and the two answers. */ +function ApprovalCard({ name, input, connectors, onRespond }: { + name: string; input: unknown; connectors: PublicConnector[]; onRespond: (approved: boolean) => void; +}) { + const of = fromToolName(name); + const c = of && connectors.find((x) => x.id === of.id); + return ( +
+
+ +

+ The assistant wants to call {of?.tool ?? name} on {c?.name ?? of?.id ?? "an external server"} + {c && <> ({c.host})}, a server outside this app. This is exactly what it would send: +

+
+
{JSON.stringify(input, null, 2)}
+

Deny it if it names a patient or sample, or anything that could identify one person.

+
+ + +
+
+ ); +} + +/** The connectors: off until switched on, each with its sign-in when it needs one, and what became of it last turn. */ +function ConnectorsPanel({ connectors, error, state, status, note, saveFailed, onDismissNote, onSwitch, onDisconnect, onConnect, onSaveToken }: { + connectors: PublicConnector[]; error: string | null; state: ConnectorState; status: Record; note: string | null; saveFailed: boolean; + onDismissNote: () => void; onSwitch: (id: string, on: boolean) => void; onDisconnect: (id: string) => void; onConnect: (id: string) => void; onSaveToken: (id: string, token: string) => void; +}) { + const now = Date.now(); + return ( +
+

+ Connectors are external servers the assistant can ask. They are off until you switch them on. What the assistant writes in a call goes to that server, a third party, and this app cannot check it, + so you approve every call before it runs, and the assistant is told never to put a patient or sample identifier in one. Switches and sign-ins are kept in this browser only. +

+ {error &&

The deployment's connectors could not be read: {error}

} + {note &&

{note}

} + {saveFailed &&

This browser would not keep the setting (its storage is full or blocked), so connectors stay off.

} + {!error && connectors.length === 0 &&

This deployment has no connectors.

} +
    + {connectors.map((c) => { + const can = canSwitchOn(state, c, now); + const on = state.on.includes(c.id) && can.ok; + const s = status[c.id]; + return ( +
  • +
    +
    +
    {c.name} {c.host}
    +
    {c.what}
    +
    + +
    + {c.sendsFreeText &&

    It takes free text, so anything the assistant writes in a question leaves this app.

    } + {c.auth === "oauth" && ( +
    + {signedIn(state, c.id, now) + ? <>Signed in + : <>{state.tokens[c.id] ? "Sign-in expired." : "Not signed in."}} +
    + )} + {c.auth === "token" && ( + signedIn(state, c.id, now) + ?
    API token saved in this browser
    + : onSaveToken(c.id, t)} /> + )} + {!can.ok &&

    Cannot be switched on: {can.why}.

    } + {on && s && !s.ok && ( +

    + Not available at the last message: {s.reason}. + {s.signIn && c.auth === "oauth" && <> } + {s.signIn && c.auth === "token" && <> Remove the token and add a good one.} +

    + )} + {on && s?.ok &&

    Reached at the last message ({s.tools} {s.tools === 1 ? "tool" : "tools"}).

    } +
  • + ); + })} +
+
+ ); +} + +/** An API token being typed: the draft stays in this field; it is sent only to the connector's own server, in the header it names. */ +function TokenField({ name, onSave }: { name: string; onSave: (token: string) => void }) { + const [draft, setDraft] = useState(""); + return ( +
{ e.preventDefault(); if (draft.trim()) { onSave(draft.trim()); setDraft(""); } }}> + setDraft(e.target.value)} /> + +
+ ); +} diff --git a/app/_agent/ask.ts b/app/_agent/ask.ts index 6e77c6da8..3a80aaa8e 100644 --- a/app/_agent/ask.ts +++ b/app/_agent/ask.ts @@ -4,6 +4,7 @@ // sidebar handles it exactly as it handles typed text. It adds no tool and no private way into the // page: the model still reads the page only through the page's own tools. import { useEffect, useState } from "react"; +import type { PublicConnector } from "../../lib/chat-connectors.ts"; export const ASK_EVENT = "cbiolab:ask"; export interface AskDetail { text: string; /** drop the current conversation first (the default) */ newChat?: boolean } @@ -13,7 +14,7 @@ export function askAssistant(text: string, newChat = true): void { window.dispatchEvent(new CustomEvent(ASK_EVENT, { detail: { text, newChat } })); } -export interface ChatInfo { enabled: boolean; signInRequired: boolean; model: string | null } +export interface ChatInfo { enabled: boolean; signInRequired: boolean; model: string | null; connectors: PublicConnector[]; connectorsError: string | null } // one request per page load, shared by the sidebar and every button that needs to know let info: Promise | null = null; diff --git a/app/api/chat/connectors/oauth/callback/route.ts b/app/api/chat/connectors/oauth/callback/route.ts new file mode 100644 index 000000000..faef102da --- /dev/null +++ b/app/api/chat/connectors/oauth/callback/route.ts @@ -0,0 +1,29 @@ +// Step two: the server's sign-in page sends the reader back here with a code. The code becomes a +// token, which goes to the reader's browser and is forgotten (lib/chat-connector-oauth.ts). +import { connection } from "next/server"; +import { clearedCookie, doneHtml, failedHtml, finish, originOf, readFlow } from "../../../../../../lib/chat-connector-oauth.ts"; +import { chatGuard, registry } from "../../../../../../lib/chat-connector-tools.ts"; + +const html = (body: string, cookie: string) => + new Response(body, { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Set-Cookie": cookie } }); + +export async function GET(req: Request) { + await connection(); + const denied = chatGuard(req); + if (denied) return denied; + const origin = originOf(req); + const clear = clearedCookie(origin.startsWith("https:")); + const q = new URL(req.url).searchParams; + const flow = readFlow(req.headers.get("cookie")); + if (!flow) return html(failedHtml("This sign-in could not be finished: it was not started here, or it took more than ten minutes. Try Connect again.", "/"), clear); + if (q.get("error")) return html(failedHtml("The sign-in was not completed: " + (q.get("error_description") || q.get("error")), flow.returnTo), clear); + if (!q.get("code") || q.get("state") !== flow.state) return html(failedHtml("This sign-in could not be finished: its answer did not match the one asked for. Try Connect again.", flow.returnTo), clear); + try { + const c = registry().find((x) => x.id === flow.id); + if (!c) throw new Error("no such connector"); + const token = await finish(c, origin, flow, q.get("code")!); + return html(doneHtml(c, token, flow.returnTo), clear); + } catch (e) { + return html(failedHtml("The sign-in did not give a token: " + String((e as Error)?.message || e).slice(0, 200), flow.returnTo), clear); + } +} diff --git a/app/api/chat/connectors/oauth/start/route.ts b/app/api/chat/connectors/oauth/start/route.ts new file mode 100644 index 000000000..f8edf96b8 --- /dev/null +++ b/app/api/chat/connectors/oauth/start/route.ts @@ -0,0 +1,22 @@ +// Step one of signing a reader in to a connector (lib/chat-connector-oauth.ts): find the server's +// sign-in page and send the reader there. GET /api/chat/connectors/oauth/start?id=&returnTo= +import { connection } from "next/server"; +import { begin, clearedCookie, flowCookie, originOf } from "../../../../../../lib/chat-connector-oauth.ts"; +import { chatGuard, registry } from "../../../../../../lib/chat-connector-tools.ts"; + +export async function GET(req: Request) { + await connection(); + const denied = chatGuard(req); + if (denied) return denied; + const q = new URL(req.url).searchParams; + try { + const c = registry().find((x) => x.id === q.get("id")); + if (!c || c.auth !== "oauth") return Response.json({ error: "no connector here that needs a sign-in has that id" }, { status: 404 }); + const origin = originOf(req); + const { authUrl, flow } = await begin(c, origin, q.get("returnTo") || "/"); + const secure = origin.startsWith("https:"); + return new Response(null, { status: 302, headers: { Location: authUrl, "Set-Cookie": flowCookie(flow, secure), "Cache-Control": "no-store" } }); + } catch (e) { + return Response.json({ error: "could not start the sign-in: " + String((e as Error)?.message || e) }, { status: 502, headers: { "Set-Cookie": clearedCookie(originOf(req).startsWith("https:")) } }); + } +} diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts index 6dae1a0f2..0a1f95d87 100644 --- a/app/api/chat/route.ts +++ b/app/api/chat/route.ts @@ -5,7 +5,12 @@ // (window.cohortLab.tools), they are declared here WITHOUT an implementation, and each call the // model makes streams back to the browser, which runs it through window.cohortLab.call and sends // the result with the next request. This route never touches the database, the engine or the -// document; it holds no tool of its own. +// document; it holds no page tool of its own. +// +// The one thing it runs itself is a CONNECTOR (lib/chat-connectors.ts): an external MCP server the +// reader has switched on, whose tools each wait for the reader's approval. A connector reaches only +// what the model puts in an approved call — never the app's data, the engine or the page — and a +// request names it by id, so the address always comes from the deployment's registry. // // GET says whether this deployment has chat (lib/chat-model.ts: a dev server, or a deployment that // opts in off Vercel) and whether this browser must sign in first, as a deployment requires. @@ -14,6 +19,8 @@ import { z } from "zod"; import { connection } from "next/server"; import { chatConfig, chatModel, chatProviderOptions, type ChatConfig } from "../../../lib/chat-model.ts"; import { AccessError, loginEnabled, requirePrincipal, userFor } from "../../../lib/auth.ts"; +import { connectorInstructions, publicConnector, type Connector } from "../../../lib/chat-connectors.ts"; +import { approvalSecret, connectConnectors, registry } from "../../../lib/chat-connector-tools.ts"; export const maxDuration = 300; @@ -25,9 +32,12 @@ const PageTool = z.object({ const ChatRequest = z.object({ messages: z.array(z.record(z.string(), z.unknown())).min(1).max(400), page: z.string().max(100).default("unknown"), - tools: z.array(PageTool).max(64).default([]) + tools: z.array(PageTool).max(64).default([]), + /** the connectors the reader has on, by id, each with the reader's token when it needs one */ + connectors: z.array(z.object({ id: z.string().max(40), token: z.string().max(8000).optional() })).max(8).default([]) }); + const instructions = (page: string, names: string[]) => `You are the research assistant in the chat sidebar of cbio-lab, a cohort-analysis tool built on cBioPortal data. You act on the site only through the tools the current page exposes: the same WebMCP tools any researcher's assistant uses from outside the page. You cannot see the page except through them. Each page has its own tools; site_pages lists the pages and site_open moves to another one. After site_open the browser loads that page and this conversation continues there with its tools, so carry on with the task once they appear. @@ -48,8 +58,10 @@ export async function GET(req: Request) { await connection(); let c = null; try { c = config(); } catch { /* reported by POST */ } + let connectors: ReturnType[] = [], connectorsError: string | null = null; + try { connectors = registry().map(publicConnector); } catch (e) { connectorsError = String((e as Error)?.message || e); } return Response.json({ enabled: !!c, provider: c?.provider ?? null, model: c?.model ?? null, - signInRequired: !!c?.signIn && !userFor(req) }); + signInRequired: !!c?.signIn && !userFor(req), connectors, connectorsError }); } export async function POST(req: Request) { @@ -75,17 +87,31 @@ export async function POST(req: Request) { const tools: ToolSet = {}; for (const t of body.tools) tools[t.name] = tool({ description: t.description, inputSchema: jsonSchema(t.input) }); + // the connectors the reader switched on: run here, each tool after the reader's approval + let known: Connector[]; + try { known = registry(); } catch (e) { return Response.json({ error: String((e as Error)?.message || e) }, { status: 500 }); } + const connected = await connectConnectors(body.connectors, known); + for (const [name, t] of Object.entries(connected.tools)) if (!(name in tools)) tools[name] = t; + const on = body.connectors.map((a) => known.find((k) => k.id === a.id)).filter((k): k is Connector => !!k); + const result = streamText({ model: chatModel(c), - system: instructions(body.page, body.tools.map((t) => t.name)), + system: instructions(body.page, body.tools.map((t) => t.name)) + connectorInstructions(on, connected.status), messages: await convertToModelMessages(body.messages as unknown as UIMessage[], { ignoreIncompleteToolCalls: true }), tools, maxOutputTokens: 64000, providerOptions: chatProviderOptions(c), - abortSignal: req.signal + abortSignal: req.signal, + experimental_toolApprovalSecret: approvalSecret(), + // the connections end with the response, however it ends + onFinish: () => { void connected.close(); }, + onAbort: () => { void connected.close(); }, + onError: () => { void connected.close(); } }); return result.toUIMessageStreamResponse({ sendReasoning: true, + // what became of each connector this turn, for the sidebar's Connectors menu (reasons only; never a token) + headers: body.connectors.length ? { "x-chat-connectors": encodeURIComponent(JSON.stringify(connected.status)) } : {}, onError: (e) => String((e as Error)?.message || e) }); } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1131a3810..56e810bb6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -399,9 +399,21 @@ and commit both. assistant (Claude in Chrome, Claude Desktop) does: each request sends the tools the page exposes (`window.cohortLab.tools`), the route declares them **without implementations**, and every call runs in the browser through `window.cohortLab.call`. **Never give it a private way in** — no - tools in the route, no reading page state or calling the engine or an API directly. A capability + page tools in the route, no reading page state or calling the engine or an API directly. A capability it lacks is a new WebMCP tool, which every assistant then gets. Opening a page reloads it, so the conversation lives in `sessionStorage` and resumes on the new page's tools. No other route calls a model. + **The one exception is a connector** (`lib/chat-connectors.ts`, `lib/chat-connector-tools.ts`, issue + #128): an external MCP server the reader switches on — off by default — that the route itself calls. + It reaches only what the model puts in a call the reader approves, never the app's data, the engine or + the page; page tools still run in the browser through `window.cohortLab`. The rules that keep it that way: + a request names a connector by **id** and the address always comes from the deployment's registry + (`CHAT_CONNECTORS`, else the defaults), so a request cannot point the route anywhere; every connector tool + is namespaced `__`, **waits for the reader's approval** (the sidebar shows the server and the exact + arguments; approval requests are signed, so a browser cannot forge one) and has no "always allow"; the + reader's token (an OAuth sign-in, `lib/chat-connector-oauth.ts`, or a pasted API token) lives in their browser + (`localStorage`) and is sent per request, never stored, logged, cached or returned by the server; a connector that + cannot be reached is reported in the `x-chat-connectors` header and left out of that turn. The data-boundary + side is in [`DATA-BOUNDARY.md`](DATA-BOUNDARY.md) (Known limits). - **`mcp/tools.ts`** — MCP registry, for agents: `describe_dsl`, `run_analysis`, `render_oncoprint` (+v1 event tools). MCP returns oncoprints as a static image rendered from the server SVG; the interactive figure is the web app's, not a third renderer. It serves no federation: that is diff --git a/docs/DATA-BOUNDARY.md b/docs/DATA-BOUNDARY.md index 4ad9dd06d..c1bdfcead 100644 --- a/docs/DATA-BOUNDARY.md +++ b/docs/DATA-BOUNDARY.md @@ -261,6 +261,13 @@ suite fail. A test that cannot fail is decoration. ## Known limits — stated, not hidden +- **A connector sends what the model writes to a third party, and this app cannot check it.** A + chat **connector** (`lib/chat-connectors.ts`: OpenEvidence, cBioPortal MCP, or what `CHAT_CONNECTORS` + names) is an external server the reader switches on; it is off by default. What the assistant puts in a + call to one leaves the app, and free-text ones (`sendsFreeText`) can carry a patient fact in a question. The + guards are procedural, not technical: the model is told never to include an identifier, the reader approves + every call after seeing the server and the exact arguments (no "always allow"), and a connector never + receives the app's data, only that call. A deployment that must not allow it sets `CHAT_CONNECTORS=[]`. - **The assistant sends what a page shows to a model provider.** The chat sidebar (`CHAT_PROVIDER`) sends the page's content, and what its tools return, to Anthropic or Bedrock whenever the reader asks. The patient page's **Summarize** button diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index d557c20fd..31f8f11fb 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -136,6 +136,8 @@ see the security notes below. | `CHAT_MODEL` | Claude Sonnet 5.5 under the provider's id | the model | | `CHAT_EFFORT` | `medium` | `low`, `medium`, `high`, `xhigh` or `max` | | `CHAT_ON_DEPLOYMENT` | — | `1`: also on a built deployment (never on Vercel), for signed-in users only | +| `CHAT_CONNECTORS` | OpenEvidence and cBioPortal MCP | a JSON array of the external MCP servers the sidebar may offer, each `{id, name, url (https), auth: "none"\|"oauth"\|"token", tokenHeader (with "token"), what, sendsFreeText, tools?}`; `[]` offers none. A malformed entry is an error, never skipped | +| `CHAT_APPROVAL_SECRET` | `AUTH_SESSION_SECRET`, else one per process | signs the approval requests for connector calls, so a browser cannot forge one. Set it where several instances serve the chat, or an approval that lands on another instance is refused and the call is asked for again | The sidebar keeps a history of conversations in the browser's `localStorage` (key `cohortlab.chat.history`; `lib/chat-history.ts`), opened from the clock button in its header. It keeps @@ -144,6 +146,13 @@ assistant's replies, never what the tools returned. The live conversation stays with its tool results, which the resume-after-reload path needs. The history menu says when the oldest conversation was dropped, and when the browser's storage is full or blocked. +**Connectors** (issue #128) are external MCP servers the reader switches on in the sidebar's plug menu; all are +off until then. OpenEvidence takes an API token the reader pastes (sent in `x-api-token`); cBioPortal MCP takes an +OAuth sign-in (`/api/chat/connectors/oauth/…`, standard MCP OAuth with dynamic client registration, so the +server must accept this app's `/api/chat/connectors/oauth/callback` as a redirect). Tokens stay in the reader's +browser. Every connector call waits for the reader's approval. See `ARCHITECTURE.md` for the rule and +`DATA-BOUNDARY.md` for what it sends. + Where the assistant is on, the patient page also shows a **Summarize** button that puts a fixed prompt (`lib/summarize-prompt.ts`) to it in a new conversation; it has no setting of its own, so turning the assistant off removes it. What it sends is described in `DATA-BOUNDARY.md`, "Known limits". diff --git a/lib/chat-connector-oauth.ts b/lib/chat-connector-oauth.ts new file mode 100644 index 000000000..8ddbe866a --- /dev/null +++ b/lib/chat-connector-oauth.ts @@ -0,0 +1,133 @@ +// Signing a reader in to a connector that needs it (issue #128): the standard MCP OAuth flow — +// discovery, dynamic client registration, authorization code with PKCE — run by the SDK's own +// `auth()`, with NOTHING kept on the server. What the flow needs between its two requests (the PKCE +// verifier, the registered client, the state) rides in a short-lived httpOnly cookie; the token the +// server gives goes to the reader's browser (localStorage) on the callback page, and the server +// forgets it. Server only. +// +// The app registers itself with the server (dynamic client registration) on every sign-in, as the +// server advertises it accepts: a public client where the server allows one, otherwise a client +// with the secret the server hands back, which lives only in that cookie, for the ten minutes the +// sign-in may take. +import { auth, discoverAuthorizationServerMetadata, discoverOAuthProtectedResourceMetadata, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { randomBytes } from "node:crypto"; +import { CONNECTORS_KEY, CONNECTOR_NOTE_KEY, CONNECT_PATH, type ConnectorToken } from "./chat-connector-state.ts"; +import type { Connector } from "./chat-connectors.ts"; + +export const OAUTH_COOKIE = "cbiolab_connector_oauth"; +export const START_PATH = CONNECT_PATH; +export const CALLBACK_PATH = "/api/chat/connectors/oauth/callback"; +const COOKIE_PATH = "/api/chat/connectors/oauth"; +/** a sign-in must be finished within this, or its cookie is gone */ +export const FLOW_SECONDS = 600; + +/** How this app registers itself with a server, from what the server says it supports. */ +export interface Registration { grants: string[]; method: "none" | "client_secret_post" | "client_secret_basic" } +const GRANTS = ["authorization_code", "refresh_token"]; +export function registrationFor(meta: { grant_types_supported?: string[]; token_endpoint_auth_methods_supported?: string[] } | undefined): Registration { + const grants = meta?.grant_types_supported?.length ? GRANTS.filter((g) => meta.grant_types_supported!.includes(g)) : ["authorization_code"]; + const m = meta?.token_endpoint_auth_methods_supported; + const method = !m?.length || m.includes("none") ? "none" : m.includes("client_secret_post") ? "client_secret_post" : "client_secret_basic"; + return { grants: grants.length ? grants : ["authorization_code"], method }; +} +/** Ask the server what it supports: its protected-resource metadata names its authorization server, else the server itself is one. */ +async function discoverRegistration(serverUrl: string): Promise { + let issuer: string | URL = new URL(serverUrl).origin; + try { issuer = (await discoverOAuthProtectedResourceMetadata(serverUrl)).authorization_servers?.[0] ?? issuer; } catch { /* the server is its own authorization server */ } + return registrationFor(await discoverAuthorizationServerMetadata(issuer).catch(() => undefined)); +} + +/** What a sign-in carries from its first request to its second. */ +export interface Flow { id: string; state: string; verifier?: string; client?: OAuthClientInformationMixed; returnTo: string } + +/** where to go back to: a path on this site, never another site */ +export function safeReturnTo(x: string | null | undefined): string { + if (!x || !x.startsWith("/") || x.startsWith("//") || x.includes("\\") || /[\r\n]/.test(x)) return "/"; + try { + // Browsers strip tabs before parsing, so a path such as /\t/host can become an external URL. + const origin = "https://cbiolab.invalid"; + return new URL(x, origin).origin === origin ? x : "/"; + } catch { return "/"; } +} + +/** this app's address as the reader's browser sees it, behind a proxy too */ +export function originOf(req: Request): string { + const u = new URL(req.url); + const host = req.headers.get("x-forwarded-host") || u.host; + const proto = (req.headers.get("x-forwarded-proto") || u.protocol.replace(":", "")).split(",")[0].trim(); + return proto + "://" + host; +} + +class FlowProvider implements OAuthClientProvider { + tokensGiven: OAuthTokens | undefined; + authUrl: string | undefined; + origin: string; + flow: Flow; + how: Registration; + constructor(origin: string, flow: Flow, how: Registration) { this.origin = origin; this.flow = flow; this.how = how; } + get redirectUrl() { return this.origin + CALLBACK_PATH; } + get clientMetadata(): OAuthClientMetadata { + return { client_name: "cbio-lab", redirect_uris: [this.redirectUrl], grant_types: this.how.grants, response_types: ["code"], token_endpoint_auth_method: this.how.method }; + } + state() { return this.flow.state; } + clientInformation() { return this.flow.client; } + saveClientInformation(c: OAuthClientInformationMixed) { this.flow.client = c; } + tokens() { return undefined; } // never reuses one: every sign-in is a fresh one + saveTokens(t: OAuthTokens) { this.tokensGiven = t; } + redirectToAuthorization(u: URL) { this.authUrl = u.toString(); } + saveCodeVerifier(v: string) { this.flow.verifier = v; } + codeVerifier() { if (!this.flow.verifier) throw new Error("this sign-in has no code verifier"); return this.flow.verifier; } +} + +/** First request: where to send the reader to sign in, and the flow to remember until they return. */ +export async function begin(c: Connector, origin: string, returnTo: string): Promise<{ authUrl: string; flow: Flow }> { + const flow: Flow = { id: c.id, state: randomBytes(16).toString("base64url"), returnTo: safeReturnTo(returnTo) }; + const p = new FlowProvider(origin, flow, await discoverRegistration(c.url)); + const r = await auth(p, { serverUrl: c.url }); + if (r !== "REDIRECT" || !p.authUrl) throw new Error(`${c.name} did not ask for a sign-in`); + return { authUrl: p.authUrl, flow: p.flow }; +} + +/** Second request: trade the code for a token. */ +export async function finish(c: Connector, origin: string, flow: Flow, code: string): Promise { + const p = new FlowProvider(origin, flow, registrationFor(undefined)); // registration is over: only the code is traded + const r = await auth(p, { serverUrl: c.url, authorizationCode: code }); + if (r !== "AUTHORIZED" || !p.tokensGiven?.access_token) throw new Error(`${c.name} gave no token`); + const t = p.tokensGiven; + return { token: t.access_token, ...(typeof t.expires_in === "number" ? { expiresAt: Date.now() + t.expires_in * 1000 } : {}) }; +} + +const b64 = (x: unknown) => Buffer.from(JSON.stringify(x)).toString("base64url"); +export function flowCookie(flow: Flow, secure: boolean): string { + return `${OAUTH_COOKIE}=${b64(flow)}; Path=${COOKIE_PATH}; HttpOnly; SameSite=Lax; Max-Age=${FLOW_SECONDS}${secure ? "; Secure" : ""}`; +} +export const clearedCookie = (secure: boolean): string => `${OAUTH_COOKIE}=; Path=${COOKIE_PATH}; HttpOnly; SameSite=Lax; Max-Age=0${secure ? "; Secure" : ""}`; +export function readFlow(cookieHeader: string | null): Flow | null { + const m = cookieHeader?.split(/;\s*/).find((x) => x.startsWith(OAUTH_COOKIE + "=")); + if (!m) return null; + try { + const f = JSON.parse(Buffer.from(m.slice(OAUTH_COOKIE.length + 1), "base64url").toString()); + return f && typeof f.id === "string" && typeof f.state === "string" && typeof f.returnTo === "string" ? { ...f, returnTo: safeReturnTo(f.returnTo) } : null; + } catch { return null; } +} + +/** a value as JavaScript inside a `); +} +/** The callback's answer when the sign-in did not complete: back to the page, with the reason as a note. */ +export function failedHtml(message: string, returnTo: string): string { + const code = `try{sessionStorage.setItem(${js(CONNECTOR_NOTE_KEY)},${js(message)})}catch(e){}location.replace(${js(safeReturnTo(returnTo))})`; + return page(`

${message.replace(/[<>&"]/g, "")}

`); +} diff --git a/lib/chat-connector-state.ts b/lib/chat-connector-state.ts new file mode 100644 index 000000000..096ad7969 --- /dev/null +++ b/lib/chat-connector-state.ts @@ -0,0 +1,60 @@ +// What the browser remembers about connectors (issue #128): which the reader has switched on, and the +// token each one's sign-in gave. Kept in localStorage; nothing is stored on the server. Pure — the +// storage is passed in — so it runs under test. The OAuth callback page (lib/chat-connector-oauth.ts) +// writes the same shape. +import type { Connector } from "./chat-connectors.ts"; + +/** where a reader's sign-in to a connector starts (app/api/chat/connectors/oauth/start) */ +export const CONNECT_PATH = "/api/chat/connectors/oauth/start"; +export const connectUrl = (id: string, returnTo: string): string => CONNECT_PATH + "?id=" + encodeURIComponent(id) + "&returnTo=" + encodeURIComponent(returnTo); +export const CONNECTORS_KEY = "cohortlab.chat.connectors"; +/** a message the sign-in left for the sidebar to show once (sessionStorage) */ +export const CONNECTOR_NOTE_KEY = "cohortlab.chat.connectors.note"; + +export interface ConnectorToken { token: string; /** epoch ms; absent when the server gave none */ expiresAt?: number } +export interface ConnectorState { on: string[]; tokens: Record } +export interface Store { getItem(k: string): string | null; setItem(k: string, v: string): void } + +const EMPTY = (): ConnectorState => ({ on: [], tokens: {} }); + +/** The stored state; nothing on, nobody signed in, when there is none or it cannot be read. */ +export function loadState(store: Store | null): ConnectorState { + try { + const v = JSON.parse(store?.getItem(CONNECTORS_KEY) || "null"); + if (!v || typeof v !== "object") return EMPTY(); + const tokens: Record = {}; + for (const [id, t] of Object.entries((v.tokens || {}) as Record)) + if (t && typeof t.token === "string" && t.token) tokens[id] = { token: t.token, ...(typeof t.expiresAt === "number" ? { expiresAt: t.expiresAt } : {}) }; + return { on: Array.isArray(v.on) ? v.on.filter((x: unknown): x is string => typeof x === "string") : [], tokens }; + } catch { return EMPTY(); } +} +/** false when the store is full or blocked */ +export function saveState(store: Store | null, s: ConnectorState): boolean { + try { if (!store) return false; store.setItem(CONNECTORS_KEY, JSON.stringify(s)); return true; } catch { return false; } +} + +export const signedIn = (s: ConnectorState, id: string, now: number): boolean => { + const t = s.tokens[id]; + return !!t && !(t.expiresAt !== undefined && t.expiresAt <= now); +}; +/** Whether a connector may be on: one that needs a sign-in or a token needs one that has not run out. */ +export function canSwitchOn(s: ConnectorState, c: Pick, now: number): { ok: true } | { ok: false; why: string } { + if (c.auth === "none" || signedIn(s, c.id, now)) return { ok: true }; + return { ok: false, why: c.auth === "token" ? "add your API token first" : s.tokens[c.id] ? "the sign-in has expired: connect again" : "connect (sign in) first" }; +} +export function withOn(s: ConnectorState, id: string, on: boolean): ConnectorState { + return { ...s, on: on ? [...new Set([...s.on, id])] : s.on.filter((x) => x !== id) }; +} +export function withToken(s: ConnectorState, id: string, t: ConnectorToken | null): ConnectorState { + const tokens = { ...s.tokens }; + if (t) tokens[id] = t; else delete tokens[id]; + return { on: t ? s.on : s.on.filter((x) => x !== id), tokens }; +} +/** + * What a chat request names: each connector that is on AND may be (an OAuth or token one has a good + * credential), with its token. One stored as on that has lost its credential is left out, as the panel + * shows it off, so the model is not told about a connector that cannot answer. + */ +export function requestEntries(s: ConnectorState, known: Pick[], now: number): { id: string; token?: string }[] { + return known.filter((c) => s.on.includes(c.id) && canSwitchOn(s, c, now).ok).map((c) => ({ id: c.id, ...(signedIn(s, c.id, now) ? { token: s.tokens[c.id].token } : {}) })); +} diff --git a/lib/chat-connector-tools.ts b/lib/chat-connector-tools.ts new file mode 100644 index 000000000..dacb2bf38 --- /dev/null +++ b/lib/chat-connector-tools.ts @@ -0,0 +1,131 @@ +// The chat route's side of the connectors (issue #128): for one request, connect to each connector +// the reader has on, and turn its tools into tools the model can call — every one waiting for the +// reader's approval before it runs. Server only. +// +// A request names connectors by id and may carry the reader's token for each; the URL always comes +// from the registry (lib/chat-connectors.ts), so a request cannot point this at an address of its +// own choosing. A token is put in the Authorization header of the call and nowhere else: it is not +// logged, not cached, not returned. A connector that cannot be reached, or refuses the token, is +// reported and left out for the turn; it never fails the chat. +import { randomBytes } from "node:crypto"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"; +import { jsonSchema, tool, type ToolSet } from "ai"; +import { chatConfig } from "./chat-model.ts"; +import { loginEnabled, requirePrincipal, AccessError } from "./auth.ts"; +import { MAX_TOOLS, parseConnectors, toolName, tokenHeader, validToolName, type Connector, type ConnectorStatus } from "./chat-connectors.ts"; + +/** The deployment's connectors (CHAT_CONNECTORS or the defaults); a malformed setting is an error, not a quiet omission. */ +export const registry = (): Connector[] => parseConnectors(process.env.CHAT_CONNECTORS); + +/** + * The secret that signs each approval request, so a browser cannot send an approval for a call the + * model never made. A deployment with several instances sets CHAT_APPROVAL_SECRET (or + * AUTH_SESSION_SECRET) so they agree; otherwise each instance has its own, and an approval that + * reaches another one is refused and the call is asked for again. + */ +const own = randomBytes(32).toString("hex"); +export const approvalSecret = (): string => process.env.CHAT_APPROVAL_SECRET || process.env.AUTH_SESSION_SECRET || own; + +/** Where the chat is not on, or the reader must sign in first, the connector routes answer as /api/chat does; null when allowed. */ +export function chatGuard(req: Request): Response | null { + try { + const c = chatConfig(); + if (!c || (c.signIn && !loginEnabled())) return Response.json({ error: "this deployment has no chat" }, { status: 404 }); + if (c.signIn) requirePrincipal(req, "use the assistant"); + return null; + } catch (e) { + return Response.json({ error: String((e as Error)?.message || e) }, { status: e instanceof AccessError ? e.status : 500 }); + } +} + +export const CONNECT_MS = 15_000; +export const CALL_MS = 120_000; +/** what a connector's answer may be, so one cannot fill the model's context */ +export const MAX_RESULT_CHARS = 60_000; + +export interface Requested { id: string; token?: string } +export interface Connected { + tools: ToolSet; + /** one entry per connector that was asked for, in the order asked */ + status: ConnectorStatus[]; + /** ends every connection; safe to call more than once */ + close: () => Promise; +} + +/** + * A connector is used one request and one answer at a time, within a chat turn, so the stream a server + * may open to push messages of its own is declined (a 405, which the MCP spec lets a client take as "not + * offered"). Some servers hold that stream open and answer nothing else while it is: OpenEvidence's did. + */ +const noPushStream: typeof fetch = (input, init) => + (init?.method ?? "GET") === "GET" ? Promise.resolve(new Response(null, { status: 405 })) : fetch(input, init); + +const text = (e: unknown) => String((e as Error)?.message || e); + +/** Why a connection or a call failed, in words for the reader; `signIn` when a new sign-in would help. */ +export function refusal(e: unknown, auth: Connector["auth"] = "oauth"): { reason: string; signIn: boolean } { + const code = (e as StreamableHTTPError)?.code; + if (e instanceof UnauthorizedError || code === 401 || code === 403 || /\b40[13]\b|invalid_token|unauthori[sz]ed/i.test(text(e))) + return { reason: auth === "token" ? "it refused the API token (missing, expired or not accepted): check it" : "it refused the sign-in (missing, expired or not accepted): connect again", signIn: true }; + if (/abort|timeout|timed out|time out/i.test(text(e))) return { reason: "it did not answer in time", signIn: false }; + return { reason: "it could not be reached: " + text(e).slice(0, 200), signIn: false }; +} + +/** A tool result as text: its text parts, and a note for anything else; a server's own error becomes a thrown one. */ +export function resultText(r: { content?: unknown; isError?: boolean; structuredContent?: unknown }): string { + const parts = Array.isArray(r.content) ? r.content as { type?: string; text?: string }[] : []; + let out = parts.map((p) => p.type === "text" ? String(p.text ?? "") : `[${p.type ?? "unknown"} content not shown]`).join("\n"); + if (!out && r.structuredContent !== undefined) out = JSON.stringify(r.structuredContent, null, 2); + if (out.length > MAX_RESULT_CHARS) out = out.slice(0, MAX_RESULT_CHARS) + `\n… [${(out.length - MAX_RESULT_CHARS).toLocaleString()} more characters not shown]`; + if (r.isError) throw new Error(out || "the connector reported an error"); + return out; +} + +export async function connectConnectors(asked: Requested[], registry: Connector[], opts: { connectMs?: number; callMs?: number } = {}): Promise { + const tools: ToolSet = {}; + const status: ConnectorStatus[] = []; + const clients: Client[] = []; + const connectMs = opts.connectMs ?? CONNECT_MS, callMs = opts.callMs ?? CALL_MS; + const seen = new Set(); + const results = await Promise.all(asked.filter((a) => !seen.has(a.id) && !!seen.add(a.id)).map(async (a) => { + const c = registry.find((x) => x.id === a.id); + if (!c) return { status: { id: a.id, ok: false, tools: 0, reason: "this deployment has no such connector" } as ConnectorStatus, made: {} as ToolSet }; + if (c.auth !== "none" && !a.token) return { status: { id: c.id, ok: false, tools: 0, reason: c.auth === "token" ? "no API token: add yours in the Connectors menu" : "not signed in: connect it first", signIn: true } as ConnectorStatus, made: {} as ToolSet }; + const client = new Client({ name: "cbio-lab", version: "1" }); + try { + const transport = new StreamableHTTPClientTransport(new URL(c.url), { fetch: noPushStream, requestInit: a.token ? { headers: tokenHeader(c, a.token) } : {} }); + await client.connect(transport, { timeout: connectMs }); + clients.push(client); + const listed: Awaited>["tools"] = []; + let cursor: string | undefined; + do { + const page = await client.listTools(cursor === undefined ? undefined : { cursor }, { timeout: connectMs }); + listed.push(...page.tools); + cursor = page.nextCursor; + } while (cursor !== undefined); + const offered = c.tools ? listed.filter((t) => c.tools!.includes(t.name)) : listed; + if (offered.length > MAX_TOOLS) throw new Error(`it has ${offered.length} tools, over the ${MAX_TOOLS} one request may carry; list the ones to offer in the connector's "tools"`); + const made: ToolSet = {}; + for (const t of offered) { + const name = toolName(c.id, t.name); + if (!validToolName(name)) continue; // a name the model API refuses is left out, not renamed + made[name] = tool({ + description: `[${c.name}, an external server (${new URL(c.url).host}) — what you send leaves this app] ${t.description ?? t.name}`, + inputSchema: jsonSchema((t.inputSchema ?? { type: "object", properties: {} }) as Record), + needsApproval: true, + execute: async (args: unknown) => resultText(await client.callTool({ name: t.name, arguments: (args ?? {}) as Record }, undefined, { timeout: callMs }) as Parameters[0]) + }); + } + return { status: { id: c.id, ok: true, tools: Object.keys(made).length } as ConnectorStatus, made }; + } catch (e) { + await client.close().catch(() => {}); + const { reason, signIn } = refusal(e, c.auth); + return { status: { id: c.id, ok: false, tools: 0, reason, ...(signIn ? { signIn } : {}) } as ConnectorStatus, made: {} as ToolSet }; + } + })); + for (const r of results) { status.push(r.status); Object.assign(tools, r.made); } + let closed = false; + return { tools, status, close: async () => { if (closed) return; closed = true; await Promise.all(clients.map((c) => c.close().catch(() => {}))); } }; +} diff --git a/lib/chat-connectors.ts b/lib/chat-connectors.ts new file mode 100644 index 000000000..44330660d --- /dev/null +++ b/lib/chat-connectors.ts @@ -0,0 +1,105 @@ +// External MCP servers the chat sidebar can use ("connectors", issue #128): the registry, and how a +// connector's tools are named and described to the model. Pure and browser-safe. +// +// A connector is a remote server the READER switches on (off by default). It reaches only what the +// model puts in a call the reader approves — never the app's data, the engine or the page. The +// browser names connectors by id; the URL always comes from this registry, never from a request. + +export interface Connector { + id: string; + name: string; + /** the server's MCP endpoint, https only */ + url: string; + /** + * "oauth": the reader signs in to the server (lib/chat-connector-oauth.ts); + * "token": the reader pastes an API token, which goes in the header named by `tokenHeader`; + * "none": the server is open + */ + auth: "none" | "oauth" | "token"; + /** with auth "token": the header the server reads the token from (a bearer token is `Authorization`) */ + tokenHeader?: string; + /** what it is for, in a line — shown to the reader and told to the model */ + what: string; + /** takes free text from the model (a question), so a patient fact can leave in it */ + sendsFreeText: boolean; + /** only these of the server's tools are offered; absent means all, up to MAX_TOOLS */ + tools?: string[]; +} +/** what the browser may know of a connector: no more than it needs to show and to name it */ +export type PublicConnector = Pick & { host: string }; + +/** the header and value that carry a reader's token to a connector */ +export const tokenHeader = (c: Pick, token: string): Record => + c.auth === "oauth" || (c.auth === "token" && (c.tokenHeader ?? "Authorization").toLowerCase() === "authorization") + ? { Authorization: "Bearer " + token } : c.auth === "token" ? { [c.tokenHeader!]: token } : {}; + +export const MAX_TOOLS = 40; + +export const DEFAULT_CONNECTORS: Connector[] = [ + { id: "openevidence", name: "OpenEvidence", url: "https://oe-playground-723124486874.us-central1.run.app/mcp", auth: "token", tokenHeader: "x-api-token", sendsFreeText: true, + what: "clinical questions answered with citations from peer-reviewed literature (PubMed, FDA, CDC)" }, + { id: "cbioportal", name: "cBioPortal MCP", url: "https://mcp.cbioportal.org/db/mcp", auth: "oauth", sendsFreeText: false, + what: "cBioPortal's public data: its ClickHouse tables, study guides and OncoTree search" } +]; + +const ID = /^[a-z0-9-]{1,24}$/; + +/** + * The deployment's connectors: the defaults, or what CHAT_CONNECTORS (a JSON array) says. A + * malformed entry is an error naming it — never skipped, so a typo does not quietly remove one. + */ +export function parseConnectors(raw: string | undefined): Connector[] { + if (!raw?.trim()) return DEFAULT_CONNECTORS; + let list: unknown; + try { list = JSON.parse(raw); } catch (e) { throw new Error("CHAT_CONNECTORS is not JSON: " + (e as Error).message, { cause: e }); } + if (!Array.isArray(list)) throw new Error("CHAT_CONNECTORS must be a JSON array of connectors"); + const seen = new Set(); + return list.map((x, i) => { + const c = x as Partial | null; + const at = `CHAT_CONNECTORS[${i}]${c && typeof c.id === "string" ? " (" + c.id + ")" : ""}`; + if (!c || typeof c !== "object") throw new Error(at + " is not an object"); + if (typeof c.id !== "string" || !ID.test(c.id)) throw new Error(at + ": id is 1–24 lowercase letters, digits or -"); + if (seen.has(c.id)) throw new Error(at + ": id is used twice"); + seen.add(c.id); + if (typeof c.name !== "string" || !c.name.trim()) throw new Error(at + ": name is required"); + if (typeof c.what !== "string" || !c.what.trim()) throw new Error(at + ": what is required (a line saying what it is for)"); + let url: URL; + try { url = new URL(String(c.url)); } catch { throw new Error(at + ": url is not a URL"); } + if (url.protocol !== "https:") throw new Error(at + ": url must be https"); + if (c.auth !== "none" && c.auth !== "oauth" && c.auth !== "token") throw new Error(at + ': auth is "none", "oauth" or "token"'); + if (c.auth === "token" && !(typeof c.tokenHeader === "string" && /^[A-Za-z0-9-]{1,64}$/.test(c.tokenHeader))) throw new Error(at + ": a token connector names the header its token goes in (tokenHeader)"); + if (typeof c.sendsFreeText !== "boolean") throw new Error(at + ": sendsFreeText is true or false"); + if (c.tools !== undefined && (!Array.isArray(c.tools) || c.tools.some((t) => typeof t !== "string"))) throw new Error(at + ": tools is a list of tool names"); + return { id: c.id, name: c.name.trim(), url: url.toString(), auth: c.auth, what: c.what.trim(), sendsFreeText: c.sendsFreeText, ...(c.auth === "token" ? { tokenHeader: c.tokenHeader } : {}), ...(c.tools ? { tools: c.tools } : {}) }; + }); +} + +export const publicConnector = (c: Connector): PublicConnector => + ({ id: c.id, name: c.name, auth: c.auth, what: c.what, sendsFreeText: c.sendsFreeText, host: new URL(c.url).host }); + +const SEP = "__"; +/** a connector tool's name as the model sees it, which cannot shadow a page tool */ +export const toolName = (id: string, tool: string): string => id + SEP + tool; +/** the connector and tool a model's tool name stands for, or null for a page tool */ +export function fromToolName(name: string): { id: string; tool: string } | null { + const i = name.indexOf(SEP); + return i > 0 ? { id: name.slice(0, i), tool: name.slice(i + SEP.length) } : null; +} +/** a name the model API accepts (1–64 of letters, digits, _ -) */ +export const validToolName = (name: string): boolean => /^[A-Za-z0-9_-]{1,64}$/.test(name); + +export interface ConnectorStatus { id: string; ok: boolean; tools: number; reason?: string; signIn?: boolean } + +/** The paragraph of the model's instructions about the connectors that are on, and those that could not be reached. */ +export function connectorInstructions(on: Connector[], status: ConnectorStatus[]): string { + if (!on.length) return ""; + const live = on.filter((c) => status.find((s) => s.id === c.id)?.ok); + const down = status.filter((s) => !s.ok); + return [ + "", + "The researcher has switched on external connectors: remote servers outside this app. " + (live.length ? "Their tools are named __: " + + live.map((c) => `${c.id} (${c.name}: ${c.what})`).join("; ") + "." : "None of them could be reached this turn."), + "Every call to one is shown to the researcher, who approves or denies it first. What you put in a call leaves this app for a third party: never include a patient or sample identifier, a name, a date of birth, or any detail that could identify one person, and ask a general question instead. If a call is denied, do not repeat it with the same arguments; say what you could not do and why.", + ...(down.length ? ["Not available this turn: " + down.map((s) => `${on.find((c) => c.id === s.id)?.name ?? s.id} (${s.reason})`).join("; ") + ". Tell the researcher if they asked for it."] : []) + ].join("\n"); +} diff --git a/test/chat-connector-oauth.test.ts b/test/chat-connector-oauth.test.ts new file mode 100644 index 000000000..3d73f1fbc --- /dev/null +++ b/test/chat-connector-oauth.test.ts @@ -0,0 +1,164 @@ +// Signing in to a connector (lib/chat-connector-oauth.ts): the standard MCP OAuth flow end to end +// against a stub authorization server run in the test — discovery, dynamic client registration, the +// authorization URL with its PKCE challenge, and the code traded for a token — and what the flow +// leaves on the server (nothing), in the cookie (no token) and on the callback page (the token only +// for this browser's storage, escaped). +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { + OAUTH_COOKIE, begin, clearedCookie, doneHtml, failedHtml, finish, flowCookie, originOf, readFlow, registrationFor, safeReturnTo +} from "../lib/chat-connector-oauth.ts"; +import type { Connector } from "../lib/chat-connectors.ts"; + +let server: http.Server, base = ""; +const log: { path: string; body?: string }[] = []; +/** a server like mcp.cbioportal.org: confidential clients only, and registration must ask for both grants */ +const mode = { confidential: false }; + +before(async () => { + server = http.createServer((req, res) => { + let body = ""; + req.on("data", (d) => (body += d)); + req.on("end", () => { + log.push({ path: req.url || "", body }); + const json = (o: object, code = 200) => res.writeHead(code, { "content-type": "application/json" }).end(JSON.stringify(o)); + if (req.url === "/.well-known/oauth-authorization-server") return json({ + issuer: base, authorization_endpoint: base + "/authorize", token_endpoint: base + "/token", registration_endpoint: base + "/register", + response_types_supported: ["code"], code_challenge_methods_supported: ["S256"], + grant_types_supported: mode.confidential ? ["authorization_code", "refresh_token"] : ["authorization_code"], + token_endpoint_auth_methods_supported: mode.confidential ? ["client_secret_post"] : ["none"] + }); + if (req.url === "/register") { + const m = JSON.parse(body); + if (mode.confidential && (m.grant_types?.join() !== "authorization_code,refresh_token" || m.token_endpoint_auth_method !== "client_secret_post")) + return json({ error: "invalid_client_metadata", error_description: "grant_types must be authorization_code and refresh_token" }, 400); + return json({ ...m, client_id: "client-1", ...(mode.confidential ? { client_secret: "CS-secret" } : {}) }, 201); + } + if (req.url === "/token") { + const p = new URLSearchParams(body); + if (p.get("code") !== "the-code" || !p.get("code_verifier")) return json({ error: "invalid_grant" }, 400); + if (mode.confidential && p.get("client_secret") !== "CS-secret") return json({ error: "invalid_client" }, 401); + return json({ access_token: "AT-secret", token_type: "Bearer", expires_in: 3600, refresh_token: "RT-secret" }); + } + json({ error: "not found" }, 404); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + base = "http://127.0.0.1:" + (server.address() as AddressInfo).port; +}); +after(() => { server.closeAllConnections(); server.close(); }); + +const conn = (): Connector => ({ id: "cb", name: "CB", url: base + "/mcp", auth: "oauth", what: "w", sendsFreeText: false }); + +describe("the sign-in flow", () => { + test("begin registers this app, and sends the reader to the server's page with state and a PKCE challenge", async () => { + const { authUrl, flow } = await begin(conn(), "https://lab.example", "/portal/patient?study=s"); + const u = new URL(authUrl); + assert.equal(u.origin + u.pathname, base + "/authorize"); + assert.equal(u.searchParams.get("client_id"), "client-1"); + assert.equal(u.searchParams.get("redirect_uri"), "https://lab.example/api/chat/connectors/oauth/callback"); + assert.equal(u.searchParams.get("response_type"), "code"); + assert.equal(u.searchParams.get("code_challenge_method"), "S256"); + assert.ok(u.searchParams.get("code_challenge")); + assert.equal(u.searchParams.get("state"), flow.state); + assert.equal(flow.returnTo, "/portal/patient?study=s"); + assert.ok(flow.verifier && flow.client); + const reg = JSON.parse(log.find((l) => l.path === "/register")!.body!); + assert.equal(reg.token_endpoint_auth_method, "none", "a public client where the server allows one"); + assert.deepEqual(reg.redirect_uris, ["https://lab.example/api/chat/connectors/oauth/callback"]); + }); + test("finish trades the code for a token, with the verifier; the refresh token is not kept", async () => { + const { flow } = await begin(conn(), "https://lab.example", "/"); + const t = await finish(conn(), "https://lab.example", flow, "the-code"); + assert.equal(t.token, "AT-secret"); + assert.ok(t.expiresAt! > Date.now() + 3_000_000 && t.expiresAt! < Date.now() + 3_700_000); + assert.ok(!JSON.stringify(t).includes("RT-secret")); + }); + test("a server that takes only confidential clients and both grants is registered as such, and the secret is used to trade the code", async () => { + mode.confidential = true; + try { + const { authUrl, flow } = await begin(conn(), "https://lab.example", "/"); + assert.ok(authUrl.includes("client_id=client-1")); + assert.equal(flow.client && "client_secret" in flow.client ? flow.client.client_secret : null, "CS-secret"); + const t = await finish(conn(), "https://lab.example", flow, "the-code"); + assert.equal(t.token, "AT-secret"); + assert.ok(!JSON.stringify(t).includes("CS-secret"), "the secret does not go to the browser"); + } finally { mode.confidential = false; } + }); + test("what to register is read from what the server advertises", () => { + assert.deepEqual(registrationFor(undefined), { grants: ["authorization_code"], method: "none" }); + assert.deepEqual(registrationFor({ grant_types_supported: ["authorization_code", "refresh_token", "x"], token_endpoint_auth_methods_supported: ["client_secret_post"] }), { grants: ["authorization_code", "refresh_token"], method: "client_secret_post" }); + assert.equal(registrationFor({ token_endpoint_auth_methods_supported: ["client_secret_basic"] }).method, "client_secret_basic"); + assert.equal(registrationFor({ token_endpoint_auth_methods_supported: ["client_secret_post", "none"] }).method, "none", "a public client where the server allows one"); + }); + test("a wrong code gives no token, and says so", async () => { + const { flow } = await begin(conn(), "https://lab.example", "/"); + await assert.rejects(finish(conn(), "https://lab.example", flow, "other"), /invalid_grant|grant/i); + }); + test("the origin is the browser's, behind a proxy too", () => { + assert.equal(originOf(new Request("http://internal:3000/x")), "http://internal:3000"); + assert.equal(originOf(new Request("http://internal:3000/x", { headers: { "x-forwarded-host": "lab.example", "x-forwarded-proto": "https, http" } })), "https://lab.example"); + }); +}); + +describe("what the flow leaves behind", () => { + test("the cookie holds the flow (no token), is httpOnly and short-lived, and reads back", async () => { + const { flow } = await begin(conn(), "https://lab.example", "/a"); + const c = flowCookie(flow, true); + assert.match(c, /HttpOnly/); + assert.match(c, /SameSite=Lax/); + assert.match(c, /Max-Age=600/); + assert.match(c, /Secure/); + assert.ok(!flowCookie(flow, false).includes("Secure")); + assert.deepEqual(readFlow(c.split(";")[0] + "; other=1"), flow); + assert.match(clearedCookie(false), /Max-Age=0/); + }); + test("a missing, damaged or odd cookie is no flow", () => { + assert.equal(readFlow(null), null); + assert.equal(readFlow("a=b"), null); + assert.equal(readFlow(OAUTH_COOKIE + "=%%%"), null); + assert.equal(readFlow(OAUTH_COOKIE + "=" + Buffer.from('{"id":1}').toString("base64url")), null); + }); + test("a return address is a path on this site, never another", () => { + assert.equal(safeReturnTo("/portal/patient?a=1"), "/portal/patient?a=1"); + for (const bad of ["//evil.example", "https://evil.example", "/\\evil.example", "javascript:alert(1)", "", null, undefined, "/a\r\nSet-Cookie: x=1"]) + assert.equal(safeReturnTo(bad), "/", String(bad)); + assert.equal(readFlow(OAUTH_COOKIE + "=" + Buffer.from(JSON.stringify({ id: "a", state: "s", returnTo: "//evil.example" })).toString("base64url"))!.returnTo, "/"); + }); + test("browser URL normalization cannot turn a return path into an external redirect", () => { + for (const bad of ["/\t/evil.example", "/\t/evil.example/path", "/\t/["]) { + assert.equal(safeReturnTo(bad), "/"); + const cookie = OAUTH_COOKIE + "=" + Buffer.from(JSON.stringify({ id: "a", state: "s", returnTo: bad })).toString("base64url"); + assert.equal(readFlow(cookie)!.returnTo, "/"); + assert.match(doneHtml({ id: "a", name: "A" }, { token: "test" }, bad), /location\.replace\("\/"\)/); + assert.match(failedHtml("Denied", bad), /location\.replace\("\/"\)/); + } + for (const path of ["/portal/patient?a=1#summary", "/a/..//evil.example", "/?next=https://example.org"]) + assert.equal(safeReturnTo(path), path); + }); +}); + +describe("the callback page", () => { + test("writes the token to this browser's connector state and returns to the page", () => { + const h = doneHtml({ id: "cb", name: "CB" }, { token: "AT-secret", expiresAt: 5 }, "/portal/patient"); + assert.match(h, /var k="cohortlab\.chat\.connectors"/); + assert.match(h, /localStorage\.setItem\(k,/); + assert.match(h, /s\.tokens\["cb"\]=\{"token":"AT-secret","expiresAt":5\}/); + assert.match(h, /location\.replace\("\/portal\/patient"\)/); + }); + test("a value cannot end the script early or send the reader elsewhere", () => { + const h = doneHtml({ id: "cb", name: "CB" }, { token: "" }, "//evil.example"); + assert.ok(!h.includes("