Skip to content
Merged
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
27 changes: 26 additions & 1 deletion docs/custom-mcp-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,29 @@ key named **MCP Client** under **Settings → API Keys**, where revoking it ends
the connection. The key lasts one year, then the card asks you to sign in
again. See [BubblaV's OpenMausBot guide](https://docs.bubblav.com/user-guide/integrations/openmausbot).

### Gemini Notebook

In Plugins, find **Gemini Notebook** and click **Connect**. The card uses
Google's official hosted MCP endpoint, `https://notebook.googleapis.com/mcp`
(Gemini Notebook API, public preview). Google signs in only an app you
register yourself, so the card asks for its client ID and secret first:

1. In a Google Cloud project of your own, enable the API:
`gcloud services enable notebook.googleapis.com --project=<project>`. No
billing account is needed.
2. Under **Google Auth Platform**, set up the consent screen for an
**External** audience, add yourself under **Test users**, and add the
scope `https://www.googleapis.com/auth/notebook` under **Data access**.
3. Under **Clients**, create a **Desktop app** client and paste its client ID
and secret into the card.

**Connect** then opens Google's sign-in. The card saves the app like
**Sign-in app** below, so later sign-ins need no paste. While the API is in
preview it accepts personal Google accounts only, and each account must have
opened `notebook.google.com` once. Its tools create, list and rename notebooks
and add web, YouTube and text sources; it cannot delete, upload files or read a
notebook's contents yet.

### Servers that ask you to sign in

Some URL servers take no token; they want you to sign in with your browser
Expand Down Expand Up @@ -160,7 +183,9 @@ has nothing to work on. Background checks never do this.
address or removing the server drops them. **Sign out** revokes them when
the server offers that, then forgets them.
- **Refresh.** A token is refreshed shortly before it expires. If the server
refuses the refresh, the server goes back to **Needs sign-in**.
refuses the refresh, the server goes back to **Needs sign-in**. Google
issues a refresh token only when asked for offline access, so a sign-in at
`accounts.google.com` asks for it and shows Google's consent page each time.

#### Signing in from another computer

Expand Down
55 changes: 55 additions & 0 deletions server/mcp-oauth-vendor-wiring.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const vendor = vi.hoisted(() => ({ issuer: "", calls: [] as string[] }));
vi.mock("./mcp-oauth-vendor.ts", () => ({
vendorAuthorizationParams: (issuer: string) => {
vendor.calls.push(issuer);
return issuer === vendor.issuer ? { access_type: "offline", prompt: "consent" } : {};
},
}));

import { McpOAuthManager } from "./mcp-oauth.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "./testing/fake-http-mcp-server.ts";
import { startFakeOAuth, type FakeOAuth } from "./testing/fake-oauth-server.ts";

let dir: string;
let oauth: FakeOAuth;
let mcp: FakeHttpMcp;
let manager: McpOAuthManager;

beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), "mcp-oauth-vendor-"));
vendor.calls = [];
oauth = await startFakeOAuth();
mcp = await startFakeHttpMcp({ acceptBearer: oauth.isValid, wwwAuthenticate: oauth.challenge });
manager = new McpOAuthManager({ file: join(dir, "mcp-oauth.json") });
});
afterEach(async () => {
manager.dispose();
await mcp.close();
await oauth.close();
rmSync(dir, { recursive: true, force: true });
});

describe("authorization request parameters a vendor needs", () => {
it("asks the discovered issuer's vendor parameters and puts them on the authorization link", async () => {
vendor.issuer = oauth.issuer;
const started = await manager.start("docs", mcp.url);
expect(vendor.calls).toEqual([oauth.issuer]);
const link = new URL(started.authorizationUrl!);
expect(link.searchParams.get("access_type")).toBe("offline");
expect(link.searchParams.get("prompt")).toBe("consent");
expect(link.searchParams.get("code_challenge_method")).toBe("S256");
});

it("adds nothing when the issuer's vendor needs nothing", async () => {
vendor.issuer = "https://accounts.google.com";
const started = await manager.start("docs", mcp.url);
const link = new URL(started.authorizationUrl!);
expect(link.searchParams.has("access_type")).toBe(false);
expect(link.searchParams.has("prompt")).toBe(false);
});
});
16 changes: 16 additions & 0 deletions server/mcp-oauth-vendor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";

