#!/usr/bin/env node

// src/server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import fs2 from "fs/promises";
import path2 from "path";
import { fileURLToPath as fileURLToPath2 } from "url";

// src/source-reader.ts
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
var __filename = fileURLToPath(import.meta.url);
var __dirname = path.dirname(__filename);
function getProjectRoot() {
  return path.resolve(__dirname, "..");
}
function getSourceRoot() {
  if (process.env.CC_SOURCE_ROOT) {
    return path.resolve(process.env.CC_SOURCE_ROOT);
  }
  return path.join(getProjectRoot(), "claude-code-main", "src");
}
function getModuleNotesRoot() {
  if (process.env.MODULE_NOTES_ROOT) {
    return path.resolve(process.env.MODULE_NOTES_ROOT);
  }
  return path.join(getProjectRoot(), "claude-code-main", "MODULE_NOTES");
}
var MAX_LINES_PER_READ = 500;
function validatePath(filePath, root) {
  const resolved = path.resolve(root, filePath);
  if (!resolved.startsWith(root)) {
    throw new Error(`Path escapes source root: ${filePath}`);
  }
  return resolved;
}
function normalizeSrcRelativePath(filePath) {
  let p = filePath.trim();
  while (p.startsWith("/")) p = p.slice(1);
  if (p.startsWith("src/")) p = p.slice(4);
  return p;
}
async function readSourceCode(filePath, startLine, endLine) {
  const root = getSourceRoot();
  const normalized = normalizeSrcRelativePath(filePath);
  const absolutePath = validatePath(normalized, root);
  try {
    await fs.access(absolutePath);
  } catch {
    throw new Error(`File not found: ${filePath} (resolved to src/${normalized})`);
  }
  const content = await fs.readFile(absolutePath, "utf-8");
  const lines = content.split("\n");
  const totalLines = lines.length;
  const start = Math.max(1, startLine ?? 1);
  const end = Math.min(totalLines, endLine ?? Math.min(totalLines, start + MAX_LINES_PER_READ - 1));
  const actualEnd = Math.min(end, start + MAX_LINES_PER_READ - 1);
  const selectedLines = lines.slice(start - 1, actualEnd);
  const numberedContent = selectedLines.map((line, i) => `${(start + i).toString().padStart(4)}\u2502${line}`).join("\n");
  return {
    filePath: normalized,
    content: numberedContent,
    startLine: start,
    endLine: actualEnd,
    totalLines
  };
}
async function readModuleNotes(relativePath) {
  const root = getModuleNotesRoot();
  const absolutePath = validatePath(relativePath, root);
  try {
    await fs.access(absolutePath);
  } catch {
    throw new Error(`Module notes file not found: ${relativePath}`);
  }
  return fs.readFile(absolutePath, "utf-8");
}
async function readModuleNotesSection(relativePath, startLine, endLine) {
  const content = await readModuleNotes(relativePath);
  const lines = content.split("\n");
  return lines.slice(startLine - 1, endLine).join("\n");
}
async function listSourceFiles(dirPath = "") {
  const root = getSourceRoot();
  const normalized = normalizeSrcRelativePath(dirPath);
  const absolutePath = validatePath(normalized, root);
  try {
    const entries = await fs.readdir(absolutePath, { withFileTypes: true });
    return entries.map((e) => {
      const rel = path.relative(root, path.join(absolutePath, e.name));
      return e.isDirectory() ? rel + "/" : rel;
    });
  } catch {
    throw new Error(`Directory not found: ${dirPath}`);
  }
}

