Skip to content

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

9.1 KB
Raw Blame
import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js'
import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'

import { hasScopes } from '@/lib/api'
import { mergeToolFactories } from '@/tools/mergeToolFactories'
import {
    type ToolDefinition,
    type ToolFilterOptions,
    getToolDefinitions,
    getToolsForFeatures,
} from '@/tools/toolDefinitions'
import type { Tool, ToolBase, ZodObjectAny } from '@/tools/types'

interface PreBuiltTool {
    /**
     * Builds a fresh tool object. Generated tools construct their zod schema
     * inside the factory, so nothing holds a schema between calls.
     */
    build: () => ToolBase<ZodObjectAny>
    meta: ToolBase<ZodObjectAny>['_meta']
    rawInputSchema: ToolBase<ZodObjectAny>['rawInputSchema']
    renderedNote?: ToolBase<ZodObjectAny>['renderedNote']
    definition: ToolDefinition | undefined
}

export interface ToolCatalogFilterOptions extends ToolFilterOptions {
    scopes?: string[]
    excludeTools?: string[]
}

export type { PreBuiltTool }

const EMPTY_OBJECT_JSON_SCHEMA = { type: 'object' as const, properties: {} }

type JsonSchema = Record<string, unknown>

/**
 * Merge a top-level anyOf/oneOf of object variants into a single object schema,
 * or return null if any variant is not a plain object schema.
 *
 * A root union keyword breaks clients that translate tool schemas into a
 * restricted JSON Schema subset: GitHub Copilot Chat rejects the whole tool at
 * registration with "object has unsupported top-level schema keyword 'anyOf'".
 * The merge is advertisement-only and lossy (a variant's extra requirements are
 * not enforced by the merged schema); call-time validation in the executor still
 * runs against the original zod union, so invalid variant mixes are rejected.
 */
function flattenTopLevelUnion(variants: JsonSchema[]): JsonSchema | null {
    if (variants.length === 0 || !variants.every((v) => v['type'] === 'object' && v['properties'])) {
        return null
    }
    const properties: Record<string, JsonSchema> = {}
    for (const variant of variants) {
        for (const [name, prop] of Object.entries(variant['properties'] as Record<string, JsonSchema>)) {
            const existing = properties[name]
            if (!existing) {
                properties[name] = prop
            } else if (Array.isArray(existing['enum']) && Array.isArray(prop['enum'])) {
                // Discriminator fields carry one enum value per variant; merge them
                // so every variant stays expressible.
                properties[name] = { ...existing, enum: [...new Set([...existing['enum'], ...prop['enum']])] }
            }
        }
    }
    // Only fields required by every variant stay required.
    const required = variants
        .map((v) => (Array.isArray(v['required']) ? (v['required'] as string[]) : []))
        .reduce((acc, r) => acc.filter((field) => r.includes(field)))
    return { type: 'object', properties, ...(required.length > 0 ? { required } : {}) }
}

/**
 * Convert a tool's zod schema to the MCP `inputSchema` wire shape. Single source
 * for every advertised schema (catalog entries and the `render-ui` umbrella entry)
 * so what `tools/list` advertises cannot drift from what the executor validates.
 */
export function toMcpInputSchema(schema: ZodObjectAny): McpTool['inputSchema'] {
    // Spread drops the non-enumerable `~standard` handle zod attaches to its
    // output. Its `validate` closure points at the zod instance, so keeping it
    // would pin every built schema for the life of the catalog.
    let jsonSchema = { ...(toJsonSchemaCompat(schema, { strictUnions: true }) as Record<string, unknown>) }
    delete jsonSchema['$schema']
    delete jsonSchema['additionalProperties']
    // MCP requires inputSchema.type === 'object'. Top-level discriminated unions
    // (e.g. `oneOf` on a polymorphic request body) come back without a root `type`.
    // Flatten object-variant unions (see flattenTopLevelUnion); for anything else,
    // add the root `type` so the schema satisfies the MCP tool contract.
    if (!jsonSchema['type'] && (Array.isArray(jsonSchema['anyOf']) || Array.isArray(jsonSchema['oneOf']))) {
        const variants = (jsonSchema['anyOf'] ?? jsonSchema['oneOf']) as JsonSchema[]
        jsonSchema = flattenTopLevelUnion(variants) ?? { type: 'object', ...jsonSchema }
    }
    return jsonSchema as McpTool['inputSchema']
}

