Files
PaperClipAI/doc/connections/GENERIC-REMOTE-MCP.md
DottaandClaude Opus 5.5 f6c5986b61 feat(connections): machine sign-in (MCP OAuth client credentials) for organization connections (#21473)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use apps through connections to remote MCP servers
> - Today an organization connection must sign in as a person (browser
sign-in) or use a static key
> - Service accounts and CI-style integrations have no person who can
sign in
> - The MCP OAuth Client Credentials extension (2026-07-28) defines
machine-to-machine sign-in for this case
> - This pull request adds "Machine sign-in" for organization
connections, with a Paperclip-held signing key (recommended) or a client
secret
> - The benefit is that organizations can connect automation-owned MCP
servers safely, with credentials only in the vault and bound to one
sign-in service

## Linked Issues or Issue Description

**Subsystem affected**
Connections: remote MCP OAuth (server `tool-access/oauth`, tool gateway
token refresh) and the custom MCP server setup flow in the UI.

**Problem or motivation**
Organization-owned automation (service accounts, CI integrations) cannot
connect an MCP server that requires OAuth, because no person can
complete a browser sign-in. The MCP OAuth Client Credentials extension
(`io.modelcontextprotocol/oauth-client-credentials`) solves this with
`grant_type=client_credentials` and RFC 7523 signed client assertions.

**Proposed solution**
Add machine sign-in for organization connections only. Paperclip creates
a keypair per connection, keeps the private key in the company vault,
and shows the public key (PEM and JWK) for the admin to register. A
client secret is also supported. The sign-in service (issuer and token
endpoint) is pinned at setup. Tokens use the existing organization grant
refresh path, so caching, concurrent dedupe and 401 re-request reuse the
existing lease and single flight.

**Alternatives considered**
Reuse the deployment-wide `PAPERCLIP_TOOL_OAUTH_*` client env path that
already sent `client_credentials`. Rejected: it is not per connection,
it keeps secrets in env, and it has no issuer pin. Route machine sign-in
through `connectGalleryApp`. Rejected: its rollback deletes the draft on
a failed test, which would lose a key the admin already registered.

**Roadmap alignment**
Phase 1 of the enterprise MCP plan (no enterprise single sign-on
needed). OIDC login and enterprise-managed authorization (ID-JAG) are
later phases.

## What Changed

- `oauth/client-credentials.ts`: keypair generation (RS256, or ES256
when the service requires it), RFC 7638 key IDs, and RFC 7523 assertions
(`iss` = `sub` = client ID, `aud` = token endpoint, 60 s `exp`, unique
`jti`) with Node `crypto` only.
- `oauth/client.ts`: the token exchange accepts a signed assertion and
then sends only `client_assertion_type` and `client_assertion` (no
`client_id` or secret), as the extension specifies.
- `oauth/client-credentials-service.ts`: discovery of the sign-in
service (protected-resource metadata, then RFC 8414/OIDC metadata with
issuer check, or a token URL entered directly), issuer pinning,
vault-only key and secret handling, draft creation, test-and-activate,
and no-downtime rotation (test the new secret first; stage a new key and
switch only after the provider accepts it).
- `oauth/grant-refresh.ts` and `oauth/connection-refresh.ts`: machine
sign-in requests a new access token with the connection's own
credentials instead of needing a refresh token. It never falls back to
deployment-wide OAuth clients.
- `catalog/discovery.ts`: a rejected token on a machine sign-in
connection never re-runs discovery or rewrites the pinned endpoints.
- `mcp-http.ts` and the tool gateway: declare
`io.modelcontextprotocol/oauth-client-credentials` in client
capabilities only for connections that use it.
- Routes (with OpenAPI and activity logging): `POST
/companies/{companyId}/tools/machine-sign-in`, `GET|POST
/tool-connections/{id}/machine-sign-in[/test|/rotate|/rotate/complete]`.
Removal activity now records `machineSignIn: true`. The runner API
treats these routes as sensitive.
- Shared validators and types for machine sign-in.
- UI: "Machine sign-in" under Advanced authentication in the custom MCP
server flow (organization connections only), `MachineSignInSetup`
(choose Paperclip key or client secret, register the public key, test),
and Storybook stories for each setup state.
- Docs: `doc/connections/MCP-CLIENT-CREDENTIALS.md`, linked from
`doc/connections/README.md` and `GENERIC-REMOTE-MCP.md`.

## Verification

- `server/src/__tests__/tool-access-client-credentials.test.ts`: 16/16
pass. It uses a fake sign-in service that verifies real signatures
against registered keys, and a fake MCP server. It covers RS256 and
ES256 assertion claims and signatures, assertion-only client
authentication, the secret flow (`client_secret_basic`), discovery and
direct token URL, issuer pinning (refuses a different sign-in service
and sends it nothing), the pinned endpoint surviving a hostile
challenge, the token cache (0 token requests while live), concurrent
dedupe (5 callers on 2 service instances produce 1 token request), 401
re-request, key and secret rotation, a refused personal connection,
secret redaction in responses, rows and activity, and vault cleanup on
removal.
- Red/green: with the grant-refresh machine sign-in branch and the
discovery pin guard disabled, 5 runtime tests fail (pin, cache/dedupe,
401 re-request, both rotations). Restored: 16/16 pass. The other tests
cover new routes and services that do not exist on `master`.
- `ui/src/features/connections/MachineSignInSetup.test.tsx`: 3/3.
`ConnectionSetupFlow.architecture` and `.oauth` tests: 19/19.
- `openapi-routes.test.ts`: 51/51. `runner-api.test.ts`: 2153/2153.
`mcp-http.test.ts`: 9/9. Existing `tool-access-service.test.ts` refresh
and legacy client-credentials tests: 54/54 (filtered).
- Server package `tsc --noEmit`: clean. UI `tsc`: clean except the
pre-existing generated Storybook catalog imports.
- Not run locally (machine under heavy load): full suites, repo-wide
typecheck, browser check of the live app. CI covers breadth.

## Risks

- No migration. New config lives in `config.oauth` (`grantType:
"client_credentials"` plus `clientAuth`). Older env-configured
client-credentials connections have no `clientAuth` and keep their
original path.
- The capability declaration adds one extension key only for machine
sign-in connections. Other requests are unchanged.
- Rotation has no settings-page control yet; it is available through the
API. This is a follow-up.
- Low risk to agent boot and time to first token: a live token is read
exactly like a browser sign-in token.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, test runs).

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 03:10:32 +00:00

