#!/usr/bin/env node
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 { z } from "zod";

// ============================================
// CONFIGURATION - Customize for each MCP
// ============================================
const MCP_NAME = "template";
const MCP_VERSION = "1.0.0";
const API_BASE_URL = "https://api.example.com";

// ============================================
// API CLIENT
// ============================================
class APIClient {
  private apiKey: string;
  private baseUrl: string;

  constructor(apiKey: string) {
    this.apiKey = apiKey;
    this.baseUrl = API_BASE_URL;
  }

  async request(endpoint: string, options: RequestInit = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const response = await fetch(url, {
      ...options,
      headers: {
        "Authorization": `Bearer ${this.apiKey}`,
        "Content-Type": "application/json",
        ...options.headers,
      },
    });

    if (!response.ok) {
      throw new Error(`API error: ${response.status} ${response.statusText}`);
    }

    return response.json();
  }

  async get(endpoint: string) {
    return this.request(endpoint, { method: "GET" });
  }

  async post(endpoint: string, data: any) {
    return this.request(endpoint, {
      method: "POST",
      body: JSON.stringify(data),
    });
  }

  async put(endpoint: string, data: any) {
    return this.request(endpoint, {
      method: "PUT",
      body: JSON.stringify(data),
    });
  }

  async delete(endpoint: string) {
    return this.request(endpoint, { method: "DELETE" });
  }
}

// ============================================
// TOOL DEFINITIONS - Customize for each MCP
// ============================================
const tools = [
  {
    name: "list_items",
    description: "List all items",
    inputSchema: {
      type: "object" as const,
      properties: {
        limit: { type: "number", description: "Max items to return" },
        offset: { type: "number", description: "Pagination offset" },
      },
    },
  },
  {
    name: "get_item",
    description: "Get a specific item by ID",
    inputSchema: {
      type: "object" as const,
      properties: {
        id: { type: "string", description: "Item ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "create_item",
    description: "Create a new item",
    inputSchema: {
      type: "object" as const,
      properties: {
        name: { type: "string", description: "Item name" },
        data: { type: "object", description: "Item data" },
      },
      required: ["name"],
    },
  },
  {
    name: "update_item",
    description: "Update an existing item",
    inputSchema: {
      type: "object" as const,
      properties: {
        id: { type: "string", description: "Item ID" },
        data: { type: "object", description: "Updated data" },
      },
      required: ["id", "data"],
    },
  },
  {
    name: "delete_item",
    description: "Delete an item",
    inputSchema: {
      type: "object" as const,
      properties: {
        id: { type: "string", description: "Item ID" },
      },
      required: ["id"],
    },
  },
];

// ============================================
// TOOL HANDLERS - Customize for each MCP
// ============================================
async function handleTool(client: APIClient, name: string, args: any) {
  switch (name) {
    case "list_items": {
      const { limit = 50, offset = 0 } = args;
      return await client.get(`/items?limit=${limit}&offset=${offset}`);
    }
    case "get_item": {
      const { id } = args;
      return await client.get(`/items/${id}`);
    }
    case "create_item": {
      const { name, data = {} } = args;
      return await client.post("/items", { name, ...data });
    }
    case "update_item": {
      const { id, data } = args;
      return await client.put(`/items/${id}`, data);
    }
    case "delete_item": {
      const { id } = args;
      return await client.delete(`/items/${id}`);
    }
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
}

// ============================================
// SERVER SETUP
// ============================================
async function main() {
  const apiKey = process.env.API_KEY;
  if (!apiKey) {
    console.error("Error: API_KEY environment variable required");
    process.exit(1);
  }

  const client = new APIClient(apiKey);

  const server = new Server(
    { name: `${MCP_NAME}-mcp`, version: MCP_VERSION },
    { capabilities: { tools: {} } }
  );

  // List available tools
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools,
  }));

  // Handle tool calls
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;
    
    try {
      const result = await handleTool(client, name, args || {});
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
      };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return {
        content: [{ type: "text", text: `Error: ${message}` }],
        isError: true,
      };
    }
  });

  // Start server
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error(`${MCP_NAME} MCP server running on stdio`);
}

main().catch(console.error);
