← Files Planets360 AstrologyARCHIVED FILE

src/index.ts

12.2 KB · Nov 3, 2026 · 19:07 UTC

↓ Download file

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { z, type ZodRawShape } from "zod";

const API_BASE_URL = (process.env.PLANETS360_API_BASE_URL ?? "https://ephemeris.gopim.dev").replace(/\/$/, "");
const API_TOKEN = process.env.PLANETS360_API_TOKEN;
const WEBSITE_BASE_URL = "https://planets360.in";

const SERVER_NAME = "planets360-ai-vedic-astrology";
const SERVER_VERSION = "1.0.0";

function buildServer(): McpServer {
  const server = new McpServer({
    name: SERVER_NAME,
    version: SERVER_VERSION,
  });

const geoDateTime = {
  latitude: z.string().describe("Latitude in decimal degrees, -90 to 90."),
  longitude: z.string().describe("Longitude in decimal degrees, -180 to 180."),
  timeZone: z.string().describe("IANA time-zone ID, e.g. Asia/Kolkata."),
  year: z.number().int(),
  month: z.number().int().min(1).max(12),
  day: z.number().int().min(1).max(31),
  hour: z.number().int().min(0).max(23),
  minute: z.number().int().min(0).max(59),
};
const geoYear = {
  latitude: z.string().describe("Latitude in decimal degrees, -90 to 90."),
  longitude: z.string().describe("Longitude in decimal degrees, -180 to 180."),
  timeZone: z.string().describe("IANA time-zone ID, e.g. Asia/Kolkata."),
  year: z.number().int(),
};

function jsonResult(data: unknown) {
  return { content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }] };
}

async function callApi(path: string, body: Record<string, unknown>) {
  if (!API_TOKEN) {
    throw new Error("Planets360 API token is not configured. Set PLANETS360_API_TOKEN in the server environment; do not send the token in chat.");
  }
  const response = await fetch(`${API_BASE_URL}${path}`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "accept": "application/json",
      "authorization": `Bearer ${API_TOKEN}`,
    },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(30_000),
  });
  const text = await response.text();
  let parsed: unknown = text;
  try { parsed = text ? JSON.parse(text) : null; } catch { /* retain text response */ }
  if (!response.ok) {
    const detail = typeof parsed === "object" && parsed !== null ? JSON.stringify(parsed) : String(parsed);
    throw new Error(`Planets360 API returned HTTP ${response.status}: ${detail.slice(0, 1500)}`);
  }
  return parsed;
}

function registerApiTool(name: string, description: string, schema: ZodRawShape, path: string) {
  server.registerTool(name, {
    description: `${description} Justification: read-only tool - it forwards only the supplied fields to the Planets360 calculation API and returns the report; it performs no write actions and stores no data.`,
    inputSchema: schema,
    annotations: {
      title: name,
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: true,
    },
  }, async (args) => {
    try {
      const data = await callApi(path, args as Record<string, unknown>);
      return jsonResult(data);
    } catch (error) {
      return jsonResult({ error: error instanceof Error ? error.message : String(error) });
    }
  });
}

