From 0199c963e2b1254a3637059beea6a01423cffa05 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:35:49 -0600 Subject: [PATCH] feat(apps): ship the redesigned sign-in step for a pasted MCP server (#21469) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Apps lets an operator connect a remote MCP server by pasting its address ("Connect your own MCP server") > - Step 2 of that flow put every sign-in choice in an "Advanced authentication" box with wrapped pill buttons and a hint paragraph > - The box hid the choice behind a vague label, and its shape did not match the access line ("Connects for everyone… Change") right below it > - The owner approved a redesign: a stated sign-in default with a Change link, and five options with their fields directly below each option > - This pull request wires that redesign into the real screen, removes the old step, and updates copy that named the removed box > - The benefit is a screen that reads as two stated answers and one action, with the same default path (paste the address, press Check link) ## Linked Issues or Issue Description No public issue exists. Enhancement: **What existing behavior does this improve?** The sign-in section of the "Connect your own MCP server" step in Apps. **Subsystem affected** UI: Apps connection setup (`ui/src/features/connections`). Small copy changes in the server OAuth client registration message and docs. **Current behavior** Step 2 shows an "Advanced authentication" collapsible with five wrapped pill buttons and a hint paragraph below them. The fields for the chosen mode appear further down. Guidance banners tell the operator to look "under Advanced authentication". The page also shows the "Unverified server" badge twice (header and body). The stepper reads "Pick app · Add your key", even when the server needs no key. **Proposed behavior** Step 2 states the sign-in choice in one line ("Paperclip asks the server how to sign in.") with a Change link. Change shows five radio cards: Let Paperclip check, Key or token, Browser sign-in, Custom headers, No sign-in needed. The fields for the selected option are directly below it. Done collapses the list to a one-line summary (for example "Signs in with 1 custom header."). The list stays open while the chosen option still needs a value. Client ID and secret are behind "Use your own client ID" unless they have values or the server asked for them. The stepper reads "Pick app · Connect". **Reason and benefit** The choice is visible as a stated default in the same shape as the access line. Each option keeps its fields next to it. No copy points at a box that does not exist. **Breaking changes** None. The five auth modes and their request payloads do not change. **Additional context** Related open PRs change server behavior for the same flow. They are not duplicates. Refs #15192, Refs #15450. ## What Changed - `ui/src/features/connections/GenericMcpConnectStep.tsx`: new step component (same props as the old `LinkConnectStep`). It uses stable field ids `generic-mcp-key`, `generic-mcp-client-id`, `generic-mcp-client-secret` and a `data-testid` on the sign-in Change/Done link. - `ui/src/features/connections/ConnectionSetupFlow.tsx`: render `GenericMcpConnectStep`; delete `LinkConnectStep`, `GENERIC_AUTH_MODE_OPTIONS`, `SegmentedOption` and unused imports; change the pasted-link stepper label from "Add your key" to "Connect" (`STEP_LABELS` is used only by the pasted-link flow; curated apps keep their own `["Add your key"]`). - `ui/src/pages/apps/generic-mcp-connect.ts`: `oauth_challenge` and `oauth_manual_client_required` guidance now say "below" instead of "under Advanced authentication". - `server/src/services/tool-access/oauth/client-registration.ts`: the manual-client message no longer names the removed box. - `doc/connections/GENERIC-REMOTE-MCP.md`: describe the sign-in line, Change, and the five options. - Comments in `packages/shared` and `server/src/services/tool-access.ts` reworded. `tests/runner-e2e/source-sdk-public-inputs.json` regenerated for the two shared files (blob hashes only). - `ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx`: 14 stories for the shipped component; annotation is now `current` / `production`. - Tests: `AppsConnect.test.tsx` generic MCP block uses the sign-in toggle and radio options; new tests for the collapsed summary, the open-while-empty-key rule, and a single "Unverified server" label. New `GenericMcpConnectStep.test.ts` unit-tests `genericMcpAuthSummary`. Before: "Advanced authentication" box with pill buttons and a hint; fields below the pills; two "Unverified server" badges; stepper "Pick app · Add your key". After: one sign-in line with Change; five radio cards with fields under the selected card; one "Unverified server" badge in the header; stepper "Pick app · Connect". Storybook: `byo-mcp-sign-in--choosing`, `byo-mcp-sign-in--server-asked-for-key`. ## Verification - `cd ui && pnpm exec vitest run src/pages/apps/AppsConnect.test.tsx src/pages/apps/generic-mcp-connect.test.ts src/features/connections/GenericMcpConnectStep.test.ts src/features/connections/ConnectionSetupFlow.architecture.test.ts src/features/connections/ConnectionSetupFlow.oauth.test.ts`: 5 files, 300 tests pass. - `cd ui && node ../scripts/run-tsc.mjs -b`: pass. - `pnpm -s typecheck` in `packages/shared` and `server`: pass. - `pnpm check:token-gates`: all gates clean. - `node scripts/storybook-catalog.mjs`: pass (generated indexes not committed). - `pnpm verify`: exit 2 (broader verification required, because `doc/connections/GENERIC-REMOTE-MCP.md` is a global CI input). Required CI supplies that coverage. The focused files above were rerun on the final revision after the rebase. - Headless Playwright against the Storybook dev server: the Default, Choosing and Server-asked-for-key stories render the new step, the new guidance copy, and the "Pick app · Connect" stepper. ## Risks - Low risk. UI change on one screen; request payloads (`genericConnectPayload`) do not change. - Tests that click the first collapsed "Change" button now skip the sign-in toggle, because the access line also has a "Change" button. - The server message for `oauth_manual_client_required` changes text. No code matches on the text; the client uses the error code. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, headless Playwright). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 --- doc/connections/GENERIC-REMOTE-MCP.md | 22 +- packages/shared/src/types/tool-access.ts | 2 +- packages/shared/src/validators/tool-access.ts | 2 +- server/src/services/tool-access.ts | 2 +- .../tool-access/oauth/client-registration.ts | 2 +- .../runner-e2e/source-sdk-public-inputs.json | 4 +- .../connections/ConnectionSetupFlow.tsx | 324 +------------- .../connections/GenericMcpConnectStep.test.ts | 44 ++ .../connections/GenericMcpConnectStep.tsx | 405 ++++++++++++++++++ ui/src/pages/apps/AppsConnect.test.tsx | 110 ++++- ui/src/pages/apps/generic-mcp-connect.test.ts | 4 +- ui/src/pages/apps/generic-mcp-connect.ts | 4 +- .../byo-mcp-sign-in.stories.tsx | 276 ++++++++++++ 13 files changed, 844 insertions(+), 357 deletions(-) create mode 100644 ui/src/features/connections/GenericMcpConnectStep.test.ts create mode 100644 ui/src/features/connections/GenericMcpConnectStep.tsx create mode 100644 ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx diff --git a/doc/connections/GENERIC-REMOTE-MCP.md b/doc/connections/GENERIC-REMOTE-MCP.md index 9cc4d5cd12c..026eab63090 100644 --- a/doc/connections/GENERIC-REMOTE-MCP.md +++ b/doc/connections/GENERIC-REMOTE-MCP.md @@ -41,7 +41,7 @@ endpoint and branches: | --- | --- | | Nothing needed | Discovered actions, straight to review. | | Needs authorization, and publishes discoverable OAuth metadata | **Sign in to continue** — a browser sign-in at the provider. | -| Needs authorization, but no discoverable sign-in | A prompt to add the key or headers its docs list, under **Advanced authentication**. | +| Needs authorization, but no discoverable sign-in | A prompt to add the key or headers its docs list, with the sign-in options open below it. | | Needs a client you registered yourself | A prompt for a client ID and secret. The draft connection is kept — you don't start over. | | Not a valid address / private network / unreachable | The specific problem and which field to change. | @@ -87,15 +87,23 @@ connection. Signing in alone does not enable that app setting. Paperclip shows this as a setup error and keeps the connection available for retry. See [Slack's MCP app requirements](https://docs.slack.dev/ai/slack-mcp-server/#app-identity). -### Advanced authentication +### Choosing how the server signs in -Collapsed by default. Open it when the server's docs are specific: +The connect screen states the sign-in choice in one line, **Paperclip asks the +server how to sign in.**, with a **Change** link, the same shape as the access +line below it. **Change** lists five options, each with its fields directly +beneath it when selected: -- **No sign-in needed** — the server is open to anyone with the address. +- **Let Paperclip check** — the default; Paperclip probes and walks you through it. - **Key or token** — sent as an `Authorization` header. +- **Browser sign-in** — you sign in at the provider. **Use your own client ID** + reveals a client ID and secret, for providers that require you to register + Paperclip first. - **Custom headers** — for servers that name their own headers. -- **Browser sign-in** — optionally with a client ID and secret you registered - yourself, for providers that require preregistration. +- **No sign-in needed** — the server is open to anyone with the address. + +**Done** collapses the list back to a one-line summary of the choice. It stays +open while the chosen option still needs a value. Every value you enter becomes a Paperclip secret. Values are write-only: they never appear in stored config JSON, logs, activity details, API responses after @@ -130,7 +138,7 @@ Recorded here for security review and diagnostics. In preference order: advertises a `registration_endpoint`. Paperclip registers a public client (`token_endpoint_auth_method: none`, `application_type: web`, PKCE S256). 4. **Manual preregistered client.** The client ID and secret you paste under - **Advanced authentication → Browser sign-in**. + **Change → Browser sign-in → Use your own client ID**. A generic connection may register (tiers 2 and 3) **only after** validated protected-resource and authorization-server discovery actually produced a diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 9a96b4ab4fe..4c05d176f9b 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1209,7 +1209,7 @@ export interface ToolOAuthHandoff { * What an unknown remote MCP endpoint told Paperclip it needs, so the wizard can * branch without re-probing. `manualClientRequired` means discovery succeeded but * the authorization server supports neither CIMD nor DCR, so the operator has to - * supply a preregistered client under Advanced authentication. + * supply a preregistered client in the sign-in options on the connect screen. */ export interface ConnectToolAppAuthChallenge { kind: "oauth"; diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts index f55163c22eb..cd28549a930 100644 --- a/packages/shared/src/validators/tool-access.ts +++ b/packages/shared/src/validators/tool-access.ts @@ -352,7 +352,7 @@ export type DisableToolStdioCommandTemplate = z.infer, number> = { gallery: 0, key: 1, @@ -2794,7 +2790,7 @@ function StandardConnectionSetupFlow({ )} {step === "key" && !entry && linkUrl && !zapierSource && ( - void; - authMode: GenericMcpAuthMode; - onAuthModeChange: (next: GenericMcpAuthMode) => void; - headers: CustomHeaderRow[]; - onHeadersChange: (next: CustomHeaderRow[]) => void; - oauthClientId: string; - onOAuthClientIdChange: (next: string) => void; - oauthClientSecret: string; - onOAuthClientSecretChange: (next: string) => void; - advancedOpen: boolean; - onAdvancedOpenChange: (next: boolean) => void; - guidance: GenericConnectGuidance | null; - /** A curated app whose endpoint matches, offered as a convenience only. */ - matchedEntry?: AppDefinition | null; - onUseMatchedEntry?: () => void; - submitting: boolean; - /** The stated default and its Advanced disclosure (PAP-659 C0). */ - defaults?: ReactNode; - onBack: () => void; - onConnect: () => void; -}) { - const host = endpointHost(link); - const headerError = authMode === "custom_headers" ? customHeaderError(headers) : null; - const draft: GenericConnectDraft = { - link, - name, - authMode, - needsKey, - keyValue, - headers, - oauthClientId, - oauthClientSecret, - }; - const canSubmit = canSubmitGenericConnect(draft); - // PAP-659 bucket H: the address alone is the whole default path. `needsKey` is - // now set by the server's probe after a credential challenge, never guessed at - // up front, so the field appears exactly when it is known to be required. - const showKeyField = (authMode === "auto" && needsKey) || authMode === "bearer"; - const displayedLink = matchedEntry?.slug === "zapier" ? redactUrlSecrets(link) : link; - - const updateHeader = (id: string, patch: Partial) => { - onHeadersChange(headers.map((row) => (row.id === id ? { ...row, ...patch } : row))); - }; - - return ( -
-
-

{displayedLink}

- -
- - {matchedEntry && onUseMatchedEntry ? ( -
-
- - Paperclip has a guided setup for {matchedEntry.name}. -
- -
- ) : null} - - {guidance ? ( -
- - {guidance.body} - -
- ) : null} - -
- {showKeyField ? ( -
-
- - onKeyChange(e.target.value)} - placeholder="••••••••••••••••" - className="mt-2 h-11 font-mono" - /> -

- Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions. -

-
-
- ) : null} - - - - Advanced authentication - - - -

