feat: move MCP server sign-in to Agents settings and simplify the + menu (#31396)

This commit is contained in:
Michael Suchacz authored and GitHub committed 2026-10-29 06:52:05 +01:00
1 parent 2255794d65
commit 036d286384
30 files changed
+1966 -642

No files matched your search

+49
View File
@@ -328,6 +328,55 @@ The list of available skills in the agent's system prompt shortens a description
The stored description keeps the full text.
The `read_skill` result returns the skill body without the frontmatter, so it doesn't include the description.
## Connect to MCP servers
Organization admins register MCP servers for each organization.
Refer to [MCP servers](./platform-controls/mcp-servers.md) for how admins add and configure them.
A chat offers its organization's servers in the chat's **+** menu, under **MCP servers**.
A server that uses OAuth2 needs your own account before a chat can use it.
You connect your accounts on the **MCP connections** settings page.
To open it from a chat, select **Manage** in the **MCP servers** list.
The page opens for the chat's organization.
You can connect only to servers you have access to.
New servers grant access to the organization's **Everyone** group, so all members have access by default.
To connect your account to a server:
1. Open the **Agents** page and go to **Settings** > **MCP connections**.
1. If you belong to more than one organization, choose the chat's organization in the organization picker.
A server that you connect in one organization doesn't appear in the chats of another organization.
1. Select **Connect** next to the server.
The provider's sign-in page opens in a popup.
1. Sign in to the provider in the popup.
When the sign-in finishes, the row shows **Disconnect**.
The server then appears in the chat's **MCP servers** list.
Connecting a server doesn't change whether it is on in a chat.
Servers that don't use OAuth2 need no connection, so their rows show **No auth required**, and chats offer them without one.
To disconnect a server, select **Disconnect** next to it, then select **Disconnect** in the confirmation dialog.
Coder removes your credentials for that server, and you can connect again later.
### Turn a server on or off in a chat
You can turn servers on or off only in a chat that you own.
In the chat, open the **+** menu and select **MCP servers**, or select the MCP pill in the message box.
The pill shows **Add MCPs** when no server is on, and otherwise the number of servers that are on.
Use the switch next to a server to turn it on or off for that chat.
The change applies from the next message you send.
A server that an administrator turns on for every chat shows a lock, and you can't turn it off.
A server that is on for the chat but not connected shows an orange dot instead of a switch until you connect it.
Hover over the dot to see **Not connected**.
This applies to a server that is on by default, and to a server that was on when its connection ended.
The footer of the list counts the OAuth2 servers that you haven't connected.
## Workspace MCP tools
Workspace templates can expose custom [MCP](https://modelcontextprotocol.io/introduction) tools by placing a `.mcp.json` file in the workspace working directory.
@@ -45,11 +45,11 @@ The add and update views always show the target organization, as a read-only fie
#### Availability policies
| Policy | Behavior |
|---------------|-----------------------------------------------------------------------------------|
| `force_on` | Injected into every chat whose owner has ACL access to the server. No opting out. |
| `default_on` | Pre-selected in new chats. Users can opt out. |
| `default_off` | Available in the server list but users must opt in. |
| Policy | Behavior |
|---------------|-------------------------------------------------------------------------------------------------------------------------|
| `force_on` | Injected into every chat whose owner has ACL access to the server. No opting out. |
| `default_on` | Pre-selected in new chats. Users can opt out. |
| `default_off` | Available in the chat's **MCP servers** list but users must opt in. An OAuth2 server is listed after the user connects. |
## Authentication
@@ -107,10 +107,11 @@ When none matches, it uses the server URL with the scheme and host lowercased an
Explicit `oauth2_revocation_url` and `oauth2_resource` values in the request take precedence over the discovered values.
Discovery runs only when a configuration is created, so to add a resource indicator to an existing configuration, set `oauth2_resource` on it or re-create the server.
Users connect through a popup that redirects through the OAuth2 provider.
Users connect their own accounts in **Agents** > **Settings** > **MCP connections**, through a popup that redirects through the OAuth2 provider.
Refer to [Connect to MCP servers](../extending-agents.md#connect-to-mcp-servers) for the steps users follow.
Tokens are stored per-user and refreshed automatically.
Changing the server URL, authentication type, `oauth2_client_id`, `oauth2_token_url`, `oauth2_revocation_url`, or `oauth2_resource` deletes every user's stored token, so users must connect again.
Users can disconnect via the UI or API to remove stored tokens.
Users can disconnect in **MCP connections** or through the API to remove stored tokens.
When a revocation endpoint is configured, disconnecting also asks the provider to revoke the token (RFC 7009).
Provider revocation is best-effort: the stored token is always deleted from Coder, and the disconnect response reports whether provider revocation succeeded via `token_revoked` and `token_revocation_error`.
@@ -22,6 +22,7 @@ Running more than 1 organization requires a [Premium license](../../../admin/use
| Personal model overrides | User, per organization | **Agents** > **Settings** > **Agents** |
| Personal override toggle | Deployment | **Admin settings** > **AI** > **Coder Agents** > **Deployment settings** |
| MCP servers | Organization | **Admin settings** > **AI** > **Coder Agents** > **MCP servers** |
| MCP server connections | User, per organization | **Agents** > **Settings** > **MCP connections** |
| Organization skills | Organization | **Admin settings** > **AI** > **Coder Agents** > **Skills** |
| Personal skills | User | **Agents** > **Settings** > **Skills** |
| System prompt | Deployment | **Admin settings** > **AI** > **Coder Agents** > **Instructions** |
+4 -1
View File
@@ -3389,7 +3389,10 @@ export const mcpServerConfigACLAvailable = (
enabled: organization !== "" && id !== "",
});
const invalidateMCPServerConfigQueries = async (queryClient: QueryClient) => {
/** Invalidates the MCP server queries of every organization. */
export const invalidateMCPServerConfigQueries = async (
queryClient: QueryClient,
) => {
await queryClient.invalidateQueries({ queryKey: mcpServersKey });
};
@@ -1,4 +1,5 @@
import { useContext } from "react";
import type { User } from "#/api/typesGenerated";
import { DashboardContext, type DashboardValue } from "./DashboardProvider";
export const useDashboard = (): DashboardValue => {
@@ -18,3 +19,14 @@ export const getDefaultOrganizationName = (
export const getDefaultOrganizationId = (
organizations: DashboardValue["organizations"],
): string | undefined => organizations.find((org) => org.is_default)?.id;
/**
* Keeps the dashboard organizations the user belongs to, in dashboard order.
* The dashboard lists every organization the user can read, but chats only
* run in member ones.
*/
export const getMemberOrganizations = (
organizations: DashboardValue["organizations"],
user: Pick<User, "organization_ids">,
): DashboardValue["organizations"] =>
organizations.filter((org) => user.organization_ids.includes(org.id));
@@ -1,7 +1,14 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { hashKey } from "react-query";
import { Outlet, useNavigate } from "react-router";
import { expect, spyOn, userEvent, waitFor, within } from "storybook/test";
import {
expect,
screen,
spyOn,
userEvent,
waitFor,
within,
} from "storybook/test";
import {
reactRouterOutlet,
reactRouterParameters,
@@ -3426,9 +3433,12 @@ export const RemoveLastMCPServer: Story = {
"createChatMessage",
).mockResolvedValue({ queued: false });
await userEvent.click(await canvas.findByRole("button", { name: "1 MCP" }));
const menu = await screen.findByRole("dialog");
await userEvent.click(
await canvas.findByRole("button", { name: "Remove MCP Server" }),
within(menu).getByRole("switch", { name: "Disable MCP Server" }),
);
await userEvent.keyboard("{Escape}");
const editor = await canvas.findByTestId("chat-message-input");
await userEvent.click(editor);
await userEvent.type(editor, "Send without MCP tools");
@@ -3495,6 +3505,9 @@ export const EditAppliesMCPServerSelection: Story = {
await canvas.findByRole("button", { name: "Edit message" }),
);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: /MCP servers/ }),
);
await userEvent.click(
await body.findByRole("switch", {
name: `Enable ${MockMCPServerConfig.display_name}`,
@@ -207,10 +207,6 @@ const AgentChatPage: React.FC = () => {
}
};
const handleMCPAuthComplete = (_serverId: string) => {
void mcpServersQuery.refetch();
};
const {
options: modelOptions,
isModelCatalogLoading,
@@ -846,7 +842,6 @@ const AgentChatPage: React.FC = () => {
mcpServers={mcpServers}
selectedMCPServerIds={effectiveMCPServerIds}
onMCPSelectionChange={handleMCPSelectionChange}
onMCPAuthComplete={handleMCPAuthComplete}
/>
)}
</>
@@ -201,7 +201,6 @@ const StoryAgentChatPageView: React.FC<StoryProps> = ({
typeof AgentChatPageView
>["selectedMCPServerIds"],
onMCPSelectionChange: fn(),
onMCPAuthComplete: fn(),
canConfigureAgentSetup: true,
providerCount: 1,
modelCount: 1,
@@ -174,7 +174,6 @@ type AgentChatPageViewProps = {
mcpServers: readonly TypesGen.MCPServerConfig[];
selectedMCPServerIds: readonly string[];
onMCPSelectionChange: (ids: string[]) => void;
onMCPAuthComplete: (serverId: string) => void;
// Desktop chat ID (optional).
desktopChatId?: string;
@@ -315,7 +314,6 @@ export const AgentChatPageView: React.FC<AgentChatPageViewProps> = ({
mcpServers,
selectedMCPServerIds,
onMCPSelectionChange,
onMCPAuthComplete,
desktopChatId,
}) => {
const { proxy } = useProxy();
@@ -956,7 +954,6 @@ export const AgentChatPageView: React.FC<AgentChatPageViewProps> = ({
mcpServers={mcpServers}
selectedMCPServerIds={selectedMCPServerIds}
onMCPSelectionChange={onMCPSelectionChange}
onMCPAuthComplete={onMCPAuthComplete}
workspace={workspace}
workspaceAgent={workspaceAgent}
sshCommand={sshCommand}
@@ -0,0 +1,314 @@
import { act, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Navigate } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { API } from "#/api/api";
import type * as TypesGen from "#/api/typesGenerated";
import { toast } from "#/components/Toaster/toast";
import { MockMCPServerConfig } from "#/testHelpers/chatEntities";
import {
MockDefaultOrganization,
MockOrganization2,
MockOrganization3,
MockUserMember,
} from "#/testHelpers/entities";
import { renderWithAuth } from "#/testHelpers/renderHelpers";
import AgentSettingsMCPConnectionsPage from "./AgentSettingsMCPConnectionsPage";
const mockGitHubMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-github",
display_name: "GitHub",
auth_type: "oauth2",
auth_connected: false,
};
const mockNotionMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-notion",
display_name: "Notion",
auth_type: "oauth2",
auth_connected: true,
};
const setup = (
getServers: (organizationId: string) => TypesGen.MCPServerConfig[],
) => {
vi.spyOn(API, "getAuthenticatedUser").mockResolvedValue({
...MockUserMember,
organization_ids: [
MockDefaultOrganization.id,
MockOrganization2.id,
MockOrganization3.id,
],
});
vi.spyOn(API, "getOrganizations").mockResolvedValue([
MockDefaultOrganization,
MockOrganization2,
MockOrganization3,
]);
return vi
.spyOn(API.experimental, "getMCPServerConfigs")
.mockImplementation(async (organizationId) => getServers(organizationId));
};
// An iframe's window stands in for the sign-in popup that
// window.open returns.
const stubSignInPopup = () => {
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const popup = iframe.contentWindow;
const open = vi.spyOn(window, "open").mockReturnValue(popup);
return { popup, open, removePopup: () => iframe.remove() };
};
const completeSignIn = (popup: Window | null, serverID: string) => {
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "mcp-oauth2-complete", serverID },
origin: location.origin,
source: popup,
}),
);
});
};
const renderPage = (state?: { organizationId: string }) =>
renderWithAuth(<AgentSettingsMCPConnectionsPage />, {
path: "/agents/settings/mcp-connections",
route: "/start",
extraRoutes: [
{
path: "/start",
element: (
<Navigate to="/agents/settings/mcp-connections" state={state} />
),
},
],
});
describe("AgentSettingsMCPConnectionsPage", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("adds connected and no-auth servers to the table and offers the rest as cards", async () => {
const mockRegistryMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-registry",
display_name: "Registry",
auth_type: "none",
};
setup(() => [mockRegistryMCP, mockGitHubMCP, mockNotionMCP]);
renderPage();
const table = await screen.findByRole("table", {
name: `Added connectors in ${MockDefaultOrganization.display_name}`,
});
const names = within(table)
.getAllByRole("row")
.slice(1)
.map((row) => within(row).getAllByRole("cell")[0]?.textContent);
expect(names).toEqual(["Notion", "Registry"]);
const cards = within(
screen.getByRole("region", { name: "Available connectors" }),
).getAllByRole("listitem");
expect(cards.map((card) => card.textContent)).toEqual([
"GitHubNo descriptionConnect",
]);
});
it("jumps to the available connectors", async () => {
const user = userEvent.setup();
const scrollIntoView = vi.spyOn(HTMLElement.prototype, "scrollIntoView");
setup(() => [mockGitHubMCP, mockNotionMCP]);
renderPage();
await user.click(
await screen.findByRole("button", { name: "View 1 available" }),
);
const available = screen.getByRole("region", {
name: "Available connectors",
});
expect(scrollIntoView.mock.contexts).toEqual([available]);
expect(available).toHaveFocus();
});
it("connects through the organization's popup and refreshes the list when sign-in completes", async () => {
const user = userEvent.setup();
const getServers = setup(() => [mockGitHubMCP]);
const { popup, open, removePopup } = stubSignInPopup();
renderPage();
await user.click(
await screen.findByRole("button", { name: "Connect GitHub" }),
);
expect(open).toHaveBeenCalledWith(
`/api/v2/organizations/${MockDefaultOrganization.id}/mcp-servers/${mockGitHubMCP.id}/oauth2/connect`,
"_blank",
"width=900,height=600",
);
getServers.mockResolvedValue([{ ...mockGitHubMCP, auth_connected: true }]);
completeSignIn(popup, mockGitHubMCP.id);
await waitFor(() => expect(getServers).toHaveBeenCalledTimes(2));
removePopup();
});
it("confirms a sign-in that finishes after the organization changes", async () => {
const user = userEvent.setup();
setup((organizationId) =>
organizationId === MockDefaultOrganization.id
? [mockGitHubMCP]
: [mockNotionMCP],
);
const { popup, removePopup } = stubSignInPopup();
const toastSuccess = vi.spyOn(toast, "success");
renderPage();
await user.click(
await screen.findByRole("button", { name: "Connect GitHub" }),
);
await user.click(
screen.getByRole("combobox", {
name: `Organization ${MockDefaultOrganization.display_name}`,
}),
);
await user.click(
screen.getByRole("option", {
name: new RegExp(MockOrganization2.display_name),
}),
);
await screen.findByRole("button", { name: "Disconnect Notion" });
completeSignIn(popup, mockGitHubMCP.id);
await waitFor(() =>
expect(toastSuccess).toHaveBeenCalledWith("Connected GitHub."),
);
removePopup();
});
it("disconnects after confirmation", async () => {
const user = userEvent.setup();
setup(() => [mockNotionMCP]);
const disconnect = vi
.spyOn(API.experimental, "disconnectMCPServerOAuth2")
.mockResolvedValue({ token_revoked: true });
const toastSuccess = vi.spyOn(toast, "success");
renderPage();
await user.click(
await screen.findByRole("button", { name: "Disconnect Notion" }),
);
const dialog = await screen.findByRole("dialog");
await user.click(
within(dialog).getByRole("button", { name: "Disconnect" }),
);
await waitFor(() =>
expect(toastSuccess).toHaveBeenCalledWith("Disconnected Notion."),
);
expect(disconnect).toHaveBeenCalledWith(mockNotionMCP.id);
});
it("warns when the provider could not revoke the token", async () => {
const user = userEvent.setup();
setup(() => [mockNotionMCP]);
vi.spyOn(API.experimental, "disconnectMCPServerOAuth2").mockResolvedValue({
token_revoked: false,
token_revocation_error: "The provider rejected the revocation.",
});
const toastWarning = vi.spyOn(toast, "warning");
renderPage();
await user.click(
await screen.findByRole("button", { name: "Disconnect Notion" }),
);
await user.click(
within(await screen.findByRole("dialog")).getByRole("button", {
name: "Disconnect",
}),
);
await waitFor(() =>
expect(toastWarning).toHaveBeenCalledWith("Disconnected Notion.", {
description: "The provider rejected the revocation.",
}),
);
});
it("reports a failed disconnect", async () => {
const user = userEvent.setup();
setup(() => [mockNotionMCP]);
vi.spyOn(API.experimental, "disconnectMCPServerOAuth2").mockRejectedValue(
new Error("disconnect failed"),
);
const toastError = vi.spyOn(toast, "error");
renderPage();
await user.click(
await screen.findByRole("button", { name: "Disconnect Notion" }),
);
await user.click(
within(await screen.findByRole("dialog")).getByRole("button", {
name: "Disconnect",
}),
);
await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
});
it("does not disconnect when the confirmation is cancelled", async () => {
const user = userEvent.setup();
setup(() => [mockNotionMCP]);
const disconnect = vi.spyOn(API.experimental, "disconnectMCPServerOAuth2");
renderPage();
await user.click(
await screen.findByRole("button", { name: "Disconnect Notion" }),
);
await user.click(
within(await screen.findByRole("dialog")).getByRole("button", {
name: "Cancel",
}),
);
expect(disconnect).not.toHaveBeenCalled();
});
it("starts with the chat's organization and lists another one on demand", async () => {
const user = userEvent.setup();
const getServers = setup((organizationId) =>
organizationId === MockOrganization2.id
? [mockGitHubMCP]
: [mockNotionMCP],
);
renderPage({ organizationId: MockOrganization2.id });
await screen.findByRole("table", {
name: `Added connectors in ${MockOrganization2.display_name}`,
});
expect(getServers).toHaveBeenCalledWith(MockOrganization2.id);
expect(getServers).not.toHaveBeenCalledWith(MockDefaultOrganization.id);
await user.click(
screen.getByRole("combobox", {
name: `Organization ${MockOrganization2.display_name}`,
}),
);
await user.click(
screen.getByRole("option", {
name: new RegExp(MockOrganization3.display_name),
}),
);
await screen.findByRole("button", { name: "Disconnect Notion" });
expect(getServers).toHaveBeenCalledWith(MockOrganization3.id);
});
it("starts with the default organization when the chat's organization is not a member one", async () => {
const getServers = setup(() => [mockGitHubMCP]);
renderPage({ organizationId: "not-a-member-organization" });
await screen.findByRole("table", {
name: `Added connectors in ${MockDefaultOrganization.display_name}`,
});
expect(getServers).toHaveBeenCalledWith(MockDefaultOrganization.id);
});
});
@@ -0,0 +1,130 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { useLocation } from "react-router";
import { getErrorMessage } from "#/api/errors";
import {
disconnectMCPServerOAuth2,
invalidateMCPServerConfigQueries,
mcpServerConfigs,
} from "#/api/queries/chats";
import type * as TypesGen from "#/api/typesGenerated";
import { toast } from "#/components/Toaster/toast";
import { useAuthenticated } from "#/hooks/useAuthenticated";
import {
getDefaultOrganizationId,
getMemberOrganizations,
useDashboard,
} from "#/modules/dashboard/useDashboard";
import { useMCPOAuthFlow } from "../../hooks/useMCPOAuthFlow";
import { AgentSettingsMCPConnectionsPageView } from "./AgentSettingsMCPConnectionsPageView";
const getStateOrganizationId = (state: unknown): string | undefined =>
typeof state === "object" &&
state !== null &&
"organizationId" in state &&
typeof state.organizationId === "string"
? state.organizationId
: undefined;
const getInitialOrganizationId = (
organizations: readonly TypesGen.Organization[],
locationState: unknown,
): string | undefined => {
const stateOrganizationId = getStateOrganizationId(locationState);
if (organizations.some(({ id }) => id === stateOrganizationId)) {
return stateOrganizationId;
}
const defaultOrganizationId = getDefaultOrganizationId(organizations);
if (defaultOrganizationId) {
return defaultOrganizationId;
}
return organizations.at(0)?.id;
};
const AgentSettingsMCPConnectionsPage: React.FC = () => {
const { user } = useAuthenticated();
const location = useLocation();
const queryClient = useQueryClient();
const memberOrganizations = getMemberOrganizations(
useDashboard().organizations,
user,
);
const [selectedOrganizationId, setSelectedOrganizationId] = useState(() =>
getInitialOrganizationId(memberOrganizations, location.state),
);
const organization = memberOrganizations.find(
({ id }) => id === selectedOrganizationId,
);
const organizationId = organization?.id ?? "";
const serversQuery = useQuery({
...mcpServerConfigs(organizationId),
enabled: organizationId !== "",
});
const servers = serversQuery.data;
const { connectingServerId, connect } = useMCPOAuthFlow({
organizationId,
// A sign-in can finish after the picker leaves its organization,
// so every organization's list refreshes.
onAuthComplete: () => {
void invalidateMCPServerConfigQueries(queryClient);
},
onFlowSuccess: (server) => {
toast.success(`Connected ${server.display_name}.`);
},
});
const [disconnectTarget, setDisconnectTarget] =
useState<TypesGen.MCPServerConfig | null>(null);
const disconnectMutation = useMutation(
disconnectMCPServerOAuth2(queryClient),
);
const handleConfirmDisconnect = () => {
if (!disconnectTarget) {
return;
}
const name = disconnectTarget.display_name;
disconnectMutation.mutate(disconnectTarget.id, {
onSuccess: (response) => {
setDisconnectTarget(null);
if (response.token_revocation_error) {
toast.warning(`Disconnected ${name}.`, {
description: response.token_revocation_error,
});
} else {
toast.success(`Disconnected ${name}.`);
}
},
onError: (error) => {
toast.error(getErrorMessage(error, `Failed to disconnect ${name}.`));
},
});
};
return (
<AgentSettingsMCPConnectionsPageView
organizations={memberOrganizations}
organization={organization}
onOrganizationChange={({ id }) => setSelectedOrganizationId(id)}
servers={servers}
error={serversQuery.error}
isLoading={serversQuery.isLoading}
isRetrying={serversQuery.isFetching}
onRetry={() => {
void serversQuery.refetch();
}}
connectingServerId={connectingServerId}
onConnect={connect}
onDisconnect={setDisconnectTarget}
disconnectTarget={disconnectTarget}
isDisconnecting={disconnectMutation.isPending}
onConfirmDisconnect={handleConfirmDisconnect}
onCancelDisconnect={() => setDisconnectTarget(null)}
/>
);
};
export default AgentSettingsMCPConnectionsPage;
@@ -0,0 +1,198 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { fn } from "storybook/test";
import type * as TypesGen from "#/api/typesGenerated";
import { MockMCPServerConfig } from "#/testHelpers/chatEntities";
import {
MockDefaultOrganization,
MockOrganization2,
mockApiError,
} from "#/testHelpers/entities";
import { AgentSettingsMCPConnectionsPageView } from "./AgentSettingsMCPConnectionsPageView";
const mockCoderMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-coder",
display_name: "Coder",
description: "Workspaces, templates and tasks",
auth_type: "oauth2",
};
const mockGitHubMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-github",
display_name: "GitHub",
description: "Repositories, pull requests and issues",
icon_url: "/icon/github.svg",
auth_type: "oauth2",
auth_connected: true,
};
const mockGranolaMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-granola",
display_name: "Granola",
availability: "force_on",
auth_type: "oauth2",
};
const mockImageMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-image",
display_name: "Image",
auth_connected: true,
};
const mockRegistryMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-registry",
display_name: "Registry",
auth_type: "api_key",
auth_connected: true,
};
const mockWizMCP: TypesGen.MCPServerConfig = {
...MockMCPServerConfig,
id: "mcp-wiz",
display_name: "Wiz",
description:
"Query Wiz cloud security data with your own Wiz account (requires a Wiz service account with read access to issues, vulnerabilities and inventory)",
auth_type: "oauth2",
};
const mockServers = [
mockCoderMCP,
mockGitHubMCP,
mockGranolaMCP,
mockImageMCP,
mockRegistryMCP,
mockWizMCP,
];
const meta = {
title: "pages/AgentsPage/AgentSettingsMCPConnectionsPageView",
component: AgentSettingsMCPConnectionsPageView,
args: {
organizations: [MockDefaultOrganization],
organization: MockDefaultOrganization,
onOrganizationChange: fn(),
servers: mockServers,
error: undefined,
isLoading: false,
isRetrying: false,
onRetry: fn(),
connectingServerId: null,
onConnect: fn(),
onDisconnect: fn(),
disconnectTarget: null,
isDisconnecting: false,
onConfirmDisconnect: fn(),
onCancelDisconnect: fn(),
},
} satisfies Meta<typeof AgentSettingsMCPConnectionsPageView>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {};
export const MultipleOrganizations: Story = {
args: {
organizations: [MockDefaultOrganization, MockOrganization2],
},
};
export const Connecting: Story = {
args: {
connectingServerId: "mcp-coder",
},
};
export const Mobile: Story = {
parameters: {
viewport: { defaultViewport: "mobile1" },
pixel: { matrix: { viewports: ["phone"] } },
},
};
// Between the @lg and @3xl container widths: two card columns.
export const NarrowContainer: Story = {
decorators: [
(Story) => (
<div className="w-[580px]">
<Story />
</div>
),
],
};
export const AllAdded: Story = {
args: {
servers: [mockGitHubMCP, mockImageMCP, mockRegistryMCP],
},
};
export const NoneAdded: Story = {
args: {
servers: [mockCoderMCP, mockGranolaMCP, mockWizMCP],
},
};
export const Loading: Story = {
args: {
servers: undefined,
isLoading: true,
},
};
export const LoadingMobile: Story = {
args: {
servers: undefined,
isLoading: true,
},
parameters: {
viewport: { defaultViewport: "mobile1" },
pixel: { matrix: { viewports: ["phone"] } },
},
};
export const LoadError: Story = {
args: {
servers: undefined,
error: mockApiError({ message: "Failed to load MCP servers." }),
},
};
export const Empty: Story = {
args: {
servers: [],
},
};
export const NoOrganization: Story = {
args: {
organizations: [],
organization: undefined,
servers: undefined,
},
};
export const DisconnectDialogOpen: Story = {
args: {
disconnectTarget: mockGitHubMCP,
},
};
export const Disconnecting: Story = {
args: {
disconnectTarget: mockGitHubMCP,
isDisconnecting: true,
},
};
/** A failed refetch keeps the last list below the error. */
export const RefetchError: Story = {
args: {
error: mockApiError({ message: "Failed to load MCP servers." }),
},
};
export const Retrying: Story = {
args: {
error: mockApiError({ message: "Failed to load MCP servers." }),
isRetrying: true,
},
};
@@ -0,0 +1,410 @@
import { ArrowDownIcon } from "lucide-react";
import { useId, useRef } from "react";
import type * as TypesGen from "#/api/typesGenerated";
import { ErrorAlert } from "#/components/Alert/ErrorAlert";
import { Badge } from "#/components/Badge/Badge";
import { Button } from "#/components/Button/Button";
import { ConfirmDialog } from "#/components/Dialog/ConfirmDialog/ConfirmDialog";
import { OrganizationField } from "#/components/OrganizationAutocomplete/OrganizationAutocomplete";
import { Skeleton } from "#/components/Skeleton/Skeleton";
import { Spinner } from "#/components/Spinner/Spinner";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "#/components/Table/Table";
import { TableEmpty } from "#/components/TableEmpty/TableEmpty";
import {
TableLoaderSkeleton,
TableRowSkeleton,
} from "#/components/TableLoader/TableLoader";
import { MCPServerIcon } from "#/modules/mcpServers/MCPServerIcon";
import { needsSignIn } from "../../components/mcpMenuServers";
import { RetryButton } from "../../components/RetryButton";
import { SectionHeader } from "../../components/SectionHeader";
type AgentSettingsMCPConnectionsPageViewProps = {
organizations: readonly TypesGen.Organization[];
organization: TypesGen.Organization | undefined;
onOrganizationChange: (organization: TypesGen.Organization) => void;
servers: readonly TypesGen.MCPServerConfig[] | undefined;
error: unknown;
isLoading: boolean;
isRetrying: boolean;
onRetry: () => void;
connectingServerId: string | null;
onConnect: (server: TypesGen.MCPServerConfig) => void;
onDisconnect: (server: TypesGen.MCPServerConfig) => void;
disconnectTarget: TypesGen.MCPServerConfig | null;
isDisconnecting: boolean;
onConfirmDisconnect: () => void;
onCancelDisconnect: () => void;
};
type AddedConnectorActionProps = {
server: TypesGen.MCPServerConfig;
onDisconnect: (server: TypesGen.MCPServerConfig) => void;
};
const AddedConnectorAction: React.FC<AddedConnectorActionProps> = ({
server,
onDisconnect,
}) => {
if (server.auth_type !== "oauth2") {
return (
<span className="whitespace-nowrap text-content-secondary">
No auth required
</span>
);
}
return (
<Button
variant="outline"
size="sm"
aria-label={`Disconnect ${server.display_name}`}
onClick={() => onDisconnect(server)}
>
Disconnect
</Button>
);
};
type AddedConnectorRowProps = {
server: TypesGen.MCPServerConfig;
onDisconnect: (server: TypesGen.MCPServerConfig) => void;
};
const AddedConnectorRow: React.FC<AddedConnectorRowProps> = ({
server,
onDisconnect,
}) => {
return (
<TableRow>
<TableCell className="w-full max-w-0 @lg:w-auto @lg:max-w-48">
<div className="flex items-center gap-2">
<MCPServerIcon iconUrl={server.icon_url} className="size-6" />
<span className="truncate" title={server.display_name}>
{server.display_name}
</span>
</div>
</TableCell>
<TableCell
className="hidden w-full max-w-0 truncate @lg:table-cell"
title={server.description || undefined}
>
{server.description || (
<span className="text-content-disabled">No description</span>
)}
</TableCell>
<TableCell className="text-right">
<AddedConnectorAction server={server} onDisconnect={onDisconnect} />
</TableCell>
</TableRow>
);
};
type AvailableConnectorCardProps = {
server: TypesGen.MCPServerConfig;
connectingServerId: string | null;
onConnect: (server: TypesGen.MCPServerConfig) => void;
};
const AvailableConnectorCard: React.FC<AvailableConnectorCardProps> = ({
server,
connectingServerId,
onConnect,
}) => {
const isConnecting = connectingServerId === server.id;
const connectLabel = isConnecting ? "Connecting" : "Connect";
return (
<li className="flex flex-col gap-3 rounded-lg border border-solid border-border p-4">
<div className="flex items-center gap-3">
<MCPServerIcon iconUrl={server.icon_url} className="size-8" />
<span
className="truncate font-medium text-content-primary"
title={server.display_name}
>
{server.display_name}
</span>
</div>
<p
className="m-0 line-clamp-2 text-sm text-content-secondary break-words"
title={server.description || undefined}
>
{server.description || (
<span className="text-content-disabled">No description</span>
)}
</p>
<Button
variant="outline"
size="sm"
className="mt-auto self-end"
aria-label={`${connectLabel} ${server.display_name}`}
disabled={connectingServerId !== null}
onClick={() => onConnect(server)}
>
<Spinner loading={isConnecting} className="size-4" />
{connectLabel}
</Button>
</li>
);
};
type AddedConnectorsSectionProps = {
organizationName: string;
servers: readonly TypesGen.MCPServerConfig[];
enabledCount: number;
availableCount: number;
isLoading: boolean;
emptyMessage: string;
onShowAvailable: () => void;
onDisconnect: (server: TypesGen.MCPServerConfig) => void;
};
const AddedConnectorsSection: React.FC<AddedConnectorsSectionProps> = ({
organizationName,
servers,
enabledCount,
availableCount,
isLoading,
emptyMessage,
onShowAvailable,
onDisconnect,
}) => {
const showCounts = !isLoading && enabledCount > 0;
let body: React.ReactNode = <TableEmpty message={emptyMessage} />;
if (isLoading) {
body = (
<TableLoaderSkeleton>
<TableRowSkeleton aria-label="Loading MCP servers">
<TableCell className="w-full max-w-0 @lg:w-auto @lg:max-w-48">
<Skeleton variant="text" className="w-32" />
</TableCell>
<TableCell className="hidden w-full max-w-0 @lg:table-cell">
<Skeleton variant="text" />
</TableCell>
<TableCell>
<Skeleton className="ml-auto h-8 w-24" />
</TableCell>
</TableRowSkeleton>
</TableLoaderSkeleton>
);
} else if (servers.length > 0) {
body = servers.map((server) => (
<AddedConnectorRow
key={server.id}
server={server}
onDisconnect={onDisconnect}
/>
));
}
return (
<section aria-label="Added connectors" className="flex flex-col gap-4">
<SectionHeader
level="section"
label="Added connectors"
badge={
showCounts && (
<Badge size="sm">
{servers.length} of {enabledCount}
</Badge>
)
}
description="Servers you've connected, plus ones that need no sign-in. They appear in the chat's + menu."
action={
showCounts &&
availableCount > 0 && (
<Button variant="outline" size="sm" onClick={onShowAvailable}>
View {availableCount} available
<ArrowDownIcon />
</Button>
)
}
/>
<Table
aria-label={`Added connectors in ${organizationName}`}
// Beside the settings sidebar the table is far narrower than the
// viewport, so the columns follow the wrapper, not the screen.
wrapperClassName="@container"
>
<TableHeader>
<TableRow>
<TableHead className="whitespace-nowrap">Name</TableHead>
<TableHead className="hidden w-full @lg:table-cell">
Description
</TableHead>
<TableHead>
<span className="sr-only">Actions</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody size="lg">{body}</TableBody>
</Table>
</section>
);
};
type AvailableConnectorsSectionProps = {
ref: React.Ref<HTMLElement>;
servers: readonly TypesGen.MCPServerConfig[];
connectingServerId: string | null;
onConnect: (server: TypesGen.MCPServerConfig) => void;
};
const AvailableConnectorsSection: React.FC<AvailableConnectorsSectionProps> = ({
ref,
servers,
connectingServerId,
onConnect,
}) => {
return (
<section
ref={ref}
aria-label="Available connectors"
tabIndex={-1}
className="flex scroll-mt-8 flex-col gap-4 outline-hidden"
>
<SectionHeader
level="section"
label="Available connectors"
badge={<Badge size="sm">{servers.length}</Badge>}
description="Servers your organization offers. Connect to one to add it to chat."
/>
<ul className="m-0 grid list-none grid-cols-1 gap-3 p-0 @lg:grid-cols-2 @3xl:grid-cols-3">
{servers.map((server) => (
<AvailableConnectorCard
key={server.id}
server={server}
connectingServerId={connectingServerId}
onConnect={onConnect}
/>
))}
</ul>
</section>
);
};
/**
* The table lists the enabled servers a chat can use now; the OAuth2 servers
* the user has not signed in to are cards below it, each with Connect.
* `onDisconnect` should set `disconnectTarget`, which opens the confirmation,
* and while `connectingServerId` is set, every Connect button is disabled.
*/
export const AgentSettingsMCPConnectionsPageView: React.FC<
AgentSettingsMCPConnectionsPageViewProps
> = ({
organizations,
organization,
onOrganizationChange,
servers,
error,
isLoading,
isRetrying,
onRetry,
connectingServerId,
onConnect,
onDisconnect,
disconnectTarget,
isDisconnecting,
onConfirmDisconnect,
onCancelDisconnect,
}) => {
const organizationFieldId = useId();
const availableSectionRef = useRef<HTMLElement>(null);
const organizationName = organization
? organization.display_name || organization.name
: "your organization";
const enabledServers = servers?.filter((server) => server.enabled) ?? [];
const availableServers = enabledServers.filter(needsSignIn);
const addedServers = [
...enabledServers.filter(
(server) => server.auth_type === "oauth2" && server.auth_connected,
),
...enabledServers.filter((server) => server.auth_type !== "oauth2"),
];
const failedFirstLoad = Boolean(error) && servers === undefined;
let emptyMessage = "Connect a server below to add it to chat";
if (!organization) {
emptyMessage = "You are not a member of any organization";
} else if (enabledServers.length === 0) {
emptyMessage = `No MCP servers in ${organizationName}`;
}
const showAvailableServers = () => {
const section = availableSectionRef.current;
section?.scrollIntoView({ behavior: "smooth", block: "start" });
section?.focus({ preventScroll: true });
};
return (
<div className="flex flex-col gap-8 @container">
<SectionHeader
label="MCP connections"
description="Sign in to the MCP servers your organization offers. Connected servers appear in the chat's + menu under MCP servers, where you turn them on for each chat."
/>
{organization && (
<OrganizationField
id={organizationFieldId}
className="w-full sm:w-60"
organizations={organizations}
organization={organization}
onChange={onOrganizationChange}
showLabel={false}
/>
)}
{Boolean(error) && (
<ErrorAlert
error={error}
actions={
<RetryButton
size="sm"
variant="outline"
aria-label={`Retry loading ${organizationName} MCP servers`}
isRetrying={isRetrying}
onRetry={onRetry}
/>
}
/>
)}
{!failedFirstLoad && (
<AddedConnectorsSection
organizationName={organizationName}
servers={addedServers}
enabledCount={enabledServers.length}
availableCount={availableServers.length}
isLoading={isLoading}
emptyMessage={emptyMessage}
onShowAvailable={showAvailableServers}
onDisconnect={onDisconnect}
/>
)}
{!isLoading && availableServers.length > 0 && (
<AvailableConnectorsSection
ref={availableSectionRef}
servers={availableServers}
connectingServerId={connectingServerId}
onConnect={onConnect}
/>
)}
<ConfirmDialog
open={disconnectTarget !== null}
title={`Disconnect ${disconnectTarget?.display_name ?? "MCP server"}?`}
description="This removes your credentials for this MCP server from Coder. You can authenticate again later."
type="delete"
confirmText="Disconnect"
confirmLoading={isDisconnecting}
onConfirm={onConfirmDisconnect}
onClose={onCancelDisconnect}
/>
</div>
);
};
@@ -4,7 +4,10 @@ import { organizationSkills } from "#/api/queries/organizationSkills";
import { ErrorAlert } from "#/components/Alert/ErrorAlert";
import { OrganizationField } from "#/components/OrganizationAutocomplete/OrganizationAutocomplete";
import { useAuthenticated } from "#/hooks/useAuthenticated";
import { useDashboard } from "#/modules/dashboard/useDashboard";
import {
getMemberOrganizations,
useDashboard,
} from "#/modules/dashboard/useDashboard";
import { RetryButton } from "../../components/RetryButton";
import { SectionHeader } from "../../components/SectionHeader";
import { SkillsTable } from "../../components/SkillsTable";
@@ -17,10 +20,9 @@ import {
const AgentSettingsSkillsPage: React.FC = () => {
const { user } = useAuthenticated();
// The dashboard lists every organization the user can read, but chats
// only run in organizations the user is a member of.
const memberOrganizations = useDashboard().organizations.filter(
(organization) => user.organization_ids.includes(organization.id),
const memberOrganizations = getMemberOrganizations(
useDashboard().organizations,
user,
);
const organizationSkillQueries = useQueries({
queries: memberOrganizations.map((organization) =>
@@ -441,6 +441,9 @@ export const OrganizationScopedMCPServers: Story = {
);
});
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: /MCP servers/ }),
);
expect(
(await body.findAllByText("Default organization MCP")).length,
).toBeGreaterThan(0);
@@ -460,6 +463,9 @@ export const OrganizationScopedMCPServers: Story = {
);
});
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: /MCP servers/ }),
);
expect(
(await body.findAllByText("Second organization MCP")).length,
).toBeGreaterThan(0);
@@ -1,16 +1,7 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { MonitorDotIcon } from "lucide-react";
import { useEffect, useRef } from "react";
import {
expect,
fn,
screen,
spyOn,
userEvent,
waitFor,
within,
} from "storybook/test";
import { API } from "#/api/api";
import { expect, fn, screen, userEvent, waitFor, within } from "storybook/test";
import { preferenceSettingsKey } from "#/api/queries/users";
import type * as TypesGen from "#/api/typesGenerated";
import {
@@ -27,7 +18,6 @@ import { setupMatchMedia } from "#/testHelpers/matchMedia";
import {
withDashboardProvider,
withProxyProvider,
withToaster,
} from "#/testHelpers/storybook";
import {
AgentChatInput,
@@ -663,34 +653,22 @@ const mockSlackMCPAlwaysOnNeedingAuth = buildMCPServer({
const mcpDefaults = {
chatOrganizationId: "org-1",
onMCPSelectionChange: fn(),
onMCPAuthComplete: fn(),
};
const dispatchMCPOAuthComplete = (
serverID: string,
source: MessageEventSource | null = null,
) => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "mcp-oauth2-complete", serverID },
origin: location.origin,
source,
}),
const mockNotionMCPSignedOut = { ...notionMCPConnected, auth_connected: false };
const openMCPSubmenu: Story["play"] = async ({ canvasElement }) => {
await userEvent.click(
within(canvasElement).getByRole("button", { name: "More options" }),
);
await userEvent.click(
await screen.findByRole("button", { name: /MCP servers/ }),
);
};
// Requires window.open mocked to return a Window; the completion
// message's source must be that same mocked popup to correlate.
const startMCPOAuthFlow = async (canvasElement: HTMLElement) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(await body.findByRole("button", { name: "Auth" }));
};
// ── MCP stories ────────────────────────────────────────────────
/** Three selected servers collapse into a single "3 MCPs" pill. */
/** Selected servers share one "N MCPs" pill. */
export const WithMCPServers: Story = {
args: {
...mcpDefaults,
@@ -718,11 +696,16 @@ export const ReadOnlyNotice: Story = {
},
};
/** The pill lists only its active servers; Notion stays in the plus menu. */
export const MCPGroupPopoverOpen: Story = {
args: {
...WithMCPServers.args,
mcpServers: [sentryMCP, linearMCP, githubMCPConnected, notionMCPConnected],
mcpServers: [
sentryMCP,
linearMCP,
githubMCPConnected,
notionMCPConnected,
mockSlackMCPAlwaysOnNeedingAuth,
],
},
play: async ({ canvasElement }) => {
await userEvent.click(
@@ -740,6 +723,15 @@ export const MCPGroupDisabled: Story = {
play: MCPGroupPopoverOpen.play,
};
export const MCPGroupReadOnly: Story = {
args: {
...ReadOnlyNotice.args,
mcpServers: [sentryMCP, linearMCP, githubMCPConnected],
selectedMCPServerIds: [sentryMCP.id, linearMCP.id, githubMCPConnected.id],
},
play: MCPGroupPopoverOpen.play,
};
const mockLongNameMCP = buildMCPServer({
id: "mcp-long-name",
display_name: "Coder Internal Documentation Search Server",
@@ -749,7 +741,6 @@ const mockLongNameMCP = buildMCPServer({
enabled: true,
});
/** A long server name truncates inside the popover instead of pushing its X out of view. */
export const MCPGroupPopoverLongName: Story = {
args: {
...mcpDefaults,
@@ -759,174 +750,57 @@ export const MCPGroupPopoverLongName: Story = {
play: MCPGroupPopoverOpen.play,
};
export const PlusMenuAlwaysOnNeedingAuth: Story = {
export const MCPSubmenuOpen: Story = {
args: {
...WithMCPServers.args,
...mcpDefaults,
mcpServers: [sentryMCP, githubMCP, linearMCP, notionMCPConnected],
selectedMCPServerIds: [sentryMCP.id, linearMCP.id],
},
play: openMCPSubmenu,
};
export const MCPSubmenuSelectedDisconnected: Story = {
args: {
...mcpDefaults,
mcpServers: [
sentryMCP,
githubMCP,
linearMCP,
githubMCPConnected,
mockSlackMCPAlwaysOnNeedingAuth,
],
selectedMCPServerIds: [sentryMCP.id, githubMCP.id, linearMCP.id],
},
play: async ({ canvasElement }) => {
await userEvent.click(
within(canvasElement).getByRole("button", { name: "More options" }),
);
},
play: openMCPSubmenu,
};
/** MCP server needing OAuth — shows Auth button instead of toggle. */
export const WithMCPNeedingAuth: Story = {
export const MCPSubmenuNoUsableServers: Story = {
args: {
...mcpDefaults,
mcpServers: [sentryMCP, githubMCP],
selectedMCPServerIds: [sentryMCP.id, githubMCP.id],
},
beforeEach: () => {
spyOn(window, "open").mockReturnValue(null);
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(body.getByRole("button", { name: "Auth" }));
expect(window.open).toHaveBeenCalledWith(
"/api/v2/organizations/org-1/mcp-servers/mcp-github/oauth2/connect",
"_blank",
"width=900,height=600",
);
// The popup was blocked (window.open returned null), so the flow
// must not enter the connecting state that disables Auth buttons.
expect(body.getByRole("button", { name: "Auth" })).toBeEnabled();
},
};
export const MCPAutoEnablesAfterOAuthCompletes: Story = {
args: {
...mcpDefaults,
mcpServers: [linearMCP, githubMCP],
selectedMCPServerIds: [linearMCP.id],
},
beforeEach: () => {
spyOn(window, "open").mockReturnValue(window);
},
play: async ({ args, canvasElement }) => {
await startMCPOAuthFlow(canvasElement);
expect(window.open).toHaveBeenCalledWith(
`/api/v2/organizations/org-1/mcp-servers/${githubMCP.id}/oauth2/connect`,
"_blank",
"width=900,height=600",
);
dispatchMCPOAuthComplete(githubMCP.id, window);
await waitFor(() => {
expect(args.onMCPSelectionChange).toHaveBeenCalledWith([
linearMCP.id,
githubMCP.id,
]);
expect(args.onMCPAuthComplete).toHaveBeenCalledWith(githubMCP.id);
});
},
};
// The coderd callback page posts the completion message and then closes
// the popup, so the close poll can observe the closed popup before the
// queued message is dispatched. An iframe contentWindow stands in for
// the popup: it is a real Window whose closed becomes true on removal.
export const MCPAutoEnablesWhenPopupClosesBeforeMessage: Story = {
args: {
...mcpDefaults,
mcpServers: [githubMCP],
mcpServers: [githubMCP, mockNotionMCPSignedOut],
selectedMCPServerIds: [],
},
play: async ({ args, canvasElement }) => {
const doc = canvasElement.ownerDocument;
const iframe = doc.createElement("iframe");
doc.body.appendChild(iframe);
const popup = iframe.contentWindow;
if (!popup) {
throw new Error("iframe contentWindow unavailable");
}
spyOn(window, "open").mockReturnValue(popup);
await startMCPOAuthFlow(canvasElement);
iframe.remove();
expect(popup.closed).toBe(true);
// Wait for the close poll to clear the connecting state before
// delivering the completion message.
const body = within(doc.body);
await waitFor(
() => {
expect(body.getByRole("button", { name: "Auth" })).toBeEnabled();
},
{ timeout: 2_000 },
);
dispatchMCPOAuthComplete(githubMCP.id, popup);
await waitFor(() => {
expect(args.onMCPSelectionChange).toHaveBeenCalledWith([githubMCP.id]);
});
},
play: openMCPSubmenu,
};
export const MCPDoesNotDuplicateSelectionAfterOAuthCompletes: Story = {
export const MCPSubmenuAllConnected: Story = {
args: {
...mcpDefaults,
mcpServers: [githubMCP],
selectedMCPServerIds: [githubMCP.id],
},
beforeEach: () => {
spyOn(window, "open").mockReturnValue(window);
},
play: async ({ args, canvasElement }) => {
await startMCPOAuthFlow(canvasElement);
dispatchMCPOAuthComplete(githubMCP.id, window);
await waitFor(() => {
expect(args.onMCPAuthComplete).toHaveBeenCalledWith(githubMCP.id);
});
expect(args.onMCPSelectionChange).not.toHaveBeenCalled();
mcpServers: [sentryMCP, githubMCPConnected, linearMCP],
selectedMCPServerIds: [sentryMCP.id],
},
play: openMCPSubmenu,
};
export const MCPIgnoresUnsolicitedOAuthComplete: Story = {
args: {
...mcpDefaults,
mcpServers: [linearMCP, githubMCP],
selectedMCPServerIds: [linearMCP.id],
},
play: async ({ args }) => {
dispatchMCPOAuthComplete(githubMCP.id, window);
await waitFor(() => {
expect(args.onMCPAuthComplete).toHaveBeenCalledWith(githubMCP.id);
});
expect(args.onMCPSelectionChange).not.toHaveBeenCalled();
export const MCPSubmenuMobile: Story = {
args: MCPSubmenuOpen.args,
parameters: {
viewport: { defaultViewport: "mobile1" },
pixel: { matrix: { viewports: ["phone"] } },
},
play: openMCPSubmenu,
};
export const MCPIgnoresMismatchedServerAfterOAuthCompletes: Story = {
args: {
...mcpDefaults,
mcpServers: [linearMCP, githubMCP],
selectedMCPServerIds: [],
},
beforeEach: () => {
spyOn(window, "open").mockReturnValue(window);
},
play: async ({ args, canvasElement }) => {
await startMCPOAuthFlow(canvasElement);
dispatchMCPOAuthComplete(linearMCP.id, window);
await waitFor(() => {
expect(args.onMCPAuthComplete).toHaveBeenCalledWith(linearMCP.id);
});
expect(args.onMCPSelectionChange).not.toHaveBeenCalled();
},
};
/** No MCP servers active — shows only "MCP" label with chevron. */
/** No MCP servers active: the pill reads "Add MCPs". */
export const WithMCPNoneActive: Story = {
args: {
...mcpDefaults,
@@ -962,131 +836,6 @@ export const PlusMenuOpen: Story = {
},
};
export const MCPDisconnectControls: Story = {
args: {
...mcpDefaults,
mcpServers: [linearMCP, githubMCP, notionMCPConnected],
selectedMCPServerIds: [linearMCP.id, notionMCPConnected.id],
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
},
};
export const MCPDisconnectCancel: Story = {
args: {
...mcpDefaults,
mcpServers: [githubMCPConnected],
selectedMCPServerIds: [githubMCPConnected.id],
},
beforeEach: () => {
spyOn(API.experimental, "disconnectMCPServerOAuth2").mockResolvedValue({
token_revoked: true,
});
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: "Disconnect GitHub" }),
);
expect(await body.findByText("Disconnect GitHub?")).toBeInTheDocument();
await userEvent.click(body.getByRole("button", { name: "Cancel" }));
await waitFor(() =>
expect(body.queryByText("Disconnect GitHub?")).not.toBeInTheDocument(),
);
expect(API.experimental.disconnectMCPServerOAuth2).not.toHaveBeenCalled();
},
};
export const MCPDisconnectConfirm: Story = {
args: {
...mcpDefaults,
mcpServers: [githubMCPConnected],
selectedMCPServerIds: [githubMCPConnected.id],
},
beforeEach: () => {
spyOn(API.experimental, "disconnectMCPServerOAuth2").mockResolvedValue({
token_revoked: true,
});
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: "Disconnect GitHub" }),
);
await body.findByText("Disconnect GitHub?");
await userEvent.click(body.getByRole("button", { name: "Disconnect" }));
await waitFor(() =>
expect(body.queryByText("Disconnect GitHub?")).not.toBeInTheDocument(),
);
expect(API.experimental.disconnectMCPServerOAuth2).toHaveBeenCalledTimes(1);
expect(API.experimental.disconnectMCPServerOAuth2).toHaveBeenCalledWith(
githubMCPConnected.id,
);
},
};
export const MCPDisconnectRevocationWarning: Story = {
args: {
...mcpDefaults,
mcpServers: [githubMCPConnected],
selectedMCPServerIds: [githubMCPConnected.id],
},
decorators: [withToaster],
beforeEach: () => {
spyOn(API.experimental, "disconnectMCPServerOAuth2").mockResolvedValue({
token_revoked: false,
token_revocation_error:
"The OAuth provider rejected the revocation request.",
});
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: "Disconnect GitHub" }),
);
await body.findByText("Disconnect GitHub?");
await userEvent.click(body.getByRole("button", { name: "Disconnect" }));
await body.findByText(
"The OAuth provider rejected the revocation request.",
);
},
};
export const MCPDisconnectError: Story = {
args: {
...mcpDefaults,
mcpServers: [githubMCPConnected],
selectedMCPServerIds: [githubMCPConnected.id],
},
beforeEach: () => {
spyOn(API.experimental, "disconnectMCPServerOAuth2").mockRejectedValue(
new Error("disconnect failed"),
);
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(canvas.getByRole("button", { name: "More options" }));
await userEvent.click(
await body.findByRole("button", { name: "Disconnect GitHub" }),
);
await body.findByText("Disconnect GitHub?");
await userEvent.click(body.getByRole("button", { name: "Disconnect" }));
await waitFor(() =>
expect(API.experimental.disconnectMCPServerOAuth2).toHaveBeenCalled(),
);
expect(body.getByText("Disconnect GitHub?")).toBeInTheDocument();
},
};
export const PlanFirstMenuItem: Story = {
args: {
onPlanModeToggle: fn(),
@@ -1396,8 +1145,8 @@ export const MCPGroupInOverflow: Story = {
await userEvent.click(
within(overflow).getByRole("button", { name: "3 MCPs" }),
);
// The group popover is a second dialog, so wait for one of its pills.
await screen.findByRole("button", { name: "Remove Linear" });
// The group popover is a second dialog, so wait for one of its switches.
await screen.findByRole("switch", { name: "Disable Linear" });
},
};
@@ -8,6 +8,7 @@ import {
} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { createRef } from "react";
import { createMemoryRouter, MemoryRouter, useLocation } from "react-router";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { AppProviders } from "#/App";
import { API } from "#/api/api";
@@ -16,11 +17,17 @@ import { userSkills } from "#/api/queries/userSkills";
import type * as TypesGen from "#/api/typesGenerated";
import { toast } from "#/components/Toaster/toast";
import { MockMCPServerConfig } from "#/testHelpers/chatEntities";
import { MockChatProject } from "#/testHelpers/entities";
import { MockChatProject, MockWorkspace } from "#/testHelpers/entities";
import { createMockFile } from "#/testHelpers/files";
import { createTestQueryClient } from "#/testHelpers/renderHelpers";
import {
createTestQueryClient,
renderWithRouter,
} from "#/testHelpers/renderHelpers";
import { MockSkill } from "#/testHelpers/skills";
import { mobileViewportMediaQuery } from "#/utils/mobile";
import {
belowMdViewportMediaQuery,
mobileViewportMediaQuery,
} from "#/utils/mobile";
import type * as speechRecognition from "../hooks/useSpeechRecognition";
import { useSpeechRecognition } from "../hooks/useSpeechRecognition";
import { AgentChatInput, type ChatMessageInputRef } from "./AgentChatInput";
@@ -45,12 +52,13 @@ const mockedUseSpeechRecognition = vi.mocked(useSpeechRecognition);
// implementation rather than a previous stub.
const originalMatchMedia = window.matchMedia;
const stubViewport = (isMobile: boolean) => {
const stubViewport = (
matches: boolean,
mediaQuery = mobileViewportMediaQuery,
) => {
vi.stubGlobal("matchMedia", (query: string) => {
const result = originalMatchMedia(query);
return query === mobileViewportMediaQuery
? { ...result, matches: isMobile }
: result;
return query === mediaQuery ? { ...result, matches } : result;
});
};
@@ -123,7 +131,9 @@ const mockMCPServers = [mockSentryMCP, mockLinearMCP, mockGitHubMCP];
const mockSelectedMCPServerIds = mockMCPServers.map((server) => server.id);
const renderInput = (children: React.ReactNode) => {
return render(<AppProviders>{children}</AppProviders>);
return render(<AppProviders>{children}</AppProviders>, {
wrapper: MemoryRouter,
});
};
beforeAll(() => {
@@ -209,6 +219,7 @@ describe("AgentChatInput", () => {
chatOrganizationId="org-1"
/>
</AppProviders>,
{ wrapper: MemoryRouter },
);
await user.click(screen.getByRole("textbox", { name: "Chat message" }));
@@ -258,6 +269,7 @@ describe("AgentChatInput", () => {
chatProjectId="project-1"
/>
</AppProviders>,
{ wrapper: MemoryRouter },
);
await user.click(screen.getByRole("textbox", { name: "Chat message" }));
@@ -293,7 +305,7 @@ describe("AgentChatInput", () => {
</AppProviders>
);
const { rerender } = render(renderInput(true));
const { rerender } = render(renderInput(true), { wrapper: MemoryRouter });
await screen.findByRole("textbox", { name: "Chat message" });
expect(getChatProjectSkills).not.toHaveBeenCalled();
@@ -340,7 +352,7 @@ describe("AgentChatInput", () => {
);
});
it("removes a selected MCP server from the group", async () => {
it("turns a server off from the group pill's menu", async () => {
const user = userEvent.setup();
const onMCPSelectionChange = vi.fn();
renderInput(
@@ -354,8 +366,8 @@ describe("AgentChatInput", () => {
await user.click(screen.getByRole("button", { name: "3 MCPs" }));
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "Remove Linear",
within(screen.getByRole("dialog")).getByRole("switch", {
name: "Disable Linear",
}),
);
expect(onMCPSelectionChange).toHaveBeenCalledWith([
@@ -364,7 +376,37 @@ describe("AgentChatInput", () => {
]);
});
it("enables an unselected MCP server from the plus menu while the group is collapsed", async () => {
it("keeps keyboard focus in the menu through the below-md submenus", async () => {
const user = userEvent.setup();
stubViewport(true, belowMdViewportMediaQuery);
renderInput(
<AgentChatInput
{...inputProps}
mcpServers={mockMCPServers}
selectedMCPServerIds={mockSelectedMCPServerIds}
onMCPSelectionChange={vi.fn()}
workspaceOptions={[MockWorkspace]}
onWorkspaceChange={vi.fn()}
/>,
);
await user.click(screen.getByRole("button", { name: "More options" }));
(await screen.findByRole("button", { name: /MCP servers/ })).focus();
await user.keyboard("{Enter}");
expect(await screen.findByRole("button", { name: "Back" })).toHaveFocus();
await user.keyboard("{Enter}");
expect(screen.getByRole("button", { name: /MCP servers/ })).toHaveFocus();
screen.getByRole("button", { name: "Attach workspace" }).focus();
await user.keyboard("{Enter}");
expect(await screen.findByRole("button", { name: "Back" })).toHaveFocus();
await user.keyboard("{Enter}");
expect(
screen.getByRole("button", { name: "Attach workspace" }),
).toHaveFocus();
});
it("enables an unselected MCP server from the MCP servers submenu", async () => {
const user = userEvent.setup();
const onMCPSelectionChange = vi.fn();
renderInput(
@@ -377,6 +419,9 @@ describe("AgentChatInput", () => {
);
await user.click(screen.getByRole("button", { name: "More options" }));
await user.click(
await screen.findByRole("button", { name: /MCP servers/ }),
);
await user.click(
await screen.findByRole("switch", { name: "Enable Notion" }),
);
@@ -388,25 +433,54 @@ describe("AgentChatInput", () => {
]);
});
it("keeps two active MCP servers as individual pills", async () => {
it("announces a disconnected always-on server as always on", async () => {
const user = userEvent.setup();
const mockDisconnectedSentryMCP = {
...mockSentryMCP,
auth_connected: false,
};
renderInput(
<AgentChatInput
{...inputProps}
mcpServers={[mockDisconnectedSentryMCP, mockLinearMCP]}
selectedMCPServerIds={[mockDisconnectedSentryMCP.id, mockLinearMCP.id]}
onMCPSelectionChange={vi.fn()}
/>,
);
await user.click(screen.getByRole("button", { name: "More options" }));
await user.click(
await screen.findByRole("button", { name: /MCP servers/ }),
);
const menu = await screen.findByRole("group", { name: "MCP servers" });
expect(menu).toHaveTextContent(/Sentry\s*Always on/);
expect(
within(menu).getByRole("img", { name: "Not connected" }),
).toBeInTheDocument();
});
it("turns a server on from the empty MCP pill", async () => {
const user = userEvent.setup();
const onMCPSelectionChange = vi.fn();
renderInput(
<AgentChatInput
{...inputProps}
mcpServers={[mockLinearMCP, mockGitHubMCP]}
selectedMCPServerIds={[mockLinearMCP.id, mockGitHubMCP.id]}
selectedMCPServerIds={[]}
onMCPSelectionChange={onMCPSelectionChange}
/>,
);
await user.click(screen.getByRole("button", { name: "Remove Linear" }));
expect(onMCPSelectionChange).toHaveBeenCalledWith([mockGitHubMCP.id]);
await user.click(screen.getByRole("button", { name: "Add MCPs" }));
await user.click(
within(screen.getByRole("dialog")).getByRole("switch", {
name: "Enable Linear",
}),
);
expect(onMCPSelectionChange).toHaveBeenCalledWith([mockLinearMCP.id]);
});
it("excludes selected MCP servers that still need OAuth from the group", async () => {
const user = userEvent.setup();
const onMCPSelectionChange = vi.fn();
it("excludes selected MCP servers that still need OAuth from the pill count", () => {
renderInput(
<AgentChatInput
{...inputProps}
@@ -416,15 +490,11 @@ describe("AgentChatInput", () => {
mockLinearMCP.id,
mockGitHubMCPNeedingAuth.id,
]}
onMCPSelectionChange={onMCPSelectionChange}
onMCPSelectionChange={vi.fn()}
/>,
);
await user.click(screen.getByRole("button", { name: "Remove Linear" }));
expect(onMCPSelectionChange).toHaveBeenCalledWith([
mockSentryMCP.id,
mockGitHubMCPNeedingAuth.id,
]);
expect(screen.getByRole("button", { name: "2 MCPs" })).toBeInTheDocument();
});
it("allows viewing a disabled MCP group without changing its selection", async () => {
@@ -442,13 +512,59 @@ describe("AgentChatInput", () => {
await user.click(screen.getByRole("button", { name: "3 MCPs" }));
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "Remove Linear",
within(screen.getByRole("dialog")).getByRole("switch", {
name: "Disable Linear",
}),
);
expect(onMCPSelectionChange).not.toHaveBeenCalled();
});
it("opens MCP connections settings with a way back to the chat", async () => {
const user = userEvent.setup();
const onSettingsState = vi.fn();
const SettingsPage = () => {
onSettingsState(useLocation().state);
return null;
};
renderWithRouter(
createMemoryRouter(
[
{
path: "/agents/:chatId",
element: (
<AgentChatInput
{...inputProps}
chatOrganizationId="org-1"
mcpServers={[mockLinearMCP]}
selectedMCPServerIds={[]}
onMCPSelectionChange={vi.fn()}
/>
),
},
{
path: "/agents/settings/mcp-connections",
element: <SettingsPage />,
},
],
{ initialEntries: ["/agents/chat-1?tab=git"] },
),
);
await user.click(screen.getByRole("button", { name: "More options" }));
await user.click(
await screen.findByRole("button", { name: /MCP servers/ }),
);
await user.click(
await screen.findByRole("button", { name: "Manage MCP connections" }),
);
await waitFor(() =>
expect(onSettingsState).toHaveBeenCalledWith({
from: "/agents/chat-1?tab=git",
organizationId: "org-1",
}),
);
});
it("swaps Stop for the Queue button once a draft is entered while streaming", async () => {
const user = userEvent.setup();
const inputRef = createRef<ChatMessageInputRef>();
@@ -658,7 +774,7 @@ describe("AgentChatInput", () => {
<AgentChatInput {...inputProps} inputRef={inputRef} />
</AppProviders>
);
const { rerender } = render(input());
const { rerender } = render(input(), { wrapper: MemoryRouter });
await waitFor(() => expect(inputRef.current).not.toBeNull());
act(() => inputRef.current?.insertSkill("project", "triage"));
const chip = {
@@ -6,24 +6,20 @@ import {
ChevronDownIcon,
ChevronRightIcon,
InfoIcon,
LockIcon,
MicIcon,
MonitorIcon,
PaperclipIcon,
PencilIcon,
PlugIcon,
PlusIcon,
ServerIcon,
SquareIcon,
TriangleAlertIcon,
UnlinkIcon,
XIcon,
} from "lucide-react";
import type React from "react";
import { useEffect, useId, useImperativeHandle, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { Link } from "react-router";
import { getErrorMessage } from "#/api/errors";
import { disconnectMCPServerOAuth2 } from "#/api/queries/chats";
import { useQuery } from "react-query";
import { Link, useLocation, useNavigate } from "react-router";
import { preferenceSettings } from "#/api/queries/users";
import type * as TypesGen from "#/api/typesGenerated";
import type { ChatQueuedMessage } from "#/api/typesGenerated";
@@ -37,8 +33,6 @@ import {
CommandItem,
CommandList,
} from "#/components/Command/Command";
import { ConfirmDialog } from "#/components/Dialog/ConfirmDialog/ConfirmDialog";
import { ExternalImage } from "#/components/ExternalImage/ExternalImage";
import {
Popover,
PopoverContent,
@@ -48,7 +42,6 @@ import {
import { Separator } from "#/components/Separator/Separator";
import { Skeleton } from "#/components/Skeleton/Skeleton";
import { Spinner } from "#/components/Spinner/Spinner";
import { Switch } from "#/components/Switch/Switch";
import { toast } from "#/components/Toaster/toast";
import {
Tooltip,
@@ -69,7 +62,6 @@ import {
mobileViewportMediaQuery,
} from "#/utils/mobile";
import { chatWidthClass, useChatFullWidth } from "../hooks/useChatFullWidth";
import { useMCPOAuthFlow } from "../hooks/useMCPOAuthFlow";
import { useOverflowCount } from "../hooks/useOverflowCount";
import { useSpeechRecognition } from "../hooks/useSpeechRecognition";
import {
@@ -101,6 +93,7 @@ import type { AgentContextUsage } from "./ContextUsageIndicator";
import { ContextUsageIndicator } from "./ContextUsageIndicator";
import { ImageLightbox } from "./ImageLightbox";
import { MCPServerIconStack } from "./MCPServerIconStack";
import { MCPServersMenuContent } from "./MCPServersMenuContent";
import { ProjectSkillActions } from "./ProjectSkillActions";
import { QueuedMessagesList } from "./QueuedMessagesList";
import { TextPreviewDialog } from "./TextPreviewDialog";
@@ -229,7 +222,6 @@ type AgentChatInputProps = {
mcpServers?: readonly TypesGen.MCPServerConfig[];
selectedMCPServerIds?: readonly string[];
onMCPSelectionChange?: (ids: string[]) => void;
onMCPAuthComplete?: (serverId: string) => void;
workspaceSkills?: readonly SkillMetadata[];
workspace?: TypesGen.Workspace;
workspaceAgent?: TypesGen.WorkspaceAgent;
@@ -283,15 +275,12 @@ const BadgePopoverContent: React.FC<PopoverContentProps> = ({
type ToolBadgeData =
| { kind: "workspace"; name: string }
| ({ kind: "attached-workspace" } & AttachedWorkspaceInfo)
| { kind: "mcp"; server: TypesGen.MCPServerConfig }
| { kind: "mcp-group"; servers: readonly TypesGen.MCPServerConfig[] }
| { kind: "planning" };
// Non-MCP badges can share a kind, so their keys are position-qualified.
const badgeKey = (badge: ToolBadgeData, index: number) => {
switch (badge.kind) {
case "mcp":
return badge.server.id;
case "mcp-group":
return badge.kind;
default:
@@ -323,19 +312,22 @@ const BadgeDismissButton: React.FC<{
type MCPGroupBadgeProps = {
servers: readonly TypesGen.MCPServerConfig[];
onRemoveMcp?: (serverId: string) => void;
isDisabled: boolean;
menu: React.ReactNode;
className: string;
};
const MCPGroupBadge: React.FC<MCPGroupBadgeProps> = ({
servers,
onRemoveMcp,
isDisabled,
menu,
className,
}) => {
const [open, setOpen] = useState(false);
const label = `${servers.length} MCPs`;
let label = `${servers.length} MCPs`;
if (servers.length === 0) {
label = "Add MCPs";
} else if (servers.length === 1) {
label = "1 MCP";
}
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -348,32 +340,51 @@ const MCPGroupBadge: React.FC<MCPGroupBadgeProps> = ({
"cursor-pointer border-0 transition-colors hover:bg-surface-tertiary hover:text-content-primary",
)}
>
<MCPServerIconStack servers={servers} />
{servers.length === 0 ? (
<PlugIcon className="size-3 shrink-0" />
) : (
<MCPServerIconStack servers={servers} />
)}
{label}
<ChevronDownIcon
className={cn("size-3 transition-transform", open && "rotate-180")}
/>
</button>
</PopoverTrigger>
<BadgePopoverContent>
{servers.map((server) => (
<ToolBadge
key={server.id}
badge={{ kind: "mcp", server }}
onRemoveMcp={onRemoveMcp}
isDisabled={isDisabled}
/>
))}
</BadgePopoverContent>
<PopoverContent side="top" align="start" className="w-72 p-1">
{menu}
</PopoverContent>
</Popover>
);
};
type MCPServersMenuRowContentProps = {
activeCount: number;
isOpen?: boolean;
};
const MCPServersMenuRowContent: React.FC<MCPServersMenuRowContentProps> = ({
activeCount,
isOpen,
}) => (
<>
<PlugIcon className="size-3.5 shrink-0" />
<span>MCP servers</span>
<span className="ml-auto">{activeCount} on</span>
<ChevronRightIcon
className={cn(
"size-icon-sm transition-transform",
isOpen && "rotate-180",
)}
/>
</>
);
const ToolBadge: React.FC<{
badge: ToolBadgeData;
onRemoveWorkspace?: () => void;
onRemoveMcp?: (serverId: string) => void;
onRemovePlanning?: () => void;
mcpMenu: React.ReactNode;
isDisabled: boolean;
className?: string;
// The overflow popover auto-focuses badges; suppress the tooltip there.
@@ -381,8 +392,8 @@ const ToolBadge: React.FC<{
}> = ({
badge,
onRemoveWorkspace,
onRemoveMcp,
onRemovePlanning,
mcpMenu,
isDisabled,
className,
disableTooltip,
@@ -462,48 +473,48 @@ const ToolBadge: React.FC<{
);
}
if (badge.kind === "mcp-group") {
return (
<MCPGroupBadge
servers={badge.servers}
onRemoveMcp={onRemoveMcp}
isDisabled={isDisabled}
className={badgeCls}
/>
);
}
const isForceOn = badge.server.availability === "force_on";
return (
<span className={badgeCls}>
{badge.server.icon_url ? (
<ExternalImage
src={badge.server.icon_url}
alt=""
className="size-3 rounded-sm"
/>
) : (
<ServerIcon className="size-3" />
)}
<span className="truncate">{badge.server.display_name}</span>
{isForceOn ? (
<>
<LockIcon className="size-3 shrink-0" />
<span className="sr-only">Always on</span>
</>
) : (
onRemoveMcp && (
<BadgeDismissButton
onClick={() => onRemoveMcp(badge.server.id)}
ariaLabel={`Remove ${badge.server.display_name}`}
isDisabled={isDisabled}
/>
)
)}
</span>
<MCPGroupBadge
servers={badge.servers}
menu={mcpMenu}
className={badgeCls}
/>
);
};
type PlusMenuSubmenu = "workspace" | "mcp";
// Below md, swapping the plus menu's views unmounts the focused control.
// A callback ref moves focus to its replacement, because biome's
// lint/a11y/noAutofocus rule rejects autoFocus on native buttons.
const focusOnMount = (element: HTMLElement | null) => {
element?.focus();
};
type PlusMenuSubmenuPanelProps = {
onBack: () => void;
children: React.ReactNode;
};
const PlusMenuSubmenuPanel: React.FC<PlusMenuSubmenuPanelProps> = ({
onBack,
children,
}) => (
<div className="p-0">
<button
ref={focusOnMount}
type="button"
onClick={onBack}
className="flex h-8 w-full cursor-pointer items-center gap-1.5 border-none bg-transparent px-1 text-xs text-content-secondary shadow-none transition-colors hover:text-content-primary"
>
<ArrowLeftIcon className="size-3.5 shrink-0" />
<span>Back</span>
</button>
<Separator className="my-1" />
{children}
</div>
);
export const AgentChatInput: React.FC<AgentChatInputProps> = ({
onSend,
placeholder = "Type a message...",
@@ -557,7 +568,6 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
mcpServers,
selectedMCPServerIds,
onMCPSelectionChange,
onMCPAuthComplete,
workspaceSkills,
workspace,
workspaceAgent,
@@ -602,33 +612,16 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
string | null
>(null);
const [plusMenuOpen, setPlusMenuOpen] = useState(false);
const [plusMenuView, setPlusMenuView] = useState<"main" | "workspace">(
const [plusMenuView, setPlusMenuView] = useState<"main" | PlusMenuSubmenu>(
"main",
);
// The submenu that Back closed, so the main view focuses its row.
const [lastPlusMenuSubmenu, setLastPlusMenuSubmenu] =
useState<PlusMenuSubmenu | null>(null);
const [workspacePickerOpen, setWorkspacePickerOpen] = useState(false);
const { connectingServerId: mcpConnectingId, connect: connectMCPServer } =
useMCPOAuthFlow({
organizationId: chatOrganizationId,
onAuthComplete: onMCPAuthComplete,
onFlowSuccess: (serverID) => {
if (
onMCPSelectionChange &&
selectedMCPServerIds &&
mcpServers?.some(
(server) => server.id === serverID && server.enabled,
) &&
!selectedMCPServerIds.includes(serverID)
) {
onMCPSelectionChange([...selectedMCPServerIds, serverID]);
}
},
});
const [mcpDisconnectTarget, setMcpDisconnectTarget] =
useState<TypesGen.MCPServerConfig | null>(null);
const queryClient = useQueryClient();
const mcpDisconnectMutation = useMutation(
disconnectMCPServerOAuth2(queryClient),
);
const [mcpMenuOpen, setMcpMenuOpen] = useState(false);
const navigate = useNavigate();
const location = useLocation();
const [hasChips, setHasChips] = useState(false);
const [cycleIndex, setCycleIndex] = useState<number | null>(null);
@@ -717,28 +710,6 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
}
};
const handleMcpDisconnectConfirm = () => {
if (!mcpDisconnectTarget) {
return;
}
const name = mcpDisconnectTarget.display_name;
mcpDisconnectMutation.mutate(mcpDisconnectTarget.id, {
onSuccess: (response) => {
setMcpDisconnectTarget(null);
if (response.token_revocation_error) {
toast.warning(`Disconnected ${name}.`, {
description: response.token_revocation_error,
});
} else {
toast.success(`Disconnected ${name}.`);
}
},
onError: (error) => {
toast.error(getErrorMessage(error, `Failed to disconnect ${name}.`));
},
});
};
// Only a chat-bound workspace counts: an unbound selection (new chat
// form, or a picked workspace before the first send) has no pinned
// context to resolve, so treating it as a workspace would leave the
@@ -756,6 +727,7 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
? selectedWorkspace.id !== linkedWorkspaceId
: false;
const isReadOnlyView = readOnlyNotice !== undefined;
const enabledMcpServers = mcpServers?.filter((s) => s.enabled) ?? [];
const activeMcpServers = enabledMcpServers.filter(
(s) =>
@@ -790,28 +762,76 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
if (shouldShowSelectedWorkspaceBadge && selectedWorkspace) {
allBadges.push({ kind: "workspace", name: selectedWorkspace.name });
}
if (activeMcpServers.length >= 3) {
// Read-only chats cannot add servers, so they show the pill only for
// servers already in use.
if (
activeMcpServers.length > 0 ||
(enabledMcpServers.length > 0 && !isReadOnlyView)
) {
allBadges.push({ kind: "mcp-group", servers: activeMcpServers });
} else {
for (const server of activeMcpServers) {
allBadges.push({ kind: "mcp", server });
}
}
const overflowCount = useOverflowCount(badgeContainerRef, allBadges.length);
const visibleCount = Math.max(0, allBadges.length - overflowCount);
const overflowBadges = allBadges.slice(visibleCount);
const isReadOnlyView = readOnlyNotice !== undefined;
const readOnlyModel = isReadOnlyView
? modelOptions.find((option) => option.id === selectedModel)
: undefined;
const handleRemoveWorkspace = () => onWorkspaceChange?.(null);
const removeWorkspaceHandler =
onWorkspaceChange && !isReadOnlyView ? handleRemoveWorkspace : undefined;
const handleRemoveMcp = isReadOnlyView
? undefined
: (serverId: string) => handleMcpToggle(serverId, false);
const closePlusMenuSubmenu = (submenu: PlusMenuSubmenu) => {
setLastPlusMenuSubmenu(submenu);
setPlusMenuView("main");
};
const plusMenuRowRef = (submenu: PlusMenuSubmenu) =>
lastPlusMenuSubmenu === submenu ? focusOnMount : undefined;
const handleManageConnections = () => {
setMcpMenuOpen(false);
setPlusMenuOpen(false);
setPlusMenuView("main");
navigate("/agents/settings/mcp-connections", {
state: {
from: location.pathname + location.search,
organizationId: chatOrganizationId,
},
});
};
const mcpMenuContent = (
<MCPServersMenuContent
servers={enabledMcpServers}
selectedServerIds={selectedMCPServerIds}
isDisabled={isDisabled}
onToggle={isReadOnlyView ? undefined : handleMcpToggle}
onManageConnections={isReadOnlyView ? undefined : handleManageConnections}
/>
);
let plusMenuSubmenuPanel: React.ReactNode = null;
if (plusMenuView === "mcp") {
plusMenuSubmenuPanel = (
<PlusMenuSubmenuPanel onBack={() => closePlusMenuSubmenu("mcp")}>
{mcpMenuContent}
</PlusMenuSubmenuPanel>
);
} else if (plusMenuView === "workspace") {
plusMenuSubmenuPanel = (
<PlusMenuSubmenuPanel onBack={() => closePlusMenuSubmenu("workspace")}>
<WorkspacePickerList
workspaceOptions={workspaceOptions}
selectedWorkspaceId={selectedWorkspaceId}
chatOrganizationId={chatOrganizationId}
onSelect={(id) => {
onWorkspaceChange?.(id);
setPlusMenuOpen(false);
}}
/>
</PlusMenuSubmenuPanel>
);
}
const handlePlanModeToggle = () => {
onPlanModeToggle(!planModeEnabled);
@@ -1542,7 +1562,11 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
open={plusMenuOpen}
onOpenChange={(open) => {
setPlusMenuOpen(open);
if (!open) setPlusMenuView("main");
setLastPlusMenuSubmenu(null);
if (!open) {
setPlusMenuView("main");
setMcpMenuOpen(false);
}
}}
>
{" "}
@@ -1570,27 +1594,8 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
align="start"
className="mobile-full-width-dropdown mobile-full-width-dropdown-bottom w-auto min-w-[200px] p-1"
>
{plusMenuView === "workspace" ? (
<div className="p-0">
<button
type="button"
onClick={() => setPlusMenuView("main")}
className="flex h-8 w-full cursor-pointer items-center gap-1.5 border-none bg-transparent px-1 text-xs text-content-secondary shadow-none transition-colors hover:text-content-primary"
>
<ArrowLeftIcon className="size-3.5 shrink-0" />
<span>Back</span>
</button>
<Separator className="my-1" />
<WorkspacePickerList
workspaceOptions={workspaceOptions}
selectedWorkspaceId={selectedWorkspaceId}
chatOrganizationId={chatOrganizationId}
onSelect={(id) => {
onWorkspaceChange?.(id);
setPlusMenuOpen(false);
}}
/>
</div>
{plusMenuView !== "main" ? (
plusMenuSubmenuPanel
) : (
<>
{onAttach && (
@@ -1627,6 +1632,7 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
<button
type="button"
disabled={!canUseWorkspacePicker}
ref={plusMenuRowRef("workspace")}
onClick={() => setPlusMenuView("workspace")}
className="group flex h-8 w-full cursor-pointer items-center gap-1.5 border-none bg-transparent px-1 text-xs text-content-secondary shadow-none transition-colors hover:text-content-primary disabled:cursor-not-allowed disabled:opacity-50"
>
@@ -1677,94 +1683,43 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
{enabledMcpServers.length > 0 && (
<>
<Separator className="my-1" />
{enabledMcpServers.map((server) => {
const isForceOn = server.availability === "force_on";
const isSelected =
isForceOn ||
(selectedMCPServerIds?.includes(server.id) ??
false);
const needsAuth =
server.auth_type === "oauth2" &&
!server.auth_connected;
const isConnecting = mcpConnectingId === server.id;
return (
<div
key={server.id}
className="flex items-center gap-1.5 px-1 py-1.5"
>
{server.icon_url ? (
<ExternalImage
src={server.icon_url}
alt=""
className="size-3.5 shrink-0 rounded-sm"
{isBelowMdViewport() ? (
<button
type="button"
ref={plusMenuRowRef("mcp")}
onClick={() => setPlusMenuView("mcp")}
className="flex h-8 w-full cursor-pointer items-center gap-1.5 border-none bg-transparent px-1 text-xs text-content-secondary shadow-none transition-colors hover:text-content-primary"
>
<MCPServersMenuRowContent
activeCount={activeMcpServers.length}
/>
</button>
) : (
<Popover
open={mcpMenuOpen}
onOpenChange={setMcpMenuOpen}
>
<PopoverTrigger asChild>
<button
type="button"
className="flex h-8 w-full cursor-pointer items-center gap-1.5 border-none bg-transparent px-1 text-xs text-content-secondary shadow-none transition-colors hover:text-content-primary"
>
<MCPServersMenuRowContent
activeCount={activeMcpServers.length}
isOpen={mcpMenuOpen}
/>
) : (
<ServerIcon className="size-3.5 shrink-0 text-content-secondary" />
)}
<span className="min-w-0 flex-1 truncate text-xs text-content-secondary">
{server.display_name}
</span>
{isForceOn && (
<LockIcon className="size-3 shrink-0 text-content-secondary" />
)}
{needsAuth ? (
<>
{isForceOn && (
<span className="sr-only">Always on</span>
)}
<Button
variant="outline"
size="sm"
className="h-6 shrink-0 px-2 text-[10px] leading-none"
onClick={() => connectMCPServer(server.id)}
disabled={
isDisabled || mcpConnectingId !== null
}
>
{isConnecting ? (
<Spinner
loading
className="h-2.5 w-2.5"
/>
) : null}
Auth
</Button>
</>
) : (
<>
{server.auth_type === "oauth2" && (
<Button
variant="subtle"
size="icon"
className="size-6 shrink-0 text-content-secondary [&>svg]:size-3"
onClick={() => {
setPlusMenuOpen(false);
setMcpDisconnectTarget(server);
}}
disabled={isDisabled}
aria-label={`Disconnect ${server.display_name}`}
>
<UnlinkIcon />
</Button>
)}
<Switch
size="sm"
checked={isSelected}
onCheckedChange={(checked) =>
handleMcpToggle(server.id, checked)
}
disabled={isDisabled || isForceOn}
aria-label={
isForceOn
? `${server.display_name} always on`
: `${isSelected ? "Disable" : "Enable"} ${server.display_name}`
}
/>
</>
)}
</div>
);
})}
</button>
</PopoverTrigger>
<PopoverContent
side="right"
align="end"
sideOffset={8}
className="w-72 p-1"
>
{mcpMenuContent}
</PopoverContent>
</Popover>
)}
</>
)}
</>
@@ -1857,8 +1812,8 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
key={badgeKey(badge, i)}
badge={badge}
onRemoveWorkspace={removeWorkspaceHandler}
onRemoveMcp={handleRemoveMcp}
onRemovePlanning={handleDisablePlanMode}
mcpMenu={mcpMenuContent}
isDisabled={isDisabled}
className={isOverflow ? "hidden" : undefined}
/>
@@ -1928,8 +1883,8 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
key={badgeKey(badge, visibleCount + i)}
badge={badge}
onRemoveWorkspace={removeWorkspaceHandler}
onRemoveMcp={handleRemoveMcp}
onRemovePlanning={handleDisablePlanMode}
mcpMenu={mcpMenuContent}
isDisabled={isDisabled}
disableTooltip
/>
@@ -2075,16 +2030,6 @@ export const AgentChatInput: React.FC<AgentChatInputProps> = ({
}}
/>
)}
<ConfirmDialog
open={mcpDisconnectTarget !== null}
title={`Disconnect ${mcpDisconnectTarget?.display_name ?? "MCP server"}?`}
description="This removes your credentials for this MCP server from Coder. You can authenticate again later."
type="delete"
confirmText="Disconnect"
confirmLoading={mcpDisconnectMutation.isPending}
onConfirm={handleMcpDisconnectConfirm}
onClose={() => setMcpDisconnectTarget(null)}
/>
</>
);
};
@@ -700,6 +700,9 @@ describe("AgentCreateForm organization lock", () => {
{ queryClient },
);
await user().click(screen.getByRole("button", { name: "More options" }));
await user().click(
await screen.findByRole("button", { name: /MCP servers/ }),
);
await user().click(
await screen.findByRole("switch", { name: "Enable Notion" }),
);
@@ -834,24 +837,26 @@ describe("AgentCreateForm prefill", () => {
render(
<StrictMode>
<AppProviders queryClient={createTestQueryClient()}>
<AgentCreateForm
onCreateChat={onCreateChat}
isCreating={false}
createError={undefined}
canCreateChat
canConfigureAgentSetup={false}
workspaceCount={0}
workspaceOptions={[]}
workspacesError={undefined}
isWorkspacesLoading={false}
prefill={{
message: "Why did this build fail?",
attachment: {
name: "workspace-build-logs.txt",
text: "Error: exit status 1\n",
},
}}
/>
<MemoryRouter>
<AgentCreateForm
onCreateChat={onCreateChat}
isCreating={false}
createError={undefined}
canCreateChat
canConfigureAgentSetup={false}
workspaceCount={0}
workspaceOptions={[]}
workspacesError={undefined}
isWorkspacesLoading={false}
prefill={{
message: "Why did this build fail?",
attachment: {
name: "workspace-build-logs.txt",
text: "Error: exit status 1\n",
},
}}
/>
</MemoryRouter>
</AppProviders>
</StrictMode>,
);
@@ -1102,7 +1102,6 @@ const AgentCreateFormContent: React.FC<AgentCreateFormProps> = ({
saveMCPSelection(organizationId, ids);
}
}}
onMCPAuthComplete={() => void mcpServersQuery.refetch()}
workspaceOptions={filteredWorkspaces}
selectedWorkspaceId={effectiveWorkspaceId}
// Do not persist a workspace until its organization is authorized.
@@ -148,7 +148,6 @@ const StoryChatPageInput: React.FC<{
mcpServers={[]}
selectedMCPServerIds={[]}
onMCPSelectionChange={fn()}
onMCPAuthComplete={fn()}
isWorkspaceLoading={false}
/>
</div>
@@ -493,7 +492,6 @@ const CompactionChatPageInput: React.FC = () => {
mcpServers={[]}
selectedMCPServerIds={[]}
onMCPSelectionChange={fn()}
onMCPAuthComplete={fn()}
isWorkspaceLoading={false}
/>
</div>
@@ -55,7 +55,6 @@ const renderChatPageInput = (
mcpServers={[]}
selectedMCPServerIds={[]}
onMCPSelectionChange={vi.fn()}
onMCPAuthComplete={vi.fn()}
isWorkspaceLoading={false}
{...overrides}
/>,
@@ -329,7 +329,6 @@ type ChatPageInputProps = {
mcpServers: readonly TypesGen.MCPServerConfig[];
selectedMCPServerIds: readonly string[];
onMCPSelectionChange: (ids: string[]) => void;
onMCPAuthComplete: (serverId: string) => void;
onWorkspaceChange?: (workspaceId: string | null) => void;
isWorkspaceLoading: boolean;
workspace?: TypesGen.Workspace;
@@ -378,7 +377,6 @@ export const ChatPageInput: React.FC<ChatPageInputProps> = ({
mcpServers,
selectedMCPServerIds,
onMCPSelectionChange,
onMCPAuthComplete,
onWorkspaceChange,
isWorkspaceLoading,
workspace,
@@ -833,7 +831,6 @@ export const ChatPageInput: React.FC<ChatPageInputProps> = ({
mcpServers={mcpServers}
selectedMCPServerIds={selectedMCPServerIds}
onMCPSelectionChange={onMCPSelectionChange}
onMCPAuthComplete={onMCPAuthComplete}
workspaceSkills={workspaceSkills}
workspace={workspace}
workspaceAgent={workspaceAgent}
@@ -5,6 +5,7 @@ import {
BotIcon,
KeyIcon,
PanelLeftCloseIcon,
PlugIcon,
ReceiptTextIcon,
Settings2Icon,
ShrinkIcon,
@@ -96,6 +97,13 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
to="/agents/settings/skills"
state={location.state}
/>
<SettingsNavItem
icon={PlugIcon}
label="MCP connections"
active={settingsSection === "mcp-connections"}
to="/agents/settings/mcp-connections"
state={location.state}
/>
<SettingsNavItem
icon={ShrinkIcon}
label="Compaction"
@@ -0,0 +1,147 @@
import { ArrowRightIcon, LockIcon, ServerIcon } from "lucide-react";
import type * as TypesGen from "#/api/typesGenerated";
import { Button } from "#/components/Button/Button";
import { ExternalImage } from "#/components/ExternalImage/ExternalImage";
import { Separator } from "#/components/Separator/Separator";
import { StatusIndicatorDot } from "#/components/StatusIndicator/StatusIndicator";
import { Switch } from "#/components/Switch/Switch";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "#/components/Tooltip/Tooltip";
import {
countMCPServersNeedingSignIn,
getMCPMenuServers,
} from "./mcpMenuServers";
type MCPServerMenuRowProps = {
server: TypesGen.MCPServerConfig;
isSelected: boolean;
isDisconnected: boolean;
isDisabled: boolean;
onToggle?: (serverId: string, checked: boolean) => void;
};
const MCPServerMenuRow: React.FC<MCPServerMenuRowProps> = ({
server,
isSelected,
isDisconnected,
isDisabled,
onToggle,
}) => {
const isForceOn = server.availability === "force_on";
let switchLabel = `Enable ${server.display_name}`;
if (isForceOn) {
switchLabel = `${server.display_name} always on`;
} else if (isSelected) {
switchLabel = `Disable ${server.display_name}`;
}
return (
<div className="flex min-h-8 items-center gap-1.5 px-1 py-1.5">
{server.icon_url ? (
<ExternalImage
src={server.icon_url}
alt=""
className="size-3.5 shrink-0 rounded-sm"
/>
) : (
<ServerIcon className="size-3.5 shrink-0 text-content-secondary" />
)}
<span className="min-w-0 flex-1 truncate text-xs text-content-secondary">
{server.display_name}
</span>
{isForceOn && (
<LockIcon className="size-3 shrink-0 text-content-secondary" />
)}
{isDisconnected ? (
<>
{isForceOn && <span className="sr-only">Always on</span>}
<Tooltip>
<TooltipTrigger asChild>
<StatusIndicatorDot
role="img"
aria-label="Not connected"
variant="warning"
size="sm"
className="shrink-0"
/>
</TooltipTrigger>
<TooltipContent>Not connected</TooltipContent>
</Tooltip>
</>
) : (
<Switch
size="sm"
checked={isSelected}
onCheckedChange={(checked) => onToggle?.(server.id, checked)}
disabled={isDisabled || isForceOn || !onToggle}
aria-label={switchLabel}
/>
)}
</div>
);
};
type MCPServersMenuContentProps = {
servers: readonly TypesGen.MCPServerConfig[];
selectedServerIds: readonly string[] | undefined;
isDisabled: boolean;
onToggle?: (serverId: string, checked: boolean) => void;
onManageConnections?: () => void;
};
/**
* Without `onToggle` the switches are read-only; without
* `onManageConnections` the link is hidden.
*/
export const MCPServersMenuContent: React.FC<MCPServersMenuContentProps> = ({
servers,
selectedServerIds,
isDisabled,
onToggle,
onManageConnections,
}) => {
const rows = getMCPMenuServers(servers, selectedServerIds);
const disconnectedCount = countMCPServersNeedingSignIn(servers);
return (
<div role="group" aria-label="MCP servers" className="flex flex-col">
{rows.length === 0 ? (
<p className="m-0 px-1 py-1.5 text-xs text-content-secondary">
No servers connected yet
</p>
) : (
rows.map((row) => (
<MCPServerMenuRow
key={row.server.id}
{...row}
isDisabled={isDisabled}
onToggle={onToggle}
/>
))
)}
<Separator className="my-1" />
<div className="flex items-center gap-3 px-1 py-0.5">
<span className="whitespace-nowrap text-xs text-content-secondary">
{disconnectedCount === 0
? "All connected"
: `${disconnectedCount} not connected`}
</span>
{onManageConnections && (
<Button
variant="outline"
size="sm"
className="ml-auto"
aria-label="Manage MCP connections"
onClick={onManageConnections}
>
Manage
<ArrowRightIcon />
</Button>
)}
</div>
</div>
);
};
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import type { MCPServerConfig } from "#/api/typesGenerated";
import { MockMCPServerConfig } from "#/testHelpers/chatEntities";
import {
countMCPServersNeedingSignIn,
getMCPMenuServers,
} from "./mcpMenuServers";
describe("getMCPMenuServers", () => {
const mockAPIKeyServer: MCPServerConfig = {
...MockMCPServerConfig,
id: "linear",
auth_type: "api_key",
};
const mockConnectedServer: MCPServerConfig = {
...MockMCPServerConfig,
id: "github",
auth_type: "oauth2",
auth_connected: true,
};
const mockSignedOutSelectedServer: MCPServerConfig = {
...MockMCPServerConfig,
id: "notion",
auth_type: "oauth2",
auth_connected: false,
};
const mockSignedOutForcedServer: MCPServerConfig = {
...MockMCPServerConfig,
id: "slack",
auth_type: "oauth2",
auth_connected: false,
availability: "force_on",
};
const mockSignedOutUnselectedServer: MCPServerConfig = {
...MockMCPServerConfig,
id: "wiz",
auth_type: "oauth2",
auth_connected: false,
};
const mockServers = [
mockAPIKeyServer,
mockConnectedServer,
mockSignedOutSelectedServer,
mockSignedOutForcedServer,
mockSignedOutUnselectedServer,
];
it("lists usable servers and selected or forced servers that are signed out", () => {
expect(
getMCPMenuServers(mockServers, [
mockConnectedServer.id,
mockSignedOutSelectedServer.id,
]),
).toEqual([
{ server: mockAPIKeyServer, isSelected: false, isDisconnected: false },
{ server: mockConnectedServer, isSelected: true, isDisconnected: false },
{
server: mockSignedOutSelectedServer,
isSelected: true,
isDisconnected: true,
},
{
server: mockSignedOutForcedServer,
isSelected: true,
isDisconnected: true,
},
]);
});
it("counts every server that needs sign-in", () => {
expect(countMCPServersNeedingSignIn(mockServers)).toBe(3);
});
});
@@ -0,0 +1,36 @@
import type * as TypesGen from "#/api/typesGenerated";
/** Reports whether the user must sign in before a chat can use the server. */
export const needsSignIn = (server: TypesGen.MCPServerConfig) =>
server.auth_type === "oauth2" && !server.auth_connected;
/**
* Servers the chat's MCP menu lists: those usable right now, plus those
* the chat selected (or an admin forces on) whose sign-in has lapsed, so
* the user can see why they stopped working.
*/
export const getMCPMenuServers = (
servers: readonly TypesGen.MCPServerConfig[],
selectedIds: readonly string[] | undefined,
): {
server: TypesGen.MCPServerConfig;
isSelected: boolean;
isDisconnected: boolean;
}[] =>
servers.flatMap((server) => {
const isDisconnected = needsSignIn(server);
const isSelected =
server.availability === "force_on" ||
(selectedIds?.includes(server.id) ?? false);
return !isDisconnected || isSelected
? [{ server, isSelected, isDisconnected }]
: [];
});
/**
* Counts OAuth2 servers the user has no connected account for, whatever
* their availability; callers pass only enabled servers.
*/
export const countMCPServersNeedingSignIn = (
servers: readonly TypesGen.MCPServerConfig[],
): number => servers.filter(needsSignIn).length;
@@ -0,0 +1,109 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MockMCPServerConfig } from "#/testHelpers/chatEntities";
import { useMCPOAuthFlow } from "./useMCPOAuthFlow";
const dispatchComplete = (
serverID: string,
source: MessageEventSource | null,
) => {
act(() => {
window.dispatchEvent(
new MessageEvent("message", {
data: { type: "mcp-oauth2-complete", serverID },
origin: location.origin,
source,
}),
);
});
};
// An iframe's window stands in for the popup so the hook sees a real
// Window. jsdom does not implement Window.closed, so closing defines it.
const createPopup = () => {
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const popup = iframe.contentWindow;
if (!popup) {
throw new Error("iframe contentWindow unavailable");
}
return {
popup,
closePopup: () => Object.defineProperty(popup, "closed", { value: true }),
};
};
const renderFlow = () => {
const onAuthComplete = vi.fn();
const onFlowSuccess = vi.fn();
const hook = renderHook(() =>
useMCPOAuthFlow({ organizationId: "org-1", onAuthComplete, onFlowSuccess }),
);
return { ...hook, onAuthComplete, onFlowSuccess };
};
describe("useMCPOAuthFlow", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("opens the organization's connect path and reports the initiating popup's completion", () => {
const { popup } = createPopup();
const open = vi.spyOn(window, "open").mockReturnValue(popup);
const { result, onAuthComplete, onFlowSuccess } = renderFlow();
act(() => result.current.connect(MockMCPServerConfig));
expect(open).toHaveBeenCalledWith(
`/api/v2/organizations/org-1/mcp-servers/${MockMCPServerConfig.id}/oauth2/connect`,
"_blank",
"width=900,height=600",
);
expect(result.current.connectingServerId).toBe(MockMCPServerConfig.id);
dispatchComplete(MockMCPServerConfig.id, popup);
expect(onAuthComplete).toHaveBeenCalledWith(MockMCPServerConfig.id);
expect(onFlowSuccess).toHaveBeenCalledWith(MockMCPServerConfig);
expect(result.current.connectingServerId).toBeNull();
});
it("does not enter the connecting state when the popup is blocked", () => {
vi.spyOn(window, "open").mockReturnValue(null);
const { result } = renderFlow();
act(() => result.current.connect(MockMCPServerConfig));
expect(result.current.connectingServerId).toBeNull();
});
it("refreshes but does not report success for an unsolicited completion", () => {
const { onAuthComplete, onFlowSuccess } = renderFlow();
dispatchComplete("mcp-github", window);
expect(onAuthComplete).toHaveBeenCalledWith("mcp-github");
expect(onFlowSuccess).not.toHaveBeenCalled();
});
it("does not report success for a completion about another server", () => {
const { popup } = createPopup();
vi.spyOn(window, "open").mockReturnValue(popup);
const { result, onAuthComplete, onFlowSuccess } = renderFlow();
act(() => result.current.connect(MockMCPServerConfig));
dispatchComplete("mcp-linear", popup);
expect(onAuthComplete).toHaveBeenCalledWith("mcp-linear");
expect(onFlowSuccess).not.toHaveBeenCalled();
});
it("reports success when the popup closes before its completion message arrives", async () => {
const { popup, closePopup } = createPopup();
vi.spyOn(window, "open").mockReturnValue(popup);
const { result, onFlowSuccess } = renderFlow();
act(() => result.current.connect(MockMCPServerConfig));
closePopup();
await waitFor(() => expect(result.current.connectingServerId).toBeNull(), {
timeout: 2_000,
});
dispatchComplete(MockMCPServerConfig.id, popup);
expect(onFlowSuccess).toHaveBeenCalledWith(MockMCPServerConfig);
});
});
@@ -1,5 +1,6 @@
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { mcpServerOAuth2ConnectPath } from "#/api/api";
import type { MCPServerConfig } from "#/api/typesGenerated";
type UseMCPOAuthFlowOptions = {
organizationId?: string;
@@ -9,12 +10,12 @@ type UseMCPOAuthFlowOptions = {
onAuthComplete?: (serverId: string) => void;
// Called only for a completion posted by the initiating popup for
// the initiating server.
onFlowSuccess: (serverId: string) => void;
onFlowSuccess: (server: MCPServerConfig) => void;
};
type MCPOAuthFlow = {
connectingServerId: string | null;
connect: (serverId: string) => void;
connect: (server: MCPServerConfig) => void;
};
/**
@@ -35,7 +36,9 @@ export const useMCPOAuthFlow = ({
// Retained after popup close: the callback page posts before
// closing, and the close poll can run before the queued message is
// dispatched.
const flowRef = useRef<{ popup: Window; serverID: string } | null>(null);
const flowRef = useRef<{ popup: Window; server: MCPServerConfig } | null>(
null,
);
const handleAuthComplete = useEffectEvent(
(serverID: string, source: MessageEventSource | null) => {
@@ -43,12 +46,12 @@ export const useMCPOAuthFlow = ({
// Only a message from the initiating popup for the initiating
// server counts as flow success.
const flow = flowRef.current;
if (!flow || source !== flow.popup || serverID !== flow.serverID) {
if (!flow || source !== flow.popup || serverID !== flow.server.id) {
return;
}
flowRef.current = null;
setConnectingServerId(null);
onFlowSuccess(serverID);
onFlowSuccess(flow.server);
},
);
@@ -86,16 +89,16 @@ export const useMCPOAuthFlow = ({
};
}, [connectingServerId]);
const connect = (serverId: string) => {
const connect = (server: MCPServerConfig) => {
if (!organizationId) {
return;
}
const connectUrl = mcpServerOAuth2ConnectPath(organizationId, serverId);
const connectUrl = mcpServerOAuth2ConnectPath(organizationId, server.id);
const popup = window.open(connectUrl, "_blank", "width=900,height=600");
// A blocked popup (window.open returns null) must not enter the
// connecting state; nothing would ever clear it.
flowRef.current = popup ? { popup, serverID: serverId } : null;
setConnectingServerId(popup ? serverId : null);
flowRef.current = popup ? { popup, server } : null;
setConnectingServerId(popup ? server.id : null);
};
return { connectingServerId, connect };
+10
View File
@@ -408,6 +408,12 @@ const AgentSettingsSkillsPage = lazy(
"./pages/AgentsPage/AgentSettingsPage/AgentSettingsSkillsPage/AgentSettingsSkillsPage"
),
);
const AgentSettingsMCPConnectionsPage = lazy(
() =>
import(
"./pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage"
),
);
const AgentSettingsAPIKeysPage = lazy(
() =>
import(
@@ -877,6 +883,10 @@ export const router = createBrowserRouter(
element={<AgentSettingsUserAgentsPage />}
/>
<Route path="skills" element={<AgentSettingsSkillsPage />} />
<Route
path="mcp-connections"
element={<AgentSettingsMCPConnectionsPage />}
/>
<Route
path="personal-skills"
element={<Navigate to="/agents/settings/skills" replace />}