mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
feat(connections): render MCP Apps views in the task chat, starting with Circleback (#21119)
## 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
6a24b417c0
commit
8ff45c0fa9
67 files changed
+3865
-134
No files matched your search
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 <app>" 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 `<meta http-equiv>` 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.
|
||||
@@ -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:
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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");
|
||||
+368
-2
@@ -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": "",
|
||||
+7
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -190,6 +190,7 @@ export {
|
||||
toolGatewaySessions,
|
||||
connectionTokenIssuances,
|
||||
toolInvocations,
|
||||
toolMcpAppViews,
|
||||
toolActionRequests,
|
||||
toolCallEvents,
|
||||
toolRateLimitCounters,
|
||||
|
||||
@@ -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<Record<string, unknown>>().notNull().default({}),
|
||||
outputSchema: jsonb("output_schema").$type<Record<string, unknown>>(),
|
||||
annotations: jsonb("annotations").$type<Record<string, unknown>>().notNull().default({}),
|
||||
/** Normalized MCP Apps `_meta.ui` declaration (`ui://` view), when the tool has one. */
|
||||
uiMeta: jsonb("ui_meta").$type<McpAppToolUi>(),
|
||||
riskLevel: text("risk_level").$type<ToolRiskLevel>().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<Record<string, unknown>>().notNull().default({}),
|
||||
toolResult: jsonb("tool_result").$type<Record<string, unknown>>().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",
|
||||
{
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
@@ -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[];
|
||||
@@ -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({
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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: "<html><body>hi</body></html>",
|
||||
_meta: { ui: { csp: { resourceDomains: ["https://cdn.circleback.ai"] }, prefersBorder: false } },
|
||||
}],
|
||||
}, uri);
|
||||
expect(resource).toMatchObject({ html: "<html><body>hi</body></html>", prefersBorder: false, csp: { resourceDomains: ["https://cdn.circleback.ai"] } });
|
||||
});
|
||||
|
||||
it("decodes base64 blob content", () => {
|
||||
const blob = Buffer.from("<p>café</p>", "utf8").toString("base64");
|
||||
expect(readMcpAppResource({ contents: [{ uri, mimeType: "text/html; profile=mcp-app", blob }] }, uri)?.html).toBe("<p>café</p>");
|
||||
});
|
||||
|
||||
it("rejects other mime types and other resources", () => {
|
||||
expect(readMcpAppResource({ contents: [{ uri, mimeType: "text/html", text: "<p>x</p>" }] }, uri)).toBeNull();
|
||||
expect(readMcpAppResource({ contents: [{ uri: "ui://other", mimeType: MCP_APP_MIME_TYPE, text: "<p>x</p>" }] }, 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();
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
_meta?: Record<string, unknown>;
|
||||
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<typeof mcpAppToolCallSchema>;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : 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("; ");
|
||||
}
|
||||
@@ -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" }
|
||||
]
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { McpAppToolUi } from "../mcp-apps.js";
|
||||
import type {
|
||||
ConnectionTokenIssuanceOutcome,
|
||||
ConnectionTokenIssuancePath,
|
||||
@@ -568,6 +569,8 @@ export interface ToolCatalogEntry {
|
||||
inputSchema: Record<string, unknown> | null;
|
||||
outputSchema: Record<string, unknown> | null;
|
||||
annotations: Record<string, unknown> | null;
|
||||
/** MCP Apps view declaration (`_meta.ui`), when the tool renders one. */
|
||||
uiMeta?: McpAppToolUi | null;
|
||||
riskLevel: ToolRiskLevel;
|
||||
isReadOnly: boolean;
|
||||
isWrite: boolean;
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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 = `<!doctype html><html><body><div id=cards>Meetings</div><script>/* ${"view bundle ".repeat(120_000)} */</script></body></html>`;
|
||||
|
||||
// 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<typeof createDb>;
|
||||
let temp: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
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<string | null> = [];
|
||||
let failResourceReads = false;
|
||||
let expireNextResourceRead = false;
|
||||
let initializeGate: { wait: Promise<void>; 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<void>((resolve) => { markEntered = resolve; });
|
||||
initializeGate = { wait: new Promise<void>((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" });
|
||||
});
|
||||
});
|
||||
@@ -41,6 +41,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<ToolGatewayService, "readMcpAppViewResource">;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -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"],
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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.",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
}): 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";
|
||||
}
|
||||
@@ -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]));
|
||||
|
||||
@@ -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<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : 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<void> {
|
||||
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<string, unknown>,
|
||||
});
|
||||
} 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<McpAppViewSummary[]> {
|
||||
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<ViewRow | null> {
|
||||
const [row] = await db.select().from(toolMcpAppViews)
|
||||
.where(and(eq(toolMcpAppViews.companyId, companyId), eq(toolMcpAppViews.id, viewId)))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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" },
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
annotations?: Record<string, unknown>;
|
||||
/** 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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
outputSchema: Record<string, unknown> | null;
|
||||
annotations: Record<string, unknown>;
|
||||
/** 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<ToolGatewayDescriptor> {
|
||||
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<ToolGatewayDescriptor[]> {
|
||||
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<string, unknown>;
|
||||
callerHeaders?: Record<string, string | string[] | undefined>;
|
||||
/** 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<unknown> {
|
||||
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<string, string>; sessionId: string } | null = null;
|
||||
const send = async (fresh: boolean) => {
|
||||
let requestHeaders: Record<string, string> = 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<string, unknown>;
|
||||
callerHeaders?: Record<string, string | string[] | undefined>;
|
||||
maxResponseBytes?: number;
|
||||
markHealth?: boolean;
|
||||
}): Promise<unknown> {
|
||||
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<string> {
|
||||
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<object, Record<string, unknown>>();
|
||||
|
||||
/** The provider `_meta` of a normalized MCP result, redacted, for MCP Apps views only. */
|
||||
async function redactedMcpResultMeta(result: unknown): Promise<Record<string, unknown> | 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<string, unknown>, 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<string, unknown> }
|
||||
| {
|
||||
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<McpAppResource> {
|
||||
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<string, unknown>;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<McpAppCallToolResult> {
|
||||
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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.7 KiB |
@@ -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",
|
||||
|
||||
@@ -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<McpAppViewSummary[]>(`/issues/${issueId}/mcp-app-views`, { cache: "no-store" }),
|
||||
detail: (issueId: string, viewId: string, signal?: AbortSignal) =>
|
||||
api.get<McpAppViewDetail>(`/issues/${issueId}/mcp-app-views/${viewId}`, { cache: "no-store", signal }),
|
||||
callTool: (issueId: string, viewId: string, name: string, args: Record<string, unknown>) =>
|
||||
api.post<McpAppCallToolResult>(`/issues/${issueId}/mcp-app-views/${viewId}/tool-calls`, { name, arguments: args }),
|
||||
};
|
||||
@@ -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 (
|
||||
<TaskChatRequestHistoryContext.Provider value={issueId ?? "unknown"}>
|
||||
<McpAppIssueProvider issueId={issueId}>
|
||||
<TaskChatExpansionState.Provider value={expansionState.current}>
|
||||
<TaskChatScrollReady.Provider value={(historyRevealed || !historyPending || historyWaitExpired) && !scrollTargetPending}>
|
||||
<TaskChatPresentationProvider
|
||||
@@ -3534,6 +3537,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
/>
|
||||
) : (
|
||||
<TaskChatShimmerScope items={tailItems}>
|
||||
<McpAppTurnViews runId={tailRunId} refreshKey={mcpAppRunRefreshKey(tailItems, tailStatus)} />
|
||||
<TaskChatLiveTail
|
||||
items={tailItems}
|
||||
emptyMessage={
|
||||
@@ -3707,6 +3711,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
|
||||
</TaskChatPresentationProvider>
|
||||
</TaskChatScrollReady.Provider>
|
||||
</TaskChatExpansionState.Provider>
|
||||
</McpAppIssueProvider>
|
||||
</TaskChatRequestHistoryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -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(
|
||||
<McpAppFrame
|
||||
title="Circleback: Display meetings"
|
||||
viewId="view-1"
|
||||
toolName="DisplayMeetings"
|
||||
resource={{ uri: "ui://circleback/meetings", html: "<p>cards</p>", 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("<p>cards</p>");
|
||||
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(<McpAppFrame {...props("<p>cards</p>")} />));
|
||||
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(<McpAppFrame {...props("<p>cards</p>")} />));
|
||||
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(<McpAppFrame {...props("<p>new cards</p>")} />));
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<string, string> {
|
||||
if (typeof document === "undefined") return {};
|
||||
const computed = getComputedStyle(document.documentElement);
|
||||
const variables: Record<string, string> = {};
|
||||
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<string, unknown>;
|
||||
toolResult: McpAppCallToolResult;
|
||||
callTool: (name: string, args: Record<string, unknown>) => Promise<McpAppCallToolResult>;
|
||||
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<HTMLIFrameElement>(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 (
|
||||
<iframe
|
||||
key={frameKey}
|
||||
ref={iframeRef}
|
||||
title={title}
|
||||
srcDoc={srcDoc}
|
||||
// Never add allow-same-origin: the opaque origin is the boundary between
|
||||
// the provider's view and Paperclip's session. No popups either: links
|
||||
// go through `ui/open-link`, which the host opens with noopener.
|
||||
sandbox="allow-scripts"
|
||||
referrerPolicy="no-referrer"
|
||||
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; fullscreen 'none'"
|
||||
data-testid="mcp-app-frame"
|
||||
style={{ height }}
|
||||
className={cn("block w-full border-0 bg-transparent", className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// @vitest-environment jsdom
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act, type ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
|
||||
const list = vi.fn<(issueId: string) => Promise<McpAppViewSummary[]>>();
|
||||
vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: (issueId: string) => list(issueId) } }));
|
||||
|
||||
const { McpAppIssueProvider, useMcpAppViewsForRun } = await import("./McpAppIssueContext");
|
||||
|
||||
function view(id: string, runId: string): McpAppViewSummary {
|
||||
return {
|
||||
id, issueId: "issue-1", runId, connectionId: "conn-1", applicationName: "Circleback",
|
||||
toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings",
|
||||
resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function wrapper(client: QueryClient) {
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={client}>
|
||||
<McpAppIssueProvider issueId="issue-1">{children}</McpAppIssueProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function renderHook<P, R>(hook: (props: P) => R, options: { wrapper: (props: { children: ReactNode }) => ReactNode; initialProps?: P }) {
|
||||
const result = { current: undefined as unknown as R };
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
const Wrapper = options.wrapper;
|
||||
function Probe({ props }: { props: P }) {
|
||||
result.current = hook(props);
|
||||
return null;
|
||||
}
|
||||
const render = (props: P) => act(() => root.render(<Wrapper><Probe props={props} /></Wrapper>));
|
||||
await render(options.initialProps as P);
|
||||
return { result, rerender: (props: P) => render(props), unmount: () => act(() => root.unmount()) };
|
||||
}
|
||||
|
||||
async function waitFor(check: () => void, timeoutMs = 2000) {
|
||||
const started = Date.now();
|
||||
for (;;) {
|
||||
try {
|
||||
check();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (Date.now() - started > timeoutMs) throw error;
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => list.mockReset());
|
||||
|
||||
describe("useMcpAppViewsForRun", () => {
|
||||
it("refreshes the task's list once when a live run completes another MCP tool call", async () => {
|
||||
list.mockResolvedValueOnce([]).mockResolvedValueOnce([view("v1", "run-1")]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const { result, rerender } = await renderHook(
|
||||
({ refreshKey }: { refreshKey: string }) => useMcpAppViewsForRun("run-1", { refreshKey }),
|
||||
{ wrapper: wrapper(client), initialProps: { refreshKey: "0:running" } },
|
||||
);
|
||||
await waitFor(() => expect(list).toHaveBeenCalledTimes(1));
|
||||
expect(result.current.views).toEqual([]);
|
||||
await rerender({ refreshKey: "1:running" });
|
||||
await waitFor(() => expect(list).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"]));
|
||||
await rerender({ refreshKey: "1:running" });
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("refreshes once for a settled reply newer than the loaded list", async () => {
|
||||
list.mockResolvedValueOnce([]).mockResolvedValue([view("v1", "run-1")]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const { result } = await renderHook(
|
||||
() => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() + 60_000 }),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"]));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not refresh for a reply older than the loaded list", async () => {
|
||||
list.mockResolvedValue([view("v1", "run-1")]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const { result } = await renderHook(
|
||||
() => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() - 60_000 }),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
await waitFor(() => expect(result.current.views).toHaveLength(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(list).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { createContext, useContext, useEffect, useRef, type ReactNode } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
import { mcpAppsApi } from "@/api/mcpApps";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { mcpAppViewIndexFor } from "./mcp-app-matching";
|
||||
|
||||
/** The task whose chat is showing, so a run's replies can find their MCP Apps views. */
|
||||
const McpAppIssueContext = createContext<string | null>(null);
|
||||
|
||||
export function McpAppIssueProvider({ issueId, children }: { issueId: string | null | undefined; children: ReactNode }) {
|
||||
return <McpAppIssueContext.Provider value={issueId ?? null}>{children}</McpAppIssueContext.Provider>;
|
||||
}
|
||||
|
||||
export function useMcpAppIssueId(): string | null {
|
||||
return useContext(McpAppIssueContext);
|
||||
}
|
||||
|
||||
const NO_VIEWS: McpAppViewSummary[] = [];
|
||||
|
||||
export interface McpAppViewsFreshness {
|
||||
/**
|
||||
* Changes when the run may have recorded a new view: for a live run, the
|
||||
* count of its completed MCP tool calls and its status. A change refreshes
|
||||
* the task's list once.
|
||||
*/
|
||||
refreshKey?: string;
|
||||
/** The reply's time (ms). A list loaded before it may miss the run's views, so it is refreshed once. */
|
||||
notBeforeMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The views a run recorded. A task's views load in one request, shared by
|
||||
* every reply of the task, and the list is indexed once by run.
|
||||
*/
|
||||
export function useMcpAppViewsForRun(runId: string | null | undefined, freshness: McpAppViewsFreshness = {}): {
|
||||
issueId: string | null;
|
||||
views: McpAppViewSummary[];
|
||||
} {
|
||||
const issueId = useMcpAppIssueId();
|
||||
const queryClient = useQueryClient();
|
||||
const enabled = Boolean(issueId && runId);
|
||||
const queryKey = queryKeys.mcpApps.views(issueId ?? "");
|
||||
const { data, dataUpdatedAt, isFetching } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => mcpAppsApi.list(issueId!),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
// A run's new tool call can record a view after the list loaded.
|
||||
const lastRefreshKey = useRef(freshness.refreshKey);
|
||||
useEffect(() => {
|
||||
if (!enabled || freshness.refreshKey === undefined || freshness.refreshKey === lastRefreshKey.current) return;
|
||||
lastRefreshKey.current = freshness.refreshKey;
|
||||
void queryClient.invalidateQueries({ queryKey, exact: true });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- queryKey is derived from issueId
|
||||
}, [enabled, freshness.refreshKey, issueId, queryClient]);
|
||||
|
||||
// A settled reply newer than the loaded list: look once more.
|
||||
const refreshedForReply = useRef(false);
|
||||
const notBeforeMs = freshness.notBeforeMs;
|
||||
useEffect(() => {
|
||||
if (!enabled || refreshedForReply.current || !data || isFetching) return;
|
||||
if (notBeforeMs === undefined || !Number.isFinite(notBeforeMs) || dataUpdatedAt >= notBeforeMs) return;
|
||||
refreshedForReply.current = true;
|
||||
void queryClient.invalidateQueries({ queryKey, exact: true });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- queryKey is derived from issueId
|
||||
}, [enabled, data, dataUpdatedAt, isFetching, notBeforeMs, issueId, queryClient]);
|
||||
|
||||
const views = enabled && data ? mcpAppViewIndexFor(data).forRun(runId!) : NO_VIEWS;
|
||||
return { issueId, views };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment jsdom
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
|
||||
const detail = vi.fn(() => new Promise(() => undefined));
|
||||
vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: vi.fn(), detail: (...args: unknown[]) => detail(...(args as [])), callTool: vi.fn() } }));
|
||||
|
||||
const { McpAppIssueProvider } = await import("./McpAppIssueContext");
|
||||
const { McpAppTurnViews } = await import("./McpAppTurnViews");
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function views(count: number): McpAppViewSummary[] {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
id: `00000000-0000-4000-8000-00000000000${index}`, issueId: "issue-1", runId: "run-1", connectionId: "conn-1",
|
||||
applicationName: "Circleback", toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings",
|
||||
resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
}));
|
||||
}
|
||||
|
||||
let observers: Array<{ callback: IntersectionObserverCallback; targets: Element[] }> = [];
|
||||
class FakeIntersectionObserver {
|
||||
targets: Element[] = [];
|
||||
constructor(public callback: IntersectionObserverCallback) { observers.push(this); }
|
||||
observe(target: Element) { this.targets.push(target); }
|
||||
disconnect() { this.targets = []; }
|
||||
unobserve() {}
|
||||
takeRecords() { return []; }
|
||||
}
|
||||
|
||||
async function render(count: number) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(queryKeys.mcpApps.views("issue-1"), views(count));
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<McpAppIssueProvider issueId="issue-1"><McpAppTurnViews runId="run-1" /></McpAppIssueProvider>
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
return { container, root };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
observers = [];
|
||||
detail.mockClear();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("McpAppTurnViews", () => {
|
||||
it("loads a view's document only when it nears the viewport", async () => {
|
||||
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
|
||||
vi.stubGlobal("navigation", { addEventListener: () => undefined });
|
||||
const { container, root } = await render(2);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(2);
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
const first = observers[0]!;
|
||||
await act(async () => first.callback([{ isIntersecting: true, target: first.targets[0]! } as IntersectionObserverEntry], first as unknown as IntersectionObserver));
|
||||
expect(detail).toHaveBeenCalledTimes(1);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(1);
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("shows five views per run and the rest on request", async () => {
|
||||
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
|
||||
const { container, root } = await render(7);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5);
|
||||
const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more")!;
|
||||
expect(more).toBeTruthy();
|
||||
await act(async () => more.click());
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7);
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useMcpAppIssueId, useMcpAppViewsForRun, type McpAppViewsFreshness } from "./McpAppIssueContext";
|
||||
import { McpAppView } from "./McpAppView";
|
||||
|
||||
/** "DisplayMeetings" → "Display meetings". */
|
||||
export function mcpAppToolDisplayName(toolName: string): string {
|
||||
const words = toolName.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim().toLowerCase();
|
||||
return words ? words[0]!.toUpperCase() + words.slice(1) : toolName;
|
||||
}
|
||||
|
||||
function McpAppRunView({ issueId, view }: { issueId: string; view: McpAppViewSummary }) {
|
||||
const displayName = mcpAppToolDisplayName(view.upstreamToolName);
|
||||
return (
|
||||
<section data-testid="mcp-app-turn-view" aria-label={`${view.applicationName}: ${displayName}`} className="flex min-w-0 flex-col gap-2">
|
||||
<div className="flex min-w-0 items-baseline gap-2 text-xs">
|
||||
<span className="text-muted-foreground">Widget from {view.applicationName}</span>
|
||||
<span className="truncate font-medium text-foreground">{displayName}</span>
|
||||
</div>
|
||||
<NearViewport placeholderLabel={`${view.applicationName}: ${displayName}`}>
|
||||
<McpAppView issueId={issueId} view={view} displayName={displayName} />
|
||||
</NearViewport>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Views start loading this far before they scroll into view. */
|
||||
const NEAR_VIEWPORT_MARGIN = "600px";
|
||||
/** Views shown per run before "Show N more". */
|
||||
export const MCP_APP_VIEWS_PER_RUN = 5;
|
||||
|
||||
/**
|
||||
* Mounts its children (and so fetches the view document, up to 4 MB, and starts
|
||||
* its iframe) only once the placeholder nears the viewport. A long chat with
|
||||
* many recorded views pays only for the ones the reader reaches.
|
||||
*/
|
||||
function NearViewport({ children, placeholderLabel }: { children: ReactNode; placeholderLabel: string }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");
|
||||
useEffect(() => {
|
||||
if (near || !ref.current) return;
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) setNear(true);
|
||||
}, { rootMargin: NEAR_VIEWPORT_MARGIN });
|
||||
observer.observe(ref.current);
|
||||
return () => observer.disconnect();
|
||||
}, [near]);
|
||||
if (near) return <>{children}</>;
|
||||
return <div ref={ref} role="status" aria-label={`${placeholderLabel} (not loaded yet)`} data-testid="mcp-app-view-placeholder" className="h-24 rounded-lg border border-border bg-muted/30" />;
|
||||
}
|
||||
|
||||
/**
|
||||
* A run's MCP Apps views, shown with the agent's reply rather than inside the
|
||||
* folded tool history, as other MCP Apps hosts do. Keyed by run, so settled
|
||||
* history needs no transcript to show them.
|
||||
*/
|
||||
export function McpAppTurnViews({ runId, ...freshness }: { runId: string | null | undefined } & McpAppViewsFreshness) {
|
||||
// Outside a task chat (or before a run exists) there is nothing to load.
|
||||
const issueId = useMcpAppIssueId();
|
||||
return issueId && runId ? <RunViews runId={runId} {...freshness} /> : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh key for a live run: its completed MCP tool calls and its status.
|
||||
* Tool rows may be nested in activity phases.
|
||||
*/
|
||||
export function mcpAppRunRefreshKey(items: readonly unknown[], status?: string | null): string {
|
||||
let completed = 0;
|
||||
const visit = (list: readonly unknown[]) => {
|
||||
for (const entry of list) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const item = entry as { kind?: string; status?: string; rawName?: string; name?: string; items?: unknown };
|
||||
if (item.kind === "tool" && item.status === "completed" && /mcp/i.test(item.rawName ?? item.name ?? "")) completed += 1;
|
||||
else if (Array.isArray(item.items)) visit(item.items);
|
||||
}
|
||||
};
|
||||
visit(items);
|
||||
return `${completed}:${status ?? ""}`;
|
||||
}
|
||||
|
||||
function RunViews({ runId, ...freshness }: { runId: string } & McpAppViewsFreshness) {
|
||||
const { issueId, views } = useMcpAppViewsForRun(runId, freshness);
|
||||
const [showAll, setShowAll] = useState(false);
|
||||
if (!issueId || views.length === 0) return null;
|
||||
const shown = showAll ? views : views.slice(0, MCP_APP_VIEWS_PER_RUN);
|
||||
const hidden = views.length - shown.length;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-6 py-4" data-testid="mcp-app-turn-views">
|
||||
{shown.map((view) => <McpAppRunView key={view.id} issueId={issueId} view={view} />)}
|
||||
{hidden > 0 ? (
|
||||
<Button type="button" variant="ghost" size="sm" className="self-start" onClick={() => setShowAll(true)}>
|
||||
Show {hidden} more
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { McpAppViewDetail } from "@paperclipai/shared";
|
||||
import { McpAppViewContent } from "./McpAppView";
|
||||
import { mcpAppNavigationGuardSupported } from "./mcp-app-host";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const detail: McpAppViewDetail = {
|
||||
id: "view-1", issueId: "issue-1", runId: "run-1", connectionId: "conn-1", applicationName: "Circleback",
|
||||
toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", resourceUri: "ui://circleback/meetings",
|
||||
toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
toolResult: { content: [] },
|
||||
resource: { uri: "ui://circleback/meetings", html: "<p>cards</p>", csp: {}, permissions: {}, prefersBorder: true },
|
||||
};
|
||||
|
||||
async function render() {
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(
|
||||
<McpAppViewContent detail={detail} status="ready" callTool={async () => ({ content: [] })} displayName="Display meetings" />,
|
||||
));
|
||||
return { container, root };
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("McpAppViewContent", () => {
|
||||
it("does not mount a view where the navigation guard cannot work", async () => {
|
||||
expect(mcpAppNavigationGuardSupported()).toBe(false);
|
||||
const { container, root } = await render();
|
||||
expect(container.querySelector("iframe")).toBeNull();
|
||||
expect(container.textContent).toContain("This browser can't show this app's widget safely.");
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("mounts the view where the Navigation API is available", async () => {
|
||||
vi.stubGlobal("navigation", { addEventListener: () => undefined });
|
||||
const { container, root } = await render();
|
||||
expect(container.querySelector("iframe")).not.toBeNull();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useCallback } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { McpAppCallToolResult, McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared";
|
||||
import { mcpAppsApi } from "@/api/mcpApps";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { McpAppFrame } from "./McpAppFrame";
|
||||
import { mcpAppNavigationGuardSupported } from "./mcp-app-host";
|
||||
|
||||
const UNSUPPORTED_BROWSER_MESSAGE = "This browser can't show this app's widget safely. The tool result is still in the activity.";
|
||||
|
||||
export interface McpAppViewContentProps {
|
||||
detail: McpAppViewDetail | undefined;
|
||||
status: "loading" | "error" | "ready";
|
||||
errorMessage?: string | null;
|
||||
callTool: (name: string, args: Record<string, unknown>) => Promise<McpAppCallToolResult>;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
/** Presentational shell, shared by the live view and its stories. */
|
||||
export function McpAppViewContent({ detail, status, errorMessage, callTool, displayName }: McpAppViewContentProps) {
|
||||
const unsupported = !mcpAppNavigationGuardSupported();
|
||||
if (status === "error" || unsupported) {
|
||||
return (
|
||||
<div role="status" data-testid="mcp-app-view-error" className="ml-1.5 mt-0.5 border-l-2 border-border py-1 pl-2.5 text-(length:--text-micro) text-muted-foreground">
|
||||
{unsupported ? UNSUPPORTED_BROWSER_MESSAGE : errorMessage ?? "This app's view could not be shown."}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div
|
||||
data-testid="mcp-app-view"
|
||||
className={cn(
|
||||
"min-w-0 max-w-full overflow-hidden",
|
||||
detail?.resource.prefersBorder !== false && "rounded-lg border border-border bg-card p-3",
|
||||
)}
|
||||
>
|
||||
{status === "loading" || !detail ? (
|
||||
<div role="status" aria-label={`Loading ${detail?.applicationName ?? "app"} view`} className="h-24 animate-pulse bg-muted/40" />
|
||||
) : (
|
||||
<McpAppFrame
|
||||
title={`${detail.applicationName}: ${displayName}`}
|
||||
viewId={detail.id}
|
||||
toolName={detail.upstreamToolName}
|
||||
resource={detail.resource}
|
||||
toolInput={detail.toolInput}
|
||||
toolResult={detail.toolResult}
|
||||
callTool={callTool}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function viewErrorMessage(error: unknown, applicationName: string): string {
|
||||
if (error instanceof ApiError && error.status === 404) return `This ${applicationName} view is no longer available.`;
|
||||
return `${applicationName} could not show this view. The tool result is still in the row above.`;
|
||||
}
|
||||
|
||||
/** Loads a recorded view and renders it under its tool row. */
|
||||
export function McpAppView({ issueId, view, displayName }: { issueId: string; view: McpAppViewSummary; displayName: string }) {
|
||||
const query = useQuery({
|
||||
queryKey: queryKeys.mcpApps.detail(issueId, view.id),
|
||||
queryFn: ({ signal }) => mcpAppsApi.detail(issueId, view.id, signal),
|
||||
// No document download where the view cannot be shown safely.
|
||||
enabled: mcpAppNavigationGuardSupported(),
|
||||
staleTime: 5 * 60_000,
|
||||
retry: 1,
|
||||
});
|
||||
const callTool = useCallback(
|
||||
(name: string, args: Record<string, unknown>) => mcpAppsApi.callTool(issueId, view.id, name, args),
|
||||
[issueId, view.id],
|
||||
);
|
||||
return (
|
||||
<McpAppViewContent
|
||||
detail={query.data}
|
||||
status={query.data ? "ready" : query.error ? "error" : "loading"}
|
||||
errorMessage={!query.data && query.error ? viewErrorMessage(query.error, view.applicationName) : null}
|
||||
callTool={callTool}
|
||||
displayName={displayName}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createMcpAppHost, MCP_APP_NAVIGATION_GUARD, mcpAppDocument, safeExternalUrl, type McpAppHostContext } from "./mcp-app-host";
|
||||
|
||||
const hostContext: McpAppHostContext = {
|
||||
theme: "dark",
|
||||
displayMode: "inline",
|
||||
availableDisplayModes: ["inline"],
|
||||
containerDimensions: { maxHeight: 640 },
|
||||
locale: "en-US",
|
||||
timeZone: "UTC",
|
||||
platform: "web",
|
||||
toolInfo: { id: "view-1", tool: { name: "DisplayMeetings", inputSchema: { type: "object" } } },
|
||||
};
|
||||
|
||||
function setup(overrides: Partial<Parameters<typeof createMcpAppHost>[0]> = {}) {
|
||||
const posted: any[] = [];
|
||||
const options = {
|
||||
post: (message: unknown) => posted.push(message),
|
||||
hostContext: () => hostContext,
|
||||
toolInput: { meetingIds: ["m1"] },
|
||||
toolResult: { content: [{ type: "text", text: "ok" }], structuredContent: { meetings: [{ id: "m1" }] } },
|
||||
callTool: vi.fn(async () => ({ content: [{ type: "text", text: "called" }] })),
|
||||
openLink: vi.fn(),
|
||||
onSizeChanged: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
return { host: createMcpAppHost(options), posted, options };
|
||||
}
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
describe("createMcpAppHost", () => {
|
||||
it("answers ui/initialize with the host context and sends nothing before initialized", async () => {
|
||||
const { host, posted } = setup();
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: { protocolVersion: "2026-01-26" } });
|
||||
await flush();
|
||||
expect(posted).toHaveLength(1);
|
||||
expect(posted[0]).toMatchObject({ id: 1, result: { protocolVersion: "2026-01-26", hostInfo: { name: "Paperclip" }, hostContext: { theme: "dark" } } });
|
||||
host.hostContextChanged({ theme: "light" });
|
||||
expect(posted).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("sends tool-input then tool-result once the view is initialized", () => {
|
||||
const { host, posted } = setup();
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
expect(posted.map((message) => message.method)).toEqual(["ui/notifications/tool-input", "ui/notifications/tool-result"]);
|
||||
expect(posted[0].params).toEqual({ arguments: { meetingIds: ["m1"] } });
|
||||
expect(posted[1].params.structuredContent).toEqual({ meetings: [{ id: "m1" }] });
|
||||
});
|
||||
|
||||
it("proxies tools/call and reports failures as JSON-RPC errors", async () => {
|
||||
const callTool = vi.fn()
|
||||
.mockResolvedValueOnce({ content: [{ type: "text", text: "called" }] })
|
||||
.mockRejectedValueOnce(new Error("denied"));
|
||||
const { host, posted } = setup({ callTool });
|
||||
host.receive({ jsonrpc: "2.0", id: "init", method: "ui/initialize", params: {} });
|
||||
host.receive({ jsonrpc: "2.0", id: "a", method: "tools/call", params: { name: "ReadMeetings", arguments: { ids: ["m1"] } } });
|
||||
host.receive({ jsonrpc: "2.0", id: "b", method: "tools/call", params: { name: "DeleteTag" } });
|
||||
await flush();
|
||||
expect(callTool).toHaveBeenCalledWith("ReadMeetings", { ids: ["m1"] });
|
||||
expect(posted.find((message) => message.id === "a")).toMatchObject({ result: { content: [{ text: "called" }] } });
|
||||
expect(posted.find((message) => message.id === "b")).toMatchObject({ error: { code: -32000, message: "denied" } });
|
||||
});
|
||||
|
||||
it("opens only http(s) links and rejects unknown methods", async () => {
|
||||
const { host, posted, options } = setup();
|
||||
host.receive({ jsonrpc: "2.0", id: 0, method: "ui/initialize", params: {} });
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/open-link", params: { url: "https://app.circleback.ai/meetings/m1" } });
|
||||
host.receive({ jsonrpc: "2.0", id: 2, method: "ui/open-link", params: { url: "javascript:alert(1)" } });
|
||||
host.receive({ jsonrpc: "2.0", id: 3, method: "ui/message", params: { role: "user", content: { type: "text", text: "hi" } } });
|
||||
await flush();
|
||||
expect(options.openLink).toHaveBeenCalledTimes(1);
|
||||
expect(options.openLink).toHaveBeenCalledWith("https://app.circleback.ai/meetings/m1");
|
||||
expect(posted.find((message) => message.id === 2)).toMatchObject({ error: { code: -32000 } });
|
||||
expect(posted.find((message) => message.id === 3)).toMatchObject({ error: { code: -32601 } });
|
||||
});
|
||||
|
||||
it("refuses tool calls and links before the view's ui/initialize", async () => {
|
||||
const callTool = vi.fn(async () => ({ content: [] }));
|
||||
const { host, posted, options } = setup({ callTool });
|
||||
host.receive({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "DeleteTag", arguments: {} } });
|
||||
host.receive({ jsonrpc: "2.0", id: 2, method: "ui/open-link", params: { url: "https://evil.example" } });
|
||||
host.receive({ jsonrpc: "2.0", id: 3, method: "ping" });
|
||||
await flush();
|
||||
expect(callTool).not.toHaveBeenCalled();
|
||||
expect(options.openLink).not.toHaveBeenCalled();
|
||||
expect(posted.find((message) => message.id === 1)).toMatchObject({ error: { code: -32000 } });
|
||||
expect(posted.find((message) => message.id === 2)).toMatchObject({ error: { code: -32000 } });
|
||||
expect(posted.find((message) => message.id === 3)).toMatchObject({ result: {} });
|
||||
});
|
||||
|
||||
it("reports size changes, ignores malformed messages and stops after teardown", () => {
|
||||
const { host, posted, options } = setup();
|
||||
host.receive({ method: "ui/notifications/size-changed", params: { height: 200 } });
|
||||
host.receive("not json-rpc");
|
||||
expect(options.onSizeChanged).not.toHaveBeenCalled();
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: 200 } });
|
||||
expect(options.onSizeChanged).toHaveBeenCalledWith({ height: 200, width: undefined });
|
||||
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
|
||||
host.teardown();
|
||||
expect(posted.at(-1)).toMatchObject({ method: "ui/resource-teardown" });
|
||||
const count = posted.length;
|
||||
host.receive({ jsonrpc: "2.0", id: 9, method: "ping" });
|
||||
expect(posted).toHaveLength(count);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mcpAppDocument", () => {
|
||||
it("installs the CSP before the view's markup and keeps one doctype", () => {
|
||||
const doc = mcpAppDocument("<!DOCTYPE html><html><head><script>1</script></head></html>", { connectDomains: ["https://api.circleback.ai"] });
|
||||
expect(doc.startsWith("<!doctype html><meta http-equiv=\"Content-Security-Policy\"")).toBe(true);
|
||||
expect(doc.indexOf("Content-Security-Policy")).toBeLessThan(doc.indexOf("<script>"));
|
||||
expect(doc.match(/<!doctype/gi)).toHaveLength(1);
|
||||
expect(doc).toContain("connect-src https://api.circleback.ai");
|
||||
});
|
||||
|
||||
it("runs the navigation guard before any of the view's scripts", () => {
|
||||
const doc = mcpAppDocument("<html><head><script>window.viewStarted = true</script></head></html>", {});
|
||||
expect(doc.indexOf(MCP_APP_NAVIGATION_GUARD)).toBeGreaterThan(doc.indexOf("Content-Security-Policy"));
|
||||
expect(doc.indexOf(MCP_APP_NAVIGATION_GUARD)).toBeLessThan(doc.indexOf("window.viewStarted"));
|
||||
});
|
||||
|
||||
it("routes links of any target and window.open through ui/open-link", () => {
|
||||
const posted: unknown[] = [];
|
||||
const parentWindow = { postMessage: (message: unknown) => posted.push(message) };
|
||||
const anchors: Array<{ href: string; attrs: Record<string, string> }> = [
|
||||
{ href: "https://app.circleback.ai/meetings/m1", attrs: { href: "https://app.circleback.ai/meetings/m1", target: "_blank" } },
|
||||
{ href: "https://app.circleback.ai/meetings/m2", attrs: { href: "https://app.circleback.ai/meetings/m2" } },
|
||||
{ href: "about:srcdoc#top", attrs: { href: "#top" } },
|
||||
{ href: "javascript:alert(1)", attrs: { href: "javascript:alert(1)" } },
|
||||
];
|
||||
let clickHandler: ((event: unknown) => void) | null = null;
|
||||
const fakeWindow: Record<string, unknown> = { open: () => "real window" };
|
||||
const fakeDocument = {
|
||||
baseURI: "about:srcdoc",
|
||||
addEventListener: (type: string, handler: (event: unknown) => void) => { if (type === "click") clickHandler = handler; },
|
||||
};
|
||||
new Function("window", "document", "parent", MCP_APP_NAVIGATION_GUARD)(fakeWindow, fakeDocument, parentWindow);
|
||||
const prevented: boolean[] = [];
|
||||
for (const anchor of anchors) {
|
||||
let defaultPrevented = false;
|
||||
clickHandler!({
|
||||
defaultPrevented: false,
|
||||
preventDefault: () => { defaultPrevented = true; },
|
||||
target: { closest: () => ({ href: anchor.href, getAttribute: (name: string) => anchor.attrs[name] ?? null }) },
|
||||
});
|
||||
prevented.push(defaultPrevented);
|
||||
}
|
||||
expect((fakeWindow.open as (url: string) => unknown)("https://circleback.ai/meetings/m3")).toBeNull();
|
||||
expect(prevented).toEqual([true, true, false, true]);
|
||||
expect(posted.map((message) => (message as { params: { url: string } }).params.url)).toEqual([
|
||||
"https://app.circleback.ai/meetings/m1",
|
||||
"https://app.circleback.ai/meetings/m2",
|
||||
"https://circleback.ai/meetings/m3",
|
||||
]);
|
||||
});
|
||||
|
||||
it("allows only http(s) external urls", () => {
|
||||
expect(safeExternalUrl("https://circleback.ai")).toBe("https://circleback.ai/");
|
||||
expect(safeExternalUrl("data:text/html,x")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
import {
|
||||
buildMcpAppCsp,
|
||||
MCP_APPS_PROTOCOL_VERSION,
|
||||
type McpAppCallToolResult,
|
||||
type McpAppResourceCsp,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
/**
|
||||
* Host side of the MCP Apps postMessage protocol (spec 2026-01-26). Pure and
|
||||
* transport-agnostic: the iframe component feeds it messages from the view and
|
||||
* it answers through `post`.
|
||||
*/
|
||||
|
||||
export interface McpAppHostContext {
|
||||
theme: "light" | "dark";
|
||||
displayMode: "inline";
|
||||
availableDisplayModes: ["inline"];
|
||||
containerDimensions: { maxHeight: number; width?: number };
|
||||
locale: string;
|
||||
timeZone: string;
|
||||
platform: "web";
|
||||
userAgent?: string;
|
||||
toolInfo: { id: string; tool: { name: string; inputSchema: Record<string, unknown> } };
|
||||
styles?: { variables: Record<string, string> };
|
||||
}
|
||||
|
||||
export interface McpAppHostOptions {
|
||||
post: (message: unknown) => void;
|
||||
hostContext: () => McpAppHostContext;
|
||||
toolInput: Record<string, unknown>;
|
||||
toolResult: McpAppCallToolResult;
|
||||
callTool: (name: string, args: Record<string, unknown>) => Promise<McpAppCallToolResult>;
|
||||
openLink: (url: string) => void;
|
||||
onSizeChanged: (size: { width?: number; height?: number }) => void;
|
||||
onLog?: (entry: unknown) => void;
|
||||
}
|
||||
|
||||
type JsonRpcId = string | number;
|
||||
interface JsonRpcMessage {
|
||||
jsonrpc: "2.0";
|
||||
id?: JsonRpcId;
|
||||
method?: string;
|
||||
params?: unknown;
|
||||
result?: unknown;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
const METHOD_NOT_FOUND = -32601;
|
||||
const INVALID_PARAMS = -32602;
|
||||
const SERVER_ERROR = -32000;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
}
|
||||
|
||||
export function isJsonRpcMessage(value: unknown): value is JsonRpcMessage {
|
||||
const message = record(value);
|
||||
return message?.jsonrpc === "2.0" && (typeof message.method === "string" || "id" in message);
|
||||
}
|
||||
|
||||
/** Only http(s) links leave the sandbox, and always into a new browsing context. */
|
||||
export function safeExternalUrl(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function createMcpAppHost(options: McpAppHostOptions) {
|
||||
let initialized = false;
|
||||
// Set once this document has sent `ui/initialize`. Requests that act on the
|
||||
// user's behalf are refused before it.
|
||||
let handshakeStarted = false;
|
||||
let toolDataSent = false;
|
||||
let nextRequestId = 1;
|
||||
let disposed = false;
|
||||
|
||||
const respond = (id: JsonRpcId, result: unknown) => options.post({ jsonrpc: "2.0", id, result });
|
||||
const fail = (id: JsonRpcId, code: number, message: string) => options.post({ jsonrpc: "2.0", id, error: { code, message } });
|
||||
const notify = (method: string, params: unknown) => {
|
||||
// The host must not send anything before the view reports it is initialized.
|
||||
if (initialized && !disposed) options.post({ jsonrpc: "2.0", method, params });
|
||||
};
|
||||
|
||||
function sendToolData() {
|
||||
if (toolDataSent) return;
|
||||
toolDataSent = true;
|
||||
notify("ui/notifications/tool-input", { arguments: options.toolInput });
|
||||
notify("ui/notifications/tool-result", options.toolResult);
|
||||
}
|
||||
|
||||
async function handleRequest(message: JsonRpcMessage & { id: JsonRpcId; method: string }) {
|
||||
const params = record(message.params) ?? {};
|
||||
if (!handshakeStarted && message.method !== "ui/initialize" && message.method !== "ping") {
|
||||
fail(message.id, SERVER_ERROR, "The view must call ui/initialize first");
|
||||
return;
|
||||
}
|
||||
switch (message.method) {
|
||||
case "ui/initialize":
|
||||
handshakeStarted = true;
|
||||
respond(message.id, {
|
||||
protocolVersion: MCP_APPS_PROTOCOL_VERSION,
|
||||
hostInfo: { name: "Paperclip", version: "1.0.0" },
|
||||
hostCapabilities: {
|
||||
openLinks: {},
|
||||
serverTools: {},
|
||||
logging: {},
|
||||
sandbox: { permissions: {}, csp: {} },
|
||||
},
|
||||
hostContext: options.hostContext(),
|
||||
});
|
||||
return;
|
||||
case "ping":
|
||||
respond(message.id, {});
|
||||
return;
|
||||
case "tools/call": {
|
||||
const name = typeof params.name === "string" ? params.name : "";
|
||||
const args = record(params.arguments) ?? {};
|
||||
if (!name) {
|
||||
fail(message.id, INVALID_PARAMS, "params.name is required");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
respond(message.id, await options.callTool(name, args));
|
||||
} catch (error) {
|
||||
fail(message.id, SERVER_ERROR, error instanceof Error ? error.message : "Tool call failed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "ui/open-link": {
|
||||
const url = safeExternalUrl(params.url);
|
||||
if (!url) {
|
||||
fail(message.id, SERVER_ERROR, "Only http and https links can be opened");
|
||||
return;
|
||||
}
|
||||
options.openLink(url);
|
||||
respond(message.id, {});
|
||||
return;
|
||||
}
|
||||
case "ui/request-display-mode":
|
||||
respond(message.id, { mode: "inline" });
|
||||
return;
|
||||
case "ui/update-model-context":
|
||||
// Accepted; Paperclip does not yet feed view context back to the agent.
|
||||
respond(message.id, {});
|
||||
return;
|
||||
default:
|
||||
fail(message.id, METHOD_NOT_FOUND, `${message.method} is not supported by Paperclip`);
|
||||
}
|
||||
}
|
||||
|
||||
function handleNotification(message: JsonRpcMessage & { method: string }) {
|
||||
const params = record(message.params) ?? {};
|
||||
switch (message.method) {
|
||||
case "ui/notifications/initialized":
|
||||
initialized = true;
|
||||
sendToolData();
|
||||
return;
|
||||
case "ui/notifications/size-changed":
|
||||
options.onSizeChanged({
|
||||
width: typeof params.width === "number" ? params.width : undefined,
|
||||
height: typeof params.height === "number" ? params.height : undefined,
|
||||
});
|
||||
return;
|
||||
case "notifications/message":
|
||||
options.onLog?.(params);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
/** Feed one message received from the view. Malformed messages are ignored. */
|
||||
receive(data: unknown) {
|
||||
if (disposed || !isJsonRpcMessage(data)) return;
|
||||
if (typeof data.method === "string" && data.id !== undefined) {
|
||||
void handleRequest(data as JsonRpcMessage & { id: JsonRpcId; method: string });
|
||||
} else if (typeof data.method === "string") {
|
||||
handleNotification(data as JsonRpcMessage & { method: string });
|
||||
}
|
||||
// Responses to host requests (teardown) need no handling.
|
||||
},
|
||||
hostContextChanged(partial: Partial<McpAppHostContext>) {
|
||||
notify("ui/notifications/host-context-changed", partial);
|
||||
},
|
||||
/** Sends `ui/resource-teardown` and stops handling messages. */
|
||||
teardown(reason = "The view was closed") {
|
||||
if (initialized && !disposed) {
|
||||
options.post({ jsonrpc: "2.0", id: `teardown-${nextRequestId++}`, method: "ui/resource-teardown", params: { reason } });
|
||||
}
|
||||
disposed = true;
|
||||
},
|
||||
get initialized() {
|
||||
return initialized;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The view document with its CSP installed before any of its markup is parsed.
|
||||
* The meta tag goes right after the doctype; the parser hoists it into the
|
||||
* implicit head, so the view's own `<html>`/`<head>` merge after it and the
|
||||
* document keeps standards mode.
|
||||
*/
|
||||
export function mcpAppDocument(html: string, csp: McpAppResourceCsp): string {
|
||||
const policy = buildMcpAppCsp(csp).replace(/"/g, """);
|
||||
const body = html.replace(/^?\s*<!doctype[^>]*>/i, "");
|
||||
return `<!doctype html><meta http-equiv="Content-Security-Policy" content="${policy}"><meta name="referrer" content="no-referrer"><script>${MCP_APP_NAVIGATION_GUARD}</script>${body}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Views render only where the navigation guard can cancel script-driven
|
||||
* navigations of the frame (location assignment, meta refresh), which needs the
|
||||
* Navigation API. The parent and the sandboxed frame run in the same engine.
|
||||
*/
|
||||
export function mcpAppNavigationGuardSupported(target: unknown = typeof window === "undefined" ? undefined : window): boolean {
|
||||
const navigation = (target as { navigation?: { addEventListener?: unknown } } | undefined)?.navigation;
|
||||
return typeof navigation?.addEventListener === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs before the view's own scripts. The view's frame must never load another
|
||||
* document: that document would inherit the frame's message channel. The
|
||||
* sandbox allows no popups, so every way out goes through the host's
|
||||
* `ui/open-link` (http and https only, opened in a new tab with noopener):
|
||||
* - cross-document navigations of the frame are cancelled (Navigation API);
|
||||
* - link clicks, whatever their target, are routed to the host;
|
||||
* - `window.open` posts to the host and returns null.
|
||||
* Same-document navigations (pushState, hashes) still work.
|
||||
*/
|
||||
export const MCP_APP_NAVIGATION_GUARD = `(function(){
|
||||
var n=0;function open(u){try{u=String(new URL(String(u),document.baseURI))}catch(_){return;}if(/^https?:/i.test(u))parent.postMessage({jsonrpc:"2.0",id:"paperclip-link-"+(++n),method:"ui/open-link",params:{url:u}},"*");}
|
||||
window.open=function(u){if(u!=null&&u!=="")open(u);return null;};
|
||||
var nav=window.navigation;
|
||||
if(nav&&nav.addEventListener)nav.addEventListener("navigate",function(e){var d=e.destination;if(!d||d.sameDocument||e.downloadRequest||!e.cancelable)return;e.preventDefault();open(d.url);});
|
||||
document.addEventListener("click",function(e){var t=e.target,a=t&&t.closest?t.closest("a[href]"):null;if(!a||e.defaultPrevented)return;if((a.getAttribute("href")||"").charAt(0)==="#")return;e.preventDefault();open(a.href);},true);
|
||||
})();`;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
import { createMcpAppViewIndex, mcpAppViewIndexFor } from "./mcp-app-matching";
|
||||
import { mcpAppToolDisplayName } from "./McpAppTurnViews";
|
||||
|
||||
function view(id: string, overrides: Partial<McpAppViewSummary> = {}): McpAppViewSummary {
|
||||
return {
|
||||
id,
|
||||
issueId: "issue-1",
|
||||
runId: "run-1",
|
||||
connectionId: "conn-1",
|
||||
applicationName: "Circleback",
|
||||
toolName: "mcp.circleback-1a2b3c4d:displaymeetings",
|
||||
upstreamToolName: "DisplayMeetings",
|
||||
resourceUri: "ui://circleback/meetings",
|
||||
toolInput: { meetingIds: ["a"] },
|
||||
createdAt: "2026-11-12T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("mcp app view index", () => {
|
||||
it("groups views by run in call order and ignores views without a run", () => {
|
||||
const index = createMcpAppViewIndex([view("a"), view("b", { runId: "run-2" }), view("c"), view("d", { runId: null })]);
|
||||
expect(index.forRun("run-1").map((v) => v.id)).toEqual(["a", "c"]);
|
||||
expect(index.forRun("run-2").map((v) => v.id)).toEqual(["b"]);
|
||||
expect(index.forRun("run-3")).toEqual([]);
|
||||
});
|
||||
|
||||
it("builds one index per loaded list and answers each reply without rescanning", () => {
|
||||
// Realistic upper bound: 200 saved views over 100 runs, 2,000 rendered replies.
|
||||
const views = Array.from({ length: 200 }, (_, index) => view(`v${index}`, { runId: `run-${index % 100}` }));
|
||||
const index = mcpAppViewIndexFor(views);
|
||||
expect(mcpAppViewIndexFor(views)).toBe(index);
|
||||
const started = performance.now();
|
||||
const counts = Array.from({ length: 2000 }, (_, reply) => index.forRun(`run-${reply % 100}`).length);
|
||||
expect(performance.now() - started).toBeLessThan(50);
|
||||
expect(counts.every((count) => count === 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("names tools for people", () => {
|
||||
expect(mcpAppToolDisplayName("DisplayMeetings")).toBe("Display meetings");
|
||||
expect(mcpAppToolDisplayName("display_calendar_events")).toBe("Display calendar events");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
|
||||
export interface McpAppViewIndex {
|
||||
/** The views a run recorded, oldest first. */
|
||||
forRun(runId: string): McpAppViewSummary[];
|
||||
}
|
||||
|
||||
const EMPTY: McpAppViewSummary[] = [];
|
||||
|
||||
/** Groups a task's views by run once; each reply then reads only its own run. */
|
||||
export function createMcpAppViewIndex(views: readonly McpAppViewSummary[]): McpAppViewIndex {
|
||||
const byRun = new Map<string, McpAppViewSummary[]>();
|
||||
for (const view of views) {
|
||||
if (!view.runId) continue;
|
||||
const list = byRun.get(view.runId);
|
||||
if (list) list.push(view);
|
||||
else byRun.set(view.runId, [view]);
|
||||
}
|
||||
return { forRun: (runId) => byRun.get(runId) ?? EMPTY };
|
||||
}
|
||||
|
||||
const indexCache = new WeakMap<readonly McpAppViewSummary[], McpAppViewIndex>();
|
||||
|
||||
/** One index per loaded view list, shared by every reply of the task. */
|
||||
export function mcpAppViewIndexFor(views: readonly McpAppViewSummary[]): McpAppViewIndex {
|
||||
let index = indexCache.get(views);
|
||||
if (!index) {
|
||||
index = createMcpAppViewIndex(views);
|
||||
indexCache.set(views, index);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { groupImageResources } from "./image-resources";
|
||||
import { McpAppTurnViews, mcpAppRunRefreshKey } from "@/components/mcp-app/McpAppTurnViews";
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import type { ExecutionProjection } from "@paperclipai/shared";
|
||||
import { useSecondTick } from "@/hooks/useSecondTick";
|
||||
@@ -307,6 +308,7 @@ export function TaskChatRunnerTurn({
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<McpAppTurnViews runId={runId} refreshKey={mcpAppRunRefreshKey(turnItems, status)} />
|
||||
{final ? (
|
||||
<div
|
||||
className="w-full"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { groupImageResources } from "./image-resources";
|
||||
import { McpAppTurnViews } from "@/components/mcp-app/McpAppTurnViews";
|
||||
import { TaskBrowserActivity } from "../task-side-panel/TaskBrowserActivity";
|
||||
import { TaskChatProjectCreatedCard } from "./TaskChatProjectCreatedCard";
|
||||
import { TaskChatSkillCreatedCard } from "./TaskChatSkillCreatedCard";
|
||||
@@ -159,7 +160,11 @@ function renderItem(
|
||||
}
|
||||
/>
|
||||
) : undefined;
|
||||
return (
|
||||
// MCP Apps views ride with the reply, outside the folded tool history.
|
||||
const appViews = item.author === "agent" && item.sourceRunId
|
||||
? <McpAppTurnViews runId={item.sourceRunId} notBeforeMs={item.createdAtIso ? Date.parse(item.createdAtIso) : undefined} />
|
||||
: null;
|
||||
const bubble = (
|
||||
<TaskChatBubble
|
||||
item={item}
|
||||
// Hydration and live-to-durable reconciliation may move a logical
|
||||
@@ -173,7 +178,7 @@ function renderItem(
|
||||
: actions
|
||||
}
|
||||
queuedAction={renderQueuedAction?.(item)}
|
||||
beforeTurn={item.attachedTurn?.standaloneHeader ? turn : undefined}
|
||||
beforeTurn={item.attachedTurn?.standaloneHeader ? <>{turn}{appViews}</> : undefined}
|
||||
attachedTurn={item.attachedTurn?.standaloneHeader ? undefined : turn}
|
||||
hideAgentIdentity={Boolean(item.attachedTurn?.standaloneHeader)}
|
||||
onTryAgainNoLiveExecutionPath={onTryAgainNoLiveExecutionPath}
|
||||
@@ -183,6 +188,7 @@ function renderItem(
|
||||
attachments={attachments}
|
||||
/>
|
||||
);
|
||||
return appViews && !item.attachedTurn?.standaloneHeader ? <>{appViews}{bubble}</> : bubble;
|
||||
}
|
||||
case "marker":
|
||||
return (
|
||||
|
||||
@@ -146,6 +146,7 @@ export function commentsToTaskChatItems(
|
||||
: undefined,
|
||||
agentIcon,
|
||||
onBehalfOfUserName,
|
||||
...(kind === "agent" && sourceRunId ? { sourceRunId } : {}),
|
||||
// System notices carry their structured hints through to the render
|
||||
// layer (PAP-443); other authors keep the item lean.
|
||||
presentation: kind === "system" ? comment.presentation ?? null : undefined,
|
||||
|
||||
@@ -146,6 +146,8 @@ export interface TaskChatMessageItem {
|
||||
optimistic?: "pending" | "queued";
|
||||
/** Live run this queued message is waiting behind. */
|
||||
queueTargetRunId?: string | null;
|
||||
/** Run that wrote this agent reply; its MCP Apps views show with the reply. */
|
||||
sourceRunId?: string;
|
||||
/** Non-blocking verification limitations attached to the run's durable reply. */
|
||||
verificationCaveats?: Array<{
|
||||
commandOrCheck: string;
|
||||
|
||||
@@ -465,6 +465,11 @@ function recommendedManagedConnectorMethod(
|
||||
);
|
||||
}
|
||||
|
||||
// One-method sign-in skips the access step. These providers' warnings (Railway
|
||||
// project scope, Circleback sharing outside the workspace) must still be read
|
||||
// before authorizing, so the sign-in screen repeats them.
|
||||
const SIGN_IN_GUIDANCE_SLUGS = new Set(["railway", "circleback"]);
|
||||
|
||||
function canUseAutomaticOAuthFastPath(entry: AppDefinition | null | undefined): boolean {
|
||||
if (!entry) return false;
|
||||
const methods = availableToolConnectionMethods(entry);
|
||||
@@ -2337,7 +2342,7 @@ function StandardConnectionSetupFlow({
|
||||
} : undefined}
|
||||
authorizationHost={authorizationHost}
|
||||
authorizationUrl={authorizationFallbackUrl}
|
||||
guidance={entry?.slug === "railway" && accessStepMethod ? (
|
||||
guidance={entry && SIGN_IN_GUIDANCE_SLUGS.has(entry.slug) && accessStepMethod ? (
|
||||
<div className="space-y-3 text-sm text-muted-foreground">
|
||||
<p>{accessStepMethod.guidanceMd}</p>
|
||||
<ul className="list-disc space-y-2 pl-5">
|
||||
|
||||
@@ -78,6 +78,10 @@ const APP_COPY: Record<string, AppCopy> = {
|
||||
tagline: "Reuse approved product copy and follow your style guide.",
|
||||
short: "Sign in with Ditto. API keys are optional.",
|
||||
},
|
||||
circleback: {
|
||||
tagline: "Search meeting notes, transcripts, and action items.",
|
||||
short: "Sign in with Circleback. Meetings appear as cards in chat.",
|
||||
},
|
||||
gauge: {
|
||||
tagline: "Track your brand in AI answers and run content workflows.",
|
||||
short: "Sign in with Gauge and pick an organization. API keys are optional.",
|
||||
|
||||
@@ -309,6 +309,10 @@ export const queryKeys = {
|
||||
["status-cards", "detail", id, "summary-revisions"] as const,
|
||||
dryRun: (id: string) => ["status-cards", "detail", id, "dry-run"] as const,
|
||||
},
|
||||
mcpApps: {
|
||||
views: (issueId: string) => ["mcp-app-views", issueId] as const,
|
||||
detail: (issueId: string, viewId: string) => ["mcp-app-views", issueId, "detail", viewId] as const,
|
||||
},
|
||||
issues: {
|
||||
recoveryActions: (id: string, actionId: string | null, runId: string | null) =>
|
||||
["issues", id, "recovery-actions", actionId, runId] as const,
|
||||
|
||||
@@ -72,6 +72,7 @@ const POSTHOG = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "posthog"
|
||||
const NEON = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "neon")!;
|
||||
const SUPERAGENT = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "superagent")!;
|
||||
const GAUGE = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "gauge")!;
|
||||
const CIRCLEBACK = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "circleback")!;
|
||||
const DITTO = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "ditto")!;
|
||||
const BRAINTRUST = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "braintrust")!;
|
||||
const POSTMAN = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "postman")!;
|
||||
@@ -2438,6 +2439,24 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it("connects Circleback with direct browser sign-in and shows the share warning first", async () => {
|
||||
mockParams.appKey = "circleback";
|
||||
listGalleryMock.mockResolvedValueOnce({ apps: [CIRCLEBACK] });
|
||||
await render();
|
||||
// Share and delete advice must be visible before sign-in on the only path.
|
||||
expect(container.textContent).toContain("anyone with the link");
|
||||
expect(container.textContent).toContain("Set share and delete actions to Ask first");
|
||||
expect(container.querySelector('input[type="password"]')).toBeNull();
|
||||
expect(container.textContent).not.toContain("API key");
|
||||
const primary = buttonByText("Continue to Circleback");
|
||||
expect(primary?.disabled).toBe(false);
|
||||
await act(async () => primary!.click());
|
||||
await vi.waitFor(() => expect(connectAppMock).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
||||
galleryKey: "circleback",
|
||||
connectionMethodKey: "mcp-oauth",
|
||||
})));
|
||||
});
|
||||
|
||||
it("enables Neon's Connect button only once the API key is entered, with pin and read-only optional", async () => {
|
||||
mockParams.appKey = "neon";
|
||||
listGalleryMock.mockResolvedValueOnce({ apps: [NEON] });
|
||||
|
||||
@@ -387,11 +387,11 @@ describe("Connectors landing page", () => {
|
||||
}
|
||||
|
||||
function composioFixture() {
|
||||
aggregatorCatalogMock.push(indexedApp("Circleback"));
|
||||
aggregatorCatalogMock.push(indexedApp("Fathom"));
|
||||
listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("composio")] });
|
||||
listApplicationsMock.mockResolvedValue({ applications: [application({ id: "gateway-app", name: "Composio", metadata: { sourceTemplateKey: "composio" } })] });
|
||||
listConnectionsMock.mockResolvedValue({ connections: [connection({ applicationId: "gateway-app", name: "Composio account", transport: "mcp_remote", config: { sourceTemplateKey: "composio" } })] });
|
||||
const snapshot = { connectionId: "conn-notion", toolkit: "circleback", status: "connected", checkedAt: new Date().toISOString(), accounts: [{ id: "ca-work", alias: "Meeting notes", status: "ACTIVE", isDefault: true }] };
|
||||
const snapshot = { connectionId: "conn-notion", toolkit: "fathom", status: "connected", checkedAt: new Date().toISOString(), accounts: [{ id: "ca-work", alias: "Meeting notes", status: "ACTIVE", isDefault: true }] };
|
||||
listComposioAppsMock.mockResolvedValue({ apps: [snapshot] });
|
||||
refreshComposioAppsMock.mockResolvedValue({ apps: [snapshot] });
|
||||
return snapshot;
|
||||
@@ -414,7 +414,7 @@ describe("Connectors landing page", () => {
|
||||
}
|
||||
|
||||
async function connectionMenu(name = "Meeting notes") {
|
||||
const trigger = container.querySelector<HTMLButtonElement>(`[data-app-slug="circleback"] button[aria-label="Manage ${name} connection"]`)!;
|
||||
const trigger = container.querySelector<HTMLButtonElement>(`[data-app-slug="fathom"] button[aria-label="Manage ${name} connection"]`)!;
|
||||
expect(trigger).toBeTruthy();
|
||||
await act(() => { trigger.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); });
|
||||
await flushReact();
|
||||
@@ -533,19 +533,19 @@ describe("Connectors landing page", () => {
|
||||
listUserDirectoryMock.mockResolvedValue({ users: [{ principalId: "user-1", status: "active", user: { id: "user-1", name: "Dotta", email: "dotta@example.com", image: null } }] });
|
||||
aggregatorCatalogMock.push(...Array.from({ length: 60 }, (_, index) => indexedApp(`Indexed App ${index}`)));
|
||||
await renderBrowse();
|
||||
const circleback = container.querySelector('[data-app-slug="circleback"]')!;
|
||||
expect(circleback.getAttribute("data-connected")).toBe("true");
|
||||
expect(circleback.textContent).toContain("Accounts managed in Composio.");
|
||||
expect(circleback.textContent).toContain("Managed by Composio ·“Composio account”");
|
||||
expect(circleback.textContent).not.toContain("Connected by");
|
||||
expect(circleback.textContent).not.toContain("Dotta");
|
||||
expect(circleback.querySelector('[title="Connected"]')).toBeTruthy();
|
||||
expect(circleback.querySelector('button[aria-label="Manage Meeting notes"]')).toBeTruthy();
|
||||
expect(circleback.querySelector('button[aria-label="Connect Circleback"]')).toBeNull();
|
||||
const fathom = container.querySelector('[data-app-slug="fathom"]')!;
|
||||
expect(fathom.getAttribute("data-connected")).toBe("true");
|
||||
expect(fathom.textContent).toContain("Accounts managed in Composio.");
|
||||
expect(fathom.textContent).toContain("Managed by Composio ·“Composio account”");
|
||||
expect(fathom.textContent).not.toContain("Connected by");
|
||||
expect(fathom.textContent).not.toContain("Dotta");
|
||||
expect(fathom.querySelector('[title="Connected"]')).toBeTruthy();
|
||||
expect(fathom.querySelector('button[aria-label="Manage Meeting notes"]')).toBeTruthy();
|
||||
expect(fathom.querySelector('button[aria-label="Connect Fathom"]')).toBeNull();
|
||||
await clickButton("Next", container);
|
||||
expect(container.querySelector('[data-app-slug="circleback"] button[aria-label="Manage Circleback"]')).toBeTruthy();
|
||||
expect(container.querySelector('[data-app-slug="fathom"] button[aria-label="Manage Fathom"]')).toBeTruthy();
|
||||
await search("Meeting notes");
|
||||
expect(container.querySelectorAll('[data-app-slug="circleback"]')).toHaveLength(1);
|
||||
expect(container.querySelectorAll('[data-app-slug="fathom"]')).toHaveLength(1);
|
||||
await clickButton("Manage", container);
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Meeting notes");
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain('“Composio account”');
|
||||
@@ -560,12 +560,12 @@ describe("Connectors landing page", () => {
|
||||
listComposioAppsMock.mockResolvedValue({ apps: [pending] });
|
||||
refreshComposioAppsMock.mockResolvedValue({ apps: [pending] });
|
||||
await renderBrowse();
|
||||
const circleback = container.querySelector('[data-app-slug="circleback"]')!;
|
||||
expect(circleback.textContent).toContain("Waiting for sign-in");
|
||||
expect(circleback.textContent).toContain("Finish connecting this account.");
|
||||
expect(circleback.querySelector('[title="Connected"]')).toBeNull();
|
||||
await act(() => circleback.querySelector<HTMLButtonElement>('button[aria-label="Manage Meeting notes"]')!.click());
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Manage Circleback");
|
||||
const fathom = container.querySelector('[data-app-slug="fathom"]')!;
|
||||
expect(fathom.textContent).toContain("Waiting for sign-in");
|
||||
expect(fathom.textContent).toContain("Finish connecting this account.");
|
||||
expect(fathom.querySelector('[title="Connected"]')).toBeNull();
|
||||
await act(() => fathom.querySelector<HTMLButtonElement>('button[aria-label="Manage Meeting notes"]')!.click());
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Manage Fathom");
|
||||
});
|
||||
|
||||
it("discovers app authorization on refresh and reflects a disconnection when returning from Composio", async () => {
|
||||
@@ -574,12 +574,12 @@ describe("Connectors landing page", () => {
|
||||
listComposioAppsMock.mockResolvedValue({ apps: [] });
|
||||
syncComposioAppsMock.mockResolvedValue(response);
|
||||
await renderBrowse();
|
||||
await vi.waitFor(() => expect(container.querySelector('[data-app-slug="circleback"]')?.getAttribute("data-connected")).toBe("true"));
|
||||
await vi.waitFor(() => expect(container.querySelector('[data-app-slug="fathom"]')?.getAttribute("data-connected")).toBe("true"));
|
||||
listComposioAppsMock.mockResolvedValue({ apps: [] });
|
||||
syncComposioAppsMock.mockResolvedValue({ apps: [] });
|
||||
await act(() => focusManager.setFocused(false));
|
||||
await act(() => focusManager.setFocused(true));
|
||||
await vi.waitFor(() => expect(container.querySelector('button[aria-label="Connect Circleback"]')).toBeTruthy());
|
||||
await vi.waitFor(() => expect(container.querySelector('button[aria-label="Connect Fathom"]')).toBeTruthy());
|
||||
focusManager.setFocused(undefined);
|
||||
expect(setupComposioAppMock).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -596,8 +596,8 @@ describe("Connectors landing page", () => {
|
||||
const disconnected = { ...snapshot, status: "not_connected", accounts: [] };
|
||||
refreshComposioAppsMock.mockResolvedValue({ apps: [disconnected] });
|
||||
await clickButton("Refresh", dialog);
|
||||
expect(refreshComposioAppsMock).toHaveBeenCalledWith("conn-notion", ["circleback"]);
|
||||
expect(dialog.textContent).toContain("No connected Circleback accounts.");
|
||||
expect(refreshComposioAppsMock).toHaveBeenCalledWith("conn-notion", ["fathom"]);
|
||||
expect(dialog.textContent).toContain("No connected Fathom accounts.");
|
||||
expect(manageComposioAppAccountMock).not.toHaveBeenCalled();
|
||||
expect(setupComposioAppMock).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -606,8 +606,8 @@ describe("Connectors landing page", () => {
|
||||
const snapshot = composioFixture();
|
||||
listComposioAppsMock.mockResolvedValue({ apps: [{ ...snapshot, errorAt: new Date().toISOString() }], sync: { status: "error", error: "Unavailable" } });
|
||||
await renderBrowse();
|
||||
expect(container.querySelector('button[aria-label="Manage Circleback"]')).toBeTruthy();
|
||||
expect(container.querySelector('[data-app-slug="circleback"] [title="Connected"]')).toBeNull();
|
||||
expect(container.querySelector('button[aria-label="Manage Fathom"]')).toBeTruthy();
|
||||
expect(container.querySelector('[data-app-slug="fathom"] [title="Connected"]')).toBeNull();
|
||||
expect(container.textContent).toContain("Last known account · Refresh to verify");
|
||||
expect(container.textContent).toContain("Unavailable");
|
||||
const menu = await openComposioAccountMenu();
|
||||
@@ -619,16 +619,16 @@ describe("Connectors landing page", () => {
|
||||
it("keeps the last known aggregator accounts without a load-error notice when a refetch fails transiently", async () => {
|
||||
composioFixture();
|
||||
const client = await renderBrowse();
|
||||
const circleback = () => container.querySelector('[data-app-slug="circleback"]');
|
||||
expect(circleback()?.textContent).toContain("Meeting notes");
|
||||
expect(circleback()?.querySelector('[title="Connected"]')).toBeTruthy();
|
||||
const fathom = () => container.querySelector('[data-app-slug="fathom"]');
|
||||
expect(fathom()?.textContent).toContain("Meeting notes");
|
||||
expect(fathom()?.querySelector('[title="Connected"]')).toBeTruthy();
|
||||
|
||||
listComposioAppsMock.mockRejectedValue(new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }));
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: ["tools", "aggregator-apps"] }); });
|
||||
await flushReact();
|
||||
|
||||
expect(circleback()?.textContent).toContain("Meeting notes");
|
||||
expect(circleback()?.querySelector('[title="Connected"]')).toBeTruthy();
|
||||
expect(fathom()?.textContent).toContain("Meeting notes");
|
||||
expect(fathom()?.querySelector('[title="Connected"]')).toBeTruthy();
|
||||
expect(container.textContent).not.toContain("Last known account · Refresh to verify");
|
||||
expect(container.textContent).not.toContain("Couldn’t load Composio accounts");
|
||||
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
|
||||
@@ -638,13 +638,13 @@ describe("Connectors landing page", () => {
|
||||
it("reports a real aggregator account failure while keeping the last known accounts", async () => {
|
||||
composioFixture();
|
||||
const client = await renderBrowse();
|
||||
expect(container.querySelector('[data-app-slug="circleback"]')?.textContent).toContain("Meeting notes");
|
||||
expect(container.querySelector('[data-app-slug="fathom"]')?.textContent).toContain("Meeting notes");
|
||||
|
||||
listComposioAppsMock.mockRejectedValue(new ApiError("Boom", 500, { error: "Boom" }));
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: ["tools", "aggregator-apps"] }); });
|
||||
await flushReact();
|
||||
|
||||
expect(container.querySelector('[data-app-slug="circleback"]')?.textContent).toContain("Meeting notes");
|
||||
expect(container.querySelector('[data-app-slug="fathom"]')?.textContent).toContain("Meeting notes");
|
||||
expect(container.textContent).toContain("Couldn’t load Composio accounts. Use Refresh in the connection’s menu to try again.");
|
||||
expect(container.textContent).toContain("Last known account · Refresh to verify");
|
||||
});
|
||||
@@ -716,6 +716,22 @@ describe("Connectors landing page", () => {
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Which service would you like to use?");
|
||||
});
|
||||
|
||||
it.each([true, false])("keeps native Circleback in place of its Composio listing (cloud: %s)", async (cloud) => {
|
||||
// Composio publishes it as "Circleback MCP" (slug circleback-mcp).
|
||||
aggregatorCatalogMock.push({ name: "Circleback", slug: "circleback-mcp", aliases: ["circleback_mcp"], routes: [{
|
||||
provider: "composio", toolkit: "circleback_mcp", logoUrl: "https://logos.composio.dev/api/circleback_mcp", docsUrl: "https://docs.composio.dev/toolkits/circleback_mcp",
|
||||
}] });
|
||||
listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("circleback")] });
|
||||
await renderBrowse(true, { cloud });
|
||||
|
||||
expect(container.querySelector('[data-app-slug="circleback-mcp"]')).toBeNull();
|
||||
const rows = container.querySelectorAll('[data-app-slug="circleback"]');
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]!.textContent).not.toContain("Connect through Composio");
|
||||
await clickButton("Connect", rows[0]!);
|
||||
expect(navigateMock).toHaveBeenCalledWith("/apps/connect?source=circleback");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Chat connectors offer its setup path", { enableChatConnectors: true }, true],
|
||||
["the instance is self-hosted", {}, false],
|
||||
@@ -836,28 +852,28 @@ describe("Connectors landing page", () => {
|
||||
});
|
||||
|
||||
it.each(["composio", "arcade"] as const)("skips provider selection and opens setup for a sole %s provider", async (provider) => {
|
||||
const app = indexedApp("Circleback", [provider]);
|
||||
const app = indexedApp("Fathom", [provider]);
|
||||
app.routes[0].toolkit = "circle_back";
|
||||
aggregatorCatalogMock.push(app);
|
||||
await renderBrowse();
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Circleback"]')!.click());
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Fathom"]')!.click());
|
||||
expect(navigateMock).toHaveBeenCalledWith(`/apps/connect?source=${provider}&targetToolkit=circle_back`);
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("opens the saved gateway flow directly for a sole provider and allows cancellation", async () => {
|
||||
aggregatorCatalogMock.push(indexedApp("Circleback"));
|
||||
aggregatorCatalogMock.push(indexedApp("Fathom"));
|
||||
listGalleryMock.mockResolvedValue({ apps: [getAppStoreDefinition("composio")] });
|
||||
listApplicationsMock.mockResolvedValue({ applications: [application({ id: "gateway-app", name: "Composio", metadata: { sourceTemplateKey: "composio" } })] });
|
||||
listConnectionsMock.mockResolvedValue({ connections: [connection({ applicationId: "gateway-app", name: "Composio account", config: { sourceTemplateKey: "composio" } })] });
|
||||
await renderBrowse();
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Circleback"]')!.click());
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Fathom"]')!.click());
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
expect(dialog.textContent).toContain("Connect Circleback through Composio");
|
||||
expect(dialog.textContent).toContain("Connect Fathom through Composio");
|
||||
expect(dialog.textContent).not.toContain("Which service would you like to use?");
|
||||
expect(dialog.textContent).not.toContain("Back");
|
||||
expect(dialog.textContent).not.toContain("Connection settings");
|
||||
expect(dialog.textContent).not.toContain("An agent can check Circleback in Composio");
|
||||
expect(dialog.textContent).not.toContain("An agent can check Fathom in Composio");
|
||||
expect(dialog.querySelector('[data-slot="badge"]')).toBeNull();
|
||||
expect(dialog.querySelector<HTMLSelectElement>('#composio-app-account')?.value).toBe("conn-notion");
|
||||
expect(dialog.querySelector('#composio-app-agent')).toBeNull();
|
||||
@@ -911,19 +927,19 @@ describe("Connectors landing page", () => {
|
||||
listAgentsMock.mockRejectedValue(new Error("Agents are unavailable"));
|
||||
setupComposioAppMock.mockReset().mockResolvedValueOnce({ status: "authorization_required", authorizationUrl: "https://connect.composio.dev/link/personal" }).mockResolvedValueOnce({ status: "connected" });
|
||||
await renderBrowse();
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Circleback"]')!.click());
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Fathom"]')!.click());
|
||||
const select = document.querySelector<HTMLSelectElement>('#composio-app-account')!;
|
||||
expect(Array.from(select.options).map(option => option.textContent)).toEqual(["Work Composio", "Personal Composio", "Connect a new account…"]);
|
||||
await act(() => { select.value = "conn-personal"; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
await flushReact();
|
||||
await clickButton("Continue", document.querySelector('[role="dialog"]')!);
|
||||
expect(setupComposioAppMock).toHaveBeenCalledWith("conn-personal", "circleback", { action: "start" });
|
||||
expect(setupComposioAppMock).toHaveBeenCalledWith("conn-personal", "fathom", { action: "start" });
|
||||
expect(document.querySelector('a[href="https://connect.composio.dev/link/personal"]')).toBeTruthy();
|
||||
await act(() => { select.value = "conn-notion"; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
await flushReact();
|
||||
expect(document.querySelector('a[href="https://connect.composio.dev/link/personal"]')).toBeNull();
|
||||
await clickButton("Continue", document.querySelector('[role="dialog"]')!);
|
||||
expect(setupComposioAppMock).toHaveBeenLastCalledWith("conn-notion", "circleback", { action: "start" });
|
||||
expect(setupComposioAppMock).toHaveBeenLastCalledWith("conn-notion", "fathom", { action: "start" });
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
expect(listAgentsMock).not.toHaveBeenCalled();
|
||||
expect(openNewIssueMock).not.toHaveBeenCalled();
|
||||
@@ -936,13 +952,13 @@ describe("Connectors landing page", () => {
|
||||
refreshComposioAppsMock.mockResolvedValue({ apps: [] });
|
||||
setupComposioAppMock.mockReset();
|
||||
await renderBrowse();
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Circleback"]')!.click());
|
||||
await act(() => container.querySelector<HTMLButtonElement>('button[aria-label="Connect Fathom"]')!.click());
|
||||
const select = document.querySelector<HTMLSelectElement>('#composio-app-account')!;
|
||||
await act(() => { select.value = "__new__"; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
await flushReact();
|
||||
expect(navigateMock).not.toHaveBeenCalled();
|
||||
await clickButton("Connect new account", document.querySelector('[role="dialog"]')!);
|
||||
expect(navigateMock).toHaveBeenCalledWith("/apps/connect?source=composio&targetToolkit=circleback&new=1");
|
||||
expect(navigateMock).toHaveBeenCalledWith("/apps/connect?source=composio&targetToolkit=fathom&new=1");
|
||||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||||
expect(setupComposioAppMock).not.toHaveBeenCalled();
|
||||
expect(listAgentsMock).not.toHaveBeenCalled();
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { McpAppCallToolResult } from "@paperclipai/shared";
|
||||
import { McpAppIssueProvider } from "@/components/mcp-app/McpAppIssueContext";
|
||||
import { McpAppTurnViews } from "@/components/mcp-app/McpAppTurnViews";
|
||||
import { McpAppViewContent } from "@/components/mcp-app/McpAppView";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import {
|
||||
ISSUE_ID,
|
||||
MEETINGS,
|
||||
MEETINGS_VIEW_DETAIL,
|
||||
MEETINGS_VIEW_SUMMARY,
|
||||
RUN_ID,
|
||||
} from "../../support/mcp-app/fixtures";
|
||||
|
||||
function Frame({ children }: { children: ReactNode }) {
|
||||
return <div className="mx-auto w-full max-w-(--tc-shell-max-w) p-6">{children}</div>;
|
||||
}
|
||||
|
||||
/** The production reply-level block with the run's recorded view in the query cache. */
|
||||
function SeededRunViews() {
|
||||
const queryClient = useQueryClient();
|
||||
const [seeded] = useState(() => {
|
||||
queryClient.setQueryData(queryKeys.mcpApps.views(ISSUE_ID), [MEETINGS_VIEW_SUMMARY]);
|
||||
queryClient.setQueryData(queryKeys.mcpApps.detail(ISSUE_ID, MEETINGS_VIEW_SUMMARY.id), MEETINGS_VIEW_DETAIL);
|
||||
return true;
|
||||
});
|
||||
if (!seeded) return null;
|
||||
return (
|
||||
<McpAppIssueProvider issueId={ISSUE_ID}>
|
||||
<Frame>
|
||||
<McpAppTurnViews runId={RUN_ID} />
|
||||
<p className="mt-3 text-sm text-foreground">Your most recent meetings are shown above.</p>
|
||||
</Frame>
|
||||
</McpAppIssueProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const refreshedResult: McpAppCallToolResult = {
|
||||
content: [{ type: "text", text: "Refreshed" }],
|
||||
structuredContent: { meetings: [...MEETINGS, { ...MEETINGS[0]!, id: "m3", name: "Weekly product sync", tag: "Product Meeting", when: "Today" }] },
|
||||
};
|
||||
|
||||
function ViewState({ state }: { state: "ready" | "loading" | "error" | "tool-call-denied" }) {
|
||||
const callTool = async (): Promise<McpAppCallToolResult> => state === "tool-call-denied"
|
||||
? { content: [{ type: "text", text: "This action needs approval first. It was sent for review." }], isError: true }
|
||||
: refreshedResult;
|
||||
return (
|
||||
<Frame>
|
||||
<McpAppViewContent
|
||||
detail={state === "loading" ? undefined : MEETINGS_VIEW_DETAIL}
|
||||
status={state === "tool-call-denied" ? "ready" : state}
|
||||
errorMessage={state === "error" ? "Circleback could not show this view. The tool result is still in the row above." : null}
|
||||
callTool={callTool}
|
||||
displayName="Display meetings"
|
||||
/>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = {
|
||||
id: "tasks-task-chat-mcp-app",
|
||||
title: "Tasks and conversations/Task creation and lifecycle/Tasks/MCP App views",
|
||||
component: ViewState,
|
||||
parameters: {
|
||||
layout: "fullscreen",
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"MCP Apps (io.modelcontextprotocol/ui) views shown with the agent's reply, such as Circleback meeting cards. The view runs in an opaque-origin sandboxed iframe and talks to Paperclip only through the MCP Apps postMessage protocol: initialize, tool input and result, size changes, tool calls and opening links.",
|
||||
},
|
||||
},
|
||||
paperclip: {
|
||||
"capabilities": [
|
||||
"tasks/discussion",
|
||||
"runs-adapters/runs"
|
||||
],
|
||||
"status": "current",
|
||||
"implementation": "production",
|
||||
"boundary": "fixtures",
|
||||
"notes": "The view document is an original fixture that follows the 2026-01-26 MCP Apps protocol. Provider HTML comes from the connection at runtime.",
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof ViewState>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const WithReply: Story = { name: "01 · Meeting cards with the agent's reply", render: () => <SeededRunViews />, args: { state: "ready" } };
|
||||
export const Ready: Story = { name: "02 · View (Refresh calls a tool)", args: { state: "ready" } };
|
||||
export const Loading: Story = { name: "03 · Loading", args: { state: "loading" } };
|
||||
export const ErrorFallback: Story = { name: "04 · View unavailable", args: { state: "error" } };
|
||||
export const ToolCallNeedsApproval: Story = { name: "05 · Tool call needs approval", args: { state: "tool-call-denied" } };
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared";
|
||||
|
||||
/**
|
||||
* A self-contained MCP Apps view that follows the 2026-01-26 protocol by hand:
|
||||
* ui/initialize → ui/notifications/initialized → tool-input/tool-result, then
|
||||
* size-changed, tools/call and ui/open-link. It stands in for a provider's
|
||||
* meeting-card view; the markup is original fixture content.
|
||||
*/
|
||||
export const MEETING_CARDS_VIEW_HTML = String.raw`<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
:root { color-scheme: light dark; font-family: var(--font-sans, system-ui, sans-serif); }
|
||||
body { margin: 0; padding: 8px 12px; background: transparent; color: var(--color-text-primary, CanvasText); }
|
||||
.row { display: flex; align-items: center; gap: 12px; padding: 8px 4px; border-radius: 8px; cursor: pointer; }
|
||||
.row:hover { background: var(--color-background-secondary, rgba(127,127,127,.12)); }
|
||||
.avatar { width: 32px; height: 32px; border-radius: 999px; display: grid; place-items: center; font-size: 12px; font-weight: 600; color: #fff; background: #b9655a; flex: none; }
|
||||
.text { min-width: 0; flex: 1; }
|
||||
.name { font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.who { font-size: 12px; color: var(--color-text-secondary, GrayText); }
|
||||
.tag { font-size: 12px; padding: 2px 8px; border: 1px solid var(--color-border-primary, rgba(127,127,127,.4)); border-radius: 999px; white-space: nowrap; }
|
||||
.date { font-size: 12px; color: var(--color-text-secondary, GrayText); width: 64px; text-align: right; }
|
||||
.actions { padding: 6px 4px 2px; }
|
||||
button { font: inherit; font-size: 12px; background: none; border: 1px solid var(--color-border-primary, rgba(127,127,127,.4)); color: inherit; border-radius: 6px; padding: 2px 8px; cursor: pointer; }
|
||||
.status { font-size: 12px; color: var(--color-text-secondary, GrayText); margin-left: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="list"><div class="who">Waiting for the meeting list…</div></div>
|
||||
<div class="actions"><button id="refresh" type="button">Refresh</button><span class="status" id="status"></span></div>
|
||||
<script>
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
function request(method, params) {
|
||||
const id = nextId++;
|
||||
parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
|
||||
return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
|
||||
}
|
||||
function notify(method, params) { parent.postMessage({ jsonrpc: "2.0", method, params }, "*"); }
|
||||
function applyContext(context) {
|
||||
if (!context) return;
|
||||
if (context.theme) document.documentElement.style.colorScheme = context.theme;
|
||||
const vars = context.styles && context.styles.variables;
|
||||
if (vars) for (const key of Object.keys(vars)) document.documentElement.style.setProperty(key, vars[key]);
|
||||
}
|
||||
function initials(name) { return name.split(/\s+/).map((part) => part[0]).join("").slice(0, 2).toUpperCase(); }
|
||||
function render(result) {
|
||||
const meetings = (result && result.structuredContent && result.structuredContent.meetings) || [];
|
||||
const list = document.getElementById("list");
|
||||
list.innerHTML = "";
|
||||
for (const meeting of meetings) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "row";
|
||||
row.innerHTML = '<div class="avatar"></div><div class="text"><div class="name"></div><div class="who"></div></div><span class="tag"></span><span class="date"></span>';
|
||||
row.querySelector(".avatar").textContent = initials(meeting.organizer);
|
||||
row.querySelector(".name").textContent = meeting.name;
|
||||
row.querySelector(".who").textContent = meeting.attendees;
|
||||
row.querySelector(".tag").textContent = meeting.tag;
|
||||
row.querySelector(".date").textContent = meeting.when;
|
||||
row.addEventListener("click", () => request("ui/open-link", { url: meeting.url }));
|
||||
list.appendChild(row);
|
||||
}
|
||||
if (!meetings.length) list.innerHTML = '<div class="who">No meetings</div>';
|
||||
reportSize();
|
||||
}
|
||||
function reportSize() { notify("ui/notifications/size-changed", { height: Math.ceil(document.body.getBoundingClientRect().height) }); }
|
||||
window.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
if (!message || message.jsonrpc !== "2.0") return;
|
||||
if (message.id !== undefined && pending.has(message.id)) {
|
||||
const entry = pending.get(message.id); pending.delete(message.id);
|
||||
message.error ? entry.reject(message.error) : entry.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
if (message.method === "ui/notifications/tool-result") render(message.params);
|
||||
if (message.method === "ui/notifications/host-context-changed") applyContext(message.params);
|
||||
if (message.method === "ui/resource-teardown") parent.postMessage({ jsonrpc: "2.0", id: message.id, result: {} }, "*");
|
||||
});
|
||||
document.getElementById("refresh").addEventListener("click", async () => {
|
||||
const status = document.getElementById("status");
|
||||
status.textContent = "Refreshing…";
|
||||
try {
|
||||
const result = await request("tools/call", { name: "RefreshMeetingCards", arguments: {} });
|
||||
render(result);
|
||||
status.textContent = result.isError ? "Refresh failed" : "Updated";
|
||||
} catch (error) {
|
||||
status.textContent = (error && error.message) || "Refresh failed";
|
||||
}
|
||||
reportSize();
|
||||
});
|
||||
request("ui/initialize", { protocolVersion: "2026-01-26", appCapabilities: { availableDisplayModes: ["inline"] }, clientInfo: { name: "meeting-cards-fixture", version: "1" } })
|
||||
.then((result) => { applyContext(result.hostContext); notify("ui/notifications/initialized", {}); reportSize(); });
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
export const MEETINGS = [
|
||||
{ id: "m1", name: "Paperclip/Tom", organizer: "Tom Drummond", attendees: "Tom Drummond, you, and 2 others", tag: "External / Vendor", when: "Yesterday", url: "https://app.circleback.ai/meetings/m1" },
|
||||
{ id: "m2", name: "Paperclip <> Heavybit, Partner Meeting", organizer: "Tom Drummond", attendees: "Tom Drummond, you, and 2 others", tag: "3 tags", when: "Tue", url: "https://app.circleback.ai/meetings/m2" },
|
||||
];
|
||||
|
||||
export const ISSUE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
export const RUN_ID = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
export const MEETINGS_VIEW_SUMMARY: McpAppViewSummary = {
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
issueId: ISSUE_ID,
|
||||
runId: RUN_ID,
|
||||
connectionId: "44444444-4444-4444-8444-444444444444",
|
||||
applicationName: "Circleback",
|
||||
toolName: "mcp.circleback-44444444:displaymeetings",
|
||||
upstreamToolName: "DisplayMeetings",
|
||||
resourceUri: "ui://circleback/meetings.html",
|
||||
toolInput: { meetingIds: ["m1", "m2"] },
|
||||
createdAt: "2026-11-12T15:00:00.000Z",
|
||||
};
|
||||
|
||||
export const MEETINGS_VIEW_DETAIL: McpAppViewDetail = {
|
||||
...MEETINGS_VIEW_SUMMARY,
|
||||
toolResult: {
|
||||
content: [{ type: "text", text: "Showing 2 meetings as cards." }],
|
||||
structuredContent: { meetings: MEETINGS },
|
||||
},
|
||||
resource: {
|
||||
uri: "ui://circleback/meetings.html",
|
||||
html: MEETING_CARDS_VIEW_HTML,
|
||||
csp: {},
|
||||
permissions: {},
|
||||
prefersBorder: true,
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user