Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

32.7 KB
Raw Blame
import {
  ORIGIN,
  catalogSites,
  sitesById,
  formatPublicSite,
  createSavedList,
  getSavedList,
} from "./lists.js";
import { getFavoritesRanking } from "./favorites.js";
import { CATEGORIES, handleSubmission } from "./submit.js";
import {
  APP_PANEL,
  APP_HTML,
  APP_RESOURCE_META,
  PANEL_MIME,
} from "./mcp-app.js";

const SERVER_ICONS = [
  {
    src: `${ORIGIN}/icon-192.png`,
    mimeType: "image/png",
    sizes: ["192x192"],
  },
  {
    src: `${ORIGIN}/favicon.svg`,
    mimeType: "image/svg+xml",
    sizes: ["any"],
  },
];

const SERVER_INFO = {
  name: "designtaste",
  title: "DesignTaste",
  version: "1.1.0",
  description:
    "Curated website design inspiration gallery, interactive in-chat browser, and shareable moodboard lists (designtaste.wtf).",
  websiteUrl: ORIGIN,
  icons: SERVER_ICONS,
};

const SUPPORTED_PROTOCOLS = [
  "2025-11-25",
  "2025-06-18",
  "2025-03-26",
  "2024-11-05",
];

function uiToolMeta(invoking, invoked) {
  return {
    ui: { resourceUri: APP_PANEL },
    "ui/resourceUri": APP_PANEL,
    "openai/outputTemplate": APP_PANEL,
    "openai/toolInvocation/invoking": invoking,
    "openai/toolInvocation/invoked": invoked,
  };
}

