:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): stop exposing project credentials in project tool responses (#103357)
posthog[bot]fe37c9cc5cdc
diff --git a/products/tasks/backend/prompts.py b/products/tasks/backend/prompts.pyindex 2e4d691eb2be..a73d61e1ac5e 100644--- a/products/tasks/backend/prompts.py+++ b/products/tasks/backend/prompts.py@@ -120,8 +120,8 @@ git show --stat HEAD | grep -E '\.[^/]+/skills/' && echo "FAIL: skills files com3. If you can't configure them automatically, do not commit anything in this step - instead writedown in your notes which variables are needed and what values they must be set to,for use in the PR description in Step 4.-4. You should know the project API token from the PostHog MCP server context. If you don't have- it, run the `projects-get` MCP tool to fetch it.+4. Run the `project-get` MCP tool to fetch the project API token. It is the only tool that+ returns the token; the session context and `projects-get` leave it out.**Checkpoint:** exactly one of the following is true:diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 2f5ed0cc8700..0f45ed71941f 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -387,7 +387,9 @@ tools:idempotent: truetitle: Get projectdescription: |- Retrieve a project and its settings. Omit the ID to get the caller's active project.+ Retrieve a project and its settings. Omit the ID to get the caller's active project. This is the one tool+ that returns the project API token, which is safe to put in client-side code. Project listing, project+ updates and the session context leave it out, so ask for a single project when you need the token.param_overrides:id:description: Project ID. If omitted, returns the caller's active project.@@ -399,6 +401,7 @@ tools:- secret_api_token- secret_api_token_backup- live_events_token+ - heatmaps_screenshot_secret- default_modifiersproject-secret-api-keys-create:operation: project_secret_api_keys_create@@ -456,6 +459,14 @@ tools:id:description: Project ID, or `@current` to target the caller's active project.cast: string-int+ response:+ exclude:+ - api_token+ - secret_api_token+ - secret_api_token_backup+ - live_events_token+ - heatmaps_screenshot_secret+ - default_modifiersprojects-destroy:operation: organizations_projects_destroyenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 256e028b1013..aa0f5747b8fe 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8950,7 +8950,7 @@}},"project-get": {- "description": "Retrieve a project and its settings. Omit the ID to get the caller's active project.",+ "description": "Retrieve a project and its settings. Omit the ID to get the caller's active project. This is the one tool\nthat returns the project API token, which is safe to put in client-side code. Project listing, project\nupdates and the session context leave it out, so ask for a single project when you need the token.","category": "Core","feature": "core","summary": "Get project",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 4eecef330d7c..8b0d590be079 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9480,7 +9480,7 @@}},"project-get": {- "description": "Retrieve a project and its settings. Omit the ID to get the caller's active project.",+ "description": "Retrieve a project and its settings. Omit the ID to get the caller's active project. This is the one tool\nthat returns the project API token, which is safe to put in client-side code. Project listing, project\nupdates and the session context leave it out, so ask for a single project when you need the token.","category": "Core","feature": "core","summary": "Get project",diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex d4242855c4da..06d29d083341 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -92,16 +92,15 @@ export function buildActiveEnvironmentContextPrompt(if (org || project) {const projectName = project?.name ?? 'Unknown'const projectId = project?.id ?? 'unknown'- const projectToken = project?.api_token ?? 'unknown'if (org) {const orgName = org.name ?? 'Unknown'const orgId = org.id ?? 'unknown'lines.push(- `You are currently in project "${projectName}" (id: ${projectId}, token: ${projectToken}) within organization "${orgName}" (id: ${orgId}).`+ `You are currently in project "${projectName}" (id: ${projectId}) within organization "${orgName}" (id: ${orgId}).`)} else {- lines.push(`You are currently in project "${projectName}" (id: ${projectId}, token: ${projectToken}).`)+ lines.push(`You are currently in project "${projectName}" (id: ${projectId}).`)}}if (regionalBaseUrl) {diff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.tsindex 314a651147fa..f8e3b6b40e19 100644--- a/services/mcp/src/tools/generated/core.ts+++ b/services/mcp/src/tools/generated/core.ts@@ -253,6 +253,7 @@ const projectGet = (): ToolBase<ReturnType<typeof ProjectGetSchema>, Schemas.Pro'secret_api_token','secret_api_token_backup','live_events_token',+ 'heatmaps_screenshot_secret','default_modifiers',]) as typeof resultreturn filtered@@ -497,7 +498,15 @@ const projectSettingsUpdate = (): ToolBase<path: `/api/organizations/${encodeURIComponent(String(orgId))}/projects/${encodeURIComponent(String(params.id))}/`,body,})- return result+ const filtered = omitResponseFields(result, [+ 'api_token',+ 'secret_api_token',+ 'secret_api_token_backup',+ 'live_events_token',+ 'heatmaps_screenshot_secret',+ 'default_modifiers',+ ]) as typeof result+ return filtered},})diff --git a/services/mcp/src/tools/projects/getProjects.ts b/services/mcp/src/tools/projects/getProjects.tsindex f627a8aa4cf5..e225faad3ce6 100644--- a/services/mcp/src/tools/projects/getProjects.ts+++ b/services/mcp/src/tools/projects/getProjects.ts@@ -1,12 +1,24 @@import type { Schemas } from '@/api/generated'import { ProjectGetAllSchema } from '@/schema/tool-inputs'+import { omitResponseFields } from '@/tools/tool-utils'import type { Context, ToolBase } from '@/tools/types'const schema = ProjectGetAllSchema-export const getProjectsHandler: ToolBase<typeof schema, Schemas.ProjectBackwardCompat[]>['handler'] = async (- context: Context-) => {+// Credentials never belong in a discovery response; `id` is enough to correlate+// a project. A caller that needs the public token asks `project-get` for one+// project, which is the only tool that still returns it.+const CREDENTIAL_FIELDS = [+ 'api_token',+ 'secret_api_token',+ 'secret_api_token_backup',+ 'live_events_token',+ 'heatmaps_screenshot_secret',+] as const satisfies readonly (keyof Schemas.ProjectBackwardCompat)[]++type PublicProject = Omit<Schemas.ProjectBackwardCompat, (typeof CREDENTIAL_FIELDS)[number]>++export const getProjectsHandler: ToolBase<typeof schema, PublicProject[]>['handler'] = async (context: Context) => {const orgId = await context.stateManager.getOrgID()const projectsResult = await context.api.organizations().projects({ orgId }).list()@@ -15,10 +27,12 @@ export const getProjectsHandler: ToolBase<typeof schema, Schemas.ProjectBackwardthrow new Error(`Failed to get projects: ${projectsResult.error.message}`)}- return projectsResult.data+ return projectsResult.data.map(+ (project: Schemas.ProjectBackwardCompat) => omitResponseFields(project, [...CREDENTIAL_FIELDS]) as PublicProject+ )}-const tool = (): ToolBase<typeof schema, Schemas.ProjectBackwardCompat[]> => ({+const tool = (): ToolBase<typeof schema, PublicProject[]> => ({name: 'projects-get',schema,handler: getProjectsHandler,diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex eb06d8062ed3..f9afebc83054 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -321,16 +321,21 @@ describe('buildActiveEnvironmentContextPrompt', () => {it('renders the full project + org line when both are present', () => {const result = buildActiveEnvironmentContextPrompt(user, org, project)expect(result).toContain(- 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).'+ 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).')})+ it('never leaks the project API token into the environment prompt', () => {+ const result = buildActiveEnvironmentContextPrompt(user, org, project)+ expect(result).not.toContain('token_1')+ })+it('omits the organization clause when org is undefined (scope-gated path)', () => {// Project-scoped personal API keys lack `organization:read`, so the org// fetch is skipped. The line drops the "within organization …" tail// rather than rendering a fabricated "Unknown" placeholder.const result = buildActiveEnvironmentContextPrompt(user, undefined, project)- expect(result).toContain('You are currently in project "My App" (id: 1, token: token_1).')+ expect(result).toContain('You are currently in project "My App" (id: 1).')expect(result).not.toContain('within organization')expect(result).not.toContain('Unknown')expect(result).not.toContain('unknown')@@ -348,9 +353,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {// Sits right after the project/org context line.const lines = (result ?? '').split('\n')expect(lines.indexOf('Base URL: us.posthog.com — add /project/1 for project-scoped paths.')).toBe(- lines.indexOf(- 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).'- ) + 1+ lines.indexOf('You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).') + 1)})@@ -385,7 +388,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {// The org branch is unchanged — only the no-org branch was added.const result = buildActiveEnvironmentContextPrompt(user, org, undefined)expect(result).toContain(- 'You are currently in project "Unknown" (id: unknown, token: unknown) within organization "Acme" (id: org_1).'+ 'You are currently in project "Unknown" (id: unknown) within organization "Acme" (id: org_1).')})diff --git a/services/mcp/tests/unit/projects-credentials.test.ts b/services/mcp/tests/unit/projects-credentials.test.tsnew file mode 100644index 000000000000..d6528745845d--- /dev/null+++ b/services/mcp/tests/unit/projects-credentials.test.ts@@ -0,0 +1,100 @@+import fs from 'node:fs'+import path from 'node:path'++import { describe, expect, it, vi } from 'vitest'+import { parse as parseYaml } from 'yaml'++import { GENERATED_TOOL_MAP } from '@/tools/generated'+import getProjectsTool from '@/tools/projects/getProjects'+import type { Context } from '@/tools/types'++const ORG_ID = 'org-1'+const PROJECT_ID = 42++// `project-get` is the surface whose exclude list is reviewed when a secret is+// added to the project serializer. Deriving the fixture from it means a new+// secret there also has to be dropped by the other project surfaces, instead of+// leaking until someone notices the lists drifted apart.+const coreDefinitions = parseYaml(fs.readFileSync(path.resolve(__dirname, '../../definitions/core.yaml'), 'utf-8'))+const SECRET_FIELDS: string[] = (coreDefinitions.tools['project-get'].response.exclude as string[]).filter(+ (field) => field.includes('token') || field.includes('secret')+)++const secretValue = (field: string): string => `SECRET_VALUE_${field}`+const API_TOKEN = 'phc_public_write_key'++const PROJECT_WITH_CREDENTIALS = {+ id: PROJECT_ID,+ name: 'My project',+ organization: ORG_ID,+ api_token: API_TOKEN,+ ...Object.fromEntries(SECRET_FIELDS.map((field) => [field, secretValue(field)])),+}++function expectNoSecrets(payload: unknown): void {+ const serialized = JSON.stringify(payload)+ for (const field of SECRET_FIELDS) {+ expect(serialized).not.toContain(secretValue(field))+ }+}++describe('project tools do not expose credentials', () => {+ it('derives a non-empty secret set that excludes the public token', () => {+ expect(SECRET_FIELDS).toContain('secret_api_token')+ expect(SECRET_FIELDS).not.toContain('api_token')+ })++ it('projects-get strips secrets and the API token from every listed project', async () => {+ const context = {+ stateManager: { getOrgID: vi.fn().mockResolvedValue(ORG_ID) },+ api: {+ organizations: () => ({+ projects: () => ({+ list: vi.fn().mockResolvedValue({ success: true, data: [PROJECT_WITH_CREDENTIALS] }),+ }),+ }),+ },+ } as unknown as Context++ const projects = await getProjectsTool().handler(context, {})++ expect(projects).toHaveLength(1)+ expect(projects[0]!.id).toBe(PROJECT_ID)+ expectNoSecrets(projects)+ expect(JSON.stringify(projects)).not.toContain(API_TOKEN)+ })++ it('project-get strips secrets but keeps the API token callers ask it for', async () => {+ const context = {+ stateManager: {+ getOrgID: vi.fn().mockResolvedValue(ORG_ID),+ getProjectId: vi.fn().mockResolvedValue(PROJECT_ID),+ },+ api: { request: vi.fn().mockResolvedValue(PROJECT_WITH_CREDENTIALS) },+ } as unknown as Context++ const project = await GENERATED_TOOL_MAP['project-get']!().handler(context, {})++ expect((project as { id: number }).id).toBe(PROJECT_ID)+ expectNoSecrets(project)+ // The setup wizard in products/tasks reads the public token from here;+ // it is the only tool that still returns it.+ expect((project as { api_token: string }).api_token).toBe(API_TOKEN)+ })++ it('project-settings-update strips secrets and the API token from the updated project', async () => {+ const context = {+ stateManager: { getOrgID: vi.fn().mockResolvedValue(ORG_ID) },+ api: { request: vi.fn().mockResolvedValue(PROJECT_WITH_CREDENTIALS) },+ } as unknown as Context++ const project = await GENERATED_TOOL_MAP['project-settings-update']!().handler(context, {+ id: PROJECT_ID,+ name: 'Renamed project',+ })++ expect((project as { id: number }).id).toBe(PROJECT_ID)+ expectNoSecrets(project)+ expect(JSON.stringify(project)).not.toContain(API_TOKEN)+ })+})diff --git a/services/mcp/tests/unit/switch-project.test.ts b/services/mcp/tests/unit/switch-project.test.tsindex 5f88dac12201..e3b2b8adbfbc 100644--- a/services/mcp/tests/unit/switch-project.test.ts+++ b/services/mcp/tests/unit/switch-project.test.ts@@ -87,6 +87,18 @@ describe('switch-project', () => {expect(setSessionActiveContext).toHaveBeenCalledWith({ projectId: '42', orgId: ACTIVE_ORG })})+ it('never exposes the project API token in the switch response', async () => {+ const projectGet = vi.fn().mockResolvedValue({+ success: true,+ data: { id: 42, name: 'My project', organization: ACTIVE_ORG, api_token: 'phc_secret_token' },+ })+ const { context } = createMockContext({ projectGet })++ const result = await tool.handler(context, { projectId: 42 })++ expect(result.content[0]!.text).not.toContain('phc_secret_token')+ })+it('syncs the active organization via the shared resolver when the project is in another org', async () => {const projectGet = vi.fn().mockResolvedValue({success: true,