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.

chore(mcp): show agent API diffs and autoresolve generated files (#111812)

Julian Bezc2c070977baf
diff --git a/.agents/skills/autoresolving-pr-conflicts/SKILL.md b/.agents/skills/autoresolving-pr-conflicts/SKILL.md
index 36771b95ec03..9e8ee725253b 100644
--- a/.agents/skills/autoresolving-pr-conflicts/SKILL.md
+++ b/.agents/skills/autoresolving-pr-conflicts/SKILL.md
@@ -79,12 +79,12 @@ All marker reads and writes go through the helper (run from your sweep-start sna
1. Set `HEAD_REF='<headRefName>'` (quoted everywhere below). Confirm the PR still targets `master` (`gh api "repos/$REPO/pulls/<n>" --jq .base.ref`) and skip it if not; a retarget between the listing and here does not move the head, so nothing else catches it. Verify the remote head still matches the OID from the listing: `git ls-remote --exit-code origin "refs/heads/$HEAD_REF"`. If the branch moved, skip silently; a later run handles the new state. Never pre-screen with `branches/<b> --jq .protected`: an org-level ruleset makes it true for every branch here. Let the push fail instead, and treat a refused push as the protected-branch case.
2. `git checkout -B "$HEAD_REF" refs/remotes/pull/<n>`, then `git merge --no-commit --no-ff origin/master`.
3. Classify the conflicted files (`git diff --name-only --diff-filter=U`):
- - **Generated artifacts**: `pnpm-lock.yaml`, `**/pnpm-lock.yaml`, `uv.lock`, `frontend/src/generated/**`, `products/**/frontend/generated/**`. Never hand-edit these.
+ - **Generated artifacts**: `pnpm-lock.yaml`, `**/pnpm-lock.yaml`, `uv.lock`, `frontend/src/generated/**`, `products/**/frontend/generated/**`, `frontend/src/lib/agentScopes.generated.ts`, and the generated MCP files (`services/mcp/src/api/generated.ts`, `services/mcp/src/generated/**`, `services/mcp/src/tools/generated/**`, `services/mcp/schema/{generated-tool-definitions,tool-definitions-all,tool-inputs}.json`, `services/mcp/schema/exec-command-reference.md`, `services/mcp/src/resources/ui-apps.generated.ts`, `services/mcp/src/ui-apps/generated/**`, `services/mcp/src/ui-apps/apps/generated/**`). Never hand-edit these.
- **Source**: everything else, including `max_migration.txt`.
4. Resolve source conflicts first, with judgment. Reconcile both sides' intent; a correct resolution usually keeps behavior from both. Flag for a human instead of resolving when both sides changed the same logic in incompatible ways, the intent is ambiguous or contradictory, the code is security-sensitive, or you are not confident the merged result is correct. Migration-numbering conflicts (`max_migration.txt`): renumber to avoid collisions and keep dependencies valid, renaming sibling migration files as needed; follow the conventions in `.agents/skills/django-migrations/`.
5. Regenerate generated artifacts deterministically, after source is resolved. The merged tree is PR-controlled code, so regeneration never runs in your credentialed session; it runs in a disposable, credentialless container (requires Docker, i.e. the VM runtime). The export/import boundary is scripted so it can't drift — use the snapshot's `regen-artifacts.sh`:
- `regen-artifacts.sh export . "$SCRATCH/<pr>/tree"` copies the merged tree without `.git` (which holds the token-bearing remote). Use a fresh, PR-unique destination each time; the helper refuses a directory that already exists, so a file from an earlier PR can never linger in the tree and leak into this one.
- - Run the regen inside a fresh container over that copy only: empty environment (`--env-file /dev/null`), no mounts outside the copy, only the network the step needs. In there, `bin/hogli ci:preflight --fix` covers lockfiles; `bin/hogli build:openapi` covers generated API types and needs Postgres and ClickHouse — start those services once per sweep and reuse them across PRs (they run no PR-controlled code and hold no credentials; only the code container is per-PR and disposable). Never mount host paths into any of them.
+ - Run the regen inside a fresh container over that copy only: empty environment (`--env-file /dev/null`), no mounts outside the copy, only the network the step needs. In there, `bin/hogli ci:preflight --fix` covers lockfiles; `bin/hogli build:openapi` covers generated API types and the MCP files built from the OpenAPI spec (Zod, tool handlers, tool definitions JSON) and needs Postgres and ClickHouse — start those services once per sweep and reuse them across PRs (they run no PR-controlled code and hold no credentials; only the code container is per-PR and disposable). The MCP files that need no backend (`tool-inputs.json`, the UI app files) regenerate afterwards with `bin/hogli build:schema-mcp` and `pnpm --filter=@posthog/mcp run generate:ui-apps`. Never mount host paths into any of them.
- `regen-artifacts.sh import "$SCRATCH/<pr>/tree" .` copies back only files matching the generated-artifact globs; everything else the container produced is discarded. It refuses if any destination path component is a symlink (a symlinked generated directory is an attack, not a layout choice); on refusal, flag the PR for a human and note it in the report.
- If this isolation is unavailable (no Docker), do not fall back to running the tooling in-session: flag the PR for a human with the reason "generated artifacts need regeneration", even if every other conflict resolved cleanly.
6. Verify: none of the originally conflicted files still contain a line starting with `<<<<<<<` or `>>>>>>>` (don't scan the whole tree; a stray `=======` divider in unrelated content would false-flag).
diff --git a/.agents/skills/autoresolving-pr-conflicts/scripts/regen-artifacts.sh b/.agents/skills/autoresolving-pr-conflicts/scripts/regen-artifacts.sh
index cc1e78bfcbf9..7b9a114c1d18 100755
--- a/.agents/skills/autoresolving-pr-conflicts/scripts/regen-artifacts.sh
+++ b/.agents/skills/autoresolving-pr-conflicts/scripts/regen-artifacts.sh
@@ -35,7 +35,18 @@ case "$cmd" in
find . -type f \
\( -name pnpm-lock.yaml -o -name uv.lock \
-o -path './frontend/src/generated/*' \
- -o -path './products/*/frontend/generated/*' \) -print0
+ -o -path './products/*/frontend/generated/*' \
+ -o -path ./frontend/src/lib/agentScopes.generated.ts \
+ -o -path ./services/mcp/src/api/generated.ts \
+ -o -path './services/mcp/src/generated/*' \
+ -o -path './services/mcp/src/tools/generated/*' \
+ -o -path ./services/mcp/schema/generated-tool-definitions.json \
+ -o -path ./services/mcp/schema/tool-definitions-all.json \
+ -o -path ./services/mcp/schema/exec-command-reference.md \
+ -o -path ./services/mcp/schema/tool-inputs.json \
+ -o -path ./services/mcp/src/resources/ui-apps.generated.ts \
+ -o -path './services/mcp/src/ui-apps/generated/*' \
+ -o -path './services/mcp/src/ui-apps/apps/generated/*' \) -print0
) | while IFS= read -r -d '' f; do
rel=${f#./}
path=$dest
diff --git a/.github/owners.yaml b/.github/owners.yaml
index f091a9b91961..7933618f90a6 100644
--- a/.github/owners.yaml
+++ b/.github/owners.yaml
@@ -11,9 +11,10 @@ rules:
owners: [team-devex, team-ai-observability]
- match:
- '/workflows/cd-mcp-image.yml'
+ - '/workflows/ci-mcp-agent-api-diff.yml'
- '/workflows/ci-mcp-ui-apps.yml'
- '/workflows/ci-mcp.yml'
- owners: [team-devex, team-context-mcp]
+ owners: [team-devex, team-context-and-mcp]
- match:
- '/workflows/ci-llm-gateway.yml'
- '/workflows/llm-gateway-cd.yml'
diff --git a/.github/workflows/ci-mcp-agent-api-diff.yml b/.github/workflows/ci-mcp-agent-api-diff.yml
new file mode 100644
index 000000000000..039091f7b022
--- /dev/null
+++ b/.github/workflows/ci-mcp-agent-api-diff.yml
@@ -0,0 +1,123 @@
+name: MCP agent API diff
+
+# Posts a short summary of what a PR changes for agents (tools added or removed, params, scopes,
+# annotations, input schema size) into the shared CI report comment. Reviewers of a product PR
+# that only regenerates MCP files see megabytes of diff and no hint of what agents will notice.
+# Informational only: nothing here can fail a PR, and nothing here is a required check.
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened, ready_for_review]
+ paths:
+ - 'products/*/mcp/**'
+ - 'services/mcp/definitions/**'
+ - 'services/mcp/schema/**'
+ - 'services/mcp/tests/unit/__snapshots__/tool-schemas/**'
+ - 'services/mcp/scripts/agent-api-diff.ts'
+ - 'services/mcp/scripts/lib/agent-api-diff.ts'
+ - 'services/mcp/scripts/post-agent-api-diff-section.mjs'
+ - '.github/workflows/ci-mcp-agent-api-diff.yml'
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ # Runs PR-controlled code, so it holds no write token. Its only output is a markdown artifact,
+ # which the posting job treats as data.
+ compute:
+ name: Compute agent API changes
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ # Same-repo PRs only: a fork's token cannot write the report comment. The merge queue's
+ # draft PRs are ephemeral and unread, and every section write spends shared token budget.
+ if: github.event.pull_request.head.repo.full_name == github.repository && !startsWith(github.head_ref, 'trunk-merge/')
+ permissions:
+ contents: read
+ outputs:
+ compared: ${{ steps.diff.outcome == 'success' }}
+ steps:
+ # The checked-out ref is the PR merged into its base, so HEAD^1 is the base tip and
+ # the diff against it is exactly what the PR changes, even when the branch is behind.
+ - name: Checkout code
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 2
+ persist-credentials: false
+
+ - name: Install pnpm dependencies
+ # Match services/mcp/Dockerfile exactly. No App token here: this job runs PR code and
+ # the action's token only feeds setup-node's rate-limited manifest lookups.
+ uses: ./.github/actions/pnpm-install
+ with:
+ install-command: pnpm --filter=@posthog/mcp... install --frozen-lockfile
+
+ # Guarded for branches that predate the scripts, and for a checkout without a base parent.
+ # Exit 3 from the script means the comparison could not run. The post job is then
+ # skipped, so an earlier report stays and is never replaced by a false "no changes".
+ - name: Compute agent API diff
+ id: diff
+ continue-on-error: true
+ run: |
+ if [ ! -f services/mcp/scripts/agent-api-diff.ts ]; then
+ echo "::notice::Skipping agent API diff - script not present on this checkout"
+ exit 1
+ fi
+ if ! git rev-parse --verify --quiet 'HEAD^1' > /dev/null; then
+ echo "::notice::Skipping agent API diff - no base commit to compare against"
+ exit 1
+ fi
+ mkdir -p agent-api-diff
+ pnpm --filter=@posthog/mcp exec tsx scripts/agent-api-diff.ts --base-ref 'HEAD^1' > agent-api-diff/agent-api-diff.md
+
+ - name: Upload agent API diff
+ if: steps.diff.outcome == 'success'
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: agent-api-diff
+ path: agent-api-diff/agent-api-diff.md
+ retention-days: 1
+ if-no-files-found: error
+
+ # Holds the write token, so it never checks out PR code. The posting script comes from the
+ # PR's base commit; the artifact is data and the script sanitizes it again.
+ post:
+ name: Post agent API changes
+ needs: compute
+ if: needs.compute.outputs.compared == 'true'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ pull-requests: write
+ steps:
+ - name: Checkout trusted scripts from base
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.base.sha }}
+ sparse-checkout: |
+ services/mcp/scripts/post-agent-api-diff-section.mjs
+ frontend/bin/ci-report
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
+
+ - name: Download agent API diff
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
+ with:
+ name: agent-api-diff
+ path: agent-api-diff
+
+ # Before this workflow lands on the base branch the script does not exist there.
+ - name: Post agent API diff to CI report comment
+ continue-on-error: true
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ if [ -f services/mcp/scripts/post-agent-api-diff-section.mjs ]; then
+ node services/mcp/scripts/post-agent-api-diff-section.mjs agent-api-diff/agent-api-diff.md
+ else
+ echo "::notice::Skipping report section - posting script not present on the base branch"
+ fi
diff --git a/.github/workflows/pr-autoresolve-conflicts.yml b/.github/workflows/pr-autoresolve-conflicts.yml
index a97fc71965de..bdeec77605ce 100644
--- a/.github/workflows/pr-autoresolve-conflicts.yml
+++ b/.github/workflows/pr-autoresolve-conflicts.yml
@@ -10,7 +10,7 @@ name: Auto-resolve PR conflicts
# running both would be redundant rather than harmful. To fall back to this implementation, restore
# the `schedule:` trigger below and pause the Loop.
#
-# Deterministic fixes (lockfiles, migration numbering, generated types) skip the model; the backend
+# Deterministic fixes (lockfiles, migration numbering, generated types, generated MCP files) skip the model; the backend
# stack comes up only for `build:openapi`. A marker comment records the last-attempted (head, master)
# so nothing re-runs on an unchanged conflict. Runs on GitHub-hosted runners (cheapest for a public
# repo).
@@ -46,10 +46,35 @@ env:
uv.lock
frontend/src/generated/**
products/**/frontend/generated/**
+ frontend/src/lib/agentScopes.generated.ts
+ services/mcp/src/api/generated.ts
+ services/mcp/src/generated/**
+ services/mcp/src/tools/generated/**
+ services/mcp/schema/generated-tool-definitions.json
+ services/mcp/schema/tool-definitions-all.json
+ services/mcp/schema/exec-command-reference.md
+ services/mcp/schema/tool-inputs.json
+ services/mcp/src/resources/ui-apps.generated.ts
+ services/mcp/src/ui-apps/generated/**
+ services/mcp/src/ui-apps/apps/generated/**
# Subset of GENERATED_GLOBS whose regen needs the backend stack (build:openapi).
+ # The MCP files here are the ones build:openapi writes from the OpenAPI spec.
API_TYPE_GLOBS: >-
frontend/src/generated/**
products/**/frontend/generated/**
+ frontend/src/lib/agentScopes.generated.ts
+ services/mcp/src/api/generated.ts
+ services/mcp/src/generated/**
+ services/mcp/src/tools/generated/**
+ services/mcp/schema/generated-tool-definitions.json
+ services/mcp/schema/tool-definitions-all.json
+ services/mcp/schema/exec-command-reference.md
+ # Subset of GENERATED_GLOBS regenerated from MCP YAML and Zod alone (no backend stack).
+ MCP_LOCAL_GLOBS: >-
+ services/mcp/schema/tool-inputs.json
+ services/mcp/src/resources/ui-apps.generated.ts
+ services/mcp/src/ui-apps/generated/**
+ services/mcp/src/ui-apps/apps/generated/**
jobs:
detect:
@@ -218,7 +243,7 @@ jobs:
# needs_backend = any conflict is a generated API type (build:openapi needs the stack)
# The agent (source) runs first; the deterministic regen then derives the generated
# files from the resolved source.
- run_deterministic=false; run_agent=false; needs_backend=false
+ run_deterministic=false; run_agent=false; needs_backend=false; needs_mcp_local=false
: > "$RUNNER_TEMP/conflicts_source.txt"
set -f # the *_GLOBS are case patterns; never let the shell expand them against the tree
while IFS= read -r f; do
@@ -235,13 +260,17 @@ jobs:
for glob in $API_TYPE_GLOBS; do
case "$f" in $glob) needs_backend=true; break;; esac
done
+ for glob in $MCP_LOCAL_GLOBS; do
+ case "$f" in $glob) needs_mcp_local=true; break;; esac
+ done
done < "$RUNNER_TEMP/conflicts.txt"
{
echo "run_deterministic=$run_deterministic"
echo "run_agent=$run_agent"
echo "needs_backend=$needs_backend"
+ echo "needs_mcp_local=$needs_mcp_local"
} >> "$GITHUB_OUTPUT"
- echo "deterministic=$run_deterministic agent=$run_agent backend=$needs_backend"
+ echo "deterministic=$run_deterministic agent=$run_agent backend=$needs_backend mcp_local=$needs_mcp_local"
# Heavy path only. build:openapi needs only Postgres + ClickHouse — the same trim as
# ci-backend.yml's "Validate OpenAPI types" job (no migrations; zookeeper rides along as
@@ -361,6 +390,7 @@ jobs:
if: steps.merge.outputs.skip != 'true' && steps.merge.outputs.run_deterministic == 'true' && steps.agent_outcome.outputs.abort != 'true'
env:
NEEDS_BACKEND: ${{ steps.merge.outputs.needs_backend }}
+ NEEDS_MCP_LOCAL: ${{ steps.merge.outputs.needs_mcp_local }}
run: |
set -euo pipefail
# Lockfiles + migration numbering: cheap, no services.
@@ -369,6 +399,13 @@ jobs:
if [ "$NEEDS_BACKEND" = "true" ]; then
bin/hogli build:openapi
fi
+ # MCP files that come from YAML and Zod only. They run after build:openapi so they
+ # read the regenerated tool files.
+ if [ "$NEEDS_MCP_LOCAL" = "true" ]; then
+ # Same commands hogli build:schema-mcp runs, called directly: this path has no Python.
+ (cd services/mcp && npx tsx scripts/generate-tool-schema.ts && pnpm exec oxfmt schema/tool-inputs.json)
+ pnpm --filter=@posthog/mcp run generate:ui-apps
+ fi
# --- Final status: agent abort, else leftover markers in any conflicted file ---
- name: Determine result
diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjs
index 22b05e9f429b..0ad96a535788 100644
--- a/frontend/bin/ci-report/update-ci-report.mjs
+++ b/frontend/bin/ci-report/update-ci-report.mjs
@@ -25,6 +25,7 @@ export const SECTIONS = [
{ id: 'toolbar-size', title: 'Toolbar bundle' },
{ id: 'dist-size', title: 'Dist folder size' },
{ id: 'mcp-ui-apps', title: 'MCP UI apps size' },
+ { id: 'mcp-agent-api', title: 'MCP agent API' },
{ id: 'playwright', title: 'Playwright' },
{ id: 'storybook-snapshots', title: 'Storybook snapshots' },
{ id: 'playwright-snapshots', title: 'Playwright snapshots' },
diff --git a/posthog/test/repo_invariants/test_signals_scout_tool_citations.py b/posthog/test/repo_invariants/test_signals_scout_tool_citations.py
index 226d54953902..9d2926b037b8 100644
--- a/posthog/test/repo_invariants/test_signals_scout_tool_citations.py
+++ b/posthog/test/repo_invariants/test_signals_scout_tool_citations.py
@@ -29,14 +29,14 @@ Regenerate the baseline (after confirming a rename, or when a body cites a new t
"""
import re
-import json
from pathlib import Path
import pytest
+from posthog.mcp_tool_definitions import get_mcp_tool_definitions
+
REPO_ROOT = Path(__file__).parents[3]
BASELINE_PATH = Path(__file__).parent / "signals_scout_tool_citations_baseline.txt"
-CATALOG_PATH = REPO_ROOT / "services" / "mcp" / "schema" / "tool-definitions-all.json"
TOOL_NAME_VERBS = frozenset(
{
@@ -70,7 +70,7 @@ def has_tool_shape(name: str) -> bool:
def catalog_names() -> set[str]:
- return set(json.loads(CATALOG_PATH.read_text(encoding="utf-8")))
+ return set(get_mcp_tool_definitions())
def _canonical_sources() -> list[tuple[str, str]]:
@@ -135,7 +135,7 @@ def test_invocation_pattern_reads_a_tool_named_on_its_own_line(text: str, expect
def test_tool_shaped_citations_resolve_against_the_catalog() -> None:
catalog = catalog_names()
- assert catalog, f"empty MCP tool catalog at {CATALOG_PATH}"
+ assert catalog, "empty MCP tool catalog"
backticked, invoked = cited_names()
unresolvable: dict[str, set[str]] = {
name: sources for name, sources in backticked.items() if has_tool_shape(name) and name not in catalog
diff --git a/products/tasks/backend/logic/services/test_space_setup.py b/products/tasks/backend/logic/services/test_space_setup.py
index 0bd5ae9f4afc..f0bf5687d2ce 100644
--- a/products/tasks/backend/logic/services/test_space_setup.py
+++ b/products/tasks/backend/logic/services/test_space_setup.py
@@ -1,12 +1,12 @@
import re
import json
from datetime import date
-from pathlib import Path
from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.mcp_tool_definitions import get_mcp_tool_definitions
from posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPE, INTERNAL_SCOPES
from products.tasks.backend.facade.contracts import (
@@ -145,9 +145,7 @@ class TestChannelSetupWriteSerializer(SimpleTestCase):
class TestSpaceSetupScopes(SimpleTestCase):
def test_every_tool_the_setup_steps_name_is_callable_with_the_setup_scopes(self):
- definitions = json.loads(
- (Path(__file__).parents[5] / "services" / "mcp" / "schema" / "tool-definitions-all.json").read_text()
- )
+ definitions = get_mcp_tool_definitions()
prompt = build_space_setup_prompt(
team_id=1,
channel_id=CHANNEL_ID,
@@ -162,9 +160,7 @@ class TestSpaceSetupScopes(SimpleTestCase):
granted = {*SPACE_SETUP_SCOPES, *INTERNAL_SCOPES, CONTEXT_LAYER_INTERNAL_SCOPE}
missing = {
- name: sorted(
- scope for scope in definitions[name].get("required_scopes", []) if not _granted(granted, scope)
- )
+ name: sorted(scope for scope in definitions[name].required_scopes if not _granted(granted, scope))
for name in sorted(named_tools)
}
assert {name: scopes for name, scopes in missing.items() if scopes} == {}
diff --git a/services/mcp/scripts/agent-api-diff.ts b/services/mcp/scripts/agent-api-diff.ts
new file mode 100644
index 000000000000..e7f9de6294a6
--- /dev/null
+++ b/services/mcp/scripts/agent-api-diff.ts
@@ -0,0 +1,69 @@
+#!/usr/bin/env tsx
+/**
+ * Summarizes what a PR changes for agents: tools added or removed, top-level params,
+ * scopes, annotations and input schema size. Reads the tool schema snapshots and the
+ * tool definitions JSON from two checkouts.
+ *
+ * The base side comes from `git archive <base-ref>`, so no second checkout or build runs.
+ * Prints markdown to stdout, and nothing when a comparison ran and found no change.
+ * Exit codes: 0 = compared (stdout may be empty), 3 = comparison unavailable (a side lacks
+ * the snapshots, or reading failed; reason on stderr, stdout empty), anything else = crash.
+ * Callers must not read empty output as "no change" unless the exit code is 0.
+ *
+ * Usage:
+ * pnpm --filter=@posthog/mcp exec tsx scripts/agent-api-diff.ts [--base-ref HEAD^1] [--base-dir <dir>]
+ */
+import { spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+import { parseArgs } from 'node:util'
+
+import { diffToolSurfaces, loadToolSurface, renderAgentApiDiff } from './lib/agent-api-diff'
+
+const REPO_ROOT = path.resolve(__dirname, '../../..')
+const TRACKED_PATHS = ['services/mcp/schema', 'services/mcp/tests/unit/__snapshots__/tool-schemas']
+
+const EXIT_UNAVAILABLE = 3
+
+function extractBaseRef(baseRef: string, target: string): string | null {
+ const archive = spawnSync('git', ['archive', baseRef, '--', ...TRACKED_PATHS], {
+ cwd: REPO_ROOT,
+ maxBuffer: 256 * 1024 * 1024,
+ })
+ if (archive.status !== 0) {
+ console.warn(`Could not read ${baseRef}: ${archive.stderr?.toString().trim()}`)
+ return null
+ }
+ const untar = spawnSync('tar', ['-x', '-C', target], { input: archive.stdout })
+ if (untar.status !== 0) {
+ console.warn(`Could not unpack ${baseRef}: ${untar.stderr?.toString().trim()}`)
+ return null
+ }
+ return target
+}
+
+function main(): void {
+ const { values } = parseArgs({
+ options: { 'base-ref': { type: 'string', default: 'HEAD^1' }, 'base-dir': { type: 'string' } },
+ })
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-api-base-'))
+ try {
+ const baseDir = values['base-dir'] ?? extractBaseRef(values['base-ref'] as string, scratch)
+ const base = baseDir ? loadToolSurface(baseDir) : null
+ const head = loadToolSurface(REPO_ROOT)
+ if (!base || !head) {
+ console.warn('Tool schema snapshots or definitions are missing on one side, so there is no agent API diff.')
+ process.exitCode = EXIT_UNAVAILABLE
+ return
+ }
+ process.stdout.write(renderAgentApiDiff(diffToolSurfaces(base, head)))
+ } catch (error) {
+ console.warn(`Could not compare tool surfaces: ${error}`)
+ process.exitCode = EXIT_UNAVAILABLE
+ } finally {
+ fs.rmSync(scratch, { recursive: true, force: true })
+ }
+}
+
+main()
diff --git a/services/mcp/scripts/lib/agent-api-diff.ts b/services/mcp/scripts/lib/agent-api-diff.ts
new file mode 100644
index 000000000000..54f3a0b0c581
--- /dev/null
+++ b/services/mcp/scripts/lib/agent-api-diff.ts
@@ -0,0 +1,292 @@
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+// Claude's tool registry rejects a tool whose input schema is larger than this. Same literal as
+// the exec tool check in tests/unit/instructions-formatter-snapshot.test.ts.
+export const INPUT_SCHEMA_CHAR_LIMIT = 16_384
+
+const MAX_NAMES_LISTED = 60
+const MAX_ROWS = 40
+const MAX_CELL_ITEMS = 8
+// Well under GitHub's 65,536 char comment limit, which the shared CI report also uses.
+const MAX_MARKDOWN_CHARS = 15_000
+
+const DEFINITION_FILES = ['tool-definitions.json', 'generated-tool-definitions.json']
+const SCHEMA_SNAPSHOT_DIR = 'services/mcp/tests/unit/__snapshots__/tool-schemas'
+const SCHEMA_DIR = 'services/mcp/schema'
+
+export interface ToolDefinition {
+ title?: string
+ category?: string
+ description?: string
+ required_scopes?: string[]
+ annotations?: Record<string, unknown>
+}
+
+export interface ToolSurface {
+ definitions: Record<string, ToolDefinition>
+ // Input JSON schema per tool, as written by the tool-schema snapshot test.
+ schemas: Record<string, { properties?: Record<string, unknown> }>
+}
+
+export interface ToolChange {
+ name: string
+ paramsAdded: string[]
+ paramsRemoved: string[]
+ scopesAdded: string[]
+ scopesRemoved: string[]
+ annotationChanges: string[]
+ titleChanged: boolean
+ descriptionChanged: boolean
+ categoryChanged: boolean
+ // The schema differs although no listed field above shows it, for example a property type.
+ schemaChanged: boolean
+ sizeBefore: number | null
+ sizeAfter: number | null
+}
+
+export interface AgentApiDiff {
+ added: { name: string; size: number | null }[]
+ removed: string[]
+ changed: ToolChange[]
+ overLimit: { name: string; size: number; wasSize: number | null }[]
+}
+
+function readJson(file: string): unknown {
+ return JSON.parse(fs.readFileSync(file, 'utf-8'))
+}
+
+/**
+ * Read the tool surface under a repo root. Returns null when either source is missing, so a
+ * checkout that predates the snapshots degrades to "no diff" instead of failing the run.
+ */
+export function loadToolSurface(root: string): ToolSurface | null {
+ const schemaDir = path.join(root, SCHEMA_SNAPSHOT_DIR)
+ const definitionPaths = DEFINITION_FILES.map((file) => path.join(root, SCHEMA_DIR, file))
+ if (!fs.existsSync(schemaDir) || !definitionPaths.every((file) => fs.existsSync(file))) {
+ return null
+ }
+
+ // Generated definitions win over hand-written ones, the same precedence the server uses.
+ const definitions: Record<string, ToolDefinition> = {}
+ for (const file of definitionPaths) {
+ Object.assign(definitions, readJson(file))
+ }
+
+ const schemas: ToolSurface['schemas'] = {}
+ for (const entry of fs.readdirSync(schemaDir, { withFileTypes: true })) {
+ if (entry.isFile() && entry.name.endsWith('.json')) {
+ schemas[entry.name.replace(/\.json$/, '')] = readJson(
+ path.join(schemaDir, entry.name)
+ ) as ToolSurface['schemas'][string]
+ }
+ }
+ return { definitions, schemas }
+}
+
+// Names, params and scopes come from PR-controlled YAML and go into a shared bot comment, so
+// anything that could close a code span or forge a report marker is replaced.
+function safe(value: string): string {
+ return value.replace(/[^A-Za-z0-9_:.\-/ ]/g, '?')
+}
+
+function sorted(values: Iterable<string>): string[] {
+ return [...values].sort()
+}
+
+function subtract(from: Iterable<string>, remove: Set<string>): string[] {
+ return sorted([...from].filter((value) => !remove.has(value)))
+}
+
+function paramNames(surface: ToolSurface, name: string): Set<string> {
+ return new Set(Object.keys(surface.schemas[name]?.properties ?? {}))
+}
+
+// The server drops these root keys before advertising a schema (see toMcpInputSchema), so the
+// size counts without them to stay close to what Claude's registry measures.
+function advertisedSchema(surface: ToolSurface, name: string): object | null {
+ const schema = surface.schemas[name]
+ if (!schema) {
+ return null
+ }
+ const { $schema: _schema, additionalProperties: _additional, ...rest } = schema as Record<string, unknown>
+ return rest
+}
+
+function schemaSize(surface: ToolSurface, name: string): number | null {
+ const schema = advertisedSchema(surface, name)
+ return schema ? JSON.stringify(schema).length : null
+}
+
+function schemaText(surface: ToolSurface, name: string): string | null {
+ const schema = advertisedSchema(surface, name)
+ return schema ? JSON.stringify(schema) : null
+}
+
+function diffAnnotations(before: Record<string, unknown> = {}, after: Record<string, unknown> = {}): string[] {
+ return sorted(new Set([...Object.keys(before), ...Object.keys(after)]))
+ .filter((key) => before[key] !== after[key])
+ .map((key) => `${safe(key)}: ${safe(String(before[key] ?? 'unset'))} -> ${safe(String(after[key] ?? 'unset'))}`)
+}
+
+function toolNames(surface: ToolSurface): Set<string> {
+ return new Set([...Object.keys(surface.definitions), ...Object.keys(surface.schemas)])
+}
+
+export function diffToolSurfaces(base: ToolSurface, head: ToolSurface): AgentApiDiff {
+ const baseNames = toolNames(base)
+ const headNames = toolNames(head)
+
+ const diff: AgentApiDiff = {
+ added: subtract(headNames, baseNames).map((name) => ({ name, size: schemaSize(head, name) })),
+ removed: subtract(baseNames, headNames),
+ changed: [],
+ overLimit: [],
+ }
+
+ for (const name of sorted(headNames)) {
+ const sizeAfter = schemaSize(head, name)
+ const sizeBefore = baseNames.has(name) ? schemaSize(base, name) : null
+ const wasOverLimit = sizeBefore !== null && sizeBefore >= INPUT_SCHEMA_CHAR_LIMIT
+ if (sizeAfter !== null && sizeAfter >= INPUT_SCHEMA_CHAR_LIMIT && !wasOverLimit) {
+ diff.overLimit.push({ name, size: sizeAfter, wasSize: sizeBefore })
+ }
+ if (!baseNames.has(name)) {
+ continue
+ }
+
+ const baseParams = paramNames(base, name)
+ const headParams = paramNames(head, name)
+ const baseScopes = new Set(base.definitions[name]?.required_scopes ?? [])
+ const headScopes = new Set(head.definitions[name]?.required_scopes ?? [])
+ const change: ToolChange = {
+ name,
+ paramsAdded: subtract(headParams, baseParams),
+ paramsRemoved: subtract(baseParams, headParams),
+ scopesAdded: subtract(headScopes, baseScopes),
+ scopesRemoved: subtract(baseScopes, headScopes),
+ annotationChanges: diffAnnotations(
+ base.definitions[name]?.annotations,
+ head.definitions[name]?.annotations
+ ),
+ titleChanged: base.definitions[name]?.title !== head.definitions[name]?.title,
+ categoryChanged: base.definitions[name]?.category !== head.definitions[name]?.category,
+ descriptionChanged: base.definitions[name]?.description !== head.definitions[name]?.description,
+ // Snapshot files are key-sorted, so equal schemas serialize to equal text.
+ schemaChanged: schemaText(base, name) !== schemaText(head, name),
+ sizeBefore,
+ sizeAfter,
+ }
+ const hasChange =
+ change.paramsAdded.length > 0 ||
+ change.paramsRemoved.length > 0 ||
+ change.scopesAdded.length > 0 ||
+ change.scopesRemoved.length > 0 ||
+ change.annotationChanges.length > 0 ||
+ change.titleChanged ||
+ change.descriptionChanged ||
+ change.categoryChanged ||
+ change.schemaChanged
+ if (hasChange) {
+ diff.changed.push(change)
+ }
+ }
+ return diff
+}
+
+function chars(size: number | null): string {
+ return size === null ? 'n/a' : size.toLocaleString('en-US')
+}
+
+function listNames(items: { name: string; note?: string }[]): string {
+ const shown = items.slice(0, MAX_NAMES_LISTED)
+ const more = items.length > shown.length ? `, and ${items.length - shown.length} more` : ''
+ return shown.map(({ name, note }) => `\`${safe(name)}\`${note ? ` (${note})` : ''}`).join(', ') + more
+}
+
+function capItems(items: string[]): string {
+ const shown = items.slice(0, MAX_CELL_ITEMS)
+ return items.length > shown.length ? `${shown.join(' ')} ... ${items.length - shown.length} more` : shown.join(' ')
+}
+
+function paramsCell(change: ToolChange): string {
+ const parts = [
+ ...change.paramsAdded.map((param) => `+\`${safe(param)}\``),
+ ...change.paramsRemoved.map((param) => `-\`${safe(param)}\``),
+ ]
+ const looksRenamed = change.paramsAdded.length > 0 && change.paramsRemoved.length > 0
+ return capItems(parts) + (looksRenamed ? ' (rename?)' : '')
+}
+
+function scopesCell(change: ToolChange): string {
+ return capItems([
+ ...change.scopesAdded.map((scope) => `+\`${safe(scope)}\``),
+ ...change.scopesRemoved.map((scope) => `-\`${safe(scope)}\``),
+ ])
+}
+
+function sizeCell(change: ToolChange): string {
+ if (change.sizeBefore !== change.sizeAfter) {
+ return `${chars(change.sizeBefore)} -> ${chars(change.sizeAfter)}`
+ }
+ return change.schemaChanged ? 'schema changed' : ''
+}
+
+/** Compact markdown for a PR comment. Empty string when nothing changed for agents. */
+export function renderAgentApiDiff(diff: AgentApiDiff): string {
+ if (diff.added.length + diff.removed.length + diff.changed.length === 0) {
+ return ''
+ }
+
+ const lines: string[] = []
+ if (diff.added.length > 0) {
+ const items = diff.added.map(({ name, size }) => ({
+ name,
+ note: size === null ? undefined : `${chars(size)} chars`,
+ }))
+ lines.push(`**Tools added (${diff.added.length}):** ${listNames(items)}`)
+ }
+ if (diff.removed.length > 0) {
+ lines.push(`**Tools removed (${diff.removed.length}):** ${listNames(diff.removed.map((name) => ({ name })))}`)
+ }
+ if (diff.overLimit.length > 0) {
+ const items = diff.overLimit.map(({ name, size, wasSize }) => ({
+ name,
+ note: `${chars(size)}, was ${chars(wasSize)}`,
+ }))
+ lines.push(
+ `**Input schema now at or over ${INPUT_SCHEMA_CHAR_LIMIT.toLocaleString('en-US')} chars (${diff.overLimit.length}):** ${listNames(items)}`
+ )
+ }
+
+ if (diff.changed.length > 0) {
+ const rows = diff.changed.slice(0, MAX_ROWS).map((change) => {
+ const annotations = change.annotationChanges.join('; ')
+ const title = [
+ change.titleChanged ? 'title changed' : '',
+ change.descriptionChanged ? 'description changed' : '',
+ change.categoryChanged ? 'category changed' : '',
+ ]
+ .filter(Boolean)
+ .join('; ')
+ return `| \`${safe(change.name)}\` | ${paramsCell(change)} | ${scopesCell(change)} | ${[annotations, title].filter(Boolean).join('; ')} | ${sizeCell(change)} |`
+ })
+ lines.push(
+ '',
+ `**Tools changed (${diff.changed.length}):**`,
+ '',
+ '| Tool | Params | Scopes | Annotations | Schema chars |',
+ '| --- | --- | --- | --- | --- |',
+ ...rows
+ )
+ if (diff.changed.length > rows.length) {
+ lines.push('', `...and ${diff.changed.length - rows.length} more changed tools.`)
+ }
+ }
+ const markdown = lines.join('\n') + '\n'
+ if (markdown.length <= MAX_MARKDOWN_CHARS) {
+ return markdown
+ }
+ const cut = markdown.slice(0, markdown.lastIndexOf('\n', MAX_MARKDOWN_CHARS))
+ return `${cut}\n\n...truncated, ${diff.changed.length} changed tools in total.\n`
+}
diff --git a/services/mcp/scripts/post-agent-api-diff-section.mjs b/services/mcp/scripts/post-agent-api-diff-section.mjs
new file mode 100644
index 000000000000..d81f815f87a6
--- /dev/null
+++ b/services/mcp/scripts/post-agent-api-diff-section.mjs
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+import fs from 'node:fs'
+
+import { clearSectionIfPresent, postSection } from '../../../frontend/bin/ci-report/update-ci-report.mjs'
+
+const SECTION_ID = 'mcp-agent-api'
+const [markdownPath] = process.argv.slice(2)
+
+// No output file means the comparison never ran. Leave the report alone.
+if (!markdownPath || !fs.existsSync(markdownPath)) {
+ console.info('No agent API diff output - leaving the report unchanged.')
+ process.exit(0)
+}
+
+// The file comes from a job that ran PR code, so it is data: drop HTML comment markers (the
+// shared report parser reads them as section boundaries) and cap the size.
+const MAX_CHARS = 20_000
+const markdown = fs
+ .readFileSync(markdownPath, 'utf-8')
+ .replaceAll(/<!--|-->/g, '')
+ .trim()
+ .slice(0, MAX_CHARS)
+
+if (!markdown) {
+ // A change that a later push reverted must not leave a stale table behind.
+ await clearSectionIfPresent({
+ id: SECTION_ID,
+ summary: 'no agent API changes',
+ body: 'This PR no longer changes the tools, params, scopes or annotations agents see.',
+ })
+ process.exit(0)
+}
+
+const overLimit = markdown.includes('**Input schema now at or over')
+await postSection({
+ id: SECTION_ID,
+ status: overLimit ? 'warn' : 'info',
+ summary: overLimit ? 'tool input schema over the Claude limit' : 'agent-facing tool changes',
+ body: `What this PR changes for agents, from the tool schema snapshots and tool definitions.\n\n${markdown}`,
+})
diff --git a/services/mcp/tests/unit/agent-api-diff.test.ts b/services/mcp/tests/unit/agent-api-diff.test.ts
new file mode 100644
index 000000000000..0672857ca7f1
--- /dev/null
+++ b/services/mcp/tests/unit/agent-api-diff.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ INPUT_SCHEMA_CHAR_LIMIT,
+ diffToolSurfaces,
+ renderAgentApiDiff,
+ type ToolSurface,
+} from '../../scripts/lib/agent-api-diff'
+
+function surface(
+ tools: Record<string, { params?: string[]; scopes?: string[]; readOnly?: boolean; pad?: number }>
+): ToolSurface {
+ const result: ToolSurface = { definitions: {}, schemas: {} }
+ for (const [name, { params = [], scopes = [], readOnly = true, pad = 0 }] of Object.entries(tools)) {
+ result.definitions[name] = { title: name, required_scopes: scopes, annotations: { readOnlyHint: readOnly } }
+ result.schemas[name] = {
+ properties: Object.fromEntries(params.map((param) => [param, { type: 'string' }])),
+ ...(pad ? { description: 'x'.repeat(pad) } : {}),
+ } as ToolSurface['schemas'][string]
+ }
+ return result
+}
+
+describe('agent API diff', () => {
+ it('renders nothing when the tool surface is unchanged', () => {
+ const same = surface({ 'a-list': { params: ['limit'] } })
+ expect(renderAgentApiDiff(diffToolSurfaces(same, surface({ 'a-list': { params: ['limit'] } })))).toBe('')
+ })
+
+ it('reports added and removed tools, param changes, scopes and annotations', () => {
+ const base = surface({
+ 'old-tool': {},
+ 'flag-get': { params: ['id', 'name'], scopes: ['flag:read'] },
+ })
+ const head = surface({
+ 'new-tool': {},
+ 'flag-get': { params: ['id', 'key'], scopes: ['flag:read', 'user:read'], readOnly: false },
+ })
+
+ const markdown = renderAgentApiDiff(diffToolSurfaces(base, head))
+
+ expect(markdown).toContain('**Tools added (1):** `new-tool`')
+ expect(markdown).toContain('**Tools removed (1):** `old-tool`')
+ expect(markdown).toContain(
+ '| `flag-get` | +`key` -`name` (rename?) | +`user:read` | readOnlyHint: true -> false |'
+ )
+ })
+
+ it('flags a schema only when it crosses the registry limit', () => {
+ const under = INPUT_SCHEMA_CHAR_LIMIT - 1000
+ const over = INPUT_SCHEMA_CHAR_LIMIT + 1000
+ const base = surface({ 'crossing-tool': { pad: under }, 'already-big': { pad: over } })
+ const head = surface({ 'crossing-tool': { pad: over }, 'already-big': { pad: over + 50 } })
+
+ const { overLimit } = diffToolSurfaces(base, head)
+
+ expect(overLimit.map(({ name }) => name)).toEqual(['crossing-tool'])
+ })
+
+ it('caps list cells and total size so the comment stays under the GitHub limit', () => {
+ const tools = Object.fromEntries(
+ Array.from({ length: 200 }, (_, i) => [
+ `tool-${i}`,
+ { params: Array.from({ length: 30 }, (_, j) => `p${j}`) },
+ ])
+ )
+ const markdown = renderAgentApiDiff(diffToolSurfaces(surface({}), surface(tools)))
+ const changed = renderAgentApiDiff(
+ diffToolSurfaces(
+ surface(tools),
+ surface(Object.fromEntries(Object.keys(tools).map((name) => [name, { params: ['q'] }])))
+ )
+ )
+
+ expect(markdown.length).toBeLessThan(16_000)
+ expect(changed.length).toBeLessThan(16_000)
+ expect(changed).toContain('more')
+ })
+
+ it('reports description and category changes', () => {
+ const base = surface({ 'a-tool': {} })
+ const head = surface({ 'a-tool': {} })
+ base.definitions['a-tool']!.description = 'Old text'
+ head.definitions['a-tool']!.description = 'New text'
+
+ base.definitions['a-tool']!.category = 'Old'
+ head.definitions['a-tool']!.category = 'New'
+
+ const markdown = renderAgentApiDiff(diffToolSurfaces(base, head))
+
+ expect(markdown).toContain('description changed')
+ expect(markdown).toContain('category changed')
+ })
+
+ it('reports a same-length schema change and neutralizes markup from PR-controlled names', () => {
+ const base = surface({ 'a-tool': { params: ['mode'] } })
+ const head = surface({ 'a-tool': { params: ['mode'], scopes: ['x`\n<!-- ci-report:section:bundle-size -->'] } })
+ head.schemas['a-tool'] = { properties: { mode: { type: 'number' } } }
+ base.schemas['a-tool'] = { properties: { mode: { type: 'string' } } }
+
+ const markdown = renderAgentApiDiff(diffToolSurfaces(base, head))
+
+ expect(markdown).toContain('schema changed')
+ expect(markdown).not.toContain('<!--')
+ expect(markdown).not.toContain('\n<')
+ })
+})