🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(mcp): Report errors as isError tool results (#19579)
Ben Bachem15e7e2205039
diff --git a/web/src/__tests__/server/mcp-error-formatting.servertest.ts b/web/src/__tests__/server/mcp-error-formatting.servertest.tsindex 079e8ff20c..e81a24da0c 100644--- a/web/src/__tests__/server/mcp-error-formatting.servertest.ts+++ b/web/src/__tests__/server/mcp-error-formatting.servertest.ts@@ -13,12 +13,9 @@ vi.mock("@langfuse/shared/src/server", async () => {};});-import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";+import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";import { ZodError, z } from "zod";-import {- formatErrorForUser,- wrapErrorHandling,-} from "@/src/features/mcp/core/error-formatting";+import { formatErrorForUser } from "@/src/features/mcp/core/error-formatting";import { UserInputError, ApiServerError } from "@/src/features/mcp/core/errors";import {UnauthorizedError,@@ -37,7 +34,6 @@ describe("MCP Error Formatting", () => {const error = new UserInputError("Prompt 'foo' not found");const mcpError = formatErrorForUser(error);- expect(mcpError).toBeInstanceOf(McpError);expect(mcpError.code).toBe(ErrorCode.InvalidRequest);expect(mcpError.message).toContain("Prompt 'foo' not found");});@@ -66,7 +62,6 @@ describe("MCP Error Formatting", () => {const error = new ApiServerError("Database connection failed");const mcpError = formatErrorForUser(error);- expect(mcpError).toBeInstanceOf(McpError);expect(mcpError.code).toBe(ErrorCode.InternalError);// Should NOT expose internal error messageexpect(mcpError.message).toContain(@@ -219,10 +214,10 @@ describe("MCP Error Formatting", () => {});it.each([- ["Access denied", "MCP error -32600: Access denied"],+ ["Access denied", "Access denied"],[undefined,- "MCP error -32600: Access denied. You do not have permission to access this resource.",+ "Access denied. You do not have permission to access this resource.",],])("preserves the ForbiddenError message: %s",@@ -358,118 +353,6 @@ describe("MCP Error Formatting", () => {});});- describe("wrapErrorHandling", () => {- it("should pass through successful function result", async () => {- const fn = async () => ({ result: "success" });- const wrapped = wrapErrorHandling(fn);-- const result = await wrapped();- expect(result).toEqual({ result: "success" });- });-- it("should pass through function arguments", async () => {- const fn = async (a: number, b: string) => `${a}-${b}`;- const wrapped = wrapErrorHandling(fn);-- const result = await wrapped(42, "test");- expect(result).toBe("42-test");- });-- it("should wrap UserInputError in McpError", async () => {- const fn = async () => {- throw new UserInputError("Invalid input");- };- const wrapped = wrapErrorHandling(fn);-- await expect(wrapped()).rejects.toThrow(McpError);- try {- await wrapped();- } catch (e) {- const mcpError = e as McpError;- expect(mcpError.code).toBe(ErrorCode.InvalidRequest);- expect(mcpError.message).toContain("Invalid input");- }- });-- it("should wrap ApiServerError in McpError with generic message", async () => {- const fn = async () => {- throw new ApiServerError("Database crashed");- };- const wrapped = wrapErrorHandling(fn);-- await expect(wrapped()).rejects.toThrow(McpError);- await expect(wrapped()).rejects.toMatchObject({- code: ErrorCode.InternalError,- });- });-- it("should wrap ZodError in McpError", async () => {- const schema = z.object({ name: z.string() });- const fn = async () => {- schema.parse({ name: 123 });- };- const wrapped = wrapErrorHandling(fn);-- await expect(wrapped()).rejects.toThrow(McpError);- await expect(wrapped()).rejects.toMatchObject({- code: ErrorCode.InvalidParams,- });- });-- it("should wrap generic Error in McpError", async () => {- const fn = async () => {- throw new Error("Unexpected error");- };- const wrapped = wrapErrorHandling(fn);-- await expect(wrapped()).rejects.toThrow(McpError);- await expect(wrapped()).rejects.toMatchObject({- code: ErrorCode.InternalError,- });- });-- it("should handle async function that returns promise", async () => {- const fn = () => Promise.resolve({ data: "async result" });- const wrapped = wrapErrorHandling(fn);-- const result = await wrapped();- expect(result).toEqual({ data: "async result" });- });-- it("should handle rejected promise", async () => {- const fn = () => Promise.reject(new UserInputError("Async rejection"));- const wrapped = wrapErrorHandling(fn);-- try {- await wrapped();- } catch (e) {- const mcpError = e as McpError;- expect(mcpError.code).toBe(ErrorCode.InvalidRequest);- expect(mcpError.message).toContain("Async rejection");- }- });-- it("should preserve function return type", async () => {- interface PromptResult {- id: string;- name: string;- version: number;- }-- const fn = async (): Promise<PromptResult> => ({- id: "123",- name: "test",- version: 1,- });- const wrapped = wrapErrorHandling(fn);-- const result = await wrapped();- expect(result.id).toBe("123");- expect(result.name).toBe("test");- expect(result.version).toBe(1);- });- });-describe("Error priority and categorization", () => {it("should categorize user-fixable errors as InvalidRequest", () => {const userErrors = [diff --git a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts b/web/src/__tests__/server/mcp-public-api-tools.servertest.tsindex b8b566233f..e61e60a53b 100644--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts@@ -413,7 +413,7 @@ describe("MCP public API tools", () => {{ queueId: queue.id, userId: user.id },context,),- ).rejects.toThrow("An unexpected error occurred");+ ).rejects.toThrow("audit failed");} finally {auditLogCreateSpy.mockRestore();}@@ -613,7 +613,7 @@ describe("MCP public API tools", () => {},context,),- ).rejects.toThrow("Validation failed");+ ).rejects.toMatchObject({ name: "ZodError" });const conflictingDatasetName = `mcp-dataset-conflict-${uuidv4()}`;await handleUpsertDataset({ name: conflictingDatasetName }, context);@@ -714,7 +714,7 @@ describe("MCP public API tools", () => {{ datasetId: dataset.id, items: [] },context,),- ).rejects.toThrow("Validation failed");+ ).rejects.toMatchObject({ name: "ZodError" });await expect(handleBatchUpsertDatasetItems(@@ -724,7 +724,7 @@ describe("MCP public API tools", () => {},context,),- ).rejects.toThrow("Validation failed");+ ).rejects.toMatchObject({ name: "ZodError" });const datasetItems = (await handleListDatasetItems({ datasetId: dataset.id, page: 1, limit: 10 },diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex f29cff8e89..a075a7e52e 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -36,7 +36,6 @@ vi.mock(import { nanoid } from "nanoid";import { createHash, randomUUID } from "crypto";-import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";import { z } from "zod";import { prisma } from "@langfuse/shared/src/db";import {@@ -1430,7 +1429,16 @@ describe("MCP Read Tools", () => {} as unknown as Parameters<typeof handleListObservations>[0],mockServerContext(),),- ).rejects.toThrow('Invalid observation filter column "startTime"');+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({+ path: ["filter", 0, "column"],+ message: expect.stringContaining(+ 'Invalid observation filter column "startTime"',+ ),+ }),+ ]),+ });},);@@ -1969,7 +1977,12 @@ describe("MCP Read Tools", () => {>[0],context,),- ).rejects.toThrow(/fromStartTime.*toStartTime/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["fromStartTime"] }),+ expect.objectContaining({ path: ["toStartTime"] }),+ ]),+ });await expect(handleListObservations(@@ -1987,7 +2000,12 @@ describe("MCP Read Tools", () => {} as unknown as Parameters<typeof handleListObservations>[0],context,),- ).rejects.toThrow(/fromStartTime.*toStartTime/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["fromStartTime"] }),+ expect.objectContaining({ path: ["toStartTime"] }),+ ]),+ });await expect(handleListObservations(@@ -2005,7 +2023,12 @@ describe("MCP Read Tools", () => {} as unknown as Parameters<typeof handleListObservations>[0],context,),- ).rejects.toThrow(/fromStartTime.*toStartTime/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["fromStartTime"] }),+ expect.objectContaining({ path: ["toStartTime"] }),+ ]),+ });await expect(handleListObservations(@@ -2016,7 +2039,12 @@ describe("MCP Read Tools", () => {} as unknown as Parameters<typeof handleListObservations>[0],context,),- ).rejects.toThrow(/fromStartTime.*toStartTime/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["fromStartTime"] }),+ expect.objectContaining({ path: ["toStartTime"] }),+ ]),+ });await expect(handleListObservations(@@ -2113,7 +2141,7 @@ describe("MCP Read Tools", () => {>[0],context,),- ).rejects.toThrow(/fromStartTime.*toStartTime/i);+ ).rejects.toThrow(/fromStartTime.*toStartTime/is);await expect(handleListObservations(@@ -2236,7 +2264,14 @@ describe("MCP Read Tools", () => {},context,),- ).rejects.toThrow(/Validation failed: .*filter\.0\.type: .*number/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({+ path: ["filter", 0, "type"],+ message: expect.stringMatching(/number/i),+ }),+ ]),+ });});it("should reject hidden/internal advanced filter columns", async () => {@@ -2744,7 +2779,6 @@ describe("MCP Read Tools", () => {context,),).rejects.toMatchObject({- code: ErrorCode.InvalidRequest,message: expect.stringContaining("Field 'usageType' cannot be used as a filter.",),@@ -3405,7 +3439,11 @@ describe("MCP Read Tools", () => {{ column: "input", limit: 100 } as any,context,),- ).rejects.toThrow(/validation failed/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["column"], code: "invalid_value" }),+ ]),+ });});});@@ -3622,13 +3660,34 @@ describe("MCP Read Tools", () => {// by the strict schema instead of being silently ignored.await expect(handleListScores({ limit: 10, userId: "user-1" } as any, context),- ).rejects.toThrow(/validation failed/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({+ code: "unrecognized_keys",+ keys: ["userId"],+ }),+ ]),+ });await expect(handleListScores({ limit: 10, traceTags: ["tag"] } as any, context),- ).rejects.toThrow(/validation failed/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({+ code: "unrecognized_keys",+ keys: ["traceTags"],+ }),+ ]),+ });await expect(handleListScores({ limit: 10, page: 1 } as any, context),- ).rejects.toThrow(/validation failed/i);+ ).rejects.toMatchObject({+ issues: expect.arrayContaining([+ expect.objectContaining({+ code: "unrecognized_keys",+ keys: ["page"],+ }),+ ]),+ });});});diff --git a/web/src/__tests__/server/mcp-tools-write.servertest.ts b/web/src/__tests__/server/mcp-tools-write.servertest.tsindex 98f260d082..3900456eb2 100644--- a/web/src/__tests__/server/mcp-tools-write.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-write.servertest.ts@@ -51,7 +51,6 @@ vi.mock(import { prisma, Role } from "@langfuse/shared/src/db";import { nanoid } from "nanoid";import { z } from "zod";-import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";import { SkillVersionSchema } from "@langfuse/shared";import { handleUpdateSkillLabels } from "@/src/features/mcp/server/skills/tools/updateSkillLabels";import { handleUpdateSkillTags } from "@/src/features/mcp/server/skills/tools/updateSkillTags";@@ -1235,8 +1234,10 @@ describe("MCP Write Tools", () => {setup.context,),).rejects.toMatchObject({- code: ErrorCode.InvalidParams,- message: expect.stringContaining("filter.0.operator"),+ name: "ZodError",+ issues: expect.arrayContaining([+ expect.objectContaining({ path: ["filter", 0, "operator"] }),+ ]),});expect(queueMocks.batchActionQueueAdd).not.toHaveBeenCalled();});@@ -2059,10 +2060,13 @@ describe("MCP Write Tools", () => {context,),).rejects.toMatchObject({- code: -32602, // INVALID_PARAMS- message: expect.stringContaining(- "Chat prompts must have at least one message",- ),+ issues: expect.arrayContaining([+ expect.objectContaining({+ path: ["prompt"],+ code: "too_small",+ message: "Chat prompts must have at least one message",+ }),+ ]),});});@@ -2567,10 +2571,10 @@ describe("MCP Write Tools", () => {if (testCase.expectForbidden) {await expect(update).rejects.toMatchObject({- name: "McpError",- code: ErrorCode.InvalidRequest,+ name: "ForbiddenError",+ httpCode: 403,message:- "MCP error -32600: You don't have permission to add a protected label to a prompt. Please contact your project admin for assistance.\n\n Protected labels are: production",+ "You don't have permission to add a protected label to a prompt. Please contact your project admin for assistance.\n\n Protected labels are: production",});const prompt = await prisma.prompt.findFirst({@@ -2618,9 +2622,9 @@ describe("MCP Write Tools", () => {context,),).rejects.toMatchObject({- name: "McpError",- code: ErrorCode.InvalidRequest,- message: `MCP error -32600: You don't have permission to create a prompt with a protected label. Please contact your project admin for assistance.\n\n Protected labels are: ${protectedLabel}`,+ name: "ForbiddenError",+ httpCode: 403,+ message: `You don't have permission to create a prompt with a protected label. Please contact your project admin for assistance.\n\n Protected labels are: ${protectedLabel}`,});await expect(@@ -2660,10 +2664,10 @@ describe("MCP Write Tools", () => {context,),).rejects.toMatchObject({- name: "McpError",- code: ErrorCode.InvalidRequest,+ name: "ForbiddenError",+ httpCode: 403,message:- "MCP error -32600: You don't have permission to add a protected label to a prompt. Please contact your project admin for assistance.\n\n Protected labels are: production",+ "You don't have permission to add a protected label to a prompt. Please contact your project admin for assistance.\n\n Protected labels are: production",});});});diff --git a/web/src/__tests__/server/unit/mcp-calltool-error.servertest.ts b/web/src/__tests__/server/unit/mcp-calltool-error.servertest.tsnew file mode 100644index 0000000000..bc98d17e04--- /dev/null+++ b/web/src/__tests__/server/unit/mcp-calltool-error.servertest.ts@@ -0,0 +1,102 @@+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";+import { LangfuseNotFoundError } from "@langfuse/shared";+import { ClickHouseResourceError } from "@langfuse/shared/src/server";+import { describe, expect, it, vi } from "vitest";+import { z } from "zod";+import { defineTool } from "@/src/features/mcp/core/define-tool";+import { createMcpServer } from "@/src/features/mcp/server/mcpServer";+import { toolRegistry } from "@/src/features/mcp/server/registry";+import { __dangerouslySkipAuthz } from "@/src/features/public-api/server";+import type { ServerContext } from "@/src/features/mcp/types";++vi.mock("@/src/features/mcp/server/registry", () => ({+ toolRegistry: { getEnabledTool: vi.fn() },+}));++const context: ServerContext = {+ projectId: "project-1",+ orgId: "org-1",+ apiKeyId: "key-1",+ accessLevel: "project",+ publicKey: "pk-lf-test",+ plan: "oss",+ rateLimitOverrides: [],+};++describe("MCP tool results", () => {+ it.each([+ {+ name: "timeout",+ error: new ClickHouseResourceError(+ "TIMEOUT",+ new Error("internal query"),+ ),+ input: "valid",+ message:+ "The ClickHouse query timed out. Narrow the query by shortening the date range or adding more specific filters before trying again.",+ },+ {+ name: "missing resource",+ error: new LangfuseNotFoundError("Prompt 'example' not found"),+ input: "valid",+ message: "Prompt 'example' not found",+ },+ {+ name: "validation",+ error: undefined,+ input: "",+ message: "Validation failed: name: Name is required",+ },+ ...[+ new Error("internal secret"),+ new McpError(ErrorCode.InternalError, "internal secret"),+ ].map((error) => ({+ name: error.constructor.name,+ error,+ input: "valid",+ message: "An unexpected error occurred. Please try again later.",+ })),+ { name: "success", error: undefined, input: "valid", message: "ok" },+ ])(+ "preserves safe output for $name through defineTool",+ async ({ error, input, message }) => {+ const schema = z.object({ name: z.string().min(1, "Name is required") });+ const [definition, handler] = defineTool({+ name: "test-tool",+ description: "test",+ action: __dangerouslySkipAuthz,+ baseSchema: schema,+ inputSchema: schema,+ handler: async () => {+ if (error) throw error;+ return "ok";+ },+ });+ vi.mocked(toolRegistry.getEnabledTool).mockImplementation(async (name) =>+ name === definition.name ? { definition, handler } : undefined,+ );+ const server = createMcpServer(context);+ const client = new Client({ name: "test", version: "1.0.0" });+ const [serverTransport, clientTransport] =+ InMemoryTransport.createLinkedPair();+ try {+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ const result = await client.callTool({+ name: definition.name,+ arguments: { name: input },+ });+ expect(result.content).toEqual([{ type: "text", text: message }]);+ expect(result.isError).toBe(message === "ok" ? undefined : true);+ await expect(+ client.callTool({ name: "unknown", arguments: {} }),+ ).rejects.toMatchObject({ code: ErrorCode.InvalidParams });+ } finally {+ await client.close();+ await server.close();+ }+ },+ );+});diff --git a/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts b/web/src/__tests__/server/unit/mcp-define-tool.servertest.tsindex d9494d1f31..d6e67abad9 100644--- a/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts+++ b/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts@@ -40,7 +40,7 @@ describe("defineTool", () => {const invalid = "2024-02-30T06:15Z";expect(pattern.test(invalid)).toBe(false);await expect(run({ timestamp: invalid }, context)).rejects.toThrow(- "Validation failed",+ z.ZodError,);expect(handler).toHaveBeenCalledTimes(2);});@@ -130,7 +130,7 @@ describe("defineTool", () => {// MCP clients submit unvalidated JSON to the typed handler.await expect(run(invalid as Parameters<typeof run>[0], context),- ).rejects.toThrow("Validation failed");+ ).rejects.toThrow(z.ZodError);}expect(handler).toHaveBeenCalledExactlyOnceWith(input, context);});diff --git a/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts b/web/src/__tests__/server/unit/run-mcp-tool.servertest.tsindex bc11fb59a5..8361b2df78 100644--- a/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts+++ b/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts@@ -175,9 +175,7 @@ describe("MCP observation search cooldown", () => {);await expect(handleListObservations(input, context),- ).rejects.toMatchObject({- code: ErrorCode.InvalidRequest,- });+ ).rejects.toBeInstanceOf(InvalidRequestError);await expect(handleListObservations(input, context)).rejects.toThrow(/retry in 30s/i,@@ -221,8 +219,8 @@ describe("MCP observation search cooldown", () => {new Error("private query details"),),);- await expect(handleListObservations(input, context)).rejects.toThrow(- /query timed out/i,+ await expect(handleListObservations(input, context)).rejects.toBeInstanceOf(+ ClickHouseResourceError,);await expect(handleListObservations(input, context)).resolves.toBeDefined();diff --git a/web/src/features/mcp/core/define-tool.ts b/web/src/features/mcp/core/define-tool.tsindex f12cd1a936..c5de607ba4 100644--- a/web/src/features/mcp/core/define-tool.ts+++ b/web/src/features/mcp/core/define-tool.ts@@ -6,7 +6,6 @@*/import { z } from "zod";-import { wrapErrorHandling } from "./error-formatting";import type { ApiAction } from "@/src/features/public-api/server";import type { ServerContext } from "../types";@@ -173,14 +172,14 @@ export function defineTool<TInput, const TName extends string>(};}- // Wrap handler with validation and error handling- const wrappedHandler: ToolHandler<TInput> = wrapErrorHandling(- async (rawInput: unknown, context: ServerContext) => {- // Validate input with the full schema (including refinements)- const validatedInput = inputSchema.parse(rawInput);- return await handler(validatedInput, context);- },- );+ const wrappedHandler: ToolHandler<TInput> = async (+ rawInput: unknown,+ context: ServerContext,+ ) => {+ // Validate input with the full schema (including refinements)+ const validatedInput = inputSchema.parse(rawInput);+ return await handler(validatedInput, context);+ };return [toolDefinition, wrappedHandler];}diff --git a/web/src/features/mcp/core/error-formatting.ts b/web/src/features/mcp/core/error-formatting.tsindex 5672b330ca..ff727b158c 100644--- a/web/src/features/mcp/core/error-formatting.ts+++ b/web/src/features/mcp/core/error-formatting.ts@@ -5,7 +5,7 @@* Following Sentry pattern of categorizing and formatting errors appropriately.*/-import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";+import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";import { ZodError } from "zod";import { isUserInputError, isApiServerError } from "./errors";import {@@ -18,28 +18,28 @@ import {import { ClickHouseResourceError, logger } from "@langfuse/shared/src/server";/**- * Format an error for MCP response.- * Returns a properly formatted McpError with appropriate error code.- *- * @param error - The error to format- * @returns Formatted McpError+ * Sanitize errors independently of whether the caller returns a tool result+ * or a protocol error. Call only at the response boundary, not inside handlers.*/-export function formatErrorForUser(error: unknown): McpError {+export function formatErrorForUser(error: unknown): {+ code: ErrorCode;+ message: string;+} {// Log server errors for monitoring (sanitized to avoid PII exposure)if (isApiServerError(error)) {logger.error("MCP API Server Error", {message: error.message,name: error.name,});- return new McpError(- ErrorCode.InternalError,- "An internal server error occurred. Please try again later.",- );+ return {+ code: ErrorCode.InternalError,+ message: "An internal server error occurred. Please try again later.",+ };}// User input errors - provide helpful messageif (isUserInputError(error)) {- return new McpError(ErrorCode.InvalidRequest, error.message);+ return { code: ErrorCode.InvalidRequest, message: error.message };}// Zod validation errors@@ -47,30 +47,30 @@ export function formatErrorForUser(error: unknown): McpError {const messages = error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`,);- return new McpError(- ErrorCode.InvalidParams,- `Validation failed: ${messages.join(", ")}`,- );+ return {+ code: ErrorCode.InvalidParams,+ message: `Validation failed: ${messages.join(", ")}`,+ };}// Langfuse standard errorsif (error instanceof UnauthorizedError) {- return new McpError(- ErrorCode.InvalidRequest,- "Authentication failed. Please check your API key.",- );+ return {+ code: ErrorCode.InvalidRequest,+ message: "Authentication failed. Please check your API key.",+ };}if (error instanceof ForbiddenError) {- return new McpError(ErrorCode.InvalidRequest, error.message);+ return { code: ErrorCode.InvalidRequest, message: error.message };}if (error instanceof LangfuseNotFoundError) {- return new McpError(ErrorCode.InvalidRequest, error.message);+ return { code: ErrorCode.InvalidRequest, message: error.message };}if (error instanceof InvalidRequestError) {- return new McpError(ErrorCode.InvalidRequest, error.message);+ return { code: ErrorCode.InvalidRequest, message: error.message };}if (error instanceof ClickHouseResourceError) {@@ -78,12 +78,13 @@ export function formatErrorForUser(error: unknown): McpError {errorType: error.errorType,tags: error.tags,});- return new McpError(- ErrorCode.InvalidRequest,- error.errorType === "TIMEOUT"- ? "The ClickHouse query timed out. Narrow the query by shortening the date range or adding more specific filters before trying again."- : ClickHouseResourceError.ERROR_ADVICE_MESSAGE,- );+ return {+ code: ErrorCode.InvalidRequest,+ message:+ error.errorType === "TIMEOUT"+ ? "The ClickHouse query timed out. Narrow the query by shortening the date range or adding more specific filters before trying again."+ : ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ };}if (error instanceof BaseError && error.httpCode >= 500) {@@ -91,15 +92,15 @@ export function formatErrorForUser(error: unknown): McpError {name: error.name,httpCode: error.httpCode,});- return new McpError(- ErrorCode.InternalError,- "An internal server error occurred. Please try again later.",- );+ return {+ code: ErrorCode.InternalError,+ message: "An internal server error occurred. Please try again later.",+ };}if (error instanceof BaseError) {logger.warn("MCP BaseError", error);- return new McpError(ErrorCode.InvalidRequest, error.message);+ return { code: ErrorCode.InvalidRequest, message: error.message };}// Generic errors (sanitized logging)@@ -108,37 +109,18 @@ export function formatErrorForUser(error: unknown): McpError {message: error.message,name: error.name,});- return new McpError(- ErrorCode.InternalError,- "An unexpected error occurred. Please try again later.",- );+ return {+ code: ErrorCode.InternalError,+ message: "An unexpected error occurred. Please try again later.",+ };}// Unknown error type (sanitized logging)logger.error("MCP Unknown Error Type", {errorType: typeof error,});- return new McpError(- ErrorCode.InternalError,- "An unexpected error occurred. Please try again later.",- );-}--/**- * Wrap a function to catch and format errors for MCP.- * Prevents errors from bubbling up unformatted.- *- * @param fn - Function to wrap- * @returns Wrapped function that catches and formats errors- */-export function wrapErrorHandling<T extends (...args: any[]) => Promise<any>>(- fn: T,-): T {- return (async (...args: Parameters<T>) => {- try {- return await fn(...args);- } catch (error) {- throw formatErrorForUser(error);- }- }) as T;+ return {+ code: ErrorCode.InternalError,+ message: "An unexpected error occurred. Please try again later.",+ };}diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.tsindex eaf8fde971..b8ed04972c 100644--- a/web/src/features/mcp/server/mcpServer.ts+++ b/web/src/features/mcp/server/mcpServer.ts@@ -16,6 +16,8 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";import {ListToolsRequestSchema,CallToolRequestSchema,+ McpError,+ ErrorCode,} from "@modelcontextprotocol/sdk/types.js";import { isProductFeedbackAvailable } from "@/src/features/feedback/server";import { shadowAuthorize } from "@/src/features/public-api/server";@@ -111,13 +113,13 @@ export function createMcpServer(context: ServerContext): Server {const registeredTool = await toolRegistry.getEnabledTool(name, context);if (!registeredTool) {- throw new Error(`Unknown tool: ${name}`);+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);}assertToolAuthorized(registeredTool.definition, context);// Execute handler with context- // Handler performs validation and error handling via defineTool wrapper+ // Handler validates input; errors are formatted only at this boundary.const clickHouseCtx = contextWithLangfuseProps({projectId: context.projectId,apiKeyId: context.apiKeyId,@@ -126,21 +128,29 @@ export function createMcpServer(context: ServerContext): Server {route: name,},});- const result = await otelContext.with(clickHouseCtx, () =>- registeredTool.handler(args, context),- );-- return {- content: [- {- type: "text",- text:- typeof result === "string"- ? result- : JSON.stringify(result, null, 2),- },- ],- };+ try {+ const result = await otelContext.with(clickHouseCtx, () =>+ registeredTool.handler(args, context),+ );++ return {+ content: [+ {+ type: "text",+ text:+ typeof result === "string"+ ? result+ : JSON.stringify(result, null, 2),+ },+ ],+ };+ } catch (error) {+ const { message } = formatErrorForUser(error);+ return {+ content: [{ type: "text", text: message }],+ isError: true,+ };+ }});return server;@@ -160,7 +170,10 @@ function assertToolAuthorized(scope: { accessLevel: context.accessLevel },},});- if (!decision.success) throw formatErrorForUser(decision.error);+ if (!decision.success) {+ const { code, message } = formatErrorForUser(decision.error);+ throw new McpError(code, message);+ }}export const __test = { assertToolAuthorized };diff --git a/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts b/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.tsindex a37ad01944..a01458d366 100644--- a/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts+++ b/worker/src/features/in-app-agent/runtime/human-in-the-loop.test.ts@@ -47,6 +47,37 @@ function toolResultContent(events: { type: string; content?: string }[]) {}describe("createManualToolApprovalRunInput", () => {+ it("marks a resolved MCP failure as an error and gives the model retry guidance", async () => {+ const message = "Categories must have unique labels";+ const result = {+ content: [{ type: "text", text: message }],+ isError: true,+ };+ const { input, syntheticEvents, developerGuidance } =+ await createManualToolApprovalRunInput({+ input: resumeInput(),+ executeToolCall: async () => ({ result, modelResult: result }),+ });++ expect(input.messages.find((entry) => entry.role === "tool")).toMatchObject(+ {+ error: message,+ },+ );+ expect(+ syntheticEvents.find(+ (event) => event.type === EventType.TOOL_CALL_RESULT,+ ),+ ).toMatchObject({+ error: message,+ content: JSON.stringify(result),+ });+ expect(developerGuidance).toContain(message);+ expect(developerGuidance).toContain(+ "Do not call the same tool again with identical arguments.",+ );+ });+it("resumes a non-silent approval with the inner payload, not the LanguageModelV3 wrapper", async () => {const result = {id: "score-config-1",diff --git a/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts b/worker/src/features/in-app-agent/runtime/human-in-the-loop.tsindex 307f3a9a5d..fa0a57894f 100644--- a/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts+++ b/worker/src/features/in-app-agent/runtime/human-in-the-loop.ts@@ -9,6 +9,7 @@ import {isInAppAgentToolWithInputs,} from "@langfuse/shared/in-app-agent";import { toAgUiToolResultContent } from "@langfuse/shared/in-app-agent/server/toolResults";+import { getToolFailureMessage } from "@langfuse/shared/in-app-agent/server/toolErrors";import type { AgUiRunAgentInput, ResumeForwardedProps } from "./types";const MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE =@@ -172,7 +173,11 @@ async function executeApprovedToolCall(params: {params.resumeData,);- return { toolResult: result, modelToolResult: modelResult };+ return {+ toolResult: result,+ modelToolResult: modelResult,+ toolError: getToolFailureMessage(undefined, result),+ };} catch (error) {const toolError = formatToolExecutionError(error);diff --git a/worker/src/features/in-app-agent/runtime/tools.ts b/worker/src/features/in-app-agent/runtime/tools.tsindex debcb3bb33..3cd14219bd 100644--- a/worker/src/features/in-app-agent/runtime/tools.ts+++ b/worker/src/features/in-app-agent/runtime/tools.ts@@ -190,9 +190,8 @@ export function withOptionalSilentMcpOutput(params: {// Rethrow instead of returning a structured failure: the tool-error// chunk rewrite already feeds the error back as a tool result the- // loop continues from, executeApprovedToolCall classifies- // approved-tool failures from the throw, and an aborted run must- // unwind rather than look like one more failed tool call.+ // loop continues from, and an aborted run must unwind rather than+ // look like one more failed tool call.throw error;}