Skip to content

: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.

fix(mcp): sanitize forwarded header values at egress (#80038)

Phil Haackb19b11f5b283
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 6c858c6e485d..6cb7b60db7ef 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -10,7 +10,7 @@ import {
PostHogRateLimitError,
PostHogValidationError,
} from '@/lib/errors'
-import { getSearchParamsFromRecord } from '@/lib/utils.js'
+import { getSearchParamsFromRecord, sanitizeHeaders, sanitizeHeaderValue } from '@/lib/utils.js'
import type {
ApiEventDefinition,
ApiOAuthIntrospection,
@@ -163,34 +163,38 @@ export class ApiClient {
protected async fetch(url: string, options?: RequestInit): Promise<Response> {
const defaultHeaders: HeadersInit = {
Authorization: `Bearer ${this.config.apiToken}`,
- 'User-Agent': getUserAgent({ clientUserAgent: this.config.clientUserAgent }),
- ...(this.config.clientUserAgent
- ? {
- // Forward the originating client's User-Agent as a custom header so the
- // PostHog API can attach it to analytics events for MCP source attribution.
- 'x-posthog-mcp-user-agent': this.config.clientUserAgent,
- }
- : {}),
- // Forward MCP clientInfo fields from the initialize request so the
- // PostHog API can attach them to analytics events.
- ...(this.config.mcpClientName ? { 'x-posthog-mcp-client-name': this.config.mcpClientName } : {}),
- ...(this.config.mcpClientVersion ? { 'x-posthog-mcp-client-version': this.config.mcpClientVersion } : {}),
- ...(this.config.mcpProtocolVersion
- ? { 'x-posthog-mcp-protocol-version': this.config.mcpProtocolVersion }
- : {}),
- ...(this.config.mcpConsumer ? { 'x-posthog-mcp-consumer': this.config.mcpConsumer } : {}),
- ...(this.config.oauthClientName ? { 'x-posthog-mcp-oauth-client-name': this.config.oauthClientName } : {}),
- // Forward MCP session and conversation ids so backend logs and OTLP
- // spans for downstream API hops can correlate with the same MCP context
- // the events carry. This is attribute-based correlation only — we do
- // not forward `traceparent` (the Worker emits no OTLP today), so the
- // Django-rooted span is not a child of any Worker-side span.
- ...(this.config.mcpSessionId ? { 'x-posthog-mcp-session-id': this.config.mcpSessionId } : {}),
- ...(this.config.mcpConversationId
- ? { 'x-posthog-mcp-conversation-id': this.config.mcpConversationId }
- : {}),
- // Forward the sandbox task id so API writes are attributed to the agent's task.
- ...(this.config.taskId ? { 'X-PostHog-Task-Id': this.config.taskId } : {}),
+ // Every value below originates from the MCP client, so it is sanitized here at
+ // assembly rather than trusted to have been sanitized on the boundary it arrived
+ // on. `oauthClientName` in particular is read straight back from the token cache,
+ // which can still hold a name written before the ingest sanitizer covered it. A
+ // character above U+00FF makes the runtime throw converting headers to a
+ // ByteString, failing the API call itself — losing attribution detail is cheaper.
+ // The composed User-Agent stays out of the batch below: sanitizing it whole would
+ // truncate at the value cap and could slice off our own trailing token, so the
+ // client-supplied input is sanitized before composition instead. The other parts
+ // are code constants and an ASCII-only regex match, already header-safe.
+ 'User-Agent': getUserAgent({ clientUserAgent: sanitizeHeaderValue(this.config.clientUserAgent) }),
+ ...sanitizeHeaders({
+ // Forward the originating client's User-Agent as a custom header so the
+ // PostHog API can attach it to analytics events for MCP source attribution.
+ 'x-posthog-mcp-user-agent': this.config.clientUserAgent,
+ // Forward MCP clientInfo fields from the initialize request so the
+ // PostHog API can attach them to analytics events.
+ 'x-posthog-mcp-client-name': this.config.mcpClientName,
+ 'x-posthog-mcp-client-version': this.config.mcpClientVersion,
+ 'x-posthog-mcp-protocol-version': this.config.mcpProtocolVersion,
+ 'x-posthog-mcp-consumer': this.config.mcpConsumer,
+ 'x-posthog-mcp-oauth-client-name': this.config.oauthClientName,
+ // Forward MCP session and conversation ids so backend logs and OTLP
+ // spans for downstream API hops can correlate with the same MCP context
+ // the events carry. This is attribute-based correlation only — we do
+ // not forward `traceparent` (the Worker emits no OTLP today), so the
+ // Django-rooted span is not a child of any Worker-side span.
+ 'x-posthog-mcp-session-id': this.config.mcpSessionId,
+ 'x-posthog-mcp-conversation-id': this.config.mcpConversationId,
+ // Forward the sandbox task id so API writes are attributed to the agent's task.
+ 'X-PostHog-Task-Id': this.config.taskId,
+ }),
'X-PostHog-Client': 'mcp',
}
if (options?.body) {
diff --git a/services/mcp/src/cli/context.ts b/services/mcp/src/cli/context.ts
index effed858f605..c529d385a261 100644
--- a/services/mcp/src/cli/context.ts
+++ b/services/mcp/src/cli/context.ts
@@ -7,6 +7,7 @@ import { buildMCPAnalyticsGroups, buildMCPContextProperties } from '@/lib/postho
import type { AnalyticsEvent } from '@/lib/posthog/analytics'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
+import { sanitizeHeaderValue } from '@/lib/utils'
import type { Context, Env, State } from '@/tools/types'
import type { CliConfig } from './config'
@@ -53,7 +54,7 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {
baseUrl: config.host.replace(/\/+$/, ''),
clientUserAgent: `posthog-cli api`,
mcpClientName: 'posthog-cli',
- mcpClientVersion: process.env.POSTHOG_CLI_VERSION,
+ mcpClientVersion: sanitizeHeaderValue(process.env.POSTHOG_CLI_VERSION),
mcpConsumer: 'posthog-cli',
})
const stateManager = new StateManager(cache, api)
diff --git a/services/mcp/src/lib/utils.ts b/services/mcp/src/lib/utils.ts
index 82c1f756f10b..b04a18a9815b 100644
--- a/services/mcp/src/lib/utils.ts
+++ b/services/mcp/src/lib/utils.ts
@@ -66,6 +66,19 @@ export function sanitizeHeaderValue(value?: string): string | undefined {
return sanitised || undefined
}
+// Sanitize a batch of optional header values, dropping the ones that are absent or that
+// sanitize away to nothing, so the result can be spread straight into a headers object.
+export function sanitizeHeaders(headers: Record<string, string | undefined>): Record<string, string> {
+ const sanitised: Record<string, string> = {}
+ for (const [name, value] of Object.entries(headers)) {
+ const safeValue = sanitizeHeaderValue(value)
+ if (safeValue) {
+ sanitised[name] = safeValue
+ }
+ }
+ return sanitised
+}
+
export type McpMode = 'tools' | 'cli'
// Caller-supplied selection between the tool-based MCP (each PostHog tool registered
diff --git a/services/mcp/tests/unit/api-client-header-safety.test.ts b/services/mcp/tests/unit/api-client-header-safety.test.ts
new file mode 100644
index 000000000000..9444ec12457b
--- /dev/null
+++ b/services/mcp/tests/unit/api-client-header-safety.test.ts
@@ -0,0 +1,56 @@
+import http from 'node:http'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+import { ApiClient } from '@/api/client'
+
+// The forwarded MCP attribution headers carry client-supplied strings (`clientInfo.name`,
+// the OAuth app name, the wrapping consumer), and the runtime converts header values to a
+// ByteString — so a character above U+00FF in any of them throws before the request leaves
+// the process, failing the API call rather than just losing attribution. The OAuth app name
+// reaches the client from the token cache, which no ingest-side sanitizer covers. These
+// tests go through the real `fetch` (the rest of the ApiClient suite stubs it, which
+// structurally cannot catch this) against a throwaway local server.
+describe('ApiClient header safety', () => {
+ let server: http.Server
+ let baseUrl: string
+ let seenHeaders: http.IncomingHttpHeaders = {}
+
+ beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ seenHeaders = req.headers
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ id: 2, name: 'test project' }))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ baseUrl = `http://127.0.0.1:${(server.address() as { port: number }).port}`
+ })
+
+ afterAll(async () => {
+ await new Promise<void>((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())))
+ })
+
+ it('resolves the project when client-supplied names contain characters headers cannot carry', async () => {
+ const client = new ApiClient({
+ apiToken: 'phx_test',
+ baseUrl,
+ clientUserAgent: 'my-agent/1.0',
+ mcpClientName: 'Claude \u{1F389} Code',
+ mcpClientVersion: '1.0.0',
+ mcpConsumer: 'wrapper',
+ oauthClientName: 'Acme — Analytics',
+ })
+
+ const result = await client.projects().get({ projectId: '2' })
+
+ expect(result.success).toBe(true)
+ expect(seenHeaders['x-posthog-mcp-client-name']).toBe('Claude Code')
+ expect(seenHeaders['x-posthog-mcp-oauth-client-name']).toBe('Acme Analytics')
+ expect(seenHeaders['x-posthog-mcp-consumer']).toBe('wrapper')
+ })
+
+ it('confirms the unsanitized value would have been fatal', () => {
+ // Guards the test above from silently passing if header validation ever stops
+ // being enforced in this environment.
+ expect(() => new Headers({ 'x-posthog-mcp-oauth-client-name': 'Acme — Analytics' })).toThrow(/ByteString/)
+ })
+})