Skip to content

Commit 9fea95f

Browse files
kathiekiwiTrigger.dev RepoOps
authored andcommitted
chore(mcp): groundwork for remote-only MCP tools and confirmation classes
Mono-RevId: 86ab8d1922a687485cf193a9a68c37a430e6bbed
1 parent 354738e commit 9fea95f

23 files changed

Lines changed: 935 additions & 50 deletions

‎apps/webapp/app/mcp/confirm/confirmation.server.ts‎

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { createHash, createHmac } from "node:crypto";
22
import { $replica } from "~/db.server";
3-
import type { McpConfirmSpec, McpIdentity, McpSubject } from "../gate/types";
3+
import type { McpConfirmSpec, McpIdentity, McpPreviewRefusal, McpSubject } from "../gate/types";
44

5-
const PREVIEW_LIMIT = 64 * 1024;
5+
export const PREVIEW_LIMIT = 64 * 1024;
66
const SENSITIVE_KEY = /secret|password|token|apikey|api_key|authorization/i;
77

88
export function canonicalJson(value: unknown): string {
@@ -51,19 +51,40 @@ async function defaultFingerprintKey() {
5151
return (await import("~/env.server")).env.SESSION_SECRET;
5252
}
5353

54+
export async function confirmationPreview(
55+
tool: string,
56+
spec: true,
57+
args: unknown,
58+
subject: McpSubject | null,
59+
fingerprintKey?: string
60+
): Promise<{ preview: string; truncated: boolean }>;
61+
export async function confirmationPreview(
62+
tool: string,
63+
spec: true | McpConfirmSpec,
64+
args: unknown,
65+
subject: McpSubject | null,
66+
fingerprintKey?: string
67+
): Promise<{ preview: string; truncated: boolean } | McpPreviewRefusal>;
5468
export async function confirmationPreview(
5569
tool: string,
5670
spec: true | McpConfirmSpec,
5771
args: unknown,
5872
subject: McpSubject | null,
5973
fingerprintKey?: string
60-
): Promise<{ preview: string; truncated: boolean }> {
61-
const preview =
62-
spec === true
63-
? `${tool} ${canonicalJson(
64-
hideSensitive(args ?? {}, fingerprintKey ?? (await defaultFingerprintKey()))
65-
)}`
66-
: spec.preview(args, subject);
74+
): Promise<{ preview: string; truncated: boolean } | McpPreviewRefusal> {
75+
if (spec !== true) {
76+
const preview = await spec.preview(args, subject);
77+
if (typeof preview !== "string") return preview;
78+
if (preview.length > PREVIEW_LIMIT) {
79+
return {
80+
refuse: `This change is too large to confirm in full (${preview.length} characters, the limit is ${PREVIEW_LIMIT}). Split it into smaller calls.`,
81+
};
82+
}
83+
return { preview, truncated: false };
84+
}
85+
const preview = `${tool} ${canonicalJson(
86+
hideSensitive(args ?? {}, fingerprintKey ?? (await defaultFingerprintKey()))
87+
)}`;
6788
return preview.length > PREVIEW_LIMIT
6889
? { preview: `${preview.slice(0, PREVIEW_LIMIT)}…`, truncated: true }
6990
: { preview, truncated: false };

‎apps/webapp/app/mcp/confirm/store.server.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export type McpConfirmationStore = {
4848
get: (id: string, userId: string) => Promise<McpConfirmationRecord | null>;
4949
approve: (id: string, userId: string) => Promise<boolean>;
5050
deny: (id: string, userId: string) => Promise<boolean>;
51-
consumeApproved: (lookup: McpApprovalLookup) => Promise<{ id: string } | null>;
51+
consumeApproved: (lookup: McpApprovalLookup) => Promise<{ id: string; preview: string } | null>;
5252
};
5353

5454
const approveScript = `
@@ -96,7 +96,7 @@ if ttl <= 0 then return nil end
9696
r.consumedAt = tonumber(ARGV[7])
9797
redis.call("SET", KEYS[2], cjson.encode(r), "PX", ttl)
9898
redis.call("DEL", KEYS[1])
99-
return r.id
99+
return { r.id, r.preview }
100100
`;
101101

102102
const recordKey = (userId: string, id: string) => `mcp:confirm:{${userId}}:record:${id}`;
@@ -208,7 +208,9 @@ export function createMcpConfirmationStore(
208208
lookup.argsDigest,
209209
String(now())
210210
);
211-
return typeof consumed === "string" ? { id: consumed } : null;
211+
return Array.isArray(consumed)
212+
? { id: consumed[0] as string, preview: consumed[1] as string }
213+
: null;
212214
},
213215
};
214216
}

