Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): default to cli mode, keep tools mode for cursor and chatgpt (#69629)

Georgiy Tarasov03ae6601b075
diff --git a/services/mcp/README.md b/services/mcp/README.md
index bbb3a115fa1f..45d6f4e4796d 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -266,7 +266,9 @@ The example above exposes all flag tools plus `dashboard-get`.
### Server mode (tools vs cli)
-The MCP server can register either every PostHog tool individually (**tools** mode, the default for most clients) or wrap them all behind a single `posthog` CLI-like tool (**cli** mode, used for token-constrained coding agents). When the caller does not say which mode they want, the server picks one automatically based on the client (coding agents get the cli mode when the rollout flag is enabled).
+The MCP server can register either every PostHog tool individually (**tools** mode) or wrap them all behind a single `posthog` CLI-like tool (**cli** mode).
+**cli is the default for all clients.**
+When the caller does not pin a mode, the server only auto-selects tools mode for a short allow-list of clients that are better served by the full per-tool roster — currently Cursor (matched by its self-reported client name or its `Cursor/…` User-Agent) and ChatGPT (matched by its `openai-mcp … (ChatGPT)` User-Agent).
You can pin the choice yourself with either a query parameter or a header. Only `tools` and `cli` are accepted:
@@ -285,7 +287,8 @@ x-posthog-mcp-mode: tools
| `tools` | Force tools mode (one MCP tool per PostHog tool). |
| `cli` | Force cli mode (single `posthog` tool wraps all tools). |
-The header wins when both the header and the query parameter are set. Any other value is ignored and the auto-detection takes over.
+The header wins when both the header and the query parameter are set.
+An explicit value always wins over the client auto-detection; any other value is ignored and the auto-detection takes over.
### Consumer attribution
diff --git a/services/mcp/evals/runner/probe.ts b/services/mcp/evals/runner/probe.ts
index e06f32b5ce66..6805a057697a 100644
--- a/services/mcp/evals/runner/probe.ts
+++ b/services/mcp/evals/runner/probe.ts
@@ -87,7 +87,10 @@ async function main(): Promise<void> {
const benchmark = loadBenchmark()
const transport = new StreamableHTTPClientTransport(new URL('/mcp', url), {
- requestInit: { headers: { Authorization: `Bearer ${token}` } },
+ // Pin tools mode: the probe audits the full per-tool roster, and the
+ // server's auto-detection would otherwise resolve this client to the
+ // single-exec CLI default.
+ requestInit: { headers: { Authorization: `Bearer ${token}`, 'x-posthog-mcp-mode': 'tools' } },
})
const client = new Client({ name: 'mcp-eval-probe', version: '0.0.0' }, { capabilities: {} })
await client.connect(transport)
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 89d74f4e3718..9a1e64ff7b45 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -51,27 +51,16 @@ export interface ResolvedState {
// ─── Pure helpers ───
-export function resolveMode(args: {
- mode: McpMode | undefined
- clientProfile: MCPClientProfile
- // The raw `mcp-render-ui` flag value — NOT the UI-host-gated `renderUiEnabled`
- // on ResolvedState; the UI-host check is applied here, on the flag.
- renderUiFlagEnabled: boolean
-}): {
+export function resolveMode(args: { mode: McpMode | undefined; clientProfile: MCPClientProfile }): {
mode: McpMode
useSingleExec: boolean
} {
- const { mode, clientProfile, renderUiFlagEnabled } = args
- const useSingleExec =
- mode === 'cli' ||
- (mode !== 'tools' &&
- (clientProfile.isCliModeEnabled() ||
- clientProfile.isPostHogCodeConsumer() ||
- clientProfile.isVibeCodingClient() ||
- // Claude web/desktop render MCP Apps UI; put them in single-exec so
- // `render-ui` is available — but only when the feature flag is on.
- (renderUiFlagEnabled && clientProfile.isClaudeUiHost())))
- return { mode: mode ?? (useSingleExec ? 'cli' : 'tools'), useSingleExec }
+ const { mode, clientProfile } = args
+ // CLI (single-exec) is the default; only allow-listed clients (Cursor,
+ // ChatGPT) keep the full per-tool roster, and an explicit ?mode= /
+ // x-posthog-mcp-mode header always wins over auto-detection.
+ const resolved: McpMode = mode ?? (clientProfile.isToolsModeClient() ? 'tools' : 'cli')
+ return { mode: resolved, useSingleExec: resolved === 'cli' }
}
// ─── Resolver ───
@@ -163,14 +152,12 @@ export class RequestStateResolver {
// mount its iframe. The flag is necessary but not sufficient: Claude Code and other
// single-exec CLI clients pool the same flag value, so the tool's advertisement and
// execution must also require the UI-host check — otherwise rolling the flag out to
- // everyone leaks `render-ui` into Claude Code. `resolveMode` applies the same gate
- // independently for its single-exec decision, so it receives the raw flag value.
+ // everyone leaks `render-ui` into Claude Code.
const renderUiEnabled = renderUiFlagEnabled && clientProfile.isClaudeUiHost()
const { mode: resolvedMode, useSingleExec } = resolveMode({
mode: requestContext.mode,
clientProfile,
- renderUiFlagEnabled,
})
requestContext.mode = resolvedMode
reqCtx.setMcpContexts(requestContext, sessionContext)
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
index 3b92565beb2d..f93f39b831f6 100644
--- a/services/mcp/src/index.ts
+++ b/services/mcp/src/index.ts
@@ -297,7 +297,7 @@ const handleRequest = async (
const readOnly = readOnlyRaw === 'true' || readOnlyRaw === '1' || undefined
// Explicit selection between tool-based and CLI-based MCP. Falls back to the
- // flag + client-detection logic in `MCP.init()` when unset. See `parseMcpMode`.
+ // client-detection logic in `resolveMode` when unset. See `parseMcpMode`.
const mode = parseMcpMode(request.headers.get('x-posthog-mcp-mode') || url.searchParams.get('mode'))
const extraContextProps = { features, tools, region: regionParam, version, readOnly, mode }
diff --git a/services/mcp/src/lib/client-detection.ts b/services/mcp/src/lib/client-detection.ts
index 7066f890d3d3..ee92876573eb 100644
--- a/services/mcp/src/lib/client-detection.ts
+++ b/services/mcp/src/lib/client-detection.ts
@@ -8,29 +8,26 @@
*
* The `MCPClientProfile` class owns all per-client behavior decisions:
*
- * - `isCliModeEnabled()` matches clients that should default to single-exec
- * ("CLI") mode and drop `structuredContent` when a `formatted_results`
- * override is set. Every known Anthropic client qualifies — matched against
- * the `x-anthropic-client` (`vendorClient`) header, since Anthropic pools MCP
- * transports across all its products and reports the live one there. Other
- * coding agents are matched by self-reported client name. Cursor is
- * deliberately excluded from the name match — it reads text for the model and
- * renders `structuredContent` in UI, so it does not need single-exec mode or
- * the formatted-results workaround.
+ * - `isToolsModeClient()` matches the clients that keep the full per-tool
+ * roster ("tools" mode) instead of the single-exec CLI default. This is the
+ * only way a client lands in tools mode without an explicit `?mode=` /
+ * `x-posthog-mcp-mode` override — see `resolveMode`.
+ *
+ * - `isCliModeEnabled()` matches clients that should drop `structuredContent`
+ * when a `formatted_results` override is set. Every known Anthropic client
+ * qualifies — matched against the `x-anthropic-client` (`vendorClient`)
+ * header, since Anthropic pools MCP transports across all its products and
+ * reports the live one there. Other coding agents are matched by
+ * self-reported client name. Cursor is deliberately excluded from the name
+ * match — it reads text for the model and renders `structuredContent` in UI,
+ * so it does not need the formatted-results workaround.
*
* - `isPostHogCodeConsumer()` matches the `x-posthog-mcp-consumer` header
* sent by the PostHog Code Tasks wrapper.
*
- * - `isVibeCodingClient()` matches the OAuth application name (returned by
- * token introspection — see `StateManager._fetchApiKey`). Vibe-coding
- * platforms like Lovable and Replit connect through their own OAuth app
- * while reporting a generic `clientInfo.name`, so the OAuth name is the
- * reliable identifier. Used to force single-exec mode regardless of the
- * self-reported MCP client name.
- *
* - `isClaudeUiHost()` matches Claude web/desktop and Cowork — MCP Apps hosts
- * that render interactive UI (iframes). Used to put them in single-exec mode so
- * the `render-ui` tool is available, gated behind the `mcp-render-ui` flag.
+ * that render interactive UI (iframes). Used to advertise the `render-ui`
+ * tool to them, gated behind the `mcp-render-ui` flag.
*
* - `isClaudeChatHost()` matches Claude web/desktop only — the chat surfaces that
* report `supportsInstructions` but never surface the `instructions` payload to
@@ -57,11 +54,13 @@ function matchesAnyFragment(clientName: string | undefined, fragments: readonly
return fragments.some((fragment) => normalized.includes(normalizeClientName(fragment)))
}
+// Coding agents and LLM-driven clients that render text rather than MCP Apps UI.
+// Matched by `isCliModeEnabled()`, which gates dropping `structuredContent` when a
+// `formatted_results` override is set. Mode selection does NOT read this list — CLI
+// (single-exec) is the default for every client; `TOOLS_MODE_CLIENT_NAME_FRAGMENTS`
+// is the tools-mode allow-list.
export const CODING_AGENT_CLIENT_NAME_FRAGMENTS = [
'claude-code',
- // Cursor sends `content[].text` to the model and displays `structuredContent` in UI,
- // so it doesn't need this workaround — leaving structuredContent available for the UI.
- // 'cursor',
'cline',
'roo-code',
'roo-cline',
@@ -104,6 +103,20 @@ export const CODING_AGENT_CLIENT_NAME_FRAGMENTS = [
'ando-mcp-gateway',
] as const
+// Clients that keep the full per-tool roster ("tools" mode) instead of the
+// single-exec CLI default.
+// - Cursor self-reports `clientInfo.name` (`cursor-vscode`, `Cursor`); it sends
+// `content[].text` to the model and renders `structuredContent` in its UI, so
+// the full roster serves it better than the exec wrapper. Some older Cursor
+// builds omit `clientInfo.name` and are only identifiable by their
+// `Cursor/x.y.z (...)` User-Agent, hence the UA fragment too.
+// - ChatGPT connects through OpenAI's shared `openai-mcp` client whose
+// `clientInfo.name` is generic; the surface only shows up in the User-Agent
+// parenthetical (`openai-mcp/1.0.0 (ChatGPT)`). Other openai-mcp surfaces
+// (Codex, Agent Builder, Responses API) stay on the CLI default.
+export const TOOLS_MODE_CLIENT_NAME_FRAGMENTS = ['cursor', 'chatgpt'] as const
+export const TOOLS_MODE_USER_AGENT_FRAGMENTS = ['cursor', 'chatgpt'] as const
+
// Known `x-anthropic-client` (`vendorClient`) header values. Anthropic pools
// MCP transports across all its products and reports the live one in this
// header, so it's the reliable identifier for an Anthropic client (the
@@ -150,23 +163,11 @@ export function resolveEffectiveClientName(
// Value sent in `x-posthog-mcp-consumer` by PostHog Code (the Tasks sandbox
// wrapper around the Claude Agent SDK) when the task was launched from the
-// PostHog Code UI. Used to force coding-agent behavior and to gate UI-apps
-// emission in single-exec mode. Slack-launched runs send `"slack"` and
-// posthog_ai (Max) runs send `"posthog_ai"`; only PostHog Code renders MCP UI
-// apps, so this is the sole consumer that gates UI-apps payload emission.
+// PostHog Code UI. Slack-launched runs send `"slack"` and posthog_ai (Max) runs
+// send `"posthog_ai"`; only PostHog Code renders MCP UI apps, so this is the
+// sole consumer that gates UI-apps payload emission in single-exec mode.
export const POSTHOG_CODE_CONSUMER = 'posthog-code'
-// OAuth application names (from token introspection) for upstream tools that
-// should default to single-exec mode. These match against the OAuth
-// `client_name` (the registered OAuth app name in PostHog), not the MCP
-// `clientInfo.name` self-report — many of these platforms connect through a
-// generic MCP client wrapper, so the OAuth name is what reliably identifies
-// the upstream tool. Substring match is case-insensitive and separator-agnostic
-// so "Lovable", "Lovable.dev", "Replit", and "Replit Agent" all resolve.
-// Notion is included here because a sizeable share of sessions only carry the
-// OAuth name without the `notion-mcp-client` self-report.
-export const VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS = ['lovable', 'replit', 'notion'] as const
-
// Claude web/desktop and Cowork are MCP Apps hosts that render interactive UI
// (iframes), so the `render-ui` tool is meaningful for them. They send
// `x-anthropic-client: ClaudeAI` / `Cowork` (vs `ClaudeCode` for Claude Code) and
@@ -212,13 +213,19 @@ export const DEFAULT_CLIENT_CAPABILITIES: ClientCapabilities = {
}
type CapabilityOverride = {
+ // Matched against the self-reported `clientInfo.name`.
fragments: readonly string[]
+ // Matched against the User-Agent, for surfaces that omit `clientInfo.name`
+ // entirely — Codex through OpenAI's shared `openai-mcp` client identifies
+ // only via `openai-mcp/x.y.z (Codex)`.
+ userAgentFragments?: readonly string[]
capabilities: Partial<ClientCapabilities>
}
const CLIENT_CAPABILITY_OVERRIDES: readonly CapabilityOverride[] = [
{
fragments: ['codex'],
+ userAgentFragments: ['codex'],
capabilities: { supportsInstructions: false },
},
]
@@ -255,8 +262,22 @@ export class MCPClientProfile {
this.userAgent = input.userAgent
}
+ isToolsModeClient(): boolean {
+ // The only clients that auto-select the full per-tool roster; everyone
+ // else defaults to CLI (single-exec) mode — see `resolveMode`. Matched on
+ // the self-reported `clientInfo.name` and the User-Agent (ChatGPT's
+ // surface only appears in the UA parenthetical); never on the vendor
+ // header, so Anthropic pooled transports can't land in tools mode.
+ return (
+ matchesAnyFragment(this.clientName, TOOLS_MODE_CLIENT_NAME_FRAGMENTS) ||
+ matchesAnyFragment(this.userAgent, TOOLS_MODE_USER_AGENT_FRAGMENTS)
+ )
+ }
+
isCliModeEnabled(): boolean {
- // Every Anthropic product runs in CLI (single-exec) mode.
+ // Gates dropping `structuredContent` when a `formatted_results` override
+ // is set — these clients read `content[].text`, so the structured copy
+ // would only bloat the payload. Every Anthropic product qualifies.
if (this.isAnthropicClient()) {
return true
}
@@ -284,10 +305,6 @@ export class MCPClientProfile {
return this.consumer === POSTHOG_CODE_CONSUMER
}
- isVibeCodingClient(): boolean {
- return matchesAnyFragment(this.oauthClientName, VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS)
- }
-
isClaudeUiHost(): boolean {
// The per-request vendor client (`x-anthropic-client`) is authoritative: it
// distinguishes the Claude surfaces that pool the same MCP transport —
@@ -336,7 +353,10 @@ export class MCPClientProfile {
private _resolveCapabilities(): ClientCapabilities {
const resolved: ClientCapabilities = { ...DEFAULT_CLIENT_CAPABILITIES }
for (const override of CLIENT_CAPABILITY_OVERRIDES) {
- if (matchesAnyFragment(this.clientName, override.fragments)) {
+ if (
+ matchesAnyFragment(this.clientName, override.fragments) ||
+ matchesAnyFragment(this.userAgent, override.userAgentFragments ?? [])
+ ) {
Object.assign(resolved, override.capabilities)
}
}
@@ -352,8 +372,8 @@ export function isPostHogCodeConsumer(mcpConsumer: string | undefined): boolean
return new MCPClientProfile({ consumer: mcpConsumer }).isPostHogCodeConsumer()
}
-export function isVibeCodingClient(oauthClientName: string | undefined): boolean {
- return new MCPClientProfile({ oauthClientName }).isVibeCodingClient()
+export function isToolsModeClient(clientName: string | undefined, userAgent?: string | undefined): boolean {
+ return new MCPClientProfile({ clientName, userAgent }).isToolsModeClient()
}
export function isClaudeUiHostClient(args: {
diff --git a/services/mcp/src/lib/utils.ts b/services/mcp/src/lib/utils.ts
index 8151aa56fdb0..b7f7a656b15a 100644
--- a/services/mcp/src/lib/utils.ts
+++ b/services/mcp/src/lib/utils.ts
@@ -63,8 +63,8 @@ export type McpMode = 'tools' | 'cli'
// Caller-supplied selection between the tool-based MCP (each PostHog tool registered
// individually) and the CLI-based MCP (a single `posthog` CLI-like tool that wraps
-// all tools). Anything other than `tools` or `cli` returns undefined and lets the
-// auto-detection in `MCP.init()` pick.
+// all tools). Anything other than `tools` or `cli` returns undefined and lets
+// `resolveMode` pick: cli by default, tools for allow-listed clients (Cursor, ChatGPT).
export function parseMcpMode(raw: string | null | undefined): McpMode | undefined {
const value = raw?.trim().toLowerCase()
return value === 'tools' ? 'tools' : value === 'cli' ? 'cli' : undefined
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index 469107606ea2..6afe540c04eb 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -142,18 +142,41 @@ describe('RequestStateResolver MCP client contexts', () => {
})
it('uses cached session client props when request client detection would resolve differently', async () => {
- await makeResolver().resolve(makeProps())
+ // Cursor pins tools mode at initialize; a later request self-reporting a
+ // cli-defaulting client must not downgrade the session out of tools mode.
+ await makeResolver().resolve(makeProps({ mcpClientName: 'cursor' }))
- const props = makeProps({ mcpClientName: 'Claude Desktop' })
+ const props = makeProps({ mcpClientName: 'claude-code' })
+ const result = await makeResolver().resolve(props)
+
+ expect(result.useSingleExec).toBe(false)
+ expect(props.mode).toBe('tools')
+ expect(props.mcpClientName).toBe('claude-code')
+ expect(result.requestContext.mcpClientName).toBe('claude-code')
+ expect(result.sessionContext?.mcpClientName).toBe('cursor')
+ expect(result.clientProfile.clientName).toBe('cursor')
+ })
+
+ it('auto-selects tools mode from the ChatGPT user-agent', async () => {
+ // ChatGPT's clientInfo.name is generic; the surface only shows up in the
+ // User-Agent. Guards the `userAgent: props.clientUserAgent` profile plumbing.
+ const props = makeProps({ mcpClientName: undefined, clientUserAgent: 'openai-mcp/1.0.0 (ChatGPT)' })
+ const result = await makeResolver().resolve(props)
+
+ expect(result.useSingleExec).toBe(false)
+ expect(props.mode).toBe('tools')
+ })
+
+ it('defaults to cli mode when no client hints are present', async () => {
+ const props = makeProps({
+ mcpClientName: undefined,
+ mcpClientVersion: undefined,
+ mcpProtocolVersion: undefined,
+ })
const result = await makeResolver().resolve(props)
expect(result.useSingleExec).toBe(true)
expect(props.mode).toBe('cli')
- expect(props.mcpClientName).toBe('Claude Desktop')
- expect(result.requestContext.mcpClientName).toBe('Claude Desktop')
- expect(result.sessionContext?.mcpClientName).toBe('claude-code')
- expect(result.clientProfile.clientName).toBe('claude-code')
- expect(result.clientProfile.isCliModeEnabled()).toBe(true)
})
it('uses cached session client props for instruction capabilities without overwriting request props', async () => {
diff --git a/services/mcp/tests/hono/session-mode-pool.test.ts b/services/mcp/tests/hono/session-mode-pool.test.ts
index 75a18d388ef7..f2c549c36d14 100644
--- a/services/mcp/tests/hono/session-mode-pool.test.ts
+++ b/services/mcp/tests/hono/session-mode-pool.test.ts
@@ -4,15 +4,14 @@
// `x-anthropic-client` header. The server caches the initial raw session
// identity hints and derives mode from those cached-first hints; a later
// `tools/call` carrying a different vendor must NOT flip the resolved
-// mode/version.
+// mode/version. The same pinning protects a tools-mode session (Cursor) from
+// being dragged back to the cli default by a mid-session vendor header.
//
// To probe the resolved mode DIRECTLY we issue a raw `tools/list` on the pooled
// session: cli (single-exec) mode collapses the wire roster to a single `exec`
-// tool, while tools mode exposes the full multi-tool roster. If cli mode
-// survives the vendor flip, a `tools/list` carrying the flipped vendor still
-// returns just `[exec]`; if mode flipped to tools, it would return the full
-// roster. That's a direct observable for "the resolved mode at headers_2 equals
-// the resolved mode at headers_1".
+// tool, while tools mode exposes the full multi-tool roster. That's a direct
+// observable for "the resolved mode at headers_2 equals the resolved mode at
+// headers_1".
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { setupServer } from 'msw/node'
@@ -103,18 +102,13 @@ async function listToolsOnSession(sessionId: string, vendorClient: string): Prom
}
describe('Resolved mode is preserved across pooled-transport vendor flips', () => {
- it('cli init via x-anthropic-client survives a non-coding-agent vendor on the same session', async () => {
- // headers_1 — clientInfo.name is the new Claude Desktop-style vendor-prefixed
- // shape (NOT a coding-agent fragment), while the per-request vendor header
- // identifies the inner client as Claude Code. This is the production-pool
- // scenario where the body identifies the transport-owner and the header
- // identifies the live consumer.
- //
- // Without reading the vendor header, the resolver picks tools mode at
- // init (because `Anthropic/ClaudeAI` doesn't match any coding-agent
- // fragment) and the SDK gets the full multi-tool roster. With vendor
- // reading + cached session hints, the resolver picks cli mode at init
- // and the SDK gets the wrapped `[exec]` roster.
+ it('cli init via x-anthropic-client survives a vendor flip on the same session', async () => {
+ // headers_1 — clientInfo.name is the vendor-prefixed pool-owner shape, while
+ // the per-request vendor header identifies the inner client as Claude Code.
+ // This is the production-pool scenario where the body identifies the
+ // transport-owner and the header identifies the live consumer. Neither
+ // matches the tools-mode allow-list, so the session resolves to the cli
+ // default and the SDK gets the wrapped `[exec]` roster at init.
const transportA = new StreamableHTTPClientTransport(new URL('/mcp', BASE_URL), {
fetch: fetchViaApp,
requestInit: {
@@ -136,15 +130,43 @@ describe('Resolved mode is preserved across pooled-transport vendor flips', () =
const cachedTools = await clientA.listTools()
expect(cachedTools.tools.map((t) => t.name).sort()).toEqual(['exec'])
- // headers_2 — pool member flipping to a different Anthropic vendor.
- // `ClaudeAI` is itself an Anthropic client, so it resolves to cli mode on
- // its own merits; combined with the cached session hints from init, the
- // request stays in cli mode and the roster still collapses to the `exec`
- // umbrella tool. Every Anthropic vendor (the `x-anthropic-client` header)
- // runs in cli mode, so no pooled vendor flip can downgrade to tools mode.
+ // headers_2 — pool member flipping to a different Anthropic vendor. The
+ // vendor header never participates in tools-mode detection, so the request
+ // stays in cli mode and the roster still collapses to the `exec` umbrella
+ // tool.
const pooledRoster = await listToolsOnSession(sessionId!, 'ClaudeAI')
expect(pooledRoster.map((t) => t.name).sort()).toEqual(['exec'])
await clientA.close()
})
+
+ it('tools init via the Cursor client name survives an Anthropic vendor flip on the same session', async () => {
+ // Cursor pins tools mode through its self-reported clientInfo.name at init.
+ // A later request on the pooled session carrying an Anthropic vendor header
+ // must not flip the session to the cli default: `isToolsModeClient` reads
+ // only the session-pinned client name and user-agent, never the vendor.
+ const transport = new StreamableHTTPClientTransport(new URL('/mcp', BASE_URL), {
+ fetch: fetchViaApp,
+ requestInit: {
+ headers: { Authorization: `Bearer ${TOKEN}` },
+ },
+ })
+ const client = new Client({ name: 'cursor', version: '1.0.0' }, { capabilities: {} })
+ await client.connect(transport as ConnectableTransport)
+
+ const sessionId = transport.sessionId
+ expect(sessionId).toBeTruthy()
+
+ // Tools mode exposes the full multi-tool roster on the wire.
+ const initRoster = await client.listTools()
+ expect(initRoster.tools.length).toBeGreaterThan(1)
+ expect(initRoster.tools.map((t) => t.name)).not.toContain('exec')
+
+ // The vendor flip keeps the pinned tools mode.
+ const pooledRoster = await listToolsOnSession(sessionId!, 'ClaudeCode')
+ expect(pooledRoster.length).toBeGreaterThan(1)
+ expect(pooledRoster.map((t) => t.name)).not.toContain('exec')
+
+ await client.close()
+ })
})
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
index 45d9c3d4fcac..2b52254aa483 100644
--- a/services/mcp/tests/integration/mcp-protocol-suite.ts
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -41,8 +41,12 @@ function buildStreamableClient(
token: string = harness.token
): { client: Client; transport: StreamableHTTPClientTransport } {
const transport = new StreamableHTTPClientTransport(new URL('/mcp', harness.baseUrl), {
+ // Pin tools mode: this suite exercises the per-tool roster, and the
+ // server's auto-detection would otherwise resolve this client to the
+ // single-exec cli default. Exec-mode coverage pins `cli` explicitly
+ // via `buildExecModeClient`.
fetch: harness.fetch,
- requestInit: { headers: { Authorization: `Bearer ${token}` } },
+ requestInit: { headers: { Authorization: `Bearer ${token}`, 'x-posthog-mcp-mode': 'tools' } },
})
const client = new Client({ name: 'mcp-integration-test', version: '0.0.0' }, { capabilities: {} })
return { client, transport }
@@ -1307,8 +1311,10 @@ export function defineCatalogFilterTests(
const url = new URL('/mcp', harness.baseUrl)
url.search = search
const transport = new StreamableHTTPClientTransport(url, {
+ // Pin tools mode — catalog filtering is observed on the full
+ // per-tool roster, not the single-exec cli default.
fetch: harness.fetch,
- requestInit: { headers: { Authorization: `Bearer ${harness.token}` } },
+ requestInit: { headers: { Authorization: `Bearer ${harness.token}`, 'x-posthog-mcp-mode': 'tools' } },
})
const client = new Client({ name: 'filter-test', version: '0.0.0' }, { capabilities: {} })
try {
diff --git a/services/mcp/tests/unit/client-detection.test.ts b/services/mcp/tests/unit/client-detection.test.ts
index 46afac0fb083..d4ff28f34471 100644
--- a/services/mcp/tests/unit/client-detection.test.ts
+++ b/services/mcp/tests/unit/client-detection.test.ts
@@ -8,11 +8,12 @@ import {
DEFAULT_CLIENT_CAPABILITIES,
MCPClientProfile,
POSTHOG_CODE_CONSUMER,
- VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS,
+ TOOLS_MODE_CLIENT_NAME_FRAGMENTS,
+ TOOLS_MODE_USER_AGENT_FRAGMENTS,
isClaudeUiHostClient,
isCliModeEnabledClient,
isPostHogCodeConsumer,
- isVibeCodingClient,
+ isToolsModeClient,
resolveEffectiveClientName,
} from '@/lib/client-detection'
@@ -89,7 +90,8 @@ describe('isCliModeEnabledClient', () => {
describe('explicitly excluded clients', () => {
// Cursor sends content[].text to the model and displays structuredContent in UI,
- // so the workaround isn't needed. Guard against someone adding it back.
+ // so the formatted-results suppression isn't needed. Guard against someone
+ // adding it to the coding-agent list.
it('returns false for cursor (intentionally excluded)', () => {
expect(isCliModeEnabledClient('cursor')).toBe(false)
expect(isCliModeEnabledClient('Cursor')).toBe(false)
@@ -180,39 +182,44 @@ describe('isPostHogCodeConsumer', () => {
})
})
-describe('isVibeCodingClient', () => {
+describe('isToolsModeClient', () => {
+ it.each([['cursor'], ['Cursor'], ['cursor-vscode'], ['cursor/1.2.3'], ['cursor-editor']])(
+ 'returns true for client name %s',
+ (clientName) => {
+ expect(isToolsModeClient(clientName)).toBe(true)
+ }
+ )
+
it.each([
- ['Lovable'],
- ['lovable'],
- ['LOVABLE'],
- ['Lovable.dev'],
- ['lovable-app'],
- ['Replit'],
- ['replit'],
- ['Replit Agent'],
- ['replit-ai'],
- ['Notion'],
- ['notion'],
- ])('returns true for OAuth client name %s', (oauthClientName) => {
- expect(isVibeCodingClient(oauthClientName)).toBe(true)
+ // ChatGPT never self-reports a client name; the surface is UA-only.
+ ['openai-mcp/1.0.0 (ChatGPT)'],
+ // Older Cursor builds omit clientInfo.name and identify only via UA.
+ ['Cursor/3.1.15 (darwin arm64)'],
+ ])('returns true for the name-less user-agent %s', (userAgent) => {
+ expect(isToolsModeClient(undefined, userAgent)).toBe(true)
})
- it.each([['Claude Code (posthog)'], ['Cursor'], ['some-random-app'], ['']])(
- 'returns false for OAuth client name %s',
- (oauthClientName) => {
- expect(isVibeCodingClient(oauthClientName)).toBe(false)
+ it.each([['openai-mcp/1.0.0'], ['openai-mcp/1.0.0 (Codex)'], ['openai-mcp/1.0.0 (Agent Builder)']])(
+ 'returns false for the non-ChatGPT openai-mcp surface %s',
+ (userAgent) => {
+ expect(isToolsModeClient(undefined, userAgent)).toBe(false)
}
)
- it('returns false for undefined', () => {
- expect(isVibeCodingClient(undefined)).toBe(false)
- })
+ it.each([['claude-code'], ['mcp-inspector'], ['some-random-tool'], [''], [undefined]])(
+ 'returns false for client name %s',
+ (clientName) => {
+ expect(isToolsModeClient(clientName)).toBe(false)
+ }
+ )
- it('keeps the fragment list non-empty and lowercased', () => {
- expect(VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS.length).toBeGreaterThan(0)
- for (const fragment of VIBE_CODING_OAUTH_CLIENT_NAME_FRAGMENTS) {
- expect(fragment).toBe(fragment.toLowerCase())
- expect(fragment.length).toBeGreaterThan(0)
+ it('keeps the fragment lists non-empty and lowercased', () => {
+ for (const fragments of [TOOLS_MODE_CLIENT_NAME_FRAGMENTS, TOOLS_MODE_USER_AGENT_FRAGMENTS]) {
+ expect(fragments.length).toBeGreaterThan(0)
+ for (const fragment of fragments) {
+ expect(fragment).toBe(fragment.toLowerCase())
+ expect(fragment.length).toBeGreaterThan(0)
+ }
}
})
})
@@ -368,35 +375,14 @@ describe('MCPClientProfile', () => {
})
})
- describe('isVibeCodingClient()', () => {
- it.each([['Lovable'], ['lovable.dev'], ['Replit'], ['Replit Agent'], ['Notion']])(
- 'returns true for OAuth client name %s',
- (oauthClientName) => {
- expect(new MCPClientProfile({ oauthClientName }).isVibeCodingClient()).toBe(true)
- }
- )
-
- it.each([['Claude Code (posthog)'], ['Cursor'], [''], [' ']])(
- 'returns false for OAuth client name %s',
- (oauthClientName) => {
- expect(new MCPClientProfile({ oauthClientName }).isVibeCodingClient()).toBe(false)
- }
- )
-
- it('returns false when oauthClientName is undefined', () => {
- expect(new MCPClientProfile({}).isVibeCodingClient()).toBe(false)
- })
-
- it('uses oauthClientName, not the MCP clientName', () => {
- // A generic MCP client name should not trigger a match — only the
- // OAuth application name does, since vibe-coding platforms typically
- // wrap a generic MCP client.
- expect(
- new MCPClientProfile({ clientName: 'lovable', oauthClientName: 'Cursor' }).isVibeCodingClient()
- ).toBe(false)
- expect(
- new MCPClientProfile({ clientName: 'mcp-inspector', oauthClientName: 'Lovable' }).isVibeCodingClient()
- ).toBe(true)
+ describe('isToolsModeClient()', () => {
+ it('does not match the vendor header — Anthropic pooled transports stay in cli mode', () => {
+ // Only the self-reported name and the user-agent participate; a vendor
+ // value that happened to contain a tools-mode fragment must not match.
+ expect(new MCPClientProfile({ vendorClient: 'cursor' }).isToolsModeClient()).toBe(false)
+ expect(new MCPClientProfile({ vendorClient: 'ClaudeCode', clientName: 'cursor' }).isToolsModeClient()).toBe(
+ true
+ )
})
})
@@ -487,6 +473,19 @@ describe('MCPClientProfile', () => {
}
)
+ it('is false for the name-less Codex surface of openai-mcp (User-Agent only)', () => {
+ expect(
+ new MCPClientProfile({ userAgent: 'openai-mcp/1.0.0 (Codex)' }).capabilities.supportsInstructions
+ ).toBe(false)
+ })
+
+ it.each([['openai-mcp/1.0.0'], ['openai-mcp/1.0.0 (ChatGPT)']])(
+ 'stays true for the non-Codex openai-mcp user-agent %s',
+ (userAgent) => {
+ expect(new MCPClientProfile({ userAgent }).capabilities.supportsInstructions).toBe(true)
+ }
+ )
+
it.each([
['claude-code'],
['Claude Code'],
diff --git a/services/mcp/tests/unit/protocol-types.test.ts b/services/mcp/tests/unit/protocol-types.test.ts
index cc6594455d60..bff21e0b77f9 100644
--- a/services/mcp/tests/unit/protocol-types.test.ts
+++ b/services/mcp/tests/unit/protocol-types.test.ts
@@ -11,95 +11,36 @@ describe('resolveMode', () => {
const base = {
mode: undefined as undefined,
clientProfile: profile(),
- renderUiFlagEnabled: false,
}
- it('defaults to tools mode, no single exec', () => {
- expect(resolveMode(base)).toEqual({ mode: 'tools', useSingleExec: false })
+ it('defaults to cli mode (single exec) for unknown clients', () => {
+ expect(resolveMode(base)).toEqual({ mode: 'cli', useSingleExec: true })
})
- it('explicit mode=cli forces single exec', () => {
- expect(resolveMode({ ...base, mode: 'cli' })).toEqual({ mode: 'cli', useSingleExec: true })
- })
-
- it('explicit mode=tools disables single exec even for a coding agent', () => {
- const result = resolveMode({
- ...base,
- mode: 'tools',
- clientProfile: profile({ clientName: 'claude-code' }),
- })
- expect(result.useSingleExec).toBe(false)
- })
-
- it('coding agent activates single exec', () => {
- const result = resolveMode({
- ...base,
- clientProfile: profile({ clientName: 'claude-code' }),
- })
- expect(result).toEqual({ mode: 'cli', useSingleExec: true })
- })
-
- it('LibreChat activates single exec', () => {
- const result = resolveMode({
- ...base,
- clientProfile: profile({ clientName: 'LibreChat' }),
+ it('defaults to cli mode when no client hints are present at all', () => {
+ expect(resolveMode({ mode: undefined, clientProfile: new MCPClientProfile({}) })).toEqual({
+ mode: 'cli',
+ useSingleExec: true,
})
- expect(result).toEqual({ mode: 'cli', useSingleExec: true })
})
- it('non-coding agent does NOT activate single exec', () => {
- const result = resolveMode({
- ...base,
- clientProfile: profile({ clientName: 'some-dashboard-client' }),
- })
- expect(result.useSingleExec).toBe(false)
+ it.each([
+ ['Cursor client name', profile({ clientName: 'cursor' })],
+ ['ChatGPT user-agent', profile({ clientName: undefined, userAgent: 'openai-mcp/1.0.0 (ChatGPT)' })],
+ ])('auto-selects tools mode for the %s', (_label, clientProfile) => {
+ expect(resolveMode({ mode: undefined, clientProfile })).toEqual({ mode: 'tools', useSingleExec: false })
})
- it('PostHog code consumer activates single exec', () => {
- const result = resolveMode({
- ...base,
- clientProfile: profile({ consumer: 'posthog-code' }),
- })
- expect(result.useSingleExec).toBe(true)
+ it('explicit mode=cli forces single exec', () => {
+ expect(resolveMode({ ...base, mode: 'cli' })).toEqual({ mode: 'cli', useSingleExec: true })
})
- it('Claude web/desktop activates single exec when render-ui is enabled', () => {
- const result = resolveMode({
- ...base,
- clientProfile: profile({ vendorClient: 'ClaudeAI' }),
- renderUiFlagEnabled: true,
- })
+ it('explicit mode=cli wins over the Cursor tools-mode auto-detection', () => {
+ const result = resolveMode({ mode: 'cli', clientProfile: profile({ clientName: 'cursor' }) })
expect(result).toEqual({ mode: 'cli', useSingleExec: true })
})
- it('Claude web/desktop detected via User-Agent activates single exec when render-ui is enabled', () => {
- const result = resolveMode({
- ...base,
- clientProfile: profile({ userAgent: 'Claude-User' }),
- renderUiFlagEnabled: true,
- })
- expect(result.useSingleExec).toBe(true)
- })
-
- it('Claude web/desktop detected via User-Agent stays single exec even when render-ui is disabled', () => {
- // Anthropic clients always run in CLI (single-exec) mode, so the Claude-User
- // user-agent resolves to single-exec regardless of the render-ui flag — the
- // flag only gates whether the `render-ui` tool itself is advertised.
- const result = resolveMode({
- ...base,
- clientProfile: profile({ userAgent: 'Claude-User' }),
- renderUiFlagEnabled: false,
- })
- expect(result.useSingleExec).toBe(true)
- })
-
- it('explicit mode=tools wins over Claude UI host even with render-ui enabled', () => {
- const result = resolveMode({
- ...base,
- mode: 'tools',
- clientProfile: profile({ vendorClient: 'ClaudeAI' }),
- renderUiFlagEnabled: true,
- })
- expect(result.useSingleExec).toBe(false)
+ it('explicit mode=tools disables single exec for a client that would default to cli', () => {
+ expect(resolveMode({ ...base, mode: 'tools' })).toEqual({ mode: 'tools', useSingleExec: false })
})
})