Skip to content

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

refactor(mcp): Clean up MCP server (#13850)

Ben Bachem1ba4cd892562
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 9767b342a1..2668693878 100644
--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
@@ -135,10 +135,11 @@ const createProjectUser = async ({
};
describe("MCP public API tools", () => {
- it("registers new public API tools and gates mutating tools for in-app agent keys", async () => {
- const toolNames = (
- await toolRegistry.getToolDefinitions(mockServerContext())
- ).map((tool) => tool.name);
+ const getToolNames = async (context = mockServerContext()) =>
+ (await toolRegistry.getToolDefinitions(context)).map((tool) => tool.name);
+
+ it("registers public API tools", async () => {
+ const toolNames = await getToolNames();
expect(toolNames).toEqual(
expect.arrayContaining([
@@ -153,21 +154,85 @@ describe("MCP public API tools", () => {
"createScoreConfig",
]),
);
+ });
- const inAppToolNames = (
- await toolRegistry.getToolDefinitions(
- mockServerContext({ isInAppAgentKey: true }),
- )
- ).map((tool) => tool.name);
+ it("exposes read-only tools for in-app agent keys", async () => {
+ const toolNames = await getToolNames();
+ const inAppToolNames = await getToolNames(
+ mockServerContext({ isInAppAgentKey: true }),
+ );
+
+ expect(inAppToolNames).toEqual(
+ expect.arrayContaining([
+ "listDatasets",
+ "getHealth",
+ "listScores",
+ "getScore",
+ "listScoreConfigs",
+ "listPrompts",
+ "getPrompt",
+ "getPromptUnresolved",
+ ]),
+ );
+
+ const readOnlyToolNames = toolNames.filter(
+ (toolName) =>
+ toolRegistry.getTool(toolName)?.definition.annotations?.readOnlyHint,
+ );
+ expect(inAppToolNames).toEqual(expect.arrayContaining(readOnlyToolNames));
+ });
+
+ it("hides mutating tools for in-app agent keys", async () => {
+ const toolNames = await getToolNames();
+ const inAppToolNames = await getToolNames(
+ mockServerContext({ isInAppAgentKey: true }),
+ );
- expect(inAppToolNames).toContain("listDatasets");
- expect(inAppToolNames).toContain("getHealth");
- expect(inAppToolNames).not.toContain("listScores");
- expect(inAppToolNames).not.toContain("getScore");
- expect(inAppToolNames).not.toContain("listScoreConfigs");
expect(inAppToolNames).not.toContain("createDataset");
expect(inAppToolNames).not.toContain("createModel");
+ const writableToolNames = toolNames.filter(
+ (toolName) =>
+ !toolRegistry.getTool(toolName)?.definition.annotations?.readOnlyHint,
+ );
+ for (const toolName of writableToolNames) {
+ expect(inAppToolNames).not.toContain(toolName);
+ }
+ });
+
+ it("marks destructive public API tools", async () => {
+ const toolNames = await getToolNames();
+
+ const destructiveToolNames = toolNames
+ .filter(
+ (toolName) =>
+ toolRegistry.getTool(toolName)?.definition.annotations
+ ?.destructiveHint,
+ )
+ .sort();
+ expect(destructiveToolNames).toEqual(
+ [
+ "createChatPrompt",
+ "createDataset",
+ "createDatasetItem",
+ "createScore",
+ "createScoreConfig",
+ "createTextPrompt",
+ "deleteAnnotationQueueAssignment",
+ "deleteAnnotationQueueItem",
+ "deleteDatasetItem",
+ "deleteDatasetRun",
+ "deleteModel",
+ "deleteScore",
+ "deleteScoreConfig",
+ "updateAnnotationQueueItem",
+ "updatePromptLabels",
+ "updateScoreConfig",
+ ].sort(),
+ );
+ });
+
+ it("uses a larger MCP request body limit", () => {
expect(mcpRouteConfig.api.bodyParser.sizeLimit).toBe("4.5mb");
});
diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.ts
index d0bf13fd50..13be9df827 100644
--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts
@@ -1979,12 +1979,12 @@ describe("MCP Read Tools", () => {
verifyToolAnnotations(getPromptTool, { readOnlyHint: true });
});
- it("should not be available to in-app agent keys", async () => {
+ it("should be available to in-app agent keys", async () => {
const context = mockServerContext({ isInAppAgentKey: true });
await expect(
toolRegistry.getEnabledTool(getPromptTool.name, context),
- ).resolves.toBeUndefined();
+ ).resolves.toBeDefined();
});
it("should fetch prompt by name only (defaults to production label)", async () => {
@@ -2226,12 +2226,12 @@ describe("MCP Read Tools", () => {
verifyToolAnnotations(listPromptsTool, { readOnlyHint: true });
});
- it("should not be available to in-app agent keys", async () => {
+ it("should be available to in-app agent keys", async () => {
const context = mockServerContext({ isInAppAgentKey: true });
await expect(
toolRegistry.getEnabledTool(listPromptsTool.name, context),
- ).resolves.toBeUndefined();
+ ).resolves.toBeDefined();
});
it("should list all prompts for project", async () => {
@@ -2258,14 +2258,15 @@ describe("MCP Read Tools", () => {
context,
)) as {
data: Array<{ name: string }>;
- pagination: { totalItems: number };
+ meta: { totalItems: number };
};
// Should include our prompts (may include others from setup)
const names = result.data.map((p) => p.name);
expect(names).toContain(prompt1Name);
expect(names).toContain(prompt2Name);
- expect(result.pagination.totalItems).toBeGreaterThanOrEqual(2);
+ expect(result.meta.totalItems).toBeGreaterThanOrEqual(2);
+ expect(Object.keys(result).sort()).toEqual(["data", "meta"]);
});
it("should filter by name", async () => {
@@ -2501,13 +2502,13 @@ describe("MCP Read Tools", () => {
context,
)) as {
data: Array<{ name: string }>;
- pagination: { page: number; limit: number; totalPages: number };
+ meta: { page: number; limit: number; totalPages: number };
};
expect(result.data.length).toBeLessThanOrEqual(2);
- expect(result.pagination.page).toBe(1);
- expect(result.pagination.limit).toBe(2);
- expect(result.pagination.totalPages).toBeGreaterThanOrEqual(1);
+ expect(result.meta.page).toBe(1);
+ expect(result.meta.limit).toBe(2);
+ expect(result.meta.totalPages).toBeGreaterThanOrEqual(1);
});
it("should return empty results for no matches", async () => {
@@ -2518,11 +2519,11 @@ describe("MCP Read Tools", () => {
context,
)) as {
data: Array<unknown>;
- pagination: { totalItems: number };
+ meta: { totalItems: number };
};
expect(result.data).toEqual([]);
- expect(result.pagination.totalItems).toBe(0);
+ expect(result.meta.totalItems).toBe(0);
});
it("should use context.projectId for tenant isolation", async () => {
@@ -2561,12 +2562,12 @@ describe("MCP Read Tools", () => {
{ page: 1, limit: 100 },
context,
)) as {
- pagination: { page: number; limit: number };
+ meta: { page: number; limit: number };
};
// Default values from validation schema
- expect(result.pagination.page).toBe(1);
- expect(result.pagination.limit).toBeLessThanOrEqual(100); // Max limit
+ expect(result.meta.page).toBe(1);
+ expect(result.meta.limit).toBeLessThanOrEqual(100); // Max limit
});
it("should include prompt metadata in list results", async () => {
@@ -2605,12 +2606,12 @@ describe("MCP Read Tools", () => {
verifyToolAnnotations(getPromptUnresolvedTool, { readOnlyHint: true });
});
- it("should not be available to in-app agent keys", async () => {
+ it("should be available to in-app agent keys", async () => {
const context = mockServerContext({ isInAppAgentKey: true });
await expect(
toolRegistry.getEnabledTool(getPromptUnresolvedTool.name, context),
- ).resolves.toBeUndefined();
+ ).resolves.toBeDefined();
});
it("should fetch prompt without resolving dependencies (by name only)", async () => {
diff --git a/web/src/features/mcp/core/run-mcp-tool.ts b/web/src/features/mcp/core/run-mcp-tool.ts
new file mode 100644
index 0000000000..b53b44a7c2
--- /dev/null
+++ b/web/src/features/mcp/core/run-mcp-tool.ts
@@ -0,0 +1,36 @@
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { SpanKind, type Span } from "@opentelemetry/api";
+
+import type { ServerContext } from "../types";
+
+type McpToolAttribute = string | number | boolean;
+
+export const runMcpTool = async <TResult>({
+ spanName,
+ context,
+ attributes,
+ fn,
+}: {
+ spanName: string;
+ context: ServerContext;
+ attributes?: Record<string, McpToolAttribute | undefined>;
+ fn: (span: Span) => Promise<TResult>;
+}): Promise<TResult> =>
+ instrumentAsync(
+ { name: spanName, spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ span.setAttributes({
+ "langfuse.project.id": context.projectId,
+ "langfuse.org.id": context.orgId,
+ "mcp.api_key_id": context.apiKeyId,
+ ...Object.fromEntries(
+ Object.entries(attributes ?? {}).filter(
+ (entry): entry is [string, McpToolAttribute] =>
+ entry[1] !== undefined,
+ ),
+ ),
+ });
+
+ return await fn(span);
+ },
+ );
diff --git a/web/src/features/mcp/features/annotationQueues/index.ts b/web/src/features/mcp/features/annotationQueues/index.ts
index de323295ef..db07c2d257 100644
--- a/web/src/features/mcp/features/annotationQueues/index.ts
+++ b/web/src/features/mcp/features/annotationQueues/index.ts
@@ -1,26 +1,44 @@
import type { McpFeatureModule } from "../../server/registry";
import {
createAnnotationQueueAssignmentTool,
+ handleCreateAnnotationQueueAssignment,
+} from "./tools/createAnnotationQueueAssignment";
+import {
createAnnotationQueueItemTool,
+ handleCreateAnnotationQueueItem,
+} from "./tools/createAnnotationQueueItem";
+import {
createAnnotationQueueTool,
+ handleCreateAnnotationQueue,
+} from "./tools/createAnnotationQueue";
+import {
deleteAnnotationQueueAssignmentTool,
+ handleDeleteAnnotationQueueAssignment,
+} from "./tools/deleteAnnotationQueueAssignment";
+import {
deleteAnnotationQueueItemTool,
+ handleDeleteAnnotationQueueItem,
+} from "./tools/deleteAnnotationQueueItem";
+import {
getAnnotationQueueItemTool,
+ handleGetAnnotationQueueItem,
+} from "./tools/getAnnotationQueueItem";
+import {
getAnnotationQueueTool,
- handleCreateAnnotationQueue,
- handleCreateAnnotationQueueAssignment,
- handleCreateAnnotationQueueItem,
- handleDeleteAnnotationQueueAssignment,
- handleDeleteAnnotationQueueItem,
handleGetAnnotationQueue,
- handleGetAnnotationQueueItem,
+} from "./tools/getAnnotationQueue";
+import {
handleListAnnotationQueueItems,
- handleListAnnotationQueues,
- handleUpdateAnnotationQueueItem,
listAnnotationQueueItemsTool,
+} from "./tools/listAnnotationQueueItems";
+import {
+ handleListAnnotationQueues,
listAnnotationQueuesTool,
+} from "./tools/listAnnotationQueues";
+import {
+ handleUpdateAnnotationQueueItem,
updateAnnotationQueueItemTool,
-} from "./tools";
+} from "./tools/updateAnnotationQueueItem";
export const annotationQueuesFeature: McpFeatureModule = {
name: "annotationQueues",
diff --git a/web/src/features/mcp/features/annotationQueues/schema.ts b/web/src/features/mcp/features/annotationQueues/schema.ts
new file mode 100644
index 0000000000..c4d159e9fc
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/schema.ts
@@ -0,0 +1,64 @@
+import { z } from "zod";
+import {
+ AnnotationQueueAssignmentQuery,
+ CreateAnnotationQueueAssignmentBody,
+ CreateAnnotationQueueItemBody,
+ DeleteAnnotationQueueAssignmentBody,
+ GetAnnotationQueueItemByIdQuery,
+ UpdateAnnotationQueueItemBody,
+} from "@/src/features/public-api/types/annotation-queues";
+
+export const CreateAnnotationQueueItemToolSchema = z
+ .object({
+ queueId: z.string(),
+ })
+ .extend(CreateAnnotationQueueItemBody.shape);
+
+export const UpdateAnnotationQueueItemToolSchema =
+ GetAnnotationQueueItemByIdQuery.extend(UpdateAnnotationQueueItemBody.shape);
+
+export const CreateAnnotationQueueAssignmentToolSchema =
+ AnnotationQueueAssignmentQuery.extend(
+ CreateAnnotationQueueAssignmentBody.shape,
+ );
+
+export const DeleteAnnotationQueueAssignmentToolSchema =
+ AnnotationQueueAssignmentQuery.extend(
+ DeleteAnnotationQueueAssignmentBody.shape,
+ );
+
+export const annotationQueueToApi = (queue: {
+ id: string;
+ name: string;
+ description: string | null;
+ scoreConfigIds: string[];
+ createdAt: Date;
+ updatedAt: Date;
+}) => ({
+ id: queue.id,
+ name: queue.name,
+ description: queue.description,
+ scoreConfigIds: queue.scoreConfigIds,
+ createdAt: queue.createdAt,
+ updatedAt: queue.updatedAt,
+});
+
+export const annotationQueueItemToApi = (item: {
+ id: string;
+ queueId: string;
+ objectId: string;
+ objectType: "TRACE" | "OBSERVATION" | "SESSION";
+ status: "PENDING" | "COMPLETED";
+ completedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+}) => ({
+ id: item.id,
+ queueId: item.queueId,
+ objectId: item.objectId,
+ objectType: item.objectType,
+ status: item.status,
+ completedAt: item.completedAt,
+ createdAt: item.createdAt,
+ updatedAt: item.updatedAt,
+});
diff --git a/web/src/features/mcp/features/annotationQueues/tools.ts b/web/src/features/mcp/features/annotationQueues/tools.ts
deleted file mode 100644
index e379b3eb52..0000000000
--- a/web/src/features/mcp/features/annotationQueues/tools.ts
+++ /dev/null
@@ -1,682 +0,0 @@
-import { z } from "zod";
-import {
- AnnotationQueueStatus,
- InvalidRequestError,
- LangfuseNotFoundError,
- MethodNotAllowedError,
- Prisma as SharedPrisma,
-} from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-import { getUserProjectRoles } from "@langfuse/shared/src/server";
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import {
- AnnotationQueueAssignmentQuery,
- CreateAnnotationQueueAssignmentBody,
- CreateAnnotationQueueAssignmentResponse,
- CreateAnnotationQueueBody,
- CreateAnnotationQueueItemBody,
- CreateAnnotationQueueItemResponse,
- CreateAnnotationQueueResponse,
- DeleteAnnotationQueueAssignmentBody,
- DeleteAnnotationQueueAssignmentResponse,
- DeleteAnnotationQueueItemQuery,
- DeleteAnnotationQueueItemResponse,
- GetAnnotationQueueByIdQuery,
- GetAnnotationQueueByIdResponse,
- GetAnnotationQueueItemByIdQuery,
- GetAnnotationQueueItemByIdResponse,
- GetAnnotationQueueItemsQuery,
- GetAnnotationQueueItemsResponse,
- GetAnnotationQueuesQuery,
- GetAnnotationQueuesResponse,
- UpdateAnnotationQueueItemBody,
- UpdateAnnotationQueueItemResponse,
-} from "@/src/features/public-api/types/annotation-queues";
-import { defineTool } from "../../core/define-tool";
-import {
- getMcpPublicApiAuth,
- paginationMeta,
- runPublicApiTool,
-} from "../publicApi";
-
-const annotationQueueToApi = (queue: {
- id: string;
- name: string;
- description: string | null;
- scoreConfigIds: string[];
- createdAt: Date;
- updatedAt: Date;
-}) => ({
- id: queue.id,
- name: queue.name,
- description: queue.description,
- scoreConfigIds: queue.scoreConfigIds,
- createdAt: queue.createdAt,
- updatedAt: queue.updatedAt,
-});
-
-const annotationQueueItemToApi = (item: {
- id: string;
- queueId: string;
- objectId: string;
- objectType: "TRACE" | "OBSERVATION" | "SESSION";
- status: "PENDING" | "COMPLETED";
- completedAt: Date | null;
- createdAt: Date;
- updatedAt: Date;
-}) => ({
- id: item.id,
- queueId: item.queueId,
- objectId: item.objectId,
- objectType: item.objectType,
- status: item.status,
- completedAt: item.completedAt,
- createdAt: item.createdAt,
- updatedAt: item.updatedAt,
-});
-
-const verifyAnnotationQueue = async ({
- projectId,
- queueId,
-}: {
- projectId: string;
- queueId: string;
-}) => {
- const queue = await prisma.annotationQueue.findUnique({
- where: {
- id: queueId,
- projectId,
- },
- });
-
- if (!queue) {
- throw new LangfuseNotFoundError("Annotation queue not found");
- }
-
- return queue;
-};
-
-export const [listAnnotationQueuesTool, handleListAnnotationQueues] =
- defineTool({
- name: "listAnnotationQueues",
- description:
- "List annotation queues, worklists that collect trace or observation items for human review and scoring, with pagination.",
- baseSchema: GetAnnotationQueuesQuery,
- inputSchema: GetAnnotationQueuesQuery,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queues.list",
- context,
- attributes: {
- "mcp.pagination_page": input.page,
- "mcp.pagination_limit": input.limit,
- },
- fn: async () => {
- const [queues, totalItems] = await Promise.all([
- prisma.annotationQueue.findMany({
- where: { projectId: context.projectId },
- orderBy: [{ createdAt: "desc" }, { id: "desc" }],
- take: input.limit,
- skip: (input.page - 1) * input.limit,
- }),
- prisma.annotationQueue.count({
- where: { projectId: context.projectId },
- }),
- ]);
-
- return GetAnnotationQueuesResponse.parse({
- data: queues.map(annotationQueueToApi),
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
- });
-
-export const [createAnnotationQueueTool, handleCreateAnnotationQueue] =
- defineTool({
- name: "createAnnotationQueue",
- description:
- "Create an annotation queue, a worklist that collects trace or observation items for human review and scoring.",
- baseSchema: CreateAnnotationQueueBody,
- inputSchema: CreateAnnotationQueueBody,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queues.create",
- context,
- attributes: { "mcp.annotation_queue_name": input.name },
- fn: async () => {
- const auth = await getMcpPublicApiAuth(context);
-
- if (auth.scope.plan === "cloud:hobby") {
- const queueCount = await prisma.annotationQueue.count({
- where: { projectId: context.projectId },
- });
-
- if (queueCount >= 1) {
- throw new MethodNotAllowedError(
- "Maximum number of annotation queues reached on Hobby plan.",
- );
- }
- }
-
- const existingQueue = await prisma.annotationQueue.findFirst({
- where: {
- projectId: context.projectId,
- name: input.name,
- },
- });
-
- if (existingQueue) {
- throw new InvalidRequestError(
- "A queue with this name already exists.",
- );
- }
-
- const scoreConfigs = await prisma.scoreConfig.findMany({
- where: {
- id: { in: input.scoreConfigIds },
- projectId: context.projectId,
- },
- select: { id: true },
- });
- const scoreConfigIdSet = new Set(
- scoreConfigs.map((config) => config.id),
- );
-
- if (input.scoreConfigIds.some((id) => !scoreConfigIdSet.has(id))) {
- throw new InvalidRequestError(
- "At least one of the score config IDs cannot be found for the given project.",
- );
- }
-
- const queue = await prisma.annotationQueue.create({
- data: {
- projectId: context.projectId,
- name: input.name,
- description: input.description,
- scoreConfigIds: input.scoreConfigIds,
- },
- });
-
- await auditLog({
- action: "create",
- resourceType: "annotationQueue",
- resourceId: queue.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- after: queue,
- });
-
- return CreateAnnotationQueueResponse.parse(
- annotationQueueToApi(queue),
- );
- },
- }),
- });
-
-export const [getAnnotationQueueTool, handleGetAnnotationQueue] = defineTool({
- name: "getAnnotationQueue",
- description:
- "Get an annotation queue, a worklist of trace or observation items for human review and scoring, by ID.",
- baseSchema: GetAnnotationQueueByIdQuery,
- inputSchema: GetAnnotationQueueByIdQuery,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queues.get",
- context,
- attributes: { "mcp.annotation_queue_id": input.queueId },
- fn: async () => {
- const queue = await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- return GetAnnotationQueueByIdResponse.parse(
- annotationQueueToApi(queue),
- );
- },
- }),
- readOnlyHint: true,
-});
-
-export const [listAnnotationQueueItemsTool, handleListAnnotationQueueItems] =
- defineTool({
- name: "listAnnotationQueueItems",
- description:
- "List annotation queue items, each linking one trace or observation to a queue with a review status, with optional status filtering.",
- baseSchema: GetAnnotationQueueItemsQuery,
- inputSchema: GetAnnotationQueueItemsQuery,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_items.list",
- context,
- attributes: {
- "mcp.annotation_queue_id": input.queueId,
- "mcp.pagination_page": input.page,
- "mcp.pagination_limit": input.limit,
- },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- const where = {
- projectId: context.projectId,
- queueId: input.queueId,
- ...(input.status ? { status: input.status } : {}),
- };
-
- const [items, totalItems] = await Promise.all([
- prisma.annotationQueueItem.findMany({
- where,
- orderBy: [{ createdAt: "desc" }, { id: "desc" }],
- take: input.limit,
- skip: (input.page - 1) * input.limit,
- }),
- prisma.annotationQueueItem.count({ where }),
- ]);
-
- return GetAnnotationQueueItemsResponse.parse({
- data: items.map(annotationQueueItemToApi),
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
- });
-
-export const [getAnnotationQueueItemTool, handleGetAnnotationQueueItem] =
- defineTool({
- name: "getAnnotationQueueItem",
- description:
- "Get an annotation queue item, one queued trace or observation with review status, by queue ID and item ID.",
- baseSchema: GetAnnotationQueueItemByIdQuery,
- inputSchema: GetAnnotationQueueItemByIdQuery,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_items.get",
- context,
- attributes: {
- "mcp.annotation_queue_id": input.queueId,
- "mcp.annotation_queue_item_id": input.itemId,
- },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- const item = await prisma.annotationQueueItem.findUnique({
- where: {
- id: input.itemId,
- queueId: input.queueId,
- projectId: context.projectId,
- },
- });
-
- if (!item) {
- throw new LangfuseNotFoundError("Annotation queue item not found");
- }
-
- return GetAnnotationQueueItemByIdResponse.parse(
- annotationQueueItemToApi(item),
- );
- },
- }),
- readOnlyHint: true,
- });
-
-const CreateAnnotationQueueItemToolSchema = z
- .object({
- queueId: z.string(),
- })
- .extend(CreateAnnotationQueueItemBody.shape);
-
-export const [createAnnotationQueueItemTool, handleCreateAnnotationQueueItem] =
- defineTool({
- name: "createAnnotationQueueItem",
- description:
- "Add an annotation queue item, one trace or observation to review, to a queue.",
- baseSchema: CreateAnnotationQueueItemToolSchema,
- inputSchema: CreateAnnotationQueueItemToolSchema,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_items.create",
- context,
- attributes: { "mcp.annotation_queue_id": input.queueId },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- const status = input.status || AnnotationQueueStatus.PENDING;
- const completedAt =
- status === AnnotationQueueStatus.COMPLETED ? new Date() : null;
-
- const item = await prisma.annotationQueueItem.create({
- data: {
- queueId: input.queueId,
- objectId: input.objectId,
- objectType: input.objectType,
- status,
- completedAt,
- projectId: context.projectId,
- },
- });
-
- await auditLog({
- action: "create",
- resourceType: "annotationQueueItem",
- resourceId: item.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- after: item,
- });
-
- return CreateAnnotationQueueItemResponse.parse(
- annotationQueueItemToApi(item),
- );
- },
- }),
- });
-
-const UpdateAnnotationQueueItemToolSchema =
- GetAnnotationQueueItemByIdQuery.extend(UpdateAnnotationQueueItemBody.shape);
-
-export const [updateAnnotationQueueItemTool, handleUpdateAnnotationQueueItem] =
- defineTool({
- name: "updateAnnotationQueueItem",
- description:
- "Update an annotation queue item's review status, such as pending or completed.",
- baseSchema: UpdateAnnotationQueueItemToolSchema,
- inputSchema: UpdateAnnotationQueueItemToolSchema,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_items.update",
- context,
- attributes: {
- "mcp.annotation_queue_id": input.queueId,
- "mcp.annotation_queue_item_id": input.itemId,
- },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- const existingItem = await prisma.annotationQueueItem.findUnique({
- where: {
- id: input.itemId,
- queueId: input.queueId,
- projectId: context.projectId,
- },
- });
-
- if (!existingItem) {
- throw new LangfuseNotFoundError("Annotation queue item not found");
- }
-
- const item = await prisma.annotationQueueItem.update({
- where: {
- id: input.itemId,
- queueId: input.queueId,
- projectId: context.projectId,
- },
- data: {
- status: input.status,
- completedAt:
- input.status === AnnotationQueueStatus.COMPLETED
- ? new Date()
- : undefined,
- },
- });
-
- await auditLog({
- action: "update",
- resourceType: "annotationQueueItem",
- resourceId: item.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- before: existingItem,
- after: item,
- });
-
- return UpdateAnnotationQueueItemResponse.parse(
- annotationQueueItemToApi(item),
- );
- },
- }),
- });
-
-export const [deleteAnnotationQueueItemTool, handleDeleteAnnotationQueueItem] =
- defineTool({
- name: "deleteAnnotationQueueItem",
- description:
- "Remove an annotation queue item, the queued trace or observation, from a queue.",
- baseSchema: DeleteAnnotationQueueItemQuery,
- inputSchema: DeleteAnnotationQueueItemQuery,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_items.delete",
- context,
- attributes: {
- "mcp.annotation_queue_id": input.queueId,
- "mcp.annotation_queue_item_id": input.itemId,
- },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- const existingItem = await prisma.annotationQueueItem.findUnique({
- where: {
- id: input.itemId,
- queueId: input.queueId,
- projectId: context.projectId,
- },
- });
-
- if (!existingItem) {
- throw new LangfuseNotFoundError("Annotation queue item not found");
- }
-
- await prisma.annotationQueueItem.delete({
- where: {
- id: input.itemId,
- queueId: input.queueId,
- projectId: context.projectId,
- },
- });
-
- await auditLog({
- action: "delete",
- resourceType: "annotationQueueItem",
- resourceId: existingItem.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- before: existingItem,
- });
-
- return DeleteAnnotationQueueItemResponse.parse({
- success: true,
- message: "Annotation queue item deleted successfully",
- });
- },
- }),
- destructiveHint: true,
- });
-
-const CreateAnnotationQueueAssignmentToolSchema =
- AnnotationQueueAssignmentQuery.extend(
- CreateAnnotationQueueAssignmentBody.shape,
- );
-
-export const [
- createAnnotationQueueAssignmentTool,
- handleCreateAnnotationQueueAssignment,
-] = defineTool({
- name: "createAnnotationQueueAssignment",
- description:
- "Assign a project user to an annotation queue so they can work through its review items.",
- baseSchema: CreateAnnotationQueueAssignmentToolSchema,
- inputSchema: CreateAnnotationQueueAssignmentToolSchema,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_assignments.create",
- context,
- attributes: { "mcp.annotation_queue_id": input.queueId },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- const user = await getUserProjectRoles({
- projectId: context.projectId,
- orgId: context.orgId,
- filterCondition: [
- {
- column: "userId",
- operator: "any of",
- value: [input.userId],
- type: "stringOptions",
- },
- ],
- searchFilter: SharedPrisma.empty,
- limit: 1,
- page: 0,
- orderBy: SharedPrisma.empty,
- });
-
- if (!user || user.length === 0) {
- throw new LangfuseNotFoundError(
- "User not found or not authorized for this project",
- );
- }
-
- const assignmentWhere = {
- projectId: context.projectId,
- queueId: input.queueId,
- userId: input.userId,
- };
-
- const createResult = await prisma.annotationQueueAssignment.createMany({
- data: [assignmentWhere],
- skipDuplicates: true,
- });
-
- if (createResult.count === 0) {
- return CreateAnnotationQueueAssignmentResponse.parse({
- userId: input.userId,
- projectId: context.projectId,
- queueId: input.queueId,
- });
- }
-
- const assignment =
- await prisma.annotationQueueAssignment.findUniqueOrThrow({
- where: {
- projectId_queueId_userId: assignmentWhere,
- },
- });
-
- await auditLog({
- action: "create",
- resourceType: "annotationQueueAssignment",
- resourceId: assignment.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- after: assignment,
- });
-
- return CreateAnnotationQueueAssignmentResponse.parse({
- userId: input.userId,
- projectId: context.projectId,
- queueId: input.queueId,
- });
- },
- }),
-});
-
-const DeleteAnnotationQueueAssignmentToolSchema =
- AnnotationQueueAssignmentQuery.extend(
- DeleteAnnotationQueueAssignmentBody.shape,
- );
-
-export const [
- deleteAnnotationQueueAssignmentTool,
- handleDeleteAnnotationQueueAssignment,
-] = defineTool({
- name: "deleteAnnotationQueueAssignment",
- description: "Remove a project user's assignment from an annotation queue.",
- baseSchema: DeleteAnnotationQueueAssignmentToolSchema,
- inputSchema: DeleteAnnotationQueueAssignmentToolSchema,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.annotation_queue_assignments.delete",
- context,
- attributes: { "mcp.annotation_queue_id": input.queueId },
- fn: async () => {
- await verifyAnnotationQueue({
- projectId: context.projectId,
- queueId: input.queueId,
- });
-
- let assignment;
- try {
- assignment = await prisma.annotationQueueAssignment.delete({
- where: {
- projectId_queueId_userId: {
- projectId: context.projectId,
- queueId: input.queueId,
- userId: input.userId,
- },
- },
- });
- } catch (error) {
- if (
- error instanceof SharedPrisma.PrismaClientKnownRequestError &&
- error.code === "P2025"
- ) {
- return DeleteAnnotationQueueAssignmentResponse.parse({
- success: true,
- });
- }
-
- throw error;
- }
-
- await auditLog({
- action: "delete",
- resourceType: "annotationQueueAssignment",
- resourceId: assignment.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- before: assignment,
- });
-
- return DeleteAnnotationQueueAssignmentResponse.parse({
- success: true,
- });
- },
- }),
- destructiveHint: true,
-});
diff --git a/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueue.ts b/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueue.ts
new file mode 100644
index 0000000000..f1359c15d2
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueue.ts
@@ -0,0 +1,94 @@
+import { InvalidRequestError, MethodNotAllowedError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ CreateAnnotationQueueBody,
+ CreateAnnotationQueueResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { getMcpPublicApiAuth } from "../../publicApi";
+import { annotationQueueToApi } from "../schema";
+
+export const [createAnnotationQueueTool, handleCreateAnnotationQueue] =
+ defineTool({
+ name: "createAnnotationQueue",
+ description:
+ "Create an annotation queue, a worklist that collects trace or observation items for human review and scoring.",
+ baseSchema: CreateAnnotationQueueBody,
+ inputSchema: CreateAnnotationQueueBody,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queues.create",
+ context,
+ attributes: { "mcp.annotation_queue_name": input.name },
+ fn: async () => {
+ const auth = await getMcpPublicApiAuth(context);
+
+ if (auth.scope.plan === "cloud:hobby") {
+ const queueCount = await prisma.annotationQueue.count({
+ where: { projectId: context.projectId },
+ });
+
+ if (queueCount >= 1) {
+ throw new MethodNotAllowedError(
+ "Maximum number of annotation queues reached on Hobby plan.",
+ );
+ }
+ }
+
+ const existingQueue = await prisma.annotationQueue.findFirst({
+ where: {
+ projectId: context.projectId,
+ name: input.name,
+ },
+ });
+
+ if (existingQueue) {
+ throw new InvalidRequestError(
+ "A queue with this name already exists.",
+ );
+ }
+
+ const scoreConfigs = await prisma.scoreConfig.findMany({
+ where: {
+ id: { in: input.scoreConfigIds },
+ projectId: context.projectId,
+ },
+ select: { id: true },
+ });
+ const scoreConfigIdSet = new Set(
+ scoreConfigs.map((config) => config.id),
+ );
+
+ if (input.scoreConfigIds.some((id) => !scoreConfigIdSet.has(id))) {
+ throw new InvalidRequestError(
+ "At least one of the score config IDs cannot be found for the given project.",
+ );
+ }
+
+ const queue = await prisma.annotationQueue.create({
+ data: {
+ projectId: context.projectId,
+ name: input.name,
+ description: input.description,
+ scoreConfigIds: input.scoreConfigIds,
+ },
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "annotationQueue",
+ resourceId: queue.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: queue,
+ });
+
+ return CreateAnnotationQueueResponse.parse(
+ annotationQueueToApi(queue),
+ );
+ },
+ }),
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueueAssignment.ts b/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueueAssignment.ts
new file mode 100644
index 0000000000..090ec5b351
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueueAssignment.ts
@@ -0,0 +1,100 @@
+import {
+ LangfuseNotFoundError,
+ Prisma as SharedPrisma,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { getUserProjectRoles } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { CreateAnnotationQueueAssignmentResponse } from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { CreateAnnotationQueueAssignmentToolSchema } from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [
+ createAnnotationQueueAssignmentTool,
+ handleCreateAnnotationQueueAssignment,
+] = defineTool({
+ name: "createAnnotationQueueAssignment",
+ description:
+ "Assign a project user to an annotation queue so they can work through its review items.",
+ baseSchema: CreateAnnotationQueueAssignmentToolSchema,
+ inputSchema: CreateAnnotationQueueAssignmentToolSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_assignments.create",
+ context,
+ attributes: { "mcp.annotation_queue_id": input.queueId },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ const user = await getUserProjectRoles({
+ projectId: context.projectId,
+ orgId: context.orgId,
+ filterCondition: [
+ {
+ column: "userId",
+ operator: "any of",
+ value: [input.userId],
+ type: "stringOptions",
+ },
+ ],
+ searchFilter: SharedPrisma.empty,
+ limit: 1,
+ page: 0,
+ orderBy: SharedPrisma.empty,
+ });
+
+ if (!user || user.length === 0) {
+ throw new LangfuseNotFoundError(
+ "User not found or not authorized for this project",
+ );
+ }
+
+ const assignmentWhere = {
+ projectId: context.projectId,
+ queueId: input.queueId,
+ userId: input.userId,
+ };
+
+ const createResult = await prisma.annotationQueueAssignment.createMany({
+ data: [assignmentWhere],
+ skipDuplicates: true,
+ });
+
+ if (createResult.count === 0) {
+ return CreateAnnotationQueueAssignmentResponse.parse({
+ userId: input.userId,
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+ }
+
+ const assignment =
+ await prisma.annotationQueueAssignment.findUniqueOrThrow({
+ where: {
+ projectId_queueId_userId: assignmentWhere,
+ },
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "annotationQueueAssignment",
+ resourceId: assignment.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: assignment,
+ });
+
+ return CreateAnnotationQueueAssignmentResponse.parse({
+ userId: input.userId,
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+ },
+ }),
+});
diff --git a/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueueItem.ts b/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueueItem.ts
new file mode 100644
index 0000000000..f0584e1e84
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/createAnnotationQueueItem.ts
@@ -0,0 +1,61 @@
+import { AnnotationQueueStatus } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { CreateAnnotationQueueItemResponse } from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import {
+ annotationQueueItemToApi,
+ CreateAnnotationQueueItemToolSchema,
+} from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [createAnnotationQueueItemTool, handleCreateAnnotationQueueItem] =
+ defineTool({
+ name: "createAnnotationQueueItem",
+ description:
+ "Add an annotation queue item, one trace or observation to review, to a queue.",
+ baseSchema: CreateAnnotationQueueItemToolSchema,
+ inputSchema: CreateAnnotationQueueItemToolSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_items.create",
+ context,
+ attributes: { "mcp.annotation_queue_id": input.queueId },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ const status = input.status || AnnotationQueueStatus.PENDING;
+ const completedAt =
+ status === AnnotationQueueStatus.COMPLETED ? new Date() : null;
+
+ const item = await prisma.annotationQueueItem.create({
+ data: {
+ queueId: input.queueId,
+ objectId: input.objectId,
+ objectType: input.objectType,
+ status,
+ completedAt,
+ projectId: context.projectId,
+ },
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "annotationQueueItem",
+ resourceId: item.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: item,
+ });
+
+ return CreateAnnotationQueueItemResponse.parse(
+ annotationQueueItemToApi(item),
+ );
+ },
+ }),
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/tools/deleteAnnotationQueueAssignment.ts b/web/src/features/mcp/features/annotationQueues/tools/deleteAnnotationQueueAssignment.ts
new file mode 100644
index 0000000000..2bc79f2e28
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/deleteAnnotationQueueAssignment.ts
@@ -0,0 +1,69 @@
+import { Prisma as SharedPrisma } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { DeleteAnnotationQueueAssignmentResponse } from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { DeleteAnnotationQueueAssignmentToolSchema } from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [
+ deleteAnnotationQueueAssignmentTool,
+ handleDeleteAnnotationQueueAssignment,
+] = defineTool({
+ name: "deleteAnnotationQueueAssignment",
+ description: "Remove a project user's assignment from an annotation queue.",
+ baseSchema: DeleteAnnotationQueueAssignmentToolSchema,
+ inputSchema: DeleteAnnotationQueueAssignmentToolSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_assignments.delete",
+ context,
+ attributes: { "mcp.annotation_queue_id": input.queueId },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ let assignment;
+ try {
+ assignment = await prisma.annotationQueueAssignment.delete({
+ where: {
+ projectId_queueId_userId: {
+ projectId: context.projectId,
+ queueId: input.queueId,
+ userId: input.userId,
+ },
+ },
+ });
+ } catch (error) {
+ if (
+ error instanceof SharedPrisma.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ return DeleteAnnotationQueueAssignmentResponse.parse({
+ success: true,
+ });
+ }
+
+ throw error;
+ }
+
+ await auditLog({
+ action: "delete",
+ resourceType: "annotationQueueAssignment",
+ resourceId: assignment.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: assignment,
+ });
+
+ return DeleteAnnotationQueueAssignmentResponse.parse({
+ success: true,
+ });
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/annotationQueues/tools/deleteAnnotationQueueItem.ts b/web/src/features/mcp/features/annotationQueues/tools/deleteAnnotationQueueItem.ts
new file mode 100644
index 0000000000..1b32488ec5
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/deleteAnnotationQueueItem.ts
@@ -0,0 +1,70 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ DeleteAnnotationQueueItemQuery,
+ DeleteAnnotationQueueItemResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [deleteAnnotationQueueItemTool, handleDeleteAnnotationQueueItem] =
+ defineTool({
+ name: "deleteAnnotationQueueItem",
+ description:
+ "Remove an annotation queue item, the queued trace or observation, from a queue.",
+ baseSchema: DeleteAnnotationQueueItemQuery,
+ inputSchema: DeleteAnnotationQueueItemQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_items.delete",
+ context,
+ attributes: {
+ "mcp.annotation_queue_id": input.queueId,
+ "mcp.annotation_queue_item_id": input.itemId,
+ },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ const existingItem = await prisma.annotationQueueItem.findUnique({
+ where: {
+ id: input.itemId,
+ queueId: input.queueId,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!existingItem) {
+ throw new LangfuseNotFoundError("Annotation queue item not found");
+ }
+
+ await prisma.annotationQueueItem.delete({
+ where: {
+ id: input.itemId,
+ queueId: input.queueId,
+ projectId: context.projectId,
+ },
+ });
+
+ await auditLog({
+ action: "delete",
+ resourceType: "annotationQueueItem",
+ resourceId: existingItem.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: existingItem,
+ });
+
+ return DeleteAnnotationQueueItemResponse.parse({
+ success: true,
+ message: "Annotation queue item deleted successfully",
+ });
+ },
+ }),
+ destructiveHint: true,
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/tools/getAnnotationQueue.ts b/web/src/features/mcp/features/annotationQueues/tools/getAnnotationQueue.ts
new file mode 100644
index 0000000000..591fbc15ae
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/getAnnotationQueue.ts
@@ -0,0 +1,33 @@
+import {
+ GetAnnotationQueueByIdQuery,
+ GetAnnotationQueueByIdResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { annotationQueueToApi } from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [getAnnotationQueueTool, handleGetAnnotationQueue] = defineTool({
+ name: "getAnnotationQueue",
+ description:
+ "Get an annotation queue, a worklist of trace or observation items for human review and scoring, by ID.",
+ baseSchema: GetAnnotationQueueByIdQuery,
+ inputSchema: GetAnnotationQueueByIdQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queues.get",
+ context,
+ attributes: { "mcp.annotation_queue_id": input.queueId },
+ fn: async () => {
+ const queue = await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ return GetAnnotationQueueByIdResponse.parse(
+ annotationQueueToApi(queue),
+ );
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/annotationQueues/tools/getAnnotationQueueItem.ts b/web/src/features/mcp/features/annotationQueues/tools/getAnnotationQueueItem.ts
new file mode 100644
index 0000000000..daa5b8a410
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/getAnnotationQueueItem.ts
@@ -0,0 +1,51 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetAnnotationQueueItemByIdQuery,
+ GetAnnotationQueueItemByIdResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { annotationQueueItemToApi } from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [getAnnotationQueueItemTool, handleGetAnnotationQueueItem] =
+ defineTool({
+ name: "getAnnotationQueueItem",
+ description:
+ "Get an annotation queue item, one queued trace or observation with review status, by queue ID and item ID.",
+ baseSchema: GetAnnotationQueueItemByIdQuery,
+ inputSchema: GetAnnotationQueueItemByIdQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_items.get",
+ context,
+ attributes: {
+ "mcp.annotation_queue_id": input.queueId,
+ "mcp.annotation_queue_item_id": input.itemId,
+ },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ const item = await prisma.annotationQueueItem.findUnique({
+ where: {
+ id: input.itemId,
+ queueId: input.queueId,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!item) {
+ throw new LangfuseNotFoundError("Annotation queue item not found");
+ }
+
+ return GetAnnotationQueueItemByIdResponse.parse(
+ annotationQueueItemToApi(item),
+ );
+ },
+ }),
+ readOnlyHint: true,
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/tools/index.ts b/web/src/features/mcp/features/annotationQueues/tools/index.ts
new file mode 100644
index 0000000000..35e71625bb
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/index.ts
@@ -0,0 +1,10 @@
+export * from "./createAnnotationQueue";
+export * from "./createAnnotationQueueAssignment";
+export * from "./createAnnotationQueueItem";
+export * from "./deleteAnnotationQueueAssignment";
+export * from "./deleteAnnotationQueueItem";
+export * from "./getAnnotationQueue";
+export * from "./getAnnotationQueueItem";
+export * from "./listAnnotationQueueItems";
+export * from "./listAnnotationQueues";
+export * from "./updateAnnotationQueueItem";
diff --git a/web/src/features/mcp/features/annotationQueues/tools/listAnnotationQueueItems.ts b/web/src/features/mcp/features/annotationQueues/tools/listAnnotationQueueItems.ts
new file mode 100644
index 0000000000..73af9cbdc2
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/listAnnotationQueueItems.ts
@@ -0,0 +1,61 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetAnnotationQueueItemsQuery,
+ GetAnnotationQueueItemsResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+import { annotationQueueItemToApi } from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [listAnnotationQueueItemsTool, handleListAnnotationQueueItems] =
+ defineTool({
+ name: "listAnnotationQueueItems",
+ description:
+ "List annotation queue items, each linking one trace or observation to a queue with a review status, with optional status filtering.",
+ baseSchema: GetAnnotationQueueItemsQuery,
+ inputSchema: GetAnnotationQueueItemsQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_items.list",
+ context,
+ attributes: {
+ "mcp.annotation_queue_id": input.queueId,
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ const where = {
+ projectId: context.projectId,
+ queueId: input.queueId,
+ ...(input.status ? { status: input.status } : {}),
+ };
+
+ const [items, totalItems] = await Promise.all([
+ prisma.annotationQueueItem.findMany({
+ where,
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ take: input.limit,
+ skip: (input.page - 1) * input.limit,
+ }),
+ prisma.annotationQueueItem.count({ where }),
+ ]);
+
+ return GetAnnotationQueueItemsResponse.parse({
+ data: items.map(annotationQueueItemToApi),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/tools/listAnnotationQueues.ts b/web/src/features/mcp/features/annotationQueues/tools/listAnnotationQueues.ts
new file mode 100644
index 0000000000..409d835247
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/listAnnotationQueues.ts
@@ -0,0 +1,50 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetAnnotationQueuesQuery,
+ GetAnnotationQueuesResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+import { annotationQueueToApi } from "../schema";
+
+export const [listAnnotationQueuesTool, handleListAnnotationQueues] =
+ defineTool({
+ name: "listAnnotationQueues",
+ description:
+ "List annotation queues, worklists that collect trace or observation items for human review and scoring, with pagination.",
+ baseSchema: GetAnnotationQueuesQuery,
+ inputSchema: GetAnnotationQueuesQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queues.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ const [queues, totalItems] = await Promise.all([
+ prisma.annotationQueue.findMany({
+ where: { projectId: context.projectId },
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ take: input.limit,
+ skip: (input.page - 1) * input.limit,
+ }),
+ prisma.annotationQueue.count({
+ where: { projectId: context.projectId },
+ }),
+ ]);
+
+ return GetAnnotationQueuesResponse.parse({
+ data: queues.map(annotationQueueToApi),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/tools/updateAnnotationQueueItem.ts b/web/src/features/mcp/features/annotationQueues/tools/updateAnnotationQueueItem.ts
new file mode 100644
index 0000000000..88df99b058
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools/updateAnnotationQueueItem.ts
@@ -0,0 +1,78 @@
+import { AnnotationQueueStatus, LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { UpdateAnnotationQueueItemResponse } from "@/src/features/public-api/types/annotation-queues";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import {
+ annotationQueueItemToApi,
+ UpdateAnnotationQueueItemToolSchema,
+} from "../schema";
+import { verifyAnnotationQueue } from "../utils";
+
+export const [updateAnnotationQueueItemTool, handleUpdateAnnotationQueueItem] =
+ defineTool({
+ name: "updateAnnotationQueueItem",
+ description:
+ "Update an annotation queue item's review status, such as pending or completed.",
+ baseSchema: UpdateAnnotationQueueItemToolSchema,
+ inputSchema: UpdateAnnotationQueueItemToolSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.annotation_queue_items.update",
+ context,
+ attributes: {
+ "mcp.annotation_queue_id": input.queueId,
+ "mcp.annotation_queue_item_id": input.itemId,
+ },
+ fn: async () => {
+ await verifyAnnotationQueue({
+ projectId: context.projectId,
+ queueId: input.queueId,
+ });
+
+ const existingItem = await prisma.annotationQueueItem.findUnique({
+ where: {
+ id: input.itemId,
+ queueId: input.queueId,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!existingItem) {
+ throw new LangfuseNotFoundError("Annotation queue item not found");
+ }
+
+ const item = await prisma.annotationQueueItem.update({
+ where: {
+ id: input.itemId,
+ queueId: input.queueId,
+ projectId: context.projectId,
+ },
+ data: {
+ status: input.status,
+ completedAt:
+ input.status === AnnotationQueueStatus.COMPLETED
+ ? new Date()
+ : undefined,
+ },
+ });
+
+ await auditLog({
+ action: "update",
+ resourceType: "annotationQueueItem",
+ resourceId: item.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: existingItem,
+ after: item,
+ });
+
+ return UpdateAnnotationQueueItemResponse.parse(
+ annotationQueueItemToApi(item),
+ );
+ },
+ }),
+ destructiveHint: true,
+ });
diff --git a/web/src/features/mcp/features/annotationQueues/utils.ts b/web/src/features/mcp/features/annotationQueues/utils.ts
new file mode 100644
index 0000000000..5513f00abf
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/utils.ts
@@ -0,0 +1,23 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+
+export const verifyAnnotationQueue = async ({
+ projectId,
+ queueId,
+}: {
+ projectId: string;
+ queueId: string;
+}) => {
+ const queue = await prisma.annotationQueue.findUnique({
+ where: {
+ id: queueId,
+ projectId,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Annotation queue not found");
+ }
+
+ return queue;
+};
diff --git a/web/src/features/mcp/features/comments/index.ts b/web/src/features/mcp/features/comments/index.ts
index b8e3919f42..758a39a845 100644
--- a/web/src/features/mcp/features/comments/index.ts
+++ b/web/src/features/mcp/features/comments/index.ts
@@ -1,12 +1,7 @@
import type { McpFeatureModule } from "../../server/registry";
-import {
- createCommentTool,
- getCommentTool,
- handleCreateComment,
- handleGetComment,
- handleListComments,
- listCommentsTool,
-} from "./tools";
+import { createCommentTool, handleCreateComment } from "./tools/createComment";
+import { getCommentTool, handleGetComment } from "./tools/getComment";
+import { handleListComments, listCommentsTool } from "./tools/listComments";
export const commentsFeature: McpFeatureModule = {
name: "comments",
diff --git a/web/src/features/mcp/features/comments/schema.ts b/web/src/features/mcp/features/comments/schema.ts
new file mode 100644
index 0000000000..469fc3bb82
--- /dev/null
+++ b/web/src/features/mcp/features/comments/schema.ts
@@ -0,0 +1,28 @@
+import type { z } from "zod";
+import { PostCommentsV1Body } from "@/src/features/public-api/types/comments";
+
+export const CreateCommentToolSchema = PostCommentsV1Body.omit({
+ projectId: true,
+});
+
+export const publicComment = (comment: {
+ id: string;
+ projectId: string;
+ createdAt: Date;
+ updatedAt: Date;
+ objectType: "TRACE" | "OBSERVATION" | "SESSION" | "PROMPT";
+ objectId: string;
+ content: string;
+ authorUserId: string | null;
+}) => ({
+ id: comment.id,
+ projectId: comment.projectId,
+ createdAt: comment.createdAt,
+ updatedAt: comment.updatedAt,
+ objectType: comment.objectType,
+ objectId: comment.objectId,
+ content: comment.content,
+ authorUserId: comment.authorUserId,
+});
+
+export type CreateCommentToolInput = z.infer<typeof CreateCommentToolSchema>;
diff --git a/web/src/features/mcp/features/comments/tools.ts b/web/src/features/mcp/features/comments/tools.ts
deleted file mode 100644
index 9811a53237..0000000000
--- a/web/src/features/mcp/features/comments/tools.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { LangfuseNotFoundError } from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-import { v4 } from "uuid";
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";
-import {
- GetCommentV1Query,
- GetCommentV1Response,
- GetCommentsV1Query,
- GetCommentsV1Response,
- PostCommentsV1Body,
- PostCommentsV1Response,
-} from "@/src/features/public-api/types/comments";
-import { defineTool } from "../../core/define-tool";
-import { paginationMeta, runPublicApiTool } from "../publicApi";
-
-const CreateCommentToolSchema = PostCommentsV1Body.omit({
- projectId: true,
-});
-
-const publicComment = (comment: {
- id: string;
- projectId: string;
- createdAt: Date;
- updatedAt: Date;
- objectType: "TRACE" | "OBSERVATION" | "SESSION" | "PROMPT";
- objectId: string;
- content: string;
- authorUserId: string | null;
-}) => ({
- id: comment.id,
- projectId: comment.projectId,
- createdAt: comment.createdAt,
- updatedAt: comment.updatedAt,
- objectType: comment.objectType,
- objectId: comment.objectId,
- content: comment.content,
- authorUserId: comment.authorUserId,
-});
-
-export const [createCommentTool, handleCreateComment] = defineTool({
- name: "createComment",
- description:
- "Create a comment on a trace, observation, session, or prompt in the current Langfuse project.",
- baseSchema: CreateCommentToolSchema,
- inputSchema: CreateCommentToolSchema,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.comments.create",
- context,
- attributes: {
- "mcp.comment_object_type": input.objectType,
- "mcp.comment_object_id": input.objectId,
- },
- fn: async () => {
- const body = PostCommentsV1Body.parse({
- ...input,
- projectId: context.projectId,
- });
-
- const result = await validateCommentReferenceObject({
- ctx: {
- prisma,
- auth: { scope: { projectId: context.projectId } },
- },
- input: body,
- });
-
- if (result.errorMessage) {
- throw new LangfuseNotFoundError(result.errorMessage);
- }
-
- const comment = await prisma.comment.create({
- data: {
- content: body.content,
- objectId: body.objectId,
- objectType: body.objectType,
- authorUserId: body.authorUserId,
- id: v4(),
- projectId: context.projectId,
- },
- });
-
- await auditLog({
- action: "create",
- resourceType: "comment",
- resourceId: comment.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- after: comment,
- });
-
- return PostCommentsV1Response.parse({ id: comment.id });
- },
- }),
-});
-
-export const [listCommentsTool, handleListComments] = defineTool({
- name: "listComments",
- description:
- "List comments in the current Langfuse project, optionally filtered by object or author.",
- baseSchema: GetCommentsV1Query,
- inputSchema: GetCommentsV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.comments.list",
- context,
- attributes: {
- "mcp.comment_object_type": input.objectType ?? undefined,
- "mcp.comment_object_id": input.objectId ?? undefined,
- "mcp.pagination_page": input.page,
- "mcp.pagination_limit": input.limit,
- },
- fn: async () => {
- const where = {
- projectId: context.projectId,
- objectType: input.objectType ?? undefined,
- objectId: input.objectId ?? undefined,
- authorUserId: input.authorUserId ?? undefined,
- };
-
- const [comments, totalItems] = await Promise.all([
- prisma.comment.findMany({
- where,
- take: input.limit,
- skip: (input.page - 1) * input.limit,
- }),
- prisma.comment.count({ where }),
- ]);
-
- return GetCommentsV1Response.parse({
- data: comments.map(publicComment),
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
-});
-
-export const [getCommentTool, handleGetComment] = defineTool({
- name: "getComment",
- description: "Get a comment by ID from the current Langfuse project.",
- baseSchema: GetCommentV1Query,
- inputSchema: GetCommentV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.comments.get",
- context,
- attributes: { "mcp.comment_id": input.commentId },
- fn: async () => {
- const comment = await prisma.comment.findUnique({
- where: {
- id: input.commentId,
- projectId: context.projectId,
- },
- });
-
- if (!comment) {
- throw new LangfuseNotFoundError(
- "Comment not found within authorized project",
- );
- }
-
- return GetCommentV1Response.parse(publicComment(comment));
- },
- }),
- readOnlyHint: true,
-});
diff --git a/web/src/features/mcp/features/comments/tools/createComment.ts b/web/src/features/mcp/features/comments/tools/createComment.ts
new file mode 100644
index 0000000000..313286fa7c
--- /dev/null
+++ b/web/src/features/mcp/features/comments/tools/createComment.ts
@@ -0,0 +1,69 @@
+import { v4 } from "uuid";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";
+import {
+ PostCommentsV1Body,
+ PostCommentsV1Response,
+} from "@/src/features/public-api/types/comments";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { CreateCommentToolSchema } from "../schema";
+
+export const [createCommentTool, handleCreateComment] = defineTool({
+ name: "createComment",
+ description: "Create a comment on a trace, observation, session, or prompt.",
+ baseSchema: CreateCommentToolSchema,
+ inputSchema: CreateCommentToolSchema,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.comments.create",
+ context,
+ attributes: {
+ "mcp.comment_object_type": input.objectType,
+ "mcp.comment_object_id": input.objectId,
+ },
+ fn: async () => {
+ const body = PostCommentsV1Body.parse({
+ ...input,
+ projectId: context.projectId,
+ });
+
+ const result = await validateCommentReferenceObject({
+ ctx: {
+ prisma,
+ auth: { scope: { projectId: context.projectId } },
+ },
+ input: body,
+ });
+
+ if (result.errorMessage) {
+ throw new LangfuseNotFoundError(result.errorMessage);
+ }
+
+ const comment = await prisma.comment.create({
+ data: {
+ content: body.content,
+ objectId: body.objectId,
+ objectType: body.objectType,
+ authorUserId: body.authorUserId,
+ id: v4(),
+ projectId: context.projectId,
+ },
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "comment",
+ resourceId: comment.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: comment,
+ });
+
+ return PostCommentsV1Response.parse({ id: comment.id });
+ },
+ }),
+});
diff --git a/web/src/features/mcp/features/comments/tools/getComment.ts b/web/src/features/mcp/features/comments/tools/getComment.ts
new file mode 100644
index 0000000000..7509e078f6
--- /dev/null
+++ b/web/src/features/mcp/features/comments/tools/getComment.ts
@@ -0,0 +1,39 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetCommentV1Query,
+ GetCommentV1Response,
+} from "@/src/features/public-api/types/comments";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { publicComment } from "../schema";
+
+export const [getCommentTool, handleGetComment] = defineTool({
+ name: "getComment",
+ description: "Get a comment by ID from the current Langfuse project.",
+ baseSchema: GetCommentV1Query,
+ inputSchema: GetCommentV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.comments.get",
+ context,
+ attributes: { "mcp.comment_id": input.commentId },
+ fn: async () => {
+ const comment = await prisma.comment.findUnique({
+ where: {
+ id: input.commentId,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!comment) {
+ throw new LangfuseNotFoundError(
+ "Comment not found within authorized project",
+ );
+ }
+
+ return GetCommentV1Response.parse(publicComment(comment));
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/comments/tools/index.ts b/web/src/features/mcp/features/comments/tools/index.ts
new file mode 100644
index 0000000000..81e094292b
--- /dev/null
+++ b/web/src/features/mcp/features/comments/tools/index.ts
@@ -0,0 +1,3 @@
+export * from "./createComment";
+export * from "./getComment";
+export * from "./listComments";
diff --git a/web/src/features/mcp/features/comments/tools/listComments.ts b/web/src/features/mcp/features/comments/tools/listComments.ts
new file mode 100644
index 0000000000..972402017b
--- /dev/null
+++ b/web/src/features/mcp/features/comments/tools/listComments.ts
@@ -0,0 +1,55 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetCommentsV1Query,
+ GetCommentsV1Response,
+} from "@/src/features/public-api/types/comments";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+import { publicComment } from "../schema";
+
+export const [listCommentsTool, handleListComments] = defineTool({
+ name: "listComments",
+ description:
+ "List comments in the current Langfuse project, optionally filtered by object or author.",
+ baseSchema: GetCommentsV1Query,
+ inputSchema: GetCommentsV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.comments.list",
+ context,
+ attributes: {
+ "mcp.comment_object_type": input.objectType ?? undefined,
+ "mcp.comment_object_id": input.objectId ?? undefined,
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ const where = {
+ projectId: context.projectId,
+ objectType: input.objectType ?? undefined,
+ objectId: input.objectId ?? undefined,
+ authorUserId: input.authorUserId ?? undefined,
+ };
+
+ const [comments, totalItems] = await Promise.all([
+ prisma.comment.findMany({
+ where,
+ take: input.limit,
+ skip: (input.page - 1) * input.limit,
+ }),
+ prisma.comment.count({ where }),
+ ]);
+
+ return GetCommentsV1Response.parse({
+ data: comments.map(publicComment),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/index.ts b/web/src/features/mcp/features/datasets/index.ts
index e68e774c8f..2f81e46224 100644
--- a/web/src/features/mcp/features/datasets/index.ts
+++ b/web/src/features/mcp/features/datasets/index.ts
@@ -1,30 +1,40 @@
import type { McpFeatureModule } from "../../server/registry";
+import { createDatasetTool, handleCreateDataset } from "./tools/createDataset";
import {
createDatasetItemTool,
- createDatasetRunItemTool,
- createDatasetTool,
- deleteDatasetItemTool,
- deleteDatasetRunTool,
- getDatasetItemTool,
- getDatasetRunTool,
- getDatasetTool,
- handleCreateDataset,
handleCreateDatasetItem,
+} from "./tools/createDatasetItem";
+import {
+ createDatasetRunItemTool,
handleCreateDatasetRunItem,
+} from "./tools/createDatasetRunItem";
+import {
+ deleteDatasetItemTool,
handleDeleteDatasetItem,
+} from "./tools/deleteDatasetItem";
+import {
+ deleteDatasetRunTool,
handleDeleteDatasetRun,
- handleGetDataset,
+} from "./tools/deleteDatasetRun";
+import { getDatasetTool, handleGetDataset } from "./tools/getDataset";
+import {
+ getDatasetItemTool,
handleGetDatasetItem,
- handleGetDatasetRun,
+} from "./tools/getDatasetItem";
+import { getDatasetRunTool, handleGetDatasetRun } from "./tools/getDatasetRun";
+import {
handleListDatasetItems,
- handleListDatasetRunItems,
- handleListDatasetRuns,
- handleListDatasets,
listDatasetItemsTool,
+} from "./tools/listDatasetItems";
+import {
+ handleListDatasetRunItems,
listDatasetRunItemsTool,
+} from "./tools/listDatasetRunItems";
+import {
+ handleListDatasetRuns,
listDatasetRunsTool,
- listDatasetsTool,
-} from "./tools";
+} from "./tools/listDatasetRuns";
+import { handleListDatasets, listDatasetsTool } from "./tools/listDatasets";
export const datasetsFeature: McpFeatureModule = {
name: "datasets",
diff --git a/web/src/features/mcp/features/datasets/schema.ts b/web/src/features/mcp/features/datasets/schema.ts
new file mode 100644
index 0000000000..c09e1661c7
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/schema.ts
@@ -0,0 +1,38 @@
+import { z } from "zod";
+import type { JSONValue } from "@langfuse/shared";
+import {
+ DeleteDatasetRunV1Query,
+ GetDatasetRunV1Query,
+ GetDatasetRunsV1Query,
+ GetDatasetV2Query,
+} from "@/src/features/public-api/types/datasets";
+
+export const resolveMetadata = (
+ metadata: JSONValue,
+): Record<string, unknown> => {
+ if (Array.isArray(metadata)) {
+ return { metadata };
+ }
+ if (typeof metadata === "object" && metadata !== null) {
+ return metadata as Record<string, unknown>;
+ }
+ return { metadata };
+};
+
+export const GetDatasetMcpInput = GetDatasetV2Query.extend({
+ datasetName: z.string(),
+});
+
+export const GetDatasetRunsMcpInput = GetDatasetRunsV1Query.extend({
+ name: z.string(),
+});
+
+export const GetDatasetRunMcpInput = GetDatasetRunV1Query.extend({
+ name: z.string(),
+ runName: z.string(),
+});
+
+export const DeleteDatasetRunMcpInput = DeleteDatasetRunV1Query.extend({
+ name: z.string(),
+ runName: z.string(),
+});
diff --git a/web/src/features/mcp/features/datasets/tools.ts b/web/src/features/mcp/features/datasets/tools.ts
deleted file mode 100644
index 609b9c0cb4..0000000000
--- a/web/src/features/mcp/features/datasets/tools.ts
+++ /dev/null
@@ -1,807 +0,0 @@
-import { v4 } from "uuid";
-import { z } from "zod";
-import {
- ApiError,
- type JSONValue,
- LangfuseConflictError,
- LangfuseNotFoundError,
-} from "@langfuse/shared";
-import { prisma, Prisma } from "@langfuse/shared/src/db";
-import {
- addToDeleteDatasetQueue,
- createDatasetItemFilterState,
- deleteDatasetItem,
- eventTypes,
- getDatasetItemById,
- getDatasetItems,
- getDatasetItemsCount,
- getObservationById,
- logger,
- processEventBatch,
- upsertDatasetItem,
-} from "@langfuse/shared/src/server";
-import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { addDatasetRunItemsToEvalQueue } from "@/src/features/evals/server/addDatasetRunItemsToEvalQueue";
-import { createOrFetchDatasetRun } from "@/src/features/public-api/server/dataset-runs";
-import {
- generateDatasetRunItemsForPublicApi,
- getDatasetRunItemsCountForPublicApi,
-} from "@/src/features/public-api/server/dataset-run-items";
-import { upsertDataset } from "@/src/features/datasets/server/actions/createDataset";
-import {
- DeleteDatasetItemV1Query,
- DeleteDatasetItemV1Response,
- DeleteDatasetRunV1Query,
- DeleteDatasetRunV1Response,
- GetDatasetItemV1Query,
- GetDatasetItemV1Response,
- GetDatasetItemsV1Query,
- GetDatasetItemsV1Response,
- GetDatasetRunItemsV1Query,
- GetDatasetRunItemsV1Response,
- GetDatasetRunV1Query,
- GetDatasetRunV1Response,
- GetDatasetRunsV1Query,
- GetDatasetRunsV1Response,
- GetDatasetV2Query,
- GetDatasetV2Response,
- GetDatasetsV2Query,
- GetDatasetsV2Response,
- PostDatasetItemsV1Body,
- PostDatasetItemsV1Response,
- PostDatasetRunItemsV1Body,
- PostDatasetRunItemsV1Response,
- PostDatasetsV2Body,
- PostDatasetsV2Response,
- type APIDatasetRunItem,
- transformDbDatasetItemDomainToAPIDatasetItem,
- transformDbDatasetRunToAPIDatasetRun,
- transformDbDatasetToAPIDataset,
-} from "@/src/features/public-api/types/datasets";
-import { defineTool } from "../../core/define-tool";
-import {
- getMcpPublicApiAuth,
- paginationMeta,
- runPublicApiTool,
-} from "../publicApi";
-
-const resolveMetadata = (metadata: JSONValue): Record<string, unknown> => {
- if (Array.isArray(metadata)) {
- return { metadata };
- }
- if (typeof metadata === "object" && metadata !== null) {
- return metadata as Record<string, unknown>;
- }
- return { metadata };
-};
-
-const GetDatasetMcpInput = GetDatasetV2Query.extend({
- datasetName: z.string(),
-});
-
-const GetDatasetRunsMcpInput = GetDatasetRunsV1Query.extend({
- name: z.string(),
-});
-
-const GetDatasetRunMcpInput = GetDatasetRunV1Query.extend({
- name: z.string(),
- runName: z.string(),
-});
-
-const DeleteDatasetRunMcpInput = DeleteDatasetRunV1Query.extend({
- name: z.string(),
- runName: z.string(),
-});
-
-export const [createDatasetTool, handleCreateDataset] = defineTool({
- name: "createDataset",
- description:
- "Create or update a dataset, a named collection of input and optional expected-output examples for experiments and evaluations.",
- baseSchema: PostDatasetsV2Body,
- inputSchema: PostDatasetsV2Body,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.datasets.create",
- context,
- attributes: { "mcp.dataset_name": input.name },
- fn: async () => {
- const dataset = await upsertDataset({
- input: {
- name: input.name,
- description: input.description ?? undefined,
- metadata: input.metadata ?? undefined,
- inputSchema: input.inputSchema,
- expectedOutputSchema: input.expectedOutputSchema,
- },
- projectId: context.projectId,
- });
-
- await auditLog({
- action: "create",
- resourceType: "dataset",
- resourceId: dataset.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- after: dataset,
- });
-
- return PostDatasetsV2Response.parse(
- transformDbDatasetToAPIDataset(dataset),
- );
- },
- }),
-});
-
-export const [listDatasetsTool, handleListDatasets] = defineTool({
- name: "listDatasets",
- description:
- "List datasets, named collections of input and optional expected-output examples for experiments and evaluations.",
- baseSchema: GetDatasetsV2Query,
- inputSchema: GetDatasetsV2Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.datasets.list",
- context,
- attributes: {
- "mcp.pagination_page": input.page,
- "mcp.pagination_limit": input.limit,
- },
- fn: async () => {
- const [datasets, totalItems] = await Promise.all([
- prisma.dataset.findMany({
- select: {
- name: true,
- description: true,
- metadata: true,
- inputSchema: true,
- expectedOutputSchema: true,
- projectId: true,
- createdAt: true,
- updatedAt: true,
- id: true,
- },
- where: { projectId: context.projectId },
- orderBy: { createdAt: "desc" },
- take: input.limit,
- skip: (input.page - 1) * input.limit,
- }),
- prisma.dataset.count({ where: { projectId: context.projectId } }),
- ]);
-
- return GetDatasetsV2Response.parse({
- data: datasets,
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
-});
-
-export const [getDatasetTool, handleGetDataset] = defineTool({
- name: "getDataset",
- description:
- "Get a dataset, a named collection of input and optional expected-output examples for experiments and evaluations, by name.",
- baseSchema: GetDatasetMcpInput,
- inputSchema: GetDatasetMcpInput,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.datasets.get",
- context,
- attributes: { "mcp.dataset_name": input.datasetName },
- fn: async () => {
- const dataset = await prisma.dataset.findFirst({
- where: {
- name: input.datasetName,
- projectId: context.projectId,
- },
- });
-
- if (!dataset) {
- throw new LangfuseNotFoundError("Dataset not found");
- }
-
- return GetDatasetV2Response.parse(
- transformDbDatasetToAPIDataset(dataset),
- );
- },
- }),
- readOnlyHint: true,
-});
-
-export const [createDatasetItemTool, handleCreateDatasetItem] = defineTool({
- name: "createDatasetItem",
- description:
- "Create or upsert a dataset item, one example in a dataset with input and optional expected output.",
- baseSchema: PostDatasetItemsV1Body,
- inputSchema: PostDatasetItemsV1Body,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_items.create",
- context,
- attributes: { "mcp.dataset_name": input.datasetName },
- fn: async () => {
- try {
- const datasetItem = await upsertDatasetItem({
- projectId: context.projectId,
- datasetName: input.datasetName,
- datasetItemId: input.id ?? undefined,
- input: input.input ?? undefined,
- expectedOutput: input.expectedOutput ?? undefined,
- metadata: input.metadata ?? undefined,
- sourceTraceId: input.sourceTraceId ?? undefined,
- sourceObservationId: input.sourceObservationId ?? undefined,
- status: input.status ?? undefined,
- normalizeOpts: { sanitizeControlChars: true },
- validateOpts: { normalizeUndefinedToNull: input.id ? false : true },
- });
-
- await auditLog({
- action: "create",
- resourceType: "datasetItem",
- resourceId: datasetItem.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- after: datasetItem,
- });
-
- return PostDatasetItemsV1Response.parse(
- transformDbDatasetItemDomainToAPIDatasetItem({
- ...datasetItem,
- datasetName: input.datasetName,
- status: datasetItem.status ?? "ACTIVE",
- }),
- );
- } catch (error) {
- if (error instanceof Prisma.PrismaClientKnownRequestError) {
- if (error.code === "P2025") {
- logger.warn(
- `Failed to upsert dataset item. Dataset item ${input.id} already exists for a different dataset than ${input.datasetName}`,
- );
- throw new LangfuseNotFoundError(
- `The dataset item with id ${input.id} already exists in a dataset other than ${input.datasetName}`,
- );
- }
- if (error.code === "P2002") {
- logger.warn(
- `Failed to upsert dataset item due to version conflict. Dataset item ${input.id} was modified concurrently.`,
- );
- throw new LangfuseConflictError(
- `Dataset item ${input.id ?? "new"} was modified concurrently. Please retry the request.`,
- );
- }
- }
- throw error;
- }
- },
- }),
-});
-
-export const [listDatasetItemsTool, handleListDatasetItems] = defineTool({
- name: "listDatasetItems",
- description:
- "List dataset items, individual examples with input and optional expected output, optionally filtered by dataset name, source trace, source observation, or version.",
- baseSchema: GetDatasetItemsV1Query,
- inputSchema: GetDatasetItemsV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_items.list",
- context,
- attributes: {
- "mcp.dataset_name": input.datasetName ?? undefined,
- "mcp.pagination_page": input.page,
- "mcp.pagination_limit": input.limit,
- },
- fn: async () => {
- let datasetId: string | undefined;
- if (input.datasetName) {
- const dataset = await prisma.dataset.findFirst({
- where: {
- name: input.datasetName,
- projectId: context.projectId,
- },
- });
- if (!dataset) {
- throw new LangfuseNotFoundError("Dataset not found");
- }
- datasetId = dataset.id;
- }
-
- const filterState = createDatasetItemFilterState({
- ...(datasetId && { datasetIds: [datasetId] }),
- sourceTraceId: input.sourceTraceId ?? undefined,
- sourceObservationId: input.sourceObservationId ?? undefined,
- status: "ACTIVE",
- });
-
- const [items, totalItems] = await Promise.all([
- getDatasetItems({
- projectId: context.projectId,
- filterState,
- version: input.version ?? undefined,
- includeDatasetName: true,
- limit: input.limit,
- page: input.page - 1,
- }),
- getDatasetItemsCount({
- projectId: context.projectId,
- filterState,
- version: input.version ?? undefined,
- }),
- ]);
-
- return GetDatasetItemsV1Response.parse({
- data: items.map(transformDbDatasetItemDomainToAPIDatasetItem),
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
-});
-
-export const [getDatasetItemTool, handleGetDatasetItem] = defineTool({
- name: "getDatasetItem",
- description:
- "Get a dataset item, one example in a dataset with input and optional expected output, by ID.",
- baseSchema: GetDatasetItemV1Query,
- inputSchema: GetDatasetItemV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_items.get",
- context,
- attributes: { "mcp.dataset_item_id": input.datasetItemId },
- fn: async () => {
- const datasetItem = await getDatasetItemById({
- projectId: context.projectId,
- datasetItemId: input.datasetItemId,
- });
-
- if (!datasetItem) {
- throw new LangfuseNotFoundError("Dataset item not found");
- }
-
- const dataset = await prisma.dataset.findUnique({
- where: {
- id_projectId: {
- projectId: context.projectId,
- id: datasetItem.datasetId,
- },
- },
- select: { name: true },
- });
-
- if (!dataset) {
- throw new LangfuseNotFoundError("Dataset not found");
- }
-
- return GetDatasetItemV1Response.parse(
- transformDbDatasetItemDomainToAPIDatasetItem({
- id: datasetItem.id,
- validFrom: datasetItem.validFrom,
- projectId: datasetItem.projectId,
- datasetId: datasetItem.datasetId,
- status: datasetItem.status ?? "ACTIVE",
- input: datasetItem.input,
- expectedOutput: datasetItem.expectedOutput,
- metadata: datasetItem.metadata,
- sourceTraceId: datasetItem.sourceTraceId,
- sourceObservationId: datasetItem.sourceObservationId,
- createdAt: datasetItem.createdAt,
- updatedAt: datasetItem.updatedAt,
- datasetName: dataset.name,
- }),
- );
- },
- }),
- readOnlyHint: true,
-});
-
-export const [deleteDatasetItemTool, handleDeleteDatasetItem] = defineTool({
- name: "deleteDatasetItem",
- description:
- "Delete a dataset item, one example in a dataset, and all its run items.",
- baseSchema: DeleteDatasetItemV1Query,
- inputSchema: DeleteDatasetItemV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_items.delete",
- context,
- attributes: { "mcp.dataset_item_id": input.datasetItemId },
- fn: async () => {
- const result = await deleteDatasetItem({
- projectId: context.projectId,
- datasetItemId: input.datasetItemId,
- });
-
- await auditLog({
- action: "delete",
- resourceType: "datasetItem",
- resourceId: input.datasetItemId,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- before: result.deletedItem,
- });
-
- return DeleteDatasetItemV1Response.parse({
- message: "Dataset item successfully deleted",
- });
- },
- }),
- destructiveHint: true,
-});
-
-export const [createDatasetRunItemTool, handleCreateDatasetRunItem] =
- defineTool({
- name: "createDatasetRunItem",
- description:
- "Create a dataset run item, a result that links one dataset item to a trace or observation in a dataset run.",
- baseSchema: PostDatasetRunItemsV1Body,
- inputSchema: PostDatasetRunItemsV1Body,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_run_items.create",
- context,
- attributes: {
- "mcp.dataset_item_id": input.datasetItemId,
- "mcp.dataset_run_name": input.runName,
- },
- fn: async () => {
- const datasetItem = await getDatasetItemById({
- projectId: context.projectId,
- datasetItemId: input.datasetItemId,
- status: "ACTIVE",
- version: input.datasetVersion ?? undefined,
- });
-
- if (!datasetItem) {
- throw new LangfuseNotFoundError("Dataset item not found");
- }
-
- let finalTraceId = input.traceId;
- if (!input.traceId && input.observationId) {
- const observation = await getObservationById({
- id: input.observationId,
- projectId: context.projectId,
- fetchWithInputOutput: false,
- });
- if (!observation) {
- throw new LangfuseNotFoundError("Observation not found");
- }
- finalTraceId = observation.traceId;
- }
-
- if (!finalTraceId) {
- throw new LangfuseNotFoundError("Trace not found");
- }
-
- const metadata = {
- ...(input.metadata ? resolveMetadata(input.metadata) : {}),
- ...(input.datasetVersion
- ? { dataset_version: input.datasetVersion.toISOString() }
- : {}),
- };
- const createdAt = input.createdAt
- ? new Date(input.createdAt)
- : new Date();
-
- const run = await createOrFetchDatasetRun({
- name: input.runName,
- description: input.runDescription ?? undefined,
- metadata,
- projectId: context.projectId,
- datasetId: datasetItem.datasetId,
- createdAt,
- });
-
- const runItemId = v4();
- const event = {
- id: runItemId,
- type: eventTypes.DATASET_RUN_ITEM_CREATE,
- timestamp: new Date().toISOString(),
- body: {
- id: runItemId,
- traceId: finalTraceId,
- observationId: input.observationId ?? undefined,
- error: null,
- createdAt: createdAt.toISOString(),
- datasetId: datasetItem.datasetId,
- runId: run.id,
- datasetItemId: datasetItem.id,
- datasetVersion: datasetItem.validFrom.toISOString(),
- },
- };
-
- const auth = await getMcpPublicApiAuth(context);
- const ingestionResult = await processEventBatch([event], auth, {
- isLangfuseInternal: true,
- });
-
- if (ingestionResult.errors.length > 0) {
- const error = ingestionResult.errors[0];
- throw new Error(error.error ?? error.message);
- }
- if (ingestionResult.successes.length !== 1) {
- logger.error("Failed to create dataset run item", {
- result: ingestionResult,
- });
- throw new Error("Failed to create dataset run item");
- }
-
- await addDatasetRunItemsToEvalQueue({
- projectId: context.projectId,
- datasetItemId: datasetItem.id,
- datasetItemValidFrom: datasetItem.validFrom,
- traceId: finalTraceId,
- observationId: input.observationId ?? undefined,
- });
-
- const mockDatasetRunItem: APIDatasetRunItem = {
- id: event.body.id,
- datasetRunId: run.id,
- datasetRunName: run.name,
- datasetItemId: datasetItem.id,
- traceId: finalTraceId,
- observationId: input.observationId ?? null,
- createdAt,
- updatedAt: createdAt,
- };
-
- return PostDatasetRunItemsV1Response.parse(mockDatasetRunItem);
- },
- }),
- });
-
-export const [listDatasetRunItemsTool, handleListDatasetRunItems] = defineTool({
- name: "listDatasetRunItems",
- description:
- "List dataset run items, each linking one dataset item to a trace or observation within a dataset run, by dataset ID and run name.",
- baseSchema: GetDatasetRunItemsV1Query,
- inputSchema: GetDatasetRunItemsV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_run_items.list",
- context,
- attributes: {
- "mcp.dataset_id": input.datasetId,
- "mcp.dataset_run_name": input.runName,
- },
- fn: async () => {
- const datasetRun = await prisma.datasetRuns.findUnique({
- where: {
- datasetId_projectId_name: {
- datasetId: input.datasetId,
- name: input.runName,
- projectId: context.projectId,
- },
- },
- select: { id: true, name: true },
- });
-
- if (!datasetRun) {
- throw new LangfuseNotFoundError(
- "Dataset run not found for the given project and dataset id",
- );
- }
-
- const [items, count] = await Promise.all([
- generateDatasetRunItemsForPublicApi({
- props: {
- datasetId: input.datasetId,
- runId: datasetRun.id,
- projectId: context.projectId,
- limit: input.limit,
- page: input.page,
- },
- }),
- getDatasetRunItemsCountForPublicApi({
- props: {
- datasetId: input.datasetId,
- runId: datasetRun.id,
- projectId: context.projectId,
- limit: input.limit,
- page: input.page,
- },
- }),
- ]);
-
- const totalItems = count || 0;
- return GetDatasetRunItemsV1Response.parse({
- data: items,
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
-});
-
-export const [listDatasetRunsTool, handleListDatasetRuns] = defineTool({
- name: "listDatasetRuns",
- description:
- "List dataset runs, each experiment or evaluation execution over a dataset, by dataset name.",
- baseSchema: GetDatasetRunsMcpInput,
- inputSchema: GetDatasetRunsMcpInput,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_runs.list",
- context,
- attributes: { "mcp.dataset_name": input.name },
- fn: async () => {
- const dataset = await prisma.dataset.findFirst({
- where: {
- name: input.name,
- projectId: context.projectId,
- },
- include: {
- datasetRuns: {
- where: { projectId: context.projectId },
- take: input.limit,
- skip: (input.page - 1) * input.limit,
- orderBy: { createdAt: "desc" },
- },
- },
- });
-
- if (!dataset) {
- throw new LangfuseNotFoundError("Dataset not found");
- }
-
- const totalItems = await prisma.datasetRuns.count({
- where: {
- datasetId: dataset.id,
- projectId: context.projectId,
- },
- });
-
- return GetDatasetRunsV1Response.parse({
- data: dataset.datasetRuns
- .map((run) => ({ ...run, datasetName: dataset.name }))
- .map(transformDbDatasetRunToAPIDatasetRun),
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
-});
-
-export const [getDatasetRunTool, handleGetDatasetRun] = defineTool({
- name: "getDatasetRun",
- description:
- "Get a dataset run, one experiment or evaluation execution over a dataset, and its run items by dataset and run name.",
- baseSchema: GetDatasetRunMcpInput,
- inputSchema: GetDatasetRunMcpInput,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_runs.get",
- context,
- attributes: {
- "mcp.dataset_name": input.name,
- "mcp.dataset_run_name": input.runName,
- },
- fn: async () => {
- const datasetRuns = await prisma.datasetRuns.findMany({
- where: {
- projectId: context.projectId,
- name: input.runName,
- dataset: {
- name: input.name,
- projectId: context.projectId,
- },
- },
- include: { dataset: { select: { name: true } } },
- });
-
- if (datasetRuns.length > 1) {
- throw new ApiError("Found more than one dataset run with this name");
- }
- if (!datasetRuns[0]) {
- throw new LangfuseNotFoundError("Dataset run not found");
- }
-
- const { dataset, ...run } = datasetRuns[0];
- const datasetRunItems = await generateDatasetRunItemsForPublicApi({
- props: {
- datasetId: run.datasetId,
- runId: run.id,
- projectId: context.projectId,
- },
- });
-
- return GetDatasetRunV1Response.parse({
- ...transformDbDatasetRunToAPIDatasetRun({
- ...run,
- datasetName: dataset.name,
- }),
- datasetRunItems,
- });
- },
- }),
- readOnlyHint: true,
-});
-
-export const [deleteDatasetRunTool, handleDeleteDatasetRun] = defineTool({
- name: "deleteDatasetRun",
- description:
- "Delete a dataset run, one experiment or evaluation execution over a dataset, and enqueue deletion of its run items.",
- baseSchema: DeleteDatasetRunMcpInput,
- inputSchema: DeleteDatasetRunMcpInput,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.dataset_runs.delete",
- context,
- attributes: {
- "mcp.dataset_name": input.name,
- "mcp.dataset_run_name": input.runName,
- },
- fn: async () => {
- const datasetRuns = await prisma.datasetRuns.findMany({
- where: {
- projectId: context.projectId,
- name: input.runName,
- dataset: {
- name: input.name,
- projectId: context.projectId,
- },
- },
- });
-
- if (datasetRuns.length === 0) {
- throw new LangfuseNotFoundError("Dataset run not found");
- }
- if (datasetRuns.length > 1) {
- throw new ApiError(
- "Found more than one dataset run with this name and dataset",
- );
- }
-
- const datasetRun = datasetRuns[0];
- await prisma.datasetRuns.delete({
- where: {
- id_projectId: {
- projectId: context.projectId,
- id: datasetRun.id,
- },
- },
- });
-
- await auditLog({
- action: "delete",
- resourceType: "datasetRun",
- resourceId: datasetRun.id,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- before: datasetRun,
- });
-
- await addToDeleteDatasetQueue({
- deletionType: "dataset-runs",
- projectId: context.projectId,
- datasetRunIds: [datasetRun.id],
- datasetId: datasetRun.datasetId,
- });
-
- return DeleteDatasetRunV1Response.parse({
- message: "Dataset run successfully deleted",
- });
- },
- }),
- destructiveHint: true,
-});
diff --git a/web/src/features/mcp/features/datasets/tools/createDataset.ts b/web/src/features/mcp/features/datasets/tools/createDataset.ts
new file mode 100644
index 0000000000..40204d3c3f
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/createDataset.ts
@@ -0,0 +1,50 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { upsertDataset } from "@/src/features/datasets/server/actions/createDataset";
+import {
+ PostDatasetsV2Body,
+ PostDatasetsV2Response,
+ transformDbDatasetToAPIDataset,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [createDatasetTool, handleCreateDataset] = defineTool({
+ name: "createDataset",
+ description:
+ "Create or update a dataset, a named collection of input and optional expected-output examples for experiments and evaluations.",
+ baseSchema: PostDatasetsV2Body,
+ inputSchema: PostDatasetsV2Body,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.datasets.create",
+ context,
+ attributes: { "mcp.dataset_name": input.name },
+ fn: async () => {
+ const dataset = await upsertDataset({
+ input: {
+ name: input.name,
+ description: input.description ?? undefined,
+ metadata: input.metadata ?? undefined,
+ inputSchema: input.inputSchema,
+ expectedOutputSchema: input.expectedOutputSchema,
+ },
+ projectId: context.projectId,
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "dataset",
+ resourceId: dataset.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: dataset,
+ });
+
+ return PostDatasetsV2Response.parse(
+ transformDbDatasetToAPIDataset(dataset),
+ );
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/createDatasetItem.ts b/web/src/features/mcp/features/datasets/tools/createDatasetItem.ts
new file mode 100644
index 0000000000..ba8260be8c
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/createDatasetItem.ts
@@ -0,0 +1,81 @@
+import { LangfuseConflictError, LangfuseNotFoundError } from "@langfuse/shared";
+import { Prisma } from "@langfuse/shared/src/db";
+import { logger, upsertDatasetItem } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ PostDatasetItemsV1Body,
+ PostDatasetItemsV1Response,
+ transformDbDatasetItemDomainToAPIDatasetItem,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [createDatasetItemTool, handleCreateDatasetItem] = defineTool({
+ name: "createDatasetItem",
+ description:
+ "Create or upsert a dataset item, one example in a dataset with input and optional expected output.",
+ baseSchema: PostDatasetItemsV1Body,
+ inputSchema: PostDatasetItemsV1Body,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_items.create",
+ context,
+ attributes: { "mcp.dataset_name": input.datasetName },
+ fn: async () => {
+ try {
+ const datasetItem = await upsertDatasetItem({
+ projectId: context.projectId,
+ datasetName: input.datasetName,
+ datasetItemId: input.id ?? undefined,
+ input: input.input ?? undefined,
+ expectedOutput: input.expectedOutput ?? undefined,
+ metadata: input.metadata ?? undefined,
+ sourceTraceId: input.sourceTraceId ?? undefined,
+ sourceObservationId: input.sourceObservationId ?? undefined,
+ status: input.status ?? undefined,
+ normalizeOpts: { sanitizeControlChars: true },
+ validateOpts: { normalizeUndefinedToNull: input.id ? false : true },
+ });
+
+ await auditLog({
+ action: "create",
+ resourceType: "datasetItem",
+ resourceId: datasetItem.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: datasetItem,
+ });
+
+ return PostDatasetItemsV1Response.parse(
+ transformDbDatasetItemDomainToAPIDatasetItem({
+ ...datasetItem,
+ datasetName: input.datasetName,
+ status: datasetItem.status ?? "ACTIVE",
+ }),
+ );
+ } catch (error) {
+ if (error instanceof Prisma.PrismaClientKnownRequestError) {
+ if (error.code === "P2025") {
+ logger.warn(
+ `Failed to upsert dataset item. Dataset item ${input.id} already exists for a different dataset than ${input.datasetName}`,
+ );
+ throw new LangfuseNotFoundError(
+ `The dataset item with id ${input.id} already exists in a dataset other than ${input.datasetName}`,
+ );
+ }
+ if (error.code === "P2002") {
+ logger.warn(
+ `Failed to upsert dataset item due to version conflict. Dataset item ${input.id} was modified concurrently.`,
+ );
+ throw new LangfuseConflictError(
+ `Dataset item ${input.id ?? "new"} was modified concurrently. Please retry the request.`,
+ );
+ }
+ }
+ throw error;
+ }
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/createDatasetRunItem.ts b/web/src/features/mcp/features/datasets/tools/createDatasetRunItem.ts
new file mode 100644
index 0000000000..40ed44f453
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/createDatasetRunItem.ts
@@ -0,0 +1,141 @@
+import { v4 } from "uuid";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import {
+ eventTypes,
+ getDatasetItemById,
+ getObservationById,
+ logger,
+ processEventBatch,
+} from "@langfuse/shared/src/server";
+import { addDatasetRunItemsToEvalQueue } from "@/src/features/evals/server/addDatasetRunItemsToEvalQueue";
+import { createOrFetchDatasetRun } from "@/src/features/public-api/server/dataset-runs";
+import {
+ type APIDatasetRunItem,
+ PostDatasetRunItemsV1Body,
+ PostDatasetRunItemsV1Response,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { getMcpPublicApiAuth } from "../../publicApi";
+import { resolveMetadata } from "../schema";
+
+export const [createDatasetRunItemTool, handleCreateDatasetRunItem] =
+ defineTool({
+ name: "createDatasetRunItem",
+ description:
+ "Create a dataset run item, a result that links one dataset item to a trace or observation in a dataset run.",
+ baseSchema: PostDatasetRunItemsV1Body,
+ inputSchema: PostDatasetRunItemsV1Body,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_run_items.create",
+ context,
+ attributes: {
+ "mcp.dataset_item_id": input.datasetItemId,
+ "mcp.dataset_run_name": input.runName,
+ },
+ fn: async () => {
+ const datasetItem = await getDatasetItemById({
+ projectId: context.projectId,
+ datasetItemId: input.datasetItemId,
+ status: "ACTIVE",
+ version: input.datasetVersion ?? undefined,
+ });
+
+ if (!datasetItem) {
+ throw new LangfuseNotFoundError("Dataset item not found");
+ }
+
+ let finalTraceId = input.traceId;
+ if (!input.traceId && input.observationId) {
+ const observation = await getObservationById({
+ id: input.observationId,
+ projectId: context.projectId,
+ fetchWithInputOutput: false,
+ });
+ if (!observation) {
+ throw new LangfuseNotFoundError("Observation not found");
+ }
+ finalTraceId = observation.traceId;
+ }
+
+ if (!finalTraceId) {
+ throw new LangfuseNotFoundError("Trace not found");
+ }
+
+ const metadata = {
+ ...(input.metadata ? resolveMetadata(input.metadata) : {}),
+ ...(input.datasetVersion
+ ? { dataset_version: input.datasetVersion.toISOString() }
+ : {}),
+ };
+ const createdAt = input.createdAt
+ ? new Date(input.createdAt)
+ : new Date();
+
+ const run = await createOrFetchDatasetRun({
+ name: input.runName,
+ description: input.runDescription ?? undefined,
+ metadata,
+ projectId: context.projectId,
+ datasetId: datasetItem.datasetId,
+ createdAt,
+ });
+
+ const runItemId = v4();
+ const event = {
+ id: runItemId,
+ type: eventTypes.DATASET_RUN_ITEM_CREATE,
+ timestamp: new Date().toISOString(),
+ body: {
+ id: runItemId,
+ traceId: finalTraceId,
+ observationId: input.observationId ?? undefined,
+ error: null,
+ createdAt: createdAt.toISOString(),
+ datasetId: datasetItem.datasetId,
+ runId: run.id,
+ datasetItemId: datasetItem.id,
+ datasetVersion: datasetItem.validFrom.toISOString(),
+ },
+ };
+
+ const auth = await getMcpPublicApiAuth(context);
+ const ingestionResult = await processEventBatch([event], auth, {
+ isLangfuseInternal: true,
+ });
+
+ if (ingestionResult.errors.length > 0) {
+ const error = ingestionResult.errors[0];
+ throw new Error(error.error ?? error.message);
+ }
+ if (ingestionResult.successes.length !== 1) {
+ logger.error("Failed to create dataset run item", {
+ result: ingestionResult,
+ });
+ throw new Error("Failed to create dataset run item");
+ }
+
+ await addDatasetRunItemsToEvalQueue({
+ projectId: context.projectId,
+ datasetItemId: datasetItem.id,
+ datasetItemValidFrom: datasetItem.validFrom,
+ traceId: finalTraceId,
+ observationId: input.observationId ?? undefined,
+ });
+
+ const mockDatasetRunItem: APIDatasetRunItem = {
+ id: event.body.id,
+ datasetRunId: run.id,
+ datasetRunName: run.name,
+ datasetItemId: datasetItem.id,
+ traceId: finalTraceId,
+ observationId: input.observationId ?? null,
+ createdAt,
+ updatedAt: createdAt,
+ };
+
+ return PostDatasetRunItemsV1Response.parse(mockDatasetRunItem);
+ },
+ }),
+ });
diff --git a/web/src/features/mcp/features/datasets/tools/deleteDatasetItem.ts b/web/src/features/mcp/features/datasets/tools/deleteDatasetItem.ts
new file mode 100644
index 0000000000..767fd3d4b5
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/deleteDatasetItem.ts
@@ -0,0 +1,43 @@
+import { deleteDatasetItem } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ DeleteDatasetItemV1Query,
+ DeleteDatasetItemV1Response,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [deleteDatasetItemTool, handleDeleteDatasetItem] = defineTool({
+ name: "deleteDatasetItem",
+ description:
+ "Delete a dataset item, one example in a dataset, and all its run items.",
+ baseSchema: DeleteDatasetItemV1Query,
+ inputSchema: DeleteDatasetItemV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_items.delete",
+ context,
+ attributes: { "mcp.dataset_item_id": input.datasetItemId },
+ fn: async () => {
+ const result = await deleteDatasetItem({
+ projectId: context.projectId,
+ datasetItemId: input.datasetItemId,
+ });
+
+ await auditLog({
+ action: "delete",
+ resourceType: "datasetItem",
+ resourceId: input.datasetItemId,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: result.deletedItem,
+ });
+
+ return DeleteDatasetItemV1Response.parse({
+ message: "Dataset item successfully deleted",
+ });
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/deleteDatasetRun.ts b/web/src/features/mcp/features/datasets/tools/deleteDatasetRun.ts
new file mode 100644
index 0000000000..22e24cce6f
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/deleteDatasetRun.ts
@@ -0,0 +1,78 @@
+import { ApiError, LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { addToDeleteDatasetQueue } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { DeleteDatasetRunV1Response } from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { DeleteDatasetRunMcpInput } from "../schema";
+
+export const [deleteDatasetRunTool, handleDeleteDatasetRun] = defineTool({
+ name: "deleteDatasetRun",
+ description:
+ "Delete a dataset run, one experiment or evaluation execution over a dataset, and enqueue deletion of its run items.",
+ baseSchema: DeleteDatasetRunMcpInput,
+ inputSchema: DeleteDatasetRunMcpInput,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_runs.delete",
+ context,
+ attributes: {
+ "mcp.dataset_name": input.name,
+ "mcp.dataset_run_name": input.runName,
+ },
+ fn: async () => {
+ const datasetRuns = await prisma.datasetRuns.findMany({
+ where: {
+ projectId: context.projectId,
+ name: input.runName,
+ dataset: {
+ name: input.name,
+ projectId: context.projectId,
+ },
+ },
+ });
+
+ if (datasetRuns.length === 0) {
+ throw new LangfuseNotFoundError("Dataset run not found");
+ }
+ if (datasetRuns.length > 1) {
+ throw new ApiError(
+ "Found more than one dataset run with this name and dataset",
+ );
+ }
+
+ const datasetRun = datasetRuns[0];
+ await prisma.datasetRuns.delete({
+ where: {
+ id_projectId: {
+ projectId: context.projectId,
+ id: datasetRun.id,
+ },
+ },
+ });
+
+ await auditLog({
+ action: "delete",
+ resourceType: "datasetRun",
+ resourceId: datasetRun.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: datasetRun,
+ });
+
+ await addToDeleteDatasetQueue({
+ deletionType: "dataset-runs",
+ projectId: context.projectId,
+ datasetRunIds: [datasetRun.id],
+ datasetId: datasetRun.datasetId,
+ });
+
+ return DeleteDatasetRunV1Response.parse({
+ message: "Dataset run successfully deleted",
+ });
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/getDataset.ts b/web/src/features/mcp/features/datasets/tools/getDataset.ts
new file mode 100644
index 0000000000..a5823ef019
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/getDataset.ts
@@ -0,0 +1,40 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetDatasetV2Response,
+ transformDbDatasetToAPIDataset,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { GetDatasetMcpInput } from "../schema";
+
+export const [getDatasetTool, handleGetDataset] = defineTool({
+ name: "getDataset",
+ description:
+ "Get a dataset, a named collection of input and optional expected-output examples for experiments and evaluations, by name.",
+ baseSchema: GetDatasetMcpInput,
+ inputSchema: GetDatasetMcpInput,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.datasets.get",
+ context,
+ attributes: { "mcp.dataset_name": input.datasetName },
+ fn: async () => {
+ const dataset = await prisma.dataset.findFirst({
+ where: {
+ name: input.datasetName,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!dataset) {
+ throw new LangfuseNotFoundError("Dataset not found");
+ }
+
+ return GetDatasetV2Response.parse(
+ transformDbDatasetToAPIDataset(dataset),
+ );
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/getDatasetItem.ts b/web/src/features/mcp/features/datasets/tools/getDatasetItem.ts
new file mode 100644
index 0000000000..e4134c7118
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/getDatasetItem.ts
@@ -0,0 +1,67 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { getDatasetItemById } from "@langfuse/shared/src/server";
+import {
+ GetDatasetItemV1Query,
+ GetDatasetItemV1Response,
+ transformDbDatasetItemDomainToAPIDatasetItem,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [getDatasetItemTool, handleGetDatasetItem] = defineTool({
+ name: "getDatasetItem",
+ description:
+ "Get a dataset item, one example in a dataset with input and optional expected output, by ID.",
+ baseSchema: GetDatasetItemV1Query,
+ inputSchema: GetDatasetItemV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_items.get",
+ context,
+ attributes: { "mcp.dataset_item_id": input.datasetItemId },
+ fn: async () => {
+ const datasetItem = await getDatasetItemById({
+ projectId: context.projectId,
+ datasetItemId: input.datasetItemId,
+ });
+
+ if (!datasetItem) {
+ throw new LangfuseNotFoundError("Dataset item not found");
+ }
+
+ const dataset = await prisma.dataset.findUnique({
+ where: {
+ id_projectId: {
+ projectId: context.projectId,
+ id: datasetItem.datasetId,
+ },
+ },
+ select: { name: true },
+ });
+
+ if (!dataset) {
+ throw new LangfuseNotFoundError("Dataset not found");
+ }
+
+ return GetDatasetItemV1Response.parse(
+ transformDbDatasetItemDomainToAPIDatasetItem({
+ id: datasetItem.id,
+ validFrom: datasetItem.validFrom,
+ projectId: datasetItem.projectId,
+ datasetId: datasetItem.datasetId,
+ status: datasetItem.status ?? "ACTIVE",
+ input: datasetItem.input,
+ expectedOutput: datasetItem.expectedOutput,
+ metadata: datasetItem.metadata,
+ sourceTraceId: datasetItem.sourceTraceId,
+ sourceObservationId: datasetItem.sourceObservationId,
+ createdAt: datasetItem.createdAt,
+ updatedAt: datasetItem.updatedAt,
+ datasetName: dataset.name,
+ }),
+ );
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/getDatasetRun.ts b/web/src/features/mcp/features/datasets/tools/getDatasetRun.ts
new file mode 100644
index 0000000000..89db086bf3
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/getDatasetRun.ts
@@ -0,0 +1,65 @@
+import { ApiError, LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { generateDatasetRunItemsForPublicApi } from "@/src/features/public-api/server/dataset-run-items";
+import {
+ GetDatasetRunV1Response,
+ transformDbDatasetRunToAPIDatasetRun,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { GetDatasetRunMcpInput } from "../schema";
+
+export const [getDatasetRunTool, handleGetDatasetRun] = defineTool({
+ name: "getDatasetRun",
+ description:
+ "Get a dataset run, one experiment or evaluation execution over a dataset, and its run items by dataset and run name.",
+ baseSchema: GetDatasetRunMcpInput,
+ inputSchema: GetDatasetRunMcpInput,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_runs.get",
+ context,
+ attributes: {
+ "mcp.dataset_name": input.name,
+ "mcp.dataset_run_name": input.runName,
+ },
+ fn: async () => {
+ const datasetRuns = await prisma.datasetRuns.findMany({
+ where: {
+ projectId: context.projectId,
+ name: input.runName,
+ dataset: {
+ name: input.name,
+ projectId: context.projectId,
+ },
+ },
+ include: { dataset: { select: { name: true } } },
+ });
+
+ if (datasetRuns.length > 1) {
+ throw new ApiError("Found more than one dataset run with this name");
+ }
+ if (!datasetRuns[0]) {
+ throw new LangfuseNotFoundError("Dataset run not found");
+ }
+
+ const { dataset, ...run } = datasetRuns[0];
+ const datasetRunItems = await generateDatasetRunItemsForPublicApi({
+ props: {
+ datasetId: run.datasetId,
+ runId: run.id,
+ projectId: context.projectId,
+ },
+ });
+
+ return GetDatasetRunV1Response.parse({
+ ...transformDbDatasetRunToAPIDatasetRun({
+ ...run,
+ datasetName: dataset.name,
+ }),
+ datasetRunItems,
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/index.ts b/web/src/features/mcp/features/datasets/tools/index.ts
new file mode 100644
index 0000000000..48842998b8
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/index.ts
@@ -0,0 +1,12 @@
+export * from "./createDataset";
+export * from "./createDatasetItem";
+export * from "./createDatasetRunItem";
+export * from "./deleteDatasetItem";
+export * from "./deleteDatasetRun";
+export * from "./getDataset";
+export * from "./getDatasetItem";
+export * from "./getDatasetRun";
+export * from "./listDatasetItems";
+export * from "./listDatasetRunItems";
+export * from "./listDatasetRuns";
+export * from "./listDatasets";
diff --git a/web/src/features/mcp/features/datasets/tools/listDatasetItems.ts b/web/src/features/mcp/features/datasets/tools/listDatasetItems.ts
new file mode 100644
index 0000000000..ab693d02ae
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/listDatasetItems.ts
@@ -0,0 +1,81 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ createDatasetItemFilterState,
+ getDatasetItems,
+ getDatasetItemsCount,
+} from "@langfuse/shared/src/server";
+import {
+ GetDatasetItemsV1Query,
+ GetDatasetItemsV1Response,
+ transformDbDatasetItemDomainToAPIDatasetItem,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+
+export const [listDatasetItemsTool, handleListDatasetItems] = defineTool({
+ name: "listDatasetItems",
+ description:
+ "List dataset items, individual examples with input and optional expected output, optionally filtered by dataset name, source trace, source observation, or version.",
+ baseSchema: GetDatasetItemsV1Query,
+ inputSchema: GetDatasetItemsV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_items.list",
+ context,
+ attributes: {
+ "mcp.dataset_name": input.datasetName ?? undefined,
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ let datasetId: string | undefined;
+ if (input.datasetName) {
+ const dataset = await prisma.dataset.findFirst({
+ where: {
+ name: input.datasetName,
+ projectId: context.projectId,
+ },
+ });
+ if (!dataset) {
+ throw new LangfuseNotFoundError("Dataset not found");
+ }
+ datasetId = dataset.id;
+ }
+
+ const filterState = createDatasetItemFilterState({
+ ...(datasetId && { datasetIds: [datasetId] }),
+ sourceTraceId: input.sourceTraceId ?? undefined,
+ sourceObservationId: input.sourceObservationId ?? undefined,
+ status: "ACTIVE",
+ });
+
+ const [items, totalItems] = await Promise.all([
+ getDatasetItems({
+ projectId: context.projectId,
+ filterState,
+ version: input.version ?? undefined,
+ includeDatasetName: true,
+ limit: input.limit,
+ page: input.page - 1,
+ }),
+ getDatasetItemsCount({
+ projectId: context.projectId,
+ filterState,
+ version: input.version ?? undefined,
+ }),
+ ]);
+
+ return GetDatasetItemsV1Response.parse({
+ data: items.map(transformDbDatasetItemDomainToAPIDatasetItem),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/listDatasetRunItems.ts b/web/src/features/mcp/features/datasets/tools/listDatasetRunItems.ts
new file mode 100644
index 0000000000..6bf7d32a46
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/listDatasetRunItems.ts
@@ -0,0 +1,80 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ generateDatasetRunItemsForPublicApi,
+ getDatasetRunItemsCountForPublicApi,
+} from "@/src/features/public-api/server/dataset-run-items";
+import {
+ GetDatasetRunItemsV1Query,
+ GetDatasetRunItemsV1Response,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+
+export const [listDatasetRunItemsTool, handleListDatasetRunItems] = defineTool({
+ name: "listDatasetRunItems",
+ description:
+ "List dataset run items, each linking one dataset item to a trace or observation within a dataset run, by dataset ID and run name.",
+ baseSchema: GetDatasetRunItemsV1Query,
+ inputSchema: GetDatasetRunItemsV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_run_items.list",
+ context,
+ attributes: {
+ "mcp.dataset_id": input.datasetId,
+ "mcp.dataset_run_name": input.runName,
+ },
+ fn: async () => {
+ const datasetRun = await prisma.datasetRuns.findUnique({
+ where: {
+ datasetId_projectId_name: {
+ datasetId: input.datasetId,
+ name: input.runName,
+ projectId: context.projectId,
+ },
+ },
+ select: { id: true, name: true },
+ });
+
+ if (!datasetRun) {
+ throw new LangfuseNotFoundError(
+ "Dataset run not found for the given project and dataset id",
+ );
+ }
+
+ const [items, count] = await Promise.all([
+ generateDatasetRunItemsForPublicApi({
+ props: {
+ datasetId: input.datasetId,
+ runId: datasetRun.id,
+ projectId: context.projectId,
+ limit: input.limit,
+ page: input.page,
+ },
+ }),
+ getDatasetRunItemsCountForPublicApi({
+ props: {
+ datasetId: input.datasetId,
+ runId: datasetRun.id,
+ projectId: context.projectId,
+ limit: input.limit,
+ page: input.page,
+ },
+ }),
+ ]);
+
+ const totalItems = count || 0;
+ return GetDatasetRunItemsV1Response.parse({
+ data: items,
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/listDatasetRuns.ts b/web/src/features/mcp/features/datasets/tools/listDatasetRuns.ts
new file mode 100644
index 0000000000..324eba0bbd
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/listDatasetRuns.ts
@@ -0,0 +1,63 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetDatasetRunsV1Response,
+ transformDbDatasetRunToAPIDatasetRun,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+import { GetDatasetRunsMcpInput } from "../schema";
+
+export const [listDatasetRunsTool, handleListDatasetRuns] = defineTool({
+ name: "listDatasetRuns",
+ description:
+ "List dataset runs, each experiment or evaluation execution over a dataset, by dataset name.",
+ baseSchema: GetDatasetRunsMcpInput,
+ inputSchema: GetDatasetRunsMcpInput,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.dataset_runs.list",
+ context,
+ attributes: { "mcp.dataset_name": input.name },
+ fn: async () => {
+ const dataset = await prisma.dataset.findFirst({
+ where: {
+ name: input.name,
+ projectId: context.projectId,
+ },
+ include: {
+ datasetRuns: {
+ where: { projectId: context.projectId },
+ take: input.limit,
+ skip: (input.page - 1) * input.limit,
+ orderBy: { createdAt: "desc" },
+ },
+ },
+ });
+
+ if (!dataset) {
+ throw new LangfuseNotFoundError("Dataset not found");
+ }
+
+ const totalItems = await prisma.datasetRuns.count({
+ where: {
+ datasetId: dataset.id,
+ projectId: context.projectId,
+ },
+ });
+
+ return GetDatasetRunsV1Response.parse({
+ data: dataset.datasetRuns
+ .map((run) => ({ ...run, datasetName: dataset.name }))
+ .map(transformDbDatasetRunToAPIDatasetRun),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/datasets/tools/listDatasets.ts b/web/src/features/mcp/features/datasets/tools/listDatasets.ts
new file mode 100644
index 0000000000..886ef99dfe
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools/listDatasets.ts
@@ -0,0 +1,57 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetDatasetsV2Query,
+ GetDatasetsV2Response,
+} from "@/src/features/public-api/types/datasets";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+
+export const [listDatasetsTool, handleListDatasets] = defineTool({
+ name: "listDatasets",
+ description:
+ "List datasets, named collections of input and optional expected-output examples for experiments and evaluations.",
+ baseSchema: GetDatasetsV2Query,
+ inputSchema: GetDatasetsV2Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.datasets.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ const [datasets, totalItems] = await Promise.all([
+ prisma.dataset.findMany({
+ select: {
+ name: true,
+ description: true,
+ metadata: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
+ projectId: true,
+ createdAt: true,
+ updatedAt: true,
+ id: true,
+ },
+ where: { projectId: context.projectId },
+ orderBy: { createdAt: "desc" },
+ take: input.limit,
+ skip: (input.page - 1) * input.limit,
+ }),
+ prisma.dataset.count({ where: { projectId: context.projectId } }),
+ ]);
+
+ return GetDatasetsV2Response.parse({
+ data: datasets,
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/health/index.ts b/web/src/features/mcp/features/health/index.ts
index 9de48fcb78..58fffd3b5c 100644
--- a/web/src/features/mcp/features/health/index.ts
+++ b/web/src/features/mcp/features/health/index.ts
@@ -1,5 +1,5 @@
import type { McpFeatureModule } from "../../server/registry";
-import { getHealthTool, handleGetHealth } from "./tools";
+import { getHealthTool, handleGetHealth } from "./tools/getHealth";
export const healthFeature: McpFeatureModule = {
name: "health",
diff --git a/web/src/features/mcp/features/health/tools.ts b/web/src/features/mcp/features/health/tools/getHealth.ts
similarity index 96%
rename from web/src/features/mcp/features/health/tools.ts
rename to web/src/features/mcp/features/health/tools/getHealth.ts
index f27ddfcfce..96c25ac80e 100644
--- a/web/src/features/mcp/features/health/tools.ts
+++ b/web/src/features/mcp/features/health/tools/getHealth.ts
@@ -8,8 +8,8 @@ import {
queryClickhouse,
traceException,
} from "@langfuse/shared/src/server";
-import { defineTool } from "../../core/define-tool";
-import { runPublicApiTool } from "../publicApi";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
const HealthInputSchema = z.object({
failIfDatabaseUnavailable: z.boolean().optional().default(false),
@@ -30,7 +30,7 @@ export const [getHealthTool, handleGetHealth] = defineTool({
baseSchema: HealthInputSchema,
inputSchema: HealthInputSchema,
handler: async (input, context) =>
- runPublicApiTool({
+ runMcpTool({
spanName: "mcp.health.get",
context,
fn: async () => {
diff --git a/web/src/features/mcp/features/health/tools/index.ts b/web/src/features/mcp/features/health/tools/index.ts
new file mode 100644
index 0000000000..6782562bf0
--- /dev/null
+++ b/web/src/features/mcp/features/health/tools/index.ts
@@ -0,0 +1 @@
+export * from "./getHealth";
diff --git a/web/src/features/mcp/features/media/index.ts b/web/src/features/mcp/features/media/index.ts
index 37ad45bdb7..f560ac1865 100644
--- a/web/src/features/mcp/features/media/index.ts
+++ b/web/src/features/mcp/features/media/index.ts
@@ -9,6 +9,7 @@ export const mediaFeature: McpFeatureModule = {
{
definition: getMediaTool,
handler: handleGetMedia,
+ allowInAppAgentKey: true,
},
],
};
diff --git a/web/src/features/mcp/features/media/tools/getMedia.ts b/web/src/features/mcp/features/media/tools/getMedia.ts
index 6ed1ba2980..efa62e415b 100644
--- a/web/src/features/mcp/features/media/tools/getMedia.ts
+++ b/web/src/features/mcp/features/media/tools/getMedia.ts
@@ -1,33 +1,25 @@
-import { SpanKind } from "@opentelemetry/api";
-
import { getMedia } from "@/src/features/media/server/mediaService";
import { GetMediaQuerySchema } from "@/src/features/media/validation";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
export const [getMediaTool, handleGetMedia] = defineTool({
name: "getMedia",
- description:
- "Fetch metadata and a signed download URL for one media asset in the current Langfuse project.",
+ description: "Fetch metadata and a signed download URL for one media asset.",
baseSchema: GetMediaQuerySchema,
inputSchema: GetMediaQuerySchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.media.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.media_id": input.mediaId,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.media.get",
+ context,
+ attributes: { "mcp.media_id": input.mediaId },
+ fn: async () => {
return await getMedia({
projectId: context.projectId,
mediaId: input.mediaId,
});
},
- );
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/metrics/index.ts b/web/src/features/mcp/features/metrics/index.ts
index 3f42a0a59d..0276bee5a1 100644
--- a/web/src/features/mcp/features/metrics/index.ts
+++ b/web/src/features/mcp/features/metrics/index.ts
@@ -14,10 +14,12 @@ export const metricsFeature: McpFeatureModule = {
{
definition: queryMetricsTool,
handler: handleQueryMetrics,
+ allowInAppAgentKey: true,
},
{
definition: getMetricsSchemaTool,
handler: handleGetMetricsSchema,
+ allowInAppAgentKey: true,
},
],
isEnabled: async () => env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true",
diff --git a/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts b/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
index 6e10563094..95f3770931 100644
--- a/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
+++ b/web/src/features/mcp/features/metrics/tools/getMetricsSchema.ts
@@ -6,6 +6,7 @@ import {
} from "@langfuse/shared/query";
import { z } from "zod";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
const GetMetricsSchemaInput = z.object({
view: viewsV2
@@ -19,55 +20,64 @@ export const [getMetricsSchemaTool, handleGetMetricsSchema] = defineTool({
"Discover which Langfuse metrics can be analyzed and how to group, filter, aggregate, and time-bucket them before calling queryMetrics.",
baseSchema: GetMetricsSchemaInput,
inputSchema: GetMetricsSchemaInput,
- handler: async (input) => {
- const supportedViews = viewsV2.options;
- const selectedViews = input.view ? [input.view] : supportedViews;
+ handler: async (input, context) => {
+ return await runMcpTool({
+ spanName: "mcp.metrics.schema",
+ context,
+ attributes: { "mcp.metrics_view": input.view },
+ fn: async () => {
+ const supportedViews = viewsV2.options;
+ const selectedViews = input.view ? [input.view] : supportedViews;
- return {
- supportedViews,
- granularities: granularities.options,
- config: {
- bins: { min: 1, max: 100 },
- row_limit: { min: 1, max: 1000, default: 100 },
- },
- views: Object.fromEntries(
- selectedViews.map((viewName) => {
- const view = viewDeclarations.v2[viewName];
+ return {
+ supportedViews,
+ granularities: granularities.options,
+ config: {
+ bins: { min: 1, max: 100 },
+ row_limit: { min: 1, max: 1000, default: 100 },
+ },
+ views: Object.fromEntries(
+ selectedViews.map((viewName) => {
+ const view = viewDeclarations.v2[viewName];
- return [
- viewName,
- {
- description: view.description,
- timeDimension: view.timeDimension,
- dimensions: Object.fromEntries(
- Object.entries(view.dimensions).map(([name, definition]) => [
- name,
- {
- description: definition.description,
- type: definition.type,
- unit: definition.unit,
- highCardinality: Boolean(definition.highCardinality),
- },
- ]),
- ),
- measures: Object.fromEntries(
- Object.entries(view.measures).map(([name, definition]) => [
- name,
- {
- description: definition.description,
- type: definition.type,
- unit: definition.unit,
- validAggregations: getValidAggregationsForMeasureType(
- definition.type,
+ return [
+ viewName,
+ {
+ description: view.description,
+ timeDimension: view.timeDimension,
+ dimensions: Object.fromEntries(
+ Object.entries(view.dimensions).map(
+ ([name, definition]) => [
+ name,
+ {
+ description: definition.description,
+ type: definition.type,
+ unit: definition.unit,
+ highCardinality: Boolean(definition.highCardinality),
+ },
+ ],
),
- },
- ]),
- ),
- },
- ];
- }),
- ),
- };
+ ),
+ measures: Object.fromEntries(
+ Object.entries(view.measures).map(([name, definition]) => [
+ name,
+ {
+ description: definition.description,
+ type: definition.type,
+ unit: definition.unit,
+ validAggregations: getValidAggregationsForMeasureType(
+ definition.type,
+ ),
+ },
+ ]),
+ ),
+ },
+ ];
+ }),
+ ),
+ };
+ },
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
index f2305ce507..94643fdd96 100644
--- a/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
+++ b/web/src/features/mcp/features/metrics/tools/queryMetrics.ts
@@ -3,6 +3,7 @@ import { executeQuery } from "@langfuse/shared/query/server";
import { validateQuery } from "@langfuse/shared/query";
import { MetricsQueryObjectV2 } from "@/src/features/public-api/types/metrics";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
const DEFAULT_ROW_LIMIT = 100;
@@ -13,30 +14,39 @@ export const [queryMetricsTool, handleQueryMetrics] = defineTool({
baseSchema: MetricsQueryObjectV2,
inputSchema: MetricsQueryObjectV2,
handler: async (input, context) => {
- const validation = validateQuery(input, "v2");
+ return await runMcpTool({
+ spanName: "mcp.metrics.query",
+ context,
+ attributes: {
+ "mcp.metrics_view": input.view,
+ },
+ fn: async () => {
+ const validation = validateQuery(input, "v2");
- if (!validation.valid) {
- throw new InvalidRequestError(validation.reason);
- }
+ if (!validation.valid) {
+ throw new InvalidRequestError(validation.reason);
+ }
- const { config, ...query } = input;
- const queryParams = {
- ...query,
- chartConfig: {
- type: "TABLE",
- ...config,
- row_limit: config?.row_limit ?? DEFAULT_ROW_LIMIT,
- },
- };
+ const { config, ...query } = input;
+ const queryParams = {
+ ...query,
+ chartConfig: {
+ type: "TABLE",
+ ...config,
+ row_limit: config?.row_limit ?? DEFAULT_ROW_LIMIT,
+ },
+ };
- const result = await executeQuery(
- context.projectId,
- queryParams,
- "v2",
- true,
- );
+ const result = await executeQuery(
+ context.projectId,
+ queryParams,
+ "v2",
+ true,
+ );
- return { data: result };
+ return { data: result };
+ },
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/models/index.ts b/web/src/features/mcp/features/models/index.ts
index f92b19588b..8139c65b11 100644
--- a/web/src/features/mcp/features/models/index.ts
+++ b/web/src/features/mcp/features/models/index.ts
@@ -1,14 +1,8 @@
import type { McpFeatureModule } from "../../server/registry";
-import {
- createModelTool,
- deleteModelTool,
- getModelTool,
- handleCreateModel,
- handleDeleteModel,
- handleGetModel,
- handleListModels,
- listModelsTool,
-} from "./tools";
+import { createModelTool, handleCreateModel } from "./tools/createModel";
+import { deleteModelTool, handleDeleteModel } from "./tools/deleteModel";
+import { getModelTool, handleGetModel } from "./tools/getModel";
+import { handleListModels, listModelsTool } from "./tools/listModels";
export const modelsFeature: McpFeatureModule = {
name: "models",
diff --git a/web/src/features/mcp/features/models/schema.ts b/web/src/features/mcp/features/models/schema.ts
new file mode 100644
index 0000000000..d1a1444133
--- /dev/null
+++ b/web/src/features/mcp/features/models/schema.ts
@@ -0,0 +1,18 @@
+export const modelPricingInclude = {
+ pricingTiers: {
+ select: {
+ id: true,
+ name: true,
+ isDefault: true,
+ priority: true,
+ conditions: true,
+ prices: {
+ select: {
+ usageType: true,
+ price: true,
+ },
+ },
+ },
+ orderBy: { priority: "asc" as const },
+ },
+};
diff --git a/web/src/features/mcp/features/models/tools.ts b/web/src/features/mcp/features/models/tools/createModel.ts
similarity index 51%
rename from web/src/features/mcp/features/models/tools.ts
rename to web/src/features/mcp/features/models/tools/createModel.ts
index 151f5834d8..a0a65159f9 100644
--- a/web/src/features/mcp/features/models/tools.ts
+++ b/web/src/features/mcp/features/models/tools/createModel.ts
@@ -1,92 +1,16 @@
-import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";
+import { InvalidRequestError } from "@langfuse/shared";
import { Prisma, prisma } from "@langfuse/shared/src/db";
import { clearModelCacheForProject } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { isValidPostgresRegex } from "@/src/features/models/server/isValidPostgresRegex";
import {
- DeleteModelV1Query,
- DeleteModelV1Response,
- GetModelV1Query,
- GetModelV1Response,
- GetModelsV1Query,
- GetModelsV1Response,
PostModelsV1Body,
PostModelsV1Response,
prismaToApiModelDefinition,
} from "@/src/features/public-api/types/models";
-import { defineTool } from "../../core/define-tool";
-import { paginationMeta, runPublicApiTool } from "../publicApi";
-
-const modelPricingInclude = {
- pricingTiers: {
- select: {
- id: true,
- name: true,
- isDefault: true,
- priority: true,
- conditions: true,
- prices: {
- select: {
- usageType: true,
- price: true,
- },
- },
- },
- orderBy: { priority: "asc" as const },
- },
-};
-
-export const [listModelsTool, handleListModels] = defineTool({
- name: "listModels",
- description:
- "List custom and Langfuse-managed model definitions visible to the current project.",
- baseSchema: GetModelsV1Query,
- inputSchema: GetModelsV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.models.list",
- context,
- attributes: {
- "mcp.pagination_page": input.page,
- "mcp.pagination_limit": input.limit,
- },
- fn: async () => {
- const where = {
- OR: [{ projectId: context.projectId }, { projectId: null }],
- };
-
- const [models, totalItems] = await Promise.all([
- prisma.model.findMany({
- where,
- orderBy: [
- { modelName: "asc" },
- { unit: "asc" },
- {
- startDate: {
- sort: "desc",
- nulls: "last",
- },
- },
- ],
- include: modelPricingInclude,
- take: input.limit,
- skip: (input.page - 1) * input.limit,
- }),
- prisma.model.count({ where }),
- ]);
-
- return GetModelsV1Response.parse({
- data: models.map(prismaToApiModelDefinition),
- meta: paginationMeta({
- page: input.page,
- limit: input.limit,
- totalItems,
- }),
- });
- },
- }),
- readOnlyHint: true,
-});
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { modelPricingInclude } from "../schema";
export const [createModelTool, handleCreateModel] = defineTool({
name: "createModel",
@@ -95,7 +19,7 @@ export const [createModelTool, handleCreateModel] = defineTool({
baseSchema: PostModelsV1Body,
inputSchema: PostModelsV1Body,
handler: async (input, context) =>
- runPublicApiTool({
+ runMcpTool({
spanName: "mcp.models.create",
context,
attributes: { "mcp.model_name": input.modelName },
@@ -226,88 +150,3 @@ export const [createModelTool, handleCreateModel] = defineTool({
},
}),
});
-
-export const [getModelTool, handleGetModel] = defineTool({
- name: "getModel",
- description: "Get a model definition by ID from the current project scope.",
- baseSchema: GetModelV1Query,
- inputSchema: GetModelV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.models.get",
- context,
- attributes: { "mcp.model_id": input.modelId },
- fn: async () => {
- const model = await prisma.model.findFirst({
- where: {
- AND: [
- { id: input.modelId },
- {
- OR: [{ projectId: context.projectId }, { projectId: null }],
- },
- ],
- },
- include: modelPricingInclude,
- });
-
- if (!model) {
- throw new LangfuseNotFoundError("No model with this id found.");
- }
-
- return GetModelV1Response.parse(prismaToApiModelDefinition(model));
- },
- }),
- readOnlyHint: true,
-});
-
-export const [deleteModelTool, handleDeleteModel] = defineTool({
- name: "deleteModel",
- description:
- "Delete a custom model definition from the current project. Built-in models cannot be deleted.",
- baseSchema: DeleteModelV1Query,
- inputSchema: DeleteModelV1Query,
- handler: async (input, context) =>
- runPublicApiTool({
- spanName: "mcp.models.delete",
- context,
- attributes: { "mcp.model_id": input.modelId },
- fn: async () => {
- const model = await prisma.model.findFirst({
- where: {
- id: input.modelId,
- projectId: context.projectId,
- },
- });
-
- if (!model) {
- throw new LangfuseNotFoundError(
- "No model with this id found. Note: You cannot delete built-in models, override them with a model with the same name.",
- );
- }
-
- await prisma.model.delete({
- where: {
- id: input.modelId,
- projectId: context.projectId,
- },
- });
-
- await auditLog({
- action: "delete",
- resourceType: "model",
- resourceId: input.modelId,
- projectId: context.projectId,
- orgId: context.orgId,
- apiKeyId: context.apiKeyId,
- before: model,
- });
-
- await clearModelCacheForProject(context.projectId);
-
- return DeleteModelV1Response.parse({
- message: "Model successfully deleted",
- });
- },
- }),
- destructiveHint: true,
-});
diff --git a/web/src/features/mcp/features/models/tools/deleteModel.ts b/web/src/features/mcp/features/models/tools/deleteModel.ts
new file mode 100644
index 0000000000..5446bdbb68
--- /dev/null
+++ b/web/src/features/mcp/features/models/tools/deleteModel.ts
@@ -0,0 +1,62 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { clearModelCacheForProject } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ DeleteModelV1Query,
+ DeleteModelV1Response,
+} from "@/src/features/public-api/types/models";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [deleteModelTool, handleDeleteModel] = defineTool({
+ name: "deleteModel",
+ description:
+ "Delete a custom model definition from the current project. Built-in models cannot be deleted.",
+ baseSchema: DeleteModelV1Query,
+ inputSchema: DeleteModelV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.models.delete",
+ context,
+ attributes: { "mcp.model_id": input.modelId },
+ fn: async () => {
+ const model = await prisma.model.findFirst({
+ where: {
+ id: input.modelId,
+ projectId: context.projectId,
+ },
+ });
+
+ if (!model) {
+ throw new LangfuseNotFoundError(
+ "No model with this id found. Note: You cannot delete built-in models, override them with a model with the same name.",
+ );
+ }
+
+ await prisma.model.delete({
+ where: {
+ id: input.modelId,
+ projectId: context.projectId,
+ },
+ });
+
+ await auditLog({
+ action: "delete",
+ resourceType: "model",
+ resourceId: input.modelId,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: model,
+ });
+
+ await clearModelCacheForProject(context.projectId);
+
+ return DeleteModelV1Response.parse({
+ message: "Model successfully deleted",
+ });
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/mcp/features/models/tools/getModel.ts b/web/src/features/mcp/features/models/tools/getModel.ts
new file mode 100644
index 0000000000..122442ae9c
--- /dev/null
+++ b/web/src/features/mcp/features/models/tools/getModel.ts
@@ -0,0 +1,43 @@
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetModelV1Query,
+ GetModelV1Response,
+ prismaToApiModelDefinition,
+} from "@/src/features/public-api/types/models";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { modelPricingInclude } from "../schema";
+
+export const [getModelTool, handleGetModel] = defineTool({
+ name: "getModel",
+ description: "Get a model definition by ID from the current project scope.",
+ baseSchema: GetModelV1Query,
+ inputSchema: GetModelV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.models.get",
+ context,
+ attributes: { "mcp.model_id": input.modelId },
+ fn: async () => {
+ const model = await prisma.model.findFirst({
+ where: {
+ AND: [
+ { id: input.modelId },
+ {
+ OR: [{ projectId: context.projectId }, { projectId: null }],
+ },
+ ],
+ },
+ include: modelPricingInclude,
+ });
+
+ if (!model) {
+ throw new LangfuseNotFoundError("No model with this id found.");
+ }
+
+ return GetModelV1Response.parse(prismaToApiModelDefinition(model));
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/models/tools/index.ts b/web/src/features/mcp/features/models/tools/index.ts
new file mode 100644
index 0000000000..185aea8d6e
--- /dev/null
+++ b/web/src/features/mcp/features/models/tools/index.ts
@@ -0,0 +1,4 @@
+export * from "./createModel";
+export * from "./deleteModel";
+export * from "./getModel";
+export * from "./listModels";
diff --git a/web/src/features/mcp/features/models/tools/listModels.ts b/web/src/features/mcp/features/models/tools/listModels.ts
new file mode 100644
index 0000000000..88b78f0977
--- /dev/null
+++ b/web/src/features/mcp/features/models/tools/listModels.ts
@@ -0,0 +1,62 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetModelsV1Query,
+ GetModelsV1Response,
+ prismaToApiModelDefinition,
+} from "@/src/features/public-api/types/models";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
+import { modelPricingInclude } from "../schema";
+
+export const [listModelsTool, handleListModels] = defineTool({
+ name: "listModels",
+ description:
+ "List custom and Langfuse-managed model definitions visible to the current project.",
+ baseSchema: GetModelsV1Query,
+ inputSchema: GetModelsV1Query,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.models.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
+ const where = {
+ OR: [{ projectId: context.projectId }, { projectId: null }],
+ };
+
+ const [models, totalItems] = await Promise.all([
+ prisma.model.findMany({
+ where,
+ orderBy: [
+ { modelName: "asc" },
+ { unit: "asc" },
+ {
+ startDate: {
+ sort: "desc",
+ nulls: "last",
+ },
+ },
+ ],
+ include: modelPricingInclude,
+ take: input.limit,
+ skip: (input.page - 1) * input.limit,
+ }),
+ prisma.model.count({ where }),
+ ]);
+
+ return GetModelsV1Response.parse({
+ data: models.map(prismaToApiModelDefinition),
+ meta: paginationMeta({
+ page: input.page,
+ limit: input.limit,
+ totalItems,
+ }),
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/observations/tools/getObservation.ts b/web/src/features/mcp/features/observations/tools/getObservation.ts
index 753b6e856e..bb5a6c0257 100644
--- a/web/src/features/mcp/features/observations/tools/getObservation.ts
+++ b/web/src/features/mcp/features/observations/tools/getObservation.ts
@@ -1,11 +1,8 @@
-import { SpanKind } from "@opentelemetry/api";
import { LangfuseNotFoundError } from "@langfuse/shared";
import { z } from "zod";
-import {
- getObservationsV2FromEventsTableForPublicApi,
- instrumentAsync,
-} from "@langfuse/shared/src/server";
+import { getObservationsV2FromEventsTableForPublicApi } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import {
ExpandMetadataKeysSchema,
getMetadataExpansionForProjection,
@@ -33,17 +30,15 @@ export const [getObservationTool, handleGetObservation] = defineTool({
baseSchema: GetObservationBaseSchema,
inputSchema: GetObservationBaseSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.observations.get", spanKind: SpanKind.INTERNAL },
- async (span) => {
+ return await runMcpTool({
+ spanName: "mcp.observations.get",
+ context,
+ attributes: { "mcp.observation_id": input.observationId },
+ fn: async (span) => {
const projectionFields = getProjectionFields(input.fields);
const fieldGroups = getProjectionFieldGroups(projectionFields);
span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.observation_id": input.observationId,
"mcp.projection_fields": projectionFields.join(","),
"mcp.field_groups": fieldGroups.join(","),
});
@@ -87,7 +82,7 @@ export const [getObservationTool, handleGetObservation] = defineTool({
projectionFields,
);
},
- );
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/observations/tools/getObservationFilterValues.ts b/web/src/features/mcp/features/observations/tools/getObservationFilterValues.ts
index 2304bf2053..47724e99b2 100644
--- a/web/src/features/mcp/features/observations/tools/getObservationFilterValues.ts
+++ b/web/src/features/mcp/features/observations/tools/getObservationFilterValues.ts
@@ -1,13 +1,12 @@
-import { SpanKind } from "@opentelemetry/api";
import {
InvalidRequestError,
ObservationTypeDomain,
type timeFilter,
} from "@langfuse/shared";
import { z } from "zod";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { getEventFilterValuePage } from "@/src/features/events/server/eventsService";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import {
ObservationLimitSchema,
type ObservationMcpFilterColumn,
@@ -154,17 +153,14 @@ export const [
baseSchema: GetObservationFilterValuesBaseSchema,
inputSchema: GetObservationFilterValuesBaseSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.observations.filterValues", spanKind: SpanKind.INTERNAL },
- async (span) => {
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.filter_column": input.column,
- "mcp.pagination_limit": input.limit,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.observations.filterValues",
+ context,
+ attributes: {
+ "mcp.filter_column": input.column,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async () => {
const startTimeFilter = buildStartTimeFilter({
fromStartTime: input.fromStartTime,
toStartTime: input.toStartTime,
@@ -206,7 +202,7 @@ export const [
: {},
};
},
- );
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/observations/tools/listObservations.ts b/web/src/features/mcp/features/observations/tools/listObservations.ts
index 497c276d55..db46204309 100644
--- a/web/src/features/mcp/features/observations/tools/listObservations.ts
+++ b/web/src/features/mcp/features/observations/tools/listObservations.ts
@@ -1,4 +1,3 @@
-import { SpanKind } from "@opentelemetry/api";
import {
InvalidRequestError,
OBSERVATION_MCP_ALLOWED_EVENTS_TABLE_FILTER_COLUMNS,
@@ -15,10 +14,7 @@ import {
timeFilter,
type ColumnDefinition,
} from "@langfuse/shared";
-import {
- getObservationsV2FromEventsTableForPublicApi,
- instrumentAsync,
-} from "@langfuse/shared/src/server";
+import { getObservationsV2FromEventsTableForPublicApi } from "@langfuse/shared/src/server";
import { z } from "zod";
import {
EncodedObservationsCursorV2,
@@ -26,6 +22,7 @@ import {
encodeCursor,
} from "@/src/features/public-api/types/observations";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import {
ExpandMetadataKeysSchema,
getMetadataExpansionForProjection,
@@ -312,18 +309,18 @@ export const [listObservationsTool, handleListObservations] = defineTool({
baseSchema: ListObservationsBaseSchema as z.ZodType<ListObservationsInput>,
inputSchema: ListObservationsInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.observations.list", spanKind: SpanKind.INTERNAL },
- async (span) => {
+ return await runMcpTool({
+ spanName: "mcp.observations.list",
+ context,
+ attributes: {
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async (span) => {
const projectionFields = getProjectionFields(input.fields);
const fieldGroups = getProjectionFieldGroups(projectionFields);
assertAllowedExpensiveObservationAccess(input, projectionFields);
span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.pagination_limit": input.limit,
"mcp.projection_fields": projectionFields.join(","),
"mcp.field_groups": fieldGroups.join(","),
});
@@ -385,7 +382,7 @@ export const [listObservationsTool, handleListObservations] = defineTool({
: {},
};
},
- );
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/prompts/index.ts b/web/src/features/mcp/features/prompts/index.ts
index ba148c50a3..263c472d8f 100644
--- a/web/src/features/mcp/features/prompts/index.ts
+++ b/web/src/features/mcp/features/prompts/index.ts
@@ -48,14 +48,17 @@ export const promptsFeature: McpFeatureModule = {
{
definition: getPromptTool,
handler: handleGetPrompt,
+ allowInAppAgentKey: true,
},
{
definition: getPromptUnresolvedTool,
handler: handleGetPromptUnresolved,
+ allowInAppAgentKey: true,
},
{
definition: listPromptsTool,
handler: handleListPrompts,
+ allowInAppAgentKey: true,
},
{
definition: createTextPromptTool,
diff --git a/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts b/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts
index 79dd175b21..263f8256fd 100644
--- a/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts
+++ b/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts
@@ -2,7 +2,6 @@
* MCP Tool: createChatPrompt
*
* Creates a new chat prompt version in Langfuse.
- * Write operation with destructive hint.
*/
import { z } from "zod";
@@ -17,8 +16,7 @@ import {
import { createPrompt as createPromptAction } from "@/src/features/prompts/server/actions/createPrompt";
import { prisma } from "@langfuse/shared/src/db";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { instrumentAsync } from "@langfuse/shared/src/server";
-import { SpanKind } from "@opentelemetry/api";
+import { runMcpTool } from "../../../core/run-mcp-tool";
/**
* Schema for a single chat message (role + content)
@@ -98,18 +96,14 @@ export const [createChatPromptTool, handleCreateChatPrompt] = defineTool({
baseSchema: CreateChatPromptBaseSchema,
inputSchema: CreateChatPromptInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.prompts.create_chat", spanKind: SpanKind.INTERNAL },
- async (span) => {
- // Set span attributes for observability
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.prompt_name": input.name,
- "mcp.prompt_type": "chat",
- });
-
+ return await runMcpTool({
+ spanName: "mcp.prompts.create_chat",
+ context,
+ attributes: {
+ "mcp.prompt_name": input.name,
+ "mcp.prompt_type": "chat",
+ },
+ fn: async (span) => {
const createdPrompt = await createPromptAction({
projectId: context.projectId,
name: input.name,
@@ -149,6 +143,7 @@ export const [createChatPromptTool, handleCreateChatPrompt] = defineTool({
message: `Successfully created chat prompt '${createdPrompt.name}' version ${createdPrompt.version}${createdPrompt.labels.length > 0 ? ` with labels: ${createdPrompt.labels.join(", ")}` : ""}`,
};
},
- );
+ });
},
+ destructiveHint: true,
});
diff --git a/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts b/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts
index 69bb53ec1b..aa1b50d80e 100644
--- a/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts
+++ b/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts
@@ -2,7 +2,6 @@
* MCP Tool: createTextPrompt
*
* Creates a new text prompt version in Langfuse.
- * Write operation with destructive hint.
*/
import { z } from "zod";
@@ -17,8 +16,7 @@ import {
import { createPrompt as createPromptAction } from "@/src/features/prompts/server/actions/createPrompt";
import { prisma } from "@langfuse/shared/src/db";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { instrumentAsync } from "@langfuse/shared/src/server";
-import { SpanKind } from "@opentelemetry/api";
+import { runMcpTool } from "../../../core/run-mcp-tool";
/**
* Base schema for JSON Schema generation (MCP client display)
@@ -86,18 +84,14 @@ export const [createTextPromptTool, handleCreateTextPrompt] = defineTool({
baseSchema: CreateTextPromptBaseSchema,
inputSchema: CreateTextPromptInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.prompts.create_text", spanKind: SpanKind.INTERNAL },
- async (span) => {
- // Set span attributes for observability
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.prompt_name": input.name,
- "mcp.prompt_type": "text",
- });
-
+ return await runMcpTool({
+ spanName: "mcp.prompts.create_text",
+ context,
+ attributes: {
+ "mcp.prompt_name": input.name,
+ "mcp.prompt_type": "text",
+ },
+ fn: async (span) => {
const createdPrompt = await createPromptAction({
projectId: context.projectId,
name: input.name,
@@ -137,6 +131,7 @@ export const [createTextPromptTool, handleCreateTextPrompt] = defineTool({
message: `Successfully created text prompt '${createdPrompt.name}' version ${createdPrompt.version}${createdPrompt.labels.length > 0 ? ` with labels: ${createdPrompt.labels.join(", ")}` : ""}`,
};
},
- );
+ });
},
+ destructiveHint: true,
});
diff --git a/web/src/features/mcp/features/prompts/tools/listPrompts.ts b/web/src/features/mcp/features/prompts/tools/listPrompts.ts
index d4338e5189..361cd3f4a2 100644
--- a/web/src/features/mcp/features/prompts/tools/listPrompts.ts
+++ b/web/src/features/mcp/features/prompts/tools/listPrompts.ts
@@ -14,8 +14,8 @@ import {
} from "../validation";
import { ParamLimit, ParamPage } from "../../../core/validation";
import { getPromptsMeta } from "@/src/features/prompts/server/actions/getPromptsMeta";
-import { instrumentAsync } from "@langfuse/shared/src/server";
-import { SpanKind } from "@opentelemetry/api";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+import { paginationMeta } from "../../publicApi";
const ParamFromUpdatedAt = z.iso
.datetime({ offset: true })
@@ -88,37 +88,22 @@ export const [listPromptsTool, handleListPrompts] = defineTool({
baseSchema: ListPromptsBaseSchema,
inputSchema: ListPromptsInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.prompts.list", spanKind: SpanKind.INTERNAL },
- async (span) => {
+ return await runMcpTool({
+ spanName: "mcp.prompts.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page ?? 1,
+ "mcp.pagination_limit": input.limit ?? 50,
+ "mcp.filter_name": input.name,
+ "mcp.filter_label": input.label,
+ "mcp.filter_tag": input.tag,
+ "mcp.filter_fromUpdatedAt": input.fromUpdatedAt,
+ "mcp.filter_toUpdatedAt": input.toUpdatedAt,
+ },
+ fn: async (span) => {
const { name, label, tag, fromUpdatedAt, toUpdatedAt, page, limit } =
input;
- // Set span attributes for observability
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.pagination_page": page ?? 1,
- "mcp.pagination_limit": limit ?? 50,
- });
-
- if (name) {
- span.setAttribute("mcp.filter_name", name);
- }
- if (label) {
- span.setAttribute("mcp.filter_label", label);
- }
- if (tag) {
- span.setAttribute("mcp.filter_tag", tag);
- }
- if (fromUpdatedAt) {
- span.setAttribute("mcp.filter_fromUpdatedAt", fromUpdatedAt);
- }
- if (toUpdatedAt) {
- span.setAttribute("mcp.filter_toUpdatedAt", toUpdatedAt);
- }
-
// Fetch prompts metadata using existing service
const result = await getPromptsMeta({
projectId: context.projectId, // Auto-injected from authenticated API key
@@ -145,15 +130,14 @@ export const [listPromptsTool, handleListPrompts] = defineTool({
lastUpdatedAt: prompt.lastUpdatedAt,
lastConfig: prompt.lastConfig,
})),
- pagination: {
+ meta: paginationMeta({
page: result.pagination.page,
limit: result.pagination.limit,
- totalPages: result.pagination.totalPages,
totalItems: result.pagination.totalItems,
- },
+ }),
};
},
- );
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts b/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts
index 5906ecee05..bc6f7d066e 100644
--- a/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts
+++ b/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts
@@ -1,11 +1,10 @@
import { z } from "zod";
-import { SpanKind } from "@opentelemetry/api";
import { type Prompt } from "@langfuse/shared";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { getPromptByName } from "@/src/features/prompts/server/actions/getPromptByName";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { UserInputError } from "../../../core/errors";
import {
ParamPromptLabel,
@@ -68,30 +67,18 @@ export const createPromptReadTool = (options: CreatePromptReadToolOptions) => {
baseSchema: PromptReadBaseSchema,
inputSchema: PromptReadInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: spanName, spanKind: SpanKind.INTERNAL },
- async (span) => {
+ return await runMcpTool({
+ spanName,
+ context,
+ attributes: {
+ "mcp.prompt_name": input.name,
+ "mcp.unresolved": resolve ? undefined : true,
+ "mcp.prompt_label": input.label,
+ "mcp.prompt_version": input.version ?? undefined,
+ },
+ fn: async () => {
const { name, label, version } = input;
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.prompt_name": name,
- });
-
- if (!resolve) {
- span.setAttribute("mcp.unresolved", true);
- }
-
- if (label) {
- span.setAttribute("mcp.prompt_label", label);
- }
-
- if (version) {
- span.setAttribute("mcp.prompt_version", version);
- }
-
const prompt = await getPromptByName({
promptName: name,
projectId: context.projectId,
@@ -112,7 +99,7 @@ export const createPromptReadTool = (options: CreatePromptReadToolOptions) => {
return formatPromptResponse(prompt);
},
- );
+ });
},
readOnlyHint: true,
});
diff --git a/web/src/features/mcp/features/prompts/tools/updatePromptLabels.ts b/web/src/features/mcp/features/prompts/tools/updatePromptLabels.ts
index ad16b093d1..edaceccec0 100644
--- a/web/src/features/mcp/features/prompts/tools/updatePromptLabels.ts
+++ b/web/src/features/mcp/features/prompts/tools/updatePromptLabels.ts
@@ -13,8 +13,7 @@ import { updatePrompt } from "@/src/features/prompts/server/actions/updatePrompt
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { prisma } from "@langfuse/shared/src/db";
import { UserInputError } from "../../../core/errors";
-import { instrumentAsync } from "@langfuse/shared/src/server";
-import { SpanKind } from "@opentelemetry/api";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { PROMPT_NAME_MAX_LENGTH } from "@langfuse/shared";
@@ -74,21 +73,17 @@ export const [updatePromptLabelsTool, handleUpdatePromptLabels] = defineTool({
baseSchema: UpdatePromptLabelsBaseSchema,
inputSchema: UpdatePromptLabelsInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.prompts.update_labels", spanKind: SpanKind.INTERNAL },
- async (span) => {
+ return await runMcpTool({
+ spanName: "mcp.prompts.update_labels",
+ context,
+ attributes: {
+ "mcp.prompt_name": input.name,
+ "mcp.prompt_version": input.version,
+ "mcp.new_labels_count": input.newLabels.length,
+ },
+ fn: async () => {
const { name, version, newLabels } = input;
- // Set span attributes for observability
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- "mcp.prompt_name": name,
- "mcp.prompt_version": version,
- "mcp.new_labels_count": newLabels.length,
- });
-
// Fetch existing prompt to capture "before" state for audit log
const existingPrompt = await prisma.prompt.findUnique({
where: {
@@ -135,6 +130,7 @@ export const [updatePromptLabelsTool, handleUpdatePromptLabels] = defineTool({
message: `Successfully updated labels for '${updatedPrompt.name}' version ${updatedPrompt.version}. Labels are now: ${updatedPrompt.labels.length > 0 ? updatedPrompt.labels.join(", ") : "(none)"}`,
};
},
- );
+ });
},
+ destructiveHint: true,
});
diff --git a/web/src/features/mcp/features/publicApi.ts b/web/src/features/mcp/features/publicApi.ts
index ca12133963..feeb298039 100644
--- a/web/src/features/mcp/features/publicApi.ts
+++ b/web/src/features/mcp/features/publicApi.ts
@@ -1,7 +1,5 @@
import { CloudConfigSchema, type Plan } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { instrumentAsync } from "@langfuse/shared/src/server";
-import { SpanKind } from "@opentelemetry/api";
import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
import type { ServerContext } from "../types";
@@ -62,33 +60,3 @@ export const paginationMeta = ({
totalItems,
totalPages: Math.ceil(totalItems / limit),
});
-
-export const runPublicApiTool = async <TResult>({
- spanName,
- context,
- attributes,
- fn,
-}: {
- spanName: string;
- context: ServerContext;
- attributes?: Record<string, string | number | boolean | undefined>;
- fn: () => Promise<TResult>;
-}): Promise<TResult> =>
- instrumentAsync(
- { name: spanName, spanKind: SpanKind.INTERNAL },
- async (span) => {
- span.setAttributes({
- "langfuse.project.id": context.projectId,
- "langfuse.org.id": context.orgId,
- "mcp.api_key_id": context.apiKeyId,
- ...Object.fromEntries(
- Object.entries(attributes ?? {}).filter(
- (entry): entry is [string, string | number | boolean] =>
- entry[1] !== undefined,
- ),
- ),
- });
-
- return await fn();
- },
- );
diff --git a/web/src/features/mcp/features/scores/index.ts b/web/src/features/mcp/features/scores/index.ts
index 10109fcc09..721b378725 100644
--- a/web/src/features/mcp/features/scores/index.ts
+++ b/web/src/features/mcp/features/scores/index.ts
@@ -32,10 +32,12 @@ export const scoresFeature: McpFeatureModule = {
{
definition: listScoresTool,
handler: handleListScores,
+ allowInAppAgentKey: true,
},
{
definition: getScoreTool,
handler: handleGetScore,
+ allowInAppAgentKey: true,
},
{
definition: createScoreTool,
@@ -48,10 +50,12 @@ export const scoresFeature: McpFeatureModule = {
{
definition: listScoreConfigsTool,
handler: handleListScoreConfigs,
+ allowInAppAgentKey: true,
},
{
definition: getScoreConfigTool,
handler: handleGetScoreConfig,
+ allowInAppAgentKey: true,
},
{
definition: createScoreConfigTool,
diff --git a/web/src/features/mcp/features/scores/tools/createScore.ts b/web/src/features/mcp/features/scores/tools/createScore.ts
index 470913c127..2b10c416f8 100644
--- a/web/src/features/mcp/features/scores/tools/createScore.ts
+++ b/web/src/features/mcp/features/scores/tools/createScore.ts
@@ -1,4 +1,3 @@
-import { SpanKind } from "@opentelemetry/api";
import {
InvalidRequestError,
LangfuseNotFoundError,
@@ -6,9 +5,9 @@ import {
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 { runMcpTool } from "../../../core/run-mcp-tool";
import { ApiServerError } from "../../../core/errors";
type CreateScoreBatchError = {
@@ -41,18 +40,16 @@ export const [createScoreTool, handleCreateScore] = defineTool({
"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,
+ destructiveHint: true,
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,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.scores.create",
+ context,
+ attributes: {
+ "mcp.score_id": input.id ?? undefined,
+ "mcp.score_name": input.name,
+ },
+ fn: async (span) => {
const scoresApiService = new ScoresApiService("v2");
const { id: scoreId, result } = await scoresApiService.createScore({
body: input,
@@ -80,7 +77,6 @@ export const [createScoreTool, handleCreateScore] = defineTool({
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
index a4b46e2088..90f36eb164 100644
--- a/web/src/features/mcp/features/scores/tools/createScoreConfig.ts
+++ b/web/src/features/mcp/features/scores/tools/createScoreConfig.ts
@@ -1,6 +1,5 @@
-import { SpanKind } from "@opentelemetry/api";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-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";
@@ -15,21 +14,19 @@ const CreateScoreConfigInputSchema = z
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.",
+ "Create a score configuration. Supports numeric, categorical, boolean, and text configs. Boolean configs automatically receive True and False categories.",
baseSchema: CreateScoreConfigInputSchema,
inputSchema: CreateScoreConfigInputSchema,
+ destructiveHint: true,
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,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.score_configs.create",
+ context,
+ attributes: {
+ "mcp.score_config_name": input.name,
+ "mcp.score_config_data_type": input.dataType,
+ },
+ fn: async (span) => {
const config = await createScoreConfig({
context,
body: input,
@@ -38,7 +35,6 @@ export const [createScoreConfigTool, handleCreateScoreConfig] = defineTool({
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
index a3521b3653..6a1fef2e33 100644
--- a/web/src/features/mcp/features/scores/tools/deleteScore.ts
+++ b/web/src/features/mcp/features/scores/tools/deleteScore.ts
@@ -1,8 +1,7 @@
-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";
+import { runMcpTool } from "../../../core/run-mcp-tool";
export const [deleteScoreTool, handleDeleteScore] = defineTool({
name: "deleteScore",
@@ -11,16 +10,11 @@ export const [deleteScoreTool, handleDeleteScore] = defineTool({
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,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.scores.delete",
+ context,
+ attributes: { "mcp.score_id": input.scoreId },
+ fn: async () => {
const scoresApiService = new ScoresApiService("v2");
const result = await scoresApiService.deleteScore({
scoreId: input.scoreId,
@@ -31,7 +25,7 @@ export const [deleteScoreTool, handleDeleteScore] = defineTool({
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
index 9bb3631c40..8902787cb3 100644
--- a/web/src/features/mcp/features/scores/tools/deleteScoreConfig.ts
+++ b/web/src/features/mcp/features/scores/tools/deleteScoreConfig.ts
@@ -1,6 +1,5 @@
-import { SpanKind } from "@opentelemetry/api";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { updateScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
import { PutScoreConfigQuery } from "@/src/features/public-api/types/score-configs";
@@ -11,23 +10,18 @@ export const [deleteScoreConfigTool, handleDeleteScoreConfig] = defineTool({
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 runMcpTool({
+ spanName: "mcp.score_configs.delete",
+ context,
+ attributes: { "mcp.score_config_id": input.configId },
+ fn: async () => {
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
index 6dd9296776..e36ba285dd 100644
--- a/web/src/features/mcp/features/scores/tools/getScore.ts
+++ b/web/src/features/mcp/features/scores/tools/getScore.ts
@@ -1,16 +1,12 @@
-import { SpanKind } from "@opentelemetry/api";
import {
GetScoreQueryV2,
GetScoreResponseV2,
InternalServerError,
LangfuseNotFoundError,
} from "@langfuse/shared";
-import {
- instrumentAsync,
- logger,
- traceException,
-} from "@langfuse/shared/src/server";
+import { logger, traceException } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
export const [getScoreTool, handleGetScore] = defineTool({
@@ -20,16 +16,11 @@ export const [getScoreTool, handleGetScore] = defineTool({
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,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.scores.get",
+ context,
+ attributes: { "mcp.score_id": input.scoreId },
+ fn: async () => {
const scoresApiService = new ScoresApiService("v2");
const score = await scoresApiService.getScoreById({
projectId: context.projectId,
@@ -49,7 +40,7 @@ export const [getScoreTool, handleGetScore] = defineTool({
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
index fec4a20d41..150b33ab37 100644
--- a/web/src/features/mcp/features/scores/tools/getScoreConfig.ts
+++ b/web/src/features/mcp/features/scores/tools/getScoreConfig.ts
@@ -1,6 +1,5 @@
-import { SpanKind } from "@opentelemetry/api";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { getScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
import { GetScoreConfigQuery } from "@/src/features/public-api/types/score-configs";
@@ -11,22 +10,17 @@ export const [getScoreConfigTool, handleGetScoreConfig] = defineTool({
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 runMcpTool({
+ spanName: "mcp.score_configs.get",
+ context,
+ attributes: { "mcp.score_config_id": input.configId },
+ fn: async () => {
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
index 2e764a3039..58bdea2748 100644
--- a/web/src/features/mcp/features/scores/tools/listScoreConfigs.ts
+++ b/web/src/features/mcp/features/scores/tools/listScoreConfigs.ts
@@ -1,27 +1,23 @@
-import { SpanKind } from "@opentelemetry/api";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-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.",
+ "List score configurations. 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,
- });
-
+ return await runMcpTool({
+ spanName: "mcp.score_configs.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ },
+ fn: async (span) => {
const result = await listScoreConfigs({
projectId: context.projectId,
page: input.page,
@@ -31,7 +27,7 @@ export const [listScoreConfigsTool, handleListScoreConfigs] = defineTool({
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
index 705bde3755..fcca2e9b26 100644
--- a/web/src/features/mcp/features/scores/tools/listScores.ts
+++ b/web/src/features/mcp/features/scores/tools/listScores.ts
@@ -1,4 +1,3 @@
-import { SpanKind } from "@opentelemetry/api";
import {
filterAndValidateV2GetScoreList,
InvalidRequestError,
@@ -7,10 +6,11 @@ import {
singleFilter,
publicApiPaginationZod,
} from "@langfuse/shared";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { z } from "zod";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";
+import { paginationMeta } from "../../publicApi";
const ScoreFieldsSchema = z
.array(z.enum(["score", "trace"]))
@@ -72,27 +72,24 @@ const assertValidScoreFields = (input: ListScoresInput) => {
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.",
+ "Find scores in Langfuse.",
+ "Use this to review quality, evaluation, or feedback scores for traces, observations, sessions, and dataset runs.",
+ "Filter by score details, time range, environment, source, trace information, or dataset run context to narrow the results.",
].join("\n"),
baseSchema: ListScoresInputSchema,
inputSchema: ListScoresInputSchema,
handler: async (input, context) => {
- return await instrumentAsync(
- { name: "mcp.scores.list", spanKind: SpanKind.INTERNAL },
- async (span) => {
+ return await runMcpTool({
+ spanName: "mcp.scores.list",
+ context,
+ attributes: {
+ "mcp.pagination_page": input.page,
+ "mcp.pagination_limit": input.limit,
+ "mcp.score_fields": input.fields.join(","),
+ },
+ fn: 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,
@@ -130,15 +127,14 @@ export const [listScoresTool, handleListScores] = defineTool({
return {
data,
- meta: {
+ meta: paginationMeta({
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
index 675fc6d75e..89d9830ccc 100644
--- a/web/src/features/mcp/features/scores/tools/updateScoreConfig.ts
+++ b/web/src/features/mcp/features/scores/tools/updateScoreConfig.ts
@@ -1,6 +1,5 @@
-import { SpanKind } from "@opentelemetry/api";
-import { instrumentAsync } from "@langfuse/shared/src/server";
import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
import { updateScoreConfig } from "@/src/features/public-api/server/score-configs-api-service";
import {
PutScoreConfigBodyWithoutArchived,
@@ -22,20 +21,16 @@ const McpUpdateScoreConfigInputSchema = z
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.",
+ "Update a score configuration. 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) => {
+ return await runMcpTool({
+ spanName: "mcp.score_configs.update",
+ context,
+ attributes: { "mcp.score_config_id": input.configId },
+ fn: async () => {
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,
@@ -43,7 +38,7 @@ export const [updateScoreConfigTool, handleUpdateScoreConfig] = defineTool({
body,
});
},
- );
+ });
},
destructiveHint: true,
});