Open History to see the last commit
1import { compile } from 'json-schema-to-typescript'
2import type { ServerSurface } from './introspect'
3
4/**
5 * Convert an arbitrary server/tool name into a valid PascalCase identifier.
6 * Falls back to `Generated` for names with no alphanumeric characters and
7 * prefixes an underscore when the result would start with a digit.
8 */
9function pascal(name: string): string {
10 const base = name
11 .replace(/[^a-zA-Z0-9]+/g, ' ')
12 .split(' ')
13 .filter(Boolean)
14 .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
15 .join('')
16 const safe = base || 'Generated'
17 return /^[A-Za-z_]/.test(safe) ? safe : `_${safe}`
18}
19
20/** Escape a value as a TypeScript string literal (handles quotes/newlines). */
21function tsString(value: string): string {
22 return JSON.stringify(value)
23}
24
25/**
26 * Compile a JSON Schema into a TypeScript type via `json-schema-to-typescript`.
27 * Returns `'unknown'` for absent/non-object schemas. The compiled output is an
28 * `export interface <typeName> { ... }` declaration which callers inline via
29 * {@link inlineBody}.
30 */
31async function schemaToType(
32 schema: unknown,
33 typeName: string,
34): Promise<string> {
35 if (!schema || typeof schema !== 'object') return 'unknown'
36 const compiled = await compile(schema, typeName, {
37 bannerComment: '',
38 additionalProperties: false,
39 declareExternallyReferenced: true,
40 })
41 return compiled.trim()
42}
43
44export interface EmitInput {
45 [serverName: string]: { prefix?: string; surface: ServerSurface }
46}
47
48export async function emitDescriptors(input: EmitInput): Promise<string> {
49 const blocks: Array<string> = [
50 '// AUTO-GENERATED by `npx @tanstack/ai-mcp generate`. Do not edit.',
51 "import type { ServerDescriptor } from '@tanstack/ai-mcp'",
52 '',
53 ]
54 // Track config-key -> interface-name so we can emit the combined pool map.
55 const mapEntries: Array<[string, string]> = []
56 // Distinct server keys can pascal-case to the same identifier
57 // (`foo-bar` vs `foo_bar`) — fail loudly rather than emit duplicate
58 // interface declarations.
59 const seenIfaces = new Set<string>()
60 for (const [serverName, { prefix, surface }] of Object.entries(input)) {
61 const iface = `${pascal(serverName)}Server`
62 if (seenIfaces.has(iface)) {
63 throw new Error(
64 `Interface name collision for server key "${serverName}" -> ${iface}. ` +
65 `Rename one of the colliding servers in your codegen config.`,
66 )
67 }
68 seenIfaces.add(iface)
69 mapEntries.push([serverName, iface])
70 const toolEntries: Array<string> = []
71 for (const tool of surface.tools) {
72 const key = prefix ? `${prefix}_${tool.name}` : tool.name
73 const inputType = await schemaToType(
74 tool.inputSchema,
75 `${pascal(key)}Input`,
76 )
77 const outputType = tool.outputSchema
78 ? await schemaToType(tool.outputSchema, `${pascal(key)}Output`)
79 : 'unknown'
80 // Inline the compiled interface bodies as anonymous object types.
81 toolEntries.push(
82 ` ${tsString(key)}: { input: ${inlineBody(inputType)}; output: ${inlineBody(outputType)} }`,
83 )
84 }
85 blocks.push(
86 `export interface ${iface} extends ServerDescriptor {`,
87 ` tools: {`,
88 toolEntries.join('\n'),
89 ` }`,
90 ` resources: ${emitResources(surface)}`,
91 ` prompts: ${emitPrompts(surface)}`,
92 ` capabilities: ${JSON.stringify(surface.capabilities)} & Record<string, unknown>`,
93 `}`,
94 '',
95 )
96 }
97 // Combined map for createMCPClients<MCPServers>(...). Keys = config keys
98 // verbatim (NOT pascal-cased) so they match the runtime config object and
99 // pool.clients access.
100 blocks.push(
101 'export interface MCPServers extends Record<string, ServerDescriptor> {',
102 ...mapEntries.map(([key, iface]) => ` ${tsString(key)}: ${iface}`),
103 '}',
104 '',
105 )
106 return blocks.join('\n')
107}
108
109/**
110 * Extract the `{ ... }` body from a compiled `export interface X { ... }`
111 * declaration so it can be inlined as an anonymous object type. Collapses
112 * newlines onto a single line. Falls back to `unknown` when no brace is found
113 * (e.g. the compiled type is itself `unknown`).
114 */
115function inlineBody(compiled: string): string {
116 const brace = compiled.indexOf('{')
117 return brace >= 0
118 ? compiled.slice(brace).replace(/\n/g, ' ').trim()
119 : 'unknown'
120}
121
122function emitResources(s: ServerSurface): string {
123 if (!s.resources.length) return '{}'
124 return `{ ${s.resources
125 .map(
126 (r) => `${tsString(r.uri)}: { uri: ${tsString(r.uri)}; data: unknown }`,
127 )
128 .join('; ')} }`
129}
130
131function emitPrompts(s: ServerSurface): string {
132 if (!s.prompts.length) return '{}'
133 return `{ ${s.prompts
134 .map(
135 (p) =>
136 `${tsString(p.name)}: { args: Record<string, string>; messages: unknown }`,
137 )
138 .join('; ')} }`
139}