diff --git a/docs/ai-coder/agents/extending-agents.md b/docs/ai-coder/agents/extending-agents.md index 6b58048b93c..ec35e9bab2a 100644 --- a/docs/ai-coder/agents/extending-agents.md +++ b/docs/ai-coder/agents/extending-agents.md @@ -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. diff --git a/docs/ai-coder/agents/platform-controls/mcp-servers.md b/docs/ai-coder/agents/platform-controls/mcp-servers.md index 02c0fbad8e2..02414ab21a3 100644 --- a/docs/ai-coder/agents/platform-controls/mcp-servers.md +++ b/docs/ai-coder/agents/platform-controls/mcp-servers.md @@ -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`. diff --git a/docs/ai-coder/agents/platform-controls/organizations.md b/docs/ai-coder/agents/platform-controls/organizations.md index 9d98967fc34..51921d98a21 100644 --- a/docs/ai-coder/agents/platform-controls/organizations.md +++ b/docs/ai-coder/agents/platform-controls/organizations.md @@ -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** | diff --git a/site/src/api/queries/chats.ts b/site/src/api/queries/chats.ts index 8041131b72c..b377e8b17ce 100644 --- a/site/src/api/queries/chats.ts +++ b/site/src/api/queries/chats.ts @@ -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 }); }; diff --git a/site/src/modules/dashboard/useDashboard.ts b/site/src/modules/dashboard/useDashboard.ts index b6f9378d689..7fc0fdd3bc1 100644 --- a/site/src/modules/dashboard/useDashboard.ts +++ b/site/src/modules/dashboard/useDashboard.ts @@ -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, +): DashboardValue["organizations"] => + organizations.filter((org) => user.organization_ids.includes(org.id)); diff --git a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.stories.tsx b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.stories.tsx index 34c99dc609f..a0d0b9bd629 100644 --- a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.stories.tsx +++ b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.stories.tsx @@ -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}`, diff --git a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.tsx b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.tsx index 7261651836d..21153e7e0a7 100644 --- a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.tsx +++ b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPage.tsx @@ -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} /> )} diff --git a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.stories.tsx b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.stories.tsx index f394f81d286..ecf2aba3301 100644 --- a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.stories.tsx +++ b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.stories.tsx @@ -201,7 +201,6 @@ const StoryAgentChatPageView: React.FC = ({ typeof AgentChatPageView >["selectedMCPServerIds"], onMCPSelectionChange: fn(), - onMCPAuthComplete: fn(), canConfigureAgentSetup: true, providerCount: 1, modelCount: 1, diff --git a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.tsx b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.tsx index 9d60c8f0cd2..e8c3cd6f848 100644 --- a/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.tsx +++ b/site/src/pages/AgentsPage/AgentChatPage/AgentChatPageView.tsx @@ -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 = ({ mcpServers, selectedMCPServerIds, onMCPSelectionChange, - onMCPAuthComplete, desktopChatId, }) => { const { proxy } = useProxy(); @@ -956,7 +954,6 @@ export const AgentChatPageView: React.FC = ({ mcpServers={mcpServers} selectedMCPServerIds={selectedMCPServerIds} onMCPSelectionChange={onMCPSelectionChange} - onMCPAuthComplete={onMCPAuthComplete} workspace={workspace} workspaceAgent={workspaceAgent} sshCommand={sshCommand} diff --git a/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage.test.tsx b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage.test.tsx new file mode 100644 index 00000000000..595d1e3e6b6 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage.test.tsx @@ -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(, { + path: "/agents/settings/mcp-connections", + route: "/start", + extraRoutes: [ + { + path: "/start", + element: ( + + ), + }, + ], + }); + +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); + }); +}); diff --git a/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage.tsx b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage.tsx new file mode 100644 index 00000000000..1ad75d13a8e --- /dev/null +++ b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPage.tsx @@ -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(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 ( + 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; diff --git a/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPageView.stories.tsx b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPageView.stories.tsx new file mode 100644 index 00000000000..8b5ec2ed8d0 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPageView.stories.tsx @@ -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; + +export default meta; +type Story = StoryObj; + +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) => ( +
+ +
+ ), + ], +}; + +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, + }, +}; diff --git a/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPageView.tsx b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPageView.tsx new file mode 100644 index 00000000000..7ff83aa8f06 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsMCPConnectionsPage/AgentSettingsMCPConnectionsPageView.tsx @@ -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 = ({ + server, + onDisconnect, +}) => { + if (server.auth_type !== "oauth2") { + return ( + + No auth required + + ); + } + + return ( + + ); +}; + +type AddedConnectorRowProps = { + server: TypesGen.MCPServerConfig; + onDisconnect: (server: TypesGen.MCPServerConfig) => void; +}; + +const AddedConnectorRow: React.FC = ({ + server, + onDisconnect, +}) => { + return ( + + +
+ + + {server.display_name} + +
+
+ + {server.description || ( + No description + )} + + + + +
+ ); +}; + +type AvailableConnectorCardProps = { + server: TypesGen.MCPServerConfig; + connectingServerId: string | null; + onConnect: (server: TypesGen.MCPServerConfig) => void; +}; + +const AvailableConnectorCard: React.FC = ({ + server, + connectingServerId, + onConnect, +}) => { + const isConnecting = connectingServerId === server.id; + const connectLabel = isConnecting ? "Connecting" : "Connect"; + + return ( +
  • +
    + + + {server.display_name} + +
    +

    + {server.description || ( + No description + )} +

    + +
  • + ); +}; + +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 = ({ + organizationName, + servers, + enabledCount, + availableCount, + isLoading, + emptyMessage, + onShowAvailable, + onDisconnect, +}) => { + const showCounts = !isLoading && enabledCount > 0; + + let body: React.ReactNode = ; + if (isLoading) { + body = ( + + + + + + + + + + + + + + ); + } else if (servers.length > 0) { + body = servers.map((server) => ( + + )); + } + + return ( +
    + + {servers.length} of {enabledCount} + + ) + } + description="Servers you've connected, plus ones that need no sign-in. They appear in the chat's + menu." + action={ + showCounts && + availableCount > 0 && ( + + ) + } + /> + + + + Name + + Description + + + Actions + + + + {body} +
    +
    + ); +}; + +type AvailableConnectorsSectionProps = { + ref: React.Ref; + servers: readonly TypesGen.MCPServerConfig[]; + connectingServerId: string | null; + onConnect: (server: TypesGen.MCPServerConfig) => void; +}; + +const AvailableConnectorsSection: React.FC = ({ + ref, + servers, + connectingServerId, + onConnect, +}) => { + return ( +
    + {servers.length}} + description="Servers your organization offers. Connect to one to add it to chat." + /> +
      + {servers.map((server) => ( + + ))} +
    +
    + ); +}; + +/** + * 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(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 ( +
    + + {organization && ( + + )} + {Boolean(error) && ( + + } + /> + )} + {!failedFirstLoad && ( + + )} + {!isLoading && availableServers.length > 0 && ( + + )} + +
    + ); +}; diff --git a/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsSkillsPage/AgentSettingsSkillsPage.tsx b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsSkillsPage/AgentSettingsSkillsPage.tsx index d6fcec4c46a..5848db27f0c 100644 --- a/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsSkillsPage/AgentSettingsSkillsPage.tsx +++ b/site/src/pages/AgentsPage/AgentSettingsPage/AgentSettingsSkillsPage/AgentSettingsSkillsPage.tsx @@ -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) => diff --git a/site/src/pages/AgentsPage/AgentsPageLayout.stories.tsx b/site/src/pages/AgentsPage/AgentsPageLayout.stories.tsx index 02c5cd88d06..b89a25a8671 100644 --- a/site/src/pages/AgentsPage/AgentsPageLayout.stories.tsx +++ b/site/src/pages/AgentsPage/AgentsPageLayout.stories.tsx @@ -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); diff --git a/site/src/pages/AgentsPage/components/AgentChatInput.stories.tsx b/site/src/pages/AgentsPage/components/AgentChatInput.stories.tsx index 43a68181276..b67f9e3c618 100644 --- a/site/src/pages/AgentsPage/components/AgentChatInput.stories.tsx +++ b/site/src/pages/AgentsPage/components/AgentChatInput.stories.tsx @@ -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" }); }, }; diff --git a/site/src/pages/AgentsPage/components/AgentChatInput.test.tsx b/site/src/pages/AgentsPage/components/AgentChatInput.test.tsx index 3e7b6475160..68e7cd8ff21 100644 --- a/site/src/pages/AgentsPage/components/AgentChatInput.test.tsx +++ b/site/src/pages/AgentsPage/components/AgentChatInput.test.tsx @@ -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({children}); + return render({children}, { + wrapper: MemoryRouter, + }); }; beforeAll(() => { @@ -209,6 +219,7 @@ describe("AgentChatInput", () => { chatOrganizationId="org-1" /> , + { wrapper: MemoryRouter }, ); await user.click(screen.getByRole("textbox", { name: "Chat message" })); @@ -258,6 +269,7 @@ describe("AgentChatInput", () => { chatProjectId="project-1" /> , + { wrapper: MemoryRouter }, ); await user.click(screen.getByRole("textbox", { name: "Chat message" })); @@ -293,7 +305,7 @@ describe("AgentChatInput", () => { ); - 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( + , + ); + + 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( + , + ); + + 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( , ); - 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( { 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: ( + + ), + }, + { + path: "/agents/settings/mcp-connections", + element: , + }, + ], + { 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(); @@ -658,7 +774,7 @@ describe("AgentChatInput", () => { ); - 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 = { diff --git a/site/src/pages/AgentsPage/components/AgentChatInput.tsx b/site/src/pages/AgentsPage/components/AgentChatInput.tsx index 8e81c4d6a86..80cf9e6f429 100644 --- a/site/src/pages/AgentsPage/components/AgentChatInput.tsx +++ b/site/src/pages/AgentsPage/components/AgentChatInput.tsx @@ -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 = ({ 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 = ({ 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 ( @@ -348,32 +340,51 @@ const MCPGroupBadge: React.FC = ({ "cursor-pointer border-0 transition-colors hover:bg-surface-tertiary hover:text-content-primary", )} > - + {servers.length === 0 ? ( + + ) : ( + + )} {label} - - {servers.map((server) => ( - - ))} - + + {menu} + ); }; +type MCPServersMenuRowContentProps = { + activeCount: number; + isOpen?: boolean; +}; + +const MCPServersMenuRowContent: React.FC = ({ + activeCount, + isOpen, +}) => ( + <> + + MCP servers + {activeCount} on + + +); + 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 ( - - ); - } - - const isForceOn = badge.server.availability === "force_on"; return ( - - {badge.server.icon_url ? ( - - ) : ( - - )} - {badge.server.display_name} - {isForceOn ? ( - <> - - Always on - - ) : ( - onRemoveMcp && ( - onRemoveMcp(badge.server.id)} - ariaLabel={`Remove ${badge.server.display_name}`} - isDisabled={isDisabled} - /> - ) - )} - + ); }; +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 = ({ + onBack, + children, +}) => ( +
    + + + {children} +
    +); + export const AgentChatInput: React.FC = ({ onSend, placeholder = "Type a message...", @@ -557,7 +568,6 @@ export const AgentChatInput: React.FC = ({ mcpServers, selectedMCPServerIds, onMCPSelectionChange, - onMCPAuthComplete, workspaceSkills, workspace, workspaceAgent, @@ -602,33 +612,16 @@ export const AgentChatInput: React.FC = ({ 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(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(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(null); @@ -717,28 +710,6 @@ export const AgentChatInput: React.FC = ({ } }; - 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 = ({ ? 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 = ({ 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 = ( + + ); + + let plusMenuSubmenuPanel: React.ReactNode = null; + if (plusMenuView === "mcp") { + plusMenuSubmenuPanel = ( + closePlusMenuSubmenu("mcp")}> + {mcpMenuContent} + + ); + } else if (plusMenuView === "workspace") { + plusMenuSubmenuPanel = ( + closePlusMenuSubmenu("workspace")}> + { + onWorkspaceChange?.(id); + setPlusMenuOpen(false); + }} + /> + + ); + } const handlePlanModeToggle = () => { onPlanModeToggle(!planModeEnabled); @@ -1542,7 +1562,11 @@ export const AgentChatInput: React.FC = ({ 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 = ({ align="start" className="mobile-full-width-dropdown mobile-full-width-dropdown-bottom w-auto min-w-[200px] p-1" > - {plusMenuView === "workspace" ? ( -
    - - - { - onWorkspaceChange?.(id); - setPlusMenuOpen(false); - }} - /> -
    + {plusMenuView !== "main" ? ( + plusMenuSubmenuPanel ) : ( <> {onAttach && ( @@ -1627,6 +1632,7 @@ export const AgentChatInput: React.FC = ({ + ) : ( + + + - - ) : ( - <> - {server.auth_type === "oauth2" && ( - - )} - - handleMcpToggle(server.id, checked) - } - disabled={isDisabled || isForceOn} - aria-label={ - isForceOn - ? `${server.display_name} always on` - : `${isSelected ? "Disable" : "Enable"} ${server.display_name}` - } - /> - - )} - - ); - })} + + + + {mcpMenuContent} + + + )} )} @@ -1857,8 +1812,8 @@ export const AgentChatInput: React.FC = ({ 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 = ({ 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 = ({ }} /> )} - setMcpDisconnectTarget(null)} - /> ); }; diff --git a/site/src/pages/AgentsPage/components/AgentCreateForm.test.tsx b/site/src/pages/AgentsPage/components/AgentCreateForm.test.tsx index 70adb723637..1ebab0370a5 100644 --- a/site/src/pages/AgentsPage/components/AgentCreateForm.test.tsx +++ b/site/src/pages/AgentsPage/components/AgentCreateForm.test.tsx @@ -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( - + + + , ); diff --git a/site/src/pages/AgentsPage/components/AgentCreateForm.tsx b/site/src/pages/AgentsPage/components/AgentCreateForm.tsx index 0868eca91c2..beab212303f 100644 --- a/site/src/pages/AgentsPage/components/AgentCreateForm.tsx +++ b/site/src/pages/AgentsPage/components/AgentCreateForm.tsx @@ -1102,7 +1102,6 @@ const AgentCreateFormContent: React.FC = ({ saveMCPSelection(organizationId, ids); } }} - onMCPAuthComplete={() => void mcpServersQuery.refetch()} workspaceOptions={filteredWorkspaces} selectedWorkspaceId={effectiveWorkspaceId} // Do not persist a workspace until its organization is authorized. diff --git a/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx b/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx index f597d790701..edf39db7663 100644 --- a/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx @@ -148,7 +148,6 @@ const StoryChatPageInput: React.FC<{ mcpServers={[]} selectedMCPServerIds={[]} onMCPSelectionChange={fn()} - onMCPAuthComplete={fn()} isWorkspaceLoading={false} /> @@ -493,7 +492,6 @@ const CompactionChatPageInput: React.FC = () => { mcpServers={[]} selectedMCPServerIds={[]} onMCPSelectionChange={fn()} - onMCPAuthComplete={fn()} isWorkspaceLoading={false} /> diff --git a/site/src/pages/AgentsPage/components/ChatPageContent.test.tsx b/site/src/pages/AgentsPage/components/ChatPageContent.test.tsx index b17c742868d..e8430015c6b 100644 --- a/site/src/pages/AgentsPage/components/ChatPageContent.test.tsx +++ b/site/src/pages/AgentsPage/components/ChatPageContent.test.tsx @@ -55,7 +55,6 @@ const renderChatPageInput = ( mcpServers={[]} selectedMCPServerIds={[]} onMCPSelectionChange={vi.fn()} - onMCPAuthComplete={vi.fn()} isWorkspaceLoading={false} {...overrides} />, diff --git a/site/src/pages/AgentsPage/components/ChatPageContent.tsx b/site/src/pages/AgentsPage/components/ChatPageContent.tsx index d3df48f489d..2ae47c2abed 100644 --- a/site/src/pages/AgentsPage/components/ChatPageContent.tsx +++ b/site/src/pages/AgentsPage/components/ChatPageContent.tsx @@ -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 = ({ mcpServers, selectedMCPServerIds, onMCPSelectionChange, - onMCPAuthComplete, onWorkspaceChange, isWorkspaceLoading, workspace, @@ -833,7 +831,6 @@ export const ChatPageInput: React.FC = ({ mcpServers={mcpServers} selectedMCPServerIds={selectedMCPServerIds} onMCPSelectionChange={onMCPSelectionChange} - onMCPAuthComplete={onMCPAuthComplete} workspaceSkills={workspaceSkills} workspace={workspace} workspaceAgent={workspaceAgent} diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/settings/SettingsPanel.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/settings/SettingsPanel.tsx index 21c326bc770..47f74150913 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/settings/SettingsPanel.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/settings/SettingsPanel.tsx @@ -5,6 +5,7 @@ import { BotIcon, KeyIcon, PanelLeftCloseIcon, + PlugIcon, ReceiptTextIcon, Settings2Icon, ShrinkIcon, @@ -96,6 +97,13 @@ export const SettingsPanel: React.FC = ({ to="/agents/settings/skills" state={location.state} /> + void; +}; + +const MCPServerMenuRow: React.FC = ({ + 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 ( +
    + {server.icon_url ? ( + + ) : ( + + )} + + {server.display_name} + + {isForceOn && ( + + )} + {isDisconnected ? ( + <> + {isForceOn && Always on} + + + + + Not connected + + + ) : ( + onToggle?.(server.id, checked)} + disabled={isDisabled || isForceOn || !onToggle} + aria-label={switchLabel} + /> + )} +
    + ); +}; + +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 = ({ + servers, + selectedServerIds, + isDisabled, + onToggle, + onManageConnections, +}) => { + const rows = getMCPMenuServers(servers, selectedServerIds); + const disconnectedCount = countMCPServersNeedingSignIn(servers); + + return ( +
    + {rows.length === 0 ? ( +

    + No servers connected yet +

    + ) : ( + rows.map((row) => ( + + )) + )} + +
    + + {disconnectedCount === 0 + ? "All connected" + : `${disconnectedCount} not connected`} + + {onManageConnections && ( + + )} +
    +
    + ); +}; diff --git a/site/src/pages/AgentsPage/components/mcpMenuServers.test.ts b/site/src/pages/AgentsPage/components/mcpMenuServers.test.ts new file mode 100644 index 00000000000..a983d821365 --- /dev/null +++ b/site/src/pages/AgentsPage/components/mcpMenuServers.test.ts @@ -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); + }); +}); diff --git a/site/src/pages/AgentsPage/components/mcpMenuServers.ts b/site/src/pages/AgentsPage/components/mcpMenuServers.ts new file mode 100644 index 00000000000..c895350c30c --- /dev/null +++ b/site/src/pages/AgentsPage/components/mcpMenuServers.ts @@ -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; diff --git a/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.test.ts b/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.test.ts new file mode 100644 index 00000000000..f40021351ee --- /dev/null +++ b/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.test.ts @@ -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); + }); +}); diff --git a/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.ts b/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.ts index c3d22620649..cbd98601720 100644 --- a/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.ts +++ b/site/src/pages/AgentsPage/hooks/useMCPOAuthFlow.ts @@ -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 }; diff --git a/site/src/router.tsx b/site/src/router.tsx index 9860827ff92..1099222dd5a 100644 --- a/site/src/router.tsx +++ b/site/src/router.tsx @@ -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={} /> } /> + } + /> }