Skip to content

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

feat(mcp): add health,comments, datasets, annotationqueues models routes (#13783)

Nimar7c501c41b1be
diff --git a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
new file mode 100644
index 0000000000..9767b342a1
--- /dev/null
+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
@@ -0,0 +1,666 @@
+process.env.LANGFUSE_DATASET_SERVICE_READ_FROM_VERSIONED_IMPLEMENTATION =
+ "true";
+process.env.LANGFUSE_DATASET_SERVICE_WRITE_TO_VERSIONED_IMPLEMENTATION = "true";
+
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ const queue = {
+ add: vi.fn().mockResolvedValue(undefined),
+ disconnect: vi.fn(),
+ on: vi.fn(),
+ };
+
+ return {
+ ...actual,
+ EventPropagationQueue: {
+ getInstance: () => queue,
+ },
+ EntityChangeQueue: {
+ getInstance: () => queue,
+ },
+ DatasetRunItemUpsertQueue: {
+ getInstance: () => queue,
+ },
+ DatasetDeleteQueue: {
+ getInstance: () => queue,
+ },
+ };
+});
+
+import { v4 as uuidv4 } from "uuid";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ createObservation,
+ createObservationsCh,
+ createDatasetRunItem,
+ createDatasetRunItemsCh,
+ createTrace,
+ createTracesCh,
+} from "@langfuse/shared/src/server";
+import {
+ createMcpTestSetup,
+ createPromptInDb,
+ mockServerContext,
+ waitFor,
+} from "./mcp-helpers";
+import "@/src/features/mcp/server/bootstrap";
+import { config as mcpRouteConfig } from "@/src/pages/api/public/mcp";
+import { toolRegistry } from "@/src/features/mcp/server/registry";
+import {
+ handleCreateAnnotationQueue,
+ handleCreateAnnotationQueueAssignment,
+ handleCreateAnnotationQueueItem,
+ handleDeleteAnnotationQueueAssignment,
+ handleDeleteAnnotationQueueItem,
+ handleGetAnnotationQueue,
+ handleGetAnnotationQueueItem,
+ handleListAnnotationQueueItems,
+ handleListAnnotationQueues,
+ handleUpdateAnnotationQueueItem,
+} from "@/src/features/mcp/features/annotationQueues/tools";
+import {
+ handleCreateComment,
+ handleGetComment,
+ handleListComments,
+} from "@/src/features/mcp/features/comments/tools";
+import {
+ handleCreateDataset,
+ handleCreateDatasetItem,
+ handleCreateDatasetRunItem,
+ handleDeleteDatasetItem,
+ handleDeleteDatasetRun,
+ handleGetDataset,
+ handleGetDatasetItem,
+ handleGetDatasetRun,
+ handleListDatasetItems,
+ handleListDatasetRunItems,
+ handleListDatasetRuns,
+ handleListDatasets,
+} from "@/src/features/mcp/features/datasets/tools";
+import { handleGetHealth } from "@/src/features/mcp/features/health/tools";
+import {
+ handleCreateModel,
+ handleDeleteModel,
+ handleGetModel,
+ handleListModels,
+} from "@/src/features/mcp/features/models/tools";
+import { handleCreateScoreConfig } from "@/src/features/mcp/features/scores/tools/createScoreConfig";
+import { handleGetScoreConfig } from "@/src/features/mcp/features/scores/tools/getScoreConfig";
+import { handleListScoreConfigs } from "@/src/features/mcp/features/scores/tools/listScoreConfigs";
+import { handleUpdateScoreConfig } from "@/src/features/mcp/features/scores/tools/updateScoreConfig";
+
+const createScoreConfig = async (projectId: string) =>
+ prisma.scoreConfig.create({
+ data: {
+ id: uuidv4(),
+ projectId,
+ name: `mcp-score-${uuidv4().slice(0, 8)}`,
+ dataType: "NUMERIC",
+ },
+ });
+
+const createProjectUser = async ({
+ orgId,
+ projectId,
+}: {
+ orgId: string;
+ projectId: string;
+}) => {
+ const user = await prisma.user.create({
+ data: {
+ id: uuidv4(),
+ email: `mcp-user-${uuidv4()}@example.com`,
+ name: "MCP Test User",
+ },
+ });
+
+ const orgMembership = await prisma.organizationMembership.create({
+ data: {
+ orgId,
+ userId: user.id,
+ role: "MEMBER",
+ },
+ });
+
+ await prisma.projectMembership.create({
+ data: {
+ projectId,
+ userId: user.id,
+ role: "MEMBER",
+ orgMembershipId: orgMembership.id,
+ },
+ });
+
+ return user;
+};
+
+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);
+
+ expect(toolNames).toEqual(
+ expect.arrayContaining([
+ "listAnnotationQueues",
+ "createAnnotationQueue",
+ "createComment",
+ "listDatasets",
+ "getHealth",
+ "listScores",
+ "getScore",
+ "createModel",
+ "createScoreConfig",
+ ]),
+ );
+
+ const inAppToolNames = (
+ await toolRegistry.getToolDefinitions(
+ mockServerContext({ isInAppAgentKey: true }),
+ )
+ ).map((tool) => tool.name);
+
+ 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");
+
+ expect(mcpRouteConfig.api.bodyParser.sizeLimit).toBe("4.5mb");
+ });
+
+ it("covers annotation queue public API routes", async () => {
+ const { context, projectId, orgId } = await createMcpTestSetup();
+ const scoreConfig = await createScoreConfig(projectId);
+ const user = await createProjectUser({ orgId, projectId });
+
+ const queue = (await handleCreateAnnotationQueue(
+ {
+ name: `mcp-queue-${uuidv4()}`,
+ description: "MCP queue",
+ scoreConfigIds: [scoreConfig.id],
+ },
+ context,
+ )) as { id: string; name: string };
+
+ const queues = (await handleListAnnotationQueues(
+ { page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string }> };
+ expect(queues.data.map((item) => item.id)).toContain(queue.id);
+
+ await expect(
+ handleGetAnnotationQueue({ queueId: queue.id }, context),
+ ).resolves.toMatchObject({ id: queue.id, name: queue.name });
+
+ const queueItem = (await handleCreateAnnotationQueueItem(
+ {
+ queueId: queue.id,
+ objectId: uuidv4(),
+ objectType: "TRACE",
+ },
+ context,
+ )) as { id: string; status: string };
+ expect(queueItem.status).toBe("PENDING");
+
+ const queueItems = (await handleListAnnotationQueueItems(
+ { queueId: queue.id, page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string }> };
+ expect(queueItems.data.map((item) => item.id)).toContain(queueItem.id);
+
+ await expect(
+ handleGetAnnotationQueueItem(
+ { queueId: queue.id, itemId: queueItem.id },
+ context,
+ ),
+ ).resolves.toMatchObject({ id: queueItem.id, queueId: queue.id });
+
+ await expect(
+ handleUpdateAnnotationQueueItem(
+ { queueId: queue.id, itemId: queueItem.id, status: "COMPLETED" },
+ context,
+ ),
+ ).resolves.toMatchObject({ id: queueItem.id, status: "COMPLETED" });
+
+ await expect(
+ handleCreateAnnotationQueueAssignment(
+ { queueId: queue.id, userId: user.id },
+ context,
+ ),
+ ).resolves.toMatchObject({
+ queueId: queue.id,
+ userId: user.id,
+ projectId,
+ });
+
+ const assignment = await prisma.annotationQueueAssignment.findUniqueOrThrow(
+ {
+ where: {
+ projectId_queueId_userId: {
+ projectId,
+ queueId: queue.id,
+ userId: user.id,
+ },
+ },
+ },
+ );
+ const assignmentAuditLogCount = await prisma.auditLog.count({
+ where: {
+ resourceType: "annotationQueueAssignment",
+ resourceId: assignment.id,
+ action: "create",
+ },
+ });
+
+ await expect(
+ handleCreateAnnotationQueueAssignment(
+ { queueId: queue.id, userId: user.id },
+ context,
+ ),
+ ).resolves.toMatchObject({
+ queueId: queue.id,
+ userId: user.id,
+ projectId,
+ });
+
+ await expect(
+ prisma.auditLog.count({
+ where: {
+ resourceType: "annotationQueueAssignment",
+ resourceId: assignment.id,
+ action: "create",
+ },
+ }),
+ ).resolves.toBe(assignmentAuditLogCount);
+
+ const auditLogCreateSpy = vi
+ .spyOn(prisma.auditLog, "create")
+ .mockRejectedValueOnce(new Error("audit failed"));
+
+ try {
+ await expect(
+ handleDeleteAnnotationQueueAssignment(
+ { queueId: queue.id, userId: user.id },
+ context,
+ ),
+ ).rejects.toThrow("An unexpected error occurred");
+ } finally {
+ auditLogCreateSpy.mockRestore();
+ }
+
+ await handleCreateAnnotationQueueAssignment(
+ { queueId: queue.id, userId: user.id },
+ context,
+ );
+
+ await expect(
+ handleDeleteAnnotationQueueAssignment(
+ { queueId: queue.id, userId: user.id },
+ context,
+ ),
+ ).resolves.toEqual({ success: true });
+
+ await expect(
+ handleDeleteAnnotationQueueItem(
+ { queueId: queue.id, itemId: queueItem.id },
+ context,
+ ),
+ ).resolves.toEqual({
+ success: true,
+ message: "Annotation queue item deleted successfully",
+ });
+ });
+
+ it("covers comment and model public API routes", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const prompt = await createPromptInDb({
+ projectId,
+ name: `mcp-comment-prompt-${uuidv4()}`,
+ prompt: "Test prompt",
+ });
+
+ const created = (await handleCreateComment(
+ {
+ objectType: "PROMPT",
+ objectId: prompt.id,
+ content: "MCP comment",
+ },
+ context,
+ )) as { id: string };
+
+ const listed = (await handleListComments(
+ {
+ objectType: "PROMPT",
+ objectId: prompt.id,
+ page: 1,
+ limit: 10,
+ },
+ context,
+ )) as { data: Array<{ id: string; content: string }> };
+ expect(listed.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: created.id, content: "MCP comment" }),
+ ]),
+ );
+
+ await expect(
+ handleGetComment({ commentId: created.id }, context),
+ ).resolves.toMatchObject({ id: created.id, objectId: prompt.id });
+
+ const modelName = `0000-mcp-model-${uuidv4()}`;
+ const model = (await handleCreateModel(
+ {
+ modelName,
+ matchPattern: `(?i)^${modelName}$`,
+ unit: "TOKENS",
+ inputPrice: 0.001,
+ outputPrice: 0.002,
+ },
+ context,
+ )) as { id: string; modelName: string };
+ expect(model.modelName).toBe(modelName);
+
+ const models = (await handleListModels(
+ { page: 1, limit: 100 },
+ context,
+ )) as { data: Array<{ id: string }> };
+ expect(models.data.map((item) => item.id)).toContain(model.id);
+
+ await expect(
+ handleGetModel({ modelId: model.id }, context),
+ ).resolves.toMatchObject({ id: model.id, modelName });
+
+ await expect(
+ handleDeleteModel({ modelId: model.id }, context),
+ ).resolves.toEqual({ message: "Model successfully deleted" });
+ });
+
+ it("covers dataset, dataset item, run item, and run public API routes", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const datasetName = `mcp-dataset-100% accuracy %20 ${uuidv4()}`;
+ const traceId = uuidv4();
+ const observationId = uuidv4();
+
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ name: "mcp-dataset-trace",
+ user_id: "mcp-user",
+ project_id: projectId,
+ }),
+ ]);
+ await createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ type: "GENERATION",
+ name: "mcp-dataset-generation",
+ start_time: new Date("2026-01-01T00:00:00.000Z").getTime(),
+ end_time: new Date("2026-01-01T00:00:01.000Z").getTime(),
+ }),
+ ]);
+
+ const dataset = (await handleCreateDataset(
+ {
+ name: datasetName,
+ description: "MCP dataset",
+ metadata: { source: "mcp" },
+ },
+ context,
+ )) as { id: string; name: string };
+ expect(dataset.name).toBe(datasetName);
+
+ const datasets = (await handleListDatasets(
+ { page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string }> };
+ expect(datasets.data.map((item) => item.id)).toContain(dataset.id);
+
+ await expect(
+ handleGetDataset({ datasetName }, context),
+ ).resolves.toMatchObject({ id: dataset.id, name: datasetName });
+
+ const datasetItem = (await handleCreateDatasetItem(
+ {
+ datasetName,
+ input: { question: "ping" },
+ expectedOutput: { answer: "pong" },
+ },
+ context,
+ )) as { id: string; datasetName: string };
+ expect(datasetItem.datasetName).toBe(datasetName);
+
+ const datasetItems = (await handleListDatasetItems(
+ { datasetName, page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string }> };
+ expect(datasetItems.data.map((item) => item.id)).toContain(datasetItem.id);
+
+ await expect(
+ handleGetDatasetItem({ datasetItemId: datasetItem.id }, context),
+ ).resolves.toMatchObject({ id: datasetItem.id, datasetName });
+
+ const runName = `mcp-run-50% accuracy %20 ${uuidv4()}`;
+ const runItem = (await handleCreateDatasetRunItem(
+ {
+ datasetItemId: datasetItem.id,
+ traceId,
+ observationId,
+ runName,
+ runDescription: "MCP run",
+ metadata: { source: "mcp" },
+ },
+ context,
+ )) as { id: string; datasetRunId: string; datasetItemId: string };
+ expect(runItem.datasetItemId).toBe(datasetItem.id);
+
+ await createDatasetRunItemsCh([
+ createDatasetRunItem({
+ id: runItem.id,
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ dataset_run_id: runItem.datasetRunId,
+ dataset_item_id: datasetItem.id,
+ dataset_id: dataset.id,
+ dataset_run_name: runName,
+ }),
+ ]);
+
+ await waitFor(async () => {
+ const runItems = (await handleListDatasetRunItems(
+ { datasetId: dataset.id, runName, page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string }> };
+
+ return runItems.data.some((item) => item.id === runItem.id);
+ });
+
+ const datasetRuns = (await handleListDatasetRuns(
+ { name: datasetName, page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string; name: string }> };
+ expect(datasetRuns.data).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: runItem.datasetRunId, name: runName }),
+ ]),
+ );
+
+ await expect(
+ handleGetDatasetRun({ name: datasetName, runName }, context),
+ ).resolves.toMatchObject({
+ id: runItem.datasetRunId,
+ name: runName,
+ datasetRunItems: expect.arrayContaining([
+ expect.objectContaining({ id: runItem.id }),
+ ]),
+ });
+
+ await expect(
+ handleDeleteDatasetRun({ name: datasetName, runName }, context),
+ ).resolves.toEqual({ message: "Dataset run successfully deleted" });
+
+ await expect(
+ handleDeleteDatasetItem({ datasetItemId: datasetItem.id }, context),
+ ).resolves.toEqual({ message: "Dataset item successfully deleted" });
+ });
+
+ it("covers health public API route and cross-project recent-event checks", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(handleGetHealth({}, context)).resolves.toMatchObject({
+ status: "OK",
+ version: expect.any(String),
+ });
+
+ const { projectId: otherProjectId } = await createMcpTestSetup();
+ const traceId = uuidv4();
+
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: otherProjectId,
+ }),
+ ]);
+ await createObservationsCh([
+ createObservation({
+ id: uuidv4(),
+ trace_id: traceId,
+ project_id: otherProjectId,
+ }),
+ ]);
+
+ await expect(
+ handleGetHealth({ failIfNoRecentEvents: true }, context),
+ ).resolves.toMatchObject({
+ status: "OK",
+ version: expect.any(String),
+ });
+ });
+
+ it("rejects cross-project access to project-scoped MCP resources", async () => {
+ const { context: sourceContext, projectId: sourceProjectId } =
+ await createMcpTestSetup();
+ const { context: targetContext } = await createMcpTestSetup();
+
+ const scoreConfig = await createScoreConfig(sourceProjectId);
+ const queue = (await handleCreateAnnotationQueue(
+ {
+ name: `mcp-queue-isolation-${uuidv4()}`,
+ scoreConfigIds: [scoreConfig.id],
+ },
+ sourceContext,
+ )) as { id: string };
+
+ await expect(
+ handleGetAnnotationQueue({ queueId: queue.id }, targetContext),
+ ).rejects.toThrow("Annotation queue not found");
+
+ const datasetName = `mcp-dataset-isolation-${uuidv4()}`;
+ const dataset = (await handleCreateDataset(
+ { name: datasetName },
+ sourceContext,
+ )) as { id: string };
+
+ await expect(
+ handleGetDataset({ datasetName }, targetContext),
+ ).rejects.toThrow("Dataset not found");
+ await expect(
+ handleListDatasetRunItems(
+ { datasetId: dataset.id, runName: "missing", page: 1, limit: 10 },
+ targetContext,
+ ),
+ ).rejects.toThrow("Dataset run not found");
+
+ const prompt = await createPromptInDb({
+ projectId: sourceProjectId,
+ name: `mcp-comment-isolation-${uuidv4()}`,
+ prompt: "Test prompt",
+ });
+ const comment = (await handleCreateComment(
+ {
+ objectType: "PROMPT",
+ objectId: prompt.id,
+ content: "MCP isolated comment",
+ },
+ sourceContext,
+ )) as { id: string };
+
+ await expect(
+ handleGetComment({ commentId: comment.id }, targetContext),
+ ).rejects.toThrow("Comment not found within authorized project");
+
+ const modelName = `mcp-model-isolation-${uuidv4()}`;
+ const model = (await handleCreateModel(
+ {
+ modelName,
+ matchPattern: `(?i)^${modelName}$`,
+ unit: "TOKENS",
+ inputPrice: 0.001,
+ outputPrice: 0.002,
+ },
+ sourceContext,
+ )) as { id: string };
+
+ await expect(
+ handleGetModel({ modelId: model.id }, targetContext),
+ ).rejects.toThrow("No model with this id found");
+
+ await expect(
+ handleGetScoreConfig({ configId: scoreConfig.id }, targetContext),
+ ).rejects.toThrow("Score config not found within authorized project");
+ await expect(
+ handleUpdateScoreConfig(
+ { configId: scoreConfig.id, description: "cross-project update" },
+ targetContext,
+ ),
+ ).rejects.toThrow("Score config not found within authorized project");
+ });
+
+ it("covers score config public API routes", async () => {
+ const { context } = await createMcpTestSetup();
+ const scoreConfigName = `mcp-score-${uuidv4().slice(0, 8)}`;
+
+ const scoreConfig = (await handleCreateScoreConfig(
+ {
+ name: scoreConfigName,
+ dataType: "NUMERIC",
+ minValue: 0,
+ maxValue: 1,
+ },
+ context,
+ )) as { id: string; name: string };
+ expect(scoreConfig.name).toBe(scoreConfigName);
+
+ const scoreConfigs = (await handleListScoreConfigs(
+ { page: 1, limit: 10 },
+ context,
+ )) as { data: Array<{ id: string }> };
+ expect(scoreConfigs.data.map((item) => item.id)).toContain(scoreConfig.id);
+
+ await expect(
+ handleGetScoreConfig({ configId: scoreConfig.id }, context),
+ ).resolves.toMatchObject({ id: scoreConfig.id, name: scoreConfigName });
+
+ await expect(
+ handleUpdateScoreConfig({ configId: scoreConfig.id }, context),
+ ).rejects.toThrow("Request body cannot be empty");
+
+ await expect(
+ handleUpdateScoreConfig(
+ {
+ configId: scoreConfig.id,
+ description: "Updated through MCP",
+ },
+ context,
+ ),
+ ).resolves.toMatchObject({
+ id: scoreConfig.id,
+ description: "Updated through MCP",
+ });
+ });
+});
diff --git a/web/src/features/mcp/features/annotationQueues/index.ts b/web/src/features/mcp/features/annotationQueues/index.ts
new file mode 100644
index 0000000000..de323295ef
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/index.ts
@@ -0,0 +1,75 @@
+import type { McpFeatureModule } from "../../server/registry";
+import {
+ createAnnotationQueueAssignmentTool,
+ createAnnotationQueueItemTool,
+ createAnnotationQueueTool,
+ deleteAnnotationQueueAssignmentTool,
+ deleteAnnotationQueueItemTool,
+ getAnnotationQueueItemTool,
+ getAnnotationQueueTool,
+ handleCreateAnnotationQueue,
+ handleCreateAnnotationQueueAssignment,
+ handleCreateAnnotationQueueItem,
+ handleDeleteAnnotationQueueAssignment,
+ handleDeleteAnnotationQueueItem,
+ handleGetAnnotationQueue,
+ handleGetAnnotationQueueItem,
+ handleListAnnotationQueueItems,
+ handleListAnnotationQueues,
+ handleUpdateAnnotationQueueItem,
+ listAnnotationQueueItemsTool,
+ listAnnotationQueuesTool,
+ updateAnnotationQueueItemTool,
+} from "./tools";
+
+export const annotationQueuesFeature: McpFeatureModule = {
+ name: "annotationQueues",
+ description:
+ "Manage annotation queues, worklists of trace or observation items for human review and scoring, plus user assignments",
+ tools: [
+ {
+ definition: listAnnotationQueuesTool,
+ handler: handleListAnnotationQueues,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: createAnnotationQueueTool,
+ handler: handleCreateAnnotationQueue,
+ },
+ {
+ definition: getAnnotationQueueTool,
+ handler: handleGetAnnotationQueue,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: listAnnotationQueueItemsTool,
+ handler: handleListAnnotationQueueItems,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getAnnotationQueueItemTool,
+ handler: handleGetAnnotationQueueItem,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: createAnnotationQueueItemTool,
+ handler: handleCreateAnnotationQueueItem,
+ },
+ {
+ definition: updateAnnotationQueueItemTool,
+ handler: handleUpdateAnnotationQueueItem,
+ },
+ {
+ definition: deleteAnnotationQueueItemTool,
+ handler: handleDeleteAnnotationQueueItem,
+ },
+ {
+ definition: createAnnotationQueueAssignmentTool,
+ handler: handleCreateAnnotationQueueAssignment,
+ },
+ {
+ definition: deleteAnnotationQueueAssignmentTool,
+ handler: handleDeleteAnnotationQueueAssignment,
+ },
+ ],
+};
diff --git a/web/src/features/mcp/features/annotationQueues/tools.ts b/web/src/features/mcp/features/annotationQueues/tools.ts
new file mode 100644
index 0000000000..e379b3eb52
--- /dev/null
+++ b/web/src/features/mcp/features/annotationQueues/tools.ts
@@ -0,0 +1,682 @@
+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/comments/index.ts b/web/src/features/mcp/features/comments/index.ts
new file mode 100644
index 0000000000..b8e3919f42
--- /dev/null
+++ b/web/src/features/mcp/features/comments/index.ts
@@ -0,0 +1,27 @@
+import type { McpFeatureModule } from "../../server/registry";
+import {
+ createCommentTool,
+ getCommentTool,
+ handleCreateComment,
+ handleGetComment,
+ handleListComments,
+ listCommentsTool,
+} from "./tools";
+
+export const commentsFeature: McpFeatureModule = {
+ name: "comments",
+ description: "Create and inspect comments",
+ tools: [
+ { definition: createCommentTool, handler: handleCreateComment },
+ {
+ definition: listCommentsTool,
+ handler: handleListComments,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getCommentTool,
+ handler: handleGetComment,
+ allowInAppAgentKey: true,
+ },
+ ],
+};
diff --git a/web/src/features/mcp/features/comments/tools.ts b/web/src/features/mcp/features/comments/tools.ts
new file mode 100644
index 0000000000..9811a53237
--- /dev/null
+++ b/web/src/features/mcp/features/comments/tools.ts
@@ -0,0 +1,173 @@
+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/datasets/index.ts b/web/src/features/mcp/features/datasets/index.ts
new file mode 100644
index 0000000000..e68e774c8f
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/index.ts
@@ -0,0 +1,78 @@
+import type { McpFeatureModule } from "../../server/registry";
+import {
+ createDatasetItemTool,
+ createDatasetRunItemTool,
+ createDatasetTool,
+ deleteDatasetItemTool,
+ deleteDatasetRunTool,
+ getDatasetItemTool,
+ getDatasetRunTool,
+ getDatasetTool,
+ handleCreateDataset,
+ handleCreateDatasetItem,
+ handleCreateDatasetRunItem,
+ handleDeleteDatasetItem,
+ handleDeleteDatasetRun,
+ handleGetDataset,
+ handleGetDatasetItem,
+ handleGetDatasetRun,
+ handleListDatasetItems,
+ handleListDatasetRunItems,
+ handleListDatasetRuns,
+ handleListDatasets,
+ listDatasetItemsTool,
+ listDatasetRunItemsTool,
+ listDatasetRunsTool,
+ listDatasetsTool,
+} from "./tools";
+
+export const datasetsFeature: McpFeatureModule = {
+ name: "datasets",
+ description:
+ "Manage datasets, named collections of dataset items for experiments and evaluations, plus runs and run items",
+ tools: [
+ { definition: createDatasetTool, handler: handleCreateDataset },
+ {
+ definition: listDatasetsTool,
+ handler: handleListDatasets,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getDatasetTool,
+ handler: handleGetDataset,
+ allowInAppAgentKey: true,
+ },
+ { definition: createDatasetItemTool, handler: handleCreateDatasetItem },
+ {
+ definition: listDatasetItemsTool,
+ handler: handleListDatasetItems,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getDatasetItemTool,
+ handler: handleGetDatasetItem,
+ allowInAppAgentKey: true,
+ },
+ { definition: deleteDatasetItemTool, handler: handleDeleteDatasetItem },
+ {
+ definition: createDatasetRunItemTool,
+ handler: handleCreateDatasetRunItem,
+ },
+ {
+ definition: listDatasetRunItemsTool,
+ handler: handleListDatasetRunItems,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: listDatasetRunsTool,
+ handler: handleListDatasetRuns,
+ allowInAppAgentKey: true,
+ },
+ {
+ definition: getDatasetRunTool,
+ handler: handleGetDatasetRun,
+ allowInAppAgentKey: true,
+ },
+ { definition: deleteDatasetRunTool, handler: handleDeleteDatasetRun },
+ ],
+};
diff --git a/web/src/features/mcp/features/datasets/tools.ts b/web/src/features/mcp/features/datasets/tools.ts
new file mode 100644
index 0000000000..609b9c0cb4
--- /dev/null
+++ b/web/src/features/mcp/features/datasets/tools.ts
@@ -0,0 +1,807 @@
+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/health/index.ts b/web/src/features/mcp/features/health/index.ts
new file mode 100644
index 0000000000..9de48fcb78
--- /dev/null
+++ b/web/src/features/mcp/features/health/index.ts
@@ -0,0 +1,14 @@
+import type { McpFeatureModule } from "../../server/registry";
+import { getHealthTool, handleGetHealth } from "./tools";
+
+export const healthFeature: McpFeatureModule = {
+ name: "health",
+ description: "Check Langfuse health",
+ tools: [
+ {
+ definition: getHealthTool,
+ handler: handleGetHealth,
+ allowInAppAgentKey: true,
+ },
+ ],
+};
diff --git a/web/src/features/mcp/features/health/tools.ts b/web/src/features/mcp/features/health/tools.ts
new file mode 100644
index 0000000000..f27ddfcfce
--- /dev/null
+++ b/web/src/features/mcp/features/health/tools.ts
@@ -0,0 +1,119 @@
+import { z } from "zod";
+import { VERSION } from "@/src/constants";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ convertDateToClickhouseDateTime,
+ logger,
+ measureAndReturn,
+ queryClickhouse,
+ traceException,
+} from "@langfuse/shared/src/server";
+import { defineTool } from "../../core/define-tool";
+import { runPublicApiTool } from "../publicApi";
+
+const HealthInputSchema = z.object({
+ failIfDatabaseUnavailable: z.boolean().optional().default(false),
+ failIfNoRecentEvents: z.boolean().optional().default(false),
+});
+
+const HealthResponseSchema = z
+ .object({
+ status: z.string(),
+ version: z.string(),
+ })
+ .strict();
+
+export const [getHealthTool, handleGetHealth] = defineTool({
+ name: "getHealth",
+ description:
+ "Check Langfuse API health. Optionally verify database availability and recent trace/observation ingestion.",
+ baseSchema: HealthInputSchema,
+ inputSchema: HealthInputSchema,
+ handler: async (input, context) =>
+ runPublicApiTool({
+ spanName: "mcp.health.get",
+ context,
+ fn: async () => {
+ const version = VERSION.replace("v", "");
+
+ try {
+ if (input.failIfDatabaseUnavailable) {
+ await prisma.$queryRaw`SELECT 1;`;
+ }
+ } catch (error) {
+ logger.error("Couldn't connect to database", error);
+ traceException(error);
+ return HealthResponseSchema.parse({
+ status: "Database not available",
+ version,
+ });
+ }
+
+ try {
+ if (input.failIfNoRecentEvents) {
+ const now = new Date();
+ const traces = await measureAndReturn({
+ operationName: "healthCheckTraces",
+ projectId: "__CROSS_PROJECT__",
+ input: {
+ now: convertDateToClickhouseDateTime(now),
+ },
+ fn: async (params: { now: string }) =>
+ queryClickhouse<{ id: string }>({
+ query: `
+ SELECT id
+ FROM traces
+ WHERE timestamp <= {now: DateTime64(3)}
+ AND timestamp >= {now: DateTime64(3)} - INTERVAL 3 MINUTE
+ LIMIT 1
+ `,
+ params,
+ tags: {
+ feature: "health-check",
+ type: "trace",
+ },
+ }),
+ });
+ const observations = await queryClickhouse<{ id: string }>({
+ query: `
+ SELECT id
+ FROM observations
+ WHERE start_time <= {now: DateTime64(3)}
+ AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE
+ LIMIT 1
+ `,
+ params: {
+ now: convertDateToClickhouseDateTime(now),
+ },
+ tags: {
+ feature: "health-check",
+ type: "observation",
+ },
+ });
+
+ if (traces.length === 0 || observations.length === 0) {
+ return HealthResponseSchema.parse({
+ status: `No ${
+ traces.length === 0 ? "traces" : "observations"
+ } within the last 3 minutes`,
+ version,
+ });
+ }
+ }
+ } catch (error) {
+ logger.error("Couldn't fetch recent events", error);
+ traceException(error);
+ return HealthResponseSchema.parse({
+ status: "Couldn't fetch recent events",
+ version,
+ });
+ }
+
+ return HealthResponseSchema.parse({
+ status: "OK",
+ version,
+ });
+ },
+ }),
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/models/index.ts b/web/src/features/mcp/features/models/index.ts
new file mode 100644
index 0000000000..f92b19588b
--- /dev/null
+++ b/web/src/features/mcp/features/models/index.ts
@@ -0,0 +1,30 @@
+import type { McpFeatureModule } from "../../server/registry";
+import {
+ createModelTool,
+ deleteModelTool,
+ getModelTool,
+ handleCreateModel,
+ handleDeleteModel,
+ handleGetModel,
+ handleListModels,
+ listModelsTool,
+} from "./tools";
+
+export const modelsFeature: McpFeatureModule = {
+ name: "models",
+ description: "Manage model definitions",
+ tools: [
+ {
+ definition: listModelsTool,
+ handler: handleListModels,
+ allowInAppAgentKey: true,
+ },
+ { definition: createModelTool, handler: handleCreateModel },
+ {
+ definition: getModelTool,
+ handler: handleGetModel,
+ allowInAppAgentKey: true,
+ },
+ { definition: deleteModelTool, handler: handleDeleteModel },
+ ],
+};
diff --git a/web/src/features/mcp/features/models/tools.ts b/web/src/features/mcp/features/models/tools.ts
new file mode 100644
index 0000000000..151f5834d8
--- /dev/null
+++ b/web/src/features/mcp/features/models/tools.ts
@@ -0,0 +1,313 @@
+import { InvalidRequestError, LangfuseNotFoundError } 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,
+});
+
+export const [createModelTool, handleCreateModel] = defineTool({
+ name: "createModel",
+ description:
+ "Create a custom model definition for cost tracking/tokenization in the current project.",
+ baseSchema: PostModelsV1Body,
+ inputSchema: PostModelsV1Body,
+ handler: async (input, context) =>
+ runPublicApiTool({
+ spanName: "mcp.models.create",
+ context,
+ attributes: { "mcp.model_name": input.modelName },
+ fn: async () => {
+ const validRegex = await isValidPostgresRegex(
+ input.matchPattern,
+ prisma,
+ );
+ if (!validRegex) {
+ throw new InvalidRequestError(
+ "matchPattern is not a valid regex pattern (Postgres)",
+ );
+ }
+
+ const { tokenizerConfig, pricingTiers: tierData, ...rest } = input;
+
+ const model = await prisma.$transaction(async (tx) => {
+ const existingModelName = await tx.model.findFirst({
+ where: {
+ projectId: context.projectId,
+ modelName: input.modelName,
+ },
+ });
+
+ if (existingModelName) {
+ throw new InvalidRequestError(
+ `Model name '${input.modelName}' already exists in project`,
+ );
+ }
+
+ const createdModel = await tx.model.create({
+ data: {
+ ...rest,
+ tokenizerConfig: tokenizerConfig ?? undefined,
+ projectId: context.projectId,
+ },
+ });
+
+ if (tierData && tierData.length > 0) {
+ for (const tier of tierData) {
+ const createdTier = await tx.pricingTier.create({
+ data: {
+ modelId: createdModel.id,
+ name: tier.name,
+ isDefault: tier.isDefault,
+ priority: tier.priority,
+ conditions: tier.conditions,
+ },
+ });
+
+ await Promise.all(
+ Object.entries(tier.prices).map(([usageType, price]) =>
+ tx.price.create({
+ data: {
+ modelId: createdModel.id,
+ projectId: createdModel.projectId,
+ pricingTierId: createdTier.id,
+ usageType,
+ price: new Prisma.Decimal(price),
+ },
+ }),
+ ),
+ );
+ }
+ } else {
+ const defaultTierId = `${createdModel.id}_tier_default`;
+ const defaultTier = await tx.pricingTier.create({
+ data: {
+ id: defaultTierId,
+ modelId: createdModel.id,
+ name: "Standard",
+ isDefault: true,
+ priority: 0,
+ conditions: [],
+ },
+ });
+
+ const prices = [
+ { usageType: "input", price: input.inputPrice },
+ { usageType: "output", price: input.outputPrice },
+ { usageType: "total", price: input.totalPrice },
+ ];
+
+ await Promise.all(
+ prices
+ .filter(({ price }) => price != null)
+ .map(({ usageType, price }) =>
+ tx.price.create({
+ data: {
+ modelId: createdModel.id,
+ projectId: createdModel.projectId,
+ pricingTierId: defaultTier.id,
+ usageType,
+ price: new Prisma.Decimal(price as number),
+ },
+ }),
+ ),
+ );
+ }
+
+ await auditLog({
+ action: "create",
+ resourceType: "model",
+ resourceId: createdModel.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: createdModel,
+ });
+
+ return createdModel;
+ });
+
+ await clearModelCacheForProject(context.projectId);
+
+ const modelWithTiers = await prisma.model.findUnique({
+ where: { id: model.id, projectId: context.projectId },
+ include: modelPricingInclude,
+ });
+
+ if (!modelWithTiers) {
+ throw new InvalidRequestError("Failed to fetch created model");
+ }
+
+ return PostModelsV1Response.parse(
+ prismaToApiModelDefinition(modelWithTiers),
+ );
+ },
+ }),
+});
+
+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/publicApi.ts b/web/src/features/mcp/features/publicApi.ts
new file mode 100644
index 0000000000..ca12133963
--- /dev/null
+++ b/web/src/features/mcp/features/publicApi.ts
@@ -0,0 +1,94 @@
+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";
+
+export type McpPublicApiAuth = {
+ validKey: true;
+ scope: {
+ projectId: string;
+ orgId: string;
+ apiKeyId: string;
+ publicKey: string;
+ accessLevel: "project";
+ plan: Plan;
+ rateLimitOverrides: [];
+ isIngestionSuspended: false;
+ isInAppAgentKey: boolean;
+ };
+};
+
+export const getMcpPublicApiAuth = async (
+ context: ServerContext,
+): Promise<McpPublicApiAuth> => {
+ const org = await prisma.organization.findUnique({
+ where: { id: context.orgId },
+ select: { cloudConfig: true },
+ });
+
+ const cloudConfig = org?.cloudConfig
+ ? CloudConfigSchema.parse(org.cloudConfig)
+ : undefined;
+
+ return {
+ validKey: true,
+ scope: {
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ publicKey: context.publicKey,
+ accessLevel: "project",
+ plan: getOrganizationPlanServerSide(cloudConfig),
+ rateLimitOverrides: [],
+ isIngestionSuspended: false,
+ isInAppAgentKey: context.isInAppAgentKey === true,
+ },
+ };
+};
+
+export const paginationMeta = ({
+ page,
+ limit,
+ totalItems,
+}: {
+ page: number;
+ limit: number;
+ totalItems: number;
+}) => ({
+ page,
+ limit,
+ 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/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
index 9ef8d3e463..056fba641e 100644
--- a/web/src/features/mcp/server/bootstrap.ts
+++ b/web/src/features/mcp/server/bootstrap.ts
@@ -13,10 +13,14 @@
import { toolRegistry } from "./registry";
import { promptsFeature } from "../features/prompts";
import { observationsFeature } from "../features/observations";
+import { annotationQueuesFeature } from "../features/annotationQueues";
+import { commentsFeature } from "../features/comments";
+import { datasetsFeature } from "../features/datasets";
+import { healthFeature } from "../features/health";
import { scoresFeature } from "../features/scores";
import { metricsFeature } from "../features/metrics";
+import { modelsFeature } from "../features/models";
// Import future features as they're added:
-// import { datasetsFeature } from "../features/datasets";
// import { tracesFeature } from "../features/traces";
// import { evalsFeature } from "../features/evals";
@@ -30,11 +34,15 @@ export function bootstrapMcpFeatures(): void {
// Register all feature modules
toolRegistry.register(promptsFeature);
toolRegistry.register(observationsFeature);
+ toolRegistry.register(annotationQueuesFeature);
+ toolRegistry.register(commentsFeature);
+ toolRegistry.register(datasetsFeature);
+ toolRegistry.register(healthFeature);
toolRegistry.register(scoresFeature);
toolRegistry.register(metricsFeature);
+ toolRegistry.register(modelsFeature);
// Add future features here:
- // toolRegistry.register(datasetsFeature);
// toolRegistry.register(tracesFeature);
// toolRegistry.register(evalsFeature);
}
diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.ts
index 9b9aaaf0e2..528463aad1 100644
--- a/web/src/pages/api/public/mcp/index.ts
+++ b/web/src/pages/api/public/mcp/index.ts
@@ -177,7 +177,7 @@ export default async function handler(
export const config = {
api: {
bodyParser: {
- sizeLimit: "1mb",
+ sizeLimit: "4.5mb",
},
},
};