- Only needed when the server's docs are specific about how to authenticate. -

-
- {GENERIC_AUTH_MODE_OPTIONS.map((option) => ( - onAuthModeChange(option.mode)} - /> - ))} -
-

- {GENERIC_AUTH_MODE_OPTIONS.find((option) => option.mode === authMode)?.hint} -

- - {authMode === "custom_headers" ? ( -
- {headers.map((row) => ( -
- updateHeader(row.id, { name: e.target.value })} - placeholder="Header name" - aria-label="Header name" - className="h-10 font-mono" - /> - updateHeader(row.id, { value: e.target.value })} - placeholder="Value" - aria-label={row.name.trim() ? `Value for ${row.name.trim()}` : "Header value"} - className="h-10 font-mono" - /> - -
- ))} - - {headerError ?

{headerError}

: null} -
- ) : null} - - {authMode === "oauth" ? ( -
-

- Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the - server's docs tell you to register Paperclip yourself first. -

-
- - onOAuthClientIdChange(e.target.value)} - autoComplete="off" - placeholder="Optional" - className="mt-2 h-11 font-mono" - /> -
-
- - onOAuthClientSecretChange(e.target.value)} - placeholder="Optional" - className="mt-2 h-11 font-mono" - /> -
-
- ) : null} -
-
-
- - {defaults} - -
- - -
-
- ); -} - -/** - * What the operator is choosing is how the *server* authenticates, in its own - * terms. Paperclip decides internally whether that means a preconfigured client, - * a client ID metadata document, dynamic registration, or the credentials pasted - * below — none of which belongs on this screen. - */ -const GENERIC_AUTH_MODE_OPTIONS: Array<{ mode: GenericMcpAuthMode; label: string; hint: string }> = [ - { - mode: "auto", - label: "Let Paperclip check", - hint: "Paperclip asks the server what it needs and walks you through it. Start here.", - }, - { - mode: "none", - label: "No sign-in needed", - hint: "The server is open to anyone with the address.", - }, - { - mode: "bearer", - label: "Key or token", - hint: "Paperclip sends your key as an Authorization header.", - }, - { - mode: "custom_headers", - label: "Custom headers", - hint: "For servers that name their own headers. Values are stored as Paperclip secrets and can\u2019t be read back.", - }, - { - mode: "oauth", - label: "Browser sign-in", - hint: "You\u2019ll sign in at the provider. Add a client ID and secret only if the provider requires you to register Paperclip first.", - }, -]; - -function SegmentedOption({ - label, - selected, - onClick, -}: { - label: string; - selected: boolean; - onClick: () => void; -}) { - return ( - - ); -} - function KeyStep({ settingsValid = true, entry, diff --git a/ui/src/features/connections/GenericMcpConnectStep.test.ts b/ui/src/features/connections/GenericMcpConnectStep.test.ts new file mode 100644 index 00000000000..07d97007775 --- /dev/null +++ b/ui/src/features/connections/GenericMcpConnectStep.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { newCustomHeaderRow, type CustomHeaderRow } from "@/pages/apps/generic-mcp-connect"; +import { genericMcpAuthSummary } from "./GenericMcpConnectStep"; + +function header(name: string, value: string): CustomHeaderRow { + return { ...newCustomHeaderRow(), name, value }; +} + +describe("genericMcpAuthSummary", () => { + const base = { headers: [newCustomHeaderRow()], oauthClientId: "" }; + + it("states each sign-in choice in plain words", () => { + expect(genericMcpAuthSummary({ ...base, authMode: "auto" })).toBe("Paperclip asks the server how to sign in."); + expect(genericMcpAuthSummary({ ...base, authMode: "none" })).toBe( + "No sign-in. The server is open to anyone with the address.", + ); + expect(genericMcpAuthSummary({ ...base, authMode: "bearer" })).toBe("Signs in with a key or token."); + expect(genericMcpAuthSummary({ ...base, authMode: "oauth" })).toBe("You’ll sign in at the provider."); + }); + + it("counts only complete custom headers", () => { + expect(genericMcpAuthSummary({ ...base, authMode: "custom_headers" })).toBe("Signs in with custom headers."); + expect( + genericMcpAuthSummary({ + ...base, + authMode: "custom_headers", + headers: [header("X-Api-Key", "a"), header("X-Workspace", " ")], + }), + ).toBe("Signs in with 1 custom header."); + expect( + genericMcpAuthSummary({ + ...base, + authMode: "custom_headers", + headers: [header("X-Api-Key", "a"), header("X-Workspace", "b")], + }), + ).toBe("Signs in with 2 custom headers."); + }); + + it("mentions an operator-supplied client ID", () => { + expect(genericMcpAuthSummary({ ...base, authMode: "oauth", oauthClientId: " client " })).toBe( + "You’ll sign in at the provider, using your own client ID.", + ); + }); +}); diff --git a/ui/src/features/connections/GenericMcpConnectStep.tsx b/ui/src/features/connections/GenericMcpConnectStep.tsx new file mode 100644 index 00000000000..40e4b14759a --- /dev/null +++ b/ui/src/features/connections/GenericMcpConnectStep.tsx @@ -0,0 +1,405 @@ +import { useState, type KeyboardEvent, type ReactNode } from "react"; +import { Loader2, Plus, X } from "lucide-react"; +import type { AppDefinition } from "@paperclipai/shared"; +import { InlineBanner } from "@/components/InlineBanner"; +import { Button } from "@/components/ui/button"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { Input } from "@/components/ui/input"; +import { RadioCard } from "@/components/ui/radio-card"; +import { redactUrlSecrets } from "@/lib/redact-url-secrets"; +import { AppLogo } from "@/pages/apps/AppLogo"; +import { + canSubmitGenericConnect, + customHeaderError, + newCustomHeaderRow, + type CustomHeaderRow, + type GenericConnectGuidance, + type GenericMcpAuthMode, +} from "@/pages/apps/generic-mcp-connect"; + +/** + * How the server authenticates, in its own terms. Paperclip decides internally + * which protocol satisfies the choice; none of that belongs on this screen. + * Ordered by how often an operator needs each one. + */ +const AUTH_OPTIONS: Array<{ mode: GenericMcpAuthMode; title: string; description: string }> = [ + { + mode: "auto", + title: "Let Paperclip check", + description: "Paperclip asks the server what it needs and walks you through it.", + }, + { + mode: "bearer", + title: "Key or token", + description: "Paperclip sends your key as an Authorization header.", + }, + { + mode: "oauth", + title: "Browser sign-in", + description: "You’ll sign in at the provider.", + }, + { + mode: "custom_headers", + title: "Custom headers", + description: "For servers that name their own headers.", + }, + { + mode: "none", + title: "No sign-in needed", + description: "The server is open to anyone with the address.", + }, +]; + +/** The resolved sign-in choice, stated in one line beside its Change control. */ +export function genericMcpAuthSummary(input: { + authMode: GenericMcpAuthMode; + headers: CustomHeaderRow[]; + oauthClientId: string; +}): string { + switch (input.authMode) { + case "none": + return "No sign-in. The server is open to anyone with the address."; + case "bearer": + return "Signs in with a key or token."; + case "custom_headers": { + const count = input.headers.filter((row) => row.name.trim() && row.value.trim()).length; + return count === 0 + ? "Signs in with custom headers." + : `Signs in with ${count} custom ${count === 1 ? "header" : "headers"}.`; + } + case "oauth": + return input.oauthClientId.trim() + ? "You’ll sign in at the provider, using your own client ID." + : "You’ll sign in at the provider."; + default: + return "Paperclip asks the server how to sign in."; + } +} + +/** + * The connect screen for an unknown remote MCP server. + * + * The address alone is the whole default path. How the server signs in is a + * stated default with a Change control, in the same shape as the access line + * below it, so the screen reads as two resolved answers and one action. Each + * sign-in option keeps its own fields directly beneath it. + * + * The operator picks how the server signs in, never which protocol Paperclip + * uses to satisfy it, so no protocol jargon appears here. The header keeps the + * endpoint host and its "Unverified server" label visible the whole way + * through, so the operator can always see whose server agents will call. + */ +export function GenericMcpConnectStep({ + link, + name, + needsKey, + keyValue, + onKeyChange, + authMode, + onAuthModeChange, + headers, + onHeadersChange, + oauthClientId, + onOAuthClientIdChange, + oauthClientSecret, + onOAuthClientSecretChange, + advancedOpen, + onAdvancedOpenChange, + guidance, + matchedEntry, + onUseMatchedEntry, + submitting, + defaults, + onBack, + onConnect, +}: { + link: string; + name: string; + /** Set by the server's probe after a credential challenge, never guessed. */ + needsKey: boolean; + keyValue: string; + onKeyChange: (next: string) => void; + authMode: GenericMcpAuthMode; + onAuthModeChange: (next: GenericMcpAuthMode) => void; + headers: CustomHeaderRow[]; + onHeadersChange: (next: CustomHeaderRow[]) => void; + oauthClientId: string; + onOAuthClientIdChange: (next: string) => void; + oauthClientSecret: string; + onOAuthClientSecretChange: (next: string) => void; + advancedOpen: boolean; + onAdvancedOpenChange: (next: boolean) => void; + guidance: GenericConnectGuidance | null; + /** A curated app whose endpoint matches, offered as a convenience only. */ + matchedEntry?: AppDefinition | null; + onUseMatchedEntry?: () => void; + submitting: boolean; + /** The stated access default and its Change disclosure. */ + defaults?: ReactNode; + onBack: () => void; + onConnect: () => void; +}) { + const [clientFieldsOpen, setClientFieldsOpen] = useState(false); + const headerError = authMode === "custom_headers" ? customHeaderError(headers) : null; + const canSubmit = canSubmitGenericConnect({ + link, + name, + authMode, + needsKey, + keyValue, + headers, + oauthClientId, + oauthClientSecret, + }); + const displayedLink = matchedEntry?.slug === "zapier" ? redactUrlSecrets(link) : link; + const probedKey = authMode === "auto" && needsKey; + // Stay open while the chosen option still needs something typed into it, so + // a disabled primary action always has its reason on screen. + const choiceNeedsInput = (authMode === "bearer" || authMode === "custom_headers") && !canSubmit; + const expanded = advancedOpen || choiceNeedsInput; + const showClientFields = clientFieldsOpen + || oauthClientId.trim().length > 0 + || oauthClientSecret.trim().length > 0 + || guidance?.focus === "credentials"; + + const updateHeader = (id: string, patch: Partial) => { + onHeadersChange(headers.map((row) => (row.id === id ? { ...row, ...patch } : row))); + }; + + const moveSelection = (event: KeyboardEvent) => { + // Arrow keys inside an option's own fields belong to that field. + if ((event.target as HTMLElement).getAttribute("role") !== "radio") return; + const step = event.key === "ArrowDown" || event.key === "ArrowRight" + ? 1 + : event.key === "ArrowUp" || event.key === "ArrowLeft" + ? -1 + : 0; + if (step === 0) return; + event.preventDefault(); + const index = AUTH_OPTIONS.findIndex((option) => option.mode === authMode); + const next = (index + step + AUTH_OPTIONS.length) % AUTH_OPTIONS.length; + onAuthModeChange(AUTH_OPTIONS[next]!.mode); + event.currentTarget.querySelectorAll('[role="radio"]')[next]?.focus(); + }; + + const keyField = (label: string | null) => ( +
+ {label ? ( + + ) : null} + onKeyChange(event.target.value)} + placeholder="Paste the key or token" + className={label ? "mt-2 h-11 font-mono" : "h-11 font-mono"} + /> +

+ Grant this key access to what your agents need. Paperclip can’t increase its permissions. +

+
+ ); + + const optionFields = (mode: GenericMcpAuthMode): ReactNode => { + if (mode === "bearer") return keyField(null); + if (mode === "custom_headers") { + return ( +
+ {headers.map((row) => ( +
+ updateHeader(row.id, { name: event.target.value })} + placeholder="Header name" + aria-label="Header name" + autoComplete="off" + spellCheck={false} + className="h-10 font-mono" + /> + updateHeader(row.id, { value: event.target.value })} + placeholder="Value" + aria-label={row.name.trim() ? `Value for ${row.name.trim()}` : "Header value"} + className="h-10 font-mono" + /> + +
+ ))} +
+ +

Values are stored as secrets and can’t be read back.

+
+ {headerError ?

{headerError}

: null} +
+ ); + } + if (mode === "oauth") { + if (!showClientFields) { + return ( + + ); + } + return ( +
+

+ Paperclip sets sign-in up on its own whenever the server allows it. Fill these in only when the + server’s docs tell you to register Paperclip yourself first. +

+
+
+ + onOAuthClientIdChange(event.target.value)} + autoComplete="off" + spellCheck={false} + placeholder="Optional" + className="mt-2 h-10 font-mono" + /> +
+
+ + onOAuthClientSecretChange(event.target.value)} + placeholder="Optional" + className="mt-2 h-10 font-mono" + /> +
+
+
+ ); + } + return null; + }; + + return ( +
+
+

{displayedLink}

+ + {matchedEntry && onUseMatchedEntry ? ( +
+
+ + Paperclip has a guided setup for {matchedEntry.name}. +
+ +
+ ) : null} + + {guidance ? ( + + {guidance.body} + + ) : null} + + {probedKey ? keyField("App key") : null} +
+ + +
+

+ {expanded ? "How does this server sign in?" : genericMcpAuthSummary({ authMode, headers, oauthClientId })} +

+ + + +
+ +
+ {AUTH_OPTIONS.map((option) => { + const selected = option.mode === authMode; + const fields = selected ? optionFields(option.mode) : null; + return ( +
+ onAuthModeChange(option.mode)} + /> + {fields ?
{fields}
: null} +
+ ); + })} +
+
+
+ + {defaults} + +
+ + +
+
+ ); +} diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index 4bc6b28c023..9dde59aaea1 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -202,7 +202,10 @@ function stepLabelsOnScreen(): string[] { */ async function openAccessAdvanced() { const change = Array.from(document.body.querySelectorAll("button")).find( - (b) => b.textContent?.trim() === "Change" && b.getAttribute("aria-expanded") === "false", + (b) => b.textContent?.trim() === "Change" + && b.getAttribute("aria-expanded") === "false" + // A pasted MCP server also states its sign-in with a Change link. + && b.dataset.testid !== "generic-mcp-sign-in-toggle", ); if (!change) return; await act(async () => { @@ -4516,9 +4519,22 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { return root; } - async function openAdvanced() { + // The sign-in line's own Change link. The access line below it has a + // Change control too, so select this one by its test hook. + function signInToggle(): HTMLButtonElement | null { + return container.querySelector('[data-testid="generic-mcp-sign-in-toggle"]'); + } + + async function openSignInOptions() { await act(async () => { - buttonContaining("Advanced authentication")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + signInToggle()?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + await flushReact(); + } + + async function chooseSignIn(title: string) { + await act(async () => { + radioContaining(title)?.dispatchEvent(new MouseEvent("click", { bubbles: true })); }); await flushReact(); } @@ -4683,7 +4699,7 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { expect(container.querySelector("#generic-mcp-name")).toBeNull(); }); - it("opens advanced authentication when the server wants a credential we can't discover", async () => { + it("opens the sign-in options when the server wants a credential we can't discover", async () => { connectAppMock.mockRejectedValue(apiError(502, "oauth_challenge", "This app needs you to sign in.")); await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); @@ -4694,8 +4710,11 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { await flushReact(); expect(container.textContent).toContain("This server wants a credential"); - // The advanced section is now open, so the fields to fix it are on screen. + // The sign-in options are now open, with the probed key field above them, + // so the fields to fix it are on screen. expect(container.textContent).toContain("Custom headers"); + expect(container.querySelector("#generic-mcp-key")).toBeTruthy(); + expect(signInToggle()?.textContent).toBe("Done"); expect(container.textContent).not.toContain("coming soon"); }); @@ -4738,7 +4757,7 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { await gotoLinkFrame(container, "https://mcp.example.test/mcp"); const stepsBeforeHandoff = stepLabelsOnScreen(); - expect(stepsBeforeHandoff).toEqual(["Pick app", "Add your key"]); + expect(stepsBeforeHandoff).toEqual(["Pick app", "Connect"]); await act(async () => { buttonByText("Check link")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); @@ -4887,11 +4906,8 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { it("submits custom headers as secret-backed credential values", async () => { await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); - await openAdvanced(); - await act(async () => { - buttonByText("Custom headers")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flushReact(); + await openSignInOptions(); + await chooseSignIn("Custom headers"); const nameInput = Array.from(container.querySelectorAll("input")) .find((input) => input.getAttribute("aria-label") === "Header name")!; @@ -4919,11 +4935,8 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { it("blocks a header Paperclip refuses to send before making a request", async () => { await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); - await openAdvanced(); - await act(async () => { - buttonByText("Custom headers")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - await flushReact(); + await openSignInOptions(); + await chooseSignIn("Custom headers"); const nameInput = Array.from(container.querySelectorAll("input")) .find((input) => input.getAttribute("aria-label") === "Header name")!; @@ -4942,9 +4955,12 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { it("sends preregistered client credentials when the operator supplies them", async () => { await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); - await openAdvanced(); + await openSignInOptions(); + await chooseSignIn("Browser sign-in"); + // The client fields stay behind their own link until the operator asks. + expect(container.querySelector("#generic-mcp-client-id")).toBeNull(); await act(async () => { - buttonByText("Browser sign-in")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + buttonByText("Use your own client ID")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); }); await flushReact(); @@ -4967,10 +4983,66 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { }); }); + it("states the chosen sign-in in one line once the operator presses Done", async () => { + await render(); + await gotoLinkFrame(container, "https://mcp.example.test/mcp"); + + expect(container.textContent).toContain("Paperclip asks the server how to sign in."); + expect(signInToggle()?.textContent).toBe("Change"); + // Collapsed: the options are not on screen. + expect(radioContaining("Custom headers")).toBeUndefined(); + + await openSignInOptions(); + await chooseSignIn("Custom headers"); + const nameInput = Array.from(container.querySelectorAll("input")) + .find((input) => input.getAttribute("aria-label") === "Header name")!; + await act(async () => setInputValue(nameInput, "X-Api-Key")); + await flushReact(); + const valueInput = Array.from(container.querySelectorAll("input")) + .find((input) => input.getAttribute("aria-label") === "Value for X-Api-Key")!; + await act(async () => setInputValue(valueInput, "phx_secret")); + await flushReact(); + + expect(signInToggle()?.textContent).toBe("Done"); + await openSignInOptions(); + + expect(container.textContent).toContain("Signs in with 1 custom header."); + expect(signInToggle()?.textContent).toBe("Change"); + expect(radioContaining("Custom headers")).toBeUndefined(); + }); + + it("keeps the sign-in options open while a chosen key is still empty", async () => { + await render(); + await gotoLinkFrame(container, "https://mcp.example.test/mcp"); + await openSignInOptions(); + await chooseSignIn("Key or token"); + + expect(container.querySelector("#generic-mcp-key")).toBeTruthy(); + expect(signInToggle()?.disabled).toBe(true); + expect(buttonByText("Check link")?.disabled).toBe(true); + + // Clicking the disabled toggle must not hide the field that explains why. + await openSignInOptions(); + expect(container.querySelector("#generic-mcp-key")).toBeTruthy(); + + await act(async () => setInputValue(container.querySelector("#generic-mcp-key")!, "sk_test")); + await flushReact(); + expect(signInToggle()?.disabled).toBe(false); + expect(buttonByText("Check link")?.disabled).toBe(false); + }); + + it("labels the server as unverified exactly once on the connect step", async () => { + await render(); + await gotoLinkFrame(container, "https://mcp.example.test/mcp"); + + const occurrences = (container.textContent ?? "").split("Unverified server").length - 1; + expect(occurrences).toBe(1); + }); + it("keeps protocol jargon off the consumer path", async () => { await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); - await openAdvanced(); + await openSignInOptions(); for (const jargon of ["DCR", "Dynamic Client Registration", "CIMD", "Client ID Metadata", "RFC", "PKCE"]) { expect(container.textContent, jargon).not.toContain(jargon); diff --git a/ui/src/pages/apps/generic-mcp-connect.test.ts b/ui/src/pages/apps/generic-mcp-connect.test.ts index d70100c3378..0f41fc29963 100644 --- a/ui/src/pages/apps/generic-mcp-connect.test.ts +++ b/ui/src/pages/apps/generic-mcp-connect.test.ts @@ -90,7 +90,7 @@ describe("genericConnectGuidance", () => { it("names the credentials for a challenge with no discoverable sign-in", () => { const guidance = genericConnectGuidance("oauth_challenge", null); expect(guidance.focus).toBe("credentials"); - expect(guidance.body).toContain("Advanced authentication"); + expect(guidance.body).toContain("key or headers its docs list below"); }); it("points at the deployment when Paperclip itself has no public HTTPS address", () => { @@ -160,7 +160,7 @@ describe("genericConnectPayload", () => { expect(payload.credentialValues).toEqual({ "credentials.authorization": "abc" }); }); - it("sends the explicit mode chosen under Advanced authentication", () => { + it("sends the explicit sign-in mode the operator chose", () => { expect(genericConnectPayload(draft({ authMode: "none" }))).toMatchObject({ authMode: "none" }); expect(genericConnectPayload(draft({ authMode: "bearer", keyValue: " abc " }))) .toMatchObject({ authMode: "bearer", credentialValues: { "credentials.authorization": "abc" } }); diff --git a/ui/src/pages/apps/generic-mcp-connect.ts b/ui/src/pages/apps/generic-mcp-connect.ts index 552b2acfd34..dc568fb3f55 100644 --- a/ui/src/pages/apps/generic-mcp-connect.ts +++ b/ui/src/pages/apps/generic-mcp-connect.ts @@ -137,14 +137,14 @@ export function genericConnectGuidance( case "oauth_challenge": return { title: "This server wants a credential", - body: "It asked us to authenticate but didn't offer a sign-in Paperclip can complete on its own. Add the key or headers its docs list under Advanced authentication.", + body: "It asked us to authenticate but didn't offer a sign-in Paperclip can complete on its own. Add the key or headers its docs list below.", focus: "credentials", }; case "oauth_manual_client_required": case "oauth_manual_client_rebinding_required": return { title: "This server needs sign-in details you create yourself", - body: "Register Paperclip in the provider's settings, then add the client ID and secret it gives you under Advanced authentication.", + body: "Register Paperclip in the provider's settings, then add the client ID and secret it gives you below.", focus: "credentials", }; case "oauth_redirect_origin_unsupported": diff --git a/ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx b/ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx new file mode 100644 index 00000000000..4bfddde9392 --- /dev/null +++ b/ui/storybook/stories/connection-setup/byo-mcp-sign-in.stories.tsx @@ -0,0 +1,276 @@ +import { useState, type ComponentProps } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { CONNECTABLE_APP_DEFINITIONS, type AppDefinition } from "@paperclipai/shared"; +import { + ConnectionAccessDefaults, + connectionDefaultSummarySentence, + StepHeader, +} from "@/features/connections/ConnectionSetupFlow"; +import { GenericMcpConnectStep } from "@/features/connections/GenericMcpConnectStep"; +import { + endpointHost, + genericConnectGuidance, + newCustomHeaderRow, + type CustomHeaderRow, + type GenericConnectGuidance, + type GenericMcpAuthMode, +} from "@/pages/apps/generic-mcp-connect"; + +/** + * Connect your own MCP server: how the server signs in. + * + * The shipped sign-in section of the pasted-address connect step. Every story + * is live: switch options, type values, and watch the summary line and the + * primary action respond. + */ + +type ConnectionGrantKind = ComponentProps["grantKind"]; + +const AGENTS = [ + { id: "agent-ceo", name: "Avery", title: "CEO", icon: null }, + { id: "agent-eng", name: "Jordan", title: "Engineer", icon: null }, + { id: "agent-ops", name: "Riley", title: "Operations", icon: null }, +]; + +const NOTION = CONNECTABLE_APP_DEFINITIONS.find((entry) => entry.slug === "notion") as AppDefinition | undefined; + +function header(name: string, value: string): CustomHeaderRow { + return { ...newCustomHeaderRow(), name, value }; +} + +interface Scenario { + link?: string; + authMode?: GenericMcpAuthMode; + open?: boolean; + needsKey?: boolean; + keyValue?: string; + headers?: CustomHeaderRow[]; + oauthClientId?: string; + oauthClientSecret?: string; + guidance?: GenericConnectGuidance | null; + matchedEntry?: AppDefinition | null; + submitting?: boolean; +} + +function Screen({ + link = "http://127.0.0.1:8848/mcp", + authMode: initialAuthMode = "auto", + open: initialOpen = false, + needsKey: initialNeedsKey = false, + keyValue: initialKey = "", + headers: initialHeaders, + oauthClientId: initialClientId = "", + oauthClientSecret: initialClientSecret = "", + guidance: initialGuidance = null, + matchedEntry = null, + submitting: initialSubmitting = false, +}: Scenario) { + const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } })); + const [authMode, setAuthMode] = useState(initialAuthMode); + const [open, setOpen] = useState(initialOpen); + const [needsKey, setNeedsKey] = useState(initialNeedsKey); + const [keyValue, setKeyValue] = useState(initialKey); + const [headers, setHeaders] = useState(() => initialHeaders ?? [newCustomHeaderRow()]); + const [clientId, setClientId] = useState(initialClientId); + const [clientSecret, setClientSecret] = useState(initialClientSecret); + const [guidance, setGuidance] = useState(initialGuidance); + const [submitting, setSubmitting] = useState(initialSubmitting); + const [grantKind, setGrantKind] = useState("organization"); + const [installChoice, setInstallChoice] = useState<"specific" | "all">("all"); + const [installAgentIds, setInstallAgentIds] = useState>(() => new Set()); + + const authKind = authMode === "none" ? "none" : authMode === "oauth" ? "oauth" : "api_key"; + + return ( + +
+ {}} + /> + { + // Mirrors the page: an explicit choice replaces the probed answer. + setAuthMode(next); + setGuidance(null); + if (next !== "auto") setNeedsKey(false); + if (next !== "bearer" && next !== "auto") setKeyValue(""); + }} + headers={headers} + onHeadersChange={(next) => { + setHeaders(next); + setGuidance(null); + }} + oauthClientId={clientId} + onOAuthClientIdChange={setClientId} + oauthClientSecret={clientSecret} + onOAuthClientSecretChange={setClientSecret} + advancedOpen={open} + onAdvancedOpenChange={setOpen} + guidance={guidance} + matchedEntry={matchedEntry} + onUseMatchedEntry={matchedEntry ? () => {} : undefined} + submitting={submitting} + defaults={ + + } + onBack={() => {}} + onConnect={() => { + setGuidance(null); + setSubmitting(true); + window.setTimeout(() => setSubmitting(false), 1500); + }} + /> +
+
+ ); +} + +const meta = { + id: "byo-mcp-sign-in", + title: "Apps, channels, and extensions/Connection setup/Apps/Connect your own MCP server — sign-in", + component: Screen, + parameters: { + layout: "fullscreen", + docs: { + description: { + component: + "Sign-in section for a pasted MCP server address. The choice is a stated default with a Change control, matching the access line below it. Each option keeps its fields directly beneath it. Fixture state only; Check link simulates a short wait.", + }, + }, + paperclip: { + "capabilities": [ + "connection-setup/identity-and-access" + ], + "status": "current", + "implementation": "production", + "boundary": "fixtures", + "notes": "Renders the production GenericMcpConnectStep used by the Apps connect route for a pasted MCP server address, with fixture state and a simulated Check link wait." + }, + }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const Default: Story = { name: "1. Default — nothing to decide" }; + +export const Choosing: Story = { + name: "2. Change — all five options", + args: { open: true }, +}; + +export const KeyOrToken: Story = { + name: "3. Key or token", + args: { open: true, authMode: "bearer" }, +}; + +export const BrowserSignIn: Story = { + name: "4. Browser sign-in", + args: { open: true, authMode: "oauth", link: "https://mcp.example.com/mcp" }, +}; + +export const BrowserSignInOwnClient: Story = { + name: "5. Browser sign-in — your own client ID", + args: { + open: true, + authMode: "oauth", + link: "https://mcp.example.com/mcp", + oauthClientId: "paperclip-prod-7f3a", + oauthClientSecret: "example-secret", + }, +}; + +export const CustomHeaders: Story = { + name: "6. Custom headers", + args: { + open: true, + authMode: "custom_headers", + headers: [header("X-Api-Key", "example-value"), header("X-Workspace", "acme")], + }, +}; + +export const CustomHeadersError: Story = { + name: "7. Custom headers — rejected header", + args: { + open: true, + authMode: "custom_headers", + headers: [header("X-Api-Key", "example-value"), header("x-api-key", "another")], + }, +}; + +export const NoSignIn: Story = { + name: "8. No sign-in needed", + args: { open: true, authMode: "none" }, +}; + +export const ChoiceCollapsed: Story = { + name: "9. A choice, collapsed", + args: { + authMode: "custom_headers", + headers: [header("X-Api-Key", "example-value"), header("X-Workspace", "acme")], + }, +}; + +export const ServerAskedForKey: Story = { + name: "10. After checking — the server wants a credential", + args: { + open: true, + needsKey: true, + link: "https://mcp.example.com/mcp", + guidance: genericConnectGuidance("oauth_challenge", null), + }, +}; + +export const ServerNeedsOwnClient: Story = { + name: "11. After checking — register Paperclip first", + args: { + open: true, + authMode: "oauth", + link: "https://mcp.example.com/mcp", + guidance: genericConnectGuidance("oauth_manual_client_required", null), + }, +}; + +export const Unreachable: Story = { + name: "12. After checking — nothing answered", + args: { guidance: genericConnectGuidance("runtime_error", null) }, +}; + +export const KnownApp: Story = { + name: "13. Address matches a listed app", + args: { link: "https://mcp.notion.com/mcp", matchedEntry: NOTION ?? null }, +}; + +export const Checking: Story = { + name: "14. Checking", + args: { submitting: true }, +};