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.

fix(mcp): add generate-app-url tool so links aren't hand-built (#61814)

Georgiy Tarasov3376c6740101
diff --git a/ee/hogai/eval/sandboxed/ci/eval_basic.py b/ee/hogai/eval/sandboxed/ci/eval_basic.py
index be6aede7c2e2..ce9a58efc968 100644
--- a/ee/hogai/eval/sandboxed/ci/eval_basic.py
+++ b/ee/hogai/eval/sandboxed/ci/eval_basic.py
@@ -12,6 +12,7 @@ Example eval case pattern:
from __future__ import annotations
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
+from ee.hogai.eval.sandboxed.cli_mcp.scorers import CalledTargetTool, SurfacedGeneratedAppUrl
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
from ee.hogai.eval.sandboxed.scorers import ExitCodeZero
@@ -44,3 +45,54 @@ async def eval_bugfix(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mod
sandboxed_demo_data=sandboxed_demo_data,
posthog_client=posthog_client,
)
+
+
+async def eval_app_link_generation(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):
+ """Entity links must be resolved via ``generate-app-url``, not hand-built.
+
+ Reproduces the reported failure where the MCP confidently returned 404 links — a person
+ UUID under the singular ``/person/`` slug instead of ``/persons/``, and session ids mistyped
+ into ``/replay/`` paths. The trigger is an entity discovered via ``execute-sql``: there is no
+ tool-attached ``_posthogUrl`` on a raw query result, so the agent must call ``generate-app-url``
+ and surface the url it returns verbatim rather than guessing the slug or retyping the id.
+
+ Runs in both mcp modes — ``generate-app-url`` is registered in each.
+ """
+ cases: list[SandboxedEvalCase] = [
+ # Person by UUID: the exact reported slug bug (`/persons/<uuid>`, not `/person/<uuid>`).
+ # Forcing the UUID via SQL keeps the agent off persons-retrieve's `_posthogUrl` shortcut,
+ # so `generate-app-url` is the only correct path.
+ SandboxedEvalCase(
+ name="person_profile_link",
+ prompt=(
+ "Using SQL, find one person in this project and read their UUID. Then give me a "
+ "clickable link to open that person's profile page in PostHog."
+ ),
+ expected={
+ "called_target_tool": {"tool": "generate-app-url"},
+ "surfaced_generated_app_url": {},
+ },
+ ),
+ # Event link: another raw-SQL entity with no `_posthogUrl` tool, where ids must be passed
+ # as params rather than transcribed into the path.
+ SandboxedEvalCase(
+ name="event_link",
+ prompt=(
+ "Using SQL, find one recent `$pageview` event and read its uuid and timestamp. "
+ "Then give me a clickable link to view that specific event in PostHog."
+ ),
+ expected={
+ "called_target_tool": {"tool": "generate-app-url"},
+ "surfaced_generated_app_url": {},
+ },
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name=f"sandboxed-app-link-generation-{mcp_mode}",
+ cases=cases,
+ scorers=[ExitCodeZero(), CalledTargetTool(), SurfacedGeneratedAppUrl()],
+ pytestconfig=pytestconfig,
+ sandboxed_demo_data=sandboxed_demo_data,
+ posthog_client=posthog_client,
+ )
diff --git a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py b/ee/hogai/eval/sandboxed/cli_mcp/scorers.py
index 7f7699b6c24d..f04257488c4c 100644
--- a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py
+++ b/ee/hogai/eval/sandboxed/cli_mcp/scorers.py
@@ -30,6 +30,8 @@ unrelated cases don't drag the rollup down.
from __future__ import annotations
+import re
+
from braintrust import Score
from braintrust_core.score import Scorer
@@ -43,10 +45,17 @@ __all__ = [
"RanPythonPostProcessing",
"RecoveredToCorrectTool",
"RetrievedSchemaPath",
+ "SurfacedGeneratedAppUrl",
"UsedJsonOutputFormat",
"VerifiedEventBeforeQuery",
]
+# URLs stop at whitespace and the delimiters that wrap them in Markdown/JSON/TOON, so the captured
+# string is the bare link — robust to `[text](url)`, `"url"`, JSON-escaped `\"url\"`, trailing
+# punctuation, etc. The backslash exclusion matters: tool results arrive JSON-escaped, so without it
+# the capture keeps a trailing `\` and never substring-matches the (unescaped) final message.
+_URL_RE = re.compile(r"https?://[^\s\"'`)\]<>\\]+")
+
def _read_tool(expected: dict | None, scorer_name: str) -> str | None:
"""Look up ``expected[scorer_name]["tool"]`` with permissive validation."""
@@ -641,6 +650,71 @@ class UsedJsonOutputFormat(Scorer):
)
+class SurfacedGeneratedAppUrl(Scorer):
+ """Binary: did the agent surface a url returned by ``generate-app-url`` verbatim?
+
+ Opt-in via presence of ``expected = {"surfaced_generated_app_url": {}}``.
+
+ The fix for hand-built 404 links is to resolve entity links through the
+ ``generate-app-url`` tool and surface the ``url`` it returns verbatim,
+ rather than guessing slugs (a person UUID lives at ``/persons/<uuid>``,
+ not ``/person/...``) or retyping ids. This scorer finds every successful
+ ``generate-app-url`` call, pulls the url out of its result, and checks the
+ final assistant message contains at least one of them.
+
+ Score 1.0 if a generated url was surfaced, 0.0 if the tool ran but its url
+ was dropped or rewritten, ``None`` if the tool was never called (that gap
+ is caught by ``CalledTargetTool``).
+ """
+
+ TOOL = "generate-app-url"
+
+ def _name(self) -> str:
+ return "surfaced_generated_app_url"
+
+ async def _run_eval_async(self, output, expected=None, **kwargs):
+ return self._evaluate(output, expected)
+
+ def _run_eval_sync(self, output, expected=None, **kwargs):
+ return self._evaluate(output, expected)
+
+ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:
+ if _read_spec(expected, self._name()) is None:
+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})
+
+ parser = _build_parser(output)
+ if parser is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ urls: set[str] = set()
+ for call in parser.get_tool_calls(self.TOOL):
+ if call.is_error:
+ continue
+ urls.update(_URL_RE.findall(call.output or ""))
+ if not urls:
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"'{self.TOOL}' was never called successfully or returned no url"},
+ )
+
+ last_message = (output or {}).get("last_message") or ""
+ if not isinstance(last_message, str):
+ last_message = str(last_message)
+
+ surfaced = sorted(url for url in urls if url in last_message)
+ if surfaced:
+ return Score(name=self._name(), score=1.0, metadata={"surfaced": surfaced})
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": "generate-app-url returned a url but it was not surfaced verbatim in the answer",
+ "tool_urls": sorted(urls),
+ },
+ )
+
+
class RanPythonPostProcessing(Scorer):
"""Binary: did the agent actually run Python to post-process tool results?
diff --git a/frontend/bin/build-app-url-manifest.mjs b/frontend/bin/build-app-url-manifest.mjs
new file mode 100644
index 000000000000..c3bc00dbf1ff
--- /dev/null
+++ b/frontend/bin/build-app-url-manifest.mjs
@@ -0,0 +1,342 @@
+// Generate services/mcp/.../app-url-manifest.json — the canonical route table the MCP `generate-app-url`
+// tool resolves entity links from, so agents never hand-build (and mis-slug) PostHog URLs.
+//
+// The complete source of truth is the merged `urls` object the frontend ships:
+// `{ ...productUrls, <~80 builders defined directly in scenes/urls.ts> }`. We can't import it in a
+// plain Node script — its transitive graph pulls monaco, `?raw` assets, scss, dayjs, etc., which only
+// the full frontend build (or jest's moduleNameMapper) resolves. So instead we extract each builder's
+// *source* via the TypeScript compiler (no app import), strip types, and reconstruct it in a tiny
+// sandbox that provides the few things builders touch (`combineUrl`, `encodeURIComponent`, ...). Then we
+// recover each route template by invoking the real builder with `:name` sentinels — the same trick
+// urls.ts itself uses (`href(':id')`) — so combineUrl/ternaries/encoding are handled by the shipped code.
+//
+// Usage:
+// node bin/build-app-url-manifest.mjs # write the manifest
+// node bin/build-app-url-manifest.mjs --check # exit 1 if the committed manifest is stale
+
+import * as ps from 'child_process'
+import fs from 'fs'
+import { combineUrl } from 'kea-router'
+import path from 'path'
+import ts from 'typescript'
+import { fileURLToPath } from 'url'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const FRONTEND = path.resolve(__dirname, '..')
+const REPO = path.resolve(FRONTEND, '..')
+const URLS_FILE = path.join(FRONTEND, 'src/scenes/urls.ts')
+const PRODUCTS_DIR = path.join(REPO, 'products')
+const OUT_FILE = path.join(REPO, 'services/mcp/src/tools/links/app-url-manifest.json')
+
+// First path segments that never get a `/project/:id` prefix. Mirrors `pathsWithoutProjectId` in
+// frontend/src/lib/utils/router-utils.ts — keep in sync there.
+const PATHS_WITHOUT_PROJECT_ID = new Set([
+ 'api',
+ 'me',
+ 'instance',
+ 'organization',
+ 'preflight',
+ 'login',
+ 'signup',
+ 'create-organization',
+ 'account',
+ 'oauth',
+ 'shared',
+ 'embedded',
+ 'interview',
+ 'cli',
+ 'render_query',
+])
+const isProjectScoped = (template) => !PATHS_WITHOUT_PROJECT_ID.has(template.split('/')[1] ?? '')
+
+// `urls` helpers that build prefixes/origins rather than linkable destinations.
+const EXCLUDED_HELPERS = new Set(['absolute', 'default', 'project', 'currentProject', 'newTab'])
+
+const sentinel = (name) => `:${name}`
+
+// ---- sandbox: turn extracted builder source into callable functions without importing the app ----
+
+function buildSandboxScope() {
+ // App-specific bindings builders reference; everything else (Boolean, Math, JSON, …) comes from
+ // the real Node globals via the get trap below.
+ const real = {
+ combineUrl,
+ // Only one builder uses toParams (experiments); a faithful-enough query serializer.
+ toParams: (obj = {}) =>
+ Object.entries(obj)
+ .filter(([, v]) => v !== undefined && v !== null)
+ .map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`)
+ .join('&'),
+ getCurrentTeamId: () => {
+ throw new Error('no team in codegen')
+ },
+ urls: {},
+ }
+ // Stand-in for unknown app identifiers — enums (`ActivityTab.ExploreEvents`) and imported type
+ // guards (`isHogQLQuery(query)`). Callable and indexable, always returning undefined, so an
+ // enum-defaulted param renders as `undefined` (the probe then supplies a sentinel, e.g.
+ // `activity` -> `/activity/{tab}`) and a guard call is simply falsy instead of throwing.
+ const stub = new Proxy(function () {}, { get: () => undefined, apply: () => undefined, construct: () => ({}) })
+ // `has: () => true` makes `with` route every identifier here; resolve known bindings, then real
+ // globals, then the stub.
+ return new Proxy(real, {
+ has: () => true,
+ get: (t, k) => (k in t ? t[k] : typeof k === 'string' && k in globalThis ? globalThis[k] : stub),
+ })
+}
+
+function stripTypes(objLiteralText) {
+ const out = ts.transpile(`(${objLiteralText})`, {
+ target: ts.ScriptTarget.ESNext,
+ module: ts.ModuleKind.None,
+ alwaysStrict: false,
+ removeComments: true,
+ })
+ // ts may emit a leading "use strict" directive, which both forbids `with` and would become the
+ // return value — strip it and any trailing semicolon.
+ return out.replace(/^\s*["']use strict["'];?\s*/, '').replace(/;?\s*$/, '')
+}
+
+function evalObject(objLiteralText, scope) {
+ const js = stripTypes(objLiteralText)
+ // eslint-disable-next-line no-new-func -- build-time codegen over first-party source
+ return new Function('__scope', `with (__scope) { return (${js}) }`)(scope)
+}
+
+// ---- extract the `urls: {}` object literal text from a source file ----
+
+function readUrlsObjectText(file, { fromManifest }) {
+ const src = fs.readFileSync(file, 'utf8')
+ const sf = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true)
+ let text = null
+ sf.forEachChild(function walk(node) {
+ if (text) {
+ return
+ }
+ if (
+ fromManifest &&
+ ts.isPropertyAssignment(node) &&
+ node.name.getText(sf) === 'urls' &&
+ ts.isObjectLiteralExpression(node.initializer)
+ ) {
+ text = node.initializer.getText(sf)
+ } else if (
+ !fromManifest &&
+ ts.isVariableDeclaration(node) &&
+ node.name.getText(sf) === 'urls' &&
+ node.initializer &&
+ ts.isObjectLiteralExpression(node.initializer)
+ ) {
+ // Drop the `...productUrls` spread — those builders come from the product manifests.
+ const props = node.initializer.properties.filter((p) => !ts.isSpreadAssignment(p))
+ text = `{${props.map((p) => p.getText(sf)).join(',\n')}}`
+ } else {
+ ts.forEachChild(node, walk)
+ }
+ })
+ return text
+}
+
+function collectUrls() {
+ const scope = buildSandboxScope()
+
+ const productUrls = {}
+ for (const product of fs.readdirSync(PRODUCTS_DIR).sort()) {
+ const manifest = path.join(PRODUCTS_DIR, product, 'manifest.tsx')
+ if (!fs.existsSync(manifest)) {
+ continue
+ }
+ const text = readUrlsObjectText(manifest, { fromManifest: true })
+ if (text) {
+ Object.assign(productUrls, evalObject(text, scope))
+ }
+ }
+
+ const directText = readUrlsObjectText(URLS_FILE, { fromManifest: false })
+ const direct = evalObject(directText, scope)
+
+ const merged = { ...productUrls, ...direct }
+ // Builders reference `urls.*` (e.g. `embedded` -> `urls.shared`); resolve self-refs to the merged set.
+ scope.urls = merged
+ return merged
+}
+
+// ---- probe each builder for its route template (ported from the runtime generator) ----
+
+function parenContents(src) {
+ const start = src.indexOf('(')
+ if (start === -1) {
+ return null
+ }
+ let depth = 0
+ for (let i = start; i < src.length; i++) {
+ const ch = src[i]
+ if (ch === '(') {
+ depth++
+ } else if (ch === ')') {
+ depth--
+ if (depth === 0) {
+ return src.slice(start + 1, i)
+ }
+ }
+ }
+ return null
+}
+
+function splitTopLevel(input) {
+ const parts = []
+ let depth = 0
+ let current = ''
+ for (const ch of input) {
+ if (ch === '(' || ch === '[' || ch === '{') {
+ depth++
+ } else if (ch === ')' || ch === ']' || ch === '}') {
+ depth--
+ }
+ if (ch === ',' && depth === 0) {
+ parts.push(current)
+ current = ''
+ } else {
+ current += ch
+ }
+ }
+ if (current.trim()) {
+ parts.push(current)
+ }
+ return parts
+}
+
+function readSignature(fn) {
+ const src = fn.toString().trim()
+ const single = src.match(/^(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/)
+ if (single) {
+ return { kind: 'positional', names: [single[1]] }
+ }
+ const paramStr = parenContents(src)
+ if (paramStr === null) {
+ return null
+ }
+ const trimmed = paramStr.trim()
+ if (trimmed === '') {
+ return { kind: 'positional', names: [] }
+ }
+ if (trimmed.startsWith('{')) {
+ return { kind: 'object', names: [] }
+ }
+ const names = splitTopLevel(trimmed)
+ .map((part) => part.trim().split('=')[0].trim())
+ .filter(Boolean)
+ return { kind: 'positional', names }
+}
+
+// Invoke with the fewest sentinel args that yield a clean path — drops optional trailing params and
+// hits guarded default branches (`replay()` -> `/replay/home`) instead of erroring on a sentinel.
+function probeBuilder(fn, signature) {
+ const maxArgs = signature.kind === 'object' ? 0 : signature.names.length
+ for (let count = 0; count <= maxArgs; count++) {
+ const args = signature.kind === 'object' ? [{}] : signature.names.slice(0, count).map(sentinel)
+ let raw
+ try {
+ raw = fn(...args)
+ } catch {
+ continue
+ }
+ if (typeof raw !== 'string') {
+ continue
+ }
+ const pathOnly = raw.split('?')[0].split('#')[0]
+ if (
+ !pathOnly.startsWith('/') ||
+ pathOnly === '/' ||
+ pathOnly.includes('undefined') ||
+ pathOnly.includes('null')
+ ) {
+ continue
+ }
+ return pathOnly
+ }
+ return null
+}
+
+function replaceSentinels(pathOnly, paramNames) {
+ let template = pathOnly
+ const found = new Set()
+ for (const name of [...paramNames].sort((a, b) => b.length - a.length)) {
+ const encoded = encodeURIComponent(sentinel(name))
+ const plain = sentinel(name)
+ const before = template
+ template = template.split(encoded).join(`{${name}}`).split(plain).join(`{${name}}`)
+ if (template !== before) {
+ found.add(name)
+ }
+ }
+ return { template, params: paramNames.filter((name) => found.has(name)) }
+}
+
+function buildManifest(urls) {
+ const manifest = {}
+ const excluded = []
+ const baseOnly = []
+ for (const name of Object.keys(urls).sort()) {
+ if (EXCLUDED_HELPERS.has(name)) {
+ excluded.push({ name, reason: 'structural helper' })
+ continue
+ }
+ const fn = urls[name]
+ if (typeof fn !== 'function') {
+ excluded.push({ name, reason: 'not a function' })
+ continue
+ }
+ const signature = readSignature(fn)
+ if (!signature) {
+ excluded.push({ name, reason: 'could not parse signature' })
+ continue
+ }
+ const probePath = probeBuilder(fn, signature)
+ if (!probePath) {
+ excluded.push({ name, reason: 'no clean path' })
+ continue
+ }
+ // Map against the full signature so a sentinel-valued default (`accountConnected`) still resolves.
+ const { template, params } = replaceSentinels(probePath, signature.names)
+ manifest[name] = { template, params, scope: isProjectScoped(template) ? 'project' : 'global' }
+ if ((signature.kind === 'object' || signature.names.length > 0) && params.length === 0) {
+ baseOnly.push(name)
+ }
+ }
+ return { manifest, excluded, baseOnly }
+}
+
+// Format with oxfmt (same as build-products.mjs) so the written file matches the repo's committed
+// style — so `build:products && git diff --exit-code` in CI catches drift instead of false-positiving
+// on formatting. oxfmt resolves on PATH under `pnpm` (node_modules/.bin).
+function renderFormatted(manifest) {
+ const tmp = path.join(FRONTEND, 'tmp')
+ fs.mkdirSync(tmp, { recursive: true })
+ const tmpFile = path.join(tmp, 'app-url-manifest.json')
+ fs.writeFileSync(tmpFile, JSON.stringify(manifest, null, 4) + '\n')
+ ps.execFileSync('oxfmt', [tmpFile])
+ const formatted = fs.readFileSync(tmpFile, 'utf8')
+ fs.rmSync(tmpFile, { force: true })
+ return formatted
+}
+
+// ---- main ----
+
+const { manifest, excluded, baseOnly } = buildManifest(collectUrls())
+const formatted = renderFormatted(manifest)
+
+if (process.argv.includes('--check')) {
+ const committed = fs.existsSync(OUT_FILE) ? fs.readFileSync(OUT_FILE, 'utf8') : ''
+ if (committed !== formatted) {
+ process.stderr.write('app-url-manifest.json is stale. Run `pnpm --filter=@posthog/frontend build:app-urls`.\n')
+ process.exit(1)
+ }
+ process.stdout.write(`app-url-manifest.json up to date (${Object.keys(manifest).length} entries).\n`)
+} else {
+ fs.writeFileSync(OUT_FILE, formatted)
+ process.stdout.write(
+ `Wrote ${Object.keys(manifest).length} entries to ${path.relative(REPO, OUT_FILE)} ` +
+ `(${baseOnly.length} base-only, ${excluded.length} excluded).\n`
+ )
+}
diff --git a/frontend/package.json b/frontend/package.json
index 9acfb31e4283..ec4f3bd93d7a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -22,6 +22,8 @@
"build:with-report": "pnpm build && node ./bin/build-bundle-report.mjs",
"build:esbuild": "DEBUG=0 node ./build.mjs",
"build:products": "DEBUG=0 node build-products.mjs",
+ "build:app-urls": "node bin/build-app-url-manifest.mjs",
+ "build:app-urls:check": "node bin/build-app-url-manifest.mjs --check",
"start": "pnpm start-http",
"start-http": "pnpm clean && pnpm copy-scripts && pnpm build:esbuild --dev",
"start-docker": "pnpm start-http --host 0.0.0.0",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b41c0bc4b116..1ec0f8074d95 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2777,6 +2777,20 @@
"readOnlyHint": true
}
},
+ "generate-app-url": {
+ "description": "Build a correct, clickable PostHog app URL for any page or entity — run `info generate-app-url` for the full catalog of path templates.\nALWAYS use this (or an existing `_posthogUrl` field on a tool result) instead of writing PostHog links by hand: slugs and project/host prefixes are easy to get wrong (a person UUID lives at `/persons/<uuid>`, not `/person/...`) and IDs must never be retyped into a path. Pass a `url` template from the catalog plus its `{placeholders}` as `params`; returns `{ url }` — surface it verbatim.",
+ "category": "Utilities",
+ "feature": "links",
+ "summary": "Build a correct PostHog app URL for a page or entity.",
+ "title": "Generate app URL",
+ "required_scopes": [],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false,
+ "readOnlyHint": true
+ }
+ },
"get-llm-total-costs-for-project": {
"description": "Fetches the total LLM daily costs for each model for a project over a given number of days. If no number of days is provided, it defaults to 7. The results are sorted by model name. The total cost is rounded to 4 decimal places. The query is executed against the project's data warehouse. Show the results as a Markdown formatted table with the following information for each model: Model name, Total cost in USD, Each day's date, Each day's cost in USD. Write in bold the model name with the highest total cost. Properly render the markdown table in the response.",
"category": "AI observability",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 1d003699f34c..cc68742ff0fd 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -1,4 +1,18 @@
{
+ "generate-app-url": {
+ "description": "Build a correct, clickable PostHog app URL for any page or entity — run `info generate-app-url` for the full catalog of path templates.\nALWAYS use this (or an existing `_posthogUrl` field on a tool result) instead of writing PostHog links by hand: slugs and project/host prefixes are easy to get wrong (a person UUID lives at `/persons/<uuid>`, not `/person/...`) and IDs must never be retyped into a path. Pass a `url` template from the catalog plus its `{placeholders}` as `params`; returns `{ url }` — surface it verbatim.",
+ "category": "Utilities",
+ "feature": "links",
+ "summary": "Build a correct PostHog app URL for a page or entity.",
+ "title": "Generate app URL",
+ "required_scopes": [],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false,
+ "readOnlyHint": true
+ }
+ },
"agent-feedback": {
"description": "Optional: report a concrete problem with this PostHog MCP server itself — a tool, input schema, response format, error, or these instructions. Keep feedback about the MCP, not the user's task, their data, or your findings. ONLY use this when something went wrong or was missing: friction that slowed you down, a surprise, a missing capability, an unhelpful error, wrong results, or unclear docs. Feedback must be constructive and actionable — point at a specific defect the PostHog team can fix and name the change in `suggested_improvement`. Do NOT submit positive or 'everything worked' reports — they are noise we cannot act on. Skip it entirely for routine tasks where nothing went wrong. Keep `summary` to one sentence and write the free-text fields as clear, concise bullet points, quoting tool names, parameters, and error messages where possible. Do not include user PII or sensitive query content. IMPORTANT: submitting feedback does NOT mean your work is done — keep going and finish the user's task using the other available tools. This tool is for reporting problems to the PostHog team, not for ending the conversation.",
"category": "Feedback",
diff --git a/services/mcp/src/templates/sections/url-patterns.md b/services/mcp/src/templates/sections/url-patterns.md
index 395285036939..a6ad0bff89a5 100644
--- a/services/mcp/src/templates/sections/url-patterns.md
+++ b/services/mcp/src/templates/sections/url-patterns.md
@@ -2,7 +2,10 @@
PostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.
-- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
-- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):
- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.
- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
+Choose the link source in this order:
+
+1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
+2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.
+3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):
+ - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.
+ - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 89987aebd2be..e88b0790889d 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -13,6 +13,8 @@ import submitFeedback from './feedback/submit'
import { GENERATED_TOOL_MAP } from './generated'
// Insights
import queryInsight from './insights/query'
+// Links (utility — builds canonical app URLs from the frontend's route table)
+import generateAppUrl from './links/generate-app-url'
// Notebooks (edit is hand-written — generated CRUD lives in generated/notebooks.ts)
import notebookEdit from './notebooks/edit'
// Organizations
@@ -64,6 +66,9 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
// Insights
'insight-query': queryInsight,
+ // Links (utility — canonical app URLs so the model never hand-builds/mis-slugs entity links)
+ 'generate-app-url': generateAppUrl,
+
// AI observability
'get-llm-total-costs-for-project': getLLMCosts,
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
new file mode 100644
index 000000000000..69e04254d39f
--- /dev/null
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -0,0 +1,1437 @@
+{
+ "accountConnected": {
+ "template": "/account-connected/{kind}",
+ "params": ["kind"],
+ "scope": "project"
+ },
+ "accountSocialConnected": {
+ "template": "/account/social-connected",
+ "params": [],
+ "scope": "global"
+ },
+ "action": {
+ "template": "/data-management/actions/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "actions": {
+ "template": "/data-management/actions",
+ "params": [],
+ "scope": "project"
+ },
+ "activity": {
+ "template": "/activity/{tab}",
+ "params": ["tab"],
+ "scope": "project"
+ },
+ "advancedActivityLogs": {
+ "template": "/activity-logs",
+ "params": [],
+ "scope": "project"
+ },
+ "agenticAccountMismatch": {
+ "template": "/agentic/account-mismatch",
+ "params": [],
+ "scope": "project"
+ },
+ "agenticAuthorize": {
+ "template": "/agentic/authorize",
+ "params": [],
+ "scope": "project"
+ },
+ "ai": {
+ "template": "/ai",
+ "params": [],
+ "scope": "project"
+ },
+ "aiHistory": {
+ "template": "/ai/history",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityCluster": {
+ "template": "/ai-observability/clusters/{runId}/{clusterId}",
+ "params": ["runId", "clusterId"],
+ "scope": "project"
+ },
+ "aiObservabilityClusters": {
+ "template": "/ai-observability/clusters",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityDashboard": {
+ "template": "/ai-observability/dashboard",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityDataset": {
+ "template": "/ai-evals/datasets/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "aiObservabilityDatasets": {
+ "template": "/ai-evals/datasets",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityErrors": {
+ "template": "/ai-observability/errors",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityEvaluation": {
+ "template": "/ai-evals/evaluations/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "aiObservabilityEvaluationTemplates": {
+ "template": "/ai-evals/evaluations/templates",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityEvaluations": {
+ "template": "/ai-evals/evaluations",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityGenerations": {
+ "template": "/ai-observability/generations",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityOfflineEvaluationExperiment": {
+ "template": "/ai-evals/evaluations/offline/experiments/{experimentId}",
+ "params": ["experimentId"],
+ "scope": "project"
+ },
+ "aiObservabilityOfflineEvaluations": {
+ "template": "/ai-evals/evaluations/offline/experiments",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityPlayground": {
+ "template": "/ai-observability/playground",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityPrompt": {
+ "template": "/prompt-management/prompts/{name}",
+ "params": ["name"],
+ "scope": "project"
+ },
+ "aiObservabilityPrompts": {
+ "template": "/prompt-management/prompts",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityReviews": {
+ "template": "/ai-observability/reviews",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilitySentiment": {
+ "template": "/ai-observability/sentiment",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilitySession": {
+ "template": "/ai-observability/sessions/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "aiObservabilitySessions": {
+ "template": "/ai-observability/sessions",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilitySkill": {
+ "template": "/prompt-management/skills/{name}",
+ "params": ["name"],
+ "scope": "project"
+ },
+ "aiObservabilitySkills": {
+ "template": "/prompt-management/skills",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityTag": {
+ "template": "/ai-evals/taggers/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "aiObservabilityTags": {
+ "template": "/ai-evals/taggers",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityTools": {
+ "template": "/ai-observability/tools",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityTrace": {
+ "template": "/ai-observability/traces/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "aiObservabilityTraces": {
+ "template": "/ai-observability/traces",
+ "params": [],
+ "scope": "project"
+ },
+ "aiObservabilityUsers": {
+ "template": "/ai-observability/users",
+ "params": [],
+ "scope": "project"
+ },
+ "alert": {
+ "template": "/insights",
+ "params": [],
+ "scope": "project"
+ },
+ "alerts": {
+ "template": "/insights",
+ "params": [],
+ "scope": "project"
+ },
+ "annotation": {
+ "template": "/data-management/annotations/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "annotations": {
+ "template": "/data-management/annotations",
+ "params": [],
+ "scope": "project"
+ },
+ "approval": {
+ "template": "/approvals/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "approvals": {
+ "template": "/settings/environment-approvals",
+ "params": [],
+ "scope": "project"
+ },
+ "asyncMigrations": {
+ "template": "/instance/async_migrations",
+ "params": [],
+ "scope": "global"
+ },
+ "asyncMigrationsFuture": {
+ "template": "/instance/async_migrations/future",
+ "params": [],
+ "scope": "global"
+ },
+ "asyncMigrationsSettings": {
+ "template": "/instance/async_migrations/settings",
+ "params": [],
+ "scope": "global"
+ },
+ "batchExport": {
+ "template": "/pipeline/batch-exports/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "batchExportNew": {
+ "template": "/pipeline/batch-exports/new/{service}",
+ "params": ["service"],
+ "scope": "project"
+ },
+ "billingAuthorizationStatus": {
+ "template": "/billing/authorization_status",
+ "params": [],
+ "scope": "project"
+ },
+ "businessKnowledge": {
+ "template": "/business-knowledge",
+ "params": [],
+ "scope": "project"
+ },
+ "canvas": {
+ "template": "/canvas",
+ "params": [],
+ "scope": "project"
+ },
+ "cliAuthorize": {
+ "template": "/cli/authorize",
+ "params": [],
+ "scope": "global"
+ },
+ "cliLive": {
+ "template": "/cli/live",
+ "params": [],
+ "scope": "global"
+ },
+ "cohort": {
+ "template": "/cohorts/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "cohortCalculationHistory": {
+ "template": "/cohorts/{id}/calculation-history",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "cohorts": {
+ "template": "/cohorts",
+ "params": [],
+ "scope": "project"
+ },
+ "comment": {
+ "template": "/data-management/comments/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "comments": {
+ "template": "/data-management/comments",
+ "params": [],
+ "scope": "project"
+ },
+ "coreEvents": {
+ "template": "/data-management/core-events",
+ "params": [],
+ "scope": "project"
+ },
+ "coupons": {
+ "template": "/coupons/{campaign}",
+ "params": ["campaign"],
+ "scope": "project"
+ },
+ "createAction": {
+ "template": "/data-management/actions/new",
+ "params": [],
+ "scope": "project"
+ },
+ "credentialReview": {
+ "template": "/account/credential-review",
+ "params": [],
+ "scope": "global"
+ },
+ "customCss": {
+ "template": "/themes/custom-css",
+ "params": [],
+ "scope": "project"
+ },
+ "customerAnalytics": {
+ "template": "/customer_analytics",
+ "params": [],
+ "scope": "project"
+ },
+ "customerAnalyticsAccounts": {
+ "template": "/customer_analytics/accounts",
+ "params": [],
+ "scope": "project"
+ },
+ "customerAnalyticsConfiguration": {
+ "template": "/customer_analytics/configuration",
+ "params": [],
+ "scope": "project"
+ },
+ "customerAnalyticsDashboard": {
+ "template": "/customer_analytics/dashboard",
+ "params": [],
+ "scope": "project"
+ },
+ "customerAnalyticsJourneys": {
+ "template": "/customer_analytics/journeys",
+ "params": [],
+ "scope": "project"
+ },
+ "customerJourneyBuilder": {
+ "template": "/customer_analytics/journeys/new",
+ "params": [],
+ "scope": "project"
+ },
+ "customerJourneyEdit": {
+ "template": "/customer_analytics/journeys/{id}/edit",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "customerJourneyTemplates": {
+ "template": "/customer_analytics/journeys/templates",
+ "params": [],
+ "scope": "project"
+ },
+ "dashboard": {
+ "template": "/dashboard/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "dashboardButtonTile": {
+ "template": "/dashboard/{id}/button-tiles/{buttonTileId}",
+ "params": ["id", "buttonTileId"],
+ "scope": "project"
+ },
+ "dashboardSharing": {
+ "template": "/dashboard/{id}/sharing",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "dashboardSubscription": {
+ "template": "/dashboard/{id}/subscriptions/{subscriptionId}",
+ "params": ["id", "subscriptionId"],
+ "scope": "project"
+ },
+ "dashboardSubscriptions": {
+ "template": "/dashboard/{id}/subscriptions",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "dashboardTemplateCopyToProject": {
+ "template": "/dashboard/templates/{templateId}/copy-to-project",
+ "params": ["templateId"],
+ "scope": "project"
+ },
+ "dashboardTextTile": {
+ "template": "/dashboard/{id}/text-tiles/{textTileId}",
+ "params": ["id", "textTileId"],
+ "scope": "project"
+ },
+ "dashboards": {
+ "template": "/dashboard",
+ "params": [],
+ "scope": "project"
+ },
+ "dataManagementHistory": {
+ "template": "/data-management/history",
+ "params": [],
+ "scope": "project"
+ },
+ "dataOps": {
+ "template": "/data-ops",
+ "params": [],
+ "scope": "project"
+ },
+ "dataPipelinesNew": {
+ "template": "/pipeline/new/",
+ "params": [],
+ "scope": "project"
+ },
+ "dataWarehouseManagedViewsets": {
+ "template": "/data-management/managed-viewsets",
+ "params": [],
+ "scope": "project"
+ },
+ "dataWarehouseSource": {
+ "template": "/data-management/sources/{id}/schemas",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "dataWarehouseSourceNew": {
+ "template": "/data-warehouse/new-source",
+ "params": [],
+ "scope": "project"
+ },
+ "dataWarehouseSourceSchema": {
+ "template": "/data-management/sources/{sourceId}/schemas/{schemaId}",
+ "params": ["sourceId", "schemaId"],
+ "scope": "project"
+ },
+ "database": {
+ "template": "/data-management/database",
+ "params": [],
+ "scope": "project"
+ },
+ "deadLetterQueue": {
+ "template": "/instance/dead_letter_queue",
+ "params": [],
+ "scope": "global"
+ },
+ "debugHog": {
+ "template": "/debug/hog",
+ "params": [],
+ "scope": "project"
+ },
+ "debugQuery": {
+ "template": "/debug",
+ "params": [],
+ "scope": "project"
+ },
+ "destinations": {
+ "template": "/data-management/destinations",
+ "params": [],
+ "scope": "project"
+ },
+ "duplicateAction": {
+ "template": "/data-management/actions/new/",
+ "params": [],
+ "scope": "project"
+ },
+ "earlyAccessFeature": {
+ "template": "/early_access_features/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "earlyAccessFeatures": {
+ "template": "/early_access_features",
+ "params": [],
+ "scope": "project"
+ },
+ "emailMFAVerify": {
+ "template": "/login/verify",
+ "params": [],
+ "scope": "global"
+ },
+ "embedded": {
+ "template": "/embedded/{token}",
+ "params": ["token"],
+ "scope": "global"
+ },
+ "endpoint": {
+ "template": "/endpoints/{name}",
+ "params": ["name"],
+ "scope": "project"
+ },
+ "endpoints": {
+ "template": "/endpoints",
+ "params": [],
+ "scope": "project"
+ },
+ "endpointsUsage": {
+ "template": "/endpoints",
+ "params": [],
+ "scope": "project"
+ },
+ "errorTracking": {
+ "template": "/error_tracking",
+ "params": [],
+ "scope": "project"
+ },
+ "errorTrackingAlert": {
+ "template": "/error_tracking/alerts/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "errorTrackingAlertNew": {
+ "template": "/error_tracking/alerts/new/{templateId}",
+ "params": ["templateId"],
+ "scope": "project"
+ },
+ "errorTrackingConfiguration": {
+ "template": "/error_tracking",
+ "params": [],
+ "scope": "project"
+ },
+ "errorTrackingIssue": {
+ "template": "/error_tracking/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "errorTrackingIssueFingerprints": {
+ "template": "/error_tracking/{id}/fingerprints",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "event": {
+ "template": "/events/{id}/{timestamp}",
+ "params": ["id", "timestamp"],
+ "scope": "project"
+ },
+ "eventDefinition": {
+ "template": "/data-management/events/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "eventDefinitionEdit": {
+ "template": "/data-management/events/{id}/edit",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "eventDefinitions": {
+ "template": "/data-management/events",
+ "params": [],
+ "scope": "project"
+ },
+ "eventFiltering": {
+ "template": "/data-management/event-filtering",
+ "params": [],
+ "scope": "project"
+ },
+ "experiment": {
+ "template": "/experiments/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "experiments": {
+ "template": "/experiments",
+ "params": [],
+ "scope": "project"
+ },
+ "experimentsSharedMetric": {
+ "template": "/experiments/shared-metrics/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "experimentsSharedMetrics": {
+ "template": "/experiments/shared-metrics",
+ "params": [],
+ "scope": "project"
+ },
+ "exports": {
+ "template": "/exports",
+ "params": [],
+ "scope": "project"
+ },
+ "featureFlag": {
+ "template": "/feature_flags/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "featureFlagNew": {
+ "template": "/feature_flags/new",
+ "params": [],
+ "scope": "project"
+ },
+ "featureFlagTemplates": {
+ "template": "/feature_flags/templates",
+ "params": [],
+ "scope": "project"
+ },
+ "featureFlags": {
+ "template": "/feature_flags",
+ "params": [],
+ "scope": "project"
+ },
+ "flappyHog": {
+ "template": "/games/flappyhog",
+ "params": [],
+ "scope": "project"
+ },
+ "game368hedgehogs": {
+ "template": "/games/368hedgehogs",
+ "params": [],
+ "scope": "project"
+ },
+ "group": {
+ "template": "/groups/{groupTypeIndex}/{groupKey}",
+ "params": ["groupTypeIndex", "groupKey"],
+ "scope": "project"
+ },
+ "groups": {
+ "template": "/groups/{groupTypeIndex}",
+ "params": ["groupTypeIndex"],
+ "scope": "project"
+ },
+ "groupsNew": {
+ "template": "/groups/{groupTypeIndex}/new",
+ "params": ["groupTypeIndex"],
+ "scope": "project"
+ },
+ "health": {
+ "template": "/health",
+ "params": [],
+ "scope": "project"
+ },
+ "healthAlerts": {
+ "template": "/health/alerts",
+ "params": [],
+ "scope": "project"
+ },
+ "healthCategory": {
+ "template": "/health/{category}",
+ "params": ["category"],
+ "scope": "project"
+ },
+ "heatmap": {
+ "template": "/heatmaps/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "heatmapNew": {
+ "template": "/heatmaps/new",
+ "params": [],
+ "scope": "project"
+ },
+ "heatmapRecording": {
+ "template": "/heatmaps/recording",
+ "params": [],
+ "scope": "project"
+ },
+ "heatmaps": {
+ "template": "/heatmaps",
+ "params": [],
+ "scope": "project"
+ },
+ "hogFunction": {
+ "template": "/functions/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "hogFunctionNew": {
+ "template": "/functions/new/{templateId}",
+ "params": ["templateId"],
+ "scope": "project"
+ },
+ "inbox": {
+ "template": "/inbox",
+ "params": [],
+ "scope": "project"
+ },
+ "ingestionWarnings": {
+ "template": "/data-management/ingestion-warnings",
+ "params": [],
+ "scope": "project"
+ },
+ "insightAlert": {
+ "template": "/insights/{insightShortId}/alerts",
+ "params": ["insightShortId"],
+ "scope": "project"
+ },
+ "insightAlerts": {
+ "template": "/insights/{insightShortId}/alerts",
+ "params": ["insightShortId"],
+ "scope": "project"
+ },
+ "insightEdit": {
+ "template": "/insights/{id}/edit",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "insightNew": {
+ "template": "/insights/new",
+ "params": [],
+ "scope": "project"
+ },
+ "insightNewHogQL": {
+ "template": "/insights/new",
+ "params": [],
+ "scope": "project"
+ },
+ "insightQuickStart": {
+ "template": "/insights/quick-start",
+ "params": [],
+ "scope": "project"
+ },
+ "insightSharing": {
+ "template": "/insights/{id}/sharing",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "insightSubcription": {
+ "template": "/insights/{id}/subscriptions/{subscriptionId}",
+ "params": ["id", "subscriptionId"],
+ "scope": "project"
+ },
+ "insightSubcriptions": {
+ "template": "/insights/{id}/subscriptions",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "insightView": {
+ "template": "/insights/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "insights": {
+ "template": "/insights",
+ "params": [],
+ "scope": "project"
+ },
+ "instanceKafkaInspector": {
+ "template": "/instance/kafka_inspector",
+ "params": [],
+ "scope": "global"
+ },
+ "instanceMetrics": {
+ "template": "/instance/metrics",
+ "params": [],
+ "scope": "global"
+ },
+ "instanceSettings": {
+ "template": "/instance/settings",
+ "params": [],
+ "scope": "global"
+ },
+ "instanceStaffUsers": {
+ "template": "/instance/staff_users",
+ "params": [],
+ "scope": "global"
+ },
+ "instanceStatus": {
+ "template": "/instance/status",
+ "params": [],
+ "scope": "global"
+ },
+ "integrationsRedirect": {
+ "template": "/integrations/{kind}/callback",
+ "params": ["kind"],
+ "scope": "project"
+ },
+ "inviteSignup": {
+ "template": "/signup/{id}",
+ "params": ["id"],
+ "scope": "global"
+ },
+ "legacyPlugin": {
+ "template": "/pipeline/plugins/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "legalDocumentNew": {
+ "template": "/legal/new/{type}",
+ "params": ["type"],
+ "scope": "project"
+ },
+ "legalDocuments": {
+ "template": "/legal",
+ "params": [],
+ "scope": "project"
+ },
+ "link": {
+ "template": "/link/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "links": {
+ "template": "/links",
+ "params": [],
+ "scope": "project"
+ },
+ "liveDebugger": {
+ "template": "/live-debugger",
+ "params": [],
+ "scope": "project"
+ },
+ "login": {
+ "template": "/login",
+ "params": [],
+ "scope": "global"
+ },
+ "login2FA": {
+ "template": "/login/2fa",
+ "params": [],
+ "scope": "global"
+ },
+ "login2FASetup": {
+ "template": "/login/2fa_setup",
+ "params": [],
+ "scope": "global"
+ },
+ "logs": {
+ "template": "/logs",
+ "params": [],
+ "scope": "project"
+ },
+ "logsAlertDetail": {
+ "template": "/logs/alerts/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "logsAlertNotificationDetail": {
+ "template": "/logs/alerts/{alertId}/notifications/{hogFunctionId}",
+ "params": ["alertId", "hogFunctionId"],
+ "scope": "project"
+ },
+ "logsSamplingDetail": {
+ "template": "/logs/drop-rules/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "logsSamplingNew": {
+ "template": "/logs/drop-rules/new",
+ "params": [],
+ "scope": "project"
+ },
+ "managedMigration": {
+ "template": "/managed_migrations",
+ "params": [],
+ "scope": "project"
+ },
+ "managedMigrationNew": {
+ "template": "/managed_migrations/new",
+ "params": [],
+ "scope": "project"
+ },
+ "marketingAnalyticsApp": {
+ "template": "/marketing",
+ "params": [],
+ "scope": "project"
+ },
+ "materializedColumns": {
+ "template": "/data-management/materialized-columns",
+ "params": [],
+ "scope": "project"
+ },
+ "mcpAnalyticsDashboard": {
+ "template": "/mcp-analytics/dashboard",
+ "params": [],
+ "scope": "project"
+ },
+ "mcpAnalyticsIntentClustering": {
+ "template": "/mcp-analytics/intent-clustering",
+ "params": [],
+ "scope": "project"
+ },
+ "mcpAnalyticsSessions": {
+ "template": "/mcp-analytics/sessions",
+ "params": [],
+ "scope": "project"
+ },
+ "mcpAnalyticsTool": {
+ "template": "/mcp-analytics/tool-quality/{toolName}",
+ "params": ["toolName"],
+ "scope": "project"
+ },
+ "mcpAnalyticsToolQuality": {
+ "template": "/mcp-analytics/tool-quality",
+ "params": [],
+ "scope": "project"
+ },
+ "metrics": {
+ "template": "/metrics",
+ "params": [],
+ "scope": "project"
+ },
+ "models": {
+ "template": "/models",
+ "params": [],
+ "scope": "project"
+ },
+ "moveToPostHogCloud": {
+ "template": "/move-to-cloud",
+ "params": [],
+ "scope": "project"
+ },
+ "nodeDetail": {
+ "template": "/models/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "notebook": {
+ "template": "/notebooks/{shortId}",
+ "params": ["shortId"],
+ "scope": "project"
+ },
+ "notebooks": {
+ "template": "/notebooks",
+ "params": [],
+ "scope": "project"
+ },
+ "oauthAuthorize": {
+ "template": "/oauth/authorize",
+ "params": [],
+ "scope": "global"
+ },
+ "onboarding": {
+ "template": "/onboarding",
+ "params": [],
+ "scope": "project"
+ },
+ "organizationBilling": {
+ "template": "/organization/billing",
+ "params": [],
+ "scope": "global"
+ },
+ "organizationBillingSection": {
+ "template": "/organization/billing/overview",
+ "params": [],
+ "scope": "global"
+ },
+ "organizationCreateFirst": {
+ "template": "/create-organization",
+ "params": [],
+ "scope": "global"
+ },
+ "organizationCreationConfirm": {
+ "template": "/organization/confirm-creation",
+ "params": [],
+ "scope": "global"
+ },
+ "organizationDeactivated": {
+ "template": "/organization-deactivated",
+ "params": [],
+ "scope": "project"
+ },
+ "organizationPendingDeletion": {
+ "template": "/organization-pending-deletion",
+ "params": [],
+ "scope": "project"
+ },
+ "passwordReset": {
+ "template": "/reset",
+ "params": [],
+ "scope": "project"
+ },
+ "passwordResetComplete": {
+ "template": "/reset/{userUuid}/{token}",
+ "params": ["userUuid", "token"],
+ "scope": "project"
+ },
+ "personByDistinctId": {
+ "template": "/person/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "personByUUID": {
+ "template": "/persons/{uuid}",
+ "params": ["uuid"],
+ "scope": "project"
+ },
+ "persons": {
+ "template": "/persons",
+ "params": [],
+ "scope": "project"
+ },
+ "pipelineStatus": {
+ "template": "/health/pipeline-status",
+ "params": [],
+ "scope": "project"
+ },
+ "preflight": {
+ "template": "/preflight",
+ "params": [],
+ "scope": "global"
+ },
+ "productTour": {
+ "template": "/product_tours/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "productTours": {
+ "template": "/product_tours",
+ "params": [],
+ "scope": "project"
+ },
+ "projectCreateFirst": {
+ "template": "/organization/create-project",
+ "params": [],
+ "scope": "global"
+ },
+ "projectHomepage": {
+ "template": "/home",
+ "params": [],
+ "scope": "project"
+ },
+ "propertyDefinition": {
+ "template": "/data-management/properties/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "propertyDefinitionEdit": {
+ "template": "/data-management/properties/{id}/edit",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "propertyDefinitions": {
+ "template": "/data-management/properties",
+ "params": [],
+ "scope": "project"
+ },
+ "queryPerformance": {
+ "template": "/instance/query_performance",
+ "params": [],
+ "scope": "global"
+ },
+ "replay": {
+ "template": "/replay/home",
+ "params": [],
+ "scope": "project"
+ },
+ "replayFilePlayback": {
+ "template": "/replay/file-playback",
+ "params": [],
+ "scope": "project"
+ },
+ "replayKiosk": {
+ "template": "/replay/kiosk",
+ "params": [],
+ "scope": "project"
+ },
+ "replayPlaylist": {
+ "template": "/replay/playlists/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "replaySettings": {
+ "template": "/replay/settings",
+ "params": [],
+ "scope": "project"
+ },
+ "replaySingle": {
+ "template": "/replay/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "replayVision": {
+ "template": "/replay-vision",
+ "params": [],
+ "scope": "project"
+ },
+ "replayVisionObservation": {
+ "template": "/replay-vision/observations/{observationId}",
+ "params": ["observationId"],
+ "scope": "project"
+ },
+ "replayVisionScannerConfigure": {
+ "template": "/replay-vision/{id}/configure",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "replayVisionScannerTriggers": {
+ "template": "/replay-vision/{id}/triggers",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "replayVisionTemplates": {
+ "template": "/replay-vision/templates",
+ "params": [],
+ "scope": "project"
+ },
+ "resourceTransfer": {
+ "template": "/resource-transfer/{resourceKind}/{resourceId}",
+ "params": ["resourceKind", "resourceId"],
+ "scope": "project"
+ },
+ "revenueAnalytics": {
+ "template": "/revenue_analytics",
+ "params": [],
+ "scope": "project"
+ },
+ "revenueSettings": {
+ "template": "/data-management/revenue",
+ "params": [],
+ "scope": "project"
+ },
+ "savedInsights": {
+ "template": "/insights",
+ "params": [],
+ "scope": "project"
+ },
+ "schemaManagement": {
+ "template": "/data-management/schema",
+ "params": [],
+ "scope": "project"
+ },
+ "sdkHealth": {
+ "template": "/health/sdk-health",
+ "params": [],
+ "scope": "project"
+ },
+ "sessionAttributionExplorer": {
+ "template": "/web/session-attribution-explorer",
+ "params": [],
+ "scope": "project"
+ },
+ "sessionProfile": {
+ "template": "/sessions/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "sessionSummaries": {
+ "template": "/session-summaries",
+ "params": [],
+ "scope": "project"
+ },
+ "sessionSummary": {
+ "template": "/session-summaries/{sessionGroupId}",
+ "params": ["sessionGroupId"],
+ "scope": "project"
+ },
+ "settings": {
+ "template": "/settings/project",
+ "params": [],
+ "scope": "project"
+ },
+ "shared": {
+ "template": "/shared/{token}",
+ "params": ["token"],
+ "scope": "global"
+ },
+ "sharedDashboard": {
+ "template": "/shared_dashboard/{shareToken}",
+ "params": ["shareToken"],
+ "scope": "project"
+ },
+ "signup": {
+ "template": "/signup",
+ "params": [],
+ "scope": "global"
+ },
+ "site": {
+ "template": "/site/{url}",
+ "params": ["url"],
+ "scope": "project"
+ },
+ "slackTaskContext": {
+ "template": "/slack-task-context",
+ "params": [],
+ "scope": "project"
+ },
+ "sources": {
+ "template": "/data-management/sources",
+ "params": [],
+ "scope": "project"
+ },
+ "sqlEditor": {
+ "template": "/sql",
+ "params": [],
+ "scope": "project"
+ },
+ "startups": {
+ "template": "/startups",
+ "params": [],
+ "scope": "project"
+ },
+ "stripeConfirmInstall": {
+ "template": "/integrations/stripe/confirm-install",
+ "params": [],
+ "scope": "project"
+ },
+ "subscription": {
+ "template": "/subscriptions/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "subscriptionEdit": {
+ "template": "/subscriptions/{id}/edit",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "subscriptionNew": {
+ "template": "/subscriptions/new",
+ "params": [],
+ "scope": "project"
+ },
+ "subscriptions": {
+ "template": "/subscriptions",
+ "params": [],
+ "scope": "project"
+ },
+ "supportDashboard": {
+ "template": "/support",
+ "params": [],
+ "scope": "project"
+ },
+ "supportSettings": {
+ "template": "/support/settings",
+ "params": [],
+ "scope": "project"
+ },
+ "supportTicketDetail": {
+ "template": "/support/tickets/{ticketId}",
+ "params": ["ticketId"],
+ "scope": "project"
+ },
+ "supportTickets": {
+ "template": "/support/tickets",
+ "params": [],
+ "scope": "project"
+ },
+ "survey": {
+ "template": "/surveys/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "surveyFormBuilder": {
+ "template": "/surveys/form/new",
+ "params": [],
+ "scope": "project"
+ },
+ "surveyWizard": {
+ "template": "/surveys/guided/new",
+ "params": [],
+ "scope": "project"
+ },
+ "surveys": {
+ "template": "/surveys",
+ "params": [],
+ "scope": "project"
+ },
+ "taskDetail": {
+ "template": "/tasks/{taskId}",
+ "params": ["taskId"],
+ "scope": "project"
+ },
+ "taskTracker": {
+ "template": "/tasks",
+ "params": [],
+ "scope": "project"
+ },
+ "toolbarLaunch": {
+ "template": "/toolbar",
+ "params": [],
+ "scope": "project"
+ },
+ "tracing": {
+ "template": "/tracing",
+ "params": [],
+ "scope": "project"
+ },
+ "transformations": {
+ "template": "/data-management/transformations",
+ "params": [],
+ "scope": "project"
+ },
+ "twoFactorReset": {
+ "template": "/reset_2fa/{userUuid}/{token}",
+ "params": ["userUuid", "token"],
+ "scope": "project"
+ },
+ "unsubscribe": {
+ "template": "/unsubscribe",
+ "params": [],
+ "scope": "project"
+ },
+ "userInterview": {
+ "template": "/user_research/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "userInterviewResponse": {
+ "template": "/user_research/{topicId}/response/{responseId}",
+ "params": ["topicId", "responseId"],
+ "scope": "project"
+ },
+ "userInterviews": {
+ "template": "/user_research",
+ "params": [],
+ "scope": "project"
+ },
+ "variable": {
+ "template": "/data-management/variables/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "variableEdit": {
+ "template": "/data-management/variables/{id}/edit",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "variables": {
+ "template": "/data-management/variables",
+ "params": [],
+ "scope": "project"
+ },
+ "vercelConnect": {
+ "template": "/connect/vercel/link",
+ "params": [],
+ "scope": "project"
+ },
+ "vercelLinkError": {
+ "template": "/integrations/vercel/link-error",
+ "params": [],
+ "scope": "project"
+ },
+ "verifyEmail": {
+ "template": "/verify_email",
+ "params": [],
+ "scope": "project"
+ },
+ "visualReviewRepoRuns": {
+ "template": "/visual_review/repos/{repoId}/runs",
+ "params": ["repoId"],
+ "scope": "project"
+ },
+ "visualReviewRun": {
+ "template": "/visual_review/runs/{runId}",
+ "params": ["runId"],
+ "scope": "project"
+ },
+ "visualReviewRuns": {
+ "template": "/visual_review",
+ "params": [],
+ "scope": "project"
+ },
+ "visualReviewSettings": {
+ "template": "/visual_review/settings",
+ "params": [],
+ "scope": "project"
+ },
+ "visualReviewSnapshotHistory": {
+ "template": "/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}",
+ "params": ["repoId", "runType", "identifier"],
+ "scope": "project"
+ },
+ "visualReviewSnapshotOverview": {
+ "template": "/visual_review/repos/{repoId}/snapshots",
+ "params": ["repoId"],
+ "scope": "project"
+ },
+ "webAnalytics": {
+ "template": "/web",
+ "params": [],
+ "scope": "project"
+ },
+ "webAnalyticsBotAnalytics": {
+ "template": "/web/bots",
+ "params": [],
+ "scope": "project"
+ },
+ "webAnalyticsHealth": {
+ "template": "/web/health",
+ "params": [],
+ "scope": "project"
+ },
+ "webAnalyticsLive": {
+ "template": "/web/live",
+ "params": [],
+ "scope": "project"
+ },
+ "webAnalyticsMarketing": {
+ "template": "/web/marketing",
+ "params": [],
+ "scope": "project"
+ },
+ "webAnalyticsPageReports": {
+ "template": "/web/page-reports",
+ "params": [],
+ "scope": "project"
+ },
+ "webAnalyticsWebVitals": {
+ "template": "/web/web-vitals",
+ "params": [],
+ "scope": "project"
+ },
+ "webScripts": {
+ "template": "/web-scripts",
+ "params": [],
+ "scope": "project"
+ },
+ "webScriptsNew": {
+ "template": "/web-scripts/new",
+ "params": [],
+ "scope": "project"
+ },
+ "wizard": {
+ "template": "/wizard",
+ "params": [],
+ "scope": "project"
+ },
+ "workflow": {
+ "template": "/workflows/{id}/{tab}",
+ "params": ["id", "tab"],
+ "scope": "project"
+ },
+ "workflowNew": {
+ "template": "/workflows/new/workflow",
+ "params": [],
+ "scope": "project"
+ },
+ "workflows": {
+ "template": "/workflows",
+ "params": [],
+ "scope": "project"
+ },
+ "workflowsLibraryMessage": {
+ "template": "/workflows/library/messages/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "workflowsLibraryTemplate": {
+ "template": "/workflows/library/templates/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
+ "workflowsLibraryTemplateFromMessage": {
+ "template": "/workflows/library/templates/new",
+ "params": [],
+ "scope": "project"
+ },
+ "workflowsLibraryTemplateNew": {
+ "template": "/workflows/library/templates/new",
+ "params": [],
+ "scope": "project"
+ }
+}
diff --git a/services/mcp/src/tools/links/generate-app-url.ts b/services/mcp/src/tools/links/generate-app-url.ts
new file mode 100644
index 000000000000..98111188c549
--- /dev/null
+++ b/services/mcp/src/tools/links/generate-app-url.ts
@@ -0,0 +1,106 @@
+import { z } from 'zod'
+
+import type { Context, ToolBase } from '@/tools/types'
+
+import appUrlManifest from './app-url-manifest.json'
+import type { AppUrlManifest } from './types'
+
+// Canonical route table generated from the frontend's `urls` registry (see
+// frontend/src/scenes/appUrlManifest.ts). The model must never hand-build entity links — slugs and
+// project/host prefixes are easy to get wrong (a person UUID lives at `/persons/<uuid>`, a distinct
+// id at `/person/<id>`) — so this tool resolves them from the same definitions the app ships.
+const MANIFEST = appUrlManifest as AppUrlManifest
+
+// template -> scope. Templates can repeat across builders, but scope is a function of the path, so
+// any entry for a given template carries the same scope.
+const SCOPE_BY_TEMPLATE = new Map<string, 'project' | 'global'>()
+for (const entry of Object.values(MANIFEST)) {
+ SCOPE_BY_TEMPLATE.set(entry.template, entry.scope)
+}
+
+// Full catalog of canonical path templates, embedded in the `url` description so an agent inspecting
+// the tool (exec `info`) sees every linkable path up front — the `{placeholders}` are the params to
+// fill. Generated from the manifest (itself generated from the frontend's `urls`) so it never drifts.
+const URL_CATALOG = [...SCOPE_BY_TEMPLATE.keys()].sort().join('\n')
+
+const PLACEHOLDER = /\{([^}]+)\}/g
+
+function placeholdersOf(template: string): string[] {
+ return [...template.matchAll(PLACEHOLDER)].map((match) => match[1]!)
+}
+
+const schema = z.object({
+ url: z
+ .string()
+ .describe(
+ 'A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its ' +
+ "`{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route " +
+ 'table, so they are always correct — never pass a path that is not in this list.\n\n' +
+ URL_CATALOG
+ ),
+ params: z
+ .record(z.string(), z.string())
+ .default({})
+ .describe(
+ 'Values for the `{placeholders}` in the chosen path, e.g. {"uuid": "..."} for `/persons/{uuid}` ' +
+ 'or {"id": "...", "timestamp": "..."} for `/events/{id}/{timestamp}`. Must match the placeholders ' +
+ 'exactly; pass {} for a path with none.'
+ ),
+})
+
+type Params = z.infer<typeof schema>
+
+interface AppUrlResult {
+ /** Full, canonical, clickable PostHog URL. Surface this verbatim — do not rewrite it. */
+ url: string
+}
+
+function substitute(template: string, params: Record<string, string>): string {
+ return template.replace(PLACEHOLDER, (_match, name: string) => encodeURIComponent(params[name] ?? ''))
+}
+
+export const generateAppUrlHandler: ToolBase<typeof schema, AppUrlResult>['handler'] = async (
+ context: Context,
+ params: Params
+): Promise<AppUrlResult> => {
+ const scope = SCOPE_BY_TEMPLATE.get(params.url)
+ if (!scope) {
+ throw new Error(
+ `Unknown url "${params.url}". Pick a path template from this tool's catalog (run \`info generate-app-url\`).`
+ )
+ }
+
+ const required = placeholdersOf(params.url)
+ const provided = Object.keys(params.params)
+ const missing = required.filter((name) => !(name in params.params))
+ const unexpected = provided.filter((name) => !required.includes(name))
+ if (missing.length > 0 || unexpected.length > 0) {
+ const issues: string[] = []
+ if (missing.length > 0) {
+ issues.push(`missing: ${missing.join(', ')}`)
+ }
+ if (unexpected.length > 0) {
+ issues.push(`unexpected: ${unexpected.join(', ')}`)
+ }
+ const expected = required.length > 0 ? `[${required.join(', ')}]` : '(none)'
+ throw new Error(`params for "${params.url}" must be exactly ${expected} — ${issues.join('; ')}.`)
+ }
+
+ // `project` paths get `${publicBaseUrl}/project/:id`; `global` (org/account/auth) paths get the
+ // bare public host. `@current` resolves to the bare host without a project segment.
+ let baseUrl: string
+ if (scope === 'project') {
+ const projectId = await context.stateManager.getProjectId()
+ baseUrl = context.api.getProjectBaseUrl(projectId)
+ } else {
+ baseUrl = context.api.getProjectBaseUrl('@current')
+ }
+
+ return { url: `${baseUrl}${substitute(params.url, params.params)}` }
+}
+
+export default (): ToolBase<typeof schema, AppUrlResult> => ({
+ name: 'generate-app-url',
+ schema,
+ handler: generateAppUrlHandler,
+})
diff --git a/services/mcp/src/tools/links/types.ts b/services/mcp/src/tools/links/types.ts
new file mode 100644
index 000000000000..e0cb035813a2
--- /dev/null
+++ b/services/mcp/src/tools/links/types.ts
@@ -0,0 +1,14 @@
+// Shape of app-url-manifest.json, generated from the frontend's `urls` registry by
+// frontend/src/scenes/appUrlManifest.ts. Kept in sync by a drift test in that same dir.
+export type AppUrlScope = 'project' | 'global'
+
+export interface AppUrlEntry {
+ /** Relative path template with `{param}` placeholders, e.g. `/persons/{uuid}`. */
+ template: string
+ /** Placeholder names that appear in `template`, in declaration order. */
+ params: string[]
+ /** `project` paths get the `/project/:id` prefix; `global` paths (org/account/auth) get only the host. */
+ scope: AppUrlScope
+}
+
+export type AppUrlManifest = Record<string, AppUrlEntry>
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 16d4cbb5b553..58bb90a1386a 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -317,10 +317,13 @@ The user's name is Jane Doe ([email protected]).
PostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.
-- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
-- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):
- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.
- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
+Choose the link source in this order:
+
+1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
+2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.
+3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):
+ - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.
+ - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
### Sharing feedback on this MCP server
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
index 46264cb48e01..05d203f845cc 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
@@ -206,10 +206,13 @@ The user's name is Jane Doe ([email protected]).
PostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.
-- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
-- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):
- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.
- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
+Choose the link source in this order:
+
+1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
+2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.
+3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):
+ - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.
+ - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
### Sharing feedback on this MCP server
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
new file mode 100644
index 000000000000..0845c05c925b
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "params": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "default": {},
+ "description": "Values for the `{placeholders}` in the chosen path, e.g. {\"uuid\": \"...\"} for `/persons/{uuid}` or {\"id\": \"...\", \"timestamp\": \"...\"} for `/events/{id}/{timestamp}`. Must match the placeholders exactly; pass {} for a path with none.",
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "url": {
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-ops\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/inbox\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/query_performance\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/login/verify\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/prompt-management/skills\n/prompt-management/skills/{name}\n/replay-vision\n/replay-vision/observations/{observationId}\n/replay-vision/templates\n/replay-vision/{id}/configure\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/revenue_analytics\n/session-summaries\n/session-summaries/{sessionGroupId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/slack-task-context\n/sql\n/startups\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-reports\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "type": "string"
+ }
+ },
+ "required": ["url"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/generate-app-url.test.ts b/services/mcp/tests/unit/generate-app-url.test.ts
new file mode 100644
index 000000000000..0879b3cdda7a
--- /dev/null
+++ b/services/mcp/tests/unit/generate-app-url.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import generateAppUrl, { generateAppUrlHandler } from '@/tools/links/generate-app-url'
+import type { Context } from '@/tools/types'
+
+function createMockContext(): Context {
+ return {
+ api: {
+ getProjectBaseUrl: (projectId: string): string =>
+ projectId === '@current' ? 'https://us.posthog.com' : `https://us.posthog.com/project/${projectId}`,
+ },
+ stateManager: {
+ getProjectId: vi.fn(async () => '354703'),
+ },
+ } as unknown as Context
+}
+
+describe('generate-app-url', () => {
+ const ctx = createMockContext()
+
+ // The regression: a person UUID belongs under the plural /persons slug, not the singular /person.
+ it('builds a person-by-UUID link with the plural /persons slug', async () => {
+ const result = await generateAppUrlHandler(ctx, {
+ url: '/persons/{uuid}',
+ params: { uuid: '12857b3c-2916-536b-af70-1e43c442a942' },
+ })
+ expect(result.url).toBe('https://us.posthog.com/project/354703/persons/12857b3c-2916-536b-af70-1e43c442a942')
+ })
+
+ it('builds a person-by-distinct-id link with the singular /person slug', async () => {
+ const result = await generateAppUrlHandler(ctx, {
+ url: '/person/{id}',
+ params: { id: '[email protected]' },
+ })
+ expect(result.url).toBe('https://us.posthog.com/project/354703/person/pekerr%40ou.org')
+ })
+
+ it('builds a single session replay link', async () => {
+ const result = await generateAppUrlHandler(ctx, {
+ url: '/replay/{id}',
+ params: { id: '019e83d3-d262-7543-a677-5ea82d8e785c' },
+ })
+ expect(result.url).toBe('https://us.posthog.com/project/354703/replay/019e83d3-d262-7543-a677-5ea82d8e785c')
+ })
+
+ it('builds a multi-param event link and URL-encodes values', async () => {
+ const result = await generateAppUrlHandler(ctx, {
+ url: '/events/{id}/{timestamp}',
+ params: { id: 'evt_1', timestamp: '2026-06-01T15:48:00Z' },
+ })
+ expect(result.url).toBe('https://us.posthog.com/project/354703/events/evt_1/2026-06-01T15%3A48%3A00Z')
+ })
+
+ it('uses the bare host (no project prefix) for global-scope pages', async () => {
+ const result = await generateAppUrlHandler(ctx, { url: '/instance/status', params: {} })
+ expect(result.url).toBe('https://us.posthog.com/instance/status')
+ })
+
+ it('throws on an unknown url template', async () => {
+ await expect(generateAppUrlHandler(ctx, { url: '/definitely/not/a/template', params: {} })).rejects.toThrow(
+ /Unknown url "\/definitely\/not\/a\/template"/
+ )
+ })
+
+ it('throws when a required param is missing', async () => {
+ await expect(generateAppUrlHandler(ctx, { url: '/persons/{uuid}', params: {} })).rejects.toThrow(
+ /must be exactly \[uuid\]/
+ )
+ })
+
+ it('throws on an unexpected param', async () => {
+ await expect(
+ generateAppUrlHandler(ctx, { url: '/persons/{uuid}', params: { uuid: 'x', extra: 'y' } })
+ ).rejects.toThrow(/unexpected: extra/)
+ })
+
+ it('exposes the tool name and accepts a valid payload', () => {
+ const tool = generateAppUrl()
+ expect(tool.name).toBe('generate-app-url')
+ expect(tool.schema.safeParse({ url: '/persons/{uuid}', params: { uuid: 'x' } }).success).toBe(true)
+ })
+})