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.

3.9 KB
Raw Blame
#!/usr/bin/env node
/**
 * Generates full TypeScript type definitions for MCP from the OpenAPI schema.
 *
 * Uses Orval with client: 'fetch' over the complete (unfiltered) schema to produce
 * flat TS interface exports, then wraps them in an `export namespace Schemas { ... }`
 * block so existing `import type { Schemas } from '@/api/generated'` usage works.
 *
 * Output:
 *   src/api/generated.ts — Schemas namespace wrapping all Orval-generated interfaces
 *
 * Invoked by `hogli build:openapi-mcp-types`.
 */
/* eslint-disable no-console */
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { preprocessSchema, runOrvalParallel } from '@posthog/openapi-codegen'

import { resolveSchemaPath } from './lib/definitions.mjs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const mcpRoot = path.resolve(__dirname, '..')
const repoRoot = path.resolve(mcpRoot, '../..')

const schemaPath = resolveSchemaPath(repoRoot)

if (!fs.existsSync(schemaPath)) {
    console.error(`OpenAPI schema not found at ${schemaPath}. Run \`hogli build:openapi-schema\` first.`)
    process.exit(1)
}

// ------------------------------------------------------------------
// Orval run — output to temp dir so we can post-process
// ------------------------------------------------------------------

const schema = preprocessSchema(JSON.parse(fs.readFileSync(schemaPath, 'utf-8')))
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-types-'))

const tempSchemaFile = path.join(tmpDir, 'openapi.json')
const tempTargetFile = path.join(tmpDir, 'generated.ts')
const tempSchemasFile = path.join(tmpDir, 'generated.schemas.ts')

fs.writeFileSync(tempSchemaFile, JSON.stringify(schema))

const results = await runOrvalParallel([
    {
        label: 'mcp-types',
        config: {
            input: tempSchemaFile,
            output: {
                target: tempTargetFile,
                mode: 'split',
                client: 'fetch',
                prettier: false,
                override: {
                    header: () => [],
                    namingConvention: {
                        enum: 'PascalCase',
                    },
                    fetch: {
                        includeHttpResponseReturnType: false,
                    },
                    components: {
                        schemas: { suffix: '' },
                    },
                },
            },
        },
    },
])

if (results[0].status === 'rejected') {
    console.error(`Orval failed: ${results[0].reason.message}`)
    process.exit(1)
}

// ------------------------------------------------------------------
// Wrap the flat Orval types in `export namespace Schemas { ... }`
// so `import type { Schemas } from '@/api/generated'` keeps working.
// ------------------------------------------------------------------

const flatTypes = fs.readFileSync(tempSchemasFile, 'utf-8')
fs.rmSync(tmpDir, { recursive: true, force: true })

// Indent every non-empty line by 4 spaces for the namespace body
const indented = flatTypes
    .split('\n')
    .map((line) => (line.length > 0 ? `    ${line}` : ''))
    .join('\n')

const targetFile = path.join(mcpRoot, 'src', 'api', 'generated.ts')

const output = `/**
 * Auto-generated from the Django backend OpenAPI schema.
 * MCP service uses these TypeScript types for tool handler return type annotations.
 * To regenerate: hogli build:openapi
 *
 * Do not edit this file directly. Edit the Django serializers and rerun the generator.
 */

// All types are exposed via the Schemas namespace:
//   import type { Schemas } from '@/api/generated'
//   handler: (...) => Promise<Schemas.Action>
export namespace Schemas {
${indented}
}
`

fs.writeFileSync(targetFile, output)

const schemaCount = Object.keys(schema.components?.schemas ?? {}).length
console.log(`MCP types: generated ${schemaCount} schemas → src/api/generated.ts`)