const TOOLS = [
  {
    name: "browse_gallery",
    title: "Browse DesignTaste gallery",
    description:
      "Open the interactive DesignTaste website gallery directly inside chat (or return structured results in text clients). Use this when the user wants to browse, explore, filter by category/tag, or pick visual references for a project. Users can search, switch categories, inspect sites, and heart sites into a shareable dt_... moodboard right inside the rendered UI. Do not repeat every card in prose when the UI renders.",
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description:
            "Optional keyword search across site name, domain, tags, category, and description.",
        },
        category: {
          type: "string",
          enum: CATEGORIES,
          description: "Optional category filter.",
        },
        tag: {
          type: "string",
          description:
            "Optional visual style tag (e.g. Dark, Minimal, Typography, Motion, Editorial).",
        },
        sort: {
          type: "string",
          enum: ["popular", "curated", "newest", "az"],
          default: "popular",
          description:
            "Sort order: popular (most favorited first), curated, newest, or az.",
        },
        limit: {
          type: "integer",
          minimum: 1,
          maximum: 24,
          default: 12,
          description: "Number of sites per page (1–24).",
        },
        offset: {
          type: "integer",
          minimum: 0,
          default: 0,
          description: "Pagination offset.",
        },
      },
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Opening DesignTaste gallery", "DesignTaste gallery ready"),
  },
  {
    name: "search_sites",
    title: "Search curated websites",
    description:
      "Search and filter curated high-craft websites on designtaste.wtf by keyword, category, visual tag, or sort order (popular, curated, newest, az). Renders the interactive gallery in MCP Apps hosts and returns editorial notes, URLs, tags, and screenshot links.",
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description:
            "Optional keyword search across site name, domain, tags, category, and description.",
        },
        category: {
          type: "string",
          enum: CATEGORIES,
          description: "Optional category filter.",
        },
        tag: {
          type: "string",
          description:
            "Optional visual style tag (e.g. Dark, Minimal, Typography, Motion, Editorial).",
        },
        sort: {
          type: "string",
          enum: ["popular", "curated", "newest", "az"],
          default: "popular",
          description:
            "Sort order: popular (most favorited first), curated, newest, or az.",
        },
        limit: {
          type: "integer",
          minimum: 1,
          maximum: 40,
          default: 12,
          description: "Maximum number of sites to return (1–40).",
        },
        offset: {
          type: "integer",
          minimum: 0,
          default: 0,
          description: "Pagination offset.",
        },
      },
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Searching DesignTaste", "Search results ready"),
  },
  {
    name: "get_site",
    title: "Inspect one website",
    description:
      "Inspect full details, design observation, tags, similar references, URL, and screenshot links for one DesignTaste website by its id. Set include_image=true to also receive the 640×400 thumbnail image directly as an MCP image block for vision models.",
    inputSchema: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: "Site slug ID (e.g. linear, anywr, stripe, rive).",
        },
        include_image: {
          type: "boolean",
          default: false,
          description:
            "If true, attach the 640×400 JPEG thumbnail as an image content block.",
        },
      },
      required: ["id"],
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Loading website details", "Website ready"),
  },
  {
    name: "find_similar_sites",
    title: "Find visually similar websites",
    description:
      "Find curated websites on designtaste.wtf that share a similar aesthetic to a given site id (e.g. 'linear') or a set of style tags and optional category. Renders an interactive visual comparison grid in chat.",
    inputSchema: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description:
            "Optional reference site slug ID (e.g. linear, stripe, raycast).",
        },
        tags: {
          type: "array",
          items: { type: "string" },
          maxItems: 8,
          description:
            "Optional style tags to match (e.g. ['Dark', 'Typography', 'Minimal']).",
        },
        category: {
          type: "string",
          enum: CATEGORIES,
          description: "Optional category boost or filter.",
        },
        limit: {
          type: "integer",
          minimum: 1,
          maximum: 24,
          default: 9,
          description: "Number of similar sites to return (1–24).",
        },
      },
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Finding similar websites", "Similar references ready"),
  },
  {
    name: "discover_random",
    title: "Discover random inspiration",
    description:
      "Surface a fresh random selection of high-craft websites from designtaste.wtf (optionally filtered by category or tag) for instant creative inspiration, with a live Shuffle button in chat.",
    inputSchema: {
      type: "object",
      properties: {
        count: {
          type: "integer",
          minimum: 1,
          maximum: 12,
          default: 6,
          description: "Number of random sites to pick (1–12).",
        },
        category: {
          type: "string",
          enum: CATEGORIES,
          description: "Optional category filter.",
        },
        tag: {
          type: "string",
          description: "Optional visual style tag filter.",
        },
      },
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: false,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Shuffling curated websites", "Fresh inspiration ready"),
  },
  {
    name: "list_categories",
    title: "Explore categories and tags",
    description:
      "List all 8 DesignTaste website categories with exact site counts, preview thumbnails, and top visual tags. Renders a clickable category explorer in MCP Apps hosts.",
    inputSchema: {
      type: "object",
      properties: {},
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Loading categories", "Categories ready"),
  },
  {
    name: "get_saved_list",
    title: "Open a shared saved list",
    description:
      "Load a human- or agent-curated DesignTaste saved moodboard by its unique ID (e.g. dt_k8x4m2p9). Renders the moodboard visually in chat and returns every website's editorial notes, tags, and screenshot URLs.",
    inputSchema: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: "Shared list ID (format: dt_xxxxxxxx).",
        },
        include_images: {
          type: "boolean",
          default: false,
          description:
            "If true, attach up to 6 site thumbnail images directly so vision models can inspect the moodboard.",
        },
      },
      required: ["id"],
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Loading saved moodboard", "Moodboard ready"),
  },
  {
    name: "create_saved_list",
    title: "Create a shareable moodboard",
    description:
      "Create a shareable DesignTaste saved list from valid site IDs (1–50 sites) and receive a unique dt_... ID plus a live designtaste.wtf/?list=... link to share with humans or other agents. Renders the saved moodboard visually in chat.",
    inputSchema: {
      type: "object",
      properties: {
        ids: {
          type: "array",
          items: { type: "string" },
          minItems: 1,
          maxItems: 50,
          description:
            "Ordered list of DesignTaste site IDs (e.g. ['linear', 'anywr', 'vercel']).",
        },
        title: {
          type: "string",
          maxLength: 80,
          description:
            "Optional short title for the list (e.g. 'Dark Developer SaaS Direction').",
        },
      },
      required: ["ids"],
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: false,
      destructiveHint: false,
      idempotentHint: false,
      openWorldHint: false,
    },
    _meta: uiToolMeta("Creating shareable moodboard", "Moodboard saved"),
  },
  {
    name: "submit_site",
    title: "Submit a website",
    description:
      "Submit a public HTTPS website URL to the DesignTaste curation queue for review. No account required; rate-limited and deduplicated.",
    inputSchema: {
      type: "object",
      properties: {
        url: {
          type: "string",
          description: "Public HTTPS website URL to recommend.",
        },
        name: {
          type: "string",
          description: "Optional site name.",
        },
        category: {
          type: "string",
          enum: CATEGORIES,
          description: "Optional suggested category.",
        },
        note: {
          type: "string",
          maxLength: 500,
          description: "Optional brief note on what stands out visually.",
        },
      },
      required: ["url"],
      additionalProperties: false,
    },
    annotations: {
      readOnlyHint: false,
      destructiveHint: false,
      idempotentHint: false,
      openWorldHint: true,
    },
  },
];

