// registry-loader.ts - Load the filesystem registry into memory. // // Implements REQ-R-001..003 of openspec/specs/config-registry/spec.md: // - Root resolution: $PI_MCP_BRIDGE_REGISTRY → /mcp-registry/ // - Server directory naming: //meta.json must parse and // its `name` must match the directory. // - Tool file naming: //tools/.json must parse with // a non-empty `name`; the filename is the registry key, the JSON's // `name` is the original MCP name. // // The loader is read-only and never throws on missing/bad data — it // returns an empty `Registry` and logs warnings instead. This keeps // `session_start` non-fatal when the registry is hand-edited. import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; import { join, resolve } from "node:path"; import { getRegistryRoot } from "../agent-dir.ts"; import { logger } from "../logger.ts"; import { slugifyToolName } from "../resource-tools.ts"; import type { Registry, RegistryServer, ServerMeta, ToolDefinition, RegistryIndex, } from "./registry-types.ts"; const INDEX_FILENAME = "index.json"; const META_FILENAME = "meta.json"; const TOOLS_DIRNAME = "tools"; /** Load the whole registry from disk. Returns an empty registry if the root is missing. */ export function loadRegistry(rootOverride?: string): Registry { const root = rootOverride ? resolve(rootOverride) : getRegistryRoot(); const registry: Registry = { root, servers: new Map(), index: null }; if (!existsSync(root)) { logger.debug(`registry root does not exist: ${root}`); return registry; } if (!statSync(root).isDirectory()) { logger.warn(`registry root is not a directory: ${root}`); return registry; } for (const entry of readdirSync(root, { withFileTypes: true })) { if (!entry.isDirectory()) continue; if (entry.name.startsWith(".")) continue; const serverDir = join(root, entry.name); const server = loadServer(serverDir, entry.name); if (server) { registry.servers.set(server.name, server); } } registry.index = loadIndex(root); if (!registry.index) { // Build a transient in-memory index so the injector can run without // waiting for the writer. The on-disk index will be regenerated by // `registry-writer.rebuildIndex()` on the next sync. registry.index = buildTransientIndex(registry); } return registry; } /** Load one server directory. Returns `null` if `meta.json` is missing or invalid. */ export function loadServer(serverDir: string, expectedName: string): RegistryServer | null { const metaPath = join(serverDir, META_FILENAME); if (!existsSync(metaPath)) { logger.debug(`skipping ${serverDir}: no ${META_FILENAME}`); return null; } let meta: ServerMeta; try { meta = parseServerMeta(readFileSync(metaPath, "utf-8"), expectedName); } catch (error) { logger.warn(`skipping ${serverDir}: ${error instanceof Error ? error.message : String(error)}`); return null; } if (meta.name !== expectedName) { logger.warn( `server directory name "${expectedName}" does not match meta.name "${meta.name}" — skipping`, ); return null; } const tools = loadTools(join(serverDir, TOOLS_DIRNAME), expectedName); return { name: meta.name, meta, tools, directory: serverDir }; } /** Parse and validate a `meta.json` document. Throws on invalid input. */ export function parseServerMeta(text: string, expectedName: string): ServerMeta { let raw: unknown; try { raw = JSON.parse(text); } catch (error) { throw new Error(`meta.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`); } if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new Error("meta.json must be a JSON object"); } const obj = raw as Record; if (typeof obj.name !== "string" || !obj.name) { throw new Error("meta.json is missing required field: name"); } if (!obj.transport || typeof obj.transport !== "object") { throw new Error("meta.json is missing required field: transport"); } const transport = obj.transport as Record; if (transport.kind !== "stdio" && transport.kind !== "http") { throw new Error(`meta.json transport.kind must be "stdio" or "http" (got: ${String(transport.kind)})`); } if (transport.kind === "stdio" && typeof transport.command !== "string") { throw new Error("meta.json stdio transport requires a `command` string"); } if (transport.kind === "http" && typeof transport.url !== "string") { throw new Error("meta.json http transport requires a `url` string"); } if (!obj.auth || typeof obj.auth !== "object") { throw new Error("meta.json is missing required field: auth"); } const auth = obj.auth as Record; if (auth.kind !== "none" && auth.kind !== "bearer" && auth.kind !== "oauth") { throw new Error(`meta.json auth.kind must be "none", "bearer", or "oauth" (got: ${String(auth.kind)})`); } // The cast is safe — we validated the discriminated unions above. return obj as unknown as ServerMeta; } /** Load every `tools/.json` for a server. Returns a map keyed by tool key. */ export function loadTools(toolsDir: string, serverName: string): Map { const tools = new Map(); if (!existsSync(toolsDir) || !statSync(toolsDir).isDirectory()) { return tools; } for (const entry of readdirSync(toolsDir, { withFileTypes: true })) { if (!entry.isFile()) continue; if (!entry.name.endsWith(".json")) continue; const key = entry.name.slice(0, -".json".length); const path = join(toolsDir, entry.name); let def: ToolDefinition; try { def = parseToolDefinition(readFileSync(path, "utf-8"), key); } catch (error) { logger.warn( `skipping ${serverName}/tools/${entry.name}: ${error instanceof Error ? error.message : String(error)}`, ); continue; } if (tools.has(key)) { logger.warn(`duplicate tool key "${key}" in ${serverName}/tools/ — overwriting`); } tools.set(key, def); } return tools; } /** Parse and validate a `tools/.json` document. Throws on invalid input. */ export function parseToolDefinition(text: string, key: string): ToolDefinition { let raw: unknown; try { raw = JSON.parse(text); } catch (error) { throw new Error(`tool ${key}.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`); } if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new Error(`tool ${key}.json must be a JSON object`); } const obj = raw as Record; if (typeof obj.name !== "string" || !obj.name) { throw new Error(`tool ${key}.json is missing required field: name`); } if (typeof obj.description !== "string") { throw new Error(`tool ${key}.json is missing required field: description`); } if (obj.inputSchema === undefined || obj.inputSchema === null) { throw new Error(`tool ${key}.json is missing required field: inputSchema`); } if (typeof obj.inputSchema !== "object" || Array.isArray(obj.inputSchema)) { throw new Error(`tool ${key}.json inputSchema must be a JSON Schema object`); } return obj as unknown as ToolDefinition; } /** Load `index.json` from the registry root. Returns `null` if missing or invalid. */ export function loadIndex(root: string): RegistryIndex | null { const indexPath = join(root, INDEX_FILENAME); if (!existsSync(indexPath)) return null; try { const raw = JSON.parse(readFileSync(indexPath, "utf-8")); if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; if ((raw as { version?: unknown }).version !== 1) return null; return raw as RegistryIndex; } catch (error) { logger.warn(`index.json is unreadable: ${error instanceof Error ? error.message : String(error)}`); return null; } } /** Build a transient in-memory index from the loaded servers (used when `index.json` is missing). */ export function buildTransientIndex(registry: Registry): RegistryIndex { return { version: 1, generatedAt: new Date().toISOString(), registryRoot: registry.root, servers: [...registry.servers.values()].map(server => ({ name: server.name, description: server.meta.description, transportKind: server.meta.transport.kind, toolCount: server.tools.size, tools: [...server.tools.entries()].map(([key, def]) => ({ name: key, description: def.description, })), resources: [], })), }; } /** Look up a tool by registry key (filename) or by original MCP name (with fuzzy match). */ export function findToolInRegistry( registry: Registry, serverName: string, toolKey: string, ): { tool: ToolDefinition; key: string } | null { const server = registry.servers.get(serverName); if (!server) return null; // Exact key match. const exact = server.tools.get(toolKey); if (exact) return { tool: exact, key: toolKey }; // Slugified key match (read-file ≈ read_file). const slug = slugifyToolName(toolKey); const bySlug = server.tools.get(slug); if (bySlug) return { tool: bySlug, key: slug }; // Match by original MCP name. for (const [key, def] of server.tools) { if (def.name === toolKey) return { tool: def, key }; } // Fuzzy match on hyphens/underscores. const normalized = toolKey.replace(/-/g, "_"); for (const [key, def] of server.tools) { if (def.name.replace(/-/g, "_") === normalized || key.replace(/-/g, "_") === normalized) { return { tool: def, key }; } } return null; } /** List all server names in the registry. */ export function listServerNames(registry: Registry): string[] { return [...registry.servers.keys()]; } /** List all tool keys for a server. */ export function listToolKeys(registry: Registry, serverName: string): string[] { return [...(registry.servers.get(serverName)?.tools.keys() ?? [])]; }