registerApiTool(
  "planets360_panchang_kundli",
  "Get the documented fast Panchang or birth-chart/planetary-position report. Supply the date, time, timezone, and coordinates. The API specification describes this same endpoint for daily Panchang or Kundli use.",
  geoDateTime,
  "/api/v1/panchang-fast",
);
registerApiTool(
  "planets360_planet_transit_range",
  "Get one planet's sign-by-sign transit segments for a year range, including documented retrograde and combustion markers.",
  {
    latitude: geoDateTime.latitude,
    longitude: geoDateTime.longitude,
    timeZone: geoDateTime.timeZone,
    startYear: z.number().int(),
    endYear: z.number().int(),
    planetName: z.enum(["Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu", "Lagna"]),
  },
  "/api/v1/planet-transit-range",
);
registerApiTool(
  "planets360_dasa_bhukti",
  "Get the documented Vimshottari Dasa/Bhukti/Antara timeline for a birth moment and location.",
  geoDateTime,
  "/api/v1/dasa-bhukti",
);
registerApiTool(
  "planets360_chandrashtama_days",
  "Get Chandrashtama days for a year, with location and timezone as required by the API.",
  geoYear,
  "/api/v1/charashamata-days",
);
registerApiTool(
  "planets360_panchapakshi_table",
  "Get the Panchapakshi day/night action table for a specified bird and birth moment.",
  { ...geoDateTime, bird: z.enum(["Peacock", "Crow", "Owl", "Rooster", "Vulture"]) },
  "/api/v1/panchapakshi",
);
registerApiTool(
  "planets360_find_bird_by_birth_info",
  "Resolve the Panchapakshi bird from birth date/time and location.",
  geoDateTime,
  "/api/v1/find-bird-by-birth-info",
);
registerApiTool(
  "planets360_find_bird_by_nakshatra",
  "Resolve the Panchapakshi bird from the supplied birth-star name. Use the API's accepted spelling.",
  { birthStar: z.string().min(1) },
  "/api/v1/find-bird-by-nakshatra",
);
registerApiTool(
  "planets360_find_bird_by_name",
  "Resolve Panchapakshi bird details from a name, as supported by the API.",
  { name: z.string().min(1) },
  "/api/v1/find-bird-by-name",
);
registerApiTool(
  "planets360_love_compatibility_birth_dates",
  "Get the API's love-compatibility score for two birth dates. The API documents date strings and an IANA timezone.",
  { boyBirthDate: z.string().describe("Date string as documented, e.g. YYYY-MM-DD."), girlBirthDate: z.string().describe("Date string as documented, e.g. YYYY-MM-DD."), timeZone: z.string().describe("IANA time-zone ID, e.g. Asia/Kolkata.") },
  "/api/v1/lc-birth-date-based",
);
registerApiTool(
  "planets360_love_compatibility_moon_signs",
  "Get the API's love-compatibility score for two supplied Moon signs.",
  { boyMoonSign: z.string().min(1), girlMoonSign: z.string().min(1) },
  "/api/v1/lc-moon-sign-based",
);
registerApiTool(
  "planets360_love_compatibility_names",
  "Get the API's name-based love-compatibility score for two supplied names.",
  { boyName: z.string().min(1), girlName: z.string().min(1) },
  "/api/v1/lc-name-based",
);
registerApiTool(
  "planets360_moon_sign_prediction",
  "Get Moon-sign prediction segments over a date range using coordinates, timezone, Moon sign, and natal Nakshatra.",
  {
    latitude: geoDateTime.latitude,
    longitude: geoDateTime.longitude,
    timeZone: geoDateTime.timeZone,
    startDate: z.string().describe("Date in YYYY-MM-DD format."),
    endDate: z.string().describe("Date in YYYY-MM-DD format."),
    moonSign: z.string().min(1),
    natalNakshatra: z.string().min(1),
  },
  "/api/v1/moon-sign-prediction",
);

server.registerTool("planets360_read_public_article", {
  description: "Fetch readable text from a public Planets360 article or page. Only HTTPS URLs on planets360.in are accepted. Use for supporting editorial explanations, not for personalized calculations. Justification: read-only tool - it fetches one allowlisted public webpage and returns extracted text; it performs no write actions and stores no data.",
  inputSchema: { url: z.string().url().describe("Full HTTPS URL on planets360.in") },
  annotations: {
    title: "planets360_read_public_article",
    readOnlyHint: true,
    destructiveHint: false,
    idempotentHint: true,
    openWorldHint: true,
  },
}, async ({ url }) => {
  try {
    const parsedUrl = new URL(url);
    if (parsedUrl.protocol !== "https:" || !(parsedUrl.hostname === "planets360.in" || parsedUrl.hostname.endsWith(".planets360.in"))) {
      throw new Error("Only HTTPS pages on planets360.in are allowed.");
    }
    const response = await fetch(parsedUrl, {
      headers: { "user-agent": "Planets360-MCP/1.0.0", "accept": "text/html" },
      redirect: "error",
      signal: AbortSignal.timeout(15_000),
    });
    if (!response.ok) throw new Error(`Website returned HTTP ${response.status}.`);
    const contentType = response.headers.get("content-type") ?? "";
    if (!contentType.includes("text/html")) throw new Error("The URL did not return an HTML page.");
    const html = (await response.text()).slice(0, 1_500_000);
    const text = html
      .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, " ")
      .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, " ")
      .replace(/<(br|\/p|\/div|\/h[1-6]|\/li|\/section|\/article)\b[^>]*>/gi, "\n")
      .replace(/<[^>]+>/g, " ")
      .replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&quot;/gi, '"')
      .replace(/&#39;|&apos;/gi, "'").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">")
      .replace(/[ \t]+/g, " ").replace(/\n\s*\n\s*\n/g, "\n\n").trim();
    return jsonResult({ sourceUrl: parsedUrl.toString(), text: text.slice(0, 18_000) });
  } catch (error) {
    return jsonResult({ error: error instanceof Error ? error.message : String(error) });
  }
});

  return server;
}

