Skip to content

feat(mcp): anchor the virtual tools to the conversation - #963

Draft
gesh wants to merge 3 commits into
posthog/mcp-virtual-tool-first-pagefrom
posthog/mcp-virtual-tool-conversation-id
Draft

gesh wants to merge 3 commits into
posthog/mcp-virtual-tool-first-pagefrom
posthog/mcp-virtual-tool-conversation-id

Conversation

@gesh

@gesh gesh commented Sep 15, 2026

Copy link
Copy Markdown
Member

Stacked on #962 — review that one first.

Problem

With enable_conversation_id=True, the SDK's virtual tools were exempt from conversation anchoring. So a $mcp_feedback or $mcp_missing_capability event was filed under a $session_id of its own.

An agent that calls echo, hits friction, and reports it lands like this:

Event Session (before)
$mcp_tool_call (echo) ses_57a5f376…
$mcp_initialize ses_01a0a522… ← spurious second one
$mcp_feedback ses_01a0a522…
$mcp_missing_capability ses_01a0a522…

The complaint about echo is not in the session containing echo. You get an orphan session holding only the report, which is most of the value of the feature gone — the point of a report is being reachable from the calls that prompted it. After: one session for all four.

Changes

get_more_tools and send_feedback now take part like any other tool, under any configured name: they advertise conversation_id, echo a minted handle back over prompt-back, and stamp $mcp_conversation_id.

The exemption lived in three places that had to agree, which is why it drifted:

  • the schema pass skipped the argument (is_sdk_virtual_tool gated both context and conversation_id; it now gates only context),
  • resolve_conversation_id short-circuited on the two names,
  • the lifecycle passed None when preparing their session, so even a resolved handle was dropped.

resolve_conversation_id loses its two tool-name parameters entirely — with no tool exempt there is nothing to compare against, so the exemption can't come back by accident.

The virtual tools still never get the injected context argument; they state their intent through their own (context for get_more_tools, summary/details for send_feedback). A handle the agent never received is still never stamped, same as for ordinary tools.

PostHogMCP is unaffected — the custom-dispatcher path has no conversation-id handling at all.

Also here: per-request tool ownership

Two reviewer findings on #962 turned out to share one root cause, and the fix belongs with this PR rather than that one, since both are about attribution rather than where the tools are advertised.

The SDK asked "is this name mine?" two ways that disagreed. Interception asked a per-request probe, which was right. Intent and the conversation exemption asked virtual_tool_collisions, which only a served tools/list writes — so on a process that had served none (the ordinary multi-pod case the probe exists for), a host tool named get_more_tools dispatched correctly but its $mcp_tool_call carried $mcp_intent=None. Permanent on FastMCP and v2 MCPServer.

The intent guard turned out to be dead code for its stated purpose: PostHog's virtual tools are intercepted before dispatch and captured by record_missing_capability / record_feedback, so they never reach record_tool_call (verified by spying on it). Everything arriving there is host-dispatched by construction, so the guard could only ever fire on a host tool sharing the name. Removed. start_tool_call_lifecycle now reads options-only names, so the call path consults no listing state at all — which also closes the second finding, where one caller's listing could suppress another caller's virtual-tool handling on a server with caller-specific catalogues.

One correction to the reports: the missing conversation id they also cite is not name-specific — an ordinary tool shows the same in that harness — so the new tests assert parity with an ordinary tool instead.

Two inverted tests

Both deliberate, with the reasoning in their docstrings so the next reader doesn't revert them:

  • test_feedback_never_mints_conversation_idtest_feedback_joins_the_conversation.
  • the renamed-tool schema case now expects conversation_id to track the option rather than always be absent.

Plus new tests asserting the report and the call it is about share a $session_id, for both the default and a renamed tool.

Note on @posthog/mcp

@posthog/mcp currently excludes the virtual tools too, by a different route — its virtual descriptors never get conversation_id injected, and resolveConversationId is gated on schema-derived ownership, so ownership.conversationId is false for them. This PR therefore puts Python ahead of TypeScript, and a matching change is worth raising there so the two don't drift. (Checked against a local feature branch rather than main, so worth confirming.)

