🪢 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
fix(mcp): return 401/403 instead of 500 for auth errors (#10633)
Michael Fröhliche2495bfb503d
diff --git a/web/src/__tests__/async/mcp-auth.servertest.ts b/web/src/__tests__/async/mcp-auth.servertest.tsnew file mode 100644index 0000000000..287f14ad45--- /dev/null+++ b/web/src/__tests__/async/mcp-auth.servertest.ts@@ -0,0 +1,100 @@+/** @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 { createMcpTestSetup } from "./mcp-helpers";++const MCP_ENDPOINT = "/api/public/mcp";++describe("MCP Authentication", () => {+ describe("HTTP status codes for auth errors", () => {+ it("should return 401 for invalid credentials", async () => {+ const invalidAuth = Buffer.from("pk-invalid:sk-invalid").toString(+ "base64",+ );++ const response = await fetch(`http://localhost:3000${MCP_ENDPOINT}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Basic ${invalidAuth}`,+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ protocolVersion: "2024-11-05",+ capabilities: {},+ clientInfo: { name: "test", version: "1.0.0" },+ },+ id: 1,+ }),+ });++ expect(response.status).toBe(401);+ const body = await response.json();+ expect(body.error).toContain("Authentication failed");+ });++ it("should return 401 for missing authorization header", async () => {+ const response = await fetch(`http://localhost:3000${MCP_ENDPOINT}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ protocolVersion: "2024-11-05",+ capabilities: {},+ clientInfo: { name: "test", version: "1.0.0" },+ },+ id: 1,+ }),+ });++ expect(response.status).toBe(401);+ });++ it("should return 200 for valid credentials", async () => {+ const { auth } = await createMcpTestSetup();++ const response = await fetch(`http://localhost:3000${MCP_ENDPOINT}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json, text/event-stream",+ // auth already includes "Basic " prefix from createBasicAuthHeader+ Authorization: auth,+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ protocolVersion: "2024-11-05",+ capabilities: {},+ clientInfo: { name: "test", version: "1.0.0" },+ },+ id: 1,+ }),+ });++ // MCP initialize should succeed with valid auth+ expect(response.status).toBe(200);+ });+ });+});diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.tsindex 9c69cee399..86ccf89ccf 100644--- a/web/src/pages/api/public/mcp/index.ts+++ b/web/src/pages/api/public/mcp/index.ts@@ -33,7 +33,9 @@ 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";+import { BaseError, UnauthorizedError, ForbiddenError } from "@langfuse/shared";+import { ZodError } from "zod/v4";+import { isUserInputError } from "@/src/features/mcp/core/errors";// Bootstrap MCP features - registers all tools at module load timeimport "@/src/features/mcp/server/bootstrap";@@ -147,7 +149,18 @@ export default async function handler(// Format error for user (never throw from handler)if (!res.headersSent) {const mcpError = formatErrorForUser(error);- res.status(500).json({++ // Return appropriate HTTP status based on error type+ let status = 500;+ if (error instanceof BaseError) {+ // BaseError subclasses have their own httpCode (401, 403, 404, 409, 500, etc.)+ status = error.httpCode;+ } else if (isUserInputError(error) || error instanceof ZodError) {+ // User-caused errors (invalid input, validation failures)+ status = 400;+ }++ res.status(status).json({error: mcpError.message,code: mcpError.code,});