🪢 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): Prevent listObservations timeouts (#17496)
Ben Bachemba72c6f73513
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex f54bde9a02..316237b4c7 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -2,6 +2,7 @@ import { prisma } from "../../db";import {TupleParam,type ClickHouseClientConfigOptions,+ type ClickHouseSettings,} from "@clickhouse/client";import type {EventsObservation,@@ -1377,6 +1378,7 @@ type PublicApiObservationsQuery = {type BuildObservationsQueryComponentsOptions = {allowUnindexedIoFilters?: boolean;+ clickhouseSettings?: ClickHouseSettings;};const EVENTS_IO_FILTER_TYPE_ERROR =@@ -1580,6 +1582,7 @@ async function getObservationsRowsFromBuilder<T>(projectId: string,queryBuilder: QueryWithParams,extraTags: Record<string, string> = {},+ clickhouseSettings?: ClickHouseSettings,): Promise<Array<T>> {const { query, params } = queryBuilder.buildWithParams();@@ -1588,6 +1591,7 @@ async function getObservationsRowsFromBuilder<T>(params,tags: { projectId, ...extraTags },preferredClickhouseService: "EventsReadOnly",+ clickhouseSettings,});}@@ -1739,6 +1743,8 @@ export const getObservationsV2FromEventsTableForPublicApi = async (await getObservationsRowsFromBuilder<EventsObservationQueryResult>(projectId,builder,+ {},+ options.clickhouseSettings,);return await enrichObservationsWithModelData(diff --git a/web/src/__tests__/server/mcp-error-formatting.servertest.ts b/web/src/__tests__/server/mcp-error-formatting.servertest.tsindex 3ec31a6660..f0522efdd9 100644--- a/web/src/__tests__/server/mcp-error-formatting.servertest.ts+++ b/web/src/__tests__/server/mcp-error-formatting.servertest.ts@@ -27,6 +27,7 @@ import {InvalidRequestError,BaseError,} from "@langfuse/shared";+import { ClickHouseResourceError } from "@langfuse/shared/src/server";describe("MCP Error Formatting", () => {describe("formatErrorForUser", () => {@@ -164,6 +165,33 @@ describe("MCP Error Formatting", () => {});describe("Langfuse standard errors", () => {+ it("should format ClickHouse timeouts with actionable guidance", () => {+ const error = new ClickHouseResourceError(+ "TIMEOUT",+ new Error("ClickHouse internal timeout details"),+ );+ const mcpError = formatErrorForUser(error);++ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);+ expect(mcpError.message).toContain("ClickHouse query timed out");+ expect(mcpError.message).toContain("Narrow the query");+ expect(mcpError.message).not.toContain("internal timeout details");+ });++ it("should format other ClickHouse resource errors without internal details", () => {+ const error = new ClickHouseResourceError(+ "MEMORY_LIMIT",+ new Error("Memory limit exceeded at 215 GiB"),+ );+ const mcpError = formatErrorForUser(error);++ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);+ expect(mcpError.message).toContain(+ ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ );+ expect(mcpError.message).not.toContain("215 GiB");+ });+it("should format UnauthorizedError with auth message", () => {const error = new UnauthorizedError("Invalid API key");const mcpError = formatErrorForUser(error);diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex 5233f40138..8e3ce51998 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -1524,6 +1524,66 @@ describe("MCP Read Tools", () => {).resolves.toMatchObject({ data: [] });});+ it("should limit date-scoped expensive observation access", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleListObservations(+ {+ fields: ["input"],+ fromStartTime: "2026-01-01T00:00:00.000Z",+ toStartTime: "2026-01-16T00:00:00.000Z",+ limit: 50,+ },+ context,+ ),+ ).rejects.toThrow(/maximum range of 14 days/i);++ await expect(+ handleListObservations(+ {+ fields: ["id"],+ fromStartTime: "2026-01-01T00:00:00.000Z",+ toStartTime: "2026-01-16T00:00:00.000Z",+ filter: [+ {+ type: "string",+ column: "input",+ operator: "matches",+ value: "needle",+ },+ ],+ limit: 50,+ },+ context,+ ),+ ).rejects.toThrow(/maximum range of 14 days/i);++ await expect(+ handleListObservations(+ {+ fields: ["input", "output"],+ fromStartTime: "2026-01-01T00:00:00.000Z",+ toStartTime: "2026-01-15T00:00:00.000Z",+ limit: 51,+ },+ context,+ ),+ ).rejects.toThrow(/maximum limit of 50/i);++ await expect(+ handleListObservations(+ {+ fields: ["input"],+ fromStartTime: "2026-01-01T00:00:00.000Z",+ toStartTime: "2026-01-15T00:00:00.000Z",+ limit: 50,+ },+ context,+ ),+ ).resolves.toMatchObject({ data: [] });+ });+it("should treat an exact observation id filter as selective scope", async () => {const { context, projectId } = await createMcpTestSetup();const observation = createObservationEvent({diff --git a/web/src/features/mcp/core/error-formatting.ts b/web/src/features/mcp/core/error-formatting.tsindex c9487914cb..9eeada3db1 100644--- a/web/src/features/mcp/core/error-formatting.ts+++ b/web/src/features/mcp/core/error-formatting.ts@@ -15,7 +15,7 @@ import {LangfuseNotFoundError,InvalidRequestError,} from "@langfuse/shared";-import { logger } from "@langfuse/shared/src/server";+import { ClickHouseResourceError, logger } from "@langfuse/shared/src/server";/*** Format an error for MCP response.@@ -76,6 +76,19 @@ export function formatErrorForUser(error: unknown): McpError {return new McpError(ErrorCode.InvalidRequest, error.message);}+ if (error instanceof ClickHouseResourceError) {+ logger.warn("MCP ClickHouse resource limit exceeded", {+ errorType: error.errorType,+ tags: error.tags,+ });+ return new McpError(+ ErrorCode.InvalidRequest,+ error.errorType === "TIMEOUT"+ ? "The ClickHouse query timed out. Narrow the query and try again."+ : ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ );+ }+if (error instanceof BaseError && error.httpCode >= 500) {logger.error("MCP BaseError (server-side)", {name: error.name,diff --git a/web/src/features/mcp/server/observations/schema.ts b/web/src/features/mcp/server/observations/schema.tsindex 1674b24801..014ad86319 100644--- a/web/src/features/mcp/server/observations/schema.ts+++ b/web/src/features/mcp/server/observations/schema.ts@@ -36,7 +36,7 @@ type ObservationMcpFieldType =| "unknown";const EXPENSIVE_FIELD_SCOPE_REQUIREMENT =- "Requires traceId, an exact id filter, or both fromStartTime and toStartTime.";+ "Requires traceId, an exact id filter, or both fromStartTime and toStartTime with a maximum range of 14 days.";const OBSERVATION_MCP_FIELDS = OBSERVATION_FIELD_GROUPS_PUBLIC_API.flatMap((group) => OBSERVATION_FIELD_GROUP_FIELD_NAMES[group],diff --git a/web/src/features/mcp/server/observations/tools/listObservations.ts b/web/src/features/mcp/server/observations/tools/listObservations.tsindex 67c6698a31..17574c09b9 100644--- a/web/src/features/mcp/server/observations/tools/listObservations.ts+++ b/web/src/features/mcp/server/observations/tools/listObservations.ts@@ -55,6 +55,10 @@ const EXPENSIVE_OBSERVATION_ACCESS_COLUMNS = new Set(["metadata",]);+const EXPENSIVE_OBSERVATION_MAX_RANGE_MS = 14 * 24 * 60 * 60 * 1000;+const EXPENSIVE_OBSERVATION_MAX_IO_LIMIT = 50;+const MCP_OBSERVATIONS_MAX_EXECUTION_TIME_SECONDS = 25;+const OBSERVATION_MCP_FILTER_COLUMN_TYPES = new Map(eventsTableCols.filter((column) =>@@ -313,14 +317,6 @@ const hasObservationIdFilter = (filters: ListObservationsInput["filter"]) =>filter.value.length > 0,) ?? false;-const hasValidStartTimeBound = (input: ListObservationsInput) => {- if (!input.fromStartTime || !input.toStartTime) return false;- return (- new Date(input.fromStartTime).getTime() <- new Date(input.toStartTime).getTime()- );-};-// Initially, we return io/metadata in full only if some limits are setconst assertAllowedExpensiveObservationAccess = (input: ListObservationsInput,@@ -342,20 +338,35 @@ const assertAllowedExpensiveObservationAccess = (if (expensiveColumns.size === 0) return;- const hasSelectiveScope =- Boolean(input.traceId) ||- hasObservationIdFilter(input.filter) ||- hasValidStartTimeBound(input);+ if (input.traceId || hasObservationIdFilter(input.filter)) return;- if (hasSelectiveScope) return;+ if (!input.fromStartTime || !input.toStartTime) {+ throw new InvalidRequestError(+ `Accessing observation ${Array.from(expensiveColumns)+ .sort()+ .join(+ ", ",+ )} requires traceId, an id filter, or both fromStartTime and toStartTime with a maximum range of 14 days.`,+ );+ }- throw new InvalidRequestError(- `Accessing observation ${Array.from(expensiveColumns)- .sort()- .join(- ", ",- )} requires traceId, an id filter, or both fromStartTime and toStartTime.`,+ const rangeMs =+ new Date(input.toStartTime).getTime() -+ new Date(input.fromStartTime).getTime();+ if (rangeMs <= 0 || rangeMs > EXPENSIVE_OBSERVATION_MAX_RANGE_MS) {+ throw new InvalidRequestError(+ "Accessing observation input, output, or metadata by date requires a maximum range of 14 days.",+ );+ }++ const projectsIo = projectionFields.some(+ (field) => field === "input" || field === "output",);+ if (projectsIo && input.limit > EXPENSIVE_OBSERVATION_MAX_IO_LIMIT) {+ throw new InvalidRequestError(+ `Projecting observation input or output by date supports a maximum limit of ${EXPENSIVE_OBSERVATION_MAX_IO_LIMIT}.`,+ );+ }};export const [listObservationsTool, handleListObservations] = defineTool({@@ -368,7 +379,7 @@ export const [listObservationsTool, handleListObservations] = defineTool({"",'By default this returns compact summary fields. Use fields: ["*"] for the full observation, or pass specific field names to limit the response size.','Important: if you request metadata explicitly, for example fields: ["id", "metadata"], metadata values are truncated to 200 UTF-8 characters per key unless you also pass expandMetadataKeys with the keys that may need full values.',- "Requests that project or filter input, output, or metadata must include traceId, an id filter, or both fromStartTime and toStartTime.",+ "Requests that project or filter input, output, or metadata must include traceId, an id filter, or a date range of at most 14 days. Date-scoped input/output projections support a maximum limit of 50.",].join("\n"),baseSchema: ListObservationsBaseSchema,inputSchema: ListObservationsInputSchema,@@ -414,31 +425,39 @@ export const [listObservationsTool, handleListObservations] = defineTool({"mcp.field_groups": fieldGroups.join(","),});- const items = await getObservationsV2FromEventsTableForPublicApi({- projectId: context.projectId,- page: 0,- limit: input.limit,- traceId: input.traceId,- userId: input.userId,- level: input.level,- name: input.name,- type: input.type,- environment: input.environment,- parentObservationId: input.parentObservationId,- isRootObservation: input.isRootObservation,- fromStartTime: dataAccessWindow.effectiveFromTimestamp?.toISOString(),- toStartTime: input.toStartTime,- version: input.version,- advancedFilters,- cursor: input.cursor- ? EncodedObservationsCursorV2.parse(input.cursor)- : undefined,- fields: fieldGroups,- expandMetadataKeys: getMetadataExpansionForProjection(- projectionFields,- input.expandMetadataKeys,- ),- });+ const items = await getObservationsV2FromEventsTableForPublicApi(+ {+ projectId: context.projectId,+ page: 0,+ limit: input.limit,+ traceId: input.traceId,+ userId: input.userId,+ level: input.level,+ name: input.name,+ type: input.type,+ environment: input.environment,+ parentObservationId: input.parentObservationId,+ isRootObservation: input.isRootObservation,+ fromStartTime:+ dataAccessWindow.effectiveFromTimestamp?.toISOString(),+ toStartTime: input.toStartTime,+ version: input.version,+ advancedFilters,+ cursor: input.cursor+ ? EncodedObservationsCursorV2.parse(input.cursor)+ : undefined,+ fields: fieldGroups,+ expandMetadataKeys: getMetadataExpansionForProjection(+ projectionFields,+ input.expandMetadataKeys,+ ),+ },+ {+ clickhouseSettings: {+ max_execution_time: MCP_OBSERVATIONS_MAX_EXECUTION_TIME_SECONDS,+ },+ },+ );const hasMore = items.length > input.limit;const dataToReturn = hasMore ? items.slice(0, input.limit) : items;