Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): add hono version of mcp server (#55266)

Joshua Snyder1aa2a1141a7d
diff --git a/.dockerignore b/.dockerignore
index 0afcdbd7f043..625099bbe752 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -6,6 +6,7 @@
!common/hogvm
!common/esbuilder
!common/migration_utils
+!common/mosaic
!common/replay-headless
!common/replay-shared
!common/plugin_transpiler/*.*
@@ -39,6 +40,15 @@
!nodejs/assets
!nodejs/tsconfig.eslint.json
!nodejs/tsconfig.json
+!services/mcp
+!services/mcp/package.json
+!services/mcp/tsconfig.json
+!services/mcp/scripts
+!services/mcp/src
+!services/mcp/shared
+!services/mcp/types.d.ts
+!services/mcp/worker-configuration.d.ts
+!services/mcp/public
!pnpm-lock.yaml
!pnpm-workspace.yaml
!pyproject.toml
@@ -55,6 +65,7 @@
!test-runner-jest-environment.js
!test-runner-jest.config.js
!tools/hogli
+!tools/openapi-codegen
!tsconfig.json
!unit.json.tpl
common/*/*/node_modules
@@ -65,6 +76,10 @@ packages/quill/**/node_modules
packages/quill/**/dist
products/**/node_modules
nodejs/node_modules
+services/mcp/node_modules
+services/mcp/dist
+services/mcp/.wrangler
+services/mcp/tests
ee/**/node_modules
docs/**/node_modules
**/__pycache__
diff --git a/.github/workflows/cd-mcp-image.yml b/.github/workflows/cd-mcp-image.yml
new file mode 100644
index 000000000000..f858f019a5e0
--- /dev/null
+++ b/.github/workflows/cd-mcp-image.yml
@@ -0,0 +1,121 @@
+#
+# Build and push MCP server container image.
+#
+# This is the MCP server that runs on k8s (EU + US clusters)
+# using Redis for session state instead of Cloudflare Durable Objects.
+#
+name: MCP Container Image CD
+
+on:
+ push:
+ branches:
+ - master
+ paths:
+ - 'services/mcp/**'
+ - '.github/workflows/cd-mcp-image.yml'
+ pull_request:
+ types: [opened, synchronize, reopened, labeled]
+ workflow_dispatch:
+
+jobs:
+ build:
+ name: Build and push container image
+ if: |
+ github.repository == 'PostHog/posthog' && (
+ github.event_name == 'push' ||
+ github.event_name == 'workflow_dispatch' ||
+ contains(github.event.pull_request.labels.*.name, 'build-mcp-image')
+ )
+ runs-on: depot-ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ packages: write
+ id-token: write
+
+ outputs:
+ sha: ${{ steps.push.outputs.digest }}
+
+ steps:
+ - name: Check out
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 2
+
+ - name: Docker meta and registry login
+ id: docker-meta
+ uses: ./.github/actions/docker-meta
+ with:
+ image-name: posthog-mcp
+ aws-role-to-assume: ${{ secrets.AWS_ECR_PUBLISH_IAM_ROLE }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ dockerhub-username: ${{ secrets.DOCKERHUB_USER }}
+ dockerhub-password: ${{ secrets.DOCKERHUB_TOKEN }}
+ push-to-dockerhub: 'false'
+
+ - name: Set up Depot CLI
+ uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+
+ - name: Build and push container image
+ id: push
+ uses: depot/build-push-action@5f3b3c2e5a00f0093de47f657aeaefcedff27d18 # v1.17.0
+ with:
+ project: c1f2m5s6zd
+ file: ./services/mcp/Dockerfile
+ buildx-fallback: false
+ push: ${{ github.ref == 'refs/heads/master' }}
+ tags: ${{ steps.docker-meta.outputs.tags }}
+ labels: ${{ steps.docker-meta.outputs.labels }}
+ platforms: linux/arm64,linux/amd64
+ build-args: COMMIT_HASH=${{ github.sha }}
+
+ deploy:
+ name: Trigger MCP deployment
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ needs: build
+ if: github.ref == 'refs/heads/master'
+ permissions: {}
+
+ steps:
+ - name: Get deployer token
+ id: deployer
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ secrets.GH_APP_CHARTS_DEPLOYER_APP_ID }}
+ private-key: ${{ secrets.GH_APP_CHARTS_DEPLOYER_PRIVATE_KEY }}
+ owner: PostHog
+ repositories: charts
+
+ - name: Get PR labels
+ id: labels
+ uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
+ with:
+ script: |
+ const { data: pulls } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ commit_sha: context.sha,
+ });
+ const labels = pulls.flatMap(pr => pr.labels.map(l => l.name));
+ return JSON.stringify([...new Set(labels)]);
+
+ - name: Trigger MCP deployment
+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1
+ with:
+ token: ${{ steps.deployer.outputs.token }}
+ repository: PostHog/charts
+ event-type: commit_state_update
+ client-payload: |
+ {
+ "values": {
+ "image": {
+ "sha": "${{ needs.build.outputs.sha }}"
+ }
+ },
+ "release": "mcp",
+ "commit": ${{ toJson(github.event.head_commit) }},
+ "repository": ${{ toJson(github.repository) }},
+ "labels": ${{ steps.labels.outputs.result }},
+ "timestamp": "${{ github.event.head_commit.timestamp }}"
+ }
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index acf9c43deb8a..aeb89db1f460 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -198,6 +198,9 @@ jobs:
exit 1
fi
+ - name: Run Hono unit tests
+ run: cd services/mcp && pnpm run test:hono
+
- name: Create snapshot patch
id: create-snapshot-patch
if: ${{ always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && !contains(github.actor, '[bot]') && github.actor != 'posthog-bot' && !contains(github.actor, 'github-actions') }}
@@ -459,7 +462,7 @@ jobs:
PersonalAPIKey.objects.create(
user=user,
label='mcp_ci_api_key',
- secure_value=hash_key_value('e2e_demo_api_key'),
+ secure_value=hash_key_value('phx_e2e_demo_api_key'),
scopes=['*'],
)
# Ensure common event definitions exist for MCP integration tests
@@ -491,7 +494,7 @@ jobs:
run: cd services/mcp && pnpm run test:integration
env:
TEST_POSTHOG_API_BASE_URL: http://localhost:8000
- TEST_POSTHOG_PERSONAL_API_KEY: e2e_demo_api_key
+ TEST_POSTHOG_PERSONAL_API_KEY: phx_e2e_demo_api_key
TEST_ORG_ID: ${{ env.TEST_ORG_ID }}
TEST_PROJECT_ID: ${{ env.TEST_PROJECT_ID }}
diff --git a/bin/start-mcp-server b/bin/start-mcp-server
index 0291482ec4b8..0f473ab85d6d 100755
--- a/bin/start-mcp-server
+++ b/bin/start-mcp-server
@@ -3,10 +3,17 @@ set -euo pipefail
cd "$(dirname "$0")/../services/mcp"
-if [ ! -f .dev.vars ]; then
- cp .dev.vars.example .dev.vars
-fi
+RUNTIME="${MCP_RUNTIME:-cloudflare}"
pnpm install --frozen-lockfile
-exec pnpm run dev
+if [ "$RUNTIME" = "hono" ]; then
+ export REDIS_URL="${REDIS_URL:-redis://localhost:6379}"
+ export PORT="${PORT:-3030}"
+ exec pnpm run dev:hono
+else
+ if [ ! -f .dev.vars ]; then
+ cp .dev.vars.example .dev.vars
+ fi
+ exec pnpm run dev
+fi
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 62e210cb73cb..35bc8f94e93f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3509,6 +3509,9 @@ importers:
services/mcp:
dependencies:
+ '@hono/node-server':
+ specifier: ^2.0.2
+ version: 2.0.2([email protected])
'@modelcontextprotocol/ext-apps':
specifier: ^1.5.0
@@ -3530,12 +3533,21 @@ importers:
ai:
specifier: ^6.0.0
version: 6.0.77([email protected])
+ esbuild:
+ specifier: ^0.25.10
+ version: 0.25.10
eventsource-parser:
specifier: ^3.0.0
version: 3.0.6
fflate:
specifier: ^0.8.2
version: 0.8.2
+ hono:
+ specifier: ^4.12.18
+ version: 4.12.18
+ ioredis:
+ specifier: ^4.28.5
+ version: 4.28.5
lucide-react:
specifier: ^0.577.0
version: 0.577.0([email protected])
@@ -3548,6 +3560,9 @@ importers:
posthog-node:
specifier: ^5.25.0
version: 5.25.0
+ prom-client:
+ specifier: ^14.2.0
+ version: 14.2.0
uuid:
specifier: ^11.1.0
version: 11.1.0
@@ -6662,6 +6677,12 @@ packages:
peerDependencies:
hono: ^4
+ resolution: {integrity: sha512-tXlTi1h/4V7sDe7i97IVP+9re9ZU7wXZZggnR5ucCRclf1+AX6YhGStrR5w8bLj+3Mlyl0pKfBh9gqTqqnGKfQ==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ hono: ^4
+
'@humanwhocodes/[email protected]':
resolution: {integrity: sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==}
engines: {node: '>=10.10.0'}
@@ -16359,8 +16380,8 @@ packages:
resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-eVkB/CYCCei7K2WElZW9yYQFWssG0DhaDhVvr7wy5jJ22K+ck8fWW0EsLpB0sITUTvPnc97+rrbQqIr5iqiy9Q==}
+ resolution: {integrity: sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==}
engines: {node: '>=16.9.0'}
@@ -29010,9 +29031,13 @@ snapshots:
dependencies:
'@hapi/hoek': 9.3.0
dependencies:
- hono: 4.11.8
+ hono: 4.12.18
+
+ dependencies:
+ hono: 4.12.18
'@humanwhocodes/[email protected]':
dependencies:
@@ -30079,7 +30104,7 @@ snapshots:
'@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])':
dependencies:
- '@hono/node-server': 1.19.14([email protected])
+ '@hono/node-server': 1.19.14([email protected])
ajv: 8.18.0
ajv-formats: 3.0.1([email protected])
content-type: 1.0.5
@@ -30089,7 +30114,7 @@ snapshots:
eventsource-parser: 3.0.6
express: 5.2.1
express-rate-limit: 8.2.1([email protected])
- hono: 4.11.8
+ hono: 4.12.18
jose: 6.1.3
json-schema-typed: 8.0.2
pkce-challenge: 5.0.0
@@ -41360,7 +41385,7 @@ snapshots:
dependencies:
parse-passwd: 1.0.0
@@ -41684,7 +41709,7 @@ snapshots:
dependencies:
cluster-key-slot: 1.1.2
- debug: 4.3.4
+ debug: 4.4.3
denque: 1.5.1
lodash.defaults: 4.2.0
lodash.flatten: 4.4.0
diff --git a/services/mcp/.dockerignore b/services/mcp/.dockerignore
new file mode 100644
index 000000000000..f7e9c2de252a
--- /dev/null
+++ b/services/mcp/.dockerignore
@@ -0,0 +1,23 @@
+# Keep the build context tight — only the directories the build actually needs.
+# The build stage copies `services/mcp/` plus the workspace lockfile and root
+# package.json. Anything else here is ballast.
+
+**
+
+!package.json
+!tsconfig.json
+!worker-configuration.d.ts
+!types.d.ts
+!scripts/**
+!src/**
+!shared/**
+!public/**
+
+# Test/dev artefacts must NOT enter the production image.
+tests/**
+.env*
+dist/**
+.wrangler/**
+node_modules/**
+.vitest/**
+.turbo/**
diff --git a/services/mcp/Dockerfile b/services/mcp/Dockerfile
index e389a99e904b..aa0f59212b52 100644
--- a/services/mcp/Dockerfile
+++ b/services/mcp/Dockerfile
@@ -1,17 +1,84 @@
-# Use a lightweight Node.js image
-FROM node:20-slim
+# PostHog MCP server (Hono / Node.js).
+#
+# Production runtime image. Build context is the repo root so we can install
+# dependencies through the pnpm workspace.
+#
+# docker build -f services/mcp/Dockerfile -t posthog-mcp .
+#
+# The legacy `Dockerfile.proxy` in this directory is for the `mcp-remote` CLI
+# proxy distribution, not the server — different artifact, don't confuse them.
-# Set the working directory inside the container
-WORKDIR /usr/src/app
+# Pin the same Node version as the rest of the monorepo (.nvmrc).
+ARG NODE_VERSION=24.13.0
+ARG NODE_IMAGE=node:${NODE_VERSION}-bookworm-slim
-# Install mcp-remote globally to avoid npx overhead on each run
-RUN npm install -g mcp-remote@latest
+#
+# Build stage — install workspace deps, bundle the Hono entry into a single .mjs.
+# Everything (including ioredis) is bundled, so the runtime stage doesn't need
+# `node_modules` at all.
+#
+FROM ${NODE_IMAGE} AS build
+WORKDIR /code
-# Set default environment variable for POSTHOG_REMOTE_MCP_URL
-ENV POSTHOG_REMOTE_MCP_URL=https://mcp.posthog.com/mcp
+# `corepack enable` reads the `packageManager` field in package.json to pick the
+# pnpm version — no `corepack prepare pnpm@latest` (non-deterministic).
+RUN corepack enable
+
+# Copy lockfile + workspace manifests first so the install layer caches across
+# unrelated source changes. `patches/` is required because pnpm-lock.yaml
+# references workspace-level patch files (e.g. `[email protected]`).
+# Root `tsconfig.json` is needed because product tsconfigs (`products/*/tsconfig.json`)
+# extend it via relative path; vite reads it during the UI apps build.
+COPY pnpm-lock.yaml pnpm-workspace.yaml package.json tsconfig.json ./
+COPY patches/ patches/
+
+# pnpm needs every referenced workspace package's `package.json` BEFORE install
+# so it can build the dependency graph and link transitive workspace deps. We
+# do this in two passes: manifests first (cache-friendly install layer), then
+# source after, so source edits don't bust the install cache.
+COPY services/mcp/package.json services/mcp/package.json
+COPY tools/openapi-codegen/package.json tools/openapi-codegen/package.json
+# UI apps depend on @posthog/quill — copy all its workspace manifests so pnpm
+# can resolve the full dependency graph during install.
+COPY packages/ packages/
+
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
+ pnpm install --frozen-lockfile --filter @posthog/mcp...
+
+COPY services/mcp/ services/mcp/
+COPY tools/openapi-codegen/ tools/openapi-codegen/
+# `scripts/build-ui-apps.ts` imports React components from `products/<x>/mcp/apps/`
+# (the generator scans `products/*/mcp/tools.yaml` and synthesizes entry points),
+# so the whole `products/` tree needs to be in the build context.
+COPY products/ products/
+WORKDIR /code/services/mcp
+RUN pnpm exec tsx scripts/build-hono.ts && pnpm run build:ui-apps
+
+#
+# Runtime stage — minimal slim image with just the bundle.
+#
+FROM ${NODE_IMAGE}
+WORKDIR /code
+
+# Commit hash burned in for incident triage; matches the convention in
+# Dockerfile.node.
+ARG COMMIT_HASH
+RUN echo "${COMMIT_HASH:-unknown}" > /code/commit.txt
+
+# Bundle is fully self-contained — ioredis and everything else is inlined.
+COPY --from=build --chown=node:node /code/services/mcp/dist/hono-server.mjs ./hono-server.mjs
+COPY --from=build --chown=node:node /code/services/mcp/dist/hono-server.mjs.map ./hono-server.mjs.map
+# UI app static assets — served at `/ui-apps/<app>/...` by `serveStatic` in app.ts.
+COPY --from=build --chown=node:node /code/services/mcp/public/ ./public/
+
+ENV NODE_ENV=production \
+ PORT=3001
+
+EXPOSE 3001
+
+# Liveness/readiness are handled by the orchestrator (k8s probes hit /healthz
+# and /readyz). No HEALTHCHECK directive — keeps the image free of curl etc.
USER node
-# The entrypoint will run mcp-remote with proper stdio handling
-# POSTHOG_AUTH_HEADER should be just the token (e.g., phx_...), we'll add "Bearer " prefix
-ENTRYPOINT ["sh", "-c", "mcp-remote \"${POSTHOG_REMOTE_MCP_URL}\" --header \"Authorization:Bearer ${POSTHOG_AUTH_HEADER}\""]
+CMD ["node", "hono-server.mjs"]
diff --git a/services/mcp/README.md b/services/mcp/README.md
index e2875b8192bf..860cd9b8f84b 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -99,60 +99,6 @@ await client.close()
See also the main PostHog MCP docs for available tools and setup flows: [https://posthog.com/docs/model-context-protocol](https://posthog.com/docs/model-context-protocol)
-### Docker install
-
-If you prefer to use Docker instead of running npx directly:
-
-1. Build the Docker image:
-
-```bash
-pnpm docker:build
-# or
-docker build -t posthog-mcp .
-```
-
-2. Configure your MCP client with Docker:
-
-```json
-{
- "mcpServers": {
- "posthog": {
- "type": "stdio",
- "command": "docker",
- "args": [
- "run",
- "-i",
- "--rm",
- "--env",
- "POSTHOG_AUTH_HEADER=${POSTHOG_AUTH_HEADER}",
- "--env",
- "POSTHOG_REMOTE_MCP_URL=${POSTHOG_REMOTE_MCP_URL:-https://mcp.posthog.com/mcp}",
- "posthog-mcp"
- ],
- "env": {
- "POSTHOG_AUTH_HEADER": "Bearer {INSERT_YOUR_PERSONAL_API_KEY_HERE}",
- "POSTHOG_REMOTE_MCP_URL": "https://mcp.posthog.com/mcp"
- }
- }
- }
-}
-```
-
-3. Test Docker with MCP Inspector:
-
-```bash
-pnpm docker:inspector
-# or
-npx @modelcontextprotocol/inspector docker run -i --rm --env POSTHOG_AUTH_HEADER=${POSTHOG_AUTH_HEADER} posthog-mcp
-```
-
-**Environment Variables:**
-
-- `POSTHOG_AUTH_HEADER`: Your PostHog API token (required)
-- `POSTHOG_REMOTE_MCP_URL`: The MCP server URL (optional, defaults to `https://mcp.posthog.com/mcp`)
-
-This approach allows you to use the PostHog MCP server without needing Node.js or npm installed locally.
-
### Example Prompts
Below are detailed examples showing realistic prompts and expected outputs:
@@ -373,6 +319,18 @@ pnpm run dev
And replace `https://mcp.posthog.com/mcp` with `http://localhost:8787/mcp` in the MCP configuration.
+### Hono runtime (Node)
+
+Alongside the Cloudflare Workers entry point, the same MCP code runs on Node via Hono — this is what ships to our k8s clusters. Useful locally when you want a CF-runtime-free debugger, fewer Wrangler quirks, or to repro a k8s-only bug.
+
+```bash
+pnpm run dev:hono
+```
+
+Defaults to port **3030**, reads config from `.env` (Node-only — separate from `.dev.vars`, which Wrangler reads), and expects a local Redis on port `6379` (used in place of Durable Objects for session state) for local development; production deployments must set `REDIS_URL` to a TLS-encrypted `rediss://` endpoint. Same routes as the CF server — point your client at `http://localhost:3030/mcp`.
+
+`bin/start-mcp-server` runs the Wrangler/CF version by default; set `MCP_RUNTIME=hono` to start the Hono runtime instead.
+
### Developing with local resources
To develop with warm loading for MCP resources (workflows, prompts, examples):
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 0d26a2ad775f..0cfe505f5e73 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -23,8 +23,11 @@
"deploy": "wrangler deploy",
"cf-typegen": "wrangler types",
"inspector": "npx @modelcontextprotocol/inspector npx -y mcp-remote@latest http://localhost:8787/mcp",
+ "build:hono": "tsx scripts/build-hono.ts",
+ "dev:hono": "tsx scripts/dev-hono.ts",
"test": "vitest",
"test:integration": "vitest run --config vitest.integration.config.mts",
+ "test:hono": "vitest run --config vitest.hono.config.mts",
"test:watch": "vitest watch",
"typecheck": "tsc --noEmit",
"generate-mcp-types": "node scripts/generate-mcp-types.mjs",
@@ -35,6 +38,7 @@
"format": "oxlint --fix --fix-suggestions --fix-dangerously --quiet && oxfmt \"./**/*.{js,mjs,ts,tsx,json,yaml,yml,css,scss}\""
},
"dependencies": {
+ "@hono/node-server": "^2.0.2",
"@modelcontextprotocol/ext-apps": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"@posthog/mcp-analytics": "npm:@posthog/[email protected]",
@@ -42,12 +46,16 @@
"@toon-format/toon": "^2.1.0",
"agents": "0.10.2",
"ai": "^6.0.0",
+ "esbuild": "^0.25.10",
"eventsource-parser": "^3.0.0",
"fflate": "^0.8.2",
+ "hono": "^4.12.18",
+ "ioredis": "^4.28.5",
"lucide-react": "^0.577.0",
"mcpcat": "0.1.15",
"posthog-js-lite": "4.2.2",
"posthog-node": "^5.25.0",
+ "prom-client": "^14.2.0",
"uuid": "^11.1.0",
"yaml": "^2.8.2",
"zod": "^4.3.6"
diff --git a/services/mcp/scripts/build-hono.ts b/services/mcp/scripts/build-hono.ts
new file mode 100644
index 000000000000..50257edb321d
--- /dev/null
+++ b/services/mcp/scripts/build-hono.ts
@@ -0,0 +1,12 @@
+import { build } from 'esbuild'
+
+import { honoEsbuildOptions, honoOutfile } from './hono-esbuild-config'
+
+build(honoEsbuildOptions())
+ .then(() => {
+ console.info(`Built MCP server → ${honoOutfile}`)
+ })
+ .catch((err: unknown) => {
+ console.error('Build failed:', err)
+ process.exit(1)
+ })
diff --git a/services/mcp/scripts/dev-hono.ts b/services/mcp/scripts/dev-hono.ts
new file mode 100644
index 000000000000..bd19438905e0
--- /dev/null
+++ b/services/mcp/scripts/dev-hono.ts
@@ -0,0 +1,88 @@
+import { spawn, type ChildProcess } from 'child_process'
+import { context, type Plugin } from 'esbuild'
+// esbuild watch + node respawn — same bundling pipeline as build-hono.ts so
+// dev and prod behave identically. tsx isn't used directly because it can't
+// load the `.md` template imports or stub the `cloudflare:workers` builtin.
+import { existsSync } from 'fs'
+import { resolve } from 'path'
+
+import { honoEsbuildOptions, honoOutfile } from './hono-esbuild-config'
+
+if (existsSync(resolve(process.cwd(), '.env'))) {
+ process.loadEnvFile(resolve(process.cwd(), '.env'))
+}
+
+// flox sets SSL_CERT_FILE; Node's TLS layer only reads NODE_EXTRA_CA_CERTS.
+if (!process.env.NODE_EXTRA_CA_CERTS && process.env.SSL_CERT_FILE) {
+ process.env.NODE_EXTRA_CA_CERTS = process.env.SSL_CERT_FILE
+}
+
+let child: ChildProcess | undefined
+
+const killChild = (): Promise<void> => {
+ return new Promise((resolve) => {
+ if (!child) {
+ resolve()
+ return
+ }
+ const proc = child
+ child = undefined
+ proc.removeAllListeners()
+ proc.on('exit', () => resolve())
+ proc.kill('SIGTERM')
+ })
+}
+
+const launch = async (): Promise<void> => {
+ await killChild()
+ child = spawn(process.execPath, [honoOutfile], {
+ stdio: 'inherit',
+ env: { ...process.env, SHUTDOWN_PRESTOP_DELAY_MS: '0' },
+ })
+ child.on('exit', (code, signal) => {
+ if (signal === 'SIGTERM') {
+ return
+ }
+ if (code !== 0) {
+ console.warn(`[dev-hono] node exited with code=${code}; waiting for next rebuild...`)
+ }
+ })
+}
+
+const restartPlugin: Plugin = {
+ name: 'dev-hono-restart',
+ setup(build): void {
+ build.onEnd((result) => {
+ if (result.errors.length > 0) {
+ console.error(`[dev-hono] build failed with ${result.errors.length} error(s); not restarting`)
+ return
+ }
+ void launch()
+ })
+ },
+}
+
+async function main(): Promise<void> {
+ const ctx = await context({
+ ...honoEsbuildOptions({ dev: true, extraPlugins: [restartPlugin] }),
+ logLevel: 'info',
+ })
+
+ const shutdown = async (): Promise<void> => {
+ if (child) {
+ child.kill('SIGTERM')
+ }
+ await ctx.dispose()
+ process.exit(0)
+ }
+ process.on('SIGINT', shutdown)
+ process.on('SIGTERM', shutdown)
+
+ await ctx.watch()
+ console.info('[dev-hono] watching src/hono/** for changes')
+}
+
+main().catch((err: unknown) => {
+ console.error('[dev-hono] fatal:', err)
+ process.exit(1)
+})
diff --git a/services/mcp/scripts/hono-esbuild-config.ts b/services/mcp/scripts/hono-esbuild-config.ts
new file mode 100644
index 000000000000..276177c97680
--- /dev/null
+++ b/services/mcp/scripts/hono-esbuild-config.ts
@@ -0,0 +1,44 @@
+import type { BuildOptions, Plugin } from 'esbuild'
+// Shared esbuild config for the Hono runtime. `build-hono.ts` runs it once for
+// production; `dev-hono.ts` wraps it in `context().watch()` for the dev loop.
+//
+// No externals: ioredis and every other prod dep is pure-JS (or has a Node-target
+// shim esbuild handles). Bundling everything lets the runtime image ship a single
+// .mjs with no node_modules at all.
+import { resolve } from 'path'
+
+export const honoOutfile = resolve(process.cwd(), 'dist/hono-server.mjs')
+
+const cfWorkersStub: Plugin = {
+ name: 'cf-workers-stub',
+ setup(build): void {
+ build.onResolve({ filter: /^cloudflare:workers$/ }, () => ({
+ path: 'cloudflare:workers',
+ namespace: 'cf-stub',
+ }))
+ build.onLoad({ filter: /.*/, namespace: 'cf-stub' }, () => ({
+ contents: 'export const env = undefined',
+ loader: 'js',
+ }))
+ },
+}
+
+export function honoEsbuildOptions(opts: { dev?: boolean; extraPlugins?: Plugin[] } = {}): BuildOptions {
+ return {
+ entryPoints: [resolve(process.cwd(), 'src/hono/index.ts')],
+ bundle: true,
+ platform: 'node',
+ target: 'node22',
+ format: 'esm',
+ outfile: honoOutfile,
+ sourcemap: true,
+ external: [],
+ plugins: [cfWorkersStub, ...(opts.extraPlugins ?? [])],
+ loader: { '.html': 'text', '.md': 'text', '.json': 'json' },
+ define: { 'process.env.NODE_ENV': opts.dev ? '"development"' : '"production"' },
+ // Bundled CJS modules (e.g. ioredis using `require('util')`) call through
+ // to a global `require`. ESM has no `require`; banner injects one. The
+ // alias avoids colliding with esbuild's own CJS-interop shim.
+ banner: { js: `import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);` },
+ }
+}
diff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.ts
new file mode 100644
index 000000000000..9f3da173c153
--- /dev/null
+++ b/services/mcp/src/hono/app.ts
@@ -0,0 +1,39 @@
+import { Hono } from 'hono'
+
+import { httpMetrics, securityHeaders } from './middleware'
+import { registerPublicRoutes } from './public-routes'
+import { StreamableMcpHandler } from './streamable-handler'
+import type { HonoCtx, RedisWithPing } from './types'
+
+export type Lifecycle = { shuttingDown: boolean }
+
+export type App = {
+ app: Hono
+ lifecycle: Lifecycle
+}
+
+export function createApp(redis: RedisWithPing): App {
+ const app = new Hono()
+ const lifecycle: Lifecycle = { shuttingDown: false }
+
+ app.use('*', securityHeaders)
+ app.use('*', httpMetrics)
+
+ registerPublicRoutes(app, redis, lifecycle)
+
+ const sseRedirect = (c: HonoCtx): Response => {
+ const target = new URL(c.req.url)
+ target.pathname = '/mcp' + target.pathname.slice('/sse'.length)
+ target.searchParams.set('_deprecated', 'sse')
+ return c.redirect(target.toString(), 308) as unknown as Response
+ }
+ app.all('/sse', sseRedirect)
+ app.all('/sse/*', sseRedirect)
+
+ const streamable = new StreamableMcpHandler(redis, lifecycle)
+ app.all('/mcp', streamable.fetch)
+ app.all('/mcp/*', streamable.fetch)
+
+ app.all('*', (c) => c.notFound())
+ return { app, lifecycle }
+}
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.ts
new file mode 100644
index 000000000000..ef2c21e54fae
--- /dev/null
+++ b/services/mcp/src/hono/cache/RedisCache.ts
@@ -0,0 +1,75 @@
+import { ScopedCache } from '@/lib/cache/ScopedCache'
+
+export interface RedisLike {
+ get(key: string): Promise<string | null>
+ set(key: string, value: string, ...args: (string | number)[]): Promise<string | null>
+ del(...keys: string[]): Promise<number>
+ unlink?(...keys: string[]): Promise<number>
+ scan(cursor: string | number, ...args: (string | number)[]): Promise<[cursor: string, keys: string[]]>
+}
+
+const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days
+// Cap on clear()'s SCAN/UNLINK pass. A user with more than this many cache
+// entries either deserves an explicit GC pass or is misbehaving — either way
+// we don't want a single request to stall on an unbounded loop.
+const CLEAR_MAX_ITERATIONS = 50
+const CLEAR_SCAN_COUNT = 100
+
+export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {
+ private redis: RedisLike
+ private ttl: number
+
+ constructor(scope: string, redis: RedisLike, ttlSeconds: number = DEFAULT_TTL_SECONDS) {
+ super(scope)
+ this.redis = redis
+ this.ttl = ttlSeconds
+ }
+
+ private getScopedKey(key: string): string {
+ return `mcp:user:${this.scope}:${key}`
+ }
+
+ async get<K extends keyof T>(key: K): Promise<T[K] | undefined> {
+ const scopedKey = this.getScopedKey(key as string)
+ const raw = await this.redis.get(scopedKey)
+ if (raw === null) {
+ return undefined
+ }
+ return JSON.parse(raw) as T[K]
+ }
+
+ async set<K extends keyof T>(key: K, value: T[K]): Promise<void> {
+ const scopedKey = this.getScopedKey(key as string)
+ await this.redis.set(scopedKey, JSON.stringify(value), 'EX', this.ttl)
+ }
+
+ async delete<K extends keyof T>(key: K): Promise<void> {
+ const scopedKey = this.getScopedKey(key as string)
+ await this.redis.del(scopedKey)
+ }
+
+ async clear(): Promise<void> {
+ const pattern = `mcp:user:${this.scope}:*`
+ let cursor = '0'
+ // UNLINK lets Redis free memory in a background thread; falls back to DEL
+ // for clients that don't expose it. Iteration cap is a guard against
+ // pathological scans on outlier accounts — a partial clear is acceptable
+ // (the remaining entries will TTL-evict).
+ const unlink = this.redis.unlink?.bind(this.redis) ?? this.redis.del.bind(this.redis)
+ for (let i = 0; i < CLEAR_MAX_ITERATIONS; i += 1) {
+ const [nextCursor, keys] = await this.redis.scan(cursor, 'MATCH', pattern, 'COUNT', CLEAR_SCAN_COUNT)
+ cursor = nextCursor
+ if (keys.length > 0) {
+ try {
+ await unlink(...keys)
+ } catch (err) {
+ console.error('[RedisCache] clear() failed mid-iteration:', err)
+ }
+ }
+ if (cursor === '0') {
+ return
+ }
+ }
+ console.warn(`[RedisCache] clear() hit iteration cap (${CLEAR_MAX_ITERATIONS}); remaining keys will TTL-evict`)
+ }
+}
diff --git a/services/mcp/src/hono/constants.ts b/services/mcp/src/hono/constants.ts
new file mode 100644
index 000000000000..a38b4dbaabf0
--- /dev/null
+++ b/services/mcp/src/hono/constants.ts
@@ -0,0 +1,41 @@
+import type { Env } from '@/tools/types'
+
+export {
+ USER_AGENT,
+ type GetUserAgentOptions,
+ getUserAgent,
+ POSTHOG_US_BASE_URL,
+ POSTHOG_EU_BASE_URL,
+ toCloudRegion,
+ getBaseUrlForRegion,
+ getCustomApiBaseUrl,
+ getAuthorizationServerUrl,
+ MCP_DOCS_URL,
+ OAUTH_PROXY_URL,
+ OAUTH_SCOPES_SUPPORTED,
+} from '@/lib/constants'
+
+export function getEnv(): Env {
+ const extras: Record<string, string | undefined> = {}
+ if (process.env.TEST) {
+ extras.TEST = process.env.TEST
+ }
+ return {
+ POSTHOG_API_BASE_URL: process.env.POSTHOG_API_BASE_URL || undefined,
+ MCP_APPS_BASE_URL: process.env.MCP_APPS_BASE_URL || undefined,
+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: process.env.POSTHOG_MCP_APPS_ANALYTICS_BASE_URL || undefined,
+ POSTHOG_UI_APPS_TOKEN: process.env.POSTHOG_UI_APPS_TOKEN || undefined,
+ POSTHOG_ANALYTICS_API_KEY: process.env.POSTHOG_ANALYTICS_API_KEY || undefined,
+ POSTHOG_ANALYTICS_HOST: process.env.POSTHOG_ANALYTICS_HOST || undefined,
+ ...extras,
+ }
+}
+
+export const AUTH_REDIRECT_PATHS = [
+ '/.well-known/oauth-authorization-server',
+ '/.well-known/jwks.json',
+ '/oauth/*',
+ '/register',
+ '/authorize',
+ '/token',
+] as const
diff --git a/services/mcp/src/hono/index.ts b/services/mcp/src/hono/index.ts
new file mode 100644
index 000000000000..2c14f57a3241
--- /dev/null
+++ b/services/mcp/src/hono/index.ts
@@ -0,0 +1,62 @@
+import { serve } from '@hono/node-server'
+import Redis from 'ioredis'
+
+import { createApp } from './app'
+import { registerShutdownHandlers } from './shutdown'
+
+const PORT = parseInt(process.env.PORT || '3001', 10)
+const HOST = process.env.HOST || '0.0.0.0'
+
+function resolveRedisUrl(): string {
+ const url = process.env.REDIS_URL
+ if (url) {
+ return url
+ }
+ if (process.env.NODE_ENV === 'production') {
+ console.error('[MCP] REDIS_URL is required in production')
+ process.exit(1)
+ }
+ // Local dev fallback only — production refuses to start without REDIS_URL above.
+ // nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
+ return 'redis://localhost:6379'
+}
+
+const redis = new Redis(resolveRedisUrl(), {
+ lazyConnect: true,
+ maxRetriesPerRequest: 3,
+ enableOfflineQueue: false,
+ connectTimeout: 5000,
+ commandTimeout: 2000,
+ keepAlive: 30000,
+ retryStrategy: (times: number) => Math.min(times * 200, 2000),
+})
+
+redis.on('error', (err: Error) => {
+ console.error('[MCP] Redis connection error:', err.message)
+})
+
+redis.on('connect', () => {
+ console.info('[MCP] Redis connected')
+})
+
+async function main(): Promise<void> {
+ try {
+ await redis.connect()
+ } catch (err) {
+ console.error('[MCP] Failed to connect to Redis:', err)
+ process.exit(1)
+ }
+
+ const { app, lifecycle } = createApp(redis as unknown as Parameters<typeof createApp>[0])
+
+ const server = serve({ fetch: app.fetch, port: PORT, hostname: HOST }, (info) => {
+ console.info(`[MCP] Server started on ${HOST}:${info.port}`)
+ })
+
+ registerShutdownHandlers({ server, lifecycle, redis })
+}
+
+main().catch((err) => {
+ console.error('[MCP] Fatal error:', err)
+ process.exit(1)
+})
diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.ts
new file mode 100644
index 000000000000..2847140be090
--- /dev/null
+++ b/services/mcp/src/hono/mcp-server.ts
@@ -0,0 +1,753 @@
+import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
+import { McpServer, type ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js'
+import type { z } from 'zod'
+
+import { ApiClient } from '@/api/client'
+import {
+ AnalyticsEvent,
+ buildMCPAnalyticsGroups,
+ buildMCPContextProperties,
+ evaluateFeatureFlags,
+ getPostHogClient,
+ isFeatureFlagEnabled,
+ type MCPAnalyticsContext,
+} from '@/lib/analytics'
+import { hasScope } from '@/lib/api'
+import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'
+import { MCPClientProfile } from '@/lib/client-detection'
+import { handleToolError, wrapError } from '@/lib/errors'
+import { type QueryToolInfo } from '@/lib/instructions'
+import { InstructionsFormatter } from '@/lib/instructions-formatter'
+import { initMcpCatObservability } from '@/lib/mcpcat'
+import { type RequestProperties } from '@/lib/request-properties'
+import { SessionManager } from '@/lib/SessionManager'
+import { StateManager } from '@/lib/StateManager'
+import { formatPrompt, type McpMode } from '@/lib/utils'
+import { registerPrompts } from '@/prompts'
+import { registerResources } from '@/resources'
+import { registerUiAppResources } from '@/resources/ui-apps'
+import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
+import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'
+import { getToolDefinition } from '@/tools/toolDefinitions'
+import { type CloudRegion, type Context, type Env, type State, type Tool } from '@/tools/types'
+
+import { RedisCache, type RedisLike } from './cache/RedisCache'
+import {
+ getCustomApiBaseUrl,
+ POSTHOG_EU_BASE_URL,
+ POSTHOG_US_BASE_URL,
+ getBaseUrlForRegion,
+ getEnv,
+ toCloudRegion,
+} from './constants'
+import { initDurationSeconds, toolCallDurationSeconds, toolCallsTotal } from './metrics'
+
+export type { RequestProperties }
+
+const instructionsFormatter = new InstructionsFormatter()
+const POSTHOG_MCP_ANALYTICS_FLAG = 'mcp-posthog-analytics-sdk'
+type McpAnalyticsProvider = 'posthog_mcp_analytics' | 'mcpcat'
+type PostHogMcpAnalyticsFlagResult = {
+ enabled: boolean
+ errorName?: string
+ errorMessage?: string
+}
+
+type HonoRequestProperties = RequestProperties & {
+ mcpAnalyticsProvider?: McpAnalyticsProvider | undefined
+ mcpAnalyticsFlagKey?: string | undefined
+ mcpAnalyticsFlagEnabled?: boolean | undefined
+ mcpAnalyticsFlagErrorName?: string | undefined
+ mcpAnalyticsFlagErrorMessage?: string | undefined
+ posthogMcpAnalyticsInitAction?: 'initialized' | 'skipped' | 'failed' | undefined
+ posthogMcpAnalyticsInitReason?: string | undefined
+ posthogMcpAnalyticsInitErrorName?: string | undefined
+ posthogMcpAnalyticsInitErrorMessage?: string | undefined
+}
+
+// Guidelines are generated at build time; optional import so tests and
+// unbundled dev runs don't explode when the file is absent.
+let _guidelines = ''
+try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const mod = require('@shared/guidelines.md')
+ _guidelines = typeof mod === 'string' ? mod : (mod?.default ?? '')
+} catch {
+ _guidelines = ''
+}
+
+export class HonoMcpServer {
+ server: McpServer
+
+ private props: HonoRequestProperties
+
+ private _cache: RedisCache<State> | undefined
+
+ private _api: ApiClient | undefined
+
+ private _sessionManager: SessionManager | undefined
+
+ private redis: RedisLike
+
+ private env: Env
+
+ private clientInfoResolved = false
+ private mcpClientName: string | undefined
+ private mcpClientVersion: string | undefined
+ private mcpProtocolVersion: string | undefined
+ private mcpMode: McpMode | undefined
+ private mcpVersion: number | undefined
+
+ constructor(redis: RedisLike, props: RequestProperties) {
+ this.props = props
+ this.redis = redis
+ this.env = getEnv()
+ this.server = new McpServer(
+ { name: 'PostHog', version: '1.0.0' },
+ { instructions: instructionsFormatter.buildV1Instructions() }
+ )
+ }
+
+ get requestProperties(): HonoRequestProperties {
+ return this.props
+ }
+
+ get cache(): RedisCache<State> {
+ if (!this.props.userHash) {
+ throw new Error('User hash is required to use the cache')
+ }
+
+ if (!this._cache) {
+ this._cache = new RedisCache<State>(this.props.userHash, this.redis)
+ }
+
+ return this._cache
+ }
+
+ get sessionManager(): SessionManager {
+ if (!this._sessionManager) {
+ this._sessionManager = new SessionManager(this.cache)
+ }
+
+ return this._sessionManager
+ }
+
+ async resolveClientInfo(): Promise<void> {
+ if (this.clientInfoResolved) {
+ return
+ }
+
+ const { mcpClientName, mcpClientVersion, mcpProtocolVersion } = this.props
+ if (mcpClientName || mcpClientVersion) {
+ this.mcpClientName = mcpClientName
+ this.mcpClientVersion = mcpClientVersion
+ this.mcpProtocolVersion = mcpProtocolVersion
+ this.clientInfoResolved = true
+ }
+ }
+
+ async detectRegion(): Promise<CloudRegion | undefined> {
+ const usClient = new ApiClient({
+ apiToken: this.props.apiToken,
+ baseUrl: POSTHOG_US_BASE_URL,
+ })
+
+ const euClient = new ApiClient({
+ apiToken: this.props.apiToken,
+ baseUrl: POSTHOG_EU_BASE_URL,
+ })
+
+ const [usResult, euResult] = await Promise.all([usClient.users().me(), euClient.users().me()])
+
+ if (usResult.success) {
+ await this.cache.set('region', 'us')
+ return 'us'
+ }
+
+ if (euResult.success) {
+ await this.cache.set('region', 'eu')
+ return 'eu'
+ }
+
+ return undefined
+ }
+
+ async getBaseUrl(): Promise<string> {
+ const customApiBaseUrl = getCustomApiBaseUrl()
+ if (customApiBaseUrl) {
+ return customApiBaseUrl
+ }
+
+ const propsRegion = this.props.region
+ if (propsRegion) {
+ const region = toCloudRegion(propsRegion)
+ await this.cache.set('region', region)
+ return getBaseUrlForRegion(region)
+ }
+
+ const cachedRegion = await this.cache.get('region')
+ const region = cachedRegion ? toCloudRegion(cachedRegion) : await this.detectRegion()
+
+ return getBaseUrlForRegion(region || 'us')
+ }
+
+ async api(): Promise<ApiClient> {
+ if (!this._api) {
+ const baseUrl = await this.getBaseUrl()
+ await this.resolveClientInfo()
+ this._api = new ApiClient({
+ apiToken: this.props.apiToken,
+ baseUrl,
+ clientUserAgent: this.props.clientUserAgent,
+ mcpClientName: this.mcpClientName,
+ mcpClientVersion: this.mcpClientVersion,
+ mcpProtocolVersion: this.mcpProtocolVersion,
+ mcpConsumer: this.props.mcpConsumer,
+ })
+ }
+
+ return this._api
+ }
+
+ async getDistinctId(): Promise<string> {
+ let _distinctId = await this.cache.get('distinctId')
+
+ if (!_distinctId) {
+ const userResult = await (await this.api()).users().me()
+ if (!userResult.success) {
+ throw wrapError(`Failed to get user: ${userResult.error.message}`, userResult.error)
+ }
+ await this.cache.set('distinctId', userResult.data.distinct_id)
+ _distinctId = userResult.data.distinct_id as string
+ }
+
+ return _distinctId
+ }
+
+ async trackEvent(
+ event: AnalyticsEvent,
+ properties: Record<string, any> = {},
+ options?: { context?: MCPAnalyticsContext; previousContext?: MCPAnalyticsContext }
+ ): Promise<void> {
+ try {
+ const distinctId = await this.getDistinctId()
+
+ const client = getPostHogClient()
+
+ await this.resolveClientInfo()
+
+ const clientName = await this.cache.get('clientName')
+
+ const contextProperties = options?.context ? buildMCPContextProperties(options.context) : {}
+ const previousContextProperties = options?.previousContext
+ ? buildMCPContextProperties(options.previousContext, { prefix: 'previous_' })
+ : {}
+ const groups = options?.context ? buildMCPAnalyticsGroups(options.context) : {}
+
+ client.capture({
+ distinctId,
+ event,
+ ...(Object.keys(groups).length > 0 ? { groups } : {}),
+ properties: {
+ ...(this.props.sessionId
+ ? {
+ $session_id: await this.sessionManager.getSessionUuid(this.props.sessionId),
+ }
+ : {}),
+ ...(clientName ? { mcp_oauth_client_name: clientName } : {}),
+ ...(this.mcpClientName ? { mcp_client_name: this.mcpClientName } : {}),
+ ...(this.mcpClientVersion ? { mcp_client_version: this.mcpClientVersion } : {}),
+ ...(this.mcpProtocolVersion ? { mcp_protocol_version: this.mcpProtocolVersion } : {}),
+ ...(this.props.mcpConsumer ? { mcp_consumer: this.props.mcpConsumer } : {}),
+ ...(this.props.transport ? { mcp_transport: this.props.transport } : {}),
+ ...(this.props.mcpSessionId ? { mcp_session_id: this.props.mcpSessionId } : {}),
+ ...(this.props.mcpConversationId ? { mcp_conversation_id: this.props.mcpConversationId } : {}),
+ ...(this.mcpMode ? { mcp_mode: this.mcpMode } : {}),
+ ...(this.mcpVersion !== undefined ? { mcp_version: this.mcpVersion } : {}),
+ mcp_runtime: 'hono',
+ ...contextProperties,
+ ...previousContextProperties,
+ ...properties,
+ },
+ })
+ } catch {
+ // skip
+ }
+ }
+
+ private async getAnalyticsContextSafe(
+ context: Pick<Context, 'stateManager'>
+ ): Promise<MCPAnalyticsContext | undefined> {
+ try {
+ return await context.stateManager.getAnalyticsContext()
+ } catch {
+ return undefined
+ }
+ }
+
+ private async trackContextSwitchEvent(
+ toolName: string,
+ context: Context,
+ previousContext: MCPAnalyticsContext | undefined
+ ): Promise<void> {
+ const resolvedContext = await this.getAnalyticsContextSafe(context)
+ if (!resolvedContext) {
+ return
+ }
+
+ const event =
+ toolName === 'switch-project'
+ ? AnalyticsEvent.MCP_PROJECT_SWITCHED
+ : toolName === 'switch-organization'
+ ? AnalyticsEvent.MCP_ORGANIZATION_SWITCHED
+ : undefined
+ if (!event) {
+ return
+ }
+
+ await this.trackEvent(event, {}, { context: resolvedContext, ...(previousContext ? { previousContext } : {}) })
+ }
+
+ registerTool<TSchema extends z.ZodObject>(
+ tool: Tool<TSchema>,
+ handler: (params: z.infer<TSchema>) => Promise<any>
+ ): void {
+ const wrappedHandler = async (params: z.infer<TSchema>): Promise<any> => {
+ const validation = tool.schema.safeParse(params)
+
+ if (!validation.success) {
+ toolCallsTotal.inc({ tool: tool.name, status: 'validation_error' })
+ const errorOutput = `Invalid input: ${validation.error.message}`
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text: errorOutput,
+ },
+ ],
+ }
+ }
+
+ const stop = toolCallDurationSeconds.startTimer({ tool: tool.name })
+ try {
+ const isContextSwitch = tool.name === 'switch-project' || tool.name === 'switch-organization'
+ const previousContext = isContextSwitch
+ ? await this.getAnalyticsContextSafe(await this.getContext())
+ : undefined
+ const handlerResult = await handler(params)
+ if (isContextSwitch) {
+ void this.trackContextSwitchEvent(tool.name, await this.getContext(), previousContext)
+ }
+ toolCallsTotal.inc({ tool: tool.name, status: 'success' })
+ stop({ status: 'success' })
+ if (isToolCallPayload(handlerResult)) {
+ return handlerResult
+ }
+ const hasUiResource = !!tool._meta?.ui?.resourceUri
+ const needsDistinctId = hasUiResource && typeof handlerResult !== 'string'
+ const distinctId = needsDistinctId ? await this.getDistinctId() : undefined
+
+ return buildToolResultPayload({
+ handlerResult,
+ toolMeta: tool._meta,
+ toolName: tool.name,
+ params,
+ clientName: this.mcpClientName,
+ distinctId,
+ })
+ } catch (error: any) {
+ toolCallsTotal.inc({ tool: tool.name, status: 'error' })
+ stop({ status: 'error' })
+ const distinctId = await this.getDistinctId()
+ return handleToolError(
+ error,
+ tool.name,
+ distinctId,
+ this.props.sessionId ? await this.sessionManager.getSessionUuid(this.props.sessionId) : undefined
+ )
+ }
+ }
+
+ let normalizedMeta = tool._meta
+ if (tool._meta?.ui?.resourceUri && !tool._meta[RESOURCE_URI_META_KEY]) {
+ normalizedMeta = {
+ ...tool._meta,
+ [RESOURCE_URI_META_KEY]: tool._meta.ui.resourceUri,
+ }
+ }
+
+ this.server.registerTool(
+ tool.name,
+ {
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.schema.shape,
+ annotations: tool.annotations,
+ ...(normalizedMeta ? { _meta: normalizedMeta } : {}),
+ },
+ wrappedHandler as unknown as ToolCallback<TSchema['shape']>
+ )
+ }
+
+ async getContext(): Promise<Context> {
+ const api = await this.api()
+ const stateManager = new StateManager(this.cache, api)
+ const partialContext: Omit<Context, 'trackEvent'> = {
+ api,
+ cache: this.cache,
+ env: this.env,
+ stateManager,
+ sessionManager: this.sessionManager,
+ getDistinctId: () => this.getDistinctId(),
+ }
+ const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {
+ const analyticsContext = await this.getAnalyticsContextSafe(partialContext)
+ await this.trackEvent(event, properties, analyticsContext ? { context: analyticsContext } : undefined)
+ }
+ return { ...partialContext, trackEvent }
+ }
+
+ async init(): Promise<void> {
+ const stopInit = initDurationSeconds.startTimer()
+ try {
+ await this.initInner()
+ } finally {
+ stopInit()
+ }
+ }
+
+ private async initInner(): Promise<void> {
+ const { features, tools, version: clientVersion, organizationId, projectId, readOnly, mode } = this.props
+
+ await this.resolveClientInfo()
+
+ // Start feature flag resolution in parallel with cache seeding
+ const flagPromise = this.resolveVersionFlag()
+ const toolFlagsPromise = this.resolveToolFeatureFlags(clientVersion)
+ const singleExecPromise = this.resolveSingleExecFlag()
+ const posthogMcpAnalyticsFlagPromise = this.resolvePostHogMcpAnalyticsFlag()
+
+ // Seed cache with header-provided IDs before any fetches
+ if (organizationId) {
+ await this.cache.set('orgId', organizationId)
+ }
+ let cachedProjectId: string | undefined
+ if (projectId) {
+ cachedProjectId = projectId
+ await this.cache.set('projectId', projectId)
+ }
+
+ const context = await this.getContext()
+ // Sticky session: skip default resolution if a previous init for this
+ // userHash already picked a project (cache survives across requests).
+ // Without this guard, switching the active org in the user's browser
+ // would silently reshuffle an established session — `users/@me`
+ // returns whatever team the browser currently has selected, and
+ // setDefaultOrganizationAndProject would overwrite the cache with it.
+ // Headers always win because they were applied to the cache above.
+ if (!cachedProjectId) {
+ cachedProjectId = await this.cache.get('projectId')
+ }
+
+ // Initialize org and project
+ if (!cachedProjectId) {
+ await context.stateManager.setDefaultOrganizationAndProject()
+ }
+
+ const [flagVersion, toolFeatureFlags, singleExecFlagOn, posthogMcpAnalyticsFlag] = await Promise.all([
+ flagPromise,
+ toolFlagsPromise,
+ singleExecPromise,
+ posthogMcpAnalyticsFlagPromise,
+ // Trigger OAuth introspection so the OAuth client name is cached before the useSingleExec decision below
+ context.stateManager.getApiKey(),
+ ])
+
+ const oauthClientName = (await this.cache.get('clientName')) || undefined
+
+ const clientProfile = new MCPClientProfile({
+ clientName: this.mcpClientName,
+ clientVersion: this.mcpClientVersion,
+ consumer: this.props.mcpConsumer,
+ oauthClientName,
+ })
+
+ const { useSingleExec, version } = this.resolveModeAndVersion({
+ mode,
+ singleExecFlagOn,
+ clientProfile,
+ flagVersion,
+ clientVersion,
+ })
+
+ // Fetch group types and metadata in parallel (cache is now seeded)
+ const resolvedProjectId = projectId || (await this.cache.get('projectId'))
+ const [groupTypes, metadata] = await Promise.all([
+ (async () => {
+ if (!resolvedProjectId) {
+ return undefined
+ }
+ const apiKey = await context.stateManager.getApiKey()
+ return hasScope(apiKey.scopes, 'group:read')
+ ? context.stateManager.getOrFetchGroupTypes(resolvedProjectId)
+ : undefined
+ })(),
+ context.stateManager.getEnvironmentPrompt(),
+ ])
+
+ // When project ID is provided, both switch tools are removed (project implies org).
+ // When only organization ID is provided, only switch-organization is removed.
+ const excludeTools: string[] = []
+ if (projectId) {
+ excludeTools.push('switch-organization', 'switch-project')
+ } else if (organizationId) {
+ excludeTools.push('switch-organization')
+ }
+
+ // Fetch tools up-front so we can build the query tool catalog (and the
+ // CLI exec tool's domain list) before constructing the system prompt.
+ const { getToolsFromContext } = await import('@/tools')
+ const allTools = await getToolsFromContext(context, {
+ features,
+ tools,
+ version,
+ excludeTools,
+ readOnly,
+ featureFlags: toolFeatureFlags,
+ })
+
+ // OAuth introspection ran above (we awaited `getApiKey()` before constructing
+ // `clientProfile`), so update the ApiClient with the verified OAuth client
+ // name for header forwarding.
+ if (oauthClientName && this._api) {
+ this._api.config.oauthClientName = oauthClientName
+ }
+
+ const toolInfos = allTools.map((t) => ({
+ name: t.name,
+ category: getToolDefinition(t.name, version).category,
+ }))
+ const queryToolInfos: QueryToolInfo[] = allTools
+ .filter((t) => t.name.startsWith('query-'))
+ .map((t) => {
+ const def = getToolDefinition(t.name, version)
+ return {
+ name: t.name,
+ title: def.title,
+ ...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),
+ }
+ })
+
+ const supportsInstructions = clientProfile.capabilities.supportsInstructions
+
+ const instructionsContext = {
+ guidelines: _guidelines,
+ groupTypes,
+ metadata,
+ tools: toolInfos,
+ queryTools: queryToolInfos,
+ featureFlags: toolFeatureFlags,
+ }
+
+ let instructions = ''
+ if (supportsInstructions) {
+ if (useSingleExec) {
+ instructions = instructionsFormatter.buildExecInstructions(instructionsContext)
+ } else if (version === 2) {
+ instructions = instructionsFormatter.buildV2Instructions(instructionsContext)
+ } else {
+ instructions = instructionsFormatter.buildV1Instructions(metadata)
+ }
+ }
+
+ this.server = new McpServer({ name: 'PostHog', version: '1.0.0' }, { instructions })
+
+ // Register prompts and resources
+ await Promise.all([
+ registerPrompts(this.server),
+ registerResources(this.server, context),
+ registerUiAppResources(this.server, context),
+ ])
+
+ // execute-sql is v2-only. Swap its description with the rich SQL prompt.
+ if (version === 2) {
+ const sqlTool = allTools.find((t) => t.name === 'execute-sql')
+ if (sqlTool) {
+ sqlTool.description = formatPrompt(EXECUTE_SQL_PROMPT, { guidelines: _guidelines.trim() })
+ }
+ }
+
+ // In single-exec mode, register one "posthog" tool that wraps all tools
+ // behind a CLI-like interface. Otherwise, register each tool individually.
+ if (useSingleExec) {
+ // When the client honors the `instructions` field, env-context is already
+ // delivered there — strip it from the command-parameter description.
+ const commandReference = instructionsFormatter.buildExecCommandReference(instructionsContext, {
+ stripEnvContext: supportsInstructions,
+ })
+
+ const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {
+ void (async () => {
+ const freshContext = await this.getAnalyticsContextSafe(await this.getContext())
+ await this.trackEvent(
+ AnalyticsEvent.MCP_TOOL_CALL,
+ { tool_name: toolName, ...properties },
+ freshContext ? { context: freshContext } : undefined
+ )
+ })()
+ }
+
+ const execTool = createExecTool(
+ allTools,
+ context,
+ instructionsFormatter.buildExecToolDescription(),
+ commandReference,
+ this.props.mcpConsumer,
+ trackInnerCall
+ )
+ const typedExecTool = execTool as Tool<z.ZodObject>
+ this.registerTool(typedExecTool, async (params) => typedExecTool.handler(context, params))
+ } else {
+ for (const tool of allTools) {
+ const typedTool = tool as Tool<z.ZodObject>
+ this.registerTool(typedTool, async (params) => typedTool.handler(context, params))
+ }
+ }
+
+ const mcpAnalyticsIdentity = {
+ getDistinctId: () => this.getDistinctId(),
+ getSessionUuid: async () =>
+ this.props.sessionId ? this.sessionManager.getSessionUuid(this.props.sessionId) : undefined,
+ getMcpClientName: async () => this.mcpClientName,
+ getMcpClientVersion: async () => this.mcpClientVersion,
+ getMcpProtocolVersion: async () => this.mcpProtocolVersion,
+ // Prefer the cached region (set on init after detection) so we don't miss it
+ // when the inbound request didn't include the `region` hint.
+ getRegion: async () => (await this.cache.get('region')) ?? this.props.region,
+ getAnalyticsContext: async () => this.getAnalyticsContextSafe(await this.getContext()),
+ getClientUserAgent: async () => this.props.clientUserAgent,
+ // Server-resolved version (may differ from the client-reported one because of
+ // the `mcp-version-2` feature flag), so observability events line up with ours.
+ getMcpVersion: async () => version,
+ getOAuthClientName: async () => (await this.cache.get('clientName')) || undefined,
+ getReadOnly: async () => readOnly,
+ getTransport: async () => this.props.transport,
+ getMcpConsumer: async () => this.props.mcpConsumer,
+ getMcpMode: async () => this.mcpMode,
+ getMcpSessionId: async () => this.props.mcpSessionId,
+ getMcpConversationId: async () => this.props.mcpConversationId,
+ }
+
+ Object.assign(this.props, {
+ mcpAnalyticsProvider: 'mcpcat' satisfies McpAnalyticsProvider,
+ mcpAnalyticsFlagKey: POSTHOG_MCP_ANALYTICS_FLAG,
+ mcpAnalyticsFlagEnabled: posthogMcpAnalyticsFlag.enabled,
+ ...(posthogMcpAnalyticsFlag.errorName
+ ? { mcpAnalyticsFlagErrorName: posthogMcpAnalyticsFlag.errorName }
+ : {}),
+ ...(posthogMcpAnalyticsFlag.errorMessage
+ ? { mcpAnalyticsFlagErrorMessage: posthogMcpAnalyticsFlag.errorMessage }
+ : {}),
+ })
+
+ // The Hono runtime always uses mcpcat for observability. The
+ // @posthog/mcp-analytics SDK depends on cloudflare:workers env and is
+ // skipped here — its flag is still resolved above for analytics parity.
+ await initMcpCatObservability(this.server, mcpAnalyticsIdentity)
+
+ const initDurationMs = this.props.requestStartTime ? Date.now() - this.props.requestStartTime : undefined
+
+ // Resolve analytics context from the already-primed cache (getEnvironmentPrompt
+ // above populated `cachedProject`/`cachedOrg`), so this is effectively free here.
+ const analyticsContext = await this.getAnalyticsContextSafe(context)
+
+ void this.trackEvent(
+ AnalyticsEvent.MCP_INIT,
+ {
+ tool_count: allTools.length,
+ has_organization_id: !!organizationId,
+ has_project_id: !!projectId,
+ read_only: !!readOnly,
+ via_sse_redirect: !!this.props.viaSseRedirect,
+ ...(mode ? { mcp_mode_explicit: mode } : {}),
+ ...(initDurationMs !== undefined ? { init_duration_ms: initDurationMs } : {}),
+ },
+ analyticsContext ? { context: analyticsContext } : undefined
+ )
+ }
+
+ /**
+ * Decide single-exec mode and the protocol version for this connection,
+ * stashing both on the instance so `trackEvent` and observability identity
+ * provider can emit `mcp_mode` / `mcp_version` on every downstream event
+ * without re-deriving them.
+ */
+ private resolveModeAndVersion(args: {
+ mode: McpMode | undefined
+ singleExecFlagOn: boolean
+ clientProfile: MCPClientProfile
+ flagVersion: number | undefined
+ clientVersion: number | undefined
+ }): { useSingleExec: boolean; version: number } {
+ const { mode, singleExecFlagOn, clientProfile, flagVersion, clientVersion } = args
+ const useSingleExec =
+ mode === 'cli' ||
+ (mode !== 'tools' &&
+ singleExecFlagOn &&
+ (clientProfile.isCodingAgent() ||
+ clientProfile.isPostHogCodeConsumer() ||
+ clientProfile.isVibeCodingClient()))
+ const version = useSingleExec ? 2 : (flagVersion ?? clientVersion ?? 1)
+
+ this.mcpMode = useSingleExec ? 'cli' : 'tools'
+ this.mcpVersion = version
+
+ return { useSingleExec, version }
+ }
+
+ private async resolveVersionFlag(): Promise<number | undefined> {
+ try {
+ const distinctId = await this.getDistinctId()
+ return (await isFeatureFlagEnabled('mcp-version-2', distinctId)) ? 2 : undefined
+ } catch {
+ return undefined
+ }
+ }
+
+ private async resolveSingleExecFlag(): Promise<boolean> {
+ try {
+ const distinctId = await this.getDistinctId()
+ return !!(await isFeatureFlagEnabled('mcp-single-exec-tool', distinctId))
+ } catch {
+ return false
+ }
+ }
+
+ private async resolvePostHogMcpAnalyticsFlag(): Promise<PostHogMcpAnalyticsFlagResult> {
+ try {
+ const distinctId = await this.getDistinctId()
+ return { enabled: !!(await isFeatureFlagEnabled(POSTHOG_MCP_ANALYTICS_FLAG, distinctId)) }
+ } catch (error) {
+ return {
+ enabled: false,
+ errorName: error instanceof Error ? error.name : 'UnknownError',
+ errorMessage: error instanceof Error ? error.message : String(error),
+ }
+ }
+ }
+
+ private async resolveToolFeatureFlags(version?: number): Promise<Record<string, boolean> | undefined> {
+ try {
+ const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')
+ const flagKeys = getRequiredFeatureFlags(version)
+ if (flagKeys.length === 0) {
+ return undefined
+ }
+ const distinctId = await this.getDistinctId()
+ return await evaluateFeatureFlags(flagKeys, distinctId)
+ } catch {
+ return undefined
+ }
+ }
+}
diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.ts
new file mode 100644
index 000000000000..3bfef969a609
--- /dev/null
+++ b/services/mcp/src/hono/metrics.ts
@@ -0,0 +1,82 @@
+// Prometheus instrumentation for the Hono runtime. CF Workers can't host a
+// scrape endpoint, so this lives Hono-side only. Metrics are registered on
+// `prom-client`'s default registry (singleton) — the long-lived Node process
+// is what makes that pattern fit; CF's per-request isolation does not.
+import { collectDefaultMetrics, Counter, Gauge, Histogram, register } from 'prom-client'
+
+// Default process-level metrics: heap, GC, event-loop lag, file descriptors, etc.
+collectDefaultMetrics({ prefix: 'mcp_' })
+
+// HTTP request volume by route + status. Path is normalized to a small set of
+// known prefixes so cardinality stays bounded — raw URLs would blow up the
+// metric (UI-app static asset paths, well-known per-resource paths).
+export const httpRequestsTotal = new Counter({
+ name: 'mcp_http_requests_total',
+ help: 'HTTP requests received by the Hono MCP server.',
+ labelNames: ['method', 'route', 'status'] as const,
+})
+
+export const httpRequestDurationSeconds = new Histogram({
+ name: 'mcp_http_request_duration_seconds',
+ help: 'HTTP request duration by route.',
+ labelNames: ['method', 'route', 'status'] as const,
+ // Wide range: health checks land in the 1ms bucket, tool calls in 100ms-10s.
+ buckets: [0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],
+})
+
+// MCP tool dispatch outcomes. `status` is `success` | `error` | `validation_error`.
+// Cardinality on `tool` is bounded by the registered tool catalog.
+export const toolCallsTotal = new Counter({
+ name: 'mcp_tool_calls_total',
+ help: 'MCP tool dispatches.',
+ labelNames: ['tool', 'status'] as const,
+})
+
+export const toolCallDurationSeconds = new Histogram({
+ name: 'mcp_tool_call_duration_seconds',
+ help: 'MCP tool dispatch duration.',
+ labelNames: ['tool', 'status'] as const,
+ buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10, 30, 60],
+})
+
+// HonoMcpServer.init() — fans out to PostHog API + flag eval + cache reads on
+// every cold session. Slow tail here is the single biggest cold-start signal.
+export const initDurationSeconds = new Histogram({
+ name: 'mcp_init_duration_seconds',
+ help: 'HonoMcpServer.init() duration (cold-start cost per new session).',
+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10],
+})
+
+// 0 normally, flips to 1 the moment SIGTERM lands. Useful in dashboards to
+// align deploy windows with traffic dips and to confirm the readiness flip
+// actually fired before pods went away.
+export const shuttingDown = new Gauge({
+ name: 'mcp_shutting_down',
+ help: 'Set to 1 when the pod is draining for shutdown.',
+})
+
+// Map a request URL to a low-cardinality label. Anything not matched falls
+// into `other` so a pathological client can't fan out the histogram series.
+export function routeLabel(pathname: string): string {
+ if (pathname === '/mcp' || pathname.startsWith('/mcp/')) {
+ return '/mcp'
+ }
+ if (pathname === '/sse' || pathname.startsWith('/sse/')) {
+ return '/sse'
+ }
+ if (pathname.startsWith('/.well-known/oauth-protected-resource')) {
+ return '/.well-known/oauth-protected-resource'
+ }
+ if (pathname.startsWith('/ui-apps/')) {
+ return '/ui-apps'
+ }
+ if (pathname === '/health' || pathname === '/healthz' || pathname === '/readyz') {
+ return pathname
+ }
+ if (pathname === '/' || pathname === '/metrics') {
+ return pathname
+ }
+ return 'other'
+}
+
+export { register }
diff --git a/services/mcp/src/hono/middleware.ts b/services/mcp/src/hono/middleware.ts
new file mode 100644
index 000000000000..5882d124a585
--- /dev/null
+++ b/services/mcp/src/hono/middleware.ts
@@ -0,0 +1,24 @@
+import { type MiddlewareHandler } from 'hono'
+
+import { httpRequestDurationSeconds, httpRequestsTotal, routeLabel } from './metrics'
+
+export const securityHeaders: MiddlewareHandler = async (c, next) => {
+ await next()
+ c.header('X-Content-Type-Options', 'nosniff')
+ c.header('X-Frame-Options', 'DENY')
+}
+
+export const httpMetrics: MiddlewareHandler = async (c, next) => {
+ const url = new URL(c.req.url)
+ if (url.pathname === '/metrics') {
+ await next()
+ return
+ }
+ const route = routeLabel(url.pathname)
+ const method = c.req.method
+ const stop = httpRequestDurationSeconds.startTimer({ method, route })
+ await next()
+ const status = String(c.res.status)
+ httpRequestsTotal.inc({ method, route, status })
+ stop({ method, route, status })
+}
diff --git a/services/mcp/src/hono/public-routes.ts b/services/mcp/src/hono/public-routes.ts
new file mode 100644
index 000000000000..e9fa71861d11
--- /dev/null
+++ b/services/mcp/src/hono/public-routes.ts
@@ -0,0 +1,104 @@
+import { serveStatic } from '@hono/node-server/serve-static'
+import type { Hono } from 'hono'
+
+import { buildRedirectUrl, getPublicUrl, matchAuthServerRedirect } from '@/lib/routing'
+
+import type { Lifecycle } from './app'
+import { AUTH_REDIRECT_PATHS, getAuthorizationServerUrl, MCP_DOCS_URL, OAUTH_SCOPES_SUPPORTED } from './constants'
+import { register } from './metrics'
+import type { HonoCtx, RedisWithPing } from './types'
+
+const WELL_KNOWN_PREFIX = '/.well-known/oauth-protected-resource'
+const OPENAI_CHALLENGE_TOKEN = 'pRLV9JYbPOF5Dy039v3Rn3-qrMuKqZ2_4SsX9GoL9aU'
+// Cap on Redis ping for readiness checks. Long enough to ride out a normal hop,
+// short enough that a tarpit doesn't block kubelet probes.
+const READYZ_REDIS_TIMEOUT_MS = 500
+
+const healthHandler = (c: HonoCtx): Response => c.json({ status: 'ok' }, 200, { 'Cache-Control': 'no-store' })
+
+function readyzHandler(redis: RedisWithPing, lifecycle: Lifecycle) {
+ return async (c: HonoCtx): Promise<Response> => {
+ // Flip readiness off as soon as SIGTERM lands so kube-proxy evicts us
+ // before we start refusing connections.
+ if (lifecycle.shuttingDown) {
+ return c.json({ status: 'shutting_down' }, 503)
+ }
+ try {
+ const probe = redis.ping
+ ? redis.ping().then((v) => v === 'PONG')
+ : redis.set('mcp:health:__readyz', 'ok', 'EX', 10).then((v) => v !== null)
+ const ok = await Promise.race([
+ probe,
+ new Promise<false>((resolve) => setTimeout(() => resolve(false), READYZ_REDIS_TIMEOUT_MS)),
+ ])
+ if (!ok) {
+ return c.json({ status: 'error', redis: 'unhealthy' }, 503)
+ }
+ return c.json({ status: 'ok', redis: 'healthy' })
+ } catch {
+ return c.json({ status: 'error', redis: 'unreachable' }, 503)
+ }
+ }
+}
+
+// RFC 9728: insert `/.well-known/oauth-protected-resource` between host and
+// resource path. The resource URL the metadata advertises has to match what
+// the client connected on, so we derive it from the request rather than
+// hard-coding the host.
+const wellKnownHandler = (c: HonoCtx): Response => {
+ const url = new URL(c.req.url)
+ const resourcePath = url.pathname.slice(WELL_KNOWN_PREFIX.length) || '/'
+ const resourceUrl = getPublicUrl(c.req.raw)
+ resourceUrl.pathname = resourcePath
+ resourceUrl.search = ''
+
+ return c.json(
+ {
+ resource: resourceUrl.toString().replace(/\/$/, ''),
+ authorization_servers: [getAuthorizationServerUrl()],
+ scopes_supported: OAUTH_SCOPES_SUPPORTED,
+ bearer_methods_supported: ['header'],
+ },
+ 200,
+ { 'Cache-Control': 'public, max-age=3600' }
+ )
+}
+
+const authRedirectHandler = (c: HonoCtx): Response => {
+ const url = new URL(c.req.url)
+ const redirect = matchAuthServerRedirect(url.pathname)
+ if (!redirect) {
+ return c.notFound() as unknown as Response
+ }
+ const redirectTo = buildRedirectUrl(getAuthorizationServerUrl(), url.pathname, url.search, redirect)
+ return c.redirect(redirectTo, redirect.status) as unknown as Response
+}
+
+/**
+ * Routes that don't require authentication: landing, healthchecks, OAuth
+ * resource metadata, MCP UI app static assets, and auth-server fallback redirects.
+ */
+export function registerPublicRoutes(app: Hono, redis: RedisWithPing, lifecycle: Lifecycle): void {
+ // MCP UI app static assets. The CF runtime serves these via the Workers
+ // Static Assets binding (`wrangler.jsonc`'s `assets.directory: ./public/`);
+ // here we serve them from disk so the same `${MCP_APPS_BASE_URL}/ui-apps/...`
+ // URL pattern works on both runtimes.
+ app.use('/ui-apps/*', serveStatic({ root: './public' }))
+
+ app.get('/', (c) => c.redirect(MCP_DOCS_URL, 302) as unknown as Response)
+ app.get('/.well-known/openai-apps-challenge', (c) => c.text(OPENAI_CHALLENGE_TOKEN))
+ app.get('/health', healthHandler)
+ app.get('/healthz', healthHandler)
+ app.get('/readyz', readyzHandler(redis, lifecycle))
+ app.get('/metrics', async (c) => {
+ c.header('Content-Type', register.contentType)
+ return c.body(await register.metrics())
+ })
+
+ app.all(WELL_KNOWN_PREFIX, wellKnownHandler)
+ app.all(`${WELL_KNOWN_PREFIX}/*`, wellKnownHandler)
+
+ for (const path of AUTH_REDIRECT_PATHS) {
+ app.all(path, authRedirectHandler)
+ }
+}
diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.ts
new file mode 100644
index 000000000000..401cafc3acc5
--- /dev/null
+++ b/services/mcp/src/hono/request-utils.ts
@@ -0,0 +1,111 @@
+import { z } from 'zod'
+
+import { getPostHogClient } from '@/lib/analytics'
+import { mapErrorToAuthResponse, mapKnownErrorMessage, validateBearerToken } from '@/lib/auth-errors'
+import {
+ type ClientInfo,
+ parseRequestProperties,
+ type RequestProperties,
+ type Transport,
+} from '@/lib/request-properties'
+import { getRegionFromRequest } from '@/lib/routing'
+import { sanitizeHeaderValue } from '@/lib/utils'
+
+import type { HonoCtx } from './types'
+
+const InitializeParamsSchema = z.object({
+ clientInfo: z
+ .object({
+ name: z.string().optional(),
+ version: z.string().optional(),
+ })
+ .optional(),
+ protocolVersion: z.string().optional(),
+})
+
+const JsonRpcMessageSchema = z.object({
+ method: z.string(),
+ params: z.unknown().optional(),
+})
+
+function parseClientInfo(bodyText: string): ClientInfo {
+ try {
+ const parsed = JSON.parse(bodyText)
+ const messages = Array.isArray(parsed) ? parsed : [parsed]
+ for (const msg of messages) {
+ const rpc = JsonRpcMessageSchema.safeParse(msg)
+ if (!rpc.success || rpc.data.method !== 'initialize') {
+ continue
+ }
+ const params = InitializeParamsSchema.safeParse(rpc.data.params)
+ if (!params.success) {
+ continue
+ }
+ return {
+ clientName: sanitizeHeaderValue(params.data.clientInfo?.name),
+ clientVersion: sanitizeHeaderValue(params.data.clientInfo?.version),
+ protocolVersion: sanitizeHeaderValue(params.data.protocolVersion),
+ }
+ }
+ } catch {}
+ return {}
+}
+
+function authenticate(c: HonoCtx): Response | null {
+ const token = c.req.header('Authorization')?.split(' ')[1]
+ return validateBearerToken(token, c.req.raw, getRegionFromRequest(c.req.raw))
+}
+
+async function preserveBody(c: HonoCtx): Promise<string> {
+ const raw = c.req.raw
+ const bodyText = await raw.text()
+ const fresh = new Request(raw.url, { method: raw.method, headers: raw.headers, body: bodyText })
+ Object.defineProperty(c.req, 'raw', { value: fresh, writable: true, configurable: true })
+ return bodyText
+}
+
+export async function authenticateAndParse(
+ c: HonoCtx,
+ transport: Transport
+): Promise<{ props: RequestProperties } | { error: Response }> {
+ const error = authenticate(c)
+ if (error) {
+ return { error }
+ }
+
+ const bodyText = await preserveBody(c)
+ const props = parseRequestProperties(c.req.raw, parseClientInfo(bodyText), transport)
+
+ props.mcpSessionId = sanitizeHeaderValue(c.req.header('mcp-session-id') || undefined)
+ props.mcpConversationId = sanitizeHeaderValue(c.req.header('mcp-conversation-id') || undefined)
+ if (new URL(c.req.url).searchParams.get('_deprecated') === 'sse') {
+ props.viaSseRedirect = true
+ }
+
+ return { props }
+}
+
+export function handleCatchError(error: unknown, props: RequestProperties): Response {
+ const authResponse = mapErrorToAuthResponse(error)
+ if (authResponse) {
+ return authResponse
+ }
+ try {
+ if (error instanceof Error) {
+ getPostHogClient().captureException(error, props.userHash, {
+ team: 'posthog_ai',
+ source: 'mcp_hono_request',
+ mcp_transport: props.transport,
+ })
+ }
+ } catch {}
+ return new Response('Internal server error', { status: 500 })
+}
+
+export async function passThrough(response: Response): Promise<Response> {
+ if (response.ok) {
+ return response
+ }
+ const body = await response.clone().text()
+ return mapKnownErrorMessage(body) ?? response
+}
diff --git a/services/mcp/src/hono/shutdown.ts b/services/mcp/src/hono/shutdown.ts
new file mode 100644
index 000000000000..7145976af14c
--- /dev/null
+++ b/services/mcp/src/hono/shutdown.ts
@@ -0,0 +1,50 @@
+import type { ServerType } from '@hono/node-server'
+import type Redis from 'ioredis'
+
+import type { Lifecycle } from './app'
+import { shuttingDown as shuttingDownMetric } from './metrics'
+
+const SHUTDOWN_GRACE_MS = parseInt(process.env.SHUTDOWN_GRACE_MS || '30000', 10)
+const SHUTDOWN_PRESTOP_DELAY_MS = parseInt(process.env.SHUTDOWN_PRESTOP_DELAY_MS || '5000', 10)
+
+const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
+
+export function registerShutdownHandlers(opts: {
+ server: ServerType
+ lifecycle: Lifecycle
+ redis: InstanceType<typeof Redis>
+}): void {
+ const { server, lifecycle, redis } = opts
+ let shuttingDown = false
+
+ const shutdown = async (signal: string): Promise<void> => {
+ if (shuttingDown) {
+ return
+ }
+ shuttingDown = true
+ console.info(`[MCP] ${signal} received — shutting down`)
+
+ lifecycle.shuttingDown = true
+ shuttingDownMetric.set(1)
+
+ const shutdownStart = Date.now()
+ if (SHUTDOWN_PRESTOP_DELAY_MS > 0) {
+ await sleep(SHUTDOWN_PRESTOP_DELAY_MS)
+ }
+
+ const drainBudget = Math.max(SHUTDOWN_GRACE_MS - (Date.now() - shutdownStart), 1000)
+ const closed = new Promise<void>((resolve) => server.close(() => resolve()))
+ await Promise.race([closed, sleep(drainBudget)])
+
+ try {
+ await redis.quit()
+ } catch (err) {
+ console.error('[MCP] Redis quit failed:', err)
+ }
+
+ process.exit(0)
+ }
+
+ process.on('SIGTERM', () => void shutdown('SIGTERM'))
+ process.on('SIGINT', () => void shutdown('SIGINT'))
+}
diff --git a/services/mcp/src/hono/streamable-handler.ts b/services/mcp/src/hono/streamable-handler.ts
new file mode 100644
index 000000000000..536e35bdc080
--- /dev/null
+++ b/services/mcp/src/hono/streamable-handler.ts
@@ -0,0 +1,38 @@
+import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
+
+import type { Lifecycle } from './app'
+import type { RedisLike } from './cache/RedisCache'
+import { HonoMcpServer } from './mcp-server'
+import { authenticateAndParse, handleCatchError, passThrough } from './request-utils'
+import type { HonoCtx } from './types'
+
+export class StreamableMcpHandler {
+ constructor(
+ private readonly redis: RedisLike,
+ private readonly lifecycle: Lifecycle
+ ) {}
+
+ fetch = async (c: HonoCtx): Promise<Response> => {
+ if (c.req.method !== 'POST') {
+ return new Response('Method not allowed', { status: 405 })
+ }
+ if (this.lifecycle.shuttingDown) {
+ return new Response('Server shutting down', { status: 503 })
+ }
+
+ const auth = await authenticateAndParse(c, 'streamable-http')
+ if ('error' in auth) {
+ return auth.error
+ }
+
+ try {
+ const mcpServer = new HonoMcpServer(this.redis, auth.props)
+ await mcpServer.init()
+ const transport = new WebStandardStreamableHTTPServerTransport({})
+ await mcpServer.server.connect(transport)
+ return passThrough(await transport.handleRequest(c.req.raw))
+ } catch (error) {
+ return handleCatchError(error, auth.props)
+ }
+ }
+}
diff --git a/services/mcp/src/hono/types.ts b/services/mcp/src/hono/types.ts
new file mode 100644
index 000000000000..9b315d0f690a
--- /dev/null
+++ b/services/mcp/src/hono/types.ts
@@ -0,0 +1,7 @@
+import type { Context } from 'hono'
+
+import type { RedisLike } from './cache/RedisCache'
+
+export type HonoCtx = Context
+
+export type RedisWithPing = RedisLike & { ping?(): Promise<string> }
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 72f274513d9f..3cf507adc77d 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -39,7 +39,14 @@ export class StateManager {
private async _fetchApiKey(): Promise<NonNullable<State['apiKey']>> {
const apiKeyResult = await this._api.apiKeys().current()
if (apiKeyResult.success) {
- return apiKeyResult.data
+ const { scopes, scoped_teams, scoped_organizations } = apiKeyResult.data
+ // The DRF serializer returns `null` (not `[]`) for unscoped keys, so
+ // normalize at the boundary — downstream code treats these as arrays.
+ return {
+ scopes,
+ scoped_teams: scoped_teams ?? [],
+ scoped_organizations: scoped_organizations ?? [],
+ }
}
const introspectionResult = await this._api.oauth().introspect({ token: this._api.config.apiToken })
@@ -61,8 +68,8 @@ export class StateManager {
return {
scopes: scope ? scope.split(' ') : [],
- scoped_teams,
- scoped_organizations,
+ scoped_teams: scoped_teams ?? [],
+ scoped_organizations: scoped_organizations ?? [],
}
}
diff --git a/services/mcp/src/lib/analytics.ts b/services/mcp/src/lib/analytics.ts
index 738b5a8f5801..541b9b77a4d6 100644
--- a/services/mcp/src/lib/analytics.ts
+++ b/services/mcp/src/lib/analytics.ts
@@ -1,6 +1,7 @@
-import { env } from 'cloudflare:workers'
import { PostHog } from 'posthog-node'
+import { env } from '@/lib/env'
+
let _client: PostHog | undefined
export enum AnalyticsEvent {
@@ -52,9 +53,9 @@ export const buildMCPContextProperties = (
export const getPostHogClient = (): PostHog => {
if (!_client) {
- _client = new PostHog(env.POSTHOG_ANALYTICS_API_KEY, {
+ _client = new PostHog(env.POSTHOG_ANALYTICS_API_KEY ?? '', {
disabled: !env.POSTHOG_ANALYTICS_API_KEY || !env.POSTHOG_ANALYTICS_HOST, // Disable if the API key or host is not set
- host: env.POSTHOG_ANALYTICS_HOST,
+ ...(env.POSTHOG_ANALYTICS_HOST ? { host: env.POSTHOG_ANALYTICS_HOST } : {}),
flushAt: 1,
flushInterval: 0,
})
diff --git a/services/mcp/src/lib/auth-errors.ts b/services/mcp/src/lib/auth-errors.ts
new file mode 100644
index 000000000000..72f517524a2e
--- /dev/null
+++ b/services/mcp/src/lib/auth-errors.ts
@@ -0,0 +1,95 @@
+// Shared helpers for building OAuth/auth error responses across both runtimes.
+//
+// The CF and Hono entry points diverge only in their *observability tail* (CF flushes
+// PostHog events via ctx.waitUntil, Hono fires them synchronously). Everything before
+// that — permission errors, known error-code mappings, missing/invalid token responses —
+// is identical and lives here.
+
+import type { CloudRegion } from '@/tools/types'
+
+import { MCP_DOCS_URL } from './oauth-constants'
+import {
+ buildInsufficientScopeChallenge,
+ ErrorCode,
+ findPostHogPermissionError,
+ formatPermissionErrorMessage,
+} from './errors'
+import { getPublicUrl } from './routing'
+
+// Map a thrown error to the appropriate auth response, or null if not auth-related.
+// Callers handle the null case (typically by emitting observability + returning 500).
+export function mapErrorToAuthResponse(error: unknown): Response | null {
+ const permissionError = findPostHogPermissionError(error)
+ if (permissionError) {
+ return new Response(formatPermissionErrorMessage(permissionError), {
+ status: 403,
+ headers: {
+ 'Content-Type': 'text/plain; charset=utf-8',
+ 'WWW-Authenticate': buildInsufficientScopeChallenge(permissionError),
+ },
+ })
+ }
+
+ if (error instanceof Error) {
+ return mapKnownErrorMessage(error.message)
+ }
+
+ return null
+}
+
+// Map a response body string to an auth response if it embeds a known error code.
+// Used to translate downstream API errors that surface as 200/4xx with a known
+// marker in the body (e.g. SDK transport wrappers).
+export function mapKnownErrorMessage(text: string): Response | null {
+ if (text.includes(ErrorCode.INACTIVE_OAUTH_TOKEN)) {
+ return new Response('OAuth token is inactive', { status: 401 })
+ }
+ if (text.includes(ErrorCode.INVALID_API_KEY)) {
+ return new Response('Invalid API key', { status: 401 })
+ }
+ return null
+}
+
+// Build the RFC 9728 `WWW-Authenticate` response for an unauthenticated request.
+// The `resource_metadata` URL points clients at the protected-resource metadata so
+// they can discover the authorization server.
+export function buildMissingTokenResponse(request: Request, effectiveRegion: CloudRegion | null): Response {
+ const url = new URL(request.url)
+ const metadataUrl = getPublicUrl(request)
+ metadataUrl.pathname = `/.well-known/oauth-protected-resource${url.pathname}`
+ metadataUrl.search = ''
+ if (effectiveRegion) {
+ metadataUrl.searchParams.set('region', effectiveRegion)
+ }
+
+ return new Response(
+ `No token provided, please provide a valid API token. View the documentation for more information: ${MCP_DOCS_URL}`,
+ {
+ status: 401,
+ headers: { 'WWW-Authenticate': `Bearer resource_metadata="${metadataUrl.toString()}"` },
+ }
+ )
+}
+
+export function buildInvalidTokenFormatResponse(): Response {
+ return new Response(
+ `Invalid token, please provide a valid API token. View the documentation for more information: ${MCP_DOCS_URL}`,
+ { status: 401 }
+ )
+}
+
+// Validate the bearer token format (must be present and `phx_`/`pha_` prefixed).
+// Returns the auth-error response if invalid, or null if the token is well-formed.
+export function validateBearerToken(
+ token: string | undefined,
+ request: Request,
+ effectiveRegion: CloudRegion | null
+): Response | null {
+ if (!token) {
+ return buildMissingTokenResponse(request, effectiveRegion)
+ }
+ if (!token.startsWith('phx_') && !token.startsWith('pha_')) {
+ return buildInvalidTokenFormatResponse()
+ }
+ return null
+}
diff --git a/services/mcp/src/lib/cache/DurableObjectCache.ts b/services/mcp/src/lib/cache/DurableObjectCache.ts
index 1c7be5e4516d..d0a49c756390 100644
--- a/services/mcp/src/lib/cache/DurableObjectCache.ts
+++ b/services/mcp/src/lib/cache/DurableObjectCache.ts
@@ -16,16 +16,14 @@ interface DurableObjectStorage {
export class DurableObjectCache<T extends Record<string, any>> extends ScopedCache<T> {
private storage: DurableObjectStorage
- private userHash: string
constructor(scope: string, storage: DurableObjectStorage) {
super(scope)
- this.userHash = scope
this.storage = storage
}
private getScopedKey(key: string): string {
- return `user:${this.userHash}:${key}`
+ return `user:${this.scope}:${key}`
}
async get<K extends keyof T>(key: K): Promise<T[K] | undefined> {
@@ -44,7 +42,7 @@ export class DurableObjectCache<T extends Record<string, any>> extends ScopedCac
}
async clear(): Promise<void> {
- const prefix = `user:${this.userHash}:`
+ const prefix = `user:${this.scope}:`
const keys = await this.storage.list({ prefix })
const keysArray = Array.from(keys.keys())
await this.storage.delete(keysArray)
diff --git a/services/mcp/src/lib/cache/ScopedCache.ts b/services/mcp/src/lib/cache/ScopedCache.ts
index f24ae6f9f5a2..eff97eaba2f3 100644
--- a/services/mcp/src/lib/cache/ScopedCache.ts
+++ b/services/mcp/src/lib/cache/ScopedCache.ts
@@ -1,5 +1,5 @@
export abstract class ScopedCache<T extends Record<string, any>> {
- constructor(private scope: string) {}
+ constructor(protected scope: string) {}
abstract get<K extends keyof T>(key: K): Promise<T[K] | undefined>
abstract set<K extends keyof T>(key: K, value: T[K]): Promise<void>
diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.ts
index c75210602498..302b510a82a9 100644
--- a/services/mcp/src/lib/constants.ts
+++ b/services/mcp/src/lib/constants.ts
@@ -1,45 +1,19 @@
-import { env } from 'cloudflare:workers'
-
-import type { CloudRegion } from '@/tools/types'
-
-import packageJson from '../../package.json'
-
-export const USER_AGENT = `posthog/mcp-server; version: ${packageJson.version}`
-
-export interface GetUserAgentOptions {
- clientUserAgent?: string | undefined
-}
-
-export function getUserAgent(opts: GetUserAgentOptions = {}): string {
- const { clientUserAgent } = opts
-
- if (clientUserAgent) {
- const match = clientUserAgent.match(/posthog\/([\w.-]+)/)
- if (match) {
- return `${USER_AGENT}; for ${match[0]}`
- }
- }
-
- return USER_AGENT
-}
-
-// Region-specific PostHog API base URLs
-export const POSTHOG_US_BASE_URL = 'https://us.posthog.com'
-export const POSTHOG_EU_BASE_URL = 'https://eu.posthog.com'
-
-// Normalize a string to a valid CloudRegion, defaulting to 'us'
-export const toCloudRegion = (value: string | undefined | null): CloudRegion => {
- const normalized = value?.toLowerCase()
- if (normalized === 'eu') {
- return 'eu'
- }
- return 'us'
-}
-
-// Get the PostHog base URL for a region
-export const getBaseUrlForRegion = (region: CloudRegion): string => {
- return region === 'eu' ? POSTHOG_EU_BASE_URL : POSTHOG_US_BASE_URL
-}
+import { env } from '@/lib/env'
+
+export {
+ USER_AGENT,
+ type GetUserAgentOptions,
+ getUserAgent,
+ POSTHOG_US_BASE_URL,
+ POSTHOG_EU_BASE_URL,
+ toCloudRegion,
+ getBaseUrlForRegion,
+ MCP_DOCS_URL,
+ OAUTH_PROXY_URL,
+ OAUTH_SCOPES_SUPPORTED,
+} from './oauth-constants'
+
+import { resolveAuthorizationServerUrl } from './oauth-constants'
/**
* Custom API base URL for self-hosted PostHog instances.
@@ -48,28 +22,6 @@ export const getBaseUrlForRegion = (region: CloudRegion): string => {
* The code automatically handles US/EU region routing via getAuthorizationServerUrl().
* Only set this for self-hosted PostHog deployments.
*/
-export const CUSTOM_API_BASE_URL = env.POSTHOG_API_BASE_URL
-
-const OAUTH_PROXY_URL = 'https://oauth.posthog.com'
-
-// Get the authorization server URL for OAuth
-// Uses the cross-region OAuth proxy for cloud, or CUSTOM_API_BASE_URL for self-hosted
-export const getAuthorizationServerUrl = (): string => {
- if (CUSTOM_API_BASE_URL) {
- return CUSTOM_API_BASE_URL
- }
-
- return OAUTH_PROXY_URL
-}
-
-// OAuth Authorization Server URL (where clients get tokens)
-// Defaults to CUSTOM_API_BASE_URL if not explicitly set
-export const OAUTH_AUTHORIZATION_SERVER_URL =
- (env as unknown as Record<string, string | undefined>).OAUTH_AUTHORIZATION_SERVER_URL || CUSTOM_API_BASE_URL
-
-export const MCP_DOCS_URL = 'https://posthog.com/docs/model-context-protocol'
+export const getCustomApiBaseUrl = (): string | undefined => env.POSTHOG_API_BASE_URL
-// OAuth Protected Resource Metadata (RFC 9728). Generated from posthog/scopes.py
-// to match what the authorization server actually advertises. See
-// oauth-scopes.generated.ts and bin/build-mcp-oauth-scopes.py.
-export { OAUTH_SCOPES_SUPPORTED, type OAuthScope } from './oauth-scopes.generated'
+export const getAuthorizationServerUrl = (): string => resolveAuthorizationServerUrl(getCustomApiBaseUrl())
diff --git a/services/mcp/src/lib/env.ts b/services/mcp/src/lib/env.ts
new file mode 100644
index 000000000000..61b314120256
--- /dev/null
+++ b/services/mcp/src/lib/env.ts
@@ -0,0 +1,5 @@
+import { env as _cfEnv } from 'cloudflare:workers'
+
+export const env = new Proxy({} as Record<string, string | undefined>, {
+ get: (_, key: string) => (_cfEnv as any)?.[key] ?? process.env[key],
+})
diff --git a/services/mcp/src/lib/mcpcat.ts b/services/mcp/src/lib/mcpcat.ts
index 0a0ad2c32d50..36eb98224181 100644
--- a/services/mcp/src/lib/mcpcat.ts
+++ b/services/mcp/src/lib/mcpcat.ts
@@ -1,8 +1,8 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-import { env } from 'cloudflare:workers'
import { track } from 'mcpcat'
import type { MCPAnalyticsContext } from '@/lib/analytics'
+import { env } from '@/lib/env'
/** Provider interface for resolving user/session identity and workspace context. */
export type McpCatIdentityProvider = {
diff --git a/services/mcp/src/lib/oauth-constants.ts b/services/mcp/src/lib/oauth-constants.ts
new file mode 100644
index 000000000000..c20705be3f06
--- /dev/null
+++ b/services/mcp/src/lib/oauth-constants.ts
@@ -0,0 +1,70 @@
+// Runtime-agnostic OAuth/region constants shared between the Cloudflare Workers
+// and Hono entry points. No imports from `cloudflare:workers` or Node-only modules
+// so this file is safe to import from either runtime.
+
+import type { CloudRegion } from '@/tools/types'
+
+import packageJson from '../../package.json'
+
+export const USER_AGENT = `posthog/mcp-server; version: ${packageJson.version}`
+
+export interface GetUserAgentOptions {
+ clientUserAgent?: string | undefined
+ /** `x-posthog-mcp-consumer` — self-identifier of the wrapping app (e.g. `posthog-code`, `slack`). */
+ mcpConsumer?: string | undefined
+ /** MCP `clientInfo.name` — the wrapped client (e.g. `claude-code`). */
+ mcpClientName?: string | undefined
+}
+
+export function getUserAgent(opts: GetUserAgentOptions = {}): string {
+ const { clientUserAgent, mcpConsumer, mcpClientName } = opts
+ const parts: string[] = []
+
+ // When the caller self-identifies as a wrapping consumer app, emit
+ // `<consumer>/<wrapped-client>` as the leading UA token so downstream
+ // services can attribute traffic without parsing custom headers.
+ if (mcpConsumer) {
+ const wrappedClient = (mcpClientName || 'unknown').replace(/\s+/g, '-')
+ parts.push(`${mcpConsumer}/${wrappedClient}`)
+ }
+
+ parts.push(USER_AGENT)
+
+ if (clientUserAgent) {
+ const match = clientUserAgent.match(/posthog\/([\w.-]+)/)
+ if (match) {
+ parts[parts.length - 1] = `${USER_AGENT}; for ${match[0]}`
+ }
+ }
+
+ return parts.join(' ')
+}
+
+export const POSTHOG_US_BASE_URL = 'https://us.posthog.com'
+export const POSTHOG_EU_BASE_URL = 'https://eu.posthog.com'
+
+export const toCloudRegion = (value: string | undefined | null): CloudRegion => {
+ const normalized = value?.toLowerCase()
+ if (normalized === 'eu') {
+ return 'eu'
+ }
+ return 'us'
+}
+
+export const getBaseUrlForRegion = (region: CloudRegion): string => {
+ return region === 'eu' ? POSTHOG_EU_BASE_URL : POSTHOG_US_BASE_URL
+}
+
+export const MCP_DOCS_URL = 'https://posthog.com/docs/model-context-protocol'
+
+export const OAUTH_PROXY_URL = 'https://oauth.posthog.com'
+
+// Resolve the OAuth authorization server URL given an optional self-hosted override.
+// Each runtime fetches the override from its own env source (CF binding vs process.env)
+// and passes it in.
+export const resolveAuthorizationServerUrl = (customApiBaseUrl: string | undefined): string => {
+ return customApiBaseUrl || OAUTH_PROXY_URL
+}
+
+// Generated from `posthog/scopes.py` — keep in sync with `hogli build:openapi`.
+export { OAUTH_SCOPES_SUPPORTED, type OAuthScope } from './oauth-scopes.generated'
diff --git a/services/mcp/src/lib/posthog-mcp-analytics.ts b/services/mcp/src/lib/posthog-mcp-analytics.ts
index 5eabb1986ec2..2b04d08d62f3 100644
--- a/services/mcp/src/lib/posthog-mcp-analytics.ts
+++ b/services/mcp/src/lib/posthog-mcp-analytics.ts
@@ -1,6 +1,6 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
-import { env } from 'cloudflare:workers'
+import { env } from '@/lib/env'
import { type McpCatIdentityProvider, redactSensitiveInformation } from '@/lib/mcpcat'
export type PostHogMcpAnalyticsIdentityProvider = McpCatIdentityProvider
@@ -20,9 +20,7 @@ export type PostHogMcpAnalyticsOptions = {
// isn't an exec call or the inner tool isn't recognized. Type accepts
// `| undefined` explicitly so callers can pass the value through
// unconditionally under `exactOptionalPropertyTypes: true`.
- resolveExecInnerToolCall?:
- | ((request: unknown) => { name: string; description: string } | undefined)
- | undefined
+ resolveExecInnerToolCall?: ((request: unknown) => { name: string; description: string } | undefined) | undefined
// In single-exec mode the SDK's $mcp_listed_tool_names on mcp_tools_list
// collapses to just the dispatcher's name (`exec`) because that's the
// only tool the server actually advertises over MCP. Passing the full
diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.ts
new file mode 100644
index 000000000000..d951b3fcb513
--- /dev/null
+++ b/services/mcp/src/lib/request-properties.ts
@@ -0,0 +1,83 @@
+// Shared request-properties extraction. Both runtimes parse the same headers
+// and query params into the same shape, so the logic lives here.
+
+import { hash, parseMcpMode, sanitizeHeaderValue, type McpMode } from './utils'
+
+export type Transport = 'streamable-http' | 'sse'
+
+export type RequestProperties = {
+ userHash: string
+ apiToken: string
+ sessionId?: string | undefined
+ features?: string[] | undefined
+ tools?: string[] | undefined
+ region?: string | undefined
+ version?: number | undefined
+ organizationId?: string | undefined
+ projectId?: string | undefined
+ clientUserAgent?: string | undefined
+ mcpConsumer?: string | undefined
+ mcpClientName?: string | undefined
+ mcpClientVersion?: string | undefined
+ mcpProtocolVersion?: string | undefined
+ readOnly?: boolean | undefined
+ mode?: McpMode | undefined
+ transport?: Transport | undefined
+ mcpSessionId?: string | undefined
+ mcpConversationId?: string | undefined
+ viaSseRedirect?: boolean | undefined
+ requestStartTime?: number | undefined
+}
+
+export type ClientInfo = {
+ clientName?: string | undefined
+ clientVersion?: string | undefined
+ protocolVersion?: string | undefined
+}
+
+function header(request: Request, name: string): string | undefined {
+ return request.headers.get(name) || undefined
+}
+
+function splitCsv(value: string | null): string[] | undefined {
+ if (!value) {
+ return undefined
+ }
+ const parts = value.split(',').filter(Boolean)
+ return parts.length > 0 ? parts : undefined
+}
+
+export function parseRequestProperties(
+ request: Request,
+ clientInfo: ClientInfo,
+ transport?: Transport
+): RequestProperties {
+ const url = new URL(request.url)
+ const params = url.searchParams
+
+ const token = request.headers.get('Authorization')?.split(' ')[1] ?? ''
+ const readOnlyRaw = header(request, 'x-posthog-readonly') || params.get('readonly')
+
+ return {
+ apiToken: token,
+ userHash: hash(token),
+ sessionId: params.get('sessionId') || undefined,
+ organizationId: header(request, 'x-posthog-organization-id') || params.get('organization_id') || undefined,
+ projectId: header(request, 'x-posthog-project-id') || params.get('project_id') || undefined,
+ features: splitCsv(params.get('features')),
+ tools: splitCsv(params.get('tools')),
+ region: params.get('region') || undefined,
+ version: Number(header(request, 'x-posthog-mcp-version') || params.get('v')) || 1,
+ readOnly: readOnlyRaw === 'true' || readOnlyRaw === '1' || undefined,
+ clientUserAgent: sanitizeHeaderValue(header(request, 'User-Agent')),
+ mcpConsumer: sanitizeHeaderValue(
+ header(request, 'x-posthog-mcp-consumer') || params.get('consumer') || undefined
+ ),
+ mcpClientName: clientInfo.clientName,
+ mcpClientVersion: clientInfo.clientVersion,
+ mcpProtocolVersion: clientInfo.protocolVersion,
+ mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),
+ transport,
+ requestStartTime: Date.now(),
+ }
+}
diff --git a/services/mcp/src/lib/routing.ts b/services/mcp/src/lib/routing.ts
index ebd684b586f2..2e50271195b9 100644
--- a/services/mcp/src/lib/routing.ts
+++ b/services/mcp/src/lib/routing.ts
@@ -1,3 +1,56 @@
+import type { CloudRegion } from '@/tools/types'
+
+// Resolve the public-facing URL for a request, honoring reverse-proxy headers.
+// Needed for local dev with ngrok/cloudflared, and for k8s deployments behind an ingress
+// where `request.url` is the in-cluster URL but the well-known/RFC-9728 metadata must
+// advertise the externally reachable origin.
+export function getPublicUrl(request: Request): URL {
+ const url = new URL(request.url)
+
+ const forwardedHost = request.headers.get('X-Forwarded-Host')
+ if (forwardedHost) {
+ url.host = forwardedHost
+ }
+
+ const forwardedProto = request.headers.get('X-Forwarded-Proto')
+ if (forwardedProto) {
+ url.protocol = forwardedProto + ':'
+ }
+
+ return url
+}
+
+// Detect region from the request hostname.
+// This is a workaround for Claude Code's OAuth bug where it ignores the
+// authorization_servers field from RFC 9728 metadata and instead fetches
+// /.well-known/oauth-authorization-server directly from the MCP server.
+// See: https://github.com/anthropics/claude-code/issues/2267
+//
+// By using a region-pinned subdomain, we can route the OAuth fallback to the
+// correct PostHog authorization server.
+export function getRegionFromHostname(request: Request): CloudRegion | undefined {
+ const hostname = getPublicUrl(request).hostname.toLowerCase()
+ if (hostname === 'mcp-eu.posthog.com' || hostname === 'mcp.eu.posthog.com') {
+ return 'eu'
+ }
+ if (hostname === 'mcp.us.posthog.com') {
+ return 'us'
+ }
+ return undefined
+}
+
+// Detect region from hostname (region-pinned subdomain) or `?region=` query param.
+// Hostname takes precedence — it's the workaround for Claude Code's OAuth bug.
+export function getRegionFromRequest(request: Request): CloudRegion | null {
+ const hostnameRegion = getRegionFromHostname(request)
+ if (hostnameRegion) {
+ return hostnameRegion
+ }
+
+ const url = new URL(request.url)
+ return url.searchParams.get('region') as CloudRegion | null
+}
+
// Authorization server redirect routes.
// MCP clients sometimes hit OAuth endpoints directly on this server instead of following
// the authorization server URLs from the protected resource metadata. Each entry defines
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index b9d6402a1b5c..99c61e5755c2 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -19,7 +19,7 @@ import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-resu
import { DurableObjectCache } from '@/lib/cache/DurableObjectCache'
import { MCPClientProfile } from '@/lib/client-detection'
import {
- CUSTOM_API_BASE_URL,
+ getCustomApiBaseUrl,
POSTHOG_EU_BASE_URL,
POSTHOG_US_BASE_URL,
getBaseUrlForRegion,
@@ -225,8 +225,9 @@ export class MCP extends McpAgent<Env> {
}
async getBaseUrl(): Promise<string> {
- if (CUSTOM_API_BASE_URL) {
- return CUSTOM_API_BASE_URL
+ const customBaseUrl = getCustomApiBaseUrl()
+ if (customBaseUrl) {
+ return customBaseUrl
}
// Check region from request props first (passed via URL param), then cache, then detect
diff --git a/services/mcp/src/schema/api.ts b/services/mcp/src/schema/api.ts
index aadd577026cf..2b072b69bb78 100644
--- a/services/mcp/src/schema/api.ts
+++ b/services/mcp/src/schema/api.ts
@@ -21,6 +21,10 @@ export interface ApiUser {
}
}
+// `scoped_teams` and `scoped_organizations` arrive from the API as either an
+// array or `null` (DRF serializer default). Callers must normalize null to []
+// at the wire boundary (see `StateManager._fetchApiKey`); this type represents
+// the post-normalization shape that the rest of the codebase consumes.
export interface ApiRedactedPersonalApiKey {
scopes: string[]
scoped_teams: number[]
diff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.ts
new file mode 100644
index 000000000000..40ba23f80202
--- /dev/null
+++ b/services/mcp/tests/hono/app-routes.test.ts
@@ -0,0 +1,342 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { Mock } from 'vitest'
+
+import { createApp } from '@/hono/app'
+import type { RedisLike } from '@/hono/cache/RedisCache'
+
+interface MockRedis extends RedisLike {
+ ping: Mock<() => Promise<string>>
+ _store: Map<string, string>
+}
+
+function createMockRedis(): MockRedis {
+ const store = new Map<string, string>()
+ return {
+ get: vi.fn(async (key: string) => store.get(key) ?? null),
+ set: vi.fn(async (key: string, value: string) => {
+ store.set(key, value)
+ return 'OK'
+ }),
+ del: vi.fn(async (...keys: string[]) => keys.length),
+ scan: vi.fn(async () => ['0', []] as [string, string[]]),
+ ping: vi.fn(async () => 'PONG'),
+ _store: store,
+ }
+}
+
+describe('Hono App Routes', () => {
+ let mockRedis: MockRedis
+
+ beforeEach(() => {
+ mockRedis = createMockRedis()
+ })
+
+ describe('GET /', () => {
+ it('should redirect to the docs', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/')
+ expect(res.status).toBe(302)
+ expect(res.headers.get('location')).toBe('https://posthog.com/docs/model-context-protocol')
+ })
+ })
+
+ describe('health checks', () => {
+ it('should return 200 with JSON on /healthz', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/healthz')
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as Record<string, unknown>
+ expect(body).toEqual({ status: 'ok' })
+ })
+
+ it('should return 200 with JSON on /health', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/health')
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as Record<string, unknown>
+ expect(body).toEqual({ status: 'ok' })
+ })
+
+ it('should return Cache-Control: no-store on /health', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/health')
+ expect(res.headers.get('Cache-Control')).toBe('no-store')
+ })
+
+ it('should return 200 on /readyz when Redis is healthy', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/readyz')
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as Record<string, unknown>
+ expect(body).toEqual({ status: 'ok', redis: 'healthy' })
+ })
+
+ it('should return 503 on /readyz when Redis ping fails', async () => {
+ mockRedis.ping.mockRejectedValue(new Error('Connection refused'))
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/readyz')
+ expect(res.status).toBe(503)
+ const body = (await res.json()) as Record<string, unknown>
+ expect(body.status).toBe('error')
+ })
+
+ it('should return 503 on /readyz when Redis returns unexpected value', async () => {
+ mockRedis.ping.mockResolvedValue('NOT_PONG')
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/readyz')
+ expect(res.status).toBe(503)
+ })
+ })
+
+ describe('GET /.well-known/openai-apps-challenge', () => {
+ it('should return the challenge token', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/openai-apps-challenge')
+ expect(res.status).toBe(200)
+ const body = await res.text()
+ expect(body).toBe('pRLV9JYbPOF5Dy039v3Rn3-qrMuKqZ2_4SsX9GoL9aU')
+ })
+ })
+
+ describe('security headers', () => {
+ it('should include X-Content-Type-Options: nosniff', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/healthz')
+ expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
+ })
+
+ it('should include X-Frame-Options: DENY', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/healthz')
+ expect(res.headers.get('X-Frame-Options')).toBe('DENY')
+ })
+ })
+
+ describe('OAuth Protected Resource Metadata', () => {
+ it('should return metadata for bare /.well-known/oauth-protected-resource', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-protected-resource')
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as Record<string, any>
+ expect(body.authorization_servers).toBeTruthy()
+ expect(body.bearer_methods_supported).toEqual(['header'])
+ expect(body.scopes_supported).toBeTruthy()
+ })
+
+ it('should return metadata for /mcp path', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-protected-resource/mcp')
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as Record<string, any>
+ expect(body.resource).toContain('/mcp')
+ })
+
+ it('should use oauth.posthog.com as authorization server', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-protected-resource/mcp')
+ const body = (await res.json()) as Record<string, any>
+ expect(body.authorization_servers[0]).toBe('https://oauth.posthog.com')
+ })
+
+ it('should set Cache-Control header', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-protected-resource/mcp')
+ expect(res.headers.get('Cache-Control')).toBe('public, max-age=3600')
+ })
+ })
+
+ describe('hostname-based region detection', () => {
+ it('should detect EU from mcp.eu.posthog.com via X-Forwarded-Host', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'POST',
+ headers: { 'X-Forwarded-Host': 'mcp.eu.posthog.com' },
+ })
+ expect(res.status).toBe(401)
+ const wwwAuth = res.headers.get('WWW-Authenticate') || ''
+ expect(wwwAuth).toContain('mcp.eu.posthog.com')
+ })
+
+ it('should detect US from mcp.us.posthog.com', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request(
+ new Request('http://mcp.us.posthog.com/.well-known/oauth-protected-resource/mcp')
+ )
+ expect(res.status).toBe(200)
+ })
+
+ it('should detect EU from legacy mcp-eu.posthog.com', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'POST',
+ headers: { 'X-Forwarded-Host': 'mcp-eu.posthog.com' },
+ })
+ expect(res.status).toBe(401)
+ const wwwAuth = res.headers.get('WWW-Authenticate') || ''
+ expect(wwwAuth).toContain('region=eu')
+ })
+ })
+
+ describe('MCP auth on /mcp', () => {
+ it('should return 401 with WWW-Authenticate when no token', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', { method: 'POST' })
+ expect(res.status).toBe(401)
+ const text = await res.text()
+ expect(text).toContain('No token provided')
+ expect(res.headers.get('WWW-Authenticate')).toContain('Bearer')
+ expect(res.headers.get('WWW-Authenticate')).toContain('oauth-protected-resource/mcp')
+ })
+
+ it('should return 401 for invalid token prefix', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer bad_token' },
+ })
+ expect(res.status).toBe(401)
+ expect(await res.text()).toContain('Invalid token')
+ })
+
+ it('should pass auth check for phx_ tokens (may fail later at init)', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'POST',
+ headers: {
+ Authorization: 'Bearer phx_test_token',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test', version: '1.0' },
+ },
+ id: 1,
+ }),
+ })
+ // Token format check passes — response is NOT "Invalid token"
+ const body = await res.text()
+ expect(body).not.toContain('Invalid token')
+ })
+
+ it('should pass auth check for pha_ tokens (may fail later at init)', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'POST',
+ headers: {
+ Authorization: 'Bearer pha_test_token',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test', version: '1.0' },
+ },
+ id: 1,
+ }),
+ })
+ // Token format check passes — response is NOT "Invalid token"
+ const body = await res.text()
+ expect(body).not.toContain('Invalid token')
+ })
+ })
+
+ describe('OAuth redirect routes', () => {
+ it('should redirect /.well-known/oauth-authorization-server', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-authorization-server', { redirect: 'manual' })
+ expect([301, 302]).toContain(res.status)
+ expect(res.headers.get('Location')).toContain('oauth.posthog.com')
+ })
+
+ it('should redirect /.well-known/jwks.json with 301', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/jwks.json', { redirect: 'manual' })
+ expect(res.status).toBe(301)
+ })
+
+ it('should redirect /oauth/* routes with 301', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/oauth/authorize', { redirect: 'manual' })
+ expect(res.status).toBe(301)
+ })
+
+ it('should redirect /register with 307 (preserves POST)', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/register', { method: 'POST', redirect: 'manual' })
+ expect(res.status).toBe(307)
+ expect(res.headers.get('Location')).toContain('/oauth/register')
+ })
+
+ it('should redirect /authorize with 302', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/authorize', { redirect: 'manual' })
+ expect(res.status).toBe(302)
+ expect(res.headers.get('Location')).toContain('/oauth/authorize')
+ })
+
+ it('should redirect /token with 307 (preserves POST)', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/token', { method: 'POST', redirect: 'manual' })
+ expect(res.status).toBe(307)
+ expect(res.headers.get('Location')).toContain('/oauth/token')
+ })
+ })
+
+ describe('Streamable HTTP endpoint', () => {
+ it('should return 405 for unsupported method (PUT)', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'PUT',
+ headers: { Authorization: 'Bearer phx_test' },
+ })
+ expect(res.status).toBe(405)
+ })
+
+ it('should return 405 for DELETE (stateless, no session management)', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/mcp', {
+ method: 'DELETE',
+ headers: {
+ Authorization: 'Bearer phx_test',
+ 'mcp-session-id': 'non-existent',
+ },
+ })
+ expect(res.status).toBe(405)
+ })
+ })
+
+ describe('404 handling', () => {
+ it('should return 404 for unknown routes', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/unknown-path')
+ expect(res.status).toBe(404)
+ })
+
+ it('should return 404 for /api paths', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/api/anything')
+ expect(res.status).toBe(404)
+ })
+ })
+
+ describe('session isolation', () => {
+ it('should create independent app instances with separate session maps', async () => {
+ const redis1 = createMockRedis()
+ const redis2 = createMockRedis()
+ const { app: app1 } = createApp(redis1)
+ const { app: app2 } = createApp(redis2)
+
+ const res1 = await app1.request('/healthz')
+ const res2 = await app2.request('/healthz')
+ expect(res1.status).toBe(200)
+ expect(res2.status).toBe(200)
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/constants.test.ts b/services/mcp/tests/hono/constants.test.ts
new file mode 100644
index 000000000000..3f02fac75a38
--- /dev/null
+++ b/services/mcp/tests/hono/constants.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, describe, expect, it } from 'vitest'
+
+import {
+ POSTHOG_EU_BASE_URL,
+ POSTHOG_US_BASE_URL,
+ USER_AGENT,
+ getAuthorizationServerUrl,
+ getBaseUrlForRegion,
+ getCustomApiBaseUrl,
+ getEnv,
+ getUserAgent,
+ toCloudRegion,
+} from '@/hono/constants'
+
+describe('Hono Constants', () => {
+ const originalEnv = { ...process.env }
+
+ afterEach(() => {
+ process.env = { ...originalEnv }
+ })
+
+ describe('toCloudRegion', () => {
+ it.each([
+ ['eu', 'eu'],
+ ['EU', 'eu'],
+ ['Eu', 'eu'],
+ ['us', 'us'],
+ ['US', 'us'],
+ [undefined, 'us'],
+ [null, 'us'],
+ ['invalid', 'us'],
+ ['', 'us'],
+ ] as const)('should return %s for input %s', (input, expected) => {
+ expect(toCloudRegion(input as string | undefined | null)).toBe(expected)
+ })
+ })
+
+ describe('getBaseUrlForRegion', () => {
+ it('should return EU URL for eu region', () => {
+ expect(getBaseUrlForRegion('eu')).toBe(POSTHOG_EU_BASE_URL)
+ })
+
+ it('should return US URL for us region', () => {
+ expect(getBaseUrlForRegion('us')).toBe(POSTHOG_US_BASE_URL)
+ })
+ })
+
+ describe('getCustomApiBaseUrl', () => {
+ it('should return undefined when env var not set', () => {
+ delete process.env.POSTHOG_API_BASE_URL
+ expect(getCustomApiBaseUrl()).toBeUndefined()
+ })
+
+ it('should return the env var value when set', () => {
+ process.env.POSTHOG_API_BASE_URL = 'https://custom.posthog.com'
+ expect(getCustomApiBaseUrl()).toBe('https://custom.posthog.com')
+ })
+ })
+
+ describe('getAuthorizationServerUrl', () => {
+ it('should return custom URL when POSTHOG_API_BASE_URL is set', () => {
+ process.env.POSTHOG_API_BASE_URL = 'https://custom.posthog.com'
+ expect(getAuthorizationServerUrl()).toBe('https://custom.posthog.com')
+ })
+
+ it('should return oauth proxy URL when no custom URL', () => {
+ delete process.env.POSTHOG_API_BASE_URL
+ expect(getAuthorizationServerUrl()).toBe('https://oauth.posthog.com')
+ })
+ })
+
+ describe('getUserAgent', () => {
+ it('should return base user agent when no options', () => {
+ expect(getUserAgent()).toBe(USER_AGENT)
+ })
+
+ it('should append posthog client info when present', () => {
+ expect(getUserAgent({ clientUserAgent: 'posthog/web-client-1.0' })).toContain('for posthog/web-client-1')
+ })
+
+ it('should return base user agent for non-posthog clients', () => {
+ expect(getUserAgent({ clientUserAgent: 'Mozilla/5.0' })).toBe(USER_AGENT)
+ })
+
+ it('should prepend consumer/client token when mcpConsumer is set', () => {
+ const ua = getUserAgent({ mcpConsumer: 'posthog-code', mcpClientName: 'claude-code' })
+ expect(ua).toMatch(/^posthog-code\/claude-code posthog\/mcp-server/)
+ })
+
+ it('should use "unknown" for mcpClientName when not provided', () => {
+ const ua = getUserAgent({ mcpConsumer: 'my-app' })
+ expect(ua).toMatch(/^my-app\/unknown posthog\/mcp-server/)
+ })
+ })
+
+ describe('getEnv', () => {
+ it('should return env vars from process.env', () => {
+ process.env.POSTHOG_ANALYTICS_API_KEY = 'test-key'
+ const env = getEnv()
+ expect(env.POSTHOG_ANALYTICS_API_KEY).toBe('test-key')
+ })
+
+ it('should return undefined for unset env vars', () => {
+ delete process.env.POSTHOG_ANALYTICS_API_KEY
+ delete process.env.POSTHOG_API_BASE_URL
+ const env = getEnv()
+ expect(env.POSTHOG_ANALYTICS_API_KEY).toBeUndefined()
+ expect(env.POSTHOG_API_BASE_URL).toBeUndefined()
+ })
+
+ it('should return all expected fields', () => {
+ const env = getEnv()
+ expect(env).toHaveProperty('POSTHOG_API_BASE_URL')
+ expect(env).toHaveProperty('MCP_APPS_BASE_URL')
+ expect(env).toHaveProperty('POSTHOG_MCP_APPS_ANALYTICS_BASE_URL')
+ expect(env).toHaveProperty('POSTHOG_UI_APPS_TOKEN')
+ expect(env).toHaveProperty('POSTHOG_ANALYTICS_API_KEY')
+ expect(env).toHaveProperty('POSTHOG_ANALYTICS_HOST')
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.ts
new file mode 100644
index 000000000000..759945976e9d
--- /dev/null
+++ b/services/mcp/tests/hono/mcp-protocol.test.ts
@@ -0,0 +1,67 @@
+import { setupServer } from 'msw/node'
+import { afterAll, beforeAll } from 'vitest'
+
+import { createApp } from '@/hono/app'
+import type { RedisLike } from '@/hono/cache/RedisCache'
+
+import { defineMcpProtocolTests } from '../integration/mcp-protocol-suite'
+import { handlers } from '../workers/fixtures/handlers'
+
+// MSW intercepts the outbound PostHog API traffic the MCP server makes during
+// init() and tool calls, serving fixtures from the same set the workers harness
+// uses. Requests to our in-process Hono `app` go through `app.request()` and
+// don't touch globalThis.fetch, so we don't need a localhost passthrough rule.
+const mswServer = setupServer(...handlers)
+
+function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {
+ const store = new Map<string, string>()
+ return {
+ get: async (key) => store.get(key) ?? null,
+ set: async (key, value) => {
+ store.set(key, String(value))
+ return 'OK'
+ },
+ del: async (...keys) => {
+ let removed = 0
+ for (const key of keys) {
+ if (store.delete(key)) {
+ removed++
+ }
+ }
+ return removed
+ },
+ scan: async (cursor) => {
+ const cur = String(cursor)
+ return [cur === '0' ? 'next' : '0', cur === '0' ? Array.from(store.keys()) : []] as [string, string[]]
+ },
+ ping: async () => 'PONG',
+ }
+}
+
+let app: ReturnType<typeof createApp>['app']
+
+beforeAll(() => {
+ process.env.TEST = '1'
+ mswServer.listen({ onUnhandledRequest: 'bypass' })
+ app = createApp(createInMemoryRedis()).app
+})
+
+afterAll(() => {
+ mswServer.close()
+})
+
+// Custom fetch that routes through the Hono app's `request()` entry point —
+// the same WHATWG Request/Response pipeline the runtime uses, minus the TCP
+// socket. Keeps the test fully in-process so no port management or shutdown
+// races; still exercises every middleware, route, and the MCP transport.
+const fetchViaApp: typeof fetch = async (input, init) => {
+ const url = input instanceof URL ? input : new URL(typeof input === 'string' ? input : input.url)
+ return app.request(url.pathname + url.search, init ?? {})
+}
+
+defineMcpProtocolTests('Hono', () => ({
+ // baseUrl host is irrelevant — `fetchViaApp` extracts only path + query.
+ baseUrl: new URL('http://hono.test'),
+ fetch: fetchViaApp,
+ token: 'phx_integration_test_token',
+}))
diff --git a/services/mcp/tests/hono/mcp-server.test.ts b/services/mcp/tests/hono/mcp-server.test.ts
new file mode 100644
index 000000000000..46c60095ce1b
--- /dev/null
+++ b/services/mcp/tests/hono/mcp-server.test.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { RedisLike } from '@/hono/cache/RedisCache'
+import { HonoMcpServer, type RequestProperties } from '@/hono/mcp-server'
+
+interface MockRedis extends RedisLike {
+ _store: Map<string, string>
+}
+
+function createMockRedis(): MockRedis {
+ const store = new Map<string, string>()
+ return {
+ get: vi.fn(async (key: string) => store.get(key) ?? null),
+ set: vi.fn(async (key: string, value: string) => {
+ store.set(key, value)
+ return 'OK'
+ }),
+ del: vi.fn(async (...keys: string[]) => keys.length),
+ scan: vi.fn(async () => ['0', []] as [string, string[]]),
+ _store: store,
+ }
+}
+
+describe('HonoMcpServer', () => {
+ let mockRedis: MockRedis
+ const baseProps: RequestProperties = {
+ userHash: 'test-hash',
+ apiToken: 'phx_test_token',
+ version: 1,
+ }
+ const originalEnv = { ...process.env }
+
+ beforeEach(() => {
+ mockRedis = createMockRedis()
+ delete process.env.POSTHOG_API_BASE_URL
+ })
+
+ afterEach(() => {
+ process.env = { ...originalEnv }
+ })
+
+ describe('constructor', () => {
+ it('should create a server instance', () => {
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ expect(server.server).toBeTruthy()
+ })
+
+ it('should expose requestProperties', () => {
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ expect(server.requestProperties.userHash).toBe('test-hash')
+ expect(server.requestProperties.apiToken).toBe('phx_test_token')
+ })
+ })
+
+ describe('getBaseUrl', () => {
+ it('should return US base URL by default', async () => {
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ vi.spyOn(server, 'detectRegion').mockResolvedValue(undefined)
+ const url = await server.getBaseUrl()
+ expect(url).toBe('https://us.posthog.com')
+ })
+
+ it('should return EU base URL when region is eu', async () => {
+ const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'eu' })
+ const url = await server.getBaseUrl()
+ expect(url).toBe('https://eu.posthog.com')
+ })
+
+ it('should use cached region when available', async () => {
+ mockRedis._store.set('mcp:user:test-hash:region', '"eu"')
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ const url = await server.getBaseUrl()
+ expect(url).toBe('https://eu.posthog.com')
+ })
+
+ it('should cache region from props', async () => {
+ const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'eu' })
+ await server.getBaseUrl()
+ expect(mockRedis.set).toHaveBeenCalledWith(
+ 'mcp:user:test-hash:region',
+ '"eu"',
+ 'EX',
+ expect.any(Number)
+ )
+ })
+
+ it('should use custom API base URL from env', async () => {
+ process.env.POSTHOG_API_BASE_URL = 'https://custom.posthog.com'
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ const url = await server.getBaseUrl()
+ expect(url).toBe('https://custom.posthog.com')
+ })
+ })
+
+ describe('sessionManager', () => {
+ it('should return a SessionManager instance', () => {
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ expect(server.sessionManager).toBeTruthy()
+ })
+
+ it('should return same instance on repeated access', () => {
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ const sm1 = server.sessionManager
+ const sm2 = server.sessionManager
+ expect(sm1).toBe(sm2)
+ })
+ })
+
+ describe('getContext', () => {
+ it('should return a context with all required fields', async () => {
+ const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'us' })
+ vi.spyOn(server, 'getBaseUrl').mockResolvedValue('https://us.posthog.com')
+ const ctx = await server.getContext()
+ expect(ctx.api).toBeTruthy()
+ expect(ctx.cache).toBeTruthy()
+ expect(ctx.env).toBeTruthy()
+ expect(ctx.stateManager).toBeTruthy()
+ expect(ctx.sessionManager).toBeTruthy()
+ expect(ctx.getDistinctId).toBeTruthy()
+ })
+ })
+
+ describe('trackEvent', () => {
+ it('should not throw on tracking errors', async () => {
+ const server = new HonoMcpServer(mockRedis, baseProps)
+ vi.spyOn(server, 'getDistinctId').mockRejectedValue(new Error('fail'))
+
+ const { AnalyticsEvent } = await import('@/lib/analytics')
+ await expect(server.trackEvent(AnalyticsEvent.MCP_INIT)).resolves.toBeUndefined()
+ })
+ })
+
+ describe('api', () => {
+ it('should cache the ApiClient instance', async () => {
+ const server = new HonoMcpServer(mockRedis, { ...baseProps, region: 'us' })
+ const api1 = await server.api()
+ const api2 = await server.api()
+ expect(api1).toBe(api2)
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/redis-cache.test.ts b/services/mcp/tests/hono/redis-cache.test.ts
new file mode 100644
index 000000000000..350bd895f29c
--- /dev/null
+++ b/services/mcp/tests/hono/redis-cache.test.ts
@@ -0,0 +1,117 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { RedisCache, type RedisLike } from '@/hono/cache/RedisCache'
+
+type TestState = {
+ region: string | undefined
+ projectId: string | undefined
+ distinctId: string | undefined
+ orgId: string | undefined
+}
+
+interface MockRedis extends RedisLike {
+ _store: Map<string, string>
+}
+
+function createMockRedis(): MockRedis {
+ const store = new Map<string, string>()
+ return {
+ get: vi.fn(async (key: string) => store.get(key) ?? null),
+ set: vi.fn(async (key: string, value: string) => {
+ store.set(key, value)
+ return 'OK'
+ }),
+ del: vi.fn(async (...keys: string[]) => {
+ let count = 0
+ for (const key of keys) {
+ if (store.delete(key)) {
+ count++
+ }
+ }
+ return count
+ }),
+ scan: vi.fn(async (_cursor: string, _match: string, pattern: string) => {
+ const matching = Array.from(store.keys()).filter((k) => {
+ const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$')
+ return regex.test(k)
+ })
+ return ['0', matching] as [string, string[]]
+ }),
+ _store: store,
+ }
+}
+
+describe('RedisCache', () => {
+ let mockRedis: MockRedis
+ let cache: RedisCache<TestState>
+
+ beforeEach(() => {
+ mockRedis = createMockRedis()
+ cache = new RedisCache<TestState>('test-user-hash', mockRedis)
+ })
+
+ describe('get', () => {
+ it('should return undefined for missing keys', async () => {
+ const result = await cache.get('region')
+ expect(result).toBeUndefined()
+ expect(mockRedis.get).toHaveBeenCalledWith('mcp:user:test-user-hash:region')
+ })
+
+ it('should return parsed JSON values', async () => {
+ mockRedis._store.set('mcp:user:test-user-hash:region', '"us"')
+ expect(await cache.get('region')).toBe('us')
+ })
+
+ it('should not read another user keys', async () => {
+ const cacheA = new RedisCache<TestState>('user-a', mockRedis)
+ const cacheB = new RedisCache<TestState>('user-b', mockRedis)
+ mockRedis._store.set('mcp:user:user-a:region', '"us"')
+ mockRedis._store.set('mcp:user:user-b:region', '"eu"')
+
+ expect(await cacheA.get('region')).toBe('us')
+ expect(await cacheB.get('region')).toBe('eu')
+ })
+ })
+
+ describe('set', () => {
+ it('should store JSON-serialized values with scoped key', async () => {
+ await cache.set('region', 'eu')
+ expect(mockRedis.set).toHaveBeenCalledWith('mcp:user:test-user-hash:region', '"eu"', 'EX', 7 * 24 * 60 * 60)
+ })
+
+ it('should isolate different users', async () => {
+ const cacheA = new RedisCache<TestState>('user-a', mockRedis)
+ const cacheB = new RedisCache<TestState>('user-b', mockRedis)
+ await cacheA.set('projectId', '111')
+ await cacheB.set('projectId', '222')
+
+ expect(mockRedis._store.get('mcp:user:user-a:projectId')).toBe('"111"')
+ expect(mockRedis._store.get('mcp:user:user-b:projectId')).toBe('"222"')
+ })
+ })
+
+ describe('delete', () => {
+ it('should only delete the targeted user key', async () => {
+ mockRedis._store.set('mcp:user:test-user-hash:region', '"us"')
+ mockRedis._store.set('mcp:user:other-user:region', '"eu"')
+ await cache.delete('region')
+ expect(mockRedis._store.has('mcp:user:other-user:region')).toBe(true)
+ })
+ })
+
+ describe('clear', () => {
+ it('should only clear keys for the scoped user', async () => {
+ mockRedis._store.set('mcp:user:test-user-hash:region', '"us"')
+ mockRedis._store.set('mcp:user:test-user-hash:projectId', '"123"')
+ mockRedis._store.set('mcp:user:other-user:region', '"eu"')
+
+ await cache.clear()
+
+ expect(mockRedis.del).toHaveBeenCalledWith(
+ 'mcp:user:test-user-hash:region',
+ 'mcp:user:test-user-hash:projectId'
+ )
+ expect(mockRedis._store.has('mcp:user:other-user:region')).toBe(true)
+ })
+ })
+})
diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.ts
new file mode 100644
index 000000000000..bbc0d464bee1
--- /dev/null
+++ b/services/mcp/tests/hono/setup.ts
@@ -0,0 +1,144 @@
+import { vi } from 'vitest'
+
+vi.mock('cloudflare:workers', () => ({
+ env: {
+ INKEEP_API_KEY: undefined,
+ POSTHOG_API_BASE_URL: undefined,
+ MCP_APPS_BASE_URL: undefined,
+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,
+ POSTHOG_UI_APPS_TOKEN: undefined,
+ POSTHOG_ANALYTICS_API_KEY: undefined,
+ POSTHOG_ANALYTICS_HOST: undefined,
+ MCP_CAT_PROJECT_ID: undefined,
+ },
+}))
+
+// Mock shared guidelines (generated by scripts/copy-instructions.ts, not checked in)
+vi.mock('@shared/guidelines.md', () => ({
+ default: '# Guidelines\nTest guidelines content.',
+}))
+
+vi.mock('@/resources/ui-apps', () => ({
+ registerUiAppResources: vi.fn().mockResolvedValue(undefined),
+ withUiApp: <T extends { _meta?: unknown }>(_appKey: string, config: Omit<T, '_meta'>): T => config as T,
+}))
+
+vi.mock('@/resources/ui-apps.generated', () => ({
+ UI_APP_REGISTRY: {},
+}))
+
+vi.mock('mcpcat', () => ({
+ track: vi.fn(),
+}))
+
+// Mock modules that may not exist on all branches yet (added on master,
+// not yet merged into this feature branch). These mocks allow the hono
+// code to import from master-targeted paths during tests.
+vi.mock('@/lib/build-tool-result', async () => {
+ try {
+ return await vi.importActual('@/lib/build-tool-result')
+ } catch {
+ return {
+ buildToolResultPayload: vi.fn(({ handlerResult }: any) => ({
+ content: [{ type: 'text', text: typeof handlerResult === 'string' ? handlerResult : JSON.stringify(handlerResult) }],
+ })),
+ isToolCallPayload: vi.fn(() => false),
+ }
+ }
+})
+
+vi.mock('@/lib/client-detection', async () => {
+ try {
+ return await vi.importActual('@/lib/client-detection')
+ } catch {
+ return {
+ MCPClientProfile: class MCPClientProfile {
+ constructor() {}
+ isCodingAgent(): boolean { return false }
+ isPostHogCodeConsumer(): boolean { return false }
+ isVibeCodingClient(): boolean { return false }
+ get capabilities(): { supportsInstructions: boolean } { return { supportsInstructions: true } }
+ },
+ isCodingAgentClient: vi.fn(() => false),
+ CODING_AGENT_CLIENT_NAME_FRAGMENTS: [],
+ }
+ }
+})
+
+vi.mock('@/lib/mcp-client-info', async () => {
+ try {
+ return await vi.importActual('@/lib/mcp-client-info')
+ } catch {
+ return {
+ extractClientInfoFromBody: vi.fn(async () => ({})),
+ }
+ }
+})
+
+// Mock @/lib/utils additions not present on all branches
+vi.mock('@/lib/utils', async () => {
+ const actual = await vi.importActual<Record<string, unknown>>('@/lib/utils')
+ return {
+ ...actual,
+ parseMcpMode: actual.parseMcpMode ?? vi.fn(() => undefined),
+ McpMode: actual.McpMode ?? undefined,
+ }
+})
+
+// Mock @/lib/errors additions not present on all branches
+vi.mock('@/lib/errors', async () => {
+ const actual = await vi.importActual<Record<string, unknown>>('@/lib/errors')
+ return {
+ ...actual,
+ wrapError: actual.wrapError ?? vi.fn((msg: string, cause: unknown) => {
+ const err = new Error(msg) as Error & { cause?: unknown }
+ err.cause = cause
+ return err
+ }),
+ findPostHogPermissionError: actual.findPostHogPermissionError ?? vi.fn(() => undefined),
+ formatPermissionErrorMessage: actual.formatPermissionErrorMessage ?? vi.fn((e: any) => e.message),
+ buildInsufficientScopeChallenge: actual.buildInsufficientScopeChallenge ?? vi.fn(() => 'Bearer'),
+ }
+})
+
+// Mock @/lib/analytics additions not present on all branches
+vi.mock('@/lib/analytics', async () => {
+ const actual = await vi.importActual<Record<string, unknown>>('@/lib/analytics')
+ return {
+ ...actual,
+ buildMCPAnalyticsGroups: actual.buildMCPAnalyticsGroups ?? vi.fn(() => ({})),
+ buildMCPContextProperties: actual.buildMCPContextProperties ?? vi.fn(() => ({})),
+ evaluateFeatureFlags: actual.evaluateFeatureFlags ?? vi.fn(async () => ({})),
+ }
+})
+
+// Mock template imports that may not exist
+vi.mock('@/templates/cli-proxy-command.md', async () => {
+ try { return await vi.importActual('@/templates/cli-proxy-command.md') } catch { return { default: '' } }
+})
+vi.mock('@/templates/cli-proxy-tool.md', async () => {
+ try { return await vi.importActual('@/templates/cli-proxy-tool.md') } catch { return { default: '' } }
+})
+vi.mock('@/templates/execute-sql-prompt.md', async () => {
+ try { return await vi.importActual('@/templates/execute-sql-prompt.md') } catch { return { default: '' } }
+})
+vi.mock('@/templates/single-exec-instructions.md', async () => {
+ try { return await vi.importActual('@/templates/single-exec-instructions.md') } catch { return { default: '' } }
+})
+
+// Mock @/tools/exec that may not exist
+vi.mock('@/tools/exec', async () => {
+ try { return await vi.importActual('@/tools/exec') } catch {
+ return {
+ createExecTool: vi.fn(() => ({ name: 'posthog', handler: vi.fn() })),
+ createExecInnerToolCallResolver: vi.fn(() => () => undefined),
+ }
+ }
+})
+
+// Mock @/lib/mcpcat
+vi.mock('@/lib/mcpcat', async () => {
+ try { return await vi.importActual('@/lib/mcpcat') } catch {
+ return { initMcpCatObservability: vi.fn() }
+ }
+})
diff --git a/services/mcp/tests/integration/global-setup.ts b/services/mcp/tests/integration/global-setup.ts
new file mode 100644
index 000000000000..a85be6aca9f0
--- /dev/null
+++ b/services/mcp/tests/integration/global-setup.ts
@@ -0,0 +1,38 @@
+// vitest globalSetup hook for the integration suite.
+//
+// MCP UI apps are React bundles emitted to `public/ui-apps/<app>/{main.js,styles.css}`
+// by `scripts/build-ui-apps.ts`. They need to exist on disk before the integration
+// suite runs, because both runtimes (Hono via `serveStatic`, CF via Workers Static
+// Assets) serve them from `./public/`. We build them once per test session and
+// skip if the output is already present (much faster on repeat runs).
+
+import { spawnSync } from 'node:child_process'
+import { existsSync, readdirSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+const MCP_DIR = resolve(__dirname, '..', '..')
+const UI_APPS_DIR = resolve(MCP_DIR, 'public', 'ui-apps')
+
+function uiAppsAlreadyBuilt(): boolean {
+ if (!existsSync(UI_APPS_DIR)) {
+ return false
+ }
+ return readdirSync(UI_APPS_DIR).some((name) =>
+ existsSync(resolve(UI_APPS_DIR, name, 'main.js'))
+ )
+}
+
+export async function setup(): Promise<void> {
+ if (uiAppsAlreadyBuilt()) {
+ return
+ }
+ console.info('[integration setup] Building MCP UI apps (one-time)…')
+ const result = spawnSync('pnpm', ['run', 'build:ui-apps'], {
+ cwd: MCP_DIR,
+ stdio: 'inherit',
+ env: process.env,
+ })
+ if (result.status !== 0) {
+ throw new Error(`build:ui-apps failed (exit code ${result.status})`)
+ }
+}
diff --git a/services/mcp/tests/integration/harness/cf.ts b/services/mcp/tests/integration/harness/cf.ts
new file mode 100644
index 000000000000..c7f8d01c0429
--- /dev/null
+++ b/services/mcp/tests/integration/harness/cf.ts
@@ -0,0 +1,68 @@
+import { createServer } from 'node:net'
+import { unstable_dev, type Unstable_DevWorker } from 'wrangler'
+
+import type { IntegrationEnv, IntegrationHarness } from './types'
+
+// `vars` are baked into workerd at boot, so we need MCP_APPS_BASE_URL to know
+// the listener's port up-front. Bind a Node TCP server to port 0, read the
+// kernel-assigned port, then close — workerd grabs that port a moment later.
+// Tiny race window vs hardcoding a fixed port; tests stay parallel-safe.
+async function reserveFreePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const server = createServer()
+ server.unref()
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address()
+ if (typeof address === 'object' && address && 'port' in address) {
+ const port = address.port
+ server.close(() => resolve(port))
+ } else {
+ server.close(() => reject(new Error('Failed to read assigned port')))
+ }
+ })
+ })
+}
+
+// Boots a real workerd via `wrangler unstable_dev` so the McpAgent framework
+// (Durable Objects, blockConcurrencyWhile, agents SDK) runs end-to-end the same
+// way it does in production. `local: true` keeps everything on the developer
+// machine — no Cloudflare account / network required.
+export async function startCfHarness(env: IntegrationEnv): Promise<IntegrationHarness> {
+ const port = await reserveFreePort()
+ const baseUrl = new URL(`http://127.0.0.1:${port}`)
+
+ const worker: Unstable_DevWorker = await unstable_dev('src/index.ts', {
+ config: 'wrangler.jsonc',
+ local: true,
+ ip: '127.0.0.1',
+ port,
+ // The CF Worker reads `POSTHOG_API_BASE_URL` via the `cloudflare:workers`
+ // env binding, not `process.env`. Pass it through `vars` so the binding
+ // resolves to the local stack. `MCP_APPS_BASE_URL` overrides the value
+ // hard-coded in `wrangler.jsonc` (which points at the production worker).
+ vars: {
+ POSTHOG_API_BASE_URL: env.apiBaseUrl,
+ MCP_APPS_BASE_URL: baseUrl.toString().replace(/\/$/, ''),
+ // Match the workers vitest config — empty values keep observability
+ // paths short-circuited and silence the analytics no-network warning.
+ POSTHOG_ANALYTICS_API_KEY: '',
+ POSTHOG_ANALYTICS_HOST: '',
+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: '',
+ POSTHOG_UI_APPS_TOKEN: '',
+ INKEEP_API_KEY: '',
+ MCP_CAT_PROJECT_ID: '',
+ },
+ experimental: {
+ disableExperimentalWarning: true,
+ disableDevRegistry: true,
+ },
+ // Quiet the dev-server console output so test runs aren't drowned out.
+ logLevel: 'warn',
+ })
+
+ return {
+ baseUrl: new URL(`http://${worker.address}:${worker.port}`),
+ stop: () => worker.stop(),
+ }
+}
diff --git a/services/mcp/tests/integration/harness/hono.ts b/services/mcp/tests/integration/harness/hono.ts
new file mode 100644
index 000000000000..021c2b2679f8
--- /dev/null
+++ b/services/mcp/tests/integration/harness/hono.ts
@@ -0,0 +1,61 @@
+import { serve } from '@hono/node-server'
+import Redis from 'ioredis'
+import type { AddressInfo } from 'node:net'
+
+import { createApp } from '@/hono/app'
+
+import type { IntegrationEnv, IntegrationHarness } from './types'
+
+// Pinned test DB so we don't collide with the dev Redis (DB 0). Must be in
+// 0–15 (Redis default DB count). FLUSHDB at boot is safe because the test
+// owns this DB exclusively. Override via TEST_REDIS_DB if your local Redis is
+// configured with a different db count.
+const TEST_REDIS_DB = parseInt(process.env.TEST_REDIS_DB ?? '15', 10)
+// Integration test harness targets a local dev Redis; production paths set REDIS_URL.
+// nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
+const TEST_REDIS_URL = process.env.TEST_REDIS_URL ?? process.env.REDIS_URL ?? 'redis://localhost:6379'
+
+async function startTestRedis(): Promise<InstanceType<typeof Redis>> {
+ const redis = new Redis(TEST_REDIS_URL, {
+ db: TEST_REDIS_DB,
+ lazyConnect: true,
+ maxRetriesPerRequest: 1,
+ connectTimeout: 2000,
+ })
+ try {
+ await redis.connect()
+ } catch (err) {
+ await redis.quit().catch(() => undefined)
+ throw new Error(
+ `Hono integration harness needs Redis at ${TEST_REDIS_URL} (db ${TEST_REDIS_DB}). ` +
+ `Boot the dev stack with \`./bin/start\`, or override TEST_REDIS_URL/TEST_REDIS_DB. Cause: ${String(err)}`
+ )
+ }
+ await redis.flushdb()
+ return redis
+}
+
+export async function startHonoHarness(env: IntegrationEnv): Promise<IntegrationHarness> {
+ // Route the MCP server's outbound API traffic at the local PostHog stack.
+ // `getBaseUrl()` checks `POSTHOG_API_BASE_URL` first and bypasses region detection.
+ process.env.POSTHOG_API_BASE_URL = env.apiBaseUrl
+
+ const redis = await startTestRedis()
+ const { app } = createApp(redis as unknown as Parameters<typeof createApp>[0])
+ const server = serve({ fetch: app.fetch, port: 0 })
+ const address = server.address() as AddressInfo
+ const baseUrl = new URL(`http://127.0.0.1:${address.port}`)
+
+ // `getEnv()` reads MCP_APPS_BASE_URL on every HonoMcpServer init, so we can
+ // set it after the listener has its port. Pointing at the harness's own
+ // origin so `/ui-apps/<app>/main.js` resolves to this server's static route.
+ process.env.MCP_APPS_BASE_URL = baseUrl.toString().replace(/\/$/, '')
+
+ return {
+ baseUrl,
+ stop: async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ await redis.quit().catch(() => undefined)
+ },
+ }
+}
diff --git a/services/mcp/tests/integration/harness/types.ts b/services/mcp/tests/integration/harness/types.ts
new file mode 100644
index 000000000000..cc495428c455
--- /dev/null
+++ b/services/mcp/tests/integration/harness/types.ts
@@ -0,0 +1,41 @@
+// Shared shape for the per-runtime integration harnesses. Each harness owns
+// the lifecycle of a real listener (Hono via `@hono/node-server`, CF via
+// `wrangler unstable_dev`) and exposes the URL the MCP SDK client connects to.
+
+export type IntegrationHarness = {
+ baseUrl: URL
+ /** Stop the listener and release any resources. Idempotent. */
+ stop: () => Promise<void>
+}
+
+export type IntegrationEnv = {
+ apiToken: string
+ /** Optional second personal API key. When set, the suite runs the
+ * concurrent-sessions isolation test that verifies one client's state
+ * doesn't bleed into another's. */
+ apiToken2?: string | undefined
+ orgId: string
+ projectId: string
+ apiBaseUrl: string
+}
+
+export function loadIntegrationEnv(): IntegrationEnv {
+ const apiToken = process.env.TEST_POSTHOG_PERSONAL_API_KEY
+ const orgId = process.env.TEST_ORG_ID
+ const projectId = process.env.TEST_PROJECT_ID
+
+ if (!apiToken || !orgId || !projectId) {
+ throw new Error(
+ 'Integration tests require TEST_POSTHOG_PERSONAL_API_KEY, TEST_ORG_ID, and TEST_PROJECT_ID to be set. ' +
+ 'See tests/shared/test-utils.ts for how the existing tool integration tests source these.'
+ )
+ }
+
+ return {
+ apiToken,
+ apiToken2: process.env.TEST_POSTHOG_PERSONAL_API_KEY_2 || undefined,
+ orgId,
+ projectId,
+ apiBaseUrl: process.env.TEST_POSTHOG_API_BASE_URL || 'http://localhost:8010',
+ }
+}
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
new file mode 100644
index 000000000000..4475645b4b45
--- /dev/null
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -0,0 +1,383 @@
+// Shared MCP-protocol integration suite. Wires the official @modelcontextprotocol/sdk
+// client against a runtime-supplied transport target and exercises the standard
+// JSON-RPC interactions: initialize handshake, tools/list, tools/call, prompts/list,
+// resources/list, and clean disconnect. Both the Cloudflare and Hono entry points
+// run the same suite so any divergence shows up as a test failure rather than a
+// silent runtime drift.
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js'
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+export type ProtocolTestHarness = {
+ /** Origin used to construct the MCP endpoint URL (e.g. `https://test.local`). */
+ baseUrl: URL
+ /** Fetch implementation routing to the runtime under test. */
+ fetch: typeof fetch
+ /** Bearer token forwarded as the `Authorization` header. */
+ token: string
+ /** Optional second bearer token for the concurrent-sessions isolation test.
+ * When omitted the isolation test is skipped. */
+ token2?: string | undefined
+ /** Whether the runtime is stateless (no session store). Stateless runtimes
+ * ignore unknown Mcp-Session-Id headers instead of rejecting them. */
+ stateless?: boolean | undefined
+}
+
+function buildStreamableClient(
+ harness: ProtocolTestHarness,
+ token: string = harness.token
+): { client: Client; transport: StreamableHTTPClientTransport } {
+ const transport = new StreamableHTTPClientTransport(new URL('/mcp', harness.baseUrl), {
+ fetch: harness.fetch,
+ requestInit: { headers: { Authorization: `Bearer ${token}` } },
+ })
+ const client = new Client({ name: 'mcp-integration-test', version: '0.0.0' }, { capabilities: {} })
+ return { client, transport }
+}
+
+// SDK exposes `sessionId` as `string | undefined` but the `Transport` interface
+// declares it as `string`. The runtime contract is satisfied (the transport
+// sets the id after the initialize handshake); the assignability mismatch is a
+// type-definition quirk we paper over at the seam.
+type ConnectableTransport = Parameters<Client['connect']>[0]
+
+async function safeClose(client: Client | undefined): Promise<void> {
+ try {
+ await client?.close()
+ } catch {
+ // SDK Client.close throws if already closed; harmless during teardown.
+ }
+}
+
+export function defineMcpProtocolTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP protocol (${label})`, () => {
+ let client: Client
+
+ beforeEach(async () => {
+ const harness = await getHarness()
+ const built = buildStreamableClient(harness)
+ client = built.client
+ await client.connect(built.transport as ConnectableTransport)
+ })
+
+ afterEach(async () => {
+ await safeClose(client)
+ })
+
+ it('reports server name and version after the initialize handshake', () => {
+ const info = client.getServerVersion()
+ expect(info?.name).toBe('PostHog')
+ expect(info?.version).toBeTruthy()
+ })
+
+ it('lists available tools with non-empty schemas', async () => {
+ const { tools } = await client.listTools()
+ expect(tools.length).toBeGreaterThan(0)
+
+ const sample = tools[0]
+ if (!sample) {
+ throw new Error('expected at least one tool')
+ }
+ expect(sample.name).toBeTruthy()
+ expect(sample.inputSchema).toBeTruthy()
+ expect(sample.inputSchema.type).toBe('object')
+ })
+
+ it('exposes a known PostHog tool (organization-get)', async () => {
+ const { tools } = await client.listTools()
+ const names = tools.map((t) => t.name)
+ expect(names).toContain('organization-get')
+ })
+
+ // Prompts and resources are populated at runtime from context-mill's
+ // GitHub release. When the fetch fails (offline, sandbox, blocked TLS)
+ // the McpServer doesn't claim those capabilities and the SDK surfaces
+ // -32601. We accept either outcome here so the suite is robust to a
+ // missing context-mill build artifact.
+ it('lists prompts (empty or unsupported)', async () => {
+ try {
+ const { prompts } = await client.listPrompts()
+ expect(Array.isArray(prompts)).toBe(true)
+ } catch (err) {
+ expect(String(err)).toMatch(/Method not found|-32601/)
+ }
+ })
+
+ it('lists resources (empty or unsupported)', async () => {
+ try {
+ const { resources } = await client.listResources()
+ expect(Array.isArray(resources)).toBe(true)
+ } catch (err) {
+ expect(String(err)).toMatch(/Method not found|-32601/)
+ }
+ })
+
+ it('reads a registered resource end-to-end', async ({ skip }) => {
+ // Resources come from two sources at runtime: context-mill (a GitHub
+ // release fetched at init) and `registerUiAppResources`. If neither
+ // produced any registrations the protocol method is "not found" and
+ // there's nothing to read — skip rather than fail.
+ let resources: Awaited<ReturnType<Client['listResources']>>['resources']
+ try {
+ resources = (await client.listResources()).resources
+ } catch {
+ skip('No resources registered (resources/list returned -32601).')
+ return
+ }
+ if (resources.length === 0) {
+ skip('No resources registered.')
+ return
+ }
+ // Pick the first resource; assert listing shape, then exercise the
+ // resources/read JSON-RPC call which hits a different code path.
+ const first = resources[0]
+ if (!first) {
+ throw new Error('expected at least one resource')
+ }
+ expect(first.uri).toBeTruthy()
+ expect(first.mimeType).toBeTruthy()
+
+ const result = await client.readResource({ uri: first.uri })
+ expect(Array.isArray(result.contents)).toBe(true)
+ expect(result.contents.length).toBeGreaterThan(0)
+ expect(result.contents[0]?.uri).toBe(first.uri)
+ })
+
+ it('calls a tool and returns content blocks', async () => {
+ const result = await client.callTool({
+ name: 'organization-get',
+ arguments: {},
+ })
+ if (result.isError) {
+ throw new Error(`tool returned error: ${JSON.stringify(result.content)}`)
+ }
+ expect(Array.isArray(result.content)).toBe(true)
+ expect((result.content as unknown[]).length).toBeGreaterThan(0)
+ })
+
+ it('returns an error result for an unknown tool name', async () => {
+ // `callTool` resolves successfully and surfaces the error in the
+ // tool-call payload rather than rejecting the JSON-RPC call.
+ const result = await client.callTool({
+ name: 'no-such-tool-exists',
+ arguments: {},
+ })
+ expect(result.isError).toBe(true)
+ })
+
+ // Concurrent sessions with different bearer tokens must not see each
+ // other's state. Different tokens hash to different `userHash`es, which
+ // is what the SessionRegistry (Hono) and DurableObject naming (CF) key
+ // off — so a regression in either would let one client's tool registry,
+ // organization context, or cached responses leak into the other's view.
+ // Two-step assertion: each client (a) initializes successfully against
+ // a different token, and (b) gets its own copy of the tool list with
+ // the same canonical entries. If session lookup ever cross-pollinates
+ // by accident, both clients would fail to initialize cleanly.
+ it('isolates state between concurrent sessions on different tokens', async ({ skip }) => {
+ const harness = await getHarness()
+ if (!harness.token2) {
+ skip('Set TEST_POSTHOG_PERSONAL_API_KEY_2 to run the concurrent-sessions isolation test.')
+ return
+ }
+
+ const a = buildStreamableClient(harness, harness.token)
+ const b = buildStreamableClient(harness, harness.token2)
+
+ try {
+ await Promise.all([
+ a.client.connect(a.transport as ConnectableTransport),
+ b.client.connect(b.transport as ConnectableTransport),
+ ])
+
+ // Both clients should resolve initialize against their own session.
+ expect(a.client.getServerVersion()?.name).toBe('PostHog')
+ expect(b.client.getServerVersion()?.name).toBe('PostHog')
+
+ const [toolsA, toolsB] = await Promise.all([a.client.listTools(), b.client.listTools()])
+
+ // Each session got a tool list (no cross-talk that would surface as
+ // empty/missing tools on one side).
+ expect(toolsA.tools.length).toBeGreaterThan(0)
+ expect(toolsB.tools.length).toBeGreaterThan(0)
+ expect(toolsA.tools.map((t) => t.name)).toContain('organization-get')
+ expect(toolsB.tools.map((t) => t.name)).toContain('organization-get')
+ } finally {
+ await Promise.all([safeClose(a.client), safeClose(b.client)])
+ }
+ })
+ })
+}
+
+// MCP UI apps coverage (the `@modelcontextprotocol/ext-apps` extension).
+// Tools wrapped with `withUiApp(...)` advertise a `_meta.ui.resourceUri` on
+// every call result. Clients fetch that URI via `resources/read` to get an
+// HTML stub that loads the per-app JS+CSS bundle from `${MCP_APPS_BASE_URL}/ui-apps/<app>/`.
+//
+// Failures this catches:
+// - Tool decorator stripped or not wired through registerTool (no `_meta`)
+// - `registerUiAppResources` skipped (e.g. MCP_APPS_BASE_URL missing)
+// - HTML stub generation produces wrong asset URLs
+// - Static-asset serving broken (Hono `serveStatic` route, CF Workers Static Assets)
+export function defineUiAppProtocolTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP UI apps (${label})`, () => {
+ let client: Client
+ let harness: ProtocolTestHarness
+
+ beforeEach(async () => {
+ harness = await getHarness()
+ const built = buildStreamableClient(harness)
+ client = built.client
+ await client.connect(built.transport as ConnectableTransport)
+ })
+
+ afterEach(async () => {
+ await safeClose(client)
+ })
+
+ // The UI metadata is on the *tool definition* (returned in `tools/list`),
+ // not on per-call results — that's how the ext-apps SDK + clients
+ // discover which UI app to render. We pull the URI here once and reuse
+ // it across the next two tests.
+ async function findDebugUiResourceUri(): Promise<string> {
+ const { tools } = await client.listTools()
+ const debug = tools.find((t) => t.name === 'debug-mcp-ui-apps')
+ if (!debug) {
+ throw new Error('debug-mcp-ui-apps tool not registered')
+ }
+ const meta = (debug as { _meta?: { ui?: { resourceUri?: string } } })._meta
+ const uri = meta?.ui?.resourceUri
+ if (!uri) {
+ throw new Error(
+ `debug-mcp-ui-apps tool definition is missing _meta.ui.resourceUri (got ${JSON.stringify(meta)})`
+ )
+ }
+ return uri
+ }
+
+ it('advertises a UI resource URI on the debug-mcp-ui-apps tool', async () => {
+ const uri = await findDebugUiResourceUri()
+ expect(uri).toMatch(/^ui:\/\/|^mcp-ext-app:\/\//)
+ })
+
+ it('reads the ext-app resource and returns an HTML stub', async () => {
+ const uri = await findDebugUiResourceUri()
+ const resource = await client.readResource({ uri })
+ expect(resource.contents.length).toBeGreaterThan(0)
+ const first = resource.contents[0]
+ if (!first) {
+ throw new Error('expected resource contents to be non-empty')
+ }
+ const text = 'text' in first ? String(first.text ?? '') : ''
+ expect(text).toContain('<!DOCTYPE html>')
+ // Stub references the per-app bundle on whichever origin
+ // MCP_APPS_BASE_URL points at — the harness sets it to its own origin.
+ expect(text).toMatch(/\/ui-apps\/debug\/main\.js/)
+ })
+
+ it('serves the UI app static asset over HTTP', async () => {
+ // The asset URL is `${MCP_APPS_BASE_URL}/ui-apps/<app>/main.js`.
+ // Hono uses @hono/node-server's serveStatic; CF uses the Workers
+ // Static Assets binding configured in wrangler.jsonc.
+ const assetUrl = new URL('/ui-apps/debug/main.js', harness.baseUrl)
+ const response = await harness.fetch(assetUrl)
+ expect(response.status).toBe(200)
+ const ctype = response.headers.get('content-type') || ''
+ expect(ctype).toMatch(/javascript|ecmascript/)
+ const body = await response.text()
+ expect(body.length).toBeGreaterThan(0)
+ })
+ })
+}
+
+// Transport-level resilience that the higher-level SDK suites don't reach:
+// - the legacy `/sse → /mcp` 308 redirect (deprecation contract)
+// - the 404-on-unknown-session-id contract that clients lean on to recover
+// after a pod is gone (graceful-shutdown story; spec-required behavior)
+export function defineResilienceTests(
+ label: string,
+ getHarness: () => Promise<ProtocolTestHarness> | ProtocolTestHarness
+): void {
+ describe(`MCP transport resilience (${label})`, () => {
+ // /sse is deprecated; clients still pointed at the legacy URL must land
+ // on /mcp with the `_deprecated=sse` marker so analytics can correlate.
+ // The redirect is `manual` because some fetch implementations follow
+ // 308s automatically and we want to assert on the response itself.
+ it('redirects /sse to /mcp with the _deprecated=sse marker', async () => {
+ const harness = await getHarness()
+ const sseUrl = new URL('/sse', harness.baseUrl)
+ const response = await harness.fetch(sseUrl, { redirect: 'manual' })
+ expect(response.status).toBe(308)
+ const location = response.headers.get('location')
+ expect(location).toBeTruthy()
+ const target = new URL(location!)
+ expect(target.pathname).toBe('/mcp')
+ expect(target.searchParams.get('_deprecated')).toBe('sse')
+ })
+
+ it('redirects /sse subpaths to /mcp subpaths', async () => {
+ const harness = await getHarness()
+ const sseSubpath = new URL('/sse/message', harness.baseUrl)
+ const response = await harness.fetch(sseSubpath, { redirect: 'manual' })
+ expect(response.status).toBe(308)
+ const target = new URL(response.headers.get('location')!)
+ expect(target.pathname).toBe('/mcp/message')
+ expect(target.searchParams.get('_deprecated')).toBe('sse')
+ })
+
+ // Stateful runtimes (CF Durable Objects) reject unknown session IDs with
+ // a 4xx so the client re-runs `initialize`. Stateless runtimes (Hono) ignore
+ // the header and process the request normally — there are no sessions to validate.
+ it('rejects requests with an unknown Mcp-Session-Id so the client re-inits', async () => {
+ const harness = await getHarness()
+ if (harness.stateless) {
+ const mcpUrl = new URL('/mcp', harness.baseUrl)
+ const response = await harness.fetch(mcpUrl, {
+ method: 'POST',
+ redirect: 'manual',
+ headers: {
+ Authorization: `Bearer ${harness.token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ 'Mcp-Session-Id': 'session-that-does-not-exist',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'recovery-probe',
+ method: 'tools/list',
+ params: {},
+ }),
+ })
+ expect(response.status).toBeLessThan(500)
+ return
+ }
+
+ const mcpUrl = new URL('/mcp', harness.baseUrl)
+ const response = await harness.fetch(mcpUrl, {
+ method: 'POST',
+ redirect: 'manual',
+ headers: {
+ Authorization: `Bearer ${harness.token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ 'Mcp-Session-Id': 'session-that-does-not-exist',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 'recovery-probe',
+ method: 'tools/list',
+ params: {},
+ }),
+ })
+ expect(response.status).toBeGreaterThanOrEqual(400)
+ expect(response.status).toBeLessThan(500)
+ })
+ })
+}
diff --git a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts
new file mode 100644
index 000000000000..c49577615824
--- /dev/null
+++ b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts
@@ -0,0 +1,41 @@
+import { afterAll, beforeAll } from 'vitest'
+
+import { startCfHarness } from './harness/cf'
+import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'
+import { defineMcpProtocolTests, defineResilienceTests, defineUiAppProtocolTests } from './mcp-protocol-suite'
+
+// End-to-end MCP protocol test against the Cloudflare Workers runtime.
+// - Real workerd via `wrangler unstable_dev` (DurableObjects, agents SDK,
+// blockConcurrencyWhile, partyserver — all live)
+// - Real PostHog stack at `TEST_POSTHOG_API_BASE_URL` (defaults to localhost:8010)
+// - Real personal API key from `TEST_POSTHOG_PERSONAL_API_KEY`
+//
+// Boot the local PostHog stack with `./bin/start` before running this suite.
+
+let env: IntegrationEnv
+let harness: IntegrationHarness
+
+beforeAll(async () => {
+ env = loadIntegrationEnv()
+ harness = await startCfHarness(env)
+}, 60_000)
+
+afterAll(async () => {
+ await harness?.stop()
+})
+
+const harnessFor = (): {
+ baseUrl: URL
+ fetch: typeof fetch
+ token: string
+ token2: string | undefined
+} => ({
+ baseUrl: harness.baseUrl,
+ fetch: globalThis.fetch,
+ token: env.apiToken,
+ token2: env.apiToken2,
+})
+
+defineMcpProtocolTests('Cloudflare Workers (real stack)', harnessFor)
+defineResilienceTests('Cloudflare Workers (real stack)', harnessFor)
+defineUiAppProtocolTests('Cloudflare Workers (real stack)', harnessFor)
diff --git a/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts b/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
new file mode 100644
index 000000000000..f075390482fc
--- /dev/null
+++ b/services/mcp/tests/integration/mcp-protocol.hono.integration.test.ts
@@ -0,0 +1,44 @@
+import { afterAll, beforeAll } from 'vitest'
+
+import { startHonoHarness } from './harness/hono'
+import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'
+import { defineMcpProtocolTests, defineResilienceTests, defineUiAppProtocolTests } from './mcp-protocol-suite'
+
+// End-to-end MCP protocol test against the Hono runtime.
+// - Real `@hono/node-server` listener (TCP + HTTP semantics, not `app.request`)
+// - Real PostHog stack at `TEST_POSTHOG_API_BASE_URL` (defaults to localhost:8010)
+// - Real personal API key from `TEST_POSTHOG_PERSONAL_API_KEY`
+//
+// Boot the local PostHog stack with `./bin/start` before running this suite.
+// Ensure `.env.test` defines TEST_POSTHOG_PERSONAL_API_KEY / TEST_ORG_ID /
+// TEST_PROJECT_ID — matching the existing `tests/tools/*.integration.test.ts`.
+
+let env: IntegrationEnv
+let harness: IntegrationHarness
+
+beforeAll(async () => {
+ env = loadIntegrationEnv()
+ harness = await startHonoHarness(env)
+})
+
+afterAll(async () => {
+ await harness?.stop()
+})
+
+const harnessFor = (): {
+ baseUrl: URL
+ fetch: typeof fetch
+ token: string
+ token2: string | undefined
+ stateless: boolean
+} => ({
+ baseUrl: harness.baseUrl,
+ fetch: globalThis.fetch,
+ token: env.apiToken,
+ token2: env.apiToken2,
+ stateless: true,
+})
+
+defineMcpProtocolTests('Hono (real stack)', harnessFor)
+defineResilienceTests('Hono (real stack)', harnessFor)
+defineUiAppProtocolTests('Hono (real stack)', harnessFor)
diff --git a/services/mcp/tests/workers/mcp-protocol.test.ts b/services/mcp/tests/workers/mcp-protocol.test.ts
new file mode 100644
index 000000000000..04da57e37fa2
--- /dev/null
+++ b/services/mcp/tests/workers/mcp-protocol.test.ts
@@ -0,0 +1,88 @@
+import { SELF } from 'cloudflare:test'
+import { describe, expect, it } from 'vitest'
+
+// HTTP-layer integration tests for the Cloudflare Workers entry point.
+//
+// Why this suite is narrower than the Hono one (`tests/hono/mcp-protocol.test.ts`):
+// the McpAgent framework wraps session init in `blockConcurrencyWhile()` on a
+// Durable Object. The workerd test runtime imposes a ~30s ceiling on that
+// primitive, and the full init flow (tool registration, region detect,
+// dual-region API fan-out) trips it under workerd's higher per-call overhead.
+// The Hono harness exercises the full SDK-client → MCP-server protocol loop
+// over the same shared suite, and the existing `tests/workers/*.test.ts` files
+// cover the DO internals via `runInDurableObject`. That leaves the entry-point
+// HTTP behavior as the gap this file fills.
+describe('MCP HTTP entry point (Cloudflare Workers)', () => {
+ describe('OAuth Protected Resource Metadata (RFC 9728)', () => {
+ it('returns metadata advertising scopes_supported for /mcp', async () => {
+ const response = await SELF.fetch(
+ 'https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp'
+ )
+
+ expect(response.status).toBe(200)
+ expect(response.headers.get('content-type')).toContain('application/json')
+ const body = (await response.json()) as Record<string, unknown>
+ expect(body.resource).toBe('https://mcp.posthog.com/mcp')
+ expect(Array.isArray(body.authorization_servers)).toBe(true)
+ expect(Array.isArray(body.scopes_supported)).toBe(true)
+ expect((body.scopes_supported as string[]).length).toBeGreaterThan(0)
+ expect(body.bearer_methods_supported).toEqual(['header'])
+ })
+
+ it('returns metadata for /sse with the same shape', async () => {
+ const response = await SELF.fetch(
+ 'https://mcp.posthog.com/.well-known/oauth-protected-resource/sse'
+ )
+
+ expect(response.status).toBe(200)
+ const body = (await response.json()) as Record<string, unknown>
+ expect(body.resource).toBe('https://mcp.posthog.com/sse')
+ })
+ })
+
+ describe('Authentication challenges', () => {
+ it('returns 401 with WWW-Authenticate Bearer + resource_metadata when no token', async () => {
+ const response = await SELF.fetch('https://mcp.posthog.com/mcp', { method: 'POST' })
+
+ expect(response.status).toBe(401)
+ const challenge = response.headers.get('WWW-Authenticate') || ''
+ expect(challenge).toContain('Bearer')
+ expect(challenge).toContain('resource_metadata=')
+ expect(challenge).toContain('/.well-known/oauth-protected-resource/mcp')
+ })
+
+ it('returns 401 for malformed bearer tokens (wrong prefix)', async () => {
+ const response = await SELF.fetch('https://mcp.posthog.com/mcp', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer not_a_posthog_token' },
+ })
+
+ expect(response.status).toBe(401)
+ expect(await response.text()).toContain('Invalid token')
+ })
+ })
+
+ describe('Authorization server redirects', () => {
+ it('redirects /.well-known/oauth-authorization-server to the auth server', async () => {
+ const response = await SELF.fetch(
+ 'https://mcp.posthog.com/.well-known/oauth-authorization-server',
+ { redirect: 'manual' }
+ )
+
+ expect(response.status).toBe(302)
+ const location = response.headers.get('location') || ''
+ expect(location).toContain('/.well-known/oauth-authorization-server')
+ })
+
+ it('rewrites /register to /oauth/register with a 307 (preserves POST)', async () => {
+ const response = await SELF.fetch('https://mcp.posthog.com/register', {
+ method: 'POST',
+ redirect: 'manual',
+ })
+
+ expect(response.status).toBe(307)
+ const location = response.headers.get('location') || ''
+ expect(location).toContain('/oauth/register')
+ })
+ })
+})
diff --git a/services/mcp/types.d.ts b/services/mcp/types.d.ts
index 83a9754caea2..e46f54a24b74 100644
--- a/services/mcp/types.d.ts
+++ b/services/mcp/types.d.ts
@@ -4,3 +4,11 @@ declare namespace Cloudflare {
MCP_CAT_PROJECT_ID: string | undefined
}
}
+
+// ioredis v4 ships without bundled type declarations. We only use the default
+// export (constructor) — typed loosely as `any` so TS can still check call sites
+// that interact with it via the local `RedisLike` interface.
+declare module 'ioredis' {
+ const Redis: any
+ export default Redis
+}
diff --git a/services/mcp/vitest.config.mts b/services/mcp/vitest.config.mts
index 6d8d57fa9377..06d8de7288ed 100644
--- a/services/mcp/vitest.config.mts
+++ b/services/mcp/vitest.config.mts
@@ -38,6 +38,7 @@ export default defineConfig({
'dist/**',
'tests/**/*.integration.test.ts',
'tests/workers/**',
+ 'tests/hono/**',
],
},
},
diff --git a/services/mcp/vitest.hono.config.mts b/services/mcp/vitest.hono.config.mts
new file mode 100644
index 000000000000..e2416dc74454
--- /dev/null
+++ b/services/mcp/vitest.hono.config.mts
@@ -0,0 +1,27 @@
+import tsconfigPaths from 'vite-tsconfig-paths'
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ plugins: [
+ tsconfigPaths({ root: '.' }),
+ {
+ name: 'text-loader',
+ transform(code, id) {
+ if (id.endsWith('.md') || id.endsWith('.html')) {
+ return {
+ code: `export default ${JSON.stringify(code)}`,
+ map: null,
+ }
+ }
+ },
+ },
+ ],
+ test: {
+ globals: true,
+ environment: 'node',
+ testTimeout: 15000,
+ setupFiles: ['tests/hono/setup.ts'],
+ include: ['tests/hono/**/*.test.ts'],
+ exclude: ['node_modules/**', 'dist/**', 'tests/hono/**/*.integration.test.ts'],
+ },
+})
diff --git a/services/mcp/vitest.integration.config.mts b/services/mcp/vitest.integration.config.mts
index afed9586728c..c307e636fe75 100644
--- a/services/mcp/vitest.integration.config.mts
+++ b/services/mcp/vitest.integration.config.mts
@@ -1,16 +1,35 @@
import tsconfigPaths from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
+// The Hono and worker entry points import `*.md` and `*.html` template files
+// directly. Vitest's default loader rejects those as JS, so we register a tiny
+// transform that stringifies their contents. Mirrors the loader in the other
+// vitest configs.
+const textLoader = {
+ name: 'text-loader',
+ transform(code: string, id: string) {
+ if (id.endsWith('.md') || id.endsWith('.html')) {
+ return {
+ code: `export default ${JSON.stringify(code)}`,
+ map: null,
+ }
+ }
+ },
+}
+
export default defineConfig({
- plugins: [tsconfigPaths({ root: '.' })],
+ plugins: [tsconfigPaths({ root: '.' }), textLoader],
test: {
globals: true,
environment: 'node',
testTimeout: 30000,
retry: 1, // Retry failed tests once to handle flaky integration tests
setupFiles: ['tests/setup.ts'],
+ // Builds `public/ui-apps/*` once per test session if missing — required for
+ // the MCP-protocol integration tests that exercise UI app resources.
+ globalSetup: ['tests/integration/global-setup.ts'],
include: ['tests/**/*.integration.test.ts'],
- exclude: ['node_modules/**', 'dist/**'],
+ exclude: ['node_modules/**', 'dist/**', 'tests/hono/**'],
// Run test files sequentially to reduce parallel API load
fileParallelism: false,
// Limit concurrent tests within a file