const RESOURCES = [
  {
    uri: APP_PANEL,
    name: "DesignTaste Interactive Browser",
    description:
      "Interactive dark-studio website gallery and moodboard builder drawn inside MCP Apps conversations.",
    mimeType: PANEL_MIME,
    icons: SERVER_ICONS,
    _meta: APP_RESOURCE_META,
  },
  {
    uri: "designtaste://catalog/summary",
    name: "DesignTaste Catalog Summary",
    description:
      "Overview of the DesignTaste curated gallery, categories, total site count, and usage guidance.",
    mimeType: "application/json",
  },
  {
    uri: "designtaste://categories",
    name: "DesignTaste Categories",
    description:
      "Category counts and common design tags across designtaste.wtf.",
    mimeType: "application/json",
  },
];

const PROMPTS = [
  {
    name: "apply_saved_list",
    description:
      "Turn a shared DesignTaste saved list (dt_...) into concrete visual direction for a UI or website.",
    arguments: [
      {
        name: "list_id",
        description: "The shared DesignTaste list ID (e.g. dt_k8x4m2p9).",
        required: true,
      },
      {
        name: "project_goal",
        description: "Optional description of what you are designing or building.",
        required: false,
      },
    ],
  },
];

function buildCategoryStats() {
  const map = new Map();
  for (const cat of CATEGORIES) {
    map.set(cat, { category: cat, count: 0, topTags: new Map(), previews: [] });
  }
  for (const s of catalogSites) {
    const entry = map.get(s.category) || {
      category: s.category,
      count: 0,
      topTags: new Map(),
      previews: [],
    };
    entry.count++;
    if (entry.previews.length < 2) {
      entry.previews.push({
        id: s.id,
        name: s.name,
        category: s.category,
        thumbUrl: `${ORIGIN}/images/${s.id}-thumb.jpg`,
      });
    }
    for (const tag of s.tags || []) {
      entry.topTags.set(tag, (entry.topTags.get(tag) || 0) + 1);
    }
    map.set(s.category, entry);
  }
  return [...map.values()].map((e) => ({
    category: e.category,
    count: e.count,
    topTags: [...e.topTags.entries()]
      .sort((a, b) => b[1] - a[1])
      .slice(0, 6)
      .map(([tag]) => tag),
    previews: e.previews,
  }));
}

function findSimilarCandidates({ referenceSite, tags = [], category = "", limit = 9 }) {
  const refTags = new Set(
    [
      ...(referenceSite?.tags || []),
      ...tags,
    ]
      .map((t) => String(t || "").trim().toLowerCase())
      .filter(Boolean),
  );
  const targetCategory = category || referenceSite?.category || "";
  const refWords = new Set(
    (referenceSite?.description || "")
      .toLowerCase()
      .split(/[^a-z0-9]+/)
      .filter((w) => w.length >= 4),
  );

  const scored = [];
  for (let i = 0; i < catalogSites.length; i++) {
    const s = catalogSites[i];
    if (referenceSite && s.id === referenceSite.id) continue;
    let score = 0;
    const siteTags = (s.tags || []).map((t) => t.toLowerCase());
    for (const t of siteTags) {
      if (refTags.has(t)) score += 3;
    }
    if (targetCategory && s.category === targetCategory) {
      score += 2.5;
    }
    if (refWords.size) {
      const desc = `${s.description} ${s.observation || ""}`.toLowerCase();
      let overlap = 0;
      for (const w of refWords) {
        if (desc.includes(w)) overlap++;
      }
      score += Math.min(2, overlap * 0.4);
    }
    if (score > 0 || (!refTags.size && !targetCategory)) {
      scored.push({ site: s, score, idx: i });
    }
  }

  scored.sort((a, b) => b.score - a.score || a.idx - b.idx);
  return scored.slice(0, limit).map((x) => formatPublicSite(x.site));
}