// src/retrieval/engine.ts
var RetrievalEngine = class {
  registry;
  keywordIndex;
  concernMap;
  moduleMap;
  constructor(registry, keywordIndex, concernMap) {
    this.registry = registry;
    this.keywordIndex = keywordIndex;
    this.concernMap = concernMap;
    this.moduleMap = /* @__PURE__ */ new Map();
    for (const mod of registry.modules) {
      this.moduleMap.set(mod.id, mod);
    }
  }
  /** Get a module entry by ID */
  getModule(id) {
    return this.moduleMap.get(id);
  }
  /** Get all modules */
  getAllModules() {
    return this.registry.modules;
  }
  /** Get modules by category */
  getModulesByCategory(category) {
    return this.registry.modules.filter((m) => m.category === category);
  }
  /**
   * Search for relevant modules given a query string.
   * Returns modules ranked by relevance.
   */
  searchModules(query, filterModuleIds) {
    const queryTokens = this.tokenize(query);
    const scores = /* @__PURE__ */ new Map();
    for (const token of queryTokens) {
      const moduleIds = this.keywordIndex[token] || [];
      for (const id of moduleIds) {
        if (filterModuleIds && !filterModuleIds.includes(id)) continue;
        scores.set(id, (scores.get(id) || 0) + 2);
      }
      const concernModules = this.concernMap[token] || [];
      for (const id of concernModules) {
        if (filterModuleIds && !filterModuleIds.includes(id)) continue;
        scores.set(id, (scores.get(id) || 0) + 3);
      }
      for (const [keyword, ids] of Object.entries(this.keywordIndex)) {
        if (keyword.includes(token) || token.includes(keyword)) {
          for (const id of ids) {
            if (filterModuleIds && !filterModuleIds.includes(id)) continue;
            scores.set(id, (scores.get(id) || 0) + 1);
          }
        }
      }
    }
    const ranked = [...scores.entries()].sort((a, b) => b[1] - a[1]).map(([id]) => this.moduleMap.get(id)).filter(Boolean);
    return ranked;
  }
  /**
   * Query architecture at a given depth.
   */
  async query(queryStr, depth, filterModuleIds) {
    const modules = this.searchModules(queryStr, filterModuleIds);
    if (modules.length === 0) {
      return { modules: [], relatedModules: [] };
    }
    const limit = depth === "brief" ? 5 : depth === "standard" ? 3 : 2;
    const topModules = modules.slice(0, limit);
    const matches = [];
    const relatedModuleIds = /* @__PURE__ */ new Set();
    for (const mod of topModules) {
      const content = await this.getModuleContent(mod, depth);
      matches.push({
        moduleId: mod.id,
        title: mod.title,
        relevance: 1,
        // Normalized later if needed
        content
      });
      const relationSections = mod.sections.filter((s) => s.type === "relation");
      if (relationSections.length > 0) {
        for (const otherMod of this.registry.modules) {
          if (otherMod.id !== mod.id && !topModules.includes(otherMod)) {
            relatedModuleIds.add(otherMod.id);
          }
        }
      }
    }
    const relatedModules = [...relatedModuleIds].slice(0, 5);
    return { modules: matches, relatedModules };
  }
  /**
   * Get module content at the specified depth.
   */
  async getModuleContent(mod, depth) {
    switch (depth) {
      case "brief":
        return this.getModuleBrief(mod);
      case "standard":
        return this.getModuleStandard(mod);
      case "deep":
        return this.getModuleDeep(mod);
      default:
        return this.getModuleBrief(mod);
    }
  }
  /**
   * Brief: Module title + responsibility section (first section)
   */
  async getModuleBrief(mod) {
    const responsibilitySections = mod.sections.filter(
      (s) => s.type === "responsibility" || s.level === 2
    );
    if (responsibilitySections.length > 0) {
      const section = responsibilitySections[0];
      const content2 = await readModuleNotesSection(mod.sourceFile, section.startLine, section.endLine);
      return `# ${mod.id}: ${mod.title}

${content2}`;
    }
    const content = await readModuleNotesSection(mod.sourceFile, 1, 30);
    return `# ${mod.id}: ${mod.title}

${content}`;
  }
  /**
   * Standard: Architecture + decision titles + principles list
   */
  async getModuleStandard(mod) {
    const parts = [`# ${mod.id}: ${mod.title}
`];
    const archSections = mod.sections.filter(
      (s) => s.type === "architecture" || s.type === "responsibility"
    );
    for (const section of archSections.slice(0, 2)) {
      const content = await readModuleNotesSection(mod.sourceFile, section.startLine, section.endLine);
      parts.push(content);
    }
    const decisionSections = mod.sections.filter((s) => s.type === "decision");
    if (decisionSections.length > 0) {
      parts.push("\n## Key Design Decisions\n");
      for (const section of decisionSections) {
        const content = await readModuleNotesSection(
          mod.sourceFile,
          section.startLine,
          Math.min(section.endLine, section.startLine + 50)
        );
        parts.push(content);
      }
    }
    const principleSections = mod.sections.filter((s) => s.type === "principle" || s.type === "pattern");
    if (principleSections.length > 0) {
      for (const section of principleSections.slice(0, 1)) {
        const content = await readModuleNotesSection(mod.sourceFile, section.startLine, section.endLine);
        parts.push(content);
      }
    }
    return parts.join("\n");
  }
  /**
   * Deep: Full module content
   */
  async getModuleDeep(mod) {
    const content = await readModuleNotes(mod.sourceFile);
    return `# ${mod.id}: ${mod.title}

${content}`;
  }
  /**
   * Get a specific section type from a module.
   */
  async getModuleSection(moduleId, sectionType) {
    const mod = this.moduleMap.get(moduleId);
    if (!mod) return null;
    const typeMap = {
      responsibility: ["responsibility"],
      architecture: ["architecture"],
      decisions: ["decision"],
      principles: ["principle", "pattern"],
      relations: ["relation"]
    };
    const targetTypes = typeMap[sectionType] || [];
    const sections = mod.sections.filter((s) => targetTypes.includes(s.type));
    if (sections.length === 0) return null;
    const parts = [];
    for (const section of sections) {
      const content = await readModuleNotesSection(mod.sourceFile, section.startLine, section.endLine);
      parts.push(content);
    }
    return parts.join("\n\n");
  }
  /**
   * Search for reusable patterns across all modules.
   * @param keywords  Optional keyword filter
   * @param moduleId  Optional restrict to a single module
   * @param maxPerSection Optional per-section character cap (default 800)
   * @param maxSections   Optional total section cap (default 12)
   */
  async searchPatterns(keywords, moduleId, maxPerSection = 800, maxSections = 12) {
    const results = [];
    for (const mod of this.registry.modules) {
      if (moduleId && mod.id !== moduleId) continue;
      const patternSections = mod.sections.filter(
        (s) => s.type === "principle" || s.type === "pattern"
      );
      if (patternSections.length === 0) continue;
      if (keywords && keywords.length > 0) {
        const modKeywords = mod.keywords.map((k) => k.toLowerCase());
        const hasMatch = keywords.some(
          (kw) => modKeywords.some((mk) => mk.includes(kw.toLowerCase()) || kw.toLowerCase().includes(mk))
        );
        if (!hasMatch) continue;
      }
      for (const section of patternSections) {
        if (results.length >= maxSections) break;
        const raw = await readModuleNotesSection(mod.sourceFile, section.startLine, section.endLine);
        const truncated = raw.length > maxPerSection;
        const body = truncated ? raw.slice(0, maxPerSection) + "\n\n\u2026 [truncated; call get_module(" + mod.id + ', section="principles") for full content]' : raw;
        results.push({
          moduleId: mod.id,
          content: `[${mod.id}: ${mod.title}]
${body}`,
          truncated
        });
      }
      if (results.length >= maxSections) break;
    }
    return results;
  }
  /**
   * Trace a concern across all modules.
   *
   * Strategy: scan every module's MODULE_NOTES body for line-level matches.
   * We deliberately do NOT pre-filter by keywords/concerns/title because those fields
   * may not lexically include the concern token even when the body discusses it
   * extensively (e.g. M06 discusses 'prompt cache' in its body but doesn't list it
   * as a keyword).
   */
  async traceConcern(concern) {
    const tokens = this.tokenize(concern);
    if (tokens.length === 0) return [];
    const results = [];
    for (const mod of this.registry.modules) {
      try {
        const content = await readModuleNotes(mod.sourceFile);
        const lines = content.split("\n");
        const matchingLines = [];
        for (let i = 0; i < lines.length; i++) {
          const lineLower = lines[i].toLowerCase();
          if (tokens.every((t) => lineLower.includes(t)) || tokens.some((t) => lineLower.includes(t) && t.length >= 4)) {
            matchingLines.push(i);
          }
        }
        if (matchingLines.length === 0) continue;
        const excerptLines = [];
        const seen = /* @__PURE__ */ new Set();
        for (const lineIdx of matchingLines.slice(0, 5)) {
          const start = Math.max(0, lineIdx - 1);
          const end = Math.min(lines.length, lineIdx + 3);
          for (let i = start; i < end; i++) {
            if (!seen.has(i)) {
              seen.add(i);
              excerptLines.push(lines[i]);
            }
          }
          excerptLines.push("...");
        }
        results.push({
          moduleId: mod.id,
          title: mod.title,
          excerpt: excerptLines.join("\n").slice(0, 2e3),
          hits: matchingLines.length
        });
      } catch {
      }
    }
    results.sort((a, b) => b.hits - a.hits);
    return results.map(({ moduleId, title, excerpt }) => ({ moduleId, title, excerpt }));
  }
  /**
   * Tokenize a query string into searchable tokens.
   */
  tokenize(query) {
    return query.toLowerCase().replace(/[_\-\/\.]/g, " ").split(/\s+/).filter((t) => t.length >= 2).map((t) => t.trim());
  }
};

