Skip to content

Commit 5bc4bb4

Browse files
kathiekiwiTrigger.dev RepoOps
authored andcommitted
feat(mcp): session update and close tools for the MCP server
Mono-RevId: 1d6e956582ef615b9e645d366f112f426d3646f7
1 parent 908950d commit 5bc4bb4

13 files changed

Lines changed: 1176 additions & 119 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
area: webapp
3+
type: feature
4+
---
5+
6+
The remote MCP server can now change a session's tags and metadata, and close a session, after you confirm it.

‎apps/webapp/app/mcp/tools/format/webhooks.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ const ENDPOINT_ID = /^wh_[a-z0-9]{1,64}$/;
2121
const WAITPOINT_ID = /^waitpoint_[a-z0-9]{1,64}$/;
2222
const CURSOR = /^[A-Za-z0-9_-]{1,2000}$/;
2323

24-
const PREVIEW_UNSAFE =
24+
export const PREVIEW_UNSAFE =
2525
/[\u007f-\u009f\u061c\u200b-\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/g;
2626

2727
export function quoteForPreview(text: string): string {

‎apps/webapp/app/mcp/tools/schemas/sessions.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,29 @@ export const ReadSessionTranscriptInput = CommonProjectsInput.extend({
125125
.default(20),
126126
});
127127

128+
export const UpdateSessionInput = CommonProjectsInput.extend({
129+
sessionId: SessionIdInput,
130+
tags: z
131+
.array(z.string().max(128))
132+
.max(10)
133+
.describe("Replaces all of the session's tags. Up to 10, each up to 128 characters.")
134+
.optional(),
135+
metadata: z
136+
.record(z.string(), z.unknown())
137+
.nullable()
138+
.describe("Replaces the session's metadata in full. Pass null to clear it.")
139+
.optional(),
140+
});
141+
142+
export type UpdateSessionInput = z.output<typeof UpdateSessionInput>;
143+
144+
export const CloseSessionInput = CommonProjectsInput.extend({
145+
sessionId: SessionIdInput,
146+
reason: z.string().max(256).describe("Why the session is closed, stored with it.").optional(),
147+
});
148+
149+
export type CloseSessionInput = z.output<typeof CloseSessionInput>;
150+
128151
export const ListPlaygroundConversationsInput = CommonProjectsInput.extend({
129152
agentSlug: z
130153
.string()

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

Lines changed: 212 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,184 @@
11
import { tryCatch } from "@trigger.dev/core/utils";
22
import type { Session } from "@trigger.dev/database";
33
import { nanoid } from "nanoid";
4+
import { prisma } from "~/db.server";
45
import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
56
import { S2RealtimeStreams } from "~/services/realtime/s2realtimeStreams.server";
67
import { SESSION_CHANNEL_NAME_REGEX } from "~/services/realtime/sessionChannels.server";
78
import {
89
canonicalSessionAddressingKey,
10+
resolveSessionByIdOrExternalId,
911
resolveSessionWithWriterFallback,
1012
} from "~/services/realtime/sessions.server";
13+
import { closeSession, sessionUpdateData } from "~/services/realtime/sessionWrites.server";
1114
import { getRealtimeStreamInstance } from "~/services/realtime/v1StreamsGlobal.server";
1215
import { ServiceValidationError } from "~/v3/services/common.server";
16+
import { canonicalJson } from "../confirm/confirmation.server";
17+
import type { McpPreviewRefusal, McpSubject } from "../gate/types";
18+
import type { McpToolContext, McpToolResult } from "../gate/withMcpToolAuth.server";
1319
import type { McpToolDefinition } from "../registry.server";
1420
import { errorResult, resolveToolEnvironment, textResult } from "./define.server";
15-
import { defineWriteTool } from "./defineWrite.server";
16-
import { WriteSessionChannelInput } from "./schemas/sessions";
21+
import { defineWriteTool, staleAnswer, staleApproval } from "./defineWrite.server";
22+
import { plainError } from "./format/insights";
23+
import { capText } from "./format/logFields";
24+
import { renderSessionId } from "./format/sessions";
25+
import { PREVIEW_UNSAFE, quoteForPreview } from "./format/webhooks";
26+
import { startReadBudget } from "./readBudget.server";
27+
import {
28+
CloseSessionInput,
29+
UpdateSessionInput,
30+
WriteSessionChannelInput,
31+
} from "./schemas/sessions";
32+
33+
const auth = { action: "write", subject: "sessions" } as const;
34+
35+
const READ_BUDGET_MS = 10_000;
36+
const SHOWN_CHARS = 16_000;
37+
const STOPPED = {
38+
aborted: "The request was cancelled before the session was read; nothing changed.",
39+
timeout: "Reading the session took too long; nothing changed. Try again.",
40+
};
41+
const SESSION_CHANGED =
42+
"The session was changed by another request before this ran; nothing changed. Call the tool again.";
43+
44+
const CLOSED_UPDATE = "the session stays closed; only its tags and metadata change.";
45+
46+
const NOTIFIED = {
47+
true: " A close message was sent on the session's input; a run waiting on it stops when it handles the message.",
48+
false: " The close message could not be sent on the session's input.",
49+
undefined: "",
50+
};
51+
52+
type Read = ReturnType<typeof startReadBudget>["read"];
53+
type Plan<T> = { preview: string; value: T } | McpPreviewRefusal;
54+
type Build<A, T> = (args: A, environmentId: string, read: Read) => Promise<Plan<T>>;
55+
56+
const sessionNotFound = (id: string) =>
57+
`Session ${renderSessionId(id)} not found in this environment; list_sessions lists the sessions in this environment. Nothing changed.`;
58+
59+
const revisionLine = (session: { updatedAt: Date }) =>
60+
`Session revision ${session.updatedAt.toISOString()}: if the session changes before this runs, it is refused.`;
61+
62+
const previewJson = (value: unknown) =>
63+
canonicalJson(value).replace(
64+
PREVIEW_UNSAFE,
65+
(c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`
66+
);
67+
68+
function shown(value: unknown) {
69+
if (value === null || value === undefined) return "none";
70+
return capText(previewJson(value), SHOWN_CHARS);
71+
}
72+
73+
const shownTags = (tags: string[]) => (tags.length === 0 ? "none" : shown(tags));
74+
75+
async function findSession(
76+
environmentId: string,
77+
sessionId: string,
78+
read: Read
79+
): Promise<{ session: Session } | McpPreviewRefusal> {
80+
const found = await read(() => resolveSessionByIdOrExternalId(prisma, environmentId, sessionId));
81+
if (!found.ok) return { refuse: STOPPED[found.reason] };
82+
if (!found.value) return { refuse: sessionNotFound(sessionId) };
83+
return { session: found.value };
84+
}
85+
86+
const sessionLabel = (session: Session) =>
87+
`session ${session.friendlyId} of agent ${quoteForPreview(session.taskIdentifier)}`;
88+
89+
async function updatePlan(
90+
args: UpdateSessionInput,
91+
environmentId: string,
92+
read: Read
93+
): Promise<Plan<Session>> {
94+
if (args.tags === undefined && args.metadata === undefined) {
95+
return { refuse: "No changes given: pass tags, metadata or both; nothing changed." };
96+
}
97+
if (args.metadata && previewJson(args.metadata).length > SHOWN_CHARS) {
98+
return {
99+
refuse: `This metadata is too large to show in full for approval (the limit is ${SHOWN_CHARS.toLocaleString("en-US")} characters). Send smaller metadata; nothing changed.`,
100+
};
101+
}
102+
const found = await findSession(environmentId, args.sessionId, read);
103+
if ("refuse" in found) return found;
104+
const { session } = found;
105+
106+
const changes = [
107+
...(args.tags !== undefined && canonicalJson(args.tags) !== canonicalJson(session.tags)
108+
? [`- Tags: ${shownTags(session.tags)} → ${shownTags(args.tags)}`]
109+
: []),
110+
...(args.metadata !== undefined &&
111+
canonicalJson(args.metadata) !== canonicalJson(session.metadata ?? null)
112+
? [`- Metadata, replaced in full: ${shown(session.metadata)} → ${shown(args.metadata)}`]
113+
: []),
114+
];
115+
if (changes.length === 0) {
116+
return {
117+
refuse: `Session ${session.friendlyId} already has these tags and metadata; nothing changed.`,
118+
};
119+
}
120+
121+
const lines = [
122+
`Update ${sessionLabel(session)}:`,
123+
...changes,
124+
...(session.closedAt ? [`It is closed; ${CLOSED_UPDATE}`] : []),
125+
"Its external ID, status and runs do not change.",
126+
revisionLine(session),
127+
];
128+
return { preview: lines.join("\n"), value: session };
129+
}
130+
131+
async function closePlan(
132+
args: CloseSessionInput,
133+
environmentId: string,
134+
read: Read
135+
): Promise<Plan<Session>> {
136+
const found = await findSession(environmentId, args.sessionId, read);
137+
if ("refuse" in found) return found;
138+
const { session } = found;
139+
if (session.closedAt) {
140+
return { refuse: `Session ${session.friendlyId} is already closed; nothing changed.` };
141+
}
142+
143+
const lines = [
144+
`Close ${sessionLabel(session)} for good. A closed session can't be reopened: it accepts no more input and starts no more runs.`,
145+
session.currentRunId
146+
? "A close message is sent on the session's input; a run waiting on it stops when it handles the message. This is best effort: the session is closed even if the message can't be sent."
147+
: "It has no current run, so no run is told.",
148+
`Reason: ${args.reason ? quoteForPreview(args.reason) : "none"}`,
149+
revisionLine(session),
150+
];
151+
return { preview: lines.join("\n"), value: session };
152+
}
153+
154+
function planPreview<A>(build: Build<A, unknown>) {
155+
return async (args: A, subject: McpSubject | null) => {
156+
if (!subject?.projectId || !subject.environmentId) return { refuse: "Environment not found" };
157+
// The gate gives a preview no request signal, so only the deadline can stop its reads.
158+
const { read } = startReadBudget(READ_BUDGET_MS, new AbortController().signal);
159+
const plan = await build(args, subject.environmentId, read);
160+
return "refuse" in plan ? plan : plan.preview;
161+
};
162+
}
163+
164+
async function runPlan<A, T>(
165+
args: A,
166+
ctx: McpToolContext,
167+
build: Build<A, T>,
168+
act: (value: T, environment: AuthenticatedEnvironment) => Promise<McpToolResult>
169+
) {
170+
const { read } = startReadBudget(READ_BUDGET_MS, ctx.signal);
171+
const found = await read(() => resolveToolEnvironment(ctx));
172+
if (!found.ok) return plainError(STOPPED[found.reason]);
173+
if (!found.value) return plainError("Environment not found");
174+
const plan = await build(args, found.value.id, read);
175+
if ("refuse" in plan) return plainError(plan.refuse);
176+
return staleApproval(ctx, plan.preview, plainError) ?? act(plan.value, found.value);
177+
}
178+
179+
/** A write refused because the session changed: stale for an approved call, plain otherwise. */
180+
const changedAnswer = (ctx: McpToolContext) =>
181+
ctx.confirmation ? staleAnswer(plainError) : plainError(SESSION_CHANGED);
17182

18183
type AppendChannelRecord = (
19184
environment: AuthenticatedEnvironment,
@@ -86,6 +251,51 @@ export function createSessionsWriteTools(
86251
);
87252
},
88253
}),
254+
defineWriteTool({
255+
name: "update_session",
256+
title: "Update Session",
257+
description:
258+
"Replace a session's tags, its metadata, or both, like the public API's session update. Omitted fields keep their values; pass metadata null to clear it. This also works on a closed session. The external ID can't be changed.",
259+
shape: UpdateSessionInput.shape,
260+
approval: "configurable",
261+
auth,
262+
confirm: { preview: planPreview(updatePlan) },
263+
run: (input, ctx) =>
264+
runPlan(input, ctx, updatePlan, async (session) => {
265+
const { count } = await prisma.session.updateMany({
266+
where: { id: session.id, updatedAt: session.updatedAt },
267+
data: sessionUpdateData({ tags: input.tags, metadata: input.metadata }),
268+
});
269+
if (count === 0) return changedAnswer(ctx);
270+
return textResult(
271+
`Updated session ${session.friendlyId}.${session.closedAt ? ` ${CLOSED_UPDATE}` : ""}`
272+
);
273+
}),
274+
}),
275+
defineWriteTool({
276+
name: "close_session",
277+
title: "Close Session",
278+
description:
279+
"Close a session for good, like the public API's session close. It accepts no more input and starts no more runs, and its current run is asked to stop (best effort). Optionally record a reason.",
280+
shape: CloseSessionInput.shape,
281+
approval: "configurable",
282+
auth,
283+
confirm: { preview: planPreview(closePlan) },
284+
run: (input, ctx) =>
285+
runPlan(input, ctx, closePlan, async (session, environment) => {
286+
const { closed, notified } = await closeSession({
287+
session,
288+
environment,
289+
paramSession: input.sessionId,
290+
reason: input.reason,
291+
revision: session.updatedAt,
292+
});
293+
if (!closed) return changedAnswer(ctx);
294+
return textResult(
295+
`Closed session ${session.friendlyId}.${NOTIFIED[String(notified) as keyof typeof NOTIFIED]}`
296+
);
297+
}),
298+
}),
89299
];
90300
}
91301

0 commit comments

Comments
 (0)