Skip to content

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

feat(agent): Connect in-app agent to langfuse MCP (#13747)

Ben Bachem8c6d09b91aab
diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.ts
index 18de30e344..60120697dc 100644
--- a/packages/shared/src/server/auth/apiKeys.ts
+++ b/packages/shared/src/server/auth/apiKeys.ts
@@ -2,7 +2,9 @@ import { PrismaClient, ApiKeyScope } from "@prisma/client";
import { compare, hash } from "bcryptjs";
import { randomUUID } from "crypto";
import * as crypto from "crypto";
+import type { Cluster, Redis } from "ioredis";
import { env } from "../../env";
+import { invalidateCachedApiKeys } from "./invalidateApiKeys";
export function getDisplaySecretKey(secretKey: string) {
return secretKey.slice(0, 6) + "..." + secretKey.slice(-4);
@@ -86,3 +88,32 @@ export async function createAndAddApiKeysToDb(p: {
displaySecretKey: displaySk,
};
}
+
+export async function deleteApiKeyFromDb(p: {
+ prisma: PrismaClient;
+ id: string;
+ entityId: string;
+ scope: ApiKeyScope;
+ redis?: Redis | Cluster | null;
+}) {
+ const entity =
+ p.scope === "PROJECT" ? { projectId: p.entityId } : { orgId: p.entityId };
+
+ const apiKey = await p.prisma.apiKey.findFirstOrThrow({
+ where: {
+ ...entity,
+ id: p.id,
+ scope: p.scope,
+ },
+ });
+
+ await invalidateCachedApiKeys([apiKey], `key ${p.id}`, p.redis);
+
+ await p.prisma.apiKey.delete({
+ where: {
+ id: apiKey.id,
+ },
+ });
+
+ return true;
+}
diff --git a/web/src/__tests__/server/unit/api-auth-span.servertest.ts b/web/src/__tests__/server/unit/api-auth-span.servertest.ts
index 2ba3023bd7..13145037f6 100644
--- a/web/src/__tests__/server/unit/api-auth-span.servertest.ts
+++ b/web/src/__tests__/server/unit/api-auth-span.servertest.ts
@@ -62,6 +62,7 @@ vi.mock("@langfuse/shared/src/server", () => ({
},
addUserToSpan: addUserToSpanMock,
createShaHash: createShaHashMock,
+ deleteApiKeyFromDb: vi.fn(),
invalidateCachedApiKeys: vi.fn(),
invalidateCachedOrgApiKeys: vi.fn(),
invalidateCachedProjectApiKeys: vi.fn(),
diff --git a/web/src/features/in-app-agent/server/agent.ts b/web/src/features/in-app-agent/server/agent.ts
index 00a89fe034..fe50d3edb4 100644
--- a/web/src/features/in-app-agent/server/agent.ts
+++ b/web/src/features/in-app-agent/server/agent.ts
@@ -19,11 +19,17 @@ const MAX_AGENT_BUDGET_USD = 5;
type CreateAgUiStreamOptions = {
resumeSessionId?: string;
+ onFinish?: () => void | Promise<void>;
createResumeStateForSessionId: (sessionId: string) => unknown;
awsBedrock: {
region?: string;
profile?: string;
};
+ langfuseMcp: {
+ url: string;
+ publicKey: string;
+ secretKey: string;
+ };
};
export function createAgUiStream(params: {
@@ -37,11 +43,24 @@ export function createAgUiStream(params: {
const awsSdkLoadConfig =
process.env.AWS_SDK_LOAD_CONFIG ?? (awsProfile ? "1" : undefined);
+ const langfuseMcpAuthHeader = `Basic ${Buffer.from(
+ `${params.options.langfuseMcp.publicKey}:${params.options.langfuseMcp.secretKey}`,
+ ).toString("base64")}`;
+
const adapter = new ClaudeAgentAdapter({
permissionMode: "dontAsk",
title: ASSISTANT_TITLE,
systemPrompt: ASSISTANT_SYSTEM_PROMPT,
- allowedTools: [],
+ allowedTools: ["mcp__langfuse__*"],
+ mcpServers: {
+ langfuse: {
+ type: "http",
+ url: params.options.langfuseMcp.url,
+ headers: {
+ Authorization: langfuseMcpAuthHeader,
+ },
+ },
+ },
settingSources: [],
additionalDirectories: [],
maxBudgetUsd: MAX_AGENT_BUDGET_USD,
@@ -73,16 +92,46 @@ export function createAgUiStream(params: {
}
: params.input;
+ let subscription: { unsubscribe: () => void } | undefined;
+ let closed = false;
+ let finished = false;
+ let abortHandler: (() => void) | undefined;
+
+ const removeAbortHandler = () => {
+ if (!abortHandler) {
+ return;
+ }
+
+ params.signal.removeEventListener("abort", abortHandler);
+ abortHandler = undefined;
+ };
+
+ const finish = () => {
+ if (finished) {
+ return;
+ }
+
+ finished = true;
+ try {
+ void Promise.resolve(params.options.onFinish?.()).catch((error) => {
+ console.error("Error in agent stream cleanup:", error);
+ });
+ } catch (error) {
+ console.error("Error in agent stream cleanup:", error);
+ }
+ };
+
return new ReadableStream<Uint8Array>({
start(controller) {
- let closed = false;
const closeController = () => {
if (closed) {
return;
}
closed = true;
+ removeAbortHandler();
controller.close();
+ finish();
};
const abort = () => {
@@ -90,9 +139,7 @@ export function createAgUiStream(params: {
closeController();
};
- let subscription: { unsubscribe: () => void } | undefined;
-
- const handleAbort = () => {
+ abortHandler = () => {
subscription?.unsubscribe();
abort();
};
@@ -102,7 +149,7 @@ export function createAgUiStream(params: {
return;
}
- params.signal.addEventListener("abort", handleAbort, { once: true });
+ params.signal.addEventListener("abort", abortHandler, { once: true });
subscription = adapter.run(adapterInput).subscribe({
next(event) {
@@ -146,6 +193,17 @@ export function createAgUiStream(params: {
},
});
},
+ cancel() {
+ if (closed) {
+ return;
+ }
+
+ closed = true;
+ removeAbortHandler();
+ subscription?.unsubscribe();
+ void adapter.interrupt().catch(() => undefined);
+ finish();
+ },
});
}
diff --git a/web/src/features/in-app-agent/server/handler.ts b/web/src/features/in-app-agent/server/handler.ts
index 6a83365fcd..a6d3eaa9f7 100644
--- a/web/src/features/in-app-agent/server/handler.ts
+++ b/web/src/features/in-app-agent/server/handler.ts
@@ -23,7 +23,13 @@ import {
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { assertUnreachable } from "@/src/utils/types";
+import {
+ createAndAddApiKeysToDb,
+ deleteApiKeyFromDb,
+} from "@langfuse/shared/src/server/auth/apiKeys";
+import { logger } from "@langfuse/shared/src/server";
+const IN_APP_AGENT_API_KEY_NOTE = "In-app agent MCP session";
const MAX_IN_APP_AGENT_INPUT_BYTES = 1024 * 1024;
export default async function handler(request: Request) {
@@ -137,37 +143,47 @@ export default async function handler(request: Request) {
const sanitizedInput = sanitizeAgentInput(input);
const awsProfile = env.LANGFUSE_IN_APP_AGENT_AWS_PROFILE;
-
- const stream = createAgUiStream({
- input: sanitizedInput,
- signal: request.signal,
- options: {
- resumeSessionId: claudeSessionId,
- createResumeStateForSessionId: (claudeSessionId) => ({
- type: "existingSession",
- claudeSessionToken: signInAppAgentSessionToken({
- userId: auth.userId,
- projectId,
- threadId: sanitizedInput.threadId,
- claudeSessionId,
- }),
- }),
- awsBedrock: {
- region: env.LANGFUSE_AWS_BEDROCK_REGION,
- ...(awsProfile ? { profile: awsProfile } : {}),
- },
- },
- });
-
- return new Response(stream, {
- headers: {
- "Content-Type": "text/event-stream; charset=utf-8",
- "Content-Encoding": "none",
- "Cache-Control": "no-cache, no-transform",
- Connection: "keep-alive",
- "X-Accel-Buffering": "no",
+ return await withInAppAgentMcpApiKeyCleanup(
+ projectId,
+ (mcpApiKey, cleanupMcpApiKey) => {
+ const stream = createAgUiStream({
+ input: sanitizedInput,
+ signal: request.signal,
+ options: {
+ resumeSessionId: claudeSessionId,
+ createResumeStateForSessionId: (claudeSessionId) => ({
+ type: "existingSession",
+ claudeSessionToken: signInAppAgentSessionToken({
+ userId: auth.userId,
+ projectId,
+ threadId: sanitizedInput.threadId,
+ claudeSessionId,
+ }),
+ }),
+ awsBedrock: {
+ region: env.LANGFUSE_AWS_BEDROCK_REGION,
+ ...(awsProfile ? { profile: awsProfile } : {}),
+ },
+ langfuseMcp: {
+ url: getLangfuseMcpUrl(),
+ publicKey: mcpApiKey.publicKey,
+ secretKey: mcpApiKey.secretKey,
+ },
+ onFinish: cleanupMcpApiKey,
+ },
+ });
+
+ return new Response(stream, {
+ headers: {
+ "Content-Type": "text/event-stream; charset=utf-8",
+ "Content-Encoding": "none",
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ "X-Accel-Buffering": "no",
+ },
+ });
},
- });
+ );
} catch (err) {
if (err instanceof BaseError) {
return Response.json({ error: err.message }, { status: err.httpCode });
@@ -184,6 +200,73 @@ export default async function handler(request: Request) {
}
}
+function getLangfuseMcpUrl(): string {
+ const rawUrl = env.NEXTAUTH_URL.replace(/\/api\/auth\/?$/, "");
+ const baseUrl = new URL(rawUrl);
+
+ baseUrl.pathname = `${baseUrl.pathname.replace(/\/$/, "")}/api/public/mcp`;
+ baseUrl.search = "";
+ baseUrl.hash = "";
+
+ return baseUrl.toString();
+}
+
+async function createInAppAgentMcpApiKey(projectId: string) {
+ return createAndAddApiKeysToDb({
+ prisma,
+ entityId: projectId,
+ scope: "PROJECT",
+ note: IN_APP_AGENT_API_KEY_NOTE,
+ isInAppAgentKey: true,
+ });
+}
+
+async function withInAppAgentMcpApiKeyCleanup<T>(
+ projectId: string,
+ createResponse: (
+ mcpApiKey: Awaited<ReturnType<typeof createInAppAgentMcpApiKey>>,
+ cleanupMcpApiKey: () => Promise<void>,
+ ) => T,
+): Promise<T> {
+ const mcpApiKey = await createInAppAgentMcpApiKey(projectId);
+ let cleanupPromise: Promise<void> | undefined;
+
+ const cleanupMcpApiKey = () => {
+ if (!cleanupPromise) {
+ cleanupPromise = cleanupInAppAgentMcpApiKey({
+ apiKeyId: mcpApiKey.id,
+ projectId,
+ }).catch((cleanupErr) => {
+ cleanupPromise = undefined;
+ throw cleanupErr;
+ });
+ }
+
+ return cleanupPromise;
+ };
+
+ try {
+ return createResponse(mcpApiKey, cleanupMcpApiKey);
+ } catch (err) {
+ await cleanupMcpApiKey().catch((cleanupErr) => {
+ logger.error("Failed to clean up in-app agent MCP API key", cleanupErr);
+ });
+ throw err;
+ }
+}
+
+async function cleanupInAppAgentMcpApiKey(params: {
+ apiKeyId: string;
+ projectId: string;
+}) {
+ await deleteApiKeyFromDb({
+ prisma,
+ id: params.apiKeyId,
+ entityId: params.projectId,
+ scope: "PROJECT",
+ });
+}
+
function sanitizeAgentInput(input: AgUiRunAgentInput): AgUiRunAgentInput {
const lastUserMessage = getLastUserMessage(input.messages);
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index babc850310..ef3decbbfd 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -1,6 +1,7 @@
import { env } from "@/src/env.mjs";
import {
createShaHash,
+ deleteApiKeyFromDb,
recordIncrement,
verifySecretKey,
type AuthHeaderVerificationResult,
@@ -61,30 +62,13 @@ export class ApiAuthService {
* @param scope - The scope of the API key (either "PROJECT" or "ORGANIZATION").
*/
async deleteApiKey(id: string, entityId: string, scope: ApiKeyScope) {
- const entity =
- scope === "PROJECT" ? { projectId: entityId } : { orgId: entityId };
- // Make sure the API key exists and belongs to the project the user has access to
- const apiKey = await this.prisma.apiKey.findFirstOrThrow({
- where: {
- ...entity,
- id: id,
- scope,
- },
- });
- if (!apiKey) {
- return false;
- }
-
- // if redis is available, delete the key from there as well
- // delete from redis even if caching is disabled via env for consistency
- await this.invalidateCachedApiKeys([apiKey], `key ${id}`);
-
- await this.prisma.apiKey.delete({
- where: {
- id: apiKey.id,
- },
+ return deleteApiKeyFromDb({
+ prisma: this.prisma,
+ id,
+ entityId,
+ scope,
+ redis: this.redis,
});
- return true;
}
async verifyAuthHeaderAndReturnScope(