// src/tools/queryArchitecture.ts
var queryArchitectureToolDef = {
  name: "query_architecture",
  description: "Search the Claude Code architecture knowledge base. Returns relevant module analysis at the requested depth level. Use this to understand how specific features, patterns, or subsystems are implemented.",
  inputSchema: {
    type: "object",
    properties: {
      query: {
        type: "string",
        description: "Natural language query about Claude Code architecture (e.g., 'how does context trimming work', 'permission system', 'streaming tool execution')"
      },
      depth: {
        type: "string",
        enum: ["brief", "standard", "deep"],
        description: "Level of detail: 'brief' = module overview (fast), 'standard' = architecture + key decisions, 'deep' = full module content"
      },
      modules: {
        type: "array",
        items: { type: "string" },
        description: "Optional: limit search to specific module IDs (e.g., ['M02', 'M06']). If omitted, searches all modules."
      }
    },
    required: ["query"]
  }
};
async function handleQueryArchitecture(engine, args) {
  const depth = args.depth || "standard";
  const result = await engine.query(args.query, depth, args.modules);
  if (result.modules.length === 0) {
    return `No modules found matching query: "${args.query}"

Tip: Try broader terms or use 'list_modules' to see available modules.`;
  }
  const parts = [];
  for (const match of result.modules) {
    parts.push(match.content);
    parts.push("\n---\n");
  }
  if (result.relatedModules.length > 0) {
    parts.push(`
**Related modules**: ${result.relatedModules.join(", ")}`);
  }
  return parts.join("\n");
}