Verification

  • pytest posthog/test/mcp on both MCP SDK majors: 512 passed on v1, 443 passed / 19 skipped on v2.
  • Full suite: 2751 passed. The 9 failures are the same pre-existing live-API tests under posthog/test/ai/ hitting a 403 product_access_denied.
  • ruff format --check, ruff check, filtered mypy (clean), check_public_api.py.
  • End-to-end: the four events above collapse from two sessions to one, and the spurious second $mcp_initialize disappears.

Created with PostHog Desktop

@gesh
gesh requested a review from a team as a code owner September 15, 2026 13:07
@gesh
gesh removed the request for review from a team September 15, 2026 13:08
@gesh
gesh marked this pull request as draft September 15, 2026 13:09
@github-actions

github-actions Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-16 10:04:21 UTC
Duration: 256372ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 516ms
Endpoint And Method.Does Not Use Legacy Endpoints 511ms
Required Headers.Has Authorization Bearer Header 510ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 510ms
Required Headers.Has Posthog Request Id 512ms
Required Headers.Has Posthog Request Timestamp 510ms
Required Headers.Has User Agent 509ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 511ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 510ms
Event Format.Event Uuid Is Valid 509ms
Event Format.Event Timestamp Is Rfc3339 510ms
Event Format.Distinct Id Is String 510ms
Event Format.Distinct Id At Root Not Properties 510ms
Event Format.Custom Properties Preserved 510ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 509ms
Event Format.Groups Properties Preserved 510ms
Event Format.Sdk Generates Uuid If Not Provided 511ms
Event Format.Event Has Required Root Fields Batch 513ms
Event Format.Event Uuid Is Valid Batch 516ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 513ms
Event Format.Distinct Id At Root Not Properties Batch 513ms
Event Format.Custom Properties Preserved Batch 514ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 513ms
Event Format.Groups Properties Preserved Batch 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 517ms
Batch Behavior.Batch Envelope Smoke 516ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 517ms
Deduplication.Different Events Same Content Different Uuids 512ms
Deduplication.Preserves Uuid On Retry 6515ms
Deduplication.Preserves Timestamp On Retry 6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6523ms
Deduplication.No Duplicate Events In Batch 518ms
Header Behavior On Retry.Attempt Header Starts At One 509ms
Header Behavior On Retry.Attempt Header Increments On Retry 13526ms
Header Behavior On Retry.Request Id Preserved On Retry 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3019ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6519ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 512ms
Response Format Validation.Success No Retry After When All Ok 512ms
Response Format Validation.Success Retry After Present When Retry Events 1516ms
Response Format Validation.Success No Retry After When Drop Only 513ms
Response Format Validation.Response Echoes Request Id 510ms
Retry Behavior.Retries On 408 6517ms
Retry Behavior.Retries On 500 6520ms
Retry Behavior.Retries On 503 8522ms
Retry Behavior.Retries On 504 6519ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11522ms
Retry Behavior.Does Not Retry On 400 2513ms
Retry Behavior.Does Not Retry On 401 2511ms
Retry Behavior.Does Not Retry On 402 2513ms
Retry Behavior.Does Not Retry On 413 2512ms
Retry Behavior.Does Not Retry On 415 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22534ms
Retry Behavior.Max Retries Respected 22532ms
Partial Batch Handling.Handles 200 Full Success 2511ms
Partial Batch Handling.Handles 200 With All Ok 3516ms
Partial Batch Handling.Does Not Retry Dropped Events 3513ms
Partial Batch Handling.Does Not Retry Limited Events 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6519ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial 6519ms
Partial Batch Handling.Partial Retry Preserves Uuids 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved 6517ms
Partial Batch Handling.Respects Retry After On Partial 8521ms
Partial Batch Handling.Unknown Result Treated As Terminal 3515ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3517ms
Compression.Sends Gzip Content Encoding 512ms
Compression.No Content Encoding When Disabled 510ms
Compression.Compressed Body Is Decompressible 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2510ms
Event Options.Cookieless Mode Override 511ms
Event Options.Disable Skew Correction Override 509ms
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 510ms
Geoip And Historical Migration.Historical Migration Set In Body 510ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

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 9ms
Request Payload.Flags Request Hits Flags Path Not Decide 9ms
Request Payload.Flags Request Omits Authorization Header 9ms
Request Payload.Token In Flags Body Matches Init 9ms
Request Payload.Groups Round Trip 9ms
Request Payload.Groups Default To Empty Object 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 9ms
Request Payload.Disable Geoip Omitted Defaults To False 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
Request Lifecycle.No Flags Request On Init Alone 4ms
Request Lifecycle.No Flags Request On Normal Capture 509ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 14ms
Request Lifecycle.Mock Response Value Is Returned To Caller 9ms
Retry Behavior.Retries Flags On 502 312ms
Retry Behavior.Retries Flags On 504 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 511ms

