: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): recruit interview participants with native elicitation (#117751)
Adam Bowker48af077773cb
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 680d96510b26..edab1eb29815 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -90,6 +90,132 @@ Primarily oriented toward coding agents (PostHog Desktop, PostHog AI, Claude CodWhen the MCP server advertises Business Knowledge or documentation search tools, its agent instructions require one search of each available source before the first answer to a request. Business Knowledge is searched first, followed by current PostHog documentation. If a search fails or returns no relevant result, the agent continues with the other available evidence. In exec sessions with skill discovery enabled, the agent loads the relevant skill before it runs these searches.+## Interview recruitment with URL elicitation++> [!CAUTION]+> **Unsolicited elicitation can spam users and damage trust in the MCP.**+> A native dialog interrupts the user's work even when it is easy to implement or feature-flag.+> This recruitment flow is a narrow exception, not a general-purpose advertising or survey channel.+> Read the [MCP agent policy](../../../../../services/mcp/AGENTS.md#unsolicited-elicitation-high-risk) before adding unsolicited prompts or expanding this flow.+> Reviewers should challenge the interruption's user value, audience, timing, frequency, opt-out behavior, and measurement.++The `mcp-interview-recruitment` multivariate flag selects one optional interview invitation before a tool call.+Each variant key identifies a campaign and has its own invitation payload.+To add an approved study, read [the integration guide](../../../../../services/mcp/INTERVIEW_RECRUITMENT.md).+Create the flag in the MCP server's analytics project and manage its audience and rollout there.+A missing or disabled flag skips recruitment. Local development also keeps it disabled unless a+development flag override explicitly enables it with an explicit `MCP_INTERVIEW_RECRUITMENT_PAYLOAD`.+See the [local testing instructions](../../../../../services/mcp/INTERVIEW_RECRUITMENT.md#code-and-checks).++Set each variant's JSON payload to customize its invitation without deploying:++```json+{+ "message": "Squeal on our MCP. Book a 20-minute chat. We'll pay you in PostHog merch.",+ "booking_url": "https://cal.com/adam-posthog/posthog-chat",+ "min_completed_tool_calls": 3,+ "min_session_age_seconds": 120+}+```++Each variant must explicitly supply `message` and `booking_url`; omitted timing fields use the defaults above.+A boolean `true` identifies the original `mcp-research` campaign, but requires the same explicit copy and URL.+A missing payload skips recruitment; no invitation copy or booking URL is supplied by the code.+A malformed payload, an empty message, a message over 1,000+characters, or a non-HTTPS booking URL skips recruitment. Flag values and payloads come from the same+evaluation, with the same audience properties. Payload edits apply to subsequent requests without+restarting the server. A displayed invitation keeps its original campaign, copy, and URL even if targeting changes.+Use release conditions to assign variants, with higher-priority conditions first. One evaluation selects+one campaign; no invitation queue is created for overlapping audiences.++By default, an eligible conversation must complete three successful product tool calls and have been+observed for at least 120 seconds. The earliest invitation is before its fourth product call, once both+thresholds are met. Discovery commands, skills, documentation lookups, private scout tools, and failed calls do not count.+The timer starts at the first eligible product request; it does not measure when the chat UI opened.+The payload accepts 0–1,000 completed calls and 0–86,400 seconds. Setting both to zero permits an+immediate invitation for testing.++Progress is updated atomically in shared Redis, scoped to the user, instance, client, and conversation+handle already resolved by the MCP Analytics SDK. The SDK returns a handle on the first call for the+agent to echo on subsequent calls. If it is missing or changes, progress does not accumulate across+those calls. This measures calls observed under that handle, not chat messages or an independently+verified client UI conversation boundary. A client reusing a handle across chats also reuses its progress.+The counter expires after 24 hours without eligible activity, caps at 1,000 completions, and deduplicates+identical RPC IDs and tool arguments. A retried call with a new RPC ID is a new request. Continuations+of an invitation do not increment it.++Flag evaluation uses the authenticated user's distinct ID and the existing organization/project groups.+Use existing person or group properties and cohorts for additional audience filters. The server does+not inject client metadata as person-property overrides during flag evaluation.++No client-name or task conditions are required in the flag. The server requires native URL+elicitation support and enforces its surface and task exclusions independently of the flag.+Use the flag for rollout and any additional audience filters. Alternative condition groups are OR+conditions.++Only requests classified as `mcp` can recruit. Other surfaces, including PostHog AI and recognized+self-driving OAuth applications, always skip recruitment. Task-bound requests and credentials with+`internal_run:read` also skip recruitment even if their source is `mcp` and the flag is enabled.+Client names and consumer headers are self-reported; they do not prove a human is present.+A third-party unattended agent using the same identity and capabilities as an interactive client+cannot 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.+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-elicitation+completion notification; see the [SDK protocol notes](https://ts.sdk.modelcontextprotocol.io/v2/servers/elicitation).++- Accepting the link records `booking_link_accepted` and stops further invitations. This records+ permission to open the booking page, not a completed booking or permission to contact an account email.+- Declining the invitation records `do_not_ask_again` and stops further invitations.+- Canceling or abandoning the invitation starts a seven-day cooldown.++Responses are JSON records in the MCP server's shared Redis, under+`mcp:interview:{<identity hash>}:response`. The identity hash is the SHA-256 hex digest of+`JSON.stringify([publicPostHogBaseUrl, distinctId])`; it scopes the preference to the authenticated+user and PostHog instance, across tokens, sessions, and projects. Submitted records contain+`distinct_id`, `campaign_id`, `response`, and `responded_at`. Suppression is shared across campaigns. Use `SCAN MATCH 'mcp:interview:*:response'` and `GET`+to inspect responses. This implementation records the invitation response; it does not send an email or track completed bookings.++Accepted-link and opted-out records have no TTL. They remain suppressed until reset, provided Redis+retains the records; this is not a separate durable database. Do not put these keys behind an+expiring 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.++Recruitment analytics use the existing PostHog SDK and the MCP server's analytics project:++| Event | Meaning |+| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |+| `mcp interview invitation sent` | The server returns a native invitation after reserving it. This does not confirm that the client rendered the dialog. |+| `mcp interview booking link opened` | The invitation's redirect URL receives its first GET request. Repeated opens do not add events. |+| `mcp interview invitation responded` | A valid response is saved, with `response` equal to `accept`, `decline`, or `cancel`. |++Every event carries the authenticated user's distinct ID, `campaign_id`, `invitation_id`, and the `feature_flag`+key. The campaign comes from the selected variant and is retained for link opens and responses. Count distinct people for reach and invitation IDs for attempts. Invitations without a response+are unanswered, which can include abandonment, an open dialog, or a lost connection. An accepted+response records permission to open the link; it does not establish that the booking page opened.++The native dialog opens `/interview/<opaque UUID>` on the MCP host, which redirects to the configured+HTTPS booking URL. Redis holds the destination and identity for seven days. Unknown or expired links+return 404. Redirects disable caching and referrer forwarding, and HEAD requests do not count as opens.+A GET can also come from a link scanner; this is a measured redirect request, not proof of a human visit+or completed booking. Analytics delivery uses the SDK's normal best-effort pipeline and never blocks+the original tool or a known booking redirect. Suppressed and impersonated requests do not recruit.++To reset one user, delete that user's `:response` key and any matching+`:response:mcp-interview:*` pending keys. Disable the flag or finish any open invitation before+resetting. Do not reset all users just to test a change. Pending continuations expire after ten minutes+and are bound to the original token, tool arguments, organization, and project. A changed context+rejects the continuation before the tool runs. Consumed continuations retain a ten-minute marker+and cannot run again. Expired or consumed errors require checking the original tool's outcome+before retrying, because a write may already have succeeded.+## Claude web and desktop exec schema budgetClaude web and desktop silently drop a tool when its serialized `inputSchema` reaches 16,384 characters, so the final `exec` input schema has a test budget below that limit.diff --git a/services/mcp/AGENTS.md b/services/mcp/AGENTS.mdindex 0b457b3b7bb5..216c1523ccf4 100644--- a/services/mcp/AGENTS.md+++ b/services/mcp/AGENTS.md@@ -9,6 +9,19 @@ Run these commands from the repository root:- Run `pnpm --filter=@posthog/mcp run lint:fix` to apply safe Oxlint fixes. It does not apply suggestion fixes that may change behavior.- Run `pnpm --filter=@posthog/mcp run fix` before committing JavaScript, TypeScript, JSON, YAML, CSS, or SCSS changes. It applies safe Oxlint fixes, always runs Oxfmt, and fails if either tool fails.+## Unsolicited elicitation: high risk++> [!CAUTION]+> **Elicitation can spam users and damage trust in the MCP.**+> It can interrupt an agent mid-task and put advertising or research questions directly in front of the user.+> The interview recruitment flow is a narrow exception. It does not establish permission to add more prompts.++- **New unsolicited elicitation requires explicit approval from a human MCP owner before implementation.** `[review]` This includes surveys, recruitment, upsells, promotional questions, and reusing the interview flow for another purpose. A general request to improve the MCP does not authorize these interruptions.+- **Expanding an existing prompt's reach or frequency, or weakening its opt-out behavior, requires the same approval.** `[review]` Review must justify the interruption's user value, audience, timing, frequency, reliable suppression, and measurement. A feature flag or client capability alone does not justify showing a prompt.+- Read the [interview recruitment guide](../../docs/published/handbook/engineering/ai/implementing-mcp-tools.md#interview-recruitment-with-url-elicitation) before changing unsolicited elicitation. It documents the existing flow's capability checks, exclusions, warmup, suppression, and analytics. Preserve those protections when fixing or maintaining it.++This policy covers unsolicited interruptions. Elicitation needed to complete the user's requested task, such as a necessary clarification or confirmation, remains a separate use case.+## MCP Analytics- Before adding or changing MCP Analytics instrumentation, read the [tracking and observability architecture](ARCHITECTURE.md#tracking-and-observability).diff --git a/services/mcp/INTERVIEW_RECRUITMENT.md b/services/mcp/INTERVIEW_RECRUITMENT.mdnew file mode 100644index 000000000000..c1ae190d614a--- /dev/null+++ b/services/mcp/INTERVIEW_RECRUITMENT.md@@ -0,0 +1,88 @@+# Adding an interview to MCP recruitment++> [!CAUTION]+> Unsolicited elicitation interrupts users and can become advertising spam.+> Get explicit approval from a human MCP owner for the study, audience, copy, and frequency before enabling it.+> Read [AGENTS.md](AGENTS.md#unsolicited-elicitation-high-risk). Adding a variant does not bypass that policy.++## Use the existing flag++Use the shared `mcp-interview-recruitment` multivariate flag in the MCP server's analytics project.+Each variant is one interview campaign. The server uses the selected variant key as `campaign_id`+and reads that variant's JSON payload from the same flag evaluation.++1. Choose a stable variant key, such as `warehouse-research`. Keys must match `[a-z][a-z0-9_-]{0,63}`.+2. Add the variant and its JSON payload. Supply both `message` and an HTTPS `booking_url`.+3. Add release conditions using existing person/group properties or cohorts. Assign the desired variant to each condition explicitly.+4. Put higher-priority, more specific conditions first. Check people who match only your study, only another study, both, and neither. One evaluation selects one interview; overlapping audiences do not produce multiple dialogs.+5. Agree on rollout with the MCP owner before changing percentages or enabling the flag. Preserve the other studies' variants, payloads, and release conditions when editing it.++Example payload:++```json+{+ "message": "Help us understand your warehouse workflow. Book a 20-minute interview.",+ "booking_url": "https://example.com/research-booking",+ "min_completed_tool_calls": 3,+ "min_session_age_seconds": 120+}+```++Replace the example URL and copy with the approved study details. Missing or invalid copy/URL skips+that campaign; a new variant never inherits another study's booking URL. Omitted timing fields default+to three completed product calls and 120 seconds. Do not put targeting rules or a `campaign_id` in+the payload. Targeting belongs in release conditions; campaign identity comes from the variant key.+The server does not supply current-client metadata as feature-flag property overrides.++The original campaign key is `mcp-research`. Boolean `true` remains compatible with this original+campaign for local development and existing boolean configurations, but still requires an explicit valid payload.+There is no fallback invitation copy or booking URL for any flag value.++## Shared protections and reporting++All campaigns share the same per-user suppression record. Accepting a booking link or declining an+invitation stops further recruitment across campaigns. Canceling or abandoning an invitation starts+a shared seven-day cooldown. Adding or renaming a campaign must not reset these records.++The code also enforces URL elicitation capability, direct MCP surface eligibility, task exclusions,+conversation warmup, and atomic reservation against simultaneous invitations. Reuse this flow;+do not add another tool, dispatcher hook, independent recruitment flag, or suppression namespace.++The existing events carry `campaign_id` and `invitation_id`:++- `mcp interview invitation sent`: the server offers the invitation; client rendering is not confirmed.+- `mcp interview booking link opened`: the first GET of its tracked redirect, including possible link scanners.+- `mcp interview invitation responded`: `response` is `accept`, `decline`, or `cancel`.++Filter by `campaign_id` for your study's results. Count distinct people for reach and invitation IDs+for attempts. Redirects, responses, and suppression records retain the campaign selected when the+invitation was sent, even if the flag changes while the dialog is open. Continuations also require the+original resolved organization and project. Consumed continuations cannot run again; errors must not+encourage automatically repeating the original tool, because a write may already have succeeded. These events do not track+completed bookings.++## Code and checks++The implementation is [src/hono/interview-recruitment.ts](src/hono/interview-recruitment.ts).+The request resolver passes the evaluated flag value and payload into its configuration parser.+Adding an ordinary study requires flag configuration, not another code path.++For a localhost development server, supply an explicit payload alongside the existing flag override:++```sh+export NODE_ENV=development+export FEATURE_FLAG_OVERRIDES='{"mcp-interview-recruitment":"mcp-research"}'+export MCP_INTERVIEW_RECRUITMENT_PAYLOAD='{"message":"Synthetic interview invitation","booking_url":"https://example.com/book","min_completed_tool_calls":0,"min_session_age_seconds":0}'+```++Start or restart the local MCP server with those variables. This payload is accepted only for a localhost+API in `development` or `test`, with an explicit recruitment override. Production ignores it.+Missing, malformed, or incomplete payloads skip recruitment. The example disables warmup only for+local testing; production timing still comes from the flag payload. To verify event ingestion too,+configure the existing analytics API key and host for your local PostHog project.++For code changes, run the existing regression suites:++```sh+pnpm --filter=@posthog/mcp exec vitest run --config vitest.hono.config.mts tests/hono/interview-recruitment.test.ts tests/hono/request-state-resolver.test.ts+```diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 36027ee081e7..0ae4779d874b 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -26,6 +26,7 @@ import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'import { McpSessionResetRequiredError, SESSION_RESET_REQUIRED_REASON } from '@/lib/errors'import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'+import { getPublicUrl } from '@/lib/routing'import {isModernRequest,META_SERVER_INFO,@@ -41,6 +42,7 @@ import { trackInitEvent } from './analytics'import type { RedisLike } from './cache/RedisCache'import { getEnv, MCP_EXEC_SKILLS_FEATURE_FLAG } from './constants'import { InstructionsBuilder } from './instructions'+import { InterviewRecruitment, InterviewRequestError } from './interview-recruitment'import { initDurationSeconds, initTotal } from './metrics'import { RequestStateResolver, type ResolvedState } from './request-state-resolver'import { ResourceCatalog } from './resource-catalog'@@ -143,6 +145,7 @@ class McpDispatcher {private readonly toolExecutor: ToolExecutorprivate readonly instructionsBuilder: InstructionsBuilderprivate readonly skillCatalogService: SkillCatalogService+ private readonly interviewRecruitment: InterviewRecruitmentprivate warmupPromise: Promise<void> | undefined@@ -154,6 +157,7 @@ class McpDispatcher {this.instructionsBuilder = new InstructionsBuilder(GUIDELINES)this.skillCatalogService = new SkillCatalogService(redis, { archiveUrl: env.POSTHOG_MCP_SKILLS_URL })this.toolExecutor = new ToolExecutor(catalog, this.instructionsBuilder, this.skillCatalogService)+ this.interviewRecruitment = new InterviewRecruitment(redis)}async warmup(): Promise<void> {@@ -286,21 +290,22 @@ class McpDispatcher {}if (!wasArray && requests.length === 1) {- const result = await this.dispatch(requests[0]!, props, state)+ const result = await this.dispatch(requests[0]!, props, state, getPublicUrl(req).origin)// SEP-2575: unsupported RPCs get HTTP 404 in the modern dialect.const status =singleModern && 'error' in result && result.error.code === ErrorCode.MethodNotFound ? 404 : 200return new Response(JSON.stringify(result), { status, headers })}- const results = await Promise.all(requests.map((r) => this.dispatch(r, props, state)))+ const results = await Promise.all(requests.map((r) => this.dispatch(r, props, state, getPublicUrl(req).origin)))return new Response(JSON.stringify(results), { status: 200, headers })}private async dispatch(request: JSONRPCRequest,props: RequestProperties,- state: ResolvedState | undefined+ state: ResolvedState | undefined,+ requestOrigin: string): Promise<JsonRpcResponse> {const { id, method, params } = request@@ -310,12 +315,15 @@ class McpDispatcher {const stateless = protocolMeta.protocolVersion === STATELESS_PROTOCOL_VERSIONtry {- const result = await this.dispatchMethod(method, params, props, state, stateless)+ const result = await this.dispatchMethod(method, params, props, state, stateless, id, requestOrigin)if (result === METHOD_NOT_FOUND) {return jsonRpcMethodError(id, ErrorCode.MethodNotFound, 'Method not found')}return jsonRpcResult(id, stateless ? this.decorateStatelessResult(method, result) : result)} catch (error) {+ if (error instanceof InterviewRequestError) {+ return jsonRpcMethodError(id, ErrorCode.InvalidParams, error.message)+ }console.error('[McpDispatcher] Internal error:', error)return jsonRpcMethodError(id, ErrorCode.InternalError, 'Internal error')}@@ -327,7 +335,9 @@ class McpDispatcher {params: Record<string, unknown> | undefined,props: RequestProperties,state: ResolvedState | undefined,- stateless: boolean+ stateless: boolean,+ requestId: string | number,+ requestOrigin: string): Promise<unknown> {// SEP-2575 removed `initialize` and `ping` from the modern dialect.if (stateless && (method === Method.Initialize || method === Method.Ping)) {@@ -341,7 +351,23 @@ class McpDispatcher {case Method.ToolsList:return await this.toolExecutor.handleToolsList(state!)case Method.ToolsCall:- return await this.toolExecutor.handleToolCall(params, state!)+ return await this.toolExecutor.handleToolCall(+ params,+ state!,+ stateless && params+ ? {+ beforeExecute: (callState) =>+ this.interviewRecruitment.beforeToolCall(+ params,+ callState,+ props.userHash,+ requestOrigin+ ),+ afterExecute: (callState, result) =>+ this.interviewRecruitment.afterToolCall(params, callState, result, requestId),+ }+ : undefined+ )case Method.ResourcesList:return this.resourceCatalog.getResourcesList()case Method.ResourcesRead:@@ -366,7 +392,7 @@ class McpDispatcher {base._meta && typeof base._meta === 'object' ? (base._meta as Record<string, unknown>) : undefinedreturn {...base,- resultType: 'complete',+ resultType: base.resultType === 'input_required' ? 'input_required' : 'complete',...(CACHEABLE_METHODS.has(method)? { ttlMs: CACHEABLE_RESULT_TTL_MS, cacheScope: 'private' as const }: {}),diff --git a/services/mcp/src/hono/interview-recruitment.ts b/services/mcp/src/hono/interview-recruitment.tsnew file mode 100644index 000000000000..fe6336234807--- /dev/null+++ b/services/mcp/src/hono/interview-recruitment.ts@@ -0,0 +1,434 @@+import { createHash, randomUUID } from 'node:crypto'+import { z } from 'zod'++import { getPostHogClient } from '@/lib/posthog'+import { META_CLIENT_CAPABILITIES } from '@/lib/stateless-protocol'+import { isPrivateScoutTrialTool } from '@/lib/tool-privacy'+import { parseExecCallInnerToolName } from '@/tools/exec'++import type { RedisLike } from './cache/RedisCache'+import { resolveSessionKey } from './mcp-context'+import type { ResolvedState } from './request-state-resolver'++// WARNING: Unsolicited elicitation can interrupt users' work and turn the MCP into an advertising channel.+// This interview flow is a narrow exception, not a general survey or promotion mechanism.+// services/mcp/AGENTS.md requires human MCP owner approval before adding prompts or expanding their reach/frequency.+export const MCP_INTERVIEW_RECRUITMENT_FLAG = 'mcp-interview-recruitment'++const DEFAULT_CAMPAIGN_ID = 'mcp-research'+const campaignIdSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)+const invitationMessageSchema = z.string().trim().min(1).max(1000)++const bookingUrlSchema = z.url().refine((value) => value.startsWith('https://'))++const interviewRecruitmentConfigSchema = z.object({+ min_completed_tool_calls: z.number().int().min(0).max(1000).default(3),+ min_session_age_seconds: z.number().int().min(0).max(86400).default(120),+ message: invitationMessageSchema,+ booking_url: bookingUrlSchema,+})++export type InterviewRecruitmentConfig = z.infer<typeof interviewRecruitmentConfigSchema> & { campaign_id: string }++export function resolveInterviewRecruitmentConfig(+ value: unknown,+ payload: unknown+): InterviewRecruitmentConfig | undefined {+ const campaign = campaignIdSchema.safeParse(value === true ? DEFAULT_CAMPAIGN_ID : value)+ if (!campaign.success) {+ return undefined+ }+ const config = interviewRecruitmentConfigSchema.safeParse(payload)+ return config.success ? { ...config.data, campaign_id: campaign.data } : undefined+}++const INPUT_ID = 'mcp-interview'+const STATE_PREFIX = 'mcp-interview:'+const PENDING_SECONDS = 10 * 60+const COOLDOWN_SECONDS = 7 * 24 * 60 * 60+const CONVERSATION_IDLE_SECONDS = 24 * 60 * 60++// 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])+local completed = tonumber(redis.call('HGET', KEYS[1], 'completed_calls') or '0')+if ARGV[3] ~= '' and completed < 1000 then+ if redis.call('HSETNX', KEYS[1], 'request:' .. ARGV[3], '1') == 1 then+ completed = redis.call('HINCRBY', KEYS[1], 'completed_calls', 1)+ end+end+redis.call('EXPIRE', KEYS[1], ARGV[2])+return {completed, tonumber(redis.call('HGET', KEYS[1], 'started_at'))}+`++// Both keys share a Redis Cluster slot. Reserving before returning the invitation prevents parallel calls from asking twice.+const RESERVE_INVITATION = `+if redis.call('EXISTS', KEYS[1]) == 1 then return 0 end+redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[3])+redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[4])+return 1+`++const SAVE_RESPONSE = `+if redis.call('GET', KEYS[2]) ~= ARGV[1] then return 0 end+if ARGV[3] == '0' then+ redis.call('SET', KEYS[1], ARGV[2])+else+ redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])+end+redis.call('SET', KEYS[2], ARGV[4], 'EX', ARGV[5])+return 1+`++const bookingLinkSchema = z.object({+ distinct_id: z.string().min(1),+ invitation_id: z.uuid(),+ url: bookingUrlSchema,+ campaign_id: campaignIdSchema,+})++const pendingInvitationSchema = z.object({+ fingerprint: z.string(),+ campaign_id: campaignIdSchema,+ organization_id: z.string().min(1),+ project_id: z.string().min(1),+ consumed: z.boolean().default(false),+})++const responseSchema = z.object({ action: z.enum(['accept', 'decline', 'cancel']) })++export class InterviewRequestError extends Error {}++export class InterviewRecruitment {+ constructor(private readonly redis: RedisLike) {}++ private track(+ event: string,+ distinctId: string,+ invitationId: string,+ campaignId: string,+ response?: string+ ): void {+ try {+ getPostHogClient().capture({+ distinctId,+ event,+ properties: {+ invitation_id: invitationId,+ campaign_id: campaignId,+ feature_flag: MCP_INTERVIEW_RECRUITMENT_FLAG,+ ...(response ? { response } : {}),+ },+ })+ } catch {+ // Analytics availability must not block the invitation or booking page.+ }+ }++ private bookingLinkKey(invitationId: string): string {+ return `mcp:interview:link:{${invitationId}}`+ }++ async openBookingLink(invitationId: string): Promise<string | undefined> {+ if (!z.uuid().safeParse(invitationId).success) {+ return undefined+ }+ const key = this.bookingLinkKey(invitationId)+ const raw = await this.redis.get(key)+ if (!raw) {+ return undefined+ }+ const link = bookingLinkSchema.safeParse(JSON.parse(raw))+ if (!link.success || link.data.invitation_id !== invitationId) {+ return undefined+ }+ try {+ const firstOpen = await this.redis.set(`${key}:opened`, '1', 'EX', COOLDOWN_SECONDS, 'NX')+ if (firstOpen === 'OK') {+ this.track(+ 'mcp interview booking link opened',+ link.data.distinct_id,+ invitationId,+ link.data.campaign_id+ )+ }+ } catch {+ // A failed analytics deduplication write must not prevent a known booking redirect.+ }+ return link.data.url+ }++ private preferenceKey(state: ResolvedState): string {+ const identity = createHash('sha256')+ .update(JSON.stringify([state.context.api.getProjectBaseUrl('@current'), state.distinctId]))+ .digest('hex')+ return `mcp:interview:{${identity}}:response`+ }++ private requestFingerprint(params: Record<string, unknown>, userHash: string): string {+ return createHash('sha256')+ .update(+ JSON.stringify([userHash, params.name, params.arguments ?? {}], (_key, value: unknown) =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))+ : value+ )+ )+ .digest('hex')+ }++ private supportsUrl(params: Record<string, unknown>): boolean {+ 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> | undefined+ const name =+ params.name === 'exec'+ ? typeof args?.command === 'string'+ ? parseExecCallInnerToolName(args.command)+ : undefined+ : params.name+ return (+ typeof name === 'string' &&+ name !== 'docs-search' &&+ !isPrivateScoutTrialTool(name) &&+ !/^skills?-/.test(name) &&+ state.allTools.some((tool) => tool.name === name)+ )+ }++ private eligibleConversation(+ params: Record<string, unknown>,+ state: ResolvedState+ ): { config: InterviewRecruitmentConfig; key: string } | undefined {+ const config = state.interviewRecruitmentConfig+ if (+ params.requestState !== undefined ||+ !config ||+ state.isImpersonated ||+ state.suppressAnalytics ||+ !this.supportsUrl(params) ||+ !this.isProductCall(params, state)+ ) {+ return undefined+ }+ const conversation = resolveSessionKey(state.requestContext)+ if (!conversation) {+ return undefined+ }+ const client = state.requestContext+ const hash = createHash('sha256')+ .update(JSON.stringify([client.mcpClientName, client.mcpVendorClient, client.mcpConsumer, conversation]))+ .digest('hex')+ return { config, key: `${this.preferenceKey(state)}:conversation:${hash}` }+ }++ async afterToolCall(+ params: Record<string, unknown>,+ state: ResolvedState,+ result: unknown,+ requestId: string | number+ ): Promise<void> {+ if (+ !result ||+ typeof result !== 'object' ||+ !('content' in result) ||+ !Array.isArray(result.content) ||+ ('isError' in result && result.isError === true)+ ) {+ return+ }+ const conversation = this.eligibleConversation(params, state)+ if (!conversation) {+ return+ }+ try {+ if ((await this.redis.get(this.preferenceKey(state))) !== null) {+ return+ }+ await this.redis.eval(+ OBSERVE_CONVERSATION,+ 1,+ conversation.key,+ Date.now(),+ CONVERSATION_IDLE_SECONDS,+ this.requestFingerprint(params, JSON.stringify(requestId))+ )+ } catch {+ // Recruitment bookkeeping must not change the outcome of a completed tool call.+ }+ }++ private async resume(params: Record<string, unknown>, state: ResolvedState, userHash: string): Promise<void> {+ const requestState = params.requestState as string+ if (!/^mcp-interview:[0-9a-f-]{36}$/.test(requestState)) {+ throw new InterviewRequestError('Invalid interview invitation state.')+ }+ const parsed = responseSchema.safeParse(+ (params.inputResponses as Record<string, unknown> | undefined)?.[INPUT_ID]+ )+ if (!parsed.success) {+ throw new InterviewRequestError('Missing or invalid interview response.')+ }+ const response =+ parsed.data.action === 'accept'+ ? 'booking_link_accepted'+ : parsed.data.action === 'decline'+ ? 'do_not_ask_again'+ : 'not_now'+ const preferenceKey = this.preferenceKey(state)+ 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)) {+ throw new InterviewRequestError(+ 'Interview invitation expired, changed, or is unavailable. Check whether the original tool completed before retrying; do not automatically repeat a write.'+ )+ }+ if (pending.data.consumed) {+ throw new InterviewRequestError(+ '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.'+ )+ }+ const saved = await this.redis.eval(+ SAVE_RESPONSE,+ 2,+ preferenceKey,+ pendingKey,+ rawPending,+ JSON.stringify({+ distinct_id: state.distinctId,+ campaign_id: pending.data.campaign_id,+ response,+ responded_at: new Date().toISOString(),+ }),+ response === 'not_now' ? COOLDOWN_SECONDS : 0,+ JSON.stringify({ ...pending.data, consumed: true }),+ PENDING_SECONDS+ )+ if (saved !== 1) {+ throw new InterviewRequestError(+ 'Interview invitation expired, changed, or is unavailable. Check whether the original tool completed before retrying; do not automatically repeat a write.'+ )+ }+ if (!state.isImpersonated && !state.suppressAnalytics) {+ this.track(+ 'mcp interview invitation responded',+ state.distinctId,+ requestState.slice(STATE_PREFIX.length),+ pending.data.campaign_id,+ parsed.data.action+ )+ }+ }++ async beforeToolCall(+ params: Record<string, unknown>,+ state: ResolvedState,+ userHash: string,+ requestOrigin: string+ ): Promise<Record<string, unknown> | undefined> {+ if (typeof params.requestState === 'string' && params.requestState.startsWith(STATE_PREFIX)) {+ // A flag change must not discard a response to an invitation that was already displayed.+ await this.resume(params, state, userHash)+ return undefined+ }+ const conversation = this.eligibleConversation(params, state)+ if (!conversation) {+ return undefined+ }+ const { config, key: conversationKey } = conversation++ const invitationId = randomUUID()+ const requestState = `${STATE_PREFIX}${invitationId}`+ const linkKey = this.bookingLinkKey(invitationId)+ const preferenceKey = this.preferenceKey(state)+ try {+ if ((await this.redis.get(preferenceKey)) !== null) {+ return undefined+ }+ const now = Date.now()+ const progress = z+ .tuple([z.number(), z.number()])+ .parse(+ await this.redis.eval(OBSERVE_CONVERSATION, 1, conversationKey, now, CONVERSATION_IDLE_SECONDS, '')+ )+ if (+ progress[0] < config.min_completed_tool_calls ||+ now - progress[1] < config.min_session_age_seconds * 1000+ ) {+ return undefined+ }+ const [organizationId, projectId] = await Promise.all([+ state.context.stateManager.getOrgID(),+ state.context.stateManager.getProjectId(),+ ])+ await this.redis.set(+ linkKey,+ JSON.stringify({+ distinct_id: state.distinctId,+ invitation_id: invitationId,+ url: config.booking_url,+ campaign_id: config.campaign_id,+ }),+ 'EX',+ COOLDOWN_SECONDS+ )+ const reserved = await this.redis.eval(+ RESERVE_INVITATION,+ 2,+ preferenceKey,+ `${preferenceKey}:${requestState}`,+ JSON.stringify({+ response: 'pending',+ campaign_id: config.campaign_id,+ asked_at: new Date().toISOString(),+ }),+ JSON.stringify({+ fingerprint: this.requestFingerprint(params, userHash),+ campaign_id: config.campaign_id,+ organization_id: organizationId,+ project_id: projectId,+ }),+ COOLDOWN_SECONDS,+ PENDING_SECONDS+ )+ if (reserved !== 1) {+ await this.redis.del(linkKey)+ return undefined+ }+ } catch {+ // If suppression cannot be checked atomically, skip recruitment and let the user's task proceed.+ return undefined+ }++ this.track('mcp interview invitation sent', state.distinctId, invitationId, config.campaign_id)+ const bookingLink = new URL(`/interview/${invitationId}`, requestOrigin).toString()+ return {+ resultType: 'input_required',+ requestState,+ inputRequests: {+ [INPUT_ID]: {+ method: 'elicitation/create',+ params: {+ mode: 'url',+ message: config.message,+ url: bookingLink,+ },+ },+ },+ }+ }+}diff --git a/services/mcp/src/hono/public-routes.ts b/services/mcp/src/hono/public-routes.tsindex 315b1fab6f6f..c5b80ecbcde2 100644--- a/services/mcp/src/hono/public-routes.ts+++ b/services/mcp/src/hono/public-routes.ts@@ -8,6 +8,7 @@ import { getAdvertisedOAuthScopes } from '@/tools/toolDefinitions'import type { Lifecycle } from './app'import { AUTH_REDIRECT_PATHS, getAuthorizationServerUrl, MCP_DOCS_URL } from './constants'+import { InterviewRecruitment } from './interview-recruitment'import { register } from './metrics'import type { HonoCtx, RedisWithPing } from './types'@@ -104,6 +105,21 @@ export function registerPublicRoutes(app: Hono, redis: RedisWithPing, lifecycle:// URL pattern works on both runtimes.app.use('/ui-apps/*', serveStatic({ root: './public' }))+ const interviews = new InterviewRecruitment(redis)+ app.get('/interview/:id', async (c) => {+ if (c.req.raw.method === 'HEAD') {+ return c.body(null, 405)+ }+ c.header('Cache-Control', 'no-store')+ c.header('Referrer-Policy', 'no-referrer')+ try {+ const url = await interviews.openBookingLink(c.req.param('id'))+ return url ? c.redirect(url, 302) : c.notFound()+ } catch {+ return c.body(null, 503)+ }+ })+app.get('/', (c) => c.redirect(MCP_DOCS_URL, 302) as unknown as Response)app.get('/.well-known/openai-apps-challenge', (c) => c.text(OPENAI_CHALLENGE_TOKEN))app.get('/health', healthHandler)diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 4e36def8c28b..66ec2bc9ccaa 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -1,10 +1,13 @@import { MCPClientProfile } from '@/lib/client-detection'import { isCloudApi, isLocalApi, MCP_GATEWAY_FLAG } from '@/lib/constants'+import { env } from '@/lib/env'import { McpSessionResetRequiredError } from '@/lib/errors'+import { EVENT_SOURCE, resolveEventSource } from '@/lib/event-source'import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'import {type EvaluatedFlags,evaluateFeatureFlags,+ type FlagEvaluation,type FlagGroups,resolveFeatureFlagOverrides,} from '@/lib/posthog/flags'@@ -24,9 +27,15 @@ import type { Context, Env, PinnedActiveContext, Tool, ZodObjectAny } from '@/toimport { McpSessionRedisStore } from './cache/McpSessionRedisStore'import type { RedisLike } from './cache/RedisCache'import { MCP_EXEC_SKILLS_FEATURE_FLAG } from './constants'+import {+ type InterviewRecruitmentConfig,+ resolveInterviewRecruitmentConfig,+ MCP_INTERVIEW_RECRUITMENT_FLAG,+} from './interview-recruitment'import {buildMCPRequestContext,getEffectiveMCPClientContext,+ getEffectiveMCPClientIdentity,type MCPRequestContext,type MCPSessionContext,} from './mcp-context'@@ -40,6 +49,7 @@ export interface ResolvedState {context: ContextuseSingleExec: booleantoolFeatureFlags: EvaluatedFlags | undefined+ interviewRecruitmentConfig?: InterviewRecruitmentConfigapiKeyScopes: string[]isImpersonated?: booleansuppressAnalytics?: boolean@@ -154,21 +164,59 @@ export class RequestStateResolver {// MCP_GATEWAY_FLAG gates no tool of its own — it gates the third-party tools `exec`// resolves — so the tool-definition scan can't discover it; join it in explicitly.// MCP_EXEC_SKILLS_FEATURE_FLAG gates the `learn` skill commands the same way.- const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), MCP_GATEWAY_FLAG, MCP_EXEC_SKILLS_FEATURE_FLAG])]+ const allFlagKeys = [+ ...new Set([+ ...getRequiredFeatureFlags(),+ MCP_GATEWAY_FLAG,+ MCP_EXEC_SKILLS_FEATURE_FLAG,+ MCP_INTERVIEW_RECRUITMENT_FLAG,+ ]),+ ]const flagAnalyticsContext = await reqCtx.safelyGetAnalyticsContext(context)const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined- const [allFlags, _apiKey, distinctId] = await Promise.all([+ const [{ flags: allFlags, payloads }, _apiKey, distinctId] = await Promise.all([this.resolveAllFlags(reqCtx, allFlagKeys, flagGroups),context.stateManager.getApiKey(),reqCtx.getDistinctId(),])+ const [oauthClientName, oauthClientId] = await Promise.all([+ reqCtx.tokenCache.get('clientName'),+ reqCtx.tokenCache.get('oauthClientId'),+ ])props.suppressAnalytics = _apiKey?.suppress_analytics === true+ const liveClient = getEffectiveMCPClientIdentity(requestContext, sessionContext)+ const source = resolveEventSource({+ mcpConsumer: liveClient.mcpConsumer,+ clientUserAgent: props.clientUserAgent,+ apiKeyScopes: _apiKey?.scopes,+ oauthClientId: oauthClientId || undefined,+ })// Dev/test-only overrides win over evaluated values (no-op in production).const overrides = resolveFeatureFlagOverrides(props.featureFlagOverrides)const mergedFlags = { ...allFlags, ...overrides }+ let recruitmentPayload = payloads[MCP_INTERVIEW_RECRUITMENT_FLAG]+ if (+ recruitmentPayload === undefined &&+ isLocalApi() &&+ (env.NODE_ENV === 'development' || env.NODE_ENV === 'test') &&+ overrides[MCP_INTERVIEW_RECRUITMENT_FLAG]+ ) {+ try {+ recruitmentPayload = JSON.parse(env.MCP_INTERVIEW_RECRUITMENT_PAYLOAD ?? '')+ } catch {+ // Local opt-in still requires explicit, valid invitation content.+ }+ }+ const interviewRecruitmentConfig =+ source === EVENT_SOURCE.MCP &&+ !_apiKey?.scopes?.includes('internal_run:read') &&+ !props.taskId &&+ !props.taskOriginProduct+ ? resolveInterviewRecruitmentConfig(mergedFlags[MCP_INTERVIEW_RECRUITMENT_FLAG], recruitmentPayload)+ : undefined// Preserve variant strings (and `undefined` for unevaluated flags) — the// tool filter needs raw values to support `feature_flag_variant` matching.// Include override keys so a forced flag reaches the tool/instructions layer@@ -176,14 +224,11 @@ export class RequestStateResolver {const flagKeysForState = [...new Set([...allFlagKeys, ...Object.keys(overrides)])]const toolFeatureFlags = Object.fromEntries(flagKeysForState.map((k) => [k, mergedFlags[k]]))- const oauthClientName = (await reqCtx.tokenCache.get('clientName')) || undefined- const oauthClientId = (await reqCtx.tokenCache.get('oauthClientId')) || undefined-const clientProfile = new MCPClientProfile({clientName: clientContext.mcpClientName,clientVersion: clientContext.mcpClientVersion,consumer: clientContext.mcpConsumer,- oauthClientName,+ oauthClientName: oauthClientName || undefined,vendorClient: clientContext.mcpVendorClient,userAgent: props.clientUserAgent,})@@ -243,10 +288,11 @@ export class RequestStateResolver {context,useSingleExec,toolFeatureFlags,+ interviewRecruitmentConfig,apiKeyScopes,isImpersonated: _apiKey?.is_impersonated === true,suppressAnalytics: props.suppressAnalytics,- oauthClientId,+ oauthClientId: oauthClientId || undefined,clientProfile,requestContext,sessionContext,@@ -378,21 +424,23 @@ export class RequestStateResolver {reqCtx: RequestContext,flagKeys: string[],groups?: FlagGroups- ): Promise<EvaluatedFlags> {+ ): Promise<FlagEvaluation> {if (flagKeys.length === 0) {- return {}+ return { flags: {}, payloads: {} }}- // Local dev runs against the locally-running project, where the dev-only- // surfaces these flags gate exist. The flags only hide those surfaces on- // prod until GA, so enable them all locally — the analytics flag-eval client is disabled in dev anyway.+ // Enable product surfaces locally because the analytics flag client is disabled there.+ // Recruitment still needs an explicit override so development tasks do not ask for interviews.if (isLocalApi()) {- return Object.fromEntries(flagKeys.map((key) => [key, true]))+ return {+ flags: Object.fromEntries(flagKeys.map((key) => [key, key !== MCP_INTERVIEW_RECRUITMENT_FLAG])),+ payloads: {},+ }}try {const distinctId = await reqCtx.getDistinctId()return await evaluateFeatureFlags(flagKeys, distinctId, groups)} catch {- return {}+ return { flags: {}, payloads: {} }}}}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 8985becf1b3d..54debc93409d 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -132,6 +132,12 @@ function stateForToolCall(state: ResolvedState, intent: string | undefined): Resreturn scoped}+// Hooks run after SDK preparation to share its conversation handle and preserve per-call privacy suppression.+export interface ToolCallHooks {+ beforeExecute(state: ResolvedState): Promise<Record<string, unknown> | undefined>+ afterExecute(state: ResolvedState, result: unknown): Promise<void>+}+export class ToolExecutor {private readonly catalog: ToolCatalogprivate readonly instructionsBuilder: InstructionsBuilder@@ -201,7 +207,11 @@ export class ToolExecutor {return this.buildAdvertisedTools(state).find((tool) => tool.name === toolName)}- async handleToolCall(params: Record<string, unknown> | undefined, state: ResolvedState): Promise<unknown> {+ async handleToolCall(+ params: Record<string, unknown> | undefined,+ state: ResolvedState,+ hooks?: ToolCallHooks+ ): Promise<unknown> {const toolName = params?.name as stringif (!toolName) {return { content: [{ type: 'text', text: 'Missing tool name' }], isError: true }@@ -231,8 +241,14 @@ export class ToolExecutor {const callState = stateForToolCall(state, analyticsMeta.intent)const callParams = { ...params, arguments: args }+ const invitation = await hooks?.beforeExecute(callState)+ if (invitation) {+ return invitation+ }const result = await this.dispatchToolCall(toolName, callParams, callState, analyticsMeta)- return this.deliverConversationHandle(result, preparedCall)+ const delivered = this.deliverConversationHandle(result, preparedCall)+ await hooks?.afterExecute(callState, delivered)+ return delivered}// The agent can only echo a handle it has been given. One exit for every dispatch path,diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.tsindex 03d31cb164db..6b13da70eecf 100644--- a/services/mcp/src/lib/posthog/flags.ts+++ b/services/mcp/src/lib/posthog/flags.ts@@ -19,26 +19,30 @@ export async function isFeatureFlagEnabled(flagKey: string, distinctId: string,/** Raw value from posthog-node for a single flag — `true`/`false` for boolean flags, a variant string for multivariate. */export type FlagValue = boolean | string | undefined-/** Shape returned by {@link evaluateFeatureFlags} and threaded through the tool-filtering and instructions layers. */export type EvaluatedFlags = Record<string, FlagValue>+export type FlagEvaluation = { flags: EvaluatedFlags; payloads: Record<string, unknown> }+export async function evaluateFeatureFlags(flagKeys: string[],distinctId: string,groups?: FlagGroups-): Promise<EvaluatedFlags> {+): Promise<FlagEvaluation> {if (flagKeys.length === 0) {- return {}+ return { flags: {}, payloads: {} }}const client = getPostHogClient()const hasGroups = groups && Object.keys(groups).length > 0- const allFlags = await client.getAllFlags(distinctId, { flagKeys, ...(hasGroups ? { groups } : {}) })+ const evaluation = await client.getAllFlagsAndPayloads(distinctId, {+ flagKeys,+ ...(hasGroups ? { groups } : {}),+ })const result: EvaluatedFlags = {}for (const key of flagKeys) {- result[key] = allFlags[key] as FlagValue+ result[key] = evaluation.featureFlags?.[key] as FlagValue}- return result+ return { flags: result, payloads: evaluation.featureFlagPayloads ?? {} }}// Env var (or Cloudflare var) holding a JSON object of flag overrides, e.g.diff --git a/services/mcp/tests/hono/interview-recruitment.test.ts b/services/mcp/tests/hono/interview-recruitment.test.tsnew file mode 100644index 000000000000..6515375b4798--- /dev/null+++ b/services/mcp/tests/hono/interview-recruitment.test.ts@@ -0,0 +1,601 @@+import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'+import { Hono } from 'hono'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const { resolveState, executeTool, captureRecruitment } = vi.hoisted(() => ({+ resolveState: vi.fn(),+ executeTool: vi.fn(),+ captureRecruitment: vi.fn(),+}))++vi.mock('@/lib/posthog', () => ({ getPostHogClient: () => ({ capture: captureRecruitment }) }))++vi.mock('@/hono/request-state-resolver', () => ({+ RequestStateResolver: class {+ resolve = resolveState+ },+}))+vi.mock('@/hono/tool-executor', () => ({+ ToolExecutor: class {+ async handleToolCall(+ params: Record<string, unknown>,+ state: ResolvedState,+ hooks?: ToolCallHooks+ ): Promise<unknown> {+ const invitation = await hooks?.beforeExecute(state)+ if (invitation) {+ return invitation+ }+ const result = await executeTool(params, state)+ await hooks?.afterExecute(state, result)+ return result+ }+ },+}))++import type { RedisLike } from '@/hono/cache/RedisCache'+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 type { ToolCatalog } from '@/hono/tool-catalog'+import type { ToolCallHooks } from '@/hono/tool-executor'+import type { RequestProperties } from '@/lib/request-properties'+import {+ META_CLIENT_CAPABILITIES,+ META_CLIENT_INFO,+ META_PROTOCOL_VERSION,+ STATELESS_PROTOCOL_VERSION,+} from '@/lib/stateless-protocol'++function createRedis(): {+ redis: RedisLike+ entries: Map<string, { value: string; expires?: number }>+} {+ const entries = new Map<string, { value: string; expires?: number }>()+ const get = (key: string): string | undefined => {+ const entry = entries.get(key)+ if (entry?.expires !== undefined && entry.expires <= Date.now()) {+ entries.delete(key)+ return undefined+ }+ return entry?.value+ }+ const redis = {+ get: vi.fn(async (key: string) => get(key) ?? null),+ set: vi.fn(async (key: string, value: string, ...args: (string | number)[]) => {+ if (args.includes('NX') && get(key) !== undefined) {+ return null+ }+ const ttlIndex = args.indexOf('EX')+ entries.set(key, {+ value,+ ...(ttlIndex >= 0 ? { expires: Date.now() + Number(args[ttlIndex + 1]) * 1000 } : {}),+ })+ return 'OK'+ }),+ del: vi.fn(async (...keys: string[]) => keys.reduce((count, key) => count + Number(entries.delete(key)), 0)),+ eval: vi.fn(async (_script: string, numberOfKeys: number, ...args: (string | number)[]) => {+ if (numberOfKeys === 1) {+ const [key, now, ttl, request] = args as [string, number, number, string]+ const record = JSON.parse(get(key) ?? JSON.stringify({ started: now, completed: 0, requests: [] })) as {+ started: number+ completed: number+ requests: string[]+ }+ if (request && record.completed < 1000 && !record.requests.includes(request)) {+ record.completed+++ record.requests.push(request)+ }+ entries.set(key, { value: JSON.stringify(record), expires: now + ttl * 1000 })+ return [record.completed, record.started]+ }+ const [preference, pending, first, second, ttl, extra, consumedTtl] = args as [+ string,+ string,+ string,+ string,+ number,+ string | number,+ number | undefined,+ ]+ if (consumedTtl === undefined) {+ if (get(preference) !== undefined) {+ return 0+ }+ entries.set(preference, { value: first, expires: Date.now() + ttl * 1000 })+ entries.set(pending, { value: second, expires: Date.now() + Number(extra) * 1000 })+ } else {+ if (get(pending) !== first) {+ return 0+ }+ entries.set(preference, { value: second, ...(ttl ? { expires: Date.now() + ttl * 1000 } : {}) })+ entries.set(pending, { value: String(extra), expires: Date.now() + consumedTtl * 1000 })+ }+ return 1+ }),+ } as unknown as RedisLike+ return { redis, entries }+}++function makeState(): ResolvedState {+ return {+ distinctId: 'test-person',+ context: {+ api: { getProjectBaseUrl: () => 'https://us.posthog.com' },+ stateManager: { getOrgID: vi.fn(async () => 'org-1'), getProjectId: vi.fn(async () => '1') },+ },+ interviewRecruitmentConfig: resolveInterviewRecruitmentConfig(true, {+ message: 'Synthetic MCP interview',+ booking_url: 'https://example.com/book',+ min_completed_tool_calls: 0,+ min_session_age_seconds: 0,+ }),+ requestContext: { mcpConversationId: 'conversation-a', mcpClientName: 'test-client' },+ allTools: [{ name: 'project-get' }, { name: 'skill-get' }, { name: 'docs-search' }],+ clientProfile: { capabilities: { supportsInstructions: false } },+ } as unknown as ResolvedState+}++const props = { userHash: 'token-hash', apiToken: 'phx_test' } as RequestProperties+const toolResult = { content: [{ type: 'text', text: 'Original tool result' }] }++function callParams(capabilities: Record<string, unknown> = { elicitation: { url: {} } }): Record<string, unknown> {+ return {+ name: 'exec',+ arguments: { command: 'call project-get {}' },+ _meta: {+ [META_PROTOCOL_VERSION]: STATELESS_PROTOCOL_VERSION,+ [META_CLIENT_INFO]: { name: 'test-client', version: '1.0.0' },+ [META_CLIENT_CAPABILITIES]: capabilities,+ },+ }+}++let nextRequestId = 1++function request(params: Record<string, unknown>, id: number): Request {+ return new Request('https://mcp.test/mcp', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'MCP-Protocol-Version': STATELESS_PROTOCOL_VERSION,+ 'Mcp-Method': 'tools/call',+ 'Mcp-Name': String(params.name),+ },+ body: JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params }),+ })+}++async function call(+ dispatcher: McpDispatcher,+ params = callParams(),+ requestProps = props,+ id?: number+): Promise<{ result?: Record<string, unknown>; error?: { code: number; message: string } }> {+ return (await dispatcher.handleRequest(request(params, id ?? nextRequestId++), requestProps)).json()+}++function continuation(requestState: unknown, response: unknown): Record<string, unknown> {+ return { ...callParams(), requestState, inputResponses: { 'mcp-interview': response } }+}++describe('MCP interview recruitment', () => {+ let state: ResolvedState+ let storage: ReturnType<typeof createRedis>+ let dispatcher: McpDispatcher++ beforeEach(() => {+ vi.clearAllMocks()+ nextRequestId = 1+ state = makeState()+ resolveState.mockResolvedValue(state)+ executeTool.mockResolvedValue(toolResult)+ storage = createRedis()+ dispatcher = new McpDispatcher({} as ToolCatalog, storage.redis)+ })++ afterEach(() => vi.useRealTimers())++ it.each([{ action: 'accept' }, { action: 'decline' }])(+ 'persists $action and suppresses across reconnects and tokens until reset',+ async (answer) => {+ const invitation = await call(dispatcher)+ expect(invitation.result).toMatchObject({+ resultType: 'input_required',+ inputRequests: {+ 'mcp-interview': {+ method: 'elicitation/create',+ params: {+ mode: 'url',+ url: `https://mcp.test/interview/${String(invitation.result?.requestState).slice('mcp-interview:'.length)}`,+ message: state.interviewRecruitmentConfig!.message,+ },+ },+ },+ })+ expect(executeTool).not.toHaveBeenCalled()+ expect(captureRecruitment).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'mcp interview invitation sent',+ distinctId: 'test-person',+ properties: expect.objectContaining({+ invitation_id: String(invitation.result?.requestState).slice('mcp-interview:'.length),+ }),+ })+ )++ const resumed = await call(dispatcher, continuation(invitation.result?.requestState, answer))+ expect(resumed.result).toMatchObject({ resultType: 'complete', ...toolResult })+ expect(executeTool).toHaveBeenCalledTimes(1)+ expect(captureRecruitment).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'mcp interview invitation responded',+ properties: expect.objectContaining({ response: answer.action }),+ })+ )+ const [key, record] = [...storage.entries.entries()].find(([key]) => key.endsWith(':response'))!+ expect(record.expires).toBeUndefined()+ expect(JSON.parse(record.value)).toMatchObject({+ distinct_id: 'test-person',+ response: answer.action === 'decline' ? 'do_not_ask_again' : 'booking_link_accepted',+ })++ vi.useFakeTimers()+ vi.setSystemTime(Date.now() + 365 * 24 * 60 * 60 * 1000)+ const reconnected = new McpDispatcher({} as ToolCatalog, storage.redis)+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig('other-study', {+ message: 'Another interview',+ booking_url: 'https://example.com/other',+ min_completed_tool_calls: 0,+ min_session_age_seconds: 0,+ })+ vi.mocked(storage.redis.set).mockClear()+ vi.mocked(storage.redis.eval).mockClear()+ expect((await call(reconnected, callParams(), { ...props, userHash: 'new-token' })).result).toMatchObject(+ toolResult+ )+ expect(storage.redis.set).not.toHaveBeenCalled()+ expect(storage.redis.eval).not.toHaveBeenCalled()+ storage.entries.delete(key)+ expect((await call(reconnected)).result?.resultType).toBe('input_required')+ }+ )++ it('lets cancellation continue and asks again after the cooldown', async () => {+ vi.useFakeTimers()+ const invitation = await call(dispatcher)+ await call(dispatcher, continuation(invitation.result?.requestState, { action: 'cancel' }))+ expect(captureRecruitment).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'mcp interview invitation responded',+ properties: expect.objectContaining({ response: 'cancel' }),+ })+ )+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig('other-study', {+ message: 'Another interview',+ booking_url: 'https://example.com/other',+ min_completed_tool_calls: 0,+ min_session_age_seconds: 0,+ })+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ vi.setSystemTime(Date.now() + 7 * 24 * 60 * 60 * 1000)+ expect((await call(dispatcher)).result?.resultType).toBe('input_required')+ })++ it.each([{}, { elicitation: {} }, { elicitation: { form: {} } }, { elicitation: false }])(+ 'skips clients without URL support: %j',+ async (capabilities) => {+ expect((await call(dispatcher, callParams(capabilities))).result).toMatchObject(toolResult)+ expect(storage.entries.size).toBe(0)+ }+ )++ it.each(['disabled', 'missing', 'impersonated', 'suppressed', 'invalid-payload'])(+ 'skips recruitment when %s',+ async (condition) => {+ if (condition === 'disabled' || condition === 'missing') {+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig(+ condition === 'disabled' ? false : undefined,+ {}+ )+ }+ if (condition === 'invalid-payload') {+ state.interviewRecruitmentConfig = undefined+ }+ state.isImpersonated = condition === 'impersonated'+ state.suppressAnalytics = condition === 'suppressed'+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ expect(storage.entries.size).toBe(0)+ }+ )++ it.each([+ ['exec', 'scout-trial-get'],+ ['direct', 'scout-trial-get'],+ ['exec', 'scout-rubric-get'],+ ['direct', 'scout-rubric-get'],+ ])('excludes private %s calls to %s from invitations, progress, and analytics', async (mode, toolName) => {+ state.allTools.push({ name: toolName } as (typeof state.allTools)[number])+ const params = callParams()+ if (mode === 'exec') {+ params.arguments = { command: `call ${toolName} {}` }+ } else {+ params.name = toolName+ params.arguments = {}+ }+ expect((await call(dispatcher, params)).result).toMatchObject(toolResult)+ expect(storage.entries.size).toBe(0)+ expect(captureRecruitment).not.toHaveBeenCalled()+ })++ it('waits for three completed product calls and two minutes in the same conversation', async () => {+ vi.useFakeTimers()+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig(true, {+ message: 'Synthetic MCP interview',+ booking_url: 'https://example.com/book',+ })+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ vi.advanceTimersByTime(120_000)+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ expect((await call(dispatcher)).result?.resultType).toBe('input_required')+ expect(executeTool).toHaveBeenCalledTimes(3)+ })++ it.each(['failed', 'search', 'learn', 'skill', 'docs'])(+ 'does not count %s calls toward the warm-up',+ async (kind) => {+ vi.useFakeTimers()+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig(true, {+ message: 'Synthetic MCP interview',+ booking_url: 'https://example.com/book',+ })+ const params = callParams()+ params.arguments = {+ command: {+ failed: 'call project-get {}',+ search: 'search project',+ learn: 'learn -s project',+ skill: 'call skill-get {}',+ docs: 'call docs-search {}',+ }[kind],+ }+ for (let i = 0; i < 3; i++) {+ if (kind === 'failed') {+ executeTool.mockResolvedValueOnce({ ...toolResult, isError: true })+ }+ expect((await call(dispatcher, params)).result?.resultType).toBe('complete')+ }+ vi.advanceTimersByTime(120_000)+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ vi.advanceTimersByTime(120_000)+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ expect((await call(dispatcher)).result?.resultType).toBe('input_required')+ }+ )++ it('does not count a replay of the same completed RPC twice', async () => {+ vi.useFakeTimers()+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig(true, {+ message: 'Synthetic MCP interview',+ booking_url: 'https://example.com/book',+ })+ for (let i = 0; i < 3; i++) {+ expect((await call(dispatcher, callParams(), props, 10)).result).toMatchObject(toolResult)+ }+ vi.advanceTimersByTime(120_000)+ expect((await call(dispatcher, callParams(), props, 11)).result).toMatchObject(toolResult)+ expect((await call(dispatcher, callParams(), props, 12)).result).toMatchObject(toolResult)+ expect((await call(dispatcher, callParams(), props, 13)).result?.resultType).toBe('input_required')+ })++ it.each(['missing conversation', 'different conversation', 'different client', 'different person'])(+ 'does not reuse warm-up progress for a %s',+ async (change) => {+ vi.useFakeTimers()+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig(true, {+ message: 'Synthetic MCP interview',+ booking_url: 'https://example.com/book',+ })+ for (let i = 0; i < 3; i++) {+ await call(dispatcher)+ }+ vi.advanceTimersByTime(120_000)+ if (change === 'missing conversation') {+ state.requestContext.mcpConversationId = undefined+ }+ if (change === 'different conversation') {+ state.requestContext.mcpConversationId = 'conversation-b'+ }+ if (change === 'different client') {+ state.requestContext.mcpClientName = 'another-client'+ }+ if (change === 'different person') {+ state.distinctId = 'another-person'+ }+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ }+ )++ it('reserves only one invitation across simultaneous campaigns and server instances', async () => {+ const otherState = {+ ...state,+ interviewRecruitmentConfig: resolveInterviewRecruitmentConfig('other-study', {+ message: 'Another interview',+ booking_url: 'https://example.com/other',+ min_completed_tool_calls: 0,+ min_session_age_seconds: 0,+ }),+ }+ resolveState.mockResolvedValueOnce(state).mockResolvedValueOnce(otherState)+ const other = new McpDispatcher({} as ToolCatalog, storage.redis)+ const results = await Promise.all([call(dispatcher), call(other)])+ expect(results.filter((r) => r.result?.resultType === 'input_required')).toHaveLength(1)+ expect(executeTool).toHaveBeenCalledTimes(1)+ expect(+ captureRecruitment.mock.calls.filter(([event]) => event.event === 'mcp interview invitation sent')+ ).toHaveLength(1)+ })++ it('does not prompt legacy clients', async () => {+ const legacy = new Request('https://mcp.test/mcp', {+ method: 'POST',+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'exec' } }),+ })+ const result = (await (await dispatcher.handleRequest(legacy, props)).json()) as { result: unknown }+ expect(result.result).toEqual(toolResult)+ expect(storage.entries.size).toBe(0)+ })++ it.each(['token', 'person', 'arguments', 'project', 'organization', 'expired', 'replayed', 'invalid-answer'])(+ 'rejects a %s continuation without executing the tool',+ async (change) => {+ vi.useFakeTimers()+ const invitation = await call(dispatcher)+ const resumed = continuation(invitation.result?.requestState, {+ action: 'accept',+ })+ let continuationProps = props+ if (change === 'token') {+ continuationProps = { ...props, userHash: 'another-token' }+ } else if (change === 'person') {+ state.distinctId = 'another-person'+ } else if (change === 'arguments') {+ resumed.arguments = { command: 'call project-delete {}' }+ } else if (change === 'project') {+ vi.mocked(state.context.stateManager.getProjectId).mockResolvedValue('2')+ } else if (change === 'organization') {+ vi.mocked(state.context.stateManager.getOrgID).mockResolvedValue('org-2')+ } else if (change === 'expired') {+ vi.setSystemTime(Date.now() + 10 * 60 * 1000)+ } else if (change === 'replayed') {+ await call(dispatcher, resumed)+ executeTool.mockClear()+ } else {+ resumed.inputResponses = { 'mcp-interview': { action: 'unknown' } }+ }+ const rejected = await call(dispatcher, resumed, continuationProps)+ expect(rejected.error?.code).toBe(-32602)+ if (change === 'replayed') {+ expect(rejected.error?.message).toContain('already consumed')+ }+ if (change === 'expired') {+ expect(rejected.error?.message).toContain('Check whether the original tool completed')+ }+ expect(executeTool).not.toHaveBeenCalled()+ }+ )++ it('processes a displayed invitation after its flag has been disabled', async () => {+ const invitation = await call(dispatcher)+ state.interviewRecruitmentConfig = undefined+ expect(+ (await call(dispatcher, continuation(invitation.result?.requestState, { action: 'decline' }))).result+ ).toMatchObject(toolResult)+ expect(+ JSON.parse([...storage.entries.entries()].find(([key]) => key.endsWith(':response'))![1].value).response+ ).toBe('do_not_ask_again')+ })++ it('skips the invitation if Redis fails, but retries a response write before executing the tool', async () => {+ vi.mocked(storage.redis.eval).mockRejectedValueOnce(new Error('unavailable'))+ expect((await call(dispatcher)).result).toMatchObject(toolResult)+ executeTool.mockClear()+ const invitation = await call(dispatcher)+ const resumed = continuation(invitation.result?.requestState, { action: 'decline' })+ vi.mocked(storage.redis.eval).mockRejectedValueOnce(new Error('unavailable'))+ expect((await call(dispatcher, resumed)).error?.code).toBe(-32603)+ expect(executeTool).not.toHaveBeenCalled()+ expect((await call(dispatcher, resumed)).result).toMatchObject(toolResult)+ })++ it('keeps original campaign attribution after a flag change and deduplicates actual link opens', async () => {+ vi.useFakeTimers()+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig('first-study', {+ message: 'First interview',+ booking_url: 'https://example.com/first',+ min_completed_tool_calls: 0,+ min_session_age_seconds: 0,+ })+ const invitation = await call(dispatcher)+ const inputs = invitation.result?.inputRequests as Record<string, { params: { url: string } }>+ const url = inputs['mcp-interview']!.params.url+ state.interviewRecruitmentConfig = resolveInterviewRecruitmentConfig('second-study', {+ message: 'Second interview',+ booking_url: 'https://example.com/second',+ })+ const app = new Hono()+ registerPublicRoutes(app, storage.redis, { shuttingDown: false })+ expect(captureRecruitment.mock.calls.map(([event]) => event.event)).toEqual(['mcp interview invitation sent'])+ expect((await app.request(url, { method: 'HEAD' })).status).toBe(405)+ expect(captureRecruitment).toHaveBeenCalledTimes(1)+ const redirects = await Promise.all([app.request(url), app.request(url)])+ for (const redirect of redirects) {+ expect(redirect.status).toBe(302)+ expect(redirect.headers.get('Location')).toBe('https://example.com/first')+ expect(redirect.headers.get('Referrer-Policy')).toBe('no-referrer')+ expect(redirect.headers.get('Cache-Control')).toBe('no-store')+ }+ expect(captureRecruitment.mock.calls.map(([event]) => event.event)).toEqual([+ 'mcp interview invitation sent',+ 'mcp interview booking link opened',+ ])+ await call(dispatcher, continuation(invitation.result?.requestState, { action: 'accept' }))+ expect(captureRecruitment).toHaveBeenLastCalledWith(+ expect.objectContaining({+ event: 'mcp interview invitation responded',+ properties: expect.objectContaining({ response: 'accept' }),+ })+ )+ vi.advanceTimersByTime(7 * 24 * 60 * 60 * 1000)+ expect((await app.request(url)).status).toBe(404)+ expect((await app.request('/interview/unknown?url=https://example.com')).status).toBe(404)+ expect(captureRecruitment).toHaveBeenCalledTimes(3)+ for (const [event] of captureRecruitment.mock.calls) {+ expect(event.properties.campaign_id).toBe('first-study')+ }+ const responseRecord = [...storage.entries.entries()].find(([key]) => key.endsWith(':response'))![1]+ expect(JSON.parse(responseRecord.value).campaign_id).toBe('first-study')+ })++ it('continues the booking redirect and original tool when analytics capture fails', async () => {+ captureRecruitment.mockImplementation(() => {+ throw new Error('capture unavailable')+ })+ try {+ const invitation = await call(dispatcher)+ const app = new Hono()+ registerPublicRoutes(app, storage.redis, { shuttingDown: false })+ const inputs = invitation.result?.inputRequests as Record<string, { params: { url: string } }>+ expect((await app.request(inputs['mcp-interview']!.params.url)).status).toBe(302)+ expect(+ (await call(dispatcher, continuation(invitation.result?.requestState, { action: 'accept' }))).result+ ).toMatchObject(toolResult)+ } finally {+ captureRecruitment.mockReset()+ }+ })++ 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)+ expect(executeTool).toHaveBeenCalledTimes(1)+ } finally {+ await client.close()+ }+ })+})diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex a88be6028e7a..94ed886b7030 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -8,7 +8,9 @@ const {mockRefreshTtlCalls,mockRedisFailures,mockPinned,+ mockGetApiKey,} = vi.hoisted(() => ({+ mockGetApiKey: vi.fn(),mockSessionStore: new Map<string, unknown>(),mockTokenStore: new Map<string, unknown>(),mockApiKey: {@@ -32,7 +34,7 @@ const {}))vi.mock('@/lib/posthog/flags', () => ({- evaluateFeatureFlags: vi.fn(async () => ({})),+ evaluateFeatureFlags: vi.fn(async () => ({ flags: {}, payloads: {} })),resolveFeatureFlagOverrides: vi.fn(() => ({})),}))@@ -122,7 +124,7 @@ vi.mock('@/hono/request-context', () => {return {stateManager: {setDefaultOrganizationAndProject: vi.fn(async () => {}),- getApiKey: vi.fn(async () => mockApiKey),+ getApiKey: mockGetApiKey,getAiConsentGiven: vi.fn(async () => undefined),getAvailableFeatures: vi.fn(async () => undefined),},@@ -141,6 +143,7 @@ vi.mock('@/hono/request-context', () => {import type { RedisLike } from '@/hono/cache/RedisCache'import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'+import { MCP_INTERVIEW_RECRUITMENT_FLAG } from '@/hono/interview-recruitment'import { RequestStateResolver } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { evaluateFeatureFlags, resolveFeatureFlagOverrides } from '@/lib/posthog/flags'@@ -192,6 +195,7 @@ describe('RequestStateResolver MCP client contexts', () => {mockRedisFailures.legacyReadError = undefinedmockRedisFailures.contextReads = 0mockPinned.last = undefined+ mockGetApiKey.mockReset().mockImplementation(async () => mockApiKey)mockApiKey.scopes = ['*']mockApiKey.is_impersonated = undefinedmockApiKey.suppress_analytics = undefined@@ -268,7 +272,10 @@ describe('RequestStateResolver MCP client contexts', () => {if (sandbox) {mockApiKey.scopes.push('internal_run:read')}- vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'tasks-mcp-agent-run-start': true, tasks: true })+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({+ flags: { 'tasks-mcp-agent-run-start': true, tasks: true },+ payloads: {},+ })const catalog = new ToolCatalog()await catalog.warmup()const resolver = new RequestStateResolver(catalog, {} as RedisLike, {} as Env)@@ -483,19 +490,118 @@ describe('RequestStateResolver MCP client contexts', () => {expect(props.mode).toBe('cli')})- it('evaluates the exec skills flag even though no generated tool declares it', async () => {- vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ [MCP_EXEC_SKILLS_FEATURE_FLAG]: true })+ it.each([MCP_EXEC_SKILLS_FEATURE_FLAG, MCP_INTERVIEW_RECRUITMENT_FLAG])(+ 'evaluates %s even though no generated tool declares it',+ async (flag) => {+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ flags: { [flag]: true }, payloads: {} })- const result = await makeResolver().resolve(makeProps())+ const result = await makeResolver().resolve(makeProps())- expect(evaluateFeatureFlags).toHaveBeenCalledWith(- expect.arrayContaining([MCP_EXEC_SKILLS_FEATURE_FLAG]),- 'distinct-id',- undefined- )- expect(result.toolFeatureFlags?.[MCP_EXEC_SKILLS_FEATURE_FLAG]).toBe(true)+ expect(evaluateFeatureFlags).toHaveBeenCalledWith(expect.arrayContaining([flag]), 'distinct-id', undefined)+ expect(result.toolFeatureFlags?.[flag]).toBe(true)+ }+ )++ it.each([+ { taskId: 'test-task' },+ { taskOriginProduct: 'signals_scout' },+ { taskOriginProduct: 'research' },+ { scopes: ['internal_run:read'] },+ { oauthClientId: 'jpSRPhGBBbDGpKprit9bgJEuo6oUTa8ULymqf8PE' },+ { oauthClientId: 'N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu' },+ { oauthClientId: 'jpSRPhGBBbDGpKprit9bgJEuo6oUTa8ULymqf8PE', cold: true },+ { oauthClientId: 'N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu', cold: true },+ { oauthClientId: 'https://posthog.com/.well-known/oauth/webmcp/client-metadata.json' },+ { mcpConsumer: 'posthog-cli' },+ ])('enforces recruitment eligibility even when the flag is forced on: %j', async (input) => {+ if (input.scopes) {+ mockApiKey.scopes = input.scopes+ }+ if (input.oauthClientId) {+ if (input.cold) {+ mockGetApiKey.mockImplementationOnce(async () => {+ await new Promise<void>((resolve) => setImmediate(resolve))+ mockTokenStore.set('oauthClientId', input.oauthClientId)+ mockTokenStore.set('clientName', 'Synthetic first-party application')+ return mockApiKey+ })+ } else {+ mockTokenStore.set('oauthClientId', input.oauthClientId)+ }+ }+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({+ flags: {},+ payloads: {+ [MCP_INTERVIEW_RECRUITMENT_FLAG]: {+ message: 'Synthetic interview',+ booking_url: 'https://example.com/book',+ },+ },+ })+ vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({ [MCP_INTERVIEW_RECRUITMENT_FLAG]: true })+ const result = await makeResolver().resolve(makeProps(input))+ if (input.oauthClientId) {+ expect(result.oauthClientId).toBe(input.oauthClientId)+ }+ expect(result.interviewRecruitmentConfig).toBeUndefined()})+ it.each([+ {+ payload: { message: 'Synthetic interview', booking_url: 'https://example.com/book' },+ expected: {+ campaign_id: 'mcp-research',+ booking_url: 'https://example.com/book',+ min_completed_tool_calls: 3,+ min_session_age_seconds: 120,+ },+ },+ {+ payload: { message: 'A new invitation', booking_url: 'https://example.com/book' },+ expected: { message: 'A new invitation', booking_url: 'https://example.com/book' },+ },+ { payload: { message: '' }, expected: undefined },+ { payload: { booking_url: 'javascript:alert(1)' }, expected: undefined },+ { payload: { booking_url: 'http://example.com/book' }, expected: undefined },+ { payload: { booking_url: 'not a URL' }, expected: undefined },+ { payload: 'invalid', expected: undefined },+ { payload: undefined, expected: undefined },+ { payload: null, expected: undefined },+ { payload: {}, expected: undefined },+ { payload: { message: 'Synthetic interview' }, expected: undefined },+ { payload: { booking_url: 'https://example.com/book' }, expected: undefined },+ {+ value: 'other-study',+ payload: { message: 'Another interview', booking_url: 'https://example.com/other' },+ expected: {+ campaign_id: 'other-study',+ booking_url: 'https://example.com/other',+ min_completed_tool_calls: 3,+ min_session_age_seconds: 120,+ },+ },+ { value: 'other-study', payload: undefined, expected: undefined },+ { value: 'other-study', payload: {}, expected: undefined },+ { value: 'other-study', payload: { message: 'Another interview' }, expected: undefined },+ { value: 'other-study', payload: { booking_url: 'https://example.com/other' }, expected: undefined },+ { value: '', payload: {}, expected: undefined },+ { value: false, payload: {}, expected: undefined },+ ])(+ 'validates recruitment configuration from the flag payload: $payload',+ async ({ value = true, payload, expected }) => {+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({+ flags: { [MCP_INTERVIEW_RECRUITMENT_FLAG]: value },+ payloads: { [MCP_INTERVIEW_RECRUITMENT_FLAG]: payload },+ })+ const state = await makeResolver().resolve(makeProps())+ if (expected) {+ expect(state.interviewRecruitmentConfig).toMatchObject(expected)+ } else {+ expect(state.interviewRecruitmentConfig).toBeUndefined()+ }+ }+ )+it('honors a dev/test flag override even when evaluation returns nothing', async () => {// Evaluation stays empty (analytics client disabled, as in local dev/evals);// the override seam is what flips a tool flag on so it reaches the tool layer.@@ -506,6 +612,45 @@ describe('RequestStateResolver MCP client contexts', () => {expect(result.toolFeatureFlags?.['dev-forced-flag']).toBe(true)})+ it.each([+ { mode: 'development', override: undefined, payload: 'valid', enabled: false },+ { mode: 'development', override: true, payload: undefined, enabled: false },+ { mode: 'development', override: true, payload: '{', enabled: false },+ { mode: 'development', override: true, payload: '{}', enabled: false },+ { mode: 'development', override: true, payload: 'valid', enabled: true },+ { mode: 'development', override: 'other-study', payload: 'valid', enabled: true },+ { mode: 'test', override: true, payload: 'valid', enabled: true },+ { mode: 'production', override: true, payload: 'valid', enabled: false },+ ])('requires explicit local recruitment opt-in and payload: %j', async ({ mode, override, payload, enabled }) => {+ vi.stubEnv('POSTHOG_API_BASE_URL', 'http://localhost:8000')+ vi.stubEnv('NODE_ENV', mode)+ vi.stubEnv(+ 'MCP_INTERVIEW_RECRUITMENT_PAYLOAD',+ payload === 'valid'+ ? JSON.stringify({ message: 'Synthetic local interview', booking_url: 'https://example.com/book' })+ : payload+ )+ try {+ if (override) {+ vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({+ [MCP_INTERVIEW_RECRUITMENT_FLAG]: override,+ })+ }+ const result = await makeResolver().resolve(makeProps())+ if (enabled) {+ expect(result.interviewRecruitmentConfig).toMatchObject({+ campaign_id: typeof override === 'string' ? override : 'mcp-research',+ message: 'Synthetic local interview',+ booking_url: 'https://example.com/book',+ })+ } else {+ expect(result.interviewRecruitmentConfig).toBeUndefined()+ }+ } finally {+ vi.unstubAllEnvs()+ }+ })+describe('pinned project/org context', () => {// What the switch-project handler records on the session (Context.setSessionActiveContext).const simulateSwitch = (mcpSessionId: string, projectId: string, orgId?: string): void => {diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 2249d2e03184..858a4b6c462b 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -31,6 +31,7 @@ vi.mock('@/lib/posthog', async () => {import { InstructionsBuilder } from '@/hono/instructions'import { toolCallsTotal } from '@/hono/metrics'+import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'import { getPostHogClient } from '@/lib/posthog'@@ -480,17 +481,29 @@ describe('ToolExecutor analytics capture', () => {const state = statelessState()await executor.handleToolsList(state)- const first = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, state)+ const observedHandles: (string | undefined)[] = []+ const hooks = {+ beforeExecute: async (callState: ResolvedState): Promise<undefined> => {+ observedHandles.push(callState.requestContext.mcpConversationId)+ return undefined+ },+ afterExecute: async (): Promise<void> => {},+ }+ const first = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, state, hooks)const handle = readConversationHandle(first)expect(handle).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(1))expect(captureSpy.mock.calls[0]![0].conversationId).toBe(handle)+ const secondState = statelessState()const second = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools', conversation_id: handle } },- state+ secondState,+ hooks)+ expect(observedHandles).toEqual([handle, handle])+ expect(secondState.requestContext.mcpConversationId).toBe(handle)await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(2))expect(captureSpy.mock.calls[1]![0].conversationId).toBe(handle)diff --git a/services/mcp/tests/unit/feature-flag-version.test.ts b/services/mcp/tests/unit/feature-flag-version.test.tsindex 382027379c0a..10fbe02123ac 100644--- a/services/mcp/tests/unit/feature-flag-version.test.ts+++ b/services/mcp/tests/unit/feature-flag-version.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'const mockIsFeatureEnabled = vi.fn()-const mockGetAllFlags = vi.fn()+const mockGetAllFlagsAndPayloads = vi.fn()// Mock the client `flags.ts` consumes, not posthog-node directly: `getPostHogClient()`// returns a `PostHogMCP` (a posthog-node subclass) from the externalized// `@posthog/mcp-analytics`, whose internal posthog-node import a `vi.mock('posthog-node')`@@ -9,7 +9,7 @@ const mockGetAllFlags = vi.fn()vi.mock('@/lib/posthog/client', () => ({getPostHogClient: () => ({isFeatureEnabled: mockIsFeatureEnabled,- getAllFlags: mockGetAllFlags,+ getAllFlagsAndPayloads: mockGetAllFlagsAndPayloads,}),}))@@ -74,30 +74,36 @@ describe('evaluateFeatureFlags', () => {vi.clearAllMocks()})- it('should evaluate multiple flags via getAllFlags and forward groups', async () => {- mockGetAllFlags.mockResolvedValue({ 'flag-on': true, 'flag-off': false, unrelated: true })+ it('should evaluate multiple flags with their payloads and forward groups', async () => {+ mockGetAllFlagsAndPayloads.mockResolvedValue({+ featureFlags: { 'flag-on': true, 'flag-off': false, unrelated: true },+ featureFlagPayloads: { 'flag-on': { message: 'Example invitation' } },+ })const result = await evaluateFeatureFlags(['flag-on', 'flag-off'], 'user-123', { organization: 'org-abc' })- expect(result).toEqual({ 'flag-on': true, 'flag-off': false })- expect(mockGetAllFlags).toHaveBeenCalledWith('user-123', {+ expect(result).toEqual({+ flags: { 'flag-on': true, 'flag-off': false },+ payloads: { 'flag-on': { message: 'Example invitation' } },+ })+ expect(mockGetAllFlagsAndPayloads).toHaveBeenCalledWith('user-123', {flagKeys: ['flag-on', 'flag-off'],groups: { organization: 'org-abc' },})})it('should omit groups when not provided', async () => {- mockGetAllFlags.mockResolvedValue({ 'flag-a': true })+ mockGetAllFlagsAndPayloads.mockResolvedValue({ featureFlags: { 'flag-a': true }, featureFlagPayloads: {} })await evaluateFeatureFlags(['flag-a'], 'user-123')- expect(mockGetAllFlags).toHaveBeenCalledWith('user-123', { flagKeys: ['flag-a'] })+ expect(mockGetAllFlagsAndPayloads).toHaveBeenCalledWith('user-123', { flagKeys: ['flag-a'] })})it('should short-circuit when no flag keys are requested', async () => {const result = await evaluateFeatureFlags([], 'user-123', { organization: 'org-abc' })- expect(result).toEqual({})- expect(mockGetAllFlags).not.toHaveBeenCalled()+ expect(result).toEqual({ flags: {}, payloads: {} })+ expect(mockGetAllFlagsAndPayloads).not.toHaveBeenCalled()})})