Skip to content

feat(mcp): support conversations in custom dispatchers - #982

Draft
gesh wants to merge 1 commit into
mainfrom
feat/mcp-dispatcher-conversations
Draft

gesh wants to merge 1 commit into
mainfrom
feat/mcp-dispatcher-conversations

Conversation

@gesh

@gesh gesh commented Sep 25, 2026

Copy link
Copy Markdown
Member

💡 Motivation and Context

  • A Python MCP server with its own dispatcher gets one PostHog session per tool call on stateless transports. instrument() servers already group those calls through conversation_id.
  • @posthog/mcp fixed this for JS custom dispatchers in feat(mcp): support conversations in custom dispatchers posthog-js#5074. This PR ports that change so both SDKs behave the same.
  • PostHogMCP.capture_tool_call() had no conversation_id argument, so a dispatcher could not work around the gap by hand.

Changes

  • Custom dispatchers now group calls by conversation by default. PostHogMCP(enable_conversation_id=False) restores the previous behavior.
  • prepare_tool_list() adds an optional conversation_id argument and declares _mcp_instructions on compatible output schemas. It copies tools and does not change the originals.
  • Tools that already declare either field, use a composed schema, or share a name with another tool are left alone.
  • prepare_tool_call() takes a new session_id for a session the transport already carries. It returns the resolved session_id and conversation_id.
  • A valid echoed UUIDv7 handle wins over a carried session. A carried session stops the SDK from minting a new handle.
  • The new prepare_tool_result() returns PreparedToolResult(result, session_id, conversation_id). It appends a minted handle to content and mirrors the handle into structuredContent when the output schema declares it.
  • If a minted handle cannot reach the client, prepare_tool_result() returns conversation_id=None and keeps the derived session.
  • All capture_* methods accept conversation_id.
  • Mechanical: README examples, a minor Sampo changeset, and the regenerated public API snapshot.

Note

Differences from JS:

  • prepare_tool_result() also handles CallToolResult models, including one wrapped in an MCP SDK 1.x ServerResult.
  • Python cannot hide the delivery state the way JS does, so PreparedToolCall carries a private _conversation_state field. It survives copy and pickle across workers.

Both SDKs share two limits. A replica that never served the listing and gets no original_tool reads conversation_id but does not strip it. Preparing an already-prepared list turns ownership off. llm_model already behaves the same way, and the README tells dispatchers to pass original_tool.

💚 How did you test it?

  • Ported the 14 JS test cases to test_posthog_mcp.py. They cover schema injection, opt-out, application-owned fields, echo validation, carried sessions, delivery with and without mutation, pickle round trips, error results, and capture.
  • Added a Python-only case for CallToolResult and ServerResult results.
  • Broke the carried-session guard, the undelivered-handle drop, and the output-schema declaration one at a time. A new test failed each time.
  • Ran the MCP suite locally against MCP SDK 1.x and against 2.x in a separate venv, set up the same way as the CI mcp-major: v2 job.
  • Not tested by hand against a live MCP client.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Written with Claude Code (Claude Opus 5.5, claude-opus-5-5[1m]) at the assignee's direction. Skill used: writing-pr-descriptions.
  • The work checked the Python SDK against posthog-js#5074 and found the gap, then ported the JS behavior and tests. The existing _conversation_id, _output_instructions and session helpers were reused.
  • No sdk-specs entry covers MCP, so posthog-js is the contract.
  • A self-review found that a result wrapped in a ServerResult got only the structured channel. This PR fixes that.

🤖 Generated with Claude Code

Port posthog-js#5074 to PostHogMCP. Custom dispatchers now correlate
calls through an agent-carried conversation_id and a derived session id,
like instrument() already does.

- enable_conversation_id constructor option, on by default
- prepare_tool_list() injects conversation_id and _mcp_instructions
- prepare_tool_call() accepts a carried session_id and returns the
  resolved session_id and conversation_id
