Skip to content

Commit 306fd5d

Browse files
kathiekiwiTrigger.dev RepoOps
authored andcommitted
feat(cli): find the project of a run from its ID in MCP read tools
Mono-RevId: 9a4eaf4c58c94b4098ee45ce73803ec5cbd74fc3
1 parent 3b3b517 commit 306fd5d

11 files changed

Lines changed: 914 additions & 53 deletions

File tree

‎.changeset/mcp-run-id-project.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"trigger.dev": patch
3+
---
4+
5+
MCP run tools find a run's project and environment from its run ID.

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,22 @@ export async function withoutRefused<T>(
1818
};
1919
}
2020

21-
export async function listUsableProjects(identity: McpIdentity) {
22-
const memberProjects = await prisma.project.findMany({
21+
export function memberProjects(userId: string) {
22+
return prisma.project.findMany({
2323
where: {
2424
organization: {
2525
deletedAt: null,
26-
members: { some: { userId: identity.userId } },
26+
members: { some: { userId } },
2727
},
2828
version: "V3",
2929
deletedAt: null,
3030
},
3131
include: { organization: true },
3232
orderBy: [{ organizationId: "asc" }, { createdAt: "asc" }, { id: "asc" }],
3333
});
34-
return withoutRefused(memberProjects, (project) => project.organizationId, identity);
34+
}
35+
36+
export async function listUsableProjects(identity: McpIdentity) {
37+
const projects = await memberProjects(identity.userId);
38+
return withoutRefused(projects, (project) => project.organizationId, identity);
3539
}

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import { isReadReplicaClient } from "@internal/run-store";
22
import type { RuntimeEnvironmentType } from "@trigger.dev/database";
33
import { $replica } from "~/db.server";
4+
import { authenticatedEnvironmentForAuthentication } from "~/services/apiAuth.server";
5+
import { authorizePatEnvironmentAccess } from "~/services/environmentVariableApiAccess.server";
6+
import { rbac } from "~/services/rbac.server";
47
import { runStore } from "~/v3/runStore.server";
8+
import { memberProjects } from "./projectsList.server";
59

610
const replicaReadClient = <T>(client: T): T | undefined =>
711
isReadReplicaClient(client) ? client : undefined;
@@ -56,3 +60,53 @@ export async function findRunEnvironment(
5660
branch: environment.parentEnvironmentId ? (environment.branchName ?? undefined) : undefined,
5761
};
5862
}
63+
64+
// Answers only where the env JWT route would mint for this user; a thrown Response means no.
65+
export async function locateRunForUser(
66+
runId: string,
67+
userId: string,
68+
request: Request,
69+
reads: RunReads = productionReads()
70+
) {
71+
const projects = await memberProjects(userId);
72+
const projectId = await findRunProjectId(
73+
runId,
74+
projects.map(({ id }) => id),
75+
reads
76+
);
77+
const project = projects.find(({ id }) => id === projectId);
78+
if (!project) return null;
79+
80+
const found = await findRunEnvironment(runId, project.id, reads);
81+
if (!found) return null;
82+
83+
const environment = await authenticatedEnvironmentForAuthentication(
84+
{ type: "personalAccessToken", result: { userId } },
85+
project.externalRef,
86+
found.environment,
87+
found.branch,
88+
{ organizationScoped: true }
89+
);
90+
if (environment.id !== found.environmentId) return null;
91+
92+
const scope = { organizationId: environment.organizationId, projectId: environment.project.id };
93+
const denied = await authorizePatEnvironmentAccess({
94+
request,
95+
authType: "personalAccessToken",
96+
...scope,
97+
envType: environment.type,
98+
resource: "apiKeys",
99+
action: "read",
100+
});
101+
if (denied) return null;
102+
const scoped = await rbac.authenticatePat(request, scope);
103+
if (!scoped.ok || !scoped.ability.can("read", { type: "runs", envType: environment.type })) {
104+
return null;
105+
}
106+
107+
return {
108+
projectRef: project.externalRef,
109+
environment: found.environment,
110+
...(found.branch === undefined ? {} : { branch: found.branch }),
111+
};
112+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { json } from "@remix-run/server-runtime";
2+
import { isUserActorToken } from "@trigger.dev/rbac";
3+
import { z } from "zod";
4+
import { locateRunForUser } from "~/mcp/tools/runEnvironment.server";
5+
import { logger } from "~/services/logger.server";
6+
import {
7+
boundaryErrorLogValue,
8+
createLoaderPATApiRoute,
9+
} from "~/services/routeBuilders/apiBuilder.server";
10+
import { unroutableIdResponse } from "~/services/routeBuilders/unroutableId.server";
11+
import { sanitizeHttpUrl } from "~/utils/sanitizeHttpUrl";
12+
13+
const notFound = () => json({ error: "Run not found" }, { status: 404 });
14+
15+
export const loader = createLoaderPATApiRoute(
16+
{ params: z.object({ runId: z.string() }) },
17+
async ({ request, params, authentication }) => {
18+
const bearer = request.headers
19+
.get("Authorization")
20+
?.replace(/^Bearer /, "")
21+
.trim();
22+
if (bearer && isUserActorToken(bearer)) return notFound();
23+
24+
try {
25+
const located = await locateRunForUser(params.runId, authentication.userId, request);
26+
return located ? json(located) : notFound();
27+
} catch (error) {
28+
if (error instanceof Response) return notFound();
29+
if (unroutableIdResponse(error)) {
30+
logger.error("Unroutable id", {
31+
error: boundaryErrorLogValue(error),
32+
url: sanitizeHttpUrl(request.url),
33+
});
34+
return notFound();
35+
}
36+
logger.error("Failed to look up the project of a run", { error });
37+
return json({ error: "Internal Server Error" }, { status: 500 });
38+
}
39+
}
40+
);

0 commit comments

Comments
 (0)