@greptile-apps

greptile-apps Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/mcp/_instrument_fastmcp.py:337-349
**Duplicated prompt-back policy**

This helper repeats the same mint/delivery logic in `_instrument_lowlevel.py` and `_instrument_v2.py`, recreating the risk of adapters drifting apart. It violates the repository’s “says everything once and only once” requirement, which must be satisfied before merging. Move the shared policy into one helper and leave only adapter-specific result wrapping in each adapter.

### Issue 2
posthog/test/mcp/test_units.py:318-320
**Tool-name loop tests identical inputs**

Each iteration calls `resolve_conversation_id(True, {})` with identical inputs; `name` only changes the assertion message. This suggests tool-specific coverage without exercising different behavior and violates the repository’s “no superfluous parts” requirement, which must be satisfied before merging. Replace the loop with one assertion and keep tool-name coverage at the lifecycle or adapter level, where names are actually consumed.

```suggestion
    cid, minted = resolve_conversation_id(True, {})
    assert minted is True and cid
```

---

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

Reviews (1): Last reviewed commit: "feat(mcp): anchor the virtual tools to t..." | Re-trigger Greptile

Comment on lines +337 to +349
def _conversation_prompt_back(lifecycle: Any) -> Tuple[Any, bool]:
"""``(prompt_back_block_or_None, delivered)`` for a virtual tool's reply.

A minted handle rides a prompt-back block so the agent can echo it on its
next call and keep the whole exchange in one session; an echoed one needs no
delivery. ``delivered`` gates stamping the handle on the event, so a handle
the agent never received is never recorded."""
if lifecycle.conversation_id and lifecycle.minted_conversation_id:
block = mcp_types.TextContent(
type="text", text=build_prompt_back(lifecycle.conversation_id)["text"]
)
return block, True
return None, bool(lifecycle.conversation_id)

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.

P2 Duplicated prompt-back policy

This helper repeats the same mint/delivery logic in _instrument_lowlevel.py and _instrument_v2.py, recreating the risk of adapters drifting apart. It violates the repository’s “says everything once and only once” requirement, which must be satisfied before merging. Move the shared policy into one helper and leave only adapter-specific result wrapping in each adapter.

Context Used: Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/mcp/_instrument_fastmcp.py
Line: 337-349

Comment:
**Duplicated prompt-back policy**

This helper repeats the same mint/delivery logic in `_instrument_lowlevel.py` and `_instrument_v2.py`, recreating the risk of adapters drifting apart. It violates the repository’s “says everything once and only once” requirement, which must be satisfied before merging. Move the shared policy into one helper and leave only adapter-specific result wrapping in each adapter.

**Context Used:** Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +318 to +320
for name in ("get_more_tools", "send_feedback", "echo"):
cid, minted = resolve_conversation_id(True, {})
assert minted is True and cid, name

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.

P2 Tool-name loop tests identical inputs

Each iteration calls resolve_conversation_id(True, {}) with identical inputs; name only changes the assertion message. This suggests tool-specific coverage without exercising different behavior and violates the repository’s “no superfluous parts” requirement, which must be satisfied before merging. Replace the loop with one assertion and keep tool-name coverage at the lifecycle or adapter level, where names are actually consumed.

Suggested change
for name in ("get_more_tools", "send_feedback", "echo"):
cid, minted = resolve_conversation_id(True, {})
assert minted is True and cid, name
cid, minted = resolve_conversation_id(True, {})
assert minted is True and cid

Context Used: Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/test/mcp/test_units.py
Line: 318-320

Comment:
**Tool-name loop tests identical inputs**

Each iteration calls `resolve_conversation_id(True, {})` with identical inputs; `name` only changes the assertion message. This suggests tool-specific coverage without exercising different behavior and violates the repository’s “no superfluous parts” requirement, which must be satisfied before merging. Replace the loop with one assertion and keep tool-name coverage at the lifecycle or adapter level, where names are actually consumed.

