Skip to content

Commit 001ecbe

Browse files
fix(server): preserve forwarded tool validation and codecs
1 parent c43cb3a commit 001ecbe

6 files changed

Lines changed: 92 additions & 26 deletions

File tree

‎apps/server/src/mcp/toolkits/orchestrator/tools.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
import { EnvironmentId } from "@t3tools/contracts";
12
import { assert, describe, it } from "@effect/vitest";
23
import { Tool } from "effect/ai";
4+
import * as Schema from "effect/Schema";
35

46
import {
57
CreateThreadsTool,
@@ -88,5 +90,14 @@ describe("orchestrator MCP tool guidance", () => {
8890
"clientRequestId",
8991
]);
9092
assert.include(ThreadUpdateTool.description ?? "", "Workspace and branch changes");
93+
const decode = Schema.decodeUnknownSync(ThreadUpdateTool.parametersSchema);
94+
assert.throws(() => decode({ action: "regenerate_title", title: "Requested title" }));
95+
assert.throws(() => decode({ action: "rename" }));
96+
const environmentId = EnvironmentId.make("peer-environment");
97+
assert.deepEqual(decode({ action: "rename", title: "Requested title", environmentId }), {
98+
action: "rename",
99+
title: "Requested title",
100+
environmentId,
101+
});
91102
});
92103
});

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -231,10 +231,10 @@ const ThreadReadTool = Tool.make("t3_thread_read", {
231231
export const ThreadUpdateTool = Tool.make("t3_thread_update", {
232232
description:
233233
"Update metadata for a thread. Omit threadId to update this thread. Use action='rename' with title, action='regenerate_title' with no extra field, action='link_pull_request' with pullRequest, or action='unlink_pull_request'. Workspace and branch changes are intentionally not supported. clientRequestId makes retries idempotent.",
234-
parameters: Schema.Struct({
235-
environmentId: OrchestratorMcpEnvironmentTarget,
236-
...ThreadMetadataMcpUpdateInput.fields,
237-
}),
234+
parameters: ThreadMetadataMcpUpdateInput.mapFields(
235+
(fields) => ({ environmentId: OrchestratorMcpEnvironmentTarget, ...fields }),
236+
{ unsafePreserveChecks: true },
237+
),
238238
success: ThreadMetadataMcpUpdateResult,
239239
failure: OrchestratorMcpFailure,
240240
failureMode: "return",

‎apps/server/src/orchestration-v2/ThreadStop.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1025,9 +1025,31 @@ it.effect("a partial delegated Stop retries only the original children that fail
10251025
const parentThreadId = ThreadId.make("thread:stop-partial");
10261026
yield* createWatchingThread(parentThreadId, 6);
10271027
yield* send(parentThreadId, "work", "start_immediately");
1028+
const rootRefused = yield* threads
1029+
.dispatch({
1030+
type: "thread.stop",
1031+
commandId: CommandId.make("stop-root-above-limit"),
1032+
threadId: parentThreadId,
1033+
})
1034+
.pipe(
1035+
Effect.provideService(DispatchModeLimit, {
1036+
runtimeMode: "approval-required",
1037+
interactionMode: "default",
1038+
}),
1039+
Effect.exit,
1040+
);
1041+
assert.isTrue(Exit.isFailure(rootRefused));
1042+
assert.deepEqual((yield* threadState(parentThreadId)).runs, ["starting"]);
10281043
const blockedChild = yield* delegate(parentThreadId, "default task");
10291044
const advancedChild = yield* delegate(parentThreadId, "default task that advances");
10301045
const stoppedChild = yield* delegate(parentThreadId, "plan task");
1046+
const blockedGrandchild = yield* delegate(stoppedChild, "broader grandchild");
1047+
yield* orchestrator.dispatch({
1048+
type: "thread.runtime-mode.set",
1049+
commandId: CommandId.make("approval-child"),
1050+
threadId: stoppedChild,
1051+
runtimeMode: "approval-required",
1052+
});
10311053
yield* orchestrator.dispatch({
10321054
type: "thread.interaction-mode.set",
10331055
commandId: CommandId.make("plan-child"),
@@ -1038,14 +1060,15 @@ it.effect("a partial delegated Stop retries only the original children that fail
10381060
yield* orchestrator.dispatch({ type: "thread.stop", commandId, threadId: parentThreadId });
10391061
const walked = yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId }).pipe(
10401062
Effect.provideService(DispatchModeLimit, {
1041-
runtimeMode: "full-access",
1063+
runtimeMode: "approval-required",
10421064
interactionMode: "plan",
10431065
}),
10441066
Effect.exit,
10451067
);
10461068
assert.isTrue(Exit.isFailure(walked));
10471069
assert.deepEqual((yield* threadState(stoppedChild)).runs, ["interrupted"]);
10481070
assert.deepEqual((yield* threadState(blockedChild)).runs, ["starting"]);
1071+
assert.deepEqual((yield* threadState(blockedGrandchild)).runs, ["starting"]);
10491072

10501073
yield* orchestrator.dispatch({
10511074
type: "thread.stop",
@@ -1059,6 +1082,7 @@ it.effect("a partial delegated Stop retries only the original children that fail
10591082
const newChild = yield* delegate(parentThreadId, "new child");
10601083
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId });
10611084
assert.deepEqual((yield* threadState(blockedChild)).runs, ["interrupted"]);
1085+
assert.deepEqual((yield* threadState(blockedGrandchild)).runs, ["interrupted"]);
10621086
assert.deepEqual((yield* threadState(stoppedChild)).runs, ["interrupted", "starting"]);
10631087
assert.deepEqual((yield* threadState(advancedChild)).runs, ["interrupted", "starting"]);
10641088
assert.deepEqual((yield* threadState(newChild)).runs, ["starting"]);

‎apps/server/src/peer/PeerForwarding.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
44
import {
55
EnvironmentId,
66
type OrchestrationV2Run,
7+
type ModelSelection,
78
ProjectId,
89
ProviderInstanceId,
910
RunId,
@@ -51,21 +52,31 @@ interface Seen {
5152
readonly projects: ReadonlyArray<ProjectService.ProjectCreateInput>;
5253
/** Commands dispatched and delegated-task stops, as `<type> <threadId>`. */
5354
readonly stops: ReadonlyArray<string>;
55+
readonly selections: ReadonlyArray<ModelSelection>;
5456
}
5557
const nothingSeen: Seen = {
5658
sends: [],
5759
waits: [],
5860
launches: [],
5961
projects: [],
6062
stops: [],
63+
selections: [],
6164
};
6265

6366
/**
6467
* B's threads: one `auto` thread in `boxProject`, whose run finishes on the
6568
* third wait. Every send and wait is recorded.
6669
*/
6770
const boxThreads = (seen: Ref.Ref<Seen>) => {
68-
const shell = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
71+
const shell = {
72+
...liveThreadShell(boxThread, { runtimeMode: "auto" }),
73+
projectId: boxProject,
74+
modelSelection: {
75+
instanceId: ProviderInstanceId.make("codex"),
76+
model: "gpt-5",
77+
options: [{ id: "reasoning", value: "high" }],
78+
},
79+
};
6980
const run = (status: OrchestrationV2Run["status"]) =>
7081
({ id: boxRun, status }) as unknown as OrchestrationV2Run;
7182
const projection = { thread: shell, runs: [run("running")], runtimeRequests: [] } as never;
@@ -81,6 +92,10 @@ const boxThreads = (seen: Ref.Ref<Seen>) => {
8192
dispatch: (command) =>
8293
Ref.update(seen, (current) => ({
8394
...current,
95+
selections:
96+
command.type === "thread.model-selection.set"
97+
? [...current.selections, command.modelSelection]
98+
: current.selections,
8499
stops: [
85100
...current.stops,
86101
`${command.type} ${"threadId" in command ? command.threadId : ""}`,
@@ -538,6 +553,20 @@ it.effect("runs any tool that takes a linked environment there", () =>
538553
expect(archived.isError).toBe(false);
539554
expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]);
540555

556+
const selection = {
557+
instanceId: "codex",
558+
model: "gpt-5",
559+
options: [{ id: "reasoning", value: "high" }],
560+
};
561+
const configured = yield* a.call("thread:laptop-full", "t3_thread_configure", {
562+
environmentId: box.environmentId,
563+
threadId: boxThread,
564+
modelSelection: { provider: "codex", model: "gpt-5", options: { reasoning: "high" } },
565+
});
566+
expect(configured.isError).toBe(false);
567+
expect((yield* Ref.get(seen)).selections).toEqual([selection]);
568+
expect(there.structuredContent).toHaveProperty("modelSelection", selection);
569+
541570
// This environment's own id keeps the call here.
542571
const own = yield* a.call("thread:laptop-full", "t3_thread_configuration", {
543572
environmentId: laptop.environmentId,

‎apps/server/src/peer/PeerForwarding.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,10 @@ const make = Effect.gen(function* () {
9696
) =>
9797
Effect.gen(function* () {
9898
const limits = yield* callerLimits(scope);
99-
const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
100-
params,
101-
).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
99+
const jsonParameters = Schema.toCodecJson(parameters as Schema.Encoder<unknown>);
100+
const encoded = (yield* Schema.encodeUnknownEffect(jsonParameters)(params).pipe(
101+
Effect.mapError(unavailable),
102+
)) as Record<string, unknown>;
102103
const { environmentId: _target, ...args } = encoded;
103104
// A pending upload lives here, so it cannot go with the call.
104105
if (Array.isArray(args.attachments) && args.attachments.length > 0) {
@@ -125,7 +126,7 @@ const make = Effect.gen(function* () {
125126
tool: toolName,
126127
arguments: args,
127128
limits,
128-
success: success as Schema.Decoder<A>,
129+
success: Schema.toCodecJson(success as Schema.Decoder<A>),
129130
});
130131
});
131132

‎apps/server/src/peer/PeerLinks.testkit.ts‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import * as Context from "effect/Context";
99
import * as Effect from "effect/Effect";
1010
import * as Layer from "effect/Layer";
1111
import * as Schema from "effect/Schema";
12-
import type * as McpSchema from "effect/ai/McpSchema";
12+
import * as McpSchema from "effect/ai/McpSchema";
1313
import * as Ref from "effect/Ref";
1414
import * as FetchHttpClient from "effect/http/FetchHttpClient";
1515
import * as HttpRouter from "effect/http/HttpRouter";
@@ -36,6 +36,7 @@ import * as PeerMcpClient from "./PeerMcpClient.ts";
3636
const decodeMcpRequest = Schema.decodeUnknownEffect(
3737
Schema.Struct({ method: Schema.String, id: Schema.optional(Schema.Number) }),
3838
);
39+
const encodeToolResult = Schema.encodeSync(Schema.fromJsonString(McpSchema.CallToolResult));
3940

4041
class PeerTestApi extends HttpApi.make("environment")
4142
.add(EnvironmentHttpApi.groups.metadata)
@@ -96,21 +97,6 @@ export const servePeer = <E, R>(
9697
if (request.url.startsWith("/.well-known/t3/environment")) {
9798
yield* Ref.update(probes, (count) => count + 1);
9899
if (request.headers.host?.startsWith("localhost:")) {
99-
if (yield* Ref.get(sse)) {
100-
return HttpServerResponse.text(
101-
[
102-
'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"result":"notification"}}',
103-
"",
104-
'data: {"jsonrpc":"2.0","id":999,"error":{"code":-1,"message":"other request"}}',
105-
"",
106-
'data: {"jsonrpc":"2.0",',
107-
'data: "id":' + rpc.id + ',"result":' + JSON.stringify(result) + "}",
108-
"",
109-
"",
110-
].join("\r\n"),
111-
{ contentType: "text/event-stream" },
112-
);
113-
}
114100
return HttpServerResponse.jsonUnsafe(yield* Ref.get(alternateDescriptor));
115101
}
116102
}
@@ -136,6 +122,21 @@ export const servePeer = <E, R>(
136122
if (result !== null && request.url === "/mcp" && response.status === 200) {
137123
const rpc = yield* decodeMcpRequest(yield* request.json);
138124
if (rpc.method === "tools/call") {
125+
if (yield* Ref.get(sse)) {
126+
return HttpServerResponse.text(
127+
[
128+
'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"result":"notification"}}',
129+
"",
130+
'data: {"jsonrpc":"2.0","id":999,"error":{"code":-1,"message":"other request"}}',
131+
"",
132+
'data: {"jsonrpc":"2.0",',
133+
'data: "id":' + rpc.id + ',"result":' + encodeToolResult(result) + "}",
134+
"",
135+
"",
136+
].join("\r\n"),
137+
{ contentType: "text/event-stream" },
138+
);
139+
}
139140
return HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: rpc.id, result });
140141
}
141142
}

0 commit comments

Comments
 (0)