async function queryGallerySites(args = {}, { env, fetchImpl }) {
  const query = String(args.query || "").trim().toLowerCase();
  const words = query ? query.split(/\s+/).filter(Boolean) : [];
  const category = args.category ? String(args.category).trim() : "";
  const tag = args.tag ? String(args.tag).trim().toLowerCase() : "";
  const sort = ["popular", "curated", "newest", "az"].includes(args.sort)
    ? args.sort
    : "popular";
  const maxLimit = args._maxLimit || 40;
  const limit = Math.min(maxLimit, Math.max(1, Number(args.limit) || 12));
  const offset = Math.max(0, Number(args.offset) || 0);

  let matches = catalogSites.filter((s) => {
    if (category && s.category !== category) return false;
    if (tag && !(s.tags || []).some((t) => t.toLowerCase() === tag)) {
      return false;
    }
    if (words.length) {
      const hay = [
        s.id,
        s.name,
        s.url,
        s.category,
        ...(s.tags || []),
        s.description,
        s.observation || "",
      ]
        .join(" ")
        .toLowerCase();
      if (!words.every((w) => hay.includes(w))) return false;
    }
    return true;
  });

  const curatedIndex = new Map(catalogSites.map((s, i) => [s.id, i]));
  if (sort === "az") {
    matches = [...matches].sort((a, b) => a.name.localeCompare(b.name));
  } else if (sort === "newest") {
    matches = [...matches].sort(
      (a, b) =>
        b.capturedAt.localeCompare(a.capturedAt) ||
        curatedIndex.get(a.id) - curatedIndex.get(b.id),
    );
  } else if (sort === "popular") {
    const rankRes = await getFavoritesRanking({ env, fetchImpl });
    const rankList = rankRes?.body?.ranking || [];
    const rankMap = new Map(rankList.map((id, i) => [id, i]));
    matches = [...matches].sort((a, b) => {
      const ra = rankMap.has(a.id)
        ? rankMap.get(a.id)
        : 1000000 + curatedIndex.get(a.id);
      const rb = rankMap.has(b.id)
        ? rankMap.get(b.id)
        : 1000000 + curatedIndex.get(b.id);
      return ra - rb;
    });
  }

  const page = matches.slice(offset, offset + limit).map(formatPublicSite);
  return {
    kind: "gallery",
    query: String(args.query || "").trim(),
    category,
    tag: String(args.tag || "").trim(),
    sort,
    limit,
    offset,
    totalMatches: matches.length,
    categories: CATEGORIES,
    sites: page,
  };
}

async function fetchThumbAsImageBlock(siteId, fetchImpl = fetch) {
  if (!sitesById.has(siteId)) return null;
  try {
    // Strictly fixed origin + validated catalog ID — never user-supplied URLs.
    const res = await fetchImpl(`${ORIGIN}/images/${siteId}-thumb.jpg`);
    if (!res.ok) return null;
    const buf = Buffer.from(await res.arrayBuffer());
    if (buf.length > 250 * 1024) return null;
    return {
      type: "image",
      data: buf.toString("base64"),
      mimeType: "image/jpeg",
    };
  } catch {
    return null;
  }
}

