🪢 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): add allowed hosts to be set (#14270)
Nimarf23edbcf066b
diff --git a/.env.prod.example b/.env.prod.exampleindex 79e47b0981..27d6415cdd 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -254,6 +254,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# Valid values: core, io, scores, observations, metrics# LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS=+# Comma-separated additional hostnames/origins accepted by the MCP endpoint.+# LANGFUSE_MCP_ALLOWED_HOSTS=internal-langfuse.example.com,https://api.example.com+# Legacy tracing UI controls# Disable input/output full-text search in legacy V3 tracing tables (metadata search remains available)# LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH=falsediff --git a/web/src/__tests__/server/unit/mcp-security.servertest.ts b/web/src/__tests__/server/unit/mcp-security.servertest.tsnew file mode 100644index 0000000000..8a279149d1--- /dev/null+++ b/web/src/__tests__/server/unit/mcp-security.servertest.ts@@ -0,0 +1,47 @@+const mockEnv = vi.hoisted(() => ({+ env: {+ LANGFUSE_MCP_ALLOWED_HOSTS: [] as string[],+ NEXTAUTH_URL: "https://langfuse.example.com",+ NODE_ENV: "production",+ },+}));++vi.mock("@/src/env.mjs", () => mockEnv);++import type { NextApiRequest } from "next";+import { validateMcpRequestSecurity } from "@/src/features/mcp/server/security";++const mockRequest = (headers: NextApiRequest["headers"]): NextApiRequest =>+ ({ headers }) as NextApiRequest;++describe("MCP request security", () => {+ beforeEach(() => {+ mockEnv.env.NEXTAUTH_URL = "https://langfuse.example.com";+ mockEnv.env.NODE_ENV = "production";+ mockEnv.env.LANGFUSE_MCP_ALLOWED_HOSTS = [];+ });++ it("allows an exact additional host from LANGFUSE_MCP_ALLOWED_HOSTS", () => {+ mockEnv.env.LANGFUSE_MCP_ALLOWED_HOSTS = ["internal-langfuse.example.com"];++ expect(+ validateMcpRequestSecurity(+ mockRequest({+ host: "internal-langfuse.example.com",+ origin: "https://internal-langfuse.example.com",+ }),+ ),+ ).toBe("https://internal-langfuse.example.com");+ });++ it("rejects hosts that are not configured exactly", () => {+ mockEnv.env.LANGFUSE_MCP_ALLOWED_HOSTS = [+ "*.example.com",+ "internal-langfuse.example.com/api",+ ];++ expect(() =>+ validateMcpRequestSecurity(mockRequest({ host: "evil.example.com" })),+ ).toThrow("Invalid Host header: evil.example.com");+ });+});diff --git a/web/src/env.mjs b/web/src/env.mjsindex fc32df8712..789ca5576f 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -61,6 +61,17 @@ export const env = createEnv({// VERCEL_URL doesn't include `https` so it can't be validated as a URLprocess.env.VERCEL ? z.string().min(1) : z.url(),),+ LANGFUSE_MCP_ALLOWED_HOSTS: z+ .string()+ .optional()+ .transform((val) =>+ val+ ? val+ .split(",")+ .map((host) => host.toLowerCase().trim())+ .filter(Boolean)+ : [],+ ),NEXTAUTH_COOKIE_DOMAIN: z.string().optional(),LANGFUSE_TEAM_SLACK_WEBHOOK: z.url().optional(),LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.url().optional(),@@ -496,6 +507,7 @@ export const env = createEnv({NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,NEXTAUTH_COOKIE_DOMAIN: process.env.NEXTAUTH_COOKIE_DOMAIN,NEXTAUTH_URL: process.env.NEXTAUTH_URL,+ LANGFUSE_MCP_ALLOWED_HOSTS: process.env.LANGFUSE_MCP_ALLOWED_HOSTS,NEXT_PUBLIC_LANGFUSE_CLOUD_REGION:process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF:diff --git a/web/src/features/mcp/README.md b/web/src/features/mcp/README.mdindex 2743fa4011..7e95151707 100644--- a/web/src/features/mcp/README.md+++ b/web/src/features/mcp/README.md@@ -141,6 +141,11 @@ This outputs your BasicAuth token (e.g., `cGstbGYt...`).**Self-Hosted:**- Use your domain with HTTPS: `https://your-domain.com`+- If a reverse proxy forwards a different `Host` header than `NEXTAUTH_URL`,+ either preserve the public host at the proxy or set+ `LANGFUSE_MCP_ALLOWED_HOSTS` to a comma-separated list of exact additional+ hostnames/origins accepted by the MCP endpoint. Wildcards and paths are not+ supported.**Local Development:**diff --git a/web/src/features/mcp/server/security.ts b/web/src/features/mcp/server/security.tsindex 91bb34694e..4275a3c6ce 100644--- a/web/src/features/mcp/server/security.ts+++ b/web/src/features/mcp/server/security.ts@@ -5,6 +5,39 @@ import { type NextApiRequest, type NextApiResponse } from "next";const LOCALHOST_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"] as const;const LOCALHOST_HOST_PATTERN = /^(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i;+function parseAllowedMcpHostEntry(+ entry: string,+ fallbackProtocol: string,+): { hostname: string; origin: string } | null {+ const trimmedEntry = entry.trim();+ let url: URL;+ try {+ url = new URL(+ /^https?:\/\//i.test(trimmedEntry)+ ? trimmedEntry+ : `${fallbackProtocol}//${trimmedEntry}`,+ );+ } catch {+ return null;+ }++ if (+ url.username ||+ url.password ||+ url.pathname !== "/" ||+ url.search ||+ url.hash ||+ url.hostname.includes("*")+ ) {+ return null;+ }++ return {+ hostname: url.hostname.toLowerCase(),+ origin: url.origin.toLowerCase(),+ };+}+function getAllowedMcpOriginsAndHostnames() {const rawBaseUrl = env.NEXTAUTH_URL;const baseUrl = new URL(@@ -15,6 +48,14 @@ function getAllowedMcpOriginsAndHostnames() {const allowedHostnames = new Set([baseUrl.hostname.toLowerCase()]);const allowedOrigins = new Set([baseUrl.origin.toLowerCase()]);+ for (const entry of env.LANGFUSE_MCP_ALLOWED_HOSTS) {+ const allowedHost = parseAllowedMcpHostEntry(entry, baseUrl.protocol);+ if (!allowedHost) continue;++ allowedHostnames.add(allowedHost.hostname);+ allowedOrigins.add(allowedHost.origin);+ }+if (env.NODE_ENV !== "production") {const localPort =baseUrl.port ||