docs(connections): modularize connector playbook and add create-connector skill (#23384)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - App connectors let agents interact with external tools, suites, REST
APIs, and chat channels under instance governance
> - `doc/connections/CONNECTOR-PLAYBOOK.md` grew to 2,968 lines (171 KB)
and accumulated stale guidance on `rest_api` adapters and setup UX, with
no upfront research-and-interview gate to aim new connectors at user
expectations
> - An autonomous agent cannot reliably build a new connector in one
command when the playbook mixes every track together and defaults
blindly to remote MCP
> - This pull request splits the playbook into a concise router plus six
load-on-demand track guides and adds the
`.agents/skills/create-connector` skill
> - The benefit is that agents and contributors audit official vendor
docs up front, recommend the right architecture track, and load only the
guidance needed for that connector

## Linked Issues or Issue Description

**Issue type**
Outdated (no longer matches behavior)

**Where is the issue?**
`doc/connections/CONNECTOR-PLAYBOOK.md`, `doc/connections/README.md`,
`.agents/skills/create-connector/`

**What's wrong?**
`doc/connections/CONNECTOR-PLAYBOOK.md` was a 2,968-line monolith that
still claimed `rest_api` is not exposed through the gateway (despite
`rest-registry.ts`, `browser-use-cloud`, and
`google-workspace-rest-tools`), contradicted itself on one-screen setup
vs. a two-step Access → Connect flow, and jumped straight into MCP
endpoint probing without an official-docs feasibility audit or product
alignment interview.

**Suggested fix**
Refactor `CONNECTOR-PLAYBOOK.md` into a short canonical router +
universal invariants contract, move track-specific details into
`doc/connections/tracks/`, and add `.agents/skills/create-connector/`
with a mandatory Research-First → Proactive Recommendation & Interview
gate.

## What Changed

- Refactored `doc/connections/CONNECTOR-PLAYBOOK.md` from 2,968 lines to
184 lines (Phase 0 official-docs feasibility audit & interview, 6-track
selection matrix, universal invariants, canonical one-screen setup UX,
production validation matrix, preserved inbound anchors).
- Created six focused track guides and one deep reference under
`doc/connections/tracks/`:
  - `remote-mcp.md` (Track A)
  - `rest-adapter.md` (Track B)
  - `managed-oauth-suite.md` (Track C)
  - `connector-skills.md` (Track D)
  - `chat-channel.md` (Track E)
  - `local-and-aggregators.md` (Track F)
- `app-definition-reference.md` (field reference, troubleshooting,
provider attribution, proposal template)
- Added `.agents/skills/create-connector/SKILL.md` and
`.agents/skills/create-connector/brief-template.md` implementing the
one-command connector workflow with three explicit human Stop Gates.
- Updated `doc/connections/README.md` to link the modular playbook,
track guides, and `create-connector` skill.

## Verification

- Verified all relative markdown links across all 11 created/modified
files resolve to existing files with zero broken links.
- Verified `git diff --check` passes cleanly on all modified and added
files.
- Confirmed all existing inbound anchors to `CONNECTOR-PLAYBOOK.md`
(`#step-9-align-with-production-validation`, `#chat-channel-connectors`,
`#question-experience-inventory`,
`#retain-inspectable-per-format-evidence`) remain intact.

## Risks

- Low risk: documentation and agent-skill changes only; no runtime,
schema, or UI code is modified.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, tool use and code
execution enabled)

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-01 16:33:39 +00:00
1 parent 176cb8eee2
commit 8403e1c4ce
11 files changed
+913 -2966

No files matched your search

