feat(apps): ship the redesigned sign-in step for a pasted MCP server (#21469)

## 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 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Fable 5.2 authored and GitHub committed 2026-11-13 14:35:49 -06:00
1 parent e9d7895648
commit 0199c963e2
13 files changed
+844 -357

No files matched your search

+15 -7
View File
@@ -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
+1 -1
View File
@@ -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";
@@ -352,7 +352,7 @@ export type DisableToolStdioCommandTemplate = z.infer<typeof disableToolStdioCom
*
* `auto` is the default and the only value the simple path sends: Paperclip
* probes the endpoint and branches on what it finds. The rest are the explicit
* choices behind "Advanced authentication", where the operator already knows.
* choices behind the sign-in Change control, where the operator already knows.
*/
export const GENERIC_MCP_AUTH_MODES = ["auto", "none", "bearer", "custom_headers", "oauth"] as const;
+1 -1
View File
@@ -2220,7 +2220,7 @@ export function toolAccessService(
const credentialValues = input.credentialValues ?? {};
// A curated method declares its auth kind. A pasted URL declares one only
// under Advanced authentication; on the simple path it starts from what the
// when the operator picks a sign-in option; on the simple path it starts from what the
// operator supplied and is upgraded to `oauth` when discovery proves the
// endpoint needs sign-in (see `remoteTools` and `startOAuth`).
const genericAuthKind: ToolConnectionAuthKind =
@@ -565,7 +565,7 @@ function canRegisterOAuthClientDynamically(
// 4. Dynamic client registration.
if (!input.endpoints.registrationUrl) {
throw unprocessable(
"This server needs sign-in details you create yourself. Add a client ID and secret under Advanced authentication.",
"This server needs sign-in details you create yourself. Register Paperclip with the provider, then add the client ID and secret it gives you.",
{ code: "oauth_manual_client_required" },
);
}
@@ -429,7 +429,7 @@
"packages/shared/src/types/summary-slot.ts": "9698bb7d628be3f2310d050037e30157d474ed48",
"packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb",
"packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be",
"packages/shared/src/types/tool-access.ts": "9a96b4ab4fe52bd74f45a1b18ce596aeee410f82",
"packages/shared/src/types/tool-access.ts": "4c05d176f9bb1d30593fd904c7c4fc3e91b431ca",
"packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f",
"packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459",
"packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086",
@@ -518,7 +518,7 @@
"packages/shared/src/validators/teams-catalog.ts": "7bddf40c091a52aaa54e79de784bea5ae496f9aa",
"packages/shared/src/validators/text.ts": "74c430fe17cdcfd4b56dd08a4c57cd3d567670a8",
"packages/shared/src/validators/tool-access.test.ts": "b5838320115946a936b256919a5bd3a2294c6070",
"packages/shared/src/validators/tool-access.ts": "f55163c22eb9e7db2a2f0ac61abeb953c2c16e10",
"packages/shared/src/validators/tool-access.ts": "cd28549a930e0b222904bb1121db17659bf12b05",
"packages/shared/src/validators/trust-policy.test.ts": "1fc4818984eb0e14f034d56ad147600224496d4e",
"packages/shared/src/validators/trust-policy.ts": "f16b002db940b06bd882d51df8b5712c576e1d7b",
"packages/shared/src/validators/voice-sessions.ts": "018a71f9ac544645041ac3cc9919e59c95fbe998",
@@ -13,6 +13,7 @@ import { useMemoryConnectorsEnabled } from "@/hooks/useMemoryConnectorsEnabled";
import { useConnectorAvailability } from "@/hooks/useConnectorAvailability";
import { AiConnectionCredentialStep } from "@/components/ai-connections/AiConnectionCredentialStep";
import { ConnectionChoiceList } from "./ConnectionChoiceList";
import { GenericMcpConnectStep } from "./GenericMcpConnectStep";
import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode, type Ref } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
@@ -20,7 +21,6 @@ import {
Bot,
Building2,
Check,
ChevronDown,
ChevronRight,
Cloud,
Copy,
@@ -86,7 +86,6 @@ import { cn } from "@/lib/utils";
import { useCopyAction } from "@/lib/use-copy-action";
import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";
import { prepareOAuthNavigation, savePendingCloudHandoff } from "@/lib/oauthHandoff";
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
import { askFirstCatalogEntryIdsFor } from "./connection-defaults";
import { AppLogo } from "@/pages/apps/AppLogo";
import { appApplicationSourceSlug, appConnectionSourceSlug } from "@/pages/apps/app-definition-display";
@@ -101,8 +100,6 @@ import {
import { parseGoogleSheetIds } from "@/pages/apps/google-sheets";
import { connectionNameForGrantKind } from "@/pages/apps/connection-identity";
import {
canSubmitGenericConnect,
customHeaderError,
defaultGenericMcpName,
endpointHost,
genericConnectGuidance,
@@ -110,7 +107,6 @@ import {
newCustomHeaderRow,
oauthCallbackUrlForBrowser,
type CustomHeaderRow,
type GenericConnectDraft,
type GenericConnectGuidance,
type GenericMcpAuthMode,
} from "@/pages/apps/generic-mcp-connect";
@@ -349,7 +345,7 @@ type AppAccessSelection = "all_agents" | { agentIds: string[] };
// PAP-659: identity and agent reach are no longer a step. They are resolved to
// a default, stated in one line above the primary action, and changed either in
// the Advanced disclosure on this screen or on the Permissions tab afterwards.
const STEP_LABELS = ["Pick app", "Add your key"];
const STEP_LABELS = ["Pick app", "Connect"];
const STEP_INDEX: Record<Exclude<Step, "success">, number> = {
gallery: 0,
key: 1,
@@ -2794,7 +2790,7 @@ function StandardConnectionSetupFlow({
)}
{step === "key" && !entry && linkUrl && !zapierSource && (
<LinkConnectStep
<GenericMcpConnectStep
link={linkUrl}
name={linkName}
needsKey={linkNeedsKey}
@@ -3349,320 +3345,6 @@ function normalizeAppLink(value: string): string | null {
}
}
/**
* The guided universal flow for an unknown remote MCP server (PAP-17087, plan 2).
*
* The simple path stays exactly as short as it was — URL, name, "does it need a
* key?" — because that is all most servers need. Everything protocol-shaped lives
* behind "Advanced authentication", and no OAuth/DCR/CIMD jargon appears on the
* consumer path: the operator picks how the server authenticates, not which RFC
* Paperclip will use to satisfy it.
*
* The endpoint host and the "Unverified server" label stay visible the whole way
* through, so the operator can always see whose server they are about to let
* agents call.
*/
function LinkConnectStep({
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;
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 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<CustomHeaderRow>) => {
onHeadersChange(headers.map((row) => (row.id === id ? { ...row, ...patch } : row)));
};
return (
<div className="mx-auto max-w-xl">
<div className="flex items-center justify-between gap-3">
<p className="min-w-0 truncate font-mono text-sm text-muted-foreground" title={displayedLink}>{displayedLink}</p>
<UnverifiedServerBadge host={host} />
</div>
{matchedEntry && onUseMatchedEntry ? (
<div className="mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2">
<div className="flex min-w-0 items-center gap-2 text-sm">
<AppLogo name={matchedEntry.name} logoUrl={matchedEntry.branding.logoUrl} darkLogoUrl={matchedEntry.branding.darkLogoUrl} size={24} />
<span className="truncate">Paperclip has a guided setup for {matchedEntry.name}.</span>
</div>
<Button type="button" size="sm" variant="outline" onClick={onUseMatchedEntry}>
Use {matchedEntry.name}
</Button>
</div>
) : null}
{guidance ? (
<div className="mt-6">
<InlineBanner tone="warning" title={guidance.title}>
{guidance.body}
</InlineBanner>
</div>
) : null}
<div className="mt-6 space-y-6">
{showKeyField ? (
<div className="space-y-4">
<div>
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-key">App key</label>
<Input
id="generic-mcp-key"
type="password"
autoComplete="off"
value={keyValue}
onChange={(e) => onKeyChange(e.target.value)}
placeholder="••••••••••••••••"
className="mt-2 h-11 font-mono"
/>
<p className="mt-2 text-xs text-muted-foreground">
Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions.
</p>
</div>
</div>
) : null}
<Collapsible open={advancedOpen} onOpenChange={onAdvancedOpenChange}>
<CollapsibleTrigger className="flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40">
Advanced authentication
<ChevronDown className={cn("h-4 w-4 text-muted-foreground transition-transform", advancedOpen && "rotate-180")} />
</CollapsibleTrigger>
<CollapsibleContent className="space-y-5 pt-4">
<p className="text-xs text-muted-foreground">
Only needed when the server's docs are specific about how to authenticate.
</p>
<div className="flex flex-wrap gap-2">
{GENERIC_AUTH_MODE_OPTIONS.map((option) => (
<SegmentedOption
key={option.mode}
label={option.label}
selected={authMode === option.mode}
onClick={() => onAuthModeChange(option.mode)}
/>
))}
</div>
<p className="text-xs text-muted-foreground">
{GENERIC_AUTH_MODE_OPTIONS.find((option) => option.mode === authMode)?.hint}
</p>
{authMode === "custom_headers" ? (
<div className="space-y-3">
{headers.map((row) => (
<div key={row.id} className="flex items-start gap-2">
<Input
value={row.name}
onChange={(e) => updateHeader(row.id, { name: e.target.value })}
placeholder="Header name"
aria-label="Header name"
className="h-10 font-mono"
/>
<Input
type="password"
autoComplete="off"
value={row.value}
onChange={(e) => 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"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="h-10 shrink-0"
onClick={() => onHeadersChange(headers.filter((candidate) => candidate.id !== row.id))}
disabled={headers.length === 1}
>
Remove
</Button>
</div>
))}
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onHeadersChange([...headers, newCustomHeaderRow()])}
>
Add another header
</Button>
{headerError ? <p className="text-xs text-destructive">{headerError}</p> : null}
</div>
) : null}
{authMode === "oauth" ? (
<div className="space-y-4">
<p className="text-xs text-muted-foreground">
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.
</p>
<div>
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-id">
Client ID
</label>
<Input
id="generic-mcp-client-id"
value={oauthClientId}
onChange={(e) => onOAuthClientIdChange(e.target.value)}
autoComplete="off"
placeholder="Optional"
className="mt-2 h-11 font-mono"
/>
</div>
<div>
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-secret">
Client secret
</label>
<Input
id="generic-mcp-client-secret"
type="password"
autoComplete="off"
value={oauthClientSecret}
onChange={(e) => onOAuthClientSecretChange(e.target.value)}
placeholder="Optional"
className="mt-2 h-11 font-mono"
/>
</div>
</div>
) : null}
</CollapsibleContent>
</Collapsible>
</div>
{defaults}
<div className="mt-8 flex items-center justify-between">
<Button variant="ghost" onClick={onBack} disabled={submitting}>
Back
</Button>
<Button onClick={onConnect} disabled={submitting || !canSubmit || Boolean(headerError)}>
{submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{submitting ? "Checking…" : "Check link"}
</Button>
</div>
</div>
);
}
/**
* 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 (
<button
type="button"
onClick={onClick}
aria-pressed={selected}
className={cn(
"min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",
selected
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}
>
{label}
</button>
);
}
function KeyStep({
settingsValid = true,
entry,
@@ -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.",
);
});
});
@@ -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<CustomHeaderRow>) => {
onHeadersChange(headers.map((row) => (row.id === id ? { ...row, ...patch } : row)));
};
const moveSelection = (event: KeyboardEvent<HTMLDivElement>) => {
// 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<HTMLButtonElement>('[role="radio"]')[next]?.focus();
};
const keyField = (label: string | null) => (
<div>
{label ? (
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-key">{label}</label>
) : null}
<Input
id="generic-mcp-key"
type="password"
autoComplete="off"
aria-label={label ? undefined : "Key or token"}
value={keyValue}
onChange={(event) => onKeyChange(event.target.value)}
placeholder="Paste the key or token"
className={label ? "mt-2 h-11 font-mono" : "h-11 font-mono"}
/>
<p className="mt-2 text-xs text-muted-foreground">
Grant this key access to what your agents need. Paperclip can’t increase its permissions.
</p>
</div>
);
const optionFields = (mode: GenericMcpAuthMode): ReactNode => {
if (mode === "bearer") return keyField(null);
if (mode === "custom_headers") {
return (
<div className="space-y-2">
{headers.map((row) => (
<div key={row.id} className="flex items-center gap-2">
<Input
value={row.name}
onChange={(event) => updateHeader(row.id, { name: event.target.value })}
placeholder="Header name"
aria-label="Header name"
autoComplete="off"
spellCheck={false}
className="h-10 font-mono"
/>
<Input
type="password"
autoComplete="off"
value={row.value}
onChange={(event) => 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"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="shrink-0 text-muted-foreground"
aria-label={row.name.trim() ? `Remove ${row.name.trim()}` : "Remove header"}
onClick={() => onHeadersChange(headers.filter((candidate) => candidate.id !== row.id))}
disabled={headers.length === 1}
>
<X className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
))}
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
<Button
type="button"
variant="ghost"
size="sm"
className="-ml-2.5"
onClick={() => onHeadersChange([...headers, newCustomHeaderRow()])}
>
<Plus className="h-4 w-4" aria-hidden="true" />
Add header
</Button>
<p className="text-xs text-muted-foreground">Values are stored as secrets and can’t be read back.</p>
</div>
{headerError ? <p role="alert" className="text-xs text-destructive">{headerError}</p> : null}
</div>
);
}
if (mode === "oauth") {
if (!showClientFields) {
return (
<Button
type="button"
variant="link"
className="h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
onClick={() => setClientFieldsOpen(true)}
>
Use your own client ID
</Button>
);
}
return (
<div className="space-y-4">
<p className="text-xs text-muted-foreground">
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.
</p>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-id">
Client ID
</label>
<Input
id="generic-mcp-client-id"
value={oauthClientId}
onChange={(event) => onOAuthClientIdChange(event.target.value)}
autoComplete="off"
spellCheck={false}
placeholder="Optional"
className="mt-2 h-10 font-mono"
/>
</div>
<div>
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-secret">
Client secret
</label>
<Input
id="generic-mcp-client-secret"
type="password"
autoComplete="off"
value={oauthClientSecret}
onChange={(event) => onOAuthClientSecretChange(event.target.value)}
placeholder="Optional"
className="mt-2 h-10 font-mono"
/>
</div>
</div>
</div>
);
}
return null;
};
return (
<div className="mx-auto max-w-xl">
<div className="flex flex-col gap-6">
<p className="min-w-0 truncate font-mono text-sm text-muted-foreground" title={displayedLink}>{displayedLink}</p>
{matchedEntry && onUseMatchedEntry ? (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2">
<div className="flex min-w-0 items-center gap-2 text-sm">
<AppLogo name={matchedEntry.name} logoUrl={matchedEntry.branding.logoUrl} darkLogoUrl={matchedEntry.branding.darkLogoUrl} size={24} />
<span className="truncate">Paperclip has a guided setup for {matchedEntry.name}.</span>
</div>
<Button type="button" size="sm" variant="outline" onClick={onUseMatchedEntry}>
Use {matchedEntry.name}
</Button>
</div>
) : null}
{guidance ? (
<InlineBanner tone="warning" title={guidance.title}>
{guidance.body}
</InlineBanner>
) : null}
{probedKey ? keyField("App key") : null}
</div>
<Collapsible
open={expanded}
onOpenChange={onAdvancedOpenChange}
className="mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3"
>
<div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
<p className="text-sm text-muted-foreground">
{expanded ? "How does this server sign in?" : genericMcpAuthSummary({ authMode, headers, oauthClientId })}
</p>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="link"
className="h-auto p-0 text-xs font-semibold underline underline-offset-2"
disabled={submitting || choiceNeedsInput}
data-testid="generic-mcp-sign-in-toggle"
>
{expanded ? "Done" : "Change"}
</Button>
</CollapsibleTrigger>
</div>
<CollapsibleContent>
<div
role="radiogroup"
aria-label="How this server signs in"
className="mt-3 grid gap-2 pb-1"
onKeyDown={moveSelection}
>
{AUTH_OPTIONS.map((option) => {
const selected = option.mode === authMode;
const fields = selected ? optionFields(option.mode) : null;
return (
<div key={option.mode}>
<RadioCard
selected={selected}
title={option.title}
description={option.description}
tabIndex={selected ? 0 : -1}
disabled={submitting}
className="bg-background"
onClick={() => onAuthModeChange(option.mode)}
/>
{fields ? <div className="px-4 pb-2 pt-3">{fields}</div> : null}
</div>
);
})}
</div>
</CollapsibleContent>
</Collapsible>
{defaults}
<div className="mt-8 flex items-center justify-between">
<Button variant="ghost" onClick={onBack} disabled={submitting}>
Back
</Button>
<Button onClick={onConnect} disabled={submitting || !canSubmit || Boolean(headerError)}>
{submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{submitting ? "Checking…" : "Check link"}
</Button>
</div>
</div>
);
}
+91 -19
View File
@@ -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<HTMLButtonElement>('[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<HTMLInputElement>("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<HTMLInputElement>("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<HTMLInputElement>("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<HTMLInputElement>("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<HTMLInputElement>("#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);
@@ -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" } });
+2 -2
View File
@@ -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":
@@ -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<typeof ConnectionAccessDefaults>["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<CustomHeaderRow[]>(() => 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<ConnectionGrantKind>("organization");
const [installChoice, setInstallChoice] = useState<"specific" | "all">("all");
const [installAgentIds, setInstallAgentIds] = useState<Set<string>>(() => new Set());
const authKind = authMode === "none" ? "none" : authMode === "oauth" ? "oauth" : "api_key";
return (
<QueryClientProvider client={client}>
<div className="max-w-5xl p-6">
<StepHeader
subtitle="Step 2 of 2"
step="key"
activeIndex={1}
labels={["Pick app", "Connect"]}
unverifiedHost={endpointHost(link)}
onCancel={() => {}}
/>
<GenericMcpConnectStep
link={link}
name=""
needsKey={needsKey}
keyValue={keyValue}
onKeyChange={setKeyValue}
authMode={authMode}
onAuthModeChange={(next) => {
// 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={
<ConnectionAccessDefaults
companyId="company-storybook"
agents={AGENTS}
sentence={connectionDefaultSummarySentence({
grantKind,
authKind,
installChoice,
installCount: installAgentIds.size,
})}
authKind={authKind}
grantKind={grantKind}
setGrantKind={setGrantKind}
installChoice={installChoice}
setInstallChoice={setInstallChoice}
installAgentIds={installAgentIds}
setInstallAgentIds={setInstallAgentIds}
capabilities={{ canCreateOrganizationGrant: true, canSetCompanyInstall: true }}
disabled={submitting}
/>
}
onBack={() => {}}
onConnect={() => {
setGuidance(null);
setSubmitting(true);
window.setTimeout(() => setSubmitting(false), 1500);
}}
/>
</div>
</QueryClientProvider>
);
}
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<typeof Screen>;
export default meta;
type Story = StoryObj<typeof meta>;
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 },
};