export class ToolCatalog {
    private _preBuilt: Map<string, PreBuiltTool> = new Map()
    private _entries: McpTool[] = []
    private _entriesByName = new Map<string, McpTool>()
    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'),
        ])

        // Hand-written TOOL_MAP wins on collision (e.g. update-feature-flag group merge).
        const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = mergeToolFactories({
            generated: GENERATED_TOOL_MAP,
            handwritten: TOOL_MAP,
        })

        const defs = getToolDefinitions()

        for (const [name, factory] of Object.entries(allFactories)) {
            const base = factory()
            this._preBuilt.set(name, {
                build: factory,
                meta: base._meta,
                rawInputSchema: base.rawInputSchema,
                renderedNote: base.renderedNote,
                definition: defs[name],
            })
        }

        this._buildEntries()

        this._warmedUp = true
        console.info(
            `[ToolCatalog] warmup complete: ${this._preBuilt.size} tools in ${(performance.now() - start).toFixed(0)}ms`
        )
    }

    private _buildEntries(): void {
        this._entries = []
        this._entriesByName = new Map()

        for (const [name, preBuilt] of this._preBuilt) {
            const def = preBuilt.definition
            if (!def) {
                continue
            }

            let jsonSchema: McpTool['inputSchema']
            try {
                jsonSchema = toMcpInputSchema(preBuilt.build().schema)
            } catch {
                jsonSchema = EMPTY_OBJECT_JSON_SCHEMA
            }

            let meta = preBuilt.meta as Record<string, unknown> | undefined
            if (meta?.ui && typeof meta.ui === 'object' && 'resourceUri' in meta.ui && !meta[RESOURCE_URI_META_KEY]) {
                meta = {
                    ...meta,
                    [RESOURCE_URI_META_KEY]: (meta.ui as Record<string, unknown>).resourceUri,
                }
            }

            const entry: McpTool = {
                name,
                title: def.title,
                description: def.description,
                inputSchema: jsonSchema,
                annotations: def.annotations as McpTool['annotations'],
                ...(meta ? { _meta: meta } : {}),
            }
            this._entries.push(entry)
            this._entriesByName.set(name, entry)
        }
    }

    getAllPreBuilt(): ReadonlyMap<string, PreBuiltTool> {
        return this._preBuilt
    }

    getToolByName(name: string): PreBuiltTool | undefined {
        return this._preBuilt.get(name)
    }

    getPreBuiltEntries(): McpTool[] {
        return this._entries
    }

    getPreBuiltEntry(name: string): McpTool | undefined {
        return this._entriesByName.get(name)
    }

    getFilteredTools(options: ToolCatalogFilterOptions): Tool<ZodObjectAny>[] {
        const { scopes = [], excludeTools = [], ...filterOptions } = options
        const allowedToolNames = getToolsForFeatures(filterOptions).filter((name) => !excludeTools.includes(name))

        const tools: Tool<ZodObjectAny>[] = []

        for (const name of allowedToolNames) {
            const preBuilt = this._preBuilt.get(name)
            if (!preBuilt) {
                continue
            }
            const definition = preBuilt.definition
            if (!definition) {
                continue
            }

            if (!hasScopes(scopes, definition.required_scopes ?? [])) {
                continue
            }

            tools.push({
                name,
                // Built on access: listing tools must not build a schema per tool.
                get schema() {
                    return preBuilt.build().schema
                },
                handler: (context, params) => preBuilt.build().handler(context, params),
                ...(preBuilt.rawInputSchema ? { rawInputSchema: preBuilt.rawInputSchema } : {}),
                ...(preBuilt.meta ? { _meta: preBuilt.meta } : {}),
                ...(preBuilt.renderedNote ? { renderedNote: preBuilt.renderedNote } : {}),
                title: definition.title,
                description: definition.description,
                scopes: definition.required_scopes ?? [],
                annotations: definition.annotations,
            })
        }

        return tools
    }
}