🪢 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
feat(mcp): Make observations available via MCP (#13656)
Ben Bachem058f54581d0f
diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.tsindex 030b260548..edec4f84ae 100644--- a/packages/shared/src/eventsTable.ts+++ b/packages/shared/src/eventsTable.ts@@ -1,8 +1,14 @@import { type ColumnDefinition } from "./tableDefinitions";+type MutableDeep<T> = T extends readonly (infer U)[]+ ? MutableDeep<U>[]+ : T extends object+ ? { -readonly [K in keyof T]: MutableDeep<T[K]> }+ : T;+// Column definitions for the ClickHouse events table// Used for filtering, sorting, and mapping UI columns to ClickHouse columns-export const eventsTableCols: ColumnDefinition[] = [+const eventsTableColsDefinition = [{name: "ID",id: "id",@@ -330,4 +336,53 @@ export const eventsTableCols: ColumnDefinition[] = [type: "boolean",internal: "e.experiment_item_root_span_id = e.span_id",},-];+] as const satisfies readonly ColumnDefinition[];++// TODO: Remove MutableDeep once consumers accept readonly column definitions.+export const eventsTableCols =+ eventsTableColsDefinition as unknown as MutableDeep<+ typeof eventsTableColsDefinition+ > &+ ColumnDefinition[];++type EventsTableColumnId = (typeof eventsTableColsDefinition)[number]["id"];++// Subset of columns that are allowed to be used as filters in the MCP observations API+const OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMN_IDS = [+ "id",+ "traceId",+ "startTime",+ "endTime",+ "name",+ "type",+ "environment",+ "version",+ "userId",+ "sessionId",+ "traceName",+ "level",+ "statusMessage",+ "promptName",+ "promptVersion",+ "modelId",+ "providedModelName",+ "totalCost",+ "inputTokens",+ "outputTokens",+ "totalTokens",+ "inputCost",+ "outputCost",+ "latency",+ "timeToFirstToken",+ "input",+ "output",+ "metadata",+ "traceTags",+ "hasParentObservation",+] as const satisfies readonly EventsTableColumnId[];++export type ObservationMcpAllowedEventsTableFilterColumn =+ (typeof OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMN_IDS)[number];++export const OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS: ReadonlySet<EventsTableColumnId> =+ new Set(OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMN_IDS);diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex 3e05c92570..befa6b3d02 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -1,3 +1,7 @@+import {+ OBSERVATION_FIELD_GROUPS_PUBLIC_API,+ ObservationFieldGroupPublicApi,+} from "../../../domain/observation-field-groups";import { OBSERVATIONS_TO_TRACE_INTERVAL } from "../../repositories/constants";import { FilterList, StringFilter } from "./clickhouse-filter";@@ -415,6 +419,15 @@ const FIELD_SETS = {export type FieldSetName = keyof typeof FIELD_SETS;+export const OBSERVATION_FIELD_GROUP_FIELD_NAMES = Object.fromEntries(+ OBSERVATION_FIELD_GROUPS_PUBLIC_API.map((group) => [+ group,+ FIELD_SETS[group],+ ]),+) as {+ [K in ObservationFieldGroupPublicApi]: (typeof FIELD_SETS)[K];+};+/*** Aggregation fields for trace-level queries* These fields use ClickHouse aggregation functions and require GROUP BY@@ -926,6 +939,7 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<private ioFields: { truncated: boolean; charLimit?: number } | null = null;// Metadata expansion config: null = use truncated (default), string[] = expand specific keys, empty array = expand allprivate metadataExpansionKeys: string[] | null = null;+ private shouldForceFullTable = false;// Raw SELECT expressions for custom columns (e.g., from CTEs)private rawSelectExpressions: string[] = [];@@ -995,6 +1009,14 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<return this;}+ /**+ * Force queries to read from events_full instead of events_core.+ */+ forceFullTable(): this {+ this.shouldForceFullTable = true;+ return this;+ }+/*** Build the SELECT clause for row-level queries*/@@ -1077,7 +1099,7 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<const needsFullMetadata =this.metadataExpansionKeys !== null && this.selectFields.has("metadata");- return needsFullIO || needsFullMetadata;+ return needsFullIO || needsFullMetadata || this.shouldForceFullTable;}/**diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 4309063faf..bc55e80f81 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -40,6 +40,7 @@ export {EventsSessionAggregationQueryBuilder,EventsQueryBuilder,ExperimentsAggregationQueryBuilder,+ OBSERVATION_FIELD_GROUP_FIELD_NAMES,buildEventsFullTableSplitQuery,type CTESchema,type CTEWithSchema,diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 09ea87bae3..6aee2823ee 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -78,7 +78,6 @@ import {buildEventsFullTableSplitQuery,type QueryWithParams,type SessionEventsMetricsRow,- type FieldSetName,OrderByEntry,} from "../queries/clickhouse-sql/event-query-builder";import { type EventsObservationPublic } from "../queries/createGenerationsQuery";@@ -934,6 +933,13 @@ function buildObservationsQueryComponents(const hasTraceFilter = observationsFilter.some((f) => f.clickhouseTable === "traces",);+ const filtersNeedFullTable = observationsFilter.some(+ (f) =>+ f.clickhouseTable.startsWith("events") &&+ (f.field === "e.input" ||+ f.field === "e.output" ||+ f.field === "metadata"),+ );// Extract time filter and apply filtersconst startTimeFrom = extractTimeFilter(observationsFilter);@@ -956,6 +962,7 @@ function buildObservationsQueryComponents(// Build query with joins and filters (no CTEs)const queryBuilder = new EventsQueryBuilder({ projectId })+ .when(filtersNeedFullTable, (b) => b.forceFullTable()).when(hasTraceFilter, (b) =>b.leftJoin("traces t",@@ -1528,9 +1535,17 @@ export const updateEvents = async (* Get grouped provided model names from events table* Used for filter options*/+type GroupedEventsFilterOptions = {+ extraWhereRaw?: string;+ limit?: number;+ offset?: number;+ orderBy?: string;+};+export const getEventsGroupedByModel = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1551,8 +1566,10 @@ export const getEventsGroupedByModel = async (.whereRaw("e.provided_model_name IS NOT NULL AND length(e.provided_model_name) > 0",)- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(+ opts?.orderBy ?? "ORDER BY count() DESC, e.provided_model_name ASC",+ )+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -1577,6 +1594,7 @@ export const getEventsGroupedByModel = async (export const getEventsGroupedByModelId = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1595,8 +1613,8 @@ export const getEventsGroupedByModelId = async (}).where(appliedEventsFilter).whereRaw("e.model_id IS NOT NULL AND length(e.model_id) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.model_id ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -1621,6 +1639,7 @@ export const getEventsGroupedByModelId = async (export const getEventsGroupedByName = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1639,8 +1658,8 @@ export const getEventsGroupedByName = async (}).where(appliedEventsFilter).whereRaw("e.name IS NOT NULL AND length(e.name) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.name ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -1665,7 +1684,7 @@ export const getEventsGroupedByName = async (export const getEventsGroupedByTraceName = async (projectId: string,filter: FilterState,- opts?: { extraWhereRaw?: string },+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1684,8 +1703,8 @@ export const getEventsGroupedByTraceName = async (}).where(appliedEventsFilter).whereRaw("e.trace_name IS NOT NULL AND length(e.trace_name) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.trace_name ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);if (opts?.extraWhereRaw) queryBuilder.whereRaw(opts.extraWhereRaw);@@ -1719,7 +1738,8 @@ export const getEventsGroupedByTraceName = async (export const getEventsGroupedByTraceTags = async (projectId: string,filter: FilterState,- opts?: { extraWhereRaw?: string },+ // We do not support counts for tags so changing the orderBy does not make sense. Therefore, we omit orderBy from options.+ opts?: Pick<GroupedEventsFilterOptions, "extraWhereRaw" | "limit" | "offset">,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1751,7 +1771,7 @@ export const getEventsGroupedByTraceTags = async (.from("filtered_events", "fe").select("DISTINCT arrayJoin(fe.tags) AS tag").orderBy("ORDER BY tag ASC")- .limit(1000, 0);+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = tagsQueryBuilder.buildWithParams();@@ -1782,6 +1802,7 @@ export const getEventsGroupedByTraceTags = async (export const getEventsGroupedByPromptName = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1801,8 +1822,8 @@ export const getEventsGroupedByPromptName = async (.whereRaw("e.type = 'GENERATION'").whereRaw("e.prompt_name IS NOT NULL AND e.prompt_name != ''").where(appliedEventsFilter)- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.prompt_name ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -1828,6 +1849,7 @@ export const getEventsGroupedByPromptName = async (export const getEventsGroupedByType = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1846,8 +1868,8 @@ export const getEventsGroupedByType = async (}).where(appliedEventsFilter).whereRaw("e.type IS NOT NULL AND length(e.type) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.type ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -1872,7 +1894,7 @@ export const getEventsGroupedByType = async (export const getEventsGroupedByUserId = async (projectId: string,filter: FilterState,- opts?: { extraWhereRaw?: string },+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1893,8 +1915,8 @@ export const getEventsGroupedByUserId = async (}).where(appliedEventsFilter).whereRaw("e.user_id IS NOT NULL AND length(e.user_id) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.user_id ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);if (opts?.extraWhereRaw) queryBuilder.whereRaw(opts.extraWhereRaw);@@ -1921,6 +1943,7 @@ export const getEventsGroupedByUserId = async (export const getEventsGroupedByVersion = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1941,8 +1964,8 @@ export const getEventsGroupedByVersion = async (}).where(appliedEventsFilter).whereRaw("e.version IS NOT NULL AND length(e.version) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.version ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -1967,6 +1990,7 @@ export const getEventsGroupedByVersion = async (export const getEventsGroupedBySessionId = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -1987,8 +2011,8 @@ export const getEventsGroupedBySessionId = async (}).where(appliedEventsFilter).whereRaw("e.session_id IS NOT NULL AND length(e.session_id) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.session_id ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -2013,6 +2037,7 @@ export const getEventsGroupedBySessionId = async (export const getEventsGroupedByLevel = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -2033,8 +2058,8 @@ export const getEventsGroupedByLevel = async (}).where(appliedEventsFilter).whereRaw("e.level IS NOT NULL AND length(e.level) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.level ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -2059,6 +2084,7 @@ export const getEventsGroupedByLevel = async (export const getEventsGroupedByEnvironment = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -2079,8 +2105,8 @@ export const getEventsGroupedByEnvironment = async (}).where(appliedEventsFilter).whereRaw("e.environment IS NOT NULL AND length(e.environment) > 0")- .orderBy("ORDER BY count() DESC")- .limit(1000, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.environment ASC")+ .limit(opts?.limit ?? 1000, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -2126,7 +2152,7 @@ export const getEventsGroupedByExperimentDatasetId = async (.whereRaw("e.experiment_dataset_id IS NOT NULL AND length(e.experiment_dataset_id) > 0",)- .orderBy("ORDER BY count() DESC")+ .orderBy("ORDER BY count() DESC, e.experiment_dataset_id ASC").limit(1000, 0);const { query, params } = queryBuilder.buildWithParams();@@ -2173,7 +2199,7 @@ export const getEventsGroupedByExperimentId = async (}).where(appliedEventsFilter).whereRaw("e.experiment_id IS NOT NULL AND length(e.experiment_id) > 0")- .orderBy("ORDER BY count() DESC")+ .orderBy("ORDER BY count() DESC, e.experiment_id ASC").limit(1000, 0);const { query, params } = queryBuilder.buildWithParams();@@ -2217,7 +2243,7 @@ export const getEventsGroupedByExperimentName = async (}).where(appliedEventsFilter).whereRaw("e.experiment_name IS NOT NULL AND length(e.experiment_name) > 0")- .orderBy("ORDER BY count() DESC")+ .orderBy("ORDER BY count() DESC, e.experiment_name ASC").limit(1000, 0);const { query, params } = queryBuilder.buildWithParams();@@ -2243,6 +2269,7 @@ export const getEventsGroupedByExperimentName = async (export const getEventsGroupedByHasParentObservation = async (projectId: string,filter: FilterState,+ opts?: GroupedEventsFilterOptions,) => {const eventsFilter = new FilterList(createFilterFromFilterState(@@ -2261,8 +2288,8 @@ export const getEventsGroupedByHasParentObservation = async ("(e.parent_span_id != '') as hasParentObservation, count() as count",}).where(appliedEventsFilter)- .orderBy("ORDER BY hasParentObservation ASC")- .limit(2, 0);+ .orderBy(opts?.orderBy ?? "ORDER BY hasParentObservation ASC")+ .limit(opts?.limit ?? 2, opts?.offset ?? 0);const { query, params } = queryBuilder.buildWithParams();@@ -2305,7 +2332,7 @@ export const getEventsGroupedByToolName = async (}).where(appliedEventsFilter).whereRaw("length(mapKeys(e.tool_definitions)) > 0")- .orderBy("ORDER BY count() DESC")+ .orderBy("ORDER BY count() DESC, toolName ASC").limit(1000, 0);const { query, params } = queryBuilder.buildWithParams();@@ -2350,7 +2377,7 @@ export const getEventsGroupedByCalledToolName = async (}).where(appliedEventsFilter).whereRaw("length(e.tool_call_names) > 0")- .orderBy("ORDER BY count() DESC")+ .orderBy("ORDER BY count() DESC, calledToolName ASC").limit(1000, 0);const { query, params } = queryBuilder.buildWithParams();@@ -3000,7 +3027,7 @@ export const getEventsForBlobStorageExport = function (queryBuilder.selectIO(false); // Full I/O, no truncation} else if (group !== "model") {// model_export is selected below via needsModelFields to avoid double-selecting- queryBuilder.selectFieldSet(group as FieldSetName);+ queryBuilder.selectFieldSet(group);}}diff --git a/web/src/__tests__/server/event-query-builder.servertest.ts b/web/src/__tests__/server/event-query-builder.servertest.tsindex 7e6ae25ed9..d9293c01b2 100644--- a/web/src/__tests__/server/event-query-builder.servertest.ts+++ b/web/src/__tests__/server/event-query-builder.servertest.ts@@ -146,6 +146,17 @@ describe("EventsQueryBuilder", () => {expect(defaultQuery).toContain('e.tool_call_names as "tool_call_names"');});+ it("should query events_full when forceFullTable is enabled", () => {+ const query = new EventsQueryBuilder({+ projectId: "test-project",+ })+ .selectFieldSet("core")+ .forceFullTable()+ .buildWithParams().query;++ expect(query).toContain("FROM events_full e");+ });+it("should include pricing tier fields in observation list, detail, usage, and export field sets", () => {const buildQuery = (...fieldSets: Parameters<EventsQueryBuilder["selectFieldSet"]>diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex 82d144915b..27b0c51db5 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -14,14 +14,37 @@ vi.mock("@langfuse/shared/src/server", async () => {});import { nanoid } from "nanoid";+import { randomUUID } from "crypto";import { prisma } from "@langfuse/shared/src/db";+import { createEvent, createEventsCh } from "@langfuse/shared/src/server";import {createMcpTestSetup,createPromptInDb,verifyToolAnnotations,} from "./mcp-helpers";+import { env } from "@/src/env.mjs";// Import MCP tool handlers directly+import {+ getObservationTool,+ handleGetObservation,+} from "@/src/features/mcp/features/observations/tools/getObservation";+import {+ getObservationFieldSchemaTool,+ handleGetObservationFieldSchema,+} from "@/src/features/mcp/features/observations/tools/getObservationFieldSchema";+import {+ getObservationFilterSchemaTool,+ handleGetObservationFilterSchema,+} from "@/src/features/mcp/features/observations/tools/getObservationFilterSchema";+import {+ getObservationFilterValuesTool,+ handleGetObservationFilterValues,+} from "@/src/features/mcp/features/observations/tools/getObservationFilterValues";+import {+ listObservationsTool,+ handleListObservations,+} from "@/src/features/mcp/features/observations/tools/listObservations";import {getPromptTool,handleGetPrompt,@@ -35,7 +58,934 @@ import {handleListPrompts,} from "@/src/features/mcp/features/prompts/tools/listPrompts";+const maybeEventsTable =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ ? describe+ : describe.skip;++const createObservationEvent = (params: {+ projectId: string;+ traceId?: string;+ observationId?: string;+ name?: string;+ type?: "GENERATION" | "SPAN" | "EVENT";+ startTime?: Date;+ parentObservationId?: string | null;+ providedModelName?: string;+ input?: string;+ output?: string;+ metadata?: Record<string, string>;+ tags?: string[];+ userId?: string;+ sessionId?: string;+ totalCost?: number;+}) => {+ const observationId = params.observationId ?? randomUUID();+ const startTime = params.startTime ?? new Date();+ const metadata = params.metadata ?? { source: "mcp-test" };+ const metadataKeys = Object.keys(metadata).sort();++ return createEvent({+ id: observationId,+ span_id: observationId,+ trace_id: params.traceId ?? randomUUID(),+ parent_span_id: params.parentObservationId ?? null,+ project_id: params.projectId,+ name: params.name ?? `mcp-observation-${nanoid()}`,+ type: params.type ?? "GENERATION",+ level: "DEFAULT",+ start_time: startTime.getTime() * 1000,+ end_time: startTime.getTime() * 1000 + 1000 * 1000,+ input: params.input ?? "Observation input",+ output: params.output ?? "Observation output",+ metadata_names: metadataKeys,+ metadata_values: metadataKeys.map((key) => metadata[key]),+ provided_model_name: params.providedModelName ?? "gpt-4o-mini",+ ...(params.totalCost === undefined+ ? {}+ : { cost_details: { total: params.totalCost } }),+ tags: params.tags ?? [],+ user_id: params.userId ?? null,+ session_id: params.sessionId ?? null,+ });+};+describe("MCP Read Tools", () => {+ describe("getObservationFieldSchema tool", () => {+ it("should have readOnlyHint annotation", () => {+ verifyToolAnnotations(getObservationFieldSchemaTool, {+ readOnlyHint: true,+ });+ });++ it("should return the observation projection field schema", async () => {+ const { context } = await createMcpTestSetup();++ const result = (await handleGetObservationFieldSchema({}, context)) as {+ resource: string;+ defaultFields: string[];+ fields: Record<+ string,+ {+ type: string;+ nullable: boolean;+ default: boolean;+ expensive: boolean;+ sensitive: boolean;+ description?: string;+ }+ >;+ };++ expect(result.resource).toBe("observation");+ expect(result.defaultFields).toEqual(+ expect.arrayContaining([+ "id",+ "traceId",+ "parentObservationId",+ "name",+ "type",+ "level",+ "statusMessage",+ "startTime",+ "endTime",+ "latency",+ "providedModelName",+ ]),+ );+ expect(result.fields.providedModelName.default).toBe(true);+ expect(result.fields.providedModelName.type).toBe("string");+ expect(result.fields.providedModelName.nullable).toBe(true);+ expect(result.fields.startTime.type).toBe("datetime");+ expect(result.fields.startTime.nullable).toBe(false);+ expect(result.fields.costDetails.type).toBe("map<string, number>");+ expect(result.fields.input.expensive).toBe(true);+ expect(result.fields.input.sensitive).toBe(true);+ expect(result.fields.metadata.expensive).toBe(true);+ expect(result.fields.metadata.description).toContain(+ "truncated to 200 UTF-8 characters per key",+ );+ expect(result.fields.userId.sensitive).toBe(true);+ });+ });++ describe("getObservationFilterSchema tool", () => {+ it("should have readOnlyHint annotation", () => {+ verifyToolAnnotations(getObservationFilterSchemaTool, {+ readOnlyHint: true,+ });+ });++ it("should return public-compatible observation filter schema", async () => {+ const { context } = await createMcpTestSetup();++ const result = (await handleGetObservationFilterSchema({}, context)) as {+ resource: string;+ columns: Record<string, { type: string; operators: string[] }>;+ };++ expect(result.resource).toBe("observation");+ expect(result.columns.providedModelName.type).toBe("stringOptions");+ expect(result.columns.tags.type).toBe("arrayOptions");+ expect(result.columns.traceTags).toBeUndefined();+ expect(result.columns.comments).toBeUndefined();+ expect(result.columns.scores).toBeUndefined();+ expect(result.columns.name.operators).toContain("any of");+ });++ it.each([+ ["name", "stringOptions", true],+ ["type", "stringOptions", false],+ ["environment", "stringOptions", true],+ ["version", "string", true],+ ["userId", "string", true],+ ["sessionId", "string", true],+ ["traceName", "stringOptions", true],+ ["level", "stringOptions", false],+ ["promptName", "stringOptions", true],+ ["modelId", "stringOptions", true],+ ["providedModelName", "stringOptions", true],+ ["tags", "arrayOptions", false],+ ["hasParentObservation", "boolean", false],+ ])(+ "should expose the %s column used by observation filter values",+ async (column, type, nullable) => {+ const { context } = await createMcpTestSetup();++ const result = (await handleGetObservationFilterSchema(+ {},+ context,+ )) as {+ columns: Record<+ string,+ { type: string; operators: string[]; nullable: boolean }+ >;+ };++ expect(result.columns[column]).toEqual(+ expect.objectContaining({+ type,+ nullable,+ operators: expect.any(Array),+ }),+ );+ expect(result.columns[column]?.operators.length).toBeGreaterThan(0);+ },+ );+ });++ maybeEventsTable("listObservations tool", () => {+ it("should have readOnlyHint annotation", () => {+ verifyToolAnnotations(listObservationsTool, { readOnlyHint: true });+ });++ it("should expose object-shaped advanced filters in the tool schema", () => {+ const filterSchema = listObservationsTool.inputSchema.properties+ .filter as+ | {+ type?: string;+ items?: {+ anyOf?: Array<{+ type?: string;+ properties?: Record<+ string,+ {+ const?: unknown;+ enum?: unknown[];+ type?: string;+ }+ >;+ required?: string[];+ }>;+ oneOf?: Array<{+ type?: string;+ properties?: Record<+ string,+ {+ const?: unknown;+ enum?: unknown[];+ type?: string;+ }+ >;+ required?: string[];+ }>;+ };+ }+ | undefined;++ expect(filterSchema?.type).toBe("array");+ const filterVariants =+ filterSchema?.items?.anyOf ?? filterSchema?.items?.oneOf;+ const totalCostSchemas =+ filterVariants?.filter(+ (schema) =>+ schema.properties?.column?.const === "totalCost" ||+ schema.properties?.column?.enum?.includes("totalCost"),+ ) ?? [];+ const totalCostSchema = totalCostSchemas[0];++ expect(totalCostSchemas).not.toHaveLength(0);+ expect(+ totalCostSchemas.every(+ (schema) => schema.properties?.type?.const === "number",+ ),+ ).toBe(true);++ expect(totalCostSchema?.type).toBe("object");+ expect(totalCostSchema?.required).toEqual(+ expect.arrayContaining(["column", "operator", "value"]),+ );+ expect(totalCostSchema?.required).not.toContain("type");+ expect(totalCostSchema?.properties?.type?.const).toBe("number");+ expect(totalCostSchema?.properties?.operator?.enum).toEqual(+ expect.arrayContaining([">", "<", ">=", "<="]),+ );+ expect(totalCostSchema?.properties?.value?.type).toBe("number");+ });++ it("should list observations with compact default projection", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const observation = createObservationEvent({+ projectId,+ traceId,+ name: `mcp-list-default-${nanoid()}`,+ input: "hidden input",+ output: "hidden output",+ metadata: { hidden: "metadata" },+ });++ await createEventsCh([observation]);++ const result = (await handleListObservations(+ { traceId, limit: 100 },+ context,+ )) as {+ data: Array<Record<string, unknown>>;+ meta: Record<string, unknown>;+ };++ const createdObservation = result.data.find(+ (item) => item.id === observation.id,+ );++ expect(createdObservation).toBeDefined();+ expect(createdObservation).toMatchObject({+ id: observation.id,+ traceId,+ name: observation.name,+ type: "GENERATION",+ level: "DEFAULT",+ providedModelName: "gpt-4o-mini",+ });+ expect(createdObservation?.input).toBeUndefined();+ expect(createdObservation?.output).toBeUndefined();+ expect(createdObservation?.metadata).toBeUndefined();+ expect(result.meta).toBeDefined();+ });++ it("should project only requested fields", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const observation = createObservationEvent({+ projectId,+ traceId,+ name: `mcp-list-fields-${nanoid()}`,+ });++ await createEventsCh([observation]);++ const result = (await handleListObservations(+ { traceId, fields: ["id", "name", "type"], limit: 100 },+ context,+ )) as { data: Array<Record<string, unknown>> };++ const createdObservation = result.data.find(+ (item) => item.id === observation.id,+ );++ expect(createdObservation).toEqual({+ id: observation.id,+ name: observation.name,+ type: "GENERATION",+ });+ });++ it("should include payload fields when requested with wildcard projection", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const observation = createObservationEvent({+ projectId,+ traceId,+ name: `mcp-list-wildcard-${nanoid()}`,+ input: "visible input",+ output: "visible output",+ metadata: { customer: "acme" },+ });++ await createEventsCh([observation]);++ const result = (await handleListObservations(+ { traceId, fields: ["*"], limit: 100 },+ context,+ )) as { data: Array<Record<string, unknown>> };++ const createdObservation = result.data.find(+ (item) => item.id === observation.id,+ );++ expect(createdObservation?.input).toBe("visible input");+ expect(createdObservation?.output).toBe("visible output");+ expect(createdObservation?.metadata).toEqual({ customer: "acme" });+ expect(createdObservation).toHaveProperty("userId");+ });++ it("should filter by advanced filters", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const matchingUserId = `mcp-filter-user-${nanoid()}`;++ await createEventsCh([+ createObservationEvent({+ projectId,+ traceId,+ userId: matchingUserId,+ }),+ createObservationEvent({+ projectId,+ traceId,+ userId: `mcp-filter-user-miss-${nanoid()}`,+ }),+ ]);++ const result = (await handleListObservations(+ {+ traceId,+ filter: [+ {+ type: "string",+ column: "userId",+ operator: "=",+ value: matchingUserId,+ },+ ],+ fields: ["id", "userId"],+ limit: 100,+ },+ context,+ )) as { data: Array<{ id: string; userId: string | null }> };++ expect(result.data).toEqual([+ { userId: matchingUserId, id: expect.any(String) },+ ]);+ });++ it("should match advanced input filters beyond the events_core truncation boundary", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const needle = `needle-${nanoid()}`;+ const matchingObservation = createObservationEvent({+ projectId,+ traceId,+ input: `${"x".repeat(250)}${needle}`,+ });++ await createEventsCh([+ matchingObservation,+ createObservationEvent({+ projectId,+ traceId,+ input: "short-input-without-match",+ }),+ ]);++ const result = (await handleListObservations(+ {+ traceId,+ filter: [+ {+ type: "string",+ column: "input",+ operator: "contains",+ value: needle,+ },+ ],+ fields: ["id"],+ limit: 100,+ },+ context,+ )) as { data: Array<{ id: string }> };++ expect(result.data).toEqual([{ id: matchingObservation.id }]);+ });++ it("should require selective scope for full io and metadata access", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleListObservations({ fields: ["input"], limit: 100 }, context),+ ).rejects.toThrow(+ /requires traceId, an id filter, or both fromStartTime and toStartTime/i,+ );++ await expect(+ handleListObservations(+ {+ fields: ["id"],+ filter: [+ {+ type: "string",+ column: "input",+ operator: "contains",+ value: "secret",+ },+ ],+ limit: 100,+ },+ context,+ ),+ ).rejects.toThrow(+ /requires traceId, an id filter, or both fromStartTime and toStartTime/i,+ );++ await expect(+ handleListObservations(+ {+ fields: ["input"],+ filter: [+ {+ type: "stringOptions",+ column: "id",+ operator: "any of",+ value: [randomUUID()],+ },+ ],+ limit: 100,+ },+ context,+ ),+ ).resolves.toMatchObject({ data: [] });++ await expect(+ handleListObservations(+ {+ fields: ["metadata"],+ fromStartTime: "2026-01-01T00:00:00.000Z",+ toStartTime: "2026-01-02T00:00:00.000Z",+ limit: 100,+ },+ context,+ ),+ ).resolves.toMatchObject({ data: [] });+ });++ it("should infer advanced filter type from the column", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const matchingObservation = createObservationEvent({+ projectId,+ traceId,+ name: `mcp-filter-infer-match-${nanoid()}`,+ totalCost: 0.003,+ });++ await createEventsCh([+ matchingObservation,+ createObservationEvent({+ projectId,+ traceId,+ name: `mcp-filter-infer-miss-${nanoid()}`,+ totalCost: 0.001,+ }),+ ]);++ const result = (await handleListObservations(+ {+ traceId,+ filter: [+ { column: "totalCost", operator: ">", value: 0.0029 } as any,+ ],+ fields: ["id", "name"],+ limit: 100,+ },+ context,+ )) as { data: Array<{ id: string; name: string }> };++ expect(result.data).toEqual([+ { id: matchingObservation.id, name: matchingObservation.name },+ ]);+ });++ it("should reject explicit advanced filters with a mismatched column type", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleListObservations(+ {+ filter: [+ {+ type: "string",+ column: "totalCost",+ operator: "=",+ value: "abc",+ },+ ],+ limit: 100,+ },+ context,+ ),+ ).rejects.toThrow(/Validation failed: filter\.0: Invalid input/i);+ });++ it("should reject hidden/internal advanced filter columns", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleListObservations(+ {+ filter: [+ {+ type: "arrayOptions",+ column: "toolNames",+ operator: "any of",+ value: ["internal-tool"],+ },+ ],+ limit: 100,+ },+ context,+ ),+ ).rejects.toThrow(/getObservationFilterSchema/i);++ await expect(+ handleListObservations(+ {+ filter: [+ {+ type: "stringOptions",+ column: "traceTags",+ operator: "any of",+ value: ["internal-name"],+ },+ ],+ limit: 100,+ },+ context,+ ),+ ).rejects.toThrow(/getObservationFilterSchema/i);+ });++ it("should allow the public tags advanced filter column", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const matchingTag = `mcp-filter-tag-${nanoid()}`;+ const matchingObservation = createObservationEvent({+ projectId,+ traceId,+ name: `mcp-filter-tag-match-${nanoid()}`,+ tags: [matchingTag],+ });++ await createEventsCh([+ matchingObservation,+ createObservationEvent({+ projectId,+ traceId,+ name: `mcp-filter-tag-miss-${nanoid()}`,+ tags: [`mcp-filter-tag-miss-${nanoid()}`],+ }),+ ]);++ const result = (await handleListObservations(+ {+ traceId,+ filter: [+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: [matchingTag],+ },+ ],+ fields: ["id"],+ limit: 100,+ },+ context,+ )) as { data: Array<{ id: string }> };++ expect(result.data).toEqual([{ id: matchingObservation.id }]);+ });++ it("should return a cursor when more results are available", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();++ await createEventsCh([+ createObservationEvent({+ projectId,+ traceId,+ name: `mcp-cursor-1-${nanoid()}`,+ startTime: new Date("2026-01-01T00:00:00.000Z"),+ }),+ createObservationEvent({+ projectId,+ traceId,+ name: `mcp-cursor-2-${nanoid()}`,+ startTime: new Date("2026-01-02T00:00:00.000Z"),+ }),+ ]);++ const result = (await handleListObservations(+ { traceId, fields: ["id"], limit: 1 },+ context,+ )) as { data: Array<{ id: string }>; meta: { cursor?: string } };++ expect(result.data).toHaveLength(1);+ expect(result.meta.cursor).toEqual(expect.any(String));+ });++ it("should reject invalid field projections", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleListObservations({ fields: ["*", "id"], limit: 50 }, context),+ ).rejects.toThrow(/mixed wildcard projection/i);++ await expect(+ handleListObservations(+ { fields: ["unknownField"], limit: 50 },+ context,+ ),+ ).rejects.toThrow(/getObservationFieldSchema/i);+ });++ it("should enforce max limit of 100", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleListObservations({ limit: 101 }, context),+ ).rejects.toThrow(/<=100/i);+ });++ it("should use context.projectId for tenant isolation", async () => {+ const { context: context1, projectId: projectId1 } =+ await createMcpTestSetup();+ const { context: context2 } = await createMcpTestSetup();+ const traceId = randomUUID();+ const observation = createObservationEvent({+ projectId: projectId1,+ traceId,+ name: `mcp-list-isolation-${nanoid()}`,+ });++ await createEventsCh([observation]);++ const result1 = (await handleListObservations(+ { traceId, fields: ["id"], limit: 100 },+ context1,+ )) as { data: Array<{ id: string }> };+ const result2 = (await handleListObservations(+ { traceId, fields: ["id"], limit: 100 },+ context2,+ )) as { data: Array<{ id: string }> };++ expect(result1.data.map((item) => item.id)).toContain(observation.id);+ expect(result2.data).toEqual([]);+ });+ });++ maybeEventsTable("getObservation tool", () => {+ it("should have readOnlyHint annotation", () => {+ verifyToolAnnotations(getObservationTool, { readOnlyHint: true });+ });++ it("should fetch a single observation by id with compact default projection", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const observation = createObservationEvent({+ projectId,+ name: `mcp-get-default-${nanoid()}`,+ input: "hidden input",+ });++ await createEventsCh([observation]);++ const result = (await handleGetObservation(+ { observationId: observation.id },+ context,+ )) as Record<string, unknown>;++ expect(result).toMatchObject({+ id: observation.id,+ traceId: observation.trace_id,+ name: observation.name,+ type: "GENERATION",+ providedModelName: "gpt-4o-mini",+ });+ expect(result.input).toBeUndefined();+ expect(result.output).toBeUndefined();+ expect(result.metadata).toBeUndefined();+ });++ it("should return requested fields for a single observation", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const observation = createObservationEvent({+ projectId,+ name: `mcp-get-fields-${nanoid()}`,+ metadata: { customer: "acme" },+ });++ await createEventsCh([observation]);++ const result = (await handleGetObservation(+ { observationId: observation.id, fields: ["id", "metadata"] },+ context,+ )) as Record<string, unknown>;++ expect(result).toEqual({+ id: observation.id,+ metadata: { customer: "acme" },+ });+ });++ it("should reject missing observations", async () => {+ const { context } = await createMcpTestSetup();+ const observationId = randomUUID();++ await expect(+ handleGetObservation({ observationId }, context),+ ).rejects.toThrow(new RegExp(`Observation ${observationId} not found`));+ });++ it("should not fetch cross-project observations", async () => {+ const { projectId: projectId1 } = await createMcpTestSetup();+ const { context: context2 } = await createMcpTestSetup();+ const observation = createObservationEvent({+ projectId: projectId1,+ name: `mcp-get-isolation-${nanoid()}`,+ });++ await createEventsCh([observation]);++ await expect(+ handleGetObservation({ observationId: observation.id }, context2),+ ).rejects.toThrow(/not found/i);+ });+ });++ maybeEventsTable("getObservationFilterValues tool", () => {+ it("should have readOnlyHint annotation", () => {+ verifyToolAnnotations(getObservationFilterValuesTool, {+ readOnlyHint: true,+ });+ });++ it("should return values for a dynamic filter column", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const uniqueModel = `mcp-model-${nanoid()}`;++ await createEventsCh([+ createObservationEvent({+ projectId,+ name: `mcp-filter-values-${nanoid()}`,+ providedModelName: uniqueModel,+ }),+ createObservationEvent({+ projectId,+ name: `mcp-filter-values-${nanoid()}`,+ providedModelName: uniqueModel,+ }),+ ]);++ const result = (await handleGetObservationFilterValues(+ { column: "providedModelName", limit: 100 },+ context,+ )) as {+ column: string;+ values: Array<{ value: string; count?: number }>;+ meta: Record<string, unknown>;+ };++ expect(result.column).toBe("providedModelName");+ expect(result.values).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ value: uniqueModel, count: 2 }),+ ]),+ );+ expect(result.meta).toBeDefined();+ });++ it("should map public tags column to traceTags option source", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const uniqueTag = `mcp-tag-${nanoid()}`;++ await createEventsCh([+ createObservationEvent({+ projectId,+ name: `mcp-filter-tags-${nanoid()}`,+ tags: [uniqueTag],+ }),+ ]);++ const result = (await handleGetObservationFilterValues(+ { column: "tags", limit: 100 },+ context,+ )) as { column: string; values: Array<{ value: string }> };++ expect(result.column).toBe("tags");+ expect(result.values).toEqual(+ expect.arrayContaining([expect.objectContaining({ value: uniqueTag })]),+ );+ });++ it("should return boolean values for hasParentObservation with counts", async () => {+ const { context, projectId } = await createMcpTestSetup();++ await createEventsCh([+ createObservationEvent({+ projectId,+ name: `mcp-filter-has-parent-${nanoid()}`,+ parentObservationId: randomUUID(),+ }),+ createObservationEvent({+ projectId,+ name: `mcp-filter-root-${nanoid()}`,+ parentObservationId: null,+ }),+ ]);++ const result = (await handleGetObservationFilterValues(+ { column: "hasParentObservation", limit: 100 },+ context,+ )) as {+ column: string;+ values: Array<{ value: boolean; count?: number }>;+ };++ expect(result.column).toBe("hasParentObservation");+ expect(result.values).toEqual([+ expect.objectContaining({ value: false, count: 1 }),+ expect.objectContaining({ value: true, count: 1 }),+ ]);+ });++ it("should preserve backend order and paginate filter values with an opaque cursor", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const topName = `mcp-filter-page-top-${nanoid()}`;+ const nextName = `mcp-filter-page-next-${nanoid()}`;+ const lastName = `mcp-filter-page-last-${nanoid()}`;++ await createEventsCh([+ createObservationEvent({ projectId, name: topName }),+ createObservationEvent({ projectId, name: topName }),+ createObservationEvent({ projectId, name: topName }),+ createObservationEvent({ projectId, name: nextName }),+ createObservationEvent({ projectId, name: nextName }),+ createObservationEvent({ projectId, name: lastName }),+ ]);++ const firstPage = (await handleGetObservationFilterValues(+ { column: "name", limit: 2 },+ context,+ )) as {+ values: Array<{ value: string; count?: number }>;+ meta: { cursor?: string };+ };++ expect(firstPage.values).toEqual([+ { value: topName, count: 3 },+ { value: nextName, count: 2 },+ ]);+ expect(firstPage.meta.cursor).toEqual(expect.any(String));++ const secondPage = (await handleGetObservationFilterValues(+ { column: "name", limit: 2, cursor: firstPage.meta.cursor },+ context,+ )) as {+ values: Array<{ value: string; count?: number }>;+ };++ expect(secondPage.values).toEqual([{ value: lastName, count: 1 }]);+ });++ it("should reject invalid cursors and unavailable columns", async () => {+ const { context } = await createMcpTestSetup();++ await expect(+ handleGetObservationFilterValues(+ { column: "name", limit: 100, cursor: "not-base64-json" },+ context,+ ),+ ).rejects.toThrow(/invalid cursor format/i);++ await expect(+ handleGetObservationFilterValues(+ { column: "input", limit: 100 } as any,+ context,+ ),+ ).rejects.toThrow(/validation failed/i);+ });+ });+describe("getPrompt tool", () => {it("should have readOnlyHint annotation", () => {verifyToolAnnotations(getPromptTool, { readOnlyHint: true });diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex e53b8e0739..6cf7ebe3a0 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -35,6 +35,7 @@ import {} from "@langfuse/shared/src/server";import { type timeFilter, type FilterState } from "@langfuse/shared";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import { assertUnreachable } from "@/src/utils/types";type TimeFilter = z.infer<typeof timeFilter>;@@ -75,8 +76,21 @@ interface GetObservationsFilterOptionsParams {projectId: string;startTimeFilter?: TimeFilter[];hasParentObservation?: boolean;+ observationType?: string;}+type EventFilterValueOption = {+ value: string;+ count?: number;+};++type GroupedEventsFilterOptions = {+ extraWhereRaw?: string;+ limit?: number;+ offset?: number;+ orderBy?: string;+};+/*** Get paginated list of events*/@@ -218,13 +232,22 @@ export async function getEventCount(params: GetObservationsCountParams) {return { totalCount };}-/**- * Get all available filter options for events table- */-export async function getEventFilterOptions(+const toFilterValueOptions = <+ TKey extends string,+ TItem extends Record<TKey, string | null> & { count: number },+>(+ items: TItem[],+ key: TKey,+) =>+ items.flatMap((item) => {+ const value = item[key];+ return value === null ? [] : [{ value, count: item.count }];+ });++const getEventFilterOptionsScope = (params: GetObservationsFilterOptionsParams,-) {- const { projectId, startTimeFilter, hasParentObservation } = params;+) => {+ const { startTimeFilter, hasParentObservation, observationType } = params;// Build filter with optional hasParentObservation for scoping filter optionsconst eventsFilter: FilterState = [@@ -239,6 +262,16 @@ export async function getEventFilterOptions(},]: []),+ ...(observationType+ ? [+ {+ column: "type" as const,+ type: "string" as const,+ operator: "=" as const,+ value: observationType,+ },+ ]+ : []),];// Map startTimeFilter to Timestamp column for trace queries@@ -261,6 +294,169 @@ export async function getEventFilterOptions(})): [];+ return {+ eventsFilter,+ traceTimestampFilters,+ traceScoreTimestampFilters,+ };+};++export async function getEventFilterValuePage(+ params: GetObservationsFilterOptionsParams & {+ column:+ | "traceTags"+ | "hasParentObservation"+ | "providedModelName"+ | "modelId"+ | "name"+ | "traceName"+ | "type"+ | "userId"+ | "version"+ | "sessionId"+ | "level"+ | "environment"+ | "promptName";+ limit: number;+ offset: number;+ },+) {+ const { projectId, column, limit, offset } = params;+ const { eventsFilter } = getEventFilterOptionsScope(params);+ const queryLimit = limit + 1;++ const createResultFromGroupedQuery = async <T>(+ query: (+ projectId: string,+ filter: FilterState,+ opts?: GroupedEventsFilterOptions,+ ) => Promise<Array<T & { count?: number }>>,+ valueGetter: (item: T) => string,+ ) => {+ const values = await query(projectId, eventsFilter, {+ limit: queryLimit,+ offset,+ }).then((items) =>+ items.map(+ (item) =>+ ({+ value: valueGetter(item),+ count: item.count,+ }) satisfies EventFilterValueOption,+ ),+ );++ return {+ values: values.slice(0, limit),+ nextOffset: values.length > limit ? offset + limit : undefined,+ };+ };++ if (column === "hasParentObservation") {+ return createResultFromGroupedQuery(+ getEventsGroupedByHasParentObservation,+ (item) => (item.hasParentObservation ? "true" : "false"),+ );+ }++ if (column === "traceTags") {+ // Trace tags do not support counting right now+ return createResultFromGroupedQuery(+ getEventsGroupedByTraceTags,+ (item) => item.tag,+ );+ }++ if (column === "providedModelName") {+ return createResultFromGroupedQuery(+ getEventsGroupedByModel,+ (item) => item.model,+ );+ }++ if (column === "modelId") {+ return createResultFromGroupedQuery(+ getEventsGroupedByModelId,+ (item) => item.modelId,+ );+ }++ if (column === "name") {+ return createResultFromGroupedQuery(+ getEventsGroupedByName,+ (item) => item.name,+ );+ }++ if (column === "traceName") {+ return createResultFromGroupedQuery(+ getEventsGroupedByTraceName,+ (item) => item.traceName,+ );+ }++ if (column === "type") {+ return createResultFromGroupedQuery(+ getEventsGroupedByType,+ (item) => item.type,+ );+ }++ if (column === "userId") {+ return createResultFromGroupedQuery(+ getEventsGroupedByUserId,+ (item) => item.userId,+ );+ }++ if (column === "version") {+ return createResultFromGroupedQuery(+ getEventsGroupedByVersion,+ (item) => item.version,+ );+ }++ if (column === "sessionId") {+ return createResultFromGroupedQuery(+ getEventsGroupedBySessionId,+ (item) => item.sessionId,+ );+ }++ if (column === "level") {+ return createResultFromGroupedQuery(+ getEventsGroupedByLevel,+ (item) => item.level,+ );+ }++ if (column === "environment") {+ return createResultFromGroupedQuery(+ getEventsGroupedByEnvironment,+ (item) => item.environment,+ );+ }++ if (column === "promptName") {+ return createResultFromGroupedQuery(+ getEventsGroupedByPromptName,+ (item) => item.promptName,+ );+ }++ return assertUnreachable(column);+}++/**+ * Get all available filter options for events table+ */+export async function getEventFilterOptions(+ params: GetObservationsFilterOptionsParams,+) {+ const { projectId } = params;+ const { eventsFilter, traceTimestampFilters, traceScoreTimestampFilters } =+ getEventFilterOptionsScope(params);+const [numericScoreNames,categoricalScoreNames,@@ -326,95 +522,34 @@ export async function getEventFilterOptions();return {- providedModelName: providedModelName- .filter((i) => i.model !== null)- .map((i) => ({ value: i.model as string, count: i.count })),- modelId: modelId- .filter((i) => i.modelId !== null)- .map((i) => ({- value: i.modelId as string,- count: i.count,- })),- name: name- .filter((i) => i.name !== null)- .map((i) => ({ value: i.name as string, count: i.count })),+ providedModelName: toFilterValueOptions(providedModelName, "model"),+ modelId: toFilterValueOptions(modelId, "modelId"),+ name: toFilterValueOptions(name, "name"),scores_avg: numericScoreNames.map((score) => score.name),score_categories: categoricalScoreNames,trace_scores_avg: traceNumericScoreNames,trace_score_categories: categoricalScoreNames.filter((score) =>traceCategoricalScoreNames.has(score.label),),- promptName: promptNames- .filter((i) => i.promptName !== null)- .map((i) => ({- value: i.promptName as string,- count: i.count,- })),+ promptName: toFilterValueOptions(promptNames, "promptName"),traceTags: traceTags.filter((i) => i.tag !== null).map((i) => ({- value: i.tag as string,- })),- traceName: traceNames- .filter((i) => i.traceName !== null)- .map((i) => ({- value: i.traceName as string,- count: i.count,- })),- type: types- .filter((i) => i.type !== null)- .map((i) => ({- value: i.type as string,- count: i.count,- })),- userId: userIds- .filter((i) => i.userId !== null)- .map((i) => ({- value: i.userId as string,- count: i.count,- })),- version: versions- .filter((i) => i.version !== null)- .map((i) => ({- value: i.version as string,- count: i.count,- })),- sessionId: sessionIds- .filter((i) => i.sessionId !== null)- .map((i) => ({- value: i.sessionId as string,- count: i.count,- })),- level: levels- .filter((i) => i.level !== null)- .map((i) => ({- value: i.level as string,- count: i.count,- })),- environment: environments- .filter((i) => i.environment !== null)- .map((i) => ({- value: i.environment as string,- count: i.count,- })),- experimentDatasetId: experimentDatasetIds- .filter((i) => i.experimentDatasetId !== null)- .map((i) => ({- value: i.experimentDatasetId as string,- count: i.count,- })),- experimentId: experimentIds- .filter((i) => i.experimentId !== null)- .map((i) => ({- value: i.experimentId as string,- count: i.count,- })),- experimentName: experimentNames- .filter((i) => i.experimentName !== null)- .map((i) => ({- value: i.experimentName as string,- count: i.count,+ value: i.tag,})),+ traceName: toFilterValueOptions(traceNames, "traceName"),+ type: toFilterValueOptions(types, "type"),+ userId: toFilterValueOptions(userIds, "userId"),+ version: toFilterValueOptions(versions, "version"),+ sessionId: toFilterValueOptions(sessionIds, "sessionId"),+ level: toFilterValueOptions(levels, "level"),+ environment: toFilterValueOptions(environments, "environment"),+ experimentDatasetId: toFilterValueOptions(+ experimentDatasetIds,+ "experimentDatasetId",+ ),+ experimentId: toFilterValueOptions(experimentIds, "experimentId"),+ experimentName: toFilterValueOptions(experimentNames, "experimentName"),hasParentObservation: hasParentObservationResults.map((i) => ({// ClickHouse returns UInt8 (0/1) for computed boolean; normalize to "true"/"false"value: i.hasParentObservation ? "true" : "false",@@ -422,10 +557,10 @@ export async function getEventFilterOptions(})),toolNames: toolNames.filter((i) => i.toolName !== null)- .map((i) => ({ value: i.toolName as string })),+ .map((i) => ({ value: i.toolName })),calledToolNames: calledToolNames.filter((i) => i.calledToolName !== null)- .map((i) => ({ value: i.calledToolName as string })),+ .map((i) => ({ value: i.calledToolName })),};}diff --git a/web/src/features/mcp/README.md b/web/src/features/mcp/README.mdindex 45ebbfa856..9b989a2fe3 100644--- a/web/src/features/mcp/README.md+++ b/web/src/features/mcp/README.md@@ -1,6 +1,6 @@# Langfuse MCP Server-Model Context Protocol (MCP) server for Langfuse, enabling AI assistants to interact with your Langfuse prompts programmatically.+Model Context Protocol (MCP) server for Langfuse, enabling AI assistants to interact with Langfuse prompts and read observation data programmatically.## Quick Start (Local Development)@@ -37,14 +37,19 @@ Model Context Protocol (MCP) server for Langfuse, enabling AI assistants to inte--header "Authorization: Basic {your-base64-token}"```-4. **Verify**+4. **Verify prompt tools**In Claude Code: `List all prompts in the project`+5. **Verify observation tools**+ In Claude Code: `List recent Langfuse observations`+---## Available Tools-The MCP server provides 6 tools for prompt management:+The MCP server provides prompt-management tools and read-only observation tools.++### Prompt Tools- **`getPrompt`** - Fetch a specific prompt by name with optional label or version (fully resolved with dependencies)- **`getPromptUnresolved`** - Fetch a specific prompt WITHOUT resolving dependencies (useful for prompt composition analysis)@@ -53,13 +58,26 @@ The MCP server provides 6 tools for prompt management:- **`createChatPrompt`** - Create a new chat prompt version (OpenAI-style messages)- **`updatePromptLabels`** - Add/move labels across prompt versions-**Implementation:** See [`/web/src/features/mcp/features/prompts/tools/`](/web/src/features/mcp/features/prompts/tools/) for detailed schemas, parameters, and examples for each tool.+**Implementation:** See [`/web/src/features/mcp/features/prompts/tools/`](/web/src/features/mcp/features/prompts/tools/) for detailed schemas, parameters, and examples for each prompt tool.++### Observation Tools++Observation tools read from the events table v2 and are project-scoped to the authenticated API key.++- **`listObservations`** - Find observations in the current project with filters, field projection, and cursor pagination+- **`getObservation`** - Fetch one observation by observation ID+- **`getObservationFieldSchema`** - List fields that can be requested from `listObservations` and `getObservation`+- **`getObservationFilterSchema`** - List fields and operators that can be used in `listObservations` advanced filters+- **`getObservationFilterValues`** - Discover available values for supported filter fields, such as names, types, levels, environments, model names, tags, users, or sessions++**Implementation:** See [`/web/src/features/mcp/features/observations/tools/`](/web/src/features/mcp/features/observations/tools/) for detailed schemas and handlers.### Prompt Resolution: `getPrompt` vs `getPromptUnresolved`Langfuse supports **prompt composition** where prompts can reference other prompts via dependency tags like `@@@langfusePrompt:name=xxx|label=yyy@@@`. The MCP server provides two tools for fetching prompts with different resolution behaviors:#### `getPrompt` (Fully Resolved)+- **Use when**: You want the final, executable prompt ready to send to an LLM- **Behavior**: Recursively resolves all dependency tags by fetching and inserting referenced prompts- **Returns**: Final prompt content with all dependencies replaced@@ -70,6 +88,7 @@ Langfuse supports **prompt composition** where prompts can reference other promp```#### `getPromptUnresolved` (Raw)+- **Use when**: You want to analyze prompt composition, debug dependencies, or understand the prompt structure- **Behavior**: Returns raw prompt content with dependency tags intact- **Returns**: Original prompt content with `@@@langfusePrompt:...@@@` tags preserved@@ -80,11 +99,31 @@ Langfuse supports **prompt composition** where prompts can reference other promp```**Use Cases for `getPromptUnresolved`**:+- Understanding how prompts compose together (prompt stacking)- Debugging dependency chains before execution- Analyzing prompt structure and references- Building tools that manage prompt composition+### Observation Inspection++Observation tools let MCP clients inspect traces at the observation level: generations, spans, events, agent steps, tool calls, model usage, cost, latency, payloads, and metadata.++Typical workflow:++1. **Discover fields**: call `getObservationFieldSchema`+2. **Discover filters**: call `getObservationFilterSchema`+3. **Find observations**: call `listObservations` with time, trace, type, level, environment, or advanced filters+4. **Inspect one observation**: call `getObservation` with the returned observation ID++Field projection controls response size:++- Omit `fields` for compact defaults+- Use `fields: ["*"]` for all available fields+- Pass explicit fields such as `["id", "name", "type", "latency", "totalCost"]` for focused responses++Payload and metadata fields can be large and may contain sensitive application data. MCP clients should request `input`, `output`, `metadata`, and `modelParameters` only when needed.+---## Architecture@@ -138,8 +177,8 @@ This design:Tools include hints for clients about their behavior:-- **`readOnly: true`**: Safe operations that don't modify data (getPrompt, listPrompts)-- **`destructive: true`**: Operations that create/modify data (createTextPrompt, createChatPrompt, updatePromptLabels)+- **`readOnlyHint: true`**: Safe operations that don't modify data (getPrompt, getPromptUnresolved, listPrompts, all observation tools)+- **`destructiveHint: true`**: Operations that create/modify data (createTextPrompt, createChatPrompt, updatePromptLabels)Clients like Claude Code can use these annotations to:@@ -148,7 +187,7 @@ Clients like Claude Code can use these annotations to:### Audit Logging-All write operations (createTextPrompt, createChatPrompt, updatePromptLabels) automatically create audit log entries with before/after snapshots.+All write operations (createTextPrompt, createChatPrompt, updatePromptLabels) automatically create audit log entries with before/after snapshots. Observation tools are read-only and do not create audit log entries.---diff --git a/web/src/features/mcp/features/observations/index.ts b/web/src/features/mcp/features/observations/index.tsnew file mode 100644index 0000000000..9880d69a79--- /dev/null+++ b/web/src/features/mcp/features/observations/index.ts@@ -0,0 +1,51 @@+import type { McpFeatureModule } from "../../server/registry";+import {+ getObservationTool,+ handleGetObservation,+} from "./tools/getObservation";+import {+ getObservationFieldSchemaTool,+ handleGetObservationFieldSchema,+} from "./tools/getObservationFieldSchema";+import {+ getObservationFilterSchemaTool,+ handleGetObservationFilterSchema,+} from "./tools/getObservationFilterSchema";+import {+ getObservationFilterValuesTool,+ handleGetObservationFilterValues,+} from "./tools/getObservationFilterValues";+import {+ listObservationsTool,+ handleListObservations,+} from "./tools/listObservations";+import { env } from "@/src/env.mjs";++export const observationsFeature: McpFeatureModule = {+ name: "observations",+ description:+ "Inspect generations, spans, events, and other observations in Langfuse",+ tools: [+ {+ definition: listObservationsTool,+ handler: handleListObservations,+ },+ {+ definition: getObservationTool,+ handler: handleGetObservation,+ },+ {+ definition: getObservationFieldSchemaTool,+ handler: handleGetObservationFieldSchema,+ },+ {+ definition: getObservationFilterSchemaTool,+ handler: handleGetObservationFilterSchema,+ },+ {+ definition: getObservationFilterValuesTool,+ handler: handleGetObservationFilterValues,+ },+ ],+ isEnabled: async () => env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true",+};diff --git a/web/src/features/mcp/features/observations/schema.ts b/web/src/features/mcp/features/observations/schema.tsnew file mode 100644index 0000000000..4ee2858c9b--- /dev/null+++ b/web/src/features/mcp/features/observations/schema.ts@@ -0,0 +1,219 @@+import { z } from "zod";+import {+ OBSERVATION_FIELD_GROUPS_PUBLIC_API,+ type ObservationFieldGroupPublicApi,+ type ObservationMcpAllowedEventsTableFilterColumn,+} from "@langfuse/shared";+import { OBSERVATION_FIELD_GROUP_FIELD_NAMES } from "@langfuse/shared/src/server";++type ObservationMcpFieldMetadata = {+ type: ObservationMcpFieldType;+ nullable?: boolean;+ default?: boolean;+ expensive?: boolean;+ sensitive?: boolean;+ description?: string;+};++type ObservationMcpFieldDefinition = ObservationMcpFieldMetadata & {+ field: ObservationMcpField;+ group: ObservationFieldGroupPublicApi;+};++type ObservationMcpField =+ (typeof OBSERVATION_FIELD_GROUP_FIELD_NAMES)[ObservationFieldGroupPublicApi][number];++type ObservationMcpFieldType =+ | "array"+ | "boolean"+ | "datetime"+ | "map<string, number>"+ | "number"+ | "record"+ | "string"+ | "unknown";++const OBSERVATION_MCP_FIELDS = OBSERVATION_FIELD_GROUPS_PUBLIC_API.flatMap(+ (group) => OBSERVATION_FIELD_GROUP_FIELD_NAMES[group],+);++const OBSERVATION_MCP_FIELD_SET = new Set<string>(OBSERVATION_MCP_FIELDS);++const OBSERVATION_MCP_FIELD_METADATA: Record<+ ObservationMcpField,+ ObservationMcpFieldMetadata+> = {+ id: { type: "string", default: true },+ traceId: { type: "string", nullable: true, default: true },+ startTime: { type: "datetime", default: true },+ endTime: { type: "datetime", nullable: true, default: true },+ projectId: { type: "string", sensitive: true },+ parentObservationId: { type: "string", nullable: true, default: true },+ type: { type: "string", default: true },+ name: { type: "string", nullable: true, default: true },+ level: { type: "string", default: true },+ statusMessage: { type: "string", nullable: true, default: true },+ version: { type: "string", nullable: true },+ environment: { type: "string", nullable: true },+ bookmarked: { type: "boolean" },+ public: { type: "boolean" },+ userId: { type: "string", nullable: true, sensitive: true },+ sessionId: { type: "string", nullable: true, sensitive: true },+ completionStartTime: { type: "datetime", nullable: true },+ createdAt: { type: "datetime" },+ updatedAt: { type: "datetime" },+ input: { type: "unknown", expensive: true, sensitive: true },+ output: { type: "unknown", expensive: true, sensitive: true },+ metadata: {+ type: "record",+ expensive: true,+ sensitive: true,+ description:+ "Metadata values are truncated to 200 UTF-8 characters per key by default. When requesting metadata explicitly, pass expandMetadataKeys with the keys that may need full values.",+ },+ providedModelName: { type: "string", nullable: true, default: true },+ internalModelId: { type: "string", nullable: true },+ modelParameters: {+ type: "record",+ nullable: true,+ expensive: true,+ sensitive: true,+ },+ usageDetails: { type: "map<string, number>" },+ costDetails: { type: "map<string, number>" },+ totalCost: { type: "number", nullable: true },+ promptId: { type: "string", nullable: true },+ promptName: { type: "string", nullable: true },+ promptVersion: { type: "number", nullable: true },+ latency: { type: "number", nullable: true, default: true },+ timeToFirstToken: { type: "number", nullable: true },+ tags: { type: "array", sensitive: true },+ release: { type: "string", nullable: true },+ traceName: { type: "string", nullable: true, sensitive: true },+ usagePricingTierName: { type: "string", nullable: true },+ usagePricingTierId: { type: "string", nullable: true },+} as const;++export type { ObservationMcpField };++export const OBSERVATION_MCP_FIELD_DEFINITIONS: ObservationMcpFieldDefinition[] =+ OBSERVATION_FIELD_GROUPS_PUBLIC_API.flatMap((group) =>+ OBSERVATION_FIELD_GROUP_FIELD_NAMES[group].map((field) => ({+ field,+ group,+ ...OBSERVATION_MCP_FIELD_METADATA[field],+ })),+ );++export const OBSERVATION_MCP_DEFAULT_FIELDS = OBSERVATION_MCP_FIELDS.filter(+ (field) => Boolean(OBSERVATION_MCP_FIELD_METADATA[field].default),+);++const isObservationMcpField = (field: string): field is ObservationMcpField =>+ OBSERVATION_MCP_FIELD_SET.has(field);++export const ObservationFieldsSchema = z+ .array(z.string())+ .optional()+ .superRefine((fields, ctx) => {+ if (!fields) return;++ if (fields.length === 0) {+ ctx.addIssue({+ code: "custom",+ message:+ "Fields array cannot be empty. Use undefined for defaults or specify fields.",+ });+ return;+ }++ const hasWildcard = fields.includes("*");+ if (hasWildcard && fields.length > 1) {+ ctx.addIssue({+ code: "custom",+ message:+ 'Use either fields: ["*"] or explicit field names. Mixed wildcard projection is invalid.',+ });+ return;+ }++ for (const field of fields) {+ if (field !== "*" && !OBSERVATION_MCP_FIELD_SET.has(field)) {+ ctx.addIssue({+ code: "custom",+ message: `Invalid observation field "${field}". Call getObservationFieldSchema for accepted fields.`,+ });+ }+ }+ })+ .describe(+ 'Observation fields to include in the response. Omit for compact defaults, use ["*"] for all available fields, or pass specific field names to keep responses small. Call getObservationFieldSchema to list accepted fields.',+ );++export const ObservationLimitSchema = z.coerce+ .number()+ .int()+ .min(1)+ .max(100)+ .default(50)+ .describe("Number of observations to return (1-100, default: 50)");++export const ExpandMetadataKeysSchema = z+ .array(z.string())+ .optional()+ .describe(+ "Metadata keys that may need full values. Metadata values are truncated to 200 UTF-8 characters per key by default when metadata is projected without this option.",+ );++type ObservationMcpFilterColumn =+ | Exclude<ObservationMcpAllowedEventsTableFilterColumn, "traceTags">+ | "tags";++export type { ObservationMcpFilterColumn };++export const getProjectionFields = (+ fields: string[] | undefined,+): ObservationMcpField[] => {+ if (!fields) return [...OBSERVATION_MCP_DEFAULT_FIELDS];+ if (fields.length === 1 && fields[0] === "*")+ return [...OBSERVATION_MCP_FIELDS];+ return fields.filter(isObservationMcpField);+};++export const getProjectionFieldGroups = (+ fields: ObservationMcpField[],+): ObservationFieldGroupPublicApi[] => {+ const groups = new Set<ObservationFieldGroupPublicApi>(["core"]);+ const projectionFields = new Set(fields);+ for (const definition of OBSERVATION_MCP_FIELD_DEFINITIONS) {+ if (projectionFields.has(definition.field)) {+ groups.add(definition.group);+ }+ }+ return Array.from(groups);+};++export const projectObservation = (+ observation: Record<string, unknown>,+ fields: ObservationMcpField[],+): Record<string, unknown> => {+ const projected: Record<string, unknown> = {};++ for (const field of fields) {+ if (field === "providedModelName" && "model" in observation) {+ projected[field] = observation.model;+ } else if (field in observation) {+ projected[field] = observation[field];+ }+ }++ return projected;+};++export const getMetadataExpansionForProjection = (+ fields: ObservationMcpField[],+ expandMetadataKeys: string[] | undefined,+): string[] | undefined => {+ if (!fields.includes("metadata")) return undefined;+ return expandMetadataKeys;+};diff --git a/web/src/features/mcp/features/observations/tools/getObservation.ts b/web/src/features/mcp/features/observations/tools/getObservation.tsnew file mode 100644index 0000000000..753b6e856e--- /dev/null+++ b/web/src/features/mcp/features/observations/tools/getObservation.ts@@ -0,0 +1,93 @@+import { SpanKind } from "@opentelemetry/api";+import { LangfuseNotFoundError } from "@langfuse/shared";+import { z } from "zod";+import {+ getObservationsV2FromEventsTableForPublicApi,+ instrumentAsync,+} from "@langfuse/shared/src/server";+import { defineTool } from "../../../core/define-tool";+import {+ ExpandMetadataKeysSchema,+ getMetadataExpansionForProjection,+ ObservationFieldsSchema,+ getProjectionFieldGroups,+ getProjectionFields,+ projectObservation,+} from "../schema";++const GetObservationBaseSchema = z.object({+ observationId: z.string().min(1),+ fields: ObservationFieldsSchema,+ expandMetadataKeys: ExpandMetadataKeysSchema,+});++export const [getObservationTool, handleGetObservation] = defineTool({+ name: "getObservation",+ description: [+ "Get the details for a single observation in the current Langfuse project by observation ID.",+ "Use this when you already know the observation ID and want to inspect its timing, model, status, payload, metadata, usage, cost, or prompt fields.",+ "",+ '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.',+ ].join("\n"),+ baseSchema: GetObservationBaseSchema,+ inputSchema: GetObservationBaseSchema,+ handler: async (input, context) => {+ return await instrumentAsync(+ { name: "mcp.observations.get", spanKind: SpanKind.INTERNAL },+ async (span) => {+ const projectionFields = getProjectionFields(input.fields);+ const fieldGroups = getProjectionFieldGroups(projectionFields);++ span.setAttributes({+ "langfuse.project.id": context.projectId,+ "langfuse.org.id": context.orgId,+ "mcp.api_key_id": context.apiKeyId,+ "mcp.observation_id": input.observationId,+ "mcp.projection_fields": projectionFields.join(","),+ "mcp.field_groups": fieldGroups.join(","),+ });++ const items = await getObservationsV2FromEventsTableForPublicApi({+ projectId: context.projectId,+ page: 0,+ limit: 1,+ fields: fieldGroups,+ advancedFilters: [+ {+ type: "stringOptions",+ column: "id",+ operator: "any of",+ value: [input.observationId],+ },+ ],+ expandMetadataKeys: getMetadataExpansionForProjection(+ projectionFields,+ input.expandMetadataKeys,+ ),+ });++ const observation = items.find(+ (item) => item.id === input.observationId,+ );+ if (!observation) {+ throw new LangfuseNotFoundError(+ `Observation ${input.observationId} not found`,+ );+ }++ return projectObservation(+ {+ ...observation,+ parentObservationId:+ observation.parentObservationId === ""+ ? null+ : observation.parentObservationId,+ },+ projectionFields,+ );+ },+ );+ },+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/features/observations/tools/getObservationFieldSchema.ts b/web/src/features/mcp/features/observations/tools/getObservationFieldSchema.tsnew file mode 100644index 0000000000..f8a0e05cf8--- /dev/null+++ b/web/src/features/mcp/features/observations/tools/getObservationFieldSchema.ts@@ -0,0 +1,39 @@+import { defineTool } from "../../../core/define-tool";+import {+ OBSERVATION_MCP_DEFAULT_FIELDS,+ OBSERVATION_MCP_FIELD_DEFINITIONS,+} from "../schema";+import { z } from "zod";++const EmptyInputSchema = z.object({});++export const [getObservationFieldSchemaTool, handleGetObservationFieldSchema] =+ defineTool({+ name: "getObservationFieldSchema",+ description:+ "Show which observation fields can be requested from listObservations and getObservation. The response marks default fields and fields that may be large or contain sensitive application data.",+ baseSchema: EmptyInputSchema,+ inputSchema: EmptyInputSchema,+ handler: async () => {+ return {+ resource: "observation",+ defaultFields: OBSERVATION_MCP_DEFAULT_FIELDS,+ fields: Object.fromEntries(+ OBSERVATION_MCP_FIELD_DEFINITIONS.map((definition) => [+ definition.field,+ {+ type: definition.type,+ nullable: Boolean(definition.nullable),+ default: Boolean(definition.default),+ expensive: Boolean(definition.expensive),+ sensitive: Boolean(definition.sensitive),+ ...(definition.description+ ? { description: definition.description }+ : {}),+ },+ ]),+ ),+ };+ },+ readOnlyHint: true,+ });diff --git a/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.ts b/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.tsnew file mode 100644index 0000000000..34ac8ef2d1--- /dev/null+++ b/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.ts@@ -0,0 +1,73 @@+import { z } from "zod";+import {+ eventsTableCols,+ filterOperators,+ OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS,+} from "@langfuse/shared";+import { defineTool } from "../../../core/define-tool";+import { observationEventsFilterConfig } from "@/src/features/events/config/filter-config";++const EmptyInputSchema = z.object({});++const OBSERVATION_MCP_FILTER_COLUMNS = eventsTableCols+ .filter((column) => {+ for (const allowedColumn of OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS) {+ if (allowedColumn === column.id) return true;+ }+ return false;+ })+ .map((column) =>+ // eventsTableCols uses traceTags for the table/filter id, while the MCP+ // observation shape exposes the field as tags.+ column.id === "traceTags" ? "tags" : column.id,+ );++const OBSERVATION_MCP_FILTER_CONFIG_COLUMN_OVERRIDES: Record<string, string> = {+ tags: "traceTags",+};++export const [+ getObservationFilterSchemaTool,+ handleGetObservationFilterSchema,+] = defineTool({+ name: "getObservationFilterSchema",+ description:+ "Show which observation fields can be used in listObservations filters, including the supported operators for each field.",+ baseSchema: EmptyInputSchema,+ inputSchema: EmptyInputSchema,+ handler: async () => {+ const publicFilterColumnsByConfigColumn = Object.fromEntries(+ OBSERVATION_MCP_FILTER_COLUMNS.map((publicColumn) => [+ OBSERVATION_MCP_FILTER_CONFIG_COLUMN_OVERRIDES[publicColumn] ??+ publicColumn,+ publicColumn,+ ]),+ );++ const columns = Object.fromEntries(+ observationEventsFilterConfig.columnDefinitions+ .filter((column) => column.id in publicFilterColumnsByConfigColumn)+ .map((column) => {+ const publicColumn = publicFilterColumnsByConfigColumn[column.id];++ return [+ publicColumn,+ {+ type: column.type,+ operators: filterOperators[column.type],+ nullable: Boolean(column.nullable),+ requiresKey:+ column.type === "stringObject" ||+ column.type === "numberObject",+ },+ ];+ }),+ );++ return {+ resource: "observation",+ columns,+ };+ },+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/features/observations/tools/getObservationFilterValues.ts b/web/src/features/mcp/features/observations/tools/getObservationFilterValues.tsnew file mode 100644index 0000000000..2304bf2053--- /dev/null+++ b/web/src/features/mcp/features/observations/tools/getObservationFilterValues.ts@@ -0,0 +1,212 @@+import { SpanKind } from "@opentelemetry/api";+import {+ InvalidRequestError,+ ObservationTypeDomain,+ type timeFilter,+} from "@langfuse/shared";+import { z } from "zod";+import { instrumentAsync } from "@langfuse/shared/src/server";+import { getEventFilterValuePage } from "@/src/features/events/server/eventsService";+import { defineTool } from "../../../core/define-tool";+import {+ ObservationLimitSchema,+ type ObservationMcpFilterColumn,+} from "../schema";++const OBSERVATION_MCP_FILTER_VALUE_COLUMNS = [+ "name",+ "type",+ "environment",+ "version",+ "userId",+ "sessionId",+ "traceName",+ "level",+ "promptName",+ "modelId",+ "providedModelName",+ "tags",+ "hasParentObservation",+] as const satisfies readonly ObservationMcpFilterColumn[];++const FilterValueColumnSchema = z.enum(OBSERVATION_MCP_FILTER_VALUE_COLUMNS);++const GetObservationFilterValuesBaseSchema = z.object({+ column: FilterValueColumnSchema,+ fromStartTime: z.iso.datetime({ offset: true }).optional(),+ toStartTime: z.iso.datetime({ offset: true }).optional(),+ observationType: ObservationTypeDomain.optional(),+ hasParentObservation: z.boolean().optional(),+ limit: ObservationLimitSchema,+ cursor: z.string().optional(),+});++type FilterOption = {+ value: string | boolean;+ count?: number;+};++const buildStartTimeFilter = (params: {+ fromStartTime?: string;+ toStartTime?: string;+}): z.infer<typeof timeFilter>[] => {+ const filters: z.infer<typeof timeFilter>[] = [];++ if (params.fromStartTime) {+ filters.push({+ column: "startTime",+ operator: ">=",+ value: new Date(params.fromStartTime),+ type: "datetime",+ });+ }++ if (params.toStartTime) {+ filters.push({+ column: "startTime",+ operator: "<",+ value: new Date(params.toStartTime),+ type: "datetime",+ });+ }++ return filters;+};++const normalizeFilterOptions = (+ values: unknown[],+ column: z.infer<typeof FilterValueColumnSchema>,+): FilterOption[] => {+ const normalizeValue = (value: unknown): string | boolean | null => {+ if (typeof value === "string") {+ // Special handling for the "hasParentObservation" column to convert "true"/"false" strings to boolean values.+ if (column === "hasParentObservation") {+ if (value === "true") return true;+ if (value === "false") return false;+ }+ return value;+ }++ if (typeof value === "boolean") return value;++ return null;+ };++ return values+ .map((value): FilterOption | null => {+ const normalizedPrimitive = normalizeValue(value);+ if (normalizedPrimitive !== null) return { value: normalizedPrimitive };++ if (typeof value === "object" && value !== null && "value" in value) {+ const normalizedObjectValue = normalizeValue(value.value);+ if (normalizedObjectValue === null) return null;++ return {+ value: normalizedObjectValue,+ count:+ "count" in value && typeof value.count === "number"+ ? value.count+ : undefined,+ };+ }+ return null;+ })+ .filter((value): value is FilterOption => value !== null);+};++// The cursor is just a base64-encoded JSON string containing the offset for pagination.+// Therefore we need to encode and decode it when sending to and receiving from the client.+const decodeObservationFilterValueCursor = (+ cursor: string | undefined,+): number => {+ if (!cursor) return 0;++ try {+ const parsed = JSON.parse(Buffer.from(cursor, "base64").toString("utf-8"));+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ Number.isInteger(parsed.offset) &&+ parsed.offset >= 0+ ) {+ return parsed.offset;+ }+ } catch (_error) {+ // Fall through to the standard public API-style validation error.+ }++ throw new InvalidRequestError("Invalid cursor format");+};++// The cursor is just a base64-encoded JSON string containing the offset for pagination.+// Therefore we need to encode and decode it when sending to and receiving from the client.+const encodeObservationFilterValueCursor = (offset: number): string => {+ return Buffer.from(JSON.stringify({ offset })).toString("base64");+};++export const [+ getObservationFilterValuesTool,+ handleGetObservationFilterValues,+] = defineTool({+ name: "getObservationFilterValues",+ description:+ "List available values for an observation filter field, such as names, types, levels, environments, model names, tags, users, or sessions. Use the returned cursor to page through long value lists.",+ baseSchema: GetObservationFilterValuesBaseSchema,+ inputSchema: GetObservationFilterValuesBaseSchema,+ handler: async (input, context) => {+ return await instrumentAsync(+ { name: "mcp.observations.filterValues", spanKind: SpanKind.INTERNAL },+ async (span) => {+ span.setAttributes({+ "langfuse.project.id": context.projectId,+ "langfuse.org.id": context.orgId,+ "mcp.api_key_id": context.apiKeyId,+ "mcp.filter_column": input.column,+ "mcp.pagination_limit": input.limit,+ });++ const startTimeFilter = buildStartTimeFilter({+ fromStartTime: input.fromStartTime,+ toStartTime: input.toStartTime,+ });++ const offset = decodeObservationFilterValueCursor(input.cursor);++ // The `tags` column is stored in the database as `traceTags`+ const eventsColumn =+ input.column === "tags" ? "traceTags" : input.column;++ const page = await getEventFilterValuePage({+ column: eventsColumn,+ projectId: context.projectId,+ startTimeFilter,+ hasParentObservation: input.hasParentObservation,+ observationType: input.observationType,+ limit: input.limit,+ offset,+ });++ if (!Array.isArray(page.values)) {+ throw new InvalidRequestError(+ `Filter values are not available for column ${input.column}`,+ );+ }++ const normalizedValues = normalizeFilterOptions(+ page.values,+ input.column,+ );++ return {+ column: input.column,+ values: normalizedValues,+ meta:+ page.nextOffset !== undefined+ ? { cursor: encodeObservationFilterValueCursor(page.nextOffset) }+ : {},+ };+ },+ );+ },+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/features/observations/tools/listObservations.ts b/web/src/features/mcp/features/observations/tools/listObservations.tsnew file mode 100644index 0000000000..497c276d55--- /dev/null+++ b/web/src/features/mcp/features/observations/tools/listObservations.ts@@ -0,0 +1,391 @@+import { SpanKind } from "@opentelemetry/api";+import {+ InvalidRequestError,+ OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS,+ booleanFilter,+ eventsTableCols,+ filterOperators,+ numberFilter,+ ObservationLevelDomain,+ ObservationTypeDomain,+ singleFilter,+ stringFilter,+ stringObjectFilter,+ stringOptionsFilter,+ timeFilter,+ type ColumnDefinition,+} from "@langfuse/shared";+import {+ getObservationsV2FromEventsTableForPublicApi,+ instrumentAsync,+} from "@langfuse/shared/src/server";+import { z } from "zod";+import {+ EncodedObservationsCursorV2,+ EncodedObservationsCursorV2String,+ encodeCursor,+} from "@/src/features/public-api/types/observations";+import { defineTool } from "../../../core/define-tool";+import {+ ExpandMetadataKeysSchema,+ getMetadataExpansionForProjection,+ getProjectionFieldGroups,+ getProjectionFields,+ ObservationFieldsSchema,+ ObservationLimitSchema,+ projectObservation,+} from "../schema";++const ObservationCursorSchema =+ EncodedObservationsCursorV2String.optional().describe(+ "Cursor returned by a previous listObservations call",+ );++const EXPENSIVE_OBSERVATION_ACCESS_COLUMNS = new Set([+ "input",+ "output",+ "metadata",+]);++const OBSERVATION_MCP_FILTER_COLUMN_TYPES = new Map(+ eventsTableCols+ .filter((column) =>+ OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS.has(column.id),+ )+ .map((column) => [+ column.id === "traceTags" ? "tags" : column.id,+ column.type,+ ]),+);++const OBSERVATION_MCP_FILTER_COLUMN_DEFINITIONS = eventsTableCols+ .filter((column) =>+ OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS.has(column.id),+ )+ .map((column) => ({+ column: column.id === "traceTags" ? "tags" : column.id,+ type: column.type,+ }));++const OBSERVATION_MCP_FILTER_EXAMPLE = {+ column: "totalCost",+ operator: ">",+ value: 0.0029,+} satisfies Omit<z.infer<typeof numberFilter>, "type">;++const OBSERVATION_MCP_FILTER_EXAMPLE_WITH_TYPE = {+ type: "number",+ ...OBSERVATION_MCP_FILTER_EXAMPLE,+} satisfies z.infer<typeof numberFilter>;++const OBSERVATION_MCP_FILTER_EXAMPLE_JSON = JSON.stringify(+ OBSERVATION_MCP_FILTER_EXAMPLE,+);++const OBSERVATION_MCP_FILTER_EXAMPLE_WITH_TYPE_JSON = JSON.stringify(+ OBSERVATION_MCP_FILTER_EXAMPLE_WITH_TYPE,+);++const OBSERVATION_MCP_FILTER_SCHEMA_BY_TYPE = {+ datetime: (column: string, requireType = false) =>+ timeFilter.omit({ type: true, column: true }).extend({+ type: requireType+ ? z.literal("datetime")+ : z.literal("datetime").optional(),+ column: z.literal(column),+ }),+ string: (column: string, requireType = false) =>+ stringFilter.omit({ type: true, column: true }).extend({+ type: requireType ? z.literal("string") : z.literal("string").optional(),+ column: z.literal(column),+ }),+ stringOptions: (column: string, requireType = false) =>+ stringOptionsFilter.omit({ type: true, column: true }).extend({+ type: requireType+ ? z.literal("stringOptions")+ : z.literal("stringOptions").optional(),+ column: z.literal(column),+ }),+ arrayOptions: (column: string, requireType = false) =>+ z.object({+ operator: z.enum(filterOperators.arrayOptions),+ value: z.array(z.string()),+ type: requireType+ ? z.literal("arrayOptions")+ : z.literal("arrayOptions").optional(),+ column: z.literal(column),+ }),+ number: (column: string, requireType = false) =>+ numberFilter.omit({ type: true, column: true }).extend({+ type: requireType ? z.literal("number") : z.literal("number").optional(),+ column: z.literal(column),+ }),+ stringObject: (column: string, requireType = false) =>+ stringObjectFilter.omit({ type: true, column: true }).extend({+ type: requireType+ ? z.literal("stringObject")+ : z.literal("stringObject").optional(),+ column: z.literal(column),+ }),+ boolean: (column: string, requireType = false) =>+ booleanFilter.omit({ type: true, column: true }).extend({+ type: requireType+ ? z.literal("boolean")+ : z.literal("boolean").optional(),+ column: z.literal(column),+ }),+} satisfies Partial<+ Record<+ ColumnDefinition["type"],+ (column: string, requireType?: boolean) => z.ZodType+ >+>;++type ObservationMcpFilterType =+ keyof typeof OBSERVATION_MCP_FILTER_SCHEMA_BY_TYPE;++const isObservationMcpFilterType = (+ type: string,+): type is ObservationMcpFilterType =>+ type in OBSERVATION_MCP_FILTER_SCHEMA_BY_TYPE;++const OBSERVATION_MCP_FILTER_SCHEMAS =+ OBSERVATION_MCP_FILTER_COLUMN_DEFINITIONS.flatMap(({ column, type }) =>+ isObservationMcpFilterType(type)+ ? [OBSERVATION_MCP_FILTER_SCHEMA_BY_TYPE[type](column)]+ : [],+ );++const OBSERVATION_MCP_EXPLICIT_FILTER_SCHEMAS =+ OBSERVATION_MCP_FILTER_COLUMN_DEFINITIONS.flatMap(({ column, type }) =>+ isObservationMcpFilterType(type)+ ? [OBSERVATION_MCP_FILTER_SCHEMA_BY_TYPE[type](column, true)]+ : [],+ );++const ObservationMcpFilterShapeSchema = z+ .union([+ ...OBSERVATION_MCP_FILTER_SCHEMAS,+ ...OBSERVATION_MCP_EXPLICIT_FILTER_SCHEMAS,+ ] as [+ (typeof OBSERVATION_MCP_FILTER_SCHEMAS)[number],+ (typeof OBSERVATION_MCP_FILTER_SCHEMAS)[number],+ ...(+ | (typeof OBSERVATION_MCP_FILTER_SCHEMAS)[number]+ | (typeof OBSERVATION_MCP_EXPLICIT_FILTER_SCHEMAS)[number]+ )[],+ ])+ .describe(+ `Advanced observation filter object. Example: ${OBSERVATION_MCP_FILTER_EXAMPLE_JSON}. The explicit form ${OBSERVATION_MCP_FILTER_EXAMPLE_WITH_TYPE_JSON} is also accepted.`,+ );++const ObservationMcpFilterSchema = z+ .object({ column: z.string() })+ .loose()+ .superRefine((filter, ctx) => {+ if (!OBSERVATION_MCP_FILTER_COLUMN_TYPES.has(filter.column)) {+ ctx.addIssue({+ code: "custom",+ path: ["column"],+ message: `Invalid observation filter column "${filter.column}". Call getObservationFilterSchema for accepted columns.`,+ });+ }+ })+ .pipe(ObservationMcpFilterShapeSchema)+ .transform((filter) => {+ const type =+ filter.type ?? OBSERVATION_MCP_FILTER_COLUMN_TYPES.get(filter.column);++ return singleFilter.parse(+ filter.column === "tags"+ ? { ...filter, type, column: "traceTags" }+ : { ...filter, type },+ );+ });++const ListObservationsBaseSchema = z.object({+ fields: ObservationFieldsSchema,+ expandMetadataKeys: ExpandMetadataKeysSchema,+ limit: ObservationLimitSchema,+ cursor: ObservationCursorSchema,+ type: ObservationTypeDomain.optional(),+ name: z.string().optional(),+ userId: z.string().optional(),+ level: ObservationLevelDomain.optional(),+ traceId: z.string().optional(),+ version: z.string().optional(),+ parentObservationId: z.string().optional(),+ // TODO: Re-enable string[] once the public observations API correctly+ // applies allow-multiple environment filters instead of dropping arrays.+ // see: https://linear.app/langfuse/issue/LFE-9852/bug-observations-api-accepts-multiple-environment-params-but-ignores+ environment: z+ .string()+ .optional()+ .describe(+ "Environment to filter by. Multiple environments are temporarily unsupported until the public observations API applies allow-multiple environment filters correctly.",+ ),+ fromStartTime: z.iso.datetime({ offset: true }).optional(),+ toStartTime: z.iso.datetime({ offset: true }).optional(),+ filter: z+ .array(ObservationMcpFilterShapeSchema)+ .optional()+ .describe(+ "Advanced filters. Each item must be an object with column, operator, value, and optional type. Type is inferred from getObservationFilterSchema columns when omitted.",+ ),+});++const ListObservationsInputSchema = ListObservationsBaseSchema.extend({+ filter: z+ .array(ObservationMcpFilterSchema)+ .optional()+ .describe(+ "Advanced filters. Each item must be an object with column, operator, value, and optional type. Type is inferred from getObservationFilterSchema columns when omitted.",+ ),+});++type ListObservationsInput = z.infer<typeof ListObservationsInputSchema>;++const hasObservationIdFilter = (filters: ListObservationsInput["filter"]) =>+ filters?.some(+ (filter) =>+ filter.column === "id" &&+ filter.type === "stringOptions" &&+ filter.operator === "any of" &&+ 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 set+const assertAllowedExpensiveObservationAccess = (+ input: ListObservationsInput,+ projectionFields: string[],+) => {+ const expensiveColumns = new Set<string>();++ for (const field of projectionFields) {+ if (EXPENSIVE_OBSERVATION_ACCESS_COLUMNS.has(field)) {+ expensiveColumns.add(field);+ }+ }++ for (const filter of input.filter ?? []) {+ if (EXPENSIVE_OBSERVATION_ACCESS_COLUMNS.has(filter.column)) {+ expensiveColumns.add(filter.column);+ }+ }++ if (expensiveColumns.size === 0) return;++ const hasSelectiveScope =+ Boolean(input.traceId) ||+ hasObservationIdFilter(input.filter) ||+ hasValidStartTimeBound(input);++ if (hasSelectiveScope) return;++ throw new InvalidRequestError(+ `Accessing observation ${Array.from(expensiveColumns)+ .sort()+ .join(+ ", ",+ )} requires traceId, an id filter, or both fromStartTime and toStartTime.`,+ );+};++export const [listObservationsTool, handleListObservations] = defineTool({+ name: "listObservations",+ description: [+ "Find and review observations in the current Langfuse project, such as generations, spans, events, agent steps, and tool calls.",+ "Use filters to narrow results by trace, name, type, level, environment, time range, or advanced filter conditions. Results are paginated with an opaque cursor.",+ "",+ '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.",+ ].join("\n"),+ baseSchema: ListObservationsBaseSchema as z.ZodType<ListObservationsInput>,+ inputSchema: ListObservationsInputSchema,+ handler: async (input, context) => {+ return await instrumentAsync(+ { name: "mcp.observations.list", spanKind: SpanKind.INTERNAL },+ async (span) => {+ const projectionFields = getProjectionFields(input.fields);+ const fieldGroups = getProjectionFieldGroups(projectionFields);+ assertAllowedExpensiveObservationAccess(input, projectionFields);++ span.setAttributes({+ "langfuse.project.id": context.projectId,+ "langfuse.org.id": context.orgId,+ "mcp.api_key_id": context.apiKeyId,+ "mcp.pagination_limit": input.limit,+ "mcp.projection_fields": projectionFields.join(","),+ "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,+ fromStartTime: input.fromStartTime,+ toStartTime: input.toStartTime,+ version: input.version,+ advancedFilters: input.filter,+ cursor: input.cursor+ ? EncodedObservationsCursorV2.parse(input.cursor)+ : undefined,+ fields: fieldGroups,+ expandMetadataKeys: getMetadataExpansionForProjection(+ projectionFields,+ input.expandMetadataKeys,+ ),+ });++ const hasMore = items.length > input.limit;+ const dataToReturn = hasMore ? items.slice(0, input.limit) : items;++ const data = dataToReturn.map((item) =>+ projectObservation(+ {+ ...item,+ parentObservationId:+ item.parentObservationId === ""+ ? null+ : item.parentObservationId,+ },+ projectionFields,+ ),+ );++ const lastItem = dataToReturn[dataToReturn.length - 1];++ return {+ data,+ meta:+ hasMore && lastItem+ ? {+ cursor: encodeCursor({+ lastStartTimeTo: lastItem.startTime,+ lastTraceId: lastItem.traceId ?? "",+ lastId: lastItem.id,+ }),+ }+ : {},+ };+ },+ );+ },+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.tsindex acc4ecb741..dec9f27779 100644--- a/web/src/features/mcp/server/bootstrap.ts+++ b/web/src/features/mcp/server/bootstrap.ts@@ -12,6 +12,7 @@import { toolRegistry } from "./registry";import { promptsFeature } from "../features/prompts";+import { observationsFeature } from "../features/observations";// Import future features as they're added:// import { datasetsFeature } from "../features/datasets";// import { tracesFeature } from "../features/traces";@@ -26,6 +27,7 @@ import { promptsFeature } from "../features/prompts";export function bootstrapMcpFeatures(): void {// Register all feature modulestoolRegistry.register(promptsFeature);+ toolRegistry.register(observationsFeature);// Add future features here:// toolRegistry.register(datasetsFeature);diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.tsindex 9870b95853..8c7dd4ff3b 100644--- a/web/src/features/mcp/server/mcpServer.ts+++ b/web/src/features/mcp/server/mcpServer.ts@@ -78,8 +78,9 @@ export function createMcpServer(context: ServerContext): Server {toolName: name,});- // Look up tool in registry- const registeredTool = toolRegistry.getTool(name);+ // Look up tool in registry and apply feature gates. Direct calls should+ // fail the same way as absent tools when a gated feature is disabled.+ const registeredTool = await toolRegistry.getEnabledTool(name, context);if (!registeredTool) {throw new Error(`Unknown tool: ${name}`);diff --git a/web/src/features/mcp/server/registry.ts b/web/src/features/mcp/server/registry.tsindex 9b9280790c..63ad2f27e9 100644--- a/web/src/features/mcp/server/registry.ts+++ b/web/src/features/mcp/server/registry.ts@@ -142,6 +142,27 @@ class ToolRegistry {return this.tools.get(name);}+ /**+ * Get tool handler by name after applying the owning feature's enablement+ * check. Direct calls must behave the same as discovery for gated features.+ */+ async getEnabledTool(+ name: string,+ context: ServerContext,+ ): Promise<RegisteredTool | undefined> {+ const tool = this.tools.get(name);+ if (!tool) return undefined;++ const feature = this.getFeatureForTool(name);+ if (!feature) return undefined;++ if (feature.isEnabled && !(await feature.isEnabled(context))) {+ return undefined;+ }++ return tool;+ }+/*** Get feature name for a tool (for error messages)*@@ -149,12 +170,17 @@ class ToolRegistry {* @returns Feature name or "unknown"*/private getToolFeature(toolName: string): string {- for (const [featureName, feature] of this.features.entries()) {+ const feature = this.getFeatureForTool(toolName);+ return feature?.name ?? "unknown";+ }++ private getFeatureForTool(toolName: string): McpFeatureModule | undefined {+ for (const feature of this.features.values()) {if (feature.tools.some((t) => t.definition.name === toolName)) {- return featureName;+ return feature;}}- return "unknown";+ return undefined;}/**