‎apps/webapp/app/mcp/gate/types.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { RuntimeEnvironmentType } from "@trigger.dev/database";
2+
import type { RbacScopeAction, RbacScopeResourceType } from "@trigger.dev/plugins";
23
import type { RbacAbility } from "@trigger.dev/rbac";
34
import type { McpIdentity } from "../types";
45

@@ -11,8 +12,26 @@ export type McpSubject = {
1112
environmentType?: RuntimeEnvironmentType;
1213
};
1314

15+
export type McpPreviewRefusal = { refuse: string };
16+
17+
export type McpPrecheckDenial =
18+
| "forbidden"
19+
| { action: RbacScopeAction; subject: RbacScopeResourceType; id?: string };
20+
1421
export type McpConfirmSpec<A = unknown> = {
15-
preview: (args: A, subject: McpSubject | null) => string;
22+
/**
23+
* The ability is undefined for `user: true` tools; a check that relies on it must deny then.
24+
* Return `{ action, subject, id? }` to name the missing permission; `id` narrows the token-scope check only.
25+
*/
26+
precheck?: (
27+
args: A,
28+
ability: RbacAbility | undefined,
29+
subject: McpSubject | null
30+
) => McpPrecheckDenial | void | Promise<McpPrecheckDenial | void>;
31+
preview: (
32+
args: A,
33+
subject: McpSubject | null
34+
) => string | McpPreviewRefusal | Promise<string | McpPreviewRefusal>;
1635
};
1736

1837
export type McpToolAuth =
@@ -41,5 +60,5 @@ export type McpToolContext = {
4160
ability?: RbacAbility;
4261
signal: AbortSignal;
4362
requestId: string | number;
44-
confirmation?: { id: string };
63+
confirmation?: { id: string; preview: string };
4564
};