- new prepare_tool_result() delivers a minted handle without mutating
  the original result
- capture methods accept conversation_id

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@gesh
gesh requested a review from a team as a code owner September 25, 2026 14:42
@gesh gesh self-assigned this Sep 25, 2026
@gesh
gesh removed the request for review from a team September 25, 2026 14:44
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-25T14:47:48.858943+00:00
Duration: 259984ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 515ms
Required Headers.Has Authorization Bearer Header ✅ 511ms
Required Headers.Has Content Type Json ✅ 511ms
Required Headers.Has Posthog Sdk Info Format ✅ 510ms
Required Headers.Has Posthog Attempt Header ✅ 510ms
Required Headers.Has Posthog Request Id ✅ 511ms
Required Headers.Has Posthog Request Timestamp ✅ 511ms
Required Headers.Has User Agent ✅ 510ms
Body Format.Body Has Created At And Batch ✅ 511ms
Body Format.No Api Key In Body ✅ 511ms
Body Format.No Sent At In Body ✅ 512ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 513ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 516ms
Event Format.Distinct Id Is String ✅ 512ms
Event Format.Distinct Id At Root Not Properties ✅ 510ms
Event Format.Custom Properties Preserved ✅ 511ms
Event Format.Set Properties Preserved ✅ 512ms
Event Format.Set Once Properties Preserved ✅ 510ms
Event Format.Groups Properties Preserved ✅ 511ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 511ms
Event Format.Event Has Required Root Fields Batch ✅ 518ms
Event Format.Event Uuid Is Valid Batch ✅ 513ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 514ms
Event Format.Custom Properties Preserved Batch ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 514ms
Event Format.Set Once Properties Preserved Batch ✅ 514ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 514ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 515ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 508ms
Batch Behavior.Flush At Triggers Batch ✅ 1011ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 512ms
Deduplication.Generates Unique Uuids ✅ 519ms
Deduplication.Different Events Same Content Different Uuids ✅ 514ms
Deduplication.Preserves Uuid On Retry ✅ 6516ms
Deduplication.Preserves Timestamp On Retry ✅ 6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6524ms
Deduplication.No Duplicate Events In Batch ✅ 519ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13528ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6522ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6521ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 514ms
Response Format Validation.Success No Retry After When All Ok ✅ 513ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1515ms
Response Format Validation.Success No Retry After When Drop Only ✅ 514ms
Response Format Validation.Response Echoes Request Id ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6515ms
Retry Behavior.Retries On 500 ✅ 6521ms
Retry Behavior.Retries On 503 ✅ 8519ms
Retry Behavior.Retries On 504 ✅ 6520ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3516ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11524ms
Retry Behavior.Does Not Retry On 400 ✅ 2514ms
Retry Behavior.Does Not Retry On 401 ✅ 2515ms
Retry Behavior.Does Not Retry On 402 ✅ 2514ms
Retry Behavior.Does Not Retry On 413 ✅ 2512ms
Retry Behavior.Does Not Retry On 415 ✅ 2516ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2514ms
Retry Behavior.Implements Backoff ✅ 22529ms
Retry Behavior.Max Retries Respected ✅ 22526ms
Partial Batch Handling.Handles 200 Full Success ✅ 2513ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3515ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3518ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6517ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6524ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6523ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8524ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3515ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3519ms
Compression.Sends Gzip Content Encoding ✅ 512ms
Compression.No Content Encoding When Disabled ✅ 512ms
Compression.Compressed Body Is Decompressible ✅ 511ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2514ms
Event Options.Cookieless Mode Override ✅ 510ms
Event Options.Disable Skew Correction Override ✅ 511ms
Event Options.Process Person Profile Override ✅ 510ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 511ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 511ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 511ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 510ms
Identity.Capture Ai Event Has Uuid ✅ 510ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 510ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 511ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 11ms
Request Payload.Flags Request Uses V2 Query Param ✅ 10ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 10ms
Request Payload.Flags Request Omits Authorization Header ✅ 10ms
Request Payload.Token In Flags Body Matches Init ✅ 10ms
Request Payload.Groups Round Trip ✅ 10ms
Request Payload.Groups Default To Empty Object ✅ 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 10ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 11ms
Request Lifecycle.No Flags Request On Init Alone ✅ 5ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 511ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 14ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 10ms
Retry Behavior.Retries Flags On 502 ✅ 313ms
Retry Behavior.Retries Flags On 504 ✅ 317ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 511ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 69ms
Versioned Boolean Matching.Matching Version 1 ✅ 68ms
Versioned Boolean Matching.Matching Version 2 ✅ 73ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 39ms

