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): forward mcp session and conversation ids to backend (#58467)

Lucas Ricoyc30ad13e886a
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 2cf70d29512b..9f496ff1b2c4 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -26,6 +26,7 @@ from django.utils.deprecation import MiddlewareMixin
import structlog
from django_prometheus.middleware import Metrics
from loginas.utils import is_impersonated_session, restore_original_login
+from opentelemetry import trace
from prometheus_client import Histogram
from social_core.exceptions import AuthCanceled, AuthException, AuthFailed
from statshog.defaults.django import statsd
@@ -35,7 +36,7 @@ from posthog.clickhouse.client.execute import clickhouse_query_counter
from posthog.clickhouse.query_tagging import QueryCounter, get_query_tag_value, reset_query_tags, tag_queries
from posthog.cloud_utils import is_cloud, is_dev_mode
from posthog.constants import AUTH_BACKEND_KEYS
-from posthog.event_usage import get_event_source, get_mcp_properties
+from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_value
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.helpers.user_devices import set_known_device_cookie
@@ -571,6 +572,38 @@ def per_request_logging_context_middleware(
x_forwarded_for=request.headers.get("x-forwarded-for", ""),
)
+ # Forwarded by the PostHog MCP server (services/mcp) on every API call.
+ # Binding here lets backend log lines and OTLP spans correlate with the
+ # same MCP context that's stamped on events.
+ #
+ # These headers are caller-asserted on a public API surface — anyone can
+ # set them on a request, so treat the resulting fields in logs/traces
+ # as correlation hints, not authoritative identifiers.
+ #
+ # The OTLP span tagging below depends on `DjangoInstrumentor` having
+ # already pushed a request span into the OTel context. The
+ # instrumentation library installs itself at MIDDLEWARE position 0 by
+ # default (see `posthog/otel_instrumentation.py`), so the span is in
+ # scope here. If that invariant ever changes, `set_attribute` becomes a
+ # silent no-op on the non-recording span.
+ mcp_session_id = sanitize_header_value(request.headers.get("X-Posthog-Mcp-Session-Id"))
+ mcp_conversation_id = sanitize_header_value(request.headers.get("X-Posthog-Mcp-Conversation-Id"))
+ mcp_context_bindings = {
+ k: v
+ for k, v in (
+ ("mcp_session_id", mcp_session_id),
+ ("mcp_conversation_id", mcp_conversation_id),
+ )
+ if v
+ }
+ if mcp_context_bindings:
+ structlog.contextvars.bind_contextvars(**mcp_context_bindings)
+ span = trace.get_current_span()
+ if mcp_session_id:
+ span.set_attribute("mcp.session_id", mcp_session_id)
+ if mcp_conversation_id:
+ span.set_attribute("mcp.conversation_id", mcp_conversation_id)
+
return get_response(request)
return middleware
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index d1fe02adb4a1..734b2baab639 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -9,10 +9,14 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core.cache import cache
-from django.http import HttpResponseRedirect
-from django.test import Client as DjangoClient
+from django.http import HttpResponse, HttpResponseRedirect
+from django.test import (
+ Client as DjangoClient,
+ RequestFactory,
+)
from django.urls import reverse
+import structlog
from loginas import settings as la_settings
from parameterized import parameterized
from rest_framework import status
@@ -21,6 +25,7 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParamete
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
+from posthog.middleware import per_request_logging_context_middleware
from posthog.models import Action, Cohort, FeatureFlag, Insight
from posthog.models.organization import Organization
from posthog.models.team import Team
@@ -2120,3 +2125,75 @@ def test_query_time_counting_middleware_should_instrument(path, expected) -> Non
request = RequestFactory().get(path)
assert middleware._should_instrument(request) is expected
+
+
+class TestPerRequestLoggingContextMiddlewareMcpHeaders(APIBaseTest):
+ """Covers MCP session header binding inside `per_request_logging_context_middleware`."""
+
+ def _run_middleware(self, **headers):
+ captured: dict[str, Any] = {}
+
+ def get_response(request):
+ captured["ctx"] = dict(structlog.contextvars.get_contextvars())
+ return HttpResponse()
+
+ try:
+ structlog.contextvars.clear_contextvars()
+ middleware = per_request_logging_context_middleware(get_response)
+ request = RequestFactory().get("/", **headers)
+ middleware(request)
+ finally:
+ structlog.contextvars.clear_contextvars()
+ return captured["ctx"]
+
+ @parameterized.expand(
+ [
+ (
+ "both_headers_present",
+ {
+ "HTTP_X_POSTHOG_MCP_SESSION_ID": "abc123session",
+ "HTTP_X_POSTHOG_MCP_CONVERSATION_ID": "01984ad9-bda4-7000-8000-abcdef012345",
+ },
+ "abc123session",
+ "01984ad9-bda4-7000-8000-abcdef012345",
+ ),
+ (
+ "session_id_alone",
+ {"HTTP_X_POSTHOG_MCP_SESSION_ID": "abc123session"},
+ "abc123session",
+ None,
+ ),
+ (
+ "conversation_id_alone",
+ {"HTTP_X_POSTHOG_MCP_CONVERSATION_ID": "01984ad9-bda4-7000-8000-abcdef012345"},
+ None,
+ "01984ad9-bda4-7000-8000-abcdef012345",
+ ),
+ ]
+ )
+ def test_binds_mcp_ids_when_present(self, _name, headers, expected_session, expected_conversation):
+ with patch("posthog.middleware.trace") as mock_trace:
+ span = MagicMock()
+ mock_trace.get_current_span.return_value = span
+ ctx = self._run_middleware(**headers)
+
+ if expected_session is not None:
+ assert ctx["mcp_session_id"] == expected_session
+ span.set_attribute.assert_any_call("mcp.session_id", expected_session)
+ else:
+ assert "mcp_session_id" not in ctx
+ if expected_conversation is not None:
+ assert ctx["mcp_conversation_id"] == expected_conversation
+ span.set_attribute.assert_any_call("mcp.conversation_id", expected_conversation)
+ else:
+ assert "mcp_conversation_id" not in ctx
+
+ def test_no_mcp_keys_bound_when_headers_absent(self):
+ with patch("posthog.middleware.trace") as mock_trace:
+ span = MagicMock()
+ mock_trace.get_current_span.return_value = span
+ ctx = self._run_middleware()
+
+ assert "mcp_session_id" not in ctx
+ assert "mcp_conversation_id" not in ctx
+ span.set_attribute.assert_not_called()
diff --git a/services/mcp/ARCHITECTURE.md b/services/mcp/ARCHITECTURE.md
index 25cd6fb489f9..65e800e05f0f 100644
--- a/services/mcp/ARCHITECTURE.md
+++ b/services/mcp/ARCHITECTURE.md
@@ -125,6 +125,63 @@ log.emit(response.status) // Single log with all data + duration
This produces one structured JSON log per request, making it easier to query in observability tools.
+### Tracking and observability
+
+There are three independent layers that emit signals about each MCP request:
+
+1. **PostHog analytics events** — `mcp_tool_call` and friends, captured for product analytics.
+2. **Outbound API headers** — propagated when the MCP server calls PostHog's Django backend, so backend log lines and OTLP spans can correlate with the originating MCP request.
+3. **Wide structured logs** — single JSON record per request from the Worker itself (see [Wide Logging Pattern](#wide-logging-pattern) above).
+
+#### `mcp_tool_call` event paths
+
+Three distinct code paths emit `mcp_tool_call` events; which one fires depends on the server mode and on the `mcp-posthog-analytics-sdk` feature flag:
+
+- **`mcp.ts:trackEvent`** — homegrown PostHog capture. Used by the exec-mode wrapper to emit events for inner tool calls. Properties use the bare form: `mcp_session_id`, `mcp_conversation_id`, `mcp_client_name`, etc.
+- **`lib/mcpcat.ts`** — legacy MCPcat SDK path. Same bare property names.
+- **`lib/posthog-mcp-analytics.ts`** — the [`@posthog/mcp-analytics`](https://github.com/PostHog/mcp-analytics) SDK. Property names are `$`-prefixed (`$mcp_session_id`, `$mcp_conversation_id`, …). This is the path most live traffic flows through today.
+
+Adding a new property to events means wiring it into the `McpCatIdentityProvider` interface and the property-builder in **all three** emitters, then sourcing the value on `requestProperties` (or pulling it from another DO-level source).
+
+#### Three correlation identifiers
+
+Three identifiers travel with each request, each with a different lifecycle and a different consumer:
+
+| Identifier | Source | Where it lands |
+| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **`sessionId`** (wrapper-app hint) | `?sessionId=` query param, set by integrators (setup wizard, sandbox, etc.) | Resolved to a UUIDv7 via `SessionManager.getSessionUuid()` and stamped as `$session_id` / `$ai_session_id` on events — drives Session Replay and LLM Analytics grouping. Only set when a wrapper supplies it. |
+| **`mcpSessionId`** (transport session) | `Mcp-Session-Id` HTTP header, server-minted on initialize per the [Streamable-HTTP MCP spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http) and echoed by clients on every subsequent request | Stamped on `mcp_tool_call` events as `mcp_session_id` / `$mcp_session_id`, and forwarded to Django as `X-Posthog-Mcp-Session-Id` so backend structlog contextvars + OTLP span attributes (`mcp.session_id`) can correlate. |
+| **`mcpConversationId`** (agent-echoed conversation) | The `conversation_id` arg [injected into tool schemas](https://github.com/PostHog/mcp-analytics/pull/14) by `@posthog/mcp-analytics` when `enableConversationId: true`. The SDK mints a UUID and asks the agent to echo it on subsequent calls, so it persists across transport reconnects | Same plumbing as `mcpSessionId` — stamped on events and forwarded to Django as `X-Posthog-Mcp-Conversation-Id`. |
+
+Crucially, **`sessionId` and `mcpSessionId` are different concepts** and will not match for the same request. The wrapper-app `sessionId` is only set for a small fraction of traffic (mostly integrator-driven flows); the transport `mcpSessionId` is on essentially every authenticated request after initialize.
+
+#### Forwarding session and conversation IDs to Django
+
+When the Worker calls PostHog's Django backend (any `ApiClient.fetch`), the outbound request carries:
+
+- `X-Posthog-Mcp-Session-Id: <mcpSessionId>` — when set on `ApiClient.config`
+- `X-Posthog-Mcp-Conversation-Id: <mcpConversationId>` — when set on `ApiClient.config`
+
+On the Django side, `per_request_logging_context_middleware` reads both headers (sanitized through the existing `sanitize_header_value` helper), binds them to structlog contextvars (`mcp_session_id`, `mcp_conversation_id`), and sets them on the current OTLP span as `mcp.session_id` / `mcp.conversation_id`.
+
+The headers are caller-asserted — anyone can spoof them on a request — so backend consumers should treat them as correlation hints, not authoritative identifiers.
+
+This is **attribute-based correlation, not distributed-trace span linkage** — the Worker emits no OTLP itself and forwards no `traceparent`, so the Django-rooted span is not a child of any Worker-side span. Tracing backends can correlate after the fact by querying on the attribute, but won't render a cross-service trace tree until Worker-side OTLP export ships.
+
+### Durable Object cold vs warm
+
+Cloudflare Durable Objects have two lifecycle states that matter when reasoning about cached state in this codebase:
+
+- **Cold start.** A request arrives, no live DO instance exists. The Cloudflare runtime constructs a fresh instance and calls `init()`. `_api`, `_cache`, and any other lazily-initialized fields are built from scratch. The DO is now "warm".
+- **Warm.** Subsequent requests reuse the same in-memory DO instance. `init()` does **not** re-run; cached fields (`_api`, `_cache`) keep the values captured on the cold start. Per-request props arrive via the framework's `updateProps` / `setName` ingress (which `McpAgent` overrides).
+- **Hibernation.** After ~10 s of inactivity, the runtime tears the DO down. The next request triggers a fresh cold start. DO storage (`this.ctx.storage`) persists across hibernation; in-memory caches do not.
+
+This matters for any value that's per-request but ends up snapshotted onto a long-lived cached object:
+
+- The cached `_api` is built once in `api()`, during `init()` on the cold start. The cold start's request is almost always an **initialize** call, which by spec does **not** carry the `Mcp-Session-Id` header (the server is about to mint it in the response). So `_api.config.mcpSessionId` is `undefined` at construction and stays that way for the warm DO's lifetime.
+- For values that need to refresh per request, mutate `_api.config` in place from `updateProps` / `setName` (the per-request ingress hooks). That's what `rotateCachedApiToken` does for `apiToken`.
+- Event emission is unaffected by this caching: `trackEvent` reads `this.requestProperties.mcpSessionId` directly per emission, and the `posthog-mcp-analytics` SDK reads `extra.sessionId` from the transport per event. So `mcp_session_id` lands on events even when `_api`'s copy is stale.
+
## OAuth Flow
The server implements RFC 9728 (OAuth Protected Resource Metadata) and RFC 8414 (OAuth Authorization Server Metadata):
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index cc360f42d076..e248cb6a906d 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -73,6 +73,8 @@ export interface ApiConfig {
mcpProtocolVersion?: string | undefined
mcpConsumer?: string | undefined
oauthClientName?: string | undefined
+ mcpSessionId?: string | undefined
+ mcpConversationId?: string | undefined
}
type Endpoint = Record<string, any>
@@ -115,6 +117,15 @@ export class ApiClient {
: {}),
...(this.config.mcpConsumer ? { 'x-posthog-mcp-consumer': this.config.mcpConsumer } : {}),
...(this.config.oauthClientName ? { 'x-posthog-mcp-oauth-client-name': this.config.oauthClientName } : {}),
+ // Forward MCP session and conversation ids so backend logs and OTLP
+ // spans for downstream API hops can correlate with the same MCP context
+ // the events carry. This is attribute-based correlation only — we do
+ // not forward `traceparent` (the Worker emits no OTLP today), so the
+ // Django-rooted span is not a child of any Worker-side span.
+ ...(this.config.mcpSessionId ? { 'x-posthog-mcp-session-id': this.config.mcpSessionId } : {}),
+ ...(this.config.mcpConversationId
+ ? { 'x-posthog-mcp-conversation-id': this.config.mcpConversationId }
+ : {}),
'X-PostHog-Client': 'mcp',
}
if (options?.body) {
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index f15d7c13a4a0..802574fd864d 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -56,11 +56,11 @@ export type RequestProperties = {
// own correlation key, available for direct MCP clients (Claude Code,
// Cursor, …) that never set the wrapper-app `?sessionId=` hint.
mcpSessionId?: string
- // Agent-echoed conversation id from `@posthog/mcp-analytics` PR #14
- // (`enableConversationId: true`). Plumbed alongside `mcpSessionId`
- // through every identity-provider + emitter path so the consumer side
- // is ready to read it; the producer-side source lands when that SDK
- // PR ships and a header read is wired into `index.ts`.
+ // Agent-echoed conversation id from `@posthog/mcp-analytics`'s
+ // `enableConversationId: true`. Sourced today from the inbound
+ // `mcp-conversation-id` HTTP header (see `index.ts`). Persists across
+ // transport reconnects because the agent is asked to echo the value back
+ // on every subsequent tool call.
mcpConversationId?: string
features?: string[]
tools?: string[]
@@ -248,6 +248,8 @@ export class MCP extends McpAgent<Env> {
mcpClientVersion: this.mcpClientVersion,
mcpProtocolVersion: this.mcpProtocolVersion,
mcpConsumer: this.requestProperties.mcpConsumer,
+ mcpSessionId: this.requestProperties.mcpSessionId,
+ mcpConversationId: this.requestProperties.mcpConversationId,
})
}
@@ -262,7 +264,11 @@ export class MCP extends McpAgent<Env> {
* just the cached token here — leave `this.props` and storage alone.
*/
async setName(name: string, props?: RequestProperties): Promise<void> {
- this.rotateCachedApiToken(props?.apiToken)
+ this.rotateCachedApiTokenAndTraces({
+ apiToken: props?.apiToken,
+ mcpSessionId: props?.mcpSessionId,
+ mcpConversationId: props?.mcpConversationId,
+ })
await super.setName(name, props)
}
@@ -275,21 +281,56 @@ export class MCP extends McpAgent<Env> {
*/
async updateProps(props?: RequestProperties): Promise<void> {
this.props = props as RequestProperties
- this.rotateCachedApiToken(props?.apiToken)
+ this.rotateCachedApiTokenAndTraces({
+ apiToken: props?.apiToken,
+ mcpSessionId: props?.mcpSessionId,
+ mcpConversationId: props?.mcpConversationId,
+ })
await super.updateProps(props)
}
/**
- * Rotate the cached ApiClient's auth token in place. Tool handlers read
- * the token off `context.api.config.apiToken` — the captured ApiClient
- * from init() — so replacing the instance would leave those references
- * stale. Mutating in place keeps them pointing at the latest token.
- * No-op when there's no cached client, no incoming token, or the token
- * already matches.
+ * Refresh the cached ApiClient's per-request config in place. Tool handlers
+ * read these fields off `context.api.config` — the captured ApiClient from
+ * init() — so replacing the instance would leave those references stale.
+ * Mutating in place keeps them pointing at the latest values.
+ *
+ * Name is intentionally awkward to signal that this method has grown
+ * beyond just rotating the apiToken; rename more crisply when a natural
+ * grouping emerges.
+ *
+ * Three fields rotate per inbound request:
+ * - `apiToken` — short-lived OAuth tokens get refreshed across the same
+ * transport session.
+ * - `mcpSessionId` — the `Mcp-Session-Id` HTTP header is *absent* on the
+ * initialize call (where `_api` is first constructed) and present on
+ * every subsequent request. Without this refresh, `_api` would be
+ * pinned to `undefined` for the lifetime of a warm DO and the
+ * `x-posthog-mcp-session-id` header would never be sent.
+ * - `mcpConversationId` — same shape as `mcpSessionId`; sourced from
+ * the inbound `mcp-conversation-id` header (today supplied by wrapper
+ * apps; the `@posthog/mcp-analytics` SDK injects it via tool args, but
+ * that path doesn't land on `requestProperties` yet).
+ *
+ * No-op when there's no cached client, or when an incoming field is empty
+ * (don't overwrite a real value with `undefined`).
*/
- private rotateCachedApiToken(apiToken: string | undefined): void {
- if (this._api && apiToken && this._api.config.apiToken !== apiToken) {
- this._api.config.apiToken = apiToken
+ private rotateCachedApiTokenAndTraces(updates: {
+ apiToken: string | undefined
+ mcpSessionId: string | undefined
+ mcpConversationId: string | undefined
+ }): void {
+ if (!this._api) {
+ return
+ }
+ if (updates.apiToken && this._api.config.apiToken !== updates.apiToken) {
+ this._api.config.apiToken = updates.apiToken
+ }
+ if (updates.mcpSessionId && this._api.config.mcpSessionId !== updates.mcpSessionId) {
+ this._api.config.mcpSessionId = updates.mcpSessionId
+ }
+ if (updates.mcpConversationId && this._api.config.mcpConversationId !== updates.mcpConversationId) {
+ this._api.config.mcpConversationId = updates.mcpConversationId
}
}
diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.ts
index cf1efa335ee5..679b2fe946e6 100644
--- a/services/mcp/tests/unit/api-client.test.ts
+++ b/services/mcp/tests/unit/api-client.test.ts
@@ -128,6 +128,48 @@ describe('ApiClient', () => {
vi.unstubAllGlobals()
})
+ it.each([
+ [
+ 'both ids set',
+ { mcpSessionId: 'abc123session', mcpConversationId: '01984ad9-bda4-7000-8000-abcdef012345' },
+ { 'x-posthog-mcp-session-id': 'abc123session', 'x-posthog-mcp-conversation-id': '01984ad9-bda4-7000-8000-abcdef012345' },
+ ],
+ [
+ 'only session id set',
+ { mcpSessionId: 'only-session' },
+ { 'x-posthog-mcp-session-id': 'only-session' },
+ ],
+ [
+ 'neither id set',
+ {},
+ {},
+ ],
+ ] as const)('forwards mcp id headers — %s', async (_label, extraConfig, expectedHeaders) => {
+ const mockFetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), { status: 200 }))
+ vi.stubGlobal('fetch', mockFetch)
+
+ const client = new ApiClient({
+ apiToken: 'test-token-123',
+ baseUrl: 'https://example.com',
+ ...extraConfig,
+ })
+
+ await (client as any).fetch('https://example.com/api/test', { method: 'GET' })
+
+ const [, options] = mockFetch.mock.calls[0]!
+ for (const [header, value] of Object.entries(expectedHeaders)) {
+ expect(options.headers[header]).toBe(value)
+ }
+ const absent = ['x-posthog-mcp-session-id', 'x-posthog-mcp-conversation-id'].filter(
+ (h) => !(h in expectedHeaders)
+ )
+ for (const header of absent) {
+ expect(options.headers).not.toHaveProperty(header)
+ }
+
+ vi.unstubAllGlobals()
+ })
+
describe('insights().get() — overrides forwarding', () => {
const variablesOverride =
'{"019d4838-1da4-0000-33c7-2561bf01f1c9":{"code_name":"eventname","variableId":"019d4838-1da4-0000-33c7-2561bf01f1c9","value":"signed_up"}}'
diff --git a/services/mcp/tests/unit/mcp-api-caching.test.ts b/services/mcp/tests/unit/mcp-api-caching.test.ts
index 43d6e8e9d076..79ceca1be864 100644
--- a/services/mcp/tests/unit/mcp-api-caching.test.ts
+++ b/services/mcp/tests/unit/mcp-api-caching.test.ts
@@ -296,3 +296,115 @@ describe('MCP.updateProps() token propagation (cold start / hibernation)', () =>
expect(api.config.apiToken).toBe('token-A')
})
})
+
+describe('MCP.setName() MCP-id rotation (warm DO path)', () => {
+ // The `Mcp-Session-Id` HTTP header is absent on the initialize call but
+ // present on every request after. Without explicit rotation, `_api` —
+ // constructed during init() with `mcpSessionId: undefined` — would never
+ // see the header and `x-posthog-mcp-session-id` would never be sent on
+ // the outbound API hops. These tests pin that rotation behaviour for
+ // both the protocol session id and the conversation id.
+ beforeEach(() => {
+ ApiClientCtor.mockClear()
+ storagePutSpy.mockClear()
+ superSetNameSpy.mockClear()
+ superUpdatePropsSpy.mockClear()
+ })
+
+ function buildMcpWithMcpIds(opts: { mcpSessionId?: string; mcpConversationId?: string } = {}): MCP {
+ const mcp = buildMcp('token-A')
+ ;(mcp as any).props = {
+ ...(mcp as any).props,
+ ...(opts.mcpSessionId !== undefined ? { mcpSessionId: opts.mcpSessionId } : {}),
+ ...(opts.mcpConversationId !== undefined ? { mcpConversationId: opts.mcpConversationId } : {}),
+ }
+ return mcp
+ }
+
+ it('updates the cached ApiClient mcpSessionId when the header appears on a later request', async () => {
+ // Reproduces the production bug: init() runs before any inbound
+ // `Mcp-Session-Id` exists, so `_api` is built with `mcpSessionId:
+ // undefined`. The next request *does* carry the header and must
+ // propagate onto the cached client.
+ const mcp = buildMcpWithMcpIds()
+ const api = await mcp.api()
+ expect(api.config.mcpSessionId).toBeUndefined()
+
+ await (mcp as any).setName('streamable-http:session-1', {
+ userHash: 'user-hash',
+ apiToken: 'token-A',
+ mcpSessionId: 'mcp-session-abc',
+ })
+
+ expect(api.config.mcpSessionId).toBe('mcp-session-abc')
+ expect(ApiClientCtor).toHaveBeenCalledTimes(1)
+ })
+
+ it('updates the cached ApiClient mcpConversationId when one appears', async () => {
+ const mcp = buildMcpWithMcpIds()
+ const api = await mcp.api()
+ expect(api.config.mcpConversationId).toBeUndefined()
+
+ await (mcp as any).setName('streamable-http:session-1', {
+ userHash: 'user-hash',
+ apiToken: 'token-A',
+ mcpConversationId: 'conv-xyz',
+ })
+
+ expect(api.config.mcpConversationId).toBe('conv-xyz')
+ })
+
+ it('does not overwrite a populated id with undefined', async () => {
+ // If the cached value is already set and a later request omits the
+ // header, the cached value must win — otherwise transport blips
+ // would clear the correlation id mid-session.
+ const mcp = buildMcpWithMcpIds({ mcpSessionId: 'mcp-session-abc' })
+ const api = await mcp.api()
+ expect(api.config.mcpSessionId).toBe('mcp-session-abc')
+
+ await (mcp as any).setName('streamable-http:session-1', {
+ userHash: 'user-hash',
+ apiToken: 'token-A',
+ mcpSessionId: undefined,
+ })
+
+ expect(api.config.mcpSessionId).toBe('mcp-session-abc')
+ })
+})
+
+describe('MCP.updateProps() MCP-id rotation (cold start / hibernation)', () => {
+ beforeEach(() => {
+ ApiClientCtor.mockClear()
+ storagePutSpy.mockClear()
+ superSetNameSpy.mockClear()
+ superUpdatePropsSpy.mockClear()
+ })
+
+ it('propagates a fresh mcpSessionId onto the cached ApiClient', async () => {
+ const mcp = buildMcp('token-A')
+ const api = await mcp.api()
+ expect(api.config.mcpSessionId).toBeUndefined()
+
+ await (mcp as any).updateProps({
+ userHash: 'user-hash',
+ apiToken: 'token-A',
+ mcpSessionId: 'mcp-session-abc',
+ })
+
+ expect(api.config.mcpSessionId).toBe('mcp-session-abc')
+ })
+
+ it('propagates a fresh mcpConversationId onto the cached ApiClient', async () => {
+ const mcp = buildMcp('token-A')
+ const api = await mcp.api()
+ expect(api.config.mcpConversationId).toBeUndefined()
+
+ await (mcp as any).updateProps({
+ userHash: 'user-hash',
+ apiToken: 'token-A',
+ mcpConversationId: 'conv-xyz',
+ })
+
+ expect(api.config.mcpConversationId).toBe('conv-xyz')
+ })
+})