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
40 changes: 40 additions & 0 deletions dashboard/e2e/integrations-page.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,13 @@ async function mockApi(page: Page, init: Partial<Backend> = {}): Promise<Backend
return json(r, { status: "saved" });
}
if (/^\/api\/plugins\/[a-z]+\/test$/.test(p)) return json(r, { status: "ok", tool_count: 4 });
const own = p.match(/^\/api\/mcp-servers\/apps\/([a-z]+)$/);
if (own && method === "PUT") {
if (!at("admin")) return forbidden(r);
return json(r, { own_app: { id: `app-${own[1]}`, client_id: body?.client_id, has_secret: true, status: "not_connected", status_reason: "", connected_by: "", connected_at: "", redirect_uri: "http://localhost:3000/settings/integrations/mcp-callback/" } });
}
if (/^\/api\/mcp-servers\/app-[a-z]+\/connect$/.test(p)) return json(r, { authorize_url: "/settings/integrations/mcp-callback/?state=s1&code=c1" });
if (p === "/api/mcp-servers/oauth/callback") return json(r, { server: { id: "app-figma", name: "Figma", catalog_id: "figma" }, tools_error: null, own_app: true });
if (p === "/api/alert-notify" && method === "GET") return at("admin") ? json(r, db.notify) : forbidden(r);
if (p === "/api/alert-notify" && method === "PUT") {
if (!at("admin")) return forbidden(r);
Expand Down Expand Up @@ -610,3 +617,36 @@ test("a saved webhook shows only as a hint, is tested without the page knowing i
slack_webhook: { clear: true },
});
});

test("Figma signs in with the team's own app, its redirect URL and scopes shown, a key still possible", async ({ page }) => {
const db = await mockApi(page);
const figma = db.items.find((i) => i.id === "figma")!;
(figma.detail as Record<string, unknown>).own_app_redirect_uri = "https://coderhelm.example.com/settings/integrations/mcp-callback/";
(figma.detail as { plugin: Record<string, unknown> }).plugin.own_app = {
authorize: "https://www.figma.com/oauth",
token: "https://api.figma.com/v1/oauth/token",
refresh: "https://api.figma.com/v1/oauth/refresh",
scopes: ["current_user:read", "file_content:read"],
console: "https://www.figma.com/developers/apps",
guide: "https://developers.figma.com/docs/rest-api/oauth-apps/",
};
await page.goto("/settings/integrations#integration-figma");
const panel = row(page, "figma").getByTestId("own-app");
await expect(panel).toContainText("Use my own Figma app");
await expect(panel.getByTestId("own-app-redirect")).toHaveText("https://coderhelm.example.com/settings/integrations/mcp-callback/");
await expect(panel).toContainText("current_user:read, file_content:read");
await expect(panel.getByRole("link", { name: "www.figma.com/developers/apps" })).toHaveAttribute("href", "https://www.figma.com/developers/apps");
// The key form waits behind its disclosure.
await expect(row(page, "figma").getByText("Use a key instead")).toBeVisible();
const go = panel.getByRole("button", { name: "Save and connect with Figma" });
await expect(go).toBeDisabled();
await panel.getByLabel("Client ID").fill("client-1");
await panel.getByLabel("Client secret").fill("secret-1");
await go.click();
// Saved, then sent to Figma's sign-in, whose answer the callback page finishes.
await expect.poll(() => db.calls.some((c) => c.path === "/api/mcp-servers/oauth/callback")).toBe(true);
const saved = db.calls.find((c) => c.method === "PUT" && c.path === "/api/mcp-servers/apps/figma");
expect(saved?.body).toEqual({ client_id: "client-1", client_secret: "secret-1" });
expect(db.calls.some((c) => c.method === "POST" && c.path === "/api/mcp-servers/app-figma/connect")).toBe(true);
await expect(page).toHaveURL(/\/settings\/integrations\/#integration-figma$/);
});
14 changes: 11 additions & 3 deletions dashboard/src/app/settings/integrations/mcp-callback/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default function McpCallbackGuarded() {
);
}

type View = { kind: "working" } | { kind: "idle" } | { kind: "failed"; message: string } | { kind: "done"; name: string; note: string };
type View = { kind: "working" } | { kind: "idle" } | { kind: "failed"; message: string } | { kind: "done"; name: string; note: string; ownApp: boolean };

