: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(mcp): remove the Cloudflare durable object MCP server (#61841)
Georgiy Tarasovcbb957043b3f
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 384ef34be629..a4a34d4a66ea 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3807,9 +3807,6 @@ importers:'@toon-format/toon':specifier: ^2.1.0version: 2.1.0- agents:- specifier: 0.10.2- version: 0.10.2(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])ai:specifier: ^6.0.0version: 6.0.77([email protected])@@ -4061,10 +4058,6 @@ packages:'@antfu/[email protected]':resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}- '@apidevtools/[email protected]':- resolution: {integrity: sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ==}- engines: {node: '>= 16'}-'@aws-crypto/[email protected]':resolution: {integrity: sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==}engines: {node: '>=16.0.0'}@@ -4720,12 +4713,6 @@ packages:peerDependencies:'@babel/core': ^7.0.0-0- '@babel/[email protected]':- resolution: {integrity: sha512-CVBVv3VY/XRMxRYq5dwr2DS7/MvqPm23cOCjbwNnVrfOqcWlnefua1uUs0sjdKOGjvPUG633o07uWzJq4oI6dA==}- engines: {node: '>=6.9.0'}- peerDependencies:- '@babel/core': ^7.0.0-0-'@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2':resolution: {integrity: sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==}engines: {node: '>=6.9.0'}@@ -4753,12 +4740,6 @@ packages:peerDependencies:'@babel/core': ^7.0.0-0- '@babel/[email protected]':- resolution: {integrity: sha512-71EYI0ONURHJBL4rSFXnITXqXrrY8q4P0q006DPfN+Rk+ASM+++IBXem/ruokgBZR8YNEWZ8R6B+rCb8VcUTqA==}- engines: {node: '>=6.9.0'}- peerDependencies:- '@babel/core': ^7.0.0-0-'@babel/[email protected]':resolution: {integrity: sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==}peerDependencies:@@ -5225,10 +5206,6 @@ packages:'@babel/[email protected]':resolution: {integrity: sha512-x/rqGMdzj+fWZvCOYForTghzbtqPDZ5gPwaoNGHdgDfF2QA/XZbCBp4Moo5scrkAMPhB7z26XM/AaHuIJdgauA==}- '@babel/[email protected]':- resolution: {integrity: sha512-Lc94FOD5+0aXhdb0Tdg3RUtqT6yWbI/BbFWvlaSJ3gAb9Ks+99nHRDKADVqC37er4eCB0fHyWT+y+K3QOvJKbw==}- engines: {node: '>=6.9.0'}-'@babel/[email protected]':resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}engines: {node: '>=6.9.0'}@@ -7194,9 +7171,6 @@ packages:'@js-sdsl/[email protected]':resolution: {integrity: sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==}- '@jsdevtools/[email protected]':- resolution: {integrity: sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==}-'@jsonjoy.com/[email protected]':resolution: {integrity: sha512-q6XAnWQDIMA3+FTiOYajoYqySkO+JSat0ytXGSuRdq9uXE7o92gzuQwQM14xaCRlBLGq3v5miDGC4vkVTn54xA==}engines: {node: '>=10.0'}@@ -7625,12 +7599,6 @@ packages:'@napi-rs/[email protected]':resolution: {integrity: sha512-z8YVS3XszxFTO73iwvFDNpQIzdMmSDTP/mB3E/ucR37V3Sx57hSExcXyMoNwaucWxnsWf4xfbZv0iZ30jr0M4Q==}- '@napi-rs/[email protected]':- resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==}- peerDependencies:- '@emnapi/core': ^1.7.1- '@emnapi/runtime': ^1.7.1-'@nicolo-ribaudo/[email protected]':resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==}@@ -8213,9 +8181,6 @@ packages:'@orval/[email protected]':resolution: {integrity: sha512-MV75Xzz28W3ZttloNNmdTPa96AneY8FZExEwxmcySdY7lirJtErsqXt2EHnorETDAVEvSldVszhWG/AXpFBAPg==}- '@oxc-project/[email protected]':- resolution: {integrity: sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==}-'@oxc-resolver/[email protected]':resolution: {integrity: sha512-wYe+dlF8npM7cwopOOxbdNjtmJp17e/xF5c0K2WooQXy5VOh74icydM33+Uh/SZDgwyum09/U1FVCX5GdeQk+A==}cpu: [arm64]@@ -9630,124 +9595,9 @@ packages:'@remote-ui/[email protected]':resolution: {integrity: sha512-P1kN1F3p0oMgnLN8Of1Ie9am3sLvJ7nhqHH1pvzkrxqjVwhhyPVZNcwOHyUNZPKp62izhDavdrcnqrdXzVJqGA==}- '@rolldown/[email protected]':- resolution: {integrity: sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [android]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [darwin]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [darwin]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [freebsd]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm]- os: [linux]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [ppc64]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [s390x]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [linux]- libc: [musl]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [openharmony]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==}- engines: {node: '>=14.0.0'}- cpu: [wasm32]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-KmoUoU7HnN+Si5YWJigfTws1jz1bKBYDQKdbLspz0UaqjjFkddHsqorgiW1mxcAj88lYUE6NC/zJNwT+SloqtA==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [win32]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [win32]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-+zEk16yGlz1F9STiRr6uG9hmIXb6nprjLczV/htGptYuLoCuxb+itZ03RKCEeOhBpDDd1NU7qF6x1VLMUp62bw==}- engines: {node: '>=22.12.0 || ^24.0.0'}- peerDependencies:- '@babel/core': ^7.29.0 || ^8.0.0-rc.1- '@babel/plugin-transform-runtime': ^7.29.0 || ^8.0.0-rc.1- '@babel/runtime': ^7.27.0 || ^8.0.0-rc.1- rolldown: ^1.0.0-rc.5- vite: ^8.0.0- peerDependenciesMeta:- '@babel/plugin-transform-runtime':- optional: true- '@babel/runtime':- optional: true- vite:- optional: true-'@rolldown/[email protected]':resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}- '@rolldown/[email protected]':- resolution: {integrity: sha512-UromN0peaE53IaBRe9W7CjrZgXl90fqGpK+mIZbA3qSTeYqg3pqpROBdIPvOG3F5ereDHNwoHBI2e50n1BDr1g==}-'@rolldown/[email protected]':resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==}@@ -11565,9 +11415,6 @@ packages:'@tybys/[email protected]':resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}- '@tybys/[email protected]':- resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}-'@tybys/[email protected]':resolution: {integrity: sha512-6+7nlbMVX/PVDCwaIQ8nTOPveOcFLSt8GcXdx8hD0bt39uWxYT88uXzqTd4fTvqta7oeUJqudepapKNt2DYJFw==}@@ -12731,39 +12578,6 @@ packages:resolution: {integrity: sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==}engines: {node: '>= 14'}- resolution: {integrity: sha512-zltFKKENDClZgIJB7aRneI8tRpnCbMbP4RGPh4t8OgqKHomxUNZJEqMrjcgwP/0FX1W9GGrrLJVo9Ez2ibHVvA==}- hasBin: true- peerDependencies:- '@ai-sdk/openai': ^3.0.0- '@ai-sdk/react': ^3.0.0- '@cloudflare/ai-chat': ^0.4.2- '@cloudflare/codemode': ^0.3.4- '@x402/core': ^2.0.0- '@x402/evm': ^2.0.0- ai: ^6.0.0- react: 18.3.1- viem: '>=2.0.0'- vite: '>=6.0.0 <9.0.0'- zod: ^4.0.0- peerDependenciesMeta:- '@ai-sdk/openai':- optional: true- '@ai-sdk/react':- optional: true- '@cloudflare/ai-chat':- optional: true- '@cloudflare/codemode':- optional: true- '@x402/core':- optional: true- '@x402/evm':- optional: true- viem:- optional: true- vite:- optional: true-resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==}engines: {node: '>=8'}@@ -13653,10 +13467,6 @@ packages:resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}engines: {node: '>=12'}- resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==}- engines: {node: '>=20'}-resolution: {integrity: sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==}engines: {node: '>=6'}@@ -13876,9 +13686,6 @@ packages:resolution: {integrity: sha512-4ZIyeNbW/Cn1wkMMDy+mvrRUxrwFNjKwbhCfQpDd+eLgYipDqp8oGFGtLmhh18EDPKA0g3VUBYOxQGGwvWLVpA==}- resolution: {integrity: sha512-XM4RFka59xATyJv/cS3O3Kml72hQXUeGRuuTmMYFxwzc9/7C8OYTaIR/Ji+Yt8DXzsFLNhat15cE/JP15HrCgw==}-resolution: {integrity: sha512-7vsMc/Lty6AGnn7uFpYT56QesI5D2Y/UkgKounk87OP9Z2H9Z8kj6jzcSGAxFmUtDOS0ntK6lbQz+Nsa0Jj6mQ==}@@ -13959,10 +13766,6 @@ packages:resolution: {integrity: sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==}engines: {node: '>=18'}- resolution: {integrity: sha512-BoZaseYGXOo5j5HUwTaegIog3JJbuH4BbrY9A1ArLjXpy+RWb3mV28F/9Gv1dDA7E2L8kngWva4NWisnLTyfgQ==}- engines: {node: '>=20'}-resolution: {integrity: sha512-XnW4vuK/jPJjmTyDWiej1Zq36Od7ITwxaV2O1pzHZuyMVvdy7NAvyvIBzybt+idqSpfqYuoDG7uf/ocGtJVWxA==}hasBin: true@@ -14966,9 +14769,6 @@ packages:resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}engines: {node: '>= 0.6'}- resolution: {integrity: sha512-Gs6RLjzlLRdT8X9ZipJdIZI/Y6/HhRLyq9RdDlCsnpxr/+Nn6bU2EFGuC94GjxqhM+Nmij2Vcq98yoHrU8uNFQ==}-resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}engines: {node: '>=6'}@@ -16955,9 +16755,6 @@ packages:resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}engines: {node: '>=10'}- resolution: {integrity: sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==}-resolution: {integrity: sha512-qJFDTcgBGvuPzsck0jNm1puKvJQ3AL8J3bIyrvF1KfsbljOVj8N/o9Kbr8RXlBx1J8aapcRpMCiG6h1l6QgYhQ==}@@ -17032,11 +16829,6 @@ packages:resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==}- resolution: {integrity: sha512-Su9oK8DR4xCmDsLlyvadkXzX6+GGXJpbhwoLtOGArAG61dvbW4YQmSEno2y66ahpIdmLMg6YUf/QHLgiwvkrHQ==}- engines: {node: '>=16.0.0'}- hasBin: true-resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}@@ -17949,9 +17741,6 @@ packages:engines: {node: '>=10.0.0'}hasBin: true- resolution: {integrity: sha512-eQXpbNrtxLCjUtiVbR/qR09dbPgZ2o+KR1uA7QKqGhbn8QV7HIL16mXXsobBL4/8TqoYh1us31kfz+dNfCev9g==}-resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}engines: {node: '>=6'}@@ -18192,11 +17981,6 @@ packages:engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}hasBin: true- resolution: {integrity: sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ==}- engines: {node: ^18 || >=20}- hasBin: true-resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}@@ -18676,19 +18460,6 @@ packages:resolution: {integrity: sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==}- resolution: {integrity: sha512-StSs0oY8RmTxjGNil7VbCG4gnTN+4rYX20fiUIItAxTPpr/5rPDZT6PIvMROkk9M1Gn7GzE1wuQXwhxceaGhXA==}- peerDependencies:- '@cloudflare/workers-types': ^4.20240729.0-- resolution: {integrity: sha512-d7xFv+ZC7x0p/DAHWJ5FhxQhimIx+ucyZY+kxL0cKddLBmK9c4p2tEA/L+dOOrWm6EYrRwrBjKQV0uSzOY9x1w==}- peerDependencies:- react: 18.3.1- peerDependenciesMeta:- react:- optional: true-resolution: {integrity: sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==}@@ -20356,11 +20127,6 @@ packages:resolution: {integrity: sha512-ndEIpszUHiG4HtDsQLeIuMvRsDnn8c8rYStabochtUeCvfuvNptb5TUbVD68LRAILPX7p9nqQGh4xJgn3EHS/g==}- resolution: {integrity: sha512-Ff31guA5zT6WjnGp0SXw76X6hzGRk/OQq2hE+1lcDe+lJdHSgnSX6nK3erbONHyCbpSj9a9E+uX/OvytZoWp2g==}- engines: {node: ^20.19.0 || >=22.12.0}- hasBin: true-resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==}engines: {node: '>=18.0.0', npm: '>=8.0.0'}@@ -22786,10 +22552,6 @@ packages:resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}engines: {node: '>=12'}- resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==}- engines: {node: ^20.19.0 || ^22.12.0 || >=23}-resolution: {integrity: sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==}@@ -22809,10 +22571,6 @@ packages:resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}engines: {node: '>=12'}- resolution: {integrity: sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==}- engines: {node: ^20.19.0 || ^22.12.0 || >=23}-resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}@@ -22967,12 +22725,6 @@ snapshots:package-manager-detector: 1.6.0tinyexec: 1.1.2- '@apidevtools/[email protected]':- dependencies:- '@jsdevtools/ono': 7.1.3- '@types/json-schema': 7.0.15- js-yaml: 4.1.1-'@aws-crypto/[email protected]':dependencies:'@aws-crypto/util': 5.2.0@@ -24698,15 +24450,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.29.0- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-decorators': 7.28.6(@babel/[email protected])- transitivePeerDependencies:- - supports-color-'@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/[email protected])':dependencies:'@babel/core': 7.26.0@@ -24756,11 +24499,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.29.0- '@babel/helper-plugin-utils': 7.28.6-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.26.0@@ -25887,10 +25625,6 @@ snapshots:'@babel/[email protected]': {}- '@babel/[email protected]':- dependencies:- core-js-pure: 3.49.0-'@babel/[email protected]': {}'@babel/[email protected]': {}@@ -26009,7 +25743,8 @@ snapshots:transitivePeerDependencies:- supports-color- '@cfworker/[email protected]': {}+ '@cfworker/[email protected]':+ optional: true'@chevrotain/[email protected]': {}@@ -27870,8 +27605,6 @@ snapshots:'@js-sdsl/[email protected]': {}- '@jsdevtools/[email protected]': {}-'@jsonjoy.com/[email protected]([email protected])':dependencies:tslib: 2.8.1@@ -28303,13 +28036,6 @@ snapshots:'@tybys/wasm-util': 0.9.0optional: true- dependencies:- '@emnapi/core': 1.9.2- '@emnapi/runtime': 1.9.2- '@tybys/wasm-util': 0.10.2- optional: true-'@nicolo-ribaudo/[email protected]':optional: true@@ -29181,8 +28907,6 @@ snapshots:- supports-color- typescript- '@oxc-project/[email protected]': {}-'@oxc-resolver/[email protected]':optional: true@@ -30720,68 +30444,8 @@ snapshots:'@remote-ui/[email protected]': {}- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- dependencies:- '@emnapi/core': 1.9.2- '@emnapi/runtime': 1.9.2- '@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected](@babel/[email protected])(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@babel/core': 7.29.0- picomatch: 4.0.4- rolldown: 1.0.0-rc.15- optionalDependencies:- '@babel/runtime': 7.29.2- vite: 5.4.21(@types/[email protected])([email protected])([email protected])([email protected])([email protected])-'@rolldown/[email protected]': {}- '@rolldown/[email protected]': {}-'@rolldown/[email protected]': {}'@rollup/[email protected]([email protected])':@@ -32985,11 +32649,6 @@ snapshots:tslib: 2.8.1optional: true- '@tybys/[email protected]':- dependencies:- tslib: 2.8.1- optional: true-'@tybys/[email protected]':dependencies:tslib: 2.8.1@@ -34365,34 +34024,6 @@ snapshots:- [email protected](@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):- dependencies:- '@babel/plugin-proposal-decorators': 7.29.0(@babel/[email protected])- '@cfworker/json-schema': 4.1.1- '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])- '@rolldown/plugin-babel': 0.2.3(@babel/[email protected])(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))- ai: 6.0.77([email protected])- cron-schedule: 6.0.0- json-schema: 0.4.0- json-schema-to-typescript: 15.0.4- mimetext: 3.0.28- nanoid: 5.1.7- partyserver: 0.4.1(@cloudflare/[email protected])- partysocket: 1.1.16([email protected])- picomatch: 4.0.4- react: 18.3.1- yargs: 18.0.0- zod: 4.3.6- optionalDependencies:- vite: 5.4.21(@types/[email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - '@babel/core'- - '@babel/plugin-transform-runtime'- - '@babel/runtime'- - '@cloudflare/workers-types'- - rolldown- - supports-color-dependencies:clean-stack: 2.2.0@@ -35548,12 +35179,6 @@ snapshots:strip-ansi: 6.0.1wrap-ansi: 7.0.0- dependencies:- string-width: 7.2.0- strip-ansi: 7.2.0- wrap-ansi: 9.0.2-dependencies:is-plain-object: 2.0.4@@ -35730,8 +35355,6 @@ snapshots:dependencies:browserslist: 4.28.1- [email protected]: {}-@@ -35866,8 +35489,6 @@ snapshots:dependencies:luxon: 3.7.2- [email protected]: {}-@@ -37189,8 +36810,6 @@ snapshots:- [email protected]: {}-@@ -40273,8 +39892,6 @@ snapshots:- [email protected]: {}-@@ -40383,18 +40000,6 @@ snapshots:- dependencies:- '@apidevtools/json-schema-ref-parser': 11.9.3- '@types/json-schema': 7.0.15- '@types/lodash': 4.17.24- is-glob: 4.0.3- js-yaml: 4.1.1- lodash: 4.18.1- minimist: 1.2.8- prettier: 3.6.2- tinyglobby: 0.2.16-@@ -41581,13 +41186,6 @@ snapshots:- dependencies:- '@babel/runtime': 7.29.2- '@babel/runtime-corejs3': 7.29.2- js-base64: 3.7.8- mime-types: 2.1.35-@@ -41878,8 +41476,6 @@ snapshots:- [email protected]: {}-@@ -42497,17 +42093,6 @@ snapshots:- [email protected](@cloudflare/[email protected]):- dependencies:- '@cloudflare/workers-types': 4.20260207.0- nanoid: 5.1.7-- dependencies:- event-target-polyfill: 0.0.4- optionalDependencies:- react: 18.3.1-dependencies:no-case: 3.0.4@@ -44535,27 +44120,6 @@ snapshots:- dependencies:- '@oxc-project/types': 0.124.0- '@rolldown/pluginutils': 1.0.0-rc.15- optionalDependencies:- '@rolldown/binding-android-arm64': 1.0.0-rc.15- '@rolldown/binding-darwin-arm64': 1.0.0-rc.15- '@rolldown/binding-darwin-x64': 1.0.0-rc.15- '@rolldown/binding-freebsd-x64': 1.0.0-rc.15- '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-rc.15- '@rolldown/binding-linux-arm64-gnu': 1.0.0-rc.15- '@rolldown/binding-linux-arm64-musl': 1.0.0-rc.15- '@rolldown/binding-linux-ppc64-gnu': 1.0.0-rc.15- '@rolldown/binding-linux-s390x-gnu': 1.0.0-rc.15- '@rolldown/binding-linux-x64-gnu': 1.0.0-rc.15- '@rolldown/binding-linux-x64-musl': 1.0.0-rc.15- '@rolldown/binding-openharmony-arm64': 1.0.0-rc.15- '@rolldown/binding-wasm32-wasi': 1.0.0-rc.15- '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.15- '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.15-dependencies:'@types/estree': 1.0.8@@ -47383,8 +46947,6 @@ snapshots:- [email protected]: {}-dependencies:cliui: 5.0.0@@ -47442,15 +47004,6 @@ snapshots:y18n: 5.0.8yargs-parser: 21.1.1- dependencies:- cliui: 9.0.1- escalade: 3.2.0- get-caller-file: 2.0.5- string-width: 7.2.0- y18n: 5.0.8- yargs-parser: 22.0.0-dependencies:buffer-crc32: 0.2.13diff --git a/services/mcp/ARCHITECTURE.md b/services/mcp/ARCHITECTURE.mdindex c1541553a889..f2f4a869cc91 100644--- a/services/mcp/ARCHITECTURE.md+++ b/services/mcp/ARCHITECTURE.md@@ -1,110 +1,58 @@# MCP Integration Architecture-This directory contains the Cloudflare Workers implementation of PostHog's MCP (Model Context Protocol) server.+This directory contains PostHog's MCP (Model Context Protocol) server. The protocol is served by the **Hono runtime** (Node, deployed to our k8s clusters). A thin **Cloudflare Worker** sits in front of it as a stateless edge router that terminates OAuth, validates tokens, and proxies `/mcp` traffic to the regional Hono deployment.## Overview-The implementation uses two Cloudflare primitives:--1. **Worker** (`index.ts`) - Stateless request router-2. **Durable Object** (`mcp.ts`) - Stateful MCP protocol handler-```mermaidflowchart TBsubgraph Worker["Cloudflare Worker (index.ts)"]W1["Stateless - new instance per request"]W2["Handles OAuth metadata endpoints (RFC 8414, RFC 9728)"]- W3["Validates tokens and routes to Durable Object"]+ W3["Validates tokens and resolves the user's region"]W4["Wide logging via middleware"]end- subgraph DO["Durable Object (mcp.ts)"]- D1["Stateful - one instance per user (keyed by token hash)"]- D2["SQLite storage for persistence (region, distinctId)"]- D3["Handles MCP protocol (tools, prompts, resources)"]- D4["Tracks analytics events to PostHog"]+ subgraph Hono["Hono runtime (Node / k8s)"]+ H1["Serves the MCP protocol (tools, prompts, resources)"]+ H2["Per-user session state in Redis (keyed by token hash)"]+ H3["Tracks analytics events to PostHog"]end- Worker -->|"MCP.serve() / MCP.serveSSE()<br/>passes ctx.props with token, userHash, etc."| DO+ Worker -->|"proxyToHono(): forwards /mcp to<br/>mcp.{us,eu}.posthog.com"| Hono```+The Worker no longer serves the protocol itself — an earlier iteration ran a stateful Cloudflare Durable Object (`mcp.ts`) for this, but that has been removed in favor of always proxying to Hono.+## File Structure```txt-src/integrations/mcp/-├── index.ts # Worker entry point and request router-├── mcp.ts # Durable Object class (MCP protocol handler)-├── README.md # This file-└── utils/- ├── client.ts # PostHog analytics client- ├── formatResponse.ts- ├── handleToolError.ts- └── logging.ts # Wide logging middleware+src/+├── index.ts # Worker entry point: OAuth, routing, /mcp proxy+├── proxy.ts # Region resolution + reverse proxy to the Hono runtime+├── hono/ # The Hono runtime that actually serves the MCP protocol+└── lib/ # Shared helpers (caching, analytics, logging, …)```## Key Concepts-### Worker → Durable Object Communication+### Worker → Hono communication-The Worker passes request context to the Durable Object via `ctx.props`:+The Worker resolves the caller's region (from cache/KV or by probing both regions) and reverse-proxies the request to the matching Hono deployment:```typescript// In Worker (index.ts)-Object.assign(ctx.props, {- apiToken: token,- userHash: hash(token),- sessionId: sessionId,- features: features,- region: regionParam,-})--// Then route to Durable Object-MCP.serve('/mcp').fetch(request, env, ctx)-```--The Durable Object accesses this via `this.props`:--```typescript-// In Durable Object (mcp.ts)-get requestProperties(): RequestProperties {- return this.props as RequestProperties+if (url.pathname.startsWith('/mcp')) {+ const region = await resolveProxyRegion(token, ctx.props.userHash, env.MCP_KV)+ return proxyToHono(request, region)}```-### Per-User State via Durable Objects--Durable Objects provide a single shared SQLite storage instance (`this.ctx.storage`). To achieve per-user isolation within this shared storage, we use a **namespaced key pattern**:--```mermaid-flowchart LR- subgraph Storage["Durable Object Storage (shared SQLite)"]- subgraph UserA["User A (hash: abc123)"]- A1["user:abc123:region = 'us'"]- A2["user:abc123:distinctId = 'user_1'"]- end- subgraph UserB["User B (hash: def456)"]- B1["user:def456:region = 'eu'"]- B2["user:def456:distinctId = 'user_2'"]- end- end-```--The `DurableObjectCache` handles this namespacing automatically:--```typescript-// In DurableObjectCache (src/lib/cache/DurableObjectCache.ts)-private getScopedKey(key: string): string {- return `user:${this.userHash}:${key}`-}--// When mcp.ts calls:-await this.cache.set('region', 'us')+`RequestProperties` (the parsed headers and query params for a request) is defined in `src/lib/request-properties.ts` and shared by both runtimes.-// It actually stores:-await this.storage.put('user:abc123:region', 'us')-```+### Per-User State-The `userHash` is a PBKDF2 hash of the API token (see `src/lib/utils/helper-functions.ts`), ensuring:+The Hono runtime keeps per-user session state (active project/organization, region, distinctId) in Redis, namespaced by `userHash` — a PBKDF2 hash of the API token (see `src/lib/utils`), ensuring:- **Isolation**: Users can't access each other's cached data (different prefix)- **Persistence**: Region and distinctId survive across requests@@ -137,7 +85,7 @@ There are three independent layers that emit signals about each MCP request:Three distinct code paths emit `mcp_tool_call` events; which one fires depends on the server mode and on the `mcp-posthog-analytics-sdk` feature flag:-- **`mcp.ts:trackEvent`** — homegrown PostHog capture. Used by the exec-mode wrapper to emit events for inner tool calls. Properties use the bare form: `mcp_session_id`, `mcp_conversation_id`, `mcp_client_name`, etc.+- **`hono/analytics.ts`** — homegrown PostHog capture. Used by the exec-mode wrapper to emit events for inner tool calls. Properties use the bare form: `mcp_session_id`, `mcp_conversation_id`, `mcp_client_name`, etc.- **`lib/mcpcat.ts`** — legacy MCPcat SDK path. Same bare property names.- **`lib/posthog-mcp-analytics.ts`** — the [`@posthog/mcp-analytics`](https://github.com/PostHog/mcp-analytics) SDK. Property names are `$`-prefixed (`$mcp_session_id`, `$mcp_conversation_id`, …). This is the path most live traffic flows through today.@@ -168,20 +116,6 @@ The headers are caller-asserted — anyone can spoof them on a request — so baThis is **attribute-based correlation, not distributed-trace span linkage** — the Worker emits no OTLP itself and forwards no `traceparent`, so the Django-rooted span is not a child of any Worker-side span. Tracing backends can correlate after the fact by querying on the attribute, but won't render a cross-service trace tree until Worker-side OTLP export ships.-### Durable Object cold vs warm--Cloudflare Durable Objects have two lifecycle states that matter when reasoning about cached state in this codebase:--- **Cold start.** A request arrives, no live DO instance exists. The Cloudflare runtime constructs a fresh instance and calls `init()`. `_api`, `_cache`, and any other lazily-initialized fields are built from scratch. The DO is now "warm".-- **Warm.** Subsequent requests reuse the same in-memory DO instance. `init()` does **not** re-run; cached fields (`_api`, `_cache`) keep the values captured on the cold start. Per-request props arrive via the framework's `updateProps` / `setName` ingress (which `McpAgent` overrides).-- **Hibernation.** After ~10 s of inactivity, the runtime tears the DO down. The next request triggers a fresh cold start. DO storage (`this.ctx.storage`) persists across hibernation; in-memory caches do not.--This matters for any value that's per-request but ends up snapshotted onto a long-lived cached object:--- The cached `_api` is built once in `api()`, during `init()` on the cold start. The cold start's request is almost always an **initialize** call, which by spec does **not** carry the `Mcp-Session-Id` header (the server is about to mint it in the response). So `_api.config.mcpSessionId` is `undefined` at construction and stays that way for the warm DO's lifetime.-- For values that need to refresh per request, mutate `_api.config` in place from `updateProps` / `setName` (the per-request ingress hooks). That's what `rotateCachedApiToken` does for `apiToken`.-- Event emission is unaffected by this caching: `trackEvent` reads `this.requestProperties.mcpSessionId` directly per emission, and the `posthog-mcp-analytics` SDK reads `extra.sessionId` from the transport per event. So `mcp_session_id` lands on events even when `_api`'s copy is stale.-## OAuth FlowThe server implements RFC 9728 (OAuth Protected Resource Metadata) and RFC 8414 (OAuth Authorization Server Metadata):@@ -204,23 +138,14 @@ sequenceDiagram## Wrangler Configuration-The Durable Object binding is configured in `wrangler.jsonc`:+The Worker no longer binds a Durable Object — `/mcp` is proxied to the Hono runtime. The historical DO migrations remain in `wrangler.jsonc` as tombstones, with a final `deleted_classes` migration that retires the class (and its per-user SQLite storage) in Cloudflare:```jsonc{- "durable_objects": {- "bindings": [- {- "class_name": "MCP",- "name": "MCP_OBJECT",- },- ],- },"migrations": [{ "new_sqlite_classes": ["MyMCP"], "tag": "v1" },{ "renamed_classes": [{ "from": "MyMCP", "to": "MCP" }], "tag": "v2" },+ { "deleted_classes": ["MCP"], "tag": "v3" },],}```--The `MCP` class must be exported from the Worker entry point for Wrangler to find it.diff --git a/services/mcp/README.md b/services/mcp/README.mdindex 35c42dd3fd96..bbb3a115fa1f 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -416,6 +416,6 @@ Claude Desktop is one of the easiest ways to test MCP Apps - while PostHog Code### Data handling-The MCP server acts as a proxy to your PostHog instance. It does not store your analytics data - all queries are executed against your PostHog project and results are returned directly to your AI client. Session state (active project/organization) is cached temporarily using Cloudflare Durable Objects tied to your API key hash.+The MCP server acts as a proxy to your PostHog instance. It does not store your analytics data - all queries are executed against your PostHog project and results are returned directly to your AI client. Session state (active project/organization) is cached temporarily, keyed by your API key hash.For EU users, use the `mcp-eu.posthog.com` endpoint to ensure OAuth flows route to the EU PostHog instance.diff --git a/services/mcp/package.json b/services/mcp/package.jsonindex 8a6a6d71d2dc..90d5d46f4b4f 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -47,7 +47,6 @@"@posthog/quill": "workspace:*","@posthog/quill-charts": "workspace:*","@toon-format/toon": "^2.1.0",- "agents": "0.10.2","ai": "^6.0.0","esbuild": "^0.25.11","eventsource-parser": "^3.0.0",diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.tsindex 202d889f61a2..e45d8f119fc7 100644--- a/services/mcp/src/index.ts+++ b/services/mcp/src/index.ts@@ -3,10 +3,10 @@ import { isIdJagAccessToken } from '@/lib/id-jag'import { RequestLogger, withLogging } from '@/lib/logging'import { extractClientInfoFromBody } from '@/lib/mcp-client-info'import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'+import { RequestProperties } from '@/lib/request-properties'import { hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'import type { CloudRegion } from '@/tools/types'-import { RequestProperties } from './mcp'import { proxyToHono, resolveProxyRegion } from './proxy'// Helper to get the public-facing URL, respecting reverse proxy headers@@ -328,9 +328,6 @@ const handleRequest = async (return new Response('Not found', { status: 404 })}-// Durable Object class export - required for Wrangler to find the class for the MCP_OBJECT binding-export { MCP } from './mcp'-// Worker entry pointexport default {fetch: withLogging(handleRequest),diff --git a/services/mcp/src/lib/cache/DurableObjectCache.ts b/services/mcp/src/lib/cache/DurableObjectCache.tsdeleted file mode 100644index d0a49c756390..000000000000--- a/services/mcp/src/lib/cache/DurableObjectCache.ts+++ /dev/null@@ -1,50 +0,0 @@-import { ScopedCache } from './ScopedCache'--interface DurableObjectStorage {- get<T = unknown>(key: string): Promise<T | undefined>- put<T>(key: string, value: T): Promise<void>- delete(key: string): Promise<boolean>- delete(keys: string[]): Promise<number>- list(options?: {- prefix?: string- start?: string- end?: string- limit?: number- reverse?: boolean- }): Promise<Map<string, unknown>>-}--export class DurableObjectCache<T extends Record<string, any>> extends ScopedCache<T> {- private storage: DurableObjectStorage-- constructor(scope: string, storage: DurableObjectStorage) {- super(scope)- this.storage = storage- }-- private getScopedKey(key: string): string {- return `user:${this.scope}:${key}`- }-- async get<K extends keyof T>(key: K): Promise<T[K] | undefined> {- const scopedKey = this.getScopedKey(key as string)- return await this.storage.get(scopedKey)- }-- async set<K extends keyof T>(key: K, value: T[K]): Promise<void> {- const scopedKey = this.getScopedKey(key as string)- await this.storage.put(scopedKey, value)- }-- async delete<K extends keyof T>(key: K): Promise<void> {- const scopedKey = this.getScopedKey(key as string)- await this.storage.delete(scopedKey)- }-- async clear(): Promise<void> {- 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/mcp.ts b/services/mcp/src/mcp.tsdeleted file mode 100644index 800383922bf0..000000000000--- a/services/mcp/src/mcp.ts+++ /dev/null@@ -1,907 +0,0 @@-import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'-import { McpServer, type ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js'-import guidelines from '@shared/guidelines.md'-import { McpAgent } from 'agents/mcp'-import type { z } from 'zod'--import { ApiClient } from '@/api/client'-import { hasScope } from '@/lib/api'-import { buildToolResultPayload, isToolCallPayload } from '@/lib/build-tool-result'-import { DurableObjectCache } from '@/lib/cache/DurableObjectCache'-import { MCPClientProfile } from '@/lib/client-detection'-import {- getCustomApiBaseUrl,- getPublicBaseUrl,- MCP_SERVER_NAME,- MCP_SERVER_VERSION,- POSTHOG_EU_BASE_URL,- POSTHOG_US_BASE_URL,- getBaseUrlForRegion,- toCloudRegion,-} from '@/lib/constants'-import { handleToolError, wrapError } from '@/lib/errors'-import { type QueryToolInfo } from '@/lib/instructions'-import { InstructionsFormatter } from '@/lib/instructions-formatter'-import { getPostHogClient } from '@/lib/posthog'-import {- AnalyticsEvent,- buildMCPAnalyticsGroups,- buildMCPContextProperties,- initMcpAnalytics,- MCP_ANALYTICS_VERSION,- McpAnalyticsInitResult,- type MCPAnalyticsContext,-} from '@/lib/posthog/analytics'-import { type EvaluatedFlags, evaluateFeatureFlags, type FlagGroups } from '@/lib/posthog/flags'-import { SessionManager } from '@/lib/SessionManager'-import { StateManager } from '@/lib/StateManager'-import { formatPrompt, type McpMode, sanitizeHeaderValue } 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 { createExecInnerToolCallResolver, createExecTool, type ExecInnerCallTracker } from '@/tools/exec'-import { getScopeGatedTools, getToolDefinition } from '@/tools/toolDefinitions'-import { type CloudRegion, type Context, type State, type Tool } from '@/tools/types'--const instructionsFormatter = new InstructionsFormatter()--export type RequestProperties = {- userHash: string- apiToken: string- // Wrapper-app-provided hint from `?sessionId=` query param. Resolved to a- // UUID via `SessionManager.getSessionUuid()` and emitted as `$session_id`- // for Session Replay / AI observability grouping. Only set by wrapping- // consumer apps (setup wizard, sandbox, etc.).- sessionId?: string- // Streamable-HTTP transport session id (`Mcp-Session-Id` HTTP header).- // Server-minted per the MCP protocol spec, present on every request after- // initialize. Distinct from `sessionId` above — this is the transport's- // own correlation key, available for direct MCP clients (Claude Code,- // Cursor, …) that never set the wrapper-app `?sessionId=` hint.- mcpSessionId?: string- // Agent-echoed conversation id from `@posthog/mcp-analytics`'s- // `enableConversationId: true`. Sourced today from the inbound- // `mcp-conversation-id` HTTP header (see `index.ts`). Persists across- // transport reconnects because the agent is asked to echo the value back- // on every subsequent tool call.- mcpConversationId?: string- features?: string[]- tools?: string[]- region?: string- organizationId?: string- projectId?: string- clientUserAgent?: string- mcpConsumer?: string- mcpClientName?: string- mcpClientVersion?: string- mcpProtocolVersion?: string- // Per-request `x-anthropic-client` value. Identifies the live inner client- // on pooled MCP transports — distinct from `mcpClientName` (session-pinned- // from the initialize body's `clientInfo.name`).- mcpVendorClient?: string- readOnly?: boolean- mode?: McpMode- transport?: 'streamable-http' | 'sse'- viaSseRedirect?: boolean- requestStartTime?: number- mcpAnalyticsInitAction?: McpAnalyticsInitResult['action']- mcpAnalyticsInitReason?: string- mcpAnalyticsInitErrorName?: string- mcpAnalyticsInitErrorMessage?: string-}--export class MCP extends McpAgent<Env> {- server = new McpServer({ name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION }, { instructions: '' })-- initialState: State = {- projectId: undefined,- orgId: undefined,- distinctId: undefined,- region: undefined,- apiKey: undefined,- clientName: undefined,- mcpClientName: undefined,- mcpClientVersion: undefined,- mcpProtocolVersion: undefined,- mcpConsumer: undefined,- mcpVendorClient: undefined,- }-- _cache: DurableObjectCache<State> | undefined-- _api: ApiClient | undefined-- _sessionManager: SessionManager | undefined-- private clientInfoResolved = false- private mcpClientName: string | undefined- private mcpClientVersion: string | undefined- private mcpProtocolVersion: string | undefined- private mcpMode: McpMode | undefined-- get requestProperties(): RequestProperties {- return this.props as RequestProperties- }-- get cache(): DurableObjectCache<State> {- if (!this.requestProperties.userHash) {- throw new Error('User hash is required to use the cache')- }-- if (!this._cache) {- this._cache = new DurableObjectCache<State>(this.requestProperties.userHash, this.ctx.storage)- }-- 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- }-- // Prefer values parsed from the current request body (see- // `extractClientInfoFromBody` in index.ts). This is the only path- // that works during init(), because the framework's async- // `getInitializeRequest()` reads DO storage which is only written- // *after* `onStart`/`init()` has run.- const { mcpClientName, mcpClientVersion, mcpProtocolVersion } = this.requestProperties- if (mcpClientName || mcpClientVersion) {- this.mcpClientName = mcpClientName- this.mcpClientVersion = mcpClientVersion- this.mcpProtocolVersion = mcpProtocolVersion- this.clientInfoResolved = true- return- }-- // Fallback: read the saved initialize message from DO storage.- // Post-init only — during init() this storage write has not landed.- try {- const initRequest = await this.getInitializeRequest()- if (!initRequest || !('params' in initRequest)) {- return- }-- const params = (- initRequest as {- params?: {- clientInfo?: { name?: string; version?: string }- protocolVersion?: string- }- }- ).params- if (!params) {- return- }-- this.mcpClientName = sanitizeHeaderValue(params.clientInfo?.name)- this.mcpClientVersion = sanitizeHeaderValue(params.clientInfo?.version)- this.mcpProtocolVersion = sanitizeHeaderValue(params.protocolVersion)- this.clientInfoResolved = true- } catch (error) {- // stay unresolved so a later caller can retry- console.error('[MCP] resolveClientInfo fallback failed:', error)- }- }-- async detectRegion(): Promise<CloudRegion | undefined> {- const usClient = new ApiClient({- apiToken: this.requestProperties.apiToken,- baseUrl: POSTHOG_US_BASE_URL,- })-- const euClient = new ApiClient({- apiToken: this.requestProperties.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 customBaseUrl = getCustomApiBaseUrl()- if (customBaseUrl) {- return customBaseUrl- }-- // Check region from request props first (passed via URL param), then cache, then detect- const propsRegion = this.requestProperties.region- if (propsRegion) {- const region = toCloudRegion(propsRegion)- // Cache it for future requests- 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> {- // Token rotation on warm DOs is handled by setName(), which mutates- // this._api.config.apiToken in place. That keeps references captured- // during init() — e.g. the `context.api` passed to every tool handler- // in getContext() — seeing the latest token on subsequent fetches.- if (!this._api) {- const baseUrl = await this.getBaseUrl()- await this.resolveClientInfo()- this._api = new ApiClient({- apiToken: this.requestProperties.apiToken,- baseUrl,- publicBaseUrl: getPublicBaseUrl(),- clientUserAgent: this.requestProperties.clientUserAgent,- mcpClientName: this.mcpClientName,- mcpClientVersion: this.mcpClientVersion,- mcpProtocolVersion: this.mcpProtocolVersion,- mcpConsumer: this.requestProperties.mcpConsumer,- mcpSessionId: this.requestProperties.mcpSessionId,- mcpConversationId: this.requestProperties.mcpConversationId,- })- }-- return this._api- }-- /**- * partyserver's `setName` only re-runs `onStart` (and therefore- * `updateProps`) on cold-start DOs. On warm DOs it updates the private- * `#_props` and returns early, leaving our cached `_api.config.apiToken`- * stale across token rotations for the same `mcp-session-id`. Rotate- * just the cached token here — leave `this.props` and storage alone.- */- async setName(name: string, props?: RequestProperties): Promise<void> {- this.rotateCachedApiTokenAndTraces({- apiToken: props?.apiToken,- mcpSessionId: props?.mcpSessionId,- mcpConversationId: props?.mcpConversationId,- })- await super.setName(name, props)- }-- /**- * Called by the `agents` SDK on cold start / hibernation wake to persist- * and hydrate props. Apply the token + `this.props` synchronously BEFORE- * awaiting storage: the SDK fires `updateProps` without awaiting and then- * calls `fetch()`, so yielding first would let a tool handler read stale- * state off `context.api.config.apiToken`.- */- async updateProps(props?: RequestProperties): Promise<void> {- this.props = props as RequestProperties- this.rotateCachedApiTokenAndTraces({- apiToken: props?.apiToken,- mcpSessionId: props?.mcpSessionId,- mcpConversationId: props?.mcpConversationId,- })- await super.updateProps(props)- }-- /**- * Refresh the cached ApiClient's per-request config in place. Tool handlers- * read these fields off `context.api.config` — the captured ApiClient from- * init() — so replacing the instance would leave those references stale.- * Mutating in place keeps them pointing at the latest values.- *- * Name is intentionally awkward to signal that this method has grown- * beyond just rotating the apiToken; rename more crisply when a natural- * grouping emerges.- *- * Three fields rotate per inbound request:- * - `apiToken` — short-lived OAuth tokens get refreshed across the same- * transport session.- * - `mcpSessionId` — the `Mcp-Session-Id` HTTP header is *absent* on the- * initialize call (where `_api` is first constructed) and present on- * every subsequent request. Without this refresh, `_api` would be- * pinned to `undefined` for the lifetime of a warm DO and the- * `x-posthog-mcp-session-id` header would never be sent.- * - `mcpConversationId` — same shape as `mcpSessionId`; sourced from- * the inbound `mcp-conversation-id` header (today supplied by wrapper- * apps; the `@posthog/mcp-analytics` SDK injects it via tool args, but- * that path doesn't land on `requestProperties` yet).- *- * No-op when there's no cached client, or when an incoming field is empty- * (don't overwrite a real value with `undefined`).- */- private rotateCachedApiTokenAndTraces(updates: {- apiToken: string | undefined- mcpSessionId: string | undefined- mcpConversationId: string | undefined- }): void {- if (!this._api) {- return- }- if (updates.apiToken && this._api.config.apiToken !== updates.apiToken) {- this._api.config.apiToken = updates.apiToken- }- if (updates.mcpSessionId && this._api.config.mcpSessionId !== updates.mcpSessionId) {- this._api.config.mcpSessionId = updates.mcpSessionId- }- if (updates.mcpConversationId && this._api.config.mcpConversationId !== updates.mcpConversationId) {- this._api.config.mcpConversationId = updates.mcpConversationId- }- }-- 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) : {}-- // `groups` is translated to `$groups` server-side by posthog-node. No separate- // `groupIdentify` call: org/project group properties are populated by the main- // PostHog backend (see `posthog/event_usage.py`), and duplicating them from here- // with the minimal info we have would overwrite richer core-owned data.- client.capture({- distinctId,- event,- ...(Object.keys(groups).length > 0 ? { groups } : {}),- properties: {- ...(this.requestProperties.sessionId- ? {- $session_id: await this.sessionManager.getSessionUuid(this.requestProperties.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.requestProperties.mcpVendorClient- ? { mcp_vendor_client: this.requestProperties.mcpVendorClient }- : {}),- ...(this.requestProperties.mcpConsumer ? { mcp_consumer: this.requestProperties.mcpConsumer } : {}),- ...(this.requestProperties.transport ? { mcp_transport: this.requestProperties.transport } : {}),- ...(this.requestProperties.mcpSessionId- ? { mcp_session_id: this.requestProperties.mcpSessionId }- : {}),- ...(this.requestProperties.mcpConversationId- ? { mcp_conversation_id: this.requestProperties.mcpConversationId }- : {}),- ...(this.mcpMode ? { mcp_mode: this.mcpMode } : {}),- mcp_version: MCP_ANALYTICS_VERSION,- ...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) {- const errorOutput = `Invalid input: ${validation.error.message}`-- return {- content: [- {- type: 'text',- text: errorOutput,- },- ],- }- }-- 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) {- this.ctx.waitUntil(- this.trackContextSwitchEvent(tool.name, await this.getContext(), previousContext)- )- }- // The exec wrapper (single-exec mode) assembles the per-call payload itself —- // propagating the inner tool's UI resourceUri onto the response — so pass it- // through unchanged. Re-running `buildToolResultPayload` on the payload would- // object-rest-destructure its content/structuredContent fields.- if (isToolCallPayload(handlerResult)) {- return handlerResult- }- // Fetch distinctId only when a UI-resource tool with a non-string result might- // actually use it in structuredContent; avoids an extra round-trip otherwise.- 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,- suppressStructuredContentForFormattedResults: new MCPClientProfile({- clientName: this.mcpClientName,- vendorClient: this.requestProperties.mcpVendorClient,- }).isCodingAgent(),- distinctId,- })- } catch (error: any) {- const distinctId = await this.getDistinctId()- return handleToolError(- error,- tool.name,- distinctId,- this.requestProperties.sessionId- ? await this.sessionManager.getSessionUuid(this.requestProperties.sessionId)- : undefined- )- }- }-- // Normalize _meta to include both new (ui.resourceUri) and legacy (ui/resourceUri) formats- // for compatibility with different MCP clients- 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 { features, tools, organizationId, projectId, readOnly, mode } = this.requestProperties-- // Resolve MCP client info before any code reads it — most importantly- // the `useSingleExec` decision below. During init() this resolves from- // request properties (populated by `extractClientInfoFromBody` at the- // worker entry point); the DO-storage fallback inside- // `resolveClientInfo` is only reachable post-init.- await this.resolveClientInfo()-- // 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 DO cold-restarts).- // Without this guard, switching the active org in the user's browser- // would silently reshuffle an established Claude 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()- }-- // Flag-eval groups mirror analytics `$groups` so per-organization and per-project- // rollouts evaluate against the same entities — see `buildMCPAnalyticsGroups`.- const flagAnalyticsContext = await this.getAnalyticsContextSafe(context)- const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined- const toolFlagsPromise = this.resolveToolFeatureFlags(flagGroups)-- const [toolFeatureFlags, _apiKey] = await Promise.all([- toolFlagsPromise,- // 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.requestProperties.mcpConsumer,- oauthClientName,- vendorClient: this.requestProperties.mcpVendorClient,- })-- const { useSingleExec } = this.resolveMode({ mode, clientProfile })-- // 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,- 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).category,- }))- const queryToolInfos: QueryToolInfo[] = allTools- .filter((t) => t.name.startsWith('query-'))- .map((t) => {- const def = getToolDefinition(t.name)- return {- name: t.name,- title: def.title,- ...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),- }- })-- const supportsInstructions = clientProfile.capabilities.supportsInstructions-- const instructionsContext = {- guidelines,- groupTypes,- metadata,- tools: toolInfos,- queryTools: queryToolInfos,- featureFlags: toolFeatureFlags,- }-- // In single-exec mode, when the client honors the MCP `instructions` field we- // lift the exec-tool blurb, tool-domain list (including the `query` domain),- // defined-group types and the active-environment `{metadata}` (user name,- // project, timezone) out of the `command` description and into `instructions`.- // The query-tool catalog stays on the `command` description. Clients that ignore- // `instructions` (Codex — see `client-detection.ts`) keep today's behavior:- // empty `instructions`, everything inlined in the `command` description.- let instructions = ''- if (supportsInstructions) {- instructions = useSingleExec- ? instructionsFormatter.buildExecInstructions(instructionsContext)- : instructionsFormatter.buildToolsInstructions(instructionsContext)- }-- this.server = new McpServer({ name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION }, { instructions })-- // Register prompts and resources- await Promise.all([- registerPrompts(this.server),- registerResources(this.server, context),- registerUiAppResources(this.server, context),- ])-- // Swap execute-sql's description with the rich SQL prompt (visible via- // `info execute-sql` in single-exec, and as the tool's own description- // otherwise). It folds in the HogQL/SQL intro, guidelines, discovery- // workflow, and the truncation guidance that the base JSON description- // carried — and it triggers the `querying-posthog-data` skill more- // reliably than the shorter default.- 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) => {- this.ctx.waitUntil(- (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 aiConsentGiven = await context.stateManager.getAiConsentGiven()- const scopeGatedTools = getScopeGatedTools(_apiKey?.scopes ?? [], {- features,- tools,- excludeTools,- readOnly,- featureFlags: toolFeatureFlags,- scopedTeams: _apiKey?.scoped_teams ?? [],- ...(aiConsentGiven !== undefined ? { aiConsentGiven } : {}),- })-- const execTool = createExecTool(- allTools,- context,- instructionsFormatter.buildExecToolDescription(),- commandReference,- this.requestProperties.mcpConsumer,- trackInnerCall,- scopeGatedTools- )- 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.requestProperties.sessionId- ? this.sessionManager.getSessionUuid(this.requestProperties.sessionId)- : undefined,- getMcpClientName: async () => this.mcpClientName,- getMcpClientVersion: async () => this.mcpClientVersion,- getMcpProtocolVersion: async () => this.mcpProtocolVersion,- getMcpVendorClient: async () => this.requestProperties.mcpVendorClient,- // 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.requestProperties.region,- getAnalyticsContext: async () => this.getAnalyticsContextSafe(await this.getContext()),- getClientUserAgent: async () => this.requestProperties.clientUserAgent,- getOAuthClientName: async () => (await this.cache.get('clientName')) || undefined,- getReadOnly: async () => readOnly,- getTransport: async () => this.requestProperties.transport,- getMcpConsumer: async () => this.requestProperties.mcpConsumer,- getMcpMode: async () => this.mcpMode,- getMcpSessionId: async () => this.requestProperties.mcpSessionId,- getMcpConversationId: async () => this.requestProperties.mcpConversationId,- }-- // In single-exec mode every event's `$mcp_tool_name` is `exec`, so the- // SDK's `$mcp_tool_description` would be the dispatcher's static text on- // every call. Resolve the inner tool the agent was actually invoking- // from the command and surface its name + description as- // `$mcp_exec_tool_call_name` / `$mcp_exec_tool_call_description`.- const resolveExecInnerToolCall = useSingleExec ? createExecInnerToolCallResolver(allTools) : undefined-- // In single-exec mode the SDK's $mcp_listed_tool_names collapses to- // just `exec`, so we can't compute "advertised but never called"- // (zombie tools) from SDK data alone. Pass the inner-tool catalog- // here so analytics can attach it as $mcp_exec_inner_tool_names on- // mcp_tools_list events. Dashboards can then diff it against- // $mcp_exec_tool_call_name from mcp_tool_call.- const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined-- const initResult = await initMcpAnalytics(this.server, mcpAnalyticsIdentity, {- contextEnabled: true,- resolveExecInnerToolCall,- execInnerToolNames,- // `get_more_tools` only earns its keep outside single-exec mode — there- // it lets the model report a gap in our discrete tool catalog. In- // single-exec mode the wrapper handles every call, so the missing-tool- // signal has nothing to map to and the extra slot is pure noise.- reportMissingEnabled: !useSingleExec,- })-- Object.assign(this.requestProperties, {- mcpAnalyticsInitAction: initResult.action,- ...(initResult.action === 'skipped' ? { mcpAnalyticsInitReason: initResult.reason } : {}),- ...(initResult.action === 'failed'- ? {- mcpAnalyticsInitErrorName: initResult.errorName,- mcpAnalyticsInitErrorMessage: initResult.errorMessage,- }- : {}),- } as RequestProperties)-- const initDurationMs = this.requestProperties.requestStartTime- ? Date.now() - this.requestProperties.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)-- this.ctx.waitUntil(- this.trackEvent(- AnalyticsEvent.MCP_INIT,- {- tool_count: allTools.length,- has_organization_id: !!organizationId,- has_project_id: !!projectId,- read_only: !!readOnly,- via_sse_redirect: !!this.requestProperties.viaSseRedirect,- ...(mode ? { mcp_mode_explicit: mode } : {}),- ...(initDurationMs !== undefined ? { init_duration_ms: initDurationMs } : {}),- },- analyticsContext ? { context: analyticsContext } : undefined- )- )- }-- /**- * Decide single-exec mode for this connection, stashing it on the instance- * so `trackEvent` and the observability identity provider can emit `mcp_mode`- * on every downstream event without re-deriving it.- *- * Single-exec is restricted to coding agents — Cursor and other clients- * that render `structuredContent` in their UI need the full per-tool roster,- * not the wrapped CLI. PostHog's agent wrapper self-identifies via the- * `x-posthog-mcp-consumer` header and forces single-exec regardless of the- * wrapped client's reported name. Vibe-coding platforms (Lovable, Replit)- * are detected by OAuth client name since they typically connect through a- * generic MCP client wrapper. An explicit `mode` from the caller (header- * `x-posthog-mcp-mode` or query param `mode`) wins over the client-profile- * heuristic.- */- private resolveMode(args: { mode: McpMode | undefined; clientProfile: MCPClientProfile }): {- useSingleExec: boolean- } {- const { mode, clientProfile } = args- const useSingleExec =- mode === 'cli' ||- (mode !== 'tools' &&- (clientProfile.isCodingAgent() ||- clientProfile.isPostHogCodeConsumer() ||- clientProfile.isVibeCodingClient()))-- this.mcpMode = useSingleExec ? 'cli' : 'tools'-- return { useSingleExec }- }-- private async resolveToolFeatureFlags(groups?: FlagGroups): Promise<EvaluatedFlags | undefined> {- try {- const { getRequiredFeatureFlags } = await import('@/tools/toolDefinitions')- const flagKeys = getRequiredFeatureFlags()- if (flagKeys.length === 0) {- return undefined- }- const distinctId = await this.getDistinctId()- return await evaluateFeatureFlags(flagKeys, distinctId, groups)- } catch {- return undefined- }- }-}diff --git a/services/mcp/src/prompts/index.ts b/services/mcp/src/prompts/index.tsdeleted file mode 100644index d893aef074c5..000000000000--- a/services/mcp/src/prompts/index.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'--import { getPromptsFromManifest } from '@/resources'--export async function registerPrompts(server: McpServer): Promise<void> {- // Get prompts from the manifest (they already have URIs substituted)- const manifestPrompts = await getPromptsFromManifest()-- for (const prompt of manifestPrompts) {- // Register as zero-argument prompt- // The agent can discover available frameworks from the resource templates- server.registerPrompt(- prompt.name,- {- title: prompt.title,- description: prompt.description,- },- async () => ({- messages: prompt.messages as any,- })- )- }-}diff --git a/services/mcp/src/resources/index.ts b/services/mcp/src/resources/index.tsindex f6ed825b146f..f362ea1e4f90 100644--- a/services/mcp/src/resources/index.ts+++ b/services/mcp/src/resources/index.ts@@ -1,8 +1,4 @@-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'--import type { Context } from '@/tools/types'--import type { ContextMillResource, ResourceManifest } from './manifest-types'+import type { ResourceManifest } from './manifest-types'import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive } from './internals'export { fetchContextMillResources, filterValidEntries, loadManifestFromArchive }@@ -10,45 +6,3 @@ export { fetchContextMillResources, filterValidEntries, loadManifestFromArchiveexport async function getPromptsFromManifest(): Promise<ResourceManifest['resources']['prompts']> {return []}--export function registerResourceEntries(server: McpServer, entries: readonly ContextMillResource[]): void {- for (const entry of entries) {- server.registerResource(- entry.name,- entry.uri,- {- mimeType: entry.resource.mimeType,- description: entry.resource.description,- },- async (uri) => ({- contents: [- {- uri: uri.toString(),- mimeType: entry.resource.mimeType,- text: entry.resource.text,- },- ],- })- )- }-}--async function registerContextMillResources(server: McpServer, context: Context): Promise<void> {- if ((context.env as Record<string, string | undefined>)?.TEST === '1') {- return- }- try {- const localUrlRaw = (context.env as Record<string, string | undefined>)?.POSTHOG_MCP_LOCAL_SKILLS_URL- const localUrl = localUrlRaw && localUrlRaw.trim() !== '' ? localUrlRaw : undefined- const archive = await fetchContextMillResources(localUrl)- const manifest = loadManifestFromArchive(archive)-- registerResourceEntries(server, filterValidEntries(manifest.resources, archive))- } catch (error) {- console.error('Failed to register context-mill resources:', error)- }-}--export async function registerResources(server: McpServer, context: Context): Promise<void> {- await registerContextMillResources(server, context)-}diff --git a/services/mcp/tests/integration/harness/cf-proxy.ts b/services/mcp/tests/integration/harness/cf-proxy.tsnew file mode 100644index 000000000000..67bf965f5db0--- /dev/null+++ b/services/mcp/tests/integration/harness/cf-proxy.ts@@ -0,0 +1,76 @@+import { createServer } from 'node:net'+import { unstable_dev, type Unstable_DevWorker } from 'wrangler'++import { startHonoHarness } from './hono'+import type { IntegrationEnv, IntegrationHarness } from './types'++// Bind a Node TCP server to port 0 to get a free port, then release it. There's+// a small race vs hard-coded ports, but it keeps the harness 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 the full proxy stack:+// 1. A Hono listener (with a real Redis on `TEST_REDIS_URL` / db `TEST_REDIS_DB`)+// pointed at `env.apiBaseUrl` (the local PostHog stack).+// 2. A Cloudflare Worker via `wrangler unstable_dev` running this service's+// `src/index.ts`, with `MCP_HONO_URL` set to the Hono URL so every+// proxied request lands on the in-process Hono.+//+// Tests receive the Worker's URL — every assertion travels through the proxy+// → Hono → PostHog backend chain end-to-end. Nothing is mocked.+export async function startCfProxyHarness(env: IntegrationEnv): Promise<IntegrationHarness & { honoUrl: URL }> {+ const hono = await startHonoHarness(env)+ const port = await reserveFreePort()++ let worker: Unstable_DevWorker+ try {+ worker = await unstable_dev('src/index.ts', {+ config: 'wrangler.jsonc',+ local: true,+ ip: '127.0.0.1',+ port,+ // `vars` are baked in at boot — workerd reads them via+ // `cloudflare:workers`'s `env` export. `MCP_HONO_URL` collapses+ // both per-region targets onto the local Hono. `POSTHOG_API_BASE_URL`+ // points the worker's token-probe path at the same backend Hono+ // talks to.+ vars: {+ MCP_HONO_URL: hono.baseUrl.toString().replace(/\/$/, ''),+ POSTHOG_API_BASE_URL: env.apiBaseUrl,+ POSTHOG_ANALYTICS_API_KEY: '',+ POSTHOG_ANALYTICS_HOST: '',+ },+ experimental: {+ disableExperimentalWarning: true,+ disableDevRegistry: true,+ },+ logLevel: 'warn',+ })+ } catch (err) {+ await hono.stop().catch(() => undefined)+ throw err+ }++ return {+ baseUrl: new URL(`http://${worker.address}:${worker.port}`),+ honoUrl: hono.baseUrl,+ stop: async () => {+ await worker.stop().catch(() => undefined)+ await hono.stop().catch(() => undefined)+ },+ }+}diff --git a/services/mcp/tests/integration/harness/cf.ts b/services/mcp/tests/integration/harness/cf.tsindex 157647195905..aefbe972749d 100644--- a/services/mcp/tests/integration/harness/cf.ts+++ b/services/mcp/tests/integration/harness/cf.ts@@ -24,9 +24,9 @@ async function reserveFreePort(): Promise<number> {})}-// 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+// Boots a real workerd via `wrangler unstable_dev` so the worker entry point+// (auth gate, routing, and `/mcp` proxy to the Hono runtime) 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()diff --git a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.tsindex 9f294ace0058..1937f1d33c43 100644--- a/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts+++ b/services/mcp/tests/integration/mcp-protocol.cf.integration.test.ts@@ -1,37 +1,21 @@-import { afterAll, beforeAll, describe } from 'vitest'+import { afterAll, beforeAll } from 'vitest'import { startCfHarness } from './harness/cf'import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'-import {- defineAuthTests,- defineCatalogFilterTests,- defineMcpProtocolTests,- defineResilienceTests,- defineResourceCatalogTests,- defineToolBehaviorTests,- defineUiAppProtocolTests,- type ProtocolTestHarness,-} from './mcp-protocol-suite'+import { defineAuthTests, type ProtocolTestHarness } 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)+// Auth-boundary test against the Cloudflare Workers entry point.+// - Real workerd via `wrangler unstable_dev`// - 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.//-// What runs here vs Hono-only:-// - SDK-based suites work on both runtimes because the SDK client handles-// CF's SSE-streaming responses and Durable Object session lifecycle.-// - Raw-fetch JSON-asserting suites (defineHttpRouteTests,-// defineJsonRpcEdgeCaseTests, defineSessionLifecycleTests) are Hono-only:-// CF returns SSE bodies and requires an initialized DO session before-// it'll dispatch arbitrary JSON-RPC methods, which the raw assertions-// don't account for. These behaviors are still covered against the Hono-// runtime — both runtimes share the same dispatcher / catalog code.-// - defineAuthTests is shared because every test in it asserts on a 401-// rejection that fires before the dispatcher / session layer.+// The worker proxies all `/mcp` traffic to the Hono runtime — protocol,+// resilience, resource-catalog and tool-behavior suites run against the runtime+// that actually serves them in `mcp-protocol.hono.integration.test.ts`. Only the+// bearer-token gate still lives in the worker, so that's all this file asserts+// (every `defineAuthTests` case is a 401 that fires before any proxying).let env: IntegrationEnvlet harness: IntegrationHarness@@ -55,20 +39,4 @@ const harnessFor = (): ProtocolTestHarness => ({publicRoutes: false,})-// The worker now proxies all `/mcp` traffic to the Hono runtime instead of-// serving it locally via the durable object, so these serving suites no longer-// exercise the worker. The same protocol behavior is covered against the-// runtime that actually serves it in `mcp-protocol.hono.integration.test.ts`.-// Skipped (not removed) until the durable object itself is retired.-describe.skip('Cloudflare Workers serving (now proxied to Hono)', () => {- defineMcpProtocolTests('Cloudflare Workers (real stack)', harnessFor)- defineResilienceTests('Cloudflare Workers (real stack)', harnessFor)- defineUiAppProtocolTests('Cloudflare Workers (real stack)', harnessFor)- defineResourceCatalogTests('Cloudflare Workers (real stack)', harnessFor)- defineToolBehaviorTests('Cloudflare Workers (real stack)', harnessFor)- defineCatalogFilterTests('Cloudflare Workers (real stack)', harnessFor)-})--// The worker still enforces the bearer-token boundary before any proxying, so-// these 401 assertions remain valid against the real worker.defineAuthTests('Cloudflare Workers (real stack)', harnessFor)diff --git a/services/mcp/tests/integration/proxy.cf.integration.test.ts b/services/mcp/tests/integration/proxy.cf.integration.test.tsnew file mode 100644index 000000000000..c51700aef182--- /dev/null+++ b/services/mcp/tests/integration/proxy.cf.integration.test.ts@@ -0,0 +1,107 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { startCfProxyHarness } from './harness/cf-proxy'+import { loadIntegrationEnv, type IntegrationEnv, type IntegrationHarness } from './harness/types'+import { defineAuthTests, defineResilienceTests, type ProtocolTestHarness } from './mcp-protocol-suite'++// End-to-end test for the Cloudflare Worker → Hono proxy.+//+// What runs:+// - Real workerd via `wrangler unstable_dev` running `src/index.ts`+// - Real `@hono/node-server` listener running `createApp(redis)` behind it+// - Real Redis (TEST_REDIS_URL / db TEST_REDIS_DB, default localhost:6379 db 15)+// - Real local PostHog stack at TEST_POSTHOG_API_BASE_URL (default localhost:8010)+//+// Nothing is mocked. The Worker is configured with `MCP_HONO_URL` pointing at+// the in-process Hono, so authenticated `/mcp` traffic travels the full+// client → proxy → Hono → PostHog chain.+//+// The worker owns OAuth metadata, redirects, health, and the bearer-token gate+// locally and proxies only `/mcp` — it is not a transparent pass-through. The+// Hono-runtime public-route surface (`/readyz`, `/metrics`, unknown-path 404s,+// security headers) is asserted against the Hono integration test, not here.+//+// Boot the local PostHog stack with `./bin/start` and have a local Redis+// listening on 6379 before running this suite. Ensure `.env.test` (or the+// integration env) defines `TEST_POSTHOG_PERSONAL_API_KEY` / `TEST_ORG_ID` /+// `TEST_PROJECT_ID`.++let env: IntegrationEnv+let harness: IntegrationHarness & { honoUrl: URL }++beforeAll(async () => {+ env = loadIntegrationEnv()+ harness = await startCfProxyHarness(env)+}, 60000)++afterAll(async () => {+ await harness?.stop()+})++const harnessFor = (): ProtocolTestHarness => ({+ baseUrl: harness.baseUrl,+ fetch: globalThis.fetch,+ token: env.apiToken,+ token2: env.apiToken2,+ stateless: true,+ gracefulUnknown: true,+ orgId: env.orgId,+ projectId: env.projectId,+})++// The bearer-token gate fires in the worker before any proxying, and the+// /sse → /mcp 308 (+ `_deprecated=sse` marker) and unknown-Mcp-Session-Id+// recovery paths are forwarded to Hono. Together these are the cheapest+// end-to-end signals that the proxy preserves status, headers, body, and+// routing. The /sse cases also give parity with the old+// `tests/workers/sse-redirect.test.ts`.+defineAuthTests('CF proxy → Hono (real stack)', harnessFor)+defineResilienceTests('CF proxy → Hono (real stack)', harnessFor)++// Proxy-specific assertions: request/response fidelity and region-detection+// inputs. These stay narrow — the rich protocol surface is covered by the Hono+// suite; here we confirm the worker hands each request off (or answers it)+// cleanly.+describe('CF proxy plumbing (real stack)', () => {+ it('returns the worker 401 + WWW-Authenticate challenge for unauthenticated POST /mcp', async () => {+ // The token gate fires before proxying, so an unauthenticated POST /mcp+ // gets the worker's own RFC 9728 challenge. If the worker dropped+ // response headers we'd lose the WWW-Authenticate here.+ const res = await fetch(new URL('/mcp', harness.baseUrl), {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' }),+ })+ expect(res.status).toBe(401)+ const wwwAuth = res.headers.get('WWW-Authenticate') || ''+ expect(wwwAuth.toLowerCase()).toContain('bearer')+ expect(wwwAuth).toContain('oauth-protected-resource')+ })++ it('detects the EU region from X-Forwarded-Host when building OAuth metadata', async () => {+ const res = await fetch(new URL('/.well-known/oauth-protected-resource/mcp', harness.baseUrl), {+ headers: { 'X-Forwarded-Host': 'mcp-eu.posthog.com' },+ })+ expect(res.status).toBe(200)+ const json = (await res.json()) as { authorization_servers?: string[] }+ expect(Array.isArray(json.authorization_servers)).toBe(true)+ })++ it('serves OAuth metadata with ?region=eu without dropping the resource path', async () => {+ const res = await fetch(+ new URL('/.well-known/oauth-protected-resource/mcp?region=eu&extra=keep', harness.baseUrl)+ )+ expect(res.status).toBe(200)+ const json = (await res.json()) as { resource?: string }+ expect(json.resource).toMatch(/\/mcp$/)+ })++ it('redirects GET / to the docs', async () => {+ const res = await fetch(new URL('/', harness.baseUrl), { redirect: 'manual' })+ expect([301, 302, 307, 308]).toContain(res.status)+ expect(res.headers.get('location') || '').toContain('posthog.com')+ })+})diff --git a/services/mcp/tests/unit/mcp-api-caching.test.ts b/services/mcp/tests/unit/mcp-api-caching.test.tsdeleted file mode 100644index 79ceca1be864..000000000000--- a/services/mcp/tests/unit/mcp-api-caching.test.ts+++ /dev/null@@ -1,410 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'--const ApiClientCtor = vi.fn()--vi.mock('@/api/client', () => ({- ApiClient: class {- config: { apiToken: string; baseUrl: string }- baseUrl: string- constructor(config: any) {- this.config = config- this.baseUrl = config.baseUrl- ApiClientCtor(config)- }- },-}))--const storagePutSpy = vi.fn()-const superSetNameSpy = vi.fn()-const superUpdatePropsSpy = vi.fn()--// Stand-in for the agents/mcp base class. Mirrors the two methods our overrides-// chain into via `super`:-// - updateProps persists to storage and sets this.props (cold start / wake)-// - setName is a noop here; partyserver's real implementation updates the-// private #_props. Our subclass override handles the subclass-visible state.-vi.mock('agents/mcp', () => ({- McpAgent: class {- async setName(name: string, props?: unknown): Promise<void> {- superSetNameSpy(name, props)- }- async updateProps(props: unknown): Promise<void> {- superUpdatePropsSpy(props)- await (this as any).ctx.storage.put('props', props ?? {})- ;(this as any).props = props- }- },-}))--vi.mock('@modelcontextprotocol/sdk/server/mcp.js', () => ({- McpServer: class {},-}))--vi.mock('@modelcontextprotocol/ext-apps/server', () => ({- RESOURCE_URI_META_KEY: 'resource-uri',-}))--vi.mock('@shared/guidelines.md', () => ({- default: '',-}))--import { MCP } from '@/mcp'--function buildMcp(initialToken: string): MCP {- const mcp = Object.create(MCP.prototype) as MCP- ;(mcp as any).props = {- userHash: 'user-hash',- apiToken: initialToken,- clientUserAgent: 'test-agent',- }- ;(mcp as any).ctx = {- storage: {- put: async (key: string, value: unknown) => {- storagePutSpy(key, value)- },- },- }- ;(mcp as any).getBaseUrl = async () => 'https://us.posthog.com'- ;(mcp as any).resolveClientInfo = async () => {}- return mcp-}--type TestProps = { userHash: string; apiToken: string; clientUserAgent: string }--function nextProps(apiToken: string): TestProps {- return {- userHash: 'user-hash',- apiToken,- clientUserAgent: 'test-agent',- }-}--describe('MCP.api() lazy construction', () => {- beforeEach(() => {- ApiClientCtor.mockClear()- storagePutSpy.mockClear()- })-- it('constructs an ApiClient with the current token on first call', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()-- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- expect(ApiClientCtor).toHaveBeenLastCalledWith(expect.objectContaining({ apiToken: 'token-A' }))- expect(api.config.apiToken).toBe('token-A')- })-- it('returns the cached instance on subsequent calls', async () => {- const mcp = buildMcp('token-A')- const first = await mcp.api()- const second = await mcp.api()-- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- expect(second).toBe(first)- })-- it('does NOT rotate the cached token when props.apiToken changes directly', async () => {- // Token rotation lives in setName() / updateProps() now, not api().- // Mutating this.props.apiToken directly must NOT cause api() to rewrite- // the cached client's token: the rotation seam is the props-ingress path.- const mcp = buildMcp('token-A')- const first = await mcp.api()- ;(mcp as any).props.apiToken = 'token-B'- const second = await mcp.api()-- expect(second).toBe(first)- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- expect(second.config.apiToken).toBe('token-A')- })-})--describe('MCP.setName() token rotation (warm DO path)', () => {- beforeEach(() => {- ApiClientCtor.mockClear()- storagePutSpy.mockClear()- superSetNameSpy.mockClear()- superUpdatePropsSpy.mockClear()- })-- it('delegates to super.setName with the same arguments', async () => {- const mcp = buildMcp('token-A')- const props = nextProps('token-B')-- await (mcp as any).setName('streamable-http:session-1', props)-- expect(superSetNameSpy).toHaveBeenCalledTimes(1)- expect(superSetNameSpy).toHaveBeenCalledWith('streamable-http:session-1', props)- })-- it('rotates the cached ApiClient token in place on warm requests', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()- expect(api.config.apiToken).toBe('token-A')-- await (mcp as any).setName('streamable-http:session-1', nextProps('token-B'))-- // Same instance reference — context.api captured during init() still- // points at the live ApiClient, so mutating in place propagates.- expect(api.config.apiToken).toBe('token-B')- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- })-- it('leaves this.props untouched (partyserver owns #_props)', async () => {- const mcp = buildMcp('token-A')- await mcp.api()-- await (mcp as any).setName('streamable-http:session-1', nextProps('token-B'))-- // setName only rotates the cached token. this.props stays as whatever- // updateProps last wrote; partyserver's private #_props is what holds- // the fresh per-request props.- expect((mcp as any).props.apiToken).toBe('token-A')- })-- it('does NOT persist to storage', async () => {- // Storage writes are the cold-start / hibernation concern handled by- // updateProps. setName must stay cheap — it fires on every request.- const mcp = buildMcp('token-A')- await mcp.api()-- await (mcp as any).setName('streamable-http:session-1', nextProps('token-B'))-- expect(storagePutSpy).not.toHaveBeenCalled()- })-- it('is a no-op on the cached token when no ApiClient has been constructed', async () => {- const mcp = buildMcp('token-A')-- await (mcp as any).setName('streamable-http:session-1', nextProps('token-B'))-- // Nothing to rotate — the next api() call will build fresh with- // whatever requestProperties returns at that point.- expect(ApiClientCtor).not.toHaveBeenCalled()- })-- it('is a no-op when props is undefined', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()-- await (mcp as any).setName('streamable-http:session-1', undefined)-- expect(api.config.apiToken).toBe('token-A')- })-- it('is a no-op when props has no apiToken field', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()-- await (mcp as any).setName('streamable-http:session-1', { userHash: 'user-hash' })-- expect(api.config.apiToken).toBe('token-A')- })-- it('is a no-op when the incoming token matches the cached one', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()- const before = api.config.apiToken-- await (mcp as any).setName('streamable-http:session-1', nextProps('token-A'))-- expect(api.config.apiToken).toBe(before)- })-})--describe('MCP.updateProps() token propagation (cold start / hibernation)', () => {- beforeEach(() => {- ApiClientCtor.mockClear()- storagePutSpy.mockClear()- superSetNameSpy.mockClear()- superUpdatePropsSpy.mockClear()- })-- it('persists the new props to storage via super.updateProps', async () => {- const mcp = buildMcp('token-A')- const props = nextProps('token-B')-- await (mcp as any).updateProps(props)-- expect(superUpdatePropsSpy).toHaveBeenCalledTimes(1)- expect(superUpdatePropsSpy).toHaveBeenCalledWith(props)- expect(storagePutSpy).toHaveBeenCalledTimes(1)- expect(storagePutSpy).toHaveBeenCalledWith('props', props)- })-- it('propagates the new token onto the cached ApiClient', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()- expect(api.config.apiToken).toBe('token-A')-- await (mcp as any).updateProps(nextProps('token-B'))-- expect(api.config.apiToken).toBe('token-B')- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- })-- it('rotates the token synchronously, before awaiting storage', async () => {- // The agents SDK fires updateProps without awaiting before dispatching- // a fetch, so concurrent tool calls must see the new token on- // context.api.config.apiToken *before* storage.put resolves.- const mcp = buildMcp('token-A')- const api = await mcp.api()-- const updatePromise = (mcp as any).updateProps(nextProps('token-B'))-- expect(api.config.apiToken).toBe('token-B')- expect((mcp as any).props.apiToken).toBe('token-B')-- await updatePromise- expect(storagePutSpy).toHaveBeenCalledTimes(1)- })-- it('is a no-op on the ApiClient when none has been constructed yet', async () => {- const mcp = buildMcp('token-A')-- await (mcp as any).updateProps(nextProps('token-B'))-- const api = await mcp.api()- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- expect(api.config.apiToken).toBe('token-B')- })-- it('leaves the cached ApiClient untouched when the token is unchanged', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()-- await (mcp as any).updateProps(nextProps('token-A'))-- expect(api.config.apiToken).toBe('token-A')- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- })-- it('tolerates missing props without throwing', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()-- await expect((mcp as any).updateProps(undefined)).resolves.toBeUndefined()-- expect(api.config.apiToken).toBe('token-A')- })-- it('tolerates props without an apiToken field', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()-- await (mcp as any).updateProps({ userHash: 'user-hash' })-- expect(api.config.apiToken).toBe('token-A')- })-})--describe('MCP.setName() MCP-id rotation (warm DO path)', () => {- // The `Mcp-Session-Id` HTTP header is absent on the initialize call but- // present on every request after. Without explicit rotation, `_api` —- // constructed during init() with `mcpSessionId: undefined` — would never- // see the header and `x-posthog-mcp-session-id` would never be sent on- // the outbound API hops. These tests pin that rotation behaviour for- // both the protocol session id and the conversation id.- beforeEach(() => {- ApiClientCtor.mockClear()- storagePutSpy.mockClear()- superSetNameSpy.mockClear()- superUpdatePropsSpy.mockClear()- })-- function buildMcpWithMcpIds(opts: { mcpSessionId?: string; mcpConversationId?: string } = {}): MCP {- const mcp = buildMcp('token-A')- ;(mcp as any).props = {- ...(mcp as any).props,- ...(opts.mcpSessionId !== undefined ? { mcpSessionId: opts.mcpSessionId } : {}),- ...(opts.mcpConversationId !== undefined ? { mcpConversationId: opts.mcpConversationId } : {}),- }- return mcp- }-- it('updates the cached ApiClient mcpSessionId when the header appears on a later request', async () => {- // Reproduces the production bug: init() runs before any inbound- // `Mcp-Session-Id` exists, so `_api` is built with `mcpSessionId:- // undefined`. The next request *does* carry the header and must- // propagate onto the cached client.- const mcp = buildMcpWithMcpIds()- const api = await mcp.api()- expect(api.config.mcpSessionId).toBeUndefined()-- await (mcp as any).setName('streamable-http:session-1', {- userHash: 'user-hash',- apiToken: 'token-A',- mcpSessionId: 'mcp-session-abc',- })-- expect(api.config.mcpSessionId).toBe('mcp-session-abc')- expect(ApiClientCtor).toHaveBeenCalledTimes(1)- })-- it('updates the cached ApiClient mcpConversationId when one appears', async () => {- const mcp = buildMcpWithMcpIds()- const api = await mcp.api()- expect(api.config.mcpConversationId).toBeUndefined()-- await (mcp as any).setName('streamable-http:session-1', {- userHash: 'user-hash',- apiToken: 'token-A',- mcpConversationId: 'conv-xyz',- })-- expect(api.config.mcpConversationId).toBe('conv-xyz')- })-- it('does not overwrite a populated id with undefined', async () => {- // If the cached value is already set and a later request omits the- // header, the cached value must win — otherwise transport blips- // would clear the correlation id mid-session.- const mcp = buildMcpWithMcpIds({ mcpSessionId: 'mcp-session-abc' })- const api = await mcp.api()- expect(api.config.mcpSessionId).toBe('mcp-session-abc')-- await (mcp as any).setName('streamable-http:session-1', {- userHash: 'user-hash',- apiToken: 'token-A',- mcpSessionId: undefined,- })-- expect(api.config.mcpSessionId).toBe('mcp-session-abc')- })-})--describe('MCP.updateProps() MCP-id rotation (cold start / hibernation)', () => {- beforeEach(() => {- ApiClientCtor.mockClear()- storagePutSpy.mockClear()- superSetNameSpy.mockClear()- superUpdatePropsSpy.mockClear()- })-- it('propagates a fresh mcpSessionId onto the cached ApiClient', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()- expect(api.config.mcpSessionId).toBeUndefined()-- await (mcp as any).updateProps({- userHash: 'user-hash',- apiToken: 'token-A',- mcpSessionId: 'mcp-session-abc',- })-- expect(api.config.mcpSessionId).toBe('mcp-session-abc')- })-- it('propagates a fresh mcpConversationId onto the cached ApiClient', async () => {- const mcp = buildMcp('token-A')- const api = await mcp.api()- expect(api.config.mcpConversationId).toBeUndefined()-- await (mcp as any).updateProps({- userHash: 'user-hash',- apiToken: 'token-A',- mcpConversationId: 'conv-xyz',- })-- expect(api.config.mcpConversationId).toBe('conv-xyz')- })-})diff --git a/services/mcp/tests/workers/client-info-resolution.test.ts b/services/mcp/tests/workers/client-info-resolution.test.tsdeleted file mode 100644index 0b238357f1a7..000000000000--- a/services/mcp/tests/workers/client-info-resolution.test.ts+++ /dev/null@@ -1,160 +0,0 @@-import { env, runInDurableObject } from 'cloudflare:test'-import { afterEach, describe, expect, it, vi } from 'vitest'--import type { MCP } from '@/mcp'--// DO-level integration tests for MCP client-info resolution. The real worker-// flow sets `mcpClientName` / `mcpClientVersion` / `mcpProtocolVersion` onto-// `ctx.props` at the worker entry point (via `extractClientInfoFromBody` in-// `src/index.ts`) on requests whose body contains a JSON-RPC `initialize`-// message. Subsequent tool-call requests routed to the same warm DO have no-// `initialize` body, so the props for *that* request carry no client-info-// fields — the instance state populated during init() is what every tool-// handler reads.-//-// These tests exercise the whole `init()` flow against the real Workers-// runtime + DO and then simulate a subsequent tool-call request by mutating-// `mcp.props`. The shared workers config (vitest.workers.config.mts) stubs-// outbound PostHog calls, so init completes without real network.--function interceptWaitUntil(mcp: MCP): { flush: () => Promise<void> } {- const pending: Promise<unknown>[] = []- const ctx = (mcp as any).ctx- // Replace — do NOT forward to the original. The real `ctx.waitUntil`- // keeps the DO alive after the handler returns, which means the promise- // can access storage *after* `runInDurableObject` has already popped the- // isolated storage frame. Collecting and flushing ourselves keeps all- // storage access inside the frame.- ctx.waitUntil = (p: Promise<unknown>) => {- pending.push(p)- }- return {- async flush() {- await Promise.allSettled(pending)- pending.length = 0- },- }-}--const propsWithClientInfo = {- userHash: 'user-hash-client-info',- apiToken: 'phx_test_token',- clientUserAgent: 'test-agent',- mcpClientName: 'claude-code',- mcpClientVersion: '1.0.42',- mcpProtocolVersion: '2024-11-05',-}--const propsWithoutClientInfo = {- userHash: 'user-hash-client-info',- apiToken: 'phx_test_token',- clientUserAgent: 'test-agent',- // mcpClientName / mcpClientVersion / mcpProtocolVersion intentionally- // omitted — mirrors a tool-call request whose body isn't `initialize`.-}--describe('MCP client-info resolution inside the real Workers runtime', () => {- afterEach(() => {- vi.restoreAllMocks()- })-- it('init seeds client info from props and a subsequent tool-call request still sees it', async () => {- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-client-info-props'))-- await runInDurableObject(stub, async (mcp: MCP) => {- const bg = interceptWaitUntil(mcp)- ;(mcp as any).props = { ...propsWithClientInfo }- // Pre-seed project cache so init() skips the setDefault path.- // This test is about client-info resolution, not project resolution.- await mcp.cache.set('orgId', 'test-org')- await mcp.cache.set('projectId', 'test-project')-- await mcp.init()-- // Instance fields populated from the initialize request's props.- expect((mcp as any).mcpClientName).toBe('claude-code')- expect((mcp as any).mcpClientVersion).toBe('1.0.42')- expect((mcp as any).mcpProtocolVersion).toBe('2024-11-05')- expect((mcp as any).clientInfoResolved).toBe(true)-- // The ApiClient constructed during init — the same reference every- // tool handler captures via `context.api` — carries the client-info- // fields into its outbound headers.- const api = await mcp.api()- expect(api.config.mcpClientName).toBe('claude-code')- expect(api.config.mcpClientVersion).toBe('1.0.42')- expect(api.config.mcpProtocolVersion).toBe('2024-11-05')-- // Simulate the next request on the same warm DO: body is- // `tools/call`, so `extractClientInfoFromBody` returns empty and- // `requestProperties.mcpClientName` is now absent. A tool handler- // triggers `resolveClientInfo` via `api()` or `trackEvent()`.- ;(mcp as any).props = { ...propsWithoutClientInfo }-- await mcp.resolveClientInfo()-- // Memoized — instance state survives across requests in the same- // DO lifetime, even though the per-request props no longer hold- // the client info.- expect((mcp as any).mcpClientName).toBe('claude-code')- expect((mcp as any).mcpClientVersion).toBe('1.0.42')- expect((mcp as any).mcpProtocolVersion).toBe('2024-11-05')-- await bg.flush()- })- })-- it('init without props falls back to getInitializeRequest on the first post-init call', async () => {- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-client-info-storage'))-- await runInDurableObject(stub, async (mcp: MCP) => {- const bg = interceptWaitUntil(mcp)- ;(mcp as any).props = { ...propsWithoutClientInfo }- await mcp.cache.set('orgId', 'test-org')- await mcp.cache.set('projectId', 'test-project')-- // During init() the framework hasn't persisted the initialize- // message yet, so `getInitializeRequest()` returns nothing for- // every resolveClientInfo attempt that init makes (there are a- // couple: the explicit top-of-init call and the one inside- // `api()` → `getContext`).- const getInitializeRequest = vi- .spyOn(mcp as unknown as { getInitializeRequest: () => Promise<unknown> }, 'getInitializeRequest')- .mockResolvedValue(undefined)-- await mcp.init()-- // Init could not resolve — instance state stays unset and the- // memoization flag stays `false` so a later caller can retry.- expect((mcp as any).mcpClientName).toBeUndefined()- expect((mcp as any).mcpClientVersion).toBeUndefined()- expect((mcp as any).mcpProtocolVersion).toBeUndefined()- expect((mcp as any).clientInfoResolved).toBe(false)-- // Storage write has now landed (simulated by flipping the mock).- // A subsequent tool handler triggers `resolveClientInfo` and the- // fallback succeeds.- getInitializeRequest.mockResolvedValue({- params: {- clientInfo: { name: 'cursor', version: '0.42.1' },- protocolVersion: '2024-11-05',- },- })-- await mcp.resolveClientInfo()-- expect((mcp as any).mcpClientName).toBe('cursor')- expect((mcp as any).mcpClientVersion).toBe('0.42.1')- expect((mcp as any).mcpProtocolVersion).toBe('2024-11-05')- expect((mcp as any).clientInfoResolved).toBe(true)-- // Further calls short-circuit on the memoization flag — no- // additional `getInitializeRequest` invocation.- const beforeCalls = getInitializeRequest.mock.calls.length- await mcp.resolveClientInfo()- expect(getInitializeRequest.mock.calls.length).toBe(beforeCalls)-- await bg.flush()- })- })-})diff --git a/services/mcp/tests/workers/mcp-protocol.test.ts b/services/mcp/tests/workers/mcp-protocol.test.tsindex 682e302c094f..bc5a946532ee 100644--- a/services/mcp/tests/workers/mcp-protocol.test.ts+++ b/services/mcp/tests/workers/mcp-protocol.test.ts@@ -3,15 +3,11 @@ 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.+// The Worker is a stateless edge router: it terminates OAuth, validates tokens,+// and proxies `/mcp` to the Hono runtime. This suite covers that entry-point+// HTTP behavior (OAuth metadata, auth challenges, redirects) — the full MCP+// protocol loop is exercised against the Hono runtime in+// `tests/hono/mcp-protocol.test.ts`.describe('MCP HTTP entry point (Cloudflare Workers)', () => {describe('OAuth Protected Resource Metadata (RFC 9728)', () => {it('returns metadata advertising scopes_supported for /mcp', async () => {diff --git a/services/mcp/tests/workers/org-project-resolution.test.ts b/services/mcp/tests/workers/org-project-resolution.test.tsdeleted file mode 100644index 9602e91f7cc5..000000000000--- a/services/mcp/tests/workers/org-project-resolution.test.ts+++ /dev/null@@ -1,277 +0,0 @@-import { env, runInDurableObject } from 'cloudflare:test'-import { afterEach, describe, expect, it, vi } from 'vitest'--import { MissingProjectContextError } from '@/lib/errors'-import { StateManager } from '@/lib/StateManager'-import type { MCP } from '@/mcp'--// DO-level integration tests for the org/project resolution flow. Exercises the-// real `MCP` class running inside `@cloudflare/vitest-pool-workers` so we get-// the actual DurableObject cache, props pipeline, and `init()` side effects.-//-// The shared workers config (vitest.workers.config.mts) stubs `oauth/introspect`-// to return an active token with empty scopes and 404s every other outbound-// call. That means cold-start `init()` paths that read `users/@me` fall through-// to their wrapped error paths and let init complete.--/**- * Intercept `ctx.waitUntil` on a Durable Object instance so background promises- * (e.g. analytics fired at the end of `init()`) can be flushed before the- * `runInDurableObject` callback returns. Without this, lingering promises access- * DO storage outside the isolated storage frame and cause timeouts.- */-function interceptWaitUntil(mcp: MCP): { flush: () => Promise<void> } {- const pending: Promise<unknown>[] = []- const ctx = (mcp as any).ctx- // Replace — do NOT forward to the original. The real `ctx.waitUntil`- // tells the runtime to keep the DO alive after the handler returns,- // which means the promise can access storage *after*- // `runInDurableObject` has already popped the isolated storage frame.- // Collecting and flushing ourselves keeps all storage access inside- // the frame.- ctx.waitUntil = (p: Promise<unknown>) => {- pending.push(p)- }- return {- async flush() {- await Promise.allSettled(pending)- pending.length = 0- },- }-}--const propsFor = (- overrides: Partial<{ projectId: string; organizationId: string; apiToken: string }> = {}-): {- userHash: string- apiToken: string- clientUserAgent: string- projectId?: string- organizationId?: string-} => ({- userHash: 'user-hash-org-project',- apiToken: overrides.apiToken ?? 'phx_test_token',- clientUserAgent: 'test-agent',- ...(overrides.projectId !== undefined ? { projectId: overrides.projectId } : {}),- ...(overrides.organizationId !== undefined ? { organizationId: overrides.organizationId } : {}),-})--describe('MCP org/project resolution inside the real Workers runtime', () => {- afterEach(() => {- vi.restoreAllMocks()- })-- it('preserves cached org/project across re-init when no headers are pinned (sticky session)', async () => {- const setDefaultSpy = vi.spyOn(StateManager.prototype, 'setDefaultOrganizationAndProject')- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-sticky-cached'))-- await runInDurableObject(stub, async (mcp: MCP) => {- const bg = interceptWaitUntil(mcp)- ;(mcp as any).props = propsFor()- await mcp.cache.set('orgId', 'previously-picked-org')- await mcp.cache.set('projectId', 'previously-picked-project')-- await mcp.init()-- // Cache already pinned a project from a prior session — init must not- // overwrite it with whatever `users/@me` currently returns.- expect(setDefaultSpy).not.toHaveBeenCalled()- expect(await mcp.cache.get('orgId')).toBe('previously-picked-org')- expect(await mcp.cache.get('projectId')).toBe('previously-picked-project')-- await bg.flush()- })- })-- it('resolves defaults via setDefault... on a cold session with no headers and no cache', async () => {- // Stub the resolver so we don't depend on the (404-mocked) PostHog API- // for the inputs. We're verifying that init() *invokes* it on a cold- // session — the resolver itself is unit-tested separately.- const setDefaultSpy = vi- .spyOn(StateManager.prototype, 'setDefaultOrganizationAndProject')- .mockImplementation(async function (this: StateManager) {- await (this as any)._cache.set('orgId', 'resolved-org')- await (this as any)._cache.set('projectId', 'resolved-project')- return { organizationId: 'resolved-org', projectId: 999 }- })-- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-cold-no-cache'))-- await runInDurableObject(stub, async (mcp: MCP) => {- const bg = interceptWaitUntil(mcp)- ;(mcp as any).props = propsFor()- // No prior cache — fresh DO for this userHash.-- await mcp.init()-- expect(setDefaultSpy).toHaveBeenCalledOnce()- expect(await mcp.cache.get('orgId')).toBe('resolved-org')- expect(await mcp.cache.get('projectId')).toBe('resolved-project')-- await bg.flush()- })- })-- it('header-pinned projectId overrides a previously cached value (header wins)', async () => {- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-header-overrides-cache'))-- await runInDurableObject(stub, async (mcp: MCP) => {- const bg = interceptWaitUntil(mcp)- ;(mcp as any).props = propsFor()- // Simulate a prior session that cached an org + project.- await mcp.cache.set('orgId', 'cached-org')- await mcp.cache.set('projectId', 'old-cached-project')- ;(mcp as any).props = propsFor({ projectId: 'new-header-project' })-- await mcp.init()-- // Header wins on projectId; orgId is left as-is.- expect(await mcp.cache.get('projectId')).toBe('new-header-project')- expect(await mcp.cache.get('orgId')).toBe('cached-org')-- await bg.flush()- })- })-- it('does not throw for multi-team scoped API keys when the active team is not in the scope', async () => {- // Simulate the production scenario from cf-ray 9f0c989fbe7d0469: a personal- // API key scoped to multiple teams, none of which is the user's currently- // active team. The pre-fix resolver threw "API key has access to multiple- // projects..." here; the rewrite must pick scoped_teams[0] deterministically.- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-multi-team-scope'))-- await runInDurableObject(stub, async (mcp: MCP) => {- ;(mcp as any).props = propsFor()-- // Reach into the StateManager that init() would build via getContext().- const context = await (mcp as any).getContext()- const sm: StateManager = context.stateManager-- vi.spyOn(sm, 'getApiKey').mockResolvedValue({- scopes: [],- scoped_teams: [111, 222, 333],- scoped_organizations: [],- })- vi.spyOn(sm, 'getUser').mockResolvedValue({- distinct_id: 'distinct-multi-team',- email: '[email protected]',- organizations: [],- team: { id: 999, name: 'Active', timezone: 'UTC', organization: 'org-active' },- organization: { id: 'org-active', name: 'Active' },- } as any)-- const resolved = await sm.setDefaultOrganizationAndProject()-- expect(resolved.projectId).toBe(111) // first scoped team- expect(await mcp.cache.get('projectId')).toBe('111')- })- })-- it('prefers the active team when it is in the multi-team scope', async () => {- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-multi-team-active-in-scope'))-- await runInDurableObject(stub, async (mcp: MCP) => {- ;(mcp as any).props = propsFor()- const sm: StateManager = (await (mcp as any).getContext()).stateManager-- vi.spyOn(sm, 'getApiKey').mockResolvedValue({- scopes: [],- scoped_teams: [111, 222, 333],- scoped_organizations: [],- })- vi.spyOn(sm, 'getUser').mockResolvedValue({- distinct_id: 'distinct-active-in-scope',- email: '[email protected]',- organizations: [],- team: { id: 222, name: 'Active', timezone: 'UTC', organization: 'org-active' },- organization: { id: 'org-active', name: 'Active' },- } as any)-- const resolved = await sm.setDefaultOrganizationAndProject()-- expect(resolved.projectId).toBe(222) // the active team, not scoped_teams[0]- expect(await mcp.cache.get('projectId')).toBe('222')- })- })-- it('init completes for a project-scoped API key without organization:read (no org fetch)', async () => {- // Production scenario behind the dogpile silenced by #58726 and now- // fixed at the source: a personal API key scoped to a single project- // carries `project:read` but not `organization:read`. Pre-guard, every- // session init would still issue GET /api/organizations/{id}/ from- // both getEnvironmentPrompt and getAiConsentGiven and 403. The guard- // short-circuits the fetch so the request path completes without- // capturing the expected denial.- vi.spyOn(StateManager.prototype, 'getApiKey').mockResolvedValue({- scopes: ['project:read', 'insight:read'],- scoped_teams: [1],- scoped_organizations: [],- })- // Wrap, don't replace: the real implementation still runs and we- // observe its behavior. Without the guard this would resolve to the- // captured org fixture; with the guard it resolves to `undefined`.- const orgFetchSpy = vi.spyOn(StateManager.prototype, 'getCachedOrFetchOrg')-- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-project-scoped-no-org-read'))-- await runInDurableObject(stub, async (mcp: MCP) => {- const bg = interceptWaitUntil(mcp)- ;(mcp as any).props = propsFor()-- await expect(mcp.init()).resolves.toBeUndefined()-- // getEnvironmentPrompt and getAiConsentGiven both go through the- // org fetcher — assert it was invoked and that each invocation- // returned `undefined` without throwing.- expect(orgFetchSpy).toHaveBeenCalled()- for (const call of orgFetchSpy.mock.results) {- await expect(call.value).resolves.toBeUndefined()- }-- await bg.flush()- })- })-- it('getProjectId throws MissingProjectContextError with the scoped org when no project is resolvable', async () => {- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-missing-project'))-- await runInDurableObject(stub, async (mcp: MCP) => {- ;(mcp as any).props = propsFor()- const sm: StateManager = (await (mcp as any).getContext()).stateManager-- vi.spyOn(sm, 'getApiKey').mockResolvedValue({- scopes: [],- scoped_teams: [],- scoped_organizations: ['org-out-of-reach'],- })- vi.spyOn(sm, 'getUser').mockResolvedValue({- distinct_id: 'distinct-no-project',- email: '[email protected]',- organizations: [],- team: { id: 999, name: 'Active', timezone: 'UTC', organization: 'org-different' },- organization: { id: 'org-different', name: 'Different' },- } as any)- // Make the projects-list call fail so the resolver returns just the org.- ;(sm as any)._api = {- organizations: () => ({- projects: () => ({- list: vi.fn().mockResolvedValue({ success: false, error: new Error('boom') }),- }),- }),- }-- await expect(sm.getProjectId()).rejects.toMatchObject({- name: 'MissingProjectContextError',- organizationId: 'org-out-of-reach',- })-- try {- await sm.getProjectId()- } catch (err) {- expect(err).toBeInstanceOf(MissingProjectContextError)- expect((err as Error).message).toContain('switch-project')- expect((err as Error).message).toContain('org-out-of-reach')- }- })- })-})diff --git a/services/mcp/tests/workers/token-rotation.test.ts b/services/mcp/tests/workers/token-rotation.test.tsdeleted file mode 100644index 1c6eeed1e751..000000000000--- a/services/mcp/tests/workers/token-rotation.test.ts+++ /dev/null@@ -1,108 +0,0 @@-import { env, runInDurableObject } from 'cloudflare:test'-import { describe, expect, it } from 'vitest'--import type { MCP } from '@/mcp'--// DO-level integration test for OAuth token rotation against the real Workers-// runtime. The production bug: Cloudflare routes the same `mcp-session-id` to-// the same warm DO, and partyserver's `setName` short-circuits on warm DOs,-// updating only its private `#_props` and returning early without re-running-// `onStart`. That leaves the cached `ApiClient` — captured during `init()` and-// handed to every tool handler via `context.api` — pointing at a stale token.-//-// These tests exercise the `updateProps` override (which the agents SDK calls-// from `onStart` on every cold start and hibernation wake) against the real-// `agents/mcp` McpAgent + `partyserver` Server base classes via-// `runInDurableObject`. The `setName` override delegates to the same-// `rotateCachedApiToken` primitive, so warm-setName coverage is handled by the-// unit tests in `tests/unit/mcp-api-caching.test.ts` — attempting to exercise-// it end-to-end here would require full cold-start `init()` to complete, which-// pulls in every PostHog endpoint + context-mill + PostHog MCP analytics and-// is better covered at the HTTP layer in a future test.--const propsFor = (apiToken: string): { userHash: string; apiToken: string; clientUserAgent: string } => ({- userHash: 'user-hash',- apiToken,- clientUserAgent: 'test-agent',-})--// Mirrors what a tool handler does after capturing `context.api` in its-// closure: read `.config.apiToken` on every downstream request. If in-place-// rotation ever regresses to instance replacement, this returns stale.-function readTokenFromCapturedApi(api: { config: { apiToken: string } }): string {- return api.config.apiToken-}--describe('MCP token rotation inside the real Workers runtime', () => {- it('updateProps rotates the cached ApiClient token in place (hibernation wake path)', async () => {- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-updateprops'))-- await runInDurableObject(stub, async (mcp: MCP) => {- // Cold path: updateProps persists props to storage and assigns this.props.- // rotateCachedApiToken is a no-op since there's no cached _api yet.- await mcp.updateProps(propsFor('token-A'))- expect(mcp.props).toEqual(propsFor('token-A'))-- // Construct the ApiClient lazily — this is the reference that tool- // handlers capture via `context.api` during init().- const capturedApi = await mcp.api()- expect(readTokenFromCapturedApi(capturedApi)).toBe('token-A')-- // Hibernation-wake path: agents SDK calls updateProps(propsB) and- // our override rotates the cached token synchronously (before the- // storage write) so any tool handler reading config.apiToken- // observes the new token without waiting.- await mcp.updateProps(propsFor('token-B'))- expect(readTokenFromCapturedApi(capturedApi)).toBe('token-B')- expect(mcp.props).toEqual(propsFor('token-B'))-- // Storage persisted the new props (partyserver hydrates from here- // after the DO sleeps and wakes).- const storedProps = await (mcp as unknown as { ctx: DurableObjectState }).ctx.storage.get('props')- expect(storedProps).toEqual(propsFor('token-B'))- })- })-- it('is resilient across many updateProps rotations (OAuth refresh loop)', async () => {- // Repeated hibernation wakes with fresh tokens. The captured ApiClient- // reference must track every rotation without being rebuilt.- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-many-rotations'))-- await runInDurableObject(stub, async (mcp: MCP) => {- await mcp.updateProps(propsFor('token-initial'))- const capturedApi = await mcp.api()-- const rotations = ['token-1', 'token-2', 'token-3', 'token-4', 'token-5']- for (const token of rotations) {- await mcp.updateProps(propsFor(token))- expect(readTokenFromCapturedApi(capturedApi)).toBe(token)- }-- // Final identity check: the reference is still the instance that- // `api()` hands out — we never replaced it.- expect(await mcp.api()).toBe(capturedApi)- })- })-- it('regression: a tool-handler-style closure reads the rotated token after warm rotation', async () => {- // Reproduces the production bug. Before the override, a closure over- // `context.api` (what every tool handler is) kept returning the stale- // token on warm DOs until the DO hibernated and cold-started.- const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-closure'))-- await runInDurableObject(stub, async (mcp: MCP) => {- await mcp.updateProps(propsFor('token-before'))- const capturedApi = await mcp.api()- const toolHandler = (): string => readTokenFromCapturedApi(capturedApi)-- expect(toolHandler()).toBe('token-before')-- await mcp.updateProps(propsFor('token-after'))-- // The closure — which never re-reads `context.api` — must now see- // the new token. Regression to instance replacement (or omission- // of the rotation) flips this to 'token-before'.- expect(toolHandler()).toBe('token-after')- })- })-})diff --git a/services/mcp/worker-configuration.d.ts b/services/mcp/worker-configuration.d.tsindex 883a1e725358..adbeb7ff8230 100644--- a/services/mcp/worker-configuration.d.ts+++ b/services/mcp/worker-configuration.d.ts@@ -4,7 +4,6 @@declare namespace Cloudflare {interface GlobalProps {mainModule: typeof import("./src/index");- durableNamespaces: "MCP";}interface Env {MCP_APPS_BASE_URL: "https://mcp.posthog.com";@@ -14,7 +13,6 @@ declare namespace Cloudflare {POSTHOG_UI_APPS_TOKEN: string;POSTHOG_ANALYTICS_API_KEY: string;POSTHOG_ANALYTICS_HOST: string;- MCP_OBJECT: DurableObjectNamespace<import("./src/index").MCP>;ASSETS: Fetcher;}}diff --git a/services/mcp/wrangler.jsonc b/services/mcp/wrangler.jsoncindex 57baf97b8ec5..3429be28d47c 100644--- a/services/mcp/wrangler.jsonc+++ b/services/mcp/wrangler.jsonc@@ -26,6 +26,13 @@],"tag": "v2",},+ {+ // The worker now proxies all /mcp traffic to the Hono runtime, so the+ // MCP durable object is no longer instantiated. Drop the class and its+ // (ephemeral per-user cache) storage.+ "deleted_classes": ["MCP"],+ "tag": "v3",+ },],"kv_namespaces": [{@@ -33,14 +40,6 @@"id": "30a887fff4d04c4fbf979208293ce012",},],- "durable_objects": {- "bindings": [- {- "class_name": "MCP",- "name": "MCP_OBJECT",- },- ],- },"observability": {"enabled": true,"head_sampling_rate": 0.1,