Skip to content

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

feat(mcp): expose unstable evaluator and evaluation-rule tools (#14113)

Tobias Wochinger6c5f0aa81d64
diff --git a/web/src/__tests__/server/mcp-helpers.ts b/web/src/__tests__/server/mcp-helpers.ts
index bca98a5dcd..d6780a564c 100644
--- a/web/src/__tests__/server/mcp-helpers.ts
+++ b/web/src/__tests__/server/mcp-helpers.ts
@@ -70,6 +70,12 @@ export function mockServerContext(
};
}
+export const mcpEvalOutputDefinition = {
+ dataType: "NUMERIC" as const,
+ reasoning: { description: "Why the score was assigned" },
+ score: { description: "A score between 0 and 1" },
+};
+
/**
* Verifies that a response follows the MCP content block format.
* MCP tools return { content: [{ type: "text", text: "..." }] }
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 9d7ca1b4b1..838cd39fdd 100644
--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
@@ -148,6 +148,12 @@ describe("MCP public API tools", () => {
"listAnnotationQueues",
"createAnnotationQueue",
"createComment",
+ "listEvaluators",
+ "getEvaluator",
+ "upsertEvaluator",
+ "listEvaluationRules",
+ "getEvaluationRule",
+ "createEvaluationRule",
"listDatasets",
"getHealth",
"listScores",
@@ -171,6 +177,10 @@ describe("MCP public API tools", () => {
"listScores",
"getScore",
"listScoreConfigs",
+ "listEvaluators",
+ "getEvaluator",
+ "listEvaluationRules",
+ "getEvaluationRule",
"listPrompts",
"getPrompt",
"getPromptUnresolved",
@@ -215,6 +225,8 @@ describe("MCP public API tools", () => {
expect(destructiveToolNames).toEqual(
[
"createChatPrompt",
+ "createEvaluationRule",
+ "upsertEvaluator",
"createScore",
"createScoreConfig",
"createTextPrompt",
@@ -222,9 +234,11 @@ describe("MCP public API tools", () => {
"deleteAnnotationQueueItem",
"deleteDatasetItem",
"deleteDatasetRun",
+ "deleteEvaluationRule",
"deleteModel",
"deleteScoreConfig",
"updateAnnotationQueueItem",
+ "updateEvaluationRule",
"updatePromptLabels",
"updateScoreConfig",
"upsertDataset",
diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.ts
index 89c8bdd072..9a4f01748d 100644
--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts
@@ -19,6 +19,16 @@ vi.mock("@/src/features/media/server/getMediaStorageClient", () => ({
}),
}));
+// Skip the LLM model preflight so llm_as_judge evaluators don't require a
+// provisioned default eval model.
+vi.mock(
+ "@/src/features/evals/server/evaluator-preflight",
+ async (importActual) => ({
+ ...(await importActual<object>()),
+ getEvaluatorDefinitionPreflightError: vi.fn(async () => null),
+ }),
+);
+
import { nanoid } from "nanoid";
import { createHash, randomUUID } from "crypto";
import { z } from "zod";
@@ -33,6 +43,7 @@ import { ScoreConfigDataType } from "@langfuse/shared";
import {
createMcpTestSetup,
createPromptInDb,
+ mcpEvalOutputDefinition,
mockServerContext,
verifyAuditLog,
verifyToolAnnotations,
@@ -118,6 +129,24 @@ import {
getMediaTool,
handleGetMedia,
} from "@/src/features/mcp/features/media/tools/getMedia";
+import {
+ getEvaluatorTool,
+ handleGetEvaluator,
+} from "@/src/features/mcp/features/evals/tools/getEvaluator";
+import {
+ listEvaluatorsTool,
+ handleListEvaluators,
+} from "@/src/features/mcp/features/evals/tools/listEvaluators";
+import {
+ getEvaluationRuleTool,
+ handleGetEvaluationRule,
+} from "@/src/features/mcp/features/evals/tools/getEvaluationRule";
+import {
+ listEvaluationRulesTool,
+ handleListEvaluationRules,
+} 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 {
GetDatasetItemsMcpInput,
GetDatasetMcpInput,
@@ -133,6 +162,56 @@ const maybeEventsTable =
const maybeEventsTableIt =
env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true" ? it : it.skip;
+const createLlmEvaluatorForMcpReadTest = async (
+ setup: Awaited<ReturnType<typeof createMcpTestSetup>>,
+ name = `mcp-eval-${nanoid()}`,
+) => {
+ return (await handleUpsertEvaluator(
+ {
+ name,
+ type: "llm_as_judge",
+ prompt: "Judge {{input}} against {{output}}",
+ outputDefinition: mcpEvalOutputDefinition,
+ modelConfig: null,
+ },
+ setup.context,
+ )) as { id: string; name: string };
+};
+
+const createEvaluationRuleForMcpReadTest = async (
+ setup: Awaited<ReturnType<typeof createMcpTestSetup>>,
+) => {
+ const evaluatorName = `mcp-eval-${nanoid()}`;
+ const evaluator = await createLlmEvaluatorForMcpReadTest(
+ setup,
+ evaluatorName,
+ );
+ const ruleName = `mcp-rule-${nanoid()}`;
+ const rule = (await handleCreateEvaluationRule(
+ {
+ name: ruleName,
+ evaluator: {
+ name: evaluatorName,
+ scope: "project",
+ type: "llm_as_judge",
+ },
+ enabled: false,
+ sampling: 1,
+ target: "observation",
+ filter: [
+ { column: "version", operator: "=", value: "1.0.0", type: "string" },
+ ],
+ mapping: [
+ { variable: "input", source: "input" },
+ { variable: "output", source: "output" },
+ ],
+ },
+ setup.context,
+ )) as { id: string; name: string };
+
+ return { evaluator, rule };
+};
+
const createObservationEvent = (params: {
projectId: string;
traceId?: string;
@@ -245,6 +324,117 @@ describe("MCP Read Tools", () => {
});
});
+ describe("listEvaluators tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(listEvaluatorsTool, { readOnlyHint: true });
+ });
+
+ it("should be available to in-app agent keys", async () => {
+ const context = mockServerContext({ isInAppAgentKey: true });
+
+ await expect(
+ toolRegistry.getEnabledTool(listEvaluatorsTool.name, context),
+ ).resolves.toMatchObject({
+ definition: expect.objectContaining({ name: listEvaluatorsTool.name }),
+ });
+ });
+
+ it("should list evaluators for the current project", async () => {
+ const setup = await createMcpTestSetup();
+ const { context } = setup;
+ const evaluator = await createLlmEvaluatorForMcpReadTest(setup);
+
+ const result = (await handleListEvaluators(
+ { page: 1, limit: 50 },
+ context,
+ )) as { data: Array<{ id: string }> };
+
+ expect(result.data.map((item) => item.id)).toContain(evaluator.id);
+ });
+ });
+
+ describe("getEvaluator tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getEvaluatorTool, { readOnlyHint: true });
+ });
+
+ it("should be available to in-app agent keys", async () => {
+ const context = mockServerContext({ isInAppAgentKey: true });
+
+ await expect(
+ toolRegistry.getEnabledTool(getEvaluatorTool.name, context),
+ ).resolves.toMatchObject({
+ definition: expect.objectContaining({ name: getEvaluatorTool.name }),
+ });
+ });
+
+ it("should fetch an evaluator by id", async () => {
+ const setup = await createMcpTestSetup();
+ const evaluator = await createLlmEvaluatorForMcpReadTest(setup);
+
+ await expect(
+ handleGetEvaluator({ evaluatorId: evaluator.id }, setup.context),
+ ).resolves.toMatchObject({ id: evaluator.id, name: evaluator.name });
+ });
+ });
+
+ describe("listEvaluationRules tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(listEvaluationRulesTool, { readOnlyHint: true });
+ });
+
+ it("should be available to in-app agent keys", async () => {
+ const context = mockServerContext({ isInAppAgentKey: true });
+
+ await expect(
+ toolRegistry.getEnabledTool(listEvaluationRulesTool.name, context),
+ ).resolves.toMatchObject({
+ definition: expect.objectContaining({
+ name: listEvaluationRulesTool.name,
+ }),
+ });
+ });
+
+ it("should list evaluation rules for the current project", async () => {
+ const setup = await createMcpTestSetup();
+ const { rule } = await createEvaluationRuleForMcpReadTest(setup);
+
+ const result = (await handleListEvaluationRules(
+ { page: 1, limit: 50 },
+ setup.context,
+ )) as { data: Array<{ id: string }> };
+
+ expect(result.data.map((item) => item.id)).toContain(rule.id);
+ });
+ });
+
+ describe("getEvaluationRule tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getEvaluationRuleTool, { readOnlyHint: true });
+ });
+
+ it("should be available to in-app agent keys", async () => {
+ const context = mockServerContext({ isInAppAgentKey: true });
+
+ await expect(
+ toolRegistry.getEnabledTool(getEvaluationRuleTool.name, context),
+ ).resolves.toMatchObject({
+ definition: expect.objectContaining({
+ name: getEvaluationRuleTool.name,
+ }),
+ });
+ });
+
+ it("should fetch an evaluation rule by id", async () => {
+ const setup = await createMcpTestSetup();
+ const { rule } = await createEvaluationRuleForMcpReadTest(setup);
+
+ await expect(
+ handleGetEvaluationRule({ evaluationRuleId: rule.id }, setup.context),
+ ).resolves.toMatchObject({ id: rule.id, name: rule.name });
+ });
+ });
+
describe("getMedia tool", () => {
it("should have readOnlyHint annotation", () => {
verifyToolAnnotations(getMediaTool, { readOnlyHint: true });
diff --git a/web/src/__tests__/server/mcp-tools-write.servertest.ts b/web/src/__tests__/server/mcp-tools-write.servertest.ts
index d1f1e195c0..40ceb001a7 100644
--- a/web/src/__tests__/server/mcp-tools-write.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-write.servertest.ts
@@ -19,13 +19,36 @@ vi.mock("@langfuse/shared/src/server", async () => {
};
});
+// Code evaluators are gated behind deployment config; enable them for the
+// code-path coverage below without depending on a real dispatcher.
+vi.mock(
+ "@/src/features/evals/server/isCodeEvalEnabled",
+ async (importActual) => ({
+ ...(await importActual<object>()),
+ isCodeEvalEnabled: vi.fn(() => true),
+ isCodeEvalSourceCodeLanguageSupported: vi.fn(() => true),
+ }),
+);
+
+// Skip the LLM model preflight so llm_as_judge evaluators don't require a
+// provisioned default eval model.
+vi.mock(
+ "@/src/features/evals/server/evaluator-preflight",
+ async (importActual) => ({
+ ...(await importActual<object>()),
+ getEvaluatorDefinitionPreflightError: vi.fn(async () => null),
+ }),
+);
+
import { prisma } from "@langfuse/shared/src/db";
import { nanoid } from "nanoid";
import { z } from "zod";
import {
createMcpTestSetup,
createPromptInDb,
+ mcpEvalOutputDefinition,
verifyAuditLog,
+ verifyToolAnnotations,
} from "./mcp-helpers";
import {
DeleteDatasetRunMcpInput,
@@ -37,6 +60,23 @@ import { handleCreateTextPrompt } from "@/src/features/mcp/features/prompts/tool
import { handleCreateChatPrompt } from "@/src/features/mcp/features/prompts/tools/createChatPrompt";
import { handleUpdatePromptLabels } from "@/src/features/mcp/features/prompts/tools/updatePromptLabels";
import { handleCreateAnnotationQueue } from "@/src/features/mcp/features/annotationQueues/tools";
+import {
+ upsertEvaluatorTool,
+ handleUpsertEvaluator,
+} from "@/src/features/mcp/features/evals/tools/upsertEvaluator";
+import {
+ createEvaluationRuleTool,
+ handleCreateEvaluationRule,
+} from "@/src/features/mcp/features/evals/tools/createEvaluationRule";
+import {
+ updateEvaluationRuleTool,
+ handleUpdateEvaluationRule,
+} from "@/src/features/mcp/features/evals/tools/updateEvaluationRule";
+import {
+ deleteEvaluationRuleTool,
+ handleDeleteEvaluationRule,
+} from "@/src/features/mcp/features/evals/tools/deleteEvaluationRule";
+import { handleGetEvaluationRule } from "@/src/features/mcp/features/evals/tools/getEvaluationRule";
const createScoreConfig = async (projectId: string) =>
prisma.scoreConfig.create({
@@ -48,6 +88,56 @@ const createScoreConfig = async (projectId: string) =>
},
});
+const createLlmEvaluatorForMcpWriteTest = async (
+ setup: Awaited<ReturnType<typeof createMcpTestSetup>>,
+ name = `mcp-eval-${nanoid()}`,
+) => {
+ return (await handleUpsertEvaluator(
+ {
+ name,
+ type: "llm_as_judge",
+ prompt: "Judge {{input}} against {{output}}",
+ outputDefinition: mcpEvalOutputDefinition,
+ modelConfig: null,
+ },
+ setup.context,
+ )) as { id: string; name: string; type: string; variables: string[] };
+};
+
+const createLlmEvaluationRuleForMcpWriteTest = async (
+ setup: Awaited<ReturnType<typeof createMcpTestSetup>>,
+) => {
+ const evaluatorName = `mcp-eval-${nanoid()}`;
+ const evaluator = await createLlmEvaluatorForMcpWriteTest(
+ setup,
+ evaluatorName,
+ );
+ const ruleName = `mcp-rule-${nanoid()}`;
+ const rule = (await handleCreateEvaluationRule(
+ {
+ name: ruleName,
+ evaluator: {
+ name: evaluatorName,
+ scope: "project",
+ type: "llm_as_judge",
+ },
+ enabled: false,
+ sampling: 1,
+ target: "observation",
+ filter: [
+ { column: "version", operator: "=", value: "1.0.0", type: "string" },
+ ],
+ mapping: [
+ { variable: "input", source: "input" },
+ { variable: "output", source: "output" },
+ ],
+ },
+ setup.context,
+ )) as { id: string; name: string; target: string; sampling: number };
+
+ return { evaluator, rule };
+};
+
describe("MCP Write Tools", () => {
describe("dataset tool schemas", () => {
it("uses dataset IDs for existing dataset write addressing", () => {
@@ -65,6 +155,183 @@ describe("MCP Write Tools", () => {
});
});
+ describe("upsertEvaluator tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(upsertEvaluatorTool, { destructiveHint: true });
+ });
+
+ it("should create an llm-as-judge evaluator and audit the write", async () => {
+ const setup = await createMcpTestSetup();
+ const { projectId, apiKeyId } = setup;
+ const evaluatorName = `mcp-eval-${nanoid()}`;
+
+ const evaluator = await createLlmEvaluatorForMcpWriteTest(
+ setup,
+ evaluatorName,
+ );
+
+ expect(evaluator).toMatchObject({
+ name: evaluatorName,
+ type: "llm_as_judge",
+ });
+ expect(evaluator.variables.sort()).toEqual(["input", "output"]);
+ await expect(
+ verifyAuditLog({
+ projectId,
+ apiKeyId,
+ resourceType: "evalTemplate",
+ resourceId: evaluator.id,
+ action: "create",
+ }),
+ ).resolves.toMatchObject({ resourceId: evaluator.id, action: "create" });
+ });
+
+ it("should create code evaluators", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+
+ const evaluator = (await handleUpsertEvaluator(
+ {
+ name: `mcp-code-eval-${nanoid()}`,
+ type: "code",
+ sourceCode: "export function evaluate() { return { score: 1 }; }",
+ sourceCodeLanguage: "TYPESCRIPT",
+ },
+ context,
+ )) as { id: string; type: string; sourceCodeLanguage: string };
+
+ expect(evaluator).toMatchObject({
+ type: "code",
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+ await expect(
+ verifyAuditLog({
+ projectId,
+ apiKeyId,
+ resourceType: "evalTemplate",
+ resourceId: evaluator.id,
+ action: "create",
+ }),
+ ).resolves.toMatchObject({ resourceId: evaluator.id, action: "create" });
+ });
+ });
+
+ describe("createEvaluationRule tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(createEvaluationRuleTool, {
+ destructiveHint: true,
+ });
+ });
+
+ it("should create an evaluation rule and audit the write", async () => {
+ const setup = await createMcpTestSetup();
+ const { projectId, apiKeyId } = setup;
+
+ const { rule } = await createLlmEvaluationRuleForMcpWriteTest(setup);
+
+ expect(rule).toMatchObject({ target: "observation", sampling: 1 });
+ await expect(
+ verifyAuditLog({
+ projectId,
+ apiKeyId,
+ resourceType: "job",
+ resourceId: rule.id,
+ action: "create",
+ }),
+ ).resolves.toMatchObject({ resourceId: rule.id, action: "create" });
+ });
+
+ it("should create a code evaluation rule without mapping", async () => {
+ const { context } = await createMcpTestSetup();
+ const evaluatorName = `mcp-code-eval-${nanoid()}`;
+
+ await handleUpsertEvaluator(
+ {
+ name: evaluatorName,
+ type: "code",
+ sourceCode: "export function evaluate() { return { score: 1 }; }",
+ sourceCodeLanguage: "TYPESCRIPT",
+ },
+ context,
+ );
+
+ const rule = (await handleCreateEvaluationRule(
+ {
+ name: `mcp-code-rule-${nanoid()}`,
+ evaluator: { name: evaluatorName, scope: "project", type: "code" },
+ enabled: false,
+ target: "observation",
+ filter: [],
+ },
+ context,
+ )) as { id: string };
+ expect(rule.id).toBeDefined();
+ });
+ });
+
+ describe("updateEvaluationRule tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(updateEvaluationRuleTool, {
+ destructiveHint: true,
+ });
+ });
+
+ it("should update an evaluation rule and audit the write", async () => {
+ const setup = await createMcpTestSetup();
+ const { projectId, apiKeyId } = setup;
+ const { rule } = await createLlmEvaluationRuleForMcpWriteTest(setup);
+
+ await expect(
+ handleUpdateEvaluationRule(
+ { evaluationRuleId: rule.id, sampling: 0.5 },
+ setup.context,
+ ),
+ ).resolves.toMatchObject({ id: rule.id, sampling: 0.5 });
+ await expect(
+ verifyAuditLog({
+ projectId,
+ apiKeyId,
+ resourceType: "job",
+ resourceId: rule.id,
+ action: "update",
+ }),
+ ).resolves.toMatchObject({ resourceId: rule.id, action: "update" });
+ });
+ });
+
+ describe("deleteEvaluationRule tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(deleteEvaluationRuleTool, {
+ destructiveHint: true,
+ });
+ });
+
+ it("should delete an evaluation rule and audit the write", async () => {
+ const setup = await createMcpTestSetup();
+ const { projectId, apiKeyId } = setup;
+ const { rule } = await createLlmEvaluationRuleForMcpWriteTest(setup);
+
+ await expect(
+ handleDeleteEvaluationRule(
+ { evaluationRuleId: rule.id },
+ setup.context,
+ ),
+ ).resolves.toEqual({ message: "Evaluation rule successfully deleted" });
+ await expect(
+ verifyAuditLog({
+ projectId,
+ apiKeyId,
+ resourceType: "job",
+ resourceId: rule.id,
+ action: "delete",
+ }),
+ ).resolves.toMatchObject({ resourceId: rule.id, action: "delete" });
+
+ await expect(
+ handleGetEvaluationRule({ evaluationRuleId: rule.id }, setup.context),
+ ).rejects.toThrow();
+ });
+ });
+
describe("createAnnotationQueue tool", () => {
it("should create a basic annotation queue", async () => {
const { context, projectId } = await createMcpTestSetup();
diff --git a/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts
index ade63d813e..7b0d644368 100644
--- a/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts
+++ b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts
@@ -1,4 +1,7 @@
-import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";
+import {
+ invalidateProjectEvalConfigCaches,
+ type ApiAccessScope,
+} from "@langfuse/shared/src/server";
import { EvalTemplateType, prisma } from "@langfuse/shared/src/db";
import {
EvalTargetObject,
@@ -9,6 +12,8 @@ import {
assertCodeEvalJobConfigCanRun,
CodeEvalJobConfigError,
} from "@/src/features/evals/server/codeEvalJobConfigValidation";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import {
isCodeEvalEnabled,
isCodeEvalSourceCodeLanguageSupported,
@@ -183,6 +188,7 @@ export async function createPublicEvaluationRule(params: {
orgId: string;
projectId: string;
input: PostUnstableEvaluationRuleBodyType;
+ auditScope?: Pick<ApiAccessScope, "orgId" | "apiKeyId">;
}) {
const existing = await prisma.jobConfiguration.findFirst({
where: {
@@ -284,7 +290,21 @@ export async function createPublicEvaluationRule(params: {
await invalidateProjectEvalConfigCaches(params.projectId);
}
- return toApiEvaluationRule(created);
+ const evaluationRule = toApiEvaluationRule(created);
+
+ if (params.auditScope) {
+ await auditLog({
+ action: "create",
+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,
+ resourceId: evaluationRule.id,
+ projectId: params.projectId,
+ orgId: params.auditScope.orgId,
+ apiKeyId: params.auditScope.apiKeyId,
+ after: evaluationRule,
+ });
+ }
+
+ return evaluationRule;
}
export async function updatePublicEvaluationRule(params: {
@@ -292,6 +312,7 @@ export async function updatePublicEvaluationRule(params: {
projectId: string;
evaluationRuleId: string;
input: PatchUnstableEvaluationRuleBodyType;
+ auditScope?: Pick<ApiAccessScope, "orgId" | "apiKeyId">;
}) {
const existing = await findPublicEvaluationRuleOrThrow({
projectId: params.projectId,
@@ -424,14 +445,31 @@ export async function updatePublicEvaluationRule(params: {
await invalidateProjectEvalConfigCaches(params.projectId);
- return toApiEvaluationRule(updated);
+ const evaluationRule = toApiEvaluationRule(updated);
+
+ if (params.auditScope) {
+ await auditLog({
+ action: "update",
+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,
+ resourceId: evaluationRule.id,
+ projectId: params.projectId,
+ orgId: params.auditScope.orgId,
+ apiKeyId: params.auditScope.apiKeyId,
+ before: existingPublic,
+ after: evaluationRule,
+ });
+ }
+
+ return evaluationRule;
}
export async function deletePublicEvaluationRule(params: {
projectId: string;
evaluationRuleId: string;
+ auditScope?: Pick<ApiAccessScope, "orgId" | "apiKeyId">;
}) {
const existing = await findPublicEvaluationRuleOrThrow(params);
+ const existingPublic = toApiEvaluationRule(existing);
await prisma.jobConfiguration.delete({
where: {
@@ -442,5 +480,17 @@ export async function deletePublicEvaluationRule(params: {
await invalidateProjectEvalConfigCaches(params.projectId);
+ if (params.auditScope) {
+ await auditLog({
+ action: "delete",
+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,
+ resourceId: params.evaluationRuleId,
+ projectId: params.projectId,
+ orgId: params.auditScope.orgId,
+ apiKeyId: params.auditScope.apiKeyId,
+ before: existingPublic,
+ });
+ }
+
return existing;
}
diff --git a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
index 4c6242e6b3..8e1ae4aa74 100644
--- a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
+++ b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
@@ -5,7 +5,10 @@ import {
observationVariableMappingList,
variableMappingList,
} from "@langfuse/shared";
-import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";
+import {
+ invalidateProjectEvalConfigCaches,
+ type ApiAccessScope,
+} from "@langfuse/shared/src/server";
import { Prisma, prisma } from "@langfuse/shared/src/db";
import { type PostUnstableEvaluatorBodyParsedType } from "@/src/features/public-api/types/unstable-evaluators";
import {
@@ -17,6 +20,8 @@ import {
isCodeEvalSourceCodeLanguageSupported,
} from "@/src/features/evals/server/isCodeEvalEnabled";
import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import {
toApiEvaluator,
toStoredEvaluatorType,
@@ -145,6 +150,7 @@ export async function getPublicEvaluator(params: {
export async function createPublicEvaluator(params: {
projectId: string;
input: PostUnstableEvaluatorBodyParsedType;
+ auditScope?: Pick<ApiAccessScope, "orgId" | "apiKeyId">;
}) {
const { input } = params;
const storedEvalTemplateType = toStoredEvaluatorType(input.type);
@@ -305,10 +311,24 @@ export async function createPublicEvaluator(params: {
evaluatorId: template.id,
});
- return toApiEvaluator({
+ const evaluator = toApiEvaluator({
template: template as StoredPublicEvaluatorTemplate,
evaluationRuleCount,
});
+
+ if (params.auditScope) {
+ await auditLog({
+ action: "create",
+ resourceType: EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,
+ resourceId: evaluator.id,
+ projectId: params.projectId,
+ orgId: params.auditScope.orgId,
+ apiKeyId: params.auditScope.apiKeyId,
+ after: evaluator,
+ });
+ }
+
+ return evaluator;
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
diff --git a/web/src/features/mcp/core/filter-schema.ts b/web/src/features/mcp/core/filter-schema.ts
new file mode 100644
index 0000000000..6c8c0a9714
--- /dev/null
+++ b/web/src/features/mcp/core/filter-schema.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+
+/**
+ * Loose advanced-filter object shared by MCP tools that accept
+ * (column, operator, value) filters (scores, metrics, evaluation rules).
+ *
+ * Kept union-free so it survives MCP JSON-schema discovery (see
+ * `define-tool.ts`); each tool validates the precise per-column shape in its
+ * own `inputSchema`. `type` is the filter-kind discriminator and `key` targets
+ * object columns such as `metadata`.
+ *
+ * Note: `listObservations` intentionally uses a narrower variant (`type`
+ * optional, no `key`) because it infers the type from the column.
+ */
+export const McpAdvancedFilterBaseSchema = z.object({
+ column: z.string(),
+ operator: z.string(),
+ value: z.any(),
+ type: z.string(),
+ key: z.string().optional(),
+});
diff --git a/web/src/features/mcp/features/evals/index.ts b/web/src/features/mcp/features/evals/index.ts
new file mode 100644
index 0000000000..20da4a70b3
--- /dev/null
+++ b/web/src/features/mcp/features/evals/index.ts
@@ -0,0 +1,71 @@
+import type { McpFeatureModule } from "../../server/registry";
+import {
+ listEvaluatorsTool,
+ handleListEvaluators,
+} from "./tools/listEvaluators";
+import { getEvaluatorTool, handleGetEvaluator } from "./tools/getEvaluator";
+import {
+ upsertEvaluatorTool,
+ handleUpsertEvaluator,
+} from "./tools/upsertEvaluator";
+import {
+ listEvaluationRulesTool,
+ handleListEvaluationRules,
+} from "./tools/listEvaluationRules";
+import {
+ getEvaluationRuleTool,
+ handleGetEvaluationRule,
+} from "./tools/getEvaluationRule";
+import {
+ createEvaluationRuleTool,
+ handleCreateEvaluationRule,
+} from "./tools/createEvaluationRule";
+import {
+ updateEvaluationRuleTool,
+ handleUpdateEvaluationRule,
+} from "./tools/updateEvaluationRule";
+import {
+ deleteEvaluationRuleTool,
+ handleDeleteEvaluationRule,
+} from "./tools/deleteEvaluationRule";
+
+export const evalsFeature: McpFeatureModule = {
+ name: "evals",
+ description:
+ "Manage evaluators and evaluation rules in the current Langfuse project (unstable API)",
+ tools: [
+ {
+ definition: listEvaluatorsTool,
+ handler: handleListEvaluators,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getEvaluatorTool,
+ handler: handleGetEvaluator,
+ allowInAppAgentKey: true,
+ },
+ { definition: upsertEvaluatorTool, handler: handleUpsertEvaluator },
+ {
+ definition: listEvaluationRulesTool,
+ handler: handleListEvaluationRules,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getEvaluationRuleTool,
+ handler: handleGetEvaluationRule,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: createEvaluationRuleTool,
+ handler: handleCreateEvaluationRule,
+ },
+ {
+ definition: updateEvaluationRuleTool,
+ handler: handleUpdateEvaluationRule,
+ },
+ {
+ definition: deleteEvaluationRuleTool,
+ handler: handleDeleteEvaluationRule,
+ },
+ ],
+};
diff --git a/web/src/features/mcp/features/evals/schema.ts b/web/src/features/mcp/features/evals/schema.ts
new file mode 100644
index 0000000000..578882b97e
--- /dev/null
+++ b/web/src/features/mcp/features/evals/schema.ts
@@ -0,0 +1,55 @@
+import { z } from "zod";
+import {
+ ExperimentEvaluationRuleMapping,
+ PublicCategoricalEvaluatorOutputScoreDefinition,
+ PublicEvaluatorModelConfig,
+ PublicEvaluatorOutputDefinition,
+ PublicEvaluatorOutputFieldDefinition,
+} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import { McpAdvancedFilterBaseSchema } from "../../core/filter-schema";
+
+/**
+ * Discovery-facing base schemas for the eval tools. The MCP layer rejects union
+ * JSON schemas, so the contract's union schemas (`outputDefinition`, rule
+ * `filter`) are flattened here; everything else reuses the contract directly.
+ * Precise unions are enforced by each tool's `inputSchema`.
+ */
+
+// Derived from the contract union so a new variant can't silently drift out.
+const evaluatorOutputDataTypes = PublicEvaluatorOutputDefinition.options.map(
+ (option) => option.shape.dataType.value,
+) as [string, ...string[]];
+
+// Flattened from the contract's `dataType` union: the categorical score is the
+// widest variant, with its categorical-only fields made optional.
+export const EvaluatorOutputDefinitionBaseSchema = z
+ .object({
+ dataType: z.enum(evaluatorOutputDataTypes),
+ reasoning: PublicEvaluatorOutputFieldDefinition,
+ score: PublicCategoricalEvaluatorOutputScoreDefinition.partial({
+ categories: true,
+ shouldAllowMultipleMatches: true,
+ }),
+ })
+ .describe(
+ "Score output definition. Required when type is `llm_as_judge`; omit for `code` evaluators.",
+ );
+
+// Reused as-is; callers apply `.optional()` (never `.nullable()`, which is `anyOf`).
+export const EvaluatorModelConfigBaseSchema =
+ PublicEvaluatorModelConfig.describe(
+ "Model used for `llm_as_judge` evaluation. Optional; falls back to the project default eval model.",
+ );
+
+// Experiment mapping has the widest `source` enum, so it covers both targets.
+export const RuleMappingBaseSchema = ExperimentEvaluationRuleMapping.describe(
+ "Maps an evaluator variable to a data source. `observation` rules use `input`, `output`, `metadata`; `experiment` rules also allow `expected_output` and `experiment_item_metadata`. Required for `llm_as_judge` evaluators; omit for `code` evaluators (Langfuse manages their mapping).",
+);
+
+// Shared loose filter shape (the contract's per-column filter is a union the
+// JSON-schema guard rejects). Precise validation happens in each tool's
+// `inputSchema` against the per-target contract union.
+export const RuleFilterBaseSchema = McpAdvancedFilterBaseSchema.describe(
+ 'Filter condition, e.g. {"column":"version","operator":"=","value":"1.0.0","type":"string"}. ' +
+ "Use `key` for object columns such as `metadata`. `observation` rules filter on trace/observation columns; `experiment` rules filter on `datasetId`.",
+);
diff --git a/web/src/features/mcp/features/evals/tools/createEvaluationRule.ts b/web/src/features/mcp/features/evals/tools/createEvaluationRule.ts
new file mode 100644
index 0000000000..b08eb74e1a
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/createEvaluationRule.ts
@@ -0,0 +1,65 @@
+import { z } from "zod";
+import {
+ EvaluationRuleCreateBase,
+ PostUnstableEvaluationRuleBody,
+ PostUnstableEvaluationRuleResponse,
+} from "@/src/features/public-api/types/unstable-evaluation-rules";
+import { PublicEvaluationRuleTarget } from "@/src/features/public-api/types/unstable-public-evals-contract";
+import { createPublicEvaluationRule } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { RuleFilterBaseSchema, RuleMappingBaseSchema } from "../schema";
+
+// Superset (flattened) schema for client discovery. name/evaluator/enabled/
+// sampling are reused from the contract's EvaluationRuleCreateBase; only the
+// target-discriminated fields are flattened here (target widened to the enum,
+// filter/mapping made union-free and target-agnostic). The real per-target
+// discriminated union and code-vs-llm mapping rules are enforced at runtime by
+// `inputSchema` (PostUnstableEvaluationRuleBody).
+const CreateEvaluationRuleBaseSchema = z.object({
+ ...EvaluationRuleCreateBase,
+ target: PublicEvaluationRuleTarget,
+ filter: z
+ .array(RuleFilterBaseSchema)
+ .optional()
+ .describe("Conditions selecting which items the rule runs on."),
+ mapping: z
+ .array(RuleMappingBaseSchema)
+ .optional()
+ .describe(
+ "Variable mapping. Required for `llm_as_judge` evaluators; omit for `code` evaluators.",
+ ),
+});
+
+export const [createEvaluationRuleTool, handleCreateEvaluationRule] =
+ defineTool({
+ name: "createEvaluationRule",
+ description: [
+ "Create an evaluation rule that runs an evaluator on new observations or experiment items.",
+ "Set target to `observation` or `experiment`. For `llm_as_judge` evaluators provide a variable mapping; for `code` evaluators omit mapping (Langfuse manages it).",
+ ].join(" "),
+ baseSchema: CreateEvaluationRuleBaseSchema,
+ inputSchema: PostUnstableEvaluationRuleBody,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluation_rules.create",
+ context,
+ attributes: {
+ "mcp.evaluation_rule_name": input.name,
+ "mcp.evaluation_rule_target": input.target,
+ },
+ fn: async (span) => {
+ const evaluationRule = await createPublicEvaluationRule({
+ orgId: context.orgId,
+ projectId: context.projectId,
+ input,
+ auditScope: context,
+ });
+
+ span.setAttribute("mcp.evaluation_rule_id", evaluationRule.id);
+
+ return PostUnstableEvaluationRuleResponse.parse(evaluationRule);
+ },
+ }),
+ destructiveHint: true,
+ });
diff --git a/web/src/features/mcp/features/evals/tools/deleteEvaluationRule.ts b/web/src/features/mcp/features/evals/tools/deleteEvaluationRule.ts
new file mode 100644
index 0000000000..fe6c17b236
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/deleteEvaluationRule.ts
@@ -0,0 +1,34 @@
+import {
+ DeleteUnstableEvaluationRuleQuery,
+ DeleteUnstableEvaluationRuleResponse,
+} from "@/src/features/public-api/types/unstable-evaluation-rules";
+import { deletePublicEvaluationRule } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [deleteEvaluationRuleTool, handleDeleteEvaluationRule] =
+ defineTool({
+ name: "deleteEvaluationRule",
+ description:
+ "Delete an evaluation rule by id. This stops the rule from evaluating new items and cannot be undone.",
+ baseSchema: DeleteUnstableEvaluationRuleQuery,
+ inputSchema: DeleteUnstableEvaluationRuleQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluation_rules.delete",
+ context,
+ attributes: { "mcp.evaluation_rule_id": input.evaluationRuleId },
+ fn: async () => {
+ await deletePublicEvaluationRule({
+ projectId: context.projectId,
+ evaluationRuleId: input.evaluationRuleId,
+ auditScope: context,
+ });
+
+ return DeleteUnstableEvaluationRuleResponse.parse({
+ message: "Evaluation rule successfully deleted",
+ });
+ },
+ }),
+ destructiveHint: true,
+ });
diff --git a/web/src/features/mcp/features/evals/tools/getEvaluationRule.ts b/web/src/features/mcp/features/evals/tools/getEvaluationRule.ts
new file mode 100644
index 0000000000..e966a8d7fd
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/getEvaluationRule.ts
@@ -0,0 +1,30 @@
+import {
+ GetUnstableEvaluationRuleQuery,
+ GetUnstableEvaluationRuleResponse,
+} from "@/src/features/public-api/types/unstable-evaluation-rules";
+import { getPublicEvaluationRule } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [getEvaluationRuleTool, handleGetEvaluationRule] = defineTool({
+ name: "getEvaluationRule",
+ description:
+ "Fetch a single evaluation rule by id, including its evaluator reference, target, filter, variable mapping, sampling, and status.",
+ baseSchema: GetUnstableEvaluationRuleQuery,
+ inputSchema: GetUnstableEvaluationRuleQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluation_rules.get",
+ context,
+ attributes: { "mcp.evaluation_rule_id": input.evaluationRuleId },
+ fn: async () => {
+ const result = await getPublicEvaluationRule({
+ projectId: context.projectId,
+ evaluationRuleId: input.evaluationRuleId,
+ });
+
+ return GetUnstableEvaluationRuleResponse.parse(result);
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/evals/tools/getEvaluator.ts b/web/src/features/mcp/features/evals/tools/getEvaluator.ts
new file mode 100644
index 0000000000..3f53af6ba0
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/getEvaluator.ts
@@ -0,0 +1,30 @@
+import {
+ GetUnstableEvaluatorQuery,
+ GetUnstableEvaluatorResponse,
+} from "@/src/features/public-api/types/unstable-evaluators";
+import { getPublicEvaluator } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [getEvaluatorTool, handleGetEvaluator] = defineTool({
+ name: "getEvaluator",
+ description:
+ "Fetch a single evaluator by id, including its prompt or source code, output definition, and how many evaluation rules reference it.",
+ baseSchema: GetUnstableEvaluatorQuery,
+ inputSchema: GetUnstableEvaluatorQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluators.get",
+ context,
+ attributes: { "mcp.evaluator_id": input.evaluatorId },
+ fn: async () => {
+ const result = await getPublicEvaluator({
+ projectId: context.projectId,
+ evaluatorId: input.evaluatorId,
+ });
+
+ return GetUnstableEvaluatorResponse.parse(result);
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/evals/tools/listEvaluationRules.ts b/web/src/features/mcp/features/evals/tools/listEvaluationRules.ts
new file mode 100644
index 0000000000..8747c6501f
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/listEvaluationRules.ts
@@ -0,0 +1,34 @@
+import {
+ GetUnstableEvaluationRulesQuery,
+ GetUnstableEvaluationRulesResponse,
+} from "@/src/features/public-api/types/unstable-evaluation-rules";
+import { listPublicEvaluationRules } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [listEvaluationRulesTool, handleListEvaluationRules] = defineTool({
+ name: "listEvaluationRules",
+ description:
+ "List evaluation rules in the current Langfuse project. Each rule attaches an evaluator to incoming observations or experiment items. Results are paginated.",
+ baseSchema: GetUnstableEvaluationRulesQuery,
+ inputSchema: GetUnstableEvaluationRulesQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluation_rules.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ const result = await listPublicEvaluationRules({
+ projectId: context.projectId,
+ page: input.page,
+ limit: input.limit,
+ });
+
+ return GetUnstableEvaluationRulesResponse.parse(result);
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/evals/tools/listEvaluators.ts b/web/src/features/mcp/features/evals/tools/listEvaluators.ts
new file mode 100644
index 0000000000..36a3fe7fbe
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/listEvaluators.ts
@@ -0,0 +1,34 @@
+import {
+ GetUnstableEvaluatorsQuery,
+ GetUnstableEvaluatorsResponse,
+} from "@/src/features/public-api/types/unstable-evaluators";
+import { listPublicEvaluators } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [listEvaluatorsTool, handleListEvaluators] = defineTool({
+ name: "listEvaluators",
+ description:
+ "List evaluators (llm_as_judge and code) defined in the current Langfuse project. Results are paginated.",
+ baseSchema: GetUnstableEvaluatorsQuery,
+ inputSchema: GetUnstableEvaluatorsQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluators.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ const result = await listPublicEvaluators({
+ projectId: context.projectId,
+ page: input.page,
+ limit: input.limit,
+ });
+
+ return GetUnstableEvaluatorsResponse.parse(result);
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/evals/tools/updateEvaluationRule.ts b/web/src/features/mcp/features/evals/tools/updateEvaluationRule.ts
new file mode 100644
index 0000000000..33c97c20fe
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/updateEvaluationRule.ts
@@ -0,0 +1,63 @@
+import { z } from "zod";
+import {
+ EvaluationRulePatchBase,
+ PatchUnstableEvaluationRuleBody,
+ PatchUnstableEvaluationRuleResponse,
+} from "@/src/features/public-api/types/unstable-evaluation-rules";
+import { PublicEvaluationRuleTarget } from "@/src/features/public-api/types/unstable-public-evals-contract";
+import { updatePublicEvaluationRule } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { RuleFilterBaseSchema, RuleMappingBaseSchema } from "../schema";
+
+// Superset (flattened) schema for client discovery. name/evaluator/enabled/
+// sampling are reused from the contract's EvaluationRulePatchBase (the create
+// fields, all optional); only evaluationRuleId and the target-discriminated
+// fields are added here. Provide at least one field beyond evaluationRuleId.
+// The per-target discriminated union is enforced at runtime via `inputSchema`.
+const UpdateEvaluationRuleBaseSchema = z.object({
+ evaluationRuleId: z.string(),
+ ...EvaluationRulePatchBase,
+ target: PublicEvaluationRuleTarget.optional().describe(
+ "Provide together with filter/mapping when changing them; must match the rule's target.",
+ ),
+ filter: z.array(RuleFilterBaseSchema).optional(),
+ mapping: z.array(RuleMappingBaseSchema).optional(),
+});
+
+// evaluationRuleId addresses the rule; the rest is validated as a PATCH body.
+const UpdateEvaluationRuleInputSchema = z.intersection(
+ z.object({ evaluationRuleId: z.string() }),
+ PatchUnstableEvaluationRuleBody,
+);
+
+export const [updateEvaluationRuleTool, handleUpdateEvaluationRule] =
+ defineTool({
+ name: "updateEvaluationRule",
+ description: [
+ "Update an existing evaluation rule. Provide evaluationRuleId plus at least one field to change.",
+ "When updating filter or mapping, also pass the matching target. The evaluator type cannot be changed.",
+ ].join(" "),
+ baseSchema: UpdateEvaluationRuleBaseSchema,
+ inputSchema: UpdateEvaluationRuleInputSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluation_rules.update",
+ context,
+ attributes: { "mcp.evaluation_rule_id": input.evaluationRuleId },
+ fn: async () => {
+ const { evaluationRuleId, ...patch } = input;
+
+ const evaluationRule = await updatePublicEvaluationRule({
+ orgId: context.orgId,
+ projectId: context.projectId,
+ evaluationRuleId,
+ input: patch,
+ auditScope: context,
+ });
+
+ return PatchUnstableEvaluationRuleResponse.parse(evaluationRule);
+ },
+ }),
+ destructiveHint: true,
+ });
diff --git a/web/src/features/mcp/features/evals/tools/upsertEvaluator.ts b/web/src/features/mcp/features/evals/tools/upsertEvaluator.ts
new file mode 100644
index 0000000000..f6f11c5695
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/upsertEvaluator.ts
@@ -0,0 +1,71 @@
+import { z } from "zod";
+import {
+ EvaluatorCreateBase,
+ PostUnstableEvaluatorBody,
+ PostUnstableEvaluatorResponse,
+} from "@/src/features/public-api/types/unstable-evaluators";
+import {
+ PublicCodeEvaluatorDefinitionInput,
+ PublicEvaluatorType,
+ PublicLlmAsJudgeEvaluatorDefinitionInput,
+} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import { createPublicEvaluator } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import {
+ EvaluatorModelConfigBaseSchema,
+ EvaluatorOutputDefinitionBaseSchema,
+} from "../schema";
+
+// Superset (flattened) schema for client discovery. Both evaluator definition
+// field sets are spread from the contract (via partial(), since each set is
+// optional in the superset) so new contract fields are picked up automatically
+// — drift surfaces as a guard/type failure rather than a silent omission. Only
+// the union/nullable fields the MCP JSON-schema guard rejects are overridden;
+// per-type "required" guidance lives in the tool description. The real per-type
+// discriminated union is enforced at runtime by `inputSchema`
+// (PostUnstableEvaluatorBody).
+const UpsertEvaluatorBaseSchema = z.object({
+ ...EvaluatorCreateBase,
+ type: PublicEvaluatorType.optional().describe(
+ "Evaluator type. Defaults to `llm_as_judge` when omitted.",
+ ),
+ ...PublicLlmAsJudgeEvaluatorDefinitionInput.partial().shape,
+ ...PublicCodeEvaluatorDefinitionInput.partial().shape,
+ // outputDefinition is a discriminated union and modelConfig is nullable; both
+ // become `anyOf` in JSON Schema, so replace them with union-free equivalents.
+ outputDefinition: EvaluatorOutputDefinitionBaseSchema.optional(),
+ modelConfig: EvaluatorModelConfigBaseSchema.optional(),
+});
+
+export const [upsertEvaluatorTool, handleUpsertEvaluator] = defineTool({
+ name: "upsertEvaluator",
+ description: [
+ "Create an evaluator, or add a new version to an existing one in the current project.",
+ "Set type to `llm_as_judge` (default) and provide prompt + outputDefinition (modelConfig optional), or set type to `code` and provide sourceCode + sourceCodeLanguage.",
+ "Reusing an existing evaluator name adds a new version and migrates evaluation rules that reference it.",
+ ].join(" "),
+ baseSchema: UpsertEvaluatorBaseSchema,
+ inputSchema: PostUnstableEvaluatorBody,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluators.upsert",
+ context,
+ attributes: {
+ "mcp.evaluator_name": input.name,
+ "mcp.evaluator_type": input.type,
+ },
+ fn: async (span) => {
+ const evaluator = await createPublicEvaluator({
+ projectId: context.projectId,
+ input,
+ auditScope: context,
+ });
+
+ span.setAttribute("mcp.evaluator_id", evaluator.id);
+
+ return PostUnstableEvaluatorResponse.parse(evaluator);
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
index 1a491b0538..4ca13ce850 100644
--- a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
+++ b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
@@ -9,6 +9,7 @@ import {
} from "@langfuse/shared/query";
import { MetricsQueryObjectV2 } from "@/src/features/public-api/types/metrics";
import { defineTool } from "../../../core/define-tool";
+import { McpAdvancedFilterBaseSchema } from "../../../core/filter-schema";
import { runMcpTool } from "../../../core/run-mcp-tool";
import { z } from "zod";
@@ -57,19 +58,11 @@ const normalizeMetricOrderByFields = (
};
};
-const MetricsFilterBaseSchema = z.object({
- column: z.string(),
- operator: z.string(),
- value: z.any(),
- type: z.string(),
- key: z.string().optional(),
-});
-
const MetricsQueryObjectV2BaseSchema = z.object({
view: viewsV2,
dimensions: z.array(dimension).optional().default([]),
metrics: z.array(metric),
- filters: z.array(MetricsFilterBaseSchema).optional().default([]),
+ filters: z.array(McpAdvancedFilterBaseSchema).optional().default([]),
timeDimension: z
.object({
granularity: granularities,
diff --git a/web/src/features/mcp/features/scores/tools/listScores.ts b/web/src/features/mcp/features/scores/tools/listScores.ts
index 17999a3678..e0ef4b4b1c 100644
--- a/web/src/features/mcp/features/scores/tools/listScores.ts
+++ b/web/src/features/mcp/features/scores/tools/listScores.ts
@@ -8,6 +8,7 @@ import {
} from "@langfuse/shared";
import { z } from "zod";
import { defineTool } from "../../../core/define-tool";
+import { McpAdvancedFilterBaseSchema } from "../../../core/filter-schema";
import { runMcpTool } from "../../../core/run-mcp-tool";
import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
import { paginationMeta } from "../../publicApi";
@@ -19,14 +20,6 @@ const ScoreFieldsSchema = z
"Response field groups to include. 'score' is always required. Include 'trace' when filtering by userId or traceTags.",
);
-const ScoreFilterBaseSchema = z.object({
- column: z.string(),
- operator: z.string(),
- value: z.any(),
- type: z.string(),
- key: z.string().optional(),
-});
-
const ListScoresSharedSchemaFields = {
...publicApiPaginationZod,
fields: ScoreFieldsSchema,
@@ -52,7 +45,7 @@ const ListScoresSharedSchemaFields = {
const ListScoresBaseSchema = z.object({
...ListScoresSharedSchemaFields,
filter: z
- .array(ScoreFilterBaseSchema)
+ .array(McpAdvancedFilterBaseSchema)
.optional()
.describe(
"Advanced score filters as JSON objects with column, operator, value, and type.",
diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
index eafebba3f2..f0b179c05a 100644
--- a/web/src/features/mcp/server/bootstrap.ts
+++ b/web/src/features/mcp/server/bootstrap.ts
@@ -21,9 +21,9 @@ import { scoresFeature } from "../features/scores";
import { metricsFeature } from "../features/metrics";
import { modelsFeature } from "../features/models";
import { mediaFeature } from "../features/media";
+import { evalsFeature } from "../features/evals";
// Import future features as they're added:
// import { tracesFeature } from "../features/traces";
-// import { evalsFeature } from "../features/evals";
/**
* Bootstrap all MCP features
@@ -43,10 +43,10 @@ export function bootstrapMcpFeatures(): void {
toolRegistry.register(metricsFeature);
toolRegistry.register(modelsFeature);
toolRegistry.register(mediaFeature);
+ toolRegistry.register(evalsFeature);
// Add future features here:
// toolRegistry.register(tracesFeature);
- // toolRegistry.register(evalsFeature);
}
/**
diff --git a/web/src/features/public-api/types/unstable-evaluation-rules.ts b/web/src/features/public-api/types/unstable-evaluation-rules.ts
index dd3169e638..57d7de3d49 100644
--- a/web/src/features/public-api/types/unstable-evaluation-rules.ts
+++ b/web/src/features/public-api/types/unstable-evaluation-rules.ts
@@ -49,7 +49,7 @@ export const GetUnstableEvaluationRuleQuery = z.object({
export const GetUnstableEvaluationRuleResponse = APIEvaluationRule;
-const EvaluationRuleCreateBase = {
+export const EvaluationRuleCreateBase = {
name: z.string().min(1),
evaluator: PublicEvaluationRuleEvaluatorReference,
enabled: z.boolean(),
@@ -104,7 +104,9 @@ export const PostUnstableEvaluationRuleResponse = APIEvaluationRule;
export const PatchUnstableEvaluationRuleQuery = GetUnstableEvaluationRuleQuery;
-const EvaluationRulePatchBase = {
+// Exported for reuse (see EvaluationRuleCreateBase) — the create fields, all
+// made optional for PATCH.
+export const EvaluationRulePatchBase = {
name: z.string().min(1).optional(),
evaluator: PublicEvaluationRuleEvaluatorReferencePatch.optional(),
enabled: z.boolean().optional(),
diff --git a/web/src/features/public-api/types/unstable-evaluators.ts b/web/src/features/public-api/types/unstable-evaluators.ts
index d087dc23f2..ec7dba7796 100644
--- a/web/src/features/public-api/types/unstable-evaluators.ts
+++ b/web/src/features/public-api/types/unstable-evaluators.ts
@@ -58,8 +58,14 @@ export const GetUnstableEvaluatorQuery = z.object({
export const GetUnstableEvaluatorResponse = APIEvaluator;
-const PostUnstableLlmAsJudgeEvaluatorBody = z.object({
+// Fields shared by every create body, regardless of evaluator type. Exported so
+// non-route consumers (e.g. the MCP tool layer) reuse the same definition.
+export const EvaluatorCreateBase = {
name: z.string().min(1),
+};
+
+const PostUnstableLlmAsJudgeEvaluatorBody = z.object({
+ ...EvaluatorCreateBase,
type: z.literal(PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE),
...PublicLlmAsJudgeEvaluatorDefinitionInput.shape,
sourceCode: z.never().optional(),
@@ -67,7 +73,7 @@ const PostUnstableLlmAsJudgeEvaluatorBody = z.object({
});
const PostUnstableCodeEvaluatorBody = z.object({
- name: z.string().min(1),
+ ...EvaluatorCreateBase,
type: z.literal(PUBLIC_EVALUATOR_TYPE_CODE),
...PublicCodeEvaluatorDefinitionInput.shape,
prompt: z.never().optional(),
diff --git a/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts b/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts
index 805b8eeb7b..fa7c25d956 100644
--- a/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts
+++ b/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts
@@ -1,5 +1,3 @@
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import {
deletePublicEvaluationRule,
getPublicEvaluationRule,
@@ -35,56 +33,24 @@ export default withUnstablePublicEvalsMiddlewares({
querySchema: PatchUnstableEvaluationRuleQuery,
bodySchema: PatchUnstableEvaluationRuleBody,
responseSchema: PatchUnstableEvaluationRuleResponse,
- fn: async ({ query, body, auth }) => {
- const before = await getPublicEvaluationRule({
- projectId: auth.scope.projectId,
- evaluationRuleId: query.evaluationRuleId,
- });
-
- const evaluationRule = await updatePublicEvaluationRule({
+ fn: async ({ query, body, auth }) =>
+ updatePublicEvaluationRule({
orgId: auth.scope.orgId,
projectId: auth.scope.projectId,
evaluationRuleId: query.evaluationRuleId,
input: body,
- });
-
- await auditLog({
- action: "update",
- resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,
- resourceId: evaluationRule.id,
- projectId: auth.scope.projectId,
- orgId: auth.scope.orgId,
- apiKeyId: auth.scope.apiKeyId,
- before,
- after: evaluationRule,
- });
-
- return evaluationRule;
- },
+ auditScope: auth.scope,
+ }),
}),
DELETE: createUnstablePublicEvalsRoute({
name: "Delete Unstable Evaluation Rule",
querySchema: DeleteUnstableEvaluationRuleQuery,
responseSchema: DeleteUnstableEvaluationRuleResponse,
fn: async ({ query, auth }) => {
- const before = await getPublicEvaluationRule({
- projectId: auth.scope.projectId,
- evaluationRuleId: query.evaluationRuleId,
- });
-
await deletePublicEvaluationRule({
projectId: auth.scope.projectId,
evaluationRuleId: query.evaluationRuleId,
- });
-
- await auditLog({
- action: "delete",
- resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,
- resourceId: query.evaluationRuleId,
- projectId: auth.scope.projectId,
- orgId: auth.scope.orgId,
- apiKeyId: auth.scope.apiKeyId,
- before,
+ auditScope: auth.scope,
});
return {
diff --git a/web/src/pages/api/public/unstable/evaluation-rules/index.ts b/web/src/pages/api/public/unstable/evaluation-rules/index.ts
index b222c6f1be..f5089c7e8e 100644
--- a/web/src/pages/api/public/unstable/evaluation-rules/index.ts
+++ b/web/src/pages/api/public/unstable/evaluation-rules/index.ts
@@ -1,5 +1,3 @@
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import {
createPublicEvaluationRule,
listPublicEvaluationRules,
@@ -31,24 +29,12 @@ export default withUnstablePublicEvalsMiddlewares({
name: "Create Unstable Evaluation Rule",
bodySchema: PostUnstableEvaluationRuleBody,
responseSchema: PostUnstableEvaluationRuleResponse,
- fn: async ({ body, auth }) => {
- const evaluationRule = await createPublicEvaluationRule({
+ fn: async ({ body, auth }) =>
+ createPublicEvaluationRule({
orgId: auth.scope.orgId,
projectId: auth.scope.projectId,
input: body,
- });
-
- await auditLog({
- action: "create",
- resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,
- resourceId: evaluationRule.id,
- projectId: auth.scope.projectId,
- orgId: auth.scope.orgId,
- apiKeyId: auth.scope.apiKeyId,
- after: evaluationRule,
- });
-
- return evaluationRule;
- },
+ auditScope: auth.scope,
+ }),
}),
});
diff --git a/web/src/pages/api/public/unstable/evaluators/index.ts b/web/src/pages/api/public/unstable/evaluators/index.ts
index 3b9c2ef3bd..7bae197d2f 100644
--- a/web/src/pages/api/public/unstable/evaluators/index.ts
+++ b/web/src/pages/api/public/unstable/evaluators/index.ts
@@ -1,5 +1,3 @@
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import {
createPublicEvaluator,
listPublicEvaluators,
@@ -31,23 +29,11 @@ export default withUnstablePublicEvalsMiddlewares({
name: "Create Unstable Evaluator",
bodySchema: PostUnstableEvaluatorBody,
responseSchema: PostUnstableEvaluatorResponse,
- fn: async ({ body, auth }) => {
- const evaluator = await createPublicEvaluator({
+ fn: async ({ body, auth }) =>
+ createPublicEvaluator({
projectId: auth.scope.projectId,
input: body,
- });
-
- await auditLog({
- action: "create",
- resourceType: EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,
- resourceId: evaluator.id,
- projectId: auth.scope.projectId,
- orgId: auth.scope.orgId,
- apiKeyId: auth.scope.apiKeyId,
- after: evaluator,
- });
-
- return evaluator;
- },
+ auditScope: auth.scope,
+ }),
}),
});