function McpCallback() {
const [view, setView] = useState<View>({ kind: "working" });
Expand Down Expand Up @@ -61,7 +61,7 @@ function McpCallback() {
.then((r) => {
const s = r.server;
const knowledgeApp = s.catalog_id?.startsWith("source:");
setView({ kind: "done", name: knowledgeApp ? s.name.replace(/ \(knowledge\)$/, "") : s.name, note: knowledgeApp ? "" : (r.tools_error ?? "") });
setView({ kind: "done", name: knowledgeApp ? s.name.replace(/ \(knowledge\)$/, "") : s.name, note: knowledgeApp ? "" : (r.tools_error ?? ""), ownApp: !!r.own_app });
// Opened as a popup (a sign-in card in a chat or a run, or Knowledge
// signing in without leaving its page): tell the page that opened
// it, and close. That page carries on by itself.
Expand Down Expand Up @@ -107,7 +107,15 @@ function McpCallback() {
)}
{view.kind === "done" && (
<Callout variant="success" title={`${view.name} is connected`}>
<p>{view.note ? "Connected, but its tools couldn't be listed yet. Open Integrations to try again." : "Taking you back to pick its tools…"}</p>
<p>
{view.ownApp
? view.note
? `Signed in, but ${view.name} didn't accept the token. Open Integrations to see why.`
: "Taking you back to Integrations…"
: view.note
? "Connected, but its tools couldn't be listed yet. Open Integrations to try again."
: "Taking you back to pick its tools…"}
</p>
{view.note && <TechnicalDetails text={view.note} />}
</Callout>
)}
Expand Down
162 changes: 159 additions & 3 deletions dashboard/src/components/mcp-server-panel.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
"use client";

import { useState } from "react";
import { api, type Integration, type McpServer, type PluginDef } from "@/lib/api";
import { api, type Integration, type McpServer, type OwnAppState, type PluginDef } from "@/lib/api";
import { errorMessage } from "@/lib/data-sources";
import { Field, SecretInput } from "./field";
import { Disclosure } from "./disclosure";
import { MarkdownEditor } from "./markdown-editor";
import { useConfirm } from "./confirm-dialog";
import { useToast } from "./toast";
import { inputClass, linkButton, primaryButton, secondaryButton } from "./ui";
import { connectCatalogServer } from "./mcp-servers";
import { connectCatalogServer, startMcpSignIn } from "./mcp-servers";
import { CopyButton } from "./copy-button";

// A catalog MCP server (Sentry, Linear, Notion…), opened in place on
// Integrations and on Connections: signing in through the vendor's remote
// server when it has one, or a key, its instructions and turning it off.

/** An MCP server: credentials (entered here, never shown again), its test, its instructions, and turning it off. */
export function PluginPanel({ item, onChanged, onClose }: { item: Integration; onChanged: () => Promise<void>; onClose: () => void }) {
const d = item.detail as { plugin: PluginDef; enabled: boolean; has_credentials: boolean; custom_prompt: string; remote?: McpServer | null };
const d = item.detail as { plugin: PluginDef; enabled: boolean; has_credentials: boolean; custom_prompt: string; remote?: McpServer | null; own_app?: OwnAppState | null; own_app_redirect_uri?: string | null };
const p = d.plugin;
const keyForm = <PluginKeyPanel item={item} onChanged={onChanged} onClose={onClose} />;
// The vendor's MCP server takes only apps it approved, but its API takes
// the team's own app: sign in with that, or use a key.
if (p.own_app) {
const signedIn = d.own_app?.status === "connected";
return (
<div className="mt-4 flex flex-col gap-4">
<OwnAppPanel plugin={p} state={d.own_app ?? null} redirectUri={d.own_app_redirect_uri ?? ""} onChanged={onChanged} />
<Disclosure summary="Use a key instead" defaultOpen={!signedIn && d.has_credentials}>
{keyForm}
</Disclosure>
</div>
);
}
const noKey = p.key_unavailable ? (
<p className="text-sm text-zinc-400" data-testid="key-unavailable">
{p.key_unavailable}
Expand Down Expand Up @@ -127,6 +141,148 @@ function OAuthOffer({ plugin }: { plugin: PluginDef }) {
);
}

/** The team's own OAuth app with the vendor: where to create it, its client id and secret, and signing in with it. */
function OwnAppPanel({ plugin, state, redirectUri, onChanged }: { plugin: PluginDef; state: OwnAppState | null; redirectUri: string; onChanged: () => Promise<void> }) {
const app = plugin.own_app!;
const [clientId, setClientId] = useState(state?.client_id ?? "");
const [secret, setSecret] = useState("");
const [busy, setBusy] = useState<"" | "save" | "connect" | "remove">("");
const [error, setError] = useState("");
const { toast } = useToast();
const { confirm } = useConfirm();
// The API names this install's callback; the page's own address is the same one.
const redirect = redirectUri || state?.redirect_uri || `${window.location.origin}/settings/integrations/mcp-callback/`;
const sameApp = !!state && clientId.trim() === state.client_id;
const canSave = !!clientId.trim() && (!!secret.trim() || (sameApp && state!.has_secret));

const connect = async (id: string) => {
setBusy("connect");
try {
await startMcpSignIn(id);
} catch (e) {
setError(errorMessage(e, "Couldn't start the sign-in."));
setBusy("");
}
};
const save = async (thenConnect: boolean) => {
setBusy("save");
setError("");
try {
const r = await api.saveOwnApp(plugin.id, clientId.trim(), secret.trim());
setSecret("");
if (thenConnect) {
await connect(r.own_app.id);
return;
}
toast(`Your ${plugin.name} app is saved`);
await onChanged();
} catch (e) {
setError(errorMessage(e, "Couldn't save the app."));
} finally {
setBusy((b) => (b === "save" ? "" : b));
}
};
const remove = async () => {
if (!state) return;
const ok = await confirm({
title: `Remove your ${plugin.name} app?`,
message: `Agents stop using its sign-in (and use the saved key, if there is one). The app itself stays in ${plugin.name}.`,
confirmLabel: "Remove",
destructive: true,
});
if (!ok) return;
setBusy("remove");
try {
await api.removeMcpServer(state.id);
setClientId("");
await onChanged();
} catch (e) {
toast(errorMessage(e, "Couldn't remove it."), "error");
} finally {
setBusy("");
}
};

return (
<div className="flex flex-col gap-3 rounded-lg border border-zinc-800 bg-zinc-900/60 p-3" data-testid="own-app">
<p className="text-sm font-medium text-zinc-200">Use my own {plugin.name} app</p>
{state?.status === "connected" ? (
<p className="text-sm text-emerald-400" data-testid="own-app-status">
Signed in{state.connected_by ? ` by ${state.connected_by}` : ""}. Agents use {plugin.name} with this sign-in.
</p>
) : state?.status_reason ? (
<p role="alert" className="text-sm text-amber-400" data-testid="own-app-status">
{state.status_reason}
</p>
) : null}
<ol className="list-decimal space-y-1 pl-5 text-sm text-zinc-400">
<li>
Create an app at{" "}
<a href={app.console} target="_blank" rel="noreferrer" className={linkButton}>
{app.console.replace(/^https:\/\//, "")}
</a>{" "}
under your {plugin.name} team or organization.
</li>
<li>
Add this redirect URL:{" "}
<code className="wrap-anywhere rounded bg-zinc-800 px-1 py-0.5 text-xs text-zinc-200" data-testid="own-app-redirect">
{redirect}
</code>{" "}
<CopyButton text={redirect} variant="link" />
</li>
<li>
Give it exactly these scopes: <span className="text-zinc-200">{app.scopes.join(", ")}</span>.
</li>
<li>Publish it as a private app (no review needed), then paste its client id and secret here.</li>
</ol>
<form
className="flex flex-col gap-3"
onSubmit={(e) => {
e.preventDefault();
void save(true);
}}
>
<Field id={`${plugin.id}-own-client-id`} label="Client ID">
{(props) => <input {...props} className={inputClass} value={clientId} onChange={(e) => setClientId(e.target.value)} autoComplete="off" />}
</Field>
<Field id={`${plugin.id}-own-client-secret`} label="Client secret">
{(props) => (
<SecretInput
{...props}
className={inputClass}
placeholder={sameApp && state?.has_secret ? "Saved. Paste a new one to replace it." : ""}
value={secret}
onChange={(e) => setSecret(e.target.value)}
autoComplete="off"
/>
)}
</Field>
{error && (
<p role="alert" className="text-sm text-red-400">
{error}
</p>
)}
<div className="flex flex-wrap gap-2">
{sameApp && !secret.trim() ? (
<button type="button" disabled={!!busy} className={primaryButton} onClick={() => void connect(state!.id)}>
{busy === "connect" ? "Opening sign-in…" : state!.status === "connected" ? "Sign in again" : `Connect with ${plugin.name}`}
</button>
) : (
<button type="submit" disabled={!!busy || !canSave} className={primaryButton}>
{busy ? "Saving…" : `Save and connect with ${plugin.name}`}
</button>
)}
{state && (
<button type="button" disabled={!!busy} className={secondaryButton} onClick={() => void remove()}>
{busy === "remove" ? "Removing…" : "Remove my app"}
</button>
)}
</div>
</form>
</div>
);
}

/** An MCP server run with a key: credentials (entered here, never shown again), its test, its instructions, and turning it off. */
function PluginKeyPanel({ item, onChanged, onClose }: { item: Integration; onChanged: () => Promise<void>; onClose: () => void }) {
const d = item.detail as { plugin: PluginDef; enabled: boolean; has_credentials: boolean; custom_prompt: string };
Expand Down
37 changes: 36 additions & 1 deletion dashboard/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1456,14 +1456,20 @@ export const api = {
connectMcpServer: (id: string) =>
request<{ authorize_url: string }>(`/api/mcp-servers/${encodeURIComponent(id)}/connect`, { method: "POST" }),
finishMcpSignIn: (body: { state: string; code?: string; error?: string; iss?: string }) =>
request<{ server: McpServer; tools_error: string | null }>("/api/mcp-servers/oauth/callback", {
request<{ server: McpServer; tools_error: string | null; own_app?: boolean }>("/api/mcp-servers/oauth/callback", {
method: "POST",
body: JSON.stringify(body),
}),
disconnectMcpServer: (id: string) =>
request<{ server: McpServer; revoked: boolean }>(`/api/mcp-servers/${encodeURIComponent(id)}/connection`, { method: "DELETE" }),
removeMcpServer: (id: string) =>
request<{ status: string }>(`/api/mcp-servers/${encodeURIComponent(id)}`, { method: "DELETE" }),
/** Saves the team's own OAuth app for a catalog server (a blank secret keeps the saved one for the same client id). */
saveOwnApp: (catalogId: string, client_id: string, client_secret: string) =>
request<{ own_app: OwnAppState }>(`/api/mcp-servers/apps/${encodeURIComponent(catalogId)}`, {
method: "PUT",
body: JSON.stringify({ client_id, client_secret }),
}),
setMcpClient: (id: string, client_id: string, client_secret: string) =>
request<{ server: McpServer }>(`/api/mcp-servers/${encodeURIComponent(id)}/client`, {
method: "PUT",
Expand Down Expand Up @@ -2998,6 +3004,35 @@ export interface PluginDef {
remote_key?: boolean;
/** Why no key works for it, in plain words; empty when one does. */
key_unavailable?: string;
/** Its package also takes a token from the team's own OAuth app with the vendor (Figma). */
own_app?: OwnAppDef;
}

/** Where a team creates its own OAuth app for a catalog server, and what to give it. */
export interface OwnAppDef {
authorize: string;
token: string;
refresh: string;
/** The scopes to tick on the app, exactly. */
scopes: string[];
/** Where the app is created. */
console: string;
/** The vendor's guide to creating one. */
guide: string;
}

/** A team's own app for a catalog server, as its card shows it (never the secret). */
export interface OwnAppState {
/** The connection's id, for connect, disconnect and remove. */
id: string;
client_id: string;
has_secret: boolean;
status: "connected" | "not_connected" | "needs_reconnect" | "failed";
status_reason: string;
connected_by: string;
connected_at: string;
/** The redirect URL to add to the app. */
redirect_uri: string;
}

export interface EnabledPlugin {
Expand Down
2 changes: 1 addition & 1 deletion dashboard/src/lib/openapi-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// docs/api/openapi.json. Do not edit; run `npm run openapi:fields` instead.

/** The platform commit this was generated from. */
export const OPENAPI_REF = "b25ce7b6fe2825b72a6bc191de6f288f2c22a9bc";
export const OPENAPI_REF = "5f361c3ff7c755e6f015ad0869df4fde5fd985e5";

/** The fields each public API schema has. */
export interface OpenApiFields {
Expand Down
Loading