Skip to content

Commit 7808c1e

Browse files
flambohmaria-rcks
andauthored
fix(server): device tools accept a host's label and reject unknown hosts (#25836)
Co-authored-by: maria-rcks <[email protected]>
1 parent d7a78f0 commit 7808c1e

5 files changed

Lines changed: 113 additions & 18 deletions

File tree

‎apps/server/src/mcp/McpDeviceToolkit.test.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,22 @@ it.effect("registers the device tools and returns the screenshot as image conten
210210
expect(foreign.isError).toBe(true);
211211
expect(foreign.content.map((entry) => entry.type)).toEqual(["text"]);
212212

213+
const listed = yield* server
214+
.callTool({ name: "device_list", arguments: { hostId: "THIS MACHINE" } })
215+
.pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
216+
expect(listed.structuredContent).toMatchObject({
217+
hosts: [{ id: "local" }],
218+
devices: [device],
219+
});
220+
221+
const unknownHost = yield* server
222+
.callTool({ name: "device_screenshot", arguments: { hostId: "oliverMac" } })
223+
.pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
224+
expect(unknownHost.isError).toBe(true);
225+
expect(unknownHost.content).toEqual([
226+
{ type: "text", text: "No device host oliverMac. Known hosts: This machine (local)." },
227+
]);
228+
213229
const denied = yield* server
214230
.callTool({ name: "device_list", arguments: {} })
215231
.pipe(callWith(["preview"]), Effect.provideService(McpSchema.McpServerClient, client));
@@ -419,9 +435,14 @@ describe("device targeting across hosts", () => {
419435
run([], ({ opened, call }) =>
420436
Effect.gen(function* () {
421437
const result = yield* call("device_open", { deviceId: "MAC-UDID" });
438+
const byLabel = yield* call("device_open", { platform: "ios", hostId: "MAC MINI" });
439+
expect(byLabel.isError).toBe(false);
422440
expect(text(result)).not.toContain("No device");
423441
expect(result.isError).toBe(false);
424-
expect(opened).toEqual([{ hostId: "mac-mini", deviceId: "MAC-UDID" }]);
442+
expect(opened).toEqual([
443+
{ hostId: "mac-mini", deviceId: "MAC-UDID" },
444+
{ hostId: "mac-mini", deviceId: "MAC-UDID" },
445+
]);
425446
}),
426447
),
427448
);
@@ -515,7 +536,7 @@ describe("device targeting across hosts", () => {
515536
"No device Pixel_9 on 'Mac Mini' (hostId mac-mini). Call device_list for current ids.",
516537
);
517538
expect(yield* missing({ hostId: "unknown-host" })).toBe(
518-
"No device Pixel_9 on hostId unknown-host. Call device_list for current ids.",
539+
"No device host unknown-host. Known hosts: This machine (local), Mac Mini (mac-mini).",
519540
);
520541
expect(opened).toEqual([]);
521542
}),
@@ -528,6 +549,9 @@ describe("device targeting across hosts", () => {
528549
const result = yield* call("device_screenshot", { deviceId: "MAC-UDID" });
529550
expect(result.isError).toBe(false);
530551
expect(result.structuredContent).toMatchObject({ device: { hostId: "mac-mini" } });
552+
const byLabel = yield* call("device_screenshot", { hostId: "MAC MINI" });
553+
expect(byLabel.isError).toBe(false);
554+
expect(byLabel.structuredContent).toMatchObject({ device: { hostId: "mac-mini" } });
531555
}),
532556
),
533557
);
@@ -598,9 +622,14 @@ describe("device targeting across hosts", () => {
598622
Effect.gen(function* () {
599623
expect((yield* call("device_close", { deviceId: "MAC-UDID" })).isError).toBe(false);
600624
expect((yield* call("device_close", { deviceId: "Pixel_9" })).isError).toBe(false);
625+
expect((yield* call("device_close", { hostId: "MAC MINI" })).isError).toBe(false);
626+
const unknown = yield* call("device_close", { hostId: "unknown-host" });
627+
expect(unknown.isError).toBe(true);
628+
expect(text(unknown)).toContain("No device host unknown-host.");
601629
expect(closed).toEqual([
602630
{ hostId: "mac-mini", deviceId: "MAC-UDID" },
603631
{ hostId: undefined, deviceId: "Pixel_9" },
632+
{ hostId: "mac-mini", deviceId: undefined },
604633
]);
605634
}),
606635
),

‎apps/server/src/mcp/McpHttpServer.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ const callSnapshot = (args: Record<string, unknown>) => callTool("preview_snapsh
146146
it.effect.each([
147147
{ input: {}, open: false, message: "No device is open in this thread. Call device_open first." },
148148
{
149-
input: { deviceId: "missing", hostId: "local" },
149+
input: { deviceId: "missing" },
150150
open: false,
151151
message: "Device missing is not open in this thread. Call device_open first.",
152152
},

‎apps/server/src/mcp/toolkits/device/handlers.test.ts‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import { describe, expect, it } from "vite-plus/test";
1+
import type { DeviceHostSummary } from "@t3tools/contracts";
2+
import * as Effect from "effect/Effect";
3+
import { describe, expect, it } from "@effect/vitest";
24

3-
import { agentDeviceQuickStart, pngDimensions } from "./handlers.ts";
5+
import { agentDeviceQuickStart, pngDimensions, resolveHostId } from "./handlers.ts";
46

57
const device = {
68
hostId: "local",
@@ -12,7 +14,43 @@ const device = {
1214
physical: false,
1315
};
1416

17+
const hosts = [
18+
{ id: "local", label: "This machine" },
19+
{ id: "0dc4f37b-5e0a-4f4c-9a51-0c6b8e8a1f2d", label: "oliverMac" },
20+
{ id: "mini-1", label: "Mac mini" },
21+
{ id: "mini-2", label: "Mac mini" },
22+
].map((host): DeviceHostSummary => ({
23+
...host,
24+
kind: host.id === "local" ? "local" : "ssh",
25+
platforms: [],
26+
hubInstalled: true,
27+
agentDeviceInstalled: true,
28+
}));
29+
1530
describe("device tool helpers", () => {
31+
it.effect("resolves a host by exact id or case-insensitive label", () =>
32+
Effect.gen(function* () {
33+
const mac = "0dc4f37b-5e0a-4f4c-9a51-0c6b8e8a1f2d";
34+
expect(yield* resolveHostId(hosts, undefined)).toBeUndefined();
35+
expect(yield* resolveHostId([...hosts, { ...hosts[1]!, label: "local" }], "local")).toBe(
36+
"local",
37+
);
38+
expect(yield* resolveHostId(hosts, mac)).toBe(mac);
39+
expect(yield* resolveHostId(hosts, "olivermac")).toBe(mac);
40+
}),
41+
);
42+
43+
it.effect("rejects an unknown or ambiguous host and lists the candidates", () =>
44+
Effect.gen(function* () {
45+
const unknown = yield* Effect.flip(resolveHostId(hosts, "studio"));
46+
expect(unknown.reason).toContain("This machine (local)");
47+
expect(unknown.reason).toContain("oliverMac (0dc4f37b-5e0a-4f4c-9a51-0c6b8e8a1f2d)");
48+
const ambiguous = yield* Effect.flip(resolveHostId(hosts, "mac mini"));
49+
expect(ambiguous.reason).toContain("Mac mini (mini-1), Mac mini (mini-2)");
50+
expect(ambiguous.reason).not.toContain("oliverMac");
51+
}),
52+
);
53+
1654
it("uses the absolute launcher in every quick-start command", () => {
1755
const text = agentDeviceQuickStart(
1856
device,

‎apps/server/src/mcp/toolkits/device/handlers.ts‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,29 @@ const requireDeviceAccess = McpInvocationContext.requireThreadMcpCapability("dev
9393
),
9494
);
9595

96+
export const resolveHostId = Effect.fn("handlers.resolveHostId")(function* (
97+
hosts: ReadonlyArray<DeviceHostSummary>,
98+
hostId: string | undefined,
99+
): Effect.fn.Return<DeviceHostId | undefined, DeviceToolUnavailableError> {
100+
if (!hostId) return undefined;
101+
const exact = hosts.find((host) => host.id === hostId);
102+
if (exact) return exact.id;
103+
const labelMatches = hosts.filter((host) => host.label.toLowerCase() === hostId.toLowerCase());
104+
if (labelMatches.length === 1) return labelMatches[0]!.id;
105+
const candidates = labelMatches.length > 1 ? labelMatches : hosts;
106+
const listed = [
107+
...candidates.slice(0, 10).map((host) => `${host.label.slice(0, 64)} (${host.id})`),
108+
...(candidates.length > 10 ? [`${candidates.length - 10} more`] : []),
109+
].join(", ");
110+
const selector = hostId.slice(0, 128);
111+
return yield* new DeviceToolUnavailableError({
112+
reason:
113+
labelMatches.length > 1
114+
? `Several device hosts are named ${selector}; pass one id: ${listed}.`
115+
: `No device host ${selector}. Known hosts: ${listed || "none"}.`,
116+
});
117+
});
118+
96119
const hostName = (host: { readonly id: DeviceHostId; readonly label?: string | undefined }) =>
97120
host.label === undefined ? `hostId ${host.id}` : `'${host.label}' (hostId ${host.id})`;
98121

@@ -177,7 +200,7 @@ const handlers = {
177200
"Device support is off. Ask the user to enable it in the Device panel before installing or starting device tools.",
178201
});
179202
}
180-
const hostId = input?.hostId;
203+
const hostId = yield* resolveHostId(state.hosts, input?.hostId);
181204
const open = state.sessions
182205
.filter((session) => session.threadId === scope.thread.threadId)
183206
.map((session) => ({ hostId: session.hostId, deviceId: session.deviceId }));
@@ -204,7 +227,8 @@ const handlers = {
204227
"Device support is off. Ask the user to enable it in the Device panel before installing or starting device tools.",
205228
});
206229
}
207-
const target = yield* pickDevice(state, input);
230+
const hostId = yield* resolveHostId(state.hosts, input.hostId);
231+
const target = yield* pickDevice(state, { ...input, hostId });
208232
// Resolve consent and agent connectivity before booting or registering a session.
209233
if (!(yield* devices.agentReadinessIfSupported(target.hostId))) {
210234
return yield* new DeviceToolUnavailableError({
@@ -273,14 +297,18 @@ const handlers = {
273297
const scope = yield* requireDeviceAccess;
274298
const devices = yield* DeviceService.DeviceService;
275299
const threadId = scope.thread.threadId;
300+
const hostId =
301+
input.hostId === undefined
302+
? undefined
303+
: yield* resolveHostId((yield* devices.state).hosts, input.hostId);
276304
const target =
277305
input.deviceId === undefined
278306
? (yield* devices.sessionsForThread(threadId)).findLast(
279-
(session) => input.hostId === undefined || session.hostId === input.hostId,
307+
(session) => hostId === undefined || session.hostId === hostId,
280308
)
281309
: Option.getOrUndefined(
282310
yield* devices
283-
.locateSession({ threadId, deviceId: input.deviceId, hostId: input.hostId })
311+
.locateSession({ threadId, deviceId: input.deviceId, hostId })
284312
.pipe(mapLocateErrors),
285313
);
286314
if (!target) {
@@ -307,13 +335,17 @@ const handlers = {
307335
const scope = yield* requireDeviceAccess;
308336
const devices = yield* DeviceService.DeviceService;
309337
const deviceId = input.deviceId;
338+
const inputHostId =
339+
input.hostId === undefined
340+
? undefined
341+
: yield* resolveHostId((yield* devices.state).hosts, input.hostId);
310342
const open =
311343
deviceId === undefined
312344
? Option.none()
313345
: yield* devices
314-
.locateSession({ threadId: scope.thread.threadId, deviceId, hostId: input.hostId })
346+
.locateSession({ threadId: scope.thread.threadId, deviceId, hostId: inputHostId })
315347
.pipe(mapLocateErrors);
316-
const hostId = Option.isSome(open) ? open.value.hostId : input.hostId;
348+
const hostId = Option.isSome(open) ? open.value.hostId : inputHostId;
317349
yield* devices.close({
318350
threadId: scope.thread.threadId,
319351
...(hostId === undefined ? {} : { hostId }),

‎evals/mcp-tool-use/run.test.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1156,7 +1156,7 @@ it.effect("accepts a successful exact-host recovery after a real device_open err
11561156
hostId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
11571157
deviceId: "BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB",
11581158
};
1159-
const wrong = { ...input, hostId: "build-mac" };
1159+
const wrong = { ...input, hostId: "unknown-host" };
11601160
const error = yield* sample.devices!.call("device_open", wrong);
11611161
assert.isTrue(error.isError);
11621162
const opened = yield* sample.devices!.call("device_open", input);
@@ -3012,7 +3012,7 @@ it.effect("R12 OWN-01 protects occupied panel sessions from selected and wildcar
30123012
);
30133013

30143014
it.effect(
3015-
"R12 DISC-01 allows the retained label/all-host/refresh route and bounds failed discovery",
3015+
"R12 DISC-01 allows the retained label/all-host route and bounds repeated discovery failures",
30163016
() =>
30173017
Effect.gen(function* () {
30183018
const c = deviceCases().find((c) => c.id === "DISC-01")!;
@@ -3021,11 +3021,7 @@ it.effect(
30213021
yield* withDevices(sample);
30223022
const tools = sample.devices!;
30233023
const calls: Array<SampleRun["calls"][number]> = [];
3024-
for (const input of [
3025-
{ hostId: "build-mac" },
3026-
{},
3027-
{ hostId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" },
3028-
]) {
3024+
for (const input of [{ hostId: "build-mac" }, {}]) {
30293025
const result = yield* tools.call("device_list", input);
30303026
calls.push({
30313027
step: calls.length,

0 commit comments

Comments
 (0)