: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
fix(mcp): make initiliasation faster (#59232)
Joshua Snyderd8706969d1b7
diff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.tsindex 9f3da173c153..5ce631f40e9a 100644--- a/services/mcp/src/hono/app.ts+++ b/services/mcp/src/hono/app.ts@@ -10,6 +10,7 @@ export type Lifecycle = { shuttingDown: boolean }export type App = {app: Honolifecycle: Lifecycle+ warmup: () => Promise<void>}export function createApp(redis: RedisWithPing): App {@@ -35,5 +36,10 @@ export function createApp(redis: RedisWithPing): App {app.all('/mcp/*', streamable.fetch)app.all('*', (c) => c.notFound())- return { app, lifecycle }++ return {+ app,+ lifecycle,+ warmup: () => streamable.warmup(),+ }}diff --git a/services/mcp/src/hono/index.ts b/services/mcp/src/hono/index.tsindex 2c14f57a3241..bfe697fc4a8e 100644--- a/services/mcp/src/hono/index.ts+++ b/services/mcp/src/hono/index.ts@@ -47,7 +47,9 @@ async function main(): Promise<void> {process.exit(1)}- const { app, lifecycle } = createApp(redis as unknown as Parameters<typeof createApp>[0])+ const { app, lifecycle, warmup } = createApp(redis as unknown as Parameters<typeof createApp>[0])++ await warmup()const server = serve({ fetch: app.fetch, port: PORT, hostname: HOST }, (info) => {console.info(`[MCP] Server started on ${HOST}:${info.port}`)diff --git a/services/mcp/src/hono/mcp-server.ts b/services/mcp/src/hono/mcp-server.tsindex 1e82e985ea50..78e53d40704c 100644--- a/services/mcp/src/hono/mcp-server.ts+++ b/services/mcp/src/hono/mcp-server.ts@@ -30,9 +30,17 @@ import { createExecInnerToolCallResolver, createExecTool, type ExecInnerCallTracimport { getToolDefinition } from '@/tools/toolDefinitions'import { type Context, type Env, type State, type Tool } from '@/tools/types'+import type { ContextMillResource } from '@/resources/manifest-types'+import { RedisCache, type RedisLike } from './cache/RedisCache'import { getCustomApiBaseUrl, getEnv } from './constants'import { initDurationSeconds, toolCallDurationSeconds, toolCallsTotal } from './metrics'+import type { ToolCatalog, ToolCatalogFilterOptions } from './tool-catalog'++export interface WarmupData {+ catalog: ToolCatalog+ resourceEntries: readonly ContextMillResource[]+}export type { RequestProperties }@@ -77,11 +85,13 @@ export class HonoMcpServer {private mcpProtocolVersion: string | undefinedprivate mcpMode: McpMode | undefinedprivate mcpVersion: number | undefined+ private _warmup: WarmupData | undefined- constructor(redis: RedisLike, props: RequestProperties) {+ constructor(redis: RedisLike, props: RequestProperties, warmup?: WarmupData) {this.props = propsthis.redis = redisthis.env = getEnv()+ this._warmup = warmupthis.server = new McpServer({ name: 'PostHog', version: '1.0.0' },{ instructions: instructionsFormatter.buildV1Instructions() }@@ -365,9 +375,16 @@ export class HonoMcpServer {}private async initInner(): Promise<void> {+ const _t0 = performance.now()+ const _lap = (label: string): void => {+ const elapsed = performance.now() - _t0+ console.log(`[init-profile] ${label.padEnd(40)} +${(elapsed).toFixed(0)}ms`)+ }+const { features, tools, version: clientVersion, organizationId, projectId, readOnly, mode } = this.propsawait this.resolveClientInfo()+ _lap('resolveClientInfo')// Start feature flag resolution in parallel with cache seedingconst flagPromise = this.resolveVersionFlag()@@ -383,8 +400,11 @@ export class HonoMcpServer {cachedProjectId = projectIdawait this.cache.set('projectId', projectId)}+ _lap('cache seeding')const context = await this.getContext()+ _lap('getContext')+if (!cachedProjectId) {cachedProjectId = await this.cache.get('projectId')}@@ -393,14 +413,15 @@ export class HonoMcpServer {if (!cachedProjectId) {await context.stateManager.setDefaultOrganizationAndProject()}+ _lap('setDefaultOrgAndProject')const [flagVersion, toolFeatureFlags, singleExecFlagOn, _apiKey] = await Promise.all([flagPromise,toolFlagsPromise,singleExecPromise,- // Trigger OAuth introspection so the OAuth client name is cached before the useSingleExec decision belowcontext.stateManager.getApiKey(),])+ _lap('flags + getApiKey')const oauthClientName = (await this.cache.get('clientName')) || undefined@@ -419,20 +440,17 @@ export class HonoMcpServer {clientVersion,})- // Fetch group types and metadata in parallel (cache is now seeded)+ // Fetch group types, metadata, and AI consent 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- })(),+ const apiKeyScopes = _apiKey?.scopes ?? []+ const [groupTypes, metadata, aiConsentGiven] = await Promise.all([+ resolvedProjectId && hasScope(apiKeyScopes, 'group:read')+ ? context.stateManager.getOrFetchGroupTypes(resolvedProjectId)+ : undefined,context.stateManager.getEnvironmentPrompt(),+ context.stateManager.getAiConsentGiven(),])+ _lap('groupTypes + metadata')// When project ID is provided, both switch tools are removed (project implies org).// When only organization ID is provided, only switch-organization is removed.@@ -443,21 +461,19 @@ export class HonoMcpServer {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, {+ // Resolve tools — use pre-built catalog when available, else fall back to full init+ const allTools = await this.resolveTools(context, {features,tools,version,excludeTools,readOnly,featureFlags: toolFeatureFlags,+ scopes: apiKeyScopes,+ aiConsentGiven: aiConsentGiven ?? undefined,})+ _lap(`resolveTools (${allTools.length} tools, catalog=${!!this._warmup?.catalog.warmedUp})`)- // 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}@@ -500,13 +516,18 @@ export class HonoMcpServer {}this.server = new McpServer({ name: 'PostHog', version: '1.0.0' }, { instructions })+ _lap('new McpServer + instructions')- // Register prompts and resources- await Promise.all([- registerPrompts(this.server),- registerResources(this.server, context),- registerUiAppResources(this.server, context),- ])+ // Register prompts and resources — use pre-parsed entries when available+ await registerPrompts(this.server)+ if (this._warmup?.resourceEntries.length) {+ const { registerResourceEntries } = await import('@/resources')+ registerResourceEntries(this.server, this._warmup.resourceEntries)+ } else {+ await registerResources(this.server, context)+ }+ await registerUiAppResources(this.server, context)+ _lap('registerPrompts + registerResources')// execute-sql is v2-only. Swap its description with the rich SQL prompt.if (version === 2) {@@ -592,6 +613,8 @@ export class HonoMcpServer {// $mcp_exec_tool_call_name from mcp_tool_call.const execInnerToolNames = useSingleExec ? allTools.map((t) => t.name) : undefined+ _lap('registerTools')+const initResult = await initMcpAnalytics(this.server, mcpAnalyticsIdentity, {contextEnabled: true,resolveExecInnerToolCall,@@ -620,6 +643,8 @@ export class HonoMcpServer {// above populated `cachedProject`/`cachedOrg`), so this is effectively free here.const analyticsContext = await this.getAnalyticsContextSafe(context)+ _lap('initMcpAnalytics')+void this.trackEvent(AnalyticsEvent.MCP_INIT,{@@ -664,6 +689,17 @@ export class HonoMcpServer {return { useSingleExec, version }}+ private async resolveTools(+ context: Context,+ options: ToolCatalogFilterOptions+ ): Promise<Tool<z.ZodObject>[]> {+ if (this._warmup?.catalog.warmedUp) {+ return this._warmup.catalog.getFilteredTools(options) as Tool<z.ZodObject>[]+ }+ const { getToolsFromContext } = await import('@/tools')+ return (await getToolsFromContext(context, options)) as Tool<z.ZodObject>[]+ }+private async resolveVersionFlag(): Promise<number | undefined> {try {const distinctId = await this.getDistinctId()diff --git a/services/mcp/src/hono/request-utils.ts b/services/mcp/src/hono/request-utils.tsindex 6951df204b91..3ec4af67bb33 100644--- a/services/mcp/src/hono/request-utils.ts+++ b/services/mcp/src/hono/request-utils.ts@@ -86,6 +86,7 @@ export async function authenticateAndParse(}export function handleCatchError(error: unknown, props: RequestProperties): Response {+ console.error('[handleCatchError]', error)const authResponse = mapErrorToAuthResponse(error)if (authResponse) {return authResponsediff --git a/services/mcp/src/hono/streamable-handler.ts b/services/mcp/src/hono/streamable-handler.tsindex 536e35bdc080..8b15eadaa0e1 100644--- a/services/mcp/src/hono/streamable-handler.ts+++ b/services/mcp/src/hono/streamable-handler.ts@@ -1,17 +1,45 @@import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'+import type { ContextMillResource } from '@/resources/manifest-types'+import type { Lifecycle } from './app'import type { RedisLike } from './cache/RedisCache'import { HonoMcpServer } from './mcp-server'import { authenticateAndParse, handleCatchError, passThrough } from './request-utils'+import { ToolCatalog } from './tool-catalog'import type { HonoCtx } from './types'export class StreamableMcpHandler {+ private readonly catalog = new ToolCatalog()+ private _resourceEntries: readonly ContextMillResource[] = []+constructor(private readonly redis: RedisLike,private readonly lifecycle: Lifecycle) {}+ get resourceEntries(): readonly ContextMillResource[] {+ return this._resourceEntries+ }++ async warmup(): Promise<void> {+ await Promise.all([this.catalog.warmup(), this._warmupResources()])+ }++ private async _warmupResources(): Promise<void> {+ try {+ const { fetchContextMillResources, filterValidEntries, loadManifestFromArchive, clearResourceCache } =+ await import('@/resources/internals')+ const archive = await fetchContextMillResources()+ const manifest = loadManifestFromArchive(archive)+ this._resourceEntries = filterValidEntries(manifest.resources, archive)+ clearResourceCache()+ } catch (error) {+ console.error('[StreamableMcpHandler] Failed to pre-load context-mill resources:', error)+ this._resourceEntries = []+ }+ }+fetch = async (c: HonoCtx): Promise<Response> => {if (c.req.method !== 'POST') {return new Response('Method not allowed', { status: 405 })@@ -26,7 +54,10 @@ export class StreamableMcpHandler {}try {- const mcpServer = new HonoMcpServer(this.redis, auth.props)+ const mcpServer = new HonoMcpServer(this.redis, auth.props, {+ catalog: this.catalog,+ resourceEntries: this._resourceEntries,+ })await mcpServer.init()const transport = new WebStandardStreamableHTTPServerTransport({})await mcpServer.server.connect(transport)diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.tsnew file mode 100644index 000000000000..26fef158e750--- /dev/null+++ b/services/mcp/src/hono/tool-catalog.ts@@ -0,0 +1,110 @@+import { hasScopes } from '@/lib/api'+import {+ type ToolDefinition,+ type ToolFilterOptions,+ getToolDefinition,+ getToolDefinitions,+ getToolsForFeatures,+} from '@/tools/toolDefinitions'+import type { Tool, ToolBase, ZodObjectAny } from '@/tools/types'++interface PreBuiltTool {+ base: ToolBase<ZodObjectAny>+ definitions: {+ v1: ToolDefinition | undefined+ v2: ToolDefinition | undefined+ }+}++export interface ToolCatalogFilterOptions extends ToolFilterOptions {+ scopes?: string[]+ excludeTools?: string[]+}++export class ToolCatalog {+ private _preBuilt: Map<string, PreBuiltTool> = new Map()+ private _warmedUp = false++ get warmedUp(): boolean {+ return this._warmedUp+ }++ async warmup(): Promise<void> {+ if (this._warmedUp) {+ return+ }++ const start = performance.now()++ const [{ TOOL_MAP }, { GENERATED_TOOL_MAP }] = await Promise.all([+ import('@/tools'),+ import('@/tools/generated'),+ ])++ const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = {+ ...TOOL_MAP,+ ...GENERATED_TOOL_MAP,+ }++ const v1Defs = getToolDefinitions(1)+ const v2Defs = getToolDefinitions(2)++ for (const [name, factory] of Object.entries(allFactories)) {+ const base = factory()+ this._preBuilt.set(name, {+ base,+ definitions: {+ v1: v1Defs[name],+ v2: v2Defs[name],+ },+ })+ }++ this._warmedUp = true+ console.info(+ `[ToolCatalog] warmup complete: ${this._preBuilt.size} tools in ${(performance.now() - start).toFixed(0)}ms`+ )+ }++ getFilteredTools(options: ToolCatalogFilterOptions): Tool<ZodObjectAny>[] {+ const { scopes = [], excludeTools = [], ...filterOptions } = options+ const allowedToolNames = getToolsForFeatures(filterOptions).filter(+ (name) => !excludeTools.includes(name)+ )+ const effectiveVersion = filterOptions.version ?? 1++ const tools: Tool<ZodObjectAny>[] = []++ for (const name of allowedToolNames) {+ const preBuilt = this._preBuilt.get(name)+ if (!preBuilt) {+ continue+ }+ const { base } = preBuilt++ if (base.mcpVersion !== undefined && base.mcpVersion !== effectiveVersion) {+ continue+ }++ const definition =+ preBuilt.definitions[effectiveVersion === 2 ? 'v2' : 'v1'] ?? preBuilt.definitions.v1+ if (!definition) {+ continue+ }++ if (!hasScopes(scopes, definition.required_scopes ?? [])) {+ continue+ }++ tools.push({+ ...base,+ title: definition.title,+ description: definition.description,+ scopes: definition.required_scopes ?? [],+ annotations: definition.annotations,+ })+ }++ return tools+ }+}diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.tsindex fd1bc668cf7a..a1e4d62a78cd 100644--- a/services/mcp/src/lib/StateManager.ts+++ b/services/mcp/src/lib/StateManager.ts@@ -250,7 +250,7 @@ export class StateManager {this._cache.get(opts.fetchedAtKey),])) as [State[D], number | undefined]- if (cached !== undefined && !this.isCacheStale(fetchedAt)) {+ if (!this.isCacheStale(fetchedAt)) {return cached}@@ -263,6 +263,7 @@ export class StateManager {return data as State[D]} catch (error) {this._reportException(error, `get_or_fetch_${opts.name}`)+ await this._cache.set(opts.fetchedAtKey, Date.now() as State[F]).catch(() => {})return cached}}diff --git a/services/mcp/src/resources/index.ts b/services/mcp/src/resources/index.tsindex 893b7acd8692..f6ed825b146f 100644--- a/services/mcp/src/resources/index.ts+++ b/services/mcp/src/resources/index.ts@@ -1,126 +1,54 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'-import { type Unzipped, strFromU8, unzipSync } from 'fflate'import type { Context } from '@/tools/types'-import { loadContextMillManifest } from './manifest-loader'-import type { ContextMillManifest, ResourceManifest } from './manifest-types'+import type { ContextMillResource, ResourceManifest } from './manifest-types'+import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive } from './internals'-/**- * URL to the context-mill resources ZIP (latest release)- * Contains manifest.json + individual resource ZIPs- */-export const CONTEXT_MILL_URL =- 'https://github.com/PostHog/context-mill/releases/latest/download/skills-mcp-resources.zip'+export { fetchContextMillResources, filterValidEntries, loadManifestFromArchive }-// Cache for context-mill resources ZIP contents-let cachedResources: Unzipped | null = null--/**- * Fetches and caches the context-mill resources ZIP- * For local testing, set POSTHOG_MCP_LOCAL_SKILLS_URL to a local HTTP URL- */-async function fetchContextMillResources(context: Context): Promise<Unzipped> {- // Check for local URL override in environment (for testing)- const localUrlRaw = (context.env as Record<string, string | undefined>)?.POSTHOG_MCP_LOCAL_SKILLS_URL- const localUrl = localUrlRaw && localUrlRaw.trim() !== '' ? localUrlRaw : undefined- const url = localUrl || CONTEXT_MILL_URL-- // Skip cache for local development- if (cachedResources && !localUrl) {- return cachedResources- }-- const response = await fetch(url, localUrl ? { cache: 'no-store' } : {})-- if (!response.ok) {- throw new Error(`Failed to fetch context-mill resources from ${url}: ${response.statusText}`)- }-- const arrayBuffer = await response.arrayBuffer()- const uint8Array = new Uint8Array(arrayBuffer)- const unzipped = unzipSync(uint8Array)-- // Only cache if not using local URL override- if (!localUrl) {- cachedResources = unzipped- }-- return unzipped+export async function getPromptsFromManifest(): Promise<ResourceManifest['resources']['prompts']> {+ return []}-/**- * Load context-mill manifest from the resources archive- */-function loadManifestFromArchive(archive: Unzipped): ContextMillManifest {- const manifestData = archive['manifest.json']- if (!manifestData) {- throw new Error('manifest.json not found in archive')+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,+ },+ ],+ })+ )}- const rawManifest = JSON.parse(strFromU8(manifestData))- return loadContextMillManifest(rawManifest)-}--/**- * Get prompts from the manifest- * Currently returns empty - prompts will be migrated to context-mill resources- */-export async function getPromptsFromManifest(): Promise<ResourceManifest['resources']['prompts']> {- return []}-/**- * Register resources from the context-mill manifest.- * The manifest fully defines each resource's MCP representation —- * this function is a pure pass-through.- */async function registerContextMillResources(server: McpServer, context: Context): Promise<void> {- // Tests disable context-mill registration via the workers config so init()- // doesn't fan out to a real GitHub fetch from inside the workerd test runtime.if ((context.env as Record<string, string | undefined>)?.TEST === '1') {return}try {- const archive = await fetchContextMillResources(context)+ 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)- for (const entry of manifest.resources) {- // Validate archive file exists for non-inline resources- if (entry.file) {- const zipData = archive[entry.file]- if (!zipData) {- console.warn(`Resource file "${entry.file}" not found in archive, skipping`)- continue- }- }-- 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,- },- ],- })- )- }+ registerResourceEntries(server, filterValidEntries(manifest.resources, archive))} catch (error) {console.error('Failed to register context-mill resources:', error)}}-/**- * Registers all PostHog resources with the MCP server- * Resources are loaded from context-mill's skills-mcp-resources.zip- */export async function registerResources(server: McpServer, context: Context): Promise<void> {await registerContextMillResources(server, context)}diff --git a/services/mcp/src/resources/internals.ts b/services/mcp/src/resources/internals.tsnew file mode 100644index 000000000000..91f21f3f5f96--- /dev/null+++ b/services/mcp/src/resources/internals.ts@@ -0,0 +1,55 @@+import { type Unzipped, strFromU8, unzipSync } from 'fflate'++import type { ContextMillManifest, ContextMillResource } from './manifest-types'+import { loadContextMillManifest } from './manifest-loader'++const CONTEXT_MILL_URL =+ 'https://github.com/PostHog/context-mill/releases/latest/download/skills-mcp-resources.zip'++let cachedResources: Unzipped | null = null++export async function fetchContextMillResources(localUrl?: string): Promise<Unzipped> {+ const url = localUrl || CONTEXT_MILL_URL++ if (cachedResources && !localUrl) {+ return cachedResources+ }++ const response = await fetch(url, localUrl ? { cache: 'no-store' } : {})+ if (!response.ok) {+ throw new Error(`Failed to fetch context-mill resources from ${url}: ${response.statusText}`)+ }++ const arrayBuffer = await response.arrayBuffer()+ const uint8Array = new Uint8Array(arrayBuffer)+ const unzipped = unzipSync(uint8Array)++ if (!localUrl) {+ cachedResources = unzipped+ }++ return unzipped+}++export function loadManifestFromArchive(archive: Unzipped): ContextMillManifest {+ const manifestData = archive['manifest.json']+ if (!manifestData) {+ throw new Error('manifest.json not found in archive')+ }+ const rawManifest = JSON.parse(strFromU8(manifestData))+ return loadContextMillManifest(rawManifest)+}++export function filterValidEntries(entries: readonly ContextMillResource[], archive: Unzipped): ContextMillResource[] {+ return entries.filter((entry) => {+ if (entry.file && !archive[entry.file]) {+ console.warn(`Resource file "${entry.file}" not found in archive, skipping`)+ return false+ }+ return true+ })+}++export function clearResourceCache(): void {+ cachedResources = null+}diff --git a/services/mcp/src/resources/ui-apps.ts b/services/mcp/src/resources/ui-apps.tsindex 57a043658700..3f39e9165587 100644--- a/services/mcp/src/resources/ui-apps.ts+++ b/services/mcp/src/resources/ui-apps.ts@@ -36,10 +36,15 @@ export function buildAppStubHtml(appDir: string, baseUrl: string): string {** Each tool type can have its own visualization registered here.*/+let warnedMissingBaseUrl = false+export async function registerUiAppResources(server: McpServer, context: Context): Promise<void> {const baseUrl = context.env.MCP_APPS_BASE_URLif (!baseUrl) {- console.warn('MCP_APPS_BASE_URL is not set — UI app resources will not be registered')+ if (!warnedMissingBaseUrl) {+ warnedMissingBaseUrl = true+ console.warn('MCP_APPS_BASE_URL is not set — UI app resources will not be registered')+ }return}diff --git a/services/mcp/tests/integration/manifest.test.ts b/services/mcp/tests/integration/manifest.test.tsindex 3297cfac30c7..d992fc1fb111 100644--- a/services/mcp/tests/integration/manifest.test.ts+++ b/services/mcp/tests/integration/manifest.test.ts@@ -1,37 +1,16 @@-import { strFromU8, unzipSync } from 'fflate'import { describe, expect, it } from 'vitest'-import { CONTEXT_MILL_URL } from '@/resources/index'-import { loadContextMillManifest } from '@/resources/manifest-loader'+import { fetchContextMillResources, loadManifestFromArchive } from '@/resources/internals'describe('Context-Mill Manifest Integration', () => {it('should fetch, unzip, and validate the manifest from GitHub releases', async () => {- // Fetch the resources ZIP- const response = await fetch(CONTEXT_MILL_URL)- expect(response.ok).toBe(true)-- // Unzip the archive- const arrayBuffer = await response.arrayBuffer()- const uint8Array = new Uint8Array(arrayBuffer)- const archive = unzipSync(uint8Array)+ const archive = await fetchContextMillResources()// Verify archive is not emptyexpect(Object.keys(archive).length).toBeGreaterThan(0)- // Verify manifest.json exists- const manifestData = archive['manifest.json']- expect(manifestData).toBeTruthy()- if (!manifestData) {- throw new Error('manifest.json not found in archive')- }-- // Verify manifest is valid JSON- const manifestJson = strFromU8(manifestData)- const manifest = JSON.parse(manifestJson)- expect(manifest).toBeTruthy()-- // Validate manifest structure using our loader (throws if invalid)- const validatedManifest = loadContextMillManifest(manifest)+ // Verify manifest.json exists and validates+ const validatedManifest = loadManifestFromArchive(archive)// Verify expected structureexpect(validatedManifest.version).toBe('1.0')@@ -51,5 +30,5 @@ describe('Context-Mill Manifest Integration', () => {expect(archive[entry.file]).toBeTruthy()}}- }, 30000) // 30 second timeout for network request+ }, 30000)})diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.tsindex afb477c61201..f876689a646a 100644--- a/services/mcp/tests/unit/StateManager.test.ts+++ b/services/mcp/tests/unit/StateManager.test.ts@@ -419,6 +419,84 @@ describe('StateManager', () => {})})+ describe('getOrFetchCached (via getOrFetchGroupTypes)', () => {+ const projectId = '42'++ it('should fetch and cache on first call', async () => {+ const mockGroupTypes = [{ group_type: 'company', group_type_index: 0 }]+ const mockApi = stateManager as any+ mockApi._api = {+ getGroupTypes: vi.fn().mockResolvedValue(mockGroupTypes),+ }++ const result = await stateManager.getOrFetchGroupTypes(projectId)++ expect(result).toEqual(mockGroupTypes)+ expect(await cache.get(`groupTypes:${projectId}` as any)).toEqual(mockGroupTypes)+ expect(await cache.get(`groupTypesFetchedAt:${projectId}` as any)).toEqual(expect.any(Number))+ })++ it('should return cached value without re-fetching when not stale', async () => {+ const mockGroupTypes = [{ group_type: 'company', group_type_index: 0 }]+ await cache.set(`groupTypes:${projectId}` as any, mockGroupTypes as any)+ await cache.set(`groupTypesFetchedAt:${projectId}` as any, Date.now() as any)++ const getGroupTypes = vi.fn()+ const mockApi = stateManager as any+ mockApi._api = { getGroupTypes }++ const result = await stateManager.getOrFetchGroupTypes(projectId)++ expect(result).toEqual(mockGroupTypes)+ expect(getGroupTypes).not.toHaveBeenCalled()+ })++ it('should not retry a failed fetch within the cache TTL (negative caching)', async () => {+ const getGroupTypes = vi.fn().mockRejectedValue(new Error('API error'))+ const mockApi = stateManager as any+ mockApi._api = { getGroupTypes }++ const first = await stateManager.getOrFetchGroupTypes(projectId)+ expect(first).toBeUndefined()+ expect(getGroupTypes).toHaveBeenCalledOnce()++ const second = await stateManager.getOrFetchGroupTypes(projectId)+ expect(second).toBeUndefined()+ expect(getGroupTypes).toHaveBeenCalledOnce()+ })++ it('should retry after the cache TTL expires', async () => {+ const getGroupTypes = vi.fn().mockRejectedValue(new Error('API error'))+ const mockApi = stateManager as any+ mockApi._api = { getGroupTypes }++ await stateManager.getOrFetchGroupTypes(projectId)+ expect(getGroupTypes).toHaveBeenCalledOnce()++ await cache.set(`groupTypesFetchedAt:${projectId}` as any, (Date.now() - 11 * 60 * 1000) as any)++ await stateManager.getOrFetchGroupTypes(projectId)+ expect(getGroupTypes).toHaveBeenCalledTimes(2)+ })++ it('should return undefined (not stale data) when fetch succeeds then later fails', async () => {+ const mockGroupTypes = [{ group_type: 'company', group_type_index: 0 }]+ const getGroupTypes = vi.fn()+ .mockResolvedValueOnce(mockGroupTypes)+ .mockRejectedValueOnce(new Error('API error'))+ const mockApi = stateManager as any+ mockApi._api = { getGroupTypes }++ const first = await stateManager.getOrFetchGroupTypes(projectId)+ expect(first).toEqual(mockGroupTypes)++ await cache.set(`groupTypesFetchedAt:${projectId}` as any, (Date.now() - 11 * 60 * 1000) as any)++ const second = await stateManager.getOrFetchGroupTypes(projectId)+ expect(second).toEqual(mockGroupTypes)+ })+ })+describe('getAnalyticsContext', () => {it('returns organization, project, UUID, and name from the cached project', async () => {await cache.set('orgId', 'org-1')diff --git a/services/mcp/tests/unit/tool-catalog.test.ts b/services/mcp/tests/unit/tool-catalog.test.tsnew file mode 100644index 000000000000..12c51feecd21--- /dev/null+++ b/services/mcp/tests/unit/tool-catalog.test.ts@@ -0,0 +1,191 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { z } from 'zod'++import type { ToolBase, ZodObjectAny } from '@/tools/types'++import { ToolCatalog, type ToolCatalogFilterOptions } from '@/hono/tool-catalog'++function makeToolBase(name: string, overrides?: Partial<ToolBase<ZodObjectAny>>): ToolBase<ZodObjectAny> {+ return {+ name,+ schema: z.object({}),+ handler: vi.fn(),+ ...overrides,+ }+}++const fakeDef = (overrides?: Record<string, unknown>) => ({+ title: 'Title',+ description: 'Desc',+ feature: 'general',+ category: 'general',+ required_scopes: [] as string[],+ annotations: {+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: false,+ readOnlyHint: false,+ },+ ...overrides,+})++vi.mock('@/tools', () => ({+ TOOL_MAP: {+ 'tool-a': () => makeToolBase('tool-a'),+ 'tool-b': () => makeToolBase('tool-b'),+ 'tool-v2-only': () => makeToolBase('tool-v2-only', { mcpVersion: 2 }),+ },+}))++vi.mock('@/tools/generated', () => ({+ GENERATED_TOOL_MAP: {+ 'gen-tool-c': () => makeToolBase('gen-tool-c'),+ },+}))++const DEFINITIONS: Record<string, ReturnType<typeof fakeDef>> = {+ 'tool-a': fakeDef({ required_scopes: ['project:read'] }),+ 'tool-b': fakeDef({ feature: 'insights', annotations: { ...fakeDef().annotations, readOnlyHint: true } }),+ 'gen-tool-c': fakeDef({ required_scopes: ['action:write'] }),+ 'tool-v2-only': fakeDef(),+}++vi.mock('@/tools/toolDefinitions', () => ({+ getToolDefinitions: () => DEFINITIONS,+ getToolDefinition: (name: string) => {+ const def = DEFINITIONS[name]+ if (!def) {+ throw new Error(`Tool definition not found for: ${name}`)+ }+ return def+ },+ getToolsForFeatures: (options?: { features?: string[]; tools?: string[]; version?: number; readOnly?: boolean; aiConsentGiven?: boolean; featureFlags?: Record<string, boolean> }) => {+ let names = Object.keys(DEFINITIONS)+ if (options?.features?.length) {+ names = names.filter((n) => {+ const def = DEFINITIONS[n]+ return def && options.features!.includes(def.feature as string)+ })+ }+ if (options?.readOnly) {+ names = names.filter((n) => {+ const def = DEFINITIONS[n]+ return def?.annotations.readOnlyHint === true+ })+ }+ return names+ },+}))++describe('ToolCatalog', () => {+ let catalog: ToolCatalog++ beforeEach(async () => {+ catalog = new ToolCatalog()+ })++ describe('warmup', () => {+ it('should import tool modules and build the pre-computed map', async () => {+ expect(catalog.warmedUp).toBe(false)+ await catalog.warmup()+ expect(catalog.warmedUp).toBe(true)+ })++ it('should be idempotent', async () => {+ await catalog.warmup()+ await catalog.warmup()+ expect(catalog.warmedUp).toBe(true)+ })+ })++ describe('getFilteredTools', () => {+ beforeEach(async () => {+ await catalog.warmup()+ })++ it('should return all tools when no filters applied', () => {+ const tools = catalog.getFilteredTools({ scopes: ['project:read', 'action:write'] })+ const names = tools.map((t) => t.name).sort()+ expect(names).toEqual(['gen-tool-c', 'tool-a', 'tool-b'])+ })++ it('should exclude tools by name', () => {+ const tools = catalog.getFilteredTools({+ scopes: ['project:read', 'action:write'],+ excludeTools: ['tool-b'],+ })+ const names = tools.map((t) => t.name).sort()+ expect(names).toEqual(['gen-tool-c', 'tool-a'])+ })++ it('should filter by scopes', () => {+ const tools = catalog.getFilteredTools({ scopes: ['project:read'] })+ const names = tools.map((t) => t.name).sort()+ expect(names).toEqual(['tool-a', 'tool-b'])+ })++ it('should exclude tools when scopes are missing', () => {+ const tools = catalog.getFilteredTools({ scopes: [] })+ const names = tools.map((t) => t.name)+ expect(names).toEqual(['tool-b'])+ })++ it('should include v2-only tools when version is 2', () => {+ const tools = catalog.getFilteredTools({+ scopes: ['project:read', 'action:write'],+ version: 2,+ })+ const names = tools.map((t) => t.name).sort()+ expect(names).toEqual(['gen-tool-c', 'tool-a', 'tool-b', 'tool-v2-only'])+ })++ it('should exclude v2-only tools when version is 1', () => {+ const tools = catalog.getFilteredTools({+ scopes: ['project:read', 'action:write'],+ version: 1,+ })+ expect(tools.find((t) => t.name === 'tool-v2-only')).toBeUndefined()+ })++ it('should filter by readOnly when passed through to getToolsForFeatures', () => {+ const tools = catalog.getFilteredTools({+ scopes: ['project:read', 'action:write'],+ readOnly: true,+ })+ const names = tools.map((t) => t.name)+ expect(names).toEqual(['tool-b'])+ })++ it('should filter by features when passed through to getToolsForFeatures', () => {+ const tools = catalog.getFilteredTools({+ scopes: ['project:read'],+ features: ['insights'],+ })+ const names = tools.map((t) => t.name)+ expect(names).toEqual(['tool-b'])+ })++ it('should merge title and description from definitions onto the tool', () => {+ const tools = catalog.getFilteredTools({ scopes: ['project:read'] })+ const toolA = tools.find((t) => t.name === 'tool-a')+ expect(toolA).toBeDefined()+ expect(toolA!.title).toBe('Title')+ expect(toolA!.description).toBe('Desc')+ })++ it('should attach scopes and annotations from definitions', () => {+ const tools = catalog.getFilteredTools({ scopes: ['project:read'] })+ const toolA = tools.find((t) => t.name === 'tool-a')+ expect(toolA!.scopes).toEqual(['project:read'])+ expect(toolA!.annotations).toEqual(+ expect.objectContaining({ readOnlyHint: false })+ )+ })++ it('should return empty array when catalog is not warmed up', () => {+ const coldCatalog = new ToolCatalog()+ const tools = coldCatalog.getFilteredTools({ scopes: [] })+ expect(tools).toEqual([])+ })+ })+})