import { vendorAuthorizationParams } from "./mcp-oauth-vendor.ts";

describe("vendorAuthorizationParams", () => {
it("asks Google for offline access and a fresh consent, with or without the trailing slash", () => {
expect(vendorAuthorizationParams("https://accounts.google.com")).toEqual({ access_type: "offline", prompt: "consent" });
expect(vendorAuthorizationParams("https://accounts.google.com/")).toEqual({ access_type: "offline", prompt: "consent" });
});

it("adds nothing for any other issuer, including look-alikes", () => {
expect(vendorAuthorizationParams("https://login.microsoftonline.com/tenant/v2.0")).toEqual({});
expect(vendorAuthorizationParams("https://accounts.google.com.evil.example")).toEqual({});
expect(vendorAuthorizationParams("http://accounts.google.com")).toEqual({});
});
});
13 changes: 13 additions & 0 deletions server/mcp-oauth-vendor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const GOOGLE_ISSUER = "https://accounts.google.com";

/**
* Authorization request parameters an authorization server needs beyond RFC 6749 to issue a refresh token.
*
* Google issues a refresh token only when the request asks for `access_type=offline`, and to an app the account has
* approved before only with `prompt=consent`; it does not honour the `offline_access` scope
* (https://developers.google.com/identity/protocols/oauth2/native-app#step-2:-send-a-request-to-googles-oauth-2.0-server).
* Without them a Google MCP server (Gmail, Calendar, Gemini Notebook) is signed out when its one-hour token expires.
*/
export function vendorAuthorizationParams(issuer: string): Record<string, string> {
return issuer.replace(/\/+$/u, "") === GOOGLE_ISSUER ? { access_type: "offline", prompt: "consent" } : {};
}
1 change: 1 addition & 0 deletions server/mcp-oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ describe("McpOAuthManager sign-in", () => {
expect(link.origin + link.pathname).toBe(`${oauth.issuer}/authorize`);
expect(link.searchParams.get("code_challenge_method")).toBe("S256");
expect(link.searchParams.get("resource")).toBe(mcp.url);
expect(link.searchParams.has("access_type")).toBe(false);
expect(link.searchParams.get("redirect_uri")).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/mcp-oauth\/callback$/);

const page = await approve(started);
Expand Down
2 changes: 2 additions & 0 deletions server/mcp-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isDeepStrictEqual } from "node:util";

import type { McpServerSpec } from "./contracts.ts";
import { discoverMcpAuth, type McpAuthMetadata } from "./mcp-oauth-discovery.ts";
import { vendorAuthorizationParams } from "./mcp-oauth-vendor.ts";
import { McpOAuthStore, type McpOAuthRecord, type McpOAuthTokens } from "./mcp-oauth-store.ts";
import type { McpOAuthClientConfig } from "./mcp-registry.ts";

