"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var server_exports = {};
__export(server_exports, {
  MCPServer: () => MCPServer
});
module.exports = __toCommonJS(server_exports);
var import__ = __toESM(require("../index"));
var import_transport = require("./transport");
var import_tools = require("./tools");
const SERVER_INFO = { name: "kirograph", version: "0.1.0" };
const PROTOCOL_VERSION = "2024-11-05";
class MCPServer {
  constructor(projectPath) {
    this.transport = new import_transport.StdioTransport();
    this.cg = null;
    this.projectPath = projectPath ?? null;
    this.toolHandler = new import_tools.ToolHandler(null);
  }
  async start() {
    this.transport.start(this.handleMessage.bind(this));
    process.on("SIGINT", () => this.stop());
    process.on("SIGTERM", () => this.stop());
    process.stdin.on("end", () => this.stop());
    process.stdin.on("close", () => this.stop());
  }
  async tryInit(projectPath) {
    const root = (0, import__.findNearestKiroGraphRoot)(projectPath);
    if (!root) {
      this.projectPath = projectPath;
      return;
    }
    this.projectPath = root;
    try {
      this.cg = await import__.default.open(root);
      this.toolHandler.setDefaultKiroGraph(this.cg);
    } catch (err) {
      process.stderr.write(`[KiroGraph MCP] Failed to open ${root}: ${err}
`);
    }
  }
  async handleMessage(msg) {
    const req = msg;
    switch (req.method) {
      case "initialize": {
        const rootUri = req.params?.rootUri ?? req.params?.workspaceFolders?.[0]?.uri;
        if (rootUri) {
          const p = rootUri.startsWith("file://") ? decodeURIComponent(rootUri.replace(/^file:\/\/\/?/, "")) : rootUri;
          await this.tryInit(p);
        } else if (this.projectPath) {
          await this.tryInit(this.projectPath);
        }
        return {
          protocolVersion: PROTOCOL_VERSION,
          capabilities: { tools: {} },
          serverInfo: SERVER_INFO
        };
      }
      case "tools/list":
        return { tools: import_tools.tools };
      case "tools/call": {
        const { name, arguments: args = {} } = req.params ?? {};
        try {
          return await this.toolHandler.handle(name, args);
        } catch (err) {
          return {
            content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
            isError: true
          };
        }
      }
      case "notifications/initialized":
      case "ping":
        return {};
      default:
        this.transport.sendError(req.id, import_transport.ErrorCodes.MethodNotFound, `Unknown method: ${req.method}`);
        return void 0;
    }
  }
  stop() {
    this.cg?.close();
    this.toolHandler.closeAll();
    process.exit(0);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MCPServer
});
//# sourceMappingURL=server.js.map