17 KiB

Connecting any remote MCP server

Paperclip can connect a standards-compliant remote HTTP MCP server without a Paperclip code change. A curated AppDefinition is a convenience layer — branding, tailored fields, scoped defaults, support copy — not a prerequisite.

This is the documented baseline for connecting anything. Read Connection authoring runbook when you want to add the branded convenience layer on top for a vendor Paperclip should promote.

Accepted in the generic remote MCP plan, implemented in PAP-17087.

The two routes

Route Where Use it when
Guided URL Apps → Connect an app → Connect your own MCP server You have the server's address. Paperclip probes it and walks you through whatever it needs.
Paste a config Advanced → Paste a config A README gave you an mcpServers snippet, or the server needs headers with names Paperclip could not guess.

Both routes normalize through the same backend contract, so auth discovery, secret handling, catalog refresh and review cannot diverge between them.

Advanced → Run your own is a separate, higher-trust path for local stdio commands and is deliberately not covered here.

Don't know the address or the headers? The question-mark control beside Paste a config gives you a request you can hand to an agent: it asks the agent to consult the vendor's current documentation and reply with one paste-ready mcpServers JSON object using credential placeholders, plus notes on how to obtain each credential. Paste only the JSON block back into Paperclip; Paperclip reads the header names from it and asks you for the values, which it stores as Paperclip secrets.

What the guided URL flow does

After you paste an address and press Check link, Paperclip probes the endpoint and branches:

Endpoint says You get
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, 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.

An unknown server is labelled Unverified server with its host shown, at every step through review, access and install. Reads are enabled for review; state-changing actions start off; newly discovered actions are quarantined until reviewed. That is the same treatment a curated connection gets.

For Just me, the first probe of a new URL with no supplied credentials runs before a personal authorization exists. If the server requires OAuth, Paperclip creates the personal grant only after sign-in succeeds. If the server is public, Paperclip creates a personal grant with no credentials after the probe succeeds. That successful public probe saves the draft identity and its grant. A later catalog-refresh failure leaves them available for retry instead of undoing a grant that another setup attempt may already be using. Catalog and default-profile writes after that probe are atomic: a failure rolls back that step while retaining the established draft identity. Later health checks still require the user's authorization and return an actionable 422 error when it is missing.

Personal apps on shared agents

Installing a personal app on an agent does not require every user who runs that agent to connect the app. Runs start without probing optional apps or warning about another user's missing credentials. The installed app's cached tools stay available even when its shared health check needs attention.

Authorization happens when the agent calls an app tool. Paperclip uses the run's responsible user, never another user's personal grant. If that user has not connected the app, the tool returns user_authorization_required and adds an inline connection request. Unrelated work can continue without using the app. Disabled or uninstalled apps remain unavailable.

Optional assigned apps do not emit run-start connection warnings, including unavailable shared apps. Their health state and reconnect controls remain in Apps. An unrelated run does not need to act on that state.

Slack app access

If Slack reports that MCP access is disabled for the app, ask the Slack app owner to enable MCP access in the app's Slack settings, then refresh the 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.