Expand Down Expand Up @@ -707,6 +708,7 @@ export class McpOAuthManager {
authorize.searchParams.set("code_challenge_method", "S256");
authorize.searchParams.set("resource", meta.resource);
if (scopes?.length) authorize.searchParams.set("scope", scopes.join(" "));
for (const [key, value] of Object.entries(vendorAuthorizationParams(meta.issuer))) authorize.searchParams.set(key, value);

const status: McpSignInStatus = {
phase: "waiting",
Expand Down
134 changes: 131 additions & 3 deletions src/components/McpServersPanel.hosted.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ vi.mock("./bot-panel/panel-link", () => ({ openBotSettings: fixture.openBotSetti
import { openExternalLink } from "@/lib/app-links";
import { McpServersPanel } from "./McpServersPanel";

interface Listing { name: string; type: "http"; url: string; headerKeys: string[]; enabled: boolean; auth: "signed-in" | "needs-sign-in"; managedBy?: string }
interface Listing { name: string; type: "http"; url: string; headerKeys: string[]; enabled: boolean; auth: "signed-in" | "needs-sign-in"; managedBy?: string; oauth?: { clientId: string; scopes: string[]; clientSecretConfigured: boolean } }
const listing = (app: HostedApp, extra: Partial<Listing> = {}): Listing => ({ name: app.id, type: "http", url: app.url, headerKeys: [], enabled: false, auth: "needs-sign-in", ...extra });

let host: HTMLDivElement;
Expand Down Expand Up @@ -68,7 +68,11 @@ beforeEach(() => {
const body = init?.body ? JSON.parse(init.body as string) : undefined;
if (path === "/api/mcp/servers" && !init?.method) return Promise.resolve({ servers: structuredClone(servers) });
// Like the real server, every answer is a fresh copy, and a listing names its headers without their values.
const saved = ({ headers, ...entry }: { headers?: Record<string, string> } & Record<string, unknown>) => ({ ...entry, headerKeys: Object.keys(headers ?? {}).sort() });
const saved = ({ headers, oauth, ...entry }: { headers?: Record<string, string>; oauth?: { clientId: string; clientSecret?: string; scopes?: string[] } } & Record<string, unknown>) => ({
...entry,
headerKeys: Object.keys(headers ?? {}).sort(),
...(oauth ? { oauth: { clientId: oauth.clientId, scopes: oauth.scopes ?? [], clientSecretConfigured: Boolean(oauth.clientSecret) } } : {}),
});
if (path === "/api/mcp/servers" && init?.method === "POST") {
servers.push({ auth: "needs-sign-in", ...saved(body) } as Listing);
return Promise.resolve({ servers: structuredClone(servers) });
Expand All @@ -93,7 +97,7 @@ afterEach(async () => {
host.remove();
});

describe.each(HOSTED_MCP_APPS.filter((app) => !("key" in app)))("The $label card", (app) => {
describe.each(HOSTED_MCP_APPS.filter((app) => !("key" in app) && !("client" in app)))("The $label card", (app) => {
async function connect() {
await act(async () => button(app, "Connect").click());
await settle();
Expand Down Expand Up @@ -410,3 +414,127 @@ describe("the person's own MCP servers in the Connected view", () => {
expect(host.querySelector("[data-mcp-tile]")).toBeNull();
});
});

describe.each(HOSTED_MCP_APPS.filter((app) => "client" in app))("The $label card, which signs in only an app registered in advance", (app) => {
const field = (label: string) => card(app).querySelector<HTMLInputElement>(`input[aria-label="${label}"]`)!;
const idField = () => field(`${app.label} client ID`);
const secretField = () => field(`${app.label} client secret`);
const connectButton = () => button(app, "Connect") as HTMLButtonElement;

async function type(input: HTMLInputElement, value: string) {
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}

async function connectWith(clientId: string, secret: string) {
await type(idField(), clientId);
await type(secretField(), secret);
await act(async () => connectButton().click());
await settle();
}

it("keeps Connect off until both a client ID and its secret are typed, and hides the secret", async () => {
await mount();
expect(secretField().type).toBe("password");
expect(connectButton().disabled).toBe(true);
await type(idField(), "123.apps.googleusercontent.com");
expect(connectButton().disabled).toBe(true);
await type(secretField(), " ");
expect(connectButton().disabled).toBe(true);
await type(secretField(), "GOCSPX-secret");
expect(connectButton().disabled).toBe(false);
});

it("saves the app with its scopes on a server left off, then signs in as that app", async () => {
await mount();
await connectWith(" 123.apps.googleusercontent.com ", " GOCSPX-secret ");
expect(added()).toEqual([{
name: app.id, type: "http", url: app.url, enabled: false,
oauth: { clientId: "123.apps.googleusercontent.com", clientSecret: "GOCSPX-secret", scopes: [...app.client.scopes] },
}]);
expect(fixture.runMcpSignIn).toHaveBeenCalledWith(app.id, expect.anything());
expect(fixture.api.mock.calls.map(([path]) => String(path)).some((path) => path.includes("GOCSPX"))).toBe(false);
});

it("signs in again with the saved app without asking for it", async () => {
servers = [listing(app, { oauth: { clientId: "123.apps.googleusercontent.com", scopes: [...app.client.scopes], clientSecretConfigured: true } })];
await mount();
expect(card(app).textContent).toContain("Signs in with the saved app 123.apps.googleusercontent.com.");
expect(connectButton().disabled).toBe(false);
await act(async () => connectButton().click());
await settle();
expect(added()).toEqual([]);
expect(calls("PUT")).toEqual([]);
expect(fixture.runMcpSignIn).toHaveBeenCalledWith(app.id, expect.anything());
});

it("replaces the app on the server it already has, under any name, instead of adding another", async () => {
servers = [listing(app, { name: "notebooks", oauth: { clientId: "old", scopes: [], clientSecretConfigured: true } })];
await mount();
await connectWith("new.apps.googleusercontent.com", "GOCSPX-new");
expect(added()).toEqual([]);
expect(calls("PUT")).toEqual([["/api/mcp/servers/notebooks", {
type: "http", url: app.url, enabled: false,
oauth: { clientId: "new.apps.googleusercontent.com", clientSecret: "GOCSPX-new", scopes: [...app.client.scopes] },
}]]);
expect(fixture.runMcpSignIn).toHaveBeenCalledWith("notebooks", expect.anything());
});

it("opens the provider's page for registering the app", async () => {
await mount();
await act(async () => button(app, `Create a ${app.label} sign-in app`).click());
expect(openExternalLink).toHaveBeenCalledWith(app.client.url);
});

const savedApp = { clientId: "123.apps.googleusercontent.com", scopes: [...app.client.scopes], clientSecretConfigured: true };

it("never signs in with the saved app while a half-typed replacement is in the fields", async () => {
servers = [listing(app, { oauth: savedApp })];
await mount();
await type(secretField(), "GOCSPX-new");
expect(connectButton().disabled).toBe(true);
await act(async () => secretField().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
await settle();
expect(fixture.runMcpSignIn).not.toHaveBeenCalled();
expect(calls("PUT")).toEqual([]);
});

it("turns the server on once its tools load after sign-in", async () => {
await mount();
await connectWith("123.apps.googleusercontent.com", "GOCSPX-secret");
await act(async () => testRequest!.resolve({ ok: true, tools: [{ name: "list_notebooks" }] }));
await settle();
expect(calls("PATCH")).toEqual([[`/api/mcp/servers/${app.id}`, { enabled: true }]]);
});

it("turns the server off and signs out on Disconnect, keeping the saved app", async () => {
servers = [listing(app, { enabled: true, auth: "signed-in", oauth: savedApp })];
await mount();
expect(card(app).querySelector('[aria-label="Connected"]')).not.toBeNull();
await act(async () => button(app, "Disconnect").click());
await settle();
expect(calls("DELETE")).toEqual([]);
expect(fixture.api.mock.calls.map(([path]) => path).slice(-2)).toEqual([`/api/mcp/servers/${app.id}`, `/api/mcp/servers/${app.id}/sign-out`]);
expect(card(app).textContent).toContain("Signs in with the saved app 123.apps.googleusercontent.com.");
});

it("cannot connect, by button or Enter, a server the organization manages or a policy that allows no custom servers", async () => {
servers = [listing(app, { managedBy: "Acme", oauth: savedApp })];
await mount();
expect(connectButton().disabled).toBe(true);
expect(idField().disabled).toBe(true);
expect(secretField().disabled).toBe(true);
await act(async () => secretField().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
await settle();
expect(fixture.runMcpSignIn).not.toHaveBeenCalled();
await act(async () => root.unmount());
host.remove();
servers = [];
fixture.store = { ...fixture.store, config: { managedPolicy: { organizationName: "Acme", mcp: { allowCustom: false, allowlist: [] } } } };
await mount();
expect(connectButton().disabled).toBe(true);
expect(secretField().disabled).toBe(true);
});
});
Loading
Loading