// src/tools/getModule.ts
var getModuleToolDef = {
  name: "get_module",
  description: "Get detailed content from a specific module. Can optionally return only a specific section type (responsibility, architecture, decisions, principles, or relations).",
  inputSchema: {
    type: "object",
    properties: {
      module_id: {
        type: "string",
        description: "Module ID (e.g., 'M01', 'M02', ..., 'M22', 'SUPP-AgentSummary', 'SUPP-SessionMemory', etc.)"
      },
      section: {
        type: "string",
        enum: ["responsibility", "architecture", "decisions", "principles", "relations"],
        description: "Optional: return only a specific section type. If omitted, returns the full module."
      }
    },
    required: ["module_id"]
  }
};
async function handleGetModule(engine, args) {
  const mod = engine.getModule(args.module_id);
  if (!mod) {
    const allIds = engine.getAllModules().map((m) => m.id).join(", ");
    return `Module not found: "${args.module_id}"

Available modules: ${allIds}`;
  }
  if (args.section) {
    const sectionType = args.section;
    const content2 = await engine.getModuleSection(args.module_id, sectionType);
    if (!content2) {
      return `No "${args.section}" section found in module ${args.module_id} (${mod.title}).

Available section types in this module: ${mod.sections.map((s) => s.type).filter((v, i, a) => a.indexOf(v) === i).join(", ")}`;
    }
    return `# ${mod.id}: ${mod.title} \u2014 ${args.section}

${content2}`;
  }
  const content = await engine.getModuleContent(mod, "deep");
  return content;
}

// src/tools/getSourceCode.ts
var getSourceCodeToolDef = {
  name: "get_source_code",
  description: "Read actual Claude Code source code files. Use this to see implementation details referenced in module analysis. Supports line-range extraction. Returns at most 500 lines per call.",
  inputSchema: {
    type: "object",
    properties: {
      file_path: {
        type: "string",
        description: "Relative path within src/ (e.g., 'entrypoints/cli.tsx', 'services/api/claude.ts'). A leading 'src/' prefix is also accepted and will be stripped automatically."
      },
      start_line: {
        type: "number",
        description: "Optional: starting line number (1-based). Defaults to 1."
      },
      end_line: {
        type: "number",
        description: "Optional: ending line number (1-based). Defaults to start_line + 499."
      }
    },
    required: ["file_path"]
  }
};
async function handleGetSourceCode(args) {
  let displayPath = args.file_path.trim();
  while (displayPath.startsWith("/")) displayPath = displayPath.slice(1);
  if (displayPath.startsWith("src/")) displayPath = displayPath.slice(4);
  if (args.file_path.endsWith("/") || args.file_path === "") {
    try {
      const files = await listSourceFiles(args.file_path);
      return `## Directory: src/${displayPath}

${files.map((f) => `- ${f}`).join("\n")}`;
    } catch (e) {
      return `Error listing directory: ${e.message}`;
    }
  }
  try {
    const result = await readSourceCode(args.file_path, args.start_line, args.end_line);
    const header = `## src/${result.filePath} (lines ${result.startLine}-${result.endLine} of ${result.totalLines})

`;
    return header + "```\n" + result.content + "\n```";
  } catch (e) {
    return `Error: ${e.message}`;
  }
}

