Skip to content

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

feat(mcp): Model Context Protocol server implementation (#10552)

Michael Fröhlichf78588129e0b
diff --git a/packages/shared/src/features/prompts/constants.ts b/packages/shared/src/features/prompts/constants.ts
index 565d948730..84cc441ca0 100644
--- a/packages/shared/src/features/prompts/constants.ts
+++ b/packages/shared/src/features/prompts/constants.ts
@@ -1,3 +1,16 @@
export const PRODUCTION_LABEL = "production";
export const LATEST_PROMPT_LABEL = "latest";
export const COMMIT_MESSAGE_MAX_LENGTH = 500;
+
+// Prompt name validation
+export const PROMPT_NAME_MAX_LENGTH = 255;
+export const RESERVED_PROMPT_NAME_NEW = "new";
+export const PROMPT_NAME_PIPE_RESTRICTION_REGEX = /^[^|]*$/;
+export const PROMPT_NAME_PIPE_RESTRICTION_ERROR =
+ "Prompt name cannot contain '|' character";
+
+// Prompt label validation
+export const PROMPT_LABEL_MAX_LENGTH = 36;
+export const PROMPT_LABEL_REGEX = /^[a-z0-9_\-.]+$/;
+export const PROMPT_LABEL_REGEX_ERROR =
+ "Label must be lowercase alphanumeric with optional underscores, hyphens, or periods";
diff --git a/packages/shared/src/features/prompts/types.ts b/packages/shared/src/features/prompts/types.ts
index 45fedc022a..3ce7618c1d 100644
--- a/packages/shared/src/features/prompts/types.ts
+++ b/packages/shared/src/features/prompts/types.ts
@@ -1,7 +1,12 @@
import { z } from "zod/v4";
import type { Prompt } from "../../../prisma/generated/types";
import { jsonSchema } from "../../utils/zod";
-import { COMMIT_MESSAGE_MAX_LENGTH } from "./constants";
+import {
+ COMMIT_MESSAGE_MAX_LENGTH,
+ PROMPT_LABEL_MAX_LENGTH,
+ PROMPT_LABEL_REGEX,
+ PROMPT_LABEL_REGEX_ERROR,
+} from "./constants";
import { PromptChatMessageSchema } from "../../server/llm/types";
import { PromptNameSchema } from "./validation";
@@ -18,11 +23,8 @@ export enum PromptType {
export const PromptLabelSchema = z
.string()
.min(1)
- .max(36)
- .regex(
- /^[a-z0-9_\-.]+$/,
- "Label must be lowercase alphanumeric with optional underscores, hyphens, or periods",
- );
+ .max(PROMPT_LABEL_MAX_LENGTH)
+ .regex(PROMPT_LABEL_REGEX, PROMPT_LABEL_REGEX_ERROR);
const BaseCreateTextPromptSchema = z.object({
name: PromptNameSchema,
diff --git a/packages/shared/src/features/prompts/validation.ts b/packages/shared/src/features/prompts/validation.ts
index 6ab25de3ca..712532a5ed 100644
--- a/packages/shared/src/features/prompts/validation.ts
+++ b/packages/shared/src/features/prompts/validation.ts
@@ -1,14 +1,22 @@
import { StringNoHTMLNonEmpty } from "../../utils/zod";
import { withFolderPathValidation } from "../folders/validation";
+import {
+ PROMPT_NAME_PIPE_RESTRICTION_REGEX,
+ PROMPT_NAME_PIPE_RESTRICTION_ERROR,
+ RESERVED_PROMPT_NAME_NEW,
+} from "./constants";
/**
* Prompt name validation schema for API, tRPC and client
*/
export const PromptNameSchema = withFolderPathValidation(
StringNoHTMLNonEmpty.regex(
- /^[^|]*$/,
+ PROMPT_NAME_PIPE_RESTRICTION_REGEX,
// Note: pipe character is used for prompt composition
- "Prompt name cannot contain '|' character",
+ PROMPT_NAME_PIPE_RESTRICTION_ERROR,
),
// Note: we use "new" as a special name for the new prompt form
-).refine((name) => name !== "new", "Prompt name cannot be 'new'");
+).refine(
+ (name) => name !== RESERVED_PROMPT_NAME_NEW,
+ `Prompt name cannot be '${RESERVED_PROMPT_NAME_NEW}'`,
+);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f6b3b63907..493eda907d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -397,6 +397,9 @@ importers:
'@marsidev/react-turnstile':
specifier: ^0.5.4
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.20.2
+ version: 1.22.0(@cfworker/[email protected])
'@mui/material':
specifier: ^7.3.1
@@ -3181,6 +3184,15 @@ packages:
'@microsoft/[email protected]':
resolution: {integrity: sha512-9b8mPpKrfeGRuhFH5iO1iwCLeIIsV6+H1sRfxbkoGXIyQE2BTsPd9zqSqQJ+pv5sJ/hT5M1zvOFL02MnEezFug==}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-VUpl106XVTCpDmTBil2ehgJZjhyLY2QZikzF8NvTXtLRF1CvO5iEE2UNZdVIUer35vFOwMKYeUGbjJtvPWan3g==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@cfworker/json-schema': ^4.1.1
+ peerDependenciesMeta:
+ '@cfworker/json-schema':
+ optional: true
+
'@mrleebo/[email protected]':
resolution: {integrity: sha512-GTPkYf1meO2UXXIrz/SIDFWz+P4kXo2PTt36LYh/oNxV1PieYi7ZgenQk4IV0ut71Je3Z8ZoNZ8Tr7v2c1X1pg==}
engines: {node: '>=16'}
@@ -8512,6 +8524,14 @@ packages:
resolution: {integrity: sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA==}
engines: {node: '>=14.18'}
+ resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
+ engines: {node: '>=18.0.0'}
+
+ resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}
engines: {node: '>=10'}
@@ -8535,6 +8555,12 @@ packages:
resolution: {integrity: sha512-8QxYTVXUkuy7fIIoitQkPwGonB8F3Zj8eEO8Sqg9Zv/bkI7RJAzowee4gr81Hak/dUTpA2Z7VfQgoijjPNlUZA==}
+ resolution: {integrity: sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==}
+ engines: {node: '>= 16'}
+ peerDependencies:
+ express: '>= 4.11'
+
resolution: {integrity: sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==}
engines: {node: '>= 18'}
@@ -11290,6 +11316,10 @@ packages:
resolution: {integrity: sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==}
+ engines: {node: '>=16.20.0'}
+
resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==}
engines: {node: '>=8'}
@@ -13665,6 +13695,11 @@ packages:
peerDependencies:
zod: ^3.23.3
+ resolution: {integrity: sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ==}
+ peerDependencies:
+ zod: ^3.25 || ^4
+
resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==}
@@ -16141,7 +16176,7 @@ snapshots:
'@bundled-es-modules/[email protected]':
dependencies:
- statuses: 2.0.1
+ statuses: 2.0.2
'@bundled-es-modules/[email protected]':
dependencies:
@@ -17508,6 +17543,26 @@ snapshots:
'@microsoft/[email protected]': {}
+ '@modelcontextprotocol/[email protected](@cfworker/[email protected])':
+ dependencies:
+ ajv: 8.17.1
+ ajv-formats: 3.0.1([email protected])
+ content-type: 1.0.5
+ cors: 2.8.5
+ cross-spawn: 7.0.6
+ eventsource: 3.0.7
+ eventsource-parser: 3.0.6
+ express: 5.1.0
+ express-rate-limit: 7.5.1([email protected])
+ pkce-challenge: 5.0.0
+ raw-body: 3.0.0
+ zod: 3.25.62
+ zod-to-json-schema: 3.25.0([email protected])
+ optionalDependencies:
+ '@cfworker/json-schema': 4.1.1
+ transitivePeerDependencies:
+ - supports-color
+
'@mrleebo/[email protected]':
dependencies:
chevrotain: 10.5.0
@@ -24195,6 +24250,12 @@ snapshots:
+
+ dependencies:
+ eventsource-parser: 3.0.6
+
dependencies:
cross-spawn: 7.0.6
@@ -24233,6 +24294,10 @@ snapshots:
+ dependencies:
+ express: 5.1.0
+
dependencies:
accepts: 2.0.0
@@ -27695,6 +27760,8 @@ snapshots:
+
dependencies:
find-up: 4.1.0
@@ -30459,6 +30526,10 @@ snapshots:
dependencies:
zod: 3.25.62
+ dependencies:
+ zod: 3.25.62
+
diff --git a/web/package.json b/web/package.json
index 5624a85349..1312f5dccc 100644
--- a/web/package.json
+++ b/web/package.json
@@ -43,6 +43,7 @@
"@langfuse/shared": "workspace:*",
"@lezer/highlight": "^1.2.1",
"@marsidev/react-turnstile": "^0.5.4",
+ "@modelcontextprotocol/sdk": "^1.20.2",
"@mui/material": "^7.3.1",
"@mui/x-tree-view": "^8.17.0",
"@next-auth/prisma-adapter": "^1.0.7",
diff --git a/web/src/__tests__/async/mcp-error-formatting.servertest.ts b/web/src/__tests__/async/mcp-error-formatting.servertest.ts
new file mode 100644
index 0000000000..b0d97b5d78
--- /dev/null
+++ b/web/src/__tests__/async/mcp-error-formatting.servertest.ts
@@ -0,0 +1,451 @@
+/** @jest-environment node */
+
+// Mock queue operations to avoid Redis dependency in tests
+jest.mock("@langfuse/shared/src/server", () => {
+ const actual = jest.requireActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ // Mock queue getInstance to return a no-op queue
+ EventPropagationQueue: {
+ getInstance: () => ({
+ add: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn(),
+ }),
+ },
+ };
+});
+
+import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
+import { ZodError } from "zod/v4";
+import { z } from "zod/v4";
+import {
+ formatErrorForUser,
+ wrapErrorHandling,
+} from "@/src/features/mcp/core/error-formatting";
+import { UserInputError, ApiServerError } from "@/src/features/mcp/core/errors";
+import {
+ UnauthorizedError,
+ ForbiddenError,
+ LangfuseNotFoundError,
+ InvalidRequestError,
+ BaseError,
+} from "@langfuse/shared";
+
+describe("MCP Error Formatting", () => {
+ describe("formatErrorForUser", () => {
+ describe("UserInputError handling", () => {
+ it("should format UserInputError as InvalidRequest", () => {
+ const error = new UserInputError("Prompt 'foo' not found");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError).toBeInstanceOf(McpError);
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("Prompt 'foo' not found");
+ });
+
+ it("should preserve UserInputError message exactly", () => {
+ const error = new UserInputError(
+ "Cannot specify both label and version",
+ );
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.message).toContain(
+ "Cannot specify both label and version",
+ );
+ });
+
+ it("should handle UserInputError with special characters", () => {
+ const error = new UserInputError("Invalid name: special!@#$%^&*()");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.message).toContain("Invalid name: special!@#$%^&*()");
+ });
+ });
+
+ describe("ApiServerError handling", () => {
+ it("should format ApiServerError as InternalError with generic message", () => {
+ const error = new ApiServerError("Database connection failed");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError).toBeInstanceOf(McpError);
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ // Should NOT expose internal error message
+ expect(mcpError.message).toContain(
+ "An internal server error occurred.",
+ );
+ expect(mcpError.message).not.toContain("Database");
+ });
+
+ it("should hide sensitive information in ApiServerError", () => {
+ const error = new ApiServerError(
+ "Redis connection to redis://password:secret@host:6379 failed",
+ );
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.message).not.toContain("password");
+ expect(mcpError.message).not.toContain("secret");
+ expect(mcpError.message).not.toContain("redis://");
+ });
+
+ it("should handle ApiServerError with cause", () => {
+ const cause = new Error("Network timeout");
+ const error = new ApiServerError("Service unavailable", { cause });
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ expect(mcpError.message).not.toContain("Network timeout");
+ });
+ });
+
+ describe("ZodError handling", () => {
+ it("should format ZodError as InvalidParams", () => {
+ const schema = z.object({
+ name: z.string(),
+ version: z.number(),
+ });
+
+ let zodError: ZodError | undefined;
+ try {
+ schema.parse({ name: 123, version: "not a number" });
+ } catch (e) {
+ if (e instanceof ZodError) {
+ zodError = e;
+ }
+ }
+
+ expect(zodError).toBeDefined();
+ const mcpError = formatErrorForUser(zodError!);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidParams);
+ expect(mcpError.message).toContain("Validation failed");
+ });
+
+ it("should include field paths in validation error message", () => {
+ const schema = z.object({
+ name: z.string(),
+ config: z.object({
+ temperature: z.number().min(0).max(1),
+ }),
+ });
+
+ let zodError: ZodError | undefined;
+ try {
+ schema.parse({ name: "test", config: { temperature: 2 } });
+ } catch (e) {
+ if (e instanceof ZodError) {
+ zodError = e;
+ }
+ }
+
+ const mcpError = formatErrorForUser(zodError!);
+
+ expect(mcpError.message).toContain("config.temperature");
+ });
+
+ it("should format multiple validation errors", () => {
+ const schema = z.object({
+ name: z.string().min(1),
+ version: z.number().positive(),
+ labels: z.array(z.string()),
+ });
+
+ let zodError: ZodError | undefined;
+ try {
+ schema.parse({ name: "", version: -1, labels: "not an array" });
+ } catch (e) {
+ if (e instanceof ZodError) {
+ zodError = e;
+ }
+ }
+
+ const mcpError = formatErrorForUser(zodError!);
+
+ expect(mcpError.message).toContain("Validation failed");
+ // Should mention multiple issues
+ expect(mcpError.message.split(",").length).toBeGreaterThanOrEqual(2);
+ });
+ });
+
+ describe("Langfuse standard errors", () => {
+ it("should format UnauthorizedError with auth message", () => {
+ const error = new UnauthorizedError("Invalid API key");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("Authentication failed");
+ expect(mcpError.message).toContain("API key");
+ });
+
+ it("should format ForbiddenError with permission message", () => {
+ const error = new ForbiddenError("Access denied");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("forbidden");
+ expect(mcpError.message).toContain("permission");
+ });
+
+ it("should format LangfuseNotFoundError with original message", () => {
+ const error = new LangfuseNotFoundError("Prompt not found: chatbot");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("Prompt not found: chatbot");
+ });
+
+ it("should format InvalidRequestError with original message", () => {
+ const error = new InvalidRequestError(
+ "Cannot delete prompt with dependencies",
+ );
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain(
+ "Cannot delete prompt with dependencies",
+ );
+ });
+
+ it("should format BaseError as InvalidRequest", () => {
+ const error = new BaseError(
+ "Generic base error",
+ 500,
+ "Generic base error",
+ true,
+ );
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ // BaseError is a base class - message handling may vary
+ expect(mcpError).toBeInstanceOf(McpError);
+ });
+ });
+
+ describe("Generic errors", () => {
+ it("should format generic Error as InternalError", () => {
+ const error = new Error("Something went wrong");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ expect(mcpError.message).toContain("An unexpected error occurred.");
+ });
+
+ it("should hide implementation details from generic Error", () => {
+ const error = new Error(
+ "TypeError: Cannot read property 'foo' of undefined",
+ );
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.message).not.toContain("TypeError");
+ expect(mcpError.message).not.toContain("property");
+ expect(mcpError.message).not.toContain("undefined");
+ });
+
+ it("should handle TypeError", () => {
+ const error = new TypeError("Invalid type");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ });
+
+ it("should handle RangeError", () => {
+ const error = new RangeError("Index out of bounds");
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ });
+ });
+
+ describe("Unknown error types", () => {
+ it("should handle string thrown as error", () => {
+ const error = "Something went wrong";
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ expect(mcpError.message).toContain("An unexpected error occurred.");
+ });
+
+ it("should handle number thrown as error", () => {
+ const error = 404;
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ });
+
+ it("should handle null thrown as error", () => {
+ const error = null;
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ });
+
+ it("should handle undefined thrown as error", () => {
+ const error = undefined;
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ });
+
+ it("should handle object thrown as error", () => {
+ const error = { code: "ERR_CUSTOM", message: "Custom error" };
+ const mcpError = formatErrorForUser(error);
+
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ });
+ });
+ });
+
+ describe("wrapErrorHandling", () => {
+ it("should pass through successful function result", async () => {
+ const fn = async () => ({ result: "success" });
+ const wrapped = wrapErrorHandling(fn);
+
+ const result = await wrapped();
+ expect(result).toEqual({ result: "success" });
+ });
+
+ it("should pass through function arguments", async () => {
+ const fn = async (a: number, b: string) => `${a}-${b}`;
+ const wrapped = wrapErrorHandling(fn);
+
+ const result = await wrapped(42, "test");
+ expect(result).toBe("42-test");
+ });
+
+ it("should wrap UserInputError in McpError", async () => {
+ const fn = async () => {
+ throw new UserInputError("Invalid input");
+ };
+ const wrapped = wrapErrorHandling(fn);
+
+ await expect(wrapped()).rejects.toThrow(McpError);
+ try {
+ await wrapped();
+ } catch (e) {
+ const mcpError = e as McpError;
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("Invalid input");
+ }
+ });
+
+ it("should wrap ApiServerError in McpError with generic message", async () => {
+ const fn = async () => {
+ throw new ApiServerError("Database crashed");
+ };
+ const wrapped = wrapErrorHandling(fn);
+
+ await expect(wrapped()).rejects.toThrow(McpError);
+ await expect(wrapped()).rejects.toMatchObject({
+ code: ErrorCode.InternalError,
+ });
+ });
+
+ it("should wrap ZodError in McpError", async () => {
+ const schema = z.object({ name: z.string() });
+ const fn = async () => {
+ schema.parse({ name: 123 });
+ };
+ const wrapped = wrapErrorHandling(fn);
+
+ await expect(wrapped()).rejects.toThrow(McpError);
+ await expect(wrapped()).rejects.toMatchObject({
+ code: ErrorCode.InvalidParams,
+ });
+ });
+
+ it("should wrap generic Error in McpError", async () => {
+ const fn = async () => {
+ throw new Error("Unexpected error");
+ };
+ const wrapped = wrapErrorHandling(fn);
+
+ await expect(wrapped()).rejects.toThrow(McpError);
+ await expect(wrapped()).rejects.toMatchObject({
+ code: ErrorCode.InternalError,
+ });
+ });
+
+ it("should handle async function that returns promise", async () => {
+ const fn = () => Promise.resolve({ data: "async result" });
+ const wrapped = wrapErrorHandling(fn);
+
+ const result = await wrapped();
+ expect(result).toEqual({ data: "async result" });
+ });
+
+ it("should handle rejected promise", async () => {
+ const fn = () => Promise.reject(new UserInputError("Async rejection"));
+ const wrapped = wrapErrorHandling(fn);
+
+ try {
+ await wrapped();
+ } catch (e) {
+ const mcpError = e as McpError;
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ expect(mcpError.message).toContain("Async rejection");
+ }
+ });
+
+ it("should preserve function return type", async () => {
+ interface PromptResult {
+ id: string;
+ name: string;
+ version: number;
+ }
+
+ const fn = async (): Promise<PromptResult> => ({
+ id: "123",
+ name: "test",
+ version: 1,
+ });
+ const wrapped = wrapErrorHandling(fn);
+
+ const result = await wrapped();
+ expect(result.id).toBe("123");
+ expect(result.name).toBe("test");
+ expect(result.version).toBe(1);
+ });
+ });
+
+ describe("Error priority and categorization", () => {
+ it("should categorize user-fixable errors as InvalidRequest", () => {
+ const userErrors = [
+ new UserInputError("Invalid input"),
+ new LangfuseNotFoundError("Not found"),
+ new InvalidRequestError("Bad request"),
+ ];
+
+ for (const error of userErrors) {
+ const mcpError = formatErrorForUser(error);
+ expect(mcpError.code).toBe(ErrorCode.InvalidRequest);
+ }
+ });
+
+ it("should categorize server errors as InternalError", () => {
+ const serverErrors = [
+ new ApiServerError("Database down"),
+ new Error("Generic error"),
+ new TypeError("Type error"),
+ ];
+
+ for (const error of serverErrors) {
+ const mcpError = formatErrorForUser(error);
+ expect(mcpError.code).toBe(ErrorCode.InternalError);
+ }
+ });
+
+ it("should categorize validation errors as InvalidParams", () => {
+ const schema = z.object({ test: z.string() });
+ let zodError: ZodError | undefined;
+ try {
+ schema.parse({ test: 123 });
+ } catch (e) {
+ if (e instanceof ZodError) {
+ zodError = e;
+ }
+ }
+
+ const mcpError = formatErrorForUser(zodError!);
+ expect(mcpError.code).toBe(ErrorCode.InvalidParams);
+ });
+ });
+});
diff --git a/web/src/__tests__/async/mcp-helpers.ts b/web/src/__tests__/async/mcp-helpers.ts
new file mode 100644
index 0000000000..4b5269202b
--- /dev/null
+++ b/web/src/__tests__/async/mcp-helpers.ts
@@ -0,0 +1,277 @@
+/**
+ * MCP Test Helpers
+ *
+ * Shared utilities for testing MCP server tools.
+ * These helpers allow direct testing of tool handlers without HTTP overhead.
+ */
+
+import { prisma } from "@langfuse/shared/src/db";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import type { ServerContext } from "@/src/features/mcp/types";
+
+/**
+ * Creates a complete MCP test setup including:
+ * - Organization
+ * - Project
+ * - API key
+ * - ServerContext for MCP tool handlers
+ */
+export async function createMcpTestSetup(): Promise<{
+ projectId: string;
+ orgId: string;
+ apiKeyId: string;
+ auth: string;
+ context: ServerContext;
+}> {
+ const result = await createOrgProjectAndApiKey();
+ const { projectId, orgId, auth } = result;
+
+ // Extract apiKeyId from created API key
+ const apiKey = await prisma.apiKey.findFirst({
+ where: { projectId, publicKey: result.publicKey },
+ select: { id: true },
+ });
+
+ if (!apiKey) {
+ throw new Error("Failed to create API key for test setup");
+ }
+
+ const context: ServerContext = {
+ projectId,
+ orgId,
+ apiKeyId: apiKey.id,
+ accessLevel: "project",
+ publicKey: result.publicKey,
+ };
+
+ return {
+ projectId,
+ orgId,
+ apiKeyId: apiKey.id,
+ auth,
+ context,
+ };
+}
+
+/**
+ * Creates a mock ServerContext for testing.
+ * Use this when you need a context but don't want to create actual DB records.
+ */
+export function mockServerContext(
+ overrides?: Partial<ServerContext>,
+): ServerContext {
+ return {
+ projectId: overrides?.projectId ?? "test-project-id",
+ orgId: overrides?.orgId ?? "test-org-id",
+ apiKeyId: overrides?.apiKeyId ?? "test-api-key-id",
+ accessLevel: "project",
+ publicKey: overrides?.publicKey ?? "pk-lf-test",
+ ...overrides,
+ };
+}
+
+/**
+ * Verifies that a response follows the MCP content block format.
+ * MCP tools return { content: [{ type: "text", text: "..." }] }
+ */
+export function verifyMcpResponseFormat(
+ response: unknown,
+): asserts response is {
+ content: Array<{ type: "text"; text: string }>;
+} {
+ if (!response || typeof response !== "object") {
+ throw new Error("Response must be an object");
+ }
+
+ const resp = response as Record<string, unknown>;
+
+ if (!Array.isArray(resp.content)) {
+ throw new Error("Response must have 'content' array");
+ }
+
+ if (resp.content.length === 0) {
+ throw new Error("Response content array must not be empty");
+ }
+
+ for (const block of resp.content) {
+ if (typeof block !== "object" || block === null) {
+ throw new Error("Each content block must be an object");
+ }
+
+ const blockTyped = block as Record<string, unknown>;
+
+ if (blockTyped.type !== "text") {
+ throw new Error(
+ `Content block type must be 'text', got: ${blockTyped.type}`,
+ );
+ }
+
+ if (typeof blockTyped.text !== "string") {
+ throw new Error("Content block text must be a string");
+ }
+ }
+}
+
+/**
+ * Extracts the text content from an MCP tool response.
+ * Assumes the response has been validated with verifyMcpResponseFormat.
+ */
+export function extractMcpResponseText(response: {
+ content: Array<{ type: "text"; text: string }>;
+}): string {
+ return response.content.map((block) => block.text).join("");
+}
+
+/**
+ * Parses JSON from an MCP tool response text.
+ * Handles the common case where tool responses are JSON strings.
+ */
+export function parseMcpResponseJson<T = unknown>(response: {
+ content: Array<{ type: "text"; text: string }>;
+}): T {
+ const text = extractMcpResponseText(response);
+ return JSON.parse(text) as T;
+}
+
+/**
+ * Verifies that an audit log entry was created for an MCP operation.
+ * Returns the audit log entry for further assertions.
+ */
+export async function verifyAuditLog(params: {
+ projectId: string;
+ resourceType: string;
+ resourceId?: string;
+ action: "create" | "update" | "delete";
+ apiKeyId: string;
+}): Promise<{
+ id: string;
+ action: string;
+ resourceType: string;
+ resourceId: string;
+ before: unknown;
+ after: unknown;
+}> {
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ projectId: params.projectId,
+ resourceType: params.resourceType,
+ action: params.action,
+ apiKeyId: params.apiKeyId,
+ ...(params.resourceId && { resourceId: params.resourceId }),
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: 1,
+ });
+
+ if (auditLogs.length === 0) {
+ throw new Error(
+ `No audit log found for ${params.action} ${params.resourceType} in project ${params.projectId}`,
+ );
+ }
+
+ const log = auditLogs[0];
+
+ return {
+ id: log.id,
+ action: log.action,
+ resourceType: log.resourceType,
+ resourceId: log.resourceId,
+ before: log.before,
+ after: log.after,
+ };
+}
+
+/**
+ * Creates a prompt directly in the database for testing.
+ * Similar to the helper in prompts.v2.servertest.ts.
+ */
+export async function createPromptInDb(params: {
+ name: string;
+ prompt: string | unknown; // Can be string (text) or array (chat messages)
+ projectId: string;
+ labels?: string[];
+ version?: number;
+ config?: Record<string, unknown>;
+ tags?: string[];
+ type?: "text" | "chat";
+ createdBy?: string;
+}) {
+ return await prisma.prompt.create({
+ data: {
+ name: params.name,
+ //eslint-disable-next-line @typescript-eslint/no-explicit-any
+ prompt: params.prompt as any, // Prisma's JsonValue type - can be string or object
+ labels: params.labels ?? [],
+ version: params.version ?? 1,
+ //eslint-disable-next-line @typescript-eslint/no-explicit-any
+ config: (params.config ?? {}) as any, // Prisma's JsonValue type - safe because we control the input
+ tags: params.tags ?? [],
+ type: params.type ?? "text",
+ createdBy: params.createdBy ?? "test-user",
+ project: {
+ connect: { id: params.projectId },
+ },
+ },
+ });
+}
+
+/**
+ * Deletes all prompts for a specific project.
+ * Useful for cleanup in tests.
+ */
+export async function cleanupProjectPrompts(projectId: string): Promise<void> {
+ await prisma.prompt.deleteMany({
+ where: { projectId },
+ });
+}
+
+/**
+ * Helper to check if a tool has the correct MCP annotations.
+ */
+export function verifyToolAnnotations(
+ toolDefinition: { annotations?: Record<string, boolean> },
+ expectedAnnotations: {
+ readOnlyHint?: boolean;
+ destructiveHint?: boolean;
+ expensiveHint?: boolean;
+ },
+): void {
+ const annotations = toolDefinition.annotations ?? {};
+
+ if (expectedAnnotations.readOnlyHint !== undefined) {
+ expect(annotations.readOnlyHint).toBe(expectedAnnotations.readOnlyHint);
+ }
+
+ if (expectedAnnotations.destructiveHint !== undefined) {
+ expect(annotations.destructiveHint).toBe(
+ expectedAnnotations.destructiveHint,
+ );
+ }
+
+ if (expectedAnnotations.expensiveHint !== undefined) {
+ expect(annotations.expensiveHint).toBe(expectedAnnotations.expensiveHint);
+ }
+}
+
+/**
+ * Waits for a condition to be true with timeout.
+ * Useful for async operations that need eventual consistency.
+ */
+export async function waitFor(
+ condition: () => Promise<boolean>,
+ timeoutMs: number = 5000,
+ intervalMs: number = 100,
+): Promise<void> {
+ const startTime = Date.now();
+
+ while (Date.now() - startTime < timeoutMs) {
+ if (await condition()) {
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ }
+
+ throw new Error(`Condition not met within ${timeoutMs}ms`);
+}
diff --git a/web/src/__tests__/async/mcp-tools-read.servertest.ts b/web/src/__tests__/async/mcp-tools-read.servertest.ts
new file mode 100644
index 0000000000..4ec748f6e4
--- /dev/null
+++ b/web/src/__tests__/async/mcp-tools-read.servertest.ts
@@ -0,0 +1,521 @@
+/** @jest-environment node */
+
+// Mock queue operations to avoid Redis dependency in tests
+jest.mock("@langfuse/shared/src/server", () => {
+ const actual = jest.requireActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ // Mock queue getInstance to return a no-op queue
+ EventPropagationQueue: {
+ getInstance: () => ({
+ add: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn(),
+ }),
+ },
+ };
+});
+
+import { nanoid } from "nanoid";
+import {
+ createMcpTestSetup,
+ createPromptInDb,
+ verifyToolAnnotations,
+} from "./mcp-helpers";
+
+// Import MCP tool handlers directly
+import {
+ getPromptTool,
+ handleGetPrompt,
+} from "@/src/features/mcp/features/prompts/tools/getPrompt";
+import {
+ listPromptsTool,
+ handleListPrompts,
+} from "@/src/features/mcp/features/prompts/tools/listPrompts";
+
+describe("MCP Read Tools", () => {
+ describe("getPrompt tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(getPromptTool, { readOnlyHint: true });
+ });
+
+ it("should fetch prompt by name only (defaults to production label)", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ // Create a prompt with production label
+ await createPromptInDb({
+ name: promptName,
+ prompt: "You are a helpful assistant.",
+ projectId,
+ labels: ["production"],
+ version: 1,
+ });
+
+ const result = (await handleGetPrompt({ name: promptName }, context)) as {
+ name: string;
+ version: number;
+ labels: string[];
+ };
+
+ expect(result.name).toBe(promptName);
+ expect(result.version).toBe(1);
+ expect(result.labels).toContain("production");
+ });
+
+ it("should fetch prompt by name and specific label", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ // Create v1 with staging label
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Version 1",
+ projectId,
+ labels: ["staging"],
+ version: 1,
+ });
+
+ // Create v2 with production label
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Version 2",
+ projectId,
+ labels: ["production"],
+ version: 2,
+ });
+
+ const result = (await handleGetPrompt(
+ { name: promptName, label: "staging" },
+ context,
+ )) as { version: number; prompt: string };
+
+ expect(result.version).toBe(1);
+ expect(result.prompt).toBe("Version 1");
+ });
+
+ it("should fetch prompt by name and specific version", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Version 1",
+ projectId,
+ version: 1,
+ });
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Version 2",
+ projectId,
+ version: 2,
+ });
+
+ const result = (await handleGetPrompt(
+ { name: promptName, version: 2 },
+ context,
+ )) as { version: number; prompt: string };
+
+ expect(result.version).toBe(2);
+ expect(result.prompt).toBe("Version 2");
+ });
+
+ it("should throw error when both label and version are specified", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ });
+
+ // The input schema refinement should reject this
+ await expect(
+ handleGetPrompt(
+ { name: promptName, label: "production", version: 1 },
+ context,
+ ),
+ ).rejects.toThrow();
+ });
+
+ it("should return error for non-existent prompt", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(
+ handleGetPrompt({ name: "non-existent-prompt" }, context),
+ ).rejects.toThrow(/not found/i);
+ });
+
+ it("should return error for non-existent label", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ labels: ["staging"],
+ });
+
+ await expect(
+ handleGetPrompt({ name: promptName, label: "production" }, context),
+ ).rejects.toThrow(/not found/i);
+ });
+
+ it("should return error for non-existent version", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ version: 1,
+ });
+
+ await expect(
+ handleGetPrompt({ name: promptName, version: 999 }, context),
+ ).rejects.toThrow(/not found/i);
+ });
+
+ it("should use context.projectId for tenant isolation", async () => {
+ const { context: context1, projectId: projectId1 } =
+ await createMcpTestSetup();
+ const { context: context2, projectId: projectId2 } =
+ await createMcpTestSetup();
+
+ const promptName = `shared-name-${nanoid()}`;
+
+ // Create same-named prompt in both projects
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Project 1 content",
+ projectId: projectId1,
+ labels: ["production"],
+ });
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Project 2 content",
+ projectId: projectId2,
+ labels: ["production"],
+ });
+
+ // Each context should only see its own project's prompt
+ const result1 = (await handleGetPrompt(
+ { name: promptName },
+ context1,
+ )) as { prompt: string };
+ expect(result1.prompt).toBe("Project 1 content");
+
+ const result2 = (await handleGetPrompt(
+ { name: promptName },
+ context2,
+ )) as { prompt: string };
+ expect(result2.prompt).toBe("Project 2 content");
+ });
+
+ it("should handle special characters in prompt name", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-special!@#$%${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Special chars test",
+ projectId,
+ labels: ["production"],
+ });
+
+ const result = (await handleGetPrompt({ name: promptName }, context)) as {
+ name: string;
+ };
+ expect(result.name).toBe(promptName);
+ });
+
+ it("should include prompt config in response", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ labels: ["production"],
+ config: { model: "gpt-4", temperature: 0.7 },
+ });
+
+ const result = (await handleGetPrompt({ name: promptName }, context)) as {
+ config: Record<string, unknown>;
+ };
+
+ expect(result.config).toEqual({ model: "gpt-4", temperature: 0.7 });
+ });
+
+ it("should include tags in response", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `test-prompt-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ labels: ["production"],
+ tags: ["experimental", "v2"],
+ });
+
+ const result = (await handleGetPrompt({ name: promptName }, context)) as {
+ tags: string[];
+ };
+
+ expect(result.tags).toEqual(["experimental", "v2"]);
+ });
+ });
+
+ describe("listPrompts tool", () => {
+ it("should have readOnlyHint annotation", () => {
+ verifyToolAnnotations(listPromptsTool, { readOnlyHint: true });
+ });
+
+ it("should list all prompts for project", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+
+ // Create multiple prompts
+ const prompt1Name = `list-test-1-${nanoid()}`;
+ const prompt2Name = `list-test-2-${nanoid()}`;
+
+ await createPromptInDb({
+ name: prompt1Name,
+ prompt: "First prompt",
+ projectId,
+ });
+
+ await createPromptInDb({
+ name: prompt2Name,
+ prompt: "Second prompt",
+ projectId,
+ });
+
+ const result = (await handleListPrompts(
+ { page: 1, limit: 100 },
+ context,
+ )) as {
+ data: Array<{ name: string }>;
+ pagination: { 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);
+ });
+
+ it("should filter by name", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const uniquePrefix = `filter-name-${nanoid()}`;
+
+ await createPromptInDb({
+ name: `${uniquePrefix}-match`,
+ prompt: "Match",
+ projectId,
+ });
+
+ await createPromptInDb({
+ name: `other-${nanoid()}`,
+ prompt: "No match",
+ projectId,
+ });
+
+ const result = (await handleListPrompts(
+ { name: `${uniquePrefix}-match`, page: 1, limit: 100 },
+ context,
+ )) as {
+ data: Array<{ name: string }>;
+ };
+
+ expect(result.data.length).toBe(1);
+ expect(result.data[0].name).toBe(`${uniquePrefix}-match`);
+ });
+
+ it("should filter by label", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `filter-label-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Production version",
+ projectId,
+ labels: ["production"],
+ version: 1,
+ });
+
+ await createPromptInDb({
+ name: `other-${nanoid()}`,
+ prompt: "Staging version",
+ projectId,
+ labels: ["staging"],
+ version: 1,
+ });
+
+ const result = (await handleListPrompts(
+ { label: "production", page: 1, limit: 100 },
+ context,
+ )) as {
+ data: Array<{ name: string; labels: string[] }>;
+ };
+
+ // All returned prompts should have production label
+ for (const prompt of result.data) {
+ expect(prompt.labels).toContain("production");
+ }
+ });
+
+ it("should filter by tag", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `filter-tag-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Tagged prompt",
+ projectId,
+ tags: ["experimental"],
+ });
+
+ await createPromptInDb({
+ name: `untagged-${nanoid()}`,
+ prompt: "Untagged prompt",
+ projectId,
+ tags: [],
+ });
+
+ const result = (await handleListPrompts(
+ { tag: "experimental", page: 1, limit: 100 },
+ context,
+ )) as {
+ data: Array<{ name: string; tags: string[] }>;
+ };
+
+ // Should only return prompts with experimental tag
+ expect(result.data.length).toBeGreaterThan(0);
+ for (const prompt of result.data) {
+ expect(prompt.tags).toContain("experimental");
+ }
+ });
+
+ it("should handle pagination with page and limit", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+
+ // Create enough prompts to test pagination
+ for (let i = 0; i < 5; i++) {
+ await createPromptInDb({
+ name: `pagination-test-${i}-${nanoid()}`,
+ prompt: `Prompt ${i}`,
+ projectId,
+ });
+ }
+
+ const result = (await handleListPrompts(
+ { page: 1, limit: 2 },
+ context,
+ )) as {
+ data: Array<{ name: string }>;
+ pagination: { 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);
+ });
+
+ it("should return empty results for no matches", async () => {
+ const { context } = await createMcpTestSetup();
+
+ const result = (await handleListPrompts(
+ { name: `non-existent-${nanoid()}`, page: 1, limit: 100 },
+ context,
+ )) as {
+ data: Array<unknown>;
+ pagination: { totalItems: number };
+ };
+
+ expect(result.data).toEqual([]);
+ expect(result.pagination.totalItems).toBe(0);
+ });
+
+ it("should use context.projectId for tenant isolation", async () => {
+ const { context: context1, projectId: projectId1 } =
+ await createMcpTestSetup();
+ const { context: context2 } = await createMcpTestSetup();
+
+ const uniqueName = `isolation-test-${nanoid()}`;
+
+ // Create prompt only in project 1
+ await createPromptInDb({
+ name: uniqueName,
+ prompt: "Project 1 only",
+ projectId: projectId1,
+ });
+
+ // Project 1 should see it
+ const result1 = (await handleListPrompts(
+ { name: uniqueName, page: 1, limit: 100 },
+ context1,
+ )) as { data: Array<unknown> };
+ expect(result1.data.length).toBe(1);
+
+ // Project 2 should not see it
+ const result2 = (await handleListPrompts(
+ { name: uniqueName, page: 1, limit: 100 },
+ context2,
+ )) as { data: Array<unknown> };
+ expect(result2.data.length).toBe(0);
+ });
+
+ it("should respect default pagination values", async () => {
+ const { context } = await createMcpTestSetup();
+
+ const result = (await handleListPrompts(
+ { page: 1, limit: 100 },
+ context,
+ )) as {
+ pagination: { page: number; limit: number };
+ };
+
+ // Default values from validation schema
+ expect(result.pagination.page).toBe(1);
+ expect(result.pagination.limit).toBeLessThanOrEqual(100); // Max limit
+ });
+
+ it("should include prompt metadata in list results", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `metadata-test-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ labels: ["production"],
+ tags: ["important"],
+ version: 1,
+ });
+
+ const result = (await handleListPrompts(
+ { name: promptName, page: 1, limit: 100 },
+ context,
+ )) as {
+ data: Array<{
+ name: string;
+ version: number;
+ labels: string[];
+ tags: string[];
+ }>;
+ };
+
+ expect(result.data[0].name).toBe(promptName);
+ expect(result.data[0].labels).toContain("production");
+ expect(result.data[0].tags).toContain("important");
+ });
+ });
+});
diff --git a/web/src/__tests__/async/mcp-tools-write.servertest.ts b/web/src/__tests__/async/mcp-tools-write.servertest.ts
new file mode 100644
index 0000000000..e708ad13fe
--- /dev/null
+++ b/web/src/__tests__/async/mcp-tools-write.servertest.ts
@@ -0,0 +1,837 @@
+/** @jest-environment node */
+
+// Mock queue operations to avoid Redis dependency in tests
+jest.mock("@langfuse/shared/src/server", () => {
+ const actual = jest.requireActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ // Mock queue getInstance to return a no-op queue
+ EventPropagationQueue: {
+ getInstance: () => ({
+ add: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn(),
+ }),
+ },
+ EntityChangeQueue: {
+ getInstance: () => ({
+ add: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn(),
+ }),
+ },
+ };
+});
+
+import { prisma } from "@langfuse/shared/src/db";
+import { nanoid } from "nanoid";
+import {
+ createMcpTestSetup,
+ createPromptInDb,
+ verifyAuditLog,
+} from "./mcp-helpers";
+
+// Import MCP tool handlers directly
+import { handleCreateTextPrompt } from "@/src/features/mcp/features/prompts/tools/createTextPrompt";
+import { handleCreateChatPrompt } from "@/src/features/mcp/features/prompts/tools/createChatPrompt";
+import { handleUpdatePromptLabels } from "@/src/features/mcp/features/prompts/tools/updatePromptLabels";
+
+describe("MCP Write Tools", () => {
+ describe("createTextPrompt tool", () => {
+ it("should create a simple text prompt", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "You are a helpful assistant.",
+ },
+ context,
+ )) as {
+ id: string;
+ name: string;
+ version: number;
+ type: string;
+ labels: string[];
+ message: string;
+ };
+
+ expect(result.id).toBeDefined();
+ expect(result.name).toBe(promptName);
+ expect(result.version).toBe(1);
+ expect(result.type).toBe("text");
+ // First version automatically gets 'latest' label
+ expect(result.labels).toContain("latest");
+ expect(result.message).toContain("Successfully created");
+ });
+
+ it("should create text prompt with labels", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Production prompt",
+ labels: ["production", "stable"],
+ },
+ context,
+ )) as {
+ labels: string[];
+ message: string;
+ };
+
+ expect(result.labels).toEqual(
+ expect.arrayContaining(["production", "stable"]),
+ );
+ expect(result.message).toContain("production");
+ });
+
+ it("should create text prompt with config", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test with config",
+ config: { model: "gpt-4", temperature: 0.7 },
+ },
+ context,
+ )) as {
+ config: Record<string, unknown>;
+ };
+
+ expect(result.config).toEqual({ model: "gpt-4", temperature: 0.7 });
+ });
+
+ it("should create text prompt with tags", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test with tags",
+ tags: ["experimental", "v2"],
+ },
+ context,
+ )) as {
+ tags: string[];
+ };
+
+ expect(result.tags).toEqual(["experimental", "v2"]);
+ });
+
+ it("should create text prompt with commit message", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test with commit message",
+ commitMessage: "Initial production version",
+ },
+ context,
+ )) as {
+ id: string;
+ };
+
+ // Verify the commit message is stored
+ const prompt = await prisma.prompt.findUnique({
+ where: { id: result.id },
+ });
+ expect(prompt?.commitMessage).toBe("Initial production version");
+ });
+
+ it("should auto-increment version for same prompt name", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ // Create first version
+ const result1 = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Version 1",
+ },
+ context,
+ )) as { version: number };
+
+ // Create second version
+ const result2 = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Version 2",
+ },
+ context,
+ )) as { version: number };
+
+ expect(result1.version).toBe(1);
+ expect(result2.version).toBe(2);
+ });
+
+ it("should create audit log entry", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Audited prompt",
+ },
+ context,
+ )) as { id: string };
+
+ const auditLogEntry = await verifyAuditLog({
+ projectId,
+ resourceType: "prompt",
+ resourceId: result.id,
+ action: "create",
+ apiKeyId,
+ });
+
+ expect(auditLogEntry.after).toBeDefined();
+ expect(auditLogEntry.before).toBeNull();
+ });
+
+ it("should use context.projectId for tenant isolation", async () => {
+ const { context: context1, projectId: projectId1 } =
+ await createMcpTestSetup();
+
+ const promptName = `isolated-${nanoid()}`;
+
+ // Create prompt in project 1
+ const result1 = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Project 1 prompt",
+ },
+ context1,
+ )) as { id: string };
+
+ // Verify it's in project 1
+ const prompt = await prisma.prompt.findUnique({
+ where: { id: result1.id },
+ });
+ expect(prompt?.projectId).toBe(projectId1);
+ });
+
+ it("should support template variables in prompt", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Hello {{name}}, welcome to {{service}}!",
+ },
+ context,
+ )) as { id: string };
+
+ const prompt = await prisma.prompt.findUnique({
+ where: { id: result.id },
+ });
+ expect(prompt?.prompt).toBe("Hello {{name}}, welcome to {{service}}!");
+ });
+
+ it("should ignore 'latest' in user-provided labels (auto-managed)", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ // 'latest' is auto-managed, so if user provides it, it's ignored
+ // but the system will still add 'latest' automatically
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test",
+ labels: ["latest", "production"],
+ },
+ context,
+ )) as { labels: string[] };
+
+ // Should have 'latest' (auto) and 'production' (user-provided)
+ expect(result.labels).toContain("latest");
+ expect(result.labels).toContain("production");
+ });
+
+ it("should set createdBy to API", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `text-prompt-${nanoid()}`;
+
+ const result = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test",
+ },
+ context,
+ )) as { createdBy: string };
+
+ expect(result.createdBy).toBe("API");
+ });
+ });
+
+ describe("createChatPrompt tool", () => {
+ it("should create a simple chat prompt", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [
+ { role: "system", content: "You are a helpful assistant." },
+ { role: "user", content: "Help me with {{task}}" },
+ ],
+ },
+ context,
+ )) as {
+ id: string;
+ name: string;
+ version: number;
+ type: string;
+ labels: string[];
+ message: string;
+ };
+
+ expect(result.id).toBeDefined();
+ expect(result.name).toBe(promptName);
+ expect(result.version).toBe(1);
+ expect(result.type).toBe("chat");
+ // First version automatically gets 'latest' label
+ expect(result.labels).toContain("latest");
+ expect(result.message).toContain("Successfully created");
+ });
+
+ it("should create chat prompt with labels", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "System instruction" }],
+ labels: ["production"],
+ },
+ context,
+ )) as {
+ labels: string[];
+ };
+
+ expect(result.labels).toContain("production");
+ });
+
+ it("should create chat prompt with multiple message roles", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const messages = [
+ { role: "system", content: "You are an expert." },
+ { role: "user", content: "What is {{topic}}?" },
+ { role: "assistant", content: "I will explain {{topic}}." },
+ ];
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: messages,
+ },
+ context,
+ )) as { id: string };
+
+ const prompt = await prisma.prompt.findUnique({
+ where: { id: result.id },
+ });
+
+ expect(prompt?.prompt).toEqual(messages);
+ });
+
+ it("should create chat prompt with config", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "Test" }],
+ config: { model: "gpt-4-turbo", maxTokens: 1000 },
+ },
+ context,
+ )) as {
+ config: Record<string, unknown>;
+ };
+
+ expect(result.config).toEqual({ model: "gpt-4-turbo", maxTokens: 1000 });
+ });
+
+ it("should create chat prompt with tags", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "Test" }],
+ tags: ["multi-turn", "conversational"],
+ },
+ context,
+ )) as {
+ tags: string[];
+ };
+
+ expect(result.tags).toEqual(["multi-turn", "conversational"]);
+ });
+
+ it("should auto-increment version for same prompt name", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result1 = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "V1" }],
+ },
+ context,
+ )) as { version: number };
+
+ const result2 = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "V2" }],
+ },
+ context,
+ )) as { version: number };
+
+ expect(result1.version).toBe(1);
+ expect(result2.version).toBe(2);
+ });
+
+ it("should create audit log entry", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "Audited" }],
+ },
+ context,
+ )) as { id: string };
+
+ const auditLogEntry = await verifyAuditLog({
+ projectId,
+ resourceType: "prompt",
+ resourceId: result.id,
+ action: "create",
+ apiKeyId,
+ });
+
+ expect(auditLogEntry.after).toBeDefined();
+ expect(auditLogEntry.before).toBeNull();
+ });
+
+ it("should use context.projectId for tenant isolation", async () => {
+ const { context: context1, projectId: projectId1 } =
+ await createMcpTestSetup();
+
+ const promptName = `isolated-chat-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "Project 1" }],
+ },
+ context1,
+ )) as { id: string };
+
+ const prompt = await prisma.prompt.findUnique({
+ where: { id: result.id },
+ });
+ expect(prompt?.projectId).toBe(projectId1);
+ });
+
+ it("should support template variables in messages", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [
+ { role: "system", content: "You are a {{domain}} expert." },
+ { role: "user", content: "Explain {{concept}} to me." },
+ ],
+ },
+ context,
+ )) as { id: string };
+
+ const prompt = await prisma.prompt.findUnique({
+ where: { id: result.id },
+ });
+
+ const messages = prompt?.prompt as Array<{
+ role: string;
+ content: string;
+ }>;
+ expect(messages[0].content).toContain("{{domain}}");
+ expect(messages[1].content).toContain("{{concept}}");
+ });
+
+ it("should reject empty message array", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ // Empty array is now rejected - chat prompts need at least one message
+ await expect(
+ handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [],
+ },
+ context,
+ ),
+ ).rejects.toMatchObject({
+ code: -32602, // INVALID_PARAMS
+ message: expect.stringContaining(
+ "Chat prompts must have at least one message",
+ ),
+ });
+ });
+
+ it("should set createdBy to API", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `chat-prompt-${nanoid()}`;
+
+ const result = (await handleCreateChatPrompt(
+ {
+ name: promptName,
+ prompt: [{ role: "system", content: "Test" }],
+ },
+ context,
+ )) as { createdBy: string };
+
+ expect(result.createdBy).toBe("API");
+ });
+ });
+
+ describe("updatePromptLabels tool", () => {
+ it("should update labels for a prompt version", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `update-labels-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ labels: [],
+ version: 1,
+ });
+
+ const result = (await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 1,
+ newLabels: ["production"],
+ },
+ context,
+ )) as {
+ id: string;
+ name: string;
+ version: number;
+ labels: string[];
+ message: string;
+ };
+
+ expect(result.name).toBe(promptName);
+ expect(result.version).toBe(1);
+ expect(result.labels).toContain("production");
+ expect(result.message).toContain("Successfully updated");
+ });
+
+ it("should remove labels from other versions (label uniqueness)", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `label-unique-${nanoid()}`;
+
+ // Create v1 with production label
+ await createPromptInDb({
+ name: promptName,
+ prompt: "V1",
+ projectId,
+ labels: ["production"],
+ version: 1,
+ });
+
+ // Create v2 without labels
+ await createPromptInDb({
+ name: promptName,
+ prompt: "V2",
+ projectId,
+ labels: [],
+ version: 2,
+ });
+
+ // Move production to v2
+ await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 2,
+ newLabels: ["production"],
+ },
+ context,
+ );
+
+ // Verify v1 no longer has production
+ const v1 = await prisma.prompt.findFirst({
+ where: { projectId, name: promptName, version: 1 },
+ });
+ expect(v1?.labels).not.toContain("production");
+
+ // Verify v2 now has production
+ const v2 = await prisma.prompt.findFirst({
+ where: { projectId, name: promptName, version: 2 },
+ });
+ expect(v2?.labels).toContain("production");
+ });
+
+ it("should allow setting multiple labels", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `multi-labels-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ labels: [],
+ version: 1,
+ });
+
+ const result = (await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 1,
+ newLabels: ["staging", "testing", "qa"],
+ },
+ context,
+ )) as {
+ labels: string[];
+ };
+
+ expect(result.labels).toEqual(
+ expect.arrayContaining(["staging", "testing", "qa"]),
+ );
+ });
+
+ it("should add new labels to existing labels (additive behavior)", async () => {
+ const { context } = await createMcpTestSetup();
+ const promptName = `add-labels-${nanoid()}`;
+
+ // Create via handler so it gets 'latest' automatically
+ const created = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test",
+ labels: ["production"],
+ },
+ context,
+ )) as { version: number; labels: string[] };
+
+ expect(created.labels).toContain("production");
+ expect(created.labels).toContain("latest");
+
+ // The updatePromptLabels action ADDS labels, not replaces them
+ const result = (await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: created.version,
+ newLabels: ["staging"],
+ },
+ context,
+ )) as {
+ labels: string[];
+ message: string;
+ };
+
+ // Should have all labels: original + new
+ expect(result.labels).toContain("latest");
+ expect(result.labels).toContain("production");
+ expect(result.labels).toContain("staging");
+ });
+
+ it("should throw error for non-existent prompt", async () => {
+ const { context } = await createMcpTestSetup();
+
+ await expect(
+ handleUpdatePromptLabels(
+ {
+ name: "non-existent",
+ version: 1,
+ newLabels: ["production"],
+ },
+ context,
+ ),
+ ).rejects.toThrow(/not found/i);
+ });
+
+ it("should throw error for non-existent version", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `version-check-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ version: 1,
+ });
+
+ await expect(
+ handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 999,
+ newLabels: ["production"],
+ },
+ context,
+ ),
+ ).rejects.toThrow(/not found/i);
+ });
+
+ it("should create audit log entry with before and after states", async () => {
+ const { context, projectId, apiKeyId } = await createMcpTestSetup();
+ const promptName = `audit-update-${nanoid()}`;
+
+ // Create via handler to get proper structure
+ const created = (await handleCreateTextPrompt(
+ {
+ name: promptName,
+ prompt: "Test",
+ labels: ["staging"],
+ },
+ context,
+ )) as { version: number };
+
+ const result = (await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: created.version,
+ newLabels: ["qa"],
+ },
+ context,
+ )) as { id: string };
+
+ const auditLogEntry = await verifyAuditLog({
+ projectId,
+ resourceType: "prompt",
+ resourceId: result.id,
+ action: "update",
+ apiKeyId,
+ });
+
+ expect(auditLogEntry.before).toBeDefined();
+ expect(auditLogEntry.after).toBeDefined();
+
+ // Audit log stores JSON strings - parse them
+ const beforeState =
+ typeof auditLogEntry.before === "string"
+ ? (JSON.parse(auditLogEntry.before) as Record<string, unknown>)
+ : (auditLogEntry.before as Record<string, unknown>);
+ const afterState =
+ typeof auditLogEntry.after === "string"
+ ? (JSON.parse(auditLogEntry.after) as Record<string, unknown>)
+ : (auditLogEntry.after as Record<string, unknown>);
+
+ // Verify the before and after are different and contain labels
+ expect(beforeState).toHaveProperty("labels");
+ expect(afterState).toHaveProperty("labels");
+ // Should have the new label added
+ expect(afterState.labels).toContain("qa");
+ // Should preserve original labels (additive behavior)
+ expect(afterState.labels).toContain("staging");
+ });
+
+ it("should use context.projectId for tenant isolation", async () => {
+ const { context: context1, projectId: projectId1 } =
+ await createMcpTestSetup();
+ const { context: context2 } = await createMcpTestSetup();
+
+ const promptName = `isolated-update-${nanoid()}`;
+
+ // Create prompt in project 1
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Project 1",
+ projectId: projectId1,
+ version: 1,
+ });
+
+ // Project 2 should not be able to update it
+ await expect(
+ handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 1,
+ newLabels: ["production"],
+ },
+ context2,
+ ),
+ ).rejects.toThrow(/not found/i);
+
+ // Project 1 should be able to update it
+ const result = await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 1,
+ newLabels: ["production"],
+ },
+ context1,
+ );
+
+ expect(result).toBeDefined();
+ });
+
+ it("should reject 'latest' label", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `latest-reject-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ version: 1,
+ });
+
+ // 'latest' is auto-managed and cannot be set manually
+ await expect(
+ handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 1,
+ newLabels: ["latest"],
+ },
+ context,
+ ),
+ ).rejects.toThrow();
+ });
+
+ it("should handle special characters in prompt name", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const promptName = `special!@#$-${nanoid()}`;
+
+ await createPromptInDb({
+ name: promptName,
+ prompt: "Test",
+ projectId,
+ version: 1,
+ });
+
+ const result = (await handleUpdatePromptLabels(
+ {
+ name: promptName,
+ version: 1,
+ newLabels: ["production"],
+ },
+ context,
+ )) as { name: string };
+
+ expect(result.name).toBe(promptName);
+ });
+ });
+});
diff --git a/web/src/features/mcp/README.md b/web/src/features/mcp/README.md
new file mode 100644
index 0000000000..af9bf6363f
--- /dev/null
+++ b/web/src/features/mcp/README.md
@@ -0,0 +1,201 @@
+# Langfuse MCP Server
+
+Model Context Protocol (MCP) server for Langfuse, enabling AI assistants to interact with your Langfuse prompts programmatically.
+
+## Quick Start (Local Development)
+
+### Prerequisites
+
+- Langfuse instance running locally
+- Project-scoped API key (Public Key + Secret Key)
+- Claude Code or another MCP-compatible client
+
+### Steps
+
+1. **Get API Keys**
+ - Navigate to `http://localhost:3000/project/{project-id}/settings`
+ - Create or copy a project-scoped API key (`pk-lf-...` and `sk-lf-...`)
+ - Note: Organization-level keys are not supported
+
+2. **Encode Credentials**
+
+ ```bash
+ echo -n "pk-lf-xxx:sk-lf-xxx" | base64
+ ```
+
+ Output:
+
+ ```
+ // Example. Real token will be much longer
+ cGstbGYteHh4OnNrLWxmLXh4eA==
+ ```
+
+3. **Add to Claude Code**
+
+ ```bash
+ claude mcp add --transport http langfuse http://localhost:3000/api/public/mcp \
+ --header "Authorization: Basic {your-base64-token}"
+ ```
+
+4. **Verify**
+ In Claude Code: `List all prompts in the project`
+
+---
+
+## Available Tools
+
+The MCP server provides 5 tools for prompt management:
+
+- **`getPrompt`** - Fetch a specific prompt by name with optional label or version
+- **`listPrompts`** - List all prompts in the project with filtering and pagination
+- **`createTextPrompt`** - Create a new text prompt version
+- **`createChatPrompt`** - Create a new chat prompt version (OpenAI-style messages)
+- **`updatePromptLabels`** - Add/move labels across prompt versions
+
+**Implementation:** See [`/web/src/features/mcp/server/tools/`](/web/src/features/mcp/server/tools/) for detailed schemas, parameters, and examples for each tool.
+
+---
+
+## Architecture
+
+### Stateless Design
+
+The Langfuse MCP server uses a **stateless per-request architecture**:
+
+1. **Fresh server instance per request:** Each MCP request creates a new server instance
+2. **Context captured in closures:** Authentication context is captured in handler closures
+3. **No session storage:** Server is discarded after request completes
+4. **No state between requests:** Each request is independent
+
+This design:
+
+- Eliminates session management complexity
+- Prevents state leaks between projects
+- Simplifies authentication (project context derived from API key)
+
+### Authentication Flow
+
+```
+1. Client sends request with Authorization header
+ ↓
+2. API endpoint validates BasicAuth (PUBLIC_KEY:SECRET_KEY)
+ ↓
+3. Verify API key has project-level scope
+ ↓
+4. Build ServerContext from API key metadata
+ ↓
+5. Create fresh MCP server with context in closure
+ ↓
+6. Handle request (context auto-injected to handlers)
+ ↓
+7. Discard server instance
+```
+
+**ServerContext:**
+
+```typescript
+{
+ projectId: "proj-123", // Auto-injected from API key
+ orgId: "org-456", // Auto-injected from API key
+ apiKeyId: "key-789", // For audit logging
+ accessLevel: "project", // Required for MCP
+ publicKey: "pk-lf-..." // For reference
+}
+```
+
+### Tool Annotations
+
+Tools include hints for clients about their behavior:
+
+- **`readOnly: true`**: Safe operations that don't modify data (getPrompt, listPrompts)
+- **`destructive: true`**: Operations that create/modify data (createTextPrompt, createChatPrompt, updatePromptLabels)
+
+Clients like Claude Code can use these annotations to:
+
+- Auto-approve read-only operations
+- Require user confirmation for destructive operations
+
+### Audit Logging
+
+All write operations (createTextPrompt, createChatPrompt, updatePromptLabels) automatically create audit log entries with before/after snapshots.
+
+---
+
+# Connecting Clients
+
+## Authentication
+
+All clients require BasicAuth authentication using your Langfuse API keys.
+
+### 1. Generate Basic Auth Token
+
+Encode your Langfuse API keys (Public Key:Secret Key) to base64:
+
+```bash
+echo -n "pk-lf-your-public-key:sk-lf-your-secret-key" | base64
+```
+
+This outputs your BasicAuth token (e.g., `cGstbGYt...`).
+
+### 2. Choose Your Langfuse URL
+
+**Langfuse Cloud:**
+
+- **EU Region:** `https://cloud.langfuse.com`
+- **US Region:** `https://us.langfuse.com`
+- **HIPAA:** `https://hipaa.langfuse.com`
+
+**Self-Hosted:**
+
+- Use your domain with HTTPS: `https://your-domain.com`
+
+**Local Development:**
+
+- `http://localhost:3000`
+
+---
+
+## Claude Code
+
+Register the Langfuse MCP server:
+
+```bash
+# Langfuse Cloud (EU)
+claude mcp add --transport http langfuse https://cloud.langfuse.com/api/public/mcp \
+ --header "Authorization: Basic {your-base64-token}"
+
+# Langfuse Cloud (US)
+claude mcp add --transport http langfuse https://us.langfuse.com/api/public/mcp \
+ --header "Authorization: Basic {your-base64-token}"
+
+# Self-Hosted (HTTPS required)
+claude mcp add --transport http langfuse https://your-domain.com/api/public/mcp \
+ --header "Authorization: Basic {your-base64-token}"
+
+# Local Development
+claude mcp add --transport http langfuse http://localhost:3000/api/public/mcp \
+ --header "Authorization: Basic {your-base64-token}"
+```
+
+---
+
+## Cursor
+
+Add to your Cursor MCP settings:
+
+```json
+{
+ "mcp": {
+ "servers": {
+ "langfuse": {
+ "url": "https://cloud.langfuse.com/api/public/mcp",
+ "headers": {
+ "Authorization": "Basic {your-base64-token}"
+ }
+ }
+ }
+ }
+}
+```
+
+Replace `https://cloud.langfuse.com` with your Langfuse URL (see [Choose Your Langfuse URL](#2-choose-your-langfuse-url)).
diff --git a/web/src/features/mcp/core/define-tool.ts b/web/src/features/mcp/core/define-tool.ts
new file mode 100644
index 0000000000..5801fff3c7
--- /dev/null
+++ b/web/src/features/mcp/core/define-tool.ts
@@ -0,0 +1,155 @@
+/**
+ * MCP Tool Definition Helper
+ *
+ * Simplified helper for defining MCP tools with automatic JSON Schema generation.
+ * Handles the conversion from Zod schemas to JSON Schema for MCP compatibility.
+ */
+
+import { z } from "zod/v4";
+import { wrapErrorHandling } from "./error-formatting";
+import type { ServerContext } from "../types";
+
+/**
+ * Tool handler function type
+ */
+export type ToolHandler<TInput> = (
+ input: TInput,
+ context: ServerContext,
+) => Promise<unknown>;
+
+/**
+ * Tool definition options
+ */
+export interface DefineToolOptions<TInput> {
+ /** Tool name (must be unique across all tools) */
+ name: string;
+
+ /** Description for LLM to understand when to use this tool */
+ description: string;
+
+ /** Base Zod schema (without refinements) - used for JSON Schema generation */
+ baseSchema: z.ZodType<TInput>;
+
+ /** Full Zod schema with refinements - used for runtime validation */
+ inputSchema: z.ZodType<TInput>;
+
+ /** Handler function that executes the tool logic */
+ handler: ToolHandler<TInput>;
+
+ /** Hint: This tool only reads data, does not modify anything */
+ readOnlyHint?: boolean;
+
+ /** Hint: This tool has destructive effects (delete, overwrite) */
+ destructiveHint?: boolean;
+
+ /** Hint: This tool is expensive to run (slow, rate-limited) */
+ expensiveHint?: boolean;
+}
+
+/**
+ * MCP Tool definition
+ */
+export interface ToolDefinition {
+ name: string;
+ description: string;
+ inputSchema: {
+ type: "object";
+ properties: Record<string, unknown>;
+ required?: string[];
+ additionalProperties?: boolean;
+ };
+ annotations?: {
+ readOnlyHint?: boolean;
+ destructiveHint?: boolean;
+ expensiveHint?: boolean;
+ };
+}
+
+/**
+ * Define an MCP tool with automatic JSON Schema generation.
+ *
+ * @param options Tool configuration options
+ * @returns Tuple of [tool definition for MCP, wrapped handler for execution]
+ *
+ * @example
+ * const baseSchema = z.object({
+ * name: z.string(),
+ * version: z.number().optional(),
+ * });
+ *
+ * const [toolDef, handler] = defineTool({
+ * name: "getPrompt",
+ * description: "Fetch a prompt by name",
+ * baseSchema,
+ * inputSchema: baseSchema.refine(...), // Add runtime validations
+ * handler: async (input, context) => {
+ * // Implementation
+ * },
+ * readOnly: true,
+ * });
+ */
+export function defineTool<TInput>(
+ options: DefineToolOptions<TInput>,
+): [ToolDefinition, ToolHandler<TInput>] {
+ const {
+ name,
+ description,
+ baseSchema,
+ inputSchema,
+ handler,
+ readOnlyHint,
+ destructiveHint,
+ expensiveHint,
+ } = options;
+
+ // Convert base Zod schema to JSON Schema using Zod v4's native method
+ const jsonSchema = z.toJSONSchema(baseSchema, {
+ target: "draft-7", // MCP uses JSON Schema draft-7
+ unrepresentable: "any", // Fallback for unsupported types
+ });
+
+ if (!jsonSchema) {
+ throw new Error(
+ `Failed to convert Zod schema to JSON Schema for tool: ${name}.`,
+ );
+ }
+
+ // Validate that we got a usable schema (object or union of objects)
+ const hasObjectType = (jsonSchema as { type?: string }).type === "object";
+ const hasUnionType =
+ "oneOf" in jsonSchema ||
+ "anyOf" in jsonSchema ||
+ "discriminator" in jsonSchema;
+ if (!hasObjectType && !hasUnionType) {
+ throw new Error(
+ `Failed to convert Zod schema to JSON Schema for tool: ${name}. Expected object or union schema, got: ${JSON.stringify(jsonSchema).slice(0, 100)}`,
+ );
+ }
+
+ // Build tool definition
+ const toolDefinition: ToolDefinition = {
+ name,
+ description,
+ inputSchema: jsonSchema as ToolDefinition["inputSchema"],
+ };
+
+ // Add annotations if provided
+ if (readOnlyHint || destructiveHint || expensiveHint) {
+ toolDefinition.annotations = {
+ readOnlyHint,
+ destructiveHint,
+ expensiveHint,
+ };
+ }
+
+ // Wrap handler with validation and error handling
+ const wrappedHandler: ToolHandler<TInput> = wrapErrorHandling(
+ async (rawInput: unknown, context: ServerContext) => {
+ // Validate input with the full schema (including refinements)
+ const validatedInput = inputSchema.parse(rawInput);
+ return await handler(validatedInput, context);
+ },
+ );
+
+ return [toolDefinition, wrappedHandler];
+}
diff --git a/web/src/features/mcp/core/error-formatting.ts b/web/src/features/mcp/core/error-formatting.ts
new file mode 100644
index 0000000000..5e7160ccdb
--- /dev/null
+++ b/web/src/features/mcp/core/error-formatting.ts
@@ -0,0 +1,123 @@
+/**
+ * MCP Error Formatting
+ *
+ * Utilities to format errors for user display in MCP responses.
+ * Following Sentry pattern of categorizing and formatting errors appropriately.
+ */
+
+import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
+import { ZodError } from "zod/v4";
+import { isUserInputError, isApiServerError } from "./errors";
+import {
+ BaseError,
+ UnauthorizedError,
+ ForbiddenError,
+ LangfuseNotFoundError,
+ InvalidRequestError,
+} from "@langfuse/shared";
+import { logger } from "@langfuse/shared/src/server";
+
+/**
+ * Format an error for MCP response.
+ * Returns a properly formatted McpError with appropriate error code.
+ *
+ * @param error - The error to format
+ * @returns Formatted McpError
+ */
+export function formatErrorForUser(error: unknown): McpError {
+ // Log server errors for monitoring (sanitized to avoid PII exposure)
+ if (isApiServerError(error)) {
+ logger.error("MCP API Server Error", {
+ message: error.message,
+ name: error.name,
+ });
+ return new McpError(
+ ErrorCode.InternalError,
+ "An internal server error occurred. Please try again later.",
+ );
+ }
+
+ // User input errors - provide helpful message
+ if (isUserInputError(error)) {
+ return new McpError(ErrorCode.InvalidRequest, error.message);
+ }
+
+ // Zod validation errors
+ if (error instanceof ZodError) {
+ const messages = error.issues.map(
+ (issue) => `${issue.path.join(".")}: ${issue.message}`,
+ );
+ return new McpError(
+ ErrorCode.InvalidParams,
+ `Validation failed: ${messages.join(", ")}`,
+ );
+ }
+
+ // Langfuse standard errors
+ if (error instanceof UnauthorizedError) {
+ return new McpError(
+ ErrorCode.InvalidRequest,
+ "Authentication failed. Please check your API key.",
+ );
+ }
+
+ if (error instanceof ForbiddenError) {
+ return new McpError(
+ ErrorCode.InvalidRequest,
+ "Access forbidden. You do not have permission to access this resource.",
+ );
+ }
+
+ if (error instanceof LangfuseNotFoundError) {
+ return new McpError(ErrorCode.InvalidRequest, error.message);
+ }
+
+ if (error instanceof InvalidRequestError) {
+ return new McpError(ErrorCode.InvalidRequest, error.message);
+ }
+
+ if (error instanceof BaseError) {
+ logger.warn("MCP BaseError", error);
+ return new McpError(ErrorCode.InvalidRequest, error.message);
+ }
+
+ // Generic errors (sanitized logging)
+ if (error instanceof Error) {
+ logger.error("MCP Unexpected Error", {
+ message: error.message,
+ name: error.name,
+ });
+ return new McpError(
+ ErrorCode.InternalError,
+ "An unexpected error occurred. Please try again later.",
+ );
+ }
+
+ // Unknown error type (sanitized logging)
+ logger.error("MCP Unknown Error Type", {
+ errorType: typeof error,
+ });
+ return new McpError(
+ ErrorCode.InternalError,
+ "An unexpected error occurred. Please try again later.",
+ );
+}
+
+/**
+ * Wrap a function to catch and format errors for MCP.
+ * Prevents errors from bubbling up unformatted.
+ *
+ * @param fn - Function to wrap
+ * @returns Wrapped function that catches and formats errors
+ */
+export function wrapErrorHandling<T extends (...args: any[]) => Promise<any>>(
+ fn: T,
+): T {
+ return (async (...args: Parameters<T>) => {
+ try {
+ return await fn(...args);
+ } catch (error) {
+ throw formatErrorForUser(error);
+ }
+ }) as T;
+}
diff --git a/web/src/features/mcp/core/errors.ts b/web/src/features/mcp/core/errors.ts
new file mode 100644
index 0000000000..23e5e5d690
--- /dev/null
+++ b/web/src/features/mcp/core/errors.ts
@@ -0,0 +1,63 @@
+/**
+ * MCP Error Classes
+ *
+ * Following Sentry MCP pattern:
+ * - UserInputError: 4xx-like errors that user can fix (invalid input, not found, etc.)
+ * - ApiServerError: 5xx-like errors that should be logged to monitoring
+ */
+
+/**
+ * Error that indicates user input is invalid or incorrect.
+ * These errors should be formatted for user display and not logged as server errors.
+ *
+ * Examples:
+ * - Invalid prompt name
+ * - Prompt not found
+ * - Invalid version number
+ * - Missing required fields
+ */
+export class UserInputError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "UserInputError";
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, UserInputError);
+ }
+ }
+}
+
+/**
+ * Error that indicates an internal server problem.
+ * These errors should be logged to monitoring systems.
+ *
+ * Examples:
+ * - Database connection failure
+ * - Redis unavailable
+ * - Unexpected null value
+ * - Third-party API failure
+ */
+export class ApiServerError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "ApiServerError";
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, ApiServerError);
+ }
+ }
+}
+
+/**
+ * Type guard to check if an error is a UserInputError
+ */
+export function isUserInputError(error: unknown): error is UserInputError {
+ return error instanceof UserInputError;
+}
+
+/**
+ * Type guard to check if an error is an ApiServerError
+ */
+export function isApiServerError(error: unknown): error is ApiServerError {
+ return error instanceof ApiServerError;
+}
diff --git a/web/src/features/mcp/core/validation.ts b/web/src/features/mcp/core/validation.ts
new file mode 100644
index 0000000000..d4f7f8e319
--- /dev/null
+++ b/web/src/features/mcp/core/validation.ts
@@ -0,0 +1,51 @@
+/**
+ * MCP Core Validation Schemas
+ *
+ * Pre-defined Zod v4 schemas for common cross-feature parameters.
+ * Feature-specific validation schemas live in their respective feature directories.
+ *
+ * @example
+ * // Prompt-specific schemas:
+ * import { ParamPromptName } from "../features/prompts/validation";
+ *
+ * // Cross-feature schemas:
+ * import { ParamProjectId, ParamLimit } from "../core/validation";
+ */
+
+import { z } from "zod/v4";
+
+/**
+ * Project ID parameter
+ * No format enforcement - validated via API key authentication
+ */
+export const ParamProjectId = z.string().describe("The project ID");
+
+/**
+ * Pagination limit parameter
+ * Defaults to 50, max 100
+ */
+export const ParamLimit = z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(100)
+ .default(50)
+ .describe("Number of items to return (1-100, default: 50)");
+
+/**
+ * Pagination page parameter
+ * Defaults to 1
+ */
+export const ParamPage = z.coerce
+ .number()
+ .int()
+ .min(1)
+ .default(1)
+ .describe("Page number for pagination (default: 1)");
+
+/**
+ * Helper to extract schema description for MCP tool definitions
+ */
+export function getSchemaDescription(schema: z.ZodType): string | undefined {
+ return schema.description;
+}
diff --git a/web/src/features/mcp/features/prompts/index.ts b/web/src/features/mcp/features/prompts/index.ts
new file mode 100644
index 0000000000..b42ab91e88
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/index.ts
@@ -0,0 +1,70 @@
+/**
+ * Prompts MCP Feature Module
+ *
+ * Provides tools for managing Langfuse prompts via the MCP protocol.
+ * This module exports all prompt-related tools for registration with the MCP server.
+ *
+ * Tools provided:
+ * - getPrompt: Fetch specific prompts by name/label/version (read-only)
+ * - listPrompts: List and filter prompts with pagination (read-only)
+ * - createTextPrompt: Create new text prompt versions (destructive)
+ * - createChatPrompt: Create new chat prompt versions (destructive)
+ * - updatePromptLabels: Update labels on prompt versions (destructive)
+ */
+
+import type { McpFeatureModule } from "../../server/registry";
+import { getPromptTool, handleGetPrompt } from "./tools/getPrompt";
+import { listPromptsTool, handleListPrompts } from "./tools/listPrompts";
+import {
+ createTextPromptTool,
+ handleCreateTextPrompt,
+} from "./tools/createTextPrompt";
+import {
+ createChatPromptTool,
+ handleCreateChatPrompt,
+} from "./tools/createChatPrompt";
+import {
+ updatePromptLabelsTool,
+ handleUpdatePromptLabels,
+} from "./tools/updatePromptLabels";
+
+/**
+ * Prompts Feature Module
+ *
+ * Registers all prompt management tools with the MCP server.
+ * Tools are automatically available to MCP clients once registered.
+ */
+export const promptsFeature: McpFeatureModule = {
+ name: "prompts",
+ description:
+ "Manage Langfuse prompts - create, retrieve, and update prompt versions",
+
+ tools: [
+ {
+ definition: getPromptTool,
+ handler: handleGetPrompt,
+ },
+ {
+ definition: listPromptsTool,
+ handler: handleListPrompts,
+ },
+ {
+ definition: createTextPromptTool,
+ handler: handleCreateTextPrompt,
+ },
+ {
+ definition: createChatPromptTool,
+ handler: handleCreateChatPrompt,
+ },
+ {
+ definition: updatePromptLabelsTool,
+ handler: handleUpdatePromptLabels,
+ },
+ ],
+
+ // Optional: Feature can be conditionally enabled based on context
+ // isEnabled: async (context) => {
+ // // Example: Check entitlements, feature flags, etc.
+ // return true;
+ // },
+};
diff --git a/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts b/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts
new file mode 100644
index 0000000000..37ed983845
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/tools/createChatPrompt.ts
@@ -0,0 +1,154 @@
+/**
+ * MCP Tool: createChatPrompt
+ *
+ * Creates a new chat prompt version in Langfuse.
+ * Write operation with destructive hint.
+ */
+
+import { z } from "zod/v4";
+import { defineTool } from "../../../core/define-tool";
+import {
+ PromptType,
+ PromptLabelSchema,
+ PromptNameSchema,
+ COMMIT_MESSAGE_MAX_LENGTH,
+ PROMPT_NAME_MAX_LENGTH,
+} from "@langfuse/shared";
+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";
+
+/**
+ * Schema for a single chat message (role + content)
+ * Note: Using simple object schema instead of union to comply with MCP spec
+ */
+const ChatMessageSchema = z.object({
+ role: z.string().describe("The role (e.g., 'system', 'user', 'assistant')"),
+ content: z.string().describe("The message content"),
+});
+
+/**
+ * Base schema for JSON Schema generation (MCP client display)
+ * Uses simple types that serialize well to JSON Schema
+ */
+const CreateChatPromptBaseSchema = z.object({
+ name: z
+ .string()
+ .min(1)
+ .max(PROMPT_NAME_MAX_LENGTH)
+ .describe("The name of the prompt"),
+ prompt: z
+ .array(ChatMessageSchema)
+ .min(1)
+ .describe("Array of chat messages with role and content"),
+ labels: z
+ .array(z.string())
+ .optional()
+ .describe("Labels to assign (e.g., ['production', 'staging'])"),
+ config: z
+ .record(z.string(), z.any())
+ .optional()
+ .describe(
+ "Optional JSON config (e.g., {model: 'gpt-4', temperature: 0.7})",
+ ),
+ tags: z
+ .array(z.string())
+ .optional()
+ .describe("Optional tags for organization (e.g., ['experimental', 'v2'])"),
+ commitMessage: z
+ .string()
+ .optional()
+ .describe("Optional commit message describing the changes"),
+});
+
+/**
+ * Input schema for runtime validation
+ * Uses full validation schemas from shared package
+ */
+const CreateChatPromptInputSchema = z.object({
+ name: PromptNameSchema,
+ prompt: z
+ .array(ChatMessageSchema)
+ .min(1, "Chat prompts must have at least one message"),
+ labels: z.array(PromptLabelSchema).optional(),
+ config: z.record(z.string(), z.any()).optional(),
+ tags: z.array(z.string()).optional(),
+ commitMessage: z.string().max(COMMIT_MESSAGE_MAX_LENGTH).optional(),
+});
+
+/**
+ * createChatPrompt tool definition and handler
+ */
+export const [createChatPromptTool, handleCreateChatPrompt] = defineTool({
+ name: "createChatPrompt",
+ description: [
+ "Create a new chat prompt version in Langfuse. Chat prompts are arrays of messages with roles and content.",
+ "",
+ "Important:",
+ "- Prompts are immutable - cannot modify existing versions",
+ "- To update content, create a new version",
+ "- To promote to production, use updatePromptLabels",
+ "- Labels are unique across versions",
+ "",
+ "Message roles: system (instructions), user (input, can contain {{variables}}), assistant (examples)",
+ "Accepts: name, prompt (array of {role, content}), optional labels, config, tags, commitMessage",
+ ].join("\n"),
+ 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",
+ });
+
+ const createdPrompt = await createPromptAction({
+ projectId: context.projectId,
+ name: input.name,
+ type: PromptType.Chat,
+ prompt: input.prompt,
+ labels: input.labels ?? [],
+ config: input.config ?? {},
+ tags: input.tags,
+ commitMessage: input.commitMessage,
+ createdBy: "API",
+ prisma,
+ });
+
+ // Set created version for observability
+ span.setAttribute("mcp.created_version", createdPrompt.version);
+
+ await auditLog({
+ action: "create",
+ resourceType: "prompt",
+ resourceId: createdPrompt.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: createdPrompt,
+ });
+
+ return {
+ id: createdPrompt.id,
+ name: createdPrompt.name,
+ version: createdPrompt.version,
+ type: createdPrompt.type,
+ labels: createdPrompt.labels,
+ tags: createdPrompt.tags,
+ config: createdPrompt.config,
+ createdAt: createdPrompt.createdAt,
+ createdBy: createdPrompt.createdBy,
+ message: `Successfully created chat prompt '${createdPrompt.name}' version ${createdPrompt.version}${createdPrompt.labels.length > 0 ? ` with labels: ${createdPrompt.labels.join(", ")}` : ""}`,
+ };
+ },
+ );
+ },
+});
diff --git a/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts b/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts
new file mode 100644
index 0000000000..7887102fb0
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/tools/createTextPrompt.ts
@@ -0,0 +1,142 @@
+/**
+ * MCP Tool: createTextPrompt
+ *
+ * Creates a new text prompt version in Langfuse.
+ * Write operation with destructive hint.
+ */
+
+import { z } from "zod/v4";
+import { defineTool } from "../../../core/define-tool";
+import {
+ PromptType,
+ PromptLabelSchema,
+ PromptNameSchema,
+ COMMIT_MESSAGE_MAX_LENGTH,
+ PROMPT_NAME_MAX_LENGTH,
+} from "@langfuse/shared";
+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";
+
+/**
+ * Base schema for JSON Schema generation (MCP client display)
+ * Uses simple types that serialize well to JSON Schema
+ */
+const CreateTextPromptBaseSchema = z.object({
+ name: z
+ .string()
+ .min(1)
+ .max(PROMPT_NAME_MAX_LENGTH)
+ .describe("The name of the prompt"),
+ prompt: z
+ .string()
+ .describe("The prompt text content (supports {{variables}})"),
+ labels: z
+ .array(z.string())
+ .optional()
+ .describe("Labels to assign (e.g., ['production', 'staging'])"),
+ config: z
+ .record(z.string(), z.any())
+ .optional()
+ .describe(
+ "Optional JSON config (e.g., {model: 'gpt-4', temperature: 0.7})",
+ ),
+ tags: z
+ .array(z.string())
+ .optional()
+ .describe("Optional tags for organization (e.g., ['experimental', 'v2'])"),
+ commitMessage: z
+ .string()
+ .optional()
+ .describe("Optional commit message describing the changes"),
+});
+
+/**
+ * Input schema for runtime validation
+ * Uses full validation schemas from shared package
+ */
+const CreateTextPromptInputSchema = z.object({
+ name: PromptNameSchema,
+ prompt: z.string(),
+ labels: z.array(PromptLabelSchema).optional(),
+ config: z.record(z.string(), z.any()).optional(),
+ tags: z.array(z.string()).optional(),
+ commitMessage: z.string().max(COMMIT_MESSAGE_MAX_LENGTH).optional(),
+});
+
+/**
+ * createTextPrompt tool definition and handler
+ */
+export const [createTextPromptTool, handleCreateTextPrompt] = defineTool({
+ name: "createTextPrompt",
+ description: [
+ "Create a new text prompt version in Langfuse.",
+ "",
+ "Important:",
+ "- Prompts are immutable - cannot modify existing versions",
+ "- To update content, create a new version",
+ "- To promote to production, use updatePromptLabels",
+ "- Labels are unique across versions",
+ "- Use {{variable_name}} syntax for dynamic content",
+ "",
+ "Accepts: name, prompt (string), optional labels, config, tags, commitMessage",
+ ].join("\n"),
+ 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",
+ });
+
+ const createdPrompt = await createPromptAction({
+ projectId: context.projectId,
+ name: input.name,
+ type: PromptType.Text,
+ prompt: input.prompt,
+ labels: input.labels ?? [],
+ config: input.config ?? {},
+ tags: input.tags,
+ commitMessage: input.commitMessage,
+ createdBy: "API",
+ prisma,
+ });
+
+ // Set created version for observability
+ span.setAttribute("mcp.created_version", createdPrompt.version);
+
+ await auditLog({
+ action: "create",
+ resourceType: "prompt",
+ resourceId: createdPrompt.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ after: createdPrompt,
+ });
+
+ return {
+ id: createdPrompt.id,
+ name: createdPrompt.name,
+ version: createdPrompt.version,
+ type: createdPrompt.type,
+ labels: createdPrompt.labels,
+ tags: createdPrompt.tags,
+ config: createdPrompt.config,
+ createdAt: createdPrompt.createdAt,
+ createdBy: createdPrompt.createdBy,
+ message: `Successfully created text prompt '${createdPrompt.name}' version ${createdPrompt.version}${createdPrompt.labels.length > 0 ? ` with labels: ${createdPrompt.labels.join(", ")}` : ""}`,
+ };
+ },
+ );
+ },
+});
diff --git a/web/src/features/mcp/features/prompts/tools/getPrompt.ts b/web/src/features/mcp/features/prompts/tools/getPrompt.ts
new file mode 100644
index 0000000000..6fbd82b888
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/tools/getPrompt.ts
@@ -0,0 +1,111 @@
+/**
+ * MCP Tool: getPrompt
+ *
+ * Fetches a specific prompt by name with optional label or version.
+ * Read-only operation.
+ */
+
+import { z } from "zod/v4";
+import { defineTool } from "../../../core/define-tool";
+import {
+ ParamPromptName,
+ ParamPromptLabel,
+ ParamPromptVersion,
+} from "../validation";
+import { getPromptByName } from "@/src/features/prompts/server/actions/getPromptByName";
+import { UserInputError } from "../../../core/errors";
+import { instrumentAsync } from "@langfuse/shared/src/server";
+import { SpanKind } from "@opentelemetry/api";
+
+/**
+ * Base schema for JSON Schema generation (without refinements)
+ */
+const GetPromptBaseSchema = z.object({
+ name: ParamPromptName,
+ label: ParamPromptLabel,
+ version: ParamPromptVersion,
+});
+
+/**
+ * Full input schema with runtime validations
+ */
+const GetPromptInputSchema = GetPromptBaseSchema.refine(
+ (data) => !(data.label && data.version),
+ {
+ message:
+ "Cannot specify both label and version - they are mutually exclusive",
+ },
+);
+
+/**
+ * getPrompt tool definition and handler
+ */
+export const [getPromptTool, handleGetPrompt] = defineTool({
+ name: "getPrompt",
+ description: [
+ "Fetch a specific prompt by name with optional label or version parameter.",
+ "",
+ "Retrieval options:",
+ "- label: Get prompt with specific label (e.g., 'production', 'staging')",
+ "- version: Get specific version number (e.g., 1, 2, 3)",
+ "- neither: Returns 'production' version by default",
+ "",
+ "Note: label and version are mutually exclusive. Returns full prompt content with resolved dependencies.",
+ ].join("\n"),
+ baseSchema: GetPromptBaseSchema,
+ inputSchema: GetPromptInputSchema,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.prompts.get", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ const { name, label, version } = 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,
+ });
+
+ if (label) {
+ span.setAttribute("mcp.prompt_label", label);
+ }
+ if (version) {
+ span.setAttribute("mcp.prompt_version", version);
+ }
+
+ // Fetch prompt using existing service
+ const prompt = await getPromptByName({
+ promptName: name,
+ projectId: context.projectId, // Auto-injected from authenticated API key
+ label,
+ version,
+ });
+
+ if (!prompt) {
+ throw new UserInputError(
+ `Prompt '${name}' not found${label ? ` with label '${label}'` : ""}${version ? ` with version ${version}` : ""}`,
+ );
+ }
+
+ // Return formatted response
+ return {
+ id: prompt.id,
+ name: prompt.name,
+ version: prompt.version,
+ type: prompt.type,
+ prompt: prompt.prompt,
+ labels: prompt.labels,
+ tags: prompt.tags,
+ config: prompt.config,
+ createdAt: prompt.createdAt,
+ updatedAt: prompt.updatedAt,
+ createdBy: prompt.createdBy,
+ projectId: prompt.projectId,
+ };
+ },
+ );
+ },
+ readOnlyHint: true,
+});
diff --git a/web/src/features/mcp/features/prompts/tools/listPrompts.ts b/web/src/features/mcp/features/prompts/tools/listPrompts.ts
new file mode 100644
index 0000000000..db0469d11c
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/tools/listPrompts.ts
@@ -0,0 +1,112 @@
+/**
+ * MCP Tool: listPrompts
+ *
+ * Lists and filters prompts in the project.
+ * Read-only operation.
+ */
+
+import { z } from "zod/v4";
+import { defineTool } from "../../../core/define-tool";
+import {
+ ParamPromptName,
+ ParamPromptLabel,
+ ParamPromptTag,
+} 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";
+
+/**
+ * Base schema for listPrompts tool (no refinements needed)
+ */
+const ListPromptsBaseSchema = z.object({
+ name: ParamPromptName.optional().describe(
+ "Filter by exact prompt name match",
+ ),
+ label: ParamPromptLabel.describe(
+ "Filter by label (e.g., 'production', 'staging')",
+ ),
+ tag: ParamPromptTag.describe("Filter by tag (e.g., 'experimental', 'v1')"),
+ page: ParamPage,
+ limit: ParamLimit,
+});
+
+/**
+ * listPrompts tool definition and handler
+ */
+export const [listPromptsTool, handleListPrompts] = defineTool({
+ name: "listPrompts",
+ description: [
+ "List and filter prompts in the project. Returns metadata including versions, labels, tags, last updated timestamp, and prompt type.",
+ "",
+ "Optional filters:",
+ "- name: Filter by exact prompt name",
+ "- label: Filter by label on any version",
+ "- tag: Filter by tag",
+ "",
+ "Pagination: page (default: 1), limit (default: 50, max: 100)",
+ ].join("\n"),
+ baseSchema: ListPromptsBaseSchema,
+ inputSchema: ListPromptsBaseSchema, // No refinements, same as base
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.prompts.list", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ const { name, label, tag, 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);
+ }
+
+ // Fetch prompts metadata using existing service
+ const result = await getPromptsMeta({
+ projectId: context.projectId, // Auto-injected from authenticated API key
+ name,
+ label,
+ tag,
+ page, // Default handled by Zod schema
+ limit, // Default handled by Zod schema
+ });
+
+ // Set result count for observability
+ span.setAttribute("mcp.result_count", result.data.length);
+
+ // Return formatted response
+ return {
+ data: result.data.map((prompt) => ({
+ name: prompt.name,
+ type: prompt.type,
+ versions: prompt.versions,
+ labels: prompt.labels,
+ tags: prompt.tags,
+ lastUpdatedAt: prompt.lastUpdatedAt,
+ lastConfig: prompt.lastConfig,
+ })),
+ pagination: {
+ 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/updatePromptLabels.ts b/web/src/features/mcp/features/prompts/tools/updatePromptLabels.ts
new file mode 100644
index 0000000000..87d99abaa4
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/tools/updatePromptLabels.ts
@@ -0,0 +1,140 @@
+/**
+ * MCP Tool: updatePromptLabels
+ *
+ * Updates labels for a specific prompt version.
+ * Write operation with destructive hint.
+ * This is the ONLY way to modify existing prompts (labels only).
+ */
+
+import { z } from "zod/v4";
+import { defineTool } from "../../../core/define-tool";
+import { ParamPromptName, ParamNewLabels } from "../validation";
+import { updatePrompt } from "@/src/features/prompts/server/actions/updatePrompts";
+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 { PROMPT_NAME_MAX_LENGTH } from "@langfuse/shared";
+
+/**
+ * Base schema for JSON Schema generation (MCP client display)
+ * Uses simple types without refinements
+ */
+const UpdatePromptLabelsBaseSchema = z.object({
+ name: z
+ .string()
+ .min(1)
+ .max(PROMPT_NAME_MAX_LENGTH)
+ .describe("The name of the prompt"),
+ version: z.coerce
+ .number()
+ .int()
+ .positive()
+ .describe("The version number to update (required)"),
+ newLabels: z
+ .array(z.string())
+ .describe(
+ "Array of new labels to assign to the prompt version (can be empty to remove all labels)",
+ ),
+});
+
+/**
+ * Input schema for runtime validation
+ * Uses full validation schemas with refinements
+ */
+const UpdatePromptLabelsInputSchema = z.object({
+ name: ParamPromptName,
+ version: z.coerce
+ .number()
+ .int()
+ .positive()
+ .describe("The version number to update (required)"),
+ newLabels: ParamNewLabels,
+});
+
+/**
+ * updatePromptLabels tool definition and handler
+ */
+export const [updatePromptLabelsTool, handleUpdatePromptLabels] = defineTool({
+ name: "updatePromptLabels",
+ description: [
+ "Update labels for a specific prompt version.",
+ "",
+ "Important:",
+ "- ONLY way to modify existing prompts (labels only)",
+ "- Specified labels are added to the version (preserving others not mentioned)",
+ "- Labels are unique across versions - setting a label on one version automatically removes it from others",
+ "- 'latest' label is auto-managed and cannot be set manually",
+ "- Cannot modify prompt content, type, or tags - use createTextPrompt or createChatPrompt for new versions",
+ "",
+ "Accepts: name, version (required), newLabels (array, can be empty to remove all labels)",
+ ].join("\n"),
+ baseSchema: UpdatePromptLabelsBaseSchema,
+ inputSchema: UpdatePromptLabelsInputSchema,
+ handler: async (input, context) => {
+ return await instrumentAsync(
+ { name: "mcp.prompts.update_labels", spanKind: SpanKind.INTERNAL },
+ async (span) => {
+ 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: {
+ projectId_name_version: {
+ projectId: context.projectId,
+ name,
+ version,
+ },
+ },
+ });
+
+ if (!existingPrompt) {
+ throw new UserInputError(
+ `Prompt '${name}' version ${version} not found in project`,
+ );
+ }
+
+ // Update prompt labels using existing action
+ const updatedPrompt = await updatePrompt({
+ promptName: name,
+ projectId: context.projectId, // Auto-injected from authenticated API key
+ promptVersion: version,
+ newLabels,
+ });
+
+ // Audit log the update with both before and after states
+ await auditLog({
+ action: "update",
+ resourceType: "prompt",
+ resourceId: updatedPrompt.id,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ apiKeyId: context.apiKeyId,
+ before: existingPrompt,
+ after: updatedPrompt,
+ });
+
+ // Return formatted response
+ return {
+ id: updatedPrompt.id,
+ name: updatedPrompt.name,
+ version: updatedPrompt.version,
+ labels: updatedPrompt.labels,
+ message: `Successfully updated labels for '${updatedPrompt.name}' version ${updatedPrompt.version}. Labels are now: ${updatedPrompt.labels.length > 0 ? updatedPrompt.labels.join(", ") : "(none)"}`,
+ };
+ },
+ );
+ },
+});
diff --git a/web/src/features/mcp/features/prompts/validation.ts b/web/src/features/mcp/features/prompts/validation.ts
new file mode 100644
index 0000000000..1cf5a5e6dc
--- /dev/null
+++ b/web/src/features/mcp/features/prompts/validation.ts
@@ -0,0 +1,86 @@
+/**
+ * Prompts Feature Validation Schemas
+ *
+ * Zod v4 schemas specific to the prompts feature domain.
+ * Common cross-feature validations live in /core/validation.ts
+ */
+
+import { z } from "zod/v4";
+import {
+ PROMPT_NAME_MAX_LENGTH,
+ PROMPT_LABEL_MAX_LENGTH,
+ PROMPT_LABEL_REGEX,
+ PROMPT_LABEL_REGEX_ERROR,
+ COMMIT_MESSAGE_MAX_LENGTH,
+ LATEST_PROMPT_LABEL,
+} from "@langfuse/shared";
+
+/**
+ * Prompt name parameter
+ * Must match existing Langfuse prompt name validation
+ */
+export const ParamPromptName = z
+ .string()
+ .min(1)
+ .max(PROMPT_NAME_MAX_LENGTH)
+ .describe("The name of the prompt");
+
+/**
+ * Prompt label parameter (optional)
+ * Defaults to "production" if not specified
+ */
+export const ParamPromptLabel = z
+ .string()
+ .min(1)
+ .max(PROMPT_LABEL_MAX_LENGTH)
+ .regex(PROMPT_LABEL_REGEX, PROMPT_LABEL_REGEX_ERROR)
+ .optional()
+ .describe(
+ 'Label to retrieve (e.g., "production", "staging"). Defaults to "production".',
+ );
+
+/**
+ * Prompt version parameter (optional)
+ * Must be a positive integer
+ */
+export const ParamPromptVersion = z.coerce
+ .number()
+ .int()
+ .positive()
+ .optional()
+ .describe("Specific version number to retrieve (e.g., 1, 2, 3)");
+
+/**
+ * Prompt tag parameter (optional)
+ * Used for filtering prompts by tag
+ */
+export const ParamPromptTag = z
+ .string()
+ .optional()
+ .describe("Tag to filter prompts (e.g., 'v1', 'experimental')");
+
+/**
+ * Commit message parameter (optional)
+ * Used when creating new prompt versions
+ */
+export const ParamCommitMessage = z
+ .string()
+ .max(COMMIT_MESSAGE_MAX_LENGTH)
+ .optional()
+ .describe("Optional commit message describing the changes");
+
+/**
+ * New labels array for updating prompt labels
+ */
+export const ParamNewLabels = z
+ .array(
+ z
+ .string()
+ .min(1)
+ .max(PROMPT_LABEL_MAX_LENGTH)
+ .regex(PROMPT_LABEL_REGEX, PROMPT_LABEL_REGEX_ERROR),
+ )
+ .refine((labels) => !labels.includes(LATEST_PROMPT_LABEL), {
+ message: "Label 'latest' is always assigned to the latest prompt version",
+ })
+ .describe("Array of new labels to assign to the prompt version");
diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.ts
new file mode 100644
index 0000000000..acc4ecb741
--- /dev/null
+++ b/web/src/features/mcp/server/bootstrap.ts
@@ -0,0 +1,42 @@
+/**
+ * MCP Feature Bootstrap
+ *
+ * Registers all MCP feature modules at application startup.
+ * This file is imported once when the server starts to initialize the tool registry.
+ *
+ * To add a new MCP feature:
+ * 1. Create feature module in /features/[feature-name]/
+ * 2. Import feature module here
+ * 3. Call toolRegistry.register(featureModule)
+ */
+
+import { toolRegistry } from "./registry";
+import { promptsFeature } from "../features/prompts";
+// Import future features as they're added:
+// import { datasetsFeature } from "../features/datasets";
+// import { tracesFeature } from "../features/traces";
+// import { evalsFeature } from "../features/evals";
+
+/**
+ * Bootstrap all MCP features
+ *
+ * Called once at application startup to register all MCP feature modules.
+ * Features are registered in order of dependency (if any exist).
+ */
+export function bootstrapMcpFeatures(): void {
+ // Register all feature modules
+ toolRegistry.register(promptsFeature);
+
+ // Add future features here:
+ // toolRegistry.register(datasetsFeature);
+ // toolRegistry.register(tracesFeature);
+ // toolRegistry.register(evalsFeature);
+}
+
+/**
+ * Auto-bootstrap when this module is imported
+ *
+ * This runs once when the server starts, ensuring tools are registered
+ * before any MCP requests are handled.
+ */
+bootstrapMcpFeatures();
diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.ts
new file mode 100644
index 0000000000..fd81df59b6
--- /dev/null
+++ b/web/src/features/mcp/server/mcpServer.ts
@@ -0,0 +1,102 @@
+/**
+ * MCP Server Instance
+ *
+ * Main MCP server configuration and initialization.
+ * Implements stateless per-request server pattern.
+ *
+ * Key principles:
+ * - Fresh server instance per request
+ * - Context captured in closures (no session storage)
+ * - Tools dynamically loaded from registry
+ * - Server discarded after request completes
+ */
+
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import {
+ ListToolsRequestSchema,
+ CallToolRequestSchema,
+} from "@modelcontextprotocol/sdk/types.js";
+import type { ServerContext } from "../types";
+import { toolRegistry } from "./registry";
+import { logger } from "@langfuse/shared/src/server";
+
+const MCP_SERVER_NAME = "langfuse";
+const MCP_SERVER_VERSION = "0.2.0";
+
+/**
+ * Create and configure the MCP server instance.
+ *
+ * Creates a fresh MCP server for each request with context captured in closures.
+ * This follows the stateless pattern where no server state persists between requests.
+ *
+ * Tools are dynamically loaded from the global registry, eliminating hardcoded tool lists.
+ * Features register themselves at application startup via the bootstrap module.
+ *
+ * @param context - Server context from authenticated request (captured in closures)
+ * @returns Configured MCP Server instance
+ *
+ * @example
+ * // In API route:
+ * const server = createMcpServer(context);
+ * await server.connect(transport);
+ * // ... handle request ...
+ * // Server discarded after request
+ */
+export function createMcpServer(context: ServerContext): Server {
+ const server = new Server(
+ {
+ name: MCP_SERVER_NAME,
+ version: MCP_SERVER_VERSION,
+ },
+ {
+ capabilities: {
+ tools: {},
+ },
+ },
+ );
+
+ // ListTools handler - dynamically load from registry
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
+ const tools = await toolRegistry.getToolDefinitions(context);
+
+ logger.debug("MCP ListTools", {
+ projectId: context.projectId,
+ toolCount: tools.length,
+ toolNames: tools.map((t) => t.name),
+ });
+
+ return { tools };
+ });
+
+ // CallTool handler - route to registered tool handlers
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const { name, arguments: args } = request.params;
+
+ logger.debug("MCP CallTool", {
+ projectId: context.projectId,
+ toolName: name,
+ });
+
+ // Look up tool in registry
+ const registeredTool = toolRegistry.getTool(name);
+
+ if (!registeredTool) {
+ throw new Error(`Unknown tool: ${name}`);
+ }
+
+ // Execute handler with context
+ // Handler performs validation and error handling via defineTool wrapper
+ const result = await registeredTool.handler(args, context);
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: JSON.stringify(result, null, 2),
+ },
+ ],
+ };
+ });
+
+ return server;
+}
diff --git a/web/src/features/mcp/server/registry.ts b/web/src/features/mcp/server/registry.ts
new file mode 100644
index 0000000000..763b0d8f28
--- /dev/null
+++ b/web/src/features/mcp/server/registry.ts
@@ -0,0 +1,190 @@
+/**
+ * MCP Tool Registry
+ *
+ * Global registry for MCP feature modules and their tools.
+ * Provides dynamic tool discovery and execution.
+ *
+ * Design Pattern:
+ * - Each feature domain (prompts, datasets, traces) registers as a module
+ * - Registry handles tool name conflicts and feature-level enablement
+ * - Server queries registry instead of hardcoding tool lists
+ */
+
+import type { ToolDefinition, ToolHandler } from "../core/define-tool";
+import type { ServerContext } from "../types";
+import { logger } from "@langfuse/shared/src/server";
+
+/**
+ * Registered MCP tool
+ *
+ * Combines tool definition (for MCP protocol) with handler (for execution)
+ */
+export interface RegisteredTool {
+ /** Tool definition for MCP protocol */
+ definition: ToolDefinition;
+
+ /** Tool handler function - accepts any input type */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ handler: ToolHandler<any>;
+}
+
+/**
+ * Feature module definition
+ *
+ * Each feature domain (prompts, datasets, traces) exports a feature module
+ * that registers its tools with the MCP server.
+ *
+ * @example
+ * ```typescript
+ * export const promptsFeature: McpFeatureModule = {
+ * name: "prompts",
+ * description: "Manage Langfuse prompts",
+ * tools: [
+ * { definition: getPromptTool, handler: handleGetPrompt },
+ * { definition: listPromptsTool, handler: handleListPrompts },
+ * ],
+ * };
+ * ```
+ */
+export interface McpFeatureModule {
+ /** Feature identifier (e.g., 'prompts', 'datasets') */
+ name: string;
+
+ /** Feature description */
+ description: string;
+
+ /** Tools provided by this feature */
+ tools: RegisteredTool[];
+
+ /**
+ * Optional: Check if feature is enabled for the given context
+ * Allows conditional feature availability based on entitlements, feature flags, etc.
+ */
+ isEnabled?: (context: ServerContext) => boolean | Promise<boolean>;
+}
+
+/**
+ * Global tool registry
+ *
+ * Manages registration and lookup of MCP tools across all features.
+ * Singleton pattern ensures consistent state across application.
+ */
+class ToolRegistry {
+ private features = new Map<string, McpFeatureModule>();
+ private tools = new Map<string, RegisteredTool>();
+
+ /**
+ * Register a feature module with its tools
+ *
+ * @param feature - Feature module to register
+ * @throws Error if feature name conflicts or tool name conflicts
+ */
+ register(feature: McpFeatureModule): void {
+ if (this.features.has(feature.name)) {
+ throw new Error(`Feature '${feature.name}' is already registered`);
+ }
+
+ // Validate no tool name conflicts
+ for (const tool of feature.tools) {
+ if (this.tools.has(tool.definition.name)) {
+ const existingFeature = this.getToolFeature(tool.definition.name);
+ throw new Error(
+ `Tool '${tool.definition.name}' from feature '${feature.name}' ` +
+ `conflicts with existing tool from feature '${existingFeature}'`,
+ );
+ }
+ }
+
+ // Register feature and its tools
+ this.features.set(feature.name, feature);
+ for (const tool of feature.tools) {
+ this.tools.set(tool.definition.name, tool);
+ }
+
+ logger.info(`MCP feature registered: ${feature.name}`, {
+ featureName: feature.name,
+ toolCount: feature.tools.length,
+ toolNames: feature.tools.map((t) => t.definition.name),
+ });
+ }
+
+ /**
+ * Get all registered tool definitions (for ListTools handler)
+ *
+ * @param context - Server context for feature enablement checks
+ * @returns Array of tool definitions from enabled features
+ */
+ async getToolDefinitions(context: ServerContext): Promise<ToolDefinition[]> {
+ const definitions: ToolDefinition[] = [];
+
+ for (const feature of this.features.values()) {
+ // Check if feature is enabled for this context
+ if (feature.isEnabled && !(await feature.isEnabled(context))) {
+ continue;
+ }
+
+ // Add all tools from enabled feature
+ for (const tool of feature.tools) {
+ definitions.push(tool.definition);
+ }
+ }
+
+ return definitions;
+ }
+
+ /**
+ * Get tool handler by name (for CallTool handler)
+ *
+ * @param name - Tool name to lookup
+ * @returns Registered tool or undefined if not found
+ */
+ getTool(name: string): RegisteredTool | undefined {
+ return this.tools.get(name);
+ }
+
+ /**
+ * Get feature name for a tool (for error messages)
+ *
+ * @param toolName - Tool name to lookup
+ * @returns Feature name or "unknown"
+ */
+ private getToolFeature(toolName: string): string {
+ for (const [featureName, feature] of this.features.entries()) {
+ if (feature.tools.some((t) => t.definition.name === toolName)) {
+ return featureName;
+ }
+ }
+ return "unknown";
+ }
+
+ /**
+ * Get all registered features
+ *
+ * @returns Array of all feature modules
+ */
+ getFeatures(): McpFeatureModule[] {
+ return Array.from(this.features.values());
+ }
+
+ /**
+ * Get feature count (for diagnostics)
+ */
+ getFeatureCount(): number {
+ return this.features.size;
+ }
+
+ /**
+ * Get tool count (for diagnostics)
+ */
+ getToolCount(): number {
+ return this.tools.size;
+ }
+}
+
+/**
+ * Global singleton registry instance
+ *
+ * Exported for use across the application.
+ * Features register themselves at module load time.
+ */
+export const toolRegistry = new ToolRegistry();
diff --git a/web/src/features/mcp/server/transport.ts b/web/src/features/mcp/server/transport.ts
new file mode 100644
index 0000000000..7dfa82c28e
--- /dev/null
+++ b/web/src/features/mcp/server/transport.ts
@@ -0,0 +1,105 @@
+/**
+ * MCP Streamable HTTP Transport
+ *
+ * Implements the Streamable HTTP transport for the Model Context Protocol (2025-03-26 spec).
+ * This transport allows MCP communication over HTTP with JSON-RPC messages.
+ *
+ */
+
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { type Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
+import { formatErrorForUser } from "../core/error-formatting";
+import { logger } from "@langfuse/shared/src/server";
+
+/**
+ * Handle MCP request using Streamable HTTP transport.
+ *
+ * This function:
+ * 1. Sets CORS headers for MCP clients
+ * 2. Creates a StreamableHTTPServerTransport (stateless mode)
+ * 3. Connects the server to the transport
+ * 4. Routes the request to the transport handler
+ * 5. Transport handles the response lifecycle
+ *
+ * Supports:
+ * - POST: JSON-RPC requests (initialize, tool calls, etc.)
+ * - GET: SSE stream for server-initiated messages (optional)
+ * - DELETE: Session termination (returns 405 for stateless)
+ * - OPTIONS: CORS preflight
+ *
+ * @param server - MCP Server instance (created per-request)
+ * @param req - Next.js API request
+ * @param res - Next.js API response
+ */
+export async function handleMcpRequest(
+ server: Server,
+ req: NextApiRequest,
+ res: NextApiResponse,
+): Promise<void> {
+ try {
+ // Note: CORS headers and OPTIONS handling are now in index.ts (before authentication)
+
+ // Validate Accept header for POST requests (per spec)
+ if (req.method === "POST") {
+ const acceptHeader = req.headers.accept || "";
+ if (
+ !acceptHeader.includes("application/json") &&
+ !acceptHeader.includes("text/event-stream") &&
+ !acceptHeader.includes("*/*")
+ ) {
+ res.status(406).json({
+ jsonrpc: "2.0",
+ error: {
+ code: -32600,
+ message:
+ "Invalid Request: Accept header must include application/json or text/event-stream",
+ },
+ id: null,
+ });
+ return;
+ }
+ }
+
+ // Create Streamable HTTP transport (stateless mode - no sessionIdGenerator)
+ const transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: undefined, // Stateless mode
+ enableJsonResponse: true, // Use JSON response (simpler for stateless mode)
+ });
+
+ // Connect server to transport
+ await server.connect(transport);
+
+ logger.info("MCP server connected via Streamable HTTP transport", {
+ method: req.method,
+ });
+
+ // Handle the request through the transport
+ // IMPORTANT: The transport manages the response lifecycle internally.
+ // It will send the response and end it when appropriate.
+ // Do NOT call res.end() after this - the transport handles it.
+ await transport.handleRequest(req, res, req.body);
+
+ // Note: Do NOT end the response here. The transport has already
+ // sent the response (JSON or SSE) and ended it appropriately.
+ } catch (error) {
+ logger.error("MCP transport error", {
+ message: error instanceof Error ? error.message : "Unknown error",
+ name: error instanceof Error ? error.name : typeof error,
+ method: req.method,
+ });
+
+ // If headers not sent, send JSON-RPC error response
+ if (!res.headersSent) {
+ const mcpError = formatErrorForUser(error);
+ res.status(500).json({
+ jsonrpc: "2.0",
+ error: {
+ code: -32603,
+ message: mcpError.message,
+ },
+ id: null,
+ });
+ }
+ }
+}
diff --git a/web/src/features/mcp/types.ts b/web/src/features/mcp/types.ts
new file mode 100644
index 0000000000..39268b35c7
--- /dev/null
+++ b/web/src/features/mcp/types.ts
@@ -0,0 +1,51 @@
+/**
+ * MCP (Model Context Protocol) Server Types
+ *
+ * Type definitions for the Langfuse MCP server implementation.
+ * Following stateless design pattern from Sentry MCP server.
+ */
+
+/**
+ * Server context captured from authenticated request.
+ * Stateless design - all context from request, no session storage.
+ *
+ * SECURITY & COMPLIANCE:
+ *
+ * Audit Logging: All mutating operations must create audit log entries
+ * using @/src/features/audit-logs/auditLog
+ *
+ * PII Protection: userId is PII - use sanitized logging
+ *
+ * RBAC: Check accessLevel and scope before operations
+ *
+ * Rate Limiting: Use RateLimitService from public API
+ *
+ * @see /web/src/features/public-api/server/apiAuth.ts - Auth patterns
+ * @see /web/src/features/audit-logs/auditLog.ts - Audit logging
+ * @see /web/src/features/rbac/README.md - RBAC patterns
+ */
+export interface ServerContext {
+ /**
+ * Project ID from authenticated API key
+ * MCP requires project-scoped access only (never null)
+ */
+ projectId: string;
+
+ /** Organization ID from authenticated API key */
+ orgId: string;
+
+ /** User ID from authenticated user (optional for API key auth) */
+ userId?: string;
+
+ /** API Key ID for audit logging */
+ apiKeyId: string;
+
+ /**
+ * Access level from API key
+ * MCP enforces "project" level access only
+ */
+ accessLevel: "project";
+
+ /** Public key used for authentication */
+ publicKey: string;
+}
diff --git a/web/src/features/prompts/server/handlers/promptVersionHandler.ts b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
index 018490ede6..1d4514d1bf 100644
--- a/web/src/features/prompts/server/handlers/promptVersionHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
@@ -1,5 +1,6 @@
import { logger } from "@langfuse/shared/src/server";
import { z } from "zod/v4";
+import { LATEST_PROMPT_LABEL } from "@langfuse/shared";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
@@ -9,7 +10,7 @@ import { auditLog } from "@/src/features/audit-logs/auditLog";
const UpdatePromptBodySchema = z.object({
newLabels: z
.array(z.string())
- .refine((labels) => !labels.includes("latest"), {
+ .refine((labels) => !labels.includes(LATEST_PROMPT_LABEL), {
message: "Label 'latest' is always assigned to the latest prompt version",
}),
});
diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.ts
new file mode 100644
index 0000000000..9c69cee399
--- /dev/null
+++ b/web/src/pages/api/public/mcp/index.ts
@@ -0,0 +1,166 @@
+/**
+ * MCP (Model Context Protocol) Server API Endpoint
+ *
+ * This endpoint implements the MCP protocol for Langfuse, enabling AI assistants
+ * like Claude Desktop and Cursor to directly query, create, and manage Langfuse prompts.
+ *
+ * Architecture:
+ * - Stateless per-request pattern (fresh server instance per request)
+ * - Streamable HTTP transport (2025-03-26 spec)
+ * - BasicAuth using Langfuse API keys
+ * - Context captured in closures (no session storage)
+ *
+ * Transport: Streamable HTTP (NOT the deprecated HTTP+SSE transport)
+ * - Single endpoint handles POST (JSON-RPC), GET (SSE streams), DELETE (sessions)
+ * - JSON-RPC messages sent via POST body
+ * - No separate /message endpoint needed
+ *
+ * Note: This endpoint does NOT use withMiddlewares() like other public APIs because
+ * the transport layer needs direct response control for both JSON and SSE responses.
+ * Error handling and CORS are implemented directly in the transport layer.
+ *
+ * Authentication: BasicAuth (Public Key:Secret Key) - LF-1927
+ * Resources: Added in LF-1928
+ * Tools: Added in LF-1929
+ */
+
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { createMcpServer } from "@/src/features/mcp/server/mcpServer";
+import { handleMcpRequest } from "@/src/features/mcp/server/transport";
+import { formatErrorForUser } from "@/src/features/mcp/core/error-formatting";
+import { type ServerContext } from "@/src/features/mcp/types";
+import { logger, redis } from "@langfuse/shared/src/server";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
+import { prisma } from "@langfuse/shared/src/db";
+import { UnauthorizedError, ForbiddenError } from "@langfuse/shared";
+
+// Bootstrap MCP features - registers all tools at module load time
+import "@/src/features/mcp/server/bootstrap";
+
+/**
+ * MCP API Route Handler
+ *
+ * Handles MCP protocol requests using Streamable HTTP (SSE) transport.
+ *
+ * Request flow:
+ * 1. Authenticate request using BasicAuth (Public Key:Secret Key)
+ * 2. Check rate limits
+ * 3. Extract ServerContext from authenticated API key
+ * 4. Create fresh MCP server instance with context in closures
+ * 5. Connect to SSE transport
+ * 6. Handle MCP protocol communication
+ * 7. Discard server instance after request
+ *
+ * @param req - Next.js API request
+ * @param res - Next.js API response
+ */
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ try {
+ // CORS headers for MCP clients (must be set before authentication)
+ res.setHeader("Access-Control-Allow-Origin", "*");
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
+ res.setHeader(
+ "Access-Control-Allow-Headers",
+ "Content-Type, Authorization, Accept, Mcp-Session-Id, Last-Event-ID",
+ );
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
+
+ // Handle preflight OPTIONS request (before authentication)
+ if (req.method === "OPTIONS") {
+ res.status(200).end();
+ return;
+ }
+
+ // Authenticate request using BasicAuth (Public Key:Secret Key)
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
+
+ if (!authCheck.validKey) {
+ throw new UnauthorizedError(authCheck.error);
+ }
+
+ // MCP requires project-scoped access (no Bearer auth, no org-level keys)
+ if (
+ authCheck.scope.accessLevel !== "project" ||
+ !authCheck.scope.projectId
+ ) {
+ throw new ForbiddenError(
+ "Access denied: MCP requires project-scoped API keys with BasicAuth",
+ );
+ }
+
+ // Check if ingestion is suspended due to usage limits
+ if (authCheck.scope.isIngestionSuspended) {
+ throw new ForbiddenError(
+ "Access suspended: Usage threshold exceeded. Please upgrade your plan.",
+ );
+ }
+
+ // Rate limit MCP requests
+ const rateLimitCheck =
+ await RateLimitService.getInstance().rateLimitRequest(
+ authCheck.scope,
+ "public-api",
+ );
+
+ if (rateLimitCheck?.isRateLimited()) {
+ return rateLimitCheck.sendRestResponseIfLimited(res);
+ }
+
+ // Build ServerContext from authenticated scope
+ const context: ServerContext = {
+ projectId: authCheck.scope.projectId,
+ orgId: authCheck.scope.orgId,
+ userId: undefined, // API keys don't have associated users
+ apiKeyId: authCheck.scope.apiKeyId,
+ accessLevel: "project",
+ publicKey: authCheck.scope.publicKey,
+ };
+
+ logger.info("MCP request authenticated", {
+ method: req.method,
+ projectId: context.projectId,
+ orgId: context.orgId,
+ userAgent: req.headers["user-agent"],
+ contentType: req.headers["content-type"],
+ accept: req.headers.accept,
+ });
+
+ // Build fresh server per request (stateless pattern)
+ // Context is captured in closures and available to all handlers
+ const server = createMcpServer(context);
+
+ // Handle the MCP request using Streamable HTTP transport
+ // Transport handles routing based on HTTP method (POST, GET, DELETE, OPTIONS)
+ await handleMcpRequest(server, req, res);
+ } catch (error) {
+ logger.error("MCP API route error", {
+ message: error instanceof Error ? error.message : "Unknown error",
+ });
+
+ // Format error for user (never throw from handler)
+ if (!res.headersSent) {
+ const mcpError = formatErrorForUser(error);
+ res.status(500).json({
+ error: mcpError.message,
+ code: mcpError.code,
+ });
+ }
+ }
+}
+
+/**
+ * Enable body parsing for JSON-RPC messages
+ * Streamable HTTP transport receives JSON-RPC via POST body
+ */
+export const config = {
+ api: {
+ bodyParser: true,
+ },
+};