```suggestion
    cid, minted = resolve_conversation_id(True, {})
    assert minted is True and cid
```

**Context Used:** Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@gesh
gesh force-pushed the posthog/mcp-virtual-tool-conversation-id branch 2 times, most recently from 3bea84f to 31d5a92 Compare September 16, 2026 09:23
@gesh
gesh force-pushed the posthog/mcp-virtual-tool-first-page branch from 8daec48 to 3aac206 Compare September 16, 2026 09:29
@gesh
gesh force-pushed the posthog/mcp-virtual-tool-conversation-id branch from 31d5a92 to 24b200b Compare September 16, 2026 09:29
@gesh
gesh force-pushed the posthog/mcp-virtual-tool-conversation-id branch from 24b200b to af09f57 Compare September 16, 2026 09:54
Capture intent for tools the host owns; skip it only for PostHog's own.
The code asked that question two different ways and they disagreed.

Interception asked a per-request probe, which was right. Intent and the
conversation exemption asked `virtual_tool_collisions`, which only a
served tools/list writes. On a process that had served none -- the
ordinary multi-pod case the probe exists for -- a host tool named
`get_more_tools` dispatched correctly but its $mcp_tool_call carried
`$mcp_intent=None`. Permanent on FastMCP and v2 MCPServer; on raw
low-level it self-healed after one call, because the MCP SDK's own
`req is None` cache pass happens to refresh the state during dispatch.

The intent guard turns out to be dead code for its stated purpose:
PostHog's virtual tools are intercepted before dispatch and captured by
record_missing_capability / record_feedback, so they never reach
record_tool_call. Verified by spying on it. Everything that gets there
is host-dispatched by construction, so the guard could only ever fire
on a host tool sharing the name. Removed.

The same applies to the conversation exemption: the virtual tools'
capture paths discard the resolved handle, so exempting by name only
ever cost the host's tool its handle.

start_tool_call_lifecycle now reads `enabled_virtual_tool_names`
instead of `injectable_`, so the call path stops reading listing state
altogether. That also closes the cross-client report: the collision set
is per-server and rewritten by whichever listing ran last, so reading
it on the call path let one caller's catalogue decide another caller's
call.

Note on the reports: the missing conversation id they also cite is not
name-specific -- an ordinary tool shows the same in that harness, so it
is not a regression here. The new tests assert parity with an ordinary
tool instead, which is the rule being fixed.

The changeset claimed a real `get_more_tools` "keeps its $mcp_intent",
which was only true after a listing on the same instance. Corrected.

Reported by QA Swarm and veria-ai on #962.

Generated-By: PostHog Desktop
Task-Id: 989fd424-fd24-4ae4-8682-548b87f761f6
With enable_conversation_id on, get_more_tools and send_feedback now
advertise conversation_id, echo a minted handle back over prompt-back,
and stamp $mcp_conversation_id -- under any configured name.

They were exempt, in three places that had to agree: the schema pass
skipped the argument, resolve_conversation_id short-circuited on their
names, and the lifecycle passed None when preparing their session. So
a $mcp_feedback or $mcp_missing_capability event was filed under a
$session_id of its own. An agent's complaint about a tool landed in a
different session than the call it was complaining about, which is
most of the value of the report, and the fallback session emitted a
second spurious $mcp_initialize.

resolve_conversation_id loses its two tool-name parameters: with no
tool exempt there is nothing to compare against, so the exemption
cannot come back by accident.

The virtual tools still never get the injected `context` argument --
they state their intent through their own -- so `is_sdk_virtual_tool`
now gates only that.

Two tests are inverted on purpose, with the reasoning in their
docstrings: test_feedback_never_mints_conversation_id becomes
test_feedback_joins_the_conversation, and the renamed-tool schema case
now expects the argument to track the option.

Stacked on #962.

Generated-By: PostHog Desktop
Task-Id: 989fd424-fd24-4ae4-8682-548b87f761f6
The per-request ownership fix landed here rather than in #962, so its
user-facing effects belong in this changeset, not that one.

Generated-By: PostHog Desktop
Task-Id: 989fd424-fd24-4ae4-8682-548b87f761f6
@gesh
gesh force-pushed the posthog/mcp-virtual-tool-conversation-id branch from af09f57 to dc9873c Compare September 16, 2026 09:59
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