Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 160 additions & 16 deletions apps/server/src/mcp/toolkits/project/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type { Json } from "effect/Schema";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
Expand Down Expand Up @@ -61,6 +62,8 @@ const clientLaunchHarness = (input: {
readonly overrideModel?: ModelSelection;
readonly overrideScripts?: readonly ProjectScript[];
readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
/** The threads service the caller supplies, instead of the harness's own. */
readonly threads?: Layer.Layer<ThreadManagement.ThreadManagementService>;
readonly workspaceRoot?: string;
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
readonly hostedAppUrl?: string;
Expand Down Expand Up @@ -119,22 +122,23 @@ const clientLaunchHarness = (input: {
issuedAt: 0,
capabilities: new Set(["orchestration" as const]),
}),
Layer.mock(ThreadManagement.ThreadManagementService)({
// A thread exists once a launch started it.
getThreadShell: (threadId) => {
const launch = input.launched.find((candidate) => candidate.threadId === threadId);
return Effect.succeed(
launch === undefined
? null
: ({
id: launch.threadId,
projectId: launch.projectId,
modelSelection: launch.modelSelection,
deletedAt: null,
} as unknown as OrchestrationV2ThreadShell),
);
},
}),
input.threads ??
Layer.mock(ThreadManagement.ThreadManagementService)({
// A thread exists once a launch started it.
getThreadShell: (threadId) => {
const launch = input.launched.find((candidate) => candidate.threadId === threadId);
return Effect.succeed(
launch === undefined
? null
: ({
id: launch.threadId,
projectId: launch.projectId,
modelSelection: launch.modelSelection,
deletedAt: null,
} as unknown as OrchestrationV2ThreadShell),
);
},
}),
Layer.mock(ThreadLaunch.ThreadLaunchService)({
checkWorktreeBase: input.checkWorktreeBase ?? (() => Effect.void),
launch: (launch) => {
Expand Down Expand Up @@ -1434,3 +1438,143 @@ it.effect("a project update or create that is refused tells the agent why", () =
expect(dropped.at(-1)?.result).toMatchObject({ code: "invalid_request" });
}),
);

it.effect("a launch's outcome is read back from the receipt its own key wrote", () =>
Effect.gen(function* () {
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
const { projectId } = clientLaunchHarness({
runtimeModeCeiling: "auto",
launched,
});
// The run the launch's thread carries, keyed by the thread the receipt names.
const runs = new Map<
ThreadId,
ReadonlyArray<{ id: string; userMessageId: string; status: string }>
>();
const { dependencies: base } = clientLaunchHarness({
runtimeModeCeiling: "auto",
launched,
threads: Layer.mock(ThreadManagement.ThreadManagementService)({
acceptedLaunchOf: (commandId) => {
const launch = launched.find((candidate) => candidate.commandId === commandId);
const threadId = launch?.threadId;
return Effect.succeed(threadId === undefined ? Option.none() : Option.some(threadId));
},
getThreadShell: (threadId) => {
const launch = launched.find((candidate) => candidate.threadId === threadId);
return Effect.succeed(
launch === undefined
? null
: ({
id: launch.threadId,
projectId: launch.projectId,
modelSelection: launch.modelSelection,
deletedAt: null,
} as unknown as OrchestrationV2ThreadShell),
);
},
getThreadRecords: (threadId: ThreadId) =>
Effect.succeed({ runs: runs.get(threadId) ?? [] } as unknown as never),
}),
});
const dependenciesWithReceipts = base;
const toolkit = yield* ProjectToolkit.pipe(
Effect.provide(
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
Layer.provide(dependenciesWithReceipts),
),
),
);
const call = (name: "t3_thread_launch" | "t3_launch_outcome", input: Json) =>
toolkit
.handle(name, input)
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependenciesWithReceipts));

// Nothing accepted under this key: the launch never happened, and nothing was started.
const before = yield* call("t3_launch_outcome", { clientRequestId: "fix-1" });
expect(before.at(-1)?.result).toEqual({
accepted: false,
threadId: null,
runId: null,
status: null,
terminal: null,
});
expect(launched).toHaveLength(0);

yield* call("t3_thread_launch", {
title: "Fix",
projectId,
message: "Fix the bug",
clientRequestId: "fix-1",
});
const started = launched[0];
const threadId = started?.threadId;
if (started === undefined || threadId === undefined) return;
runs.set(threadId, [{ id: "run:launch", userMessageId: started.commandId, status: "running" }]);

const running = yield* call("t3_launch_outcome", { clientRequestId: "fix-1" });
expect(running.at(-1)?.result).toEqual({
accepted: true,
threadId,
runId: "run:launch",
status: "running",
terminal: false,
});

runs.set(threadId, [
{ id: "run:launch", userMessageId: started.commandId, status: "completed" },
]);
const finished = yield* call("t3_launch_outcome", { clientRequestId: "fix-1" });
expect(finished.at(-1)?.result).toMatchObject({ status: "completed", terminal: true });

// A different key is a different launch, and reading it starts nothing.
const other = yield* call("t3_launch_outcome", { clientRequestId: "fix-2" });
expect(other.at(-1)?.result).toMatchObject({ accepted: false });
expect(launched).toHaveLength(1);
}),
);

