Skip to content

Commit 084baeb

Browse files
kathiekiwiTrigger.dev RepoOps
authored andcommitted
feat(mcp): delete a playground conversation from the MCP server
Mono-RevId: 31090ef4e61dcacb47f4ea4627b718fdb8eb723b
1 parent dda6e92 commit 084baeb

15 files changed

Lines changed: 546 additions & 13 deletions
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 delete one of your playground conversations after you confirm it.

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,18 +65,20 @@ export async function confirmationPreview(
6565
args: unknown,
6666
subject: McpSubject | null,
6767
fingerprintKey?: string,
68-
ability?: RbacAbility
68+
ability?: RbacAbility,
69+
identity?: McpIdentity
6970
): Promise<{ preview: string; truncated: boolean } | McpPreviewRefusal>;
7071
export async function confirmationPreview(
7172
tool: string,
7273
spec: true | McpConfirmSpec,
7374
args: unknown,
7475
subject: McpSubject | null,
7576
fingerprintKey?: string,
76-
ability?: RbacAbility
77+
ability?: RbacAbility,
78+
identity?: McpIdentity
7779
): Promise<{ preview: string; truncated: boolean } | McpPreviewRefusal> {
7880
if (spec !== true) {
79-
const preview = await spec.preview(args, subject, ability);
81+
const preview = await spec.preview(args, subject, ability, identity);
8082
if (typeof preview !== "string") return preview;
8183
if (preview.length > PREVIEW_LIMIT) {
8284
return {

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ export type McpConfirmSpec<A = unknown> = {
3232
preview: (
3333
args: A,
3434
subject: McpSubject | null,
35-
ability?: RbacAbility
35+
ability?: RbacAbility,
36+
identity?: McpIdentity
3637
) => string | McpPreviewRefusal | Promise<string | McpPreviewRefusal>;
3738
};
3839

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,15 @@ async function confirm(
247247
const consumed = await store.consumeApproved(lookup);
248248
if (consumed) return { approved: true, id: consumed.id, preview: consumed.preview };
249249

250-
const preview = await confirmationPreview(tool, spec, args, subject, undefined, ability);
250+
const preview = await confirmationPreview(
251+
tool,
252+
spec,
253+
args,
254+
subject,
255+
undefined,
256+
ability,
257+
identity
258+
);
251259
if ("refuse" in preview) return { approved: false, refused: preview.refuse };
252260

253261
const created = await store.createPending({

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import { dashboardsWriteTools } from "./tools/dashboardsWrite.server";
5959
import { errorsWriteTools } from "./tools/errorsWrite.server";
6060
import { feedbackTools } from "./tools/feedback.server";
6161
import { orgsWriteTools } from "./tools/orgsWrite.server";
62+
import { playgroundWriteTools } from "./tools/playgroundWrite.server";
6263
import { promptsWriteTools } from "./tools/promptsWrite.server";
6364
import { runsEditTools } from "./tools/runsEdit.server";
6465
import { runsWriteTools } from "./tools/runsWrite.server";
@@ -146,6 +147,7 @@ export const mcpTools: McpToolDefinition[] = assertUniqueToolNames([
146147
...dashboardsEditTools,
147148
...feedbackTools,
148149
...orgsWriteTools,
150+
...playgroundWriteTools,
149151
...promptsWriteTools,
150152
...runsWriteTools,
151153
...runsEditTools,
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import type { RbacAbility } from "@trigger.dev/rbac";
2+
import { prisma } from "~/db.server";
3+
import { deletePlaygroundConversation } from "~/models/playgroundConversation.server";
4+
import type { McpIdentity, McpPreviewRefusal, McpSubject } from "../gate/types";
5+
import type { McpToolContext } from "../gate/withMcpToolAuth.server";
6+
import type { McpToolDefinition } from "../registry.server";
7+
import { textResult } from "./define.server";
8+
import { defineWriteTool, staleAnswer, staleApproval } from "./defineWrite.server";
9+
import { plainError } from "./format/insights";
10+
import { capText, untrusted } from "./format/logFields";
11+
import { quoteForPreview } from "./format/webhooks";
12+
import { startReadBudget } from "./readBudget.server";
13+
import {
14+
DeletePlaygroundConversationInput,
15+
type DeletePlaygroundConversationInput as DeleteArgs,
16+
} from "./schemas/sessions";
17+
18+
const READ_BUDGET_MS = 10_000;
19+
const TEXT_CHARS = 200;
20+
const STOPPED = {
21+
aborted: "The request was cancelled before the conversation was read; nothing changed.",
22+
timeout: "Reading the conversation took too long; nothing changed. Try again.",
23+
};
24+
type Read = ReturnType<typeof startReadBudget>["read"];
25+
type Conversation = NonNullable<Awaited<ReturnType<typeof findConversation>>>;
26+
type Scope = { environmentId: string; userId: string };
27+
28+
const notFound = (chatId: string) =>
29+
`No playground conversation of yours with chat id ${untrusted(chatId, "playground-chat-id", 256)} in this environment; list_playground_conversations lists them; nothing changed.`;
30+
31+
const quoted = (text: string) => quoteForPreview(capText(text, TEXT_CHARS));
32+
33+
function findConversation(scope: Scope, chatId: string) {
34+
return prisma.playgroundConversation.findFirst({
35+
where: { chatId, runtimeEnvironmentId: scope.environmentId, userId: scope.userId },
36+
select: {
37+
id: true,
38+
chatId: true,
39+
title: true,
40+
agentSlug: true,
41+
createdAt: true,
42+
updatedAt: true,
43+
},
44+
});
45+
}
46+
47+
async function deletePlan(
48+
args: DeleteArgs,
49+
scope: Scope,
50+
read: Read
51+
): Promise<{ preview: string; conversation: Conversation } | McpPreviewRefusal> {
52+
const found = await read(() => findConversation(scope, args.chatId));
53+
if (!found.ok) return { refuse: STOPPED[found.reason] };
54+
const conversation = found.value;
55+
if (!conversation) return { refuse: notFound(args.chatId) };
56+
57+
const preview = [
58+
`Delete your playground conversation ${quoted(conversation.title)} with agent ${quoted(conversation.agentSlug)}, chat id ${quoted(conversation.chatId)}, created ${conversation.createdAt.toISOString()}.`,
59+
"This cannot be undone. It removes the conversation from the playground list with its title and the messages and client data saved with it.",
60+
"The session behind it, its runs and its saved transcript are kept.",
61+
`Conversation revision ${conversation.updatedAt.toISOString()}: if the conversation changes before this runs, it is refused.`,
62+
].join("\n");
63+
return { preview, conversation };
64+
}
65+
66+
async function preview(
67+
args: DeleteArgs,
68+
subject: McpSubject | null,
69+
_ability?: RbacAbility,
70+
identity?: McpIdentity
71+
) {
72+
if (!subject?.projectId || !subject.environmentId || !identity) {
73+
return { refuse: "Environment not found" };
74+
}
75+
// The gate gives a preview no request signal, so only the deadline can stop its reads.
76+
const { read } = startReadBudget(READ_BUDGET_MS, new AbortController().signal);
77+
const plan = await deletePlan(
78+
args,
79+
{ environmentId: subject.environmentId, userId: identity.userId },
80+
read
81+
);
82+
return "refuse" in plan ? plan : plan.preview;
83+
}
84+
85+
async function run(args: DeleteArgs, ctx: McpToolContext) {
86+
const environmentId = ctx.subject?.projectId ? ctx.subject.environmentId : undefined;
87+
if (!environmentId) return plainError("Environment not found");
88+
89+
const { read } = startReadBudget(READ_BUDGET_MS, ctx.signal);
90+
const scope = { environmentId, userId: ctx.identity.userId };
91+
const plan = await deletePlan(args, scope, read);
92+
if ("refuse" in plan) return plainError(plan.refuse);
93+
const stale = staleApproval(ctx, plan.preview, plainError);
94+
if (stale) return stale;
95+
96+
const { conversation } = plan;
97+
const { count } = await deletePlaygroundConversation(
98+
{ id: conversation.id, runtimeEnvironmentId: scope.environmentId, userId: scope.userId },
99+
conversation.updatedAt
100+
);
101+
if (count === 0) return staleAnswer(plainError);
102+
return textResult(
103+
`Deleted playground conversation ${untrusted(conversation.title, "playground-title", TEXT_CHARS)} (chat id ${untrusted(conversation.chatId, "playground-chat-id", 256)}).`
104+
);
105+
}
106+
107+
export const playgroundWriteTools: McpToolDefinition[] = [
108+
defineWriteTool({
109+
name: "delete_playground_conversation",
110+
title: "Delete Playground Conversation",
111+
description:
112+
"Delete one of your own playground conversations, like the delete button in the agent's Playground conversation list. It removes the conversation and its saved messages from the playground; the session behind it and its runs are kept. It cannot be undone.",
113+
shape: DeletePlaygroundConversationInput.shape,
114+
approval: "required",
115+
auth: { action: "write", subject: "sessions" },
116+
confirm: { preview },
117+
run,
118+
}),
119+
];

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,3 +162,13 @@ export const ListPlaygroundConversationsInput = CommonProjectsInput.extend({
162162
.describe("How many to return, up to 10 (default 10).")
163163
.optional(),
164164
});
165+
166+
export const DeletePlaygroundConversationInput = CommonProjectsInput.extend({
167+
chatId: z
168+
.string()
169+
.min(1)
170+
.max(256)
171+
.describe("The conversation's chat id. Use list_playground_conversations to find it."),
172+
});
173+
174+
export type DeletePlaygroundConversationInput = z.output<typeof DeletePlaygroundConversationInput>;
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { prisma } from "~/db.server";
2+
3+
/**
4+
* Deletes the user's own playground conversation row in the environment. Only the row goes:
5+
* its session and runs stay. With `revision`, only while it is still at that revision.
6+
*/
7+
export function deletePlaygroundConversation(
8+
conversation: { id: string; runtimeEnvironmentId: string; userId: string },
9+
revision?: Date
10+
) {
11+
return prisma.playgroundConversation.deleteMany({
12+
where: { ...conversation, ...(revision ? { updatedAt: revision } : {}) },
13+
});
14+
}

‎apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.playground.action.tsx‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { z } from "zod";
44
import type { Prisma } from "@trigger.dev/database";
55
import { SessionId } from "@trigger.dev/core/v3/isomorphic";
66
import { prisma } from "~/db.server";
7+
import { deletePlaygroundConversation } from "~/models/playgroundConversation.server";
78
import { findProjectBySlug } from "~/models/project.server";
89
import { findEnvironmentBySlug } from "~/models/runtimeEnvironment.server";
910
import { requireUserId } from "~/services/session.server";
@@ -310,12 +311,10 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
310311
return json({ error: "deleteConversationId is required" }, { status: 400 });
311312
}
312313

313-
await prisma.playgroundConversation.deleteMany({
314-
where: {
315-
id: deleteConversationId,
316-
runtimeEnvironmentId: environment.id,
317-
userId,
318-
},
314+
await deletePlaygroundConversation({
315+
id: deleteConversationId,
316+
runtimeEnvironmentId: environment.id,
317+
userId,
319318
});
320319

321320
return json({ ok: true });

‎apps/webapp/app/services/oauth/consent.server.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ const SCOPE_LABEL_OVERRIDES: Record<string, string> = {
9090
"write:projects": "Create projects",
9191
"write:query": "Run queries",
9292
"write:runs": "Cancel and replay runs",
93-
"write:sessions": "Send to and end agent sessions, and change their tags and metadata",
93+
"write:sessions":
94+
"Send to and end agent sessions, change their tags and metadata, and delete your playground conversations",
9495
"write:tasks": "Manage tasks",
9596
"write:waitpoints": "Complete waitpoints",
9697
"write:webhooks": "Manage webhooks",

0 commit comments

Comments
 (0)