: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
feat(mcp): cache context-mill skills in redis for hono runtime (#59163)
Georgiy Tarasovb51a9a98001d
diff --git a/services/mcp/src/hono/cache/ContextMillResourceCache.ts b/services/mcp/src/hono/cache/ContextMillResourceCache.tsnew file mode 100644index 000000000000..a6911f36a211--- /dev/null+++ b/services/mcp/src/hono/cache/ContextMillResourceCache.ts@@ -0,0 +1,227 @@+import { createHash, randomUUID } from 'node:crypto'++import { fetchAndExtractEntries } from '@/resources/internals'+import type { ContextMillResource } from '@/resources/manifest-types'++import { contextMillBodyReadsTotal, contextMillCacheEventsTotal } from '../metrics'+import type { RedisLike } from './RedisCache'+import { SharedBlobCache, type SharedBlobCacheOptions } from './SharedBlobCache'++const NAMESPACE = 'context-mill'+const BODY_KEY_PREFIX = `mcp:shared-blob:${NAMESPACE}:body`+const DEFAULT_BODY_TTL_SECONDS = 7 * 24 * 60 * 60+const BODY_SIZE_WARN_BYTES = 256 * 1024++export interface SlimManifestEntry {+ uri: string+ name: string+ mimeType: string+ description: string+}++export interface SlimManifest {+ entries: SlimManifestEntry[]+}++export interface ResourceBody {+ mimeType: string+ text: string+}++export interface ContextMillResourceCacheOptions extends SharedBlobCacheOptions {+ bodyTtlSeconds?: number+ localUrl?: string+}++export type ContextMillCacheResult = 'fresh_hit' | 'stale_hit' | 'cold_refresh' | 'waited' | 'fallback'++export interface ContextMillLoadResult {+ manifest: SlimManifest+ result: ContextMillCacheResult+}++/**+ * Redis-backed cache for the context-mill resource bundle.+ *+ * Splits storage into two layers:+ *+ * - A small slim manifest blob (handled by the base `SharedBlobCache`) that+ * carries `{ entries: [{ uri, name, mimeType, description }] }` — used by+ * `resources/list` and warmup. Cheap to fetch on every cold pod.+ * - One body key per resource (`mcp:shared-blob:context-mill:body:<sha256(uri)>`)+ * that carries the heavy `{ mimeType, text }` payload — fetched lazily only+ * when `resources/read` resolves a URI.+ *+ * Bodies are URI-addressed (no per-publish generation token) so the latest+ * publish always overwrites the same key. The instant a writer pod finishes+ * `writeBodies`, every other pod reading by URI sees the new content — no+ * waiting for individual pods to refresh their in-memory manifest.+ *+ * Resources removed upstream are NOT explicitly deleted: their bodies just+ * stop getting their TTL refreshed and age out naturally. This gives clients+ * holding stale URIs graceful access to the previous content until the body+ * fully expires.+ */+export class ContextMillResourceCache extends SharedBlobCache {+ private readonly bodyTtlSeconds: number+ private readonly localUrl: string | undefined++ constructor(redis: RedisLike, opts: ContextMillResourceCacheOptions = {}) {+ super(redis, `${NAMESPACE}:manifest`, opts)+ this.localUrl = opts.localUrl+ this.bodyTtlSeconds = opts.bodyTtlSeconds ?? DEFAULT_BODY_TTL_SECONDS+ }++ /**+ * Returns the slim manifest. Cold/stale paths load entries inside the+ * SharedBlobCache writer lock, publish every body key, and only then write+ * back the slim manifest.+ */+ async loadOrRefresh(): Promise<ContextMillLoadResult> {+ const { bytes, result } = await this.fetch()+ return {+ manifest: JSON.parse(new TextDecoder().decode(bytes)) as SlimManifest,+ result,+ }+ }++ private async fetch(): Promise<{ bytes: Uint8Array; result: ContextMillCacheResult }> {+ const cached = await this.readCache()++ if (cached && cached.fresh) {+ contextMillCacheEventsTotal.inc({ event: 'fresh_hit' })+ return { bytes: cached.bytes, result: 'fresh_hit' }+ }++ if (cached) {+ // Stale-while-revalidate: serve what we have and try to refresh in+ // the background. The lock guarantees only one instance refreshes+ // even if many requests race here.+ contextMillCacheEventsTotal.inc({ event: 'stale_hit' })+ void this.refreshInBackground()+ return { bytes: cached.bytes, result: 'stale_hit' }+ }++ // Cold cache — race for the writer lock.+ contextMillCacheEventsTotal.inc({ event: 'cold_miss' })+ const token = randomUUID()+ if (await this.acquireLock(token)) {+ contextMillCacheEventsTotal.inc({ event: 'lock_acquired' })+ try {+ const bytes = await this.loadBlob()+ await this.writeCache(bytes)+ return { bytes, result: 'cold_refresh' }+ } finally {+ await this.releaseLock(token)+ }+ }++ // Another writer holds the lock — wait for them to publish.+ contextMillCacheEventsTotal.inc({ event: 'lock_contended' })+ const waited = await this.waitForCache()+ if (waited) {+ contextMillCacheEventsTotal.inc({ event: 'wait_success' })+ return { bytes: waited, result: 'waited' }+ }++ // Writer never published in time. Fetch ourselves without writing so+ // we don't trample whatever the lock holder eventually produces.+ contextMillCacheEventsTotal.inc({ event: 'wait_timeout' })+ return { bytes: await this.loadBlob(), result: 'fallback' }+ }++ private async loadBlob(): Promise<Uint8Array> {+ const entries = await this.loadEntries()+ await this.writeBodies(entries)+ const slim: SlimManifest = {+ entries: entries.map((e) => ({+ uri: e.uri,+ name: e.name,+ mimeType: e.resource.mimeType,+ description: e.resource.description,+ })),+ }+ return new TextEncoder().encode(JSON.stringify(slim))+ }++ protected async loadEntries(): Promise<ContextMillResource[]> {+ return fetchAndExtractEntries(this.localUrl)+ }++ private async refreshInBackground(): Promise<void> {+ const token = randomUUID()+ if (!(await this.acquireLock(token))) {+ contextMillCacheEventsTotal.inc({ event: 'lock_contended' })+ return+ }+ contextMillCacheEventsTotal.inc({ event: 'lock_acquired' })+ try {+ const bytes = await this.loadBlob()+ await this.writeCache(bytes)+ contextMillCacheEventsTotal.inc({ event: 'background_success' })+ } catch (err) {+ contextMillCacheEventsTotal.inc({ event: 'background_error' })+ console.error(`[ContextMillResourceCache:${this.lockKey}] background refresh failed:`, err)+ } finally {+ await this.releaseLock(token)+ }+ }++ /**+ * Invalidate the slim manifest so the next `loadOrRefresh` is treated as+ * cold and fetches upstream. Use from miss-recovery paths — e.g. when a+ * body lookup returns null because Redis evicted it but the manifest is+ * still fresh, plain `loadOrRefresh` would short-circuit.+ */+ async invalidate(): Promise<void> {+ await Promise.all([this.redis.del(this.cacheKey), this.redis.del(this.freshKey)])+ }++ /**+ * Returns the body for `uri` if present in Redis. Returns null only when+ * the body has aged out (TTL elapsed without a republish) or was evicted+ * under memory pressure. Callers should treat null as "trigger refresh+ * and degrade the current request to empty contents."+ */+ async readBody(uri: string): Promise<ResourceBody | null> {+ const raw = await this.redis.get(bodyKey(uri))+ if (raw === null) {+ contextMillBodyReadsTotal.inc({ status: 'miss' })+ return null+ }+ try {+ const body = JSON.parse(raw) as ResourceBody+ contextMillBodyReadsTotal.inc({ status: 'hit' })+ return body+ } catch (err) {+ contextMillBodyReadsTotal.inc({ status: 'parse_error' })+ throw err+ }+ }++ private async writeBodies(entries: readonly ContextMillResource[]): Promise<void> {+ await Promise.all(+ entries.map(async (entry) => {+ const stored: ResourceBody = {+ mimeType: entry.resource.mimeType,+ text: entry.resource.text,+ }+ const serialized = JSON.stringify(stored)+ if (serialized.length > BODY_SIZE_WARN_BYTES) {+ console.warn(+ `[ContextMillResourceCache] body for "${entry.uri}" is ${serialized.length} bytes — approaching Redis bulk-len limits`+ )+ }+ await this.redis.set(bodyKey(entry.uri), serialized, 'EX', this.bodyTtlSeconds)+ })+ )+ }+}++function bodyKey(uri: string): string {+ return `${BODY_KEY_PREFIX}:${sha256(uri)}`+}++function sha256(input: string): string {+ return createHash('sha256').update(input).digest('hex')+}diff --git a/services/mcp/src/hono/cache/SharedBlobCache.ts b/services/mcp/src/hono/cache/SharedBlobCache.tsnew file mode 100644index 000000000000..185ea0a86634--- /dev/null+++ b/services/mcp/src/hono/cache/SharedBlobCache.ts@@ -0,0 +1,111 @@+import type { RedisLike } from './RedisCache'++const DEFAULT_CACHE_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days — hard expiry+const DEFAULT_FRESH_SECONDS = 60 * 10 // 10 minutes — after this, trigger a refresh+const DEFAULT_LOCK_TTL_SECONDS = 60 // writer lock auto-expires+const DEFAULT_WAIT_INTERVAL_MS = 200+const DEFAULT_WAIT_TIMEOUT_MS = 10_000++export interface SharedBlobCacheOptions {+ cacheTtlSeconds?: number+ freshSeconds?: number+ lockTtlSeconds?: number+ waitIntervalMs?: number+ waitTimeoutMs?: number+}++/**+ * Redis-backed helpers for an arbitrary binary blob, shared across instances.+ *+ * - Callers can coordinate single-writer refreshes with the `SET NX EX` lock,+ * wait for another writer to publish on cold cache misses, and read/write+ * the shared bytes plus freshness marker.+ * - Hard TTL keeps the cache available across long writer outages; a separate+ * freshness timestamp lets callers decide when to refresh after the soft+ * window.+ *+ * Each blob lives under a caller-supplied namespace, so one Redis can host+ * many independent shared blobs (e.g. context-mill archive, future bundles)+ * without colliding.+ */+export class SharedBlobCache {+ public readonly cacheKey: string+ public readonly freshKey: string+ public readonly lockKey: string++ private cacheTtlSeconds: number+ private freshSeconds: number+ private lockTtlSeconds: number+ private waitIntervalMs: number+ private waitTimeoutMs: number++ constructor(+ protected readonly redis: RedisLike,+ namespace: string,+ opts: SharedBlobCacheOptions = {}+ ) {+ const prefix = `mcp:shared-blob:${namespace}`+ this.cacheKey = `${prefix}:bytes`+ this.freshKey = `${prefix}:fresh`+ this.lockKey = `${prefix}:lock`++ this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS+ this.freshSeconds = opts.freshSeconds ?? DEFAULT_FRESH_SECONDS+ this.lockTtlSeconds = opts.lockTtlSeconds ?? DEFAULT_LOCK_TTL_SECONDS+ this.waitIntervalMs = opts.waitIntervalMs ?? DEFAULT_WAIT_INTERVAL_MS+ this.waitTimeoutMs = opts.waitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS+ }++ protected async readCache(): Promise<{ bytes: Uint8Array; fresh: boolean } | null> {+ const [raw, freshUntilStr] = await Promise.all([this.redis.get(this.cacheKey), this.redis.get(this.freshKey)])+ if (raw === null) {+ return null+ }+ const buf = Buffer.from(raw, 'base64')+ const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)+ const freshUntil = freshUntilStr !== null ? Number(freshUntilStr) : 0+ const fresh = Number.isFinite(freshUntil) && Date.now() < freshUntil+ return { bytes, fresh }+ }++ protected async writeCache(bytes: Uint8Array): Promise<void> {+ const b64 = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')+ const freshUntil = Date.now() + this.freshSeconds * 1000+ await Promise.all([+ this.redis.set(this.cacheKey, b64, 'EX', this.cacheTtlSeconds),+ this.redis.set(this.freshKey, String(freshUntil), 'EX', this.cacheTtlSeconds),+ ])+ }++ protected async acquireLock(token: string): Promise<boolean> {+ const result = await this.redis.set(this.lockKey, token, 'NX', 'EX', this.lockTtlSeconds)+ return result === 'OK'+ }++ protected async releaseLock(_token: string): Promise<void> {+ // Best-effort. The lock TTL bounds the worst case (another writer's+ // entry being deleted on top); a Lua CAS could close that window but+ // would require widening the RedisLike interface.+ try {+ await this.redis.del(this.lockKey)+ } catch (err) {+ console.error(`[SharedBlobCache:${this.lockKey}] failed to release lock:`, err)+ }+ }++ protected async waitForCache(): Promise<Uint8Array | null> {+ const start = Date.now()+ while (Date.now() - start < this.waitTimeoutMs) {+ await sleep(this.waitIntervalMs)+ const cached = await this.readCache()+ if (cached) {+ return cached.bytes+ }+ }+ return null+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 83882a1c9856..26c66edb9eef 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -17,7 +17,6 @@ import type {PingRequest,ReadResourceRequest,} from '@modelcontextprotocol/sdk/types.js'-import { randomUUID } from 'node:crypto'import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'@@ -114,7 +113,7 @@ class McpDispatcher {constructor(catalog: ToolCatalog, redis: RedisLike) {const env = getEnv()this.catalog = catalog- this.resourceCatalog = new ResourceCatalog(env)+ this.resourceCatalog = new ResourceCatalog(env, redis)this.stateResolver = new RequestStateResolver(catalog, redis, env)this.instructionsBuilder = new InstructionsBuilder(loadGuidelines())this.toolExecutor = new ToolExecutor(catalog, this.instructionsBuilder)@@ -195,7 +194,7 @@ class McpDispatcher {case Method.ResourcesList:return jsonRpcResult(id, this.resourceCatalog.getResourcesList())case Method.ResourcesRead:- return jsonRpcResult(id, this.resourceCatalog.readResource(params))+ return jsonRpcResult(id, await this.resourceCatalog.readResource(params))case Method.PromptsList:return jsonRpcResult(id, this.resourceCatalog.getPromptsList())case Method.PromptsGet:@@ -222,6 +221,7 @@ class McpDispatcher {? requestedVersion: LATEST_PROTOCOL_VERSION+ await this.resourceCatalog.revalidateContextMillResources('initialize')const instructions = await this.instructionsBuilder.build(props, state)initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)diff --git a/services/mcp/src/hono/metrics.ts b/services/mcp/src/hono/metrics.tsindex 9afd502ac968..5893b068e457 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -81,6 +81,36 @@ export const rateLimitErrorsTotal = new Counter({labelNames: ['scope'] as const,})+export const contextMillRevalidationsTotal = new Counter({+ name: 'mcp_context_mill_revalidations_total',+ help: 'Context-mill resource revalidation attempts by caller and result.',+ labelNames: ['source', 'status', 'result'] as const,+})++export const contextMillRevalidationDurationSeconds = new Histogram({+ name: 'mcp_context_mill_revalidation_duration_seconds',+ help: 'Context-mill resource revalidation duration.',+ labelNames: ['source', 'status'] as const,+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30],+})++export const contextMillCacheEventsTotal = new Counter({+ name: 'mcp_context_mill_cache_events_total',+ help: 'Context-mill resource cache events.',+ labelNames: ['event'] as const,+})++export const contextMillManifestEntries = new Gauge({+ name: 'mcp_context_mill_manifest_entries',+ help: 'Latest successfully loaded context-mill slim manifest entry count.',+})++export const contextMillBodyReadsTotal = new Counter({+ name: 'mcp_context_mill_body_reads_total',+ help: 'Context-mill resource body reads by outcome.',+ labelNames: ['status'] as const,+})+export function routeLabel(pathname: string): string {if (pathname === '/mcp' || pathname.startsWith('/mcp/')) {return '/mcp'diff --git a/services/mcp/src/hono/resource-catalog.ts b/services/mcp/src/hono/resource-catalog.tsindex 49cba952ac98..acd5bb6638f2 100644--- a/services/mcp/src/hono/resource-catalog.ts+++ b/services/mcp/src/hono/resource-catalog.ts@@ -9,36 +9,58 @@ import type {TextResourceContents,} from '@modelcontextprotocol/sdk/types.js'-import {- fetchContextMillResources,- filterValidEntries,- loadManifestFromArchive,- clearResourceCache,-} from '@/resources/internals'import { getPromptsFromManifest } from '@/resources'-import { UI_APPS } from '@/resources/ui-apps.generated'import { buildAppStubHtml } from '@/resources/ui-apps'-import type { ContextMillResource } from '@/resources/manifest-types'+import { UI_APPS } from '@/resources/ui-apps.generated'import type { Env } from '@/tools/types'+import {+ ContextMillResourceCache,+ type ContextMillCacheResult,+ type SlimManifestEntry,+} from './cache/ContextMillResourceCache'+import type { RedisLike } from './cache/RedisCache'+import {+ contextMillManifestEntries,+ contextMillRevalidationDurationSeconds,+ contextMillRevalidationsTotal,+} from './metrics'++export type ContextMillRevalidationSource = 'warmup' | 'initialize'+export class ResourceCatalog {private readonly env: Env+ private readonly contextMillCache: ContextMillResourceCacheprivate resources: Resource[] = []- private resourcesByUri = new Map<string, TextResourceContents>()private prompts: Prompt[] = []private promptsByName = new Map<string, GetPromptResult>()private uiAppResources: Resource[] = []private uiAppReadEntries = new Map<string, TextResourceContents>()private allResources: Resource[] = []- private contextMillData: readonly ContextMillResource[] = []+ private contextMillEntriesByUri = new Map<string, SlimManifestEntry>()- constructor(env: Env) {+ constructor(env: Env, redis: RedisLike) {this.env = env+ const localUrl = this.contextMillLocalUrl()+ this.contextMillCache = new ContextMillResourceCache(redis, localUrl ? { localUrl } : {})+ }++ get contextMillEntries(): readonly SlimManifestEntry[] {+ return Array.from(this.contextMillEntriesByUri.values())}- get contextMillEntries(): readonly ContextMillResource[] {- return this.contextMillData+ async revalidateContextMillResources(source: ContextMillRevalidationSource): Promise<void> {+ const stop = contextMillRevalidationDurationSeconds.startTimer({ source })+ try {+ const result = await this.refreshContextMill()+ contextMillRevalidationsTotal.inc({ source, status: 'success', result })+ stop({ source, status: 'success' })+ } catch (error) {+ contextMillRevalidationsTotal.inc({ source, status: 'error', result: 'error' })+ stop({ source, status: 'error' })+ console.error('[ResourceCatalog] Failed to revalidate context-mill resources:', error)+ }}async warmup(): Promise<void> {@@ -50,19 +72,40 @@ export class ResourceCatalog {return { resources: this.allResources }}- readResource(params: Record<string, unknown> | undefined): ReadResourceResult {+ async readResource(params: Record<string, unknown> | undefined): Promise<ReadResourceResult> {const uri = (params?.uri as string) ?? ''- const entry = this.resourcesByUri.get(uri) ?? this.uiAppReadEntries.get(uri)- if (!entry) {+ const uiEntry = this.uiAppReadEntries.get(uri)+ if (uiEntry) {+ return {+ contents: [+ {+ uri: uiEntry.uri,+ mimeType: uiEntry.mimeType,+ text: uiEntry.text,+ ...(uiEntry._meta ? { _meta: uiEntry._meta } : {}),+ },+ ],+ }+ }++ const slimEntry = this.contextMillEntriesByUri.get(uri)+ if (!slimEntry) {+ return { contents: [] }+ }+ const body = await this.contextMillCache.readBody(uri)+ if (!body) {+ // Body has aged out (resource removed upstream + TTL elapsed) or+ // was evicted. Ack the removal and let the slim manifest catch up+ // on the next natural refresh; the client's context window has+ // already cached what it needs from the prior resources/list.return { contents: [] }}return {contents: [{- uri: entry.uri,- mimeType: entry.mimeType,- text: entry.text,- ...(entry._meta ? { _meta: entry._meta } : {}),+ uri: slimEntry.uri,+ mimeType: body.mimeType,+ text: body.text,},],}@@ -81,29 +124,34 @@ export class ResourceCatalog {return { messages: entry.messages }}- private async warmupResources(): Promise<void> {- try {- const archive = await fetchContextMillResources()- const manifest = loadManifestFromArchive(archive)- this.contextMillData = filterValidEntries(manifest.resources, archive)- clearResourceCache()-- for (const entry of this.contextMillEntries) {- this.resources.push({- name: entry.name,- uri: entry.uri,- mimeType: entry.resource.mimeType,- description: entry.resource.description,- })- this.resourcesByUri.set(entry.uri, {- uri: entry.uri,- mimeType: entry.resource.mimeType,- text: entry.resource.text,- })- }- } catch (error) {- console.error('[ResourceCatalog] Failed to pre-load context-mill resources:', error)+ private async refreshContextMill(): Promise<ContextMillCacheResult> {+ const { manifest: slim, result } = await this.contextMillCache.loadOrRefresh()++ const nextEntriesByUri = new Map<string, SlimManifestEntry>()+ const nextResources: Resource[] = []+ for (const entry of slim.entries) {+ nextEntriesByUri.set(entry.uri, entry)+ nextResources.push({+ name: entry.name,+ uri: entry.uri,+ mimeType: entry.mimeType,+ description: entry.description,+ })}+ this.contextMillEntriesByUri = nextEntriesByUri+ this.resources = nextResources+ this.allResources = [...this.resources, ...this.uiAppResources]+ contextMillManifestEntries.set(slim.entries.length)+ return result+ }++ private contextMillLocalUrl(): string | undefined {+ const localUrlRaw = (this.env as Record<string, string | undefined>)?.POSTHOG_MCP_LOCAL_SKILLS_URL+ return localUrlRaw && localUrlRaw.trim() !== '' ? localUrlRaw : undefined+ }++ private async warmupResources(): Promise<void> {+ await this.revalidateContextMillResources('warmup')try {const manifestPrompts = await getPromptsFromManifest()diff --git a/services/mcp/src/resources/internals.ts b/services/mcp/src/resources/internals.tsindex bf744f42f17d..e0dcbdc6768c 100644--- a/services/mcp/src/resources/internals.ts+++ b/services/mcp/src/resources/internals.ts@@ -1,27 +1,43 @@import { type Unzipped, strFromU8, unzipSync } from 'fflate'-import type { ContextMillManifest, ContextMillResource } from './manifest-types'import { loadContextMillManifest } from './manifest-loader'+import type { ContextMillManifest, ContextMillResource } from './manifest-types'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> {+export type ArchiveLoader = (url: string) => Promise<Uint8Array>++async function defaultArchiveLoader(url: string, noStore: boolean): Promise<Uint8Array> {+ const response = await fetch(url, noStore ? { cache: 'no-store' } : {})+ if (!response.ok) {+ throw new Error(`Failed to fetch context-mill resources from ${url}: ${response.statusText}`)+ }+ const arrayBuffer = await response.arrayBuffer()+ return new Uint8Array(arrayBuffer)+}++/**+ * Fetches and caches the context-mill resources ZIP.+ *+ * When `archiveLoader` is provided (hono runtime), the upstream fetch is+ * delegated to it so multiple instances share a Redis-backed cache with+ * single-writer coordination. The in-memory `cachedResources` still acts+ * as a per-process fast path on top of that layer.+ *+ * `localUrl` (`POSTHOG_MCP_LOCAL_SKILLS_URL`) always bypasses both caches.+ */+export async function fetchContextMillResources(localUrl?: string, archiveLoader?: ArchiveLoader): Promise<Unzipped> {const url = localUrl || CONTEXT_MILL_URLif (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)+ const bytes =+ !localUrl && archiveLoader ? await archiveLoader(url) : await defaultArchiveLoader(url, Boolean(localUrl))+ const unzipped = unzipSync(bytes)if (!localUrl) {cachedResources = unzipped@@ -52,3 +68,17 @@ export function filterValidEntries(entries: readonly ContextMillResource[], archexport function clearResourceCache(): void {cachedResources = null}++/**+ * Fetch + unzip + parse the context-mill manifest, returning the filtered+ * entries. Does not touch the module-level `cachedResources`; used by the+ * hono runtime to push entries into a Redis-sharded cache without retaining+ * the archive in process memory.+ */+export async function fetchAndExtractEntries(localUrl?: string): Promise<ContextMillResource[]> {+ const url = localUrl || CONTEXT_MILL_URL+ const bytes = await defaultArchiveLoader(url, Boolean(localUrl))+ const archive = unzipSync(bytes)+ const manifest = loadManifestFromArchive(archive)+ return filterValidEntries(manifest.resources, archive)+}diff --git a/services/mcp/tests/hono/context-mill-resource-cache.test.ts b/services/mcp/tests/hono/context-mill-resource-cache.test.tsnew file mode 100644index 000000000000..8b500f8cc37f--- /dev/null+++ b/services/mcp/tests/hono/context-mill-resource-cache.test.ts@@ -0,0 +1,343 @@+import { createHash } from 'node:crypto'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { mockBodyReadsInc, mockCacheEventsInc } = vi.hoisted(() => ({+ mockBodyReadsInc: vi.fn(),+ mockCacheEventsInc: vi.fn(),+}))++vi.mock('@/hono/metrics', () => ({+ contextMillBodyReadsTotal: { inc: mockBodyReadsInc },+ contextMillCacheEventsTotal: { inc: mockCacheEventsInc },+}))++import { ContextMillResourceCache, type ContextMillResourceCacheOptions } from '@/hono/cache/ContextMillResourceCache'+import type { RedisLike } from '@/hono/cache/RedisCache'+import type { ContextMillResource } from '@/resources/manifest-types'++import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'++type EntryLoader = () => Promise<ContextMillResource[]>++class TestContextMillResourceCache extends ContextMillResourceCache {+ constructor(+ redis: RedisLike,+ private loader: EntryLoader,+ opts?: ContextMillResourceCacheOptions+ ) {+ super(redis, opts)+ }++ setLoader(loader: EntryLoader): void {+ this.loader = loader+ }++ protected override loadEntries(): Promise<ContextMillResource[]> {+ return this.loader()+ }+}++interface MockRedis extends RedisLike {+ _store: Map<string, string>+ _setCalls: string[]+}++function createMockRedis(): MockRedis {+ const store = new Map<string, string>()+ const setCalls: string[] = []+ return {+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string, ...args: (string | number)[]) => {+ setCalls.push(key)+ const isNx = args.includes('NX')+ if (isNx && store.has(key)) {+ return null+ }+ store.set(key, value)+ return 'OK'+ }),+ del: vi.fn(async (...keys: string[]) => {+ let count = 0+ for (const k of keys) {+ if (store.delete(k)) {+ count+++ }+ }+ return count+ }),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ ...makeRedisRateLimitStubs(),+ _store: store,+ _setCalls: setCalls,+ }+}++const MANIFEST_BYTES_KEY = 'mcp:shared-blob:context-mill:manifest:bytes'+const MANIFEST_FRESH_KEY = 'mcp:shared-blob:context-mill:manifest:fresh'+const MANIFEST_LOCK_KEY = 'mcp:shared-blob:context-mill:manifest:lock'++function bodyKey(uri: string): string {+ const hash = createHash('sha256').update(uri).digest('hex')+ return `mcp:shared-blob:context-mill:body:${hash}`+}++function makeEntry(suffix: string, text?: string): ContextMillResource {+ return {+ id: `entry-${suffix}`,+ name: `name-${suffix}`,+ uri: `posthog://skill/${suffix}`,+ resource: {+ mimeType: 'text/markdown',+ description: `desc-${suffix}`,+ text: text ?? `# body ${suffix}`,+ },+ }+}++describe('ContextMillResourceCache', () => {+ let redis: MockRedis++ beforeEach(() => {+ mockBodyReadsInc.mockClear()+ mockCacheEventsInc.mockClear()+ redis = createMockRedis()+ })++ it('writes every body before publishing the slim manifest on cold load', async () => {+ const entries = [makeEntry('a'), makeEntry('b'), makeEntry('c')]+ const upstream = vi.fn(async () => entries)+ const cache = new TestContextMillResourceCache(redis, upstream)++ const { manifest: slim, result } = await cache.loadOrRefresh()++ expect(upstream).toHaveBeenCalledTimes(1)+ expect(result).toBe('cold_refresh')+ expect(slim.entries).toHaveLength(3)+ // Manifest exposes slim metadata only (no text).+ expect(slim.entries.map((e) => e.uri).sort()).toEqual(entries.map((e) => e.uri).sort())+ expect(slim.entries[0]).not.toHaveProperty('text')++ // Body keys must land before the manifest bytes key in Redis writes.+ const manifestIdx = redis._setCalls.indexOf(MANIFEST_BYTES_KEY)+ expect(manifestIdx).toBeGreaterThan(-1)+ for (const e of entries) {+ const bodyIdx = redis._setCalls.indexOf(bodyKey(e.uri))+ expect(bodyIdx).toBeGreaterThan(-1)+ expect(bodyIdx).toBeLessThan(manifestIdx)+ }+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'cold_miss' })+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'lock_acquired' })+ })++ it('serves manifest from cache on warm hit without calling upstream', async () => {+ const entries = [makeEntry('a')]+ const cache = new TestContextMillResourceCache(redis, async () => entries)+ await cache.loadOrRefresh()++ const upstream = vi.fn(async () => [makeEntry('z')])+ cache.setLoader(upstream)+ const { manifest: slim, result } = await cache.loadOrRefresh()++ expect(upstream).not.toHaveBeenCalled()+ expect(result).toBe('fresh_hit')+ expect(slim.entries[0]!.uri).toBe(entries[0]!.uri)+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'fresh_hit' })+ })++ it('reads a body by uri', async () => {+ const entry = makeEntry('a')+ const cache = new TestContextMillResourceCache(redis, async () => [entry])+ await cache.loadOrRefresh()++ const body = await cache.readBody(entry.uri)+ expect(body).toEqual({ mimeType: 'text/markdown', text: '# body a' })+ expect(mockBodyReadsInc).toHaveBeenCalledWith({ status: 'hit' })+ })++ it('returns null when the body is missing entirely', async () => {+ const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('a')])+ await cache.loadOrRefresh()++ const body = await cache.readBody('posthog://skill/never-published')+ expect(body).toBeNull()+ expect(mockBodyReadsInc).toHaveBeenCalledWith({ status: 'miss' })+ })++ it('records parse errors when a body is corrupt', async () => {+ const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('a')])+ await cache.loadOrRefresh()+ redis._store.set(bodyKey('posthog://skill/a'), '{')++ await expect(cache.readBody('posthog://skill/a')).rejects.toThrow()++ expect(mockBodyReadsInc).toHaveBeenCalledWith({ status: 'parse_error' })+ })++ it('overwrites bodies in place so the latest publish is served immediately', async () => {+ const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('a', 'old content')])++ await cache.loadOrRefresh()+ const beforeRefresh = await cache.readBody('posthog://skill/a')+ expect(beforeRefresh!.text).toBe('old content')++ // Second publish for the same URI with new content. With URI-keyed+ // bodies, the new value lands at the same Redis key — readers see+ // the update on the next GET, no gen check or in-memory refresh+ // required. Invalidate first so the publish actually runs upstream+ // (otherwise ContextMillResourceCache short-circuits on a fresh manifest).+ await cache.invalidate()+ cache.setLoader(async () => [makeEntry('a', 'new content')])+ await cache.loadOrRefresh()+ const afterRefresh = await cache.readBody('posthog://skill/a')+ expect(afterRefresh!.text).toBe('new content')+ })++ it('leaves removed-upstream bodies in place to age out via TTL', async () => {+ const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('keeper'), makeEntry('removed')])++ await cache.loadOrRefresh()++ const removedBodyKey = bodyKey('posthog://skill/removed')+ expect(redis._store.has(removedBodyKey)).toBe(true)++ // Second publish drops one entry. We should NOT delete the removed+ // body — clients holding the old URI can still resolve it until the+ // TTL expires naturally.+ await cache.invalidate()+ cache.setLoader(async () => [makeEntry('keeper')])+ await cache.loadOrRefresh()++ expect(redis._store.has(removedBodyKey)).toBe(true)+ const orphanedBody = await cache.readBody('posthog://skill/removed')+ expect(orphanedBody).not.toBeNull()+ })++ it('only one writer fetches upstream when many callers race on cold cache', async () => {+ const entries = [makeEntry('a')]+ let inFlight = 0+ let peak = 0+ const upstream = vi.fn(async () => {+ inFlight += 1+ peak = Math.max(peak, inFlight)+ await new Promise((r) => setTimeout(r, 20))+ inFlight -= 1+ return entries+ })+ const cache = new TestContextMillResourceCache(redis, upstream, { waitIntervalMs: 5, waitTimeoutMs: 200 })++ const concurrency = 5+ const results = await Promise.all(Array.from({ length: concurrency }, () => cache.loadOrRefresh()))++ expect(peak).toBe(1)+ expect(upstream).toHaveBeenCalledTimes(1)+ // Every caller observes the published slim manifest.+ expect(results.every((r) => r.manifest.entries[0]!.uri === entries[0]!.uri)).toBe(true)+ expect(results.some((r) => r.result === 'waited')).toBe(true)+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'lock_contended' })+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'wait_success' })+ })++ it('non-writers wait for the lock holder to publish and serve that result', async () => {+ const entries = [makeEntry('waited')]+ let resolveUpstream: ((entries: ContextMillResource[]) => void) | undefined+ const upstreamPromise = new Promise<ContextMillResource[]>((resolve) => {+ resolveUpstream = resolve+ })+ const upstream = vi.fn(() => upstreamPromise)+ const cache = new TestContextMillResourceCache(redis, upstream, {+ waitIntervalMs: 5,+ waitTimeoutMs: 1000,+ })++ // First call wins the lock and stalls in upstream.+ const writerResult = cache.loadOrRefresh()+ // Give the writer time to seize the lock before the waiter starts.+ await new Promise((r) => setTimeout(r, 10))+ const waiterResult = cache.loadOrRefresh()++ // Publish the upstream after both calls are in flight.+ await new Promise((r) => setTimeout(r, 30))+ resolveUpstream!(entries)++ const [writerResultPayload, waiterResultPayload] = await Promise.all([writerResult, waiterResult])+ expect(writerResultPayload.manifest.entries[0]!.uri).toBe(entries[0]!.uri)+ expect(waiterResultPayload.manifest.entries[0]!.uri).toBe(entries[0]!.uri)+ expect(writerResultPayload.result).toBe('cold_refresh')+ expect(waiterResultPayload.result).toBe('waited')+ expect(upstream).toHaveBeenCalledTimes(1)+ })++ it('serves stale manifest and triggers a background republish', async () => {+ const initial = [makeEntry('a')]+ const refreshed = [makeEntry('a'), makeEntry('b')]+ let call = 0+ const upstream = vi.fn(async () => {+ call += 1+ return call === 1 ? initial : refreshed+ })+ const cache = new TestContextMillResourceCache(redis, upstream, {+ freshSeconds: 0,+ waitIntervalMs: 5,+ waitTimeoutMs: 100,+ })++ const first = await cache.loadOrRefresh()+ expect(first.manifest.entries).toHaveLength(1)++ // Stale read returns the cached manifest and kicks off a background refresh.+ const second = await cache.loadOrRefresh()+ expect(second.manifest.entries).toHaveLength(1)+ expect(second.result).toBe('stale_hit')++ // Allow the background refresh to settle.+ await new Promise((r) => setTimeout(r, 30))+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'background_success' })++ const third = await cache.loadOrRefresh()+ expect(third.manifest.entries).toHaveLength(2)+ })++ it('records background refresh errors', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('a')], {+ freshSeconds: 0,+ waitIntervalMs: 5,+ waitTimeoutMs: 100,+ })+ await cache.loadOrRefresh()+ cache.setLoader(async () => {+ throw new Error('refresh failed')+ })++ await cache.loadOrRefresh()+ await new Promise((r) => setTimeout(r, 30))++ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'background_error' })+ } finally {+ consoleError.mockRestore()+ }+ })++ it('falls back to a direct load when the writer never publishes', async () => {+ redis._store.set(MANIFEST_LOCK_KEY, 'someone-else')+ const entries = [makeEntry('fallback')]+ const upstream = vi.fn(async () => entries)+ const cache = new TestContextMillResourceCache(redis, upstream, { waitIntervalMs: 10, waitTimeoutMs: 50 })++ const { manifest: slim, result } = await cache.loadOrRefresh()++ expect(slim.entries[0]!.uri).toBe(entries[0]!.uri)+ expect(result).toBe('fallback')+ expect(upstream).toHaveBeenCalledTimes(1)+ expect(redis._store.has(MANIFEST_BYTES_KEY)).toBe(false)+ expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'wait_timeout' })+ })++ it('does not leave the manifest lock held after a successful publish', async () => {+ const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('a')])+ await cache.loadOrRefresh()+ expect(redis._store.has(MANIFEST_LOCK_KEY)).toBe(false)+ expect(redis._store.has(MANIFEST_FRESH_KEY)).toBe(true)+ })+})diff --git a/services/mcp/tests/hono/dispatcher-init-revalidation.test.ts b/services/mcp/tests/hono/dispatcher-init-revalidation.test.tsnew file mode 100644index 000000000000..a6dd09ee8638--- /dev/null+++ b/services/mcp/tests/hono/dispatcher-init-revalidation.test.ts@@ -0,0 +1,146 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const {+ mockBuildInstructions,+ mockInitDurationObserve,+ mockInitTotalInc,+ mockRevalidateContextMillResources,+ mockResolveState,+ mockTrackInitEvent,+} = vi.hoisted(() => ({+ mockBuildInstructions: vi.fn(),+ mockInitDurationObserve: vi.fn(),+ mockInitTotalInc: vi.fn(),+ mockRevalidateContextMillResources: vi.fn(),+ mockResolveState: vi.fn(),+ mockTrackInitEvent: vi.fn(),+}))++vi.mock('@/hono/analytics', () => ({+ trackInitEvent: mockTrackInitEvent,+}))++vi.mock('@/hono/instructions', () => ({+ InstructionsBuilder: vi.fn().mockImplementation(() => ({+ build: mockBuildInstructions,+ })),+}))++vi.mock('@/hono/metrics', () => ({+ initDurationSeconds: { observe: mockInitDurationObserve },+ initTotal: { inc: mockInitTotalInc },+}))++vi.mock('@/hono/request-state-resolver', () => ({+ RequestStateResolver: vi.fn().mockImplementation(() => ({+ resolve: mockResolveState,+ })),+}))++vi.mock('@/hono/resource-catalog', () => ({+ ResourceCatalog: vi.fn().mockImplementation(() => ({+ getPrompt: vi.fn(() => ({ messages: [] })),+ getPromptsList: vi.fn(() => ({ prompts: [] })),+ getResourcesList: vi.fn(() => ({ resources: [] })),+ readResource: vi.fn(async () => ({ contents: [] })),+ revalidateContextMillResources: mockRevalidateContextMillResources,+ warmup: vi.fn(async () => {}),+ })),+}))++import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/sdk/types.js'++import type { RedisLike } from '@/hono/cache/RedisCache'+import { McpDispatcher } from '@/hono/dispatcher'+import type { RequestProperties } from '@/lib/request-properties'++import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'++function createMockRedis(): RedisLike {+ const store = new Map<string, string>()+ return {+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string) => {+ store.set(key, value)+ return 'OK'+ }),+ del: vi.fn(async (...keys: string[]) => {+ let count = 0+ for (const key of keys) {+ if (store.delete(key)) {+ count+++ }+ }+ return count+ }),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ ...makeRedisRateLimitStubs(),+ }+}++function makeProps(): RequestProperties {+ return {+ apiToken: 'phx_test',+ mcpClientName: 'test-client',+ mcpClientVersion: '1.0.0',+ mcpProtocolVersion: LATEST_PROTOCOL_VERSION,+ requestStartTime: Date.now(),+ transport: 'streamable-http',+ userHash: 'test-user',+ }+}++function makeInitializeRequest(): Request {+ return new Request('https://mcp.test/mcp', {+ body: JSON.stringify({+ id: 1,+ jsonrpc: '2.0',+ method: 'initialize',+ params: {+ capabilities: {},+ clientInfo: { name: 'test-client', version: '1.0.0' },+ protocolVersion: LATEST_PROTOCOL_VERSION,+ },+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ })+}++describe('McpDispatcher initialize resource revalidation', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockBuildInstructions.mockResolvedValue('')+ mockResolveState.mockResolvedValue({ distinctId: 'test-distinct-id' })+ mockTrackInitEvent.mockResolvedValue(undefined)+ mockRevalidateContextMillResources.mockResolvedValue(undefined)+ })++ it('awaits context-mill resource revalidation before returning initialize', async () => {+ let resolveRevalidation: (() => void) | undefined+ const revalidationPromise = new Promise<void>((resolve) => {+ resolveRevalidation = resolve+ })+ mockRevalidateContextMillResources.mockReturnValueOnce(revalidationPromise)++ const dispatcher = new McpDispatcher({} as any, createMockRedis())+ const responsePromise = dispatcher.handleRequest(makeInitializeRequest(), makeProps())+ let responseSettled = false+ void responsePromise.then(() => {+ responseSettled = true+ })++ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(mockRevalidateContextMillResources).toHaveBeenCalledWith('initialize')+ expect(responseSettled).toBe(false)++ resolveRevalidation!()+ const response = await responsePromise+ const body = (await response.json()) as any++ expect(response.status).toBe(200)+ expect(body.result.protocolVersion).toBe(LATEST_PROTOCOL_VERSION)+ expect(mockBuildInstructions).toHaveBeenCalled()+ })+})diff --git a/services/mcp/tests/hono/resource-catalog.test.ts b/services/mcp/tests/hono/resource-catalog.test.tsindex 2a57e02bb2f7..074bfb60a474 100644--- a/services/mcp/tests/hono/resource-catalog.test.ts+++ b/services/mcp/tests/hono/resource-catalog.test.ts@@ -1,10 +1,34 @@import { beforeEach, describe, expect, it, vi } from 'vitest'+const {+ mockBodyReadsInc,+ mockCacheEventsInc,+ mockManifestEntriesSet,+ mockRevalidationDurationStartTimer,+ mockRevalidationDurationStop,+ mockRevalidationsInc,+} = vi.hoisted(() => {+ const stop = vi.fn()+ return {+ mockBodyReadsInc: vi.fn(),+ mockCacheEventsInc: vi.fn(),+ mockManifestEntriesSet: vi.fn(),+ mockRevalidationDurationStartTimer: vi.fn(() => stop),+ mockRevalidationDurationStop: stop,+ mockRevalidationsInc: vi.fn(),+ }+})++vi.mock('@/hono/metrics', () => ({+ contextMillBodyReadsTotal: { inc: mockBodyReadsInc },+ contextMillCacheEventsTotal: { inc: mockCacheEventsInc },+ contextMillManifestEntries: { set: mockManifestEntriesSet },+ contextMillRevalidationDurationSeconds: { startTimer: mockRevalidationDurationStartTimer },+ contextMillRevalidationsTotal: { inc: mockRevalidationsInc },+}))+vi.mock('@/resources/internals', () => ({- fetchContextMillResources: vi.fn(),- filterValidEntries: vi.fn(),- loadManifestFromArchive: vi.fn(),- clearResourceCache: vi.fn(),+ fetchAndExtractEntries: vi.fn(),}))vi.mock('@/resources', () => ({@@ -14,44 +38,78 @@ vi.mock('@/resources', () => ({vi.mock('@/resources/ui-apps.generated', async (importOriginal) => importOriginal())vi.mock('@/resources/ui-apps', async (importOriginal) => importOriginal())-import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive } from '@/resources/internals'-import { getPromptsFromManifest } from '@/resources'+import type { RedisLike } from '@/hono/cache/RedisCache'import { ResourceCatalog } from '@/hono/resource-catalog'+import { getPromptsFromManifest } from '@/resources'+import { fetchAndExtractEntries } from '@/resources/internals'+import type { ContextMillResource } from '@/resources/manifest-types'++import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'const mockEnv = {MCP_APPS_BASE_URL: 'https://apps.test',POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,} as any-function makeContextMillEntry(- name: string,- uri: string-): { name: string; uri: string; resource: { mimeType: string; description: string; text: string } } {+interface MockRedis extends RedisLike {+ _store: Map<string, string>+}++function createMockRedis(): MockRedis {+ const store = new Map<string, string>()return {- name,- uri,+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string, ...args: (string | number)[]) => {+ const isNx = args.includes('NX')+ if (isNx && store.has(key)) {+ return null+ }+ store.set(key, value)+ return 'OK'+ }),+ del: vi.fn(async (...keys: string[]) => {+ let count = 0+ for (const k of keys) {+ if (store.delete(k)) {+ count+++ }+ }+ return count+ }),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ ...makeRedisRateLimitStubs(),+ _store: store,+ }+}++function makeEntry(suffix: string): ContextMillResource {+ return {+ id: `id-${suffix}`,+ name: `name-${suffix}`,+ uri: `posthog://${suffix}`,resource: {mimeType: 'text/plain',- description: `${name} desc`,- text: `content of ${name}`,+ description: `${suffix} desc`,+ text: `content of ${suffix}`,},}}+const MANIFEST_BYTES_KEY = 'mcp:shared-blob:context-mill:manifest:bytes'+const MANIFEST_FRESH_KEY = 'mcp:shared-blob:context-mill:manifest:fresh'+describe('ResourceCatalog', () => {+ let redis: MockRedis+beforeEach(() => {vi.clearAllMocks()+ mockRevalidationDurationStop.mockClear()+ redis = createMockRedis()})describe('warmup and resource listing', () => {- it('serves resources and prompts after warmup', async () => {- const entries = [- makeContextMillEntry('guide', 'posthog://guide'),- makeContextMillEntry('faq', 'posthog://faq'),- ]- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue(entries as any)+ it('serves slim metadata for context-mill resources after warmup', async () => {+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([makeEntry('guide'), makeEntry('faq')])vi.mocked(getPromptsFromManifest).mockResolvedValue([{name: 'greet',@@ -61,67 +119,152 @@ describe('ResourceCatalog', () => {},] as any)- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()const { resources } = catalog.getResourcesList()- expect(resources.map((r) => r.name)).toContain('guide')- expect(resources.map((r) => r.name)).toContain('faq')+ const names = resources.map((r) => r.name)+ expect(names).toContain('name-guide')+ expect(names).toContain('name-faq')+ // List endpoint must not carry body text.+ expect(resources.every((r) => !('text' in r))).toBe(true)const { prompts } = catalog.getPromptsList()expect(prompts).toHaveLength(1)expect(prompts[0]!.name).toBe('greet')+ expect(mockRevalidationsInc).toHaveBeenCalledWith({+ source: 'warmup',+ status: 'success',+ result: 'cold_refresh',+ })+ expect(mockRevalidationDurationStartTimer).toHaveBeenCalledWith({ source: 'warmup' })+ expect(mockRevalidationDurationStop).toHaveBeenCalledWith({ source: 'warmup', status: 'success' })+ expect(mockManifestEntriesSet).toHaveBeenCalledWith(2)})it('pre-merges resource list so getResourcesList returns a stable array', async () => {- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue([makeContextMillEntry('a', 'posthog://a')] as any)+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([makeEntry('a')])vi.mocked(getPromptsFromManifest).mockResolvedValue([])- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()const list1 = catalog.getResourcesList().resourcesconst list2 = catalog.getResourcesList().resourcesexpect(list1).toBe(list2)})++ it('revalidates context-mill resources on demand', async () => {+ vi.mocked(fetchAndExtractEntries).mockResolvedValueOnce([makeEntry('old')])+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])++ const catalog = new ResourceCatalog(mockEnv, redis)+ await catalog.warmup()++ redis._store.delete(MANIFEST_BYTES_KEY)+ redis._store.delete(MANIFEST_FRESH_KEY)+ vi.mocked(fetchAndExtractEntries).mockResolvedValueOnce([makeEntry('new')])++ await catalog.revalidateContextMillResources('initialize')++ const names = catalog.getResourcesList().resources.map((r) => r.name)+ expect(names).toContain('name-new')+ expect(names).not.toContain('name-old')+ expect(mockRevalidationsInc).toHaveBeenCalledWith({+ source: 'initialize',+ status: 'success',+ result: 'cold_refresh',+ })+ })++ it('keeps existing context-mill resources when revalidation fails', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ vi.mocked(fetchAndExtractEntries).mockResolvedValueOnce([makeEntry('stable')])+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])++ const catalog = new ResourceCatalog(mockEnv, redis)+ await catalog.warmup()++ redis._store.delete(MANIFEST_BYTES_KEY)+ redis._store.delete(MANIFEST_FRESH_KEY)+ vi.mocked(fetchAndExtractEntries).mockRejectedValueOnce(new Error('network'))++ await catalog.revalidateContextMillResources('initialize')++ expect(catalog.getResourcesList().resources.map((r) => r.name)).toContain('name-stable')+ expect(mockRevalidationsInc).toHaveBeenCalledWith({+ source: 'initialize',+ status: 'error',+ result: 'error',+ })+ expect(mockRevalidationDurationStop).toHaveBeenCalledWith({ source: 'initialize', status: 'error' })+ expect(consoleError).toHaveBeenCalledWith(+ '[ResourceCatalog] Failed to revalidate context-mill resources:',+ expect.any(Error)+ )+ } finally {+ consoleError.mockRestore()+ }+ })})describe('readResource', () => {- it('returns contents for a known URI', async () => {- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue([makeContextMillEntry('doc', 'posthog://doc')] as any)+ it('lazy-loads a context-mill body from Redis on first read', async () => {+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([makeEntry('doc')])vi.mocked(getPromptsFromManifest).mockResolvedValue([])- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- const result = catalog.readResource({ uri: 'posthog://doc' }) as any+ const result = await catalog.readResource({ uri: 'posthog://doc' })expect(result.contents).toHaveLength(1)- expect(result.contents[0].text).toBe('content of doc')+ const content = result.contents[0]! as { uri: string; text: string; mimeType: string }+ expect(content.text).toBe('content of doc')+ expect(content.uri).toBe('posthog://doc')})it('returns empty contents for unknown URI', async () => {- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue([])+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([])vi.mocked(getPromptsFromManifest).mockResolvedValue([])- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- const result = catalog.readResource({ uri: 'posthog://nonexistent' }) as any+ const result = await catalog.readResource({ uri: 'posthog://nonexistent' })expect(result.contents).toEqual([])})++ it('returns empty contents when a body has aged out without triggering a refresh', async () => {+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([makeEntry('doc')])+ vi.mocked(getPromptsFromManifest).mockResolvedValue([])++ const catalog = new ResourceCatalog(mockEnv, redis)+ await catalog.warmup()++ // Drop the body key. The read should acknowledge the removal —+ // the resource has aged out — without triggering any upstream+ // refresh. The slim manifest is left in place; the LLM client's+ // context-window cache is the source of truth for what it knows.+ for (const key of Array.from(redis._store.keys())) {+ if (key.startsWith('mcp:shared-blob:context-mill:body:')) {+ redis._store.delete(key)+ }+ }+ vi.mocked(fetchAndExtractEntries).mockClear()++ const result = await catalog.readResource({ uri: 'posthog://doc' })+ expect(result.contents).toEqual([])++ // No refresh fired on the miss path.+ await new Promise((r) => setTimeout(r, 20))+ expect(vi.mocked(fetchAndExtractEntries)).not.toHaveBeenCalled()+ })})describe('getPrompt', () => {it('returns messages for a known prompt name', async () => {- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue([])+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([])vi.mocked(getPromptsFromManifest).mockResolvedValue([{name: 'test-prompt',@@ -131,52 +274,48 @@ describe('ResourceCatalog', () => {},] as any)- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- const result = catalog.getPrompt({ name: 'test-prompt' }) as any+ const result = catalog.getPrompt({ name: 'test-prompt' })expect(result.messages).toHaveLength(1)})it('returns empty messages for unknown prompt', async () => {- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue([])+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([])vi.mocked(getPromptsFromManifest).mockResolvedValue([])- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- const result = catalog.getPrompt({ name: 'nope' }) as any+ const result = catalog.getPrompt({ name: 'nope' })expect(result.messages).toEqual([])})})describe('error resilience', () => {it('continues serving prompts when resource fetch fails', async () => {- vi.mocked(fetchContextMillResources).mockRejectedValue(new Error('network'))+ vi.mocked(fetchAndExtractEntries).mockRejectedValue(new Error('network'))vi.mocked(getPromptsFromManifest).mockResolvedValue([{ name: 'p', title: 'P', description: 'D', messages: [] },] as any)- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()const names = catalog.getResourcesList().resources.map((r) => r.name)- expect(names).not.toContain('guide')+ expect(names).not.toContain('name-guide')expect(catalog.getPromptsList().prompts).toHaveLength(1)})it('continues serving resources when prompt fetch fails', async () => {- vi.mocked(fetchContextMillResources).mockResolvedValue('archive' as any)- vi.mocked(loadManifestFromArchive).mockReturnValue({ resources: [] } as any)- vi.mocked(filterValidEntries).mockReturnValue([makeContextMillEntry('r', 'posthog://r')] as any)+ vi.mocked(fetchAndExtractEntries).mockResolvedValue([makeEntry('r')])vi.mocked(getPromptsFromManifest).mockRejectedValue(new Error('fail'))- const catalog = new ResourceCatalog(mockEnv)+ const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- expect(catalog.getResourcesList().resources.map((r) => r.name)).toContain('r')+ expect(catalog.getResourcesList().resources.map((r) => r.name)).toContain('name-r')expect(catalog.getPromptsList().prompts).toEqual([])})})diff --git a/services/mcp/tests/hono/shared-blob-cache.test.ts b/services/mcp/tests/hono/shared-blob-cache.test.tsnew file mode 100644index 000000000000..775bcc0f1cd4--- /dev/null+++ b/services/mcp/tests/hono/shared-blob-cache.test.ts@@ -0,0 +1,150 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { RedisLike } from '@/hono/cache/RedisCache'+import { SharedBlobCache, type SharedBlobCacheOptions } from '@/hono/cache/SharedBlobCache'++import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'++class TestSharedBlobCache extends SharedBlobCache {+ constructor(redis: RedisLike, namespace: string, opts?: SharedBlobCacheOptions) {+ super(redis, namespace, opts)+ }++ read(): Promise<{ bytes: Uint8Array; fresh: boolean } | null> {+ return this.readCache()+ }++ write(bytes: Uint8Array): Promise<void> {+ return this.writeCache(bytes)+ }++ acquire(token: string): Promise<boolean> {+ return this.acquireLock(token)+ }++ release(token: string): Promise<void> {+ return this.releaseLock(token)+ }++ wait(): Promise<Uint8Array | null> {+ return this.waitForCache()+ }+}++interface MockRedis extends RedisLike {+ _store: Map<string, string>+ _setCalls: Array<{ key: string; value: string; args: (string | number)[] }>+}++function createMockRedis(): MockRedis {+ const store = new Map<string, string>()+ const setCalls: Array<{ key: string; value: string; args: (string | number)[] }> = []+ return {+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string, ...args: (string | number)[]) => {+ setCalls.push({ key, value, args })+ const isNx = args.includes('NX')+ if (isNx && store.has(key)) {+ return null+ }+ store.set(key, value)+ return 'OK'+ }),+ del: vi.fn(async (...keys: string[]) => {+ let count = 0+ for (const k of keys) {+ if (store.delete(k)) {+ count+++ }+ }+ return count+ }),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ ...makeRedisRateLimitStubs(),+ _store: store,+ _setCalls: setCalls,+ }+}++const NAMESPACE = 'test-blob'+const BYTES_KEY = `mcp:shared-blob:${NAMESPACE}:bytes`+const FRESH_KEY = `mcp:shared-blob:${NAMESPACE}:fresh`+const LOCK_KEY = `mcp:shared-blob:${NAMESPACE}:lock`++describe('SharedBlobCache', () => {+ let redis: MockRedis++ beforeEach(() => {+ redis = createMockRedis()+ })++ it('writes bytes + freshness and reads them back', async () => {+ const bytes = new Uint8Array([1, 2, 3, 4, 5])+ const cache = new TestSharedBlobCache(redis, NAMESPACE)++ await cache.write(bytes)+ const cached = await cache.read()++ expect(cached).toEqual({ bytes, fresh: true })+ expect(redis._store.has(BYTES_KEY)).toBe(true)+ expect(redis._store.has(FRESH_KEY)).toBe(true)+ })++ it('marks cached bytes stale after the freshness window', async () => {+ const cache = new TestSharedBlobCache(redis, NAMESPACE, { freshSeconds: 0 })+ await cache.write(new Uint8Array([9, 8, 7]))++ const cached = await cache.read()++ expect(cached?.bytes).toEqual(new Uint8Array([9, 8, 7]))+ expect(cached?.fresh).toBe(false)+ })++ it('isolates blobs by namespace', async () => {+ const a = new TestSharedBlobCache(redis, 'alpha')+ const b = new TestSharedBlobCache(redis, 'beta')+ await a.write(new Uint8Array([1]))+ await b.write(new Uint8Array([2]))++ expect(redis._store.has('mcp:shared-blob:alpha:bytes')).toBe(true)+ expect(redis._store.has('mcp:shared-blob:beta:bytes')).toBe(true)++ expect((await a.read())?.bytes).toEqual(new Uint8Array([1]))+ expect((await b.read())?.bytes).toEqual(new Uint8Array([2]))+ })++ it('allows only one lock holder', async () => {+ const cache = new TestSharedBlobCache(redis, NAMESPACE)++ expect(await cache.acquire('first')).toBe(true)+ expect(await cache.acquire('second')).toBe(false)++ expect(redis._store.get(LOCK_KEY)).toBe('first')+ })++ it('releases the lock', async () => {+ const cache = new TestSharedBlobCache(redis, NAMESPACE)++ await cache.acquire('token')+ await cache.release('token')++ expect(redis._store.has(LOCK_KEY)).toBe(false)+ })++ it('waits for another writer to publish', async () => {+ const cache = new TestSharedBlobCache(redis, NAMESPACE, { waitIntervalMs: 5, waitTimeoutMs: 200 })+ const bytes = new Uint8Array([55, 56])++ const waited = cache.wait()+ await new Promise((r) => setTimeout(r, 20))+ await cache.write(bytes)++ expect(await waited).toEqual(bytes)+ })++ it('times out while waiting for another writer', async () => {+ const cache = new TestSharedBlobCache(redis, NAMESPACE, { waitIntervalMs: 10, waitTimeoutMs: 50 })++ expect(await cache.wait()).toBeNull()+ })+})