#!/usr/bin/env node
import { createRequire } from "module"; const require = createRequire(import.meta.url);


// src/mcp/bridge-access/bridge-access-post.ts
async function bridgeAccessPost(port, path, body) {
  const res = await fetch(`http://127.0.0.1:${port}${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
  const json = await res.json();
  if (!json.ok) {
    throw new Error("error" in json && json.error ? json.error : "Bridge access request failed");
  }
  return json.data;
}

// src/mcp/bridge-access/client.ts
function createBridgeAccessClient(port) {
  return {
    listTools: () => bridgeAccessPost(port, "/tools/list", {}),
    callTool: (sessionId, name, args) => bridgeAccessPost(port, "/tools/call", { sessionId, name, args })
  };
}

// src/mcp/bridge-mcp-constants.ts
var BRIDGE_MCP_SERVER_NAME = "buildautomaton-bridge";

// src/mcp/parse-bridge-access-port.ts
function parseBridgeAccessPortFromArgv(argv = process.argv) {
  const raw = argv[2]?.trim() ?? "";
  const port = Number.parseInt(raw, 10);
  if (!Number.isFinite(port) || port <= 0) {
    throw new Error(`Invalid bridge access port argument: ${raw || "(missing)"}`);
  }
  return port;
}

// src/mcp/parse-mcp-session-id.ts
function parseMcpSessionId(params, args) {
  const fromParams = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
  if (fromParams) return fromParams;
  const meta = params._meta;
  if (meta && typeof meta === "object" && !Array.isArray(meta)) {
    const fromMeta = typeof meta.sessionId === "string" ? meta.sessionId.trim() : "";
    if (fromMeta) return fromMeta;
  }
  if (args) {
    const fromArgs = typeof args.sessionId === "string" ? args.sessionId.trim() : "";
    if (fromArgs) return fromArgs;
  }
  return null;
}
function requireMcpSessionId(params, args) {
  const sessionId = parseMcpSessionId(params, args);
  if (!sessionId) {
    throw new Error("sessionId is required in MCP params or tool arguments");
  }
  return sessionId;
}
function stripSessionIdFromToolArgs(args) {
  if (!("sessionId" in args)) return args;
  const { sessionId: _ignored, ...rest } = args;
  return rest;
}

// src/mcp/stdio-mcp-server.ts
import * as readline from "node:readline";
var MCP_PROTOCOL_VERSION = "2024-11-05";
function writeMessage(msg) {
  process.stdout.write(`${JSON.stringify(msg)}
`);
}
function jsonRpcError(id, code, message) {
  writeMessage({ jsonrpc: "2.0", id, error: { code, message } });
}
function jsonRpcResult(id, result) {
  writeMessage({ jsonrpc: "2.0", id, result });
}
async function runStdioMcpServer(options) {
  const rl = readline.createInterface({ input: process.stdin, terminal: false });
  let initialized = false;
  for await (const line of rl) {
    const trimmed = line.trim();
    if (!trimmed) continue;
    let msg;
    try {
      msg = JSON.parse(trimmed);
    } catch {
      continue;
    }
    const method = typeof msg.method === "string" ? msg.method : "";
    const id = msg.id;
    const params = msg.params && typeof msg.params === "object" && !Array.isArray(msg.params) ? msg.params : {};
    if (method === "notifications/initialized" || method === "initialized") {
      initialized = true;
      continue;
    }
    if (id === void 0 && method.startsWith("notifications/")) {
      continue;
    }
    try {
      if (method === "initialize") {
        initialized = true;
        jsonRpcResult(id, {
          protocolVersion: MCP_PROTOCOL_VERSION,
          capabilities: { tools: {} },
          serverInfo: { name: options.serverName, version: options.serverVersion }
        });
        continue;
      }
      if (!initialized && method !== "initialize") {
        jsonRpcError(id, -32002, "Server not initialized");
        continue;
      }
      if (method === "tools/list") {
        const tools = await options.listTools(params);
        jsonRpcResult(id, { tools });
        continue;
      }
      if (method === "tools/call") {
        const name = typeof params.name === "string" ? params.name : "";
        const args = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments : {};
        if (!name) {
          jsonRpcError(id, -32602, "tools/call requires name");
          continue;
        }
        const result = await options.callTool(name, args, params);
        jsonRpcResult(id, result);
        continue;
      }
      if (id !== void 0) {
        jsonRpcError(id, -32601, `Method not found: ${method}`);
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      if (id !== void 0) {
        jsonRpcResult(id, {
          content: [{ type: "text", text: message }],
          isError: true
        });
      }
    }
  }
}

// src/mcp/bridge-mcp-server.ts
var bridgeAccessPort = parseBridgeAccessPortFromArgv();
var bridgeAccess = createBridgeAccessClient(bridgeAccessPort);
void runStdioMcpServer({
  serverName: BRIDGE_MCP_SERVER_NAME,
  serverVersion: "0.1.0",
  listTools: () => bridgeAccess.listTools(),
  callTool: (name, args, params) => {
    const sessionId = requireMcpSessionId(params, args);
    const toolArgs = stripSessionIdFromToolArgs(args);
    return bridgeAccess.callTool(sessionId, name, toolArgs);
  }
});
//# sourceMappingURL=bridge-mcp-server.js.map
