mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 21:34:48 +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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user