Choosing how the server signs in

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 (six for organization connections), each with its fields directly beneath it when selected:

  • 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.
  • No sign-in needed — the server is open to anyone with the address.
  • Machine sign-in — organization connections only. Paperclip signs in as a client you registered with the provider, using a Paperclip key or a client secret, with no person involved. It runs its own setup and test in place of Check link. See Machine sign-in.

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 write, or UI readback. Only header names are shown in review and diagnostics.

Paperclip refuses to send header names it manages or that belong to the transport — Host, Cookie, Content-Length, Transfer-Encoding, hop-by-hop headers, and anything under Proxy-* or Sec-* — and rejects values containing line breaks or control characters. This is enforced in shared code (packages/shared/src/mcp-remote-headers.ts), checked at the API boundary, and re-checked in the service immediately before the header is projected onto a real request.

How sign-in gets a client

You never choose this; Paperclip resolves it and the wizard shows none of it. Recorded here for security review and diagnostics. In preference order:

  1. Deployment-preconfigured client. PAPERCLIP_TOOL_OAUTH_<PROVIDER>_CLIENT_ID / _SECRET, or the unsuffixed PAPERCLIP_TOOL_OAUTH_CLIENT_ID / _SECRET. Always wins when set.
  2. Client ID Metadata Document (CIMD). When the authorization server advertises client_id_metadata_document_supported, Paperclip presents the URL of its own published metadata document as the client_id. Nothing is registered. Requires a public HTTPS base URL (PAPERCLIP_PUBLIC_URL): the authorization server has to fetch that document server-to-server, so loopback and plain-HTTP deployments fall through to the next tier. The document is served unauthenticated at /api/tools/oauth/client-metadata and contains only this deployment's callback and the grant/response/auth methods Paperclip uses — no company, connection or secret data.
  3. Dynamic client registration (RFC 7591). When the authorization server 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 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 metadata document, and only on an explicit operator connect action. An endpoint that merely returns a 401 does not earn a registration.

Client binding

Client material is bound to the authorization-server issuer, the MCP resource URL, the callback URI, and the company. If any of those change:

  • a Paperclip-minted client (CIMD or DCR) is re-registered;
  • a client you supplied yourself is not — Paperclip stops and asks you to re-enter it, because it cannot register on your behalf in a console it does not control.

Credentials are never reused across issuers or across companies.

Endpoint addresses are validated before they are used

Every OAuth endpoint address is chosen by the remote server — in discovered metadata, in a WWW-Authenticate hint, in a pasted config, or in a gallery default — and the authorization endpoint additionally becomes a top-level browser navigation. All of them are parsed by one shared validator (checkOAuthEndpointUrl in @paperclipai/shared) and must be:

  • https:. Plain http: is refused, except for a loopback host under the local-development policy (the same policy that allows private remote endpoints), and except for this deployment's own origin.
  • Free of embedded credentials. https://accounts.google.com@evil.test/… reads as the wrong site to a human, so Paperclip refuses it.
  • Free of a fragment, and a well-formed absolute URL.

javascript:, data:, file: and friends are therefore refused before they can reach window.location. The board applies the same validator to the address it receives, so an unsafe value cannot pass the API boundary and then execute at the navigation boundary. A refusal is reported as oauth_<kind>_endpoint_rejected (422) and the unsafe value is never persisted on the connection.

An address that passes is still only an address: a valid HTTPS authorization page can be a phishing page. The redirect screen names the host you are being sent to, and the Unverified server label stays visible for an endpoint with no curated definition.

Protocol conformance

  • RFC 8707 resource on authorization, token, and refresh requests, naming the canonical MCP endpoint (origin + path, no query or fragment), so the authorization server can audience-restrict the token to that server.
  • RFC 9728 protected-resource discovery, path-aware first (/.well-known/oauth-protected-resource<path>) then origin.
  • RFC 8414 authorization-server discovery for issuers with a path, in the spec's insertion form (/.well-known/oauth-authorization-server<path>) and the widely deployed OIDC suffix form (<path>/.well-known/...). A metadata document whose issuer disagrees with the issuer used to build the discovery URL is discarded.
  • RFC 9207 iss validated against the persisted expected issuer when the authorization server returns it. A mismatch refuses the code rather than exchanging it. An absent iss is tolerated — it is optional and widely omitted.
  • PKCE S256, exact redirect/state binding, and SSRF/private-network and redirect limits are unchanged from the curated path.

The discovered auth kind, issuer, and resource are persisted on the connection, so refresh, reconnect, revoke and diagnostics all use the generic path instead of falling back to authKind: none semantics.

Staying connected after access-token expiry