File diff suppressed because it is too large. Load diff
+12 -14
View File
@@ -3,13 +3,10 @@
Audience: internal engineers and product contributors working on integrations.
Start here when adding a provider:
[Connection authoring runbook](./CONNECTOR-PLAYBOOK.md). It is the canonical
agent tutorial from provider research and protocol classification through
manifest generation, branding, secrets, deterministic tests, real-account
proof, and PR submission.
[Connection authoring playbook](./CONNECTOR-PLAYBOOK.md) (or invoke the [`create-connector`](../../.agents/skills/create-connector/SKILL.md) skill). It routes every new integration through primary-source research, a product alignment interview, and the matching implementation track ([Remote MCP](./tracks/remote-mcp.md), [REST Adapter](./tracks/rest-adapter.md), [Managed OAuth Suite](./tracks/managed-oauth-suite.md), [Connector Skills](./tracks/connector-skills.md), [Chat Channel](./tracks/chat-channel.md), or [Local/Aggregator](./tracks/local-and-aggregators.md)).
Chat and email channels: [conversation-channel contract](./CONNECTOR-PLAYBOOK.md#chat-channel-connectors),
[question inventory and quality bar](./CONNECTOR-PLAYBOOK.md#question-experience-inventory),
Chat and email channels: [conversation-channel contract](./tracks/chat-channel.md),
[question inventory and quality bar](./tracks/chat-channel.md#question-experience-inventory-q01q11),
and [per-provider question coverage index](./CHAT-QUESTION-COVERAGE.md).
Runtime authentication: [AI Connections](./AI-CONNECTIONS.md).
@@ -31,8 +28,8 @@ organization connections where no person signs in).
Long-term memory: [Experimental memory connectors](./MEMORY.md).
Provider notes: [AWS](./AWS.md), [Google Workspace](./GOOGLE-WORKSPACE.md),
[Gmail](./GMAIL.md), [Asana](./ASANA.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md),
Provider notes: [Google Workspace](./GOOGLE-WORKSPACE.md),
[Gmail](./GMAIL.md), [AWS](./AWS.md), [Asana](./ASANA.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md),
[1Password](./1PASSWORD.md), [Unikraft](./UNIKRAFT.md), [AgentMail](./AGENTMAIL.md), [Telem.AI](./TELEM.md), [iMessage Photon](./IMESSAGE-PHOTON.md),
[Enterpret](./ENTERPRET.md), [Supabase](./SUPABASE.md), and
[Vercel](./vercel.md). Optional credential custody:
@@ -124,7 +121,7 @@ identity-service documentation or re-deriving it.
| **P3. Login with Paperclip** | *Who may authenticate against us?* | `paperclip-id` OIDC provider + DB-backed client registry | Our ES256 ID/access tokens issued *by* us to registered RPs (instances, the broker, future third parties) |
Everything in `doc/connections/` — the [First-30 matrix](./FIRST-30-MATRIX.md),
the [connection authoring runbook](./CONNECTOR-PLAYBOOK.md), and the connect-broker work —
the [connection authoring playbook](./CONNECTOR-PLAYBOOK.md) and its track guides, and the connect-broker work —
lives on **plane P2**. It never acquires, stores, or brokers a P1 sign-in token.
### The standing rule (D7)
@@ -195,11 +192,12 @@ not own durable tokens.
- [Connecting any remote MCP server](./GENERIC-REMOTE-MCP.md) is the baseline:
how an operator connects a standards-compliant remote MCP endpoint with no
Paperclip code change, and how sign-in resolves a client.
- [Connection authoring runbook](./CONNECTOR-PLAYBOOK.md) is the one
end-to-end, agent-executable guide for adding a vendor as a catalog entry on
Apps v2: research, connection-type selection, OAuth/API-key/generated-URL
setup, encrypted credential handling, branding, implementation, browser and
live-provider testing, verification, and PR submission.
- [Connection authoring playbook](./CONNECTOR-PLAYBOOK.md) (paired with the
[`create-connector`](../../.agents/skills/create-connector/SKILL.md) skill) is
the canonical router and universal contract for adding a connector on Apps v2:
Phase 0 primary-source research and product alignment, universal security and
UX invariants, production validation, and routing into the modular track
guides under `doc/connections/tracks/`.
- [Vercel Connect operator guide](./VERCEL-CONNECT.md) documents the optional
external credential source, deployment flags, runtime resolution, recovery,
and smoke requirements.
@@ -0,0 +1,149 @@
# AppDefinition Reference, Troubleshooting & Appendices
Deep reference extracted from [CONNECTOR-PLAYBOOK.md](../CONNECTOR-PLAYBOOK.md). Load this only when authoring or debugging `AppDefinition` fields, troubleshooting connector failures, writing a standalone connector proposal, or configuring provider app attribution.
## AppDefinition Field Reference
### App-level fields
| Field | Meaning and rule |
| --- | --- |
| `schemaVersion` | Must be `1`. Change only with a versioned migration plan. |
| `slug` | Stable lowercase kebab-case identity. Never rename after connections exist without a migration. |
| `name` | Provider/product name shown to users. |
| `description` | Plain-language outcome, not protocol marketing. |
| `categories` | One or more supported catalog categories. |
| `featured` | Optional merchandising signal, not availability. |
| `branding` | Local official `logoUrl`, optional `darkLogoUrl`; ingestion derives this from provenance. |
| `urlPatterns` | HTTPS patterns used to recognize pasted/generated provider URLs. Keep narrow enough to reject lookalikes. |
| `docsUrl` | Current official setup/protocol docs. |
| `setupPrerequisite` | Prerequisite users must understand or complete before credentials/consent. Includes CTA and optional ordered steps. |
| `redirectConstraints` | Currently `https-or-loopback-http`; fail before provider navigation when violated. |
| `methods` | Every genuinely supported connection method. At least one. |
| `availability` | Instance/provider availability and user-facing reason. Unavailable entries must not expose a dead action. |
| `ownershipAvailability` | Deployment override for ownership modes. Defaults currently enable `customer` and `dcr`, disable platform modes. |
| `experimentalFeatureKey` | Optional experimental flag key; shared availability checks enforce it before setup, discovery, and execution. |
| `agentInstructions` | Optional `{ id, version, text }` standing guidance template authored in `packages/shared/src/app-definitions/<slug>.json`. |
### Method fields
| Field | Meaning and rule |
| --- | --- |
| `key` | Stable method key stored on the connection as `connectionMethodKey`. |
| `label` | User-facing method label. Required in practice when multiple methods exist. |
| `transport` | `mcp_remote`, `local_stdio` (approved templates only), or `rest_api` (reviewed adapters only). |
| `auth` | `oauth`, `api_key`, or `none`. (Model bot/installation tokens via secret/grant architecture; do not invent a 4th auth enum.) |
| `ownershipModes` | Allowed OAuth client ownership modes (`dcr`, `customer`, `platform_shared`, `platform_provisioned`); also present for non-OAuth customer config. |
| `oauthStrategy` | Managed broker strategy. New definitions use `paperclip_cloud_connector`; `paperclip_id_connector` is legacy-migration-only. OAuth only. |
| `connectorProfile` | Managed connector capability/scope profile; required with `oauthStrategy`. |
| `oauthClientRegistration` | Optional `"dcr"` compatibility override when live evidence proves CIMD fails while DCR succeeds (requires `dcr` in `ownershipModes`). |
| `capabilityProfile` | User-facing read/write/mode grouping used for method selection. |
| `grantKinds` | Restricts identity to `organization`, `user`, and/or `agent`; omit for flexible methods. An `agent` method connects for exactly one chosen agent. |
| `whenToUse` | One sentence distinguishing this method from alternatives. |
| `defaults.serverUrl` | Exact fixed endpoint. For discovery-capable OAuth, omit fixed auth endpoints. |
| `defaults.serverUrlTemplate` | HTTPS endpoint with placeholders supplied by declared tenant/extension fields. Mutually exclusive with `serverUrl`. |
| `defaults.discoveryUrl` | Provider-specific discovery override only when reviewed metadata requires it. |
| `defaults.authorizationEndpoint` / `tokenEndpoint` | Authoritative fixed endpoints; ship only when provider lacks trustworthy discovery. |
| `defaults.metadataUrl` | Authorization metadata hint. |
| `defaults.scopesHint` | Explicit reviewed allowlist. Omit when docs do not require one; never copy every discovered scope. |
| `defaults.oauthAuthorizationParams` | Reviewed `access_type=offline` and/or `prompt=consent` behavior. |
| `defaults.toolArgumentDefaults` | Server-owned provider protocol arguments, hidden from caller schemas and authoritative on collision. |
| `tenantFields` / `extensionFields` | Account/project/region/resource and method-specific config fields. Mark optional narrowing `advanced: true`. |
| `configRequirements.atLeastOneOf` | Requires one of named tenant/extension fields. |
| `credentialFields` | Write-only secret/non-secret credential inputs (`secret: true` for write-only secrets). |
| `keyPlacement` | Provider request placement (use proven header path on `mcp_remote`). |
| `guidanceMd` | Setup and scoping guidance. No secrets or internal env-var names. |
| `consoleLinks` | Official registration, key, settings, and docs URLs. |
| `warnings` | Plan, preview, admin, financial, production-data, or destructive-action caveats. |
| `riskTier` | `S1` (low-risk reads), `S2` (business data/narrow writes), `S3` (broad content/ops), `S4` (payments, external sends, prod changes, deletion, tenant admin). |
| `requiredResourceFilters` | Reviewed resource boundaries — must be backed by server/wrapper enforcement, not only copy. |
| `credentialSources.vercelConnect` | Reviewed services, principal modes (`app`/`user`), scopes, and header placement for the Vercel Connect exception (authenticated `mcp_remote` only). |
### `FieldDef` Rules
Supports `text`, `password`, `textarea`, `datetime`, `select`, `checkbox`:
- Required non-checkbox fields need a `placeholder`.
- `select` needs at least one option; hidden fields need a `defaultValue`.
- `secret: true` only for write-only credential inputs; never smuggle secrets into tenant/extension config.
- `validation.pattern` is a JS regex string; always pair with a practical `maxLength`.
- `transport.location: "query"` modifies the normalized server URL; `"header"` creates a managed non-secret config header (distinct from `keyPlacement`).
- CSV fields deduplicate comma/newline-separated values; `omitFalse` prevents a false checkbox from projecting a query/header value.
---
## Troubleshooting & Failure Classification
| Symptom | Likely layer | What to inspect |
| --- | --- | --- |
| Store says Coming soon or Connect route is dead | Definition / availability / routing | `CONNECTABLE_APP_SLUGS`, store hidden set, method capability checks, `Browse.test.tsx`. |
| Direct `?source=<slug>` shows generic chooser | UI route state | `AppsConnect`, source slug lookup, availability. |
| Finish setup opens Edit config instead of resuming | Draft identity / resume | `resumeConnectionId`, stored `sourceTemplateKey`, `connectionMethodKey`, draft status. |
| OAuth never redirects | Method capability / client resolution | `ownershipModes`, metadata discovery, callback origin, manual-client requirement. |
| Provider rejects redirect URI | Deployment / provider rule | Actual browser origin, `PAPERCLIP_PUBLIC_URL`, `redirectConstraints`, provider app registration. |
| OAuth succeeds then immediately needs reconnect | Grant / secret sync or refresh | Org vs. user grant, token refs, default grant sync, expiry/refresh lease, `invalid_grant`. |
| Tools list but calls return 401 | Token audience / scope / placement | RFC 8707 `resource`, `scopesHint`, header prefix/name, endpoint path. |
| Health works but Test call fails | Gateway projection / policy | Selected grant, managed headers/args, effective profile/policy, catalog entry risk/status. |
| Required provider boilerplate appears in Test | Managed schema projection | `toolArgumentDefaults` and `projectedConnectionToolInputSchema`. |
| API key saves but is not sent | Placement or missing ref | `credentialFieldsFor`, `keyPlacement`, connection/grant refs, gateway header resolution. |
| New tool is classified `read` unexpectedly | Risk inference | Annotations, verb normalization, provider exception set, fixture. |
| Connection from another company is visible | Authorization bug | **Stop immediately**; add company-scope negative tests before any further testing. |
| Raw credential appears anywhere | Security incident | **Stop, revoke/rotate credential**, remove evidence, trace response/log/audit paths, add canary regression test. |
When a bug appears on one provider, reproduce it with a fixture or a second provider of the same auth/transport type. Fix the shared path when generic; keep provider workarounds narrow and documented.
---
## Provider App Attribution (AI / Router Providers)
When a provider supports application attribution (e.g., OpenRouter), credit Paperclip for managed requests using public product identity only — never company name, user ID, task, credential, or instance URL.
- OpenRouter policy lives in `packages/shared/src/openrouter-attribution.ts` (`HTTP-Referer: https://paperclip.ing`, `X-OpenRouter-Title: Paperclip`, `X-Title: Paperclip`, `X-OpenRouter-Categories: cloud-agent,programming-app`), applied only to actual OpenRouter endpoints (`openrouter.ai`, `eu.openrouter.ai`, `us.openrouter.ai`), never inferred from model names or repointed aliases.
- Verify outgoing headers from each pinned harness/SDK (Codex, Claude, OpenCode, Hermes, Pi), custom aliases, mixed-case conflicts, unrelated providers, secret safety, and a small live request. Record coverage limits explicitly.
---
## Documentation Standards for Per-Provider Connection Docs
Every provider doc under `doc/connections/<PROVIDER>.md` must include:
1. **Service involvement statement:** Explicitly state whether Paperclip ID or Paperclip Cloud broker participates (for RFC 7591 DCR, always "neither — DCR is instance-local").
2. **Sequence diagram + exact endpoints:** Mermaid diagram (no semicolons inside message text) plus exact authorize, token, registration, discovery, and callback paths.
3. **Administrator setup instructions:** What an admin must register (if anything), where, instance prerequisites, and end-to-end verification steps.
4. **Provider consent interaction guards:** Note any intentional provider UI delays (e.g., Sentry's 1-second Approve delay after pointer/keyboard interaction) so smoke tests do not misclassify them.
---
## Standalone Connector Proposal Template
```md
## Vendor
- App key / name / owner:
- Track: A (Remote MCP) / B (REST Adapter) / C (Managed OAuth Suite) / D (Skill/Instructions) / E (Chat Channel) / F (Deferred/Aggregator)
- Reason for track choice (and why a lighter path is or isn't enough):
- Security tier: S1 / S2 / S3 / S4
## User Jobs (Top 3–5)
1. ...
## Transport & Auth
- Transport & endpoint(s):
- Auth mode & OAuth client ownership:
- Scopes (exact reviewed allowlist):
- Grant identity (`user` / `organization` / `agent`):
- Secret storage (`paperclip_vault` / `vercel_connect`):
- Revocation behavior:
## Connection Flow (mandatory)
- Sequence diagram (Mermaid):
- Auth endpoints (authorize / token / registration / discovery / callback):
- Redirect constraints (probed):
- Paperclip ID / Paperclip Cloud broker involvement:
## Administrator Setup (mandatory)
- What the admin must register & where:
- Instance prerequisites (TLS, base URL, experimental flag, Cloud broker profile):
- How to verify end to end:
## Actions & Governance
| Tool | Risk | Default status | Resource filters | Negative test case |
| --- | --- | --- | --- | --- |
```
+82
View File
@@ -0,0 +1,82 @@
# Track E: Chat & Conversation Channels
A tool connection gives an agent actions it can call. A **chat channel connector** makes Slack, Teams, Discord, Telegram, email, or another conversation surface a place where a person can conduct work with an agent — carrying questions, decisions, follow-ups, and results through the conversation. Authentication, tool discovery, and a single outbound message do **not** qualify a chat channel.
A provider can offer both a tool connection and a chat channel (e.g., Slack user MCP vs. Slack bot channel); keep them separate and do not assume one implements the other.
> **Companion UX doc:** Also follow [CHAT-CONNECTOR-UX.md](../CHAT-CONNECTOR-UX.md) for step navigation, footer layout, credential instructions, provider handoffs, identity linking, optional message tests, and management pages.
>
> **Voice note:** Experimental voice connections use the same company-scoped channel endpoints, vault, task bindings, delivery ledger, and publications with `transport: voice` and an explicit runtime rather than Chat SDK. Never expose voice transport as an MCP tool connection.
## Platform Boundaries & Reuse
- Reuse company-scoped endpoints, verified identity links, task/conversation bindings, durable interactions, publication queues, and response-delivery receipts.
- Keep provider payloads, UI limits, and callback protocols in their platform module; follow [chat-channel-platform-boundaries.mdc](../../../rules/chat-channel-platform-boundaries.mdc).
- For Slack bot task tools, see [SLACK-TASK-TOOLS.md](../SLACK-TASK-TOOLS.md). For automatic Slack app setup, see [SLACK-AUTOMATIC-SETUP.md](../SLACK-AUTOMATIC-SETUP.md).
## Cover Every User-Question Form
For a new channel, build a capability matrix from the current shared interaction kinds, payload validators, and runtime/composer question entry points (`ISSUE_THREAD_INTERACTION_KINDS` in `packages/shared/src/constants.ts`, `packages/shared/src/types/issue.ts`, `packages/shared/src/validators/issue.ts`). Do not treat this table as frozen:
| Request family | Required coverage |
| --- | --- |
| `ask_user_questions` and runtime/composer input questions | Free text, single-select, multi-select, multiple questions, custom answers, editable starting text (legacy payloads + canonical `paperclip.question_set.v1`). |
| `request_confirmation` | Decision, supporting context, and accept/reject outcome. |
| `request_checkbox_confirmation` | Options, selection constraints, and exact submitted selection. |
| `request_item_verdicts` | Each item, its evidence/context, and individual decisions. |
| `suggest_tasks` | Proposed tasks and per-proposal decision. |
| `connection_intent` | Requested connection/access, purpose, and authorized setup/review path. |
| Approval or runtime permission requests outside interaction kinds | Explicit route to the existing authorized approval surface; a chat response must not create new approval authority. |
## Question Experience Inventory (Q01–Q11)
These IDs are shared with [CHAT-QUESTION-COVERAGE.md](../CHAT-QUESTION-COVERAGE.md):
| ID | Experience | Preferred interaction when supported |
| --- | --- | --- |
| Q01 | Free text | Native text entry with full prompt, context, editable starting text, multiline support. |
| Q02 | Short, closed single choice | Direct labeled buttons with descriptions/recommendations; avoid a modal for one simple choice. |
| Q03 | Long option single-select | Inline searchable picker preserving complete labels and selected value. |
| Q04 | Multiple selection | Checkboxes or multi-select with explicit submit action and visible selection bounds. |
| Q05 | Choice plus custom answer | Choice controls + explicit **Other…** text-entry path (test both listed and custom answers). |
| Q06 | Validated text | Text entry with expected format/example, field-level errors, and retained editable draft after invalid input. |
| Q07 | Ordinary confirmation | Clear accept/reject controls with decision and context visible; governed actions retain canonical review rules. |
| Q08 | Checklist confirmation | Labeled selections, descriptions, editable defaults, bounds, explicit save, and rejection where supported. |
| Q09 | Per-item verdicts | Decision per item, evidence/context, conditional reasons, canonical atomic or partial-resolution semantics. |
| Q10 | Suggested tasks | Direct creation for one proposal; selection + **Create selected** for several; dismissal + review/edit handoff; links to created tasks. |
| Q11 | Connection request | Explain requested access and purpose; usable link to exact authenticated review and native decline when supported; a link click never grants access. |
Also cover applicable variants under each ID: runtime input vs. composer vs. legacy vs. canonical payloads; multiple questions and repeated Yes/No labels; required/optional, Unicode, long labels; control-selection thresholds (just below, at, and above provider button/option/text/block/modal limits); accepted/rejected/dismissed/cancelled/expired/superseded outcomes, duplicate callbacks, revoked access, and recovery.
## Choose and Record the Best Available Response Path
Maintain a per-provider matrix linked from [CHAT-QUESTION-COVERAGE.md](../CHAT-QUESTION-COVERAGE.md):
- Every applicable form needs a usable path from the originating conversation: native controls, structured reply flow, or an explicit link to the exact Paperclip question/review surface. Silently omitting a request is a defect.
- Show the actual question and context, preserve validation and editable drafts, respect provider block/option/modal limits (with an excerpt + Paperclip link for oversized forms — never silent truncation), and keep saved answers/verdicts readable after controls settle.
- Apply safe external-text projection and audience rules; keep secrets/restricted content on the authenticated Paperclip surface.
- Bind responses to persisted question, conversation, and verified actor; recheck access, resolver audience, target freshness, and endpoint authority using the authoritative resolution service.
- Persist once with idempotent continuation and delivery receipts; reflect accepted, rejected, expired, and superseded outcomes in the original card or follow-up; reconcile stale cards automatically.
- Task links in chat must use the server-resolved public board origin (never internal API or webhook ingress URLs).
## Verify, Grade, and Retain Inspectable Evidence
Qualify every applicable matrix row through the real provider:
`request → visible question/context → response → persisted resolution → intended continuation → settled card and result in originating conversation.`
Grade each row independently:
| Judgment | Pass standard |
| --- | --- |
| Functional result | Exact answer/decision saved, authorization preserved, canonical continuation runs once, intended result delivered in originating conversation. |
| Good experience (✓/✕) | User can understand, answer, recover from invalid input, and read the settled outcome without guessing. |
| Best feasible experience (✓/✕) | Uses provider capabilities well — no avoidable modal, browser hop, or lost context; every handoff has a concrete capability/validation/auth reason. |
Produce a browsable HTML gallery (or equivalent) capturing **actual provider screens** per format and variant:
- **Unanswered:** full question/context and controls.
- **Answering:** open picker/modal or selected values, including invalid input + preserved draft for validation cases.
- **Answered:** settled card with permitted saved answer/labels/verdicts/reasons + resumed result or review receipt.
- **Handoffs & artifacts:** click review and created-result links and verify the authenticated destination and created artifact.
Correlate captures with saved responses, actor/authority, continuation count, and delivery receipts. Record candidate revision, date, adapter config, live-model vs. fixture status, and retained failure history. Update [CHAT-QUESTION-COVERAGE.md](../CHAT-QUESTION-COVERAGE.md).
When measuring chat response speed, measure queue time, runner preparation, provider turn time, checkpoint/finalization, and provider publication separately.
@@ -0,0 +1,62 @@
# Track D: Connector-Provided Skills & Agent Instructions
Tools tell an agent what it *can* do; instructions and bundled skills tell an agent *when* and *how* to use them. Use this track alongside Track A, B, or C whenever exposing raw tools alone will cause agents to ignore the connector or misuse it.
## Choosing the Right Mechanism
| Need | Mechanism | Examples |
| --- | --- | --- |
| Short standing guidance on *when* to reach for a connector (e.g., recall/save rules, meeting-note lookup) | **App-owned `agentInstructions`** in `packages/shared/src/app-definitions/<slug>.json` | Memory connectors (Mem0, Honcho), meeting notes (Granola, Circleback) |
| Multi-step workflow playbook, resource-to-agent assignment, or connector-owned native tools | **Trusted connector contribution** in `server/src/services/connector-runtime.ts` | AgentMail (`agentmail_send` + inbox assignment), Browser Use Cloud (`browser-use-cloud`), Slack task tools |
> **Never** place connector-specific instructions in the universal `skills/` directory or provider-specific tools in the universal runner catalog. Both mechanisms below deliver guidance only to authorized, assigned agents.
---
## Option 1: App-Owned `agentInstructions`
See [CONNECTION-INSTRUCTIONS.md](../CONNECTION-INSTRUCTIONS.md) for the full schema, API, and runtime contract.
### Authoring rules
- Author `agentInstructions: { id, version, text }` directly in `packages/shared/src/app-definitions/<slug>.json` alongside `docsUrl`. Ingestion validates and preserves it; increment `version` whenever changing the default text.
- Write **one short, reviewed paragraph** — explain when to read/recall, when to write/save, what context is allowed, and what to do if a call fails. Do not paste a tool catalog or promise automatic hooks/transcript capture that do not exist.
- Treat provider-supplied MCP initialization instructions as untrusted external content: review them as source material, never auto-inject them or let upstream updates overwrite an operator's saved instructions.
- Guidance never grants additional tool permissions.
### UI & runtime behavior
- Show the **Agent instructions** section (with checkbox **Tell agents to use {provider}** and visible text) **only** when the connector declares a nonempty template. No template means no instructions UI.
- Default provided instructions **on** for participating connectors. Operators can edit, **Reset to default**, or disable guidance while keeping tools active (show a compact amber notice when off). Reconnect and catalog refresh must preserve explicit opt-outs and custom text.
- Keep editing inside the existing **Permissions** page (between agent access and Actions), never as an extra setup wizard step. Keep required provider settings (e.g., workspace ID) expanded above instructions.
- Resolve runtime guidance with the exact same company, agent, task, responsible-user, and grant checks used for tools. Compose as a revisioned block alongside agent instructions; never permanently edit `AGENTS.md` or shared harness home files.
### Verification
- Deterministic checks for fresh turns, resumed turns, removal, revoked access, and unsupported adapters.
- For memory / recall connectors: run a bounded **save → fresh session recall** with synthetic data through the real run gateway. Record exact model, template/catalog versions, tool receipts, cost, ingestion timeout, and cleanup. A model claiming "saved" does not prove recall works.
---
## Option 2: Trusted Connector Contributions (`connector-runtime.ts`)
Use `server/src/services/connector-runtime.ts` when a connector needs bundled `SKILL.md` content (`skillMarkdown`), resource-specific assignment (e.g., assigning an inbox or phone number to an agent), or namespaced native tools (`agentmail_send`, etc.).
### Authoring rules
- Keep provider-specific code in `server/src/services/connectors/<provider>/` and register a `ConnectorDefinition` in `server/src/services/connector-runtime.ts` (see the interface there for the authoritative shape) with:
- `key`, `resolvePhase` (`Extract<ExecutionPhase, \`connectors.${string}.resolve\`>` — add the corresponding `ExecutionPhase` literal when introducing a new connector), `label`, `skillName`, optional `skillMarkdown` (materialized only for authorized assignments), `legacySkillKeys` (if retiring old keys), namespaced `tools`, `resolve(db, binding)`, and `execute(db, binding, name, value)`.
- Existing MCP connectors continue using their normal MCP catalog — do **not** write duplicate native tool wrappers just to supply a skill.
- If the connector is gated behind an experimental flag, declare `experimentalFeatureKey` in its `AppDefinition`; shared availability checks enforce it before setup, discovery, and execution.
- If the connector assigns a resource to a specific agent (like AgentMail's "Give an agent an email address"), keep that in a **second wizard launched from the saved connection's Permissions view**, reusing the saved credential rather than mixing resource assignment into initial connect.
### Eligibility, Isolation & Revocation Invariants
1. **Concrete assignment rule:** An account credential alone may not imply agent capability (e.g., AgentMail requires an active assigned inbox plus authorized credential access). Every lookup must be company-scoped and fail closed on lookup errors. Revoked grants, disabled connections, removed assignments, or disabled experimental flags must remove the contribution immediately.
2. **Transparent, isolated skill delivery:**
- Merge system-managed contributions into the run's skill bundle without mutating the agent's saved skill preferences. Deduplicate multiple resources from the same connector into one skill.
- Include only authorized resource context, never provider secrets; treat resource values as data.
- Isolated adapters receive the materialized skill bundle; shared-directory adapters receive the same assigned skill in the run prompt (including resumed turns) without writing connector files into shared user directories.
- Never contaminate a company-wide or user-wide runtime home (Codex CLI uses a separate home per agent and connector-skill revision). Disconnecting must return to a runtime without those skills; another agent must never inherit them.
- Manual skill-sync operations must exclude automatic connector bundles; the agent Skills page marks them as automatic and controlled by assignment.
3. **Runtime enforcement on every call:** Bind native tool advertisements to the pinned runtime skill bundle and include skill content, resource assignments, and tool revisions in session compatibility hashes. Revalidate live assignment, company/task/run authority, and configured action policy on every `execute()` call — removing a tool from discovery alone is not revocation enforcement.
### Required Tests
- No assignment, credential access without an assigned resource, authorized assignment, multiple resources deduplicated to one skill, cross-company denial, revocation during a retained run, disabled flags/connections, and reassignment.
- Verify skill installation and removal in both CLI/sandbox and native execution (including cache/revision invalidation and absence of provider secrets).
- Execute at least one actual connector operation through the contributed tool (record live vs. deterministic coverage explicitly).
@@ -0,0 +1,36 @@
# Track F: Local-Only, Unreachable, or Aggregator-Routed Providers
Not every requested vendor should become a native Paperclip connector immediately. Use this track when primary-source research shows that:
1. The vendor only offers a **local/desktop MCP server** (`localhost` / `local_stdio`) that a Cloud-hosted Paperclip instance cannot reach,
2. The vendor requires **Paperclip-level vendor approval** or closed partner allowlisting that blocks self-serve users, or
3. An **MCP aggregator** (Composio, Arcade, Executor, Zapier) already covers the vendor while a native connector is deferred.
## 1. Local-Only / Unreachable Providers (Go / No-Go Rule)
- **`local_stdio` is never a manifest-only shortcut.** Local stdio MCP is supported only through explicitly registered, reviewed command templates on a trusted local runtime host, and is disabled in authenticated/public Cloud deployments without that host. Never put an arbitrary CLI command in an `AppDefinition`.
- If a vendor's only MCP or API surface runs on the user's laptop (e.g., a desktop-only app with a local socket/port and no remote HTTP API), **stop during the Connector Brief** and tell the user clearly:
- It cannot work for Paperclip Cloud users without a remote API/MCP or a supported local-runner bridge.
- Record the research finding in `packages/shared/src/self-serve-mcp-research.json` (with an explicit unavailable reason) and do **not** expose a broken Connect card in the Apps gallery.
- Similarly, if a provider requires vendor-side approval of Paperclip itself before any customer can connect, keep the research record unavailable (or behind an `experimentalFeatureKey` while approval is pending) rather than shipping a dead Connect button.
## 2. How Native Connectors Interact With MCP Aggregators
Paperclip combines native `AppDefinition` entries with public aggregator snapshots (Composio and Arcade in `packages/shared/src/aggregator-app-catalog.ts`, plus routing in `packages/shared/src/connection-routing.ts`).
### Precedence & Discovery Rules
- **Native definitions always win** over aggregator routes in both `connections_search` and the Connectors gallery — including native definitions that are temporarily hidden or unavailable on the instance.
- When adding a **new native connector** for a service that previously appeared via Composio or Arcade:
- Confirm the slug and aliases align cleanly so native Connect offers take precedence, while any already-connected imported Composio/Arcade accounts remain visible under the canonical app card as **Via "<saved connection name>"**.
- Native onboarding appears under **Paperclip** and **All**; provider filters only include native cards that actually have accounts managed by that provider.
- When **deferring a native connector** and relying on an aggregator instead:
- Verify the service in the aggregator's official public catalog before updating `packages/shared/src/connection-routing.ts` (update only that app's verification date and aliases).
- For Arcade's public snapshot, refresh via `node scripts/update-arcade-app-catalog.mjs --verified-at YYYY-MM-DD`.
- Remember: a public catalog listing proves possible support, not that a user's gateway is configured or authorized.
### Key Aggregator Architecture Invariants (Do Not Break)
- **Gateway-wide access:** Composio, Arcade, and Executor gateways remain gateway-wide connections; Paperclip never creates child connections or broadens existing grants when authorizing an upstream app.
- **Observations are not grants:** `tool_connection_app_snapshots` and `tool_connection_app_syncs` store read-only account observations scoped to `(company, gateway, viewing human, effective credential version)` via `/api/tool-connections/:connectionId/aggregator/apps` (`/sync`, `/refresh`). They are never executable connections or authorization grants.
- **Explicit human choice for fallback:** `connections_search` owns next-step instructions. Falling back to an external aggregator requires an explicit `ask_user_questions` answer (`providerQuestion`) persisted and validated via `selectionInteractionId` in `connection_request`. A decline stays effective across continuations.
- **Direct Composio app setup vs. Arcade task draft:** Composio calls `COMPOSIO_MANAGE_CONNECTIONS` directly from the board (no task created, hosted auth link not persisted in audit/results; management console at `https://dashboard.composio.dev/~/org/connect/apps`). Arcade opens a task draft (`navigateOnCreate`) so the assigned agent verifies tools and requests human authorization via `connection_request` with frozen `toolNames`.
- **Managed inventory bounds:** Arcade discovery paginates its admin account list using a separate user-owned project key (never substituting an OAuth gateway token). Executor reads its MCP integration inventory or fixed read-only `connections.list`/`integrations.list` calls — never arbitrary generated code.
- **Acceptance fixtures:** `server/src/__tests__/aggregator-app-discovery.test.ts`, `server/src/__tests__/aggregator-app-sync.test.ts`, `ui/src/pages/apps/Browse.test.tsx`, `tests/aggregator-accounts/test-drive.ts`.
@@ -0,0 +1,69 @@
# Track C: Managed OAuth & Multi-Service Suites
Use this track when:
1. The provider **does not support self-serve DCR/CIMD** and requires a **Paperclip-owned OAuth app** with a fixed callback URL (handled through the Paperclip Cloud managed OAuth broker), **or**
2. The provider is a **multi-service suite** (such as Google Workspace or Microsoft 365) where users expect **one combined connection** with per-service read/write toggles rather than separate OAuth flows per product.
## Reference Implementations
- **Multi-service suite + managed OAuth + service consent picker:** [GOOGLE-WORKSPACE.md](../GOOGLE-WORKSPACE.md), [GOOGLE-WORKSPACE-SERVICE-CONSENT.md](../GOOGLE-WORKSPACE-SERVICE-CONSENT.md), `packages/shared/src/google-workspace-connectors.ts`.
- **Managed OAuth (personal + dedicated-agent grants):** [GITHUB.md](../GITHUB.md).
- **Cloud broker architecture & routes:** `paperclip-cloud/docs/managed-oauth-broker.md`, `paperclip-cloud/docs/google-connector-deploy-bootstrap.md`, `paperclip-cloud/docs/github-connector-deploy-bootstrap.md`.
## Deciding Whether Managed OAuth Is Needed
| Situation | Path |
| --- | --- |
| Provider supports RFC 7591 DCR or CIMD | Do **not** use Paperclip Cloud broker — use instance-local OAuth ([Track A](./remote-mcp.md)). |
| Provider has no DCR, and we want 1-click "Sign in with X" for all Paperclip users | Use **Paperclip Cloud managed OAuth** (`oauthStrategy: "paperclip_cloud_connector"`, `ownershipModes: ["platform_shared", "customer"]` so enterprises can still bring their own OAuth app under Advanced). |
| Provider requires enterprise-tenant-only app registration | Start with `ownershipModes: ["customer"]` and clear `consoleLinks.register` + callback URI guidance; add `platform_shared` only if a multi-tenant Paperclip app is viable and approved. |
## Hard Security Boundary (Plane P2 / Rule D7)
- Managed OAuth lives in **Paperclip Cloud** (`my.paperclip.app/v1/connector/...`), **never** in `id.paperclip.ing` (Paperclip ID is sign-in only).
- Paperclip Cloud handles the fixed provider callback (`https://my.paperclip.app/v1/connector/oauth/<provider>/callback`), exchanges the code, and immediately seals tokens to the originating instance's X25519 public key. Cloud **never** persists plaintext tokens.
- Durable provider tokens always live in the originating Paperclip instance's encrypted vault (`company_secrets` / user-scoped secret) under normal instance governance.
## Multi-Service Suite Design Rules (e.g., Google Workspace, Microsoft 365)
When a provider bundles multiple apps (Mail, Calendar, Drive/OneDrive, Docs, Teams, etc.):
1. **One combined connection, one grant lifecycle:** Give users a single catalog entry (`google-workspace`, `microsoft-365`) with one credential grant, one capability catalog, one policy profile, one audit trail, and one reconnect flow.
2. **Per-service read/write consent picker:**
- Start with the core v1 services enabled with read + write access (let users disable a service or switch it to read-only before consent).
- Request **only the scopes required by the selected services**, never a blanket union of every API the vendor offers.
- Persist validated service selection as non-secret setup intent on the draft (bound to company, connection, actor, grant kind, and subject) so cancelled sign-in or **Finish setup** restores the user's exact selection.
3. **Actual-grant enforcement (never trust requested scopes alone):**
- Users or tenant admins can decline individual scopes on the provider's consent screen.
- Persist the provider's actual granted scope subset, cap it against the reviewed allowlist, skip discovery for ungranted services, and recheck granted scopes in the gateway on every call (including after token refresh).
4. **Partial-outage isolation:**
- Namespace tools cleanly by service (e.g., `mail_*`, `calendar_*`, `drive_*`).
- If one service is unhealthy during discovery or invocation, disable only that service's actions and surface a clear health message — do not break healthy services. A revoked/expired shared OAuth grant still fails the whole connection cleanly.
5. **Experimental gate during vendor app verification:**
- While Paperclip's production OAuth app is pending vendor review (e.g., Google verification or Microsoft Publisher Verification), gate the built-in connector behind `experimentalFeatureKey` in its `AppDefinition`.
- When the flag is off, the Apps gallery hides the built-in connector and the server rejects setup/discovery/execution. Note that `Browse` still uses disabled native entries from `CONNECTABLE_APP_DEFINITIONS` to exclude matching aggregator cards (only the Google-specific case explicitly allows fallback), so verify aggregator fallback visibility explicitly rather than assuming it is automatic.
6. **Avoid duplicating existing standalone connectors:**
- Check for existing single-service definitions (e.g., `microsoft-teams.json`, `gmail.json`) and decide explicitly during the Connector Brief whether legacy standalone connections stay supported as-is without forced migration.
## Cross-Repo Checklist (`paperclip` + `paperclip-cloud`)
Adding a new managed OAuth provider touches **two repositories** and requires human-owned vendor console credentials:
### Human-Gated Vendor Console Setup (Stop & Escalate Gate)
- [ ] Register the multi-tenant OAuth app in the vendor's developer console (e.g., Microsoft Entra ID, Figma Developer Apps, Google Cloud).
- [ ] Configure the exact production callback URI: `https://my.paperclip.app/v1/connector/oauth/<provider>/callback` (and staging callback URI).
- [ ] Store the client ID and client secret in AWS Secrets Manager (never in git, PRs, or issue comments).
- [ ] Submit for vendor app verification if required for external users.
### `paperclip-cloud` Changes
- [ ] Register the provider & named profile(s) (with exact reviewed scope allowlists) in the Cloud connector broker registry.
- [ ] Wire callback, token exchange, refresh, and provider revocation routes under `/v1/connector/oauth/<provider>/callback` and broker endpoints.
- [ ] Add unit/integration tests covering enrollment, scope allowlist enforcement, sealed-claim expiry, refresh, and revocation.
- [ ] Document deployment bootstrap steps (matching `paperclip-cloud/docs/google-connector-deploy-bootstrap.md`).
- [ ] Deploy the Cloud broker profile **before** enabling the profile or un-gating the connector in `paperclip`.
### `paperclip` Changes
- [ ] Author `AppDefinition` with `oauthStrategy: "paperclip_cloud_connector"`, `connectorProfile`, `ownershipModes: ["platform_shared", "customer"]`, and `experimentalFeatureKey` (if gated).
- [ ] Implement service-consent picker + draft-intent persistence if multi-service.
- [ ] Implement transport layer (Track A remote MCP endpoints or Track B `rest-registry.ts` / dedicated REST tools) with per-call granted-scope verification and prompt-injection screening.
- [ ] Add deterministic tests for both managed (`platform_shared`) and customer-owned (`customer`) OAuth paths, declined/partial scopes, reconnect preserving prior choices, and experimental gate enforcement.
+181
View File
@@ -0,0 +1,181 @@
# Track A: Curated Remote MCP Connector
Use this track when the provider publishes an **official, Cloud-reachable remote HTTP MCP server** whose tool surface and read/write capabilities match what Paperclip users expect — and whose auth/fields can be represented by the common `AppDefinition` contract with zero or minimal runtime code.
> **Baseline:** An operator can already connect any standards-compliant remote HTTP MCP server through **Connect your own MCP server** or **Paste a config** with no code change (see [GENERIC-REMOTE-MCP.md](../GENERIC-REMOTE-MCP.md)). A curated catalog entry adds branding, tailored fields, validation, reviewed scope defaults, and support copy — nothing else. It converges on the exact same connection, gateway, and review pipeline.
## When NOT to use Track A alone
- The official MCP server is read-only or missing the core actions users expect → evaluate [Track B: Reviewed Native REST Adapter](./rest-adapter.md).
- The provider requires a Paperclip-owned OAuth app or spans a multi-service suite (e.g., Google Workspace, Microsoft 365) → also follow [Track C: Managed OAuth & Multi-Service Suites](./managed-oauth-suite.md).
- Agents need standing guidance on *when* to call the connector (e.g., memory or meeting notes) or bundled workflow skills → also follow [Track D: Connector-Provided Skills & Agent Instructions](./connector-skills.md).
- The MCP server is desktop/local-only (`localhost` / stdio) → see [Track F: Local-Only & Aggregators](./local-and-aggregators.md).
## Five Independent Axes
Never describe a connection as merely "an OAuth connection" or "an MCP connection." Every method chooses all five axes:
| Axis | Values | Question |
| --- | --- | --- |
| Transport | `mcp_remote` (default), `local_stdio` (approved templates only), `rest_api` (reviewed adapters only) | How does Paperclip reach actions? |
| Authentication | `oauth`, `api_key`, `none` | How does the provider authorize requests? |
| OAuth client ownership | `dcr`, `customer`, `platform_shared`, `platform_provisioned` | Who supplies and controls the OAuth client registration? |
| Credential source | `paperclip_vault`, reviewed `vercel_connect` | Where does durable provider credential material live? |
| Grant identity | `organization`, `user`, `agent` | Does the credential act for the company, one person, or one dedicated agent? |
## Authentication Support Matrix
| Pattern | Definition shape | What the user sees | What Paperclip stores |
| --- | --- | --- | --- |
| Automatic OAuth | `auth: "oauth"`, `ownershipModes: ["dcr"]` | Browser sign-in | DCR/CIMD client binding + token secret refs |
| Automatic OAuth + own-app escape hatch | `ownershipModes: ["customer", "dcr"]` | Recommended browser sign-in; own client under **Advanced** | Same as automatic, or supplied client ID + encrypted client secret |
| Customer OAuth only | `ownershipModes: ["customer"]` | Required client ID (+ secret), then browser sign-in | Client ID in redacted config; client secret & tokens as secret refs |
| Paperclip-managed OAuth | `oauthStrategy: "paperclip_cloud_connector"`, `connectorProfile`, `platform_shared` | Browser sign-in through Paperclip Cloud | Tokens land in instance vault on a user grant; Cloud never persists plaintext tokens |
| API key / PAT | `auth: "api_key"`, `credentialFields`, `keyPlacement` | Write-only credential field | Encrypted secret version + placement-only refs |
| Generated URL | `auth: "none"`, no fixed URL/default template | Paste provider-generated MCP URL | Public URL shape in config; full secret-bearing URL in vault |
| No auth | `auth: "none"`, fixed `serverUrl` or validated `serverUrlTemplate` | Zero fields or only required tenant/resource fields | No provider credential |
For `mcp_remote`, header credentials and secret-bearing generated URLs have the complete generic runtime path. Do not ship `query`, `body_json`, or `env` key placements on `mcp_remote` without tracing the invocation path and adding an end-to-end fixture.
## OAuth Discovery & Client Resolution
For standard OAuth methods, Paperclip resolves endpoints in `oauthEndpointsForConnection` (`server/src/services/tool-access.ts`):
1. `defaults.discoveryUrl` is authoritative when set (must describe the MCP resource or its authorization server, not a separate web/API OAuth service).
2. A complete manifest pair (`authorizationEndpoint` + `tokenEndpoint`) replaces discovery when DCR is not supported or when using an operator-entered client.
3. Otherwise, for `mcp_remote`, `discoverOAuthEndpoints` checks stored/hinted endpoints, then runs RFC 9728 (`GET <serverUrl>` → `401` + `WWW-Authenticate` → `/.well-known/oauth-protected-resource`) → RFC 8414 (`/.well-known/oauth-authorization-server`, trying both insertion and OIDC suffix forms). Authorization, token, and refresh requests carry RFC 8707 `resource` and validate RFC 9207 `iss`.
Client resolution order:
1. Deployment-preconfigured client (`PAPERCLIP_TOOL_OAUTH_<PROVIDER>_CLIENT_ID/_SECRET`).
2. Client ID Metadata Document (CIMD), when advertised and the instance has a public HTTPS URL.
3. Dynamic Client Registration (DCR / RFC 7591), when advertised and `dcr` is in `ownershipModes`.
4. Customer-supplied client ID and secret.
- Set `oauthClientRegistration: "dcr"` when live evidence proves CIMD fails while DCR works (requires `dcr` in `ownershipModes`).
- Record probed redirect-URI rules in `redirectConstraints` (e.g., `https-or-loopback-http`).
- **DCR needs neither Paperclip ID nor Paperclip Connect.** Each instance registers its own public client (`token_endpoint_auth_method: "none"` + PKCE S256) and uses its own `/api/tools/oauth/callback`. Cloud and self-hosted use the exact same path.
## Files You Normally Touch
```text
ui/public/brands/apps/<slug>.svg # official, sanitized mark
ui/public/brands/apps/manifest.json # runtime branding paths
doc/connections/tool-method-permission-reviews.json # reviewed scopes & actions
scripts/ingest-app-definitions.mjs # or scripts/app-definition-overrides/<slug>.json
packages/shared/src/app-definitions/<slug>.json # generated (+ app-owned agentInstructions if any)
packages/shared/src/app-definitions.generated.ts # generated registry
packages/shared/src/self-serve-mcp-research.json # when part of self-serve MCP research
packages/shared/src/app-definitions.test.ts # manifest/provider assertions
```
## Method Design Rules
- Create separate methods only for real user choices (e.g., US vs. EU endpoint, materially different OAuth vs. API-key path, distinct provider toolsets).
- Do **not** create separate methods for DCR vs. CIMD, DCR vs. own OAuth app on the same endpoint (fold own-app under **Advanced**), or optional filters/read-only switches (make them `advanced: true` fields with safe defaults).
- Prefer a write/draft-capable method as default; put read-only switches under **Advanced**.
- Use `grantKinds: ["user"]` for providers that only support personal delegated identity or private personal data (e.g., personal meeting notes, email).
- Use `setupPrerequisite` for steps required before consent (preview enrollment, public storefront); put plan/admin caveats in `warnings` and `guidanceMd`.
- Use `defaults.toolArgumentDefaults` only for required, provider-documented protocol metadata that Paperclip owns (hidden from agent/Test schemas and authoritative on collision).
## Minimal Method Recipes
### Automatic OAuth (DCR / CIMD)
```json
{
"key": "mcp-oauth",
"label": "Sign in with Example",
"transport": "mcp_remote",
"auth": "oauth",
"ownershipModes": ["dcr"],
"whenToUse": "Use browser sign-in for the hosted MCP server.",
"defaults": {
"serverUrl": "https://mcp.example.com/mcp",
"scopesHint": ["example.read", "example.write"]
},
"guidanceMd": "Connect the workspace agents should use.",
"consoleLinks": { "docs": "https://docs.example.com/mcp" },
"riskTier": "S3"
}
```
### Customer OAuth Only
```json
{
"key": "mcp-own-oauth",
"label": "Use your own OAuth app",
"transport": "mcp_remote",
"auth": "oauth",
"ownershipModes": ["customer"],
"whenToUse": "Register an OAuth app, then enter its client ID and secret.",
"defaults": { "serverUrl": "https://mcp.example.com/mcp" },
"guidanceMd": "Register Paperclip's callback URI in the provider console.",
"consoleLinks": {
"register": "https://example.com/developers/apps",
"docs": "https://docs.example.com/mcp/oauth"
},
"riskTier": "S3"
}
```
### API Key / PAT
```json
{
"key": "mcp-api-key",
"label": "Use an API key",
"transport": "mcp_remote",
"auth": "api_key",
"ownershipModes": ["customer"],
"whenToUse": "Use a restricted key from the provider console.",
"defaults": { "serverUrl": "https://mcp.example.com/mcp" },
"credentialFields": [
{
"key": "authorization",
"label": "Example API key",
"type": "password",
"required": true,
"placeholder": "ex_...",
"secret": true
}
],
"keyPlacement": { "location": "header", "name": "Authorization", "prefix": "Bearer " },
"guidanceMd": "Create a key limited to the resources agents need.",
"riskTier": "S3"
}
```
### Provider-Generated URL / No-Auth Tenant Template
- **Generated URL:** `auth: "none"`, `ownershipModes: ["customer"]`, `defaults: {}`, narrow `urlPatterns`.
- **No-auth tenant template:** `auth: "none"`, `defaults: { "serverUrlTemplate": "https://{tenantDomain}/api/mcp" }`, validated `tenantFields` with `pattern` + `maxLength`.
## Step-by-Step Authoring Sequence
1. **Brand first:** Follow [CONNECTOR-ICONS.md](../CONNECTOR-ICONS.md). Add the official SVG (or ≥128×128 PNG) to `ui/public/brands/apps/` and register in `ui/public/brands/apps/manifest.json`. Ingestion fails closed if branding is missing.
2. **Permission review:** Add the method's reviewed scopes, supported actions, provider restrictions, and official evidence URL to [tool-method-permission-reviews.json](../tool-method-permission-reviews.json). Never request all advertised scopes automatically.
3. **Author durable source & regenerate:** Edit `scripts/ingest-app-definitions.mjs` or `scripts/app-definition-overrides/<slug>.json`, then regenerate definitions:
```sh
# With a local paperclip-content checkout (or PAPERCLIP_CONTENT_TEMPLATES set):
pnpm connections:ingest-app-definitions
# Without the external research corpus (regenerates definitions and preserves the checked-in report):
pnpm connections:ingest-app-definitions --definitions-only
```
Inspect `git diff` to ensure no unrelated provider churn.
4. **Add generic runtime support only if needed:** Check `packages/shared/src/types/app-definition.ts`, `validators/app-definition.ts`, `normalizeConnectionMethodConfig`, `projectedConnectionHeaders`, `tool-access.ts`, `tool-gateway.ts`, and `classifyRisk`. Never add a provider-name branch when a reusable field solves the problem.
5. **Deterministic tests:** Run and extend:
```sh
node scripts/check-app-brand-assets.mjs
pnpm exec vitest run \
packages/shared/src/app-definitions.test.ts \
server/src/__tests__/tool-access-service.test.ts \
server/src/__tests__/generic-mcp-connection.test.ts \
server/src/__tests__/tool-connection-removal.test.ts \
ui/src/pages/apps/AppsConnect.test.tsx \
ui/src/pages/apps/Browse.test.tsx
```
6. **Isolated UI & live proof:** Follow the [Production Validation](../CONNECTOR-PLAYBOOK.md#step-9-align-with-production-validation) lifecycle in the main playbook.
For full field definitions, troubleshooting, and worked dry-run examples, see [app-definition-reference.md](./app-definition-reference.md).
+87
View File
@@ -0,0 +1,87 @@
# Track B: Reviewed Native REST Adapter
Use this track when an official remote HTTP MCP server **does not exist**, is **desktop/local-only**, is **preview/unreliable**, or **fails to cover the core read/write jobs users expect** — while the provider offers a well-documented HTTPS REST API.
> **Hard rule:** Setting `transport: "rest_api"` in an `AppDefinition` never enables arbitrary HTTP execution. Only reviewed adapters registered in `server/src/services/connectors/rest-registry.ts` (or a dedicated reviewed adapter such as `browser-use-cloud` or `google-workspace-rest-tools`) execute through the connection gateway.
## Existing Reference Implementations
- **Standard REST registry adapters:** `server/src/services/connectors/supabase/` and `server/src/services/connectors/vercel/`, registered in `server/src/services/connectors/rest-registry.ts`.
- **Dual-transport (MCP + REST fallback/migration):** `server/src/google-workspace-rest-tools/` (`GOOGLE_WORKSPACE_TOOL_TRANSPORT`).
- **Stateful REST adapter + live UI pane + bundled skill:** `server/src/services/connectors/browser-use-cloud/` (see [BROWSER-USE.md](../BROWSER-USE.md)).
## When to Choose Track B Over Track A
Choose Track B during the upfront Connector Brief when:
1. The vendor has a stable REST API (e.g., Microsoft Graph, Figma REST, Supabase Management API, Vercel REST) and either **no hosted MCP** or a hosted MCP that is read-only / severely incomplete for the agreed top 3–5 user jobs.
2. Users need deterministic, strict-schema actions with clear risk classification (`read` vs `write` vs `destructive`), byte limits, and redaction guarantees that an upstream MCP does not provide.
3. The connection needs custom probe/health checks that do not trigger paid work or side effects.
Keep the initial toolset **tight and job-focused** (typically 5–15 high-value tools covering the agreed user jobs) rather than wrapping 200 raw API endpoints.
## Module & Registry Contract
Keep all provider-specific endpoints, schemas, payload shaping, and error translation inside `server/src/services/connectors/<provider>/` (per `rules/module-boundaries.mdc`). Shared gateway code stays provider-agnostic and owns grants, policy, approvals, rate limits, and audit.
Every standard REST adapter implements `RestConnector` in `server/src/services/connectors/rest-registry.ts`:
```ts
interface RestConnector {
sourceTemplateKey: string;
name: string;
matches(connection: Connection): boolean;
tools: Array<{
name: string;
title?: string | null;
description?: string | null;
inputSchema?: Record<string, unknown>;
annotations?: Record<string, unknown>;
}>;
risk(name: string): ToolRiskLevel;
isCurrent(entry: CatalogEntry): boolean;
client(
connection: Connection,
headers: Record<string, string>,
request: Request,
signal?: AbortSignal,
deadlineAt?: number,
): {
probe(): Promise<unknown>;
invoke(name: string, parameters: unknown): Promise<unknown>;
};
}
```
### Mandatory Adapter Invariants
1. **Pinned base URLs & strict path validation:** Never let agent arguments supply arbitrary URLs, hostnames, or path traversals (`..`). Validate every ID/slug/ref with strict Zod regexes and `.strict()` schemas before constructing URLs.
2. **Safe, cheap `probe()`:** Health checks and setup verification must execute one narrow, read-only, zero-cost API call (e.g., current user/profile, project metadata, or workspace list) using the resolved credential headers. Never trigger paid work or writes during `probe()`.
3. **Explicit risk classification & schema hashing:**
- Classify every tool explicitly in `risk(name)` (`read`, `write`, `destructive`) and mirror it in `annotations` (`readOnlyHint`, `destructiveHint`).
- Compute deterministic `descriptorHash` / `stableHash` (`server/src/services/tool-catalog-hash.ts`) so `isCurrent(entry)` detects tool-schema changes cleanly for quarantine/review.
4. **Bounded responses & redaction:**
- Enforce a hard response byte ceiling (e.g., `2 MiB`) and respect `signal` / `deadlineAt` timeouts.
- Pass error messages through `redactSensitiveText` (`server/src/redaction.ts`); never echo raw credentials or untrusted provider error bodies containing tokens.
- Mark secret-bearing input fields in schemas so gateway argument summaries redact them and never return them.
5. **Untrusted content / prompt-injection screening:** When tools return external user-authored content (emails, comments, docs, tickets, meeting notes), route results through Paperclip's prompt-injection guard where applicable (see [GOOGLE-WORKSPACE.md](../GOOGLE-WORKSPACE.md) and `doc/prompt-injection-prevention.md`).
6. **Resource boundary enforcement:** If the `AppDefinition` declares `tenantFields` (e.g., `projectRef`, `teamId`, `siteId`), read them from `connection.config.methodConfig` in the adapter and enforce them on every API call so an agent cannot pivot to another project/team.
## Catalog, Auth, and UX Pairing
A Track B adapter still ships through the standard catalog pipeline:
- Official branding in `ui/public/brands/apps/` + `manifest.json` ([CONNECTOR-ICONS.md](../CONNECTOR-ICONS.md)).
- Reviewed `AppDefinition` with `transport: "rest_api"`, auth mode (`oauth` or `api_key`), `tenantFields` / `credentialFields`, and entry in `doc/connections/tool-method-permission-reviews.json`.
- If OAuth requires a Paperclip-owned fixed-callback app, pair this track with [Track C: Managed OAuth & Multi-Service Suites](./managed-oauth-suite.md).
- If agents need standing workflow guidance to chain the REST tools effectively, pair with [Track D: Connector-Provided Skills & Agent Instructions](./connector-skills.md).
## Verification Checklist (Track B Specific)
In addition to the universal verification ladder in [CONNECTOR-PLAYBOOK.md](../CONNECTOR-PLAYBOOK.md):
- **Unit tests (`server/src/services/connectors/<provider>/`):**
- Every tool's valid input, invalid/traversal input rejection, and `.strict()` unknown-key rejection.
- Exact outbound URL, HTTP method, headers, and timeout/abort handling using mocked `request`.
- Oversized response truncation/rejection and credential redaction on 4xx/5xx provider errors.
- Resource boundary enforcement (configured `projectRef`/`teamId` cannot be overridden by caller args).
- `risk(name)` and `isCurrent(entry)` parity for every exported tool.
- **Gateway & policy tests:** Confirm `restConnectorFor(connection)` resolves the adapter, catalog refresh populates all tools with expected risk levels, writes respect Ask-first/Off policy, and company B cannot invoke company A's connection.
- **Live proof:** Run `probe()`, one safe read tool, and (on a disposable resource) one write tool through a real run-scoped gateway, then revoke and verify immediate fail-closed behavior.