Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(mcp): Make metrics available via MCP (#13769)

Ben Bachem33e5cfcebfde
diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.ts
index 564d5d951d..f1f01b1b9f 100644
--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts
@@ -48,6 +48,14 @@ import {
listObservationsTool,
handleListObservations,
} from "@/src/features/mcp/features/observations/tools/listObservations";
+import {
+ getMetricsSchemaTool,
+ handleGetMetricsSchema,
+} from "@/src/features/mcp/features/metrics/tools/getMetricsSchema";
+import {
+ queryMetricsTool,
+ handleQueryMetrics,
+} from "@/src/features/mcp/features/metrics/tools/queryMetrics";
import {
getPromptTool,
handleGetPrompt,
@@ -808,6 +816,226 @@ describe("MCP Read Tools", () => {
});
});
+ maybeEventsTable("queryMetrics tool", () => {
+ const metricsWindow = {
+ fromTimestamp: "2025-12-31T00:00:00.000Z",
+ toTimestamp: "2026-01-02T00:00:00.000Z",
+ };
+
+ const getMetricRows = (result: unknown) => {
+ expect(result).toMatchObject({ data: expect.any(Array) });
+ return Reflect.get(Object(result), "data");
+ };
+
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(queryMetricsTool, { readOnlyHint: true });
+ });
+
+ it("should expose object-shaped metrics query input in the tool schema", () => {
+ const properties = queryMetricsTool.inputSchema.properties;
+
+ expect(properties.view).toBeDefined();
+ expect(properties.dimensions).toBeDefined();
+ expect(properties.metrics).toBeDefined();
+ expect(properties.filters).toBeDefined();
+ expect(properties.timeDimension).toBeDefined();
+ expect(properties.fromTimestamp).toBeDefined();
+ expect(properties.toTimestamp).toBeDefined();
+ expect(properties.orderBy).toBeDefined();
+ expect(properties.config).toBeDefined();
+ });
+
+ it("should query observations metrics for the current project", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const traceId = randomUUID();
+
+ await createEventsCh(
+ Array.from({ length: 3 }, (_, index) =>
+ createObservationEvent({
+ projectId,
+ traceId,
+ name: `mcp-metrics-count-${index}-${nanoid()}`,
+ startTime: new Date(`2026-01-01T00:00:0${index}.000Z`),
+ }),
+ ),
+ );
+
+ const rows = getMetricRows(
+ await handleQueryMetrics(
+ {
+ view: "observations",
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ type: "string",
+ column: "traceId",
+ operator: "=",
+ value: traceId,
+ },
+ ],
+ ...metricsWindow,
+ },
+ context,
+ ),
+ );
+
+ expect(rows).toHaveLength(1);
+ expect(Number(rows[0].count_count)).toBe(3);
+ });
+
+ it("should apply default row_limit of 100 when omitted", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const traceId = randomUUID();
+
+ await createEventsCh(
+ Array.from({ length: 150 }, (_, index) =>
+ createObservationEvent({
+ projectId,
+ traceId,
+ name: `mcp-metrics-default-limit-${index}-${nanoid()}`,
+ startTime: new Date(Date.UTC(2026, 0, 1, 0, 0, 0) + index * 1000),
+ }),
+ ),
+ );
+
+ const rows = getMetricRows(
+ await handleQueryMetrics(
+ {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ type: "string",
+ column: "traceId",
+ operator: "=",
+ value: traceId,
+ },
+ ],
+ ...metricsWindow,
+ },
+ context,
+ ),
+ );
+
+ expect(rows.length).toBeLessThanOrEqual(100);
+ });
+
+ it("should respect explicit row_limit", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const traceId = randomUUID();
+
+ await createEventsCh(
+ Array.from({ length: 20 }, (_, index) =>
+ createObservationEvent({
+ projectId,
+ traceId,
+ name: `mcp-metrics-custom-limit-${index}-${nanoid()}`,
+ startTime: new Date(`2026-01-01T00:00:${index}.000Z`),
+ }),
+ ),
+ );
+
+ const rows = getMetricRows(
+ await handleQueryMetrics(
+ {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ type: "string",
+ column: "traceId",
+ operator: "=",
+ value: traceId,
+ },
+ ],
+ config: { row_limit: 5 },
+ ...metricsWindow,
+ },
+ context,
+ ),
+ );
+
+ expect(rows.length).toBeLessThanOrEqual(5);
+ });
+
+ it("should validate high-cardinality queries before applying default row_limit", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(
+ handleQueryMetrics(
+ {
+ view: "observations",
+ dimensions: [{ field: "traceId" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ orderBy: [{ field: "count_count", direction: "desc" }],
+ ...metricsWindow,
+ },
+ context,
+ ),
+ ).rejects.toThrow(
+ /require both 'config\.row_limit' and 'orderBy' with direction 'desc'/i,
+ );
+ });
+ });
+
+ maybeEventsTable("getMetricsSchema tool", () => {
+ const getMetricsSchemaViews = (result: unknown) => {
+ expect(result).toMatchObject({ views: expect.any(Object) });
+ return Reflect.get(Object(result), "views");
+ };
+
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getMetricsSchemaTool, { readOnlyHint: true });
+ });
+
+ it("should return v2 metrics schema metadata", async () => {
+ const { context } = await createMcpTestSetup();
+
+ const result = await handleGetMetricsSchema({}, context);
+ const views = getMetricsSchemaViews(result);
+
+ expect(result).toMatchObject({
+ supportedViews: [
+ "observations",
+ "scores-numeric",
+ "scores-categorical",
+ ],
+ granularities: expect.arrayContaining(["day"]),
+ config: {
+ row_limit: { min: 1, max: 1000, default: 100 },
+ bins: { min: 1, max: 100 },
+ },
+ views: {
+ observations: {
+ dimensions: {
+ traceId: { highCardinality: true },
+ },
+ measures: {
+ count: {
+ validAggregations: expect.arrayContaining(["count"]),
+ },
+ },
+ },
+ },
+ });
+ expect(Reflect.get(Object(views), "traces")).toBeUndefined();
+ });
+
+ it("should return one requested metrics view", async () => {
+ const { context } = await createMcpTestSetup();
+
+ const result = await handleGetMetricsSchema(
+ { view: "scores-numeric" },
+ context,
+ );
+ const views = getMetricsSchemaViews(result);
+
+ expect(Object.keys(views)).toEqual(["scores-numeric"]);
+ });
+ });
+
maybeEventsTable("getObservation tool", () => {
it("should have readOnlyHint annotation", () => {
verifyToolAnnotations(getObservationTool, { readOnlyHint: true });
diff --git a/web/src/features/mcp/README.md b/web/src/features/mcp/README.md
index 9b989a2fe3..7b4193e081 100644
--- a/web/src/features/mcp/README.md
+++ b/web/src/features/mcp/README.md
@@ -47,7 +47,7 @@ Model Context Protocol (MCP) server for Langfuse, enabling AI assistants to inte
## Available Tools
-The MCP server provides prompt-management tools and read-only observation tools.
+The MCP server provides prompt-management tools, read-only observation tools, and read-only metrics tools.
### Prompt Tools
@@ -72,6 +72,17 @@ Observation tools read from the events table v2 and are project-scoped to the au
**Implementation:** See [`/web/src/features/mcp/features/observations/tools/`](/web/src/features/mcp/features/observations/tools/) for detailed schemas and handlers.
+### Metrics Tools
+
+Metrics tools are project-scoped, read-only, and use the events table v2 backend.
+
+- **`queryMetrics`** - Query `/api/public/v2/metrics` semantics through MCP. The input is the v2 metrics query object directly, not the HTTP API's JSON-string `query` wrapper.
+- **`getMetricsSchema`** - Discover supported v2 metrics views, dimensions, measures, aggregation options, granularities, and config limits.
+
+`queryMetrics` supports the public v2 metrics views `observations`, `scores-numeric`, and `scores-categorical`. The internal `traces` v2 view is not exposed through MCP. Query validation matches the public v2 API, including high-cardinality safeguards and the default `row_limit` of `100`.
+
+**Implementation:** See [`/web/src/features/mcp/features/metrics/tools/`](/web/src/features/mcp/features/metrics/tools/) for 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:
@@ -187,7 +198,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. Observation tools are read-only and do not create audit log entries.
+All write operations (createTextPrompt, createChatPrompt, updatePromptLabels) automatically create audit log entries with before/after snapshots. Observation and metrics tools are read-only and do not create audit log entries.
---
diff --git a/web/src/features/mcp/features/metrics/index.ts b/web/src/features/mcp/features/metrics/index.ts
new file mode 100644
index 0000000000..3f42a0a59d
--- /dev/null
+++ b/web/src/features/mcp/features/metrics/index.ts
@@ -0,0 +1,24 @@
+import { env } from "@/src/env.mjs";
+import type { McpFeatureModule } from "../../server/registry";
+import {
+ getMetricsSchemaTool,
+ handleGetMetricsSchema,
+} from "./tools/getMetricsSchema";
+import { queryMetricsTool, handleQueryMetrics } from "./tools/queryMetrics";
+
+export const metricsFeature: McpFeatureModule = {
+ name: "metrics",
+ description:
+ "Analyze project usage, quality, cost, and performance metrics from Langfuse data",
+ tools: [
+ {
+ definition: queryMetricsTool,
+ handler: handleQueryMetrics,
+ },
+ {
+ definition: getMetricsSchemaTool,
+ handler: handleGetMetricsSchema,
+ },
+ ],
+ isEnabled: async () => env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true",
+};
diff --git a/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts b/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
new file mode 100644
index 0000000000..6e10563094
--- /dev/null
+++ b/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
@@ -0,0 +1,73 @@
+import {
+ getValidAggregationsForMeasureType,
+ granularities,
+ viewsV2,
+ viewDeclarations,
+} from "@langfuse/shared/query";
+import { z } from "zod";
+import { defineTool } from "../../../core/define-tool";
+
+const GetMetricsSchemaInput = z.object({
+ view: viewsV2
+ .optional()
+ .describe("Limit the response to one v2 metrics view"),
+});
+
+export const [getMetricsSchemaTool, handleGetMetricsSchema] = defineTool({
+ name: "getMetricsSchema",
+ description:
+ "Discover which Langfuse metrics can be analyzed and how to group, filter, aggregate, and time-bucket them before calling queryMetrics.",
+ baseSchema: GetMetricsSchemaInput,
+ inputSchema: GetMetricsSchemaInput,
+ handler: async (input) => {
+ const supportedViews = viewsV2.options;
+ const selectedViews = input.view ? [input.view] : supportedViews;
+
+ return {
+ supportedViews,
+ granularities: granularities.options,
+ config: {
+ bins: { min: 1, max: 100 },
+ row_limit: { min: 1, max: 1000, default: 100 },
+ },
+ views: Object.fromEntries(
+ selectedViews.map((viewName) => {
+ const view = viewDeclarations.v2[viewName];
+
+ return [
+ viewName,
+ {
+ description: view.description,
+ timeDimension: view.timeDimension,
+ dimensions: Object.fromEntries(
+ Object.entries(view.dimensions).map(([name, definition]) => [
+ name,
+ {
+ description: definition.description,
+ type: definition.type,
+ unit: definition.unit,
+ highCardinality: Boolean(definition.highCardinality),
+ },
+ ]),
+ ),
+ measures: Object.fromEntries(
+ Object.entries(view.measures).map(([name, definition]) => [
+ name,
+ {
+ description: definition.description,
+ type: definition.type,
+ unit: definition.unit,
+ validAggregations: getValidAggregationsForMeasureType(
+ definition.type,
+ ),
+ },
+ ]),
+ ),
+ },
+ ];
+ }),
+ ),
+ };
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
new file mode 100644
index 0000000000..f2305ce507
--- /dev/null
+++ b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
@@ -0,0 +1,42 @@
+import { InvalidRequestError } from "@langfuse/shared";
+import { executeQuery } from "@langfuse/shared/query/server";
+import { validateQuery } from "@langfuse/shared/query";
+import { MetricsQueryObjectV2 } from "@/src/features/public-api/types/metrics";
+import { defineTool } from "../../../core/define-tool";
+
+const DEFAULT_ROW_LIMIT = 100;
+
+export const [queryMetricsTool, handleQueryMetrics] = defineTool({
+ name: "queryMetrics",
+ description:
+ "Answer analytics questions about the current Langfuse project, such as usage over time, model costs, latency, errors, scores, or grouped breakdowns by environment, trace, observation, model, user, session, tag, or score name.",
+ baseSchema: MetricsQueryObjectV2,
+ inputSchema: MetricsQueryObjectV2,
+ handler: async (input, context) => {
+ const validation = validateQuery(input, "v2");
+
+ if (!validation.valid) {
+ throw new InvalidRequestError(validation.reason);
+ }
+
+ const { config, ...query } = input;
+ const queryParams = {
+ ...query,
+ chartConfig: {
+ type: "TABLE",
+ ...config,
+ row_limit: config?.row_limit ?? DEFAULT_ROW_LIMIT,
+ },
+ };
+
+ const result = await executeQuery(
+ context.projectId,
+ queryParams,
+ "v2",
+ true,
+ );
+
+ return { data: result };
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
index dec9f27779..1a8b95b0cf 100644
--- a/web/src/features/mcp/server/bootstrap.ts
+++ b/web/src/features/mcp/server/bootstrap.ts
@@ -13,6 +13,7 @@
import { toolRegistry } from "./registry";
import { promptsFeature } from "../features/prompts";
import { observationsFeature } from "../features/observations";
+import { metricsFeature } from "../features/metrics";
// Import future features as they're added:
// import { datasetsFeature } from "../features/datasets";
// import { tracesFeature } from "../features/traces";
@@ -28,6 +29,7 @@ export function bootstrapMcpFeatures(): void {
// Register all feature modules
toolRegistry.register(promptsFeature);
toolRegistry.register(observationsFeature);
+ toolRegistry.register(metricsFeature);
// Add future features here:
// toolRegistry.register(datasetsFeature);