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(replay): return a normal result for missing MCP recordings (#106360)

Paul D'Ambraabd705f56fdf
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index c88d19b22d64..a528f3ebfe8a 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -52,6 +52,10 @@ Agents compose these primitives into higher-level workflows.
The reasoning: agents are better at composing simple tools than navigating complex ones,
and simple tools are reusable across many workflows.
+For lookup tools, return an explicit normal result when absence is an expected answer (for example,
+checking whether an event's session has a recording). Keep invalid inputs, permission failures, and
+server failures as tool errors so MCP Analytics measures genuine failures rather than routine misses.
+
## Two MCP server versions
Clients must support two main capabilities: MCPs and skills.
diff --git a/products/replay/mcp/apps/SessionRecordingView.tsx b/products/replay/mcp/apps/SessionRecordingView.tsx
index 62a0e31f0de5..237da2f956d2 100644
--- a/products/replay/mcp/apps/SessionRecordingView.tsx
+++ b/products/replay/mcp/apps/SessionRecordingView.tsx
@@ -5,6 +5,7 @@ import { Badge, Card, CardContent } from '@posthog/quill'
export interface SessionRecordingData {
id: string
+ found?: false
distinct_id?: string | null
viewed?: boolean
recording_duration?: number
@@ -81,67 +82,32 @@ function formatDuration(seconds?: number | null): string {
}
export function SessionRecordingView({ recording }: { recording: SessionRecordingData }): ReactElement {
+ if (recording.found === false) {
+ return (
+ <div className="p-4">
+ <Card>
+ <CardContent>
+ <p className="text-sm font-semibold">No session recording found</p>
+ <p className="text-sm text-muted-foreground">
+ No recording is available for session {recording.id} in this project.
+ </p>
+ </CardContent>
+ </Card>
+ </div>
+ )
+ }
+
const errors = recording.console_error_count ?? 0
const warns = recording.console_warn_count ?? 0
const logs = recording.console_log_count ?? 0
- const userDisplay = userRowDisplayValue(recording)
-
return (
<div className="p-4">
<div className="flex flex-col gap-3">
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-lg font-semibold">Session Recording</span>
- {recording.ongoing ? (
- <Badge variant="warning">Live</Badge>
- ) : (
- <Badge variant="success">{formatDuration(recording.recording_duration)}</Badge>
- )}
- {recording.viewed !== undefined && (
- <Badge variant={recording.viewed ? 'default' : 'success'}>
- {recording.viewed ? 'Viewed' : 'New'}
- </Badge>
- )}
- {recording.snapshot_source && <Badge>{recording.snapshot_source}</Badge>}
- </div>
- <span className="text-xs font-mono text-muted-foreground">{recording.id}</span>
- </div>
+ <RecordingHeader recording={recording} />
<Card>
<CardContent>
- <DescriptionList
- items={[
- {
- label: 'Started',
- value: recording.start_time ? formatStartedUtc(recording.start_time) : '\u2014',
- },
- { label: 'Active time', value: formatDuration(recording.active_seconds) },
- ...(recording.start_url
- ? [
- {
- label: 'Start URL',
- value: (
- <span className="block truncate" title={recording.start_url}>
- {recording.start_url}
- </span>
- ),
- },
- ]
- : []),
- ...(userDisplay
- ? [
- {
- label: 'User',
- value: (
- <span className="block truncate" title={userDisplay}>
- {userDisplay}
- </span>
- ),
- },
- ]
- : []),
- ]}
- />
+ <RecordingMetadata recording={recording} />
</CardContent>
</Card>
@@ -172,6 +138,68 @@ export function SessionRecordingView({ recording }: { recording: SessionRecordin
)
}
+function RecordingHeader({ recording }: { recording: SessionRecordingData }): ReactElement {
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-lg font-semibold">Session Recording</span>
+ {recording.ongoing ? (
+ <Badge variant="warning">Live</Badge>
+ ) : (
+ <Badge variant="success">{formatDuration(recording.recording_duration)}</Badge>
+ )}
+ {recording.viewed !== undefined && (
+ <Badge variant={recording.viewed ? 'default' : 'success'}>
+ {recording.viewed ? 'Viewed' : 'New'}
+ </Badge>
+ )}
+ {recording.snapshot_source && <Badge>{recording.snapshot_source}</Badge>}
+ </div>
+ <span className="text-xs font-mono text-muted-foreground">{recording.id}</span>
+ </div>
+ )
+}
+
+function RecordingMetadata({ recording }: { recording: SessionRecordingData }): ReactElement {
+ const userDisplay = userRowDisplayValue(recording)
+
+ return (
+ <DescriptionList
+ items={[
+ {
+ label: 'Started',
+ value: recording.start_time ? formatStartedUtc(recording.start_time) : '\u2014',
+ },
+ { label: 'Active time', value: formatDuration(recording.active_seconds) },
+ ...(recording.start_url
+ ? [
+ {
+ label: 'Start URL',
+ value: (
+ <span className="block truncate" title={recording.start_url}>
+ {recording.start_url}
+ </span>
+ ),
+ },
+ ]
+ : []),
+ ...(userDisplay
+ ? [
+ {
+ label: 'User',
+ value: (
+ <span className="block truncate" title={userDisplay}>
+ {userDisplay}
+ </span>
+ ),
+ },
+ ]
+ : []),
+ ]}
+ />
+ )
+}
+
function Stat({ label, value }: { label: string; value: number | string }): ReactElement {
return (
<div className="text-center">
diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yaml
index 163876308dec..b4f4a3370a78 100644
--- a/products/replay/mcp/tools.yaml
+++ b/products/replay/mcp/tools.yaml
@@ -61,14 +61,15 @@ tools:
Session recordings are reachable from events, errors, and persons via the `$session_id` property on events.
Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a
`$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that
- project or session. A 404 means no recording was captured. If the user wants to understand what happened
- without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary of
- the session. To generate one, call `vision-scanners-inline-scan-create` with the session id in
+ project or session. When no recording is available, the tool returns `found: false` with reason
+ `recording_not_found`; this is a normal lookup result, not a tool failure. If the user wants to understand
+ what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision
+ AI summary of the session. To generate one, call `vision-scanners-inline-scan-create` with the session id in
`session_ids`, `scanner_type: "summarizer"`, and a `prompt` (required), then read the summary back with
`vision-observations-list`. The investigating-replay skill carries the exact prompt and `scanner_config` the
Summarize button in the player uses, so pass those to land on the same summary (scanning is slow).
`vision-scanners-scan-session` points a saved scanner at the session instead. If a recording is missing
- (404) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query
+ (`found: false`) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query
`$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and
`$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific
session, or sample recent events for project-wide issues).
diff --git a/products/replay/skills/diagnosing-missing-recordings/SKILL.md b/products/replay/skills/diagnosing-missing-recordings/SKILL.md
index daebaa3ea336..a3abc06ca848 100644
--- a/products/replay/skills/diagnosing-missing-recordings/SKILL.md
+++ b/products/replay/skills/diagnosing-missing-recordings/SKILL.md
@@ -48,8 +48,11 @@ posthog:session-recording-get
}
```
-If this returns data, the recording exists — the issue is likely UI/filtering, not capture.
-If it returns 404, proceed to diagnose why.
+If it returns `found: false` with reason `recording_not_found`, no recording exists for this session in the active project.
+Proceed to Step 2 to diagnose why.
+If it returns recording metadata, the recording exists — the issue is likely UI/filtering, not capture.
+Any other error (for example, a missing project or a permission error) is not evidence about the recording.
+Fix that error first.
### Step 2 — Query diagnostic signals from events
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 6b93a98a11ef..4c553c0db854 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10638,7 +10638,7 @@
}
},
"session-recording-get": {
- "description": "Get a specific session recording by ID. Returns full recording metadata including duration, interaction counts, console log counts, viewing status, and a compact person summary (id, name, distinct IDs). The person's full property bag is not included — use `persons-retrieve` when you need a person's properties. Session recordings are reachable from events, errors, and persons via the `$session_id` property on events. Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a `$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that project or session. A 404 means no recording was captured. If the user wants to understand what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary of the session. To generate one, call `vision-scanners-inline-scan-create` with the session id in `session_ids`, `scanner_type: \"summarizer\"`, and a `prompt` (required), then read the summary back with `vision-observations-list`. The investigating-replay skill carries the exact prompt and `scanner_config` the Summarize button in the player uses, so pass those to land on the same summary (scanning is slow). `vision-scanners-scan-session` points a saved scanner at the session instead. If a recording is missing (404) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query `$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and `$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific session, or sample recent events for project-wide issues).",
+ "description": "Get a specific session recording by ID. Returns full recording metadata including duration, interaction counts, console log counts, viewing status, and a compact person summary (id, name, distinct IDs). The person's full property bag is not included — use `persons-retrieve` when you need a person's properties. Session recordings are reachable from events, errors, and persons via the `$session_id` property on events. Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a `$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that project or session. When no recording is available, the tool returns `found: false` with reason `recording_not_found`; this is a normal lookup result, not a tool failure. If the user wants to understand what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary of the session. To generate one, call `vision-scanners-inline-scan-create` with the session id in `session_ids`, `scanner_type: \"summarizer\"`, and a `prompt` (required), then read the summary back with `vision-observations-list`. The investigating-replay skill carries the exact prompt and `scanner_config` the Summarize button in the player uses, so pass those to land on the same summary (scanning is slow). `vision-scanners-scan-session` points a saved scanner at the session instead. If a recording is missing (`found: false`) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query `$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and `$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific session, or sample recent events for project-wide issues).",
"category": "Session replays",
"feature": "replay",
"summary": "Get session recording",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index af095b321ed2..6b06432237fd 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11210,7 +11210,7 @@
}
},
"session-recording-get": {
- "description": "Get a specific session recording by ID. Returns full recording metadata including duration, interaction counts, console log counts, viewing status, and a compact person summary (id, name, distinct IDs). The person's full property bag is not included — use `persons-retrieve` when you need a person's properties. Session recordings are reachable from events, errors, and persons via the `$session_id` property on events. Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a `$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that project or session. A 404 means no recording was captured. If the user wants to understand what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary of the session. To generate one, call `vision-scanners-inline-scan-create` with the session id in `session_ids`, `scanner_type: \"summarizer\"`, and a `prompt` (required), then read the summary back with `vision-observations-list`. The investigating-replay skill carries the exact prompt and `scanner_config` the Summarize button in the player uses, so pass those to land on the same summary (scanning is slow). `vision-scanners-scan-session` points a saved scanner at the session instead. If a recording is missing (404) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query `$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and `$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific session, or sample recent events for project-wide issues).",
+ "description": "Get a specific session recording by ID. Returns full recording metadata including duration, interaction counts, console log counts, viewing status, and a compact person summary (id, name, distinct IDs). The person's full property bag is not included — use `persons-retrieve` when you need a person's properties. Session recordings are reachable from events, errors, and persons via the `$session_id` property on events. Any `$session_id` value from an event can be passed as the `id` parameter to this tool. Note: a `$session_id` on an event does not guarantee a recording exists — session replay may not be enabled for that project or session. When no recording is available, the tool returns `found: false` with reason `recording_not_found`; this is a normal lookup result, not a tool failure. If the user wants to understand what happened without watching the recording, check `vision-observations-list` for an existing Replay Vision AI summary of the session. To generate one, call `vision-scanners-inline-scan-create` with the session id in `session_ids`, `scanner_type: \"summarizer\"`, and a `prompt` (required), then read the summary back with `vision-observations-list`. The investigating-replay skill carries the exact prompt and `scanner_config` the Summarize button in the player uses, so pass those to land on the same summary (scanning is slow). `vision-scanners-scan-session` points a saved scanner at the session instead. If a recording is missing (`found: false`) or the user asks why recordings aren't being captured, diagnose with `execute-sql`: query `$recording_status`, `$session_recording_start_reason`, `$replay_sample_rate`, and `$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific session, or sample recent events for project-wide issues).",
"category": "Session replays",
"feature": "replay",
"summary": "Get session recording",
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 2c0f438533ea..b2c5ad08f008 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -53,6 +53,7 @@ import updateEventDefinition from './projects/updateEventDefinition'
import updatePathCleaning from './projects/updatePathCleaning'
import updatePropertyDefinition from './projects/updatePropertyDefinition'
// Replay
+import getSessionRecording from './replay/getSessionRecording'
// Skills (deprecation aliases for the llma-skill-* → skill-* rename)
import { SKILL_DEPRECATED_ALIASES } from './skills/deprecatedAliases'
import { tasksArtifactsList, tasksCommentsList, tasksCommentsRetrieve } from './tasksContext'
@@ -133,6 +134,7 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
'read-data-schema': readDataSchema,
// Replay
+ 'session-recording-get': getSessionRecording,
// Data warehouse (custom handlers for non-standard request shapes)
'external-data-sources-db-schema': externalDataSourcesDbSchema,
diff --git a/services/mcp/src/tools/replay/getSessionRecording.ts b/services/mcp/src/tools/replay/getSessionRecording.ts
new file mode 100644
index 000000000000..99afb6f709f7
--- /dev/null
+++ b/services/mcp/src/tools/replay/getSessionRecording.ts
@@ -0,0 +1,42 @@
+import { PostHogApiError } from '@/lib/errors'
+import { GENERATED_TOOLS } from '@/tools/generated/replay'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const getSessionRecording = (): ToolBase<ZodObjectAny> => {
+ const tool = GENERATED_TOOLS['session-recording-get']!()
+
+ return {
+ ...tool,
+ handler: async (context: Context, params: { id: string }) => {
+ try {
+ return await tool.handler(context, params)
+ } catch (error) {
+ if (
+ error instanceof PostHogApiError &&
+ error.status === 404 &&
+ error.method === 'GET' &&
+ error.url.split('?')[0]?.endsWith(`/session_recordings/${encodeURIComponent(params.id)}/`) &&
+ isRecordingNotFound(error.body)
+ ) {
+ return {
+ found: false as const,
+ id: params.id,
+ reason: 'recording_not_found' as const,
+ message: 'No session recording is available for this ID in the active project.',
+ }
+ }
+ throw error
+ }
+ },
+ }
+}
+
+function isRecordingNotFound(body: string): boolean {
+ try {
+ return JSON.parse(body)?.detail === 'Recording not found'
+ } catch {
+ return false
+ }
+}
+
+export default getSessionRecording
diff --git a/services/mcp/tests/tools/sessionReplays.integration.test.ts b/services/mcp/tests/tools/sessionReplays.integration.test.ts
index 14bf79116f24..80e16a2bd631 100644
--- a/services/mcp/tests/tools/sessionReplays.integration.test.ts
+++ b/services/mcp/tests/tools/sessionReplays.integration.test.ts
@@ -11,6 +11,7 @@ import {
validateEnvironmentVariables,
} from '@/shared/test-utils'
import { GENERATED_TOOLS } from '@/tools/generated/replay'
+import getSessionRecording from '@/tools/replay/getSessionRecording'
import type { Context } from '@/tools/types'
describe('Session Replays', { concurrent: false }, () => {
@@ -25,7 +26,7 @@ describe('Session Replays', { concurrent: false }, () => {
describe('Session Recordings', () => {
const queryListTool = GENERATED_TOOLS['query-session-recordings-list']!()
- const getTool = GENERATED_TOOLS['session-recording-get']!()
+ const getTool = getSessionRecording()
describe('query-session-recordings-list tool', () => {
it('should return results with pagination info', async () => {
@@ -95,8 +96,12 @@ describe('Session Replays', { concurrent: false }, () => {
})
describe('session-recording-get tool', () => {
- it('should throw for a non-existent ID', async () => {
- await expect(getTool.handler(context, { id: 'nonexistent-session-id' })).rejects.toThrow()
+ it('returns an ordinary missing result for a non-existent ID', async () => {
+ await expect(getTool.handler(context, { id: 'nonexistent-session-id' })).resolves.toMatchObject({
+ found: false,
+ id: 'nonexistent-session-id',
+ reason: 'recording_not_found',
+ })
})
})
})
diff --git a/services/mcp/tests/unit/session-recording-get.test.ts b/services/mcp/tests/unit/session-recording-get.test.ts
new file mode 100644
index 000000000000..21a1ed95876f
--- /dev/null
+++ b/services/mcp/tests/unit/session-recording-get.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { PostHogApiError } from '@/lib/errors'
+import getSessionRecording from '@/tools/replay/getSessionRecording'
+import type { Context } from '@/tools/types'
+
+const recordingUrl = 'https://us.posthog.com/api/projects/42/session_recordings/session-123/'
+
+function createContext(request: ReturnType<typeof vi.fn>): Context {
+ return {
+ api: {
+ request,
+ getProjectBaseUrl: () => 'https://us.posthog.com/project/42',
+ },
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') },
+ } as unknown as Context
+}
+
+function apiError(status: number, url = recordingUrl, body = ''): PostHogApiError {
+ return new PostHogApiError({ status, statusText: 'Not Found', body, url, method: 'GET' })
+}
+
+describe('session-recording-get', () => {
+ const tool = getSessionRecording()
+
+ it('preserves the generated tool schema and UI app metadata', () => {
+ expect(tool.name).toBe('session-recording-get')
+ expect(tool.schema.safeParse({ id: 'session-123' }).success).toBe(true)
+ expect(tool._meta?.ui?.resourceUri).toBeTruthy()
+ })
+
+ it('returns recording metadata on a hit', async () => {
+ const request = vi.fn().mockResolvedValue({ id: 'session-123', person: { properties: { email: 'private' } } })
+
+ await expect(tool.handler(createContext(request), { id: 'session-123' })).resolves.toEqual({
+ id: 'session-123',
+ person: {},
+ _posthogUrl: 'https://us.posthog.com/project/42/replay/session-123',
+ })
+ expect(request).toHaveBeenCalledWith({
+ method: 'GET',
+ path: '/api/projects/42/session_recordings/session-123/',
+ })
+ })
+
+ it('treats a missing recording as a normal lookup result', async () => {
+ const request = vi.fn().mockRejectedValue(apiError(404, recordingUrl, '{"detail":"Recording not found"}'))
+
+ await expect(tool.handler(createContext(request), { id: 'session-123' })).resolves.toEqual({
+ found: false,
+ id: 'session-123',
+ reason: 'recording_not_found',
+ message: 'No session recording is available for this ID in the active project.',
+ })
+ })
+
+ it.each([
+ ['permission failure', apiError(403)],
+ ['server failure', apiError(503)],
+ ['unrelated 404', apiError(404, 'https://us.posthog.com/api/projects/42/')],
+ ['missing project', apiError(404, recordingUrl, '{"detail":"Project not found."}')],
+ ['unrecognized 404', apiError(404, recordingUrl, '{"detail":"Not found."}')],
+ ])('still throws on %s', async (_reason, error) => {
+ const request = vi.fn().mockRejectedValue(error)
+
+ await expect(tool.handler(createContext(request), { id: 'session-123' })).rejects.toBe(error)
+ })
+})
diff --git a/services/mcp/tests/unit/tool-name-validation.test.ts b/services/mcp/tests/unit/tool-name-validation.test.ts
index 5168240bd6a9..2ac4ba7048d7 100644
--- a/services/mcp/tests/unit/tool-name-validation.test.ts
+++ b/services/mcp/tests/unit/tool-name-validation.test.ts
@@ -14,7 +14,7 @@ describe('Tool name validation', () => {
it('shadows only the generated tools it means to', () => {
const shadowed = Object.keys(TOOL_MAP).filter((name) => name in GENERATED_TOOL_MAP)
- expect(shadowed.sort()).toEqual(['update-feature-flag'])
+ expect(shadowed.sort()).toEqual(['session-recording-get', 'update-feature-flag'])
})
it.each(Object.keys(allTools))('%s — name matches map key, length, and pattern', (mapKey) => {