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:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-12 13:28:05 -06:00
1 parent 6a24b417c0
commit 8ff45c0fa9
67 files changed
+3865 -134

No files matched your search

@@ -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");
+365
View File
@@ -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",
+1 -1
View File
@@ -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)
+2
View File
@@ -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,
+92
View File
@@ -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;
}
+16
View File
@@ -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"],
+54 -1
View File
@@ -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) {
+2 -2
View File
@@ -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.",
},
},
});
+4 -1
View File
@@ -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]));
+128
View File
@@ -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;
},
};
}
+3 -1
View File
@@ -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`,
+232 -27
View File
@@ -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,