import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {tools, narrowToolGroup} from "./tools";
import { logger } from "../../../utils/logger";

async function main(serverName: string, toolGroupsToLoad: string[]) {
  const server = new McpServer(
    {
      name: serverName,
      version: "1.0.0"
    },
    {
      capabilities: {
        tools: {}
      }
    }
  );

  let toolNames = "";
  for (let toolGroup of toolGroupsToLoad) {
    if (narrowToolGroup(toolGroup)) {
      for (let toolSpec of tools[toolGroup]) {
        server.tool(toolSpec.name, toolSpec.description, toolSpec.inputSchema, toolSpec.cb);
        toolNames += toolSpec.name + '\n'
      }
    } else {
      logger.error("Unrecognized toolgroup: ", toolGroup);
    }
  }

  try {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    logger.info(`MCP server connected: ${serverName} with tools: \n${toolNames}`);
  } catch(err) {
    logger.error("Could not connect to mcp server");
    process.exit(1);
  }
}

const name = process.argv[2];
if (!name) {
  console.error("Name not passed");
  process.exit(1);
}
const toolGroupsToLoad = process.argv.slice(3);

main(name, toolGroupsToLoad);