// src/tools/listModules.ts
var listModulesToolDef = {
  name: "list_modules",
  description: "List all available architecture modules. Returns module IDs, titles, and key concerns for each module. Use this to discover what knowledge is available before querying specific modules.",
  inputSchema: {
    type: "object",
    properties: {
      category: {
        type: "string",
        enum: ["core", "supplement"],
        description: "Optional: filter by category. 'core' = M01-M22 main modules, 'supplement' = SUPP-* deep-dive supplements."
      }
    },
    required: []
  }
};
function handleListModules(engine, args) {
  const modules = args.category ? engine.getModulesByCategory(args.category) : engine.getAllModules();
  const lines = ["# Available Architecture Modules\n"];
  if (!args.category || args.category === "core") {
    lines.push("## Core Modules (M01-M22)\n");
    const coreModules = modules.filter((m) => m.category === "core");
    for (const mod of coreModules) {
      lines.push(`- **${mod.id}**: ${mod.title} \u2014 [${mod.concerns.slice(0, 4).join(", ")}]`);
    }
    lines.push("");
  }
  if (!args.category || args.category === "supplement") {
    lines.push("## Supplement Deep-Dives\n");
    const suppModules = modules.filter((m) => m.category === "supplement");
    for (const mod of suppModules) {
      lines.push(`- **${mod.id}**: ${mod.title} \u2014 [${mod.concerns.slice(0, 3).join(", ")}]`);
    }
    lines.push("");
  }
  lines.push(`
Total: ${modules.length} modules. Use \`get_module\` with a module ID to read its content.`);
  return lines.join("\n");
}

// src/tools/searchPatterns.ts
var searchPatternsToolDef = {
  name: "search_patterns",
  description: `Search for reusable design patterns and principles extracted from Claude Code's architecture. Returns 'directly-reusable' patterns that you can adapt for your own Agent implementation. Output is paginated: each section is capped (default 800 chars) and total sections capped (default 12). Use module_id to focus, or get_module(section="principles") for the full text of a specific module.`,
  inputSchema: {
    type: "object",
    properties: {
      pattern_type: {
        type: "string",
        enum: ["reusable", "anti-pattern", "all"],
        description: "Type of patterns to search: 'reusable' = patterns you can copy, 'anti-pattern' = patterns to avoid, 'all' = both."
      },
      keywords: {
        type: "array",
        items: { type: "string" },
        description: "Optional: filter patterns by keywords (e.g., ['cache', 'retry', 'streaming'])."
      },
      module_id: {
        type: "string",
        description: "Optional: restrict to a single module (e.g., 'M05'). Useful when you already know the relevant module."
      },
      max_per_section: {
        type: "number",
        description: "Optional: per-section character cap (default 800). Truncated sections include a hint to fetch full content via get_module."
      },
      max_sections: {
        type: "number",
        description: "Optional: maximum total number of sections to return (default 12)."
      }
    },
    required: []
  }
};
async function handleSearchPatterns(engine, args) {
  const results = await engine.searchPatterns(
    args.keywords,
    args.module_id,
    args.max_per_section ?? 800,
    args.max_sections ?? 12
  );
  if (results.length === 0) {
    return "No patterns found matching the criteria.\n\nTip: Try broader keywords, omit the keywords filter, or remove module_id to see all available patterns.";
  }
  const parts = ["# Reusable Design Patterns\n"];
  for (const result of results) {
    parts.push(`## From ${result.moduleId}${result.truncated ? " (truncated)" : ""}
`);
    parts.push(result.content);
    parts.push("\n---\n");
  }
  const truncatedCount = results.filter((r) => r.truncated).length;
  parts.push(
    `
Returned ${results.length} pattern section(s) across ${new Set(results.map((r) => r.moduleId)).size} module(s)` + (truncatedCount > 0 ? `. ${truncatedCount} were truncated \u2014 use get_module(<id>, section="principles") for full content.` : ".")
  );
  return parts.join("\n");
}

