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
22 changes: 19 additions & 3 deletions apps/desktop/src/acp/mockMcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const signedOut = (server: JsonObject): JsonObject => ({
});

/**
* The mock's remote MCP servers that sign in with OAuth: the seeded `sentry` row and any server
* added through `_rustcode/capabilities/mcp/add`, which signs itself in a moment later as the
* The mock's remote MCP servers that sign in with OAuth: the seeded `sentry` row, a `vercel` row
* whose sign-in failed, and any server added through `_rustcode/capabilities/mcp/add`, which signs itself in a moment later as the
* engine's browser login would. Reconnecting one signs it in; logging out forgets it.
*/
export class MockAddedMcp {
Expand All @@ -24,6 +24,16 @@ export class MockAddedMcp {
scope: "user",
error: null,
}),
{
name: "vercel",
transport: "http",
target: "https://mcp.vercel.com",
enabled: true,
scope: "user",
connection: "failed",
tools: 0,
error: "MCP OAuth for 'vercel': token request failed (HTTP 401): invalid_client",
},
];

apply(method: string, params: JsonObject) {
Expand Down Expand Up @@ -61,7 +71,13 @@ export class MockAddedMcp {
if (!this.servers.some((server) => str(server.name) === name)) return false;
this.servers = this.servers.map((server) =>
str(server.name) === name
? { ...server, connection: "connected", tools: name === "sentry" ? 58 : 12, auth: "signed_in" }
? {
...server,
connection: "connected",
tools: name === "sentry" ? 58 : 12,
auth: "signed_in",
error: null,
}
: server,
);
return true;
Expand Down
43 changes: 43 additions & 0 deletions apps/desktop/src/ui/Connectors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, expect, test } from "bun:test";
import type { McpServer } from "./Capabilities";
import { cardState, firstLine } from "./Connectors";

const server = (over: Partial<McpServer>): McpServer => ({
name: "vercel",
transport: "http",
target: "https://mcp.vercel.com",
enabled: true,
scope: "user",
connection: "connecting",
tools: [],
toolCount: 0,
envKeys: [],
headerKeys: [],
copyTarget: null,
...over,
});

describe("connector card state", () => {
test("an app not set up is available", () => {
expect(cardState(undefined)).toBe("available");
});

test("a failed connection offers a retry instead of a dead chip", () => {
expect(cardState(server({ connection: "failed", error: "client registration failed" }))).toBe("failed");
});

test("a signed-out server asks for a sign-in even with an error", () => {
expect(cardState(server({ auth: "signed_out", error: "sign-in required" }))).toBe("signed-out");
});

test("connected and off win over everything else", () => {
expect(cardState(server({ connection: "connected", auth: "signed_in" }))).toBe("connected");
expect(cardState(server({ enabled: false, error: "x" }))).toBe("off");
});
});

test("a card error drops the engine's server prefix and keeps the first line", () => {
expect(firstLine("MCP OAuth for 'vercel': token request failed (HTTP 401)\nmore")).toBe(
"token request failed (HTTP 401)",
);
});
144 changes: 124 additions & 20 deletions apps/desktop/src/ui/Connectors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import { Search } from "./icons";
import { cx, noTextHelpers, Segments, Spinner } from "./primitives";
import { Action, Chip, fieldClass, SectionTitle } from "./settingsKit";

type Busy = { id: string; step: "adding" | "signing-in" } | null;
type Step = "adding" | "signing-in" | "removing";
type Busy = { id: string; step: Step } | null;

/**
* Settings › Connections › Apps: a gallery of hosted MCP servers. Connect adds one to this
Expand Down Expand Up @@ -97,6 +98,18 @@ export function ConnectorGallery() {
}
};

const remove = async (connector: Connector, server: McpServer) => {
setBusy({ id: connector.id, step: "removing" });
try {
await request(Method.mcpRemove, { name: server.name }, 15_000);
toast(`${connector.name} was removed.`, "info");
} catch (e) {
toast(errorText(e), "error");
} finally {
setBusy(null);
}
};

const reconnect = async (connector: Connector, server: McpServer) => {
try {
await signIn(connector, server.name);
Expand All @@ -107,9 +120,14 @@ export function ConnectorGallery() {
}
};

const shown = CONNECTORS.filter(
(c) => (category === "all" || c.category === category) && matchesConnector(c, query),
const servers = data?.mcpServers ?? [];
const shown = sortConnected(
CONNECTORS.filter((c) => (category === "all" || c.category === category) && matchesConnector(c, query)),
servers,
);
const connectedCount = CONNECTORS.filter(
(c) => configuredAs(c, servers)?.connection === "connected",
).length;
return (
<section className="mb-6" data-setting="Apps">
<SectionTitle
Expand All @@ -123,6 +141,7 @@ export function ConnectorGallery() {
<p className="mb-3 max-w-[70ch] px-4 text-callout text-fg-muted">
Connect an app to give every thread its tools. Sign-ins open in your browser and stay on this
computer.
{connectedCount > 0 ? ` ${connectedCount} connected.` : ""}
</p>
<div className="mb-3 flex flex-wrap items-center gap-2 px-1">
<label
Expand Down Expand Up @@ -157,6 +176,7 @@ export function ConnectorGallery() {
disabled={busy !== null && busy.id !== connector.id}
onConnect={() => void connect(connector)}
onSignIn={(server) => void reconnect(connector, server)}
onRemove={(server) => void remove(connector, server)}
/>
))}
</ul>
Expand All @@ -173,42 +193,65 @@ function ConnectorCard({
disabled,
onConnect,
onSignIn,
onRemove,
}: {
connector: Connector;
server: McpServer | undefined;
loading: boolean;
busy: "adding" | "signing-in" | null;
busy: Step | null;
disabled: boolean;
onConnect: () => void;
onSignIn: (server: McpServer) => void;
onRemove: (server: McpServer) => void;
}) {
const connected = server?.connection === "connected";
const needsSignIn = server && !connected && server.enabled && server.auth === "signed_out";
const state = cardState(server);
const status = busy ? BUSY_TEXT[busy] : cardStatus(connector, server, state);
const problem = !busy && state !== "connected" && Boolean(server?.error);
return (
<li className="flex min-h-[68px] items-center gap-3 rounded-xl bg-surface px-3 py-2">
<li
className={cx(
"flex min-h-[68px] items-center gap-3 rounded-xl px-3 py-2",
state === "connected" ? "bg-success/6" : state === "failed" ? "bg-danger/6" : "bg-surface",
)}
data-connector={connector.id}
data-state={busy ?? state}
>
<ConnectorLogo connector={connector} />
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-body">{connector.name}</span>
<span className="block truncate text-caption text-fg-muted">
{busy === "signing-in"
? "Waiting for the browser sign-in…"
: busy === "adding"
? "Adding…"
: connected && server
? `${server.toolCount} tool${server.toolCount === 1 ? "" : "s"}${server.auth === "signed_in" ? " · Signed in" : ""}`
: connector.description}
<span className="flex items-center gap-1.5">
<span className="truncate font-medium text-body">{connector.name}</span>
{state === "connected" && !busy ? (
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-success" />
) : null}
</span>
<span
title={problem ? server?.error : undefined}
className={cx("block truncate text-caption", problem ? "text-danger" : "text-fg-muted")}
>
{status}
</span>
</span>
{busy ? (
<Spinner size={14} />
) : connected ? (
) : state === "connected" ? (
<Chip tone="ok">Connected</Chip>
) : needsSignIn ? (
) : state === "signed-out" && server ? (
<Action size="sm" disabled={disabled} onClick={() => onSignIn(server)}>
Sign in
</Action>
) : server ? (
<Chip tone={server.enabled ? "warn" : "idle"}>{server.enabled ? "Not connected" : "Off"}</Chip>
) : state === "failed" && server ? (
<span className="flex shrink-0 items-center gap-1">
<Action size="sm" quiet disabled={disabled} onClick={() => onRemove(server)}>
Remove
</Action>
<Action size="sm" disabled={disabled} onClick={() => onSignIn(server)}>
Retry
</Action>
</span>
) : state === "off" ? (
<Chip tone="idle">Off</Chip>
) : state === "starting" ? (
<Chip tone="warn">Starting</Chip>
) : (
<Action size="sm" disabled={loading || disabled} onClick={onConnect}>
{connector.signIn ? "Connect" : "Add"}
Expand All @@ -218,6 +261,67 @@ function ConnectorCard({
);
}

type CardState = "available" | "connected" | "signed-out" | "failed" | "off" | "starting";

const BUSY_TEXT: Record<Step, string> = {
adding: "Adding…",
"signing-in": "Waiting for the browser sign-in…",
removing: "Removing…",
};

/** Where a catalog app stands on this computer, from its configured server (if any). */
export function cardState(server: McpServer | undefined): CardState {
if (!server) return "available";
if (server.connection === "connected") return "connected";
if (!server.enabled) return "off";
if (server.auth === "signed_out") return "signed-out";
if (server.error || server.connection === "failed") return "failed";
return "starting";
}

function cardStatus(connector: Connector, server: McpServer | undefined, state: CardState): string {
if (!server) return connector.description;
switch (state) {
case "connected":
return `${server.toolCount} tool${server.toolCount === 1 ? "" : "s"}${server.auth === "signed_in" ? " · Signed in" : ""}`;
case "failed":
return server.error ? firstLine(server.error) : "Could not connect";
case "signed-out":
return server.error ? firstLine(server.error) : "Sign in to finish connecting";
case "off":
return "Turned off in Manage servers";
default:
return "Connecting…";
}
}

/** The reason, without the engine's `MCP OAuth for '<name>':` prefix the card already shows. */
export const firstLine = (text: string) => {
const line = text.split("\n")[0]?.trim() || text;
return line.replace(/^MCP (?:OAuth )?for '[^']*':\s*/, "");
};

const RANK: Record<CardState, number> = {
connected: 0,
"signed-out": 1,
failed: 1,
starting: 1,
off: 2,
available: 3,
};

/** Apps already set up on this computer first, then the rest in catalog order. */
function sortConnected(connectors: Connector[], servers: readonly McpServer[]): Connector[] {
return connectors
.map((connector, index) => ({
connector,
index,
rank: RANK[cardState(configuredAs(connector, servers))],
}))
.sort((a, b) => a.rank - b.rank || a.index - b.index)
.map((entry) => entry.connector);
}

function ConnectorLogo({ connector }: { connector: Connector }) {
const path = CONNECTOR_LOGOS[connector.id];
return (
Expand Down
7 changes: 4 additions & 3 deletions apps/desktop/src/ui/connectorCatalog.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
* Settings › Connections › Apps: hosted MCP servers that sign in with OAuth (each advertises
* dynamic client registration, so the engine's browser login works with no client id), and a few
* that need no sign-in. Connecting one adds it as an `http` MCP server in the user config.
* Settings › Connections › Apps: hosted MCP servers that sign in with OAuth (the engine registers
* a client, or identifies as RustCode's client metadata document where a server such as Vercel
* accepts only that, so no client id is needed), and a few that need no sign-in. Connecting one
* adds it as an `http` MCP server in the user config.
*/

export type ConnectorCategory = "work" | "dev" | "design" | "commerce" | "docs";
Expand Down
9 changes: 9 additions & 0 deletions rustcode/engine/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::Child;
use tokio::sync::{Mutex, Notify, mpsc};

mod client_metadata;

pub struct McpClient {
pub name: String,
transport: Transport,
Expand Down Expand Up @@ -1850,6 +1852,13 @@ impl McpClient {
}
.filter(|id| !id.trim().is_empty());
let mut code_granted = plan.registration_grants.contains(&"authorization_code");
if client_id.is_none() && client_metadata::prefers_client_metadata(&meta) {
let document = client_metadata::client_metadata_registration();
client_id = Some(client_metadata::RUSTCODE_CLIENT_METADATA_URL.to_string());
flow = select_registered_oauth_flow(&meta, Some(&document))
.map_err(|detail| auth_required_error(&name, &mcp_url, &detail))?;
code_granted = true;
}
if client_id.is_none() {
let endpoint = registration_endpoint.ok_or_else(|| auth_required_error(
&name, &mcp_url, "configure a pre-registered `client_id`; the server offers no dynamic registration endpoint",
Expand Down
Loading
Loading