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_store): record what agents search for through exec (#78787)

Tom Owerscc052c3533c9
diff --git a/products/mcp_store/README.md b/products/mcp_store/README.md
index a1a242fcccf0..b7fcf075b421 100644
--- a/products/mcp_store/README.md
+++ b/products/mcp_store/README.md
@@ -126,6 +126,7 @@ There are two ways a caller uses a connection, and they differ in who speaks MCP
The caller wants a result, not a transport, so PostHog runs the handshake server-side (`call_upstream_tool` in `backend/tools.py`).
This is what the PostHog MCP's `exec` uses, so an external agent (Claude Code, Codex) can call a connected server's tools through its existing PostHog connection instead of authenticating each vendor separately.
Discovery for that path is `GET .../mcp_server_installations/available_tools/`, which returns every callable tool across the caller's connections in one request, each namespaced by a server slug (`linear__create_issue`).
+ When two connections share a display name, both slugs carry a fragment of their installation id (`linear-a1b2c3`), and that ambiguity is decided over every connection the caller can address rather than only the reachable ones — otherwise an expiring token could re-point a tool name at a different connection between refreshes.
The `exec` side lives in `services/mcp/src/lib/gateway-tools.ts` and is gated on the `mcp-gateway` flag.
Both paths resolve policy through the same `resolve_call_decision` / `_gateway_decision` in `backend/proxy.py` and write the same `MCPAuditEvent` rows, so approval state and the audit trail cannot diverge between them.
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index 3ee0bc5c707a..68aa72e9cdea 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -1,8 +1,10 @@
import re
import json
import time
+import uuid
import hashlib
import secrets
+from collections import Counter
from collections.abc import Mapping
from datetime import timedelta
from typing import Any, cast
@@ -554,24 +556,34 @@ def _installation_display_name(installation: MCPServerInstallation) -> str:
return installation.url
-def _unique_server_slug(name: str, url: str, used: set[str]) -> str:
- """A short lowercase identifier callers use to namespace tool names.
-
- Stable across requests because callers iterate installations in id order, and
- unique within a response because two connections can legitimately share a
- display name (for example a personal and a shared install of one server).
- """
+def _server_slug_base(name: str, url: str) -> str:
base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
if not base:
base = re.sub(r"[^a-z0-9]+", "-", (urlparse(url).hostname or "server").lower()).strip("-")
- slug = base or "server"
- if slug in used:
- suffix = 2
- while f"{slug}-{suffix}" in used:
- suffix += 1
- slug = f"{slug}-{suffix}"
- used.add(slug)
- return slug
+ return base or "server"
+
+
+def _disambiguated_server_slug(base: str, installation_id: uuid.UUID) -> str:
+ """Suffix a slug with a stable fragment of its installation id.
+
+ Two connections can legitimately share a display name — a personal and a shared
+ install of one server. Numbering them by position (`linear`, `linear-2`) would
+ reshuffle whenever one becomes unavailable, so a tool name an agent read from
+ `search` could resolve to a *different* connection on a later command. Keying the
+ suffix to the installation makes a namespaced name mean one connection for good.
+
+ The `--` separator keeps a disambiguated slug from ever colliding with a bare base:
+ `_server_slug_base` collapses every run of non-alphanumerics to a single `-`, so no
+ base can contain `--`. Without that, a connection named to match a generated slug
+ (say `linear--abcdef`) would produce that exact bare slug and route another user's
+ gateway call — resolved by first match — to the wrong server.
+
+ The fragment comes from the tail of the id, not the head: ids are UUIDv7, whose
+ leading hex is a millisecond timestamp shared by every install created in the same
+ ~4.6h window. Two same-named connections would collide on `hex[:6]`; the trailing
+ hex is the random component that actually tells them apart.
+ """
+ return f"{base}--{installation_id.hex[-6:]}"
@extend_schema_field(OpenApiTypes.OBJECT)
@@ -654,7 +666,10 @@ class AvailableToolsResponseSerializer(serializers.Serializer):
class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "project"
- scope_object_read_actions = ["list", "retrieve", "authorize", "list_tools"]
+ # An action in neither list derives no scope, and APIScopePermission rejects
+ # personal-API-key and OAuth callers outright for those — so an agent surface would
+ # get a 403 that session-authenticated tests never see.
+ scope_object_read_actions = ["list", "retrieve", "authorize", "list_tools", "available_tools"]
scope_object_write_actions = [
"create",
"update",
@@ -1965,7 +1980,20 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
.order_by("id")
)
- used_slugs: set[str] = set()
+ # Decide slug ambiguity over every connection the caller can address, ignoring
+ # whether each is reachable today. Availability changes constantly — a token
+ # expires, an admin flips a server off — and if it fed this decision, a
+ # namespaced tool name could point at a different connection after a refresh.
+ # This set only moves when someone adds or removes a connection.
+ namespace_rows = (
+ MCPServerInstallation.objects.filter(team_id=self.team_id)
+ .filter(Q(user=user) | Q(scope="shared"))
+ .select_related("template")
+ )
+ base_slug_counts: Counter[str] = Counter(
+ _server_slug_base(_installation_display_name(row), row.url) for row in namespace_rows
+ )
+
servers: list[dict[str, Any]] = []
for installation in installations:
# The same credential check `call_tool` runs, so the list can never
@@ -1995,11 +2023,12 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
continue
name = _installation_display_name(installation)
+ base = _server_slug_base(name, installation.url)
servers.append(
{
"installation_id": installation.id,
"name": name,
- "slug": _unique_server_slug(name, installation.url, used_slugs),
+ "slug": _disambiguated_server_slug(base, installation.id) if base_slug_counts[base] > 1 else base,
"tools": sorted(tools, key=lambda t: t["name"]),
}
)
diff --git a/products/mcp_store/backend/test/test_gateway_exec_tools.py b/products/mcp_store/backend/test/test_gateway_exec_tools.py
index 2e7b8ee5021c..75d0e14f999f 100644
--- a/products/mcp_store/backend/test/test_gateway_exec_tools.py
+++ b/products/mcp_store/backend/test/test_gateway_exec_tools.py
@@ -1,3 +1,5 @@
+from datetime import timedelta
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -5,6 +7,9 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from products.mcp_store.backend.models import (
MCPAuditEvent,
@@ -140,6 +145,49 @@ class TestGatewayExecTools(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
assert not mock_call.called
+ def _read_scoped_token_client(self) -> APIClient:
+ """A `project:read` OAuth client, which is how the PostHog MCP authenticates.
+ Session auth takes a different branch through APIScopePermission, so it cannot
+ catch an action that derives no scope."""
+ application = OAuthApplication.objects.create(
+ name="MCP gateway exec",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token="pha_mcp_gateway_exec_read",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="project:read",
+ scoped_teams=[self.team.id],
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")
+ return client
+
+ @parameterized.expand([("available_tools",), ("call_tool",)])
+ @patch("products.mcp_store.backend.presentation.views.call_upstream_tool", return_value=_UPSTREAM_RESULT)
+ def test_agent_surfaces_reach_both_endpoints_with_a_read_scoped_token(self, endpoint, _mock_call):
+ self._tool()
+ client = self._read_scoped_token_client()
+ base = f"/api/projects/{self.team.id}/mcp_server_installations/"
+
+ if endpoint == "available_tools":
+ response = client.get(f"{base}available_tools/")
+ else:
+ response = client.post(
+ f"{base}{self.installation.id}/call_tool/",
+ {"tool_name": "create_issue", "arguments": {}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
def test_available_tools_lists_callable_tools_with_schema(self):
self._tool()
@@ -225,7 +273,42 @@ class TestGatewayExecTools(APIBaseTest):
assert [s["installation_id"] for s in servers] == [str(shared.id)]
- def test_available_tools_gives_same_named_connections_distinct_slugs(self):
+ def test_available_tools_keys_colliding_slugs_to_their_installation(self):
+ # Numbering same-named connections by position would reshuffle when one goes
+ # unavailable, so a tool name an agent read from `search` could later resolve to a
+ # different connection. Keying the suffix to the installation prevents that.
+ self._tool()
+ second = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ gateway_server=self.server,
+ display_name="Linear",
+ url="https://mcp.linear-second.example.com/mcp",
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-second"},
+ )
+ self._tool(installation=second)
+
+ slugs = {s["installation_id"]: s["slug"] for s in self._available().json()["servers"]}
+
+ assert slugs == {
+ str(self.installation.id): f"linear--{self.installation.id.hex[-6:]}",
+ str(second.id): f"linear--{second.id.hex[-6:]}",
+ }
+
+ # The surviving connection keeps the slug it already had once its twin drops out.
+ second.is_enabled = False
+ second.save()
+
+ remaining = self._available().json()["servers"]
+ assert [s["slug"] for s in remaining] == [f"linear--{self.installation.id.hex[-6:]}"]
+
+ def test_available_tools_crafted_name_cannot_collide_with_a_generated_slug(self):
+ # A second `linear` install forces both onto `linear--<hex>` slugs. A third
+ # connection named to match one of those generated slugs (its single-dash form,
+ # the only shape a display name can normalize to) must not reuse it — a colliding
+ # slug would let exec (first match wins) route a call to the wrong server. The
+ # `--` separator keeps a display name from ever producing a generated slug.
self._tool()
second = MCPServerInstallation.objects.create(
team=self.team,
@@ -237,7 +320,17 @@ class TestGatewayExecTools(APIBaseTest):
sensitive_configuration={"api_key": "sk-second"},
)
self._tool(installation=second)
+ crafted = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ gateway_server=self.server,
+ display_name=f"linear-{self.installation.id.hex[-6:]}",
+ url="https://mcp.linear-crafted.example.com/mcp",
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-crafted"},
+ )
+ self._tool(installation=crafted)
slugs = [s["slug"] for s in self._available().json()["servers"]]
- assert sorted(slugs) == ["linear", "linear-2"]
+ assert len(slugs) == len(set(slugs)), f"slugs must be unique, got {slugs}"
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.ts
index 6716c15f164b..dddcdb23b9ae 100644
--- a/services/mcp/src/hono/analytics.ts
+++ b/services/mcp/src/hono/analytics.ts
@@ -11,6 +11,7 @@ import {
type MCPAnalyticsContext,
} from '@/lib/posthog/analytics'
import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'
+import { gatewayServerSlug, isGatewayToolName, THIRD_PARTY_TOOL_CATEGORY } from '@/lib/gateway-tools'
import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'
import { buildMCPSessionAnalyticsProperties, getEffectiveMCPClientIdentity } from './mcp-context'
@@ -128,7 +129,10 @@ export async function trackToolCall(
// The producer stamps the tool's category so the dashboard groups by it verbatim
// (it never maps tool→category itself). Omitted when unknown (e.g. the `exec`
// wrapper), which the dashboard buckets as "Uncategorized".
- const toolCategory = getToolCategory(toolName)
+ // A proxied third-party tool has no catalog entry, so without the fallback every
+ // gateway call would land uncategorized and drop out of category-sliced views.
+ const gatewayServer = gatewayServerSlug(toolName)
+ const toolCategory = getToolCategory(toolName) ?? (gatewayServer ? THIRD_PARTY_TOOL_CATEGORY : undefined)
// The description the agent saw when it picked this tool, clipped. Powers the
// tool-detail Descriptions table and description-vs-intent fit in MCP
// analytics. Callers pass servedDescription when the advertised text differs
@@ -159,6 +163,9 @@ export async function trackToolCall(
tool_name: toolName,
...(toolCategory ? { $mcp_tool_category: toolCategory } : {}),
...(toolDescription ? { $mcp_tool_description: toolDescription } : {}),
+ // Which vendor ran the tool, so "who do people actually call" is a
+ // breakdown rather than a string split over `tool_name` in HogQL.
+ ...(gatewayServer ? { mcp_gateway_server: gatewayServer } : {}),
...extraProperties,
},
})
@@ -247,6 +254,15 @@ function isMetadataQuery(query: string): boolean {
}
function shouldCaptureToolSpan(toolName: string, input: unknown): boolean {
+ // A proxied third-party tool's args and result are the vendor's content — an issue
+ // body, a support ticket, a CRM record — passing through our gateway on its way
+ // somewhere else. Key-based redaction only catches credential-shaped fields, so
+ // capturing these would put arbitrary customer content in analytics to serve
+ // evaluations that target PostHog's own tools. `$mcp_tool_call` still records that
+ // the call happened, with its server, duration and outcome.
+ if (isGatewayToolName(toolName)) {
+ return false
+ }
// execute-sql can't be captured wholesale: its payload is the query result,
// which is the bulk of MCP response volume. Metadata queries are the
// exception, because their results are small and describe what the agent
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 423dde8721e2..1fa4346189f5 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -26,6 +26,7 @@ import {
describeExecCommand,
describeValidationError,
formatInputValidationError,
+ type ExecCommandMeta,
type ExecInnerCallTracker,
} from '@/tools/exec'
import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'
@@ -54,6 +55,8 @@ interface ResolvedTool {
interface ExecMetricState {
innerToolName: string | undefined
+ /** What the agent asked for, merged onto the event whichever verb ran. */
+ commandMeta: ExecCommandMeta | undefined
}
export class ToolExecutor {
@@ -338,7 +341,7 @@ export class ToolExecutor {
state: ResolvedState,
intentMeta?: ToolCallIntentMeta
): Promise<unknown> {
- const execMetrics: ExecMetricState = { innerToolName: undefined }
+ const execMetrics: ExecMetricState = { innerToolName: undefined, commandMeta: undefined }
const resolved = this.resolveExecTool(state, execMetrics, intentMeta)
const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>
@@ -393,6 +396,7 @@ export class ToolExecutor {
...execShape,
input_tokens: estimateTokens(validation.data),
output_tokens: estimateResponseTokens(response),
+ ...execMetrics.commandMeta,
},
intentMeta,
this.servedToolDescription(execToolName(), state)
@@ -413,7 +417,7 @@ export class ToolExecutor {
Date.now() - startMs,
true,
state,
- { ...execShape, ...errorAnalyticsProperties(classification, error) },
+ { ...execShape, ...errorAnalyticsProperties(classification, error), ...execMetrics.commandMeta },
intentMeta,
this.servedToolDescription(metricTool, state)
)
@@ -514,6 +518,11 @@ export class ToolExecutor {
isInlineExecUiHost: state.clientProfile.isInlineExecUiHost(),
helpCatalog: this.instructionsBuilder.buildExecHelpCatalog(state),
...(state.gatewayToolsEnabled ? { gatewayToolsProvider: () => this.gatewayToolsFor(state) } : {}),
+ // A verb-only report lands first; `search` then reports again with its query
+ // and counts. Merge so the richer report wins without losing the verb.
+ trackCommand: (meta) => {
+ execMetrics.commandMeta = { ...execMetrics.commandMeta, ...meta }
+ },
}
)
diff --git a/services/mcp/src/lib/gateway-tools.ts b/services/mcp/src/lib/gateway-tools.ts
index 5ee61de53e62..4043f1ab228d 100644
--- a/services/mcp/src/lib/gateway-tools.ts
+++ b/services/mcp/src/lib/gateway-tools.ts
@@ -22,6 +22,10 @@ import type { Context, Tool, ZodObjectAny } from '@/tools/types'
* kebab-case and never contain `__`, so a namespaced name can't collide with one. */
export const GATEWAY_TOOL_SEPARATOR = '__'
+/** Analytics category for proxied tools. Matches the sentence case of the catalog's own
+ * categories, since both land in the same `$mcp_tool_category` breakdown. */
+export const THIRD_PARTY_TOOL_CATEGORY = 'Third-party tools'
+
type AvailableServer = Schemas.AvailableServer
type AvailableTool = Schemas.AvailableTool
@@ -36,6 +40,19 @@ export function gatewayToolName(slug: string, toolName: string): string {
return `${slug}${GATEWAY_TOOL_SEPARATOR}${toolName}`
}
+/** Whether a tool name came from a connected third-party server rather than PostHog. */
+export function isGatewayToolName(name: string): boolean {
+ return name.includes(GATEWAY_TOOL_SEPARATOR)
+}
+
+/** The server slug a namespaced tool name routes to, or undefined for a PostHog tool. */
+export function gatewayServerSlug(name: string): string | undefined {
+ if (!isGatewayToolName(name)) {
+ return undefined
+ }
+ return name.slice(0, name.indexOf(GATEWAY_TOOL_SEPARATOR))
+}
+
/**
* Upstream tools declare their contract as JSON Schema, which the upstream server also
* enforces. Validating a second time here would only add a way for us to reject a call
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 0d97c5b803df..a9a222418c54 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -9,7 +9,7 @@ import { formatResponse } from '@/lib/response'
import type { ExecHelpCatalog } from './exec-help'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
-import { GATEWAY_TOOL_SEPARATOR } from '@/lib/gateway-tools'
+import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'
import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'
import type { ScopeGatedTool } from './toolDefinitions'
@@ -78,6 +78,27 @@ export interface ExecInnerCallProperties {
export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void
+/**
+ * What the agent asked `exec` to do, for the `$mcp_tool_call` event.
+ *
+ * `call` is already attributed to the inner tool it dispatched, so the value here is in
+ * the other verbs — above all `search`, whose query is the only record of what an agent
+ * looked for. A search that matches nothing is otherwise invisible, which leaves the
+ * question "which capability do people reach for that we don't have" unanswerable.
+ */
+export interface ExecCommandMeta {
+ /** The verb the agent used: `search`, `info`, `schema`, `tools`, `learn`, `call`. */
+ exec_verb: string
+ /** The raw search query. Already bounded to MAX_SEARCH_PATTERN_LENGTH by the handler. */
+ exec_search_query?: string
+ /** How many tools matched, before the response is truncated — 0 is the interesting case. */
+ exec_search_match_count?: number
+ /** How many of those matches came from a connected third-party server. */
+ exec_search_gateway_match_count?: number
+}
+
+export type ExecCommandTracker = (meta: ExecCommandMeta) => void
+
export interface ExecToolOptions {
requireDestructiveConfirmation?: boolean
helpCatalog?: ExecHelpCatalog
@@ -95,6 +116,8 @@ export interface ExecToolOptions {
* degrades to "no third-party tools", never to a broken `exec`.
*/
gatewayToolsProvider?: () => Promise<Tool<ZodObjectAny>[]>
+ /** Reports what the agent asked for, so non-`call` verbs stop being invisible. */
+ trackCommand?: ExecCommandTracker
}
function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {
@@ -576,6 +599,9 @@ export function createExecTool(
},
handler: async (_context: Context, params: z.infer<ExecSchema>) => {
const { verb, rest } = parseCommand(params.command)
+ // Reported up front so a command that throws (unknown tool, bad regex) still
+ // records what was attempted — those are the failures worth counting.
+ options.trackCommand?.({ exec_verb: verb })
let gatewayTools: Tool<ZodObjectAny>[] | undefined
/** PostHog's tools plus any third-party tools the caller has connected.
@@ -656,12 +682,17 @@ export function createExecTool(
// predicate; plain words — including multi-word, natural-
// language queries — use forgiving token ranking.
const searchableTools = await resolveTools()
+ // `matches` is the page the agent sees; `matchedNames` is every match,
+ // which is what the counts report — a truncated page would make a broad
+ // query look as narrow as a precise one.
+ let matchedNames: string[]
let matches: string[]
let gatedMatches: ScopeGatedTool[]
let truncatedFrom = 0
if (isRegexPattern(rest)) {
try {
- matches = searchToolsRegex(searchableTools, rest).map((t) => t.name)
+ matchedNames = searchToolsRegex(searchableTools, rest).map((t) => t.name)
+ matches = matchedNames
gatedMatches = searchToolsRegex(scopeGatedTools, rest)
} catch {
throw new ExecCommandError(`Invalid regex pattern: "${rest}"`, 'invalid_regex')
@@ -669,7 +700,8 @@ export function createExecTool(
} else {
const ranked = searchToolsRanked(searchableTools, rest)
truncatedFrom = ranked.length > MAX_RANKED_SEARCH_RESULTS ? ranked.length : 0
- matches = ranked.slice(0, MAX_RANKED_SEARCH_RESULTS).map((r) => r.name)
+ matchedNames = ranked.map((r) => r.name)
+ matches = matchedNames.slice(0, MAX_RANKED_SEARCH_RESULTS)
// Preserve ranked order for gated matches too, then map
// each name back to its ScopeGatedTool (for missingScopes).
const gatedByName = new Map(scopeGatedTools.map((t) => [t.name, t]))
@@ -678,6 +710,13 @@ export function createExecTool(
.filter((t): t is ScopeGatedTool => t !== undefined)
}
+ options.trackCommand?.({
+ exec_verb: verb,
+ exec_search_query: rest,
+ exec_search_match_count: matchedNames.length,
+ exec_search_gateway_match_count: matchedNames.filter(isGatewayToolName).length,
+ })
+
if (gatedMatches.length > 0) {
const requiredScopes = [...new Set(gatedMatches.flatMap((t) => t.missingScopes))].sort()
return JSON.stringify({
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index 89dbda321dd8..9c46b9ed19ae 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -118,6 +118,22 @@ describe('Hono MCP analytics contexts', () => {
expect(properties.mcp_session_vendor_client).toBeUndefined()
})
+ it('categorizes a proxied third-party tool and names its server', async () => {
+ // A gateway tool has no catalog entry, so without the fallback it lands
+ // uncategorized and disappears from every category-sliced view.
+ await trackToolCall('linear__create_issue', 12, false, makeState())
+
+ const properties = mockCaptureToolCall.mock.calls[0]![0].properties
+ expect(properties.$mcp_tool_category).toBe('Third-party tools')
+ expect(properties.mcp_gateway_server).toBe('linear')
+ })
+
+ it('leaves a PostHog tool without a gateway server', async () => {
+ await trackToolCall('user-get', 12, false, makeState())
+
+ expect(mockCaptureToolCall.mock.calls[0]![0].properties.mcp_gateway_server).toBeUndefined()
+ })
+
describe('client identity live-first fallback', () => {
// $mcp_client_name is the property this whole fix targets: `clientInfo` arrives
// only on `initialize`, so it was empty on every tool call that followed. The
@@ -335,6 +351,11 @@ describe('Hono MCP analytics contexts', () => {
{ query: 'SELECT count() FROM events -- information_schema' },
false,
],
+ // A proxied vendor tool's args and result are the customer's content passing
+ // through the gateway. Key-based redaction only catches credential-shaped
+ // fields, so capturing the payload would put arbitrary third-party content in
+ // analytics to serve evaluations that target PostHog's own tools.
+ ['a proxied third-party tool', 'linear__create_issue', { title: 'Customer escalation' }, false],
])('gates capture for %s', async (_case, toolName, input, captured) => {
await trackToolSpan(toolName, makeState(), { durationMs: 100, isError: false, input, output: 'rows' })
diff --git a/services/mcp/tests/unit/gateway-tools.test.ts b/services/mcp/tests/unit/gateway-tools.test.ts
index 4bf44148b133..1cc018caef21 100644
--- a/services/mcp/tests/unit/gateway-tools.test.ts
+++ b/services/mcp/tests/unit/gateway-tools.test.ts
@@ -4,7 +4,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import { ExecCommandError } from '@/lib/errors'
import { buildGatewayTools } from '@/lib/gateway-tools'
-import { createExecTool } from '@/tools/exec'
+import { createExecTool, type ExecCommandMeta } from '@/tools/exec'
import type { Context, Tool, ZodObjectAny } from '@/tools/types'
const INPUT_SCHEMA = {
@@ -205,4 +205,90 @@ describe('gateway tools', () => {
expect(provider).toHaveBeenCalledTimes(1)
})
+
+ describe('command tracking', () => {
+ function createTrackedExec(gatewayPayload: Schemas.AvailableToolsResponse = payload()): {
+ exec: Tool<any>
+ tracked: ExecCommandMeta[]
+ } {
+ const tracked: ExecCommandMeta[] = []
+ const gatewayTools = buildGatewayTools(gatewayPayload, mockContext(), '1')
+ const exec = createExecTool(
+ [posthogTool()],
+ mockContext(),
+ 'description',
+ 'command reference',
+ undefined,
+ undefined,
+ [],
+ {
+ gatewayToolsProvider: async () => gatewayTools,
+ trackCommand: (meta) => tracked.push(meta),
+ }
+ )
+ return { exec, tracked }
+ }
+
+ // The zero-match row is the reason this tracking exists: a search that finds
+ // nothing is the only record of a capability someone wanted and we lack. The
+ // gateway count separates "we have this" from "a vendor has this".
+ it.each([
+ ['matches both a PostHog and a gateway tool', 'create issue', 2, 1],
+ ['matches a PostHog tool only', 'feature flag', 1, 0],
+ ['matches nothing', 'kubernetes', 0, 0],
+ ])('reports a search that %s', async (_label, query, matchCount, gatewayMatchCount) => {
+ const { exec, tracked } = createTrackedExec()
+
+ await exec.handler(mockContext(), { command: `search ${query}` })
+
+ expect(tracked.at(-1)).toEqual({
+ exec_verb: 'search',
+ exec_search_query: query,
+ exec_search_match_count: matchCount,
+ exec_search_gateway_match_count: gatewayMatchCount,
+ })
+ })
+
+ it('counts every match, not just the page a truncated search returns', async () => {
+ // A ranked search returns only its top page, so counting what was returned
+ // would make a query matching far more tools look as narrow as one that
+ // matched exactly a page — flattening the demand signal this exists to measure.
+ const manyTools = {
+ servers: [
+ {
+ installation_id: 'inst-1',
+ name: 'Linear',
+ slug: 'linear',
+ tools: Array.from({ length: 30 }, (_, i) => ({
+ name: `issue_action_${i}`,
+ description: 'Act on an issue',
+ input_schema: INPUT_SCHEMA,
+ annotations: {},
+ approval_state: 'approved',
+ })),
+ },
+ ],
+ } as Schemas.AvailableToolsResponse
+ const { exec, tracked } = createTrackedExec(manyTools)
+
+ const result = JSON.parse((await exec.handler(mockContext(), { command: 'search issue' })) as string)
+
+ expect(result.truncated).toBe(true)
+ expect(result.matches.length).toBeLessThan(30)
+ expect(tracked.at(-1)).toEqual({
+ exec_verb: 'search',
+ exec_search_query: 'issue',
+ exec_search_match_count: 30,
+ exec_search_gateway_match_count: 30,
+ })
+ })
+
+ it('reports the verb even when the command throws', async () => {
+ const { exec, tracked } = createTrackedExec()
+
+ await expect(exec.handler(mockContext(), { command: 'call nope {}' })).rejects.toThrow()
+
+ expect(tracked).toEqual([{ exec_verb: 'call' }])
+ })
+ })
})