Skip to content

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

feat(mcp): Make scores available via MCP (#13781)

Ben Bachemca8d9d4bbca4
diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.ts
index f1f01b1b9f..946ac7f476 100644
--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts
@@ -10,17 +10,30 @@ vi.mock("@langfuse/shared/src/server", async () => {
disconnect: vi.fn(),
}),
},
+ ScoreDeleteQueue: {
+ getInstance: () => ({
+ add: vi.fn().mockResolvedValue(undefined),
+ disconnect: vi.fn(),
+ }),
+ },
};
});
import { nanoid } from "nanoid";
import { randomUUID } from "crypto";
import { prisma } from "@langfuse/shared/src/db";
-import { createEvent, createEventsCh } from "@langfuse/shared/src/server";
+import {
+ createEvent,
+ createEventsCh,
+ createScoresCh,
+ createTraceScore,
+} from "@langfuse/shared/src/server";
+import { ScoreConfigDataType } from "@langfuse/shared";
import {
createMcpTestSetup,
createPromptInDb,
mockServerContext,
+ verifyAuditLog,
verifyToolAnnotations,
} from "./mcp-helpers";
import { env } from "@/src/env.mjs";
@@ -68,6 +81,42 @@ import {
listPromptsTool,
handleListPrompts,
} from "@/src/features/mcp/features/prompts/tools/listPrompts";
+import {
+ createScoreConfigTool,
+ handleCreateScoreConfig,
+} from "@/src/features/mcp/features/scores/tools/createScoreConfig";
+import {
+ createScoreTool,
+ handleCreateScore,
+} from "@/src/features/mcp/features/scores/tools/createScore";
+import {
+ deleteScoreTool,
+ handleDeleteScore,
+} from "@/src/features/mcp/features/scores/tools/deleteScore";
+import {
+ deleteScoreConfigTool,
+ handleDeleteScoreConfig,
+} from "@/src/features/mcp/features/scores/tools/deleteScoreConfig";
+import {
+ getScoreTool,
+ handleGetScore,
+} from "@/src/features/mcp/features/scores/tools/getScore";
+import {
+ getScoreConfigTool,
+ handleGetScoreConfig,
+} from "@/src/features/mcp/features/scores/tools/getScoreConfig";
+import {
+ listScoreConfigsTool,
+ handleListScoreConfigs,
+} from "@/src/features/mcp/features/scores/tools/listScoreConfigs";
+import {
+ listScoresTool,
+ handleListScores,
+} from "@/src/features/mcp/features/scores/tools/listScores";
+import {
+ updateScoreConfigTool,
+ handleUpdateScoreConfig,
+} from "@/src/features/mcp/features/scores/tools/updateScoreConfig";
const maybeEventsTable =
env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"
@@ -123,6 +172,42 @@ const createObservationEvent = (params: {
});
};
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
+
+const containsStringValue = (value: unknown, expected: string): boolean => {
+ if (typeof value === "string") {
+ return value.includes(expected);
+ }
+
+ if (Array.isArray(value)) {
+ return value.some((item) => containsStringValue(item, expected));
+ }
+
+ if (isRecord(value)) {
+ return Object.values(value).some((item) =>
+ containsStringValue(item, expected),
+ );
+ }
+
+ return false;
+};
+
+const containsPropertyName = (value: unknown, expected: string): boolean => {
+ if (Array.isArray(value)) {
+ return value.some((item) => containsPropertyName(item, expected));
+ }
+
+ if (isRecord(value)) {
+ return (
+ Object.keys(value).includes(expected) ||
+ Object.values(value).some((item) => containsPropertyName(item, expected))
+ );
+ }
+
+ return false;
+};
+
describe("MCP Read Tools", () => {
describe("getObservationFieldSchema tool", () => {
it("should have readOnlyHint annotation", () => {
@@ -1304,6 +1389,537 @@ describe("MCP Read Tools", () => {
});
});
+ describe("listScores tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(listScoresTool, { readOnlyHint: true });
+ });
+
+ it("should return paginated scores with object-shaped filters", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const matchingScore = createTraceScore({
+ project_id: projectId,
+ id: randomUUID(),
+ name: `mcp-score-${nanoid()}`,
+ data_type: "NUMERIC",
+ value: 0.9,
+ });
+ const otherScore = createTraceScore({
+ project_id: projectId,
+ id: randomUUID(),
+ name: `mcp-score-${nanoid()}`,
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ });
+
+ await createScoresCh([matchingScore, otherScore]);
+
+ const result = (await handleListScores(
+ {
+ limit: 10,
+ page: 1,
+ scoreIds: [matchingScore.id, otherScore.id],
+ dataType: "NUMERIC",
+ fields: ["score"],
+ },
+ context,
+ )) as any;
+ const data = result.data;
+
+ expect(Object.keys(result).sort()).toEqual(["data", "meta"]);
+ expect(result.meta).toMatchObject({
+ page: 1,
+ limit: 10,
+ totalItems: 1,
+ });
+ expect(data).toHaveLength(1);
+ expect(data).toEqual([
+ expect.objectContaining({
+ id: matchingScore.id,
+ dataType: "NUMERIC",
+ }),
+ ]);
+ expect(data).toEqual([
+ expect.not.objectContaining({ trace: expect.anything() }),
+ ]);
+ });
+
+ it("should enforce public v2 score field validation", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(
+ handleListScores({ fields: ["trace"], limit: 10, page: 1 }, context),
+ ).rejects.toThrow(/Scores needs to be selected always/i);
+
+ await expect(
+ handleListScores(
+ { fields: ["score"], userId: "user-1", limit: 10, page: 1 },
+ context,
+ ),
+ ).rejects.toThrow(/Cannot filter by trace properties/i);
+
+ await expect(
+ handleListScores(
+ { fields: ["score"], traceTags: [], limit: 10, page: 1 },
+ context,
+ ),
+ ).resolves.toMatchObject({ data: [] });
+ });
+ });
+
+ describe("getScore tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getScoreTool, { readOnlyHint: true });
+ });
+
+ it("should fetch a score by id", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const score = createTraceScore({
+ project_id: projectId,
+ id: randomUUID(),
+ name: `mcp-get-score-${nanoid()}`,
+ data_type: "NUMERIC",
+ value: 0.8,
+ });
+
+ await createScoresCh([score]);
+
+ const result = await handleGetScore({ scoreId: score.id }, context);
+
+ expect(result).toMatchObject({
+ id: score.id,
+ name: score.name,
+ dataType: "NUMERIC",
+ value: 0.8,
+ });
+ });
+
+ it("should reject missing and cross-project scores", async () => {
+ const { projectId } = await createMcpTestSetup();
+ const { context: otherContext } = await createMcpTestSetup();
+ const score = createTraceScore({
+ project_id: projectId,
+ id: randomUUID(),
+ });
+
+ await createScoresCh([score]);
+
+ await expect(
+ handleGetScore({ scoreId: randomUUID() }, otherContext),
+ ).rejects.toThrow(/Score not found/i);
+ await expect(
+ handleGetScore({ scoreId: score.id }, otherContext),
+ ).rejects.toThrow(/Score not found/i);
+ });
+ });
+
+ describe("createScore tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(createScoreTool, { destructiveHint: true });
+ });
+
+ it("should create a score using v1 route semantics", async () => {
+ const { context } = await createMcpTestSetup();
+ const scoreId = randomUUID();
+
+ const result = await handleCreateScore(
+ {
+ id: scoreId,
+ traceId: randomUUID(),
+ name: `mcp-create-score-${nanoid(8)}`,
+ value: 1,
+ dataType: "NUMERIC",
+ environment: "default",
+ source: "API",
+ },
+ context,
+ );
+
+ expect(result).toEqual({ id: scoreId });
+ });
+ });
+
+ describe("deleteScore tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(deleteScoreTool, { destructiveHint: true });
+ });
+
+ it("should queue score deletion using v1 route semantics", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+ const scoreId = randomUUID();
+
+ const result = await handleDeleteScore({ scoreId }, context);
+
+ expect(result).toEqual({
+ message: "Score deletion queued successfully",
+ });
+ await expect(
+ verifyAuditLog({
+ projectId,
+ resourceType: "score",
+ resourceId: scoreId,
+ action: "delete",
+ apiKeyId,
+ }),
+ ).resolves.toMatchObject({ action: "delete" });
+ });
+ });
+
+ describe("listScoreConfigs tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(listScoreConfigsTool, { readOnlyHint: true });
+ });
+
+ it("should return paginated score configs for the current project", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const { context: otherContext, projectId: otherProjectId } =
+ await createMcpTestSetup();
+ const name = `mcp-config-${nanoid()}`;
+
+ await prisma.scoreConfig.createMany({
+ data: [
+ {
+ id: randomUUID(),
+ projectId,
+ name,
+ dataType: ScoreConfigDataType.NUMERIC,
+ minValue: 0,
+ maxValue: 1,
+ },
+ {
+ id: randomUUID(),
+ projectId: otherProjectId,
+ name,
+ dataType: ScoreConfigDataType.NUMERIC,
+ minValue: 0,
+ maxValue: 1,
+ },
+ ],
+ });
+
+ const result = (await handleListScoreConfigs(
+ { limit: 10, page: 1 },
+ context,
+ )) as any;
+ const otherResult = (await handleListScoreConfigs(
+ { limit: 10, page: 1 },
+ otherContext,
+ )) as any;
+
+ expect(Object.keys(result).sort()).toEqual(["data", "meta"]);
+ expect(result.data).toEqual(
+ expect.arrayContaining([expect.objectContaining({ projectId, name })]),
+ );
+ expect(result.data).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ projectId: otherProjectId, name }),
+ ]),
+ );
+ expect(otherResult.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ projectId: otherProjectId, name }),
+ ]),
+ );
+ });
+ });
+
+ describe("getScoreConfig tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getScoreConfigTool, { readOnlyHint: true });
+ });
+
+ it("should fetch a score config by id", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const config = await prisma.scoreConfig.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ name: `mcp-get-${nanoid(8)}`,
+ dataType: ScoreConfigDataType.BOOLEAN,
+ categories: [
+ { label: "True", value: 1 },
+ { label: "False", value: 0 },
+ ],
+ },
+ });
+
+ const result = await handleGetScoreConfig(
+ { configId: config.id },
+ context,
+ );
+
+ expect(result).toMatchObject({
+ id: config.id,
+ name: config.name,
+ dataType: ScoreConfigDataType.BOOLEAN,
+ });
+ });
+
+ it("should reject missing and cross-project score configs", async () => {
+ const { projectId } = await createMcpTestSetup();
+ const { context: otherContext } = await createMcpTestSetup();
+ const config = await prisma.scoreConfig.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ name: `mcp-cross-${nanoid(8)}`,
+ dataType: ScoreConfigDataType.TEXT,
+ },
+ });
+
+ await expect(
+ handleGetScoreConfig({ configId: randomUUID() }, otherContext),
+ ).rejects.toThrow(/Score config not found/i);
+ await expect(
+ handleGetScoreConfig({ configId: config.id }, otherContext),
+ ).rejects.toThrow(/Score config not found/i);
+ });
+ });
+
+ describe("createScoreConfig tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(createScoreConfigTool, { destructiveHint: true });
+ });
+
+ it("should describe allowed score config name characters in the input schema", () => {
+ expect(
+ containsStringValue(
+ createScoreConfigTool.inputSchema,
+ "Allowed characters: letters, numbers, spaces, underscores, periods, parentheses, and hyphens.",
+ ),
+ ).toBe(true);
+ });
+
+ it.each([
+ [
+ "numeric",
+ {
+ name: `mcp-num-${nanoid(8)}`,
+ dataType: "NUMERIC" as const,
+ minValue: 0,
+ maxValue: 1,
+ },
+ ],
+ [
+ "categorical",
+ {
+ name: `mcp-cat-${nanoid(8)}`,
+ dataType: "CATEGORICAL" as const,
+ categories: [
+ { label: "High", value: 1 },
+ { label: "Low", value: 0 },
+ ],
+ },
+ ],
+ [
+ "text",
+ {
+ name: `mcp-text-${nanoid(8)}`,
+ dataType: "TEXT" as const,
+ categories: undefined,
+ },
+ ],
+ ])("should create %s score configs", async (_type, input) => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+
+ const result = (await handleCreateScoreConfig(input, context)) as any;
+
+ expect(result).toMatchObject({
+ projectId,
+ name: input.name,
+ dataType: input.dataType,
+ });
+
+ await expect(
+ verifyAuditLog({
+ projectId,
+ resourceType: "scoreConfig",
+ resourceId: result.id,
+ action: "create",
+ apiKeyId,
+ }),
+ ).resolves.toMatchObject({ action: "create" });
+ });
+
+ it("should create boolean configs with inferred categories", async () => {
+ const { context } = await createMcpTestSetup();
+
+ const result = await handleCreateScoreConfig(
+ {
+ name: `mcp-bool-${nanoid(8)}`,
+ dataType: "BOOLEAN",
+ categories: undefined,
+ },
+ context,
+ );
+
+ expect(result).toMatchObject({
+ dataType: ScoreConfigDataType.BOOLEAN,
+ categories: [
+ { label: "True", value: 1 },
+ { label: "False", value: 0 },
+ ],
+ });
+ });
+
+ it("should reject invalid categories", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(
+ handleCreateScoreConfig(
+ {
+ name: `mcp-invalid-${nanoid(8)}`,
+ dataType: "CATEGORICAL",
+ categories: [
+ { label: "Duplicate", value: 1 },
+ { label: "Duplicate", value: 2 },
+ ],
+ },
+ context,
+ ),
+ ).rejects.toThrow(/Category labels must be unique/i);
+ });
+ });
+
+ describe("updateScoreConfig tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(updateScoreConfigTool, { destructiveHint: true });
+ });
+
+ it("should describe allowed score config name characters in the input schema", () => {
+ expect(
+ containsStringValue(
+ updateScoreConfigTool.inputSchema,
+ "Allowed characters: letters, numbers, spaces, underscores, periods, parentheses, and hyphens.",
+ ),
+ ).toBe(true);
+ });
+
+ it("should not expose archive state in the input schema", () => {
+ expect(
+ containsPropertyName(updateScoreConfigTool.inputSchema, "isArchived"),
+ ).toBe(false);
+ });
+
+ it("should update allowed fields and write an audit log", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+ const config = await prisma.scoreConfig.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ name: `mcp-update-${nanoid(8)}`,
+ dataType: ScoreConfigDataType.NUMERIC,
+ minValue: 0,
+ maxValue: 1,
+ },
+ });
+
+ const result = await handleUpdateScoreConfig(
+ {
+ configId: config.id,
+ name: "mcp-updated",
+ description: "Updated through MCP",
+ minValue: -1,
+ },
+ context,
+ );
+
+ expect(result).toMatchObject({
+ id: config.id,
+ name: "mcp-updated",
+ description: "Updated through MCP",
+ minValue: -1,
+ });
+
+ await expect(
+ verifyAuditLog({
+ projectId,
+ resourceType: "scoreConfig",
+ resourceId: config.id,
+ action: "update",
+ apiKeyId,
+ }),
+ ).resolves.toMatchObject({ action: "update" });
+ });
+
+ it("should reject empty update bodies", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(
+ handleUpdateScoreConfig({ configId: randomUUID() }, context),
+ ).rejects.toThrow(/Request body cannot be empty/i);
+ });
+
+ it("should not archive score configs through update", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const config = await prisma.scoreConfig.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ name: `mcp-update-no-archive-${nanoid(8)}`,
+ dataType: ScoreConfigDataType.NUMERIC,
+ minValue: 0,
+ maxValue: 1,
+ },
+ });
+
+ const result = await handleUpdateScoreConfig(
+ {
+ configId: config.id,
+ name: "mcp-still-active",
+ isArchived: true,
+ } as unknown as Parameters<typeof handleUpdateScoreConfig>[0],
+ context,
+ );
+
+ expect(result).toMatchObject({
+ id: config.id,
+ name: "mcp-still-active",
+ isArchived: false,
+ });
+ });
+ });
+
+ describe("deleteScoreConfig tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(deleteScoreConfigTool, { destructiveHint: true });
+ });
+
+ it("should archive the score config", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+ const config = await prisma.scoreConfig.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ name: `mcp-delete-config-${nanoid(8)}`,
+ dataType: ScoreConfigDataType.NUMERIC,
+ minValue: 0,
+ maxValue: 1,
+ },
+ });
+
+ const result = await handleDeleteScoreConfig(
+ { configId: config.id },
+ context,
+ );
+
+ expect(result).toMatchObject({
+ id: config.id,
+ isArchived: true,
+ });
+
+ await expect(
+ verifyAuditLog({
+ projectId,
+ resourceType: "scoreConfig",
+ resourceId: config.id,
+ action: "update",
+ apiKeyId,
+ }),
+ ).resolves.toMatchObject({ action: "update" });
+ });
+ });
+
describe("getPrompt tool", () => {
it("should have readOnlyHint annotation", () => {
verifyToolAnnotations(getPromptTool, { readOnlyHint: true });
diff --git a/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts b/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts
new file mode 100644
index 0000000000..889e211afc
--- /dev/null
+++ b/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod";
+import { defineTool } from "../../../features/mcp/core/define-tool";
+import { updateScoreConfigTool } from "../../../features/mcp/features/scores/tools/updateScoreConfig";
+
+describe("defineTool", () => {
+ it("accepts object intersections emitted as JSON Schema allOf", () => {
+ const schema = z.object({ id: z.string() }).and(
+ z.object({
+ dataType: z.literal("NUMERIC"),
+ value: z.number(),
+ }),
+ );
+
+ const [tool] = defineTool({
+ name: "createScore",
+ description: "Create a score",
+ baseSchema: schema,
+ inputSchema: schema,
+ handler: async (input) => input,
+ });
+
+ expect(tool.inputSchema).toHaveProperty("allOf");
+ });
+
+ it("defines updateScoreConfig without omitting from a refined schema", () => {
+ expect(updateScoreConfigTool.name).toBe("updateScoreConfig");
+ });
+});
diff --git a/web/src/features/mcp/core/define-tool.ts b/web/src/features/mcp/core/define-tool.ts
index 0ffe03bcac..50127535c2 100644
--- a/web/src/features/mcp/core/define-tool.ts
+++ b/web/src/features/mcp/core/define-tool.ts
@@ -52,12 +52,7 @@ export interface DefineToolOptions<TInput> {
export interface ToolDefinition {
name: string;
description: string;
- inputSchema: {
- type: "object";
- properties: Record<string, unknown>;
- required?: string[];
- additionalProperties?: boolean;
- };
+ inputSchema: Record<string, unknown>;
annotations?: {
readOnlyHint?: boolean;
destructiveHint?: boolean;
@@ -65,6 +60,27 @@ export interface ToolDefinition {
};
}
+type JsonSchemaObject = Record<string, unknown>;
+
+function isObjectLikeJsonSchema(schema: JsonSchemaObject): boolean {
+ if (schema.type === "object") return true;
+
+ if ("oneOf" in schema || "anyOf" in schema || "discriminator" in schema) {
+ return true;
+ }
+
+ if (Array.isArray(schema.allOf)) {
+ return schema.allOf.every(
+ (subSchema) =>
+ typeof subSchema === "object" &&
+ subSchema !== null &&
+ isObjectLikeJsonSchema(subSchema as JsonSchemaObject),
+ );
+ }
+
+ return false;
+}
+
/**
* Define an MCP tool with automatic JSON Schema generation.
*
@@ -114,13 +130,9 @@ export function defineTool<TInput>(
);
}
- // Validate that we got a usable schema (object or union of objects)
- const hasObjectType = (jsonSchema as { type?: string }).type === "object";
- const hasUnionType =
- "oneOf" in jsonSchema ||
- "anyOf" in jsonSchema ||
- "discriminator" in jsonSchema;
- if (!hasObjectType && !hasUnionType) {
+ // Validate that we got a usable schema. Intersections of object schemas are
+ // emitted as top-level allOf by Zod's JSON Schema converter.
+ if (!isObjectLikeJsonSchema(jsonSchema)) {
throw new Error(
`Failed to convert Zod schema to JSON Schema for tool: ${name}. Expected object or union schema, got: ${JSON.stringify(jsonSchema).slice(0, 100)}`,
);
@@ -130,7 +142,7 @@ export function defineTool<TInput>(
const toolDefinition: ToolDefinition = {
name,
description,
- inputSchema: jsonSchema as ToolDefinition["inputSchema"],
+ inputSchema: jsonSchema,
};
// Add annotations if provided
diff --git a/web/src/features/mcp/features/scores/index.ts b/web/src/features/mcp/features/scores/index.ts
new file mode 100644
index 0000000000..10109fcc09
--- /dev/null
+++ b/web/src/features/mcp/features/scores/index.ts
@@ -0,0 +1,69 @@
+import type { McpFeatureModule } from "../../server/registry";
+import { getScoreTool, handleGetScore } from "./tools/getScore";
+import {
+ getScoreConfigTool,
+ handleGetScoreConfig,
+} from "./tools/getScoreConfig";
+import { listScoresTool, handleListScores } from "./tools/listScores";
+import {
+ listScoreConfigsTool,
+ handleListScoreConfigs,
+} from "./tools/listScoreConfigs";
+import {
+ createScoreConfigTool,
+ handleCreateScoreConfig,
+} from "./tools/createScoreConfig";
+import { createScoreTool, handleCreateScore } from "./tools/createScore";
+import { deleteScoreTool, handleDeleteScore } from "./tools/deleteScore";
+import {
+ deleteScoreConfigTool,
+ handleDeleteScoreConfig,
+} from "./tools/deleteScoreConfig";
+import {
+ updateScoreConfigTool,
+ handleUpdateScoreConfig,
+} from "./tools/updateScoreConfig";
+
+export const scoresFeature: McpFeatureModule = {
+ name: "scores",
+ description:
+ "Read scores and manage score configurations in the current Langfuse project",
+ tools: [
+ {
+ definition: listScoresTool,
+ handler: handleListScores,
+ },
+ {
+ definition: getScoreTool,
+ handler: handleGetScore,
+ },
+ {
+ definition: createScoreTool,
+ handler: handleCreateScore,
+ },
+ {
+ definition: deleteScoreTool,
+ handler: handleDeleteScore,
+ },
+ {
+ definition: listScoreConfigsTool,
+ handler: handleListScoreConfigs,
+ },
+ {
+ definition: getScoreConfigTool,
+ handler: handleGetScoreConfig,
+ },
+ {
+ definition: createScoreConfigTool,
+ handler: handleCreateScoreConfig,
+ },
+ {
+ definition: updateScoreConfigTool,
+ handler: handleUpdateScoreConfig,
+ },
+ {
+ definition: deleteScoreConfigTool,
+ handler: handleDeleteScoreConfig,
+ },
+ ],
+};
diff --git a/web/src/features/mcp/features/scores/schema.ts b/web/src/features/mcp/features/scores/schema.ts
new file mode 100644
index 0000000000..3743951f59
--- /dev/null
+++ b/web/src/features/mcp/features/scores/schema.ts
@@ -0,0 +1,7 @@
+import { ScoreConfigNameSchema } from "@langfuse/shared";
+
+const McpScoreConfigNameSchema = ScoreConfigNameSchema.describe(
+ "Allowed characters: letters, numbers, spaces, underscores, periods, parentheses, and hyphens.",
+);
+
+export { McpScoreConfigNameSchema };
diff --git a/web/src/features/mcp/features/scores/tools/createScore.ts b/web/src/features/mcp/features/scores/tools/createScore.ts
new file mode 100644
index 0000000000..470913c127
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/createScore.ts
@@ -0,0 +1,86 @@
+import { SpanKind } from "@opentelemetry/api";
+import {
+ InvalidRequestError,
+ LangfuseNotFoundError,
+ PostScoresBodyV1,
+ PostScoresResponseV1,
+ UnauthorizedError,
+} from "@langfuse/shared";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
+import { defineTool } from "../../../core/define-tool";
+import { ApiServerError } from "../../../core/errors";
+
+type CreateScoreBatchError = {
+ status: number;
+ message?: string;
+ error?: string;
+};
+
+const throwCreateScoreBatchError = (error: CreateScoreBatchError): never => {
+ const message = error.error ?? error.message ?? "Failed to create score";
+
+ if (error.status === 400) {
+ throw new InvalidRequestError(message);
+ }
+
+ if (error.status === 401) {
+ throw new UnauthorizedError(message);
+ }
+
+ if (error.status === 404) {
+ throw new LangfuseNotFoundError(message);
+ }
+
+ throw new ApiServerError("Failed to create score");
+};
+
+export const [createScoreTool, handleCreateScore] = defineTool({
+ name: "createScore",
+ description:
+ "Create one score in the current Langfuse project using the v1 /api/public/scores route semantics. This is the v1 fallback because score creation has no v2 public route.",
+ baseSchema: PostScoresBodyV1,
+ inputSchema: PostScoresBodyV1,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.scores.create", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ ...(input.id ? { "mcp.score_id": input.id } : {}),
+ "mcp.score_name": input.name,
+ });
+
+ const scoresApiService = new ScoresApiService("v2");
+ const { id: scoreId, result } = await scoresApiService.createScore({
+ body: input,
+ auth: {
+ validKey: true,
+ scope: {
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ publicKey: context.publicKey,
+ accessLevel: context.accessLevel,
+ isIngestionSuspended: false,
+ },
+ },
+ });
+ span.setAttribute("mcp.score_id", scoreId);
+
+ if (result.errors.length > 0) {
+ throwCreateScoreBatchError(result.errors[0]);
+ }
+
+ if (result.successes.length !== 1) {
+ throw new ApiServerError("Failed to create score");
+ }
+
+ return PostScoresResponseV1.parse({ id: scoreId });
+ },
+ );
+ },
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/createScoreConfig.ts b/web/src/features/mcp/features/scores/tools/createScoreConfig.ts
new file mode 100644
index 0000000000..a4b46e2088
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/createScoreConfig.ts
@@ -0,0 +1,44 @@
+import { SpanKind } from "@opentelemetry/api";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+import { createScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
+import { PostScoreConfigBody } from "@/src/features/public-api/types/score-configs";
+import { z } from "zod";
+import { McpScoreConfigNameSchema } from "../schema";
+
+const CreateScoreConfigInputSchema = z
+ .object({
+ name: McpScoreConfigNameSchema,
+ })
+ .and(PostScoreConfigBody);
+
+export const [createScoreConfigTool, handleCreateScoreConfig] = defineTool({
+ name: "createScoreConfig",
+ description:
+ "Create a score configuration in the current Langfuse project. Supports numeric, categorical, boolean, and text configs. Boolean configs automatically receive True and False categories.",
+ baseSchema: CreateScoreConfigInputSchema,
+ inputSchema: CreateScoreConfigInputSchema,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.score_configs.create", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.score_config_name": input.name,
+ "mcp.score_config_data_type": input.dataType,
+ });
+
+ const config = await createScoreConfig({
+ context,
+ body: input,
+ });
+
+ span.setAttribute("mcp.score_config_id", config.id);
+ return config;
+ },
+ );
+ },
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/deleteScore.ts b/web/src/features/mcp/features/scores/tools/deleteScore.ts
new file mode 100644
index 0000000000..a3521b3653
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/deleteScore.ts
@@ -0,0 +1,37 @@
+import { SpanKind } from "@opentelemetry/api";
+import { DeleteScoreQueryV1, DeleteScoreResponseV1 } from "@langfuse/shared";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
+import { defineTool } from "../../../core/define-tool";
+
+export const [deleteScoreTool, handleDeleteScore] = defineTool({
+ name: "deleteScore",
+ description:
+ "Delete one score from the current Langfuse project using the v1 /api/public/scores/{scoreId} route semantics. This is the v1 fallback because score deletion has no v2 public route.",
+ baseSchema: DeleteScoreQueryV1,
+ inputSchema: DeleteScoreQueryV1,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.scores.delete", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.score_id": input.scoreId,
+ });
+
+ const scoresApiService = new ScoresApiService("v2");
+ const result = await scoresApiService.deleteScore({
+ scoreId: input.scoreId,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ });
+
+ return DeleteScoreResponseV1.parse(result);
+ },
+ );
+ },
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/deleteScoreConfig.ts b/web/src/features/mcp/features/scores/tools/deleteScoreConfig.ts
new file mode 100644
index 0000000000..9bb3631c40
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/deleteScoreConfig.ts
@@ -0,0 +1,33 @@
+import { SpanKind } from "@opentelemetry/api";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+import { updateScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
+import { PutScoreConfigQuery } from "@/src/features/public-api/types/score-configs";
+
+export const [deleteScoreConfigTool, handleDeleteScoreConfig] = defineTool({
+ name: "deleteScoreConfig",
+ description:
+ "Delete a score configuration from the current Langfuse project by archiving it.",
+ baseSchema: PutScoreConfigQuery,
+ inputSchema: PutScoreConfigQuery,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.score_configs.delete", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.score_config_id": input.configId,
+ });
+
+ return await updateScoreConfig({
+ context,
+ configId: input.configId,
+ body: { isArchived: true },
+ });
+ },
+ );
+ },
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/getScore.ts b/web/src/features/mcp/features/scores/tools/getScore.ts
new file mode 100644
index 0000000000..6dd9296776
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/getScore.ts
@@ -0,0 +1,55 @@
+import { SpanKind } from "@opentelemetry/api";
+import {
+ GetScoreQueryV2,
+ GetScoreResponseV2,
+ InternalServerError,
+ LangfuseNotFoundError,
+} from "@langfuse/shared";
+import {
+ instrumentAsync,
+ logger,
+ traceException,
+} from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
+
+export const [getScoreTool, handleGetScore] = defineTool({
+ name: "getScore",
+ description:
+ "Fetch one score by ID from the current Langfuse project using the v2 /api/public/v2/scores/{scoreId} semantics. Returns the public score object directly.",
+ baseSchema: GetScoreQueryV2,
+ inputSchema: GetScoreQueryV2,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.scores.get", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.score_id": input.scoreId,
+ });
+
+ const scoresApiService = new ScoresApiService("v2");
+ const score = await scoresApiService.getScoreById({
+ projectId: context.projectId,
+ scoreId: input.scoreId,
+ });
+
+ if (!score) {
+ throw new LangfuseNotFoundError("Score not found");
+ }
+
+ const parsedScore = GetScoreResponseV2.safeParse(score);
+ if (!parsedScore.success) {
+ traceException(parsedScore.error);
+ logger.error(`Incorrect score return type ${parsedScore.error}`);
+ throw new InternalServerError("Requested score is corrupted");
+ }
+
+ return parsedScore.data;
+ },
+ );
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/getScoreConfig.ts b/web/src/features/mcp/features/scores/tools/getScoreConfig.ts
new file mode 100644
index 0000000000..fec4a20d41
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/getScoreConfig.ts
@@ -0,0 +1,32 @@
+import { SpanKind } from "@opentelemetry/api";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+import { getScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
+import { GetScoreConfigQuery } from "@/src/features/public-api/types/score-configs";
+
+export const [getScoreConfigTool, handleGetScoreConfig] = defineTool({
+ name: "getScoreConfig",
+ description:
+ "Fetch one score configuration by ID from the current Langfuse project. Returns the public score config object directly.",
+ baseSchema: GetScoreConfigQuery,
+ inputSchema: GetScoreConfigQuery,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.score_configs.get", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.score_config_id": input.configId,
+ });
+
+ return await getScoreConfig({
+ projectId: context.projectId,
+ configId: input.configId,
+ });
+ },
+ );
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/listScoreConfigs.ts b/web/src/features/mcp/features/scores/tools/listScoreConfigs.ts
new file mode 100644
index 0000000000..2e764a3039
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/listScoreConfigs.ts
@@ -0,0 +1,37 @@
+import { SpanKind } from "@opentelemetry/api";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+import { listScoreConfigs } from "@/src/features/public-api/server/score-configs-api-service";
+import { GetScoreConfigsQuery } from "@/src/features/public-api/types/score-configs";
+
+export const [listScoreConfigsTool, handleListScoreConfigs] = defineTool({
+ name: "listScoreConfigs",
+ description:
+ "List score configurations in the current Langfuse project. Returns exactly data and meta at the top level.",
+ baseSchema: GetScoreConfigsQuery,
+ inputSchema: GetScoreConfigsQuery,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.score_configs.list", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ });
+
+ const result = await listScoreConfigs({
+ projectId: context.projectId,
+ page: input.page,
+ limit: input.limit,
+ });
+
+ span.setAttribute("mcp.result_count", result.data.length);
+ return result;
+ },
+ );
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/listScores.ts b/web/src/features/mcp/features/scores/tools/listScores.ts
new file mode 100644
index 0000000000..705bde3755
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/listScores.ts
@@ -0,0 +1,144 @@
+import { SpanKind } from "@opentelemetry/api";
+import {
+ filterAndValidateV2GetScoreList,
+ InvalidRequestError,
+ ScoreDataTypeDomain,
+ ScoreSourceDomain,
+ singleFilter,
+ publicApiPaginationZod,
+} from "@langfuse/shared";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { z } from "zod";
+import { defineTool } from "../../../core/define-tool";
+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
+
+const ScoreFieldsSchema = z
+ .array(z.enum(["score", "trace"]))
+ .default(["score", "trace"])
+ .describe(
+ "Response field groups to include. 'score' is always required. Include 'trace' when filtering by userId or traceTags.",
+ );
+
+const ListScoresInputSchema = z.object({
+ ...publicApiPaginationZod,
+ fields: ScoreFieldsSchema,
+ userId: z.string().optional(),
+ dataType: ScoreDataTypeDomain.optional(),
+ configId: z.string().optional(),
+ queueId: z.string().optional(),
+ traceTags: z
+ .array(z.string())
+ .optional()
+ .describe("Trace tags to filter by."),
+ environment: z
+ .array(z.string())
+ .optional()
+ .describe("Score environments to filter by."),
+ name: z.string().optional(),
+ fromTimestamp: z.iso.datetime({ offset: true }).optional(),
+ toTimestamp: z.iso.datetime({ offset: true }).optional(),
+ source: ScoreSourceDomain.optional(),
+ value: z.number().optional(),
+ operator: z.enum(["<", ">", "<=", ">=", "!=", "="]).optional(),
+ scoreIds: z.array(z.string()).optional(),
+ sessionId: z.string().optional(),
+ traceId: z.string().optional(),
+ datasetRunId: z.string().optional(),
+ observationId: z.array(z.string()).optional(),
+ filter: z
+ .array(singleFilter)
+ .optional()
+ .describe(
+ "Advanced score filters as JSON objects with column, operator, value, and type.",
+ ),
+});
+
+type ListScoresInput = z.infer<typeof ListScoresInputSchema>;
+
+const assertValidScoreFields = (input: ListScoresInput) => {
+ if (!input.fields.includes("score")) {
+ throw new InvalidRequestError("Scores needs to be selected always.");
+ }
+
+ const hasTraceFilters =
+ Boolean(input.userId) || (input.traceTags?.length ?? 0) > 0;
+ if (!input.fields.includes("trace") && hasTraceFilters) {
+ throw new InvalidRequestError(
+ "Cannot filter by trace properties (userId, traceTags) when 'trace' field is not included. Please add 'trace' to the fields parameter or remove trace filters.",
+ );
+ }
+};
+
+export const [listScoresTool, handleListScores] = defineTool({
+ name: "listScores",
+ description: [
+ "Find scores in the current Langfuse project.",
+ "Uses the v2 /api/public/v2/scores semantics for numeric, categorical, boolean, correction, and text scores across traces, observations, sessions, and dataset runs.",
+ "Results are paginated with page and limit and return exactly data and meta at the top level.",
+ ].join("\n"),
+ baseSchema: ListScoresInputSchema,
+ inputSchema: ListScoresInputSchema,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.scores.list", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ assertValidScoreFields(input);
+
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ "mcp.score_fields": input.fields.join(","),
+ });
+
+ const scoreParams = {
+ projectId: context.projectId,
+ page: input.page,
+ limit: input.limit,
+ userId: input.userId,
+ name: input.name,
+ configId: input.configId,
+ sessionId: input.sessionId,
+ traceId: input.traceId,
+ observationId: input.observationId,
+ datasetRunId: input.datasetRunId,
+ queueId: input.queueId,
+ traceTags: input.traceTags,
+ dataType: input.dataType,
+ fromTimestamp: input.fromTimestamp,
+ toTimestamp: input.toTimestamp,
+ environment: input.environment,
+ source: input.source,
+ value: input.value,
+ operator: input.operator,
+ scoreIds: input.scoreIds,
+ fields: input.fields,
+ advancedFilters: input.filter,
+ };
+
+ const scoresApiService = new ScoresApiService("v2");
+ const [items, count] = await Promise.all([
+ scoresApiService.generateScoresForPublicApi(scoreParams),
+ scoresApiService.getScoresCountForPublicApi(scoreParams),
+ ]);
+
+ const totalItems = count ?? 0;
+ const data = filterAndValidateV2GetScoreList(items);
+ span.setAttribute("mcp.result_count", data.length);
+
+ return {
+ data,
+ meta: {
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / input.limit),
+ },
+ };
+ },
+ );
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/scores/tools/updateScoreConfig.ts b/web/src/features/mcp/features/scores/tools/updateScoreConfig.ts
new file mode 100644
index 0000000000..675fc6d75e
--- /dev/null
+++ b/web/src/features/mcp/features/scores/tools/updateScoreConfig.ts
@@ -0,0 +1,49 @@
+import { SpanKind } from "@opentelemetry/api";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { defineTool } from "../../../core/define-tool";
+import { updateScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
+import {
+ PutScoreConfigBodyWithoutArchived,
+ PutScoreConfigQuery,
+} from "@/src/features/public-api/types/score-configs";
+import { z } from "zod";
+import { McpScoreConfigNameSchema } from "../schema";
+
+const UpdateScoreConfigInputSchema = PutScoreConfigQuery.and(
+ PutScoreConfigBodyWithoutArchived,
+);
+
+const McpUpdateScoreConfigInputSchema = z
+ .object({
+ name: McpScoreConfigNameSchema.optional(),
+ })
+ .and(UpdateScoreConfigInputSchema);
+
+export const [updateScoreConfigTool, handleUpdateScoreConfig] = defineTool({
+ name: "updateScoreConfig",
+ description:
+ "Update a score configuration in the current Langfuse project. Use this to rename, describe, or adjust allowed numeric/category fields.",
+ baseSchema: McpUpdateScoreConfigInputSchema,
+ inputSchema: McpUpdateScoreConfigInputSchema,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.score_configs.update", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ const { configId, ...body } = input;
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ "mcp.score_config_id": configId,
+ });
+
+ return await updateScoreConfig({
+ context,
+ configId,
+ body,
+ });
+ },
+ );
+ },
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
index 1a8b95b0cf..9ef8d3e463 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 { scoresFeature } from "../features/scores";
import { metricsFeature } from "../features/metrics";
// Import future features as they're added:
// import { datasetsFeature } from "../features/datasets";
@@ -29,6 +30,7 @@ export function bootstrapMcpFeatures(): void {
// Register all feature modules
toolRegistry.register(promptsFeature);
toolRegistry.register(observationsFeature);
+ toolRegistry.register(scoresFeature);
toolRegistry.register(metricsFeature);
// Add future features here:
diff --git a/web/src/features/public-api/server/score-configs-api-service.ts b/web/src/features/public-api/server/score-configs-api-service.ts
new file mode 100644
index 0000000000..8773e9db54
--- /dev/null
+++ b/web/src/features/public-api/server/score-configs-api-service.ts
@@ -0,0 +1,195 @@
+import { v4 } from "uuid";
+import { type z } from "zod";
+import { isBooleanDataType } from "@/src/features/scores/lib/helpers";
+import {
+ filterAndValidateDbScoreConfigList,
+ InternalServerError,
+ InvalidRequestError,
+ LangfuseNotFoundError,
+ validateDbScoreConfig,
+ validateDbScoreConfigSafe,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { traceException } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ type PostScoreConfigBody,
+ type PutScoreConfigBody,
+} from "@/src/features/public-api/types/score-configs";
+
+type ApiKeyProjectContext = {
+ projectId: string;
+ orgId: string;
+ apiKeyId: string;
+};
+
+const inflateConfigBody = (body: z.infer<typeof PostScoreConfigBody>) => {
+ if (isBooleanDataType(body.dataType)) {
+ return {
+ ...body,
+ categories: [
+ { label: "True", value: 1 },
+ { label: "False", value: 0 },
+ ],
+ };
+ }
+
+ return body;
+};
+
+export const createScoreConfig = async ({
+ context,
+ body,
+}: {
+ context: ApiKeyProjectContext;
+ body: z.infer<typeof PostScoreConfigBody>;
+}) => {
+ const inflatedConfigInput = inflateConfigBody(body);
+
+ const config = await prisma.scoreConfig.create({
+ data: {
+ ...inflatedConfigInput,
+ categories: inflatedConfigInput.categories ?? undefined,
+ id: v4(),
+ projectId: context.projectId,
+ },
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "scoreConfig",
+ resourceId: config.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: config,
+ });
+
+ return validateDbScoreConfig(config);
+};
+
+export const listScoreConfigs = async ({
+ projectId,
+ page,
+ limit,
+}: {
+ projectId: string;
+ page: number;
+ limit: number;
+}) => {
+ const [rawConfigs, totalItems] = await Promise.all([
+ prisma.scoreConfig.findMany({
+ where: {
+ projectId,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: limit,
+ skip: (page - 1) * limit,
+ }),
+ prisma.scoreConfig.count({
+ where: {
+ projectId,
+ },
+ }),
+ ]);
+
+ const configs = filterAndValidateDbScoreConfigList(
+ rawConfigs,
+ traceException,
+ );
+
+ return {
+ data: configs,
+ meta: {
+ page,
+ limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / limit),
+ },
+ };
+};
+
+export const getScoreConfig = async ({
+ projectId,
+ configId,
+}: {
+ projectId: string;
+ configId: string;
+}) => {
+ const config = await prisma.scoreConfig.findUnique({
+ where: {
+ id: configId,
+ projectId,
+ },
+ });
+
+ if (!config) {
+ throw new LangfuseNotFoundError(
+ "Score config not found within authorized project",
+ );
+ }
+
+ const parsedConfig = validateDbScoreConfigSafe(config);
+ if (!parsedConfig.success) {
+ traceException(parsedConfig.error);
+ throw new InternalServerError("Requested score config is corrupted");
+ }
+
+ return parsedConfig.data;
+};
+
+export const updateScoreConfig = async ({
+ context,
+ configId,
+ body,
+}: {
+ context: ApiKeyProjectContext;
+ configId: string;
+ body: z.infer<typeof PutScoreConfigBody>;
+}) => {
+ const existingConfig = await prisma.scoreConfig.findUnique({
+ where: {
+ id: configId,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!existingConfig) {
+ throw new LangfuseNotFoundError(
+ "Score config not found within authorized project",
+ );
+ }
+
+ const result = validateDbScoreConfigSafe({ ...existingConfig, ...body });
+
+ if (!result.success) {
+ throw new InvalidRequestError(
+ result.error.issues.map((issue) => issue.message).join(", "),
+ );
+ }
+
+ const config = await prisma.scoreConfig.update({
+ where: {
+ id: configId,
+ projectId: context.projectId,
+ },
+ data: {
+ ...body,
+ },
+ });
+
+ await auditLog({
+ action: "update",
+ resourceType: "scoreConfig",
+ resourceId: config.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: existingConfig,
+ after: config,
+ });
+
+ return validateDbScoreConfig(config);
+};
diff --git a/web/src/features/public-api/server/scores-api-service.ts b/web/src/features/public-api/server/scores-api-service.ts
index 572f4be0b0..d80e56d896 100644
--- a/web/src/features/public-api/server/scores-api-service.ts
+++ b/web/src/features/public-api/server/scores-api-service.ts
@@ -1,15 +1,93 @@
+import { randomUUID } from "crypto";
+
import {
_handleGenerateScoresForPublicApi,
_handleGetScoresCountForPublicApi,
convertScoreToPublicApi,
type ScoreQueryType,
} from "@/src/features/public-api/server/scores";
-import { LISTABLE_SCORE_TYPES, type ScoreSourceType } from "@langfuse/shared";
-import { _handleGetScoreById } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ InternalServerError,
+ LISTABLE_SCORE_TYPES,
+ type ScoreSourceType,
+ type PostScoresBodyV1,
+} from "@langfuse/shared";
+import {
+ _handleGetScoreById,
+ eventTypes,
+ processEventBatch,
+ QueueJobs,
+ ScoreDeleteQueue,
+ type AuthHeaderValidVerificationResultIngestion,
+} from "@langfuse/shared/src/server";
+import type { z } from "zod";
export class ScoresApiService {
constructor(private readonly apiVersion: "v1" | "v2") {}
+ async createScore({
+ body,
+ auth,
+ scoreId = body.id ?? randomUUID(),
+ }: {
+ body: z.infer<typeof PostScoresBodyV1>;
+ auth: AuthHeaderValidVerificationResultIngestion;
+ scoreId?: string;
+ }) {
+ const result = await processEventBatch(
+ [
+ {
+ id: randomUUID(),
+ type: eventTypes.SCORE_CREATE,
+ timestamp: new Date().toISOString(),
+ body: { ...body, id: scoreId },
+ },
+ ],
+ auth,
+ );
+
+ return { id: scoreId, result };
+ }
+
+ async deleteScore({
+ projectId,
+ orgId,
+ apiKeyId,
+ scoreId,
+ }: {
+ projectId: string;
+ orgId: string;
+ apiKeyId: string;
+ scoreId: string;
+ }) {
+ const scoreDeleteQueue = ScoreDeleteQueue.getInstance();
+ if (!scoreDeleteQueue) {
+ throw new InternalServerError("ScoreDeleteQueue not initialized");
+ }
+
+ await auditLog({
+ action: "delete",
+ resourceType: "score",
+ resourceId: scoreId,
+ projectId,
+ orgId,
+ apiKeyId,
+ });
+
+ await scoreDeleteQueue.add(QueueJobs.ScoreDelete, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ payload: {
+ projectId,
+ scoreIds: [scoreId],
+ },
+ name: QueueJobs.ScoreDelete,
+ });
+
+ return { message: "Score deletion queued successfully" };
+ }
+
/**
* Get a specific score by ID
* v1: Returns listable scores (NUMERIC, BOOLEAN, CATEGORICAL, TEXT) - excludes CORRECTION
diff --git a/web/src/features/public-api/types/score-configs.ts b/web/src/features/public-api/types/score-configs.ts
index 6c0bfa6aa5..6dbd8076fb 100644
--- a/web/src/features/public-api/types/score-configs.ts
+++ b/web/src/features/public-api/types/score-configs.ts
@@ -117,6 +117,9 @@ export const PutScoreConfigQuery = z.object({
configId: z.string(),
});
+const nonEmptyScoreConfigUpdateMessage =
+ "Request body cannot be empty. At least one field must be provided for update.";
+
export const PutScoreConfigBody = z
.object({
isArchived: z.boolean().optional(),
@@ -127,8 +130,19 @@ export const PutScoreConfigBody = z
description: z.string().optional(),
})
.refine((data) => Object.keys(data).length > 0, {
- message:
- "Request body cannot be empty. At least one field must be provided for update.",
+ message: nonEmptyScoreConfigUpdateMessage,
+ });
+
+export const PutScoreConfigBodyWithoutArchived = z
+ .object({
+ name: ScoreConfigNameSchema.optional(),
+ minValue: z.number().optional(),
+ maxValue: z.number().optional(),
+ categories: CategoriesWithCustomError.optional(),
+ description: z.string().optional(),
+ })
+ .refine((data) => Object.keys(data).length > 0, {
+ message: nonEmptyScoreConfigUpdateMessage,
});
export const PutScoreConfigResponse = APIScoreConfig;
diff --git a/web/src/pages/api/public/score-configs/[configId].ts b/web/src/pages/api/public/score-configs/[configId].ts
index a0d02e9c9b..e037b43dc1 100644
--- a/web/src/pages/api/public/score-configs/[configId].ts
+++ b/web/src/pages/api/public/score-configs/[configId].ts
@@ -1,4 +1,8 @@
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import {
+ getScoreConfig,
+ updateScoreConfig,
+} from "@/src/features/public-api/server/score-configs-api-service";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import {
GetScoreConfigQuery,
@@ -7,14 +11,6 @@ import {
PutScoreConfigQuery as PatchScoreConfigQuery,
PutScoreConfigResponse as PatchScoreConfigResponse,
} from "@/src/features/public-api/types/score-configs";
-import {
- InternalServerError,
- InvalidRequestError,
- LangfuseNotFoundError,
- validateDbScoreConfigSafe,
-} from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-import { traceException } from "@langfuse/shared/src/server";
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
@@ -22,26 +18,10 @@ export default withMiddlewares({
querySchema: GetScoreConfigQuery,
responseSchema: GetScoreConfigResponse,
fn: async ({ query, auth }) => {
- const config = await prisma.scoreConfig.findUnique({
- where: {
- id: query.configId,
- projectId: auth.scope.projectId,
- },
+ return await getScoreConfig({
+ projectId: auth.scope.projectId,
+ configId: query.configId,
});
-
- if (!config) {
- throw new LangfuseNotFoundError(
- "Score config not found within authorized project",
- );
- }
-
- const parsedConfig = validateDbScoreConfigSafe(config);
- if (!parsedConfig.success) {
- traceException(parsedConfig.error);
- throw new InternalServerError("Requested score config is corrupted");
- }
-
- return parsedConfig.data;
},
}),
PATCH: createAuthedProjectAPIRoute({
@@ -50,39 +30,11 @@ export default withMiddlewares({
bodySchema: PatchScoreConfigBody,
responseSchema: PatchScoreConfigResponse,
fn: async ({ query, body, auth }) => {
- const existingConfig = await prisma.scoreConfig.findUnique({
- where: {
- id: query.configId,
- projectId: auth.scope.projectId,
- },
+ return await updateScoreConfig({
+ context: auth.scope,
+ configId: query.configId,
+ body,
});
-
- if (!existingConfig) {
- throw new LangfuseNotFoundError(
- "Score config not found within authorized project",
- );
- }
-
- // Merge the body with the existing config and verify schema compliance
- const result = validateDbScoreConfigSafe({ ...existingConfig, ...body });
-
- if (!result.success) {
- throw new InvalidRequestError(
- result.error.issues.map((issue) => issue.message).join(", "),
- );
- }
-
- await prisma.scoreConfig.update({
- where: {
- id: query.configId,
- projectId: auth.scope.projectId,
- },
- data: {
- ...body,
- },
- });
-
- return result.data;
},
}),
});
diff --git a/web/src/pages/api/public/score-configs/index.ts b/web/src/pages/api/public/score-configs/index.ts
index d8faa74772..1b4c6614a9 100644
--- a/web/src/pages/api/public/score-configs/index.ts
+++ b/web/src/pages/api/public/score-configs/index.ts
@@ -1,15 +1,9 @@
-import { v4 } from "uuid";
-import { type z } from "zod";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
-import { isBooleanDataType } from "@/src/features/scores/lib/helpers";
import {
- filterAndValidateDbScoreConfigList,
- validateDbScoreConfig,
-} from "@langfuse/shared";
-import { Prisma, prisma } from "@langfuse/shared/src/db";
-import { traceException } from "@langfuse/shared/src/server";
-import { auditLog } from "@/src/features/audit-logs/auditLog";
+ createScoreConfig,
+ listScoreConfigs,
+} from "@/src/features/public-api/server/score-configs-api-service";
import {
GetScoreConfigsQuery,
GetScoreConfigsResponse,
@@ -17,47 +11,16 @@ import {
PostScoreConfigResponse,
} from "@/src/features/public-api/types/score-configs";
-const inflateConfigBody = (body: z.infer<typeof PostScoreConfigBody>) => {
- if (isBooleanDataType(body.dataType)) {
- return {
- ...body,
- categories: [
- { label: "True", value: 1 },
- { label: "False", value: 0 },
- ],
- };
- }
- return body;
-};
-
export default withMiddlewares({
POST: createAuthedProjectAPIRoute({
name: "Create Score Config",
bodySchema: PostScoreConfigBody,
responseSchema: PostScoreConfigResponse,
fn: async ({ body, auth }) => {
- const inflatedConfigInput = inflateConfigBody(body);
-
- const config = await prisma.scoreConfig.create({
- data: {
- ...inflatedConfigInput,
- categories: inflatedConfigInput.categories ?? undefined,
- id: v4(),
- projectId: auth.scope.projectId,
- },
- });
-
- await auditLog({
- action: "create",
- resourceType: "scoreConfig",
- resourceId: config.id,
- projectId: auth.scope.projectId,
- orgId: auth.scope.orgId,
- apiKeyId: auth.scope.apiKeyId,
- after: config,
+ return await createScoreConfig({
+ context: auth.scope,
+ body,
});
-
- return validateDbScoreConfig(config);
},
}),
GET: createAuthedProjectAPIRoute({
@@ -66,44 +29,11 @@ export default withMiddlewares({
responseSchema: GetScoreConfigsResponse,
fn: async ({ query, auth }) => {
const { page, limit } = query;
- const rawConfigs = await prisma.scoreConfig.findMany({
- where: {
- projectId: auth.scope.projectId,
- },
- orderBy: {
- createdAt: "desc",
- },
- take: limit,
- skip: (page - 1) * limit,
+ return await listScoreConfigs({
+ projectId: auth.scope.projectId,
+ page,
+ limit,
});
-
- const configs = filterAndValidateDbScoreConfigList(
- rawConfigs,
- traceException,
- );
-
- const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(
- Prisma.sql`
- SELECT
- COUNT(*) as count
- FROM
- "score_configs" AS sc
- WHERE sc.project_id = ${auth.scope.projectId}
- `,
- );
-
- const totalItems =
- totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
-
- return {
- data: configs,
- meta: {
- page: page,
- limit: limit,
- totalItems,
- totalPages: Math.ceil(totalItems / limit),
- },
- };
},
}),
});
diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].ts
index 23be8d6123..aa469b34fb 100644
--- a/web/src/pages/api/public/scores/[scoreId].ts
+++ b/web/src/pages/api/public/scores/[scoreId].ts
@@ -8,14 +8,7 @@ import {
InternalServerError,
LangfuseNotFoundError,
} from "@langfuse/shared";
-import {
- logger,
- traceException,
- ScoreDeleteQueue,
-} from "@langfuse/shared/src/server";
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { QueueJobs } from "@langfuse/shared/src/server";
-import { randomUUID } from "crypto";
+import { logger, traceException } from "@langfuse/shared/src/server";
import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
export default withMiddlewares({
@@ -54,31 +47,13 @@ export default withMiddlewares({
fn: async ({ query, auth }) => {
const { scoreId } = query;
- const scoreDeleteQueue = ScoreDeleteQueue.getInstance();
- if (!scoreDeleteQueue) {
- throw new InternalServerError("ScoreDeleteQueue not initialized");
- }
-
- await auditLog({
- action: "delete",
- resourceType: "score",
- resourceId: scoreId,
+ const scoresApiService = new ScoresApiService("v1");
+ return await scoresApiService.deleteScore({
+ scoreId,
projectId: auth.scope.projectId,
orgId: auth.scope.orgId,
apiKeyId: auth.scope.apiKeyId,
});
-
- await scoreDeleteQueue.add(QueueJobs.ScoreDelete, {
- timestamp: new Date(),
- id: randomUUID(),
- payload: {
- projectId: auth.scope.projectId,
- scoreIds: [scoreId],
- },
- name: QueueJobs.ScoreDelete,
- });
-
- return { message: "Score deletion queued successfully" };
},
}),
});
diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.ts
index f8d9e2114a..04fe7a3300 100644
--- a/web/src/pages/api/public/scores/index.ts
+++ b/web/src/pages/api/public/scores/index.ts
@@ -1,5 +1,3 @@
-import { v4 } from "uuid";
-
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import {
@@ -9,13 +7,10 @@ import {
PostScoresBodyV1,
PostScoresResponseV1,
} from "@langfuse/shared";
-import {
- eventTypes,
- logger,
- processEventBatch,
-} from "@langfuse/shared/src/server";
+import { logger } from "@langfuse/shared/src/server";
import { ForbiddenError } from "@langfuse/shared";
import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
+import { randomUUID } from "crypto";
export default withMiddlewares({
POST: createAuthedProjectAPIRoute({
@@ -30,16 +25,19 @@ export default withMiddlewares({
);
}
- const event = {
- id: v4(),
- type: eventTypes.SCORE_CREATE,
- timestamp: new Date().toISOString(),
- body,
+ const conformedBody = {
+ ...body,
+ // We previously used `if(!body.id)` to decide if a new ID should be generated,
+ // this would accept falsy values such as empty string as valid IDs, and generate a new ID in that case.
+ // The `createScore` uses `??` instead, which would break this behavior, so we use `||` here to maintain the old behavior.
+ id: body.id || randomUUID(),
};
- if (!event.body.id) {
- event.body.id = v4();
- }
- const result = await processEventBatch([event], auth);
+
+ const scoresApiService = new ScoresApiService("v1");
+ const { id, result } = await scoresApiService.createScore({
+ body: conformedBody,
+ auth,
+ });
if (result.errors.length > 0) {
const error = result.errors[0];
res
@@ -51,7 +49,7 @@ export default withMiddlewares({
logger.error("Failed to create score", { result });
throw new Error("Failed to create score");
}
- return { id: event.body.id };
+ return { id };
},
}),
GET: createAuthedProjectAPIRoute({