Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<op>`;
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),
Expand Down
163 changes: 156 additions & 7 deletions app/_agent/ChatSidebar.tsx

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion app/_agent/ask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -13,7 +14,7 @@ export function askAssistant(text: string, newChat = true): void {
window.dispatchEvent(new CustomEvent<AskDetail>(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<ChatInfo | null> | null = null;
Expand Down
29 changes: 29 additions & 0 deletions app/api/chat/connectors/oauth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
22 changes: 22 additions & 0 deletions app/api/chat/connectors/oauth/start/route.ts
Original file line number Diff line number Diff line change
@@ -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=<connector>&returnTo=<path>
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:")) } });
}
}
36 changes: 31 additions & 5 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;

Expand All @@ -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.
Expand All @@ -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<typeof publicConnector>[] = [], 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) {
Expand All @@ -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)
});
}
14 changes: 13 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<id>__<tool>`, **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
Expand Down
7 changes: 7 additions & 0 deletions docs/DATA-BOUNDARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions docs/ENVIRONMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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".
Expand Down
Loading
Loading