async function executeTool(name, args = {}, ctx = {}) {
  const { clientKey = "anonymous", env = process.env, fetchImpl = fetch } = ctx;

  if (name === "list_categories") {
    const categories = buildCategoryStats();
    const payload = {
      kind: "categories",
      totalSites: catalogSites.length,
      categories,
    };
    return {
      content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
      structuredContent: payload,
    };
  }

  if (name === "browse_gallery" || name === "search_sites") {
    const payload = await queryGallerySites(
      { ...args, _maxLimit: name === "browse_gallery" ? 24 : 40 },
      { env, fetchImpl },
    );
    return {
      content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
      structuredContent: payload,
    };
  }

  if (name === "get_site") {
    const id = String(args.id || "").trim().toLowerCase();
    const site = sitesById.get(id);
    if (!site) {
      return {
        isError: true,
        content: [{ type: "text", text: `No site found with id "${id}".` }],
      };
    }
    const formatted = formatPublicSite(site);
    const similar = findSimilarCandidates({ referenceSite: site, limit: 3 });
    const structured = {
      kind: "site",
      site: formatted,
      similar,
    };
    const content = [
      {
        type: "text",
        text: JSON.stringify({ ...formatted, similar }, null, 2),
      },
    ];
    if (args.include_image) {
      const img = await fetchThumbAsImageBlock(site.id, fetchImpl);
      if (img) content.push(img);
    }
    return { content, structuredContent: structured };
  }

  if (name === "find_similar_sites") {
    const id = String(args.id || "").trim().toLowerCase();
    const referenceSite = id ? sitesById.get(id) : null;
    if (id && !referenceSite) {
      return {
        isError: true,
        content: [{ type: "text", text: `No site found with id "${id}".` }],
      };
    }
    const tags = Array.isArray(args.tags) ? args.tags : [];
    const category = args.category ? String(args.category).trim() : "";
    const limit = Math.min(24, Math.max(1, Number(args.limit) || 9));
    const sites = findSimilarCandidates({
      referenceSite,
      tags,
      category,
      limit,
    });
    const payload = {
      kind: "gallery",
      mode: "similar",
      title: referenceSite
        ? `Similar to ${referenceSite.name}`
        : "Similar references",
      subtitle: referenceSite
        ? `Matched on ${referenceSite.category} and tags: ${(referenceSite.tags || []).join(", ")}`
        : tags.length
          ? `Matched on tags: ${tags.join(", ")}`
          : "",
      category,
      tag: "",
      query: "",
      sort: "curated",
      limit,
      offset: 0,
      totalMatches: sites.length,
      categories: CATEGORIES,
      sites,
    };
    return {
      content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
      structuredContent: payload,
    };
  }

  if (name === "discover_random") {
    const count = Math.min(12, Math.max(1, Number(args.count) || 6));
    const category = args.category ? String(args.category).trim() : "";
    const tag = args.tag ? String(args.tag).trim().toLowerCase() : "";
    let pool = catalogSites.filter((s) => {
      if (category && s.category !== category) return false;
      if (tag && !(s.tags || []).some((t) => t.toLowerCase() === tag)) {
        return false;
      }
      return true;
    });
    pool = [...pool];
    for (let i = pool.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [pool[i], pool[j]] = [pool[j], pool[i]];
    }
    const picked = pool.slice(0, count).map(formatPublicSite);
    const payload = {
      kind: "gallery",
      mode: "random",
      title: category ? `Random ${category}` : "Random Inspiration",
      category,
      tag: String(args.tag || "").trim(),
      query: "",
      sort: "curated",
      limit: count,
      offset: 0,
      totalMatches: pool.length,
      categories: CATEGORIES,
      sites: picked,
    };
    return {
      content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
      structuredContent: payload,
    };
  }

  if (name === "get_saved_list") {
    const res = await getSavedList(args.id, { env, fetchImpl });
    if (res.status !== 200) {
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: res.body?.message || "Saved list not found.",
          },
        ],
      };
    }
    const list = res.body.list;
    const structured = {
      kind: "list",
      id: list.id,
      title: list.title,
      url: list.url,
      sites: list.sites,
    };
    const content = [
      {
        type: "text",
        text: JSON.stringify(list, null, 2),
      },
    ];
    if (args.include_images) {
      const imgs = await Promise.all(
        list.sites
          .slice(0, 6)
          .map((s) => fetchThumbAsImageBlock(s.id, fetchImpl)),
      );
      for (const img of imgs) {
        if (img) content.push(img);
      }
    }
    return { content, structuredContent: structured };
  }

  if (name === "create_saved_list") {
    const res = await createSavedList(
      { ids: args.ids, title: args.title },
      { clientKey, env, fetchImpl },
    );
    if (res.status !== 201) {
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: res.body?.message || "Could not create saved list.",
          },
        ],
      };
    }
    const sites = (res.body.ids || [])
      .map((id) => sitesById.get(id))
      .filter(Boolean)
      .map(formatPublicSite);
    const structured = {
      kind: "list",
      id: res.body.id,
      title: res.body.title,
      url: res.body.url,
      sites,
    };
    return {
      content: [{ type: "text", text: JSON.stringify(res.body, null, 2) }],
      structuredContent: structured,
    };
  }

  if (name === "submit_site") {
    try {
      const res = await handleSubmission(
        {
          url: args.url,
          name: args.name,
          category: args.category,
          note: args.note,
        },
        {
          clientKey,
          env,
          token: env.GITHUB_SUBMISSIONS_TOKEN || "",
          repo: env.GITHUB_SUBMISSIONS_REPO,
          fetchImpl,
        },
      );
      return {
        isError: !res.body?.ok,
        content: [{ type: "text", text: JSON.stringify(res.body, null, 2) }],
      };
    } catch (err) {
      return {
        isError: true,
        content: [
          { type: "text", text: err?.message || "Invalid submission." },
        ],
      };
    }
  }

  return {
    isError: true,
    content: [{ type: "text", text: `Unknown tool: ${name}` }],
  };
}

