Skip to content

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

feat(mcp,monitors): Add listMonitors and getMonitor tools (#15065)

Ben Bachem331ecdc4f873
diff --git a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
index 7fbf317e82..db593437fc 100644
--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
@@ -1,3 +1,7 @@
+vi.hoisted(() => {
+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";
+});
+
process.env.LANGFUSE_DATASET_SERVICE_READ_FROM_VERSIONED_IMPLEMENTATION =
"true";
process.env.LANGFUSE_DATASET_SERVICE_WRITE_TO_VERSIONED_IMPLEMENTATION = "true";
@@ -159,6 +163,8 @@ describe("MCP public API tools", () => {
"getHealth",
"listScores",
"getScore",
+ "listMonitors",
+ "getMonitor",
"createModel",
"createScoreConfig",
]),
diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.ts
index 1ca115934b..86ff22f228 100644
--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts
@@ -1,3 +1,7 @@
+vi.hoisted(() => {
+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";
+});
+
// Mock queue operations to avoid Redis dependency in tests
vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual("@langfuse/shared/src/server");
@@ -40,6 +44,7 @@ import {
createTraceScore,
} from "@langfuse/shared/src/server";
import { ScoreConfigDataType } from "@langfuse/shared";
+import { MonitorService } from "@langfuse/shared/monitors/server";
import {
createMcpTestSetup,
createPromptInDb,
@@ -53,6 +58,7 @@ import "@/src/features/mcp/server/bootstrap";
import { toolRegistry } from "@/src/features/mcp/server/registry";
import {
buildEvaluatorUrl,
+ buildMonitorUrl,
buildObservationUrl,
buildPromptUrl,
buildTraceUrl,
@@ -153,6 +159,14 @@ import {
} from "@/src/features/mcp/features/evals/tools/listEvaluationRules";
import { handleUpsertEvaluator } from "@/src/features/mcp/features/evals/tools/upsertEvaluator";
import { handleCreateEvaluationRule } from "@/src/features/mcp/features/evals/tools/createEvaluationRule";
+import {
+ getMonitorTool,
+ handleGetMonitor,
+} from "@/src/features/mcp/features/monitors/tools/getMonitor";
+import {
+ listMonitorsTool,
+ handleListMonitors,
+} from "@/src/features/mcp/features/monitors/tools/listMonitors";
import {
GetDatasetItemsMcpInput,
GetDatasetMcpInput,
@@ -184,6 +198,39 @@ const createLlmEvaluatorForMcpReadTest = async (
)) as { id: string; name: string };
};
+const createMonitorForMcpReadTest = async (
+ setup: Awaited<ReturnType<typeof createMcpTestSetup>>,
+ params: { name: string; tags?: string[] },
+) => {
+ const user = await prisma.user.create({
+ data: {
+ id: randomUUID(),
+ email: `mcp-monitor-${nanoid()}@example.com`,
+ name: "MCP Monitor Test User",
+ },
+ });
+
+ return MonitorService.create(
+ { userId: user.id },
+ {
+ projectId: setup.projectId,
+ view: "observations",
+ filters: [],
+ metric: { measure: "count", aggregation: "count" },
+ window: "5m",
+ thresholdOperator: "GT",
+ alertThreshold: 100,
+ warningThreshold: null,
+ noData: { mode: "SHOW_NO_DATA" },
+ renotify: { mode: "OFF" },
+ status: "ACTIVE",
+ name: params.name,
+ tags: params.tags ?? [],
+ triggerIds: ["mcp-test-trigger"],
+ },
+ );
+};
+
const createEvaluationRuleForMcpReadTest = async (
setup: Awaited<ReturnType<typeof createMcpTestSetup>>,
) => {
@@ -302,6 +349,131 @@ const containsPropertyName = (value: unknown, expected: string): boolean => {
};
describe("MCP Read Tools", () => {
+ describe("listMonitors tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(listMonitorsTool, { readOnlyHint: true });
+ });
+
+ it("should be available to in-app agent keys", async () => {
+ const context = mockServerContext({
+ inAppAgent: { permissions: "read" },
+ });
+
+ await expect(
+ toolRegistry.getEnabledTool(listMonitorsTool.name, context),
+ ).resolves.toBeDefined();
+ });
+
+ it("should not expose projectId in its input schema", () => {
+ const properties = listMonitorsTool.inputSchema.properties as Record<
+ string,
+ unknown
+ >;
+
+ expect(properties.projectId).toBeUndefined();
+ });
+
+ it("should list, filter, order, and paginate monitors in the current project", async () => {
+ const setup = await createMcpTestSetup();
+ const otherSetup = await createMcpTestSetup();
+ const tag = `mcp-monitor-${nanoid()}`;
+ const first = await createMonitorForMcpReadTest(setup, {
+ name: `A monitor ${nanoid()}`,
+ tags: [tag],
+ });
+ await createMonitorForMcpReadTest(setup, {
+ name: `B monitor ${nanoid()}`,
+ tags: [tag],
+ });
+ await createMonitorForMcpReadTest(otherSetup, {
+ name: `Other project monitor ${nanoid()}`,
+ tags: [tag],
+ });
+
+ const result = (await handleListMonitors(
+ {
+ orderBy: { column: "name", order: "ASC" },
+ filter: [
+ {
+ type: "arrayOptions",
+ column: "tags",
+ operator: "any of",
+ value: [tag],
+ },
+ ],
+ page: 1,
+ limit: 1,
+ },
+ setup.context,
+ )) as {
+ data: Array<{ id: string; url: string }>;
+ meta: { totalItems: number; totalPages: number };
+ };
+
+ expect(result).toEqual({
+ data: [
+ expect.objectContaining({
+ id: first.id,
+ url: buildMonitorUrl({
+ projectId: setup.projectId,
+ monitorId: first.id,
+ }),
+ }),
+ ],
+ meta: expect.objectContaining({ totalItems: 2, totalPages: 2 }),
+ });
+ });
+ });
+
+ describe("getMonitor tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getMonitorTool, { readOnlyHint: true });
+ });
+
+ it("should be available to in-app agent keys", async () => {
+ const context = mockServerContext({
+ inAppAgent: { permissions: "read" },
+ });
+
+ await expect(
+ toolRegistry.getEnabledTool(getMonitorTool.name, context),
+ ).resolves.toBeDefined();
+ });
+
+ it("should fetch a monitor by id", async () => {
+ const setup = await createMcpTestSetup();
+ const monitor = await createMonitorForMcpReadTest(setup, {
+ name: `Get monitor ${nanoid()}`,
+ });
+
+ await expect(
+ handleGetMonitor({ monitorId: monitor.id }, setup.context),
+ ).resolves.toMatchObject({
+ id: monitor.id,
+ name: monitor.name,
+ url: buildMonitorUrl({
+ projectId: setup.projectId,
+ monitorId: monitor.id,
+ }),
+ });
+ });
+
+ it("should reject missing and cross-project monitors", async () => {
+ const setup = await createMcpTestSetup();
+ const otherSetup = await createMcpTestSetup();
+ const monitor = await createMonitorForMcpReadTest(setup, {
+ name: `Isolated monitor ${nanoid()}`,
+ });
+
+ await expect(
+ handleGetMonitor({ monitorId: randomUUID() }, setup.context),
+ ).rejects.toThrow(/not found/i);
+ await expect(
+ handleGetMonitor({ monitorId: monitor.id }, otherSetup.context),
+ ).rejects.toThrow(/not found/i);
+ });
+ });
+
describe("dataset tool schemas", () => {
it("uses dataset IDs for existing dataset read addressing", () => {
for (const schema of [
diff --git a/web/src/ee/features/in-app-agent/server/tools.ts b/web/src/ee/features/in-app-agent/server/tools.ts
index 1e056d0924..6085c9afe9 100644
--- a/web/src/ee/features/in-app-agent/server/tools.ts
+++ b/web/src/ee/features/in-app-agent/server/tools.ts
@@ -253,6 +253,14 @@ export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES: Record<
approval: "auto",
availability: { scope: "prompts:read" },
},
+ listMonitors: {
+ approval: "auto",
+ availability: { scope: "monitors:read" },
+ },
+ getMonitor: {
+ approval: "auto",
+ availability: { scope: "monitors:read" },
+ },
listPrompts: {
approval: "auto",
availability: { scope: "prompts:read" },
diff --git a/web/src/features/mcp/features/monitors/index.ts b/web/src/features/mcp/features/monitors/index.ts
new file mode 100644
index 0000000000..501e1cef11
--- /dev/null
+++ b/web/src/features/mcp/features/monitors/index.ts
@@ -0,0 +1,15 @@
+import { env } from "@/src/env.mjs";
+
+import type { McpFeatureModule } from "../../server/registry";
+import { getMonitorTool, handleGetMonitor } from "./tools/getMonitor";
+import { listMonitorsTool, handleListMonitors } from "./tools/listMonitors";
+
+export const monitorsFeature = {
+ name: "monitors",
+ description: "Inspect monitors in the current Langfuse project",
+ tools: [
+ { definition: listMonitorsTool, handler: handleListMonitors },
+ { definition: getMonitorTool, handler: handleGetMonitor },
+ ],
+ isEnabled: async () => env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy",
+} as const satisfies McpFeatureModule;
diff --git a/web/src/features/mcp/features/monitors/tools/getMonitor.ts b/web/src/features/mcp/features/monitors/tools/getMonitor.ts
new file mode 100644
index 0000000000..03c2ea6c75
--- /dev/null
+++ b/web/src/features/mcp/features/monitors/tools/getMonitor.ts
@@ -0,0 +1,42 @@
+import { MonitorService } from "@langfuse/shared/monitors/server";
+import { z } from "zod";
+
+import { buildMonitorUrl } from "@/src/utils/product-url";
+
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+const GetMonitorInputSchema = z.object({
+ monitorId: z.string().describe("ID of the monitor to retrieve."),
+});
+
+export const [getMonitorTool, handleGetMonitor] = defineTool({
+ name: "getMonitor",
+ description: "Get a monitor by ID.",
+ baseSchema: GetMonitorInputSchema,
+ inputSchema: GetMonitorInputSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.monitors.get",
+ context,
+ attributes: { "mcp.monitor_id": input.monitorId },
+ fn: async () => {
+ const monitor = await MonitorService.getById(
+ { userId: context.userId ?? context.apiKeyId },
+ {
+ projectId: context.projectId,
+ id: input.monitorId,
+ },
+ );
+
+ return {
+ ...monitor,
+ url: buildMonitorUrl({
+ projectId: context.projectId,
+ monitorId: monitor.id,
+ }),
+ };
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/monitors/tools/listMonitors.ts b/web/src/features/mcp/features/monitors/tools/listMonitors.ts
new file mode 100644
index 0000000000..53b233bb01
--- /dev/null
+++ b/web/src/features/mcp/features/monitors/tools/listMonitors.ts
@@ -0,0 +1,76 @@
+import {
+ ListMonitorsSchema,
+ MonitorService,
+} from "@langfuse/shared/monitors/server";
+import { z } from "zod";
+
+import { buildMonitorUrl } from "@/src/utils/product-url";
+
+import { defineTool } from "../../../core/define-tool";
+import { McpAdvancedFilterBaseSchema } from "../../../core/filter-schema";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+
+const ListMonitorsSharedSchemaFields = {
+ page: ListMonitorsSchema.shape.page,
+ limit: ListMonitorsSchema.shape.limit,
+};
+
+const ListMonitorsBaseSchema = z.object({
+ ...ListMonitorsSharedSchemaFields,
+ orderBy: ListMonitorsSchema.shape.orderBy.unwrap().optional(),
+ filter: z
+ .array(McpAdvancedFilterBaseSchema)
+ .optional()
+ .describe("Filter monitors by severity or tags."),
+});
+
+const ListMonitorsInputSchema = ListMonitorsSchema.omit({
+ projectId: true,
+}).extend({
+ orderBy: ListMonitorsSchema.shape.orderBy.default(null),
+});
+
+export const [listMonitorsTool, handleListMonitors] = defineTool({
+ name: "listMonitors",
+ description:
+ "List monitors, optionally filtered by severity or tags and ordered by monitor properties.",
+ baseSchema: ListMonitorsBaseSchema,
+ inputSchema: ListMonitorsInputSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.monitors.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async (span) => {
+ const result = await MonitorService.list(
+ { userId: context.userId ?? context.apiKeyId },
+ {
+ ...input,
+ projectId: context.projectId,
+ },
+ );
+
+ span.setAttribute("mcp.result_count", result.monitors.length);
+
+ return {
+ data: result.monitors.map((monitor) => ({
+ ...monitor,
+ url: buildMonitorUrl({
+ projectId: context.projectId,
+ monitorId: monitor.id,
+ }),
+ })),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems: result.totalCount,
+ }),
+ };
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
index 09135f1c95..724b40954e 100644
--- a/web/src/features/mcp/server/bootstrap.ts
+++ b/web/src/features/mcp/server/bootstrap.ts
@@ -25,6 +25,7 @@ import { mediaFeature } from "../features/media";
import { evalsFeature } from "../features/evals";
import { dashboardWidgetsFeature } from "../features/dashboardWidgets";
import { experimentsFeature } from "../features/experiments";
+import { monitorsFeature } from "../features/monitors";
const MCP_FEATURES = [
promptsFeature,
@@ -40,6 +41,7 @@ const MCP_FEATURES = [
evalsFeature,
dashboardWidgetsFeature,
experimentsFeature,
+ monitorsFeature,
] as const satisfies readonly McpFeatureModule[];
export type McpFeature = (typeof MCP_FEATURES)[number];
diff --git a/web/src/utils/product-url.ts b/web/src/utils/product-url.ts
index 7ee9289c4f..f9ea717d53 100644
--- a/web/src/utils/product-url.ts
+++ b/web/src/utils/product-url.ts
@@ -475,6 +475,14 @@ export const buildModelUrl = (params: { projectId: string; modelId: string }) =>
`/project/${encodeURIComponent(params.projectId)}/settings/models/${encodeURIComponent(params.modelId)}`,
);
+export const buildMonitorUrl = (params: {
+ projectId: string;
+ monitorId: string;
+}) =>
+ buildProductUrl(
+ `${buildMonitorsPath(params)}/${encodeURIComponent(params.monitorId)}`,
+ );
+
export const buildDashboardWidgetUrl = (params: {
projectId: string;
widgetId: string;