TypeScript
fix(mcp): preview errors tell agents what to do instead (#13559)
Theo Browne1e192b25583d
diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.tsindex 1415e2e8dcb..5619f19b254 100644--- a/apps/server/src/mcp/McpHttpServer.test.ts+++ b/apps/server/src/mcp/McpHttpServer.test.ts@@ -161,21 +161,73 @@ it.effect.each([{}, { includeImage: false }])(Effect.provideService(McpSchema.McpServerClient, client),);+ const message = "Preview automation snapshot failed on client mcp-failure-client.";expect(snapshot.isError).toBe(true);expect(snapshot.content).toEqual([- { type: "text", text: "Preview snapshot failed: PreviewAutomationExecutionError." },+ { type: "text", text: `Preview snapshot failed: ${message}` },]);expect(snapshot.structuredContent).toEqual({error: {_tag: "PreviewAutomationExecutionError",operation: "snapshot",failureCount: 1,+ message,},});}),).pipe(Effect.provide(TestLayer)),);+it.effect.each([+ { args: {}, advice: "No active preview tab was found for snapshot. Call preview_open first." },+ {+ args: { tabId: alternateTabId },+ advice: `Preview tab ${alternateTabId} was not found for snapshot. Omit tabId to use the current tab, or call preview_open.`,+ },+])("tells the agent to open a tab when the snapshot has none $args", ({ args, advice }) =>+ Effect.scoped(+ Effect.gen(function* () {+ const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;+ const connected = yield* Deferred.make<void>();+ const events = yield* broker.connect({ clientId: "mcp-no-tab-client", environmentId });+ yield* Stream.runForEach(events, (event) =>+ event.type === "connected"+ ? Deferred.succeed(connected, undefined)+ : broker.respond({+ clientId: "mcp-no-tab-client",+ connectionId: event.connectionId,+ requestId: event.request.requestId,+ ok: false,+ error: { _tag: "PreviewAutomationTabNotFoundError", message: "no tab" },+ }),+ ).pipe(Effect.forkScoped);+ yield* Deferred.await(connected);++ const snapshot = yield* callSnapshot(args);++ expect(snapshot.isError).toBe(true);+ expect(snapshot.content).toEqual([+ { type: "text", text: `Preview snapshot failed: ${advice}` },+ ]);+ }),+ ).pipe(Effect.provide(TestLayer)),+);++it.effect("tells the agent how to fall back when no desktop app can run the snapshot", () =>+ Effect.gen(function* () {+ const snapshot = yield* callSnapshot({});++ expect(snapshot.isError).toBe(true);+ const [text] = snapshot.content;+ expect(text?.type === "text" ? text.text : "").toContain(+ "use a headless browser from the shell",+ );+ expect(snapshot.structuredContent).toMatchObject({+ error: { _tag: "PreviewAutomationNoAvailableHostError" },+ });+ }).pipe(Effect.provide(TestLayer)),+);+it.effect.each([{ mode: "default", input: {}, images: true },{ mode: "explicit image", input: { includeImage: true }, images: true },diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.tsindex f93c7643daf..5a807fc328a 100644--- a/apps/server/src/mcp/McpHttpServer.ts+++ b/apps/server/src/mcp/McpHttpServer.ts@@ -13,6 +13,7 @@ import * as Stream from "effect/Stream";import type * as Types from "effect/Types";import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";+import { PreviewAutomationError } from "@t3tools/contracts";import packageJson from "../../package.json" with { type: "json" };import * as ServerConfig from "../config.ts";@@ -328,6 +329,8 @@ const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (return screenshotPath;});+const isPreviewAutomationError = Schema.is(PreviewAutomationError);+const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {return Effect.failCause(cause).pipe(Effect.orDie);@@ -341,6 +344,9 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {typeof firstFailure._tag === "string"? firstFailure._tag: "PreviewSnapshotError";+ // Preview errors build their message on the server, never from page output,+ // and it tells the agent what to do next, such as falling back to a shell browser.+ const message = isPreviewAutomationError(firstFailure) ? firstFailure.message : undefined;const result = new McpSchema.CallToolResult({isError: true,structuredContent: {@@ -348,10 +354,11 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {_tag: errorTag,operation: "snapshot",failureCount: failures.length,+ ...(message === undefined ? {} : { message }),},},- // Agents usually see only the text content, so name the tag there too.- content: [{ type: "text", text: `Preview snapshot failed: ${errorTag}.` }],+ // Some clients show only the text content and others only structuredContent, so both carry it.+ content: [{ type: "text", text: `Preview snapshot failed: ${message ?? `${errorTag}.`}` }],});return Effect.logWarning("preview snapshot failed", {operation: "snapshot",diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.tsindex 123944206e3..4314c82e6dd 100644--- a/apps/server/src/mcp/McpInvocationContext.test.ts+++ b/apps/server/src/mcp/McpInvocationContext.test.ts@@ -34,7 +34,8 @@ it.effect("reports the scoped credential context when preview capability is unavproviderSessionId: invocation.providerSessionId,providerInstanceId: invocation.providerInstanceId,});- expect(error.message).toBe("MCP credential does not grant the preview capability.");+ expect(error.message).toContain("MCP credential does not grant the preview capability");+ expect(error.message).toContain("use a headless browser from the shell");});});diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.tsindex 431e83189d2..f87739670f7 100644--- a/packages/contracts/src/previewAutomation.ts+++ b/packages/contracts/src/previewAutomation.ts@@ -649,6 +649,7 @@ const McpCapabilityErrorFields = {providerInstanceId: ProviderInstanceId,};+/** Agents read this message, so it names the next step and not only the failure. */export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()("PreviewAutomationUnavailableError",{@@ -657,7 +658,7 @@ export class PreviewAutomationUnavailableError extends Schema.TaggedError<Previe},) {override get message(): string {- return `MCP credential does not grant the ${this.capability} capability.`;+ return `MCP credential does not grant the ${this.capability} capability: browser preview tools are off for this thread. Do not retry them. To check a page, use a headless browser from the shell, such as Playwright, or curl. The user can turn on "Agent browser access" in Settings; it applies when the agent session next starts.`;}}@@ -722,8 +723,7 @@ export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<Pr},) {override get message(): string {- const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;- return summary;+ return `No preview automation host is available for ${this.operation} in environment ${this.environmentId}. Preview tools run in a T3 Code desktop app that is open and connected to this environment; a headless server has no browser of its own. Do not retry. To check a page, use a headless browser from the shell, such as Playwright, or curl, or ask the user to open this thread in the T3 Code desktop app.`;}}@@ -747,10 +747,9 @@ export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<Previe},) {override get message(): string {- const summary = this.tabId- ? `Preview tab ${this.tabId} was not found for ${this.operation}.`- : `No active preview tab was found for ${this.operation}.`;- return summary;+ return this.tabId+ ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`+ : `No active preview tab was found for ${this.operation}. Call preview_open first.`;}}