‎apps/webapp/app/mcp/gate/withMcpToolAuth.server.ts‎

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { UrlElicitationRequiredError } from "@modelcontextprotocol/server";
22
import { buildJwtAbility, CAPLESS_USER_ACTOR_SCOPES, type RbacAbility } from "@trigger.dev/rbac";
33
import { logger } from "~/services/logger.server";
44
import { resolveAndRecheckUserActorClaims } from "~/services/personalAccessToken.server";
5-
import { mcpResource } from "~/services/oauth/metadata.server";
5+
import { MCP_SCOPES, mcpResource } from "~/services/oauth/metadata.server";
66
import { rbac } from "~/services/rbac.server";
77
import {
88
confirmationClient,
@@ -55,6 +55,8 @@ type Outcome =
5555
| "insufficient_scope"
5656
| "forbidden"
5757
| "user_denied"
58+
| "refused"
59+
| "stale"
5860
| "error"
5961
| "pending"
6062
| "confirmed";
@@ -63,6 +65,13 @@ type Denial = "denied" | "insufficient_scope" | "forbidden";
6365

6466
const DENY_REASONS = { insufficient_scope: "scope", forbidden: "role", denied: "other" } as const;
6567

68+
const staleResults = new WeakSet<McpToolResult>();
69+
70+
export const markStale = (result: McpToolResult): McpToolResult => {
71+
staleResults.add(result);
72+
return result;
73+
};
74+
6675
const NO_EXTRA: McpRequestExtra = { signal: new AbortController().signal, requestId: "" };
6776

6877
const errorText = (text: string): McpToolResult => ({
@@ -99,6 +108,14 @@ function denialResult(denial: Denial, auth: McpToolAuth): McpToolResult {
99108
);
100109
}
101110

111+
function namedPermission(denial: unknown): { action: string; subject: string; id?: string } | null {
112+
if (typeof denial !== "object" || denial === null) return null;
113+
const { action, subject, id } = denial as Record<string, unknown>;
114+
if (typeof action !== "string" || typeof subject !== "string") return null;
115+
if (!MCP_SCOPES.includes(`${action}:${subject}`)) return null;
116+
return { action, subject, ...(typeof id === "string" ? { id } : {}) };
117+
}
118+
102119
const failed = (): McpToolResult => ({
103120
content: [{ type: "text", text: "The tool failed. Try again later." }],
104121
isError: true,
@@ -204,9 +221,10 @@ async function confirm(
204221
identity: McpIdentity,
205222
subject: McpSubject | null
206223
): Promise<
207-
| { approved: true; id: string }
224+
| { approved: true; id: string; preview: string }
208225
| { approved: false; id: string; url: string; message: string }
209226
| { approved: false; denied: true; id: string }
227+
| { approved: false; refused: string }
210228
> {
211229
const lookup = {
212230
userId: identity.userId,
@@ -216,13 +234,16 @@ async function confirm(
216234
argsDigest: confirmationDigest(tool, args, subject),
217235
};
218236
const consumed = await store.consumeApproved(lookup);
219-
if (consumed) return { approved: true, id: consumed.id };
237+
if (consumed) return { approved: true, id: consumed.id, preview: consumed.preview };
238+
239+
const preview = await confirmationPreview(tool, spec, args, subject);
240+
if ("refuse" in preview) return { approved: false, refused: preview.refuse };
220241

221242
const created = await store.createPending({
222243
...lookup,
223244
clientId: identity.kind === "uat" ? (identity.clientId ?? "Unknown client") : undefined,
224245
subject: confirmationSubject(subject),
225-
...(await confirmationPreview(tool, spec, args, subject)),
246+
...preview,
226247
});
227248
if ("denied" in created) return { approved: false, denied: true, id: created.id };
228249
const { id, url } = created;
@@ -260,11 +281,38 @@ export function withMcpToolAuth<TArgs>(
260281
return denialResult(authorization.denial, auth);
261282
}
262283

263-
let confirmation: { id: string } | undefined;
284+
let confirmation: { id: string; preview: string } | undefined;
264285
const approval = requiresApproval(auth);
265286
if (approval) {
287+
const precheck =
288+
typeof approval === "object"
289+
? await approval.precheck?.(args, authorization.ability, subject)
290+
: undefined;
291+
if (precheck !== undefined) {
292+
const named = precheck === "forbidden" ? null : namedPermission(precheck);
293+
if (!named && precheck !== "forbidden") {
294+
outcome = "denied";
295+
return denialResult(outcome, auth);
296+
}
297+
const resource = named
298+
? {
299+
type: named.subject,
300+
...(named.id ? { id: named.id } : {}),
301+
...(subject?.environmentType ? { envType: subject.environmentType } : {}),
302+
}
303+
: undefined;
304+
outcome =
305+
named && missingScopes(named, identity, resource).length
306+
? "insufficient_scope"
307+
: "forbidden";
308+
return denialResult(outcome, named ?? auth);
309+
}
266310
const { store, mode } = await confirmationDefaults(options);
267311
const check = await confirm(store, tool, approval, args, identity, subject);
312+
if ("refused" in check) {
313+
outcome = "refused";
314+
return errorText(check.refused);
315+
}
268316
confirmationId = check.id;
269317
if ("denied" in check) {
270318
outcome = "user_denied";
@@ -288,7 +336,7 @@ export function withMcpToolAuth<TArgs>(
288336
check.message
289337
);
290338
}
291-
confirmation = { id: check.id };
339+
confirmation = { id: check.id, preview: check.preview };
292340
}
293341

294342
const result = await handler(args, {
@@ -300,7 +348,13 @@ export function withMcpToolAuth<TArgs>(
300348
requestId: extra.requestId,
301349
confirmation,
302350
});
303-
outcome = result.isError ? "error" : confirmation ? "confirmed" : "ok";
351+
outcome = staleResults.has(result)
352+
? "stale"
353+
: result.isError
354+
? "error"
355+
: confirmation
356+
? "confirmed"
357+
: "ok";
304358
return result;
305359
} catch (error) {
306360
if (error instanceof UrlElicitationRequiredError) throw error;

‎apps/webapp/app/mcp/registry.server.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ import { sessionsWriteTools } from "./tools/sessionsWrite.server";
3838
import { tasksWriteTools } from "./tools/tasksWrite.server";
3939
import { webhooksWriteTools } from "./tools/webhooksWrite.server";
4040

41+
export type McpApprovalClass = "required" | "configurable" | "none";
42+
4143
export type McpToolDefinition = {
4244
name: string;
4345
title?: string;
@@ -46,6 +48,7 @@ export type McpToolDefinition = {
4648
annotations?: ToolAnnotations;
4749
/** The gate holds the call for user confirmation. */
4850
confirm?: boolean;
51+
approval?: McpApprovalClass;
4952
auth?: McpToolAuth;
5053
handler: (
5154
args: unknown,

‎apps/webapp/app/mcp/tools/agentChat.server.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ import {
5050
type McpToolContext,
5151
type McpToolResult,
5252
} from "../gate/withMcpToolAuth.server";
53-
import type { McpToolDefinition } from "../registry.server";
53+
import type { McpApprovalClass, McpToolDefinition } from "../registry.server";
5454
import { errorResult, resolveToolEnvironment, textResult } from "./define.server";
5555
import { defineWriteTool, fencedError } from "./defineWrite.server";
5656
import {
@@ -625,6 +625,7 @@ export function createAgentChatTools(options: AgentChatToolsOptions = {}): McpTo
625625
title: string;
626626
description: string;
627627
shape: S;
628+
approval: McpApprovalClass;
628629
missing: (chatId: string) => McpToolResult;
629630
run: (
630631
input: z.output<z.ZodObject<S>>,
@@ -681,6 +682,7 @@ export function createAgentChatTools(options: AgentChatToolsOptions = {}): McpTo
681682
inputSchema: tool.shape,
682683
annotations: { title: tool.title, readOnlyHint: false, destructiveHint: true },
683684
confirm: requiresApproval(auth) !== false,
685+
approval: tool.approval,
684686
auth,
685687
handler: async (args, identity, request, extra) => {
686688
const parsed = schema.safeParse(args ?? {});
@@ -700,6 +702,7 @@ export function createAgentChatTools(options: AgentChatToolsOptions = {}): McpTo
700702
description:
701703
"Start a conversation with a chat agent. Returns a chatId you can use with send_agent_message. Optionally preloads the agent so it initializes before the first message.",
702704
shape: StartAgentChatInput.shape,
705+
approval: "configurable",
703706
auth: { action: "write", subject: "sessions" },
704707
run: async (input, ctx) => {
705708
const environment = await resolveToolEnvironment(ctx);
@@ -783,6 +786,7 @@ export function createAgentChatTools(options: AgentChatToolsOptions = {}): McpTo
783786
description:
784787
"Send a message to an active agent chat and get the full response text back. Use the chatId from start_agent_chat. The agent remembers full context from previous messages in the same chat.",
785788
shape: SendAgentMessageInput.shape,
789+
approval: "none",
786790
missing: (chatId) => noActiveChat(chatId, " Use start_agent_chat first."),
787791
run: async (input, handle, ctx) => {
788792
const environment = await resolveToolEnvironment(ctx);
@@ -816,6 +820,7 @@ export function createAgentChatTools(options: AgentChatToolsOptions = {}): McpTo
816820
description:
817821
"Close an agent chat conversation. The agent exits its loop gracefully. Without this, the agent will close on its own when its idle timeout expires.",
818822
shape: CloseAgentChatInput.shape,
823+
approval: "none",
819824
missing: (chatId) => noActiveChat(chatId),
820825
run: async (input, handle, ctx) => {
821826
const environment = await resolveToolEnvironment(ctx);

‎apps/webapp/app/mcp/tools/alertsWrite.server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ export const alertsWriteTools: McpToolDefinition[] = [
9797
description:
9898
"Create a monitoring alert for a project. Use list_alert_capabilities first to find a capabilityKey and understand its condition shape.",
9999
shape: CreateAlertInput.shape,
100+
approval: "configurable",
100101
auth: { action: "write", subject: "alerts" },
101102
run: async (input, ctx) => {
102103
const project = await findMonitoringAlertsProject(input.projectRef!, ctx.identity.userId);
@@ -177,6 +178,7 @@ export const alertsWriteTools: McpToolDefinition[] = [
177178
description:
178179
"Resolve a monitoring alert that needs attention, acknowledging it. The alert re-arms after resolving.",
179180
shape: ResolveAlertInput.shape,
181+
approval: "configurable",
180182
auth: { action: "write", subject: "alerts" },
181183
run: async (input, ctx) => {
182184
const project = await findMonitoringAlertsProject(input.projectRef!, ctx.identity.userId);

‎apps/webapp/app/mcp/tools/dashboardsWrite.server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export const dashboardsWriteTools: McpToolDefinition[] = [
4949
description:
5050
"Create a custom metrics dashboard, optionally with widgets. Each widget has a title, a TRQL query (use get_query_schema to see the tables and columns, and the query tool to try a query first), and a display: a table, a chart (bar or line, with x-axis and y-axis columns), a big number, or a title section header. Widgets without a position are stacked full width in order. Returns the dashboard id.",
5151
shape: CreateDashboardInput.shape,
52+
approval: "configurable",
5253
auth: { action: "write", subject: "query" },
5354
run: async (input, ctx) => {
5455
const environment = await subjectEnvironment(ctx);
@@ -80,6 +81,7 @@ export const dashboardsWriteTools: McpToolDefinition[] = [
8081
description:
8182
"Replace every widget on a custom dashboard with the given list, and optionally rename it. A widget that already exists keeps its position unless you pass a new one; new widgets without a position are stacked full width below the others. Use list_dashboards to find the dashboard id.",
8283
shape: SetDashboardWidgetsInput.shape,
84+
approval: "configurable",
8385
auth: { action: "write", subject: "query" },
8486
run: async (input, ctx) => {
8587
const environment = await subjectEnvironment(ctx);

0 commit comments

Comments
 (0)