it.effect("a placed launch's outcome is read on the environment its acknowledgement names", () =>
Effect.gen(function* () {
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
const { dependencies } = clientLaunchHarness({ runtimeModeCeiling: "auto", launched });
const there = EnvironmentId.make("environment:placed");
const forwarded: Array<{ tool: string; environmentId: EnvironmentId }> = [];
const dependenciesWithForwarding = Layer.mergeAll(
dependencies,
Layer.mock(PeerForwarding.PeerForwarding)({
call: (scope, tool, environmentId) => {
forwarded.push({ tool: tool.name, environmentId });
// The other environment's own answer. Nothing here is consulted for it.
return Effect.succeed({
accepted: true,
threadId: ThreadId.make("thread:there"),
runId: "run:there",
status: "completed",
terminal: true,
} as unknown as never);
},
}),
);
const toolkit = yield* ProjectToolkit.pipe(
Effect.provide(
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
Layer.provide(dependenciesWithForwarding),
),
),
);
const placed = yield* toolkit
.handle("t3_launch_outcome", { clientRequestId: "placed-1", environmentId: there })
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependenciesWithForwarding));

expect(placed.at(-1)?.result).toMatchObject({
accepted: true,
threadId: "thread:there",
status: "completed",
terminal: true,
});
// Followed to the named environment, and the launch was not started again here.
expect(forwarded).toEqual([{ tool: "t3_launch_outcome", environmentId: there }]);
expect(launched).toHaveLength(0);
}),
);
39 changes: 39 additions & 0 deletions apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
resolveLaunchOutcome,
unknownLaunchOutcome,
} from "../../../orchestration-v2/LaunchOutcome.ts";
import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
import { outputRequestProblem } from "../../../orchestration-v2/runOutput.ts";
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
Expand Down Expand Up @@ -426,6 +430,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
code: "invalid_request",
message: schemaProblem ?? "outputSchema needs a message that asks for the result.",
});
// The reservation is checked against the launch's first message; without one there is
// nothing to gate and the launch would start ungated.
if (input.reservation !== undefined && input.message === undefined)
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "reservation needs the message it authorizes. No thread was created.",
});
if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
Expand Down Expand Up @@ -665,6 +676,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
text: input.message ?? "",
attachments,
...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
...(input.reservation === undefined ? {} : { reservation: input.reservation }),
},
}),
createdBy: "agent",
Expand Down Expand Up @@ -741,6 +753,33 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
// The launched thread carries the caller's link, if it has one.
"stamped",
),
// The same command id the launch derived from this caller and key, so the receipt it wrote is
// the one read back. Naming an environment reads it there, through the toolkit's forwarding.
t3_launch_outcome: McpToolAccess.reads((input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const context = yield* readCaller();
const commandId = yield* launchCommandId(scope.requestNamespace, input.clientRequestId);
// The thread this command's accepted `thread.create` created. A receipt read that fails is
// a failure, not an unknown launch: unknown means the launch was not accepted.
const launched = yield* context.threads
.acceptedLaunchOf(commandId)
.pipe(Effect.mapError(unavailable));
if (Option.isNone(launched)) return unknownLaunchOutcome;
const records = yield* context.threads
.getThreadRecords(launched.value, ["runs"])
.pipe(Effect.mapError(unavailable));
return resolveLaunchOutcome({
receipt: Option.some({
status: "accepted",
commandType: "thread.create",
threadId: launched.value,
}),
runs: records.runs,
commandId,
});
}),
),
t3_project_list: McpToolAccess.reads((input) =>
Effect.gen(function* () {
const projects = yield* access;
Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/mcp/toolkits/project/tools.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { McpAttachmentInput } from "../attachment/input.ts";
import { LaunchOutcome } from "../../../orchestration-v2/LaunchOutcome.ts";
import {
clampedPositiveInt,
InboxChoiceParameter,
Expand All @@ -10,6 +11,7 @@ import {
ThreadId,
RunId,
OrchestrationV2DelegatedFrom,
OrchestrationV2LaunchReservation,
OrchestrationV2WorkflowOrigin,
OrchestrationV2RunStatus,
OrchestrationV2ThreadLaunchWorkspaceStrategy,
Expand Down Expand Up @@ -175,6 +177,12 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
description: "As in `t3_thread_send`. Needs `message`.",
}),
),
reservation: Schema.optional(
OrchestrationV2LaunchReservation.annotate({
description:
"The Linear reservation authorizing this launch: the issue, the delegate it named, and its state, as read before launch. The worker reads the issue again before starting and refuses when it no longer matches. Needs `message`.",
}),
),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
placement: Schema.optional(
Schema.Literals(["auto", "here"]).annotate({
Expand Down Expand Up @@ -215,8 +223,30 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);

/**
* The outcome of a launch already accepted. It reads the receipt and the run; it never calls the
* provider and never creates a thread. `environmentId` is the one the launch's acknowledgement
* carried, and naming it reads the outcome there rather than here.
*/
const LaunchOutcomeTool = Tool.make("t3_launch_outcome", {
...shared,
description:
"Read the outcome of a launch already accepted under `clientRequestId`. Returns whether it was accepted, the thread and run it produced, and whether that run reached a terminal state. For a launch placed on another environment, pass the `environmentId` its acknowledgement carried; the outcome is read there. Returns only what is known. Never starts a thread or a run.",
parameters: Schema.Struct({
environmentId: OrchestratorMcpEnvironmentTarget,
clientRequestId: OrchestratorMcpClientRequestId,
}),
success: LaunchOutcome,
dependencies: [...shared.dependencies, Digest.Digest],
})
.annotate(Tool.Title, "Read a launch's outcome")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);

export const ProjectToolkit = Toolkit.make(
ThreadLaunchTool,
LaunchOutcomeTool,
ProjectListTool,
ProjectReadTool,
ProjectCreateTool,
Expand Down
Loading
Loading