// src/tools/traceConcern.ts
var traceConcernToolDef = {
  name: "trace_concern",
  description: "Trace a specific architectural concern across all modules. Shows how one concept (e.g., 'prompt cache', 'error recovery', 'streaming') is handled at different layers of Claude Code's architecture.",
  inputSchema: {
    type: "object",
    properties: {
      concern: {
        type: "string",
        description: "The architectural concern to trace (e.g., 'prompt cache', 'error recovery', 'abort signal', 'streaming', 'retry')."
      }
    },
    required: ["concern"]
  }
};
async function handleTraceConcern(engine, args) {
  const results = await engine.traceConcern(args.concern);
  if (results.length === 0) {
    return `No modules found mentioning "${args.concern}".

Tip: Try different terms or use 'query_architecture' for broader searches.`;
  }
  const parts = [`# Cross-Module Trace: "${args.concern}"
`];
  parts.push(`Found in ${results.length} module(s):
`);
  for (const result of results) {
    parts.push(`## ${result.moduleId}: ${result.title}
`);
    parts.push(result.excerpt);
    parts.push("\n---\n");
  }
  return parts.join("\n");
}

// src/server.ts
var __filename3 = fileURLToPath2(import.meta.url);
var __dirname3 = path2.dirname(__filename3);
var PROJECT_ROOT = path2.resolve(__dirname3, "..");
var KNOWLEDGE_DIR = path2.join(PROJECT_ROOT, "knowledge");
async function loadKnowledgeBase() {
  const registryPath = path2.join(KNOWLEDGE_DIR, "module-registry.json");
  const keywordPath = path2.join(KNOWLEDGE_DIR, "keyword-index.json");
  const concernPath = path2.join(KNOWLEDGE_DIR, "concern-map.json");
  try {
    const [registryRaw, keywordRaw, concernRaw] = await Promise.all([
      fs2.readFile(registryPath, "utf-8"),
      fs2.readFile(keywordPath, "utf-8"),
      fs2.readFile(concernPath, "utf-8")
    ]);
    return {
      registry: JSON.parse(registryRaw),
      keywordIndex: JSON.parse(keywordRaw),
      concernMap: JSON.parse(concernRaw)
    };
  } catch (err) {
    console.error(`[agent-architecture-oracle] Failed to load knowledge base from ${KNOWLEDGE_DIR}`);
    console.error(`  Run 'pnpm build:index' first to generate the index.`);
    console.error(`  Error: ${err}`);
    return {
      registry: { version: "0.0.0", lastUpdated: (/* @__PURE__ */ new Date()).toISOString(), modules: [] },
      keywordIndex: {},
      concernMap: {}
    };
  }
}
async function main() {
  console.error("[agent-architecture-oracle] Starting MCP server...");
  const { registry, keywordIndex, concernMap } = await loadKnowledgeBase();
  const engine = new RetrievalEngine(registry, keywordIndex, concernMap);
  console.error(
    `[agent-architecture-oracle] Loaded ${registry.modules.length} modules, ${Object.keys(keywordIndex).length} keywords, ${Object.keys(concernMap).length} concerns`
  );
  const server = new Server(
    {
      name: "agent-architecture-oracle",
      version: "2.0.0"
    },
    {
      capabilities: {
        tools: {}
      }
    }
  );
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools: [
      queryArchitectureToolDef,
      getModuleToolDef,
      getSourceCodeToolDef,
      listModulesToolDef,
      searchPatternsToolDef,
      traceConcernToolDef
    ]
  }));
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;
    try {
      let result;
      switch (name) {
        case "query_architecture":
          result = await handleQueryArchitecture(engine, args);
          break;
        case "get_module":
          result = await handleGetModule(engine, args);
          break;
        case "get_source_code":
          result = await handleGetSourceCode(args);
          break;
        case "list_modules":
          result = handleListModules(engine, args);
          break;
        case "search_patterns":
          result = await handleSearchPatterns(engine, args);
          break;
        case "trace_concern":
          result = await handleTraceConcern(engine, args);
          break;
        default:
          result = `Unknown tool: ${name}. Use list_modules to see available tools.`;
      }
      return {
        content: [{ type: "text", text: result }]
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text", text: `Error: ${errMsg}` }],
        isError: true
      };
    }
  });
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("[agent-architecture-oracle] Server connected via stdio");
}
main().catch((err) => {
  console.error("[agent-architecture-oracle] Fatal error:", err);
  process.exit(1);
});