const MAX_HTTP_BODY_BYTES = 1_000_000;

async function readJsonBody(req: IncomingMessage): Promise<unknown> {
  const chunks: Buffer[] = [];
  let size = 0;
  for await (const chunk of req) {
    size += (chunk as Buffer).length;
    if (size > MAX_HTTP_BODY_BYTES) throw new Error("Request body too large.");
    chunks.push(chunk as Buffer);
  }
  const raw = Buffer.concat(chunks).toString("utf8");
  if (!raw) throw new Error("Empty request body.");
  return JSON.parse(raw);
}

function applyCors(res: ServerResponse): void {
  res.setHeader("access-control-allow-origin", "*");
  res.setHeader("access-control-allow-methods", "POST, OPTIONS");
  res.setHeader("access-control-allow-headers", "content-type, mcp-protocol-version, mcp-session-id, accept");
}

async function handleHttpMcp(req: IncomingMessage, res: ServerResponse): Promise<void> {
  applyCors(res);
  if (req.method === "OPTIONS") {
    res.writeHead(204).end();
    return;
  }
  if (req.method !== "POST") {
    res.writeHead(405, { "content-type": "application/json" });
    res.end(JSON.stringify({ error: "Method not allowed. Use POST for MCP messages." }));
    return;
  }

  // Stateless mode: a fresh server + transport per request keeps the endpoint
  // horizontally scalable behind a load balancer or serverless host.
  const server = buildServer();
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  res.on("close", () => {
    void transport.close();
    void server.close();
  });

  try {
    const body = await readJsonBody(req);
    await server.connect(transport);
    await transport.handleRequest(req, res, body);
  } catch (error) {
    if (!res.headersSent) {
      res.writeHead(400, { "content-type": "application/json" });
      res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
    } else {
      res.end();
    }
  }
}

async function startHttp(port: number, host: string): Promise<void> {
  const httpServer = createServer((req, res) => {
    const path = (req.url ?? "/").split("?")[0];
    if (path === "/mcp" || path === "/mcp/") {
      void handleHttpMcp(req, res);
      return;
    }
    if (path === "/healthz") {
      res.writeHead(200, { "content-type": "application/json" });
      res.end(JSON.stringify({ status: "ok", name: SERVER_NAME, version: SERVER_VERSION }));
      return;
    }
    res.writeHead(404, { "content-type": "application/json" });
    res.end(JSON.stringify({ error: "Not found. MCP endpoint is /mcp" }));
  });
  await new Promise<void>((resolve, reject) => {
    httpServer.once("error", reject);
    httpServer.listen(port, host, resolve);
  });
  console.error(`Planets360 MCP server (Streamable HTTP) listening on http://${host}:${port}/mcp`);
}

async function main() {
  const transport = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();
  if (transport === "stdio") {
    const stdio = new StdioServerTransport();
    await buildServer().connect(stdio);
    return;
  }
  if (transport === "http") {
    const port = Number.parseInt(process.env.MCP_HTTP_PORT ?? "8787", 10);
    const host = process.env.MCP_HTTP_HOST ?? "127.0.0.1";
    await startHttp(port, host);
    return;
  }
  throw new Error(`Unsupported MCP_TRANSPORT "${transport}". Use "stdio" or "http".`);
}
main().catch((error) => {
  console.error("Planets360 MCP server failed to start:", error);
  process.exitCode = 1;
});

SHA-256: 92e59eff8b4a1432e052f47556ecfcc93be0cabdfbe74bca82502f9af3c60d5e