Repository navigation
feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids #1193
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lucasheriques
wants to merge
8
commits into
main
Choose a base branch
from
lucas/mcp-client-meta-session
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,706
−169
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
c81277c
feat(mcp): group stateless ChatGPT calls by openai/session
lucasheriques 1688eeb
fix(mcp): read openai/session on every request and source custom events
lucasheriques 208707d
fix(mcp): keep ChatGPT calls out of shared session state and drop int…
lucasheriques 02a4815
feat(mcp): implement sdk-specs client conversation ids (ChatGPT, Code…
lucasheriques 3cbcd29
fix(mcp): pre-PR gate fixes for client conversation ids
lucasheriques 08774e9
Merge main into lucas/mcp-client-meta-session
lucasheriques 6571788
Merge remote-tracking branch 'origin/main' into lucas/mcp-client-meta…
lucasheriques 5417daa
fix(mcp): keep client-conversation sessions request-local and listing…
lucasheriques File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| pypi/posthog: minor | ||
| --- | ||
|
|
||
| MCP analytics now groups tool calls into sessions by the client's own conversation id in `_meta`: ChatGPT's `openai/session`, Codex's `sessionId`, and VS Code's `vscode.conversationId`, each read only from the client its `User-Agent` or client name identifies. The client's id wins over a conversation handle and a transport session. ChatGPT gets no `conversation_id` argument and no handle, so its tool schemas and results stay unchanged. Events from `instrument()` now carry `$mcp_session_source` (`client_metadata`, `conversation`, `transport` or `generated`), so session fragmentation can be measured. `PostHogMCP.prepare_tool_list` and `prepare_tool_call` take the request's `headers` (and `client_info`), and `capture_tool_call` takes `request_meta`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| """Client conversation ids: a value an MCP client puts in a ``tools/call`` | ||
| request's ``_meta`` to name the conversation the call belongs to. | ||
|
|
||
| ``CLIENT_CONVERSATION_ROWS`` is the table of the spec's "Session identity" | ||
| requirement, row for row. A row's key is read only from a request its recognition | ||
| rule matches, so a generic key such as Codex's ``sessionId`` is never read from a | ||
| client that means something else by it. posthog-js keeps the same table. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from typing import Any, Callable, NamedTuple, Optional, Sequence | ||
|
|
||
| from ._transport_identity import CLIENT_USER_AGENT_HEADER | ||
| from .request_headers import _to_header_bag, get_request_headers | ||
| from .session_token import decode_session_id, read_mcp_session_header | ||
|
|
||
| __all__ = [ | ||
| "CLIENT_CONVERSATION_ROWS", | ||
| "ClientConversation", | ||
| "ClientConversationRow", | ||
| "meta_client_name", | ||
| "read_client_conversation", | ||
| "recognize_client", | ||
| "recognize_manual_client", | ||
| "request_user_agent", | ||
| ] | ||
|
|
||
|
|
||
| class ClientConversation(NamedTuple): | ||
| """A recognized client's conversation id, and the ``_meta`` key it came from.""" | ||
|
|
||
| key: str | ||
| id: str | ||
|
|
||
|
|
||
| class ClientConversationRow(NamedTuple): | ||
| key: str | ||
| read_value: Callable[[Any], Optional[str]] | ||
| recognizes: Callable[[Optional[str], Optional[str]], bool] | ||
| # The client sends its id on every call, so the SDK advertises no | ||
| # ``conversation_id`` to it and mints it no handle. Rows whose clients have | ||
| # versions or kinds of conversation that send no id keep the handle. | ||
| handle_free: bool | ||
|
|
||
|
|
||
| _PRINTABLE_ASCII_UP_TO_128 = re.compile(r"[\x20-\x7e]{1,128}") | ||
| _UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") | ||
| _NIL_UUID = "00000000-0000-0000-0000-000000000000" | ||
| _CHATGPT_USER_AGENT = re.compile(r"openai-mcp/[^\s(]*\s*\(\s*chatgpt\s*[;,)]", re.I) | ||
| _VSCODE_PRODUCT_NAMES = ("Visual Studio Code", "Visual Studio Code - Insiders") | ||
|
|
||
|
|
||
| def _read_printable_ascii(value: Any) -> Optional[str]: | ||
| if isinstance(value, str) and _PRINTABLE_ASCII_UP_TO_128.fullmatch(value): | ||
| return value | ||
| return None | ||
|
|
||
|
|
||
| def _read_uuid(value: Any) -> Optional[str]: | ||
| if not isinstance(value, str): | ||
| return None | ||
| lowered = value.lower() | ||
| return lowered if _UUID.fullmatch(lowered) and lowered != _NIL_UUID else None | ||
|
|
||
|
|
||
| def _user_agent_starts_with(user_agent: Optional[str], prefixes: Sequence[str]) -> bool: | ||
| lowered = (user_agent or "").lower() | ||
| return bool(lowered) and any(lowered.startswith(p.lower()) for p in prefixes) | ||
|
|
||
|
|
||
| def _client_name_is(client_name: Optional[str], names: Sequence[str]) -> bool: | ||
| lowered = (client_name or "").lower() | ||
| return bool(lowered) and any(lowered == name.lower() for name in names) | ||
|
|
||
|
|
||
| # Checked in this order; the first row that recognizes a request is its client's row. | ||
| CLIENT_CONVERSATION_ROWS = ( | ||
| ClientConversationRow( | ||
| key="openai/session", | ||
| read_value=_read_printable_ascii, | ||
| recognizes=lambda user_agent, _: bool( | ||
| user_agent and _CHATGPT_USER_AGENT.match(user_agent) | ||
| ), | ||
| handle_free=True, | ||
| ), | ||
| ClientConversationRow( | ||
| key="sessionId", | ||
| read_value=_read_uuid, | ||
| recognizes=lambda user_agent, client_name: ( | ||
| _user_agent_starts_with(user_agent, ["codex-mcp-client/"]) | ||
| or _client_name_is(client_name, ["codex-mcp-client"]) | ||
| ), | ||
| handle_free=False, | ||
| ), | ||
| ClientConversationRow( | ||
| key="vscode.conversationId", | ||
| read_value=_read_uuid, | ||
| recognizes=lambda user_agent, client_name: ( | ||
| _user_agent_starts_with( | ||
| user_agent, [f"{name}/" for name in _VSCODE_PRODUCT_NAMES] | ||
| ) | ||
| or _client_name_is(client_name, _VSCODE_PRODUCT_NAMES) | ||
| ), | ||
| handle_free=False, | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| def recognize_client( | ||
| user_agent: Optional[str], client_name: Optional[str] | ||
| ) -> Optional[ClientConversationRow]: | ||
| """The row of the client a request's ``User-Agent`` or client name identifies. | ||
|
|
||
| The client name is ``$mcp_client_name`` as the adapters resolve it for the | ||
| request: its own ``_meta``, then a replayed session token, then a handshake.""" | ||
| user_agent = user_agent if isinstance(user_agent, str) else None | ||
| client_name = client_name if isinstance(client_name, str) else None | ||
| for row in CLIENT_CONVERSATION_ROWS: | ||
| if row.recognizes(user_agent, client_name): | ||
| return row | ||
| return None | ||
|
|
||
|
|
||
| def read_client_conversation( | ||
| row: Optional[ClientConversationRow], meta: Any | ||
| ) -> Optional[ClientConversation]: | ||
| """The recognized client's conversation id in ``meta``, or ``None`` when there | ||
| is none or it is not the row's shape.""" | ||
| if row is None or not isinstance(meta, dict): | ||
| return None | ||
| value = row.read_value(meta.get(row.key)) | ||
| return ClientConversation(row.key, value) if value is not None else None | ||
|
|
||
|
|
||
| def request_user_agent(extra: Any) -> Optional[str]: | ||
| """The request's ``User-Agent``, or ``None`` off HTTP. Never raises.""" | ||
| try: | ||
| headers = get_request_headers(extra) | ||
| except Exception: # noqa: BLE001 - a header read must not break a request | ||
| return None | ||
| value = (headers or {}).get(CLIENT_USER_AGENT_HEADER) | ||
| return value if isinstance(value, str) else None | ||
|
|
||
|
|
||
| def recognize_manual_client( | ||
| headers: Any, request_meta: Any, handshake_client_name: Optional[str] | ||
| ) -> Optional[ClientConversationRow]: | ||
| """:func:`recognize_client` for a custom dispatcher, from what it passes in: | ||
| the request's headers, its ``_meta``, and a handshake ``clientInfo`` name | ||
| bound to the request's transport session. The client name follows the | ||
| request's ``_meta``, then a replayed session token, then the handshake.""" | ||
| bag = _to_header_bag(headers) if headers is not None else None | ||
| user_agent = (bag or {}).get(CLIENT_USER_AGENT_HEADER) | ||
| token = decode_session_id(read_mcp_session_header(bag)) if bag else None | ||
| return recognize_client( | ||
| user_agent if isinstance(user_agent, str) else None, | ||
| meta_client_name(request_meta) | ||
| or (token.client_name if token is not None else None) | ||
| or handshake_client_name, | ||
| ) | ||
|
|
||
|
|
||
| def meta_client_name(meta: Any) -> Optional[str]: | ||
| """The client name a 2026-07-28 request carries in its own ``_meta``.""" | ||
| info = ( | ||
| meta.get("io.modelcontextprotocol/clientInfo") | ||
| if isinstance(meta, dict) | ||
| else None | ||
| ) | ||
| name = info.get("name") if isinstance(info, dict) else None | ||
| return name if isinstance(name, str) and name else None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.