🪢 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(agent): Mutating MCP calls & HITL (#14399)
Ben Bachem6b7c6b1e2478
diff --git a/packages/shared/prisma/migrations/20260629091506_add_in_app_agent_pending_tool_approvals/migration.sql b/packages/shared/prisma/migrations/20260629091506_add_in_app_agent_pending_tool_approvals/migration.sqlnew file mode 100644index 0000000000..e752d275a2--- /dev/null+++ b/packages/shared/prisma/migrations/20260629091506_add_in_app_agent_pending_tool_approvals/migration.sql@@ -0,0 +1,21 @@+-- CreateTable+CREATE TABLE "in_app_agent_pending_tool_approvals" (+ "project_id" TEXT NOT NULL,+ "conversation_id" TEXT NOT NULL,+ "tool_call_id" TEXT NOT NULL,+ "approval_fingerprint" TEXT NOT NULL,+ "expires_at" TIMESTAMP(3) NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "in_app_agent_pending_tool_approvals_pkey" PRIMARY KEY ("project_id","conversation_id","tool_call_id")+);++-- CreateIndex+CREATE INDEX "in_app_agent_pending_tool_approvals_expires_at_idx" ON "in_app_agent_pending_tool_approvals"("expires_at");++-- AddForeignKey+ALTER TABLE "in_app_agent_pending_tool_approvals" ADD CONSTRAINT "in_app_agent_pending_tool_approvals_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "in_app_agent_pending_tool_approvals" ADD CONSTRAINT "in_app_agent_pending_tool_approvals_conversation_id_projec_fkey" FOREIGN KEY ("conversation_id", "project_id") REFERENCES "in_app_agent_conversations"("id", "project_id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex b21e2a9204..1f52f37cef 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -180,6 +180,7 @@ model Project {InAppAgentConversation InAppAgentConversation[]InAppAgentEvent InAppAgentEvent[]InAppAgentRun InAppAgentRun[]+ InAppAgentPendingToolApproval InAppAgentPendingToolApproval[]@@index([orgId])@@map("projects")@@ -235,6 +236,7 @@ model InAppAgentConversation {events InAppAgentEvent[]runs InAppAgentRun[]+ pendingToolApprovals InAppAgentPendingToolApproval[]@@id([id, projectId])@@index([projectId, createdByUserId, deletedAt, updatedAt, id], map: "in_app_agent_conversations_project_user_list_idx")@@ -281,6 +283,22 @@ model InAppAgentRun {@@map("in_app_agent_runs")}+model InAppAgentPendingToolApproval {+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ conversationId String @map("conversation_id")+ conversation InAppAgentConversation @relation(fields: [conversationId, projectId], references: [id, projectId], onDelete: Cascade)+ toolCallId String @map("tool_call_id")+ approvalFingerprint String @map("approval_fingerprint")+ expiresAt DateTime @map("expires_at")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ @@id([projectId, conversationId, toolCallId])+ @@index([expiresAt], map: "in_app_agent_pending_tool_approvals_expires_at_idx")+ @@map("in_app_agent_pending_tool_approvals")+}+model BackgroundMigration {id String @id @default(cuid())name String @uniquediff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.tsindex 0e542a78af..335eeb71e7 100644--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -1,4 +1,7 @@import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { filterInAppAgentAvailableLangfuseMcpTools } from "@/src/ee/features/in-app-agent/server/tools";+import { storePendingToolApproval } from "@/src/ee/features/in-app-agent/server/human-in-the-loop";+import type { InAppAgentToolApprovalRequest } from "@/src/ee/features/in-app-agent/schema";import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";import {@@ -141,6 +144,411 @@ describe("in-app agent public API route auth", () => {expect(res._getJSONData()).toEqual({ ok: true });});+ it("filters Langfuse MCP tools using the in-app agent user's access", () => {+ const tools = {+ createModel: { id: "createModel" },+ listDatasets: { id: "listDatasets" },+ getPrompt: { id: "getPrompt" },+ };++ expect(+ filterInAppAgentAvailableLangfuseMcpTools({+ tools,+ userAccess: {+ projectRole: "MEMBER",+ isAdmin: false,+ },+ }),+ ).toEqual({+ listDatasets: { id: "listDatasets" },+ getPrompt: { id: "getPrompt" },+ });++ expect(+ filterInAppAgentAvailableLangfuseMcpTools({+ tools,+ userAccess: {+ projectRole: "OWNER",+ isAdmin: false,+ },+ }),+ ).toEqual(tools);+ });++ it("passes validated resume forwarded props without requiring a user message", async () => {+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;+ const originalAiFeaturesPublicKey = env.LANGFUSE_AI_FEATURES_PUBLIC_KEY;+ const originalAiFeaturesSecretKey = env.LANGFUSE_AI_FEATURES_SECRET_KEY;++ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY = "pk-lf-test";+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY = "sk-lf-test";++ const { org, project } = await createOrgProjectAndApiKey();+ const userId = randomUUID();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = {+ command: {+ resume: {+ approved: true,+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_upsertDataset",+ args: { name: "Approved dataset" },+ runId: "suspended-run-1",+ },+ },+ },+ };++ try {+ await prisma.organization.update({+ where: { id: org.id },+ data: { aiFeaturesEnabled: true },+ });+ await prisma.user.create({+ data: {+ id: userId,+ email: `in-app-agent-${userId}@example.com`,+ name: "In-app Agent User",+ },+ });+ authMocks.getServerSession.mockResolvedValue(+ createInAppAgentSession({+ orgId: org.id,+ projectId: project.id,+ userId,+ }),+ );+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ const { default: handler } =+ await import("@/src/ee/features/in-app-agent/server/handler");+ const response = await handler(+ new Request("http://localhost/api/in-app-agent", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ threadId: conversationId,+ runId: "client-run-1",+ messages: [],+ tools: [],+ context: [],+ state: {+ type: "existingConversation",+ projectId: project.id,+ conversationId,+ },+ forwardedProps,+ }),+ }),+ );++ expect(response.status).toBe(200);+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(false);+ expect(agentMocks.createAgUiStream).toHaveBeenCalledWith(+ expect.objectContaining({+ input: expect.objectContaining({+ messages: [],+ forwardedProps,+ }),+ options: expect.objectContaining({+ langfuseMcp: expect.objectContaining({+ runOverride: expect.any(String),+ }),+ }),+ }),+ );+ const createStreamCall = agentMocks.createAgUiStream.mock.calls[0]?.[0];+ expect(createStreamCall).toBeDefined();+ expect(+ JSON.parse(createStreamCall.options.langfuseMcp.runOverride),+ ).toEqual({+ toolName: "upsertDataset",+ });+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY =+ originalAiFeaturesPublicKey;+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY =+ originalAiFeaturesSecretKey;+ }+ });++ it("rejects forged resume forwarded props without a pending approval", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps();++ const { response } = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ forwardedProps,+ });++ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toEqual({+ error: "Invalid forwarded props",+ });+ expect(agentMocks.createAgUiStream).not.toHaveBeenCalled();+ });+ });++ it("rejects mutated resume forwarded props without consuming the pending approval", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps();+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ const { response } = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ forwardedProps: {+ command: {+ resume: {+ ...forwardedProps.command.resume,+ approvalRequest: {+ ...forwardedProps.command.resume.approvalRequest,+ toolName: "langfuse_deleteDataset",+ },+ },+ },+ },+ });++ expect(response.status).toBe(400);+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(true);+ expect(agentMocks.createAgUiStream).not.toHaveBeenCalled();+ });+ });++ it("rejects replayed resume forwarded props after approval consumption", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps();+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ const firstAttempt = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ forwardedProps,+ });+ const secondAttempt = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ forwardedProps,+ });++ expect(firstAttempt.response.status).toBe(200);+ expect(secondAttempt.response.status).toBe(400);+ expect(agentMocks.createAgUiStream).toHaveBeenCalledTimes(1);+ });+ });++ it("prevents concurrent resume attempts from starting the same approved tool call twice", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps();+ await prisma.inAppAgentConversation.create({+ data: {+ id: conversationId,+ projectId: project.id,+ createdByUserId: userId,+ title: "Concurrent resume test",+ },+ });+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ agentMocks.createAgUiStream.mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(() => resolve(new ReadableStream()), 25);+ }),+ );++ const attempts = await Promise.all([+ callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-concurrent-1",+ forwardedProps,+ }),+ callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-concurrent-2",+ forwardedProps,+ }),+ ]);++ expect(attempts.map(({ response }) => response.status).sort()).toEqual([+ 200, 409,+ ]);+ expect(agentMocks.createAgUiStream).toHaveBeenCalledTimes(1);+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(false);+ });+ });++ it("keeps pending approval retryable when resumed stream initialization fails", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps();+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ agentMocks.createAgUiStream.mockRejectedValueOnce(+ new Error("stream init failed"),+ );++ await expect(+ callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-failed",+ forwardedProps,+ }),+ ).rejects.toThrow("stream init failed");+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(true);++ const retry = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-retry",+ forwardedProps,+ });++ expect(retry.response.status).toBe(200);+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(false);+ expect(agentMocks.createAgUiStream).toHaveBeenCalledTimes(2);+ });+ });++ it("keeps pending approval retryable when a resumed stream errors after creation", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps();+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });+ let streamErrorHandled: Promise<void> | undefined;++ agentMocks.createAgUiStream.mockImplementationOnce((params) => {+ streamErrorHandled = new Promise((resolve, reject) =>+ setTimeout(() => {+ Promise.resolve(+ params.options.onError?.(new Error("stream failed")),+ )+ .then(() => resolve())+ .catch(reject);+ }, 0),+ );++ return new ReadableStream();+ });++ const { response } = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-post-stream-failed",+ forwardedProps,+ });++ expect(response.status).toBe(200);+ await streamErrorHandled;+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(true);++ const retry = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-post-stream-retry",+ forwardedProps,+ });++ expect(retry.response.status).toBe(200);+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(false);+ expect(agentMocks.createAgUiStream).toHaveBeenCalledTimes(2);+ });+ });+it("returns 429 when an in-app agent run exceeds the rate limit", async () => {const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;@@ -507,7 +915,7 @@ async function createPersistedInAppAgentSession(params: {function createInAppAgentSession(params: {orgId: string;projectId: string;- userId: string;+ userId?: string;admin?: boolean;includeProjectMembership?: boolean;}): Session {@@ -517,7 +925,7 @@ function createInAppAgentSession(params: {expires: new Date(Date.now() + 60_000).toISOString(),environment: { enableExperimentalFeatures: false },user: {- id: params.userId,+ id: params.userId ?? "user-1",name: "Test User",email: "[email protected]",image: null,@@ -552,3 +960,136 @@ function createInAppAgentSession(params: {},} as Session;}++async function withInAppAgentCloudEnv<T>(run: () => Promise<T>): Promise<T> {+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;+ const originalAiFeaturesPublicKey = env.LANGFUSE_AI_FEATURES_PUBLIC_KEY;+ const originalAiFeaturesSecretKey = env.LANGFUSE_AI_FEATURES_SECRET_KEY;++ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY = "pk-lf-test";+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY = "sk-lf-test";++ try {+ return await run();+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;+ (env as any).LANGFUSE_AI_FEATURES_PUBLIC_KEY = originalAiFeaturesPublicKey;+ (env as any).LANGFUSE_AI_FEATURES_SECRET_KEY = originalAiFeaturesSecretKey;+ }+}++async function setupInAppAgentProjectSession() {+ const { org, project } = await createOrgProjectAndApiKey();+ const userId = randomUUID();++ await prisma.organization.update({+ where: { id: org.id },+ data: { aiFeaturesEnabled: true },+ });+ await prisma.user.create({+ data: {+ id: userId,+ email: `in-app-agent-${userId}@example.com`,+ name: "In-app Agent User",+ },+ });+ authMocks.getServerSession.mockResolvedValue(+ createInAppAgentSession({ orgId: org.id, projectId: project.id, userId }),+ );++ return { org, project, userId };+}++function createResumeForwardedProps() {+ return {+ command: {+ resume: {+ approved: true,+ approvalRequest: {+ type: "tool_approval_request" as const,+ toolCallId: `tool-call-${randomUUID()}`,+ toolName: "langfuse_upsertDataset",+ args: { name: "Approved dataset" },+ runId: `suspended-run-${randomUUID()}`,+ },+ },+ },+ };+}++async function callInAppAgentRoute(params: {+ projectId: string;+ conversationId: string;+ runId?: string;+ forwardedProps: ReturnType<typeof createResumeForwardedProps>;+}) {+ const { default: handler } =+ await import("@/src/ee/features/in-app-agent/server/handler");+ const response = await handler(+ new Request("http://localhost/api/in-app-agent", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ threadId: params.conversationId,+ runId: params.runId ?? "client-run-1",+ messages: [],+ tools: [],+ context: [],+ state: {+ type: "existingConversation",+ projectId: params.projectId,+ conversationId: params.conversationId,+ },+ forwardedProps: params.forwardedProps,+ }),+ }),+ );++ return { response };+}++async function seedPendingToolApproval(params: {+ projectId: string;+ conversationId: string;+ userId: string;+ approvalRequest: InAppAgentToolApprovalRequest;+}) {+ await prisma.inAppAgentConversation.upsert({+ where: {+ id_projectId: {+ id: params.conversationId,+ projectId: params.projectId,+ },+ },+ create: {+ id: params.conversationId,+ projectId: params.projectId,+ createdByUserId: params.userId,+ title: "Pending approval test",+ },+ update: {},+ });++ await storePendingToolApproval(params);+}++async function pendingToolApprovalExists(params: {+ projectId: string;+ conversationId: string;+ toolCallId: string;+}) {+ const pendingApproval = await prisma.inAppAgentPendingToolApproval.findUnique(+ {+ where: {+ projectId_conversationId_toolCallId: params,+ },+ select: { toolCallId: true },+ },+ );++ return Boolean(pendingApproval);+}diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex e824caa677..162ba98ca0 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -1,6 +1,7 @@import type { Session } from "next-auth";import { EventType } from "@ag-ui/core";import { randomUUID } from "crypto";+import { vi } from "vitest";import type { Plan } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";@@ -24,6 +25,10 @@ import {import { createInnerTRPCContext } from "@/src/server/api/trpc";import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";+vi.mock("@/src/server/auth", () => ({+ getServerAuthSession: vi.fn(),+}));+describe("in-app agent persistence", () => {const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;@@ -988,6 +993,111 @@ describe("in-app agent persistence", () => {]);});+ it("drops assistant tool calls without results from loaded conversation history", async () => {+ const { caller, projectId, userId } = await createCaller();+ const conversation = await createConversation({ projectId, userId });+ const run = await createConversationRun({+ projectId,+ conversationId: conversation.id,+ userId,+ });+ const events = await startCompactRun({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ messageId: "user-1",+ content: "search",+ });+ const process = (event: AgUiEvent) =>+ processAndPersistEvent({+ projectId,+ conversationId: conversation.id,+ runId: run.id,+ events,+ event,+ });++ await process({+ type: EventType.TEXT_MESSAGE_START,+ messageId: "assistant-1",+ role: "assistant",+ });+ await process({+ type: EventType.TOOL_CALL_START,+ toolCallId: "paired-tool-call",+ toolCallName: "list_traces",+ parentMessageId: "assistant-1",+ });+ await process({+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "paired-tool-call",+ delta: "{}",+ });+ await process({+ type: EventType.TOOL_CALL_END,+ toolCallId: "paired-tool-call",+ });+ await process({+ type: EventType.TOOL_CALL_START,+ toolCallId: "unapproved-tool-call",+ toolCallName: "get_trace",+ parentMessageId: "assistant-1",+ });+ await process({+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "unapproved-tool-call",+ delta: "{}",+ });+ await process({+ type: EventType.TOOL_CALL_END,+ toolCallId: "unapproved-tool-call",+ });+ await process({+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "assistant-1",+ delta: "calling tools",+ });+ await process({+ type: EventType.TEXT_MESSAGE_END,+ messageId: "assistant-1",+ });+ await process({+ type: EventType.TOOL_CALL_RESULT,+ messageId: "tool-result-1",+ toolCallId: "paired-tool-call",+ content: "[]",+ role: "tool",+ });++ const detail = await caller.getConversation({+ projectId,+ conversationId: conversation.id,+ });++ expect(detail.messages).toEqual([+ { id: "user-1", role: "user", content: "search" },+ {+ id: "assistant-1",+ role: "assistant",+ content: "calling tools",+ runId: run.id,+ toolCalls: [+ {+ id: "paired-tool-call",+ type: "function",+ function: { name: "list_traces", arguments: "{}" },+ },+ ],+ },+ {+ id: "tool-result-1",+ role: "tool",+ content: "[]",+ toolCallId: "paired-tool-call",+ },+ ]);+ });+it("drops failed redirect tool results before replay", async () => {const { projectId, userId } = await createCaller();const conversation = await createConversation({ projectId, userId });diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsindex 99257c5df1..6002c5f20e 100644--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -1,19 +1,31 @@import { EventType } from "@ag-ui/core";import { HttpAgent } from "@ag-ui/client";import { Agent } from "@mastra/core/agent";+import { MCPClient } from "@mastra/mcp";import { describe, expect, it, vi } from "vitest";import type { AgUiEvent } from "@/src/ee/features/in-app-agent/schema";-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";+import {+ IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER,+ IN_APP_AGENT_REDIRECT_TOOL_NAME,+} from "@/src/ee/features/in-app-agent/constants";import { patchMastraToolCallInputStreaming } from "@/src/ee/features/in-app-agent/server/agent";+import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES } from "@/src/ee/features/in-app-agent/server/tools";import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@/src/features/filters/constants/internal-environments";import { decodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";+import "@/src/features/mcp/server/bootstrap";+import { toolRegistry } from "@/src/features/mcp/server/registry";import type { MastraAgent } from "@ag-ui/mastra";const adapterEvents = vi.hoisted(() => ({items: [] as AgUiEvent[],cleanup: vi.fn().mockResolvedValue(undefined),inputs: [] as unknown[],+ createScoreConfigExecute: vi.fn().mockResolvedValue({+ id: "score-config-1",+ name: "readiness",+ dataType: "NUMERIC",+ }),}));const instrumentationMocks = vi.hoisted(() => {@@ -38,6 +50,11 @@ const promptMocks = vi.hoisted(() => ({getPrompt: vi.fn(),}));+const defaultInAppAgentUserAccess = {+ projectRole: "OWNER" as const,+ isAdmin: false,+};+vi.mock("@ag-ui/mastra", () => ({MastraAgent: vi.fn().mockImplementation(function () {return {@@ -78,7 +95,21 @@ vi.mock("@mastra/mcp", () => ({listTools: vi.fn().mockResolvedValue({}),listToolsetsWithErrors: vi.fn().mockResolvedValue({toolsets: {- langfuse: { search: { server: "langfuse" } },+ langfuse: {+ getHealth: {+ server: "langfuse",+ annotations: { destructiveHint: true },+ },+ search: { server: "langfuse" },+ upsertDataset: {+ server: "langfuse",+ annotations: { destructiveHint: false },+ },+ createScoreConfig: {+ server: "langfuse",+ execute: adapterEvents.createScoreConfigExecute,+ },+ },langfuseDocs: {search: {server: "langfuseDocs",@@ -113,6 +144,12 @@ vi.mock("@mastra/mcp", () => ({},}),},+ fetch: {+ server: "langfuseDocs",+ execute: vi.fn().mockResolvedValue({+ content: "Langfuse docs content",+ }),+ },},},errors: {},@@ -310,6 +347,131 @@ describe("patchMastraToolCallInputStreaming", () => {]);});+ it("converts tool-call approval chunks to suspended tool calls", () => {+ const { forwardedChunks, onError, processor } =+ createPatchedChunkProcessor();++ processor.handleChunk({+ type: "tool-call-approval",+ payload: {+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ resumeSchema: { type: "object" },+ },+ });++ expect(onError).not.toHaveBeenCalled();+ expect(forwardedChunks).toEqual([+ {+ type: "tool-call-suspended",+ payload: {+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ resumeSchema: { type: "object" },+ suspendPayload: {+ type: "approval",+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ },+ },+ },+ ]);+ });++ it("drops streamed tool-call args when the tool call becomes an approval", () => {+ const { forwardedChunks, onError, processor } =+ createPatchedChunkProcessor();++ processor.handleChunk({+ type: "tool-call-input-streaming-start",+ payload: {+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ },+ });+ processor.handleChunk({+ type: "tool-call-delta",+ payload: {+ toolCallId: "tool-call-1",+ argsTextDelta:+ '{"name":"readiness","dataType":"NUMERIC","numericMinValue":0,"numericMaxValue":1}',+ },+ });+ processor.handleChunk({+ type: "tool-call-approval",+ payload: {+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ },+ });+ processor.handleChunk({+ type: "tool-call-input-streaming-end",+ payload: { toolCallId: "tool-call-1" },+ });++ expect(onError).not.toHaveBeenCalled();+ expect(forwardedChunks).toEqual([+ {+ type: "tool-call-suspended",+ payload: expect.objectContaining({+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ }),+ },+ ]);+ });++ it("reports malformed tool-call approvals", () => {+ const { forwardedChunks, onError, processor } =+ createPatchedChunkProcessor();++ const shouldStop = processor.handleChunk({+ type: "tool-call-approval",+ payload: {+ toolCallId: "tool-call-1",+ args: { name: "readiness" },+ },+ });++ expect(shouldStop).toBe(true);+ expect(onError).toHaveBeenCalledWith(+ new Error(+ "Malformed tool-call-approval: missing toolCallId or toolName in payload",+ ),+ );+ expect(forwardedChunks).toEqual([]);+ });+it("reports malformed tool-call deltas with no known tool name", () => {const { forwardedChunks, onError, processor } =createPatchedChunkProcessor();@@ -332,6 +494,23 @@ describe("patchMastraToolCallInputStreaming", () => {});});+describe("IN_APP_AGENT_LANGFUSE_MCP_TOOL_APPROVALS", () => {+ const getRegisteredLangfuseMcpTools = () =>+ toolRegistry+ .getFeatures()+ .flatMap((feature) => feature.tools.map((tool) => tool.definition));++ it("classifies every Langfuse MCP tool exactly once", () => {+ const tools = getRegisteredLangfuseMcpTools();+ const registeredToolNames = tools.map((tool) => tool.name).sort();+ const classifiedToolNames = Object.keys(+ IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES,+ ).sort();++ expect(classifiedToolNames).toEqual(registeredToolNames);+ });+});+describe("createAgUiStream", () => {beforeEach(() => {vi.clearAllMocks();@@ -439,6 +618,8 @@ describe("createAgUiStream", () => {url: "https://example.com/api/public/mcp",publicKey: "pk",secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",},redirectAction: {projectId: "project-1",@@ -464,19 +645,42 @@ describe("createAgUiStream", () => {const { Agent } = await import("@mastra/core/agent");expect(Agent).toHaveBeenCalledWith(expect.objectContaining({- tools: {- langfuse_search: { server: "langfuse" },+ tools: expect.objectContaining({+ langfuse_getHealth: expect.objectContaining({+ server: "langfuse",+ }),+ langfuse_upsertDataset: expect.objectContaining({+ server: "langfuse",+ requireApproval: true,+ }),langfuseDocs_search: expect.objectContaining({server: "langfuseDocs",execute: expect.any(Function),}),+ langfuseDocs_fetch: expect.objectContaining({+ server: "langfuseDocs",+ execute: expect.any(Function),+ }),langfuse_proposeRedirect: expect.objectContaining({id: "langfuse_proposeRedirect",}),- },+ }),}),);const agentConfig = vi.mocked(Agent).mock.calls[0]?.[0];+ expect(agentConfig?.tools).not.toHaveProperty("langfuse_search");+ expect(agentConfig?.tools?.langfuse_getHealth).not.toHaveProperty(+ "requireApproval",+ );+ expect(agentConfig?.tools?.langfuseDocs_search).not.toHaveProperty(+ "requireApproval",+ );+ expect(agentConfig?.tools?.langfuseDocs_fetch).not.toHaveProperty(+ "requireApproval",+ );+ expect(+ agentConfig?.tools?.[IN_APP_AGENT_REDIRECT_TOOL_NAME]?.requireApproval,+ ).not.toBe(true);const docsSearchTool = agentConfig?.tools?.langfuseDocs_search;await expect(docsSearchTool?.execute?.({}, {})).resolves.toMatchObject({_meta: expect.objectContaining({@@ -591,6 +795,308 @@ describe("createAgUiStream", () => {expect(instrumentationMocks.instrumentation.flush).toHaveBeenCalled();});+ it("executes approved tools manually and continues with tool result history", async () => {+ const { createAgUiStream } =+ await import("@/src/ee/features/in-app-agent/server/agent");+ const input = createToolApprovalResumeInput(true);+ adapterEvents.inputs = [];+ adapterEvents.items = [+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ ];+ const persistedEvents: AgUiEvent[] = [];+ const langfuseClient = {+ getPrompt: promptMocks.getPrompt,+ };++ const stream = await createAgUiStream({+ input,+ signal: new AbortController().signal,+ options: {+ onEvent: (event) => {+ persistedEvents.push(event);+ },+ awsBedrock: { modelId: "test-model" },+ langfuseMcp: {+ url: "https://example.com/api/public/mcp",+ publicKey: "pk",+ secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",+ },+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: false,+ },+ langfuseClient,+ useLocalPrompt: false,+ },+ });+ await readStream(stream);++ expect(adapterEvents.inputs).toEqual([+ expect.objectContaining({+ forwardedProps: {},+ messages: expect.arrayContaining([+ {+ id: "tool-call-1-approval-tool-call",+ role: "assistant",+ runId: "interrupted-run-1",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "langfuse_createScoreConfig",+ arguments: JSON.stringify({+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ }),+ },+ },+ ],+ },+ {+ id: "tool-call-1-approval-tool-result",+ role: "tool",+ toolCallId: "tool-call-1",+ content: JSON.stringify({+ id: "score-config-1",+ name: "readiness",+ dataType: "NUMERIC",+ }),+ },+ ]),+ }),+ ]);++ // Approved resumes intentionally create two MCP clients: the first spends+ // the single-tool override on the approved mutation, the second continues+ // the run without that header so follow-up reads are not blocked.+ expect(vi.mocked(Agent)).toHaveBeenCalledTimes(2);+ expect(vi.mocked(MCPClient)).toHaveBeenCalledTimes(2);+ expect(vi.mocked(MCPClient).mock.calls[0]?.[0]).toMatchObject({+ servers: {+ langfuse: {+ requestInit: {+ headers: expect.objectContaining({+ Authorization: expect.stringContaining("Basic "),+ [IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER]: "run-override",+ }),+ },+ },+ },+ });++ expect(vi.mocked(MCPClient).mock.calls[1]?.[0]).toMatchObject({+ servers: {+ langfuse: {+ requestInit: {+ headers: expect.not.objectContaining({+ [IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER]: expect.anything(),+ }),+ },+ },+ },+ });+ expect(persistedEvents).toEqual([+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ {+ type: EventType.TOOL_CALL_START,+ parentMessageId: "tool-call-1-approval-tool-call",+ toolCallId: "tool-call-1",+ toolCallName: "langfuse_createScoreConfig",+ },+ {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "tool-call-1",+ delta: JSON.stringify({+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ }),+ },+ {+ type: EventType.TOOL_CALL_END,+ toolCallId: "tool-call-1",+ },+ {+ type: EventType.TOOL_CALL_RESULT,+ messageId: "tool-call-1-approval-tool-result",+ toolCallId: "tool-call-1",+ content: JSON.stringify({+ id: "score-config-1",+ name: "readiness",+ dataType: "NUMERIC",+ }),+ role: "tool",+ },+ ]);++ const agentConfig = vi.mocked(Agent).mock.calls[0]?.[0];+ const createScoreConfigTool = agentConfig?.tools+ ?.langfuse_createScoreConfig as+ | {+ execute?: ReturnType<typeof vi.fn>;+ }+ | undefined;+ expect(createScoreConfigTool?.execute).toHaveBeenCalledWith(+ {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ expect.objectContaining({+ abortSignal: expect.any(AbortSignal),+ agent: expect.objectContaining({+ toolCallId: "tool-call-1",+ threadId: "conversation-1",+ }),+ }),+ );+ });++ it("continues approved tools with a tool error result when execution fails", async () => {+ const { createAgUiStream } =+ await import("@/src/ee/features/in-app-agent/server/agent");+ const input = createToolApprovalResumeInput(true);+ const validationErrorMessage =+ "MCP error -32602: Validation failed: categories: Category must be an array of objects with label value pairs, where labels and values are unique.";+ adapterEvents.createScoreConfigExecute.mockRejectedValueOnce(+ new Error(validationErrorMessage),+ );+ adapterEvents.inputs = [];+ adapterEvents.items = [+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ ];+ const persistedEvents: AgUiEvent[] = [];+ const onError = vi.fn();+ const langfuseClient = {+ getPrompt: promptMocks.getPrompt,+ };++ const stream = await createAgUiStream({+ input,+ signal: new AbortController().signal,+ options: {+ onEvent: (event) => {+ persistedEvents.push(event);+ },+ onError,+ awsBedrock: { modelId: "test-model" },+ langfuseMcp: {+ url: "https://example.com/api/public/mcp",+ publicKey: "pk",+ secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",+ },+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: false,+ },+ langfuseClient,+ useLocalPrompt: false,+ },+ });+ await readStream(stream);++ expect(onError).not.toHaveBeenCalled();+ const resumedMessages = adapterEvents.inputs[0]?.messages ?? [];+ const retryGuidanceMessage = resumedMessages.find(+ (message) =>+ message.id === "tool-call-1-approval-tool-error-guidance" &&+ message.role === "developer",+ );++ expect(adapterEvents.inputs).toEqual([+ expect.objectContaining({+ forwardedProps: {},+ messages: expect.arrayContaining([+ expect.objectContaining({+ id: "tool-call-1-approval-tool-result",+ role: "tool",+ toolCallId: "tool-call-1",+ content: validationErrorMessage,+ error: validationErrorMessage,+ }),+ expect.objectContaining({+ id: "tool-call-1-approval-tool-error-guidance",+ role: "developer",+ content: expect.any(String),+ }),+ ]),+ }),+ ]);+ expect(retryGuidanceMessage?.content).toContain(+ "The approved tool call langfuse_createScoreConfig failed during execution.",+ );+ expect(retryGuidanceMessage?.content).toContain(+ `Rejected arguments: ${JSON.stringify({+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ })}`,+ );+ expect(retryGuidanceMessage?.content).toContain(+ `Tool error: ${validationErrorMessage}`,+ );+ expect(retryGuidanceMessage?.content).toContain(+ "Do not call the same tool again with identical arguments.",+ );+ expect(persistedEvents).toEqual([+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ {+ type: EventType.TOOL_CALL_START,+ parentMessageId: "tool-call-1-approval-tool-call",+ toolCallId: "tool-call-1",+ toolCallName: "langfuse_createScoreConfig",+ },+ {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "tool-call-1",+ delta: JSON.stringify({+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ }),+ },+ {+ type: EventType.TOOL_CALL_END,+ toolCallId: "tool-call-1",+ },+ expect.objectContaining({+ type: EventType.TOOL_CALL_RESULT,+ messageId: "tool-call-1-approval-tool-result",+ toolCallId: "tool-call-1",+ content: validationErrorMessage,+ role: "tool",+ error: validationErrorMessage,+ }),+ ]);+ });+it("escapes screen context delimiters before compiling prompt instructions", async () => {const { createAgUiStream } =await import("@/src/ee/features/in-app-agent/server/agent");@@ -638,6 +1144,8 @@ describe("createAgUiStream", () => {url: "https://example.com/api/public/mcp",publicKey: "pk",secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",},redirectAction: {projectId: "project-1",@@ -663,6 +1171,95 @@ describe("createAgUiStream", () => {);});+ it("aborts rejected tools after streaming the rejected tool result", async () => {+ const { createAgUiStream } =+ await import("@/src/ee/features/in-app-agent/server/agent");+ const input = createToolApprovalResumeInput(false);+ adapterEvents.inputs = [];+ adapterEvents.items = [+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ ];+ const langfuseClient = {+ getPrompt: promptMocks.getPrompt,+ };+ const persistedEvents: AgUiEvent[] = [];+ const streamedEvents: AgUiEvent[] = [];+ const onComplete = vi.fn();++ const stream = await createAgUiStream({+ input,+ signal: new AbortController().signal,+ options: {+ onEvent: (event) => {+ persistedEvents.push(event);+ },+ onComplete,+ awsBedrock: { modelId: "test-model" },+ langfuseMcp: {+ url: "https://example.com/api/public/mcp",+ publicKey: "pk",+ secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",+ },+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: false,+ },+ langfuseClient,+ useLocalPrompt: false,+ },+ });+ await readStream(stream, (event) => {+ streamedEvents.push(event);+ });++ expect(adapterEvents.inputs).toEqual([]);+ expect(vi.mocked(MCPClient)).not.toHaveBeenCalled();+ expect(vi.mocked(Agent)).not.toHaveBeenCalled();+ expect(persistedEvents).toEqual([+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ {+ type: EventType.TOOL_CALL_START,+ parentMessageId: "tool-call-1-approval-tool-call",+ toolCallId: "tool-call-1",+ toolCallName: "langfuse_createScoreConfig",+ },+ {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: "tool-call-1",+ delta: JSON.stringify({+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ }),+ },+ {+ type: EventType.TOOL_CALL_END,+ toolCallId: "tool-call-1",+ },+ {+ type: EventType.TOOL_CALL_RESULT,+ messageId: "tool-call-1-approval-tool-result",+ toolCallId: "tool-call-1",+ content: "Tool call was not approved by the user.",+ role: "tool",+ error: "Tool call was not approved by the user.",+ },+ ]);+ expect(streamedEvents).toEqual(persistedEvents);+ expect(onComplete).toHaveBeenCalledOnce();+ });+it("uses V4-compatible filters for traces redirect actions", async () => {const { createAgUiStream } =await import("@/src/ee/features/in-app-agent/server/agent");@@ -695,6 +1292,8 @@ describe("createAgUiStream", () => {url: "https://example.com/api/public/mcp",publicKey: "pk",secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",},redirectAction: {projectId: "project-1",@@ -791,6 +1390,8 @@ describe("createAgUiStream", () => {url: "https://example.com/api/public/mcp",publicKey: "pk",secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",},redirectAction: {projectId: "project-1",@@ -856,6 +1457,46 @@ async function readStream(}}+function createToolApprovalResumeInput(approved: boolean) {+ return {+ threadId: "conversation-1",+ runId: "run-2",+ messages: [+ {+ id: "user-message-1",+ role: "user" as const,+ content: "create a readiness score config",+ },+ ],+ tools: [],+ context: [],+ state: {+ type: "existingConversation",+ projectId: "project-1",+ conversationId: "conversation-1",+ },+ forwardedProps: {+ command: {+ resume: {+ approved,+ approvalRequest: {+ type: "tool_approval_request" as const,+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ dataType: "NUMERIC",+ numericMinValue: 0,+ numericMaxValue: 1,+ },+ runId: "interrupted-run-1",+ },+ },+ },+ },+ };+}+function parseEvents(chunk: string) {return chunk.split("\n\n")diff --git a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts b/web/src/__tests__/server/mcp-public-api-tools.servertest.tsindex 01474ece94..9205792373 100644--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts@@ -164,52 +164,50 @@ describe("MCP public API tools", () => {);});- it("exposes read-only tools for in-app agent keys", async () => {+ it("exposes the same feature-enabled tools for in-app agent keys", async () => {const toolNames = await getToolNames();const inAppToolNames = await getToolNames(- mockServerContext({ isInAppAgentKey: true }),+ mockServerContext({ inAppAgent: { permissions: "read" } }),);+ expect(inAppToolNames.sort()).toEqual(toolNames.sort());+ });++ it("does not resolve mutating tools for in-app agent keys without a run override", async () => {+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });+ const inAppToolNames = await getToolNames(context);+expect(inAppToolNames).toEqual(- expect.arrayContaining([- "listDatasets",- "getHealth",- "listScores",- "getScore",- "listScoreConfigs",- "listEvaluators",- "getEvaluator",- "listEvaluationRules",- "getEvaluationRule",- "listPrompts",- "getPrompt",- "getPromptUnresolved",- ]),+ expect.arrayContaining(["upsertDataset", "createModel"]),);- const readOnlyToolNames = toolNames.filter(- (toolName) =>- toolRegistry.getTool(toolName)?.definition.annotations?.readOnlyHint,- );- expect(inAppToolNames).toEqual(expect.arrayContaining(readOnlyToolNames));+ await expect(+ toolRegistry.getEnabledTool("upsertDataset", context),+ ).resolves.toBeUndefined();+ await expect(+ toolRegistry.getEnabledTool("createModel", context),+ ).resolves.toBeUndefined();});- it("hides mutating tools for in-app agent keys", async () => {- const toolNames = await getToolNames();- const inAppToolNames = await getToolNames(- mockServerContext({ isInAppAgentKey: true }),- );-- expect(inAppToolNames).not.toContain("upsertDataset");- expect(inAppToolNames).not.toContain("createModel");+ it("resolves only the overridden mutating tool for in-app agent keys", async () => {+ const context = mockServerContext({+ inAppAgent: {+ permissions: "single-tool-override",+ allowedToolName: "upsertDataset",+ },+ });- const writableToolNames = toolNames.filter(- (toolName) =>- !toolRegistry.getTool(toolName)?.definition.annotations?.readOnlyHint,- );- for (const toolName of writableToolNames) {- expect(inAppToolNames).not.toContain(toolName);- }+ await expect(+ toolRegistry.getEnabledTool("upsertDataset", context),+ ).resolves.toBeTruthy();+ await expect(+ toolRegistry.getEnabledTool("createModel", context),+ ).resolves.toBeUndefined();+ await expect(+ toolRegistry.getEnabledTool("listDatasets", context),+ ).resolves.toBeUndefined();});it("marks destructive public API tools", async () => {diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex 82aa78fada..3a0a77b23a 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -336,7 +336,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(listEvaluatorsTool.name, context),@@ -371,7 +373,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(getEvaluatorTool.name, context),@@ -403,7 +407,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(listEvaluationRulesTool.name, context),@@ -433,7 +439,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(getEvaluationRuleTool.name, context),@@ -506,7 +514,9 @@ describe("MCP Read Tools", () => {});maybeEventsTableIt("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(@@ -575,7 +585,9 @@ describe("MCP Read Tools", () => {});maybeEventsTableIt("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(@@ -649,7 +661,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(listObservationsTool.name, context),@@ -767,7 +781,7 @@ describe("MCP Read Tools", () => {const result = (await handleListObservations({ traceId, fields: ["id"], limit: 100 },- { ...context, isInAppAgentKey: true },+ { ...context, inAppAgent: { permissions: "read" } },)) as { data: Array<{ id: string; url: string }> };expect(result.data.map((item) => item.id)).toContain(observation.id);@@ -1641,7 +1655,7 @@ describe("MCP Read Tools", () => {const result = (await handleGetObservation({ observationId: observation.id, fields: ["id"] },- { ...context, isInAppAgentKey: true },+ { ...context, inAppAgent: { permissions: "read" } },)) as Record<string, unknown>;expect(result).toEqual({diff --git a/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.tsnew file mode 100644index 0000000000..37aae40a03--- /dev/null+++ b/web/src/__tests__/server/unit/in-app-agent-mcp-run-override.servertest.ts@@ -0,0 +1,49 @@+import {+ createInAppAgentMcpRunOverride,+ InAppAgentMcpRunOverrideSchema,+} from "@/src/ee/features/in-app-agent/server/human-in-the-loop";++describe("in-app agent MCP run override", () => {+ it("serializes the override as plain JSON", async () => {+ const token = await createInAppAgentMcpRunOverride({+ toolName: "upsertDataset",+ });++ expect(JSON.parse(token)).toEqual({+ toolName: "upsertDataset",+ });+ });++ it("accepts a matching plain JSON override", async () => {+ const token = await createInAppAgentMcpRunOverride({+ toolName: "upsertDataset",+ });++ expect(InAppAgentMcpRunOverrideSchema.safeParse(JSON.parse(token))).toEqual(+ {+ success: true,+ data: {+ toolName: "upsertDataset",+ },+ },+ );+ });++ it("rejects malformed or mismatched overrides", () => {+ expect(InAppAgentMcpRunOverrideSchema.safeParse("not-json").success).toBe(+ false,+ );++ expect(+ InAppAgentMcpRunOverrideSchema.safeParse({+ toolName: "notAMcpTool",+ }).success,+ ).toBe(false);++ expect(+ InAppAgentMcpRunOverrideSchema.safeParse({+ other: "value",+ }).success,+ ).toBe(false);+ });+});diff --git a/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.ts b/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.tsnew file mode 100644index 0000000000..30a1e14e36--- /dev/null+++ b/web/src/__tests__/server/unit/mcp-route-in-app-agent-context.servertest.ts@@ -0,0 +1,66 @@+import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@/src/ee/features/in-app-agent/constants";+import {+ createInAppAgentMcpRunOverride,+ InAppAgentMcpRunOverrideSchema,+} from "@/src/ee/features/in-app-agent/server/human-in-the-loop";+import { getInAppAgentContext } from "@/src/pages/api/public/mcp";+import type { NextApiRequest, NextApiResponse } from "next";+import { createMocks } from "node-mocks-http";++describe("MCP route in-app-agent context", () => {+ const createRequest = (overrideHeader?: string) => {+ const { req } = createMocks<NextApiRequest, NextApiResponse>({+ method: "POST",+ headers:+ overrideHeader === undefined+ ? {}+ : {+ [IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER]: overrideHeader,+ },+ });++ return req;+ };++ it("returns undefined for non in-app-agent keys", () => {+ const req = createRequest('{"toolName":"upsertDataset"}');++ expect(getInAppAgentContext(req, false)).toBeUndefined();+ expect(getInAppAgentContext(req, undefined)).toBeUndefined();+ });++ it("defaults to read permissions when no override header is present", () => {+ const req = createRequest();++ expect(getInAppAgentContext(req, true)).toEqual({ permissions: "read" });+ });++ it("falls back to read permissions for malformed override headers", () => {+ const malformedJsonReq = createRequest("not-json");+ const invalidToolReq = createRequest('{"toolName":"notAMcpTool"}');++ expect(getInAppAgentContext(malformedJsonReq, true)).toEqual({+ permissions: "read",+ });+ expect(getInAppAgentContext(invalidToolReq, true)).toEqual({+ permissions: "read",+ });+ });++ it("returns a single-tool override for valid override headers", async () => {+ const overrideHeader = await createInAppAgentMcpRunOverride({+ toolName: "upsertDataset",+ });+ const req = createRequest(overrideHeader);++ expect(+ InAppAgentMcpRunOverrideSchema.parse(JSON.parse(overrideHeader)),+ ).toEqual({+ toolName: "upsertDataset",+ });+ expect(getInAppAgentContext(req, true)).toEqual({+ permissions: "single-tool-override",+ allowedToolName: "upsertDataset",+ });+ });+});diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsxindex e43f793afe..e6b7b89980 100644--- a/web/src/components/ui/button.tsx+++ b/web/src/components/ui/button.tsx@@ -18,6 +18,8 @@ const buttonVariants = cva("bg-secondary text-secondary-foreground border border-destructive disabled:hover:bg-secondary disabled:hover:text-secondary-foreground hover:bg-destructive/90 hover:text-destructive-foreground",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",+ "outline-success":+ "border border-accent-dark-green bg-background text-accent-dark-green hover:bg-accent-light-green hover:text-accent-dark-green dark:border-dark-green dark:text-dark-green dark:hover:bg-light-green dark:hover:text-dark-green","outline-solid":"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:diff --git a/web/src/ee/features/in-app-agent/README.md b/web/src/ee/features/in-app-agent/README.mdindex 4af1221531..719589d8a5 100644--- a/web/src/ee/features/in-app-agent/README.md+++ b/web/src/ee/features/in-app-agent/README.md@@ -12,9 +12,10 @@ Runs are foreground-only. A conversation can have one active run; stale unfinish## Major Files-- `schema.ts`: runtime-neutral AG-UI schemas and types shared by browser, server, persistence, replay, and rendering.+- `schema.ts`: runtime-neutral AG-UI schemas and types shared by browser, server, persistence, replay, and rendering, including Langfuse-owned human-in-the-loop wire contracts.- `server/handler.ts`: streaming route and authority boundary for auth, request sanitization, run creation, MCP credentials, and terminal state.-- `server/agent.ts`: Mastra/Bedrock/MCP runtime setup, custom tool wiring, AG-UI event normalization, and cleanup.+- `server/agent.ts`: Mastra/Bedrock/MCP runtime setup, custom tool wiring, human-in-the-loop approval gates, AG-UI event normalization, and cleanup.+- `server/human-in-the-loop.ts`: interrupt parsing helpers, pending tool approval persistence, and resume approval validation/consumption.- `server/tools.ts`: custom agent tools with strict schemas and scoped, user-visible behavior.- `server/persistence.ts`: conversations, runs, events, replay, active-run locking, and stale-run recovery.- `server/router.ts`: non-streaming tRPC routes for conversation lists, replay, and feedback.@@ -36,11 +37,14 @@ flowchart TBSchema["schema.ts\nshared AG-UI contract"] -.-> ProviderSchema -.-> Handler+ Schema -.-> HumanLoop["server/human-in-the-loop.ts\napproval state + validation"]Schema -.-> RouterSchema -.-> Persistence["server/persistence.ts"]Handler --> PersistenceHandler --> Agent["server/agent.ts\nagent runtime"]+ Handler --> HumanLoop+ Agent --> HumanLoopAgent --> Tools["server/tools.ts\ncustom tools"]Agent --> Instrumentation["server/instrumentation.ts\nLangfuse telemetry"]Router --> Persistence@@ -50,10 +54,34 @@ flowchart TB1. Browser sends the latest message, conversation state, and screen context through `HttpAgent`.2. `server/handler.ts` validates the request and creates a server-owned run.-3. `server/agent.ts` streams normalized AG-UI events and calls telemetry hooks.-4. `server/instrumentation.ts` records prompt metadata, stream events, completion, aborts, and errors.-5. `server/persistence.ts` stores compacted events and reconstructs replay messages.-6. `InAppAiAgentProvider.tsx` renders live AG-UI state and hydrates selected conversations through `server/router.ts`.+3. `server/handler.ts` creates a temporary in-app-agent MCP API key and passes the signed-in user's project role/admin state into the agent runtime.+4. `server/agent.ts` filters Langfuse MCP tools through RBAC before exposing them to the model, and for approved Langfuse MCP resumes adds a tool-scoped override payload.+5. `server/agent.ts` connects Mastra to Langfuse MCP with the temporary API key and sends the override in `x-langfuse-in-app-agent-tool-override` when a single approved mutating MCP tool may run.+6. `server/agent.ts` streams normalized AG-UI events and calls telemetry hooks.+7. `server/instrumentation.ts` records prompt metadata, stream events, completion, aborts, and errors.+8. `server/persistence.ts` stores compacted events and reconstructs replay messages.+9. `InAppAiAgentProvider.tsx` renders live AG-UI state and hydrates selected conversations through `server/router.ts`.++## MCP Tool Authorization++The in-app agent uses two request-scoped inputs when calling Langfuse MCP:++- A temporary project-scoped API key marked as an in-app-agent key.+- An optional server-generated tool override sent with `x-langfuse-in-app-agent-tool-override`.++The API key authenticates the request and scopes it to the project. Without an override, in-app-agent keys are restricted to MCP tools annotated with `readOnlyHint: true`. When the user approves a single Langfuse MCP tool call, `server/handler.ts` creates a JSON override naming that one unprefixed MCP registry tool and passes it to the MCP route through the request header above.++MCP registry behavior:++- Normal project API keys can call all enabled MCP tools.+- In-app-agent keys can call read-only tools directly when the tool has `readOnlyHint: true`.+- In-app-agent keys need a valid tool override to call one non-read-only Langfuse MCP tool.++RBAC is the first gate for Langfuse MCP tools. Before a tool is exposed to the model, `server/tools.ts` checks the signed-in user's `projectRole` and `isAdmin` against the tool's required `ProjectScope` with `hasProjectAccess()`. That means the assistant never sees tools the user could not use manually in the product UI or APIs. Human approval is a second gate on top of RBAC for tools classified as `"approval"`: approval can allow one execution of a tool the user already has access to, but it does not widen the user's project permissions.++Human approval is separate from the MCP tool override. `server/agent.ts` classifies every Langfuse MCP tool in `IN_APP_AGENT_LANGFUSE_MCP_TOOL_APPROVALS`, using unprefixed MCP registry names and either `"auto"` or `"approval"`. The map is keyed by a type-only `McpToolName` union derived from the MCP feature modules, and tests compare this map against `toolRegistry`, so adding a Langfuse MCP tool requires an explicit in-app agent approval classification without exporting MCP feature modules into production in-app-agent code.++`IN_APP_AGENT_AUTO_APPROVED_TOOL_NAMES` is generated from that map by prefixing Langfuse MCP tools with `langfuse_` and adding local tools such as `IN_APP_AGENT_REDIRECT_TOOL_NAME`; docs MCP tools are auto-approved by the `langfuseDocs_` prefix. `server/agent.ts` marks every other tool with Mastra `requireApproval: true`. Mastra emits an interrupt, the browser asks the user, and resumed approvals are validated by `server/handler.ts` against the pending approval row persisted in Postgres. `server/human-in-the-loop.ts` adapts Mastra's runtime interrupt payload into the Langfuse-owned `tool_approval_request` contract from `schema.ts`; the browser stores and forwards only that runtime-neutral shape. `server/human-in-the-loop.ts` consumes the pending approval, executes approved tool calls at the adapter boundary, and injects synthetic AG-UI tool-call events/messages before the agent continues. The pending approval row stays server-local, stores the tool call identity and a stable argument fingerprint, and expires after a short TTL.## Change Rulesdiff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsxindex d21dc43a76..faf7b61f83 100644--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx@@ -38,17 +38,24 @@ export function ControlledInAppAgentWindow(isSubmitting,loadMoreConversations,messages,+ pendingToolApprovals,+ approveToolCall,+ rejectToolCall,selectConversation,selectedConversationId,submit,submitFeedback,} = useInAppAiAgent();const isInputDisabled =- isRunning || isSubmitting || isSelectedConversationHydrating;+ isRunning ||+ isSubmitting ||+ isSelectedConversationHydrating ||+ pendingToolApprovals.length > 0;const drawerMessages = useMemo(- () => getDrawerMessages({ error, isRunning, messages }),- [error, isRunning, messages],+ () =>+ getDrawerMessages({ error, isRunning, messages, pendingToolApprovals }),+ [error, isRunning, messages, pendingToolApprovals],);const closeButtonProps =@@ -73,6 +80,8 @@ export function ControlledInAppAgentWindow(onNewConversation={() => selectConversation(null)}onExpandedChange={props.onExpandedChange}onSubmit={submit}+ onApproveToolCall={approveToolCall}+ onRejectToolCall={rejectToolCall}onSubmitFeedback={submitFeedback}{...closeButtonProps}/>diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsxindex c7ad67c432..7db31e43e1 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx@@ -45,6 +45,8 @@ import {projectMarkdownToRenderedText,} from "./utils/markdown";import styles from "./InAppAgentMessage.module.css";+import { InAppAgentToolPayload } from "./InAppAgentToolPayload";+import { type InAppAgentToolCallContent } from "@/src/ee/features/in-app-agent/components/utils/utils";export type InAppAgentMessageRole = "assistant" | "user";@@ -70,14 +72,6 @@ export type InAppAgentMessageContent =isLoading?: boolean;};-export type InAppAgentToolCallContent = {- type: "tool";- name: string;- args: string;- result?: string;- error?: string;-};-const parseAbsoluteUrl = (href: string): URL | null => {try {return new URL(href);@@ -597,7 +591,9 @@ function ToolCallGroup({isLoading?: boolean;isCompact?: boolean;}) {- const label = `${isLoading ? "Calling" : "Called"} ${tools.length} ${tools.length === 1 ? "tool" : "tools"}`;+ const label = `${isLoading ? "Calling" : "Called"} ${tools.length} ${+ tools.length === 1 ? "tool" : "tools"+ }`;const paddingX = cn(isCompact ? "px-2.5" : "px-3");const iconSize = isCompact ? "size-3" : "size-4";@@ -631,83 +627,43 @@ function ToolCallGroup({<divclassName={cn("border-border mt-2 space-y-2 border-t pt-2", paddingX)}>- {tools.map((tool, index) => (- <div key={`${tool.name}-${index}`} className="rounded-lg">- <ToolCallDetails tool={tool} />- </div>- ))}- </div>- </details>- );-}--function ToolCallDetails({ tool }: { tool: InAppAgentToolCallContent }) {- const resultLabel = tool.error ? "Error" : "Result";-- return (- <details className="group/tool min-w-0">- <summary className="flex cursor-pointer list-none items-center gap-2 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden">- <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />- <span className="min-w-0 flex-1 truncate py-0.5">Used {tool.name}</span>- <span className="text-muted-foreground text-xs group-open/tool:hidden">- Show- </span>- <span className="text-muted-foreground hidden text-xs group-open/tool:inline">- Hide- </span>- </summary>- <div className="mt-2 space-y-2">- <ToolPayload label="Arguments" value={tool.args} />- {tool.result !== undefined || tool.error !== undefined ? (- <ToolPayload- label={resultLabel}- value={tool.error ?? tool.result ?? ""}- isError={Boolean(tool.error)}- />- ) : null}+ {tools.map((tool, index) => {+ const resultLabel = tool.error ? "Error" : "Result";++ return (+ <div key={`${tool.name}-${index}`} className="rounded-lg">+ <details className="group/tool min-w-0">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden">+ <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate py-0.5">+ Used {tool.name}+ </span>+ <span className="text-muted-foreground text-xs group-open/tool:hidden">+ Show+ </span>+ <span className="text-muted-foreground hidden text-xs group-open/tool:inline">+ Hide+ </span>+ </summary>+ <div className="mt-2 space-y-2">+ <InAppAgentToolPayload label="Arguments" value={tool.args} />+ {tool.result !== undefined || tool.error !== undefined ? (+ <InAppAgentToolPayload+ label={resultLabel}+ value={tool.error ?? tool.result ?? ""}+ isError={Boolean(tool.error)}+ />+ ) : null}+ </div>+ </details>+ </div>+ );+ })}</div></details>);}-function ToolPayload({- label,- value,- isError = false,-}: {- label: string;- value: string;- isError?: boolean;-}) {- const toolPayload = useMemo(() => {- const trimmedValue = value.trim();-- if (!trimmedValue) {- return "{}";- }-- try {- return JSON.stringify(JSON.parse(trimmedValue), null, 2);- } catch {- return value;- }- }, [value]);-- return (- <div className="space-y-1">- <p className="text-muted-foreground text-xs font-medium">{label}</p>- <pre- className={cn(- "bg-muted text-muted-foreground max-h-64 overflow-auto rounded-md p-2 text-xs whitespace-pre-wrap",- isError && "text-destructive",- )}- >- {toolPayload}- </pre>- </div>- );-}-function MessageText({role,text,diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsxnew file mode 100644index 0000000000..3b410dba14--- /dev/null+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsx@@ -0,0 +1,86 @@+import preview from "../../../../../.storybook/preview";+import { fn } from "storybook/test";+import { InAppAgentToolCallCard } from "./InAppAgentToolCallCard";++const meta = preview.meta({+ component: InAppAgentToolCallCard,+});++export const Default = meta.story({+ args: {+ isCompact: true,+ tool: {+ type: "tool",+ name: "langfuse_queryMetrics",+ args: JSON.stringify(+ {+ view: "observations",+ metrics: [{ measure: "count", aggregation: "count" }],+ },+ null,+ 2,+ ),+ result: JSON.stringify({ data: [{ count_count: 42 }] }, null, 2),+ },+ },+});++export const Error = meta.story({+ args: {+ isCompact: true,+ tool: {+ type: "tool",+ name: "langfuse_getTraces",+ args: JSON.stringify({ limit: 10 }, null, 2),+ error: "Failed to load traces: missing project access.",+ },+ },+});++export const ApprovalRequired = meta.story({+ args: {+ isCompact: true,+ tool: {+ type: "tool",+ name: "langfuse_upsertDataset",+ args: JSON.stringify(+ {+ name: "regression-examples",+ description: "Examples used for release regression tests",+ },+ null,+ 2,+ ),+ approval: {+ id: "approval-1",+ status: "pending",+ },+ },+ onApproveToolCall: fn(),+ onRejectToolCall: fn(),+ },+});++export const ApprovalSubmitting = meta.story({+ args: {+ isCompact: true,+ tool: {+ type: "tool",+ name: "langfuse_upsertDataset",+ args: JSON.stringify(+ {+ name: "regression-examples",+ description: "Examples used for release regression tests",+ },+ null,+ 2,+ ),+ approval: {+ id: "approval-1",+ status: "submitting",+ },+ },+ onApproveToolCall: fn(),+ onRejectToolCall: fn(),+ },+});diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsxnew file mode 100644index 0000000000..a6e8c6320d--- /dev/null+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsx@@ -0,0 +1,109 @@+"use client";++import { Check, Loader2, Wrench } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { cn } from "@/src/utils/tailwind";+import { InAppAgentToolPayload } from "./InAppAgentToolPayload";+import { type InAppAgentToolCallContent } from "@/src/ee/features/in-app-agent/components/utils/utils";++export function InAppAgentToolCallCard({+ tool,+ isCompact = false,+ onApproveToolCall,+ onRejectToolCall,+}: {+ tool: InAppAgentToolCallContent;+ isCompact?: boolean;+ onApproveToolCall?: (approvalId: string) => Promise<void>;+ onRejectToolCall?: (approvalId: string) => Promise<void>;+}) {+ const approval = tool.approval;+ const isApprovalPending = approval?.status === "pending";+ const isApprovalSubmitting = approval?.status === "submitting";+ const resultLabel = tool.error ? "Error" : "Result";++ return (+ <div+ className={cn(+ "bg-card dark:bg-header text-foreground border-border rounded-2xl border shadow-xs",+ isCompact+ ? "rounded-xl px-2.5 py-2 text-[0.775rem]"+ : "px-3 py-2.5 text-sm",+ )}+ >+ {approval ? (+ <div className="min-w-0">+ <div className="flex items-center gap-2 text-xs leading-none font-medium">+ <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate py-0.5">+ Approve {tool.name}?+ </span>+ </div>+ <div className="mt-2 space-y-2">+ <InAppAgentToolPayload label="Arguments" value={tool.args} />+ <div className="flex flex-wrap items-center gap-2">+ <Button+ type="button"+ size="sm"+ variant="outline-success"+ className="h-7"+ disabled={isApprovalSubmitting || !onApproveToolCall}+ onClick={() => {+ if (isApprovalPending) {+ onApproveToolCall?.(approval.id).catch(() => undefined);+ }+ }}+ >+ {isApprovalSubmitting ? (+ <Loader2 className="mr-1 size-3 animate-spin" />+ ) : (+ <Check className="mr-1 size-3" />+ )}+ Confirm+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-7"+ disabled={isApprovalSubmitting || !onRejectToolCall}+ onClick={() => {+ if (isApprovalPending) {+ onRejectToolCall?.(approval.id).catch(() => undefined);+ }+ }}+ >+ Reject+ </Button>+ </div>+ </div>+ </div>+ ) : (+ <details className="group/tool min-w-0">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden">+ <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate py-0.5">+ Used {tool.name}+ </span>+ <span className="text-muted-foreground text-xs group-open/tool:hidden">+ Show+ </span>+ <span className="text-muted-foreground hidden text-xs group-open/tool:inline">+ Hide+ </span>+ </summary>+ <div className="mt-2 space-y-2">+ <InAppAgentToolPayload label="Arguments" value={tool.args} />+ {tool.result !== undefined || tool.error !== undefined ? (+ <InAppAgentToolPayload+ label={resultLabel}+ value={tool.error ?? tool.result ?? ""}+ isError={Boolean(tool.error)}+ />+ ) : null}+ </div>+ </details>+ )}+ </div>+ );+}diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsxnew file mode 100644index 0000000000..cb5185c48f--- /dev/null+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsx@@ -0,0 +1,42 @@+"use client";++import { useMemo } from "react";+import { cn } from "@/src/utils/tailwind";++export function InAppAgentToolPayload({+ label,+ value,+ isError = false,+}: {+ label: string;+ value: string;+ isError?: boolean;+}) {+ const toolPayload = useMemo(() => {+ const trimmedValue = value.trim();++ if (!trimmedValue) {+ return "{}";+ }++ try {+ return JSON.stringify(JSON.parse(trimmedValue), null, 2);+ } catch {+ return value;+ }+ }, [value]);++ return (+ <div className="space-y-1">+ <p className="text-muted-foreground text-xs font-medium">{label}</p>+ <pre+ className={cn(+ "bg-muted text-muted-foreground max-h-64 overflow-auto rounded-md p-2 text-xs whitespace-pre-wrap",+ isError && "text-destructive",+ )}+ >+ {toolPayload}+ </pre>+ </div>+ );+}diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsxindex 5846506eb8..e486cb32d0 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx@@ -433,6 +433,8 @@ const meta = preview.meta({onDeleteConversation: fn(),onLoadMoreConversations: fn(),onNewConversation: fn(),+ onApproveToolCall: fn(),+ onRejectToolCall: fn(),onSelectConversation: fn(),onClose: fn(),onExpandedChange: fn(),@@ -443,6 +445,44 @@ const meta = preview.meta({render: (args) => <StatefulInAppAgentWindow {...args} />,});+export const ToolApprovalRequired = meta.story({+ args: {+ isInputDisabled: true,+ selectedConversationId: "conversation-1",+ messages: [+ {+ id: "user-1",+ role: "user",+ content: {+ type: "text",+ text: "Create a dataset for regression examples.",+ },+ },+ {+ id: "approval-1",+ role: "assistant",+ content: {+ type: "toolGroup",+ tools: [+ {+ type: "tool",+ name: "langfuse_upsertDataset",+ args: JSON.stringify({+ name: "regression-examples",+ description: "Examples used for release regression tests",+ }),+ approval: {+ id: "approval-1",+ status: "pending",+ },+ },+ ],+ },+ },+ ],+ },+});+export const Empty = meta.story({args: {messages: [],diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsxindex 6f68cb9190..ea07773028 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx@@ -32,6 +32,7 @@ import {type InAppAgentMessageRole,} from "./InAppAgentMessage";import type { InAppAgentMessageFeedbackValue } from "@/src/ee/features/in-app-agent/schema";+import { InAppAgentToolCallCard } from "@/src/ee/features/in-app-agent/components/InAppAgentToolCallCard";const AUTO_SCROLL_THRESHOLD_PX = 50;const SCROLL_DIRECTION_TOLERANCE_PX = 1;@@ -98,6 +99,8 @@ export type InAppAgentWindowProps = {onDeleteConversation: (conversation: InAppAgentWindowConversation) => void;onLoadMoreConversations: () => void;onNewConversation: () => void;+ onApproveToolCall: (approvalId: string) => Promise<void>;+ onRejectToolCall: (approvalId: string) => Promise<void>;onSelectConversation: (conversationId: string) => void;onSubmit: (input: string) => boolean | Promise<boolean>;onSubmitFeedback: (params: {@@ -123,6 +126,8 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {onExpandedChange,onLoadMoreConversations,onNewConversation,+ onApproveToolCall,+ onRejectToolCall,onSelectConversation,onSubmit,onSubmitFeedback,@@ -136,6 +141,34 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {const [isConversationHistoryOpen, setIsConversationHistoryOpen] =useState(false);const hasUserMessage = messages.some((message) => message.role === "user");+ const pendingToolCalls = messages.flatMap((message) =>+ message.content.type === "toolGroup"+ ? message.content.tools.filter((tool) => tool.approval)+ : [],+ );+ const visibleMessages = messages+ .map((message) => {+ if (message.content.type !== "toolGroup") {+ return message;+ }++ const visibleTools = message.content.tools.filter(+ (tool) => !tool.approval,+ );++ if (visibleTools.length === 0) {+ return null;+ }++ return {+ ...message,+ content: {+ ...message.content,+ tools: visibleTools,+ },+ } satisfies InAppAgentWindowMessage;+ })+ .filter((message): message is InAppAgentWindowMessage => message !== null);const submitInput = (content: string) => {const trimmedContent = content.trim();@@ -411,20 +444,20 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {) : null}<ol className="flex w-full flex-col gap-3 pb-4">- {messages.map((message, index) => {+ {visibleMessages.map((message, index) => {const hasFullWidthContent =message.content.type === "toolGroup" ||message.content.type === "redirectAction";- const nextUserMessageIndex = messages.findIndex(+ const nextUserMessageIndex = visibleMessages.findIndex((nextMessage, nextIndex) =>nextIndex > index && nextMessage.role === "user",);const nextTurnStartIndex =nextUserMessageIndex === -1- ? messages.length+ ? visibleMessages.length: nextUserMessageIndex;- const isLastMessageOfTurn = messages+ const isLastMessageOfTurn = visibleMessages.slice(index + 1, nextTurnStartIndex).every((nextMessage) => nextMessage.role !== "assistant");const feedbackRunId =@@ -477,6 +510,31 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {) : null}</div></div>+ {pendingToolCalls.length > 0 ? (+ <div+ className={cn(+ "shrink-0 pt-1.5",+ isExpanded ? "px-1.5 pb-2" : "px-3 pb-2",+ )}+ >+ <div+ className={cn(+ "flex flex-col gap-2",+ isExpanded && "mx-auto max-w-3xl",+ )}+ >+ {pendingToolCalls.map((tool, index) => (+ <InAppAgentToolCallCard+ key={`${tool.approval?.id ?? tool.name}-${index}`}+ tool={tool}+ isCompact={!isExpanded}+ onApproveToolCall={onApproveToolCall}+ onRejectToolCall={onRejectToolCall}+ />+ ))}+ </div>+ </div>+ ) : null}<divclassName={cn("p-1.5",diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 2bbf78f052..1a31790e61 100644--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -13,12 +13,14 @@ import {import { HttpAgent } from "@ag-ui/client";import { useSession } from "next-auth/react";import { useRouter } from "next/router";+import { z } from "zod";import useSessionStorage from "@/src/components/useSessionStorage";import { env } from "@/src/env.mjs";import {createInAppAgentConversationId,createInAppAgentMessageId,+ createInAppAgentRunId,} from "@/src/ee/features/in-app-agent/ids";import {AgUiMessageSchema,@@ -26,6 +28,7 @@ import {type InAppAgentMessageFeedback,type InAppAgentMessageFeedbackValue,type InAppAgentRuntimeState,+ type InAppAgentToolApprovalRequest,} from "@/src/ee/features/in-app-agent/schema";import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showErrorToast } from "@/src/features/notifications/showErrorToast";@@ -41,6 +44,14 @@ const SELECTED_CONVERSATION_STORAGE_KEY_PREFIX =const OPEN_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-open";const FEEDBACK_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-feedback";+const MastraSuspendEventSchema = z.object({+ type: z.literal("mastra_suspend"),+ toolCallId: z.string().min(1),+ toolName: z.string().min(1),+ args: z.unknown().optional(),+ runId: z.string().min(1),+});+const getConversationAgentState = (projectId: string,conversationId: string,@@ -58,6 +69,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {setIsExpanded: () => undefined,isRunning: false,isSubmitting: false,+ pendingToolApprovals: [],isSelectedConversationHydrating: false,error: null,messages: [],@@ -69,6 +81,8 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {selectConversation: () => undefined,deleteConversation: async () => undefined,submit: async () => false,+ approveToolCall: async () => undefined,+ rejectToolCall: async () => undefined,submitFeedback: async () => undefined,};@@ -79,6 +93,12 @@ type InAppAiAgentFeedbackByConversationId = Record<Record<string, InAppAgentMessageFeedback>>;+export type InAppAgentPendingToolApproval = {+ id: string;+ approvalRequest: InAppAgentToolApprovalRequest;+ status: "pending" | "submitting";+};+export type InAppAiAgentConversation = {id: string;title: string | null;@@ -93,6 +113,7 @@ type InAppAiAgentContextType = {setIsExpanded: Dispatch<SetStateAction<boolean>>;isRunning: boolean;isSubmitting: boolean;+ pendingToolApprovals: InAppAgentPendingToolApproval[];isSelectedConversationHydrating: boolean;error: string | null;messages: InAppAiAgentMessage[];@@ -104,6 +125,8 @@ type InAppAiAgentContextType = {selectConversation: (conversationId: string | null) => void;deleteConversation: (conversationId: string) => Promise<void>;submit: (content: string) => Promise<boolean>;+ approveToolCall: (approvalId: string) => Promise<void>;+ rejectToolCall: (approvalId: string) => Promise<void>;submitFeedback: (params: {messageId: string;runId: string;@@ -190,6 +213,10 @@ function InAppAiAgentProviderInner({{},);const [messages, setMessages] = useState<InAppAiAgentMessage[]>([]);+ const [pendingToolApprovals, setPendingToolApprovals] = useState<+ InAppAgentPendingToolApproval[]+ >([]);+ const pendingToolApprovalsRef = useRef<InAppAgentPendingToolApproval[]>([]);const [isRunning, setIsRunning] = useState(false);const [isExpanded, setIsExpanded] = useState(false);const [isSubmitting, setIsSubmitting] = useState(false);@@ -275,7 +302,24 @@ function InAppAiAgentProviderInner({Boolean(selectedConversationId) &&conversationQuery.isLoading &&!conversationQuery.data;- const resetAgent = useCallback(() => {+ const updatePendingToolApprovals = useCallback(+ (+ updater: (+ currentApprovals: InAppAgentPendingToolApproval[],+ ) => InAppAgentPendingToolApproval[],+ ) => {+ const nextApprovals = updater(pendingToolApprovalsRef.current);+ pendingToolApprovalsRef.current = nextApprovals;+ setPendingToolApprovals(nextApprovals);+ },+ [],+ );++ const resetAgent = useCallback((options?: { preserveAgent?: boolean }) => {+ if (options?.preserveAgent) {+ return;+ }+if (agentRef.current?.isRunning) {intentionalAbortRef.current = true;}@@ -285,6 +329,8 @@ function InAppAiAgentProviderInner({agentRef.current?.abortRun();agentRef.current = null;activeRunIdRef.current = null;+ pendingToolApprovalsRef.current = [];+ setPendingToolApprovals([]);}, []);// Hydrate local state from the selected persisted conversation once it loads.@@ -309,7 +355,11 @@ function InAppAiAgentProviderInner({return;}- resetAgent();+ const hasResumablePendingApproval =+ pendingToolApprovalsRef.current.length > 0 &&+ agentRef.current?.threadId === selectedConversationId;++ resetAgent({ preserveAgent: hasResumablePendingApproval });// TODO: Avoid replacing hydrated messages when only server-generated ids// differ from optimistic client ids; this can cause a small post-run flicker.setMessages(storedMessages);@@ -354,42 +404,72 @@ function InAppAiAgentProviderInner({};}, [resetAgent]);- const ensureSubscription = useCallback((agent: HttpAgent) => {- if (subscriptionRef.current) {- return;- }+ const ensureSubscription = useCallback(+ (agent: HttpAgent) => {+ if (subscriptionRef.current) {+ return;+ }- subscriptionRef.current = agent.subscribe({- onRunStartedEvent: ({ event }) => {- activeRunIdRef.current = event.runId;- },- onRunErrorEvent: ({ event }) => {- if (intentionalAbortRef.current) {- return;- }+ subscriptionRef.current = agent.subscribe({+ onRunStartedEvent: ({ event }) => {+ activeRunIdRef.current = event.runId;+ },+ onCustomEvent: ({ event }) => {+ const approvalRequest = parseInAppAgentInterruptEvent(event);- const errorMessage = getAgentErrorMessage(event);- setError(errorMessage);- console.error("In-app agent drawer run error", event);- },- onMessagesChanged: ({ messages }) => {- setMessages(- attachActiveRunIdToAssistantMessages(- messages.filter(isAgentConversationMessage),- activeRunIdRef.current,- ),- );- },- onStateChanged: ({ messages }) => {- setMessages(- attachActiveRunIdToAssistantMessages(- messages.filter(isAgentConversationMessage),- activeRunIdRef.current,- ),- );- },- });- }, []);+ if (!approvalRequest) {+ return;+ }++ const approval: InAppAgentPendingToolApproval = {+ id: approvalRequest.toolCallId,+ approvalRequest,+ status: "pending",+ };++ updatePendingToolApprovals((currentApprovals) => {+ const existingIndex = currentApprovals.findIndex(+ (currentApproval) => currentApproval.id === approval.id,+ );++ if (existingIndex === -1) {+ return [...currentApprovals, approval];+ }++ const nextApprovals = [...currentApprovals];+ nextApprovals[existingIndex] = approval;+ return nextApprovals;+ });+ },+ onRunErrorEvent: ({ event }) => {+ if (intentionalAbortRef.current) {+ return;+ }++ const errorMessage = getAgentErrorMessage(event);+ setError(errorMessage);+ console.error("In-app agent drawer run error", event);+ },+ onMessagesChanged: ({ messages }) => {+ setMessages(+ attachActiveRunIdToAssistantMessages(+ messages.filter(isAgentConversationMessage),+ activeRunIdRef.current,+ ),+ );+ },+ onStateChanged: ({ messages }) => {+ setMessages(+ attachActiveRunIdToAssistantMessages(+ messages.filter(isAgentConversationMessage),+ activeRunIdRef.current,+ ),+ );+ },+ });+ },+ [updatePendingToolApprovals],+ );const getOrCreateAgent = useCallback((@@ -427,14 +507,18 @@ function InAppAiAgentProviderInner({}, []);const runAgent = useCallback(- (agent: HttpAgent, conversationId: string) => {+ (+ agent: HttpAgent,+ conversationId: string,+ runParameters?: Parameters<HttpAgent["runAgent"]>[0],+ ) => {setIsRunning(true);- agent+ return agent.runAgent({- context: [- ...createInAppAgentScreenContext({- currentUrl: window.location.href,- }),+ ...runParameters,+ context: createInAppAgentScreenContext({+ currentUrl: window.location.href,+ }).concat(...createInAppAgentUserContext({userName: session.data?.user?.name,timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,@@ -443,16 +527,22 @@ function InAppAiAgentProviderInner({? Array.from(navigator.languages): [navigator.language],}),- ],+ ),})+ .then(() => true).catch((error) => {if (intentionalAbortRef.current) {- return;+ return false;+ }++ if (runParameters?.forwardedProps?.command?.resume) {+ throw error;}const errorMessage = getAgentErrorMessage(error);setError(errorMessage);console.error("In-app agent drawer error", error);+ return false;}).finally(() => {const runId = activeRunIdRef.current;@@ -700,6 +790,108 @@ function InAppAiAgentProviderInner({}}, [open]);+ const resumeToolApproval = useCallback(+ async (approvalId: string, approved: boolean) => {+ const approval = pendingToolApprovals.find(+ (approval) => approval.id === approvalId,+ );++ if (!approval || !selectedConversationId || isRunning) {+ return;+ }++ const agent = agentRef.current;+ if (!agent || agent.threadId !== selectedConversationId) {+ showErrorToast(+ "Failed to resume tool call",+ "The interrupted assistant run is no longer available.",+ );+ return;+ }++ updatePendingToolApprovals((currentApprovals) =>+ currentApprovals.map((currentApproval) =>+ currentApproval.id === approvalId+ ? { ...currentApproval, status: "submitting" }+ : currentApproval,+ ),+ );+ setError(null);++ try {+ ensureSubscription(agent);+ const completed = await runAgent(agent, selectedConversationId, {+ runId: createInAppAgentRunId(),+ forwardedProps: {+ command: {+ resume: {+ approved,+ approvalRequest: approval.approvalRequest,+ },+ },+ },+ });++ if (!completed) {+ updatePendingToolApprovals((currentApprovals) =>+ currentApprovals.map((currentApproval) =>+ currentApproval.id === approvalId+ ? { ...currentApproval, status: "pending" }+ : currentApproval,+ ),+ );+ return;+ }++ updatePendingToolApprovals((currentApprovals) =>+ currentApprovals.filter(+ (currentApproval) => currentApproval.id !== approvalId,+ ),+ );+ } catch (error) {+ const errorMessage = getAgentErrorMessage(error);+ if (errorMessage === "Invalid forwarded props") {+ updatePendingToolApprovals((currentApprovals) =>+ currentApprovals.filter(+ (currentApproval) => currentApproval.id !== approvalId,+ ),+ );+ setError("This tool approval is no longer valid. Please try again.");+ console.error("Failed to resume in-app agent tool call", error);+ return;+ }++ updatePendingToolApprovals((currentApprovals) =>+ currentApprovals.map((currentApproval) =>+ currentApproval.id === approvalId+ ? { ...currentApproval, status: "pending" }+ : currentApproval,+ ),+ );+ setError(errorMessage);+ console.error("Failed to resume in-app agent tool call", error);+ }+ },+ [+ ensureSubscription,+ isRunning,+ pendingToolApprovals,+ runAgent,+ selectedConversationId,+ updatePendingToolApprovals,+ ],+ );++ const approveToolCall = useCallback(+ (approvalId: string) => resumeToolApproval(approvalId, true),+ [resumeToolApproval],+ );++ const rejectToolCall = useCallback(+ (approvalId: string) => resumeToolApproval(approvalId, false),+ [resumeToolApproval],+ );+const value = useMemo<InAppAiAgentContextType>(() => ({isAvailable: true,@@ -709,6 +901,7 @@ function InAppAiAgentProviderInner({setIsExpanded,isRunning,isSubmitting,+ pendingToolApprovals,isSelectedConversationHydrating,error,messages: messagesWithFeedback,@@ -720,9 +913,12 @@ function InAppAiAgentProviderInner({selectConversation,deleteConversation,submit,+ approveToolCall,+ rejectToolCall,submitFeedback,}),[+ approveToolCall,isExpanded,conversations,error,@@ -735,6 +931,8 @@ function InAppAiAgentProviderInner({loadMoreConversations,messagesWithFeedback,open,+ pendingToolApprovals,+ rejectToolCall,selectConversation,selectedConversationId,setOpen,@@ -808,6 +1006,40 @@ function attachActiveRunIdToAssistantMessages(});}+function parseInAppAgentInterruptEvent(event: unknown) {+ if (!event || typeof event !== "object") {+ return null;+ }++ if (!("name" in event) || event.name !== "on_interrupt") {+ return null;+ }++ const value = "value" in event ? event.value : undefined;+ const parsedValue = typeof value === "string" ? parseJson(value) : value;+ const interrupt = MastraSuspendEventSchema.safeParse(parsedValue);++ if (!interrupt.success) {+ return null;+ }++ return {+ type: "tool_approval_request" as const,+ toolCallId: interrupt.data.toolCallId,+ toolName: interrupt.data.toolName,+ args: interrupt.data.args,+ runId: interrupt.data.runId,+ } satisfies InAppAgentToolApprovalRequest;+}++function parseJson(value: string) {+ try {+ return JSON.parse(value) as unknown;+ } catch {+ return null;+ }+}+function getInAppAgentUrl() {return `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/in-app-agent`;}diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.tsindex 4a36b5e90a..57231d81ca 100644--- a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts+++ b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts@@ -222,4 +222,287 @@ describe("getDrawerMessages", () => {expect(mappedMessages[1]?.content).not.toHaveProperty("sources");});++ it("adds pending tool approvals as approval tool groups", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: false,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Create a dataset",+ },+ ] satisfies AgUiMessage[],+ pendingToolApprovals: [+ {+ id: "tool-call-1",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_upsertDataset",+ args: { name: "regression-examples" },+ runId: "run-1",+ },+ status: "pending",+ },+ ],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ content: { type: "text" },+ },+ {+ id: "tool-approval-tool-call-1",+ role: "assistant",+ content: {+ type: "toolGroup",+ tools: [+ {+ type: "tool",+ name: "langfuse_upsertDataset",+ args: JSON.stringify({ name: "regression-examples" }),+ approval: {+ id: "tool-call-1",+ status: "pending",+ },+ },+ ],+ },+ },+ ]);+ });++ it("attaches pending approvals to matching persisted tool calls", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: false,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Create a dataset",+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "langfuse_upsertDataset",+ arguments: JSON.stringify({ name: "regression-examples" }),+ },+ },+ ],+ },+ ] satisfies AgUiMessage[],+ pendingToolApprovals: [+ {+ id: "tool-call-1",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_upsertDataset",+ args: { name: "regression-examples" },+ runId: "run-1",+ },+ status: "pending",+ },+ ],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ content: { type: "text" },+ },+ {+ id: "tools-assistant-1",+ role: "assistant",+ content: {+ type: "toolGroup",+ tools: [+ {+ type: "tool",+ name: "langfuse_upsertDataset",+ args: JSON.stringify({ name: "regression-examples" }),+ approval: {+ id: "tool-call-1",+ status: "pending",+ },+ },+ ],+ },+ },+ ]);+ expect(+ mappedMessages.some(+ (message) => message.id === "tool-approval-tool-call-1",+ ),+ ).toBe(false);+ });++ it("does not show a stale pending approval for an errored tool result", () => {+ const toolError =+ "MCP error -32602: Validation failed: categories: Category must be an array of objects with label value pairs, where labels and values are unique.";+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: true,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Create a score config",+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "langfuse_createScoreConfig",+ arguments: JSON.stringify({+ name: "readiness",+ categories: ["invalid"],+ }),+ },+ },+ ],+ },+ {+ id: "tool-call-1-approval-tool-result",+ role: "tool",+ toolCallId: "tool-call-1",+ content: toolError,+ error: toolError,+ },+ ] satisfies AgUiMessage[],+ pendingToolApprovals: [+ {+ id: "tool-call-1",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_createScoreConfig",+ args: {+ name: "readiness",+ categories: ["invalid"],+ },+ runId: "run-1",+ },+ status: "pending",+ },+ ],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ content: { type: "text" },+ },+ {+ id: "tools-assistant-1",+ role: "assistant",+ content: {+ type: "toolGroup",+ isLoading: true,+ tools: [+ {+ type: "tool",+ name: "langfuse_createScoreConfig",+ args: JSON.stringify({+ name: "readiness",+ categories: ["invalid"],+ }),+ result: toolError,+ error: toolError,+ },+ ],+ },+ },+ ]);+ expect(mappedMessages).toHaveLength(2);+ expect(+ mappedMessages.some(+ (message) => message.id === "tool-approval-tool-call-1",+ ),+ ).toBe(false);++ const toolGroup = mappedMessages[1];+ expect(toolGroup?.content.type).toBe("toolGroup");+ if (toolGroup?.content.type === "toolGroup") {+ expect(toolGroup.content.tools[0]).not.toHaveProperty("approval");+ }+ });++ it("does not show a stale pending approval for a completed tool result", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: false,+ messages: [+ {+ id: "assistant-1",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "langfuse_upsertDataset",+ arguments: JSON.stringify({ name: "regression-examples" }),+ },+ },+ ],+ },+ {+ id: "tool-result-1",+ role: "tool",+ toolCallId: "tool-call-1",+ content: JSON.stringify({ id: "dataset-1" }),+ },+ ] satisfies AgUiMessage[],+ pendingToolApprovals: [+ {+ id: "tool-call-1",+ approvalRequest: {+ type: "tool_approval_request",+ toolCallId: "tool-call-1",+ toolName: "langfuse_upsertDataset",+ args: { name: "regression-examples" },+ runId: "run-1",+ },+ status: "pending",+ },+ ],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "tools-assistant-1",+ content: {+ type: "toolGroup",+ tools: [+ {+ result: JSON.stringify({ id: "dataset-1" }),+ },+ ],+ },+ },+ ]);+ expect(mappedMessages).toHaveLength(1);+ const toolGroup = mappedMessages[0];+ expect(toolGroup?.content.type).toBe("toolGroup");+ if (toolGroup?.content.type === "toolGroup") {+ expect(toolGroup.content.tools[0]).not.toHaveProperty("approval");+ }+ });});diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.ts b/web/src/ee/features/in-app-agent/components/utils/utils.tsindex 9836fc8a12..6c0800ee65 100644--- a/web/src/ee/features/in-app-agent/components/utils/utils.ts+++ b/web/src/ee/features/in-app-agent/components/utils/utils.ts@@ -1,10 +1,9 @@import { z } from "zod";import type { InAppAgentWindowMessage } from "../InAppAgentWindow";-import type {- InAppAgentMessageContent,- InAppAgentToolCallContent,-} from "../InAppAgentMessage";+import type { InAppAgentPendingToolApproval } from "../InAppAiAgentProvider";+import type { InAppAgentMessageContent } from "../InAppAgentMessage";import { deduplicateBy } from "@/src/utils/arrays";+import { stableJsonStringify } from "@/src/utils/json";import {AgUiMessageSchema,type AgUiMessage,@@ -14,6 +13,18 @@ import {} from "@/src/ee/features/in-app-agent/schema";import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";+export type InAppAgentToolCallContent = {+ type: "tool";+ name: string;+ args: string;+ result?: string;+ error?: string;+ approval?: {+ id: string;+ status: "pending" | "submitting";+ };+};+const LangfuseDocsDocumentSchema = z.object({type: z.literal("document"),title: z.string().trim().optional(),@@ -69,13 +80,20 @@ export function getDrawerMessages({error,isRunning,messages,+ pendingToolApprovals = [],}: {error: unknown;isRunning: boolean;messages: unknown;+ pendingToolApprovals?: readonly InAppAgentPendingToolApproval[];}): InAppAgentWindowMessage[] {const parsedMessages = z.array(AgUiMessageSchema).parse(messages);const toolResults = getToolResultsByToolCallId(parsedMessages);+ const resolvedToolCallIds = new Set(toolResults.keys());+ const pendingApprovalsByToolCallId = new Map(+ pendingToolApprovals.map((approval) => [approval.id, approval]),+ );+ const mappedPendingApprovalIds = new Set<string>();const mappedMessages: InAppAgentWindowMessage[] = [];let pendingTools: InAppAgentToolCallContent[] = [];@@ -180,12 +198,32 @@ export function getDrawerMessages({}const result = toolResults.get(toolCall.id);+ const pendingApproval = result+ ? undefined+ : findPendingApprovalForToolCall({+ toolCall,+ pendingApprovals: pendingToolApprovals,+ pendingApprovalsByToolCallId,+ mappedPendingApprovalIds,+ });++ if (pendingApproval) {+ mappedPendingApprovalIds.add(pendingApproval.id);+ }return [{type: "tool",name: toolCall.function.name,args: toolCall.function.arguments,+ ...(pendingApproval+ ? {+ approval: {+ id: pendingApproval.id,+ status: pendingApproval.status,+ },+ }+ : {}),...(result?.content !== undefined? { result: result.content }: {}),@@ -258,6 +296,35 @@ export function getDrawerMessages({flushPendingTools();+ for (const approval of pendingToolApprovals) {+ if (+ mappedPendingApprovalIds.has(approval.id) ||+ resolvedToolCallIds.has(approval.id) ||+ resolvedToolCallIds.has(approval.approvalRequest.toolCallId)+ ) {+ continue;+ }++ mappedMessages.push({+ id: `tool-approval-${approval.id}`,+ role: "assistant",+ content: {+ type: "toolGroup",+ tools: [+ {+ type: "tool",+ name: approval.approvalRequest.toolName,+ args: stringifyToolArgs(approval.approvalRequest.args),+ approval: {+ id: approval.id,+ status: approval.status,+ },+ },+ ],+ },+ });+ }+const latestUserMessageIndex = mappedMessages.findLastIndex((message) => message.role === "user",);@@ -307,6 +374,56 @@ export function getDrawerMessages({return mappedMessages;}+function stringifyToolArgs(args: unknown) {+ if (typeof args === "string") {+ return args;+ }++ try {+ return JSON.stringify(args ?? {});+ } catch {+ return "{}";+ }+}++function findPendingApprovalForToolCall({+ toolCall,+ pendingApprovals,+ pendingApprovalsByToolCallId,+ mappedPendingApprovalIds,+}: {+ toolCall: Extract<AgUiMessage, { role: "assistant" }>["toolCalls"] extends+ | Array<infer TToolCall>+ | undefined+ ? TToolCall+ : never;+ pendingApprovals: readonly InAppAgentPendingToolApproval[];+ pendingApprovalsByToolCallId: ReadonlyMap<+ string,+ InAppAgentPendingToolApproval+ >;+ mappedPendingApprovalIds: ReadonlySet<string>;+}) {+ const exactMatch = pendingApprovalsByToolCallId.get(toolCall.id);++ if (exactMatch) {+ return exactMatch;+ }++ const toolArgsFingerprint = stableJsonStringify(+ parseJsonString(toolCall.function.arguments) ?? toolCall.function.arguments,+ );+ const matchingApprovals = pendingApprovals.filter(+ (approval) =>+ !mappedPendingApprovalIds.has(approval.id) &&+ approval.approvalRequest.toolName === toolCall.function.name &&+ stableJsonStringify(approval.approvalRequest.args) ===+ toolArgsFingerprint,+ );++ return matchingApprovals.length === 1 ? matchingApprovals[0] : undefined;+}+function getToolResultsByToolCallId(messages: readonly AgUiMessage[]) {const results = new Map<string, Extract<AgUiMessage, { role: "tool" }>>();diff --git a/web/src/ee/features/in-app-agent/constants.ts b/web/src/ee/features/in-app-agent/constants.tsindex 03bc3be9d7..06b70100ff 100644--- a/web/src/ee/features/in-app-agent/constants.ts+++ b/web/src/ee/features/in-app-agent/constants.ts@@ -1,2 +1,7 @@// Avoid renaming this as the FE is aware of this when rendering, renaming it would cause history issuesexport const IN_APP_AGENT_REDIRECT_TOOL_NAME = "langfuse_proposeRedirect";++// Header used only by Langfuse's server-side in-app agent when it calls the+// Langfuse MCP endpoint with a temporary in-app-agent API key and run override.+export const IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER =+ "x-langfuse-in-app-agent-tool-override";diff --git a/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt b/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txtindex 0afefe4ac7..5f0a2dacfb 100644--- a/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt+++ b/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt@@ -36,10 +36,8 @@ Only include them if the user explicitly asks for internal or Langfuse-managed e</data_scope><permissions>-Currently, you only have read access to user's project. All your tools enforce this restriction so no need to worry about it.-If the user asks you to perform an action, you have two options:-- Explain to the user how they can perform the action themselves in the UI (use the docs for this if needed).-- If the action is available via the CLI, suggest that the user can ask their own agent (Claude, Codex or similar) to perform the action for them using the CLI, for that they should use the Langfuse skill: https://github.com/langfuse/skills. When suggesting this, provide a prompt the user can use as a code block.+Some tools can change the user's project. The product will ask the user for explicit confirmation before running actions that require approval.+Do not claim that a tool action succeeded until the tool result confirms it. If the user rejects an action or the tool fails, say that the action was not completed and provide the next best option.</permissions><user_navigation>diff --git a/web/src/ee/features/in-app-agent/schema.ts b/web/src/ee/features/in-app-agent/schema.tsindex 5b4ebd1a05..9295217baa 100644--- a/web/src/ee/features/in-app-agent/schema.ts+++ b/web/src/ee/features/in-app-agent/schema.ts@@ -218,6 +218,29 @@ export type AgUiCustomEvent = AgUiEvent & {value: unknown;};+export const InAppAgentToolApprovalRequestSchema = z.object({+ type: z.literal("tool_approval_request"),+ toolCallId: z.string().min(1),+ toolName: z.string().min(1),+ args: z.unknown().optional(),+ runId: z.string().min(1),+});++export type InAppAgentToolApprovalRequest = z.infer<+ typeof InAppAgentToolApprovalRequestSchema+>;++export const ResumeForwardedPropsSchema = z.object({+ command: z.object({+ resume: z.object({+ approved: z.boolean(),+ approvalRequest: InAppAgentToolApprovalRequestSchema,+ }),+ }),+});++export type ResumeForwardedProps = z.infer<typeof ResumeForwardedPropsSchema>;+export const InAppAgentRuntimeStateSchema = z.discriminatedUnion("type", [z.object({type: z.literal("newConversation"),diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.tsindex 760c743117..f586bfd78e 100644--- a/web/src/ee/features/in-app-agent/server/agent.ts+++ b/web/src/ee/features/in-app-agent/server/agent.ts@@ -12,16 +12,28 @@ import type { Langfuse } from "langfuse";import {type AgUiEvent,type AgUiRunAgentInput,+ type InAppAgentToolApprovalRequest,+ type ResumeForwardedProps,} from "@/src/ee/features/in-app-agent/schema";+import {+ createManualToolApprovalRunInput,+ type ManualToolApprovalRunInput,+} from "@/src/ee/features/in-app-agent/server/human-in-the-loop";import type {InAppAgentPromptMetadata,InAppAgentTracingConfig,} from "@/src/ee/features/in-app-agent/server/instrumentation";import { createInAppAgentInstrumentation } from "@/src/ee/features/in-app-agent/server/instrumentation";-import { createRedirectActionTool } from "@/src/ee/features/in-app-agent/server/tools";+import {+ createRedirectActionTool,+ filterInAppAgentAvailableLangfuseMcpTools,+ type InAppAgentUserAccess,+ withInAppAgentToolApproval,+} from "@/src/ee/features/in-app-agent/server/tools";import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@/src/features/filters/constants/internal-environments";import { logger } from "@langfuse/shared/src/server";import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";+import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@/src/ee/features/in-app-agent/constants";const ASSISTANT_TITLE = "Langfuse Assistant";const IN_APP_AGENT_SYSTEM_PROMPT_NAME = "in-app-agent-system-prompt";@@ -32,6 +44,9 @@ const LOCAL_IN_APP_AGENT_SYSTEM_PROMPT_DIR = path.join(const MAX_AGENT_STEPS = 10;const LANGFUSE_DOCS_MCP_URL = "https://langfuse.com/api/mcp";+// Screen context is included as data only. Tool execution safety is enforced by+// deterministic in-app tool approval below, not by model instructions.+// TODO: LFE-10246function serializeContext(context: AgUiRunAgentInput["context"],keys?: string[],@@ -101,6 +116,7 @@ ${serializedContext}type CreateAgUiStreamOptions = {onEvent?: (event: AgUiEvent) => void | Promise<void>;+ onApprovedToolCallExecuted?: () => void | Promise<void>;onComplete?: () => void | Promise<void>;onAbort?: () => void | Promise<void>;onError?: (error: unknown) => void | Promise<void>;@@ -114,6 +130,8 @@ type CreateAgUiStreamOptions = {url: string;publicKey: string;secretKey: string;+ userAccess: InAppAgentUserAccess;+ runOverride?: string;};redirectAction: {projectId: string;@@ -289,6 +307,26 @@ export async function createAgUiStream(params: {return params.options.onError?.(new Error(streamedRunError));};+ const completeManualToolApprovalRun = (+ runInput: ManualToolApprovalRunInput,+ ) => {+ const terminalEvents = [+ createRunStartedEvent(params.input),+ ...runInput.syntheticEvents,+ ];++ instrumentation?.recordEvents(terminalEvents);+ for (const syntheticEvent of terminalEvents) {+ enqueueEvent(syntheticEvent);+ }++ closeController(() => {+ instrumentation?.end({});+ instrumentation?.flush();+ return params.options.onComplete?.();+ });+ };+const closeController = (terminalCallback?: () => void | Promise<void>,) => {@@ -365,6 +403,36 @@ export async function createAgUiStream(params: {params.signal.addEventListener("abort", abortHandler, { once: true });+ const forwardedProps = params.input.forwardedProps as+ | ResumeForwardedProps+ | undefined;++ if (forwardedProps?.command?.resume?.approved === false) {+ createManualToolApprovalRunInput({+ input: params.input,+ executeToolCall: async () => {+ throw new Error("Rejected tool approvals must not execute tools.");+ },+ })+ .then((runInput) => {+ if (ending || closed || params.signal.aborted) {+ abortStream();+ return;+ }++ completeManualToolApprovalRun(runInput);+ })+ .catch((error) => {+ if (ending || closed) {+ return;+ }++ failStream(error);+ });++ return;+ }+createMastraAdapter({input: params.input,signal: params.signal,@@ -375,10 +443,10 @@ export async function createAgUiStream(params: {onToolsAvailable: (tools) =>instrumentation?.recordAvailableTools(tools),})- .then(({ adapter, cleanup, interrupt }) => {+ .then(async (initialAdapter) => {if (ending || closed || params.signal.aborted) {- interrupt();- cleanup().catch((error) => {+ initialAdapter.interrupt();+ initialAdapter.cleanup().catch((error) => {logger.error("Error in agent stream cleanup", {error,runId: params.input.runId,@@ -389,10 +457,67 @@ export async function createAgUiStream(params: {return;}- cleanupAdapter = cleanup;- interruptAdapter = interrupt;+ let currentAdapter = initialAdapter;+ cleanupAdapter = currentAdapter.cleanup;+ interruptAdapter = currentAdapter.interrupt;++ const runInput = await createManualToolApprovalRunInput({+ input: params.input,+ executeToolCall: currentAdapter.executeToolCall,+ onApprovedToolCallExecuted:+ params.options.onApprovedToolCallExecuted,+ });+ const pendingSyntheticEvents = [...runInput.syntheticEvents];++ if (!runInput.shouldContinue) {+ completeManualToolApprovalRun(runInput);+ return;+ }++ if (+ forwardedProps?.command?.resume?.approved === true &&+ params.options.langfuseMcp.runOverride+ ) {+ // The override is intentionally single-use: execute the approved+ // mutating MCP tool with the first client, then rebuild the MCP+ // client without the override so the continuation returns to the+ // normal read-only in-app-agent policy.++ await currentAdapter.cleanup();++ currentAdapter = await createMastraAdapter({+ input: params.input,+ signal: params.signal,+ langfuseMcpAuthHeader,+ options: {+ ...params.options,+ langfuseMcp: {+ ...params.options.langfuseMcp,+ runOverride: undefined,+ },+ },+ awsProfile,+ instructions,+ });++ if (ending || closed || params.signal.aborted) {+ currentAdapter.interrupt();+ currentAdapter.cleanup().catch((error) => {+ logger.error("Error in agent stream cleanup", {+ error,+ runId: params.input.runId,+ threadId: params.input.threadId,+ });+ });+ abortStream();+ return;+ }++ cleanupAdapter = currentAdapter.cleanup;+ interruptAdapter = currentAdapter.interrupt;+ }- subscription = adapter.run(params.input).subscribe({+ subscription = currentAdapter.adapter.run(runInput.input).subscribe({next(event) {if (ending || closed) {return;@@ -424,6 +549,17 @@ export async function createAgUiStream(params: {? handleStreamedRunError: undefined,);++ if (+ agUiEvent.type === EventType.RUN_STARTED &&+ pendingSyntheticEvents.length > 0+ ) {+ instrumentation?.recordEvents(pendingSyntheticEvents);+ for (const syntheticEvent of pendingSyntheticEvents) {+ enqueueEvent(syntheticEvent);+ }+ pendingSyntheticEvents.length = 0;+ }}},error(error) {@@ -539,6 +675,11 @@ export async function createAgUiStream(params: {});}+type ExecutableInAppAgentTool = {+ execute?: (inputData: unknown, context: unknown) => Promise<unknown>;+ toModelOutput?: (output: unknown) => unknown;+};+async function createMastraAdapter(params: {input: AgUiRunAgentInput;signal: AbortSignal;@@ -565,6 +706,12 @@ async function createMastraAdapter(params: {requestInit: {headers: {Authorization: params.langfuseMcpAuthHeader,+ ...(params.options.langfuseMcp.runOverride+ ? {+ [IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER]:+ params.options.langfuseMcp.runOverride,+ }+ : {}),},},},@@ -593,14 +740,20 @@ async function createMastraAdapter(params: {// agent.stream(..., { toolsets }) call. Keep Mastra's per-request MCP// discovery, then prefix tool names for constructor-based tools so the// model sees the same names that later appear in AG-UI tool-call events.- const tools = {- ...prefixToolsetTools("langfuse", toolsets.langfuse),+ const tools = withInAppAgentToolApproval({+ ...prefixToolsetTools(+ "langfuse",+ filterInAppAgentAvailableLangfuseMcpTools({+ tools: toolsets.langfuse,+ userAccess: params.options.langfuseMcp.userAccess,+ }),+ ),...prefixToolsetTools("langfuseDocs", toolsets.langfuseDocs),[IN_APP_AGENT_REDIRECT_TOOL_NAME]: createRedirectActionTool({projectId: params.options.redirectAction.projectId,isV4Enabled: params.options.redirectAction.isV4Enabled,}),- };+ });params.onToolsAvailable?.(tools);const agent = new Agent({@@ -627,6 +780,37 @@ async function createMastraAdapter(params: {return {adapter,+ executeToolCall: async (+ approvalRequest: InAppAgentToolApprovalRequest,+ ) => {+ const tool = tools[approvalRequest.toolName] as+ | ExecutableInAppAgentTool+ | undefined;++ if (!tool?.execute) {+ throw new Error(+ `Approved in-app agent tool is not executable: ${approvalRequest.toolName}`,+ );+ }++ const result = await tool.execute(approvalRequest.args ?? {}, {+ abortSignal: params.signal,+ observe: {+ span: async <T>(_: string, fn: () => Promise<T> | T) => fn(),+ log: () => undefined,+ },+ agent: {+ agentId: "langfuse-in-app-assistant",+ toolCallId: approvalRequest.toolCallId,+ messages: params.input.messages,+ threadId: params.input.threadId,+ resourceId: params.input.threadId,+ suspend: async () => undefined,+ },+ });++ return tool.toModelOutput ? tool.toModelOutput(result) : result;+ },interrupt: () => agent.abortRunStream(params.input.runId),cleanup: () => mcpClient.disconnect(),};@@ -676,6 +860,8 @@ type MastraStreamChunk = {toolName?: string;argsTextDelta?: string;args?: unknown;+ resumeSchema?: unknown;+ suspendPayload?: unknown;};};@@ -790,6 +976,37 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {}break;}+ case "tool-call-approval": {+ const { toolCallId, toolName, args, resumeSchema } =+ mastraChunk.payload ?? {};+ if (!toolCallId || !toolName) {+ callbacks.onError(+ new Error(+ "Malformed tool-call-approval: missing toolCallId or toolName in payload",+ ),+ );+ return true;+ }++ streamingToolCalls.delete(toolCallId);+ synthesizedToolCallIds.delete(toolCallId);++ return processor.handleChunk({+ type: "tool-call-suspended",+ payload: {+ toolCallId,+ toolName,+ args,+ resumeSchema,+ suspendPayload: {+ type: "approval",+ toolCallId,+ toolName,+ args,+ },+ },+ });+ }case "tool-call-suspended": {const { toolCallId } = mastraChunk.payload ?? {};if (toolCallId) {@@ -881,6 +1098,15 @@ function normalizeAdapterEvent(return [event];}+function createRunStartedEvent(input: AgUiRunAgentInput): AgUiEvent {+ return {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ ...(input.parentRunId ? { parentRunId: input.parentRunId } : {}),+ };+}+function createRunErrorEvent(input: AgUiRunAgentInput,error: unknown,diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex b444ee5fe2..97df450837 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -14,8 +14,22 @@ import {type AgUiEvent,InAppAgentRuntimeStateSchema,type AgUiMessage,+ ResumeForwardedPropsSchema,+ type ResumeForwardedProps,} from "@/src/ee/features/in-app-agent/schema";import { createAgUiStream } from "@/src/ee/features/in-app-agent/server/agent";+import {+ consumeAndValidatePendingToolApproval,+ createInAppAgentMcpRunOverride,+ parseInAppAgentInterruptEvent,+ storePendingToolApproval,+ validatePendingToolApproval,+} from "@/src/ee/features/in-app-agent/server/human-in-the-loop";+import {+ isMcpToolName,+ type InAppAgentUserAccess,+} from "@/src/ee/features/in-app-agent/server/tools";+import type { McpToolName } from "@/src/features/mcp/server/bootstrap";import {createRun,ensureOwnedConversation,@@ -66,7 +80,8 @@ export default async function handler(request: Request) {throw new UnauthorizedError("Unauthenticated");}- const userId = session.user.id;+ const user = session.user;+ const userId = user.id;if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {throw new BaseError(@@ -112,8 +127,6 @@ export default async function handler(request: Request) {throw new InvalidRequestError("Invalid agent state");}- const auth = { userId: session.user.id, user: session.user };-const { projectId, conversationId } = (() => {if (parsedState.data.type === "newConversation") {return {@@ -132,14 +145,14 @@ export default async function handler(request: Request) {};})();- if (!isProjectMemberOrAdmin(auth.user, projectId)) {+ if (!isProjectMemberOrAdmin(user, projectId)) {throw new ForbiddenError("User is not a member of this project");}if (!hasEntitlement({entitlement: "in-app-agent",- sessionUser: auth.user,+ sessionUser: user,projectId,})) {@@ -206,7 +219,7 @@ export default async function handler(request: Request) {// TODO: Add an additional user-level cap once the rate-limit service supports non-org keys.const rateLimitScope = getInAppAgentRateLimitScope(- auth.user,+ user,projectId,project.organization,);@@ -224,8 +237,17 @@ export default async function handler(request: Request) {prisma,projectId,conversationId,- userId: auth.userId,+ userId: userId,});++ if (isResumeAgentInput(sanitizedInput)) {+ await validatePendingToolApproval({+ projectId,+ conversationId: conversation.id,+ forwardedProps: sanitizedInput.forwardedProps,+ });+ }+const conversationMessages = await getConversationMessagesForReplay({prisma,projectId,@@ -235,11 +257,39 @@ export default async function handler(request: Request) {sanitizedInput,conversationMessages,);+ const resumeApprovalRequest = isResumeAgentInput(sanitizedInput)+ ? sanitizedInput.forwardedProps.command.resume.approvalRequest+ : undefined;return await withInAppAgentMcpApiKeyCleanup(- projectId,- async (mcpApiKey, cleanupMcpApiKey) => {+ {+ projectId,+ runId: sanitizedInput.runId,+ toolName: getInAppAgentMcpRegistryToolName(+ resumeApprovalRequest?.toolName,+ ),+ },+ async (mcpApiKey, runOverride, cleanupMcpApiKey) => {let runCreated = false;+ let pendingToolApprovalConsumed = false;+ let streamCreated = false;+ let approvedToolResultPersisted = false;++ const restorePendingToolApprovalIfRetryable = () => {+ if (+ !pendingToolApprovalConsumed ||+ !resumeApprovalRequest ||+ approvedToolResultPersisted+ ) {+ return;+ }++ return storePendingToolApproval({+ projectId,+ conversationId: conversation.id,+ approvalRequest: resumeApprovalRequest,+ });+ };try {await createRun({@@ -276,6 +326,15 @@ export default async function handler(request: Request) {await replacePersistedRunEvents();+ if (isResumeAgentInput(sanitizedInput)) {+ await consumeAndValidatePendingToolApproval({+ projectId,+ conversationId: conversation.id,+ forwardedProps: sanitizedInput.forwardedProps,+ });+ pendingToolApprovalConsumed = true;+ }+const finishCurrentRun = (error?: {errorCode: string;errorMessage: string;@@ -291,7 +350,17 @@ export default async function handler(request: Request) {input: agentInput,signal: request.signal,options: {- onEvent: (event) => {+ onEvent: async (event) => {+ const approvalRequest = parseInAppAgentInterruptEvent(event);++ if (approvalRequest) {+ await storePendingToolApproval({+ projectId,+ conversationId: conversation.id,+ approvalRequest,+ });+ }+const persistedEvent = toPersistableAgentEvent(event);if (!persistedEvent) {@@ -302,6 +371,14 @@ export default async function handler(request: Request) {return;}+ if (+ persistedEvent.type === EventType.TOOL_CALL_RESULT &&+ persistedEvent.toolCallId ===+ resumeApprovalRequest?.toolCallId+ ) {+ approvedToolResultPersisted = true;+ }+persistedEvents.push(persistedEvent);if (!shouldFlushPersistedEvent(persistedEvent)) {@@ -310,25 +387,32 @@ export default async function handler(request: Request) {return replacePersistedRunEvents();},+ onApprovedToolCallExecuted: () => {+ approvedToolResultPersisted = true;+ },onComplete: () =>replacePersistedRunEvents().finally(() => finishCurrentRun()),onAbort: () =>- replacePersistedRunEvents().finally(() =>- finishCurrentRun({- errorCode: "cancelled",- errorMessage: "Client aborted request",- }),- ),+ replacePersistedRunEvents()+ .then(() => restorePendingToolApprovalIfRetryable())+ .finally(() =>+ finishCurrentRun({+ errorCode: "cancelled",+ errorMessage: "Client aborted request",+ }),+ ),onError: (error) =>- replacePersistedRunEvents().finally(() =>- finishCurrentRun({- errorCode: "agent_error",- errorMessage:- error instanceof Error- ? error.message- : "Unknown agent error",- }),- ),+ replacePersistedRunEvents()+ .then(() => restorePendingToolApprovalIfRetryable())+ .finally(() =>+ finishCurrentRun({+ errorCode: "agent_error",+ errorMessage:+ error instanceof Error+ ? error.message+ : "Unknown agent error",+ }),+ ),onFinish: cleanupMcpApiKey,awsBedrock: {region: env.LANGFUSE_AWS_BEDROCK_REGION,@@ -339,10 +423,12 @@ export default async function handler(request: Request) {url: getLangfuseMcpUrl(),publicKey: mcpApiKey.publicKey,secretKey: mcpApiKey.secretKey,+ userAccess: getInAppAgentUserAccess(user, projectId),+ runOverride,},redirectAction: {projectId,- isV4Enabled: session.user?.v4BetaEnabled ?? false,+ isV4Enabled: user?.v4BetaEnabled ?? false,},langfuseClient,useLocalPrompt,@@ -352,13 +438,13 @@ export default async function handler(request: Request) {targetProjectId,environment: "langfuse-in-app-agent",user: {- id: auth.userId,- email: auth.user.email,+ id: userId,+ email: user.email,},traceId: conversation.id,metadata: {langfuse_ai_feature: "in-app-agent",- langfuse_user_id: auth.userId,+ langfuse_user_id: userId,langfuse_project_id: projectId,conversation_id: conversation.id,thread_id: sanitizedInput.threadId,@@ -373,6 +459,7 @@ export default async function handler(request: Request) {: undefined,},});+ streamCreated = true;return new Response(stream, {headers: {@@ -397,6 +484,10 @@ export default async function handler(request: Request) {});}+ if (!streamCreated) {+ await restorePendingToolApprovalIfRetryable();+ }+throw error;}},@@ -412,6 +503,20 @@ export default async function handler(request: Request) {type SessionUser = NonNullable<Session["user"]>;+function getInAppAgentUserAccess(+ user: SessionUser,+ projectId: string,+): InAppAgentUserAccess {+ const projectRole = user.organizations+ .flatMap((organization) => organization.projects)+ .find((project) => project.id === projectId)?.role;++ return {+ projectRole,+ isAdmin: user.admin === true,+ };+}+function getInAppAgentRateLimitScope(user: SessionUser,projectId: string,@@ -510,20 +615,23 @@ async function createInAppAgentMcpApiKey(projectId: string) {}async function withInAppAgentMcpApiKeyCleanup<T>(- projectId: string,+ params: { projectId: string; runId: string; toolName?: McpToolName },createResponse: (mcpApiKey: Awaited<ReturnType<typeof createInAppAgentMcpApiKey>>,+ runOverride: string | undefined,cleanupMcpApiKey: () => Promise<void>,) => T | Promise<T>,): Promise<T> {- const mcpApiKey = await createInAppAgentMcpApiKey(projectId);+ // Each run gets a temporary in-app-agent API key. Approved MCP resumes also+ // get a tool-scoped run override for the single mutating registry tool.+ const mcpApiKey = await createInAppAgentMcpApiKey(params.projectId);let cleanupPromise: Promise<void> | undefined;const cleanupMcpApiKey = () => {if (!cleanupPromise) {cleanupPromise = cleanupInAppAgentMcpApiKey({apiKeyId: mcpApiKey.id,- projectId,+ projectId: params.projectId,}).catch((cleanupErr) => {cleanupPromise = undefined;throw cleanupErr;@@ -534,7 +642,13 @@ async function withInAppAgentMcpApiKeyCleanup<T>(};try {- return await createResponse(mcpApiKey, cleanupMcpApiKey);+ const runOverride = params.toolName+ ? await createInAppAgentMcpRunOverride({+ toolName: params.toolName,+ })+ : undefined;++ return await createResponse(mcpApiKey, runOverride, cleanupMcpApiKey);} catch (err) {await cleanupMcpApiKey().catch((cleanupErr) => {logger.error("Failed to clean up in-app agent MCP API key", cleanupErr);@@ -543,6 +657,16 @@ async function withInAppAgentMcpApiKeyCleanup<T>(}}+function getInAppAgentMcpRegistryToolName(toolName: string | undefined) {+ if (!toolName?.startsWith("langfuse_")) {+ return undefined;+ }++ const registryToolName = toolName.slice("langfuse_".length);++ return isMcpToolName(registryToolName) ? registryToolName : undefined;+}+async function cleanupInAppAgentMcpApiKey(params: {apiKeyId: string;projectId: string;@@ -556,14 +680,62 @@ async function cleanupInAppAgentMcpApiKey(params: {});}-type SanitizedAgentInput = AgUiRunAgentInput & {- messages: [SanitizedUserMessage];-};+type SanitizedAgentInput = AgUiRunAgentInput &+ (+ | {+ messages: [SanitizedUserMessage];+ forwardedProps: Record<string, never>;+ }+ | {+ messages: [];+ forwardedProps: ResumeForwardedProps;+ }+ );++function isResumeAgentInput(+ input: SanitizedAgentInput,+): input is AgUiRunAgentInput & {+ messages: [];+ forwardedProps: ResumeForwardedProps;+} {+ return "command" in input.forwardedProps;+}function sanitizeAgentInput(input: AgUiRunAgentInput,projectId: string,): SanitizedAgentInput {+ const forwardedProps = input.forwardedProps;++ if (+ forwardedProps !== undefined &&+ (forwardedProps === null ||+ typeof forwardedProps !== "object" ||+ Array.isArray(forwardedProps))+ ) {+ throw new InvalidRequestError("Invalid forwarded props");+ }++ if (forwardedProps && "command" in forwardedProps) {+ const resumeForwardedProps =+ ResumeForwardedPropsSchema.safeParse(forwardedProps);++ if (!resumeForwardedProps.success) {+ throw new InvalidRequestError("Invalid forwarded props");+ }++ return {+ threadId: input.threadId,+ runId: createInAppAgentRunId(),+ ...(input.parentRunId ? { parentRunId: input.parentRunId } : {}),+ state: null,+ messages: [],+ tools: [],+ context: sanitizeInAppAgentContext(input.context, projectId),+ forwardedProps: resumeForwardedProps.data,+ };+ }+const lastUserMessage = getLastUserMessage(input.messages);if (!lastUserMessage) {diff --git a/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts b/web/src/ee/features/in-app-agent/server/human-in-the-loop.tsnew file mode 100644index 0000000000..09989b2fd0--- /dev/null+++ b/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts@@ -0,0 +1,390 @@+import { EventType } from "@ag-ui/core";+import { z } from "zod";++import { InvalidRequestError } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import type { McpToolName } from "@/src/features/mcp/server/bootstrap";+import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES } from "@/src/ee/features/in-app-agent/server/tools";+import { safeJsonParse, stableJsonStringify } from "@/src/utils/json";+import {+ type AgUiEvent,+ type AgUiMessage,+ type AgUiRunAgentInput,+ type InAppAgentToolApprovalRequest,+ type ResumeForwardedProps,+} from "@/src/ee/features/in-app-agent/schema";++export const IN_APP_AGENT_PENDING_TOOL_APPROVAL_TTL_SECONDS = 60 * 60;+const MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE =+ "Tool call was not approved by the user.";++const PendingToolApprovalSchema = z.object({+ toolCallId: z.string().min(1),+ toolName: z.string().min(1),+ runId: z.string().min(1),+ argsFingerprint: z.string(),+});++const McpToolNameSchema = z.custom<McpToolName>(+ (value) =>+ typeof value === "string" &&+ IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES.has(value as McpToolName),+ { message: "Invalid MCP tool name" },+);++export const InAppAgentMcpRunOverrideSchema = z.object({+ toolName: McpToolNameSchema,+});++const MastraSuspendEventSchema = z.object({+ type: z.literal("mastra_suspend"),+ toolCallId: z.string().min(1),+ toolName: z.string().min(1),+ args: z.unknown().optional(),+ runId: z.string().min(1),+});++export async function storePendingToolApproval(params: {+ projectId: string;+ conversationId: string;+ approvalRequest: InAppAgentToolApprovalRequest;+}) {+ const approvalFingerprint = createPendingToolApprovalFingerprint(+ params.approvalRequest,+ );+ const expiresAt = new Date(+ Date.now() + IN_APP_AGENT_PENDING_TOOL_APPROVAL_TTL_SECONDS * 1000,+ );++ await prisma.inAppAgentPendingToolApproval.upsert({+ where: {+ projectId_conversationId_toolCallId: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ toolCallId: params.approvalRequest.toolCallId,+ },+ },+ create: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ toolCallId: params.approvalRequest.toolCallId,+ approvalFingerprint,+ expiresAt,+ },+ update: {+ approvalFingerprint,+ expiresAt,+ },+ });+}++// Check early, before stream setup, so malformed or forged resume payloads fail+// without starting another model/tool execution attempt.+export async function validatePendingToolApproval(params: {+ projectId: string;+ conversationId: string;+ forwardedProps: ResumeForwardedProps;+}) {+ const approvalRequest = params.forwardedProps.command.resume.approvalRequest;+ const pendingApproval = await prisma.inAppAgentPendingToolApproval.findFirst({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ toolCallId: approvalRequest.toolCallId,+ approvalFingerprint:+ createPendingToolApprovalFingerprint(approvalRequest),+ expiresAt: { gt: new Date() },+ },+ select: { toolCallId: true },+ });++ if (!pendingApproval) {+ throw new InvalidRequestError("Invalid forwarded props");+ }+}++// Atomically consume before stream setup so a pending approval can start at most+// one resumed tool call attempt.+export async function consumeAndValidatePendingToolApproval(params: {+ projectId: string;+ conversationId: string;+ forwardedProps: ResumeForwardedProps;+}) {+ const approvalRequest = params.forwardedProps.command.resume.approvalRequest;+ const consumeResult = await prisma.inAppAgentPendingToolApproval.deleteMany({+ where: {+ projectId: params.projectId,+ conversationId: params.conversationId,+ toolCallId: approvalRequest.toolCallId,+ approvalFingerprint:+ createPendingToolApprovalFingerprint(approvalRequest),+ expiresAt: { gt: new Date() },+ },+ });++ if (consumeResult.count !== 1) {+ throw new InvalidRequestError("Invalid forwarded props");+ }+}++export async function createInAppAgentMcpRunOverride(params: {+ toolName: McpToolName;+}) {+ return JSON.stringify({+ toolName: params.toolName,+ });+}++export function parseInAppAgentInterruptEvent(+ event: AgUiEvent,+): InAppAgentToolApprovalRequest | undefined {+ if (event.type !== EventType.CUSTOM || event.name !== "on_interrupt") {+ return undefined;+ }++ const value = event.value;+ const interrupt =+ typeof value === "string" ? safeJsonParse(value) : (value as unknown);+ const parsedInterrupt = MastraSuspendEventSchema.safeParse(interrupt);++ return parsedInterrupt.success+ ? { ...parsedInterrupt.data, type: "tool_approval_request" }+ : undefined;+}++export type ManualToolApprovalRunInput = {+ input: AgUiRunAgentInput;+ syntheticEvents: AgUiEvent[];+ shouldContinue: boolean;+};++export async function createManualToolApprovalRunInput(params: {+ input: AgUiRunAgentInput;+ executeToolCall: (+ approvalRequest: InAppAgentToolApprovalRequest,+ ) => Promise<unknown>;+ onApprovedToolCallExecuted?: () => void | Promise<void>;+}): Promise<ManualToolApprovalRunInput> {+ const forwardedProps = getResumeForwardedProps(params.input);++ if (!forwardedProps) {+ return { input: params.input, syntheticEvents: [], shouldContinue: true };+ }++ const { approved, approvalRequest } = forwardedProps.command.resume;+ if (!approved) {+ return {+ input: {+ ...params.input,+ forwardedProps: {},+ },+ syntheticEvents: createManualToolApprovalEvents({+ approvalRequest,+ toolResultContent: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,+ toolError: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,+ }),+ shouldContinue: false,+ };+ }++ const { toolResult, toolError } = await executeApprovedToolCall({+ approvalRequest,+ executeToolCall: params.executeToolCall,+ });+ await params.onApprovedToolCallExecuted?.();+ const toolResultContent = serializeToolResultContent(toolResult);+ const assistantMessage =+ createManualToolCallAssistantMessage(approvalRequest);+ const toolMessage: AgUiMessage = {+ id: createManualToolResultMessageId(approvalRequest),+ role: "tool",+ content: toolResultContent,+ toolCallId: approvalRequest.toolCallId,+ ...(toolError ? { error: toolError } : {}),+ };+ const syntheticEvents = createManualToolApprovalEvents({+ approvalRequest,+ toolResultContent,+ toolError,+ });++ return {+ input: {+ ...params.input,+ messages: [+ ...params.input.messages,+ assistantMessage,+ toolMessage,+ ...(toolError+ ? [+ createToolExecutionErrorGuidanceMessage(+ approvalRequest,+ toolError,+ ),+ ]+ : []),+ ],+ forwardedProps: {},+ },+ syntheticEvents,+ shouldContinue: true,+ };+}++async function executeApprovedToolCall(params: {+ approvalRequest: InAppAgentToolApprovalRequest;+ executeToolCall: (+ approvalRequest: InAppAgentToolApprovalRequest,+ ) => Promise<unknown>;+}): Promise<{ toolResult: unknown; toolError?: string }> {+ try {+ return { toolResult: await params.executeToolCall(params.approvalRequest) };+ } catch (error) {+ const toolError = formatToolExecutionError(error);++ return { toolResult: toolError, toolError };+ }+}++function getResumeForwardedProps(+ input: AgUiRunAgentInput,+): ResumeForwardedProps | undefined {+ const forwardedProps = input.forwardedProps as+ | ResumeForwardedProps+ | undefined;++ if (!forwardedProps?.command?.resume) {+ return undefined;+ }++ return forwardedProps;+}++export function createManualToolCallAssistantMessage(+ approvalRequest: InAppAgentToolApprovalRequest,+): AgUiMessage {+ return {+ id: createManualToolCallParentMessageId(approvalRequest),+ role: "assistant",+ toolCalls: [+ {+ id: approvalRequest.toolCallId,+ type: "function",+ function: {+ name: approvalRequest.toolName,+ arguments: serializeToolCallArgs(approvalRequest.args),+ },+ },+ ],+ runId: approvalRequest.runId,+ };+}++function createToolExecutionErrorGuidanceMessage(+ approvalRequest: InAppAgentToolApprovalRequest,+ toolError: string,+): AgUiMessage {+ const args = serializeToolCallArgs(approvalRequest.args);++ return {+ id: `${approvalRequest.toolCallId}-approval-tool-error-guidance`,+ role: "developer",+ content: [+ `The approved tool call ${approvalRequest.toolName} failed during execution.`,+ `Rejected arguments: ${args}`,+ `Tool error: ${toolError}`,+ "Do not call the same tool again with identical arguments.",+ "Correct the arguments based on the tool error and retry only if a valid correction is clear. If you cannot infer a valid correction, ask the user for clarification or explain why the action could not be completed.",+ ].join("\n"),+ };+}++export function createManualToolApprovalEvents(params: {+ approvalRequest: InAppAgentToolApprovalRequest;+ toolResultContent: string;+ toolError?: string;+}): AgUiEvent[] {+ const { approvalRequest } = params;+ const args = serializeToolCallArgs(approvalRequest.args);++ return [+ {+ type: EventType.TOOL_CALL_START,+ parentMessageId: createManualToolCallParentMessageId(approvalRequest),+ toolCallId: approvalRequest.toolCallId,+ toolCallName: approvalRequest.toolName,+ },+ {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: approvalRequest.toolCallId,+ delta: args,+ },+ {+ type: EventType.TOOL_CALL_END,+ toolCallId: approvalRequest.toolCallId,+ },+ {+ type: EventType.TOOL_CALL_RESULT,+ messageId: createManualToolResultMessageId(approvalRequest),+ toolCallId: approvalRequest.toolCallId,+ content: params.toolResultContent,+ role: "tool",+ ...(params.toolError ? { error: params.toolError } : {}),+ },+ ];+}++function formatToolExecutionError(error: unknown) {+ if (error instanceof Error && error.message) {+ return error.message;+ }++ if (typeof error === "string" && error) {+ return error;+ }++ return "Tool execution failed.";+}++function createManualToolCallParentMessageId(+ approvalRequest: InAppAgentToolApprovalRequest,+) {+ return `${approvalRequest.toolCallId}-approval-tool-call`;+}++function createManualToolResultMessageId(+ approvalRequest: InAppAgentToolApprovalRequest,+) {+ return `${approvalRequest.toolCallId}-approval-tool-result`;+}++function serializeToolCallArgs(args: unknown) {+ return serializeToolResultContent(args ?? {});+}++function serializeToolResultContent(value: unknown) {+ if (typeof value === "string") {+ return value;+ }++ try {+ return JSON.stringify(value ?? null);+ } catch {+ return String(value);+ }+}++function createPendingToolApprovalFingerprint(+ approvalRequest: InAppAgentToolApprovalRequest,+): string {+ // Persist only the stable approval identity, including a sorted-JSON argument+ // fingerprint, so approved calls cannot be replayed with changed arguments.+ return JSON.stringify(+ PendingToolApprovalSchema.parse({+ toolCallId: approvalRequest.toolCallId,+ toolName: approvalRequest.toolName,+ runId: approvalRequest.runId,+ argsFingerprint: stableJsonStringify(approvalRequest.args),+ }),+ );+}diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.tsindex 02ea6b663a..f213c95357 100644--- a/web/src/ee/features/in-app-agent/server/persistence.ts+++ b/web/src/ee/features/in-app-agent/server/persistence.ts@@ -293,6 +293,15 @@ export async function getConversationMessages(params: {return getMessagesFromPersistedEvents(await getConversationEvents(params));}+export async function getConversationMessagesForDisplay(params: {+ prisma: PrismaClient;+ projectId: string;+ conversationId: string;+}) {+ const messages = await getConversationMessages(params);+ return dropEmptyAssistantMessages(dropUnpairedAssistantToolCalls(messages));+}+export async function getConversationMessagesForReplay(params: {prisma: PrismaClient;projectId: string;diff --git a/web/src/ee/features/in-app-agent/server/router.ts b/web/src/ee/features/in-app-agent/server/router.tsindex acfe56e447..07d8f970cb 100644--- a/web/src/ee/features/in-app-agent/server/router.ts+++ b/web/src/ee/features/in-app-agent/server/router.ts@@ -23,6 +23,7 @@ import {protectedProjectProcedureWithoutTracing,} from "@/src/server/api/trpc";import {+ getConversationMessagesForDisplay,getConversationMessages,getOwnedConversationOrThrow,serializeConversation,@@ -110,7 +111,7 @@ export const inAppAgentRouter = createTRPCRouter({userId: ctx.session.user.id,});- const messages = await getConversationMessages({+ const messages = await getConversationMessagesForDisplay({prisma: ctx.prisma,projectId: input.projectId,conversationId: input.conversationId,diff --git a/web/src/ee/features/in-app-agent/server/tools.ts b/web/src/ee/features/in-app-agent/server/tools.tsindex ce5262f2a1..c8034c5c98 100644--- a/web/src/ee/features/in-app-agent/server/tools.ts+++ b/web/src/ee/features/in-app-agent/server/tools.ts@@ -1,4 +1,6 @@import { createTool } from "@mastra/core/tools";+import type { ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";+import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { assertUnreachable } from "@/src/utils/types";import {buildDashboardsPath,@@ -20,7 +22,365 @@ import {import z from "zod";import { TABLE_AGGREGATION_OPTIONS } from "@/src/utils/date-range-utils";import { ObservationLevelDomain, TracingSearchType } from "@langfuse/shared";+import { Role } from "@langfuse/shared/src/db";import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";+import type { McpToolName } from "@/src/features/mcp/server/bootstrap";++type InAppAgentMcpToolApproval = "auto" | "approval";++export type InAppAgentUserAccess = {+ projectRole?: Role;+ isAdmin: boolean;+};++type InAppAgentMcpToolPolicy = {+ approval: InAppAgentMcpToolApproval;+ availability: {+ scope: ProjectScope;+ };+};++// Exhaustive approval policy for Langfuse MCP tools. Keys use the unprefixed+// MCP registry names; tests compare this map with toolRegistry so new MCP tools+// must be classified before the in-app agent can auto/approval-gate them.+export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES: Record<+ McpToolName,+ InAppAgentMcpToolPolicy+> = {+ listAnnotationQueues: {+ approval: "auto",+ availability: { scope: "annotationQueues:read" },+ },+ createAnnotationQueue: {+ approval: "approval",+ availability: { scope: "annotationQueues:CUD" },+ },+ getAnnotationQueue: {+ approval: "auto",+ availability: { scope: "annotationQueues:read" },+ },+ listAnnotationQueueItems: {+ approval: "auto",+ availability: { scope: "annotationQueues:read" },+ },+ getAnnotationQueueItem: {+ approval: "auto",+ availability: { scope: "annotationQueues:read" },+ },+ createAnnotationQueueItem: {+ approval: "approval",+ availability: { scope: "annotationQueues:CUD" },+ },+ updateAnnotationQueueItem: {+ approval: "approval",+ availability: { scope: "annotationQueues:CUD" },+ },+ deleteAnnotationQueueItem: {+ approval: "approval",+ availability: { scope: "annotationQueues:CUD" },+ },+ createAnnotationQueueAssignment: {+ approval: "approval",+ availability: { scope: "annotationQueueAssignments:CUD" },+ },+ deleteAnnotationQueueAssignment: {+ approval: "approval",+ availability: { scope: "annotationQueueAssignments:CUD" },+ },+ createComment: {+ approval: "approval",+ availability: { scope: "comments:CUD" },+ },+ listComments: {+ approval: "auto",+ availability: { scope: "comments:read" },+ },+ getComment: {+ approval: "auto",+ availability: { scope: "comments:read" },+ },+ upsertDataset: {+ approval: "approval",+ availability: { scope: "datasets:CUD" },+ },+ listDatasets: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ getDataset: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ upsertDatasetItem: {+ approval: "approval",+ availability: { scope: "datasets:CUD" },+ },+ listDatasetItems: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ getDatasetItem: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ deleteDatasetItem: {+ approval: "approval",+ availability: { scope: "datasets:CUD" },+ },+ createDatasetRunItem: {+ approval: "approval",+ availability: { scope: "datasets:CUD" },+ },+ listDatasetRunItems: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ listDatasetRuns: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ getDatasetRun: {+ approval: "auto",+ availability: { scope: "datasets:read" },+ },+ deleteDatasetRun: {+ approval: "approval",+ availability: { scope: "datasets:CUD" },+ },+ listEvaluators: {+ approval: "auto",+ availability: { scope: "evalTemplate:read" },+ },+ getEvaluator: {+ approval: "auto",+ availability: { scope: "evalTemplate:read" },+ },+ upsertEvaluator: {+ approval: "approval",+ availability: { scope: "evalTemplate:CUD" },+ },+ deleteEvaluator: {+ approval: "approval",+ availability: { scope: "evalTemplate:CUD" },+ },+ listEvaluationRules: {+ approval: "auto",+ availability: { scope: "evalJob:read" },+ },+ getEvaluationRule: {+ approval: "auto",+ availability: { scope: "evalJob:read" },+ },+ createEvaluationRule: {+ approval: "approval",+ availability: { scope: "evalJob:CUD" },+ },+ updateEvaluationRule: {+ approval: "approval",+ availability: { scope: "evalJob:CUD" },+ },+ deleteEvaluationRule: {+ approval: "approval",+ availability: { scope: "evalJob:CUD" },+ },+ getHealth: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getMedia: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ queryMetrics: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getMetricsSchema: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ listModels: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ createModel: {+ approval: "approval",+ availability: { scope: "models:CUD" },+ },+ getModel: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ deleteModel: {+ approval: "approval",+ availability: { scope: "models:CUD" },+ },+ listObservations: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getObservation: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getObservationFieldSchema: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getObservationFilterSchema: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getObservationFilterValues: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getPrompt: {+ approval: "auto",+ availability: { scope: "prompts:read" },+ },+ getPromptUnresolved: {+ approval: "auto",+ availability: { scope: "prompts:read" },+ },+ listPrompts: {+ approval: "auto",+ availability: { scope: "prompts:read" },+ },+ createTextPrompt: {+ approval: "approval",+ availability: { scope: "prompts:CUD" },+ },+ createChatPrompt: {+ approval: "approval",+ availability: { scope: "prompts:CUD" },+ },+ updatePromptLabels: {+ approval: "approval",+ availability: { scope: "prompts:CUD" },+ },+ listScores: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ getScore: {+ approval: "auto",+ availability: { scope: "project:read" },+ },+ createScore: {+ approval: "approval",+ availability: { scope: "scores:CUD" },+ },+ listScoreConfigs: {+ approval: "auto",+ availability: { scope: "scoreConfigs:read" },+ },+ getScoreConfig: {+ approval: "auto",+ availability: { scope: "scoreConfigs:read" },+ },+ createScoreConfig: {+ approval: "approval",+ availability: { scope: "scoreConfigs:CUD" },+ },+ updateScoreConfig: {+ approval: "approval",+ availability: { scope: "scoreConfigs:CUD" },+ },+ deleteScoreConfig: {+ approval: "approval",+ availability: { scope: "scoreConfigs:CUD" },+ },+};++export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES = new Set<McpToolName>(+ Object.keys(IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES) as McpToolName[],+);++export const IN_APP_AGENT_AUTO_APPROVED_EXTERNAL_TOOL_NAMES = new Set([+ IN_APP_AGENT_REDIRECT_TOOL_NAME,+]);++// Tools in this set can run without a human-in-the-loop approval prompt. Every+// other MCP tool is still exposed to the model, but Mastra suspends execution+// until the user explicitly approves the exact call.+export const IN_APP_AGENT_AUTO_APPROVED_TOOL_NAMES = new Set([+ ...Object.entries(IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES)+ .filter(([, policy]) => policy.approval === "auto")+ .map(([toolName]) => `langfuse_${toolName}`),+ ...IN_APP_AGENT_AUTO_APPROVED_EXTERNAL_TOOL_NAMES,+]);++export function isMcpToolName(input: string): input is McpToolName {+ return IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES.has(input as McpToolName);+}++export function isInAppAgentLangfuseMcpToolAvailable(params: {+ toolName: McpToolName;+ userAccess?: InAppAgentUserAccess;+}): boolean {+ if (!params.userAccess) {+ return false;+ }++ const policy = IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES[params.toolName];++ if (!policy) {+ return false;+ }++ return hasProjectAccess({+ role: params.userAccess.projectRole ?? Role.MEMBER,+ admin: params.userAccess.isAdmin,+ scope: policy.availability.scope,+ });+}++export function filterInAppAgentAvailableLangfuseMcpTools<TTool>(params: {+ tools: Partial<Record<McpToolName, TTool>> | undefined;+ userAccess?: InAppAgentUserAccess;+}): Partial<Record<McpToolName, TTool>> {+ return Object.fromEntries(+ Object.entries(params.tools ?? {}).flatMap(([toolName, tool]) => {+ if (!isMcpToolName(toolName)) {+ return [];+ }++ if (+ !isInAppAgentLangfuseMcpToolAvailable({+ toolName,+ userAccess: params.userAccess,+ })+ ) {+ return [];+ }++ return [[toolName, tool] as const];+ }),+ );+}++type InAppAgentTool = object;++export function withInAppAgentToolApproval<TTool extends InAppAgentTool>(+ tools: Record<string, TTool>,+): Record<string, TTool | (TTool & { requireApproval: true })> {+ return Object.fromEntries(+ Object.entries(tools).map(([toolName, tool]) => [+ toolName,+ isInAppAgentAutoApprovedToolName(toolName)+ ? tool+ : { ...tool, requireApproval: true },+ ]),+ ) as Record<string, TTool | (TTool & { requireApproval: true })>;+}++function isInAppAgentAutoApprovedToolName(toolName: string): boolean {+ return (+ toolName.startsWith("langfuseDocs_") ||+ IN_APP_AGENT_AUTO_APPROVED_TOOL_NAMES.has(toolName)+ );+}const InAppAgentRedirectDestinationSchema = z.enum(["dashboards",diff --git a/web/src/features/mcp/core/define-tool.ts b/web/src/features/mcp/core/define-tool.tsindex ff31674bf4..02c9452a8b 100644--- a/web/src/features/mcp/core/define-tool.ts+++ b/web/src/features/mcp/core/define-tool.ts@@ -20,9 +20,9 @@ export type ToolHandler<TInput> = (/*** Tool definition options*/-export interface DefineToolOptions<TInput> {+export interface DefineToolOptions<TInput, TName extends string = string> {/** Tool name (must be unique across all tools) */- name: string;+ name: TName;/** Description for LLM to understand when to use this tool */description: string;@@ -49,8 +49,8 @@ export interface DefineToolOptions<TInput> {/*** MCP Tool definition*/-export interface ToolDefinition {- name: string;+export interface ToolDefinition<TName extends string = string> {+ name: TName;description: string;inputSchema: Record<string, unknown>;annotations?: {@@ -109,9 +109,9 @@ function hasJsonSchemaUnion(value: unknown): boolean {* readOnly: true,* });*/-export function defineTool<TInput>(- options: DefineToolOptions<TInput>,-): [ToolDefinition, ToolHandler<TInput>] {+export function defineTool<TInput, const TName extends string>(+ options: DefineToolOptions<TInput, TName>,+): [ToolDefinition<TName>, ToolHandler<TInput>] {const {name,description,@@ -151,7 +151,7 @@ export function defineTool<TInput>(}// Build tool definition- const toolDefinition: ToolDefinition = {+ const toolDefinition: ToolDefinition<TName> = {name,description,inputSchema: jsonSchemaObject,diff --git a/web/src/features/mcp/features/annotationQueues/index.ts b/web/src/features/mcp/features/annotationQueues/index.tsindex db07c2d257..937e5ab030 100644--- a/web/src/features/mcp/features/annotationQueues/index.ts+++ b/web/src/features/mcp/features/annotationQueues/index.ts@@ -40,7 +40,7 @@ import {updateAnnotationQueueItemTool,} from "./tools/updateAnnotationQueueItem";-export const annotationQueuesFeature: McpFeatureModule = {+export const annotationQueuesFeature = {name: "annotationQueues",description:"Manage annotation queues, worklists of trace or observation items for human review and scoring, plus user assignments",@@ -48,7 +48,6 @@ export const annotationQueuesFeature: McpFeatureModule = {{definition: listAnnotationQueuesTool,handler: handleListAnnotationQueues,- allowInAppAgentKey: true,},{definition: createAnnotationQueueTool,@@ -57,17 +56,14 @@ export const annotationQueuesFeature: McpFeatureModule = {{definition: getAnnotationQueueTool,handler: handleGetAnnotationQueue,- allowInAppAgentKey: true,},{definition: listAnnotationQueueItemsTool,handler: handleListAnnotationQueueItems,- allowInAppAgentKey: true,},{definition: getAnnotationQueueItemTool,handler: handleGetAnnotationQueueItem,- allowInAppAgentKey: true,},{definition: createAnnotationQueueItemTool,@@ -90,4 +86,4 @@ export const annotationQueuesFeature: McpFeatureModule = {handler: handleDeleteAnnotationQueueAssignment,},],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/comments/index.ts b/web/src/features/mcp/features/comments/index.tsindex 758a39a845..909ab3cb11 100644--- a/web/src/features/mcp/features/comments/index.ts+++ b/web/src/features/mcp/features/comments/index.ts@@ -3,7 +3,7 @@ import { createCommentTool, handleCreateComment } from "./tools/createComment";import { getCommentTool, handleGetComment } from "./tools/getComment";import { handleListComments, listCommentsTool } from "./tools/listComments";-export const commentsFeature: McpFeatureModule = {+export const commentsFeature = {name: "comments",description: "Create and inspect comments",tools: [@@ -11,12 +11,10 @@ export const commentsFeature: McpFeatureModule = {{definition: listCommentsTool,handler: handleListComments,- allowInAppAgentKey: true,},{definition: getCommentTool,handler: handleGetComment,- allowInAppAgentKey: true,},],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/datasets/index.ts b/web/src/features/mcp/features/datasets/index.tsindex e2a8e5a207..d3f0a5988e 100644--- a/web/src/features/mcp/features/datasets/index.ts+++ b/web/src/features/mcp/features/datasets/index.ts@@ -36,7 +36,7 @@ import {} from "./tools/listDatasetRuns";import { handleListDatasets, listDatasetsTool } from "./tools/listDatasets";-export const datasetsFeature: McpFeatureModule = {+export const datasetsFeature = {name: "datasets",description:"Manage datasets, named collections of dataset items for experiments and evaluations, plus runs and run items",@@ -45,23 +45,19 @@ export const datasetsFeature: McpFeatureModule = {{definition: listDatasetsTool,handler: handleListDatasets,- allowInAppAgentKey: true,},{definition: getDatasetTool,handler: handleGetDataset,- allowInAppAgentKey: true,},{ definition: upsertDatasetItemTool, handler: handleUpsertDatasetItem },{definition: listDatasetItemsTool,handler: handleListDatasetItems,- allowInAppAgentKey: true,},{definition: getDatasetItemTool,handler: handleGetDatasetItem,- allowInAppAgentKey: true,},{ definition: deleteDatasetItemTool, handler: handleDeleteDatasetItem },{@@ -71,18 +67,15 @@ export const datasetsFeature: McpFeatureModule = {{definition: listDatasetRunItemsTool,handler: handleListDatasetRunItems,- allowInAppAgentKey: true,},{definition: listDatasetRunsTool,handler: handleListDatasetRuns,- allowInAppAgentKey: true,},{definition: getDatasetRunTool,handler: handleGetDatasetRun,- allowInAppAgentKey: true,},{ definition: deleteDatasetRunTool, handler: handleDeleteDatasetRun },],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/evals/index.ts b/web/src/features/mcp/features/evals/index.tsindex 4351d9f6f5..f6a7709983 100644--- a/web/src/features/mcp/features/evals/index.ts+++ b/web/src/features/mcp/features/evals/index.ts@@ -33,7 +33,7 @@ import {handleDeleteEvaluationRule,} from "./tools/deleteEvaluationRule";-export const evalsFeature: McpFeatureModule = {+export const evalsFeature = {name: "evals",description:"Manage evaluators and evaluation rules in the current Langfuse project (unstable API)",@@ -41,12 +41,10 @@ export const evalsFeature: McpFeatureModule = {{definition: listEvaluatorsTool,handler: handleListEvaluators,- allowInAppAgentKey: true,},{definition: getEvaluatorTool,handler: handleGetEvaluator,- allowInAppAgentKey: true,},{ definition: upsertEvaluatorTool, handler: handleUpsertEvaluator },{@@ -56,12 +54,10 @@ export const evalsFeature: McpFeatureModule = {{definition: listEvaluationRulesTool,handler: handleListEvaluationRules,- allowInAppAgentKey: true,},{definition: getEvaluationRuleTool,handler: handleGetEvaluationRule,- allowInAppAgentKey: true,},{definition: createEvaluationRuleTool,@@ -76,4 +72,4 @@ export const evalsFeature: McpFeatureModule = {handler: handleDeleteEvaluationRule,},],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/health/index.ts b/web/src/features/mcp/features/health/index.tsindex 58fffd3b5c..7b83afeac4 100644--- a/web/src/features/mcp/features/health/index.ts+++ b/web/src/features/mcp/features/health/index.ts@@ -1,14 +1,13 @@import type { McpFeatureModule } from "../../server/registry";import { getHealthTool, handleGetHealth } from "./tools/getHealth";-export const healthFeature: McpFeatureModule = {+export const healthFeature = {name: "health",description: "Check Langfuse health",tools: [{definition: getHealthTool,handler: handleGetHealth,- allowInAppAgentKey: true,},],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/media/index.ts b/web/src/features/mcp/features/media/index.tsindex f560ac1865..50b04aca29 100644--- a/web/src/features/mcp/features/media/index.ts+++ b/web/src/features/mcp/features/media/index.ts@@ -1,7 +1,7 @@import type { McpFeatureModule } from "../../server/registry";import { getMediaTool, handleGetMedia } from "./tools/getMedia";-export const mediaFeature: McpFeatureModule = {+export const mediaFeature = {name: "media",description:"Retrieve files, images, audio, video, text, and other media assets in the current Langfuse project",@@ -9,7 +9,6 @@ export const mediaFeature: McpFeatureModule = {{definition: getMediaTool,handler: handleGetMedia,- allowInAppAgentKey: true,},],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/metrics/index.ts b/web/src/features/mcp/features/metrics/index.tsindex ce886cf672..8c23d2ef7e 100644--- a/web/src/features/mcp/features/metrics/index.ts+++ b/web/src/features/mcp/features/metrics/index.ts@@ -6,7 +6,7 @@ import {} from "./tools/getMetricsSchema";import { queryMetricsTool, handleQueryMetrics } from "./tools/queryMetrics";-export const metricsFeature: McpFeatureModule = {+export const metricsFeature = {name: "metrics",description:"Analyze project usage, quality, cost, and performance metrics from Langfuse data",@@ -14,14 +14,12 @@ export const metricsFeature: McpFeatureModule = {{definition: queryMetricsTool,handler: handleQueryMetrics,- allowInAppAgentKey: true,},{definition: getMetricsSchemaTool,handler: handleGetMetricsSchema,- allowInAppAgentKey: true,},],isEnabled: async () =>env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true",-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/models/index.ts b/web/src/features/mcp/features/models/index.tsindex 8139c65b11..69f359dd2d 100644--- a/web/src/features/mcp/features/models/index.ts+++ b/web/src/features/mcp/features/models/index.ts@@ -4,21 +4,19 @@ import { deleteModelTool, handleDeleteModel } from "./tools/deleteModel";import { getModelTool, handleGetModel } from "./tools/getModel";import { handleListModels, listModelsTool } from "./tools/listModels";-export const modelsFeature: McpFeatureModule = {+export const modelsFeature = {name: "models",description: "Manage model definitions",tools: [{definition: listModelsTool,handler: handleListModels,- allowInAppAgentKey: true,},{ definition: createModelTool, handler: handleCreateModel },{definition: getModelTool,handler: handleGetModel,- allowInAppAgentKey: true,},{ definition: deleteModelTool, handler: handleDeleteModel },],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/observations/index.ts b/web/src/features/mcp/features/observations/index.tsindex 416e80f4b3..c2f0ce001d 100644--- a/web/src/features/mcp/features/observations/index.ts+++ b/web/src/features/mcp/features/observations/index.ts@@ -21,7 +21,7 @@ import {} from "./tools/listObservations";import { env } from "@/src/env.mjs";-export const observationsFeature: McpFeatureModule = {+export const observationsFeature = {name: "observations",description:"Inspect generations, spans, events, and other observations in Langfuse",@@ -29,29 +29,24 @@ export const observationsFeature: McpFeatureModule = {{definition: listObservationsTool,handler: handleListObservations,- allowInAppAgentKey: true,},{definition: getObservationTool,handler: handleGetObservation,- allowInAppAgentKey: true,},{definition: getObservationFieldSchemaTool,handler: handleGetObservationFieldSchema,- allowInAppAgentKey: true,},{definition: getObservationFilterSchemaTool,handler: handleGetObservationFilterSchema,- allowInAppAgentKey: true,},{definition: getObservationFilterValuesTool,handler: handleGetObservationFilterValues,- allowInAppAgentKey: true,},],isEnabled: async () =>env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true",-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/prompts/index.ts b/web/src/features/mcp/features/prompts/index.tsindex 263c472d8f..7088f9fe44 100644--- a/web/src/features/mcp/features/prompts/index.ts+++ b/web/src/features/mcp/features/prompts/index.ts@@ -39,7 +39,7 @@ import {* Registers all prompt management tools with the MCP server.* Tools are automatically available to MCP clients once registered.*/-export const promptsFeature: McpFeatureModule = {+export const promptsFeature = {name: "prompts",description:"Manage Langfuse prompts - create, retrieve, and update prompt versions",@@ -48,17 +48,14 @@ export const promptsFeature: McpFeatureModule = {{definition: getPromptTool,handler: handleGetPrompt,- allowInAppAgentKey: true,},{definition: getPromptUnresolvedTool,handler: handleGetPromptUnresolved,- allowInAppAgentKey: true,},{definition: listPromptsTool,handler: handleListPrompts,- allowInAppAgentKey: true,},{definition: createTextPromptTool,@@ -79,4 +76,4 @@ export const promptsFeature: McpFeatureModule = {// // Example: Check entitlements, feature flags, etc.// return true;// },-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts b/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.tsindex 895ffff617..f7586ee483 100644--- a/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts+++ b/web/src/features/mcp/features/prompts/tools/promptReadToolFactory.ts@@ -57,14 +57,16 @@ const buildPromptNotFoundMessage = (params: {return `Prompt '${name}' not found${label ? ` with label '${label}'` : ""}${version ? ` with version ${version}` : ""}`;};-type CreatePromptReadToolOptions = {- name: string;+type CreatePromptReadToolOptions<TName extends string> = {+ name: TName;description: string;resolve: boolean;spanName: string;};-export const createPromptReadTool = (options: CreatePromptReadToolOptions) => {+export const createPromptReadTool = <const TName extends string>(+ options: CreatePromptReadToolOptions<TName>,+) => {const { name, description, resolve, spanName } = options;return defineTool({diff --git a/web/src/features/mcp/features/publicApi.ts b/web/src/features/mcp/features/publicApi.tsindex feeb298039..55c789b872 100644--- a/web/src/features/mcp/features/publicApi.ts+++ b/web/src/features/mcp/features/publicApi.ts@@ -41,7 +41,7 @@ export const getMcpPublicApiAuth = async (plan: getOrganizationPlanServerSide(cloudConfig),rateLimitOverrides: [],isIngestionSuspended: false,- isInAppAgentKey: context.isInAppAgentKey === true,+ isInAppAgentKey: context.inAppAgent !== undefined,},};};diff --git a/web/src/features/mcp/features/scores/index.ts b/web/src/features/mcp/features/scores/index.tsindex f8e639e773..04741b5b4c 100644--- a/web/src/features/mcp/features/scores/index.ts+++ b/web/src/features/mcp/features/scores/index.ts@@ -23,7 +23,7 @@ import {handleUpdateScoreConfig,} from "./tools/updateScoreConfig";-export const scoresFeature: McpFeatureModule = {+export const scoresFeature = {name: "scores",description:"Read scores and manage score configurations in the current Langfuse project",@@ -31,12 +31,10 @@ export const scoresFeature: McpFeatureModule = {{definition: listScoresTool,handler: handleListScores,- allowInAppAgentKey: true,},{definition: getScoreTool,handler: handleGetScore,- allowInAppAgentKey: true,},{definition: createScoreTool,@@ -45,12 +43,10 @@ export const scoresFeature: McpFeatureModule = {{definition: listScoreConfigsTool,handler: handleListScoreConfigs,- allowInAppAgentKey: true,},{definition: getScoreConfigTool,handler: handleGetScoreConfig,- allowInAppAgentKey: true,},{definition: createScoreConfigTool,@@ -65,4 +61,4 @@ export const scoresFeature: McpFeatureModule = {handler: handleDeleteScoreConfig,},],-};+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/server/bootstrap.ts b/web/src/features/mcp/server/bootstrap.tsindex f0b179c05a..b8da0c2c41 100644--- a/web/src/features/mcp/server/bootstrap.ts+++ b/web/src/features/mcp/server/bootstrap.ts@@ -11,6 +11,7 @@*/import { toolRegistry } from "./registry";+import type { McpFeatureModule } from "./registry";import { promptsFeature } from "../features/prompts";import { observationsFeature } from "../features/observations";import { annotationQueuesFeature } from "../features/annotationQueues";@@ -22,8 +23,23 @@ import { metricsFeature } from "../features/metrics";import { modelsFeature } from "../features/models";import { mediaFeature } from "../features/media";import { evalsFeature } from "../features/evals";-// Import future features as they're added:-// import { tracesFeature } from "../features/traces";++const MCP_FEATURES = [+ promptsFeature,+ observationsFeature,+ annotationQueuesFeature,+ commentsFeature,+ datasetsFeature,+ healthFeature,+ scoresFeature,+ metricsFeature,+ modelsFeature,+ mediaFeature,+ evalsFeature,+] as const satisfies readonly McpFeatureModule[];++export type McpFeature = (typeof MCP_FEATURES)[number];+export type McpToolName = McpFeature["tools"][number]["definition"]["name"];/*** Bootstrap all MCP features@@ -33,20 +49,9 @@ import { evalsFeature } from "../features/evals";*/export function bootstrapMcpFeatures(): void {// Register all feature modules- toolRegistry.register(promptsFeature);- toolRegistry.register(observationsFeature);- toolRegistry.register(annotationQueuesFeature);- toolRegistry.register(commentsFeature);- toolRegistry.register(datasetsFeature);- toolRegistry.register(healthFeature);- toolRegistry.register(scoresFeature);- toolRegistry.register(metricsFeature);- toolRegistry.register(modelsFeature);- toolRegistry.register(mediaFeature);- toolRegistry.register(evalsFeature);-- // Add future features here:- // toolRegistry.register(tracesFeature);+ for (const feature of MCP_FEATURES) {+ toolRegistry.register(feature);+ }}/**diff --git a/web/src/features/mcp/server/registry.ts b/web/src/features/mcp/server/registry.tsindex 1f3f7351a8..adbe3a061a 100644--- a/web/src/features/mcp/server/registry.ts+++ b/web/src/features/mcp/server/registry.ts@@ -19,16 +19,13 @@ import { logger } from "@langfuse/shared/src/server";** Combines tool definition (for MCP protocol) with handler (for execution)*/-export interface RegisteredTool {+export interface RegisteredTool<TName extends string = string> {/** Tool definition for MCP protocol */- definition: ToolDefinition;+ definition: ToolDefinition<TName>;/** Tool handler function - accepts any input type */handler: ToolHandler<any>;-- /** Whether in-app agent API keys may discover and call this tool. */- allowInAppAgentKey?: boolean;}/**@@ -57,7 +54,7 @@ export interface McpFeatureModule {description: string;/** Tools provided by this feature */- tools: RegisteredTool[];+ tools: readonly RegisteredTool[];/*** Optional: Check if feature is enabled for the given context@@ -128,10 +125,6 @@ class ToolRegistry {// Add all tools from enabled featurefor (const tool of feature.tools) {- if (!this.canUseTool(tool, context)) {- continue;- }-definitions.push(tool.definition);}}@@ -163,23 +156,31 @@ class ToolRegistry {const feature = this.getFeatureForTool(name);if (!feature) return undefined;- if (!this.canUseTool(tool, context)) {+ if (feature.isEnabled && !(await feature.isEnabled(context))) {return undefined;}- if (feature.isEnabled && !(await feature.isEnabled(context))) {+ if (!this.canCallTool(tool, context)) {return undefined;}return tool;}- private canUseTool(tool: RegisteredTool, context: ServerContext): boolean {- if (context.isInAppAgentKey === true && tool.allowInAppAgentKey !== true) {- return false;+ private canCallTool(tool: RegisteredTool, context: ServerContext): boolean {+ if (!context.inAppAgent) {+ return true;+ }++ if (context.inAppAgent.permissions === "read") {+ return tool.definition.annotations?.readOnlyHint === true;+ }++ if (context.inAppAgent.permissions === "single-tool-override") {+ return context.inAppAgent.allowedToolName === tool.definition.name;}- return true;+ return false;}/**diff --git a/web/src/features/mcp/types.ts b/web/src/features/mcp/types.tsindex 08a9fe45b9..a67ff6a1e2 100644--- a/web/src/features/mcp/types.ts+++ b/web/src/features/mcp/types.ts@@ -1,3 +1,5 @@+import type { McpToolName } from "./server/bootstrap";+/*** MCP (Model Context Protocol) Server Types*@@ -49,6 +51,20 @@ export interface ServerContext {/** Public key used for authentication */publicKey: string;- /** Whether the authenticated API key is scoped to the in-app agent. */- isInAppAgentKey?: boolean;+ /** In-app-agent-specific MCP authorization state. */+ inAppAgent?: InAppAgentContext;}++/**+ * In-app-agent MCP access is explicit: `read` allows only tools annotated with `readOnlyHint`.+ * To allow mutating operations, `single-tool-override` can include a specific MCP registry tool name that the in-app agent is allowed to invoke.+ * Human approval is enforced earlier in the in-app agent runtime before any override is minted.+ */+export type InAppAgentContext =+ | {+ permissions: "read";+ }+ | {+ permissions: "single-tool-override";+ allowedToolName: McpToolName;+ };diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.tsindex 92d693756e..48ad36b465 100644--- a/web/src/pages/api/public/mcp/index.ts+++ b/web/src/pages/api/public/mcp/index.ts@@ -40,6 +40,9 @@ import { prisma } from "@langfuse/shared/src/db";import { BaseError, UnauthorizedError, ForbiddenError } from "@langfuse/shared";import { ZodError } from "zod";import { isUserInputError } from "@/src/features/mcp/core/errors";+import { IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER } from "@/src/ee/features/in-app-agent/constants";+import { InAppAgentMcpRunOverrideSchema } from "@/src/ee/features/in-app-agent/server/human-in-the-loop";+import { safeJsonParse } from "@/src/utils/json";// Bootstrap MCP features - registers all tools at module load timeimport "@/src/features/mcp/server/bootstrap";@@ -116,7 +119,9 @@ export default async function handler(return rateLimitCheck.sendRestResponseIfLimited(res);}- // Build ServerContext from authenticated scope+ // Build ServerContext from authenticated scope. In-app-agent keys need a+ // run override for mutating tools; read-only tools remain available+ // without it via their MCP readOnlyHint annotation.const context: ServerContext = {projectId: authCheck.scope.projectId,orgId: authCheck.scope.orgId,@@ -124,7 +129,7 @@ export default async function handler(apiKeyId: authCheck.scope.apiKeyId,accessLevel: "project",publicKey: authCheck.scope.publicKey,- isInAppAgentKey: authCheck.scope.isInAppAgentKey === true,+ inAppAgent: getInAppAgentContext(req, authCheck.scope.isInAppAgentKey),};logger.debug("MCP request authenticated", {@@ -170,6 +175,32 @@ export default async function handler(}}+export function getInAppAgentContext(+ req: NextApiRequest,+ isInAppAgentKey: boolean | undefined,+): ServerContext["inAppAgent"] {+ if (isInAppAgentKey !== true) {+ return undefined;+ }++ const headerValue = req.headers[IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER];++ if (typeof headerValue !== "string") {+ return { permissions: "read" };+ }++ const parsedOverride = InAppAgentMcpRunOverrideSchema.safeParse(+ safeJsonParse(headerValue),+ );++ return parsedOverride.success+ ? {+ permissions: "single-tool-override",+ allowedToolName: parsedOverride.data.toolName,+ }+ : { permissions: "read" };+}+/*** Enable body parsing for JSON-RPC messages* Streamable HTTP transport receives JSON-RPC via POST bodydiff --git a/web/src/utils/chatml/extractTools.ts b/web/src/utils/chatml/extractTools.tsindex 4372af4224..74b1da240e 100644--- a/web/src/utils/chatml/extractTools.ts+++ b/web/src/utils/chatml/extractTools.ts@@ -3,6 +3,7 @@ import {normalizeToolDefinitionsForChatMl,} from "@langfuse/shared";import type { PlaygroundTool } from "@/src/features/playground/page/types";+import { safeJsonParse } from "@/src/utils/json";const EMPTY_TOOL_PARAMETERS = {type: "object",@@ -12,11 +13,8 @@ const EMPTY_TOOL_PARAMETERS = {function parseIfString(value: unknown): unknown {if (typeof value !== "string") return value;- try {- return JSON.parse(value);- } catch {- return value;- }+ const parsed = safeJsonParse(value);+ return parsed === undefined ? value : parsed;}function asRecord(value: unknown): Record<string, unknown> | null {diff --git a/web/src/utils/json.ts b/web/src/utils/json.tsnew file mode 100644index 0000000000..cbb109e79e--- /dev/null+++ b/web/src/utils/json.ts@@ -0,0 +1,27 @@+export function safeJsonParse(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ return undefined;+ }+}++export function stableJsonStringify(value: unknown): string {+ return JSON.stringify(sortJsonValue(value)) ?? "undefined";+}++function sortJsonValue(value: unknown): unknown {+ if (Array.isArray(value)) {+ return value.map(sortJsonValue);+ }++ if (value && typeof value === "object") {+ return Object.fromEntries(+ Object.entries(value)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([key, nestedValue]) => [key, sortJsonValue(nestedValue)]),+ );+ }++ return value;+}