From 8ff45c0fa90cb8a7beeb2b919bd0cd4364b05a9d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:28:05 -0600 Subject: [PATCH] feat(connections): render MCP Apps views in the task chat, starting with Circleback (#21119) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents reach external apps through MCP connections. Paperclip records each call and shows it as a tool row in the task chat. > - MCP Apps (SEP-1865, extension `io.modelcontextprotocol/ui`, spec 2026-01-26) lets an MCP server attach an interactive `ui://` view to a tool. Claude, Claude Code and VS Code render these views in chat. Circleback uses them to show meeting cards. > - Paperclip dropped the tool's `_meta.ui` at discovery and the result's `_meta` at call time. Its gateway reported MCP App UI as "unsupported". Circleback was reachable only through Composio, whose toolkit has no `Display*` tools. > - This pull request makes Paperclip an MCP Apps host. It also adds Circleback as a native catalog connection. > - The benefit is that a Circleback recap in a task shows the same meeting cards as in Claude, and any other MCP server with views works the same way. ## Linked Issues or Issue Description **Subsystem affected** Connections and apps (remote MCP gateway) and the task chat. **Problem or motivation** An agent that uses Circleback in Paperclip can only return text. The same tools in Claude Code show interactive meeting cards (`DisplayMeetings`). Paperclip discards the MCP Apps metadata, so it cannot show them. **Proposed solution** Paperclip implements the host side of MCP Apps end to end. It keeps the tool's view declaration and records each call that has a view. It renders the view under the tool row in a sandboxed iframe that uses the MCP Apps postMessage protocol. Circleback becomes a native catalog connection, so its `Display*` tools are available. **Alternatives considered** Composio's `circleback_mcp` toolkit has 11 read tools and no `Display*` tools, and its meta-tools return plain JSON, so it cannot carry views. The spec's double-iframe sandbox proxy on a separate origin needs a second origin that Paperclip does not have. A single opaque-origin `srcdoc` frame with an injected CSP gives the same isolation. **Roadmap alignment** This extends the existing Apps catalog and MCP gateway. It adds no new integration substrate (decision D4 in doc/connections/README.md). **Additional context** The standard, the design and the testing plan are in `doc/connections/MCP-APPS.md`. ## What Changed - **Shared:** `packages/shared/src/mcp-apps.ts` adds MCP Apps types, `_meta.ui` and resource parsing (current and legacy keys), and a CSP builder that keeps only well-formed `https` origins. - **DB:** migration `0471` (`online_compatible`) adds `tool_catalog_entries.ui_meta` and a new `tool_mcp_app_views` table. - **Server, catalog:** discovery keeps each tool's `_meta.ui`. It is not part of the version hash, so a view never quarantines a reviewed tool. - **Server, gateway:** - Paperclip advertises the MCP Apps client capability when it initializes a session. - App-only tools (`visibility: ["app"]`) are hidden from agents. - The result `_meta` is kept for the view and is not sent to the agent. - Each successful call to a tool with a view records a view row. Recording is best effort. - The gateway's `initialize` now reports `paperclip/mcp-app-ui: host_rendered`. - The context protocol (`resources/read`) now uses the injected test transport, like the other remote calls. - **Server, routes:** `server/src/routes/mcp-apps.ts` - `GET /api/issues/:issueId/mcp-app-views` lists a task's views. It needs task read access. - `GET /api/issues/:issueId/mcp-app-views/:viewId` returns the view document, read live through the agent's connection. - `POST /api/issues/:issueId/mcp-app-views/:viewId/tool-calls` runs the view's `tools/call`. It needs `tools:use` and reaches only tools of the same connection that allow `app`. It uses the connection test-call path, so policy, Ask first and audit apply. - **UI:** `ui/src/components/mcp-app/` - The host protocol: `ui/initialize` with theme, style variables and size limits; tool-input; tool-result; size-changed; `tools/call`; `ui/open-link` (http and https only); teardown. - An opaque-origin iframe (`allow-scripts`, never `allow-same-origin`) with the CSP placed before the view's markup. - The views of a run render with that run's reply, in the live turn and in settled history. They are keyed by the reply's run, so history needs no transcript. - **Circleback:** a native catalog app (`mcp-oauth`, DCR, `user user:write`) with: - the official logo; - a reviewed risk classifier (Share* tools are writes, Delete* tools are destructive, Display* tools are reads); - warnings in the sign-in step; - `doc/connections/CIRCLEBACK.md`. Search now prefers a native app over an aggregator listing named "X MCP". - **Storybook:** `Tasks/MCP App views` shows the tool row with its view, the ready state (Refresh calls a tool), loading, view unavailable, and a tool call that needs approval. ## Verification - `pnpm exec vitest run packages/shared/src/mcp-apps.test.ts ui/src/components/mcp-app/`: 19 passed. - `pnpm exec vitest run server/src/__tests__/mcp-apps.test.ts`: 3 passed, on embedded Postgres. The test connects Circleback through the catalog with DCR OAuth against a fake Circleback MCP server. It checks: - `ui_meta` is stored; - an app-only tool is hidden from the agent; - an agent call records one view with arguments, structured content and `_meta`; - a call without a view records nothing; - the routes serve the view's HTML and CSP; - the view's tool call works and a model-only tool is refused; - another task, another company and an agent actor are refused. - Circleback connector: 13 focused files, 645 tests passed. These are the app definitions, search, aggregator fallback, connection intents, tool policy, `AppsConnect` and `Browse`. - Typecheck passed for `@paperclipai/shared`, `@paperclipai/server` and `@paperclipai/ui`. `node scripts/storybook-catalog.mjs` and the migration compatibility check also passed. - Storybook check in the browser: - In both themes, the view runs the handshake, renders the meeting cards from `structuredContent`, picks up the theme variables, and resizes to its content. - Refresh sends `tools/call` and re-renders the cards. - **Live Circleback end to end** on a local instance, with a real Circleback account: - Connected through the catalog entry with Circleback's dynamic client registration and OAuth. - Discovery stored the real view declarations: - `DisplayMeetings` uses `ui://circleback/meetings.v2.html`. - `DisplayActionItems` and `DisplayCalendarEvents` also have views. - `ListAssigneeOptions` and `SetCalendarEventRecording` are app-only helpers with no view. They are hidden from agents. - A `claude_local` agent called `DisplayMeetings` on two tasks. - The real 3.5 MB Circleback view rendered the meeting cards with the agent's reply. - Clicking a card opened that meeting in Circleback through `ui/open-link`. - The live run found two bugs, both fixed in this PR, each with a regression test: - The 1 MB tool-result limit blocked the view document. - Views were hidden inside the folded tool history. ## Risks - **New migration:** a new table and a nullable column. It is `online_compatible`. - **Existing connections:** tools get `ui_meta` on the next catalog refresh. Until then, no view shows and the tool row is unchanged. - **Untrusted provider HTML:** the view runs as provider HTML in an opaque-origin sandbox. It cannot reach Paperclip's session, DOM or API. Its network access is limited to the origins its server declared. A view's tool calls use the viewer's permissions and the normal policy and Ask-first path. - **Agent tool lists:** app-only tools are removed from them. No current provider marks tools app-only, so no listed tool disappears. - **Search:** the change that prefers a native app over an "X MCP" aggregator listing affects every app. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and subagents (one subagent authored the Circleback catalog connector). ## 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 --- doc/connections/CIRCLEBACK.md | 218 +++++++++++ doc/connections/CONNECTION-SEARCH.md | 6 +- doc/connections/CONNECTOR-PERMISSION-AUDIT.md | 3 +- doc/connections/MCP-APPS.md | 113 ++++++ doc/connections/README.md | 2 +- .../tool-method-permission-reviews.json | 20 + .../src/migrations/0473_elite_kat_farrell.sql | 29 ++ ...{0468_snapshot.json => 0473_snapshot.json} | 370 +++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/index.ts | 1 + packages/db/src/schema/tool_access.ts | 34 ++ .../shared/src/app-definitions-url.test.ts | 2 + .../shared/src/app-definitions.generated.ts | 53 +-- packages/shared/src/app-definitions.test.ts | 41 +- .../src/app-definitions/circleback.json | 52 +++ packages/shared/src/index.ts | 1 + packages/shared/src/mcp-apps.test.ts | 92 +++++ packages/shared/src/mcp-apps.ts | 223 +++++++++++ .../shared/src/self-serve-mcp-research.json | 3 +- packages/shared/src/types/tool-access.ts | 3 + .../app-definition-overrides/circleback.json | 52 +++ .../connection-aggregator-fallback.test.ts | 30 +- .../__tests__/connector-tool-policy.test.ts | 23 ++ server/src/__tests__/mcp-apps.test.ts | 365 +++++++++++++++++ server/src/__tests__/openapi-routes.test.ts | 1 + server/src/__tests__/tool-gateway.test.ts | 2 +- server/src/app.ts | 2 + server/src/routes/mcp-apps.ts | 92 +++++ server/src/routes/openapi.ts | 16 + server/src/routes/tool-access.ts | 55 ++- server/src/routes/tool-gateway.ts | 4 +- server/src/services/connection-intents.ts | 5 +- .../services/connectors/circleback/risk.ts | 45 +++ server/src/services/connectors/tool-policy.ts | 4 + server/src/services/mcp-app-views.ts | 128 ++++++ server/src/services/mcp-http.ts | 4 +- .../tool-access/catalog/descriptors.ts | 4 + .../tool-access/catalog/publication.ts | 4 +- server/src/services/tool-gateway.ts | 259 ++++++++++-- .../runner-e2e/source-sdk-public-inputs.json | 15 +- ui/public/brands/apps/circleback.png | Bin 0 -> 9887 bytes ui/public/brands/apps/manifest.json | 6 + ui/src/api/mcpApps.ts | 12 + ui/src/components/TaskChatThread.tsx | 5 + .../components/mcp-app/McpAppFrame.test.tsx | 109 ++++++ ui/src/components/mcp-app/McpAppFrame.tsx | 145 +++++++ .../mcp-app/McpAppIssueContext.test.tsx | 100 +++++ .../components/mcp-app/McpAppIssueContext.tsx | 73 ++++ .../mcp-app/McpAppTurnViews.test.tsx | 79 ++++ ui/src/components/mcp-app/McpAppTurnViews.tsx | 98 +++++ ui/src/components/mcp-app/McpAppView.test.tsx | 45 +++ ui/src/components/mcp-app/McpAppView.tsx | 84 ++++ .../components/mcp-app/mcp-app-host.test.ts | 163 ++++++++ ui/src/components/mcp-app/mcp-app-host.ts | 241 ++++++++++++ .../mcp-app/mcp-app-matching.test.ts | 45 +++ ui/src/components/mcp-app/mcp-app-matching.ts | 32 ++ .../task-chat/TaskChatRunnerTurn.tsx | 2 + .../task-chat/TaskChatThreadView.tsx | 10 +- .../components/task-chat/task-chat-adapter.ts | 1 + .../components/task-chat/task-chat-model.ts | 2 + .../connections/ConnectionSetupFlow.tsx | 7 +- ui/src/lib/app-gallery-copy.ts | 4 + ui/src/lib/queryKeys.ts | 4 + ui/src/pages/apps/AppsConnect.test.tsx | 19 + ui/src/pages/apps/Browse.test.tsx | 104 ++--- .../tasks/task-chat-mcp-app.stories.tsx | 93 +++++ ui/storybook/support/mcp-app/fixtures.ts | 133 +++++++ 67 files changed, 3865 insertions(+), 134 deletions(-) create mode 100644 doc/connections/CIRCLEBACK.md create mode 100644 doc/connections/MCP-APPS.md create mode 100644 packages/db/src/migrations/0473_elite_kat_farrell.sql rename packages/db/src/migrations/meta/{0468_snapshot.json => 0473_snapshot.json} (99%) create mode 100644 packages/shared/src/app-definitions/circleback.json create mode 100644 packages/shared/src/mcp-apps.test.ts create mode 100644 packages/shared/src/mcp-apps.ts create mode 100644 scripts/app-definition-overrides/circleback.json create mode 100644 server/src/__tests__/mcp-apps.test.ts create mode 100644 server/src/routes/mcp-apps.ts create mode 100644 server/src/services/connectors/circleback/risk.ts create mode 100644 server/src/services/mcp-app-views.ts create mode 100644 ui/public/brands/apps/circleback.png create mode 100644 ui/src/api/mcpApps.ts create mode 100644 ui/src/components/mcp-app/McpAppFrame.test.tsx create mode 100644 ui/src/components/mcp-app/McpAppFrame.tsx create mode 100644 ui/src/components/mcp-app/McpAppIssueContext.test.tsx create mode 100644 ui/src/components/mcp-app/McpAppIssueContext.tsx create mode 100644 ui/src/components/mcp-app/McpAppTurnViews.test.tsx create mode 100644 ui/src/components/mcp-app/McpAppTurnViews.tsx create mode 100644 ui/src/components/mcp-app/McpAppView.test.tsx create mode 100644 ui/src/components/mcp-app/McpAppView.tsx create mode 100644 ui/src/components/mcp-app/mcp-app-host.test.ts create mode 100644 ui/src/components/mcp-app/mcp-app-host.ts create mode 100644 ui/src/components/mcp-app/mcp-app-matching.test.ts create mode 100644 ui/src/components/mcp-app/mcp-app-matching.ts create mode 100644 ui/storybook/stories/tasks/task-chat-mcp-app.stories.tsx create mode 100644 ui/storybook/support/mcp-app/fixtures.ts diff --git a/doc/connections/CIRCLEBACK.md b/doc/connections/CIRCLEBACK.md new file mode 100644 index 00000000000..c74ac4ea3ad --- /dev/null +++ b/doc/connections/CIRCLEBACK.md @@ -0,0 +1,218 @@ +# Circleback + +Updated: 2026-11-12. Status: catalog definition reviewed against official +documentation and live provider metadata; live account qualification +outstanding. + +Circleback (`circleback.ai`) records meetings and writes notes, action items +and transcripts. Its hosted MCP server also searches the signed-in user's +calendar, connected email, people and companies, and manages action items, +tags, folders and sharing. It appears in Apps and uses Paperclip's shared +remote-MCP connection, vault, catalog, grants, policies, gateway, and audit +trail. It is a resource connection, not Paperclip sign-in. No plugin or +database migration is required. The only provider-specific runtime code is a +reviewed risk classifier (see [Capabilities and policy](#capabilities-and-policy)). + +Paperclip connects to Circleback's hosted MCP server at +`https://circleback.ai/api/mcp` (Streamable HTTP) with one method: + +- `mcp-oauth`: browser sign-in through Circleback's dynamic client + registration. The connection acts as the user who signs in. + +Circleback documents no API key for its MCP server, so there is no key +method. + +This curated connection is the preferred route for Circleback. Composio also +lists a Circleback toolkit (`circleback_mcp`), but it exposes only read tools +and none of the meeting-card tools. Connection search returns the built-in +connection for Circleback requests and does not offer the Composio route +beside it (see [Connection search](./CONNECTION-SEARCH.md)). The same URL can +also be connected from **Connect your own MCP server**; see +[Connecting any remote MCP server](./GENERIC-REMOTE-MCP.md). + +## Service involvement + +Circleback hosts the MCP resource and the authorization server. Paperclip +stores the OAuth tokens as secret references, discovers tools with +`tools/list`, and sends the token on every governed call. Neither Paperclip ID +nor Paperclip Connect participates: dynamic client registration is +instance-local, and cloud and self-hosted instances use the same path. + +## Connection flow + +```mermaid +sequenceDiagram + participant Op as Operator browser + participant PC as Paperclip instance + participant CB as circleback.ai + Op->>PC: Apps, Circleback, Continue to Circleback + PC->>CB: POST /api/mcp without a token + CB-->>PC: 401 with resource_metadata + PC->>CB: GET /.well-known/oauth-protected-resource/api/mcp + PC->>CB: GET /.well-known/oauth-authorization-server + PC->>CB: POST /api/oauth/register (public client, Paperclip callback) + CB-->>PC: client_id + PC-->>Op: Redirect to /api/oauth/authorize (PKCE S256, scope user user:write) + Op->>CB: Sign in and approve + CB-->>Op: Redirect to /api/tools/oauth/callback with code + Op->>PC: Callback + PC->>CB: POST /api/oauth/access-token (code, verifier, resource) + CB-->>PC: Access and refresh tokens + PC->>CB: tools/list + PC-->>Op: Permissions screen +``` + +## Endpoints + +| Purpose | URL | +| --- | --- | +| MCP resource | `https://circleback.ai/api/mcp` | +| Protected-resource metadata | `https://circleback.ai/.well-known/oauth-protected-resource/api/mcp` | +| Authorization-server metadata | `https://circleback.ai/.well-known/oauth-authorization-server` | +| Authorize | `https://circleback.ai/api/oauth/authorize` | +| Token | `https://circleback.ai/api/oauth/access-token` | +| Dynamic client registration | `https://circleback.ai/api/oauth/register` | +| Paperclip callback | `/api/tools/oauth/callback` | + +`app.circleback.ai` serves the same paths with its own issuer and resource +(`https://app.circleback.ai/api/mcp`). The definition uses the documented +`circleback.ai` host; both hosts are in `urlPatterns`, so a pasted URL on +either host opens this connection. + +The authorization server supports `authorization_code` and `refresh_token`, +PKCE `S256`, public clients (`token_endpoint_auth_method: none`), and Client ID +Metadata Documents. Redirect constraint: `https-or-loopback-http`. + +## Scopes + +Paperclip requests `user user:write`, Circleback's documented default and the +scope its unauthenticated 401 challenge names. `user` alone is read-only; +write tools then return an error asking the user to reconnect with write +access. This is recorded as an explicit review in +[`tool-method-permission-reviews.json`](./tool-method-permission-reviews.json). + +## Administrator setup + +Nothing needs to be registered: Paperclip registers its own public client the +first time someone connects. The instance needs an HTTPS or loopback origin. + +1. In Paperclip, open **Apps → Browse → Circleback** and click + **Continue to Circleback**. The screen lists the sharing warning first. +2. Sign in to Circleback and approve access. +3. On the connection's **Permissions** screen, set the share and delete + actions to **Ask first** or **Off** if agents run unattended. + +To verify, run a read action such as `SearchMeetings` from its **Test** button. +To disconnect, remove the connection in Paperclip. + +## Capabilities and policy + +Circleback documents these tools (checked against a live connection on +2026-11-12): + +| Group | Tools | Risk | +| --- | --- | --- | +| Meetings and transcripts | `SearchMeetings`, `ReadMeetings`, `GetTranscriptsForMeetings`, `SearchTranscripts` | read | +| Action items, calendar, email | `SearchActionItems`, `SearchCalendarEvents`, `SearchEmails` | read | +| People, companies, workspace | `FindProfiles`, `FindCompanies`, `ListTeams`, `ListTags`, `ListFolders`, `ReadFolders`, `SearchSupportArticles` | read | +| Meeting cards | `DisplayMeetings`, `DisplayActionItems`, `DisplayCalendarEvents` | read | +| Edits | `CreateActionItem`, `UpdateActionItem`, `CreateTag`, `UpdateTag`, `CreateFolder`, `UpdateFolder`, `UpdateMeeting`, `UpdateCalendarEvent` | write | +| Outward-facing | `ShareMeeting`, `ShareFolder`, `SubmitFeedback` | write | +| Deletes | `DeleteActionItem`, `DeleteTag`, `DeleteFolder` | destructive | + +The generic classifier reads `share` and `submit` as reads, so +`server/src/services/connectors/circleback/risk.ts` classifies Circleback by +exact tool name. Tools not in the list are writes until reviewed; a provider +`destructiveHint` still wins. New tools are not quarantined, matching other +MCP-direct catalog connections. + +`ShareMeeting` and `ShareFolder` can share with other people, a team, the +whole workspace, or anyone with the link, and can remove access. +`SubmitFeedback` sends text to Circleback's team. The method warning and the +capability description tell operators to set share and delete actions to Ask +first. + +### Meeting cards in chat + +`DisplayMeetings`, `DisplayActionItems` and `DisplayCalendarEvents` render as +interactive cards in the task chat through the MCP Apps extension +(`io.modelcontextprotocol/ui`): meetings open in Circleback, action items form +a checklist, and calendar events show whether Circleback joins. A change made +from a card is a call to the matching write tool and follows that tool's +policy. Clients without MCP Apps receive the same results as text. See +[MCP Apps](./MCP-APPS.md). + +## Transport and auth + +- Transport: `mcp_remote`, Streamable HTTP. +- OAuth: DCR (or CIMD when the instance has a public HTTPS URL), public client, + PKCE, scopes `user user:write`. Connects as the approving user. +- Credential owner: user-delegated; tokens stored as `company_secrets` refs. + +## Resource filters + +None. Circleback documents no query or header options that narrow the hosted +server. Access is bounded by the signed-in user's Circleback permissions; +narrow further with per-action policies. + +## Manifest + +| Field | Value | +| --- | --- | +| Slug | `circleback` | +| Category | `productivity` | +| Method | `mcp-oauth` (`dcr`, S3, scopes `user`, `user:write`) | +| Server URL | `https://circleback.ai/api/mcp` | +| URL patterns | `https://circleback.ai/*`, `https://app.circleback.ai/*` | +| Capability profile | `write`, with the share and delete warning | +| Console links | docs `https://circleback.ai/docs/support/platform/circleback-mcp` | + +The definition source is +`scripts/app-definition-overrides/circleback.json`, with the research row in +`packages/shared/src/self-serve-mcp-research.json`. Regenerate with +`node scripts/ingest-app-definitions.mjs --definitions-only`. + +## Wizard path + +`/apps/connect?source=circleback` has one automatic OAuth method, so it opens +the direct sign-in screen. That screen repeats the method guidance and both +warnings before **Continue to Circleback**. Successful sign-in and tool +discovery lead to the connection's Permissions screen. + +## Governance defaults + +- Default profile and bindings: the standard connection profile; every + discovered action starts Allowed under the current product default. +- Policies: operators narrow share, delete and feedback tools to Ask first or + Off on the Permissions screen. +- Risk: the reviewed Circleback classifier above. +- Quarantine rules: the shared defaults. + +## Brand provenance + +Circleback's site links `https://circleback.ai/logos/circleback_square.png`, a +560×560 transparent PNG of its orange "c." mark. It is used unchanged in both +themes. The `apple-touch-icon.png` is the same mark on an opaque white +background, and `logos/circleback.svg` is the wide wordmark with an embedded +bitmap, so neither was used. + +| File | Source | SHA-256 | +| --- | --- | --- | +| `ui/public/brands/apps/circleback.png` (560×560) | `https://circleback.ai/logos/circleback_square.png` | `dd858dae1efd29d95d46cb3b99a9e27603d50840bf9e3bdac109eb38dc80e3ac` | + +## Validation hook + +- Environment: definition review on 2026-11-12 against `origin/master`; no + Circleback account was connected to Paperclip. +- Metadata probe: an unauthenticated `initialize` on `/api/mcp` returned HTTP + 401 with `resource_metadata` and `scope="user user:write"`; both + `.well-known` documents returned the endpoints and scopes above, on both + `circleback.ai` and `app.circleback.ai`. +- Deterministic tests: manifest shape, store visibility, artwork, URL + recognition on both hosts, reviewed scopes, the direct sign-in screen with + its warnings, risk classification, Browse showing one native card in place + of the Composio listing, and connection search preferring the built-in + connection. +- Connect evidence, catalog evidence, allowed read, governed write, denied + case, revoke, audit: not run. The connection still needs the full live + lifecycle with a Circleback account before it is considered qualified. diff --git a/doc/connections/CONNECTION-SEARCH.md b/doc/connections/CONNECTION-SEARCH.md index 594b10a66ec..0ae27347ea9 100644 --- a/doc/connections/CONNECTION-SEARCH.md +++ b/doc/connections/CONNECTION-SEARCH.md @@ -50,7 +50,9 @@ queries to a provider. Broad provider descriptions are not evidence of support. Configured connection metadata remains scoped to the current company and identity. Archived and unauthorized catalogs cannot establish an aggregator route. -Built-in connections remain preferred for the same app. Existing AI access is +Built-in connections remain preferred for the same app. An aggregator listing +counts as the same app when its name or any alias matches the built-in name, so +Composio's "Circleback MCP" does not appear beside built-in Circleback. Existing AI access is checked through the agent's AI binding and credential selection. An aggregator route still requires a saved provider choice or a verified explicit user request. Fuzzy retrieval never grants consent. A provider connection is not proof that its underlying app is @@ -71,7 +73,7 @@ pnpm exec vitest run packages/shared/src/connection-search.test.ts packages/shar The database suite covers the original AgentMail sentence, split names, typos, capability overlap, multiple services, AI discovery, experimental gating, -Circleback/Attio/ClickUp, indexed Executor tools, and provider consent. The native +Otter.ai/Fathom/Attio/ClickUp, built-in Circleback over its Composio listing, indexed Executor tools, and provider consent. The native tool authority test searches a paragraph longer than the old 200-character limit and then creates a real connection interaction. Existing tests retain checks for private metadata, administrative denials, stale identities, and saved declines. diff --git a/doc/connections/CONNECTOR-PERMISSION-AUDIT.md b/doc/connections/CONNECTOR-PERMISSION-AUDIT.md index 9c70b98e7ca..d6c5265ee4d 100644 --- a/doc/connections/CONNECTOR-PERMISSION-AUDIT.md +++ b/doc/connections/CONNECTOR-PERMISSION-AUDIT.md @@ -12,7 +12,8 @@ ledger; the counts above are not restated. Later additions: [Neon](./NEON.md) (`mcp-api-key`; 2026-10-06), [Gauge](./GAUGE.md) (`mcp-oauth`, `mcp-api-key`; 2026-10-08), [Ditto](./DITTO.md) (`mcp-oauth`, `mcp-api-key`; 2026-10-10), [Unikraft](./UNIKRAFT.md) -(`api-token`; 2026-10-15). +(`api-token`; 2026-10-15), [Circleback](./CIRCLEBACK.md) +(`mcp-oauth`; 2026-11-12). ## Shared credential failure diff --git a/doc/connections/MCP-APPS.md b/doc/connections/MCP-APPS.md new file mode 100644 index 00000000000..a457bf1b2bb --- /dev/null +++ b/doc/connections/MCP-APPS.md @@ -0,0 +1,113 @@ +# MCP Apps: interactive views in the task chat + +Some MCP servers attach an interactive view to a tool. When an agent calls the +tool, the view appears in the task chat under the tool row. The first provider +that uses this is [Circleback](./CIRCLEBACK.md): `DisplayMeetings`, +`DisplayActionItems` and `DisplayCalendarEvents` render meeting, action item and +calendar cards. + +## The standard + +These views are **MCP Apps**, the first official MCP extension: + +- Specification: [SEP-1865, version 2026-01-26](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx) + ([overview](https://modelcontextprotocol.io/docs/extensions/apps)). +- Extension id: `io.modelcontextprotocol/ui`. +- Other hosts: Claude, Claude Desktop, Claude Code, VS Code Copilot, Goose and Postman. + +The protocol works like this: + +1. **The tool declares a view.** The tool's `_meta.ui.resourceUri` names a + `ui://` resource. `_meta.ui.visibility` lists who may call the tool: + - `"model"` means the agent can call it. The default is `["model", "app"]`. + - A tool marked `["app"]` is hidden from the agent and only the view can call it. + - Paperclip also reads the deprecated flat key `_meta["ui/resourceUri"]`. +2. **The resource is an HTML document.** `resources/read` returns it with the + mime type `text/html;profile=mcp-app`. The resource's `_meta.ui` can also + carry: + - `csp.connectDomains`, `resourceDomains`, `frameDomains` and `baseUriDomains`; + - `permissions`; + - `prefersBorder`. +3. **The host renders the view in a sandboxed iframe.** The host and view then + talk JSON-RPC over `postMessage`: + 1. The view sends `ui/initialize` and the host answers with its capabilities + and host context: theme, style variables, locale, size limits and tool info. + 2. The view sends `ui/notifications/initialized`. + 3. The host sends `ui/notifications/tool-input` and then + `ui/notifications/tool-result`, which carries the full `CallToolResult`, + including `structuredContent` and `_meta`. + 4. After that, the view may send `ui/notifications/size-changed`, + `tools/call`, `ui/open-link`, `ui/update-model-context` and `ping`. + 5. Before removing the iframe, the host sends `ui/resource-teardown`. + +## Composio and other aggregators + +The [Composio Circleback toolkit](https://docs.composio.dev/toolkits/circleback_mcp) +cannot carry views: + +- It has 11 read tools. +- It has none of the `Display*` tools. +- Composio's meta-tools return plain JSON. + +So views need a direct MCP connection, and Circleback is now a native catalog +app. When an app has a native entry, search prefers it over its aggregator +listing. See [CONNECTION-SEARCH.md](./CONNECTION-SEARCH.md). + +## How Paperclip implements it + +| Layer | What happens | Code | +| --- | --- | --- | +| Client capability | Paperclip advertises `extensions["io.modelcontextprotocol/ui"]` when it initializes an MCP session. | `server/src/services/mcp-http.ts` | +| Catalog | Each tool's normalized `_meta.ui` is kept in `tool_catalog_entries.ui_meta`. It is not part of the version hash, so adding a view never quarantines a reviewed tool. | `server/src/services/tool-access/catalog/` | +| Agent tool list | Tools whose visibility omits `"model"` are not listed to agents and cannot be called by them. | `isModelVisibleTool` in `server/src/services/tool-gateway.ts` | +| Recording | Each successful call to a tool with a view stores one `tool_mcp_app_views` row: issue, run, agent, connection, the redacted arguments and the redacted `CallToolResult`. The tool result `_meta` is kept here and never sent to the agent. Recording is best effort and never fails the agent's call. | `server/src/services/mcp-app-views.ts` | +| API | `GET /api/issues/:issueId/mcp-app-views` lists a task's views. `GET …/:viewId` returns the view, reading the `ui://` document live through the agent's connection. `POST …/:viewId/tool-calls` runs a view's `tools/call`. Reading follows task read access. Tool calls also need the `tools:use` or `tools:manage_connections` permission, and only reach tools of the same connection that allow `"app"`. They go through the same policy, Ask-first approval and audit path as a connection test call. | `server/src/routes/mcp-apps.ts` | +| Chat | A run's views render with that run's reply, outside the folded tool history, under a "Widget from " label. Views are keyed by the reply's run, so settled history needs no transcript. A task's views load in one request and are indexed by run once. | `ui/src/components/mcp-app/`, `TaskChatRunnerTurn.tsx` and `TaskChatThreadView.tsx` | + +### Sandbox + +The view runs in a `srcdoc` iframe with `sandbox="allow-scripts allow-popups +allow-popups-to-escape-sandbox"`. It never gets `allow-same-origin`. Its origin +is therefore opaque, so it cannot read Paperclip's DOM, cookies or storage, and +it cannot call the Paperclip API. + +The spec's double-iframe proxy on a separate origin solves the same problem for +hosts that render on their own origin. Paperclip uses a single opaque-origin +frame instead and installs the CSP itself: + +- The CSP is a `` placed before any of the view's markup. +- It starts from the spec's restrictive default and adds only well-formed + `https://` origins that the server declared. +- Keywords, schemes, paths and `*` are dropped. +- Without declared origins, `connect-src` and `frame-src` are `'none'`. + +Messages are accepted only from the iframe's own window. The host sends nothing +until the view reports `initialized`. + +The host answers view requests as follows: + +- `ui/open-link` opens only `http(s)` URLs, in a new tab without an opener. +- `ui/message` is refused (method not found), because posting to the task on + the user's behalf needs its own consent flow. +- `ui/update-model-context` is accepted but not yet sent to the agent. +- Display mode is always `inline`. + +## Testing plan + +| Level | What it proves | Command or location | +| --- | --- | --- | +| Shared unit | `_meta.ui` parsing (current and legacy keys, visibility, non-`ui://` rejected), resource parsing (text and base64, mime check), CSP sanitizing | `pnpm exec vitest run packages/shared/src/mcp-apps.test.ts` | +| UI unit | Host protocol: initialize result, nothing sent before `initialized`, tool input before tool result, `tools/call` proxy and errors, link and method refusals, teardown. CSP placed before the view's markup. The run index at a realistic size. | `pnpm exec vitest run ui/src/components/mcp-app/` | +| Server integration (embedded Postgres) | Circleback catalog OAuth (DCR) against a fake Circleback server. `ui_meta` stored. An app-only tool is hidden from the agent. An agent call records one view with input, structured content and `_meta`, and a call without a view records none. Routes list the view and serve its document and CSP. A view's tool call works, and a model-only tool is refused. Other tasks, other companies and agent actors are refused. | `pnpm exec vitest run server/src/__tests__/mcp-apps.test.ts` | +| Storybook | The view with the agent's reply, the ready view (Refresh calls a tool), loading, view unavailable, and a tool call that needs approval. The fixture view follows the protocol by hand. | `Tasks/MCP App views` (`ui/storybook/stories/tasks/task-chat-mcp-app.stories.tsx`) | +| Live end to end | Connect Circleback with a real account and ask an agent for a recap of a recent meeting. Check that the chat shows the meeting cards and that clicking a card opens Circleback. Done on 2026-11-12. The run found the view-size and placement bugs. | Manual, local `pnpm dev` | + +## Limits and follow-ups + +- Only `inline` display mode is supported. There is no fullscreen or + picture-in-picture yet. +- A view's `ui/message` and `ui/update-model-context` do not reach the agent yet. +- Views are rendered in the task chat only, not in other transcript surfaces. +- A view document can be at most 4 MB of HTML. Circleback's is about 3.5 MB. +- Local stdio MCP servers are recorded the same way, but no stdio provider with + views has been verified yet. diff --git a/doc/connections/README.md b/doc/connections/README.md index ab5f12475cf..b93ec6709d2 100644 --- a/doc/connections/README.md +++ b/doc/connections/README.md @@ -17,7 +17,7 @@ Runtime authentication: [AI Connections](./AI-CONNECTIONS.md). Long-term memory: [Experimental memory connectors](./MEMORY.md). Provider notes: [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), +[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), [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: diff --git a/doc/connections/tool-method-permission-reviews.json b/doc/connections/tool-method-permission-reviews.json index 405ad058330..9aff2b163af 100644 --- a/doc/connections/tool-method-permission-reviews.json +++ b/doc/connections/tool-method-permission-reviews.json @@ -614,6 +614,26 @@ "liveProof": "not-run", "keyPermissions": "Use an API key for an account with write access to the meetings your agents need to share, rename, move or turn into soundbites. Paperclip cannot increase the key\u2019s permissions." }, + { + "app": "circleback", + "method": "mcp-oauth", + "auth": "oauth", + "policy": "explicit", + "requestedScopes": [ + "user", + "user:write" + ], + "capability": "write", + "supportedActions": "Search and read meetings, notes, transcripts, action items, calendar events, connected email threads, people and company profiles, tags, folders, teams and support articles; show meetings, action items and calendar events as MCP Apps cards; create, update and delete action items, tags and folders; update meeting notes, tags and folders and upcoming calendar events' private notes and tags; share meetings and folders with people, teams, the workspace or anyone with the link, or remove access; send feedback to Circleback. Access is bounded by the signed-in user's Circleback permissions.", + "evidence": [ + "https://circleback.ai/docs/support/platform/circleback-mcp", + "https://circleback.ai/.well-known/oauth-protected-resource/api/mcp", + "https://circleback.ai/.well-known/oauth-authorization-server" + ], + "reviewedAt": "2026-11-12", + "liveProof": "not-run", + "evidenceLimit": "Public metadata and the provider's tool reference only. Circleback documents scope=user user:write as its default grant and scope=user as read-only; write tools then fail and ask the user to reconnect. The unauthenticated 401 challenge also names scope=\"user user:write\". No Paperclip account connection, discovery, governed write or revocation was run." + }, { "app": "gauge", "method": "mcp-oauth", diff --git a/packages/db/src/migrations/0473_elite_kat_farrell.sql b/packages/db/src/migrations/0473_elite_kat_farrell.sql new file mode 100644 index 00000000000..5bced602669 --- /dev/null +++ b/packages/db/src/migrations/0473_elite_kat_farrell.sql @@ -0,0 +1,29 @@ +CREATE TABLE "tool_mcp_app_views" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "invocation_id" uuid, + "issue_id" uuid, + "run_id" uuid, + "agent_id" uuid, + "responsible_user_id" text, + "connection_id" uuid NOT NULL, + "catalog_entry_id" uuid, + "application_name" text NOT NULL, + "tool_name" text NOT NULL, + "upstream_tool_name" text NOT NULL, + "resource_uri" text NOT NULL, + "tool_input" jsonb DEFAULT '{}'::jsonb NOT NULL, + "tool_result" jsonb NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "tool_catalog_entries" ADD COLUMN "ui_meta" jsonb;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_invocation_id_tool_invocations_id_fk" FOREIGN KEY ("invocation_id") REFERENCES "public"."tool_invocations"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_run_id_heartbeat_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."heartbeat_runs"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_connection_id_tool_connections_id_fk" FOREIGN KEY ("connection_id") REFERENCES "public"."tool_connections"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "tool_mcp_app_views" ADD CONSTRAINT "tool_mcp_app_views_catalog_entry_id_tool_catalog_entries_id_fk" FOREIGN KEY ("catalog_entry_id") REFERENCES "public"."tool_catalog_entries"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "tool_mcp_app_views_issue_idx" ON "tool_mcp_app_views" USING btree ("company_id","issue_id","created_at");--> statement-breakpoint +CREATE INDEX "tool_mcp_app_views_connection_idx" ON "tool_mcp_app_views" USING btree ("connection_id"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0468_snapshot.json b/packages/db/src/migrations/meta/0473_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0468_snapshot.json rename to packages/db/src/migrations/meta/0473_snapshot.json index 899f79e1f2b..45d0244b9e7 100644 --- a/packages/db/src/migrations/meta/0468_snapshot.json +++ b/packages/db/src/migrations/meta/0473_snapshot.json @@ -1,6 +1,6 @@ { - "id": "c06d4653-b3df-4e3e-bbf9-6de9b37cf806", - "prevId": "426d1f42-0983-4c6b-bb8d-5c798eee915a", + "id": "f14430e8-1ebf-414a-8c89-93c32740c4e6", + "prevId": "77704cfc-2cbe-41de-9d2c-5225b8466646", "version": "7", "dialect": "postgresql", "tables": { @@ -1417,6 +1417,34 @@ "concurrently": false, "method": "btree", "with": {} + }, + "activity_log_company_handled_for_created_idx": { + "name": "activity_log_company_handled_for_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"details\" ->> 'handledForUserId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(\"activity_log\".\"details\" ->> 'handledForUserId') IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -16340,6 +16368,18 @@ "primaryKey": false, "notNull": false }, + "default_decision_owner_user_id": { + "name": "default_decision_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "budget_owner_user_id": { + "name": "budget_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "require_board_approval_for_new_agents": { "name": "require_board_approval_for_new_agents", "type": "boolean", @@ -22302,6 +22342,18 @@ "type": "timestamp with time zone", "primaryKey": false, "notNull": false + }, + "dispatching_at": { + "name": "dispatching_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "dispatch_lease_expires_at": { + "name": "dispatch_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false } }, "indexes": { @@ -35606,6 +35658,34 @@ "method": "btree", "with": {} }, + "heartbeat_runs_queued_created_idx": { + "name": "heartbeat_runs_queued_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" = 'queued'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_cost_accounting_pending_idx": { "name": "heartbeat_runs_cost_accounting_pending_idx", "columns": [ @@ -36235,6 +36315,12 @@ "primaryKey": false, "notNull": false }, + "fingerprint": { + "name": "fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -51040,6 +51126,12 @@ "primaryKey": false, "notNull": false }, + "decision_owner_user_id": { + "name": "decision_owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "target_date": { "name": "target_date", "type": "date", @@ -53594,6 +53686,12 @@ "primaryKey": false, "notNull": true }, + "pending_delete_object_key": { + "name": "pending_delete_object_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -53617,6 +53715,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "runner_api_response_reservations_asset_idx": { + "name": "runner_api_response_reservations_asset_idx", + "columns": [ + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -57422,6 +57535,12 @@ "notNull": true, "default": "'{}'::jsonb" }, + "ui_meta": { + "name": "ui_meta", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "risk_level": { "name": "risk_level", "type": "text", @@ -59547,6 +59666,253 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.tool_mcp_app_views": { + "name": "tool_mcp_app_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "invocation_id": { + "name": "invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "catalog_entry_id": { + "name": "catalog_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "application_name": { + "name": "application_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_name": { + "name": "tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "upstream_tool_name": { + "name": "upstream_tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_uri": { + "name": "resource_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_input": { + "name": "tool_input", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "tool_result": { + "name": "tool_result", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_app_views_issue_idx": { + "name": "tool_mcp_app_views_issue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_app_views_connection_idx": { + "name": "tool_mcp_app_views_connection_idx", + "columns": [ + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_app_views_company_id_companies_id_fk": { + "name": "tool_mcp_app_views_company_id_companies_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_app_views_invocation_id_tool_invocations_id_fk": { + "name": "tool_mcp_app_views_invocation_id_tool_invocations_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "tool_invocations", + "columnsFrom": [ + "invocation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tool_mcp_app_views_issue_id_issues_id_fk": { + "name": "tool_mcp_app_views_issue_id_issues_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_app_views_run_id_heartbeat_runs_id_fk": { + "name": "tool_mcp_app_views_run_id_heartbeat_runs_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "heartbeat_runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tool_mcp_app_views_agent_id_agents_id_fk": { + "name": "tool_mcp_app_views_agent_id_agents_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tool_mcp_app_views_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_app_views_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_app_views_catalog_entry_id_tool_catalog_entries_id_fk": { + "name": "tool_mcp_app_views_catalog_entry_id_tool_catalog_entries_id_fk", + "tableFrom": "tool_mcp_app_views", + "tableTo": "tool_catalog_entries", + "columnsFrom": [ + "catalog_entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.tool_mcp_gateway_tokens": { "name": "tool_mcp_gateway_tokens", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 7238172ae7a..c9b59045d74 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3298,6 +3298,13 @@ "when": 1794503924304, "tag": "0472_runner_api_capture_pending_deletes", "breakpoints": true + }, + { + "idx": 473, + "version": "7", + "when": 1794508336827, + "tag": "0473_elite_kat_farrell", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 7812dfde547..e189d96a0de 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -190,6 +190,7 @@ export { toolGatewaySessions, connectionTokenIssuances, toolInvocations, + toolMcpAppViews, toolActionRequests, toolCallEvents, toolRateLimitCounters, diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index 9fe6662d314..968795a13d0 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -19,6 +19,7 @@ import type { ConnectionAgentInstructions, ConnectionTokenIssuanceOutcome, ConnectionTokenIssuancePath, + McpAppToolUi, McpConnectionCredentialRef, ToolActionRequestStatus, ToolApplicationStatus, @@ -382,6 +383,8 @@ export const toolCatalogEntries = pgTable( inputSchema: jsonb("input_schema").$type>().notNull().default({}), outputSchema: jsonb("output_schema").$type>(), annotations: jsonb("annotations").$type>().notNull().default({}), + /** Normalized MCP Apps `_meta.ui` declaration (`ui://` view), when the tool has one. */ + uiMeta: jsonb("ui_meta").$type(), riskLevel: text("risk_level").$type().notNull().default("read"), isReadOnly: boolean("is_read_only").notNull().default(true), isWrite: boolean("is_write").notNull().default(false), @@ -809,6 +812,37 @@ export const toolInvocations = pgTable( ], ); +/** + * One completed call to a tool that declares an MCP Apps view. Holds what the + * task chat needs to render the view: the call's arguments and its redacted + * result. The view document itself is read from the connection on demand. + */ +export const toolMcpAppViews = pgTable( + "tool_mcp_app_views", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + invocationId: uuid("invocation_id").references(() => toolInvocations.id, { onDelete: "set null" }), + issueId: uuid("issue_id").references(() => issues.id, { onDelete: "cascade" }), + runId: uuid("run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + agentId: uuid("agent_id").references(() => agents.id, { onDelete: "set null" }), + responsibleUserId: text("responsible_user_id"), + connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }), + catalogEntryId: uuid("catalog_entry_id").references(() => toolCatalogEntries.id, { onDelete: "set null" }), + applicationName: text("application_name").notNull(), + toolName: text("tool_name").notNull(), + upstreamToolName: text("upstream_tool_name").notNull(), + resourceUri: text("resource_uri").notNull(), + toolInput: jsonb("tool_input").$type>().notNull().default({}), + toolResult: jsonb("tool_result").$type>().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + index("tool_mcp_app_views_issue_idx").on(table.companyId, table.issueId, table.createdAt), + index("tool_mcp_app_views_connection_idx").on(table.connectionId), + ], +); + export const toolActionRequests = pgTable( "tool_action_requests", { diff --git a/packages/shared/src/app-definitions-url.test.ts b/packages/shared/src/app-definitions-url.test.ts index 7378d29fd84..56792d6745a 100644 --- a/packages/shared/src/app-definitions-url.test.ts +++ b/packages/shared/src/app-definitions-url.test.ts @@ -14,6 +14,8 @@ describe("tool app gallery URL matching", () => { expect(getAppDefinitionForUrl("https://workspace.google.com/")?.slug).toBe("google-workspace"); expect(getAppDefinitionForUrl("https://mcp.neon.tech/mcp")?.slug).toBe("neon"); expect(getAppDefinitionForUrl("https://app.withgauge.com/mcp")?.slug).toBe("gauge"); + expect(getAppDefinitionForUrl("https://circleback.ai/api/mcp")?.slug).toBe("circleback"); + expect(getAppDefinitionForUrl("https://app.circleback.ai/api/mcp")?.slug).toBe("circleback"); expect(getAppDefinitionForUrl("https://api.dittowords.com/v2/mcp")?.slug).toBe("ditto"); expect(getAppDefinitionForUrl("https://www.superagent.sh/mcp")?.slug).toBe("superagent"); }); diff --git a/packages/shared/src/app-definitions.generated.ts b/packages/shared/src/app-definitions.generated.ts index d74319a5c96..e314e97d3b5 100644 --- a/packages/shared/src/app-definitions.generated.ts +++ b/packages/shared/src/app-definitions.generated.ts @@ -83,30 +83,31 @@ import a81 from "./app-definitions/clickup.json" with { type: "json" }; import a82 from "./app-definitions/klaviyo.json" with { type: "json" }; import a83 from "./app-definitions/ditto.json" with { type: "json" }; import a84 from "./app-definitions/braintrust.json" with { type: "json" }; -import a85 from "./app-definitions/google-workspace.json" with { type: "json" }; -import a86 from "./app-definitions/gmail.json" with { type: "json" }; -import a87 from "./app-definitions/google-drive.json" with { type: "json" }; -import a88 from "./app-definitions/google-docs.json" with { type: "json" }; -import a89 from "./app-definitions/google-sheets.json" with { type: "json" }; -import a90 from "./app-definitions/google-slides.json" with { type: "json" }; -import a91 from "./app-definitions/google-calendar.json" with { type: "json" }; -import a92 from "./app-definitions/google-chat.json" with { type: "json" }; -import a93 from "./app-definitions/google-people.json" with { type: "json" }; -import a94 from "./app-definitions/google-workspace-search.json" with { type: "json" }; -import a95 from "./app-definitions/openai.json" with { type: "json" }; -import a96 from "./app-definitions/openrouter.json" with { type: "json" }; -import a97 from "./app-definitions/xai.json" with { type: "json" }; -import a98 from "./app-definitions/google.json" with { type: "json" }; -import a99 from "./app-definitions/bedrock.json" with { type: "json" }; -import a100 from "./app-definitions/responses-api.json" with { type: "json" }; -import a101 from "./app-definitions/messages-api.json" with { type: "json" }; -import a102 from "./app-definitions/chat-completions-api.json" with { type: "json" }; -import a103 from "./app-definitions/local.json" with { type: "json" }; -import a104 from "./app-definitions/1password.json" with { type: "json" }; -import a105 from "./app-definitions/daytona.json" with { type: "json" }; -import a106 from "./app-definitions/monday.json" with { type: "json" }; -import a107 from "./app-definitions/paperclip-notebook.json" with { type: "json" }; -import a108 from "./app-definitions/unikraft.json" with { type: "json" }; -import a109 from "./app-definitions/speko.json" with { type: "json" }; +import a85 from "./app-definitions/circleback.json" with { type: "json" }; +import a86 from "./app-definitions/google-workspace.json" with { type: "json" }; +import a87 from "./app-definitions/gmail.json" with { type: "json" }; +import a88 from "./app-definitions/google-drive.json" with { type: "json" }; +import a89 from "./app-definitions/google-docs.json" with { type: "json" }; +import a90 from "./app-definitions/google-sheets.json" with { type: "json" }; +import a91 from "./app-definitions/google-slides.json" with { type: "json" }; +import a92 from "./app-definitions/google-calendar.json" with { type: "json" }; +import a93 from "./app-definitions/google-chat.json" with { type: "json" }; +import a94 from "./app-definitions/google-people.json" with { type: "json" }; +import a95 from "./app-definitions/google-workspace-search.json" with { type: "json" }; +import a96 from "./app-definitions/openai.json" with { type: "json" }; +import a97 from "./app-definitions/openrouter.json" with { type: "json" }; +import a98 from "./app-definitions/xai.json" with { type: "json" }; +import a99 from "./app-definitions/google.json" with { type: "json" }; +import a100 from "./app-definitions/bedrock.json" with { type: "json" }; +import a101 from "./app-definitions/responses-api.json" with { type: "json" }; +import a102 from "./app-definitions/messages-api.json" with { type: "json" }; +import a103 from "./app-definitions/chat-completions-api.json" with { type: "json" }; +import a104 from "./app-definitions/local.json" with { type: "json" }; +import a105 from "./app-definitions/1password.json" with { type: "json" }; +import a106 from "./app-definitions/daytona.json" with { type: "json" }; +import a107 from "./app-definitions/monday.json" with { type: "json" }; +import a108 from "./app-definitions/paperclip-notebook.json" with { type: "json" }; +import a109 from "./app-definitions/unikraft.json" with { type: "json" }; +import a110 from "./app-definitions/speko.json" with { type: "json" }; import type { AppDefinition } from "./types/app-definition.js"; -export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102,a103,a104,a105,a106,a107,a108,a109] as AppDefinition[]; +export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102,a103,a104,a105,a106,a107,a108,a109,a110] as AppDefinition[]; diff --git a/packages/shared/src/app-definitions.test.ts b/packages/shared/src/app-definitions.test.ts index 3c048c63a6d..54cf668cf97 100644 --- a/packages/shared/src/app-definitions.test.ts +++ b/packages/shared/src/app-definitions.test.ts @@ -294,7 +294,7 @@ describe("AppDefinition catalog", () => { "google-workspace-search", ]), ); - expect(SELF_SERVE_MCP_CANDIDATES).toHaveLength(65); + expect(SELF_SERVE_MCP_CANDIDATES).toHaveLength(66); expect(BLOCKED_MCP_PROVIDERS.map((entry) => entry.slug)).toEqual([ "g2", "vercel", @@ -460,15 +460,15 @@ describe("AppDefinition catalog", () => { expect(channel("slack")?.guidanceMd).toContain("reactions"); expect(channel("slack")?.guidanceMd).toContain("direct messages"); }); - it("keeps a complete, unique, dated evidence ledger for all 69 researched MCP providers", () => { + it("keeps a complete, unique, dated evidence ledger for all 70 researched MCP providers", () => { // Ledger-wide date reflects the last full re-verification (2026-08-26); // later provider additions carry their own research evidence, but // bumping the shared date would overstate freshness for the other providers. expect(SELF_SERVE_MCP_RESEARCH.verifiedAt).toBe("2026-08-26"); - expect(SELF_SERVE_MCP_RESEARCH.entries).toHaveLength(69); + expect(SELF_SERVE_MCP_RESEARCH.entries).toHaveLength(70); expect( new Set(SELF_SERVE_MCP_RESEARCH.entries.map((entry) => entry.slug)), - ).toHaveProperty("size", 69); + ).toHaveProperty("size", 70); for (const entry of SELF_SERVE_MCP_RESEARCH.entries) { expect(new URL(entry.docsUrl).protocol).toBe("https:"); expect(new URL(entry.serverUrl).protocol).toBe("https:"); @@ -905,7 +905,7 @@ describe("AppDefinition catalog", () => { "ticktick", "xero", ]); - expect(APP_STORE_DEFINITIONS).toHaveLength(88); + expect(APP_STORE_DEFINITIONS).toHaveLength(89); const connectableSlugs = new Set( CONNECTABLE_APP_DEFINITIONS.map((entry) => entry.slug), ); @@ -1340,6 +1340,37 @@ describe("AppDefinition catalog", () => { ]); expect(method!.tenantFields?.[0]?.options?.map((option) => option.value)).toEqual(["dal", "fra", "sfo", "sin", "was"]); }); + it("connects Circleback's hosted server with browser sign-in and its documented read/write scopes", () => { + const circleback = APP_DEFINITIONS.find((app) => app.slug === "circleback")!; + expect(circleback).toMatchObject({ + name: "Circleback", + categories: ["productivity"], + urlPatterns: ["https://circleback.ai/*", "https://app.circleback.ai/*"], + docsUrl: "https://circleback.ai/docs/support/platform/circleback-mcp", + branding: { logoUrl: "/brands/apps/circleback.png" }, + redirectConstraints: "https-or-loopback-http", + }); + expect(APP_STORE_DEFINITIONS.some((app) => app.slug === "circleback")).toBe(true); + expect(CONNECTABLE_APP_DEFINITIONS.some((app) => app.slug === "circleback")).toBe(true); + // Circleback documents no API key for its MCP server. + expect(circleback.methods).toHaveLength(1); + expect(circleback.methods[0]).toMatchObject({ + key: "mcp-oauth", + label: "Sign in with Circleback", + transport: "mcp_remote", + auth: "oauth", + ownershipModes: ["dcr"], + riskTier: "S3", + // `user` alone is read-only; write tools then ask the user to reconnect. + defaults: { serverUrl: "https://circleback.ai/api/mcp", scopesHint: ["user", "user:write"] }, + capabilityProfile: { key: "write", description: expect.stringContaining("Set share and delete actions to Ask first") }, + }); + expect(circleback.methods[0]!.tenantFields ?? []).toEqual([]); + expect(circleback.methods[0]!.warnings).toEqual([ + expect.stringContaining("A Circleback account"), + expect.stringContaining("anyone with the link"), + ]); + }); it("connects Gauge's hosted server with browser sign-in or an organization API key", () => { const gauge = APP_DEFINITIONS.find((app) => app.slug === "gauge")!; expect(gauge).toMatchObject({ diff --git a/packages/shared/src/app-definitions/circleback.json b/packages/shared/src/app-definitions/circleback.json new file mode 100644 index 00000000000..2b05e87c356 --- /dev/null +++ b/packages/shared/src/app-definitions/circleback.json @@ -0,0 +1,52 @@ +{ + "schemaVersion": 1, + "slug": "circleback", + "name": "Circleback", + "description": "Search meeting notes, transcripts, action items, calendar events and emails, and show meetings as cards in chat.", + "categories": [ + "productivity" + ], + "featured": false, + "branding": { + "logoUrl": "/brands/apps/circleback.png" + }, + "urlPatterns": [ + "https://circleback.ai/*", + "https://app.circleback.ai/*" + ], + "docsUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", + "redirectConstraints": "https-or-loopback-http", + "methods": [ + { + "key": "mcp-oauth", + "label": "Sign in with Circleback", + "transport": "mcp_remote", + "auth": "oauth", + "ownershipModes": [ + "dcr" + ], + "whenToUse": "Use browser sign-in for Circleback's hosted MCP server.", + "defaults": { + "serverUrl": "https://circleback.ai/api/mcp", + "scopesHint": [ + "user", + "user:write" + ] + }, + "guidanceMd": "Sign in to Circleback and approve access. The connection acts as the Circleback user who signs in and sees the meetings, action items, calendar events and connected email that user can see. Write tools start enabled and remain governed by Paperclip's action policies.", + "warnings": [ + "A Circleback account. The connection reads the signed-in user's meetings, transcripts, calendar and connected email.", + "Circleback share tools can share meetings and folders with other people or anyone with the link, and delete tools cannot be undone. Set share and delete actions to Ask first before agents run unattended." + ], + "consoleLinks": { + "docs": "https://circleback.ai/docs/support/platform/circleback-mcp" + }, + "riskTier": "S3", + "capabilityProfile": { + "key": "write", + "label": "Read and write", + "description": "Search and read meetings, transcripts, action items, calendar events and email, and manage action items, tags, folders and meeting notes. Circleback share tools can share meetings and folders with other people or anyone with the link, and delete tools cannot be undone. Set share and delete actions to Ask first before agents run unattended." + } + } + ] +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 58b6dac8a1f..f9865d8aa6a 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2961,3 +2961,4 @@ export { issueActivityChangesTaskIdentity, } from "./issue-activity-identity.js"; export { recognizeLinkPreview, type LinkPreviewTarget, type LinkPreviewState, type LinkPreview, type LinkPreviewResult } from "./link-preview.js"; +export * from "./mcp-apps.js"; diff --git a/packages/shared/src/mcp-apps.test.ts b/packages/shared/src/mcp-apps.test.ts new file mode 100644 index 00000000000..848f3247bdc --- /dev/null +++ b/packages/shared/src/mcp-apps.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; +import { + MCP_APP_MIME_TYPE, + buildMcpAppCsp, + mcpAppToolCallableFromApp, + mcpAppToolVisibleToModel, + readMcpAppResource, + readMcpAppToolUi, + sanitizeMcpAppCspSource, +} from "./mcp-apps.js"; + +describe("readMcpAppToolUi", () => { + it("reads _meta.ui.resourceUri with the default visibility", () => { + expect(readMcpAppToolUi({ ui: { resourceUri: "ui://circleback/meetings" } })).toEqual({ + resourceUri: "ui://circleback/meetings", + visibility: ["model", "app"], + }); + }); + + it("accepts the deprecated flat key and an explicit visibility", () => { + expect(readMcpAppToolUi({ "ui/resourceUri": "ui://x/view" })?.resourceUri).toBe("ui://x/view"); + const appOnly = readMcpAppToolUi({ ui: { resourceUri: "ui://x/view", visibility: ["app", "bogus"] } }); + expect(appOnly?.visibility).toEqual(["app"]); + expect(mcpAppToolVisibleToModel(appOnly)).toBe(false); + expect(mcpAppToolCallableFromApp(appOnly)).toBe(true); + }); + + it("keeps visibility for an app-only helper without a view", () => { + const helper = readMcpAppToolUi({ ui: { visibility: ["app"] } }); + expect(helper).toEqual({ resourceUri: null, visibility: ["app"] }); + expect(mcpAppToolVisibleToModel(helper)).toBe(false); + expect(mcpAppToolVisibleToModel(readMcpAppToolUi({ ui: { resourceUri: "https://evil.example", visibility: ["app"] } }))).toBe(false); + expect(mcpAppToolVisibleToModel(readMcpAppToolUi({ ui: { visibility: [] } }))).toBe(false); + }); + + it("ignores tools without a ui:// view", () => { + expect(readMcpAppToolUi(undefined)).toBeNull(); + expect(readMcpAppToolUi({ ui: { resourceUri: "https://evil.example/view" } })).toBeNull(); + expect(mcpAppToolVisibleToModel(null)).toBe(true); + }); +}); + +describe("readMcpAppResource", () => { + const uri = "ui://circleback/meetings"; + it("reads text content with its csp and border hints", () => { + const resource = readMcpAppResource({ + contents: [{ + uri, + mimeType: MCP_APP_MIME_TYPE, + text: "hi", + _meta: { ui: { csp: { resourceDomains: ["https://cdn.circleback.ai"] }, prefersBorder: false } }, + }], + }, uri); + expect(resource).toMatchObject({ html: "hi", prefersBorder: false, csp: { resourceDomains: ["https://cdn.circleback.ai"] } }); + }); + + it("decodes base64 blob content", () => { + const blob = Buffer.from("

café

", "utf8").toString("base64"); + expect(readMcpAppResource({ contents: [{ uri, mimeType: "text/html; profile=mcp-app", blob }] }, uri)?.html).toBe("

café

"); + }); + + it("rejects other mime types and other resources", () => { + expect(readMcpAppResource({ contents: [{ uri, mimeType: "text/html", text: "

x

" }] }, uri)).toBeNull(); + expect(readMcpAppResource({ contents: [{ uri: "ui://other", mimeType: MCP_APP_MIME_TYPE, text: "

x

" }] }, uri)).toBeNull(); + }); +}); + +describe("buildMcpAppCsp", () => { + it("defaults to no network access", () => { + const csp = buildMcpAppCsp({}); + expect(csp).toContain("default-src 'none'"); + expect(csp).toContain("connect-src 'none'"); + expect(csp).toContain("frame-src 'none'"); + }); + + it("adds only well-formed https origins the server declared", () => { + const csp = buildMcpAppCsp({ + connectDomains: ["https://api.circleback.ai", "https://x.com; script-src *", "http://insecure.example", "*"], + resourceDomains: ["https://*.circleback.ai"], + }); + expect(csp).toContain("connect-src https://api.circleback.ai;"); + expect(csp).toContain("script-src 'unsafe-inline' https://*.circleback.ai;"); + expect(csp).not.toContain("insecure"); + expect(csp).not.toMatch(/script-src \*/); + }); + + it("sanitizes sources", () => { + expect(sanitizeMcpAppCspSource("https://Example.COM/")).toBe("https://example.com"); + expect(sanitizeMcpAppCspSource("'unsafe-eval'")).toBeNull(); + expect(sanitizeMcpAppCspSource("https://a.com/path")).toBeNull(); + }); +}); diff --git a/packages/shared/src/mcp-apps.ts b/packages/shared/src/mcp-apps.ts new file mode 100644 index 00000000000..12831e28596 --- /dev/null +++ b/packages/shared/src/mcp-apps.ts @@ -0,0 +1,223 @@ +/** + * MCP Apps (SEP-1865, spec 2026-01-26): interactive `ui://` views that an MCP + * server attaches to a tool. Paperclip is the host: it keeps the tool's UI + * declaration, records each call whose tool has one, and renders the view in a + * sandboxed iframe in the task chat. + * + * https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx + */ + +import { z } from "zod"; + +export const MCP_APPS_EXTENSION_ID = "io.modelcontextprotocol/ui"; +export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app"; +export const MCP_APPS_PROTOCOL_VERSION = "2026-01-26"; +/** Largest view document Paperclip renders. Larger documents fall back to the plain tool row. */ +export const MCP_APP_MAX_HTML_BYTES = 4 * 1024 * 1024; + +/** Client capability Paperclip advertises in `initialize` to MCP servers. */ +export const MCP_APPS_CLIENT_CAPABILITY = { + [MCP_APPS_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME_TYPE] }, +} as const; + +export type McpAppToolVisibility = "model" | "app"; + +/** + * A tool's normalized `_meta.ui` declaration. `resourceUri` is null for a tool + * that only declares visibility, such as an app-only helper without a view. + */ +export interface McpAppToolUi { + resourceUri: string | null; + visibility: McpAppToolVisibility[]; +} + +export interface McpAppResourceCsp { + connectDomains?: string[]; + resourceDomains?: string[]; + frameDomains?: string[]; + baseUriDomains?: string[]; +} + +export interface McpAppResourcePermissions { + camera?: boolean; + microphone?: boolean; + geolocation?: boolean; + clipboardWrite?: boolean; +} + +/** The view document plus the resource's `_meta.ui` rendering hints. */ +export interface McpAppResource { + uri: string; + html: string; + csp: McpAppResourceCsp; + permissions: McpAppResourcePermissions; + prefersBorder: boolean | null; +} + +/** One recorded tool call whose tool declares a view. */ +export interface McpAppViewSummary { + id: string; + issueId: string | null; + runId: string | null; + connectionId: string; + applicationName: string; + /** Name the agent called (the gateway tool name). */ + toolName: string; + /** The provider's own tool name. */ + upstreamToolName: string; + resourceUri: string; + toolInput: Record; + createdAt: string; +} + +export interface McpAppViewDetail extends McpAppViewSummary { + /** The MCP `CallToolResult` sent to the view as `ui/notifications/tool-result`. */ + toolResult: McpAppCallToolResult; + resource: McpAppResource; +} + +export interface McpAppCallToolResult { + content: unknown[]; + structuredContent?: Record; + _meta?: Record; + isError?: boolean; +} + +/** Body of `POST /api/issues/:issueId/mcp-app-views/:viewId/tool-calls`: a view's `tools/call`. */ +export const mcpAppToolCallSchema = z.object({ + name: z.string().min(1).max(256), + arguments: z.record(z.string(), z.unknown()).optional(), +}).strict(); + +export type McpAppToolCallRequest = z.infer; + +function record(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; +} + +function stringList(value: unknown): string[] | undefined { + if (!Array.isArray(value)) return undefined; + const list = value.filter((item): item is string => typeof item === "string" && item.trim().length > 0).map((item) => item.trim()); + return list; +} + +/** + * Reads a tool's UI declaration from its `_meta`. Accepts the deprecated flat + * `_meta["ui/resourceUri"]` key, which servers still emit during the + * transition. Visibility is kept even without a view, so an app-only helper + * stays hidden from agents. Returns null when the tool declares neither. + */ +export function readMcpAppToolUi(meta: unknown): McpAppToolUi | null { + const metaRecord = record(meta); + if (!metaRecord) return null; + const ui = record(metaRecord.ui); + const rawUri = typeof ui?.resourceUri === "string" + ? ui.resourceUri + : typeof metaRecord["ui/resourceUri"] === "string" ? metaRecord["ui/resourceUri"] as string : null; + const resourceUri = rawUri && rawUri.startsWith("ui://") && rawUri.length <= 2048 ? rawUri : null; + const declared = Array.isArray(ui?.visibility) + ? (ui.visibility as unknown[]).filter((item): item is McpAppToolVisibility => item === "model" || item === "app") + : null; + if (!resourceUri && declared === null) return null; + // An explicit list with no valid entries (for example `[]`) grants nothing. + const visibility = declared === null ? ["model", "app"] as McpAppToolVisibility[] : [...new Set(declared)]; + return { resourceUri, visibility }; +} + +export function mcpAppToolVisibleToModel(ui: McpAppToolUi | null | undefined): boolean { + return !ui || ui.visibility.includes("model"); +} + +export function mcpAppToolCallableFromApp(ui: McpAppToolUi | null | undefined): boolean { + return !ui || ui.visibility.includes("app"); +} + +/** + * Picks the view document out of a `resources/read` result. The content must be + * the requested `ui://` resource with the MCP Apps mime type; `text` or base64 + * `blob` content is accepted. + */ +export function readMcpAppResource(result: unknown, uri: string): McpAppResource | null { + const contents = record(result)?.contents; + if (!Array.isArray(contents)) return null; + for (const item of contents) { + const content = record(item); + if (!content) continue; + if (typeof content.uri === "string" && content.uri !== uri) continue; + const mimeType = typeof content.mimeType === "string" ? content.mimeType.replace(/\s+/g, "").toLowerCase() : ""; + if (mimeType !== MCP_APP_MIME_TYPE) continue; + const html = typeof content.text === "string" + ? content.text + : typeof content.blob === "string" ? decodeBase64Utf8(content.blob) : null; + if (html === null || html.length === 0) continue; + const ui = record(record(content._meta)?.ui); + const csp = record(ui?.csp); + const permissions = record(ui?.permissions); + return { + uri, + html, + csp: { + connectDomains: stringList(csp?.connectDomains), + resourceDomains: stringList(csp?.resourceDomains), + frameDomains: stringList(csp?.frameDomains), + baseUriDomains: stringList(csp?.baseUriDomains), + }, + permissions: { + camera: permissions?.camera === true || record(permissions?.camera) !== null, + microphone: permissions?.microphone === true || record(permissions?.microphone) !== null, + geolocation: permissions?.geolocation === true || record(permissions?.geolocation) !== null, + clipboardWrite: permissions?.clipboardWrite === true || record(permissions?.clipboardWrite) !== null, + }, + prefersBorder: typeof ui?.prefersBorder === "boolean" ? ui.prefersBorder : null, + }; + } + return null; +} + +function decodeBase64Utf8(value: string): string | null { + try { + const binary = globalThis.atob(value); + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); + return new TextDecoder().decode(bytes); + } catch { + return null; + } +} + +/** + * A CSP source is accepted only when it is an https origin (optionally with a + * leading `*.` subdomain wildcard). Anything else (keywords, schemes, paths, + * quotes) is dropped so a server cannot widen the policy beyond origins. + */ +export function sanitizeMcpAppCspSource(source: string): string | null { + const trimmed = source.trim(); + const match = /^https:\/\/(\*\.)?([a-z0-9-]+(\.[a-z0-9-]+)+)(:\d{1,5})?\/?$/i.exec(trimmed); + if (!match) return null; + return `https://${match[1] ?? ""}${match[2]!.toLowerCase()}${match[4] ?? ""}`; +} + +/** + * The CSP for a view: the spec's restrictive default plus only the origins the + * server declared in `_meta.ui.csp`. + */ +export function buildMcpAppCsp(csp: McpAppResourceCsp): string { + const list = (values: string[] | undefined) => (values ?? []).map(sanitizeMcpAppCspSource).filter((value): value is string => value !== null); + const resource = list(csp.resourceDomains); + const connect = list(csp.connectDomains); + const frame = list(csp.frameDomains); + const base = list(csp.baseUriDomains); + const join = (...parts: string[]) => parts.filter(Boolean).join(" "); + return [ + "default-src 'none'", + `script-src ${join("'unsafe-inline'", ...resource)}`, + `style-src ${join("'unsafe-inline'", ...resource)}`, + `img-src ${join("data:", "blob:", ...resource)}`, + `font-src ${join("data:", ...resource)}`, + `media-src ${join("data:", "blob:", ...resource)}`, + `connect-src ${connect.length > 0 ? connect.join(" ") : "'none'"}`, + `frame-src ${frame.length > 0 ? frame.join(" ") : "'none'"}`, + `base-uri ${base.length > 0 ? base.join(" ") : "'none'"}`, + "object-src 'none'", + "form-action 'none'", + ].join("; "); +} diff --git a/packages/shared/src/self-serve-mcp-research.json b/packages/shared/src/self-serve-mcp-research.json index e9f6f621627..98a90544e8e 100644 --- a/packages/shared/src/self-serve-mcp-research.json +++ b/packages/shared/src/self-serve-mcp-research.json @@ -70,6 +70,7 @@ { "slug": "monday", "name": "monday.com", "wave": 2, "status": "blocked", "docsUrl": "https://developer.monday.com/api-reference/docs/integrate-with-monday-mcp", "serverUrl": "https://mcp.monday.com/mcp", "authMode": "provider_approval", "prerequisite": "Provider DCR rejects the Paperclip HTTPS callback with HTTP 400: redirect_uris are not allowed. Contact monday.com to allowlist the callback before OAuth setup; account-admin approval may also be needed.", "riskTier": "S4", "verifiedAt": "2026-10-09", "browserOnboarding": "blocked-callback-allowlist", "liveRead": "not-run", "blocker": "Provider callback allowlisting required" }, { "slug": "context7", "name": "Context7", "wave": 2, "status": "self_serve", "docsUrl": "https://context7.com/docs/api-guide", "serverUrl": "https://mcp.context7.com/mcp", "authMode": "public", "prerequisite": "No account or API key is required for anonymous remote MCP use; the official docs state anonymous requests have low rate limits. An optional API key raises limits and supports private repositories, but this curated method does not request or store one.", "riskTier": "S1", "verifiedAt": "2026-10-09", "browserOnboarding": "completed-public-no-auth", "liveRead": "passed: resolve-library-id and query-docs returned React public documentation; repeat query passed after reload with 0 agents selected", "liveWrite": "not-applicable", "blocker": null }, { "slug": "ditto", "name": "Ditto", "wave": 4, "status": "self_serve", "docsUrl": "https://developer.dittowords.com/guides/connect-the-mcp", "serverUrl": "https://api.dittowords.com/v2/mcp", "authMode": "dcr_or_api_key", "prerequisite": "A Ditto account in the workspace whose text and style guides agents should use. API keys require developer integrations on the Ditto plan.", "riskTier": "S4" }, - { "slug": "braintrust", "name": "Braintrust", "wave": 4, "status": "self_serve", "docsUrl": "https://www.braintrust.dev/docs/integrations/developer-tools/mcp", "serverUrl": "https://api.braintrust.dev/mcp", "authMode": "dcr_or_api_key", "prerequisite": "A Braintrust account or API key. Select US or EU to match the organization’s data plane region. Account permissions bound access; evaluations and Topics processing may consume credits, dataset edits can permanently delete rows, and automation status can enable retention or delivery.", "riskTier": "S4", "verifiedAt": "2026-10-21", "browserOnboarding": "completed-oauth: US mcp-oauth authorized a temporary personal connection in an isolated instance; authenticated discovery returned 49 tools", "liveRead": "passed: US mcp-oauth bounded list_recent_objects and synthetic dataset sql_query readback through actual process-agent runs and run-scoped gateway sessions", "liveWrite": "passed: US mcp-oauth edit_dataset_rows inserted one synthetic row into a new disposable dataset through an actual process-agent gateway call; row and dataset removed", "blocker": "US API-key and both EU methods remain untested against real accounts. Live token expiry/refresh, provider-side OAuth revocation, and native CLI automatic capability delivery remain unqualified.", "evidenceLimit": "Public regional metadata probes confirmed endpoints, Streamable HTTP, DCR, PKCE S256, refresh-token support, and scope mcp without registration or account authorization. Separate US OAuth account proof passed connect, discovery, bounded read, synthetic write/readback, real process-agent gateway calls, catalog refresh, OAuth reconnect, local removal, post-removal denial, and structural API/log redaction. Token expiry/refresh was not forced; structural redaction did not decrypt tokens for exact-value scanning. The provider reported identity scopes despite the mcp request. See doc/connections/BRAINTRUST.md and braintrust-qualification-2026-10-21.json for method-specific proof and limits; metadata and fixtures do not qualify the remaining methods or lifecycle gaps." } + { "slug": "braintrust", "name": "Braintrust", "wave": 4, "status": "self_serve", "docsUrl": "https://www.braintrust.dev/docs/integrations/developer-tools/mcp", "serverUrl": "https://api.braintrust.dev/mcp", "authMode": "dcr_or_api_key", "prerequisite": "A Braintrust account or API key. Select US or EU to match the organization’s data plane region. Account permissions bound access; evaluations and Topics processing may consume credits, dataset edits can permanently delete rows, and automation status can enable retention or delivery.", "riskTier": "S4", "verifiedAt": "2026-10-21", "browserOnboarding": "completed-oauth: US mcp-oauth authorized a temporary personal connection in an isolated instance; authenticated discovery returned 49 tools", "liveRead": "passed: US mcp-oauth bounded list_recent_objects and synthetic dataset sql_query readback through actual process-agent runs and run-scoped gateway sessions", "liveWrite": "passed: US mcp-oauth edit_dataset_rows inserted one synthetic row into a new disposable dataset through an actual process-agent gateway call; row and dataset removed", "blocker": "US API-key and both EU methods remain untested against real accounts. Live token expiry/refresh, provider-side OAuth revocation, and native CLI automatic capability delivery remain unqualified.", "evidenceLimit": "Public regional metadata probes confirmed endpoints, Streamable HTTP, DCR, PKCE S256, refresh-token support, and scope mcp without registration or account authorization. Separate US OAuth account proof passed connect, discovery, bounded read, synthetic write/readback, real process-agent gateway calls, catalog refresh, OAuth reconnect, local removal, post-removal denial, and structural API/log redaction. Token expiry/refresh was not forced; structural redaction did not decrypt tokens for exact-value scanning. The provider reported identity scopes despite the mcp request. See doc/connections/BRAINTRUST.md and braintrust-qualification-2026-10-21.json for method-specific proof and limits; metadata and fixtures do not qualify the remaining methods or lifecycle gaps." }, + { "slug": "circleback", "name": "Circleback", "wave": 4, "status": "self_serve", "docsUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", "serverUrl": "https://circleback.ai/api/mcp", "authMode": "dcr", "prerequisite": "A Circleback account. The connection reads the signed-in user's meetings, transcripts, calendar and connected email.", "riskTier": "S3", "verifiedAt": "2026-11-12" } ] } diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index ec1bab56844..e9f7b60527c 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1,3 +1,4 @@ +import type { McpAppToolUi } from "../mcp-apps.js"; import type { ConnectionTokenIssuanceOutcome, ConnectionTokenIssuancePath, @@ -568,6 +569,8 @@ export interface ToolCatalogEntry { inputSchema: Record | null; outputSchema: Record | null; annotations: Record | null; + /** MCP Apps view declaration (`_meta.ui`), when the tool renders one. */ + uiMeta?: McpAppToolUi | null; riskLevel: ToolRiskLevel; isReadOnly: boolean; isWrite: boolean; diff --git a/scripts/app-definition-overrides/circleback.json b/scripts/app-definition-overrides/circleback.json new file mode 100644 index 00000000000..2b05e87c356 --- /dev/null +++ b/scripts/app-definition-overrides/circleback.json @@ -0,0 +1,52 @@ +{ + "schemaVersion": 1, + "slug": "circleback", + "name": "Circleback", + "description": "Search meeting notes, transcripts, action items, calendar events and emails, and show meetings as cards in chat.", + "categories": [ + "productivity" + ], + "featured": false, + "branding": { + "logoUrl": "/brands/apps/circleback.png" + }, + "urlPatterns": [ + "https://circleback.ai/*", + "https://app.circleback.ai/*" + ], + "docsUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", + "redirectConstraints": "https-or-loopback-http", + "methods": [ + { + "key": "mcp-oauth", + "label": "Sign in with Circleback", + "transport": "mcp_remote", + "auth": "oauth", + "ownershipModes": [ + "dcr" + ], + "whenToUse": "Use browser sign-in for Circleback's hosted MCP server.", + "defaults": { + "serverUrl": "https://circleback.ai/api/mcp", + "scopesHint": [ + "user", + "user:write" + ] + }, + "guidanceMd": "Sign in to Circleback and approve access. The connection acts as the Circleback user who signs in and sees the meetings, action items, calendar events and connected email that user can see. Write tools start enabled and remain governed by Paperclip's action policies.", + "warnings": [ + "A Circleback account. The connection reads the signed-in user's meetings, transcripts, calendar and connected email.", + "Circleback share tools can share meetings and folders with other people or anyone with the link, and delete tools cannot be undone. Set share and delete actions to Ask first before agents run unattended." + ], + "consoleLinks": { + "docs": "https://circleback.ai/docs/support/platform/circleback-mcp" + }, + "riskTier": "S3", + "capabilityProfile": { + "key": "write", + "label": "Read and write", + "description": "Search and read meetings, transcripts, action items, calendar events and email, and manage action items, tags, folders and meeting notes. Circleback share tools can share meetings and folders with other people or anyone with the link, and delete tools cannot be undone. Set share and delete actions to Ask first before agents run unattended." + } + } + ] +} diff --git a/server/src/__tests__/connection-aggregator-fallback.test.ts b/server/src/__tests__/connection-aggregator-fallback.test.ts index 1e98d0bce51..788f3288c5f 100644 --- a/server/src/__tests__/connection-aggregator-fallback.test.ts +++ b/server/src/__tests__/connection-aggregator-fallback.test.ts @@ -338,14 +338,14 @@ const support = await getEmbeddedPostgresTestSupport(); it("keeps an external typo as a discovery suggestion until its app is selected", async () => { await resetQuestions(); const result = await connectionIntentService(db).search(claims, - "Find Circlebak meeting transcripts and action items from yesterday"); - expect(result.results.some(item => item.service === "via:composio:circleback-mcp")).toBe(true); + "Find Fathm meeting transcripts and action items from yesterday"); + expect(result.results.some(item => item.service === "via:composio:fathom")).toBe(true); expect(result.providerQuestion).toBeUndefined(); expect(result.instruction).toContain("aggregator.targetService"); }); it.each([ - ["help me find tools for circle back", "circleback-mcp"], - ["Can you connect Circleback MCP to get all our meeting notes?", "circleback-mcp"], + ["help me find tools for otter ai", "otter-ai-mcp"], + ["Can you connect Fathom to get all our meeting notes?", "fathom"], ["Find Attio tools to review all our customer contacts before next week's meeting", "attio"], ["Help me find a ClickUp connection to organize our team's projects", "clickup"], ])("finds verified aggregator apps in natural-language queries: %s", async (query, target) => { @@ -379,18 +379,32 @@ const support = await getEmbeddedPostgresTestSupport(); }); it("returns multiple aggregator apps without inventing a combined route or choosing consent", async () => { await resetQuestions(); - const result = await connectionIntentService(db).search(claims, "Find Circleback and Attio tools"); - expect(result.results.map(item => item.service)).toEqual(expect.arrayContaining(["via:composio:circleback-mcp", "via:composio:attio"])); + const result = await connectionIntentService(db).search(claims, "Find Fathom and Attio tools"); + expect(result.results.map(item => item.service)).toEqual(expect.arrayContaining(["via:composio:fathom", "via:composio:attio"])); expect(result.providerQuestion).toBeUndefined(); expect(result.instruction).toContain("aggregator.targetService"); }); it("keeps native and aggregator app matches from the same query", async () => { await resetQuestions(); - const result = await connectionIntentService(db).search(claims, "Find Notion and Circleback tools"); - expect(result.results.map(item => item.service)).toEqual(expect.arrayContaining(["notion", "via:composio:circleback-mcp"])); + const result = await connectionIntentService(db).search(claims, "Find Notion and Fathom tools"); + expect(result.results.map(item => item.service)).toEqual(expect.arrayContaining(["notion", "via:composio:fathom"])); expect(result.providerQuestion).toBeUndefined(); }); + // Composio lists Circleback too (circleback_mcp), but with fewer tools and no + // meeting cards; the built-in connection answers these requests directly. + it.each([ + "help me find tools for circle back", + "Can you connect Circleback MCP to get all our meeting notes?", + "Find Circleback meeting transcripts and action items from yesterday", + ])("prefers the built-in Circleback connection over its aggregator listing: %s", async (query) => { + await resetQuestions(); + const result = await connectionIntentService(db).search(claims, query); + expect(result.results[0]?.service).toBe("circleback"); + expect(result.results.some(item => item.service.startsWith("via:"))).toBe(false); + expect(result.providerQuestion).toBeUndefined(); + expect(result.instruction).toContain("connection_request"); + }); it("prefers the built-in Jira connection and returns a direct instruction", async () => { await resetQuestions(); const result = await connectionIntentService(db).search( diff --git a/server/src/__tests__/connector-tool-policy.test.ts b/server/src/__tests__/connector-tool-policy.test.ts index f450c5c6670..baea80e0236 100644 --- a/server/src/__tests__/connector-tool-policy.test.ts +++ b/server/src/__tests__/connector-tool-policy.test.ts @@ -33,6 +33,29 @@ describe("reviewed connector risk dispatch", () => { expect(classifyRisk({ name: "new_tool", annotations: { readOnlyHint: true } }, "braintrust")).toBe("write"); }); + it("classifies Circleback's sharing and feedback tools as writes the generic verbs miss", () => { + // Red without the reviewed policy: "share" and "submit" are not generic write verbs. + expect(classifyRisk({ name: "ShareMeeting" }, "custom")).toBe("read"); + for (const name of ["ShareMeeting", "ShareFolder", "SubmitFeedback", "UpdateMeeting", "UpdateCalendarEvent", + "CreateActionItem", "UpdateActionItem", "CreateTag", "UpdateTag", "CreateFolder", "UpdateFolder"]) { + expect(classifyRisk({ name }, "circleback")).toBe("write"); + } + for (const name of ["DeleteActionItem", "DeleteTag", "DeleteFolder"]) { + expect(classifyRisk({ name }, "circleback")).toBe("destructive"); + } + for (const name of ["SearchMeetings", "ReadMeetings", "GetTranscriptsForMeetings", "SearchTranscripts", + "SearchActionItems", "SearchCalendarEvents", "SearchEmails", "FindProfiles", "FindCompanies", "ListTags", + "ListFolders", "ReadFolders", "ListTeams", "SearchSupportArticles", + "DisplayMeetings", "DisplayActionItems", "DisplayCalendarEvents"]) { + expect(classifyRisk({ name }, "circleback")).toBe("read"); + } + // Unreviewed names stay writes even when the provider hints read-only. + expect(classifyRisk({ name: "ExportMeetings", annotations: { readOnlyHint: true } }, "circleback")).toBe("write"); + expect(classifyRisk({ name: "SearchMeetings", annotations: { readOnlyHint: false } }, "circleback")).toBe("write"); + expect(classifyRisk({ name: "SearchMeetings", annotations: { destructiveHint: true } }, "circleback")).toBe("destructive"); + expect(connectorToolPolicy("circleback").quarantineNewEntries).toBe(false); + }); + it("retains generic risk behavior when the connector has no reviewed override", () => { expect(classifyRisk({ name: "get_object" }, "custom")).toBe("read"); expect(classifyRisk({ name: "new_tool", annotations: { readOnlyHint: true } }, "custom")).toBe("read"); diff --git a/server/src/__tests__/mcp-apps.test.ts b/server/src/__tests__/mcp-apps.test.ts new file mode 100644 index 00000000000..41de465d788 --- /dev/null +++ b/server/src/__tests__/mcp-apps.test.ts @@ -0,0 +1,365 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import http from "supertest"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, approvals, companies, companyMemberships, connectionGrants, createDb, heartbeatRuns, issues, principalPermissionGrants, toolActionRequests, toolCatalogEntries, toolConnections, toolInvocations, toolMcpAppViews, toolPolicies, +} from "@paperclipai/db"; +import { MCP_APP_MIME_TYPE, MCP_APPS_EXTENSION_ID } from "@paperclipai/shared"; +import { errorHandler } from "../middleware/error-handler.js"; +import { mcpAppsRoutes } from "../routes/mcp-apps.js"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { toolAccessService, type McpToolDescriptor } from "../services/tool-access.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { mcpAppCallToolResult } from "../services/mcp-app-views.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const actor = { actorType: "user" as const, actorId: "circleback-reviewer" }; +const redirectUri = "https://paperclip.fixture.test/api/tools/oauth/callback"; +const VIEW_URI = "ui://circleback/meetings.html"; +// Real views bundle their scripts; Circleback's is about 3.5 MB. This one is +// larger than the 1 MB limit on agent-facing tool results. +const VIEW_HTML = `
Meetings
`; + +// Circleback-shaped server: a model+app view tool, an app-only refresh tool, +// a model-only view tool, and a plain read tool. +const tools: McpToolDescriptor[] = [ + { name: "SearchMeetings", inputSchema: { type: "object" } }, + { name: "DisplayMeetings", inputSchema: { type: "object", properties: { meetingIds: { type: "array" } } }, + _meta: { ui: { resourceUri: VIEW_URI } } } as McpToolDescriptor, + { name: "RefreshMeetingCards", inputSchema: { type: "object" }, + _meta: { ui: { resourceUri: VIEW_URI, visibility: ["app"] } } } as McpToolDescriptor, + { name: "DisplayCalendarEvents", inputSchema: { type: "object" }, + _meta: { ui: { resourceUri: "ui://circleback/calendar.html", visibility: ["model"] } } } as McpToolDescriptor, +]; + +describe("mcpAppCallToolResult", () => { + it("rebuilds the MCP CallToolResult from the gateway's normalized result", () => { + expect(mcpAppCallToolResult({ + content: "text", + data: { content: [{ type: "text", text: "Two meetings" }], structuredContent: { meetings: [1, 2] }, isError: false }, + }, { "circleback/viewState": "cards" })).toEqual({ + content: [{ type: "text", text: "Two meetings" }], + structuredContent: { meetings: [1, 2] }, + _meta: { "circleback/viewState": "cards" }, + }); + expect(mcpAppCallToolResult({ content: "plain" })).toEqual({ content: [{ type: "text", text: "plain" }] }); + }); +}); + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("MCP Apps views end to end (Circleback)", () => { + let db: ReturnType; + let temp: Awaited>; + beforeAll(async () => { + temp = await startEmbeddedPostgresTestDatabase("paperclip-mcp-apps-"); + db = createDb(temp.connectionString); + }, 30000); + afterAll(async () => { await temp?.cleanup(); }); + + async function fixture(options: { requireSession?: boolean; personal?: boolean } = {}) { + const origin = "https://circleback.ai"; + const endpoint = `${origin}/api/mcp`; + const accessToken = `circleback-fixture-${randomUUID()}`; + const [company] = await db.insert(companies).values({ name: "Circleback fixture", issuePrefix: `CB${randomUUID().slice(0, 6)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" }); + let authorized = false; + const initializeCapabilities: unknown[] = []; + const resourceReadSessions: Array = []; + let failResourceReads = false; + let expireNextResourceRead = false; + let initializeGate: { wait: Promise; entered: () => void } | null = null; + let sessionCounter = 0; + const request = vi.fn(async (url: string, init: RequestInit) => { + const headers = new Headers(init.headers); + const body = String(init.body ?? ""); + if (url === endpoint && init.method === "POST") { + if (!authorized || headers.get("authorization") !== `Bearer ${accessToken}`) { + return new Response(null, { status: 401, headers: { "www-authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/api/mcp"` } }); + } + const rpc = JSON.parse(body); + if (rpc.method === "initialize") { + initializeCapabilities.push(rpc.params?.capabilities); + const gate = initializeGate; + initializeGate = null; + if (gate) { + gate.entered(); + await gate.wait; + } + sessionCounter += 1; + return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { protocolVersion: "2025-06-18", capabilities: { tools: {}, resources: {} }, serverInfo: { name: "Circleback fixture", version: "1" } } }, + options.requireSession ? { headers: { "mcp-session-id": `fixture-session-${sessionCounter}` } } : undefined); + } + // A stateful server refuses requests outside an initialized session. + if (options.requireSession && rpc.method !== "notifications/initialized" && !headers.get("mcp-session-id")?.startsWith("fixture-session-")) { + return Response.json({ jsonrpc: "2.0", id: rpc.id ?? null, error: { code: -32000, message: "Bad Request: No valid session ID provided" } }, { status: 400 }); + } + if (rpc.method === "notifications/initialized") return new Response(null, { status: 202 }); + if (rpc.method === "tools/list") return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { tools } }); + if (rpc.method === "resources/read") { + resourceReadSessions.push(headers.get("mcp-session-id")); + if (failResourceReads) return new Response("view unavailable", { status: 500 }); + if (expireNextResourceRead) { + expireNextResourceRead = false; + return new Response("session expired", { status: 404 }); + } + return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { contents: [{ + uri: rpc.params.uri, mimeType: MCP_APP_MIME_TYPE, text: VIEW_HTML, + _meta: { ui: { csp: { resourceDomains: ["https://cdn.circleback.ai"] }, prefersBorder: true } }, + }] } }); + } + if (rpc.method === "tools/call") { + return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { + content: [{ type: "text", text: `${rpc.params.name} done` }], + structuredContent: { tool: rpc.params.name, meetings: [{ id: "m1", name: "Paperclip <> Heavybit" }] }, + _meta: { "circleback/cards": [{ id: "m1" }] }, + } }); + } + } + if (url.includes("oauth-protected-resource")) return Response.json({ resource: endpoint, authorization_servers: [origin], scopes_supported: ["user", "user:write"] }); + if (url === `${origin}/.well-known/oauth-authorization-server`) return Response.json({ + issuer: origin, authorization_endpoint: `${origin}/api/oauth/authorize`, token_endpoint: `${origin}/api/oauth/access-token`, + registration_endpoint: `${origin}/api/oauth/register`, code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], scopes_supported: ["user", "user:write"], + }); + if (url === `${origin}/api/oauth/register`) return Response.json({ ...JSON.parse(body), client_id: "circleback-fixture-client" }); + if (url === `${origin}/api/oauth/access-token`) { + authorized = true; + return Response.json({ access_token: accessToken, refresh_token: `r-${randomUUID()}`, expires_in: 3600, token_type: "Bearer", scope: "user user:write" }); + } + return new Response(null, { status: 404 }); + }); + const service = toolAccessService(db, { remoteHttpRequest: request, remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }] }); + const connected = await service.connectGalleryApp(company.id, { galleryKey: "circleback", connectionMethodKey: "mcp-oauth", ...(options.personal ? { grantKind: "user" as const } : {}) }, actor); + const start = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor }); + const authorization = new URL(start.authorizationUrl); + expect(start.registrationSource).toBe("dcr"); + const signedIn = await service.completeOAuthCallback({ state: authorization.searchParams.get("state")!, code: "fixture-code", iss: origin, redirectUri, actor }); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Meeting analyst", role: "engineer", adapterType: "process" }).returning(); + const [otherAgent] = await db.insert(agents).values({ companyId: company.id, name: "Second analyst", role: "engineer", adapterType: "process" }).returning(); + await service.finishGalleryAppConnection(company.id, signedIn.connectionId, { enabledCatalogEntryIds: signedIn.catalog.map(entry => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [agent.id, otherAgent.id] } }, actor); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Recap the partner meeting", assigneeAgentId: agent.id }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, issueId: issue.id, + scopeKind: "issue", invocationSource: "on_demand", status: "running", responsibleUserId: actor.actorId, contextSnapshot: { issueId: issue.id } }).returning(); + const gateway = createToolGatewayService(db, { remoteHttpRequest: request, toolActionSigningSecret: "circleback-fixture-signing-key" }); + const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id, issueId: issue.id }); + const app = express(); + app.use(express.json()); + let actorKind: "board" | "agent" | "teammate" = "board"; + app.use((req, _res, next) => { + req.actor = actorKind !== "agent" + ? { type: "board", userId: actorKind === "teammate" ? "circleback-teammate" : actor.actorId, source: "session", companyIds: [company.id], + memberships: [{ companyId: company.id, status: "active", membershipRole: actorKind === "teammate" ? "member" : "admin" }] } + : { type: "agent", companyId: company.id, agentId: agent.id, source: "agent_key" }; + next(); + }); + // Same order as app.ts: a view's tool calls are served by the tool-access router. + app.use(toolAccessRoutes(db, { toolGateway: gateway, remoteHttpRequest: request, remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }] })); + app.use(mcpAppsRoutes(db, gateway)); + app.use(errorHandler); + return { company, agent, issue, run, gateway, session, request, app, initializeCapabilities, resourceReadSessions, connectionId: signedIn.connectionId, + failResourceReads: (fail: boolean) => { failResourceReads = fail; }, + expireNextResourceRead: () => { expireNextResourceRead = true; }, + /** Holds the next initialize request; `entered` resolves once that request is being held. */ + holdNextInitialize: () => { + let release!: () => void; + let markEntered!: () => void; + const entered = new Promise((resolve) => { markEntered = resolve; }); + initializeGate = { wait: new Promise((resolve) => { release = resolve; }), entered: markEntered }; + return { release, entered }; + }, + otherAgent, + setActor: (kind: "board" | "agent" | "teammate") => { actorKind = kind; } }; + } + + it("keeps the view declaration, hides app-only tools from the agent, and records the call's view", async () => { + const f = await fixture(); + // Paperclip only initializes stateful servers; when it does, it advertises MCP Apps. + expect(f.initializeCapabilities.every((capabilities) => JSON.stringify(capabilities).includes(MCP_APPS_EXTENSION_ID))).toBe(true); + const catalog = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, f.connectionId)); + expect(catalog.find(entry => entry.toolName === "DisplayMeetings")?.uiMeta).toEqual({ resourceUri: VIEW_URI, visibility: ["model", "app"] }); + expect(catalog.find(entry => entry.toolName === "SearchMeetings")?.uiMeta).toBeNull(); + + const listed = await f.gateway.listToolsForSession(f.session.token); + const listedNames = listed.map(tool => tool.upstreamToolName); + expect(listedNames).toEqual(expect.arrayContaining(["SearchMeetings", "DisplayMeetings", "DisplayCalendarEvents"])); + expect(listedNames).not.toContain("RefreshMeetingCards"); + + const display = listed.find(tool => tool.upstreamToolName === "DisplayMeetings")!; + const result = await f.gateway.executeTool({ sessionToken: f.session.token, tool: display.name, parameters: { meetingIds: ["m1"] }, idempotencyKey: randomUUID() }); + expect(JSON.stringify(result)).toContain("DisplayMeetings done"); + // The provider `_meta` is for the view only; the agent never receives it. + expect(JSON.stringify(result)).not.toContain("circleback/cards"); + // A call to a tool without a view records nothing. + const search = listed.find(tool => tool.upstreamToolName === "SearchMeetings")!; + await f.gateway.executeTool({ sessionToken: f.session.token, tool: search.name, parameters: {}, idempotencyKey: randomUUID() }); + + const views = await db.select().from(toolMcpAppViews).where(eq(toolMcpAppViews.companyId, f.company.id)); + expect(views).toHaveLength(1); + expect(views[0]).toMatchObject({ + issueId: f.issue.id, runId: f.run.id, agentId: f.agent.id, applicationName: "Circleback", + toolName: display.name, upstreamToolName: "DisplayMeetings", resourceUri: VIEW_URI, + toolInput: { meetingIds: ["m1"] }, + toolResult: { + content: [{ type: "text", text: "DisplayMeetings done" }], + structuredContent: { tool: "DisplayMeetings", meetings: [{ id: "m1", name: "Paperclip <> Heavybit" }] }, + _meta: { "circleback/cards": [{ id: "m1" }] }, + }, + }); + }); + + it("serves the view to task readers and runs the view's tool calls with the viewer's authority", async () => { + const f = await fixture(); + const listed = await f.gateway.listToolsForSession(f.session.token); + const display = listed.find(tool => tool.upstreamToolName === "DisplayMeetings")!; + await f.gateway.executeTool({ sessionToken: f.session.token, tool: display.name, parameters: { meetingIds: ["m1"] }, idempotencyKey: randomUUID() }); + + const list = await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(200); + expect(list.body).toHaveLength(1); + const viewId = list.body[0].id as string; + expect(list.body[0]).toMatchObject({ runId: f.run.id, upstreamToolName: "DisplayMeetings", toolInput: { meetingIds: ["m1"] } }); + + const detail = await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(200); + expect(detail.body.resource).toMatchObject({ uri: VIEW_URI, html: VIEW_HTML, prefersBorder: true, csp: { resourceDomains: ["https://cdn.circleback.ai"] } }); + expect(detail.body.toolResult.structuredContent.meetings[0].id).toBe("m1"); + + const appCall = await http(f.app).post(`/issues/${f.issue.id}/mcp-app-views/${viewId}/tool-calls`) + .send({ name: "RefreshMeetingCards", arguments: { meetingIds: ["m1"] } }).expect(200); + expect(appCall.body).toMatchObject({ + content: [{ type: "text", text: "RefreshMeetingCards done" }], + structuredContent: { tool: "RefreshMeetingCards" }, + // The view's own calls keep the provider `_meta` the cards need. + _meta: { "circleback/cards": [{ id: "m1" }] }, + }); + + // Task-scoped rules apply to a view's tool calls: Ask first holds the call. + const [askFirst] = await db.insert(toolPolicies).values({ companyId: f.company.id, name: "Ask first on this task", policyType: "require_approval", priority: 1, selectors: { issueId: f.issue.id } }).returning(); + const held = await http(f.app).post(`/issues/${f.issue.id}/mcp-app-views/${viewId}/tool-calls`) + .send({ name: "RefreshMeetingCards", arguments: { meetingIds: ["m1"] } }).expect(200); + expect(held.body).toMatchObject({ isError: true, content: [{ type: "text", text: expect.stringContaining("needs approval") }] }); + // Approving the held app-only call runs it, with the task still attached. + const [pending] = await db.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.companyId, f.company.id), eq(toolActionRequests.status, "pending"))); + expect(pending).toBeTruthy(); + if (pending.approvalId) await db.update(approvals).set({ status: "approved", decidedByUserId: actor.actorId, decidedAt: new Date() }).where(eq(approvals.id, pending.approvalId)); + const refreshCalls = () => f.request.mock.calls.filter(([, init]) => String(init.body).includes('"name":"RefreshMeetingCards"')).length; + const callsBefore = refreshCalls(); + await f.gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: pending.id, actor: { userId: actor.actorId } }); + expect(refreshCalls()).toBe(callsBefore + 1); + const [approvedInvocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)); + expect(approvedInvocation).toMatchObject({ status: "succeeded", issueId: f.issue.id }); + await db.delete(toolPolicies).where(eq(toolPolicies.id, askFirst.id)); + + // A held view call whose tool loses app visibility before approval does not run. + const [askFirstAgain] = await db.insert(toolPolicies).values({ companyId: f.company.id, name: "Ask first again", policyType: "require_approval", priority: 1, selectors: { issueId: f.issue.id } }).returning(); + await http(f.app).post(`/issues/${f.issue.id}/mcp-app-views/${viewId}/tool-calls`) + .send({ name: "RefreshMeetingCards", arguments: { meetingIds: ["m2"] } }).expect(200); + const [stillPending] = await db.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.companyId, f.company.id), eq(toolActionRequests.status, "pending"))); + if (stillPending.approvalId) await db.update(approvals).set({ status: "approved", decidedByUserId: actor.actorId, decidedAt: new Date() }).where(eq(approvals.id, stillPending.approvalId)); + await db.update(toolCatalogEntries).set({ uiMeta: { resourceUri: VIEW_URI, visibility: ["model"] } }) + .where(and(eq(toolCatalogEntries.connectionId, f.connectionId), eq(toolCatalogEntries.toolName, "RefreshMeetingCards"))); + const beforeRevokedApproval = refreshCalls(); + await f.gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: stillPending.id, actor: { userId: actor.actorId } }).catch(() => undefined); + expect(refreshCalls()).toBe(beforeRevokedApproval); + await db.update(toolCatalogEntries).set({ uiMeta: { resourceUri: VIEW_URI, visibility: ["app"] } }) + .where(and(eq(toolCatalogEntries.connectionId, f.connectionId), eq(toolCatalogEntries.toolName, "RefreshMeetingCards"))); + await db.delete(toolPolicies).where(eq(toolPolicies.id, askFirstAgain.id)); + + // A model-only tool is never callable from a view. + await http(f.app).post(`/issues/${f.issue.id}/mcp-app-views/${viewId}/tool-calls`) + .send({ name: "DisplayCalendarEvents", arguments: {} }).expect(404); + + // Another task cannot read this view, and agents cannot use the routes. + const [otherIssue] = await db.insert(issues).values({ companyId: f.company.id, title: "Other task" }).returning(); + await http(f.app).get(`/issues/${otherIssue.id}/mcp-app-views/${viewId}`).expect(404); + const [otherCompany] = await db.insert(companies).values({ name: "Other", issuePrefix: `OT${randomUUID().slice(0, 6)}` }).returning(); + const [foreignIssue] = await db.insert(issues).values({ companyId: otherCompany.id, title: "Foreign" }).returning(); + await http(f.app).get(`/issues/${foreignIssue.id}/mcp-app-views`).expect(404); + f.setActor("agent"); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(403); + + // A company member who cannot open a private task cannot read its views. + await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: "circleback-teammate", status: "active", membershipRole: "member" }); + f.setActor("teammate"); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(200); + // A view's tool calls need what a connection test call needs. Reading the + // task is not enough: the member also needs tool permission ... + const callFromView = () => http(f.app).post(`/issues/${f.issue.id}/mcp-app-views/${viewId}/tool-calls`) + .send({ name: "RefreshMeetingCards", arguments: {} }); + expect((await callFromView()).status).toBe(403); + await db.insert(principalPermissionGrants).values({ companyId: f.company.id, principalType: "user", principalId: "circleback-teammate", permissionKey: "tools:use", grantedByUserId: actor.actorId }); + expect((await callFromView()).status).toBe(200); + // ... and authority to act as the view's agent, which ends with the agent. + await db.update(agents).set({ status: "terminated" }).where(eq(agents.id, f.agent.id)); + expect((await callFromView()).status).toBe(403); + await db.update(agents).set({ status: "idle" }).where(eq(agents.id, f.agent.id)); + await db.update(issues).set({ visibility: "private" }).where(eq(issues.id, f.issue.id)); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(404); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(404); + }); + + it("reads view documents through an MCP session when the server requires one, without touching connection health", async () => { + const f = await fixture({ requireSession: true }); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connectionId)); + expect(connection.config).toMatchObject({ mcpSessionRequired: true }); + const listed = await f.gateway.listToolsForSession(f.session.token); + const display = listed.find(tool => tool.upstreamToolName === "DisplayMeetings")!; + await f.gateway.executeTool({ sessionToken: f.session.token, tool: display.name, parameters: { meetingIds: ["m1"] }, idempotencyKey: randomUUID() }); + const viewId = (await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(200)).body[0].id as string; + const detail = await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(200); + expect(detail.body.resource.html).toBe(VIEW_HTML); + expect(f.resourceReadSessions.at(-1)).toMatch(/^fixture-session-/); + + const healthBefore = (await db.select().from(toolConnections).where(eq(toolConnections.id, f.connectionId)))[0]!.healthStatus; + f.failResourceReads(true); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(502); + const healthAfter = (await db.select().from(toolConnections).where(eq(toolConnections.id, f.connectionId)))[0]!.healthStatus; + expect(healthAfter).toBe(healthBefore); + }); + + it("retries an expired view read without interrupting another agent's session setup", async () => { + const f = await fixture({ requireSession: true }); + const listed = await f.gateway.listToolsForSession(f.session.token); + const display = listed.find(tool => tool.upstreamToolName === "DisplayMeetings")!; + await f.gateway.executeTool({ sessionToken: f.session.token, tool: display.name, parameters: { meetingIds: ["m1"] }, idempotencyKey: randomUUID() }); + const viewId = (await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(200)).body[0].id as string; + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(200); + + // Another agent starts a tool call; its session setup is still in flight ... + const [otherRun] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.otherAgent.id, issueId: f.issue.id, + scopeKind: "issue", invocationSource: "on_demand", status: "running", contextSnapshot: { issueId: f.issue.id } }).returning(); + const otherSession = await f.gateway.createSession({ companyId: f.company.id, agentId: f.otherAgent.id, runId: otherRun.id, issueId: f.issue.id }); + const otherTool = (await f.gateway.listToolsForSession(otherSession.token)).find(tool => tool.upstreamToolName === "SearchMeetings")!; + const held = f.holdNextInitialize(); + const otherCall = f.gateway.executeTool({ sessionToken: otherSession.token, tool: otherTool.name, parameters: {}, idempotencyKey: randomUUID() }); + await held.entered; + + // ... when the view read finds its session expired and starts a new one. + f.expireNextResourceRead(); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(200); + held.release(); + await expect(otherCall).resolves.toMatchObject({ status: "completed" }); + }); + + it("reads a view's document only with the viewer's own access to the connection", async () => { + // A personal connection of the user who connected it. + const f = await fixture({ personal: true }); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connectionId)); + expect(grant).toMatchObject({ kind: "user", subjectUserId: actor.actorId }); + const listed = await f.gateway.listToolsForSession(f.session.token); + const display = listed.find(tool => tool.upstreamToolName === "DisplayMeetings")!; + await f.gateway.executeTool({ sessionToken: f.session.token, tool: display.name, parameters: { meetingIds: ["m1"] }, idempotencyKey: randomUUID() }); + const viewId = (await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(200)).body[0].id as string; + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(200); + + // A teammate who can read the task sees that the view exists, but cannot + // read its document through someone else's personal connection. + await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: "circleback-teammate", status: "active", membershipRole: "member" }); + f.setActor("teammate"); + await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views`).expect(200); + const denied = await http(f.app).get(`/issues/${f.issue.id}/mcp-app-views/${viewId}`).expect(404); + expect(denied.body).toMatchObject({ error: "View not found" }); + }); +}); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index c4e7fc9c54a..e8463283aed 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -41,6 +41,7 @@ const apiPrefixes: Record = { "auth.ts": "/api/auth", "board-chat.ts": "/api", "browser-use.ts": "/api", + "mcp-apps.ts": "/api", "built-in-agents.ts": "/api", "chat-channels.ts": "/api", "slack-tools.ts": "/api", diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index c16fd503be6..f0f63336dee 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -1515,7 +1515,7 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { .expect(200); expect(initialized.body.result).toMatchObject({ capabilities: { tools: {}, resources: {}, prompts: {} }, - _meta: { "paperclip/mcp-app-ui": "unsupported" }, + _meta: { "paperclip/mcp-app-ui": "host_rendered" }, }); const setupLimited = await request(app) .post(endpoint) diff --git a/server/src/app.ts b/server/src/app.ts index 5d845468ad4..fedfa1795ce 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -29,6 +29,7 @@ import { customerSuccessRoutes } from "./routes/customer-success.js"; import { cloudWarmStandbyMiddleware } from "./middleware/cloud-warm-standby.js"; import type { CloudWarmStandby } from "./services/cloud-warm-standby.js"; import { browserUseRoutes } from "./routes/browser-use.js"; +import { mcpAppsRoutes } from "./routes/mcp-apps.js"; import { registerChatActionWork } from "./services/chat-action-work.js"; import { registerChatDeliveryWork } from "./services/chat-delivery-work.js"; import { registerBrowserUseCleanup } from "./services/browser-use-work.js"; @@ -1019,6 +1020,7 @@ export async function createApp( (session, run) => toolGateway.browserUseSessionAuthorized({ ...session, runId: run.heartbeatRunId, invocationId: run.invocationId })); api.use(browserUseRoutes(db, browserUse)); api.use(toolGatewayRoutes(db, toolGateway)); + api.use(mcpAppsRoutes(db, toolGateway)); api.use( pluginRoutes( db, diff --git a/server/src/routes/mcp-apps.ts b/server/src/routes/mcp-apps.ts new file mode 100644 index 00000000000..e1db38014d7 --- /dev/null +++ b/server/src/routes/mcp-apps.ts @@ -0,0 +1,92 @@ +import { Router, type Request, type Response } from "express"; +import { eq } from "drizzle-orm"; +import { z } from "zod"; +import { issues, type Db } from "@paperclipai/db"; +import type { McpAppViewDetail } from "@paperclipai/shared"; +import { assertBoard, getAccessibleResource } from "./authz.js"; +import { connectionRequestUserId } from "./connection-management-authz.js"; +import { authorizationService } from "../services/authorization.js"; +import { mcpAppViewsService, toMcpAppViewSummary } from "../services/mcp-app-views.js"; +import { ToolGatewayHttpError, type ToolGatewayService } from "../services/tool-gateway.js"; + +const uuidSchema = z.string().uuid(); + +type McpAppsGateway = Pick; + +/** + * MCP Apps views in the task chat. Viewing follows task read access. A view's + * own tool calls are served by the tool-access router, which applies the + * connection test-call authorization. + */ +export function mcpAppsRoutes(db: Db, toolGateway: McpAppsGateway) { + const router = Router(); + const views = mcpAppViewsService(db); + + router.use("/issues/:issueId/mcp-app-views", async (req, res, next) => { + assertBoard(req); + if (!uuidSchema.safeParse(req.params.issueId).success) { + res.status(404).json({ error: "Task not found" }); + return; + } + const [issue] = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues) + .where(eq(issues.id, req.params.issueId as string)).limit(1); + if (!(await getAccessibleResource(req, res, issue, "Task not found"))) return; + // Company access is not enough: private tasks also need task read access. + const readable = await authorizationService(db).decide({ actor: req.actor, action: "issue:read", resource: { + type: "issue", companyId: issue.companyId, issueId: issue.id, + } }); + if (!readable.allowed) { + res.status(404).json({ error: "Task not found" }); + return; + } + res.locals.mcpAppIssue = issue; + res.setHeader("Cache-Control", "no-store"); + next(); + }); + + async function viewFor(req: Request, res: Response) { + const issue = res.locals.mcpAppIssue as { id: string; companyId: string }; + const viewId = req.params.viewId as string; + const view = uuidSchema.safeParse(viewId).success ? await views.get(issue.companyId, viewId) : null; + if (!view || view.issueId !== issue.id) { + res.status(404).json({ error: "View not found" }); + return null; + } + return { issue, view }; + } + + function sendGatewayError(res: Response, error: unknown) { + if (error instanceof ToolGatewayHttpError) { + res.status(error.status).json({ error: error.message, reasonCode: error.reasonCode }); + return true; + } + return false; + } + + router.get("/issues/:issueId/mcp-app-views", async (req, res) => { + const issue = res.locals.mcpAppIssue as { id: string; companyId: string }; + res.json(await views.listForIssue(issue.companyId, issue.id)); + }); + + router.get("/issues/:issueId/mcp-app-views/:viewId", async (req, res) => { + const found = await viewFor(req, res); + if (!found) return; + try { + const resource = await toolGateway.readMcpAppViewResource({ + companyId: found.issue.companyId, + userId: connectionRequestUserId(req) ?? "board", + view: found.view, + }); + const detail: McpAppViewDetail = { + ...toMcpAppViewSummary(found.view), + toolResult: found.view.toolResult as unknown as McpAppViewDetail["toolResult"], + resource, + }; + res.json(detail); + } catch (error) { + if (!sendGatewayError(res, error)) throw error; + } + }); + + return router; +} diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 3041bcb66ef..d0c762172c2 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -36,6 +36,7 @@ import { browserUseSettingsSchema, browserUseViewportSchema, browserUseViewerSchema, + mcpAppToolCallSchema, startVoiceSessionSchema, voiceCallbackPreferenceSchema, voicePhoneConfigurationSchema, voiceInboundDecisionSchema, VOICE_SESSION_STATES, slackToolCallSchema, slackSearchConfigSchema, @@ -1439,6 +1440,13 @@ const browserUseOperations = [ ["put", "/api/companies/{companyId}/browser-use-cloud/grants/{grantId}/settings", "Update browser credential settings", browserUseSettingsSchema], ] as const; +// MCP Apps views in the task chat. Board only; reads follow task read access. +const mcpAppsOperations = [ + ["get", "/api/issues/{issueId}/mcp-app-views", "List a task's MCP Apps views", undefined], + ["get", "/api/issues/{issueId}/mcp-app-views/{viewId}", "Read an MCP Apps view with its document", undefined], + ["post", "/api/issues/{issueId}/mcp-app-views/{viewId}/tool-calls", "Call a tool from an MCP Apps view", mcpAppToolCallSchema], +] as const; + const BOARD_ONLY_OPERATIONS = new Set([ "PATCH /api/agents/{id}/permission-grants", // Budget changes are board-only (assertBoard in routes/costs.ts). @@ -1486,6 +1494,7 @@ const BOARD_ONLY_OPERATIONS = new Set([ "DELETE /api/companies/{companyId}/observability", "POST /api/companies/{companyId}/observability/test", ...browserUseOperations.map(([method, path]) => `${method.toUpperCase()} ${path}`), + ...mcpAppsOperations.map(([method, path]) => `${method.toUpperCase()} ${path}`), "POST /api/companies/{companyId}/ai-connections/local/attempts/{sessionId}/code", "GET /api/companies/{companyId}/project-repositories", @@ -2263,6 +2272,13 @@ registry.registerPath({ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized }, }); +for (const [method, path, summary, body] of mcpAppsOperations) { + registerCurrentRoute({ + method, path, summary, body, tags: ["MCP Apps"], + responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 502: r.serverError }, + }); +} + for (const [method, path, summary, body] of browserUseOperations) { registerCurrentRoute({ method, path, summary, body, tags: ["Browser Use Cloud"], diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index a4308480b84..eb84fe95fc7 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -5,7 +5,7 @@ import { composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSche import { aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema } from "@paperclipai/shared/aggregator-apps"; import { Router, type Request, type Response } from "express"; import type { Db } from "@paperclipai/db"; -import { agents, companies, connectionGrants, issueThreadInteractions, toolConnectionInstalls } from "@paperclipai/db"; +import { agents, companies, connectionGrants, issues, issueThreadInteractions, toolConnectionInstalls, toolMcpAppViews } from "@paperclipai/db"; import { and, eq, or } from "drizzle-orm"; import { APP_STORE_DEFINITIONS, @@ -65,6 +65,9 @@ import { getActorInfo, assertBoard, assertBoardOrAgent, assertCompanyAccess, ass import { badRequest, forbidden, HttpError, notFound, unprocessable } from "../errors.js"; import { accessService, logActivity, toolAccessPolicyService, toolAccessService, vercelConnectIntegrationStatus } from "../services/index.js"; import { ToolGatewayHttpError, type ToolGatewayService } from "../services/tool-gateway.js"; +import { authorizationService } from "../services/authorization.js"; +import { mcpAppViewsService } from "../services/mcp-app-views.js"; +import { mcpAppToolCallSchema } from "@paperclipai/shared"; import { RailwayError } from "../services/railway.js"; import type { VercelConnectClient } from "../services/vercel-connect.js"; import { @@ -236,6 +239,8 @@ export function cloudConnectorEnrollmentReturnPath(issuePrefix: string, returnTo return `${companyRoot}/apps/connections?cloud_connector=enrolled`; } +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + export function toolAccessRoutes( db: Db, options: { @@ -2116,6 +2121,54 @@ function connectorEnrollmentPrincipal(req: Request): string { res.json(result); }); + // An MCP Apps view's tools/call. It runs through the connection test-call + // path, so it needs exactly what a test call needs: connection management + // (connections:test), connection access, tool permission and test-as-agent + // authority for the agent whose call recorded the view, plus task read access. + router.post("/issues/:issueId/mcp-app-views/:viewId/tool-calls", async (req, res, next) => { + assertBoard(req); + const issueId = String(req.params.issueId); + const viewId = String(req.params.viewId); + if (!UUID_PATTERN.test(issueId) || !UUID_PATTERN.test(viewId)) { + res.status(404).json({ error: "View not found" }); + return; + } + const [issue] = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).limit(1); + if (!(await getAccessibleResource(req, res, issue, "Task not found"))) return; + const readable = await authorizationService(db).decide({ actor: req.actor, action: "issue:read", resource: { type: "issue", companyId: issue.companyId, issueId: issue.id } }); + const view = readable.allowed ? await mcpAppViewsService(db).get(issue.companyId, viewId) : null; + if (!view || view.issueId !== issue.id) { + res.status(404).json({ error: "View not found" }); + return; + } + res.locals.mcpAppView = view; + // The management guard resolves the connection from this parameter. + req.params.connectionId = view.connectionId; + next(); + }, managementGuard("connections:test", "POST /issues/:issueId/mcp-app-views/:viewId/tool-calls", { personal: true }), validate(mcpAppToolCallSchema), async (req, res) => { + if (!options.toolGateway) { + res.status(501).json({ error: "Tool gateway service is not configured" }); + return; + } + const view = res.locals.mcpAppView as typeof toolMcpAppViews.$inferSelect; + const connection = await getAccessibleResource(req, res, svc.getConnection(view.connectionId), "Tool connection not found"); + if (!connection) return; + await assertBoardAnyToolPermission(req, connection.companyId, ["tools:use", "tools:manage_connections"]); + if (!view.agentId) throw forbidden("This view's agent no longer exists"); + await assertCanTestAsAgent(req, connection.companyId, view.agentId); + try { + res.json(await options.toolGateway.callMcpAppViewTool({ + companyId: connection.companyId, + userId: connectionRequestUserId(req) ?? "board", + view, + toolName: req.body.name, + arguments: req.body.arguments ?? {}, + })); + } catch (error) { + if (!sendToolGatewayError(res, error)) throw error; + } + }); + router.post("/tool-connections/:connectionId/test-calls", managementGuard("connections:test", "POST /tool-connections/:connectionId/test-calls", { personal: true }), validate(toolConnectionTestCallSchema), async (req, res) => { assertBoardOrAgent(req); if (!options.toolGateway) { diff --git a/server/src/routes/tool-gateway.ts b/server/src/routes/tool-gateway.ts index d432d2a41ce..62c68ccb7f3 100644 --- a/server/src/routes/tool-gateway.ts +++ b/server/src/routes/tool-gateway.ts @@ -100,8 +100,8 @@ async function handleMcpGatewayProtocol( capabilities: { tools: {}, resources: {}, prompts: {} }, serverInfo: { name: "Paperclip MCP Gateway", version: "1.0.0" }, _meta: { - "paperclip/mcp-app-ui": "unsupported", - "paperclip/mcp-app-ui-detail": "Interactive ui:// iframe hosting is not available in Paperclip Runner.", + "paperclip/mcp-app-ui": "host_rendered", + "paperclip/mcp-app-ui-detail": "Paperclip renders MCP Apps ui:// views in the task chat. The gateway does not forward them to clients.", }, }, }); diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index 7bb35f1c511..f06a3c0e95b 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -650,8 +650,11 @@ export function connectionIntentService(db: Db) { const previous = await providerSelections(run.companyId, issue.id, agent.id, run.responsibleUserId!, `connection-provider:${targetService}`); const explicitConsent = explicit && await hasExplicitProviderRequest(run.companyId, issue.id, run.responsibleUserId!, targetService, explicit.provider, previous[0]); if (exact.length && (!explicitConsent || exact.some(({ item }) => item.state === "unavailable"))) { + // An aggregator listing such as "Circleback MCP" is the same app as the + // built-in "Circleback"; compare its aliases too, not only its listed name. const otherApps = bestMatches.filter(({ service, nameScore }) => nameScore >= 200 && !exact.some(({ item }) => - item.service === service.slug || scoreConnectionSearch(service.name, [item.name]).nameScore === 1000)); + item.service === service.slug || [service.name, ...service.aliases].some(name => + scoreConnectionSearch(name, [item.name]).nameScore === 1000))); if (otherApps.length && !exact.some(({ item }) => item.state === "unavailable")) { const otherRoutes = (await Promise.all(otherApps.slice(0, 10).map(({ service }) => aggregatorAlternatives(service.slug, service.name, service)))).flat(); diff --git a/server/src/services/connectors/circleback/risk.ts b/server/src/services/connectors/circleback/risk.ts new file mode 100644 index 00000000000..cf56c252a3c --- /dev/null +++ b/server/src/services/connectors/circleback/risk.ts @@ -0,0 +1,45 @@ +import type { ToolRiskLevel } from "@paperclipai/shared"; + +// Reviewed against Circleback's hosted MCP tool reference on 2026-11-12: +// https://circleback.ai/docs/support/platform/circleback-mcp +// The generic classifier reads ShareMeeting, ShareFolder and SubmitFeedback as +// reads because "share" and "submit" are not write verbs. Exact names make +// additions and renames default to write until they are reviewed. +const READ_TOOLS = new Set([ + "SearchMeetings", + "ReadMeetings", + "GetTranscriptsForMeetings", + "SearchTranscripts", + "SearchActionItems", + "SearchCalendarEvents", + "SearchEmails", + "FindProfiles", + "FindCompanies", + "ListTags", + "ListFolders", + "ReadFolders", + "ListTeams", + "SearchSupportArticles", + // MCP Apps views: they render records the agent already selected. Changes + // made from a card go through the write tools below. + "DisplayMeetings", + "DisplayActionItems", + "DisplayCalendarEvents", +]); + +const DESTRUCTIVE_TOOLS = new Set([ + "DeleteActionItem", + "DeleteTag", + "DeleteFolder", +]); + +export function circlebackRisk(tool: { + name: string; + annotations?: Record; +}): ToolRiskLevel { + const annotations = tool.annotations ?? {}; + if (annotations.destructiveHint === true || annotations.destructive === true + || DESTRUCTIVE_TOOLS.has(tool.name)) return "destructive"; + if (annotations.readOnlyHint === false || annotations.writeHint === true) return "write"; + return READ_TOOLS.has(tool.name) ? "read" : "write"; +} diff --git a/server/src/services/connectors/tool-policy.ts b/server/src/services/connectors/tool-policy.ts index d8ec483fcbb..4dd42854704 100644 --- a/server/src/services/connectors/tool-policy.ts +++ b/server/src/services/connectors/tool-policy.ts @@ -3,6 +3,7 @@ import type { ToolRiskLevel } from "@paperclipai/shared"; import { NATIVE_PROVIDER_CATALOGS } from "../native-provider-catalogs.js"; import { classifyRailwayToolRisk, isRailwayEndpoint } from "../railway.js"; import { braintrustRisk } from "./braintrust/risk.js"; +import { circlebackRisk } from "./circleback/risk.js"; import { enterpretRisk } from "./enterpret/risk.js"; interface ToolDescriptor { @@ -50,6 +51,9 @@ const reviewedPolicies: ReviewedToolPolicy[] = [ })), { sourceTemplateKey: "enterpret", quarantineNewEntries: true, classifyRisk: enterpretRisk }, { sourceTemplateKey: "braintrust", quarantineNewEntries: true, classifyRisk: braintrustRisk }, + // Circleback adds tools to its hosted server over time; unreviewed names are + // writes, but stay available like other MCP-direct catalog connections. + { sourceTemplateKey: "circleback", quarantineNewEntries: false, classifyRisk: circlebackRisk }, ]; const bySource = new Map(reviewedPolicies.map(policy => [policy.sourceTemplateKey, policy])); diff --git a/server/src/services/mcp-app-views.ts b/server/src/services/mcp-app-views.ts new file mode 100644 index 00000000000..042073fd0eb --- /dev/null +++ b/server/src/services/mcp-app-views.ts @@ -0,0 +1,128 @@ +import { and, desc, eq } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { toolMcpAppViews } from "@paperclipai/db"; +import { getAppDefinitionForApplicationKey, type McpAppCallToolResult, type McpAppToolUi, type McpAppViewSummary } from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; + +/** Views shown per task. The chat renders the newest calls; older ones fall back to the plain tool row. */ +const MAX_VIEWS_PER_ISSUE = 200; +/** A result larger than this is not kept for the view; the tool row still shows it. */ +const MAX_STORED_RESULT_BYTES = 512 * 1024; + +type ViewRow = typeof toolMcpAppViews.$inferSelect; + +function record(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; +} + +/** The tool's MCP Apps view declaration, when it was discovered from an MCP server. */ +export function mcpAppToolUi(tool: { providerType?: string; providerMetadata?: unknown }): (McpAppToolUi & { resourceUri: string }) | null { + if (tool.providerType !== "mcp_remote_http" && tool.providerType !== "mcp_local_stdio") return null; + const ui = record(record(tool.providerMetadata)?.ui); + return typeof ui?.resourceUri === "string" ? ui as unknown as McpAppToolUi & { resourceUri: string } : null; +} + +/** + * Converts the gateway's normalized MCP result (`{ content, data: { content, + * structuredContent, isError } }`) and the provider `_meta` back to the MCP + * `CallToolResult` the view expects. + */ +export function mcpAppCallToolResult(result: unknown, resultMeta?: unknown): McpAppCallToolResult { + const normalized = record(result); + const data = record(normalized?.data); + const content = Array.isArray(data?.content) + ? data.content + : typeof normalized?.content === "string" ? [{ type: "text", text: normalized.content }] : []; + const structuredContent = record(data?.structuredContent); + const meta = record(resultMeta); + return { + content, + ...(structuredContent ? { structuredContent } : {}), + ...(meta ? { _meta: meta } : {}), + ...(data?.isError === true ? { isError: true } : {}), + }; +} + +/** + * Records a completed call whose tool declares an MCP Apps view, so the task + * chat can render it. Best effort: the agent's tool call never fails because + * its view could not be kept. + */ +export async function recordMcpAppView(db: Db, input: { + session: { companyId: string; agentId: string | null; runId: string | null; issueId: string | null; responsibleUserId?: string | null }; + tool: { + name: string; + providerType?: string; + providerMetadata?: unknown; + connectionId?: string | null; + catalogEntryId?: string | null; + upstreamToolName?: string | null; + applicationDisplayName?: string | null; + applicationKey?: string | null; + }; + invocationId: string; + toolInput: unknown; + result: unknown; + /** The redacted provider `_meta`, which is never part of the agent's result. */ + resultMeta?: unknown; +}): Promise { + const ui = mcpAppToolUi(input.tool); + if (!ui || !input.tool.connectionId) return; + try { + const toolResult = mcpAppCallToolResult(input.result, input.resultMeta); + if (Buffer.byteLength(JSON.stringify(toolResult), "utf8") > MAX_STORED_RESULT_BYTES) return; + await db.insert(toolMcpAppViews).values({ + companyId: input.session.companyId, + invocationId: input.invocationId, + issueId: input.session.issueId, + runId: input.session.runId, + agentId: input.session.agentId, + responsibleUserId: input.session.responsibleUserId ?? null, + connectionId: input.tool.connectionId, + catalogEntryId: input.tool.catalogEntryId ?? null, + // The catalog app's name ("Circleback"), not the connection's ("Circleback for the organization"). + applicationName: getAppDefinitionForApplicationKey(input.tool.applicationKey)?.name ?? input.tool.applicationDisplayName ?? "App", + toolName: input.tool.name, + upstreamToolName: input.tool.upstreamToolName ?? input.tool.name, + resourceUri: ui.resourceUri, + toolInput: record(input.toolInput) ?? {}, + toolResult: toolResult as unknown as Record, + }); + } catch (error) { + logger.warn({ err: error, invocationId: input.invocationId }, "Could not record MCP App view"); + } +} + +export function toMcpAppViewSummary(row: ViewRow): McpAppViewSummary { + return { + id: row.id, + issueId: row.issueId, + runId: row.runId, + connectionId: row.connectionId, + applicationName: row.applicationName, + toolName: row.toolName, + upstreamToolName: row.upstreamToolName, + resourceUri: row.resourceUri, + toolInput: row.toolInput, + createdAt: row.createdAt.toISOString(), + }; +} + +export function mcpAppViewsService(db: Db) { + return { + async listForIssue(companyId: string, issueId: string): Promise { + const rows = await db.select().from(toolMcpAppViews) + .where(and(eq(toolMcpAppViews.companyId, companyId), eq(toolMcpAppViews.issueId, issueId))) + .orderBy(desc(toolMcpAppViews.createdAt)) + .limit(MAX_VIEWS_PER_ISSUE); + return rows.reverse().map(toMcpAppViewSummary); + }, + + async get(companyId: string, viewId: string): Promise { + const [row] = await db.select().from(toolMcpAppViews) + .where(and(eq(toolMcpAppViews.companyId, companyId), eq(toolMcpAppViews.id, viewId))) + .limit(1); + return row ?? null; + }, + }; +} diff --git a/server/src/services/mcp-http.ts b/server/src/services/mcp-http.ts index b43334a5553..5cec75a5d7e 100644 --- a/server/src/services/mcp-http.ts +++ b/server/src/services/mcp-http.ts @@ -1,3 +1,4 @@ +import { MCP_APPS_CLIENT_CAPABILITY } from "@paperclipai/shared"; import { createHash } from "node:crypto"; import { markMcpHttpResponseFailure, retainMcpConnectionFailure, withMcpConnectionFailure } from "./mcp-connection-failure.js"; // Helpers for talking to remote MCP servers over the Streamable HTTP transport. @@ -67,7 +68,8 @@ export async function initializeMcpHttpSession(input: { method: "initialize", params: { protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, + // Paperclip hosts MCP Apps views in the task chat. + capabilities: { extensions: MCP_APPS_CLIENT_CAPABILITY }, clientInfo: { name: "paperclip", version: "1" }, }, }), diff --git a/server/src/services/tool-access/catalog/descriptors.ts b/server/src/services/tool-access/catalog/descriptors.ts index a10c277caca..67d772e7077 100644 --- a/server/src/services/tool-access/catalog/descriptors.ts +++ b/server/src/services/tool-access/catalog/descriptors.ts @@ -3,6 +3,7 @@ import { restConnectorFor } from "../../connectors/rest-registry.js"; import { googleWorkspaceToolTarget } from "@paperclipai/shared"; import { BROWSER_USE_TOOLS } from "@paperclipai/shared"; import { isMemoryConnectorId } from "@paperclipai/shared"; +import { readMcpAppToolUi, type McpAppToolUi } from "@paperclipai/shared"; import { toolConnections } from "@paperclipai/db"; import type { ToolRiskLevel } from "@paperclipai/shared"; import { GOOGLE_WORKSPACE_CONNECTOR_PROFILES, type GoogleWorkspaceConnectorProfileId } from "@paperclipai/shared"; @@ -20,6 +21,8 @@ export type McpToolDescriptor = { description?: string | null; inputSchema?: Record; annotations?: Record; + /** MCP Apps view declaration from the tool's `_meta.ui`. */ + ui?: McpAppToolUi | null; }; export function normalizeToolDescriptor(tool: unknown): McpToolDescriptor | null { @@ -33,6 +36,7 @@ export function normalizeToolDescriptor(tool: unknown): McpToolDescriptor | null typeof record.description === "string" ? record.description : null, inputSchema: asRecord(record.inputSchema ?? record.input_schema), annotations: asRecord(record.annotations), + ui: readMcpAppToolUi(record._meta), }; } diff --git a/server/src/services/tool-access/catalog/publication.ts b/server/src/services/tool-access/catalog/publication.ts index f47c06c50f7..bbac9d4ebbb 100644 --- a/server/src/services/tool-access/catalog/publication.ts +++ b/server/src/services/tool-access/catalog/publication.ts @@ -224,7 +224,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection id: existing?.id, companyId: connection.companyId, applicationId: connection.applicationId, connectionId: connection.id, name: existing?.name ?? descriptor.name, toolName: descriptor.name, entryKind: "tool", title: descriptor.title ?? null, description: descriptor.description ?? null, - inputSchema: descriptor.inputSchema ?? {}, annotations: descriptor.annotations ?? {}, riskLevel, + inputSchema: descriptor.inputSchema ?? {}, annotations: descriptor.annotations ?? {}, uiMeta: descriptor.ui ?? null, riskLevel, isReadOnly: riskLevel === "read", isWrite: riskLevel === "write", isDestructive: riskLevel === "destructive", status, versionHash: hash, schemaHash, firstSeenAt: existing?.firstSeenAt ?? refreshedAt, lastSeenAt: refreshedAt, quarantinedAt: existing @@ -247,7 +247,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection const rows = await tx.insert(toolCatalogEntries).values(chunk) .onConflictDoUpdate({ target: [toolCatalogEntries.connectionId, toolCatalogEntries.name], set: { title: sql`excluded.title`, description: sql`excluded.description`, inputSchema: sql`excluded.input_schema`, - annotations: sql`excluded.annotations`, riskLevel: sql`excluded.risk_level`, isReadOnly: sql`excluded.is_read_only`, + annotations: sql`excluded.annotations`, uiMeta: sql`excluded.ui_meta`, riskLevel: sql`excluded.risk_level`, isReadOnly: sql`excluded.is_read_only`, isWrite: sql`excluded.is_write`, isDestructive: sql`excluded.is_destructive`, status: sql`CASE WHEN ${toolCatalogEntries.status} = 'disabled' AND ${toolCatalogEntries.quarantineReason} IS DISTINCT FROM 'mcp_tool_removed' THEN 'disabled' ELSE excluded.status END`, versionHash: sql`excluded.version_hash`, schemaHash: sql`excluded.schema_hash`, lastSeenAt: sql`excluded.last_seen_at`, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 80e88955423..9cf4e85702e 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -38,6 +38,8 @@ import { authorizationService, canActorReadIssuePrivacy, type AuthorizationActor import { claimSlackRateLimitRetry } from "./connectors/slack-retry.js"; import { resolveSlackTaskAuthority } from "./connectors/slack-authority.js"; import { SLACK_TOOLS } from "@paperclipai/shared"; +import { MCP_APPS_CLIENT_CAPABILITY, MCP_APP_MAX_HTML_BYTES, mcpAppToolCallableFromApp, mcpAppToolVisibleToModel, readMcpAppResource, type McpAppCallToolResult, type McpAppResource, type McpAppToolUi } from "@paperclipai/shared"; +import { mcpAppCallToolResult, recordMcpAppView } from "./mcp-app-views.js"; import { slackToolsForSession } from "./connectors/slack-catalog.js"; import { boundRunIssueIdSql } from "./run-task-binding.js"; import { executeSlackTool } from "./connectors/slack.js"; @@ -333,6 +335,8 @@ export interface ConnectedMcpGatewayMetadata { inputSchema: Record; outputSchema: Record | null; annotations: Record; + /** MCP Apps view declaration, when the tool renders a `ui://` view. */ + ui?: McpAppToolUi | null; risk: { level: string; isReadOnly: boolean; @@ -342,6 +346,11 @@ export interface ConnectedMcpGatewayMetadata { onDemandTools?: boolean; } +/** MCP Apps: a tool whose `_meta.ui.visibility` omits "model" is callable only from its view. */ +export function isModelVisibleTool(tool: ToolGatewayDescriptor): boolean { + return mcpAppToolVisibleToModel(asRecord(tool.providerMetadata)?.ui as McpAppToolUi | null | undefined); +} + export interface ToolGatewayDescriptor extends AgentToolDescriptor { providerType: ToolGatewayProviderType; risk: "read" | "write" | "destructive"; @@ -437,6 +446,11 @@ interface ExecuteTestCallInput { toolName: string; parameters?: unknown; timeoutMs?: number; + /** MCP Apps view calls only: return the redacted provider `_meta`. Never set for agent-reachable callers. */ + includeResultMeta?: boolean; + /** MCP Apps view calls only: the task (and its project) the view belongs to, so task- and project-scoped rules apply. */ + issueId?: string | null; + projectId?: string | null; } interface ExecutePluginToolInput { @@ -1660,6 +1674,7 @@ export function createToolGatewayService( inputSchema, outputSchema, annotations, + ui: catalogEntry.uiMeta ?? null, risk: { level: catalogEntry.riskLevel, isReadOnly: catalogEntry.isReadOnly, @@ -3036,7 +3051,7 @@ export function createToolGatewayService( session: ToolGatewaySession, toolName: string, ): Promise { - const connectedTools = await connectedMcpToolsForCompany(session.companyId); + const connectedTools = (await connectedMcpToolsForCompany(session.companyId)).filter(isModelVisibleTool); const hasOnDemandTargets = connectedTools.some(isOnDemandRemoteTool); const virtualTools = hasOnDemandTargets ? VIRTUAL_TOOLS : []; const githubBotTools = await githubBotToolsForSession(db, session); @@ -3259,6 +3274,7 @@ export function createToolGatewayService( async function connectionToolsForContext(session: ToolGatewaySession): Promise { const guestBotConnection = await measureRunPhase("connectors.discovery.github", () => githubGuestBotConnectionForSession(db, session)); let connectedTools = (await measureRunPhase("connectors.discovery.connections", () => connectedMcpToolsForCompany(session.companyId))) + .filter(isModelVisibleTool) .filter(tool => !guestBotConnection || !tool.connectionId || (tool.connectionId === guestBotConnection && tool.providerType === "paperclip_github_chat")); const connectionIds = [...new Set(connectedTools.flatMap((tool) => tool.connectionId ? [tool.connectionId] : []))]; if (connectionIds.length) { @@ -5520,7 +5536,7 @@ export function createToolGatewayService( try { await request("initialize", { protocolVersion: "2024-11-05", - capabilities: {}, + capabilities: { extensions: MCP_APPS_CLIENT_CAPABILITY }, clientInfo: { name: "paperclip-tool-gateway", version: "0.3.1" }, }); child.stdin.write( @@ -5583,6 +5599,10 @@ export function createToolGatewayService( method: string; params: Record; callerHeaders?: Record; + /** Larger limit for MCP Apps view documents, which go to the browser, never to an agent. */ + maxResponseBytes?: number; + /** False for reads whose failure says nothing about the connection (an MCP Apps view document). */ + markHealth?: boolean; }): Promise { const grant = await resolveConnectionGrant(input.session, input.connection); const endpoint = await resolvedRemoteEndpoint( @@ -5604,24 +5624,46 @@ export function createToolGatewayService( credentialHeaders, callerHeaders: input.callerHeaders, }); - const response = await guardedRemoteHttpFetch( - endpoint, - { + const requestId = `paperclip-context-${randomUUID()}`; + const dispatch = (init: RequestInit) => options.remoteHttpRequest + ? options.remoteHttpRequest(endpoint, init) + : guardedRemoteHttpFetch(endpoint, init, remoteHttpFetchOptions()); + // Stateful servers need the same MCP session setup as tool calls. + const sessionScope = connectionRequiresMcpSession(input.connection) + ? `${input.connection.id}:grant:${grant.id}:actor:${input.session.agentId}:${endpoint}` + : null; + // The session this read used. On a 400/404 only that session is dropped: + // other identities' sessions and in-flight initializations are untouched. + let usedSession: { scope: string; headers: Record; sessionId: string } | null = null; + const send = async (fresh: boolean) => { + let requestHeaders: Record = headers; + if (sessionScope) { + if (fresh && usedSession) forgetMcpHttpSession(usedSession); + requestHeaders = await getMcpHttpSession({ + scope: sessionScope, + send: (init) => dispatch({ ...init, redirect: "manual" }), + headers, + requestId, + }); + const sessionId = new Headers(requestHeaders).get("mcp-session-id"); + usedSession = sessionId ? { scope: sessionScope, headers, sessionId } : null; + } + return dispatch({ method: "POST", redirect: "manual", - headers: mcpHttpRequestHeaders(headers), - body: JSON.stringify({ - jsonrpc: "2.0", - id: `paperclip-context-${randomUUID()}`, - method: input.method, - params: input.params, - }), - }, - remoteHttpFetchOptions(), - ); - const body = await readBoundedRemoteResponse(response); + headers: mcpHttpRequestHeaders(requestHeaders), + body: JSON.stringify({ jsonrpc: "2.0", id: requestId, method: input.method, params: input.params }), + }); + }; + let response = await send(false); + if (sessionScope && (response.status === 404 || response.status === 400)) { + // An expired or unknown session: start a new one once. + await response.body?.cancel().catch(() => undefined); + response = await send(true); + } + const body = await readBoundedRemoteResponse(response, undefined, input.maxResponseBytes); if (!response.ok) { - await markRemoteConnectionHealth( + if (input.markHealth !== false) await markRemoteConnectionHealth( input.connection, "error", `Remote MCP server failed ${input.method}.`, @@ -5670,7 +5712,7 @@ export function createToolGatewayService( }, ); } - await markRemoteConnectionHealth( + if (input.markHealth !== false) await markRemoteConnectionHealth( input.connection, "ok", `Remote MCP server responded to ${input.method}.`, @@ -5684,6 +5726,8 @@ export function createToolGatewayService( method: string; params?: Record; callerHeaders?: Record; + maxResponseBytes?: number; + markHealth?: boolean; }): Promise { const [application] = await db.select({ applicationKey: toolApplications.applicationKey }).from(toolApplications) .where(and(eq(toolApplications.id, input.connection.applicationId), eq(toolApplications.companyId, input.session.companyId))).limit(1); @@ -6002,11 +6046,12 @@ export function createToolGatewayService( async function readBoundedRemoteResponse( response: Response, onBytes?: (bytes: number) => void, + maxBytes = MAX_REMOTE_MCP_RESPONSE_BYTES, ): Promise { const contentLength = response.headers.get("content-length"); if ( contentLength && - Number(contentLength) > MAX_REMOTE_MCP_RESPONSE_BYTES + Number(contentLength) > maxBytes ) { throw responseTooLargeError(); } @@ -6016,7 +6061,7 @@ export function createToolGatewayService( if (!reader) { const body = await response.text(); onBytes?.(Buffer.byteLength(body, "utf8")); - if (Buffer.byteLength(body, "utf8") > MAX_REMOTE_MCP_RESPONSE_BYTES) { + if (Buffer.byteLength(body, "utf8") > maxBytes) { throw responseTooLargeError(); } return body; @@ -6032,7 +6077,7 @@ export function createToolGatewayService( if (done) break; bytes += value.byteLength; onBytes?.(bytes); - if (bytes > MAX_REMOTE_MCP_RESPONSE_BYTES) throw responseTooLargeError(); + if (bytes > maxBytes) throw responseTooLargeError(); body += decoder.decode(value, { stream: true }); } return body + decoder.decode(); @@ -6264,6 +6309,16 @@ export function createToolGatewayService( .join("\n"); } + const mcpResultMetaByResult = new WeakMap>(); + + /** The provider `_meta` of a normalized MCP result, redacted, for MCP Apps views only. */ + async function redactedMcpResultMeta(result: unknown): Promise | undefined> { + const meta = result && typeof result === "object" ? mcpResultMetaByResult.get(result) : undefined; + if (!meta) return undefined; + const validation = await validateToolContent({ value: meta, direction: "result", sensitiveMode: "redact", promptInjectionMode: "ignore" }); + return asRecord(validation.value) ?? undefined; + } + function normalizeMcpToolResult( result: unknown, transport: "mcp_http" | "local_stdio" | "cognee_cloud" = "mcp_http", @@ -6283,7 +6338,7 @@ export function createToolGatewayService( const content = googleWorkspacePermissionDenied ? "Google rejected this call. Google Workspace MCP is a Developer Preview: enroll the signed-in Workspace account and this OAuth client's Google Cloud project in Google's Developer Preview Program, wait for Google's registration confirmation, then reconnect and try again." : providerContent; - return { + const normalized = { content, data: { content: record.content, @@ -6296,6 +6351,11 @@ export function createToolGatewayService( ? { error: "MCP tool returned an error result", ...githubFailure } : {}), }; + // `_meta` is for MCP Apps views only. It rides beside the result, never in + // it, so no agent-facing path can return it. + const meta = asRecord(record._meta); + if (meta) mcpResultMetaByResult.set(normalized, meta); + return normalized; } function toolResultErrorMessage(result: Record, failureInstructions?: string) { @@ -7740,6 +7800,11 @@ export function createToolGatewayService( invocation: typeof toolInvocations.$inferSelect, ): boolean { if (invocation.policyExplanation?.delegatedConnectionTest) return invocation.connectionId !== null && invocation.gatewayId === null; + // An MCP Apps view's tool call is a test-path call that carries its task, + // so its approval runs through the test path with that task's rules. + if (invocation.policyExplanation?.mcpAppViewCall) { + return invocation.actorType === "user" && invocation.runId === null && invocation.gatewayId === null && invocation.connectionId !== null; + } return ( invocation.actorType === "user" && invocation.runId === null && @@ -7810,7 +7875,7 @@ export function createToolGatewayService( approvedClaim?: ToolApprovalClaim; managementContext?: ConnectionManagementContext; }): Promise< - | { decision: "allowed"; invocationId: string; result: unknown } + | { decision: "allowed"; invocationId: string; result: unknown; resultMeta?: Record } | { decision: "allowed"; invocationId: string; @@ -8016,10 +8081,13 @@ export function createToolGatewayService( }, }); void emitConnectionInvoked(db, args.invocationId); + const resultMeta = await redactedMcpResultMeta(connectedMcpExecution?.result); return { decision: "allowed" as const, invocationId: args.invocationId, result: resultValidation.value, + // Provider `_meta`, redacted, for MCP Apps views only. + ...(resultMeta ? { resultMeta } : {}), }; } @@ -8059,9 +8127,13 @@ export function createToolGatewayService( resource: ConnectionManagementContext["resource"]; } | undefined; const userId = delegated?.responsibleUserId ?? invocation.actorId ?? "board"; + const mcpAppViewCall = asRecord(invocation.policyExplanation?.mcpAppViewCall); const session: ToolGatewaySession = { id: "test-call", token: "test-call", companyId: invocation.companyId, agentId, - runId: null, issueId: null, projectId: null, actorType: delegated ? "agent" : "user", actorId: delegated?.agentId ?? userId, + runId: null, + issueId: mcpAppViewCall && typeof mcpAppViewCall.issueId === "string" ? mcpAppViewCall.issueId : null, + projectId: mcpAppViewCall && typeof mcpAppViewCall.projectId === "string" ? mcpAppViewCall.projectId : null, + actorType: delegated ? "agent" : "user", actorId: delegated?.agentId ?? userId, responsibleUserId: userId, createdAt: new Date(), expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), }; let managementContext: ConnectionManagementContext | undefined; @@ -8077,6 +8149,10 @@ export function createToolGatewayService( const tool = (await connectedMcpToolsForConnection(invocation.companyId, invocation.connectionId)) .find(candidate => candidate.name === invocation.toolName || candidate.upstreamToolName === invocation.toolName); if (!tool) throw new ToolGatewayHttpError(404, `Tool "${invocation.toolName}" is no longer connected`, "tool_not_found"); + // A view's held call runs only while its tool is still callable from apps. + if (mcpAppViewCall && !mcpAppToolCallableFromApp((asRecord(tool.providerMetadata)?.ui ?? null) as McpAppToolUi | null)) { + throw new ToolGatewayHttpError(409, `Tool "${tool.upstreamToolName ?? tool.name}" is no longer available to this app`, "mcp_app_tool_not_callable"); + } await prepareApprovedConnectionAuthorization(session, tool, signedPayload.approvalSnapshot); const liveApprovalSnapshot = await connectedRemoteApprovalSnapshot(session, tool); if (!approvalSnapshotsMatch(signedPayload.approvalSnapshot, liveApprovalSnapshot)) { @@ -9876,8 +9952,8 @@ export function createToolGatewayService( companyId: input.companyId, agentId: input.agentId, runId: input.managementContext?.workContext.runId ?? null, - issueId: input.managementContext?.workContext.issueId ?? null, - projectId: input.managementContext?.workContext.projectId ?? null, + issueId: input.issueId ?? input.managementContext?.workContext.issueId ?? null, + projectId: input.projectId ?? input.managementContext?.workContext.projectId ?? null, originatingAgentId: actingAgentId, actorType: actingAgentId ? "agent" : "user", actorId: actingAgentId ?? input.userId, @@ -9948,6 +10024,14 @@ export function createToolGatewayService( ); await policyService.writeAudit(decisionInput, accessDecision); const invocationId = recorded.invocation.id; + if (input.includeResultMeta) { + // MCP Apps view call: its approval must run through the test path + // (app-visible tools, viewer identity) with the view's task rules. + await db.update(toolInvocations).set({ policyExplanation: { + ...recorded.invocation.policyExplanation, + mcpAppViewCall: { issueId: input.issueId ?? null, projectId: input.projectId ?? null }, + } }).where(eq(toolInvocations.id, invocationId)); + } if (actingAgentId && input.managementContext) { await db.update(toolInvocations).set({ policyExplanation: { ...recorded.invocation.policyExplanation, @@ -10124,7 +10208,7 @@ export function createToolGatewayService( } await input.managementContext?.reauthorize(); - return runTestToolInvocation({ + const outcome = await runTestToolInvocation({ session, managementContext: input.managementContext, tool, @@ -10139,6 +10223,117 @@ export function createToolGatewayService( timeoutMs: input.timeoutMs, signal: input.signal, }); + if (!input.includeResultMeta && "resultMeta" in outcome) { + const { resultMeta: _viewOnly, ...rest } = outcome; + return rest; + } + return outcome; + }, + + /** + * MCP Apps: reads the `ui://` view document for a recorded call, through + * the same connection and credential the agent's call used. + */ + async readMcpAppViewResource(input: { + companyId: string; + userId: string; + view: { connectionId: string; agentId: string | null; runId: string | null; issueId: string | null; responsibleUserId: string | null; resourceUri: string }; + }): Promise { + const [connection] = await db.select().from(toolConnections) + .where(and(eq(toolConnections.id, input.view.connectionId), eq(toolConnections.companyId, input.companyId))) + .limit(1); + if (!connection) throw new ToolGatewayHttpError(404, "MCP connection not found", "connection_not_found"); + // The document is read with the viewer's own access to the connection + // (the organization grant or the viewer's personal grant), never with the + // run's credential: no run on the session, the viewer as responsible user. + const session: ToolGatewaySession = { + id: "mcp-app-view", + token: "mcp-app-view", + companyId: input.companyId, + agentId: input.view.agentId, + runId: null, + issueId: input.view.issueId, + projectId: null, + actorType: "user", + actorId: input.userId, + responsibleUserId: input.userId, + createdAt: new Date(), + expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), + }; + try { + await resolveConnectionGrant(session, connection, false); + } catch { + throw new ToolGatewayHttpError(404, "View not found", "mcp_app_view_not_accessible"); + } + const result = await callAssignedConnectionProtocol({ + session, + connection, + method: "resources/read", + params: { uri: input.view.resourceUri }, + // JSON (or SSE) framing escapes the document, so allow headroom over the HTML limit. + maxResponseBytes: MCP_APP_MAX_HTML_BYTES * 2, + // A view document that fails to load says nothing about the connection's tools. + markHealth: false, + }); + const resource = readMcpAppResource(result, input.view.resourceUri); + if (!resource) { + throw new ToolGatewayHttpError(502, "The app did not return a view for this tool", "mcp_app_resource_invalid"); + } + if (Buffer.byteLength(resource.html, "utf8") > MCP_APP_MAX_HTML_BYTES) { + throw new ToolGatewayHttpError(502, "The app's view is too large to show", "mcp_app_resource_too_large"); + } + return resource; + }, + + /** + * MCP Apps: a view's `tools/call`. Only tools of the view's own connection + * that are visible to apps can be called. The call runs with the viewer's + * authority and the agent's connection access, through the same policy, + * approval and audit path as a connection test call. + */ + async callMcpAppViewTool(input: { + companyId: string; + userId: string; + view: { connectionId: string; agentId: string | null; issueId: string | null }; + toolName: string; + arguments: Record; + signal?: AbortSignal; + }): Promise { + if (!input.view.agentId) { + throw new ToolGatewayHttpError(409, "This view's agent no longer exists", "mcp_app_agent_missing"); + } + const tool = (await connectedMcpToolsForConnection(input.companyId, input.view.connectionId)) + .find((candidate) => candidate.upstreamToolName === input.toolName); + if (!tool || !mcpAppToolCallableFromApp((asRecord(tool.providerMetadata)?.ui ?? null) as McpAppToolUi | null)) { + throw new ToolGatewayHttpError(404, `Tool "${input.toolName}" is not available to this app`, "mcp_app_tool_not_found"); + } + // Task- and project-scoped rules (block, Ask first) see the view's task. + const [issue] = input.view.issueId + ? await db.select({ id: issues.id, projectId: issues.projectId }).from(issues) + .where(and(eq(issues.id, input.view.issueId), eq(issues.companyId, input.companyId))).limit(1) + : []; + const outcome = await this.executeTestCall({ + companyId: input.companyId, + issueId: issue?.id ?? null, + projectId: issue?.projectId ?? null, + connectionId: input.view.connectionId, + agentId: input.view.agentId, + userId: input.userId, + toolName: tool.name, + parameters: input.arguments, + signal: input.signal, + includeResultMeta: true, + }); + if (outcome.decision === "ask_first") { + return { content: [{ type: "text", text: "This action needs approval first. It was sent for review." }], isError: true }; + } + if ("error" in outcome && outcome.error) { + return { content: [{ type: "text", text: outcome.error.message }], isError: true }; + } + return mcpAppCallToolResult( + "result" in outcome ? outcome.result : null, + "resultMeta" in outcome ? outcome.resultMeta : undefined, + ); }, /** @@ -11548,6 +11743,16 @@ export function createToolGatewayService( // the row to failed, and emits — an earlier success emit would make one // execution report both outcomes. void emitConnectionInvoked(db, invocationId); + if (connectedMcpExecution) { + await recordMcpAppView(db, { + session, + tool, + invocationId, + toolInput: argumentValidation.value, + result: resultValidation.value, + resultMeta: await redactedMcpResultMeta(connectedMcpExecution.result), + }); + } return { invocationId, status: "completed" as const, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index cc3eda6c434..5b0131adc80 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -69,10 +69,10 @@ "packages/shared/src/announcements.ts": "1405e849eeeeb67239bacc1bbb3903385a5faa6f", "packages/shared/src/antigravity-runtime.test.ts": "f9ebcc9430be51c342b42644b735f1434b405ec7", "packages/shared/src/api.ts": "1d61cdff51433c4136368d52ee7cf2f16aa820ed", - "packages/shared/src/app-definitions-url.test.ts": "7378d29fd8428e4807dd234b495aa9043f40e6d7", - "packages/shared/src/app-definitions.generated.ts": "d74319a5c9684633b4a0a23c8bfa682e0d3bf267", + "packages/shared/src/app-definitions-url.test.ts": "56792d6745a5bc7eafc36e7403f4c9bbd671ae99", + "packages/shared/src/app-definitions.generated.ts": "e314e97d3b535c8d3942052240f794049bb9f44a", "packages/shared/src/app-definitions.ingestion-report.json": "a7b60c7c16a484a411989315e9f08d48258fa647", - "packages/shared/src/app-definitions.test.ts": "3c048c63a6d2c630a984f6f10e1dbdd9bf7c4f68", + "packages/shared/src/app-definitions.test.ts": "54cf668cf97cf1b57e8af631beeb2828e9730558", "packages/shared/src/app-definitions.ts": "eaadd6b7831cc23998a1a3ec6fd1d3a5032a503b", "packages/shared/src/app-definitions/1password.json": "c11a4777de2c78805b2d391da5eb075a9511e0f8", "packages/shared/src/app-definitions/agentmail.json": "edd0799b1980d0f5f43b89c8f7a1173dc623f7fa", @@ -91,6 +91,7 @@ "packages/shared/src/app-definitions/calendly.json": "cdedf7bed6940ec375042b6e1982b7af6e2d7284", "packages/shared/src/app-definitions/candid.json": "7d9668da949918163ef3d4b4be85bf7b559613d5", "packages/shared/src/app-definitions/chat-completions-api.json": "021e0df41be5bdc3801f33586adf91c22bb080ae", + "packages/shared/src/app-definitions/circleback.json": "2b05e87c3569738ff3ea7820a02f4483b11df0ab", "packages/shared/src/app-definitions/clickhouse.json": "f7ede2aa309c5607b008309ba32397924c73950d", "packages/shared/src/app-definitions/clickup.json": "2367ba3afc2f22bd49572467643bd81620b3f350", "packages/shared/src/app-definitions/cloudflare.json": "693237c0a9b09b66c4fc3b265efb17520b40df31", @@ -267,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "58b6dac8a1fa6ad09abafbec3a0e3117c1038813", + "packages/shared/src/index.ts": "f9865d8aa6a8a30239e9024ff191c6767857ba5a", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -284,6 +285,8 @@ "packages/shared/src/link-preview.ts": "ffa5eb960a7e4bcfa914b4d6029c9fc50f17e027", "packages/shared/src/markdown-work-products.test.ts": "7293d14ad45ec2b11b5deaab4ce070c36f7c9010", "packages/shared/src/markdown-work-products.ts": "16a88cfb717f325c247a516e78b47d53871b52ed", + "packages/shared/src/mcp-apps.test.ts": "848f3247bdc98af398daa144b0e44991a3f352b3", + "packages/shared/src/mcp-apps.ts": "12831e28596fd92c398e820422e3939b419be8ed", "packages/shared/src/mcp-config-help-prompt.ts": "fa58effb7cd995198909315d9ba2a93dedde0552", "packages/shared/src/mcp-remote-headers.test.ts": "b59cd4fc197145d400d2eca7998a09b6fb834cb6", "packages/shared/src/mcp-remote-headers.ts": "d4522440255ddbb5b117bf1575e7fb1a6744f505", @@ -334,7 +337,7 @@ "packages/shared/src/runtime-exposure/loopback-bind.ts": "696dcbc1fc8f7e64f37314bc574360cf06bbae95", "packages/shared/src/runtime-exposure/ports.test.ts": "de27b2c17db88c65f9f4e7240d9fae969dd1551e", "packages/shared/src/runtime-exposure/ports.ts": "6566d780a36c4eb37fab5584db19714f596654b7", - "packages/shared/src/self-serve-mcp-research.json": "e9f6f6216273917205162b82a71993003225ebc2", + "packages/shared/src/self-serve-mcp-research.json": "98a90544e8e00b31350b5c07e39940429bc026b9", "packages/shared/src/self-serve-mcp-research.ts": "312abfecb0dbac8a0e5bf80fb8e3467ca94f500f", "packages/shared/src/setting-defaults.test.ts": "f5554686f7bf9cc34f14cdd4505257dcc562d410", "packages/shared/src/setting-defaults.ts": "672726c2ea0c9608829a1514d7ae3567b53d88aa", @@ -424,7 +427,7 @@ "packages/shared/src/types/summary-slot.ts": "9698bb7d628be3f2310d050037e30157d474ed48", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "ec1bab568443f1ce2e0e04531d343df3ec0aa8bd", + "packages/shared/src/types/tool-access.ts": "e9f7b60527c91bf816d7fe92834bbd20be793685", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", diff --git a/ui/public/brands/apps/circleback.png b/ui/public/brands/apps/circleback.png new file mode 100644 index 0000000000000000000000000000000000000000..2f6faa5a0609cd3a7fb4e2662e933a9bc8251f54 GIT binary patch literal 9887 zcmdtIc{r5c8$bTc*!LyN5D}G~Daw{5vPB4E%Q7jV?7OiIq7W+Es0rDPJ!EH)B{P-? zkv01$gh}?_FF=cNY#fJsmHwg~`0 z;b#{uHCTiBbI$|(q4U(W@&N#@%V!rv&*ah;SPAhl(a`|P2l&>&0_EddcW(heRT9I| z11bQxBByuzmRTU=_w@ZYW)^8z=4z9KtO(#j9gP?Dhf6lCgD)A?A6<#` zOgb&C{X5A9cK-kBhj^Dh+iTmo{;xgT(~8q6yU$zM_Vz8W0%%6-#=|!}K6NhutD+EU zu3s{_^PVQruf4DFn5)?k#F$L`+Om!p9tE z5#RL`{rkjM^GH2foZew|*JtR^)U3!kj2%_#m%J%a(yKQPD&FMZ3Fb!Qh5aN#&cdsOrhGnFl!a*uJ46Hid5AVvY29ybM; z>hSE%@GySjKcqI)K!2#VLs;d!NGic!i_2vC@yXEkz1T=g z08LjKoPtja{lV0ZL2CRUP@_nKlx+AqzNv%JlNAy(cFwxd4dtp_SW%OK9;buXjGY(| z7M~=3XZ(;aVB)I96EGNl7$||ZJBM^mT??6QP*Cgs=3DWMB~KRbQcnmlCVh?50Xp zDLkI-bERp$iWp!;S}L_ir=EM1O{RpU70^rPl4LgstTxW{x2Uc4(GTW{^+Ud5!~H&5 zUKXz+{(|bT_UN=K9ct^_=m#5446E+Mv1832FXJ7y);2$ND?{YcfKD5gHt)5V;J8)F zovTC6P)47tZrrKK6`g45>1zXup?>o}bm}OaIUq5z#XqzLcNPh~BekbPh=qW-b`jjw zAwDgI%SX=Tk zD!2kRg$f6^0e*@OZqNc_8Yg_Dm%&NHjjZof3R>$L+}F-eW0TaFHbHGU?AEPAh^fGc z52E6P@R3N?@^ep$>4K#>{u#RW6eA;*mw9ayN=O%)4%s}(y$``=03(_sWsTO_mF#5C z&EP$Oa5j7fEnG$R{8(9Md>UKnowzbRUYh_7I>SLmgQVtvyTi2~TiMkEBS!nKiubk9 z_+6Jno3bHMKlf8v+*6W6M9|v0ugBKS%ULN3bECge_yvA>?M^*(+rJAhMhoY+5J(<) z%|H9h>72vdGfE6|us_)$GNBIb8JzOrZw)4Htj| z5zZ*1nIF6!G=lh=*IUq*+C#&u^}hnI)56Pyo7FcHL=Z2$n%}m{e*PgecoOJ!39MtH z3EFm4A1ub#e74u_oF{m1R~~Fw11*n>(p%3Vt&v=I7tCh)sqrsA*c}+4UFz5RhYwTJ z9{@*hgJ38Eqd}+2U^0qf1rCIjWInGdPPb!6@|LQ4aVTm-JYSJiey$0~gkBhuwbo@q zWGUcI{B0Jg`JNxccLy4>y___g67~MxPK4>)X%gEW*zHj~wj9+C7`bG$!aFROWPeIt z`8l=Qll-EVFSt!9HBH1t;TZE*tso`bJ`}dBORhLyfPL?&c?>Bz4nceRs;=#-Y-gZF`my zu>&VH2X zqpXk2d#au^_PTwOfVVhW2U<0vy7Qk*OpBX(Sp{0P9t<`gRG(hbnPN)A(f^VsEo?&g zbD-6a4Ef7+=q ze#PM}mB_k}i|~?PO8v~Tlz6Eb5TRG6#7w| zg9WOQ)B)Tjs=U^-deBk7L-!V=gmqULcBAbN4}z*kX*#7wXUM{Vb0IHCymYFVO!EMHH$Ux{y6h+TAU8in0-+~%RO~{P-koS*{RKMdyU6!42RD!`+Bd-8}i?N zVn;3$ha303qoh5AKNI!n$K8gkp+szPD=}%S;{l2FoLD#;)+VkDOMIKk4{tOCMJ*wA+$2s+o4KpYpE!|XxT^xTM<0*i|@L-Nw;b|N^d$kI7ylY zJ3La7exU$6p4&soeW1bMVrL?1pVj^gg*KuX$Ufl{&j~S(#yr?14z^!ra&HUYd_AYJ zQj8}?kO&jR4uS|ZL&o!!T$UT&85eFF71a+}K#6?yUI(tE1+28wqs+`i>Cnu+BS&9L z{-ctBt%^R;4O;2l*MN_9Xz=7ad67iRl*bk_szs{pH*y|&FTOX+t00Y7KvbNlmtT4t zjz^B@d98G)%tv=&^4iI_Qdmm3UF6M|3cnkQ%_>z`)0v9HA0xe{*ZP<3q$NVDbqBS% zb?$Y`e|4&!%ju_YTNaOyt*qbJ1r2cr0|TPg>JzDU|Esp2XGYl}x7}P_&8vZ&sAIBY z(TW{b!NCe=KFp1faLK)1c8QZ)flDgS)Z6zU1t-695PJ<7Ywabj=NWPCtA-8!1}u9x^NctanW@t?pLr@nBdTQ% zlkdmgCe}J~?Y`OaM%q=6HpC+LO(PUPpmyBrZ_M4sD&>fg20L-kZG_~P^PK7L%xUmP zMR@G1{w5JqmW|0z`pKXteivn9cYm?!2`9JZO-{@?eSI0VIx7_go*_X$&Px{aLR{I* zzZ!Jyi|X+|Cn$WN{%u&}IOUa1l^cf|3paU~#;KPU^@w`>Hh(w8t`#v8a-cr!S~g6H zZf~e@GIGN;^yj?f2cCS|XnT?zCfbbm&WKPfIEa<%i~al63o*(a)g)(iZ&A77=90m? zvW7};ad?j$hE_)8!-2*~|KASRti`s4NG)e(PRxS%&xPK0ucFo=_MVx6lAq9ohcEUp zncx!7yIwa@ZW&q;4`|-!JDB9M$*!t-mH42s*)UM?!YH@(a+wa!wvslXFxr9m#wzEqa|I@q=WXG6c}Sgy$2=Kf33s(Afl(q5&WD+V2s?8aBxdvL% zcvwRz@-G`uB7|?&3O&8I*v!S}db;}>tdh70Rw-r_weoeX2?OT3=%9FPO;VysZPF(S z!2C8kh=Ji3vjtT%KVcoPybM`(ldM#>k#1uEEH6TqnMNRX%m|JZtSS_lPl=IFN&W&? z_-6On5Wv&Z!9C#kV9K6Ch%*3cQU|i6`<$o($SzPX5Bt15!sPW?4+iKUP5)^8hhO24 zY&uHJxI%<)J$Cr}5d&~n5Z~NQmnVz?B^N=-;w@h4=emhT6hpL7;(8y9nnpa%K^e$~ zoZY1ns=)9IaHfYWUl&`cofB-L4ut%#lxQp zRlF_T$@T=`)kJ4}NzQ}%ypZc%0MIe4NT*+D#i>iw{}t@SG^v(7|N9?ym67=;?R6kQ z2v5vQk)iZJ*#Cq9LxNDEOwB9iS3)IVU!qW=gcZXYQXCG*#REHcyk8y&D)uBn048w! ze_qIoS{l-TX5XWPB|f62Mi;Ol9Z)R8a0O#tO9vYDYFap;zD^6j+S2O<<8vMaR}-%` z8Uk4BpyzcrJra8U*NoZrXJ#1Sd=BE21yBG|LU>OOWhCIt2Z_lA@0UviD{KC*zB=#O zR0HY@v~Vywg=BkCVnWB3DAeO=;i+=HP~yeRmoYf7y*QxL>#W^4z*Nu6kct`rqqpK_ zISQX5AGS^aP0fZ>Fi8Z1pR-{xo0;WJii)~R!~;W;P)40TFyIDwwb1)r3V}^#%oG6c zZSYORIJu!`|AHHX?@a2_^s-s&0&+3HP9v5ILjf*Ca5%v&Al+r?`RYKF4F7LEeeVvgzoigMsV++k zuaIEezHr58`2QE>#X9;wzY`?EvgIJOuE_`ub zbs>jm zclF;;Efgq?q$fsf`+H)p_Y^}cIU&n{VuQ(?sABp!6fjo@Eec!yt(n}#o8G*1XFLmY zCHIQIWR3FhB=V>K6Clk9t%yJI#4UW&5&v2JpG|u0bA!f*BV8F<2?ZBYoY1EzVNS>W zAOO!!2Y(*uv0mur1J{wrsrkl?&Sys^K4M-LRUAGzL(BkDj}jxin6g2o(--7`;YR1P zArp_Ax+gX@jC+;XioY8G3 z{i~;CTJrP3a=VbNUrF5Z6wXwjMqJJ}ZKcfX2-xKEQizwj}b)D?O4GsX%wDY)YM8`fsNI3MCx!4s718xL&+BEnFlo!B<1^#+2FJWTGKE z)5F)4JeCR|s422YG^+FWwpq{{z4Jf%qSE2HWcht8t~O6xYB){WAYMX_4SV_1@X|iQO{=@)B{v&By2n@WSd%;Z z=AJ@g!;R+bC2;<{vPp%nH_OG)rr7wuA3lwX;rOad9vHD%exIFGfCH?K?4;UhLDrZ19l_9@6zja!3wIvt6_z(ke~gSptrS&VK1b8 zye_E}M$6GSUajZHj%`&e&B(`~GSY2ArTe+Y{N5d=ttvvCn9r=4rE36+9EQ1-8Nvgn z8QfD#kNL_S$*6J}gz{bfkIh=>#x>(0kKrxrMHvk1Tt=@xJSO6auR&3|&%w`*x}=&# zg{p%$pQoOWfp7~kpF&+HnUGgPiBUwU9%Q2^?#`$W7QyoRXG3>Z-SJnilXAKXCfXFX zOLk^eXXsa1Ax;Bk50*RqDEQL1yj{!1vQ5F}GpsQCMb?nnX4vs>6#gRVoK7(K0vDV4 zo16n8AoTlo6Zqct6EKrGOMWdAe9ZYyA<^fJpqHQY+_U6qy}S8sjf!QPGgz2~-_f2JfB-`vlH?5+LBJ;0Fdx1qzF^YyaJcu8Y01hNes zon~4tppTZ%vTs%4 zFEHrdh6=0Q^3yleGw+zx36D$2mOaZas)&TIe>8BiUloKnMQ7UW&-usg zT2=B!5{C_*`|d2p*y<82Hbccs|HP6QY=!Zqugpy}X|FK|*O%HQ`mT2z>&R0mX``*K zmgP~iJzCcGbfLZ1a$}tk83EK$ZV#Mh zODDa{aGzdw6z6n%xxOt2IjzOD)!~(5qCIuLd31(NLGUJXTv=;$hEmOK#fG=SH#D7H zN>NtJ(T8di)tZHLaHgGKq%IF9qnet|K=bzvdv=KTdi+fvv)x%#vOq2@c=cgwn!l&( z+g4U2Z}&}uCWKL|vR2-2>_U?R9CqsdwE3Kr$t>-$_q7RKF;#J4k33x`>&fo9jSjb? zrx&=w6B5A01aADG^58GY?^?)0dSc1A$+2~f!oM*1i}$BHYNjPK+;8uoT?BXF z??2ve>GL-!pK10!sDg1Qx5blsB+9>iOHDn+;lwIB?ih}q-#qzpG0VrzX<(wbyKiKnczuu2)ueZdUj zMhXusM|mH5kl#&-MH<>_6{~F^jG}_B70)`4<34r3^N$W+td0DHAOF>Roi?KMwyo`S zrTJcHy*0w{#>0sDR(jb0+>-$daaj>zyd35j-Yh-7bAv|r(4!nD5?bIVC-3K39C?z^ zycnwOhbTDkUspR(aih@zN!bl>yR!Tq1DF@SeGNJ4Y+EGbCbu2!{s?u8e|BxzF%0?B zb}9v;G|pSOh|BXv>%*Qvb61U@8McWBYpt@d{XCo~eIeh15nBQ>t|3uZi<} z2YdhW(}pYP;8Nc6Cr0w?4_W|JS!QrXUIgx!SbrqG-#P1@22lni$6u{eXSd2hx{y6#0tNJln4Eo&ClwZzYfryq=0-MOqi5b|(Fr zc@GLNOscez10@uyz$dklp=#lo_Nu<1k$7Q5<4KiB?tEqM5(T%K#-5cq=$G!T9b7W< z^|(*oXxi*vYQ0cp9^q2e_|j%JG>4sH+Pv;%boxk12O(;88FBt8nfcvUC$)fQ;9Km8 ze>O|-s>{%z>6dmnl2b^XDD8zS;btD}l)kWwxi6KMSXsv1*uymPSoSIZF{=t3_Iasw z+NlgW!bbiyqj8y9>7l<3IGRyytuJMAMM(OhxsSoT1e-(l`Df|Xhlk+<=R+sc5%wC2 z#{nB`kb;NLV9sq5<=jn~1K9_WGfgUDp@#unNTpRUDWF7WUG!qzzXjW`cBF4tA;JDt zHngMzOllyW!*ohNIR5PFBD^owF<=PVL6|a|&)?*pE>~Iqk`)1rP*k(}Oi;ZVk|ew2l5GE(&O3&g z#Fe!7e5HUI7=7bbx2xY<^-iomkMCqrlA99JqeFs5)SKepwKBScR^t?Yp zYo$mvlw-PiXEkr^#*HSmJyHDb5NKMaiCPCj==^hbT#v8Cl94#kM*CQHB#P8Amiwc) zHzxQ&EJ;!Byg#=n1H2;d!jTo2F8Vt&X7s~QwB7sL&f^Y(L%xtIeL)}dEdDqSOhr`~ zifYkEJ*yN{94KALsTr9SY*0-Y7#l*OEUt{Up%UGj@o2-3obG)MbTY)J*=9FJTTdR9yP#d38ViFZZ4*WFGjLwAm4x&TuOqX(e~8To4`A zZ>>#UzigTBwbiGfv|)p1a|)KYk(DU@JC9FZ=yCE1YqhEN(jv%>p9U#s-!h3CsDmSr z3ZGEHn~%aD6aCc(`#+KFTDQu!hB-#L-84tqz?`z5-}QnE#@LyBGqq3+mQjiga&}W$ zWB(h%zpLLZy7#_%K^Y6Tal8+2#HfO_|dNQ+TNIvD|yVFH066BxvQ4Gq>vYpRWqR9aOJ|p!Fa=TaV=UxRw^3$aH>E+4?4~ zM#FQB{`ZuR<^^_=Jw=8$z)d@ol$eajh+o@o0+&F^_QCVN-9uC(g9}2c@1^q3)0DmP znTpRWIbm##zrc#bluU5VvaB=wqU4#xT^KGif{j`{r7U}ceN%eMi24&Gfv;pGQ~4h< zY;9XW-0s!IGv{+Y)B%$(sTKtbF+ATUW&&=-Vdhm`b-at z@WL!DwdwtxtYPvhgcHWKLEeYyZ#lo2z!J!)0j)1%qbRMpr_3zTy|donh(E~<)d;d z1Us8)rH?=TkqK(SeC}M0`1q2gZgaOJM+!frU?}C~M6L{sYa)A{WRIV0CG9(r=e2!* zl&PJHO~1@!LpqmQ+$z8>^Y8KlI{zEAQ&MT-z>4G9O0yj?~l32xzl_xq1y15!2dq z)sjd9i`i!i`Qwwf14@rp+;FV2l5s8)#ZLn+{WdSlC4@fZZxO-|iOXnrlJyk#n{joyB;p*yiEAtJzrazBCJ!wtUZ(@&N=cssme->+`~x`^>j20Haqq2g2xU1-Zuz- z_d2em!+=01C8~?wDAFLVR0%k|Jqa^zlO{z>E4L3)!cZ=#507{d zeg*$5{hYp##PtVe$D`_lz1(%2AEY|zlnQ|9Qf-QS4&`LMkje4f;pc3~)s~6af&`o8 zgp^?&!|VMP2-}HRo3Qk_8kN}gPk4=U*K6{9LHONh8_ivjQ3q~9CckV&FiVNhf7pT> z2(hWfjxkXR7$w5Sjb0+0_sd^+>qJN2$Ur=7Ep1hfZ_#f#VfqNHI*&cSBb zpTvZEsPuQ-QSm(tjk{@X`$6L5Bx^@|!0X|Jyj9^E0_OF9fWaIicsj$;Af}-dCnt8= zdQd!H>M#;}ab79!vrN>dk?d_lMt>}84h!i=>4;s3U38q5on+JfmZ1%?`~T%rPXC?W8ge}q*n1eJWbM&KIIGdq MGQ3@`fsFkB03yx{fdBvi literal 0 HcmV?d00001 diff --git a/ui/public/brands/apps/manifest.json b/ui/public/brands/apps/manifest.json index 0316bb2d05d..5466ca41fb6 100644 --- a/ui/public/brands/apps/manifest.json +++ b/ui/public/brands/apps/manifest.json @@ -83,6 +83,12 @@ "catalogVisible": false, "localAsset": "/brands/apps/candid.png" }, + { + "slug": "circleback", + "provider": "Circleback", + "catalogVisible": true, + "localAsset": "/brands/apps/circleback.png" + }, { "slug": "clickhouse", "provider": "ClickHouse", diff --git a/ui/src/api/mcpApps.ts b/ui/src/api/mcpApps.ts new file mode 100644 index 00000000000..bc4e32343b9 --- /dev/null +++ b/ui/src/api/mcpApps.ts @@ -0,0 +1,12 @@ +import type { McpAppCallToolResult, McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared"; +import { api } from "./client"; + +/** MCP Apps views recorded for a task's tool calls. */ +export const mcpAppsApi = { + list: (issueId: string) => + api.get(`/issues/${issueId}/mcp-app-views`, { cache: "no-store" }), + detail: (issueId: string, viewId: string, signal?: AbortSignal) => + api.get(`/issues/${issueId}/mcp-app-views/${viewId}`, { cache: "no-store", signal }), + callTool: (issueId: string, viewId: string, name: string, args: Record) => + api.post(`/issues/${issueId}/mcp-app-views/${viewId}/tool-calls`, { name, arguments: args }), +}; diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index 03b9728a210..e908f70e894 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -44,6 +44,8 @@ import { } from "@/components/transcript/useLiveRunTranscripts"; import { useNativeRunTranscripts } from "@/components/transcript/useNativeRunTranscripts"; import { TaskChatLiveTail } from "@/components/task-chat/TaskChatLiveTail"; +import { McpAppIssueProvider } from "@/components/mcp-app/McpAppIssueContext"; +import { McpAppTurnViews, mcpAppRunRefreshKey } from "@/components/mcp-app/McpAppTurnViews"; import { TaskChatRunnerHeader, TaskChatRunnerTurn } from "@/components/task-chat/TaskChatRunnerTurn"; import { partitionRunHealthItems } from "@/components/task-chat/TaskChatRunHealthBanner"; import { @@ -3361,6 +3363,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { return ( + ) : ( + + ); } diff --git a/ui/src/components/mcp-app/McpAppFrame.test.tsx b/ui/src/components/mcp-app/McpAppFrame.test.tsx new file mode 100644 index 00000000000..9944a49550c --- /dev/null +++ b/ui/src/components/mcp-app/McpAppFrame.test.tsx @@ -0,0 +1,109 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vitest"; +import { McpAppFrame } from "./McpAppFrame"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +function frame(container: HTMLElement) { + const iframe = container.querySelector("iframe"); + if (!iframe) throw new Error("no iframe"); + return iframe; +} + +function fromView(iframe: HTMLIFrameElement, data: unknown) { + window.dispatchEvent(new MessageEvent("message", { data, source: iframe.contentWindow })); +} + +describe("McpAppFrame", () => { + it("ignores a navigated frame's messages and remounts the original view", async () => { + const callTool = vi.fn(async () => ({ content: [] })); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(async () => { + root.render( + cards

", csp: {}, permissions: {}, prefersBorder: true }} + toolInput={{}} + toolResult={{ content: [] }} + callTool={callTool} + />, + ); + }); + const original = frame(container); + // The view's own document loads first (jsdom fires this for srcdoc). + let loaded = original.contentDocument?.readyState === "complete"; + original.addEventListener("load", () => { loaded = true; }); + for (let i = 0; i < 100 && !loaded; i += 1) { + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); }); + } + expect(loaded).toBe(true); + + // The view's own document works. + await act(async () => { + fromView(original, { jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} }); + fromView(original, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "RefreshMeetingCards", arguments: {} } }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(callTool).toHaveBeenCalledTimes(1); + + // The frame loads another document: its channel is dropped. + await act(async () => { + original.dispatchEvent(new Event("load")); + fromView(original, { jsonrpc: "2.0", id: 3, method: "ui/initialize", params: {} }); + fromView(original, { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "DeleteTag", arguments: {} } }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(callTool).toHaveBeenCalledTimes(1); + // A fresh iframe with the original view replaces it. + const remounted = frame(container); + expect(remounted).not.toBe(original); + expect(remounted.getAttribute("srcdoc")).toContain("

cards

"); + await act(async () => root.unmount()); + container.remove(); + }); + + it("keeps the view's host when a refetch hands over equal data, and remounts for a new document", async () => { + const callTool = vi.fn(async () => ({ content: [] })); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + const props = (html: string) => ({ + title: "Circleback: Display meetings", + viewId: "view-1", + toolName: "DisplayMeetings", + // New object identities on every render, as a refetch produces. + resource: { uri: "ui://circleback/meetings", html, csp: {}, permissions: {}, prefersBorder: true }, + toolInput: { meetingIds: ["m1"] }, + toolResult: { content: [{ type: "text", text: "ok" }] }, + callTool, + }); + await act(async () => root.render(cards

")} />)); + const original = frame(container); + await act(async () => { + fromView(original, { jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + + await act(async () => root.render(cards

")} />)); + expect(frame(container)).toBe(original); + await act(async () => { + fromView(original, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "RefreshMeetingCards", arguments: {} } }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + // The same host still knows the view finished ui/initialize. + expect(callTool).toHaveBeenCalledTimes(1); + + await act(async () => root.render(new cards

")} />)); + expect(frame(container)).not.toBe(original); + expect(frame(container).getAttribute("srcdoc")).toContain("new cards"); + expect(frame(container).getAttribute("sandbox")).toBe("allow-scripts"); + await act(async () => root.unmount()); + container.remove(); + }); +}); diff --git a/ui/src/components/mcp-app/McpAppFrame.tsx b/ui/src/components/mcp-app/McpAppFrame.tsx new file mode 100644 index 00000000000..6c9f5218396 --- /dev/null +++ b/ui/src/components/mcp-app/McpAppFrame.tsx @@ -0,0 +1,145 @@ +import { useLayoutEffect, useMemo, useRef, useState } from "react"; +import type { McpAppCallToolResult, McpAppResource } from "@paperclipai/shared"; +import { cn } from "@/lib/utils"; +import { createMcpAppHost, mcpAppDocument, type McpAppHostContext } from "./mcp-app-host"; + +const MAX_HEIGHT = 640; +const INITIAL_HEIGHT = 120; +const STYLE_VARIABLES: Array<[string, string]> = [ + ["--color-background-primary", "--background"], + ["--color-background-secondary", "--muted"], + ["--color-text-primary", "--foreground"], + ["--color-text-secondary", "--muted-foreground"], + ["--color-border-primary", "--border"], + ["--font-sans", "--font-sans"], + ["--border-radius-md", "--radius"], +]; + +function resolvedTheme(): "light" | "dark" { + return typeof document !== "undefined" && document.documentElement.classList.contains("dark") ? "dark" : "light"; +} + +function hostStyleVariables(): Record { + if (typeof document === "undefined") return {}; + const computed = getComputedStyle(document.documentElement); + const variables: Record = {}; + for (const [specName, tokenName] of STYLE_VARIABLES) { + const value = computed.getPropertyValue(tokenName).trim(); + if (value) variables[specName] = value; + } + return variables; +} + +export interface McpAppFrameProps { + title: string; + viewId: string; + toolName: string; + resource: McpAppResource; + toolInput: Record; + toolResult: McpAppCallToolResult; + callTool: (name: string, args: Record) => Promise; + className?: string; +} + +/** + * Renders an MCP Apps view. The document runs in an opaque-origin iframe + * (`sandbox="allow-scripts"`, never `allow-same-origin`): it cannot reach + * Paperclip's DOM, cookies or storage, and its network access is limited to + * the origins its server declared. Everything else goes through the + * postMessage protocol in `mcp-app-host.ts`. + */ +export function McpAppFrame({ title, viewId, toolName, resource, toolInput, toolResult, callTool, className }: McpAppFrameProps) { + const iframeRef = useRef(null); + const [height, setHeight] = useState(INITIAL_HEIGHT); + // One mount is one iframe element and one document. A second `load` means the + // frame left the view's document: that frame and its channel are discarded. + const [generation, setGeneration] = useState(0); + const srcDoc = useMemo(() => mcpAppDocument(resource.html, resource.csp), [resource.html, resource.csp]); + // A refetch of the same view hands over new object identities. The host reads + // the latest values through refs, so it lives exactly as long as its document. + const latest = useRef({ callTool, toolInput, toolResult }); + latest.current = { callTool, toolInput, toolResult }; + // A different document is a different frame: remount the iframe with a new host. + const documentVersion = useRef({ srcDoc, version: 0 }); + if (documentVersion.current.srcDoc !== srcDoc) { + documentVersion.current = { srcDoc, version: documentVersion.current.version + 1 }; + } + const frameKey = `${generation}:${documentVersion.current.version}`; + + // Layout effect: the listener must exist before the view's first script posts `ui/initialize`. + useLayoutEffect(() => { + const iframe = iframeRef.current; + if (!iframe) return; + const hostContext = (): McpAppHostContext => ({ + theme: resolvedTheme(), + displayMode: "inline", + availableDisplayModes: ["inline"], + containerDimensions: { maxHeight: MAX_HEIGHT, ...(iframe.clientWidth ? { width: iframe.clientWidth } : {}) }, + locale: navigator.language, + timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, + platform: "web", + userAgent: "Paperclip", + toolInfo: { id: viewId, tool: { name: toolName, inputSchema: { type: "object" } } }, + styles: { variables: hostStyleVariables() }, + }); + const host = createMcpAppHost({ + // The view's origin is opaque ("null"), so target "*"; the message only + // ever goes to this iframe's own window. + post: (message) => iframe.contentWindow?.postMessage(message, "*"), + hostContext, + get toolInput() { return latest.current.toolInput; }, + get toolResult() { return latest.current.toolResult; }, + callTool: (name, args) => latest.current.callTool(name, args), + openLink: (url) => window.open(url, "_blank", "noopener,noreferrer"), + onSizeChanged: ({ height: next }) => { + if (typeof next === "number" && Number.isFinite(next) && next > 0) { + setHeight(Math.min(MAX_HEIGHT, Math.ceil(next))); + } + }, + }); + let loads = 0; + let navigatedAway = false; + const onLoad = () => { + loads += 1; + if (loads > 1 && !navigatedAway) { + navigatedAway = true; + host.teardown("The view left its document"); + setGeneration((value) => value + 1); + } + }; + iframe.addEventListener("load", onLoad); + const onMessage = (event: MessageEvent) => { + if (navigatedAway || event.source !== iframe.contentWindow) return; + host.receive(event.data); + }; + window.addEventListener("message", onMessage); + const themeObserver = new MutationObserver(() => host.hostContextChanged({ theme: resolvedTheme(), styles: { variables: hostStyleVariables() } })); + themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); + return () => { + themeObserver.disconnect(); + iframe.removeEventListener("load", onLoad); + host.teardown(); + window.removeEventListener("message", onMessage); + }; + // srcDoc is captured by frameKey; tool input and result are read through `latest`. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [frameKey, viewId, toolName]); + + return ( +