: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
feat(mcp): support interview elicitation on legacy clients (#118101)
Adam Bowkerf52180d3f0ae
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex af0e2e1006a1..ec3cb692f159 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -190,11 +190,19 @@ Client names and consumer headers are self-reported; they do not prove a human iA third-party unattended agent using the same identity and capabilities as an interactive clientcannot be distinguished by this feature.-The invitation uses native URL elicitation on protocol revision `2026-07-28`, for clients advertising-URL support. Legacy protocol connections and clients with only form support continue without an-invitation. No MCP App, extra tool, or agent instruction is involved. The client displays the booking-URL and asks permission to open it, using its own controls and labels. No questionnaire is displayed.-The original tool runs after the client returns the invitation response, without waiting for a booking.+The invitation uses native URL elicitation for clients advertising URL support. Clients with only+form support continue without an invitation. No MCP App, extra tool, or agent instruction is involved.+The client displays the booking URL and asks permission to open it, using its own controls and labels.+No questionnaire is displayed.++Protocol revision `2026-07-28` uses an `input_required` result. The original tool runs after the client+returns the invitation response, without waiting for a booking. Earlier protocol connections remember+URL support from initialization and receive an `elicitation/create` request alongside the completed+tool result in a short SSE response. These clients must accept `text/event-stream`; JSON-only requests+and batches skip recruitment. The tool completes once, without waiting for the invitation reply.+Both paths include an `elicitationId` for clients that require it when parsing URL requests.+Sessions initialized before capability persistence was deployed need to reconnect before they can recruit.+Claude Code can keep its dialog open after opening the URL until the user chooses “I'm done.”The server cannot remove that client-controlled step. The `2026-07-28` protocol has no URL-elicitationcompletion notification; see the [SDK protocol notes](https://ts.sdk.modelcontextprotocol.io/v2/servers/elicitation).@@ -215,8 +223,9 @@ Accepted-link and opted-out records have no TTL. They remain suppressed until reretains the records; this is not a separate durable database. Do not put these keys behind anexpiring cache or delete them during cache maintenance. Cooldown records expire after seven days.Already-suppressed users skip progress writes and booking-link creation; the final reservation remains atomic.-Redis failures skip new invitations. A response write must succeed before the original tool runs;-the client can retry the continuation if that write fails.+Redis failures skip new invitations. On `2026-07-28`, a response write must succeed before the+original tool runs; the client can retry the continuation if that write fails. Earlier protocols+already completed the tool, so an invitation reply only updates suppression and never reruns it.Recruitment analytics use the existing PostHog SDK and the MCP server's analytics project:@@ -231,7 +240,7 @@ an extra event per eligibility check:| Property | Meaning || ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `interview_recruitment_reason` | The first gate that skipped recruitment, or `continuation` when resuming an invitation. |+| `interview_recruitment_reason` | The first gate that skipped recruitment, `eligible` for a legacy call ready before execution, or `continuation` when resuming an invitation. || `interview_recruitment_url_supported`, `interview_recruitment_form_supported` | Whether this request explicitly advertises each elicitation mode. `null` means the request carries no capability metadata; it does not prove the client lacks support. || `interview_recruitment_campaign_id` | Selected campaign, when a valid recruitment configuration exists. || `interview_recruitment_completed_calls`, `interview_recruitment_session_age_seconds` | Progress before the current call, when the warmup check was reached. |@@ -244,6 +253,9 @@ Reasons distinguish `legacy_protocol`, `url_unsupported`, `surface_excluded`, `iOnly the first failing gate is recorded. A call with `flag_disabled` can also lack URL support; use thecapability booleans to compare clients independently of the selected reason.+Legacy SSE calls evaluate eligibility before execution without reserving or showing an invitation.+Their tool-call diagnostics describe that check; `eligible` does not confirm an invitation. The server+rechecks eligibility after successful execution, including any privacy suppression learned from the API.The existing `mcp interview invitation sent` event includes these diagnostics with reason `invited`.A paused invitation has not executed a tool, so do not expect a completed tool-call event until itscontinuation runs. Exec emits one tool-call event relabeled to the inner tool. Filter@@ -269,7 +281,10 @@ resetting. Do not reset all users just to test a change. Pending continuations eand are bound to the original token, tool arguments, organization, and project. A changed contextrejects the continuation before the tool runs. Consumed continuations retain a ten-minute markerand cannot run again. Expired or consumed errors require checking the original tool's outcome-before retrying, because a write may already have succeeded.+before retrying, because a write may already have succeeded. Replies on earlier protocols expire+after ten minutes and are bound to the authenticated user, PostHog instance, invitation, and original+token. They remain valid after project changes or flag changes because they cannot execute a tool.+Duplicate, expired, and mismatched replies do not update suppression or emit response events.## Claude web and desktop exec schema budgetdiff --git a/services/mcp/src/hono/cache/McpSessionRedisStore.ts b/services/mcp/src/hono/cache/McpSessionRedisStore.tsindex 6ae49d0546a0..60184baffc14 100644--- a/services/mcp/src/hono/cache/McpSessionRedisStore.ts+++ b/services/mcp/src/hono/cache/McpSessionRedisStore.ts@@ -9,6 +9,7 @@ const SESSION_CONTEXT_KEYS = ['mcpClientName','mcpClientVersion','mcpProtocolVersion',+ 'mcpElicitationUrlSupported','mcpConsumer','mcpVendorClient',] as constdiff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 8ff602ec3732..996810d64b87 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -244,6 +244,13 @@ class McpDispatcher {const requests = messages.filter(isRequest)if (requests.length === 0) {+ const responses = messages.filter((message) => this.interviewRecruitment.isLegacyResponse(message))+ if (!singleModern && responses.length > 0) {+ const state = await this.stateResolver.resolve(props)+ for (const response of responses) {+ await this.interviewRecruitment.receiveLegacyResponse(response, state, props.userHash)+ }+ }return new Response(null, { status: 202 })}@@ -290,7 +297,32 @@ class McpDispatcher {}if (!wasArray && requests.length === 1) {- const result = await this.dispatch(requests[0]!, props, state, getPublicUrl(req).origin)+ let elicitation: JSONRPCRequest | undefined+ const canStream =+ !singleModern &&+ req.headers+ .get('accept')+ ?.split(',')+ .some((value) => value.trim().split(';')[0] === 'text/event-stream')+ const result = await this.dispatch(+ requests[0]!,+ props,+ state,+ getPublicUrl(req).origin,+ canStream+ ? (request) => {+ elicitation = request+ }+ : undefined+ )+ if (elicitation) {+ const body = [elicitation, result]+ .map((message) => `event: message\ndata: ${JSON.stringify(message)}\n\n`)+ .join('')+ return new Response(body, {+ headers: { ...headers, 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },+ })+ }// SEP-2575: unsupported RPCs get HTTP 404 in the modern dialect.const status =singleModern && 'error' in result && result.error.code === ErrorCode.MethodNotFound ? 404 : 200@@ -305,7 +337,8 @@ class McpDispatcher {request: JSONRPCRequest,props: RequestProperties,state: ResolvedState | undefined,- requestOrigin: string+ requestOrigin: string,+ onLegacyElicitation?: (request: JSONRPCRequest) => void): Promise<JsonRpcResponse> {const { id, method, params } = request@@ -315,7 +348,16 @@ class McpDispatcher {const stateless = protocolMeta.protocolVersion === STATELESS_PROTOCOL_VERSIONtry {- const result = await this.dispatchMethod(method, params, props, state, stateless, id, requestOrigin)+ const result = await this.dispatchMethod(+ method,+ params,+ props,+ state,+ stateless,+ id,+ requestOrigin,+ onLegacyElicitation+ )if (result === METHOD_NOT_FOUND) {return jsonRpcMethodError(id, ErrorCode.MethodNotFound, 'Method not found')}@@ -337,7 +379,8 @@ class McpDispatcher {state: ResolvedState | undefined,stateless: boolean,requestId: string | number,- requestOrigin: string+ requestOrigin: string,+ onLegacyElicitation?: (request: JSONRPCRequest) => void): Promise<unknown> {// SEP-2575 removed `initialize` and `ping` from the modern dialect.if (stateless && (method === Method.Initialize || method === Method.Ping)) {@@ -361,10 +404,32 @@ class McpDispatcher {params,callState,props.userHash,- requestOrigin+ requestOrigin,+ onLegacyElicitation ? 'legacy' : 'stateless',+ !!onLegacyElicitation),- afterExecute: (callState, result) =>- this.interviewRecruitment.afterToolCall(params, callState, result, requestId),+ afterExecute: async (callState, result) => {+ if (onLegacyElicitation) {+ const request = await this.interviewRecruitment.afterLegacyToolCall(+ params,+ callState,+ result,+ requestId,+ props.userHash,+ requestOrigin+ )+ if (request) {+ onLegacyElicitation(request)+ }+ } else {+ await this.interviewRecruitment.afterToolCall(+ params,+ callState,+ result,+ requestId+ )+ }+ },}: undefined)diff --git a/services/mcp/src/hono/interview-recruitment.ts b/services/mcp/src/hono/interview-recruitment.tsindex 003062deb346..bfdf02dddfb5 100644--- a/services/mcp/src/hono/interview-recruitment.ts+++ b/services/mcp/src/hono/interview-recruitment.ts@@ -1,3 +1,4 @@+import type { JSONRPCRequest } from '@modelcontextprotocol/sdk/types.js'import { createHash, randomUUID } from 'node:crypto'import { z } from 'zod'@@ -46,6 +47,7 @@ export interface InterviewRecruitmentDiagnostics {reason:| InterviewRecruitmentUnavailableReason| 'legacy_protocol'+ | 'eligible'| 'continuation'| 'request_state_present'| 'configuration_unavailable'@@ -98,6 +100,28 @@ const PENDING_SECONDS = 10 * 60const COOLDOWN_SECONDS = 7 * 24 * 60 * 60const CONVERSATION_IDLE_SECONDS = 24 * 60 * 60+type InterviewInvitation = {+ resultType: 'input_required'+ requestState: string+ inputRequests: Record<+ typeof INPUT_ID,+ {+ method: 'elicitation/create'+ params: { mode: 'url'; elicitationId: string; message: string; url: string }+ }+ >+}++function isCompletedToolCall(result: unknown): boolean {+ return (+ !!result &&+ typeof result === 'object' &&+ 'content' in result &&+ Array.isArray(result.content) &&+ !('isError' in result && result.isError === true)+ )+}+// The counter and deduplication fields expire together; retries cannot increment after losing their deduplication record.const OBSERVE_CONVERSATION = `redis.call('HSETNX', KEYS[1], 'started_at', ARGV[1])@@ -139,6 +163,7 @@ const bookingLinkSchema = z.object({const pendingInvitationSchema = z.object({fingerprint: z.string(),+ delivery: z.enum(['stateless', 'legacy']).default('stateless'),campaign_id: campaignIdSchema,organization_id: z.string().min(1),project_id: z.string().min(1),@@ -146,6 +171,12 @@ const pendingInvitationSchema = z.object({})const responseSchema = z.object({ action: z.enum(['accept', 'decline', 'cancel']) })+const legacyResponseSchema = z.object({+ jsonrpc: z.literal('2.0'),+ id: z.string().regex(/^mcp-interview:[0-9a-f-]{36}$/),+ method: z.never().optional(),+ result: responseSchema,+})export class InterviewRequestError extends Error {}@@ -229,6 +260,15 @@ export class InterviewRecruitment {.digest('hex')}+ private supportsUrl(params: Record<string, unknown>, state: ResolvedState): boolean {+ if (parseRequestProtocolMeta(params).protocolVersion !== STATELESS_PROTOCOL_VERSION) {+ return state.sessionContext?.mcpElicitationUrlSupported === true+ }+ return z+ .object({ elicitation: z.object({ url: z.object({}) }) })+ .safeParse((params._meta as Record<string, unknown> | undefined)?.[META_CLIENT_CAPABILITIES]).success+ }+private isProductCall(params: Record<string, unknown>, state: ResolvedState): boolean {const args = params.arguments as Record<string, unknown> | undefinedconst name =@@ -248,9 +288,10 @@ export class InterviewRecruitment {private eligibleConversation(params: Record<string, unknown>,- state: ResolvedState+ state: ResolvedState,+ allowLegacy = false): { config: InterviewRecruitmentConfig; key: string } | { reason: InterviewRecruitmentDiagnostics['reason'] } {- if (parseRequestProtocolMeta(params).protocolVersion !== STATELESS_PROTOCOL_VERSION) {+ if (!allowLegacy && parseRequestProtocolMeta(params).protocolVersion !== STATELESS_PROTOCOL_VERSION) {return { reason: 'legacy_protocol' }}if (params.requestState !== undefined) {@@ -263,11 +304,7 @@ export class InterviewRecruitment {if (state.isImpersonated || state.suppressAnalytics) {return { reason: 'suppressed' }}- if (- !z- .object({ elicitation: z.object({ url: z.object({}) }) })- .safeParse((params._meta as Record<string, unknown> | undefined)?.[META_CLIENT_CAPABILITIES]).success- ) {+ if (!this.supportsUrl(params, state)) {return { reason: 'url_unsupported' }}if (!this.isProductCall(params, state)) {@@ -288,18 +325,13 @@ export class InterviewRecruitment {params: Record<string, unknown>,state: ResolvedState,result: unknown,- requestId: string | number+ requestId: string | number,+ allowLegacy = false): Promise<void> {- if (- !result ||- typeof result !== 'object' ||- !('content' in result) ||- !Array.isArray(result.content) ||- ('isError' in result && result.isError === true)- ) {+ if (!isCompletedToolCall(result)) {return}- const conversation = this.eligibleConversation(params, state)+ const conversation = this.eligibleConversation(params, state, allowLegacy)if ('reason' in conversation) {return}@@ -320,7 +352,60 @@ export class InterviewRecruitment {}}- private async resume(params: Record<string, unknown>, state: ResolvedState, userHash: string): Promise<void> {+ async afterLegacyToolCall(+ params: Record<string, unknown>,+ state: ResolvedState,+ result: unknown,+ requestId: string | number,+ userHash: string,+ requestOrigin: string+ ): Promise<JSONRPCRequest | undefined> {+ if (params.requestState !== undefined || !isCompletedToolCall(result)) {+ return undefined+ }+ const invitation = await this.beforeToolCall(params, state, userHash, requestOrigin, 'legacy')+ await this.afterToolCall(params, state, result, requestId, true)+ if (!invitation) {+ return undefined+ }+ const input = invitation.inputRequests[INPUT_ID]+ return {+ jsonrpc: '2.0',+ id: invitation.requestState,+ method: 'elicitation/create',+ params: input.params,+ }+ }++ isLegacyResponse(message: unknown): boolean {+ return legacyResponseSchema.safeParse(message).success+ }++ async receiveLegacyResponse(message: unknown, state: ResolvedState, userHash: string): Promise<void> {+ const response = legacyResponseSchema.safeParse(message)+ if (!response.success) {+ return+ }+ try {+ await this.resume(+ { requestState: response.data.id, inputResponses: { [INPUT_ID]: response.data.result } },+ state,+ userHash,+ 'legacy'+ )+ } catch (error) {+ if (!(error instanceof InterviewRequestError)) {+ throw error+ }+ }+ }++ private async resume(+ params: Record<string, unknown>,+ state: ResolvedState,+ userHash: string,+ delivery: 'stateless' | 'legacy' = 'stateless'+ ): Promise<void> {const requestState = params.requestState as stringif (!/^mcp-interview:[0-9a-f-]{36}$/.test(requestState)) {throw new InterviewRequestError('Invalid interview invitation state.')@@ -341,7 +426,11 @@ export class InterviewRecruitment {const pendingKey = `${preferenceKey}:${requestState}`const rawPending = (await this.redis.get(pendingKey)) ?? ''const pending = pendingInvitationSchema.safeParse(rawPending ? JSON.parse(rawPending) : undefined)- if (!pending.success || pending.data.fingerprint !== this.requestFingerprint(params, userHash)) {+ if (+ !pending.success ||+ pending.data.delivery !== delivery ||+ pending.data.fingerprint !== this.requestFingerprint(delivery === 'legacy' ? {} : params, userHash)+ ) {throw new InterviewRequestError('Interview invitation expired, changed, or is unavailable. Check whether the original tool completed before retrying; do not automatically repeat a write.')@@ -351,14 +440,16 @@ export class InterviewRecruitment {'This interview response was already consumed. The original tool may have run. Check its outcome before retrying; do not automatically repeat a write.')}- const [organizationId, projectId] = await Promise.all([- state.context.stateManager.getOrgID(),- state.context.stateManager.getProjectId(),- ])- if (pending.data.organization_id !== organizationId || pending.data.project_id !== projectId) {- throw new InterviewRequestError(- 'The active project or organization changed while the invitation was open. Restore the original context before retrying this continuation.'- )+ if (delivery === 'stateless') {+ const [organizationId, projectId] = await Promise.all([+ state.context.stateManager.getOrgID(),+ state.context.stateManager.getProjectId(),+ ])+ if (pending.data.organization_id !== organizationId || pending.data.project_id !== projectId) {+ throw new InterviewRequestError(+ 'The active project or organization changed while the invitation was open. Restore the original context before retrying this continuation.'+ )+ }}const saved = await this.redis.eval(SAVE_RESPONSE,@@ -396,15 +487,17 @@ export class InterviewRecruitment {params: Record<string, unknown>,state: ResolvedState,userHash: string,- requestOrigin: string- ): Promise<Record<string, unknown> | undefined> {+ requestOrigin: string,+ delivery: 'stateless' | 'legacy' = 'stateless',+ observeOnly = false+ ): Promise<InterviewInvitation | undefined> {const capabilities = (params._meta as Record<string, unknown> | undefined)?.[META_CLIENT_CAPABILITIES]const capabilitiesAvailable = z.record(z.string(), z.unknown()).safeParse(capabilities).successconst diagnostics: InterviewRecruitmentDiagnostics = {reason: 'continuation',urlSupported: capabilitiesAvailable? z.object({ elicitation: z.object({ url: z.object({}) }) }).safeParse(capabilities).success- : null,+ : (state.sessionContext?.mcpElicitationUrlSupported ?? null),formSupported: capabilitiesAvailable? z.object({@@ -424,7 +517,7 @@ export class InterviewRecruitment {await this.resume(params, state, userHash)return undefined}- const conversation = this.eligibleConversation(params, state)+ const conversation = this.eligibleConversation(params, state, delivery === 'legacy')if ('reason' in conversation) {diagnostics.reason = conversation.reasonreturn undefined@@ -456,6 +549,10 @@ export class InterviewRecruitment {diagnostics.reason = 'session_too_young'return undefined}+ if (observeOnly) {+ diagnostics.reason = 'eligible'+ return undefined+ }const [organizationId, projectId] = await Promise.all([state.context.stateManager.getOrgID(),state.context.stateManager.getProjectId(),@@ -482,7 +579,8 @@ export class InterviewRecruitment {asked_at: new Date().toISOString(),}),JSON.stringify({- fingerprint: this.requestFingerprint(params, userHash),+ fingerprint: this.requestFingerprint(delivery === 'legacy' ? {} : params, userHash),+ delivery,campaign_id: config.campaign_id,organization_id: organizationId,project_id: projectId,@@ -519,6 +617,7 @@ export class InterviewRecruitment {method: 'elicitation/create',params: {mode: 'url',+ elicitationId: invitationId,message: config.message,url: bookingLink,},diff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.tsindex b96feccbecbe..f91f0bc34329 100644--- a/services/mcp/src/hono/mcp-context.ts+++ b/services/mcp/src/hono/mcp-context.ts@@ -4,7 +4,12 @@ import type { McpMode } from '@/lib/utils'export interface MCPClientContext extends Pick<RequestProperties,- 'mcpClientName' | 'mcpClientVersion' | 'mcpProtocolVersion' | 'mcpConsumer' | 'mcpVendorClient'+ | 'mcpClientName'+ | 'mcpClientVersion'+ | 'mcpProtocolVersion'+ | 'mcpConsumer'+ | 'mcpVendorClient'+ | 'mcpElicitationUrlSupported'> {}export interface MCPRequestContext@@ -44,6 +49,7 @@ export function buildMCPRequestContext(props: RequestProperties): MCPRequestContmcpClientName: props.mcpClientName,mcpClientVersion: props.mcpClientVersion,mcpProtocolVersion: props.mcpProtocolVersion,+ mcpElicitationUrlSupported: props.mcpElicitationUrlSupported,transport: props.transport,mcpSessionId: props.mcpSessionId,mcpConversationId: props.mcpConversationId,diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex fb5c8e12ad6c..a9b47527ac81 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -26,6 +26,7 @@ const InitializeParamsSchema = z.object({}).optional(),protocolVersion: z.string().optional(),+ capabilities: z.unknown().optional(),})const JsonRpcMessageSchema = z.object({@@ -55,6 +56,9 @@ function parseClientInfo(bodyText: string): ClientInfo {clientName: sanitizeHeaderValue(params.data.clientInfo?.name),clientVersion: sanitizeHeaderValue(params.data.clientInfo?.version),protocolVersion: sanitizeHeaderValue(params.data.protocolVersion),+ elicitationUrlSupported: z+ .object({ elicitation: z.object({ url: z.object({}) }) })+ .safeParse(params.data.capabilities).success,}}if (!metaFallback) {diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex 776cb208e07d..aad132aa5e33 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -21,6 +21,7 @@ export type RequestProperties = {mcpConsumer?: string | undefinedmcpClientName?: string | undefinedmcpClientVersion?: string | undefined+ mcpElicitationUrlSupported?: boolean | undefinedmcpProtocolVersion?: string | undefinedmcpVendorClient?: string | undefinedreadOnly?: boolean | undefined@@ -49,6 +50,7 @@ export type ClientInfo = {clientName?: string | undefinedclientVersion?: string | undefinedprotocolVersion?: string | undefined+ elicitationUrlSupported?: boolean | undefined}function header(request: Request, name: string): string | undefined {@@ -115,6 +117,7 @@ export function parseRequestProperties(mcpClientName: resolveEffectiveClientName(clientInfo.clientName, vendorClient),mcpClientVersion: clientInfo.clientVersion,mcpProtocolVersion: clientInfo.protocolVersion,+ mcpElicitationUrlSupported: clientInfo.elicitationUrlSupported,mcpVendorClient: vendorClient,mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),taskId: sanitizeHeaderValue(header(request, 'x-posthog-task-id')),diff --git a/services/mcp/tests/hono/interview-recruitment.test.ts b/services/mcp/tests/hono/interview-recruitment.test.tsindex 54809bc380cd..fb339ff33c70 100644--- a/services/mcp/tests/hono/interview-recruitment.test.ts+++ b/services/mcp/tests/hono/interview-recruitment.test.ts@@ -38,6 +38,7 @@ import { McpDispatcher } from '@/hono/dispatcher'import { resolveInterviewRecruitmentConfig } from '@/hono/interview-recruitment'import { registerPublicRoutes } from '@/hono/public-routes'import type { ResolvedState } from '@/hono/request-state-resolver'+import { authenticateAndParse } from '@/hono/request-utils'import type { ToolCatalog } from '@/hono/tool-catalog'import type { ToolCallHooks } from '@/hono/tool-executor'import type { RequestProperties } from '@/lib/request-properties'@@ -176,6 +177,41 @@ async function call(return (await dispatcher.handleRequest(request(params, id ?? nextRequestId++), requestProps)).json()}+type LegacyMessage = {+ id: string | number+ method?: string+ params?: Record<string, unknown>+ result?: Record<string, unknown>+}++function legacyRequest(body: unknown, accept = 'application/json, text/event-stream'): Request {+ return new Request('https://mcp.test/mcp', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: accept, 'MCP-Protocol-Version': '2025-06-18' },+ body: JSON.stringify(body),+ })+}++async function legacyCall(+ dispatcher: McpDispatcher,+ accept?: string+): Promise<{ response: Response; messages: LegacyMessage[] }> {+ const params = { name: 'exec', arguments: { command: 'call project-get {}' } }+ const response = await dispatcher.handleRequest(+ legacyRequest({ jsonrpc: '2.0', id: nextRequestId++, method: 'tools/call', params }, accept),+ props+ )+ const body = await response.text()+ const messages =+ response.headers.get('Content-Type') === 'text/event-stream'+ ? body+ .split('\n\n')+ .filter(Boolean)+ .map((event) => JSON.parse(event.split('data: ')[1]!))+ : [JSON.parse(body)]+ return { response, messages }+}+function continuation(requestState: unknown, response: unknown): Record<string, unknown> {return { ...callParams(), requestState, inputResponses: { 'mcp-interview': response } }}@@ -610,24 +646,192 @@ describe('MCP interview recruitment', () => {}})- it('completes the URL round trip with the official MCP client', async () => {- const client = new Client(- { name: 'recruitment-test', version: '1.0.0' },- { capabilities: { elicitation: { url: {} } }, versionNegotiation: { mode: { pin: '2026-07-28' } } }- )- const onInvitation = vi.fn(async () => ({ action: 'accept' as const }))- client.setRequestHandler('elicitation/create', onInvitation)- const transport = new StreamableHTTPClientTransport(new URL('https://mcp.test/mcp'), {- fetch: async (input, init) => dispatcher.handleRequest(new Request(input, init), props),- })- try {- await client.connect(transport)- const result = await client.callTool({ name: 'exec', arguments: { command: 'call project-get {}' } })- expect(result).toMatchObject(toolResult)- expect(onInvitation).toHaveBeenCalledTimes(1)+ it.each(['accept', 'decline', 'cancel'] as const)(+ 'saves a legacy %s without executing the tool again',+ async (action) => {+ state.sessionContext = { mcpElicitationUrlSupported: true }+ executeTool.mockImplementationOnce(async (_params, callState: ResolvedState) => {+ expect(callState.interviewRecruitmentDiagnostics).toMatchObject({+ reason: 'eligible',+ urlSupported: true,+ formSupported: null,+ })+ expect(captureRecruitment).not.toHaveBeenCalled()+ return toolResult+ })+ const { response, messages } = await legacyCall(dispatcher)+ expect(response.headers.get('Content-Type')).toBe('text/event-stream')+ expect(messages).toHaveLength(2)+ const invitation = messages[0]!+ expect(invitation).toMatchObject({+ method: 'elicitation/create',+ params: {+ mode: 'url',+ elicitationId: expect.any(String),+ url: expect.stringContaining('https://mcp.test/interview/'),+ },+ })+ expect(messages[1]?.result).toMatchObject(toolResult)expect(executeTool).toHaveBeenCalledTimes(1)- } finally {- await client.close()+ state.interviewRecruitmentConfig = undefined+ vi.mocked(state.context.stateManager.getProjectId).mockResolvedValue('another-project')+ const reply = { jsonrpc: '2.0', id: invitation.id, result: { action } }+ expect((await dispatcher.handleRequest(legacyRequest(reply), props)).status).toBe(202)+ expect((await dispatcher.handleRequest(legacyRequest(reply), props)).status).toBe(202)+ const saved = [...storage.entries].find(([key]) => key.endsWith(':response'))![1]+ expect(JSON.parse(saved.value).response).toBe(+ action === 'accept' ? 'booking_link_accepted' : action === 'decline' ? 'do_not_ask_again' : 'not_now'+ )+ expect(saved.expires === undefined).toBe(action !== 'cancel')+ expect(+ captureRecruitment.mock.calls.filter(([event]) => event.event === 'mcp interview invitation responded')+ ).toHaveLength(1)+ expect(executeTool).toHaveBeenCalledTimes(1)+ state.interviewRecruitmentConfig = makeState().interviewRecruitmentConfig+ expect((await legacyCall(dispatcher)).messages).toHaveLength(1)}- })+ )++ it.each(['token', 'person', 'expired', 'modern-invitation'])(+ 'ignores a legacy response for a different %s',+ async (condition) => {+ vi.useFakeTimers()+ state.sessionContext = { mcpElicitationUrlSupported: true }+ const invitation =+ condition === 'modern-invitation'+ ? { id: (await call(dispatcher)).result?.requestState }+ : (await legacyCall(dispatcher)).messages[0]!+ const before = captureRecruitment.mock.calls.length+ if (condition === 'person') {+ state.distinctId = 'another-test-person'+ }+ if (condition === 'expired') {+ vi.setSystemTime(Date.now() + 11 * 60 * 1000)+ }+ await dispatcher.handleRequest(+ legacyRequest({ jsonrpc: '2.0', id: invitation.id, result: { action: 'decline' } }),+ condition === 'token' ? { ...props, userHash: 'another-token-hash' } : props+ )+ expect(captureRecruitment).toHaveBeenCalledTimes(before)+ expect(+ [...storage.entries.values()].some((record) => JSON.parse(record.value).response === 'do_not_ask_again')+ ).toBe(false)+ }+ )++ it.each(['no-url', 'json-only', 'failed-tool', 'suppressed', 'impersonated', 'redis-error', 'warmup'])(+ 'preserves the legacy tool result when %s prevents recruitment',+ async (condition) => {+ state.sessionContext = { mcpElicitationUrlSupported: condition !== 'no-url' }+ if (condition === 'failed-tool') {+ executeTool.mockResolvedValue({ ...toolResult, isError: true })+ }+ if (condition === 'suppressed' || condition === 'impersonated') {+ executeTool.mockImplementation(async () => {+ if (condition === 'suppressed') {+ state.suppressAnalytics = true+ } else {+ state.isImpersonated = true+ }+ return toolResult+ })+ }+ if (condition === 'redis-error') {+ vi.mocked(storage.redis.get).mockRejectedValue(new Error('Redis unavailable'))+ }+ if (condition === 'warmup') {+ state.interviewRecruitmentConfig!.min_completed_tool_calls = 2+ }+ const { response, messages } = await legacyCall(+ dispatcher,+ condition === 'json-only' ? 'application/json' : undefined+ )+ expect(response.headers.get('Content-Type')).toBe('application/json')+ expect(messages).toHaveLength(1)+ expect(messages[0]?.result).toMatchObject({+ ...toolResult,+ ...(condition === 'failed-tool' ? { isError: true } : {}),+ })+ expect(executeTool).toHaveBeenCalledTimes(1)+ expect(captureRecruitment).not.toHaveBeenCalled()+ expect([...storage.entries.keys()].every((key) => key.includes(':conversation:'))).toBe(true)+ if (condition === 'failed-tool') {+ expect([...storage.entries.values()].every((record) => JSON.parse(record.value).completed === 0)).toBe(+ true+ )+ }+ if (condition === 'warmup') {+ expect((await legacyCall(dispatcher)).messages).toHaveLength(1)+ expect((await legacyCall(dispatcher)).messages).toHaveLength(2)+ }+ }+ )++ it.each(['2026-07-28', '2025-11-25'])(+ 'completes the URL round trip with the official MCP client on %s',+ async (version) => {+ let receiveReply!: () => void+ const replyHandled = new Promise<void>((resolve) => {+ receiveReply = resolve+ })+ resolveState.mockImplementation(async (requestProps: RequestProperties) => {+ if (requestProps.mcpElicitationUrlSupported !== undefined) {+ state.sessionContext = { mcpElicitationUrlSupported: requestProps.mcpElicitationUrlSupported }+ }+ return state+ })+ const app = new Hono()+ app.post('/mcp', async (c) => {+ const auth = await authenticateAndParse(c, 'streamable-http')+ if ('error' in auth) {+ return auth.error+ }+ const message = (await c.req.raw.clone().json()) as { method?: string; id?: string }+ const response = await dispatcher.handleRequest(c.req.raw, auth.props)+ if (!message.method && message.id?.startsWith('mcp-interview:')) {+ receiveReply()+ }+ return response+ })+ const client = new Client(+ { name: 'recruitment-test', version: '1.0.0' },+ {+ capabilities: { elicitation: { url: {} } },+ versionNegotiation: { mode: version === '2026-07-28' ? { pin: version } : 'legacy' },+ }+ )+ const onInvitation = vi.fn(async () => ({ action: 'accept' as const }))+ client.setRequestHandler('elicitation/create', onInvitation)+ const transport = new StreamableHTTPClientTransport(new URL('https://mcp.test/mcp'), {+ fetch: async (input, init) =>+ app.fetch(+ new Request(input, {+ ...init,+ headers: {+ ...Object.fromEntries(new Headers(init?.headers)),+ Authorization: 'Bearer phx_synthetic',+ },+ })+ ),+ })+ try {+ await client.connect(transport)+ const result = await client.callTool({ name: 'exec', arguments: { command: 'call project-get {}' } })+ expect(result).toMatchObject(toolResult)+ if (version !== '2026-07-28') {+ await replyHandled+ }+ expect(captureRecruitment).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'mcp interview invitation responded',+ properties: expect.objectContaining({ response: 'accept' }),+ })+ )+ expect(onInvitation).toHaveBeenCalledTimes(1)+ expect(executeTool).toHaveBeenCalledTimes(1)+ } finally {+ await client.close()+ }+ }+ )})diff --git a/services/mcp/tests/hono/mcp-session-redis-store.test.ts b/services/mcp/tests/hono/mcp-session-redis-store.test.tsindex 70ed997ee944..9ec121e1a13c 100644--- a/services/mcp/tests/hono/mcp-session-redis-store.test.ts+++ b/services/mcp/tests/hono/mcp-session-redis-store.test.ts@@ -33,6 +33,7 @@ const liveContext: MCPClientContext = {mcpClientName: 'claude-code',mcpClientVersion: '1.2.3',mcpProtocolVersion: '2025-11-25',+ mcpElicitationUrlSupported: true,mcpConsumer: 'posthog-code',mcpVendorClient: 'ClaudeCode',}@@ -56,11 +57,12 @@ describe('McpSessionRedisStore', () => {expect(JSON.parse(redis.store.get(compactKeyIn(redis))!)).toEqual(liveContext)})- it('serves stored context back to a later request that carries none', async () => {+ it.each([true, false])('preserves URL support %s on a later request that carries none', async (supported) => {const store = new McpSessionRedisStore(redis, 'session-1')- await store.resolve(liveContext)+ const context = { ...liveContext, mcpElicitationUrlSupported: supported }+ await store.resolve(context)- expect(await store.resolve({})).toEqual(liveContext)+ expect(await new McpSessionRedisStore(redis, 'session-1').resolve({})).toEqual(context)})it('serves live context instead of throwing when the compact read fails', async () => {