For generic MCP connections, Paperclip adds offline_access to the selected tool scopes when the authorization server advertises it in scopes_supported and does not explicitly exclude the refresh-token grant. This works even when the MCP server's challenge or protected-resource metadata lists only tool scopes. Paperclip requests prompt=consent, stores the actual requested scopes for callback completion and reconnect, and refreshes access tokens using its existing encrypted-vault and rotating-token lease paths. Curated Apps continue to use their reviewed scope and authorization-parameter allowlists.

The provider still decides whether to issue a refresh token. Existing grants without one require another sign-in; reconnect also discovers refresh support for older generic connections that already cached their OAuth endpoints. Transport failures and provider-revoked refresh tokens are separate errors.

Local OAuth expiry simulation

Run the standalone MCP/OAuth test server with no external credentials:

node scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjs

It binds only to 127.0.0.1 and prints an MCP URL. Add that URL through Apps → Connect an app → Connect your own MCP server on a local/private Paperclip instance with a loopback HTTP callback URL, approve the test consent page, and use read_status. Access tokens last two minutes; later calls should refresh without another sign-in. Stop the fixture with Ctrl-C; all provider state is in memory.

The fixture separates the MCP resource's mcp:read scope from the identity provider's offline_access scope. It issues refresh tokens only with offline consent and a registered refresh grant, enforces PKCE/client/resource binding, rejects expired access tokens, and rotates refresh tokens after every use. Diagnostics record only protocol events and scope names, never token values.

Run the fixture controls and Paperclip integration regressions:

node --test scripts/mcp-fixtures/servers/oauth-refresh-fixture.test.mjs
pnpm exec vitest run server/src/__tests__/generic-mcp-connection.test.ts

The integration tests use actual loopback HTTP and a disposable PostgreSQL database. They cover shared and personal sign-in, a successful gateway tool call, two expiry/refresh rotations without another sign-in, scope overrides, unsupported refresh, and reconnecting a legacy cached connection. Provider time and cached expiry timestamps are advanced explicitly, so no real-time wait is needed. The standalone controls prove that omitting offline scope or consent creates an access-only grant that loses MCP access after expiry.

Curated definitions remain optional

A curated definition matching a pasted endpoint is offered as a branded shortcut beside the generic form — never instead of it. A definition adds labels, logos, field validation, scoped defaults and support copy. It does not unlock a separate execution capability, and it must not create a second connection or change ownership.

The bespoke PostHog connection is the worked example: it is the polished route for most users, and PostHog is also connectable generically through this page with either a key or browser sign-in.

Verifying

Deterministic coverage lives in server/src/__tests__/generic-mcp-connection.test.ts uses a simulated MCP/OAuth provider and a real loopback HTTP server for the personal public-URL regression. It needs no vendor credentials. Tests create an isolated PostgreSQL database and close their servers after use. A credentialed vendor smoke (for example live PostHog OAuth) may be recorded by QA but is not required for deterministic verification.

Opt-in generic Notion live smoke

pnpm smoke:notion-generic-live exercises the generic Advanced → Paste a config route against https://mcp.notion.com/mcp. It is intentionally outside the normal unit, browser, and CI-required suites. Run it only against an already-running, browser-reachable HTTPS Paperclip instance with these bindings provided by the execution environment:

  • PAPERCLIP_E2E_BASE_URL, PAPERCLIP_E2E_EMAIL, and PAPERCLIP_DEV_LOGIN_PASSWORD for the target instance;
  • PAPERCLIP_API_URL, PAPERCLIP_API_KEY, PAPERCLIP_RUN_ID, and PAPERCLIP_TASK_ID for the control plane;
  • the approved on-demand secret binding access.notion_generic_flow_test_account, delivered by the agent secret API under its normalized key generic-flow-test-account, for the existing Notion test account.

If that account requires an emailed one-time code, also set AGENTMAIL_API_KEY and NOTION_AGENTMAIL_INBOX_ID for the already-configured forwarding inbox. The smoke loads the AgentMail SDK only after Notion presents the code challenge, accepts only a fresh authenticated Notion message, fills the code once in memory, and never records the message, address, or code.

Check the URL, health endpoint, and binding metadata without retrieving the credential value or opening a browser:

pnpm smoke:notion-generic-live -- --dry-run

The live command retrieves the credential only after the safe preflight and Paperclip login succeed. It disables trace, video, and HAR capture, takes only post-callback screenshots, enables and invokes only notion-get-self, proves notion-create-pages remains locally denied, and removes its uniquely named connection in a finally cleanup. Its summary.json and PNG files contain sanitized IDs, decisions, outcomes, and endpoint origins/paths only; they default to PAPERCLIP_RUN_SCRATCH_DIR, or to NOTION_EVIDENCE_DIR when set.

Run the credential-free harness checks with:

node --test scripts/smoke/notion-generic-live.test.mjs