🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(MCP, API): Add feedback submission via public API and MCP tool (#14923)
Lysander Kiesela9f0808ffbf1
diff --git a/.env.dev.example b/.env.dev.exampleindex 2bf28c53ac..fdc4f2dfdf 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -167,6 +167,8 @@ NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"SLACK_CLIENT_ID=your_slack_client_idSLACK_CLIENT_SECRET=your_slack_client_secretSLACK_STATE_SECRET=your_slack_state_secret+# Optional internal feedback sink for feedback intake endpoints+# LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK=# Langfuse AI instance for tracing, promptsLANGFUSE_AI_FEATURES_PUBLIC_KEY="pk-lf-1234567890"diff --git a/.env.prod.example b/.env.prod.exampleindex 08d9c5ae68..1c288d77a2 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -306,6 +306,7 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# NEXTAUTH_COOKIE_DOMAIN=".langfuse.com"# LANGFUSE_TEAM_SLACK_WEBHOOK=+# LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK=# LANGFUSE_NEW_USER_SIGNUP_WEBHOOK=# Posthog (optional for analytics of web ui)diff --git a/fern/apis/server/definition/feedback.yml b/fern/apis/server/definition/feedback.ymlnew file mode 100644index 0000000000..f151528a2d--- /dev/null+++ b/fern/apis/server/definition/feedback.yml@@ -0,0 +1,52 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+service:+ auth: true+ base-path: /api/public+ endpoints:+ submit:+ docs: Submit explicit user-approved feedback about Langfuse skills, MCP tools, CLI, docs, or public API. Do not include secrets, credentials, customer data, trace payloads, or unrelated use-case details.+ method: POST+ path: /feedback+ request: SubmitFeedbackRequest+ response:+ status-code: 201+ type: SubmitFeedbackResponse+ errors:+ - FeedbackNotConfiguredError+types:+ FeedbackTargetType:+ enum:+ - skill+ - value: mcp-tool+ name: McpTool+ - cli+ - docs+ - value: public-api+ name: PublicApi+ - other+ SubmitFeedbackRequest:+ properties:+ targetType:+ type: FeedbackTargetType+ docs: Category of the thing the feedback is about.+ target:+ type: string+ docs: "The specific instance within targetType: the skill name, MCP tool name, CLI command, API endpoint path, or docs page path (e.g. 'queryMetrics', '/docs/mcp'). An identifier, not a sentence. Must be between 1 and 200 characters."+ feedback:+ type: string+ docs: Concise feedback text approved by the user. Must be between 1 and 3000 characters.+ goal:+ type: optional<string>+ docs: Optional user-approved goal or use case they were trying to achieve. Must be between 1 and 1500 characters when provided. Do not include secrets, customer data, trace payloads, or broad unrelated context.+ referenceUrl:+ type: optional<string>+ docs: Optional HTTP(S) reference URL. Langfuse stores it as text for triage and does not fetch it.+ SubmitFeedbackResponse:+ properties:+ id:+ type: string+ docs: Correlation ID for the submitted feedback.+errors:+ FeedbackNotConfiguredError:+ docs: Feedback submission is not configured for this deployment.+ status-code: 409diff --git a/packages/shared/src/interfaces/rate-limits.ts b/packages/shared/src/interfaces/rate-limits.tsindex 4aeb6fdbc0..bbf1c1f78a 100644--- a/packages/shared/src/interfaces/rate-limits.ts+++ b/packages/shared/src/interfaces/rate-limits.ts@@ -15,6 +15,7 @@ export const RateLimitResource = z.enum(["trace-delete","score-delete","in-app-agent-run",+ "feedback",]);// result of the rate limit check.diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 29f7e4e213..c10e689fc9 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -1796,6 +1796,57 @@ paths:application/json:schema: {}security: *ref_0+ /api/public/feedback:+ post:+ description: >-+ Submit explicit user-approved feedback about Langfuse skills, MCP tools,+ CLI, docs, or public API. Do not include secrets, credentials, customer+ data, trace payloads, or unrelated use-case details.+ operationId: feedback_submit+ tags:+ - Feedback+ parameters: []+ responses:+ '201':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SubmitFeedbackResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '409':+ description: ''+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SubmitFeedbackRequest'/api/public/health:get:description: Check health of API and database@@ -11097,6 +11148,61 @@ components:- experimentId- experimentName- experimentItemId+ FeedbackTargetType:+ title: FeedbackTargetType+ type: string+ enum:+ - skill+ - mcp-tool+ - cli+ - docs+ - public-api+ - other+ SubmitFeedbackRequest:+ title: SubmitFeedbackRequest+ type: object+ properties:+ targetType:+ $ref: '#/components/schemas/FeedbackTargetType'+ description: Category of the thing the feedback is about.+ target:+ type: string+ description: >-+ The specific instance within targetType: the skill name, MCP tool+ name, CLI command, API endpoint path, or docs page path (e.g.+ 'queryMetrics', '/docs/mcp'). An identifier, not a sentence. Must be+ between 1 and 200 characters.+ feedback:+ type: string+ description: >-+ Concise feedback text approved by the user. Must be between 1 and+ 3000 characters.+ goal:+ type: string+ nullable: true+ description: >-+ Optional user-approved goal or use case they were trying to achieve.+ Must be between 1 and 1500 characters when provided. Do not include+ secrets, customer data, trace payloads, or broad unrelated context.+ referenceUrl:+ type: string+ nullable: true+ description: >-+ Optional HTTP(S) reference URL. Langfuse stores it as text for+ triage and does not fetch it.+ required:+ - targetType+ - target+ - feedback+ SubmitFeedbackResponse:+ title: SubmitFeedbackResponse+ type: object+ properties:+ id:+ type: string+ description: Correlation ID for the submitted feedback.+ required:+ - idHealthResponse:title: HealthResponsetype: objectdiff --git a/web/src/__tests__/server/mcp-error-formatting.servertest.ts b/web/src/__tests__/server/mcp-error-formatting.servertest.tsindex a8a2e64695..9ee32af15c 100644--- a/web/src/__tests__/server/mcp-error-formatting.servertest.ts+++ b/web/src/__tests__/server/mcp-error-formatting.servertest.ts@@ -203,18 +203,33 @@ describe("MCP Error Formatting", () => {);});- it("should format BaseError as InvalidRequest", () => {+ it("should format client-side BaseError as InvalidRequest", () => {const error = new BaseError("Generic base error",- 500,+ 400,"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);+ expect(mcpError.message).toContain("Generic base error");+ });++ it("should sanitize server-side BaseError as InternalError", () => {+ const error = new BaseError(+ "Database connection failed",+ 500,+ "Database connection failed",+ true,+ );+ const mcpError = formatErrorForUser(error);++ expect(mcpError.code).toBe(ErrorCode.InternalError);+ expect(mcpError.message).toContain(+ "An internal server error occurred.",+ );+ expect(mcpError.message).not.toContain("Database");});});diff --git a/web/src/__tests__/server/mcp-helpers.ts b/web/src/__tests__/server/mcp-helpers.tsindex ae637074f0..873ea10ebf 100644--- a/web/src/__tests__/server/mcp-helpers.ts+++ b/web/src/__tests__/server/mcp-helpers.ts@@ -42,6 +42,8 @@ export async function createMcpTestSetup(): Promise<{apiKeyId: apiKey.id,accessLevel: "project",publicKey: result.publicKey,+ plan: "oss",+ rateLimitOverrides: [],};return {@@ -66,6 +68,8 @@ export function mockServerContext(apiKeyId: overrides?.apiKeyId ?? "test-api-key-id",accessLevel: "project",publicKey: overrides?.publicKey ?? "pk-lf-test",+ plan: overrides?.plan ?? "oss",+ rateLimitOverrides: overrides?.rateLimitOverrides ?? [],...overrides,};}diff --git a/web/src/__tests__/server/unit/feedback-api.servertest.ts b/web/src/__tests__/server/unit/feedback-api.servertest.tsnew file mode 100644index 0000000000..4ba6f31e77--- /dev/null+++ b/web/src/__tests__/server/unit/feedback-api.servertest.ts@@ -0,0 +1,152 @@+import {+ LangfuseConflictError,+ ServiceUnavailableError,+} from "@langfuse/shared";+import type { NextApiRequest, NextApiResponse } from "next";+import { createMocks } from "node-mocks-http";+import { beforeEach, describe, expect, it, vi } from "vitest";++const { mockRateLimitRequest, mockSubmitFeedback, mockVerifyAuth } = vi.hoisted(+ () => ({+ mockRateLimitRequest: vi.fn(),+ mockSubmitFeedback: vi.fn(),+ mockVerifyAuth: vi.fn(),+ }),+);++vi.mock("@/src/features/feedback/server/FeedbackService", () => ({+ submitFeedback: mockSubmitFeedback,+}));++vi.mock("@/src/features/public-api/server/apiAuth", () => {+ function ApiAuthService() {+ return {+ verifyAuthHeaderAndReturnScope: mockVerifyAuth,+ };+ }++ return { ApiAuthService };+});++vi.mock("@/src/features/public-api/server/RateLimitService", () => ({+ RateLimitService: {+ getInstance: () => ({+ rateLimitRequest: mockRateLimitRequest,+ }),+ },+}));++import handler from "@/src/pages/api/public/feedback";++const validScope = {+ projectId: "project-1",+ orgId: "org-1",+ plan: "oss",+ rateLimitOverrides: [],+ apiKeyId: "api-key-1",+ publicKey: "pk-test",+ accessLevel: "project",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+};++const validBody = {+ targetType: "docs",+ target: "skill-feedback.md",+ feedback: "Please mention the MCP feedback tool.",+ goal: "I wanted to send feedback after using a Langfuse skill.",+ referenceUrl: "https://langfuse.com/docs",+};++const createRequest = (body: Record<string, unknown> | null) => {+ const mocks = createMocks<NextApiRequest, NextApiResponse>({+ method: "POST",+ headers: {+ authorization: "Basic test",+ "content-type": "application/json",+ },+ body: body ?? {},+ });++ if (body === null) mocks.req.body = null;++ return mocks;+};++describe("POST /api/public/feedback", () => {+ beforeEach(() => {+ mockRateLimitRequest.mockReset();+ mockSubmitFeedback.mockReset();+ mockVerifyAuth.mockReset();++ mockRateLimitRequest.mockResolvedValue(undefined);+ mockSubmitFeedback.mockResolvedValue({+ id: "11111111-1111-4111-8111-111111111111",+ });+ mockVerifyAuth.mockResolvedValue({+ validKey: true,+ scope: validScope,+ });+ });++ it("posts feedback and returns a correlation id", async () => {+ const { req, res } = createRequest(validBody);++ await handler(req, res);++ expect(res._getStatusCode()).toBe(201);+ expect(JSON.parse(res._getData())).toEqual({+ id: "11111111-1111-4111-8111-111111111111",+ });+ expect(mockSubmitFeedback).toHaveBeenCalledWith({+ input: validBody,+ scope: validScope,+ source: "public-api",+ });+ expect(mockRateLimitRequest).toHaveBeenCalledWith(validScope, "public-api");+ });++ it("returns 400 for a null body", async () => {+ const { req, res } = createRequest(null);++ await handler(req, res);++ expect(res._getStatusCode()).toBe(400);+ expect(JSON.parse(res._getData())).toMatchObject({+ message: "Invalid request data",+ });+ expect(mockSubmitFeedback).not.toHaveBeenCalled();+ });++ it("returns 503 when the feedback sink is unavailable", async () => {+ mockSubmitFeedback.mockRejectedValueOnce(+ new ServiceUnavailableError("Feedback Slack sink rejected message"),+ );+ const { req, res } = createRequest(validBody);++ await handler(req, res);++ expect(res._getStatusCode()).toBe(503);+ expect(JSON.parse(res._getData())).toMatchObject({+ message: "Feedback Slack sink rejected message",+ error: "ServiceUnavailableError",+ });+ });++ it("returns 409 when feedback is not configured", async () => {+ mockSubmitFeedback.mockRejectedValueOnce(+ new LangfuseConflictError(+ "Feedback submission is not configured for this deployment",+ ),+ );+ const { req, res } = createRequest(validBody);++ await handler(req, res);++ expect(res._getStatusCode()).toBe(409);+ expect(JSON.parse(res._getData())).toMatchObject({+ message: "Feedback submission is not configured for this deployment",+ error: "LangfuseConflictError",+ });+ });+});diff --git a/web/src/__tests__/server/unit/feedback-service.servertest.ts b/web/src/__tests__/server/unit/feedback-service.servertest.tsnew file mode 100644index 0000000000..2a0c182668--- /dev/null+++ b/web/src/__tests__/server/unit/feedback-service.servertest.ts@@ -0,0 +1,281 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ LangfuseConflictError,+ ServiceUnavailableError,+} from "@langfuse/shared";+import type { ApiAccessScope } from "@langfuse/shared/src/server";+import type * as SharedServer from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";++const { mockRateLimitRequest, mockRecordIncrement, mockLoggerWarn } =+ vi.hoisted(() => ({+ mockRateLimitRequest: vi.fn(),+ mockRecordIncrement: vi.fn(),+ mockLoggerWarn: vi.fn(),+ }));++vi.mock("@langfuse/shared/src/server", async () => {+ const actual = await vi.importActual<typeof SharedServer>(+ "@langfuse/shared/src/server",+ );+ return {+ ...actual,+ recordIncrement: mockRecordIncrement,+ logger: Object.assign(Object.create(actual.logger), {+ warn: mockLoggerWarn,+ }),+ };+});++vi.mock("@/src/features/public-api/server/RateLimitService", () => ({+ RateLimitService: {+ getInstance: () => ({+ rateLimitRequest: mockRateLimitRequest,+ }),+ },+}));++import { submitFeedback } from "@/src/features/feedback/server/FeedbackService";+import { PostFeedbackBody } from "@/src/features/public-api/types/feedback";++const scope = {+ projectId: "project-1",+ orgId: "org-1",+ accessLevel: "project",+ plan: "cloud:pro",+ rateLimitOverrides: [],+ apiKeyId: "api-key-1",+ publicKey: "pk-test",+ isIngestionSuspended: false,+} as ApiAccessScope;++type SlackBlockForTest = {+ type?: string;+ text?: {+ type?: string;+ text?: string;+ };+ fields?: Array<{ type?: string; text?: string }>;+ elements?: Array<{ type?: string; text?: string }>;+};++describe("FeedbackService", () => {+ const originalWebhookUrl = env.LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK;+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalNodeEnv = env.NODE_ENV;++ beforeEach(() => {+ mockRateLimitRequest.mockReset();+ mockRateLimitRequest.mockResolvedValue(undefined);+ mockRecordIncrement.mockReset();+ mockLoggerWarn.mockReset();+ (env as any).LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK =+ "https://hooks.slack.com/services/test";+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ (env as any).LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK = originalWebhookUrl;+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ (env as any).NODE_ENV = originalNodeEnv;+ });++ it("posts a Slack-safe payload and maps sink failures to service unavailable", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response("ok", { status: 200 }))+ .mockResolvedValueOnce(new Response("error", { status: 500 }))+ .mockRejectedValueOnce(new DOMException("Timed out", "TimeoutError"));+ vi.stubGlobal("fetch", fetchMock);++ const input = {+ targetType: "mcp-tool" as const,+ target: "submitFeedback",+ feedback:+ "This mentions @here and <!channel> and <https://example.com|link>.",+ goal: "Help improve feedback guidance without alerting the channel.",+ referenceUrl: "https://example.com/reference",+ };++ const result = await submitFeedback({+ scope,+ input,+ source: "langfuse-mcp",+ });++ expect(result.id).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ );+ expect(mockRateLimitRequest).toHaveBeenCalledWith(scope, "feedback");+ expect(fetchMock).toHaveBeenCalledWith(+ "https://hooks.slack.com/services/test",+ expect.objectContaining({+ method: "POST",+ redirect: "error",+ headers: { "Content-Type": "application/json" },+ }),+ );++ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string) as {+ text: string;+ unfurl_links: boolean;+ unfurl_media: boolean;+ blocks: SlackBlockForTest[];+ };+ expect(body.text).toBe(+ `New Langfuse feedback · Langfuse MCP · mcp-tool · ${result.id}`,+ );+ expect(body.unfurl_links).toBe(false);+ expect(body.unfurl_media).toBe(false);+ expect(+ body.blocks.at(-1)?.elements?.map((element) => element.text),+ ).toEqual([+ `🧾 Receipt: ${result.id}`,+ "🏢 Org: org-1",+ "📁 Project: project-1",+ ]);++ // User-authored text must stay plain_text so mentions cannot ping.+ const feedbackBlock = body.blocks.find(+ (block) =>+ block.type === "section" &&+ block.text?.type === "plain_text" &&+ block.text.text?.includes("@here"),+ );+ expect(feedbackBlock).toBeTruthy();++ await expect(+ submitFeedback({ scope, input, source: "langfuse-mcp" }),+ ).rejects.toBeInstanceOf(ServiceUnavailableError);+ await expect(+ submitFeedback({ scope, input, source: "langfuse-mcp" }),+ ).rejects.toBeInstanceOf(ServiceUnavailableError);+ });++ it("rejects unsafe reference URLs at the schema boundary", () => {+ expect(+ PostFeedbackBody.safeParse({+ targetType: "docs",+ target: "/docs/mcp",+ feedback: "Please clarify setup.",+ referenceUrl: "javascript:alert(1)",+ }).success,+ ).toBe(false);+ });++ it("rejects insecure Slack sinks in production", async () => {+ (env as any).NODE_ENV = "production";+ (env as any).LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK =+ "http://hooks.slack.com/services/test";++ await expect(+ submitFeedback({+ scope,+ input: {+ targetType: "docs",+ target: "/docs/mcp",+ feedback: "Please clarify setup.",+ },+ source: "public-api",+ }),+ ).rejects.toBeInstanceOf(ServiceUnavailableError);+ });++ it("throws a 429 when the org feedback rate limit is exhausted", async () => {+ mockRateLimitRequest.mockResolvedValueOnce({+ isRateLimited: () => true,+ });+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ submitFeedback({+ scope,+ input: {+ targetType: "docs",+ target: "/docs/mcp",+ feedback: "Please clarify setup.",+ },+ source: "public-api",+ }),+ ).rejects.toMatchObject({ httpCode: 429 });++ expect(fetchMock).not.toHaveBeenCalled();+ expect(mockRecordIncrement).toHaveBeenCalledWith(+ "langfuse.feedback.submission",+ 1,+ { source: "public-api", outcome: "rate_limited" },+ );+ });++ it("returns a sanitized conflict when the Slack sink is not configured", async () => {+ (env as any).LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK = undefined;+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ const input = {+ targetType: "docs" as const,+ target: "sensitive-target",+ feedback: "sensitive-feedback",+ goal: "sensitive-goal",+ referenceUrl: "https://example.com/sensitive-reference",+ };++ await expect(+ submitFeedback({ scope, input, source: "public-api" }),+ ).rejects.toEqual(+ new LangfuseConflictError(+ "Feedback submission is not configured for this deployment",+ ),+ );++ expect(fetchMock).not.toHaveBeenCalled();+ expect(mockRecordIncrement).toHaveBeenCalledWith(+ "langfuse.feedback.submission",+ 1,+ { source: "public-api", outcome: "sink_unconfigured" },+ );+ expect(mockLoggerWarn).toHaveBeenCalledWith(+ "Feedback intake sink is not configured",+ {+ source: "public-api",+ targetType: "docs",+ orgId: "org-1",+ projectId: "project-1",+ region: "self-hosted",+ },+ );+ expect(JSON.stringify(mockLoggerWarn.mock.calls)).not.toContain(+ "sensitive-feedback",+ );+ expect(JSON.stringify(mockLoggerWarn.mock.calls)).not.toContain(+ "sensitive-target",+ );+ });++ it("never delivers to Slack in the HIPAA region even with a configured sink", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "HIPAA";+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ submitFeedback({+ scope,+ input: {+ targetType: "docs",+ target: "/docs/mcp",+ feedback: "Please clarify setup.",+ },+ source: "public-api",+ }),+ ).rejects.toBeInstanceOf(LangfuseConflictError);++ expect(fetchMock).not.toHaveBeenCalled();+ expect(mockRecordIncrement).toHaveBeenCalledWith(+ "langfuse.feedback.submission",+ 1,+ { source: "public-api", outcome: "sink_unconfigured" },+ );+ });+});diff --git a/web/src/ee/features/in-app-agent/server/tools.ts b/web/src/ee/features/in-app-agent/server/tools.tsindex 69321e4062..a12c566823 100644--- a/web/src/ee/features/in-app-agent/server/tools.ts+++ b/web/src/ee/features/in-app-agent/server/tools.ts@@ -194,6 +194,10 @@ export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES: Record<approval: "auto",availability: { scope: "project:read" },},+ submitFeedback: {+ approval: "approval",+ availability: { scope: "project:read" },+ },getHealth: {approval: "auto",availability: { scope: "project:read" },diff --git a/web/src/env.mjs b/web/src/env.mjsindex b2cd821306..1fab50b645 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -91,6 +91,7 @@ export const env = createEnv({).optional(),LANGFUSE_TEAM_SLACK_WEBHOOK: z.url().optional(),+ LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK: z.url().optional(),LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.url().optional(),LANGFUSE_ADMIN_ACCESS_WEBHOOK: z.url().optional(),// Add `.min(1) on ID and SECRET if you want to make sure they're not empty@@ -593,6 +594,8 @@ export const env = createEnv({LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION:process.env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION,LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,+ LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK:+ process.env.LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK,LANGFUSE_NEW_USER_SIGNUP_WEBHOOK:process.env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK,LANGFUSE_ADMIN_ACCESS_WEBHOOK: process.env.LANGFUSE_ADMIN_ACCESS_WEBHOOK,diff --git a/web/src/features/feedback/server/FeedbackService.ts b/web/src/features/feedback/server/FeedbackService.tsnew file mode 100644index 0000000000..ceb5e90526--- /dev/null+++ b/web/src/features/feedback/server/FeedbackService.ts@@ -0,0 +1,283 @@+import { randomUUID } from "node:crypto";+import {+ BaseError,+ LangfuseConflictError,+ ServiceUnavailableError,+} from "@langfuse/shared";+import type { ApiAccessScope } from "@langfuse/shared/src/server";+import { logger, recordIncrement } from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";+import type {+ PostFeedbackBodyType,+ PostFeedbackResponseType,+} from "@/src/features/public-api/types/feedback";++export type FeedbackSource = "langfuse-mcp" | "public-api";++type FeedbackContext = {+ projectId: string;+ orgId: string;+};++type SlackTextObject = {+ type: "plain_text" | "mrkdwn";+ text: string;+ emoji?: boolean;+};++type SlackBlock =+ | {+ type: "header";+ text: SlackTextObject;+ }+ | {+ type: "section";+ text: SlackTextObject;+ }+ | {+ type: "section";+ fields: SlackTextObject[];+ }+ | {+ type: "divider";+ }+ | {+ type: "context";+ elements: SlackTextObject[];+ };++type SlackPayload = {+ text: string;+ blocks: SlackBlock[];+ unfurl_links: false;+ unfurl_media: false;+};++type FeedbackSlackMessage = SlackPayload;++const SLACK_SECTION_TEXT_LIMIT = 3000;+const SLACK_FIELD_TEXT_LIMIT = 2000;+const FEEDBACK_SLACK_TIMEOUT_MS = 5_000;++const truncateForSlack = (value: string, maxLength: number): string => {+ if (value.length <= maxLength) return value;+ return `${value.slice(0, Math.max(0, maxLength - 14))}\n[truncated]`;+};++const plainText = (value: string, maxLength: number): SlackTextObject => ({+ type: "plain_text",+ text: truncateForSlack(value, maxLength),+ emoji: false,+});++const mrkdwnText = (value: string): SlackTextObject => ({+ type: "mrkdwn",+ text: value,+});++const appendPlainTextSection = (+ blocks: SlackBlock[],+ label: string,+ value: string | undefined,+) => {+ if (!value) return;++ blocks.push(+ {+ type: "section",+ text: mrkdwnText(`*${label}*`),+ },+ {+ type: "section",+ text: plainText(value, SLACK_SECTION_TEXT_LIMIT),+ },+ );+};++const getDataRegion = (): string =>+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ?? "self-hosted";++const feedbackSourceLabel: Record<FeedbackSource, string> = {+ "langfuse-mcp": "Langfuse MCP",+ "public-api": "Public API",+};++const buildFeedbackSlackMessage = ({+ id,+ input,+ source,+ context,+}: {+ id: string;+ input: PostFeedbackBodyType;+ source: FeedbackSource;+ context: FeedbackContext;+}): FeedbackSlackMessage => {+ const blocks: SlackBlock[] = [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: "💬 New Langfuse feedback",+ emoji: true,+ },+ },+ {+ type: "section",+ fields: [+ plainText(+ `📬 SOURCE:\n${feedbackSourceLabel[source]}`,+ SLACK_FIELD_TEXT_LIMIT,+ ),+ plainText(`🎯 TARGET:\n${input.target}`, SLACK_FIELD_TEXT_LIMIT),+ plainText(+ `🧩 TARGET TYPE:\n${input.targetType}`,+ SLACK_FIELD_TEXT_LIMIT,+ ),+ plainText(`🌍 REGION:\n${getDataRegion()}`, SLACK_FIELD_TEXT_LIMIT),+ ],+ },+ { type: "divider" },+ ];++ appendPlainTextSection(blocks, "💬 Feedback:", input.feedback);+ appendPlainTextSection(blocks, "🎯 Goal / use case:", input.goal);+ appendPlainTextSection(blocks, "🔗 Reference URL:", input.referenceUrl);++ blocks.push(+ { type: "divider" },+ {+ type: "context",+ elements: [+ plainText(`🧾 Receipt: ${id}`, SLACK_FIELD_TEXT_LIMIT),+ plainText(`🏢 Org: ${context.orgId}`, SLACK_FIELD_TEXT_LIMIT),+ plainText(`📁 Project: ${context.projectId}`, SLACK_FIELD_TEXT_LIMIT),+ ],+ },+ );++ return {+ text: `New Langfuse feedback · ${feedbackSourceLabel[source]} · ${input.targetType} · ${id}`,+ blocks,+ unfurl_links: false,+ unfurl_media: false,+ };+};++// The HIPAA region must never deliver feedback to Slack, even if a webhook+// were configured there by mistake.+const getConfiguredFeedbackWebhookUrl = (): string | undefined =>+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "HIPAA"+ ? undefined+ : env.LANGFUSE_FEEDBACK_INTAKE_SLACK_WEBHOOK;++const validateFeedbackWebhookUrl = (webhookUrl: string): string => {+ let parsed: URL;+ try {+ parsed = new URL(webhookUrl);+ } catch {+ throw new ServiceUnavailableError("Feedback Slack sink is misconfigured");+ }++ const requiresHttps = env.NODE_ENV === "production";+ const isInvalidCloudSink =+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&+ (parsed.protocol !== "https:" || parsed.hostname !== "hooks.slack.com");+ if ((requiresHttps && parsed.protocol !== "https:") || isInvalidCloudSink) {+ throw new ServiceUnavailableError("Feedback Slack sink is misconfigured");+ }++ return webhookUrl;+};++export const submitFeedback = async ({+ input,+ source,+ scope,+}: {+ input: PostFeedbackBodyType;+ source: FeedbackSource;+ scope: ApiAccessScope;+}): Promise<PostFeedbackResponseType> => {+ const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(+ scope,+ "feedback",+ );+ if (rateLimitCheck?.isRateLimited()) {+ recordIncrement("langfuse.feedback.submission", 1, {+ source,+ outcome: "rate_limited",+ });+ throw new BaseError(+ "TooManyRequestsError",+ 429,+ "Feedback rate limit exceeded",+ true,+ );+ }++ const configuredWebhookUrl = getConfiguredFeedbackWebhookUrl();+ if (!configuredWebhookUrl) {+ recordIncrement("langfuse.feedback.submission", 1, {+ source,+ outcome: "sink_unconfigured",+ });+ logger.warn("Feedback intake sink is not configured", {+ source,+ targetType: input.targetType,+ orgId: scope.orgId,+ projectId: scope.projectId,+ region: getDataRegion(),+ });+ throw new LangfuseConflictError(+ "Feedback submission is not configured for this deployment",+ );+ }++ const id = randomUUID();+ const webhookUrl = validateFeedbackWebhookUrl(configuredWebhookUrl);+ const payload = buildFeedbackSlackMessage({+ id,+ input,+ source,+ context: {+ orgId: scope.orgId,+ projectId: scope.projectId ?? "unknown",+ },+ });++ let response: Response;+ try {+ response = await fetch(webhookUrl, {+ method: "POST",+ redirect: "error",+ signal: AbortSignal.timeout(FEEDBACK_SLACK_TIMEOUT_MS),+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(payload),+ });+ } catch {+ recordIncrement("langfuse.feedback.submission", 1, {+ source,+ outcome: "sink_failed",+ });+ throw new ServiceUnavailableError("Feedback Slack sink request failed");+ }++ if (!response.ok) {+ recordIncrement("langfuse.feedback.submission", 1, {+ source,+ outcome: "sink_failed",+ });+ throw new ServiceUnavailableError("Feedback Slack sink rejected message");+ }++ recordIncrement("langfuse.feedback.submission", 1, {+ source,+ outcome: "accepted",+ });++ return { id };+};diff --git a/web/src/features/feedback/server/feedbackHandler.ts b/web/src/features/feedback/server/feedbackHandler.tsindex 85c1ec1d1e..ad967ccd45 100644--- a/web/src/features/feedback/server/feedbackHandler.ts+++ b/web/src/features/feedback/server/feedbackHandler.ts@@ -3,7 +3,7 @@ import { sendToSlack } from "@/src/features/slack/server/slack-webhook";import { type NextApiRequest, type NextApiResponse } from "next";import { logger } from "@langfuse/shared/src/server";-// Collects feedack from users that do not use the cloud version of the app+// Legacy endpoint used by older self-hosted Langfuse versions.export default async function feedbackApiHandler(req: NextApiRequest,res: NextApiResponse,diff --git a/web/src/features/mcp/core/error-formatting.ts b/web/src/features/mcp/core/error-formatting.tsindex e45f50c24c..c9487914cb 100644--- a/web/src/features/mcp/core/error-formatting.ts+++ b/web/src/features/mcp/core/error-formatting.ts@@ -76,6 +76,17 @@ export function formatErrorForUser(error: unknown): McpError {return new McpError(ErrorCode.InvalidRequest, error.message);}+ if (error instanceof BaseError && error.httpCode >= 500) {+ logger.error("MCP BaseError (server-side)", {+ name: error.name,+ httpCode: error.httpCode,+ });+ return new McpError(+ ErrorCode.InternalError,+ "An internal server error occurred. Please try again later.",+ );+ }+if (error instanceof BaseError) {logger.warn("MCP BaseError", error);return new McpError(ErrorCode.InvalidRequest, error.message);diff --git a/web/src/features/mcp/features/feedback/index.ts b/web/src/features/mcp/features/feedback/index.tsnew file mode 100644index 0000000000..1f4bfc092c--- /dev/null+++ b/web/src/features/mcp/features/feedback/index.ts@@ -0,0 +1,17 @@+import type { McpFeatureModule } from "../../server/registry";+import {+ handleSubmitFeedback,+ submitFeedbackTool,+} from "./tools/submitFeedback";++export const feedbackFeature = {+ name: "feedback",+ description:+ "Submit feedback about Langfuse skills, MCP tools, CLI, docs, or API",+ tools: [+ {+ definition: submitFeedbackTool,+ handler: handleSubmitFeedback,+ },+ ],+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/feedback/tools/submitFeedback.ts b/web/src/features/mcp/features/feedback/tools/submitFeedback.tsnew file mode 100644index 0000000000..3688c1a6da--- /dev/null+++ b/web/src/features/mcp/features/feedback/tools/submitFeedback.ts@@ -0,0 +1,38 @@+import { submitFeedback } from "@/src/features/feedback/server/FeedbackService";+import { PostFeedbackBody } from "@/src/features/public-api/types/feedback";+import { defineTool } from "../../../core/define-tool";+import { runMcpTool } from "../../../core/run-mcp-tool";++export const [submitFeedbackTool, handleSubmitFeedback] = defineTool({+ name: "submitFeedback",+ description: [+ "Submit explicit user-approved feedback to the Langfuse team about Langfuse skills, MCP tools, CLI, docs, or public API.",+ "Before calling, ask the user for permission and show the exact feedback payload, including any optional goal/use-case context.",+ "Do not include secrets, credentials, customer data, trace payloads, or unrelated context.",+ ].join("\n"),+ baseSchema: PostFeedbackBody,+ inputSchema: PostFeedbackBody,+ handler: async (input, context) =>+ runMcpTool({+ spanName: "mcp.feedback.submit",+ context,+ attributes: {+ "mcp.feedback_target_type": input.targetType,+ },+ fn: async () =>+ await submitFeedback({+ input,+ source: "langfuse-mcp",+ scope: {+ projectId: context.projectId,+ orgId: context.orgId,+ accessLevel: "project",+ plan: context.plan,+ rateLimitOverrides: context.rateLimitOverrides,+ apiKeyId: context.apiKeyId,+ publicKey: context.publicKey,+ isIngestionSuspended: false,+ },+ }),+ }),+});diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.tsindex 724b40954e..4e59934cb6 100644--- a/web/src/features/mcp/server/bootstrap.ts+++ b/web/src/features/mcp/server/bootstrap.ts@@ -24,6 +24,7 @@ import { modelsFeature } from "../features/models";import { mediaFeature } from "../features/media";import { evalsFeature } from "../features/evals";import { dashboardWidgetsFeature } from "../features/dashboardWidgets";+import { feedbackFeature } from "../features/feedback";import { experimentsFeature } from "../features/experiments";import { monitorsFeature } from "../features/monitors";@@ -40,6 +41,7 @@ const MCP_FEATURES = [mediaFeature,evalsFeature,dashboardWidgetsFeature,+ feedbackFeature,experimentsFeature,monitorsFeature,] as const satisfies readonly McpFeatureModule[];diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.tsindex 118282eb13..138fec6336 100644--- a/web/src/features/mcp/server/mcpServer.ts+++ b/web/src/features/mcp/server/mcpServer.ts@@ -28,6 +28,12 @@ const MCP_SERVER_NAME = "langfuse";// Tool availability and schemas may evolve over time, including the addition, removal, or modification of tools and fields.// Clients are expected to tolerate schema changes and refresh capabilities dynamically.const MCP_SERVER_VERSION = "0.3.0-unstable";+const MCP_SERVER_INSTRUCTIONS = [+ "Use this server for project-scoped Langfuse data and actions such as prompts, datasets, scores, comments, metrics, observations etc.",+ "Inspect the available tools and their schemas dynamically; do not assume a fixed tool list.",+ "For conceptual Langfuse product guidance, SDK/API documentation, instrumentation help, or prompt-migration guidance, prefer the Langfuse docs MCP server or installed Langfuse agent skills when they are available.",+ "To send feedback about Langfuse skills, MCP tools, CLI, docs, or public API, ask the user for permission, show the exact feedback payload, avoid secrets/customer data/trace payloads, then call submitFeedback.",+].join("\n");/*** Create and configure the MCP server instance.@@ -58,6 +64,7 @@ export function createMcpServer(context: ServerContext): Server {capabilities: {tools: {},},+ instructions: MCP_SERVER_INSTRUCTIONS,},);diff --git a/web/src/features/mcp/types.ts b/web/src/features/mcp/types.tsindex 4a1de28e11..3e13e3dae8 100644--- a/web/src/features/mcp/types.ts+++ b/web/src/features/mcp/types.ts@@ -1,3 +1,4 @@+import type { ApiAccessScope } from "@langfuse/shared/src/server";import type { McpToolName } from "./server/bootstrap";/**@@ -51,6 +52,12 @@ export interface ServerContext {/** Public key used for authentication */publicKey: string;+ /** Billing plan of the organization, for plan-based rate limiting */+ plan: ApiAccessScope["plan"];++ /** Org-level rate limit overrides from the cloud config */+ rateLimitOverrides: ApiAccessScope["rateLimitOverrides"];+/** User agent from the MCP client's HTTP request */userAgent?: string;diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.tsindex b316347215..ace36572a8 100644--- a/web/src/features/public-api/server/RateLimitService.ts+++ b/web/src/features/public-api/server/RateLimitService.ts@@ -337,6 +337,12 @@ const getPlanBasedRateLimitConfig = (points: 100,durationInSec: 86400,};+ case "feedback":+ return {+ resource: "feedback",+ points: 20,+ durationInSec: 86400, // 20 submissions per day+ };default:const exhaustiveCheck: never = resource;throw new Error(`Unhandled resource case: ${exhaustiveCheck}`);@@ -429,6 +435,12 @@ const getPlanBasedRateLimitConfig = (points: 1000,durationInSec: 86400,};+ case "feedback":+ return {+ resource: "feedback",+ points: 20,+ durationInSec: 86400, // 20 submissions per day+ };default:const exhaustiveCheck: never = resource;throw new Error(`Unhandled resource case: ${exhaustiveCheck}`);@@ -515,6 +527,12 @@ const getPlanBasedRateLimitConfig = (points: 1000,durationInSec: 86400,};+ case "feedback":+ return {+ resource: "feedback",+ points: 20,+ durationInSec: 86400, // 20 submissions per day+ };default:const exhaustiveCheck: never = resource;throw new Error(`Unhandled resource case: ${exhaustiveCheck}`);diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex 6b3a154060..9f8eaaa9d6 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -86,6 +86,11 @@ export type AuthedProjectAPIRouteConfig<* events_only mode and would silently return stale or empty data.*/rejectInEventsOnlyMode?: boolean;+ /**+ * Redact or summarize the request body before logging. Use this for routes+ * accepting user-authored content, secrets, or other sensitive payloads.+ */+ redactLogBody?: (body: unknown) => unknown;/** Stamps a top-level `_deprecation` object onto responses (LFE-10895). */deprecation?: ApiDeprecationInfo;fn: (params: {@@ -402,7 +407,9 @@ export const createAuthedProjectAPIRoute = <`Request to route ${routeConfig.name} projectId ${auth.scope.projectId}`,{query: req.query,- body: req.body,+ body: routeConfig.redactLogBody+ ? routeConfig.redactLogBody(req.body)+ : req.body,},);diff --git a/web/src/features/public-api/types/feedback.ts b/web/src/features/public-api/types/feedback.tsnew file mode 100644index 0000000000..0e79ca9dba--- /dev/null+++ b/web/src/features/public-api/types/feedback.ts@@ -0,0 +1,54 @@+import { z } from "zod";++export const FeedbackTargetType = z.enum([+ "skill",+ "mcp-tool",+ "cli",+ "docs",+ "public-api",+ "other",+]);++export const PostFeedbackBody = z+ .object({+ targetType: FeedbackTargetType.describe(+ "Category of the thing the feedback is about.",+ ),+ target: z+ .string()+ .trim()+ .min(1)+ .max(200)+ .describe(+ "The specific instance within targetType: the skill name, MCP tool name, CLI command, API endpoint path, or docs page path (e.g. 'queryMetrics', '/docs/mcp'). An identifier, not a sentence.",+ ),+ feedback: z+ .string()+ .trim()+ .min(1)+ .max(3000)+ .describe("The concise feedback text approved by the user."),+ goal: z+ .string()+ .trim()+ .min(1)+ .max(1500)+ .optional()+ .describe(+ "Optional user-approved goal or use case they were trying to achieve. Do not infer or add secrets, customer data, trace payloads, or broad unrelated context.",+ ),+ referenceUrl: z+ .url()+ .max(2048)+ .refine((url) => ["http:", "https:"].includes(new URL(url).protocol), {+ message: "referenceUrl must use http or https",+ })+ .optional()+ .describe("Optional URL reference. Langfuse stores it as text only."),+ })+ .strict();++export const PostFeedbackResponse = z.object({ id: z.uuid() }).strict();++export type PostFeedbackBodyType = z.infer<typeof PostFeedbackBody>;+export type PostFeedbackResponseType = z.infer<typeof PostFeedbackResponse>;diff --git a/web/src/pages/api/public/feedback.ts b/web/src/pages/api/public/feedback.tsnew file mode 100644index 0000000000..6faaab3817--- /dev/null+++ b/web/src/pages/api/public/feedback.ts@@ -0,0 +1,41 @@+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { submitFeedback } from "@/src/features/feedback/server/FeedbackService";+import {+ PostFeedbackBody,+ PostFeedbackResponse,+} from "@/src/features/public-api/types/feedback";++export default withMiddlewares({+ POST: createAuthedProjectAPIRoute({+ name: "Submit Feedback",+ bodySchema: PostFeedbackBody,+ responseSchema: PostFeedbackResponse,+ successStatusCode: 201,+ redactLogBody: (body) => {+ const candidate =+ typeof body === "object" && body !== null+ ? (body as {+ targetType?: unknown;+ })+ : {};+ return {+ targetType: candidate.targetType,+ };+ },+ fn: async ({ body, auth }) =>+ await submitFeedback({+ input: body,+ scope: auth.scope,+ source: "public-api",+ }),+ }),+});++export const config = {+ api: {+ bodyParser: {+ sizeLimit: "16kb",+ },+ },+};diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.tsindex fbdf58e598..18608aca23 100644--- a/web/src/pages/api/public/mcp/index.ts+++ b/web/src/pages/api/public/mcp/index.ts@@ -137,6 +137,8 @@ export default async function handler(apiKeyId: authCheck.scope.apiKeyId,accessLevel: "project",publicKey: authCheck.scope.publicKey,+ plan: authCheck.scope.plan,+ rateLimitOverrides: authCheck.scope.rateLimitOverrides,userAgent: req.headers["user-agent"],inAppAgent: getInAppAgentContext(req, authCheck.scope.isInAppAgentKey),};