/** * Domain Registry * * Provides auto-discovery and registration of framework domains for MCP servers. * Instead of hardcoding tool definitions and dispatch logic per domain, domains * export a `DomainDescriptor` and the registry generates everything automatically. * * @example * ```typescript * import { DomainRegistry } from '@lokascript/framework'; * * const registry = new DomainRegistry(); * * // Register domains (each provides a descriptor) * registry.register({ * name: 'sql', * description: 'Natural language SQL', * languages: ['en', 'es', 'ja', 'ar'], * inputLabel: 'query', * inputDescription: 'SQL query in natural language', * getDSL: () => import('@lokascript/domains/sql').then(m => m.createSQLDSL()), * getRenderer: () => import('@lokascript/domains/sql').then(m => m.renderSQL), * }); * * // Auto-generate MCP tool definitions * const tools = registry.getToolDefinitions(); * * // Dispatch a tool call * const result = await registry.handleToolCall('parse_sql', { query: 'select name from users' }); * ``` */ import type { MultilingualDSL, CompileResult, ValidationResult } from './create-dsl'; import { UnreadInputError, TranslationReadBackError } from './create-dsl'; import { readingDifference } from './reading'; import type { SemanticNode } from '../core/types'; import type { NaturalLanguageRenderer, DomainRenderFn } from '../generation/renderer'; import type { CommandSchema } from '../schema/command-schema'; import type { SchemaLookup } from '../ir/types'; import type { Diagnostic } from '../generation/diagnostics'; import type { GeneratedPrompt, PromptGeneratorConfig } from '../prompts/types'; import type { SynthesisConfig, SynthesisResult } from '../training/types'; import type { LSEFeedback } from '../feedback/types'; import { generatePrompt as _generatePrompt } from '../prompts/prompt-generator'; import { synthesizeFromSchemas as _synthesizeFromSchemas } from '../training/schema-synthesizer'; import { buildFeedback as _buildFeedback } from '../feedback/feedback-formatter'; import { parseExplicit as _parseExplicit } from '../ir/explicit-parser'; // ============================================================================= // Descriptor Interface // ============================================================================= /** * Describes a domain for auto-registration in MCP servers. * * Domains provide this descriptor to the registry, which generates * tool definitions and handles dispatch automatically. */ export interface DomainDescriptor { /** Short identifier (used in tool names: parse_{name}, compile_{name}, etc.) */ readonly name: string; /** Human-readable description */ readonly description: string; /** Supported language codes */ readonly languages: readonly string[]; /** Label for the primary input parameter (e.g., 'query', 'scenario', 'code') */ readonly inputLabel: string; /** Description of the primary input parameter */ readonly inputDescription: string; /** What compile_{name} produces (e.g., "a SQL query string"). Used in tool description. */ readonly outputDescription?: string; /** * Factory to lazily create the DSL instance. * Called once on first tool use. The result is cached. */ readonly getDSL: () => MultilingualDSL | Promise; /** * Factory to lazily create the renderer. * Required for translate_{name} tool. Called once on first use. * * The function form may return `null` for an action it cannot render; the * translate tool reports that as an unsuccessful translation. */ readonly getRenderer?: () => NaturalLanguageRenderer | DomainRenderFn | Promise; /** * Which standard tools to generate. Default: all four. */ readonly tools?: readonly ('parse' | 'compile' | 'validate' | 'translate')[]; /** * Optional command schemas for this domain. * When provided, enables system prompt generation, training data synthesis, * and structured feedback via the registry's convenience methods. */ readonly schemas?: readonly CommandSchema[]; /** * Optional scan configuration for AOT compilation and Vite plugin. * Declares which HTML attributes/script types this domain uses. */ readonly scanConfig?: { /** Attribute names to scan for (e.g., ['data-sql', '_sql']) */ readonly attributes: readonly string[]; /** Script tag types to scan for (e.g., ['text/sql-dsl']) */ readonly scriptTypes?: readonly string[]; /** Default language when not specified on element */ readonly defaultLanguage?: string; /** Keywords for detection, keyed by language code */ readonly keywords?: Readonly>; }; } // ============================================================================= // MCP Tool Types (minimal — compatible with @modelcontextprotocol/server) // ============================================================================= /** * MCP tool definition. Compatible with the MCP SDK's tool schema. */ export interface MCPToolDefinition { readonly name: string; readonly description: string; readonly inputSchema: { readonly type: 'object'; readonly properties: Record; readonly required: readonly string[]; }; } /** * MCP tool response. Compatible with the MCP SDK's response format. */ export interface MCPToolResponse { readonly content: ReadonlyArray<{ readonly type: string; readonly text: string }>; readonly isError?: boolean; } // ============================================================================= // Domain Registry // ============================================================================= /** * Registry for framework domains. * * Manages domain descriptors, generates MCP tool definitions, * and dispatches tool calls to the appropriate domain. */ export class DomainRegistry { private descriptors = new Map(); private dslCache = new Map(); private rendererCache = new Map(); /** * Register a domain. * @throws if a domain with the same name is already registered */ register(descriptor: DomainDescriptor): void { if (this.descriptors.has(descriptor.name)) { throw new Error(`Domain already registered: ${descriptor.name}`); } this.descriptors.set(descriptor.name, descriptor); } /** * Attach schemas to an already-registered domain. * Useful for lazy loading schemas after initial registration. */ setSchemas(name: string, schemas: readonly CommandSchema[]): void { const existing = this.descriptors.get(name); if (!existing) { throw new Error(`Domain not registered: ${name}`); } // Create a new descriptor with schemas attached this.descriptors.set(name, { ...existing, schemas }); } /** * Get all registered domain names. */ getDomainNames(): string[] { return Array.from(this.descriptors.keys()); } /** * Get a specific domain descriptor. */ getDescriptor(name: string): DomainDescriptor | undefined { return this.descriptors.get(name); } /** * Generate MCP tool definitions for all registered domains. */ getToolDefinitions(): MCPToolDefinition[] { const tools: MCPToolDefinition[] = []; for (const desc of this.descriptors.values()) { tools.push(...generateToolDefinitions(desc)); } return tools; } /** * Check if a tool name belongs to a registered domain. */ canHandle(toolName: string): boolean { const parsed = parseToolName(toolName); if (!parsed) return false; return this.descriptors.has(parsed.domain); } /** * Handle a tool call by dispatching to the appropriate domain. * Returns null if the tool name doesn't match any registered domain. */ async handleToolCall( toolName: string, args: Record ): Promise { const parsed = parseToolName(toolName); if (!parsed) return null; const descriptor = this.descriptors.get(parsed.domain); if (!descriptor) return null; try { const dsl = await this.getDSL(descriptor); switch (parsed.operation) { case 'parse': return await this.handleParse(descriptor, dsl, args); case 'compile': return await this.handleCompile(descriptor, dsl, args); case 'validate': return await this.handleValidate(descriptor, dsl, args); case 'translate': return await this.handleTranslate(descriptor, dsl, args); default: return jsonResponse({ error: `Unknown operation: ${parsed.operation}` }, true); } } catch (error) { // A refusal is not a tool failure: say what was refused and why, as translate_code does. if (error instanceof UnreadInputError) return unreadInputResponse(error); if (error instanceof TranslationReadBackError) return readBackResponse(error); const message = error instanceof Error ? error.message : String(error); return jsonResponse({ error: `${descriptor.name} tool error: ${message}` }, true); } } /** * Get the DSL instance for a named domain. * Returns null if the domain is not registered. * The DSL is lazily created and cached. */ async getDSLForDomain(name: string): Promise { const descriptor = this.descriptors.get(name); if (!descriptor) return null; return this.getDSL(descriptor); } // --------------------------------------------------------------------------- // LLM ↔ LSE Convenience Methods // --------------------------------------------------------------------------- /** * Generate an LLM system prompt for a domain from its schemas. * Returns null if the domain is not registered or has no schemas. */ generatePrompt(domain: string, config?: Partial): GeneratedPrompt | null { const descriptor = this.descriptors.get(domain); if (!descriptor?.schemas || descriptor.schemas.length === 0) return null; return _generatePrompt({ domain, description: descriptor.description, schemas: descriptor.schemas, ...config, }); } /** * Synthesize training data for a domain from its schemas. * Returns null if the domain is not registered or has no schemas. */ generateTrainingData(domain: string, config?: Partial): SynthesisResult | null { const descriptor = this.descriptors.get(domain); if (!descriptor?.schemas || descriptor.schemas.length === 0) return null; return _synthesizeFromSchemas(descriptor.schemas, { domain, ...config, }); } /** * Build structured feedback for a failed LSE input in a domain. * Returns null if the domain is not registered or has no schemas. */ buildFeedback( domain: string, input: string, inputFormat: 'explicit' | 'json' | 'natural', diagnostics: readonly Diagnostic[] ): LSEFeedback | null { const descriptor = this.descriptors.get(domain); if (!descriptor?.schemas || descriptor.schemas.length === 0) return null; const schemaLookup = this.createSchemaLookup(descriptor.schemas); // Try to extract the action from the input let action: string | undefined; try { if (inputFormat === 'explicit') { const node = _parseExplicit(input, { schemaLookup }); action = node.action; } } catch { // Action detection failed — still build feedback without it } return _buildFeedback(input, inputFormat, diagnostics, schemaLookup, action); } /** * Get schemas for a domain (if available). */ getSchemas(domain: string): readonly CommandSchema[] | null { const descriptor = this.descriptors.get(domain); if (!descriptor?.schemas) return null; return descriptor.schemas; } /** * Create a SchemaLookup from a domain's schemas. */ private createSchemaLookup(schemas: readonly CommandSchema[]): SchemaLookup { const map = new Map(); for (const s of schemas) { map.set(s.action, s); } return { getSchema: (action: string) => map.get(action) }; } // --------------------------------------------------------------------------- // Private: DSL/renderer lifecycle // --------------------------------------------------------------------------- private async getDSL(descriptor: DomainDescriptor): Promise { const cached = this.dslCache.get(descriptor.name); if (cached) return cached; const dsl = await descriptor.getDSL(); this.dslCache.set(descriptor.name, dsl); return dsl; } private async getRenderer( descriptor: DomainDescriptor ): Promise { if (!descriptor.getRenderer) return null; const cached = this.rendererCache.get(descriptor.name); if (cached) return cached; const renderer = await descriptor.getRenderer(); this.rendererCache.set(descriptor.name, renderer); return renderer; } // --------------------------------------------------------------------------- // Private: Tool handlers // --------------------------------------------------------------------------- private async handleParse( descriptor: DomainDescriptor, dsl: MultilingualDSL, args: Record ): Promise { const input = getString(args, descriptor.inputLabel); if (!input) return missingParam(descriptor.inputLabel); const language = getString(args, 'language', 'en'); const node = dsl.parse(input, language); const roles: Record = {}; for (const [key, value] of node.roles) { roles[key] = value; } return jsonResponse({ action: node.action, roles, language, [descriptor.inputLabel]: input, }); } private async handleCompile( descriptor: DomainDescriptor, dsl: MultilingualDSL, args: Record ): Promise { const input = getString(args, descriptor.inputLabel); if (!input) return missingParam(descriptor.inputLabel); const language = getString(args, 'language', 'en'); const result: CompileResult = dsl.compile(input, language); return jsonResponse({ ok: result.ok, code: result.code, errors: result.errors, ...(result.errorCode === 'unread-input' ? { diagnostics: [UNREAD_INPUT(result.errors)] } : {}), language, input, }); } private async handleValidate( descriptor: DomainDescriptor, dsl: MultilingualDSL, args: Record ): Promise { const input = getString(args, descriptor.inputLabel); if (!input) return missingParam(descriptor.inputLabel); const language = getString(args, 'language', 'en'); const result: ValidationResult = dsl.validate(input, language); return jsonResponse({ valid: result.valid, errors: result.errors, ...(result.errorCode === 'unread-input' ? { diagnostics: [UNREAD_INPUT(result.errors)] } : {}), language, [descriptor.inputLabel]: input, }); } private async handleTranslate( descriptor: DomainDescriptor, dsl: MultilingualDSL, args: Record ): Promise { const input = getString(args, descriptor.inputLabel); if (!input) return missingParam(descriptor.inputLabel); const from = getString(args, 'from'); if (!from) return missingParam('from'); const to = getString(args, 'to'); if (!to) return missingParam('to'); // Parse in source language const node = dsl.parse(input, from); // Compile (language-neutral output) const compiled = dsl.compile(input, from); // Render to target language let rendered: string | null = null; const renderer = await this.getRenderer(descriptor); if (renderer) { try { rendered = typeof renderer === 'function' ? renderer(node, to) : renderer.render(node, to); } catch { // Fall through with rendered = null } } else if (dsl.render) { // A descriptor without an explicit renderer can still render: the DSL // knows its own domain renderer and its schema fallback. try { rendered = dsl.render(node, to); } catch { // Fall through with rendered = null } } const roles: Record = {}; for (const [key, value] of node.roles) { roles[key] = value; } // The rendering must read back as the source, by the rule `translate` uses: the same action and // role values, or the same compiled code. A rendering that does not is refused, with the text under // `partial`, never `rendered`. if (rendered != null) { let back: SemanticNode | null = null; let why = ''; try { back = dsl.parse(rendered, to); why = readingDifference(node, back); if (why && compiled.ok) { const again = dsl.compile(rendered, to); if (again.ok && again.code === compiled.code) why = ''; } } catch (error) { why = error instanceof Error ? error.message : String(error); } if (why) return readBackResponse(new TranslationReadBackError(rendered, from, to, node, back, why)); } return jsonResponse({ ok: true, input: { [descriptor.inputLabel]: input, language: from }, ...(rendered != null && { rendered: { text: rendered, language: to } }), semantic: { action: node.action, roles }, ...(compiled.ok && compiled.code != null && { compiled: compiled.code }), }); } } // ============================================================================= // Tool Definition Generator // ============================================================================= function generateToolDefinitions(desc: DomainDescriptor): MCPToolDefinition[] { const tools: MCPToolDefinition[] = []; const ops = desc.tools ?? (['parse', 'compile', 'validate', 'translate'] as const); const langList = desc.languages.join(', '); for (const op of ops) { switch (op) { case 'parse': tools.push({ name: `parse_${desc.name}`, description: `Parse a ${desc.description} input into a semantic representation (action, roles, confidence). Supports: ${langList}.`, inputSchema: { type: 'object', properties: { [desc.inputLabel]: { type: 'string', description: desc.inputDescription, }, language: { type: 'string', description: `Language code: ${langList}`, default: 'en', }, }, required: [desc.inputLabel], }, }); break; case 'compile': tools.push({ name: `compile_${desc.name}`, description: `Compile a ${desc.description} input to ${desc.outputDescription ?? 'target code'}. Supports: ${langList}.`, inputSchema: { type: 'object', properties: { [desc.inputLabel]: { type: 'string', description: desc.inputDescription, }, language: { type: 'string', description: `Language code: ${langList}`, default: 'en', }, }, required: [desc.inputLabel], }, }); break; case 'validate': tools.push({ name: `validate_${desc.name}`, description: `Check ${desc.description} syntax for errors. Returns {valid, errors[]}. Supports: ${langList}.`, inputSchema: { type: 'object', properties: { [desc.inputLabel]: { type: 'string', description: `${desc.inputDescription} to validate`, }, language: { type: 'string', description: `Language code: ${langList}`, default: 'en', }, }, required: [desc.inputLabel], }, }); break; case 'translate': tools.push({ name: `translate_${desc.name}`, description: `Translate ${desc.description} input between natural languages (requires 'from' and 'to' codes). Supports: ${langList}. A rendering that does not read back as the source is REFUSED: ok is false, the diagnostic is TRANSLATION_DOES_NOT_READ_BACK, and its text is under \`partial\`, never \`rendered\`: do not present it as the translation. Input left unread is refused as UNREAD_INPUT.`, inputSchema: { type: 'object', properties: { [desc.inputLabel]: { type: 'string', description: `${desc.inputDescription} to translate`, }, from: { type: 'string', description: `Source language code: ${langList}`, }, to: { type: 'string', description: `Target language code: ${langList}`, }, }, required: [desc.inputLabel, 'from', 'to'], }, }); break; } } return tools; } // ============================================================================= // Helpers // ============================================================================= function parseToolName(name: string): { operation: string; domain: string } | null { const match = name.match(/^(parse|compile|validate|translate)_(.+)$/); if (!match) return null; return { operation: match[1], domain: match[2] }; } function getString(args: Record, name: string, defaultValue = ''): string { const value = args[name]; return typeof value === 'string' ? value : defaultValue; } function readingOf(node: SemanticNode): { action: string; roles: Record } { const roles: Record = {}; for (const [key, value] of node.roles) roles[key] = value; return { action: node.action, roles }; } const UNREAD_INPUT = (errors?: readonly string[]) => ({ severity: 'error', code: 'UNREAD_INPUT', message: errors?.[0] ?? 'part of the input was not read', suggestion: 'Part of the input belongs to no role of the command it reads as: remove it, or quote a value of several words.', }); /** A parse refused because it read the command only by leaving input unread. */ function unreadInputResponse(error: UnreadInputError): MCPToolResponse { return jsonResponse( { ok: false, unread: error.unread, reading: readingOf(error.reading), diagnostics: [UNREAD_INPUT([error.message])], }, true ); } /** A translation refused because it does not read back as the source; its text under `partial`. */ function readBackResponse(error: TranslationReadBackError): MCPToolResponse { return jsonResponse( { ok: false, partial: error.partial, ...(error.reading ? { reading: readingOf(error.reading) } : {}), diagnostics: [ { severity: 'error', code: 'TRANSLATION_DOES_NOT_READ_BACK', message: error.message, suggestion: 'The rendering would not mean the source in the target language: do not present `partial` as the translation.', }, ], }, true ); } function jsonResponse(data: unknown, isError?: boolean): MCPToolResponse { return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], ...(isError && { isError: true }), }; } function missingParam(param: string): MCPToolResponse { return jsonResponse({ error: `Missing required parameter: ${param}` }, true); }