@gesh
gesh marked this pull request as draft September 25, 2026 14:46
prepared: Any = result
delivered = False
if state.output_instructions:
prepared, delivered = mirror_instructions_into_structured_content(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: Shared results can expose another caller's conversation handle

For result objects without model_copy, this helper falls back to modifying structuredContent in place. If a tool returns a cached or shared custom result object, the first caller's handle remains there and is served to later callers, who can replay it to place their events in that caller's conversation and session. Copy the result before adding the metadata, or decline structured-content delivery when a safe copy cannot be made.

@veria-ai

veria-ai Bot commented Sep 25, 2026

Copy link
Copy Markdown

PR overview

This pull request adds conversation support to custom MCP dispatchers by attaching conversation metadata to tool results.

One security concern remains: when a custom tool reuses a cached or shared result object, conversation metadata may leak between callers. A later caller could reuse the exposed handle to place events into another caller’s conversation and session, though this depends on tools returning shared objects.

Open issues (1)

Fixed/addressed: 0 · PR risk: 3/10

@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium risk] Adds conversation tracking to the MCP dispatcher API.

The PR should not merge until the advertised list API works and tuple results can deliver newly minted handles.

Reviews (1) · Last reviewed commit: "feat(mcp): support conversations in cust..."

requires the constructor's ``collect_feedback`` option — the enable switch
that gates detection in :meth:`prepare_tool_call`). Returns a new list;
that gates detection in :meth:`prepare_tool_call`). By default it also
injects the optional ``conversation_id`` argument and declares

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Advertised argument is missing The changeset says custom dispatchers can pass conversation_id to prepare_tool_list(), but the method does not accept it. A dispatcher following that API gets a TypeError before it can advertise its tools. Add the parameter and its intended behavior, or remove the API promise.

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/mcp/posthog_mcp.py
Line: 423

Comment:
**Advertised argument is missing** The changeset says custom dispatchers can pass `conversation_id` to `prepare_tool_list()`, but the method does not accept it. A dispatcher following that API gets a `TypeError` before it can advertise its tools. Add the parameter and its intended behavior, or remove the API promise.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +924 to +930
if isinstance(result, dict):
return inject_prompt_back(result, conversation_id)
target = getattr(result, "root", result)
content = getattr(target, "content", None)
copy_model = getattr(target, "model_copy", None)
if not isinstance(content, list) or not callable(copy_model):
return result

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Tuple results lose handles If a custom dispatcher returns a (content_list, structured) tuple without a usable structured channel, _inject_prompt_back() does not append the newly minted handle to the content list. prepare_tool_result() then drops the conversation ID, so later calls cannot echo the handle and remain grouped. Handle tuple content as the existing FastMCP instrumentation does.

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/mcp/posthog_mcp.py
Line: 924-930

Comment:
**Tuple results lose handles** If a custom dispatcher returns a `(content_list, structured)` tuple without a usable structured channel, `_inject_prompt_back()` does not append the newly minted handle to the content list. `prepare_tool_result()` then drops the conversation ID, so later calls cannot echo the handle and remain grouped. Handle tuple content as the existing FastMCP instrumentation does.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant