: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
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import type { Schemas } from '@/api/generated'
import { getPostHogClient } from '@/lib/posthog'
import { getToolRecoveryHint } from '@/lib/tool-error-hints'
export enum ErrorCode {
INVALID_API_KEY = 'INVALID_API_KEY',
INACTIVE_OAUTH_TOKEN = 'INACTIVE_OAUTH_TOKEN',
}
export class MCPToolError extends Error {
public readonly tool: string
public readonly originalError: unknown
public readonly timestamp: Date
constructor(message: string, tool: string, originalError?: unknown) {
super(message)
this.name = 'MCPToolError'
this.tool = tool
this.originalError = originalError
this.timestamp = new Date()
}
}
export class MCPToolResultError extends Error {
constructor(
message: string,
public readonly errorType: NonNullable<Schemas.MCPToolResponse['error_type']>,
public readonly errorCode?: string
) {
super(message)
this.name = 'MCPToolResultError'
}
}
/**
* Thrown by `StateManager.getProjectId()` when no project can be resolved for
* the current session — neither pinned via header, cached from a prior init,
* nor derivable from the API key's scopes (e.g. an org-scoped key whose org
* has no listable projects). Carries a multi-line message that walks the
* agent through the available recovery tools, plus structured fields so
* detection and formatting can be programmatic.
*/
export class MissingProjectContextError extends Error {
public readonly organizationId: string | undefined
constructor(options: { organizationId?: string | undefined } = {}) {
super(formatMissingProjectContextMessage(options.organizationId))
this.name = 'MissingProjectContextError'
this.organizationId = options.organizationId
}
}
function formatMissingProjectContextMessage(organizationId: string | undefined): string {
const orgScopeLine = organizationId
? '\n\n' +
`The session is currently scoped to organization \`${organizationId}\` but no project has been picked.`
: ''
return (
'No PostHog project is selected for this MCP session, and a default could not be derived from your API key.' +
orgScopeLine +
'\n\n' +
'To pick one (in order of preference):\n' +
'1. Call `projects-get` to list projects you can access, then `switch-project` with the chosen project id.\n' +
'2. If you already know the project id, call `switch-project { projectId: <id> }` directly.\n' +
'3. (For MCP client maintainers) Pin a project at session start by sending the `x-posthog-project-id` header on the initialize request.' +
'\n\n' +
'If `projects-get` returns nothing, call `organizations-get` followed by `switch-organization` to pick a different org first — then retry `projects-get`.'
)
}
/**
* Thrown by `StateManager.getOrgID()` when no organization can be resolved for
* the current session — neither pinned via header, cached from a prior init,
* nor derivable from the API key's scopes or the active project. Throwing
* (rather than returning `undefined`) prevents callers from interpolating
* literal `"undefined"` into URLs like `/api/organizations/undefined/...`.
*/
export class MissingOrganizationContextError extends Error {
constructor() {
super(formatMissingOrganizationContextMessage())
this.name = 'MissingOrganizationContextError'
}
}
function formatMissingOrganizationContextMessage(): string {
return (
'No PostHog organization is selected for this MCP session, and a default could not be derived from your API key.' +
'\n\n' +
'To pick one (in order of preference):\n' +
'1. Call `organizations-get` to list organizations you can access, then `switch-organization` with the chosen organization id.\n' +
'2. (For MCP client maintainers) Pin an organization at session start by sending the `x-posthog-organization-id` header on the initialize request.'
)
}
/**
* Thrown by `switch-project` and `switch-organization` when the request pins the
* context and carries no MCP session id. Nothing records the switch across
* requests, so the next request applies the pin again. Failing here tells the
* agent the truth instead of a success that the next call silently reverts.
*/
export class PinnedContextSwitchError extends Error {
constructor(pinned: { organizationId?: string | undefined; projectId?: string | undefined }) {
super(formatPinnedContextSwitchMessage(pinned))
this.name = 'PinnedContextSwitchError'
}
}
function formatPinnedContextSwitchMessage(pinned: {
organizationId?: string | undefined
projectId?: string | undefined
}): string {
const target = pinned.projectId ? `project \`${pinned.projectId}\`` : `organization \`${pinned.organizationId}\``
return (
`This connection pins ${target} on every request and sends no MCP session id, so a switch cannot persist. ` +
'The next tool call would run against the pinned context again, so the switch was not applied.' +
'\n\n' +
`Keep working in the pinned ${pinned.projectId ? 'project' : 'organization'}, or ask the user to change the pin in the MCP client configuration ` +
'(the `project_id` / `organization_id` URL parameters or the `x-posthog-project-id` / `x-posthog-organization-id` headers).'
)
}
export const SESSION_RESET_REQUIRED_REASON = 'session_reset_required'
/**
* Thrown before any tool runs when an MCP session saved its project and
* organization selection under the store key that held only the session id.
* The server does not trust those values, because any credential can send the
* same session id, and it does not silently start over from the pin or the
* shared token selection either. A new session starts with a clean selection.
*/
export class McpSessionResetRequiredError extends Error {
constructor() {
super(
'This MCP session started before a PostHog MCP server update, and the server cannot restore its project and organization selection. ' +
'No tool ran. Reconnect the PostHog MCP server to start a new session, then try again.'
)
this.name = 'McpSessionResetRequiredError'
}
}
export interface PostHogValidationErrorOptions {
detail: string
attr: string | undefined
code: string | undefined
extra: Record<string, unknown> | undefined
url: string
method: string
}
/**
* Thrown when the PostHog API rejects a request with a `validation_error`
* body. Carries the structured `extra` payload (if any) so tool handlers can
* surface information that doesn't fit in a single `detail` line — for
* example, the HogQL metadata response attached to a failed /query/ call.
*/
export class PostHogValidationError extends Error {
public readonly detail: string
public readonly attr: string | undefined
public readonly code: string | undefined
public readonly extra: Record<string, unknown> | undefined
public readonly url: string
public readonly method: string
constructor(options: PostHogValidationErrorOptions) {
const attr = options.attr ? ` (field: ${options.attr})` : ''
super(`Validation error: ${options.detail}${attr}`)
this.name = 'PostHogValidationError'
this.detail = options.detail
this.attr = options.attr
this.code = options.code
this.extra = options.extra
this.url = options.url
this.method = options.method
}
}
/**
* Thrown when MCP-side schema validation rejects a tool call's input before
* any handler runs (the exec `call` path). The message is pre-formatted by
* `formatInputValidationError` and already names the offending field(s), so
* `handleToolError` returns it verbatim — capturing it as an exception would
* mint a per-tool error tracking issue for every agent slip-up, the same
* noise problem the 4xx short-circuit exists to prevent.
*/
export class ToolInputValidationError extends Error {
/** Value-free descriptors of the rejection for telemetry. */
public readonly fields: string[]
constructor(message: string, detail?: { fields?: string[] }) {
super(message)
this.name = 'ToolInputValidationError'
this.fields = detail?.fields ?? []
}
}
export type ExecCommandErrorReason =
| 'unknown_command'
| 'tool_as_command'
| 'batched_command'
| 'unknown_tool'
| 'deprecated_tool'
| 'gated_tool'
| 'missing_scope'
| 'tool_not_granted'
| 'invalid_json'
| 'usage'
| 'invalid_regex'
| 'unknown_learn_topic'
| 'needs_confirmation'
/**
* Thrown by the `exec` dispatcher when it rejects a command before any inner
* tool runs. Typed so these classify as agent mistakes rather than falling
* through to the `internal` bucket ops alerts on.
*
* `message` goes back to the agent verbatim so it can self-correct, but is
* never captured into analytics — it can echo the caller's tool name or a JSON
* parser fragment. `$mcp_error_message` is derived from the `reason` enum.
*/
export class ExecCommandError extends Error {
public readonly reason: ExecCommandErrorReason
constructor(message: string, reason: ExecCommandErrorReason) {
super(message)
this.name = 'ExecCommandError'
this.reason = reason
}
}
export interface PostHogApiErrorOptions {
status: number
statusText: string
body: string
url: string
method: string
message?: string
retryAfterSeconds?: number | null
}
/**
* Thrown when the PostHog API rejects a request with a non-success status that
* isn't already handled by a more specific subclass (PostHogPermissionError,
* PostHogValidationError). Carries the status code so callers can distinguish
* recoverable agent-input errors (4xx) from genuine service failures (5xx).
*
* Background: an LLM agent passing a placeholder UUID to an MCP tool produced
* a 404, and `handleToolError` captured it as a PostHog exception fingerprinted
* by tool name — creating a brand-new error tracking issue per tool every time
* an agent fumbled a parameter. Keying off `status` here lets `handleToolError`
* short-circuit 4xx without losing visibility into real 5xx failures.
*/
export class PostHogApiError extends Error {
public readonly status: number
public readonly statusText: string
public readonly body: string
public readonly url: string
public readonly method: string
public readonly retryAfterSeconds: number | null
constructor(options: PostHogApiErrorOptions) {
super(options.message ?? buildDefaultApiErrorMessage(options))
this.name = 'PostHogApiError'
this.status = options.status
this.statusText = options.statusText
this.body = options.body
this.url = options.url
this.method = options.method
this.retryAfterSeconds = options.retryAfterSeconds ?? null
}
}
/** The request path without the upstream host. The host is not something an
* agent can act on, and reading one makes a 4xx look like an infrastructure
* fault; `client.ts` already logs the full URL server-side. */
function requestPath(url: string): string {
try {
const parsed = new URL(url)
return `${parsed.pathname}${parsed.search}`
} catch {
return url
}
}
function buildDefaultApiErrorMessage(options: PostHogApiErrorOptions): string {
return `Request failed:\nPath: ${options.method} ${requestPath(options.url)}\nStatus Code: ${options.status} (${options.statusText})\nError Message: ${options.body}`
}
export interface PostHogRateLimitErrorOptions {
body: string
url: string
method: string
retryAfterSeconds: number | null
}
/**
* Thrown when an HTTP 429 reaches the caller, including after the JSON client's
* bounded retries. Preserves the server's Retry-After hint for the next attempt.
*/
export class PostHogRateLimitError extends PostHogApiError {
constructor(options: PostHogRateLimitErrorOptions) {
const retryHint = options.retryAfterSeconds !== null ? ` Retry after ${options.retryAfterSeconds} seconds.` : ''
super({
status: 429,
statusText: 'Too Many Requests',
body: options.body,
url: options.url,
method: options.method,
retryAfterSeconds: options.retryAfterSeconds,
message: `PostHog API rate limit exceeded (429) on ${options.method} ${options.url}.${retryHint}`,
})
this.name = 'PostHogRateLimitError'
}
}
/** True for an error raised by a request deadline, as opposed to a cancellation or a network fault. */
export function isTimeoutError(error: unknown): boolean {
return error instanceof Error && error.name === 'TimeoutError'
}
export interface PostHogTransportErrorOptions {
url: string
method: string
attempts: number
/**
* Whether another attempt is safe. True only for a method that applies
* nothing upstream. A failed write can still have reached the handler, so
* a repeat of one could apply the same work twice.
*/
retryable: boolean
cause: unknown
}
/**
* Thrown when a request to the PostHog API produced no usable response: the
* connection failed, dropped, or the body read was cut short. On a retryable
* method the client already repeated the call, so this error means the retry
* budget is spent.
*/
export class PostHogTransportError extends Error {
public readonly retryable: boolean
public readonly url: string
public readonly method: string
public readonly attempts: number
/** True when the request hit the client's deadline instead of failing to connect. */
public readonly timedOut: boolean
constructor(options: PostHogTransportErrorOptions) {
const reason = options.cause instanceof Error ? options.cause.message : String(options.cause)
const advice = options.retryable
? 'The request applies nothing upstream, so it is safe to retry.'
: 'The request may have been applied upstream, so check the state before you send it again.'
super(
`Could not reach the PostHog API on ${options.method} ${requestPath(options.url)} after ${options.attempts} attempt${options.attempts === 1 ? '' : 's'}: ${reason}. ${advice}`
)
this.name = 'PostHogTransportError'
this.retryable = options.retryable
this.url = options.url
this.method = options.method
this.attempts = options.attempts
// A forwarded request nests the local transport error, so look through the cause chain.
this.timedOut = hasTimeoutCause(options.cause)
;(this as Error & { cause?: unknown }).cause = options.cause
}
}
/**
* Parses a Retry-After header into whole seconds. Returns null for missing
* headers, HTTP-date values, and invalid delay values.
*/
export function parseRetryAfterSeconds(header: string | null): number | null {
if (!header || !/^\d+$/.test(header.trim())) {
return null
}
const seconds = Number(header)
return Number.isSafeInteger(seconds) ? seconds : null
}
export interface PostHogPermissionErrorOptions {
detail: string
missingScope?: string | undefined
challengeScopes?: string[] | undefined
url: string
method: string
}
/**
* Thrown when the PostHog API rejects a request with HTTP 403 `permission_denied`.
* Preserves the missing scope (when present) so the MCP layer can surface an
* actionable remediation message instead of a generic failure.
*/
export class PostHogPermissionError extends Error {
public readonly detail: string
public readonly missingScope: string | undefined
/** From the API's `insufficient_scope` challenge, which it sends only for a step-up token. */
public readonly challengeScopes: string[] | undefined
public readonly url: string
public readonly method: string
constructor(options: PostHogPermissionErrorOptions) {
const message = options.missingScope
? `Missing PostHog API scope: '${options.missingScope}'`
: `PostHog API permission denied: ${options.detail}`
super(message)
this.name = 'PostHogPermissionError'
this.detail = options.detail
this.missingScope = options.missingScope
this.challengeScopes = options.challengeScopes
this.url = options.url
this.method = options.method
}
get requiredScopes(): string[] | undefined {
if (this.challengeScopes?.length) {
return this.challengeScopes
}
return this.missingScope ? [this.missingScope] : undefined
}
}
/**
* Creates an Error that wraps another error as its `cause`.
* The tsconfig targets ES2021, which doesn't expose the ErrorOptions overload,
* so set `cause` manually after construction. At runtime (Node 18+ / CF Workers)
* the property still participates in cause-walking helpers like
* `findPostHogPermissionError`.
*/
export function wrapError(message: string, cause: unknown): Error {
const err = new Error(message) as Error & { cause?: unknown }
err.cause = cause
return err
}
const PERSONAL_API_KEY_DOCS_URL = 'https://posthog.com/docs/api#how-to-authenticate-with-the-posthog-api'
export function formatPermissionErrorMessage(error: PostHogPermissionError): string {
const callTarget = error.method && error.url ? `${error.method} ${error.url}` : 'this MCP request'
if (error.missingScope) {
return [
`Missing PostHog API scope: '${error.missingScope}'`,
'',
`Your Personal API key is missing the '${error.missingScope}' scope, which is required to call ${callTarget}.`,
'',
`To fix: edit the Personal API key in PostHog (User settings → Personal API keys) and add the '${error.missingScope}' scope. Alternatively, select the "MCP Server" scope preset which includes every scope the MCP needs.`,
'',
`See: ${PERSONAL_API_KEY_DOCS_URL}`,
].join('\n')
}
// The backend sends this detail when a token restricted to some projects calls an organization endpoint.
if (error.detail.includes('API keys with scoped projects are only supported on project-based endpoints')) {
return [
`PostHog API permission denied: ${error.detail}`,
'',
`The request to ${callTarget} was rejected with HTTP 403. This is an organization endpoint, and your API key or OAuth token is limited to specific projects. More project access does not fix this.`,
'',
'To fix: use a Personal API key or OAuth token with organization access. In PostHog, open User settings → Personal API keys and set the key access to "All access" or "Organizations" (with this organization), not "Projects".',
'',
`See: ${PERSONAL_API_KEY_DOCS_URL}`,
].join('\n')
}
return [
`PostHog API permission denied: ${error.detail}`,
'',
`The request to ${callTarget} was rejected with HTTP 403. Verify that your API key, OAuth token, and user account have access to this project.`,
].join('\n')
}
// Literal message shape produced by `new PostHogPermissionError({...})`. We
// reconstruct from this when the error has crossed a boundary that strips
// `cause` and the custom subclass prototype — see the fallback in
// `findPostHogPermissionError` for the full reasoning.
const MISSING_SCOPE_MESSAGE_PATTERN = /Missing PostHog API scope: ['"]([^'"]+)['"]/
/**
* Walk `Error.cause` chains to find a wrapped PostHogPermissionError.
* Tool-level wrappers (e.g. `throw new Error("Failed to X: ...", { cause })`)
* hide the underlying permission error, so callers must unwrap before acting.
*
* Fallback for the Cloudflare Durable Object RPC boundary: errors thrown
* inside the DO arrive in the worker as plain Errors — `cause`, the
* PostHogPermissionError prototype, and any custom own-properties have all
* been stripped by the cross-isolate serializer, leaving just `name`,
* `message`, and `stack`. Without this fallback, a permission error from
* `_fetchUser` (or any other init-time API call) gets mapped to an opaque
* 500 in `onCatchErrorHandler` and OAuth-aware MCP clients never see the
* 403 + `WWW-Authenticate: insufficient_scope` they need to re-consent.
*
* The literal `Missing PostHog API scope: 'X'` shape produced by the
* `PostHogPermissionError` constructor is the one piece of information that
* does survive — we re-synthesize a typed error from it. `url`/`method`
* are not recoverable from the message alone; `formatPermissionErrorMessage`
* handles the empty case.
*/
export function findPostHogPermissionError(error: unknown): PostHogPermissionError | undefined {
let current: unknown = error
const seen = new Set<unknown>()
while (current && !seen.has(current)) {
if (current instanceof PostHogPermissionError) {
return current
}
seen.add(current)
current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined
}
if (error instanceof Error && typeof error.message === 'string') {
const match = MISSING_SCOPE_MESSAGE_PATTERN.exec(error.message)
if (match) {
const missingScope = match[1]!
return new PostHogPermissionError({
detail: `API key missing required scope '${missingScope}'`,
missingScope,
url: '',
method: '',
})
}
}
return undefined
}
/**
* Walks `Error.cause` chains to find a wrapped PostHogApiError or
* PostHogValidationError. Tool-level wrappers (e.g. `throw new Error("Failed
* to X: ...", { cause })`) hide the underlying typed error, so callers must
* unwrap before classifying the failure.
*/
export function findRecoverableApiError(error: unknown): PostHogApiError | PostHogValidationError | undefined {
let current: unknown = error
const seen = new Set<unknown>()
while (current && !seen.has(current)) {
if (current instanceof PostHogApiError || current instanceof PostHogValidationError) {
return current
}
seen.add(current)
current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined
}
return undefined
}
/** True when the error or any error in its `cause` chain came from a request deadline. Tools that
* rethrow through `wrapError` keep the timeout in `cause`. */
export function hasTimeoutCause(error: unknown): boolean {
let current: unknown = error
const seen = new Set<unknown>()
while (current && !seen.has(current)) {
if (isTimeoutError(current) || (current instanceof PostHogTransportError && current.timedOut)) {
return true
}
seen.add(current)
current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined
}
return false
}
/**
* Handles tool errors and returns a structured error message.
* Any errors that originate from the tool SHOULD be reported inside the result
* object, with `isError` set to true, _not_ as an MCP protocol-level error
* response. Otherwise, the LLM would not be able to see that an error occurred
* and self-correct.
*
* @param error - The error object.
* @param tool - Tool that caused the error.
* @param distinctId - User's distinct ID for tracking.
* @param sessionId - Session UUID for tracking.
*
* @returns A structured error message.
*/
export function handleToolError(
error: any,
tool?: string,
distinctId?: string,
sessionUuid?: string,
suppressAnalytics = false
): CallToolResult {
const toolName = tool || 'unknown'
// Recoverable: expected agent or user state, not a bug — no project picked,
// input the schema rejected, a mistyped exec command. Each of these classes
// pre-formats a message the agent can self-correct from, so return it verbatim
// and skip exception capture, which would mint an issue per slip-up.
if (
error instanceof MissingProjectContextError ||
error instanceof MissingOrganizationContextError ||
error instanceof PinnedContextSwitchError ||
error instanceof ToolInputValidationError ||
error instanceof ExecCommandError ||
(error instanceof MCPToolResultError && ['validation', 'permission'].includes(error.errorType))
) {
return {
content: [
{
type: 'text',
text: `Error: [${toolName}]: ${error.message}`,
},
],
isError: true,
}
}
// Recoverable: 4xx responses from the PostHog API (and validation errors)
// are agent-input failures — the LLM passed a bad id, a stale UUID, or a
// value the serializer rejected. Returning the typed error message to the
// LLM lets it self-correct on the next turn. Capturing these as exceptions
// — fingerprinted by tool name — would create a fresh error tracking issue
// for every agent slip-up. Reserve `captureException` for 5xx and
// unexpected non-HTTP errors, which are genuinely actionable for engineers.
const recoverableApiError = findRecoverableApiError(error)
if (recoverableApiError) {
const isFourXx =
recoverableApiError instanceof PostHogValidationError ||
(recoverableApiError.status >= 400 && recoverableApiError.status < 500)
if (isFourXx) {
return {
content: [
{
type: 'text',
text: `Error: [${toolName}]: ${recoverableApiError.message}`,
},
],
isError: true,
}
}
}
const permissionError = findPostHogPermissionError(error)
if (permissionError) {
const properties: Record<string, any> = {
team: 'growth',
tool: toolName,
is_permission_error: true,
suppress_analytics: suppressAnalytics,
missing_scope: permissionError.missingScope,
$exception_fingerprint: `posthog-permission-error:${toolName}:${permissionError.missingScope ?? 'unknown'}`,
}
if (sessionUuid) {
properties.$session_id = sessionUuid
}
try {
getPostHogClient().captureException(permissionError, distinctId, properties)
} catch {
// Never let observability break the request.
}
return {
content: [
{
type: 'text',
text: `Error: [${toolName}]: ${formatPermissionErrorMessage(permissionError)}`,
},
],
isError: true,
}
}
const mcpError =
error instanceof MCPToolError
? error
: new MCPToolError(error instanceof Error ? error.message : String(error), toolName, error)
const properties: Record<string, any> = {
team: 'growth',
tool: mcpError.tool,
is_mcp_tool_error: error instanceof MCPToolError,
suppress_analytics: suppressAnalytics,
$exception_fingerprint: mcpError.tool,
}
if (sessionUuid) {
properties.$session_id = sessionUuid
}
try {
getPostHogClient().captureException(mcpError, distinctId, properties)
} catch {
// Never let observability break the request.
}
// A 5xx returns an opaque server body the agent can't act on. When the
// failed endpoint has a known recovery path (e.g. a logs query that scanned
// too much data), append a short "here's how to recover" footer so the agent
// narrows and retries instead of re-issuing the same failing call.
// `recoverableApiError` was unwrapped from any `cause` chain above; only 5xx
// reach here (4xx short-circuited earlier).
const recoveryHint =
recoverableApiError instanceof PostHogApiError
? getToolRecoveryHint({
url: recoverableApiError.url,
status: recoverableApiError.status,
retryAfterSeconds: recoverableApiError.retryAfterSeconds,
})
: undefined
return {
content: [
{
type: 'text',
text: `Error: [${mcpError.tool}]: ${mcpError.message}${recoveryHint ? `\n\n${recoveryHint}` : ''}`,
},
],
isError: true,
}
}