🪢 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(auth): In-app agent API keys (#13692)
Ben Bachem364522a4455b
diff --git a/packages/shared/prisma/migrations/20260521130000_add_in_app_agent_api_key_marker/migration.sql b/packages/shared/prisma/migrations/20260521130000_add_in_app_agent_api_key_marker/migration.sqlnew file mode 100644index 0000000000..7f4e04f109--- /dev/null+++ b/packages/shared/prisma/migrations/20260521130000_add_in_app_agent_api_key_marker/migration.sql@@ -0,0 +1 @@+ALTER TABLE "api_keys" ADD COLUMN "is_in_app_agent_key" BOOLEAN NOT NULL DEFAULT false;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex c67f638070..7de7c0c7c9 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -190,6 +190,7 @@ model ApiKey {displaySecretKey String @map("display_secret_key")lastUsedAt DateTime? @map("last_used_at")expiresAt DateTime? @map("expires_at")+ isInAppAgentKey Boolean @default(false) @map("is_in_app_agent_key")projectId String? @map("project_id")project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)orgId String? @map("organization_id")diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.tsindex 65345f69a6..18de30e344 100644--- a/packages/shared/src/server/auth/apiKeys.ts+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -41,6 +41,7 @@ export async function createAndAddApiKeysToDb(p: {entityId: string;scope: ApiKeyScope;note?: string;+ isInAppAgentKey?: boolean;predefinedKeys?: {secretKey: string;publicKey: string;@@ -72,6 +73,7 @@ export async function createAndAddApiKeysToDb(p: {fastHashedSecretKey: hashFromProvidedKey,note: p.note,scope: p.scope,+ isInAppAgentKey: p.isInAppAgentKey ?? false,},});diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex 6c7535f1eb..fb34c6f2dc 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -17,6 +17,7 @@ const ApiKeyBaseSchema = z.object({plan: z.enum(plans as unknown as [string, ...string[]]),rateLimitOverrides: CloudConfigRateLimit.nullish(),isIngestionSuspended: z.boolean().nullish(),+ isInAppAgentKey: z.boolean().default(false),});export const OrgEnrichedApiKey = z.discriminatedUnion("scope", [@@ -68,6 +69,7 @@ type ApiAccessScopeMetadata = {apiKeyId: string;publicKey: string;isIngestionSuspended: boolean | null | undefined;+ isInAppAgentKey?: boolean;};export type ApiAccessScopeIngestion = BaseApiAccessScope &diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.tsindex cbe626a505..1eb90a52be 100644--- a/web/src/__tests__/server/api-auth.servertest.ts+++ b/web/src/__tests__/server/api-auth.servertest.ts@@ -1,5 +1,6 @@import {OrgEnrichedApiKey,+ createAndAddApiKeysToDb,createBasicAuthHeader,createOrgProjectAndApiKey,createShaHash,@@ -284,6 +285,50 @@ describe("Authenticate API calls", () => {expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).toBeNull();});++ it("rejects in-app agent API keys by default", async () => {+ const apiKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: testApiKey.projectId,+ scope: "PROJECT",+ isInAppAgentKey: true,+ });++ const auth = await new ApiAuthService(+ prisma,+ null,+ ).verifyAuthHeaderAndReturnScope(+ createBasicAuthHeader(apiKey.publicKey, apiKey.secretKey),+ );++ expect(auth).toEqual({+ validKey: false,+ error:+ "Access denied - in-app agent keys are not allowed for this endpoint",+ });+ });++ it("allows in-app agent API keys when explicitly enabled", async () => {+ const apiKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: testApiKey.projectId,+ scope: "PROJECT",+ isInAppAgentKey: true,+ });++ const auth = await new ApiAuthService(+ prisma,+ null,+ ).verifyAuthHeaderAndReturnScope(+ createBasicAuthHeader(apiKey.publicKey, apiKey.secretKey),+ { allowInAppAgentKey: true },+ );++ expect(auth.validKey).toBe(true);+ if (auth.validKey) {+ expect(auth.scope.isInAppAgentKey).toBe(true);+ }+ });});describe("validates with redis", () => {@@ -315,7 +360,7 @@ describe("Authenticate API calls", () => {}, 20_000);it("should create new api key and read from cache", async () => {- const legacySecretKey = ["legacy", "secret", "key"].join("-");+ const legacySecretKey = ["legacy", "secret", "key", v4()].join("-");const legacyPublicKey = `legacy-public-key-${v4()}`;const legacyAuth = createBasicAuthHeader(legacyPublicKey,@@ -637,6 +682,7 @@ describe("Authenticate API calls", () => {lastUsedAt: null,expiresAt: null,isIngestionSuspended: expect.anything(),+ isInAppAgentKey: false,projectId: expect.any(String),orgId: testApiKey.orgId,plan: "cloud:hobby",diff --git a/web/src/__tests__/server/api-key-list-filter.servertest.ts b/web/src/__tests__/server/api-key-list-filter.servertest.tsnew file mode 100644index 0000000000..3cbd3809a8--- /dev/null+++ b/web/src/__tests__/server/api-key-list-filter.servertest.ts@@ -0,0 +1,144 @@+import { prisma } from "@langfuse/shared/src/db";+import {+ createAndAddApiKeysToDb,+ createOrgProjectAndApiKey,+} from "@langfuse/shared/src/server";+import { handleGetApiKeys as handleGetProjectApiKeys } from "@/src/ee/features/admin-api/server/projects/projectById/apiKeys";+import { handleDeleteApiKey as handleDeleteProjectApiKey } from "@/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById";+import { handleGetApiKeys as handleGetOrganizationApiKeys } from "@/src/ee/features/admin-api/server/organizations/apiKeys";+import { handleDeleteApiKey as handleDeleteOrganizationApiKey } from "@/src/ee/features/admin-api/server/organizations/apiKeys/apiKeyById";+import type { NextApiRequest, NextApiResponse } from "next";++function createMockResponse() {+ const response = {+ statusCode: 200,+ body: undefined as unknown,+ status(code: number) {+ this.statusCode = code;+ return this;+ },+ json(body: unknown) {+ this.body = body;+ return this;+ },+ };++ return response as NextApiResponse & {+ statusCode: number;+ body: { apiKeys: Array<{ id: string; note: string | null }> } & Record<+ string,+ unknown+ >;+ };+}++describe("public API key list filters", () => {+ it("filters in-app agent keys from project API key responses", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const visibleKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ note: "Visible project key",+ });++ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ note: "Hidden project in-app agent key",+ isInAppAgentKey: true,+ });++ const response = createMockResponse();+ await handleGetProjectApiKeys({} as NextApiRequest, response, projectId);++ expect(response.statusCode).toBe(200);+ expect(response.body.apiKeys.map((key) => key.id)).toContain(visibleKey.id);+ expect(response.body.apiKeys.map((key) => key.id)).not.toContain(+ inAppAgentKey.id,+ );+ expect(response.body.apiKeys.map((key) => key.note)).not.toContain(+ "Hidden project in-app agent key",+ );+ });++ it("filters in-app agent keys from organization API key responses", async () => {+ const { orgId } = await createOrgProjectAndApiKey();++ const visibleKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: orgId,+ scope: "ORGANIZATION",+ note: "Visible org key",+ });++ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: orgId,+ scope: "ORGANIZATION",+ note: "Hidden org in-app agent key",+ isInAppAgentKey: true,+ });++ const response = createMockResponse();+ await handleGetOrganizationApiKeys({} as NextApiRequest, response, orgId);++ expect(response.statusCode).toBe(200);+ expect(response.body.apiKeys.map((key) => key.id)).toContain(visibleKey.id);+ expect(response.body.apiKeys.map((key) => key.id)).not.toContain(+ inAppAgentKey.id,+ );+ expect(response.body.apiKeys.map((key) => key.note)).not.toContain(+ "Hidden org in-app agent key",+ );+ });++ it("does not delete project in-app agent keys via admin API handler", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ isInAppAgentKey: true,+ });++ const response = createMockResponse();+ await handleDeleteProjectApiKey(+ {} as NextApiRequest,+ response,+ projectId,+ inAppAgentKey.id,+ orgId,+ );++ expect(response.statusCode).toBe(404);+ await expect(+ prisma.apiKey.findUniqueOrThrow({ where: { id: inAppAgentKey.id } }),+ ).resolves.toBeDefined();+ });++ it("does not delete organization in-app agent keys via admin API handler", async () => {+ const { orgId } = await createOrgProjectAndApiKey();+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: orgId,+ scope: "ORGANIZATION",+ isInAppAgentKey: true,+ });++ const response = createMockResponse();+ await handleDeleteOrganizationApiKey(+ {} as NextApiRequest,+ response,+ orgId,+ inAppAgentKey.id,+ );++ expect(response.statusCode).toBe(404);+ await expect(+ prisma.apiKey.findUniqueOrThrow({ where: { id: inAppAgentKey.id } }),+ ).resolves.toBeDefined();+ });+});diff --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.tsnew file mode 100644index 0000000000..db1c9fba09--- /dev/null+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -0,0 +1,74 @@+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { prisma } from "@langfuse/shared/src/db";+import {+ createAndAddApiKeysToDb,+ createBasicAuthHeader,+ createOrgProjectAndApiKey,+} from "@langfuse/shared/src/server";+import type { NextApiRequest, NextApiResponse } from "next";+import { createMocks } from "node-mocks-http";+import { z } from "zod";++describe("in-app agent public API route auth", () => {+ async function createInAppAgentAuthHeader() {+ const { projectId } = await createOrgProjectAndApiKey();+ const apiKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ isInAppAgentKey: true,+ });++ return createBasicAuthHeader(apiKey.publicKey, apiKey.secretKey);+ }++ async function callRoute(params: { allowInAppAgentKey?: boolean }) {+ const handler = createAuthedProjectAPIRoute({+ name: "Test Route",+ ...(params.allowInAppAgentKey === undefined+ ? {}+ : { allowInAppAgentKey: params.allowInAppAgentKey }),+ querySchema: z.object({}),+ responseSchema: z.object({ ok: z.literal(true) }),+ fn: async () => ({ ok: true as const }),+ });+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ headers: {+ authorization: await createInAppAgentAuthHeader(),+ },+ query: {},+ });++ await handler(req, res);++ return res;+ }++ it("rejects in-app agent keys when allowInAppAgentKey is omitted", async () => {+ const res = await callRoute({});++ expect(res.statusCode).toBe(401);+ expect(res._getJSONData()).toEqual({+ message:+ "Access denied - in-app agent keys are not allowed for this endpoint",+ });+ });++ it("rejects in-app agent keys when allowInAppAgentKey is false", async () => {+ const res = await callRoute({ allowInAppAgentKey: false });++ expect(res.statusCode).toBe(401);+ expect(res._getJSONData()).toEqual({+ message:+ "Access denied - in-app agent keys are not allowed for this endpoint",+ });+ });++ it("allows in-app agent keys when allowInAppAgentKey is true", async () => {+ const res = await callRoute({ allowInAppAgentKey: true });++ expect(res.statusCode).toBe(200);+ expect(res._getJSONData()).toEqual({ ok: true });+ });+});diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex 27b0c51db5..564d5d951d 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -20,9 +20,12 @@ import { createEvent, createEventsCh } from "@langfuse/shared/src/server";import {createMcpTestSetup,createPromptInDb,+ mockServerContext,verifyToolAnnotations,} from "./mcp-helpers";import { env } from "@/src/env.mjs";+import "@/src/features/mcp/server/bootstrap";+import { toolRegistry } from "@/src/features/mcp/server/registry";// Import MCP tool handlers directlyimport {@@ -62,6 +65,8 @@ const maybeEventsTable =env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"? describe: describe.skip;+const maybeEventsTableIt =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true" ? it : it.skip;const createObservationEvent = (params: {projectId: string;@@ -118,6 +123,17 @@ describe("MCP Read Tools", () => {});});+ maybeEventsTableIt("should be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(+ getObservationFieldSchemaTool.name,+ context,+ ),+ ).resolves.toBeDefined();+ });+it("should return the observation projection field schema", async () => {const { context } = await createMcpTestSetup();@@ -176,6 +192,17 @@ describe("MCP Read Tools", () => {});});+ maybeEventsTableIt("should be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(+ getObservationFilterSchemaTool.name,+ context,+ ),+ ).resolves.toBeDefined();+ });+it("should return public-compatible observation filter schema", async () => {const { context } = await createMcpTestSetup();@@ -239,6 +266,14 @@ describe("MCP Read Tools", () => {verifyToolAnnotations(listObservationsTool, { readOnlyHint: true });});+ it("should be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(listObservationsTool.name, context),+ ).resolves.toBeDefined();+ });+it("should expose object-shaped advanced filters in the tool schema", () => {const filterSchema = listObservationsTool.inputSchema.properties.filter as@@ -344,6 +379,25 @@ describe("MCP Read Tools", () => {expect(result.meta).toBeDefined();});+ it("should list observations with an in-app agent context", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const traceId = randomUUID();+ const observation = createObservationEvent({+ projectId,+ traceId,+ name: `mcp-list-in-app-agent-${nanoid()}`,+ });++ await createEventsCh([observation]);++ const result = (await handleListObservations(+ { traceId, fields: ["id"], limit: 100 },+ { ...context, isInAppAgentKey: true },+ )) as { data: Array<{ id: string }> };++ expect(result.data.map((item) => item.id)).toContain(observation.id);+ });+it("should project only requested fields", async () => {const { context, projectId } = await createMcpTestSetup();const traceId = randomUUID();@@ -759,6 +813,14 @@ describe("MCP Read Tools", () => {verifyToolAnnotations(getObservationTool, { readOnlyHint: true });});+ it("should be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(getObservationTool.name, context),+ ).resolves.toBeDefined();+ });+it("should fetch a single observation by id with compact default projection", async () => {const { context, projectId } = await createMcpTestSetup();const observation = createObservationEvent({@@ -786,6 +848,23 @@ describe("MCP Read Tools", () => {expect(result.metadata).toBeUndefined();});+ it("should fetch an observation with an in-app agent context", async () => {+ const { context, projectId } = await createMcpTestSetup();+ const observation = createObservationEvent({+ projectId,+ name: `mcp-get-in-app-agent-${nanoid()}`,+ });++ await createEventsCh([observation]);++ const result = (await handleGetObservation(+ { observationId: observation.id, fields: ["id"] },+ { ...context, isInAppAgentKey: true },+ )) as Record<string, unknown>;++ expect(result).toEqual({ id: observation.id });+ });+it("should return requested fields for a single observation", async () => {const { context, projectId } = await createMcpTestSetup();const observation = createObservationEvent({@@ -839,6 +918,17 @@ describe("MCP Read Tools", () => {});});+ it("should be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(+ getObservationFilterValuesTool.name,+ context,+ ),+ ).resolves.toBeDefined();+ });+it("should return values for a dynamic filter column", async () => {const { context, projectId } = await createMcpTestSetup();const uniqueModel = `mcp-model-${nanoid()}`;@@ -991,6 +1081,14 @@ describe("MCP Read Tools", () => {verifyToolAnnotations(getPromptTool, { readOnlyHint: true });});+ it("should not be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(getPromptTool.name, context),+ ).resolves.toBeUndefined();+ });+it("should fetch prompt by name only (defaults to production label)", async () => {const { context, projectId } = await createMcpTestSetup();const promptName = `test-prompt-${nanoid()}`;@@ -1230,6 +1328,14 @@ describe("MCP Read Tools", () => {verifyToolAnnotations(listPromptsTool, { readOnlyHint: true });});+ it("should not be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(listPromptsTool.name, context),+ ).resolves.toBeUndefined();+ });+it("should list all prompts for project", async () => {const { context, projectId } = await createMcpTestSetup();@@ -1601,6 +1707,14 @@ describe("MCP Read Tools", () => {verifyToolAnnotations(getPromptUnresolvedTool, { readOnlyHint: true });});+ it("should not be available to in-app agent keys", async () => {+ const context = mockServerContext({ isInAppAgentKey: true });++ await expect(+ toolRegistry.getEnabledTool(getPromptUnresolvedTool.name, context),+ ).resolves.toBeUndefined();+ });+it("should fetch prompt without resolving dependencies (by name only)", async () => {const { context, projectId } = await createMcpTestSetup();const promptName = `test-prompt-unresolved-${nanoid()}`;diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex cd67172911..ca4927f198 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -3,6 +3,7 @@ import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { TRPCError } from "@trpc/server";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server";describe("organization API keys trpc", () => {const organizationId = "seed-org-id";@@ -121,6 +122,25 @@ describe("organization API keys trpc", () => {expect(newKey?.displaySecretKey).toBeDefined();});+ it("filters in-app agent API keys", async () => {+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: organizationId,+ scope: "ORGANIZATION",+ note: "In-app agent key hidden from org UI",+ isInAppAgentKey: true,+ });++ const apiKeys = await ownerCaller.organizationApiKeys.byOrganizationId({+ orgId: organizationId,+ });++ expect(apiKeys.map((key) => key.id)).not.toContain(inAppAgentKey.id);+ expect(apiKeys.map((key) => key.note)).not.toContain(+ "In-app agent key hidden from org UI",+ );+ });+it("regular member cannot fetch organization API keys", async () => {await expect(memberCaller.organizationApiKeys.byOrganizationId({@@ -212,6 +232,29 @@ describe("organization API keys trpc", () => {expect(updatedKey?.note).toBe("Updated Note");});+ it("does not update in-app agent API keys", async () => {+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: organizationId,+ scope: "ORGANIZATION",+ note: "Original in-app agent note",+ isInAppAgentKey: true,+ });++ await expect(+ ownerCaller.organizationApiKeys.updateNote({+ orgId: organizationId,+ keyId: inAppAgentKey.id,+ note: "Updated in-app agent note",+ }),+ ).rejects.toThrow();++ const persistedKey = await prisma.apiKey.findUniqueOrThrow({+ where: { id: inAppAgentKey.id },+ });+ expect(persistedKey.note).toBe("Original in-app agent note");+ });+it("regular member cannot update API key note", async () => {// Create a key as ownerconst apiKeyResult = await ownerCaller.organizationApiKeys.create({@@ -270,6 +313,26 @@ describe("organization API keys trpc", () => {expect(deletedKey).toBeUndefined();});+ it("does not delete in-app agent API keys", async () => {+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: organizationId,+ scope: "ORGANIZATION",+ isInAppAgentKey: true,+ });++ await expect(+ ownerCaller.organizationApiKeys.delete({+ orgId: organizationId,+ id: inAppAgentKey.id,+ }),+ ).resolves.toBe(false);++ await expect(+ prisma.apiKey.findUniqueOrThrow({ where: { id: inAppAgentKey.id } }),+ ).resolves.toBeDefined();+ });+it("regular member cannot delete API key", async () => {// Create a key as ownerconst apiKeyResult = await ownerCaller.organizationApiKeys.create({diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.tsnew file mode 100644index 0000000000..9c354c873a--- /dev/null+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts@@ -0,0 +1,123 @@+import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ createAndAddApiKeysToDb,+ createOrgProjectAndApiKey,+} from "@langfuse/shared/src/server";++describe("project API keys trpc", () => {+ async function createProjectCaller() {+ const { projectId, orgId } = await createOrgProjectAndApiKey();++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: orgId,+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: false,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ return { caller, projectId };+ }++ describe("projectApiKeys.byProjectId", () => {+ it("filters in-app agent API keys", async () => {+ const { caller, projectId } = await createProjectCaller();++ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ note: "In-app agent key hidden from project UI",+ isInAppAgentKey: true,+ });++ const apiKeys = await caller.projectApiKeys.byProjectId({ projectId });++ expect(apiKeys.map((key) => key.id)).not.toContain(inAppAgentKey.id);+ expect(apiKeys.map((key) => key.note)).not.toContain(+ "In-app agent key hidden from project UI",+ );+ });+ });++ describe("projectApiKeys.updateNote", () => {+ it("does not update in-app agent API keys", async () => {+ const { caller, projectId } = await createProjectCaller();+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ note: "Original in-app agent note",+ isInAppAgentKey: true,+ });++ await expect(+ caller.projectApiKeys.updateNote({+ projectId,+ keyId: inAppAgentKey.id,+ note: "Updated in-app agent note",+ }),+ ).rejects.toThrow();++ const persistedKey = await prisma.apiKey.findUniqueOrThrow({+ where: { id: inAppAgentKey.id },+ });+ expect(persistedKey.note).toBe("Original in-app agent note");+ });+ });++ describe("projectApiKeys.delete", () => {+ it("does not delete in-app agent API keys", async () => {+ const { caller, projectId } = await createProjectCaller();+ const inAppAgentKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ isInAppAgentKey: true,+ });++ await expect(+ caller.projectApiKeys.delete({+ projectId,+ id: inAppAgentKey.id,+ }),+ ).resolves.toBe(false);++ await expect(+ prisma.apiKey.findUniqueOrThrow({ where: { id: inAppAgentKey.id } }),+ ).resolves.toBeDefined();+ });+ });+});diff --git a/web/src/ee/features/admin-api/server/organizations/apiKeys/apiKeyById.ts b/web/src/ee/features/admin-api/server/organizations/apiKeys/apiKeyById.tsindex dbf7df9ec9..9e222a1eed 100644--- a/web/src/ee/features/admin-api/server/organizations/apiKeys/apiKeyById.ts+++ b/web/src/ee/features/admin-api/server/organizations/apiKeys/apiKeyById.ts@@ -31,6 +31,7 @@ export async function handleDeleteApiKey(id: apiKeyId,orgId: organizationId,scope: "ORGANIZATION",+ isInAppAgentKey: false,},});diff --git a/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts b/web/src/ee/features/admin-api/server/organizations/apiKeys/index.tsindex aee00b5a6b..2b8c05beeb 100644--- a/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts+++ b/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts@@ -25,6 +25,7 @@ export async function handleGetApiKeys(where: {orgId: organizationId,scope: "ORGANIZATION",+ isInAppAgentKey: false,},select: {id: true,diff --git a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.tsindex 97a30bba51..1c83142d19 100644--- a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts+++ b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts@@ -32,6 +32,7 @@ export async function handleDeleteApiKey(id: apiKeyId,projectId,scope: "PROJECT",+ isInAppAgentKey: false,},});diff --git a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.tsindex a4110535ee..a15f32d392 100644--- a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts+++ b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts@@ -25,6 +25,7 @@ export async function handleGetApiKeys(where: {projectId,scope: "PROJECT",+ isInAppAgentKey: false,},select: {id: true,diff --git a/web/src/features/mcp/features/observations/index.ts b/web/src/features/mcp/features/observations/index.tsindex 9880d69a79..cc9a27d71e 100644--- a/web/src/features/mcp/features/observations/index.ts+++ b/web/src/features/mcp/features/observations/index.ts@@ -29,22 +29,27 @@ 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_ENABLE_EVENTS_TABLE_V2_APIS === "true",diff --git a/web/src/features/mcp/server/registry.ts b/web/src/features/mcp/server/registry.tsindex 63ad2f27e9..1f3f7351a8 100644--- a/web/src/features/mcp/server/registry.ts+++ b/web/src/features/mcp/server/registry.ts@@ -26,6 +26,9 @@ export interface RegisteredTool {/** Tool handler function - accepts any input type */handler: ToolHandler<any>;++ /** Whether in-app agent API keys may discover and call this tool. */+ allowInAppAgentKey?: boolean;}/**@@ -125,6 +128,10 @@ class ToolRegistry {// Add all tools from enabled featurefor (const tool of feature.tools) {+ if (!this.canUseTool(tool, context)) {+ continue;+ }+definitions.push(tool.definition);}}@@ -156,6 +163,10 @@ class ToolRegistry {const feature = this.getFeatureForTool(name);if (!feature) return undefined;+ if (!this.canUseTool(tool, context)) {+ return undefined;+ }+if (feature.isEnabled && !(await feature.isEnabled(context))) {return undefined;}@@ -163,6 +174,14 @@ class ToolRegistry {return tool;}+ private canUseTool(tool: RegisteredTool, context: ServerContext): boolean {+ if (context.isInAppAgentKey === true && tool.allowInAppAgentKey !== true) {+ return false;+ }++ return true;+ }+/*** Get feature name for a tool (for error messages)*diff --git a/web/src/features/mcp/types.ts b/web/src/features/mcp/types.tsindex 39268b35c7..08a9fe45b9 100644--- a/web/src/features/mcp/types.ts+++ b/web/src/features/mcp/types.ts@@ -48,4 +48,7 @@ export interface ServerContext {/** Public key used for authentication */publicKey: string;++ /** Whether the authenticated API key is scoped to the in-app agent. */+ isInAppAgentKey?: boolean;}diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 3127d60fac..babc850310 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -26,6 +26,10 @@ import { API_KEY_NON_EXISTENT } from "@langfuse/shared/src/server";import { type z } from "zod";import { CloudConfigSchema, isPlan } from "@langfuse/shared";+type VerifyAuthHeaderOptions = {+ allowInAppAgentKey?: boolean;+};+export class ApiAuthService {prisma: PrismaClient;redis: Redis | Cluster | null;@@ -85,6 +89,7 @@ export class ApiAuthService {async verifyAuthHeaderAndReturnScope(authHeader: string | undefined,+ options: VerifyAuthHeaderOptions = {},): Promise<AuthHeaderVerificationResult> {const result: AuthHeaderVerificationResult = await instrumentAsync({ name: "api-auth-verify" },@@ -183,10 +188,12 @@ export class ApiAuthService {);const accessLevel =- finalApiKey.scope === "ORGANIZATION" ? "organization" : "project";+ finalApiKey.scope === "ORGANIZATION"+ ? ("organization" as const)+ : ("project" as const);- return {- validKey: true,+ const result = {+ validKey: true as const,scope: {projectId: finalApiKey.projectId,accessLevel,@@ -197,8 +204,11 @@ export class ApiAuthService {scope: finalApiKey.scope,publicKey,isIngestionSuspended: finalApiKey.isIngestionSuspended,+ isInAppAgentKey: finalApiKey.isInAppAgentKey,},};++ return result;}// Bearer auth, limited scope, only needs public keyif (authHeader.startsWith("Bearer ")) {@@ -226,21 +236,24 @@ export class ApiAuthService {span,);- return {- validKey: true,+ const result = {+ validKey: true as const,scope: {projectId: dbKey.projectId,- accessLevel: "scores",+ accessLevel: "scores" as const,orgId,plan,rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],apiKeyId: dbKey.id,scope: dbKey.scope,publicKey,+ isInAppAgentKey: dbKey.isInAppAgentKey,isIngestionSuspended:cloudFreeTierUsageThresholdState === "BLOCKED",},};++ return result;}} catch (error: unknown) {logger.info(@@ -266,6 +279,18 @@ export class ApiAuthService {},);+ if (+ result.validKey &&+ result.scope.isInAppAgentKey === true &&+ options.allowInAppAgentKey !== true+ ) {+ return {+ validKey: false,+ error:+ "Access denied - in-app agent keys are not allowed for this endpoint",+ };+ }+return result;}diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex 55bfbf2c37..53be5d953f 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -59,6 +59,11 @@ export type AuthedProjectAPIRouteConfig<* (which receives accessLevel "scores").*/allowedAccessLevels?: RouteAccessLevel[];+ /**+ * Whether in-app agent API keys can call this route without additional confirmation. Defaults to false.+ * Only set this to true on non-mutating (GET) routes that should be callable by the in-app agent.+ */+ allowInAppAgentKey?: boolean;fn: (params: {query: z.infer<TQuery>;body: z.infer<TBody>;@@ -85,6 +90,7 @@ export type AuthedProjectAPIRouteConfig<async function verifyApiKeyAuth(authHeader: string | undefined,allowedAccessLevels: RouteAccessLevel[] = ["project"],+ allowInAppAgentKey = false,): Promise<AuthHeaderValidVerificationResult & {scope: { projectId: string; accessLevel: RouteAccessLevel };@@ -93,7 +99,7 @@ async function verifyApiKeyAuth(const regularAuth = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(authHeader);+ ).verifyAuthHeaderAndReturnScope(authHeader, { allowInAppAgentKey });if (!regularAuth.validKey) {throw { status: 401, message: regularAuth.error };@@ -223,6 +229,7 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest): Promise<apiKeyId: "ADMIN_API_KEY", // Special identifier for audit loggingpublicKey: "ADMIN_API_KEY",isIngestionSuspended: false,+ isInAppAgentKey: false,},};}@@ -244,6 +251,7 @@ export async function verifyAuth(req: NextApiRequest,isAdminApiKeyAuthAllowed: boolean,allowedAccessLevels: RouteAccessLevel[] = ["project"],+ allowInAppAgentKey = false,): Promise<AuthHeaderValidVerificationResult & {scope: { projectId: string; accessLevel: RouteAccessLevel };@@ -260,11 +268,16 @@ export async function verifyAuth(return await verifyApiKeyAuth(req.headers.authorization,allowedAccessLevels,+ allowInAppAgentKey,);}// Only regular API key auth is allowed- return await verifyApiKeyAuth(req.headers.authorization, allowedAccessLevels);+ return await verifyApiKeyAuth(+ req.headers.authorization,+ allowedAccessLevels,+ allowInAppAgentKey,+ );}export const createAuthedProjectAPIRoute = <@@ -285,6 +298,7 @@ export const createAuthedProjectAPIRoute = <req,routeConfig.isAdminApiKeyAuthAllowed || false,routeConfig.allowedAccessLevels || ["project"],+ routeConfig.allowInAppAgentKey === true,);} catch (error: any) {const statusCode = error.status || 401;diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.tsindex d130c96906..1f155d0c02 100644--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts@@ -27,6 +27,7 @@ export const organizationApiKeysRouter = createTRPCRouter({where: {orgId: input.orgId,scope: "ORGANIZATION",+ isInAppAgentKey: false,},select: {id: true,@@ -87,6 +88,14 @@ export const organizationApiKeysRouter = createTRPCRouter({scope: "organization:CRUD_apiKeys",});+ await ctx.prisma.apiKey.findFirstOrThrow({+ where: {+ id: input.keyId,+ orgId: input.orgId,+ isInAppAgentKey: false,+ },+ });+await auditLog({session: ctx.session,resourceType: "apiKey",@@ -98,6 +107,7 @@ export const organizationApiKeysRouter = createTRPCRouter({where: {id: input.keyId,orgId: input.orgId,+ isInAppAgentKey: false,},data: {note: input.note,@@ -120,6 +130,16 @@ export const organizationApiKeysRouter = createTRPCRouter({organizationId: input.orgId,scope: "organization:CRUD_apiKeys",});+ const apiKey = await ctx.prisma.apiKey.findFirstOrThrow({+ where: {+ id: input.id,+ orgId: input.orgId,+ scope: "ORGANIZATION",+ },+ });++ if (apiKey.isInAppAgentKey) return false;+await auditLog({session: ctx.session,resourceType: "apiKey",diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.tsindex 58dd7653eb..5e8cce04c4 100644--- a/web/src/features/public-api/server/projectApiKeyRouter.ts+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts@@ -28,6 +28,7 @@ export const projectApiKeysRouter = createTRPCRouter({where: {projectId: input.projectId,scope: "PROJECT",+ isInAppAgentKey: false,},select: {id: true,@@ -88,6 +89,14 @@ export const projectApiKeysRouter = createTRPCRouter({scope: "apiKeys:CUD",});+ await ctx.prisma.apiKey.findFirstOrThrow({+ where: {+ id: input.keyId,+ projectId: input.projectId,+ isInAppAgentKey: false,+ },+ });+await auditLog({session: ctx.session,resourceType: "apiKey",@@ -99,6 +108,7 @@ export const projectApiKeysRouter = createTRPCRouter({where: {id: input.keyId,projectId: input.projectId,+ isInAppAgentKey: false,},data: {note: input.note,@@ -121,6 +131,16 @@ export const projectApiKeysRouter = createTRPCRouter({projectId: input.projectId,scope: "apiKeys:CUD",});+ const apiKey = await ctx.prisma.apiKey.findFirstOrThrow({+ where: {+ id: input.id,+ projectId: input.projectId,+ scope: "PROJECT",+ },+ });++ if (apiKey.isInAppAgentKey) return false;+await auditLog({session: ctx.session,resourceType: "apiKey",diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.tsindex 7c89145c13..9b9aaaf0e2 100644--- a/web/src/pages/api/public/mcp/index.ts+++ b/web/src/pages/api/public/mcp/index.ts@@ -80,7 +80,9 @@ export default async function handler(const authCheck = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization, {+ allowInAppAgentKey: true,+ });if (!authCheck.validKey) {throw new UnauthorizedError(authCheck.error);@@ -122,6 +124,7 @@ export default async function handler(apiKeyId: authCheck.scope.apiKeyId,accessLevel: "project",publicKey: authCheck.scope.publicKey,+ isInAppAgentKey: authCheck.scope.isInAppAgentKey === true,};logger.info("MCP request authenticated", {diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].tsindex 977f42e754..c5d4d7088a 100644--- a/web/src/pages/api/public/observations/[observationId].ts+++ b/web/src/pages/api/public/observations/[observationId].ts@@ -21,6 +21,7 @@ export default withMiddlewares({GET: createAuthedProjectAPIRoute({name: "Get Observation",+ allowInAppAgentKey: true,querySchema: GetObservationV1Query,responseSchema: GetObservationV1Response,fn: async ({ query, auth }) => {diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex a5e6b0b309..103f572c2a 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -25,6 +25,7 @@ export default withMiddlewares({GET: createAuthedProjectAPIRoute({name: "Get Observations",+ allowInAppAgentKey: true,querySchema: GetObservationsV1Query,responseSchema: GetObservationsV1Response,fn: async ({ query, auth }) => {diff --git a/web/src/pages/api/public/v2/observations/index.ts b/web/src/pages/api/public/v2/observations/index.tsindex e100cfa288..cf81801756 100644--- a/web/src/pages/api/public/v2/observations/index.ts+++ b/web/src/pages/api/public/v2/observations/index.ts@@ -14,6 +14,7 @@ import {export default withMiddlewares({GET: createAuthedProjectAPIRoute({name: "Get Observations V2",+ allowInAppAgentKey: true,querySchema: GetObservationsV2Query,responseSchema: GetObservationsV2Response,fn: async ({ query, auth }) => {