function rpcOk(id, result) {
  return { jsonrpc: "2.0", id, result };
}

function rpcError(id, code, message) {
  return { jsonrpc: "2.0", id: id ?? null, error: { code, message } };
}

export async function handleMcpMessage(msg, ctx = {}) {
  if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") {
    return rpcError(null, -32600, "Invalid JSON-RPC 2.0 request.");
  }

  const { id, method, params } = msg;
  const isNotification = id === undefined || id === null;

  if (
    method === "notifications/initialized" ||
    method === "notifications/cancelled"
  ) {
    return null;
  }

  if (method === "ping") {
    return isNotification ? null : rpcOk(id, {});
  }

  if (method === "initialize") {
    const requested = params?.protocolVersion;
    const protocolVersion = SUPPORTED_PROTOCOLS.includes(requested)
      ? requested
      : SUPPORTED_PROTOCOLS[0];
    return rpcOk(id, {
      protocolVersion,
      capabilities: {
        tools: { listChanged: false },
        resources: { subscribe: false, listChanged: false },
        prompts: { listChanged: false },
        extensions: {
          "io.modelcontextprotocol/ui": {
            mimeTypes: [PANEL_MIME],
          },
        },
      },
      serverInfo: SERVER_INFO,
      instructions:
        "DesignTaste is an open curated website design inspiration gallery (designtaste.wtf) with an interactive in-chat browser (MCP Apps). Call browse_gallery when the user wants to browse or pick websites visually, search_sites or find_similar_sites to narrow references, discover_random for sparks, get_site (with include_image=true) to inspect a reference, get_saved_list to load a dt_... moodboard, and create_saved_list to share curated shortlists via designtaste.wtf/?list=<id>. Never copy reference brands or assets.",
    });
  }

  if (method === "tools/list") {
    return rpcOk(id, { tools: TOOLS });
  }

  if (method === "tools/call") {
    const toolName = params?.name;
    if (typeof toolName !== "string") {
      return rpcError(id, -32602, "Missing tool name.");
    }
    const result = await executeTool(toolName, params?.arguments || {}, ctx);
    return rpcOk(id, result);
  }

  if (method === "resources/list") {
    return rpcOk(id, { resources: RESOURCES });
  }

  if (method === "resources/read") {
    const uri = params?.uri;
    if (uri === APP_PANEL) {
      return rpcOk(id, {
        contents: [
          {
            uri: APP_PANEL,
            mimeType: PANEL_MIME,
            text: APP_HTML,
            _meta: APP_RESOURCE_META,
          },
        ],
      });
    }
    if (uri === "designtaste://catalog/summary") {
      return rpcOk(id, {
        contents: [
          {
            uri,
            mimeType: "application/json",
            text: JSON.stringify(
              {
                name: "DesignTaste",
                website: ORIGIN,
                mcpEndpoint: `${ORIGIN}/api/mcp/`,
                totalSites: catalogSites.length,
                categories: buildCategoryStats(),
                note: "Independent curated website inspiration gallery. Designs and trademarks belong to their creators.",
              },
              null,
              2,
            ),
          },
        ],
      });
    }
    if (uri === "designtaste://categories") {
      return rpcOk(id, {
        contents: [
          {
            uri,
            mimeType: "application/json",
            text: JSON.stringify(buildCategoryStats(), null, 2),
          },
        ],
      });
    }
    return rpcError(id, -32002, `Resource not found: ${uri}`);
  }

  if (method === "prompts/list") {
    return rpcOk(id, { prompts: PROMPTS });
  }

  if (method === "prompts/get") {
    if (params?.name === "apply_saved_list") {
      const listId = String(params?.arguments?.list_id || "").trim();
      const goal = String(params?.arguments?.project_goal || "").trim();
      return rpcOk(id, {
        description: "Extract visual direction from a shared DesignTaste list.",
        messages: [
          {
            role: "user",
            content: {
              type: "text",
              text: [
                `Call the DesignTaste MCP tool get_saved_list with id="${listId}" and include_images=true.`,
                "Analyze the shared references for typography hierarchy, surface contrast, spacing rhythm, navigation structure, and interaction details.",
                goal
                  ? `Synthesize an original visual direction (palette, typography pairing, layout structure, and component feel) tailored to: ${goal}.`
                  : "Synthesize an original visual direction (palette, typography pairing, layout structure, and component feel) inspired by those references.",
                "Never copy any reference site's brand names, logos, copy, or proprietary artwork.",
              ].join("\n"),
            },
          },
        ],
      });
    }
    return rpcError(id, -32602, `Unknown prompt: ${params?.name}`);
  }

  return isNotification
    ? null
    : rpcError(id, -32601, `Method not found: ${method}`);
}

async function readJsonBody(req) {
  if (req.body && typeof req.body === "object") return req.body;
  if (typeof req.body === "string") return JSON.parse(req.body);
  const chunks = [];
  let total = 0;
  for await (const chunk of req) {
    total += chunk.length;
    if (total > 32 * 1024) {
      throw Object.assign(new Error("Payload too large."), { status: 413 });
    }
    chunks.push(chunk);
  }
  const text = Buffer.concat(chunks).toString("utf8");
  return text ? JSON.parse(text) : null;
}

export default async function handler(req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type, Accept, Mcp-Session-Id, MCP-Protocol-Version",
  );

  if (req.method === "OPTIONS") {
    return res.status(204).end();
  }

  if (req.method === "GET") {
    res.setHeader(
      "Cache-Control",
      "public, s-maxage=300, stale-while-revalidate=600",
    );
    return res.status(200).json({
      name: "DesignTaste MCP",
      description:
        "Open, zero-auth Model Context Protocol server with interactive MCP Apps in-chat UI for browsing designtaste.wtf, reading shared saved lists (dt_...), and submitting websites.",
      endpoint: `${ORIGIN}/api/mcp/`,
      docs: `${ORIGIN}/mcp/`,
      icons: SERVER_ICONS,
      transport: "streamable-http",
      auth: "none",
      mcpApps: true,
      totalSites: catalogSites.length,
      tools: TOOLS.map((t) => ({ name: t.name, description: t.description })),
      configExample: {
        mcpServers: {
          designtaste: {
            url: `${ORIGIN}/api/mcp/`,
          },
        },
      },
    });
  }

  res.setHeader("Cache-Control", "no-store");
  if (req.method !== "POST") {
    res.setHeader("Allow", "GET, POST, OPTIONS");
    return res.status(405).json(rpcError(null, -32600, "Method not allowed."));
  }

  const realIp = String(
    req.headers?.["x-real-ip"] ||
      req.headers?.["x-vercel-forwarded-for"] ||
      req.headers?.["x-forwarded-for"] ||
      "",
  )
    .split(",")[0]
    .trim();
  const clientKey = realIp || req.socket?.remoteAddress || "anonymous";

  try {
    const payload = await readJsonBody(req);
    if (Array.isArray(payload)) {
      if (payload.length === 0 || payload.length > 20) {
        return res
          .status(400)
          .json(rpcError(null, -32600, "Invalid JSON-RPC batch size."));
      }
      const responses = (
        await Promise.all(
          payload.map((item) => handleMcpMessage(item, { clientKey })),
        )
      ).filter(Boolean);
      if (responses.length === 0) return res.status(202).end();
      return res.status(200).json(responses);
    }

    const response = await handleMcpMessage(payload, { clientKey });
    if (!response) return res.status(202).end();
    return res.status(200).json(response);
  } catch (err) {
    const status = err?.status === 413 ? 413 : 400;
    return res
      .status(status)
      .json(rpcError(null, -32700, err?.message || "Invalid JSON payload."));
  }
}