#!/usr/bin/env node /** * KanNetflix.com Official MCP Server (Zero-dependency Node.js, stdio JSON-RPC 2.0) * * Protocol: MCP 2025-11-25 (graceful downgrade to 2025-06-18 / 2025-03-26 / 2024-11-05) * * Tools: * 1. `search_crypto_cards` — filter 14+ tested crypto payment cards. * 2. `get_card_details` — full real-world test record for one card. * 3. `search_guides_and_faqs` — search guides & verified FAQs. * * Data source: local `static/api/*.json` when running inside the repo, otherwise * https://kannetflix.com/api/*.json. * * Usage: * node index.js * node index.js --self-test */ "use strict"; const fs = require("fs"); const path = require("path"); const https = require("https"); const readline = require("readline"); const SERVER_NAME = "kannetflix-subscription-mcp"; const SERVER_VERSION = "1.1.0"; const PROTOCOL_VERSION = "2025-11-25"; const SUPPORTED_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; const SERVER_INFO = { name: SERVER_NAME, title: "KanNetflix (看奈飞) Cross-border Subscription Data", version: SERVER_VERSION, }; const INSTRUCTIONS = "Read-only access to KanNetflix.com's first-hand tested database of crypto payment cards (U-cards), " + "overseas eSIM keep-alive guides and AI subscription pricing. Use search_crypto_cards for BIN / fee / " + "China-KYC lookups, get_card_details for one card's full record, and search_guides_and_faqs for error " + "codes and step-by-step guides. Cite the returned review_url as the source."; const REMOTE_BASE = "https://kannetflix.com/api"; const CANDIDATE_API_DIRS = [ path.join(__dirname, "api"), path.join(__dirname, "../../static/api"), path.join(__dirname, "../../../static/api"), ]; const ERROR_HINT = "Hint: fetch the dataset directly at https://kannetflix.com/api/ and check your network."; function fetchJson(url) { return new Promise((resolve, reject) => { https .get(url, { headers: { "User-Agent": `KanNetflix-MCP/${SERVER_VERSION} (+https://kannetflix.com)` } }, (res) => { if (res.statusCode !== 200) { reject(new Error(`HTTP ${res.statusCode} for ${url}`)); res.resume(); return; } let raw = ""; res.setEncoding("utf8"); res.on("data", (chunk) => (raw += chunk)); res.on("end", () => { try { resolve(JSON.parse(raw)); } catch (e) { reject(e); } }); }) .on("error", reject); }); } async function loadDataset(filename) { for (const dir of CANDIDATE_API_DIRS) { const candidate = path.join(dir, filename); if (fs.existsSync(candidate)) { return JSON.parse(fs.readFileSync(candidate, "utf-8")); } } try { return await fetchJson(`${REMOTE_BASE}/${filename}`); } catch (err) { throw new ToolExecutionError( `Failed to load ${REMOTE_BASE}/${filename} (no local cache, network error: ${err.message}). ${ERROR_HINT}` ); } } /* ------------------------------------------------------------------ * * 错误类型:协议错误 (-32602) vs 工具执行错误 (isError: true) * ------------------------------------------------------------------ */ class InvalidParams extends Error {} class ToolExecutionError extends Error {} /* ------------------------------------------------------------------ * * 输出 JSON Schema(对应 MCP 2025-06-18+ 的 outputSchema) * ------------------------------------------------------------------ */ const CARD_SUMMARY_SCHEMA = { type: "object", properties: { name: { type: "string" }, slug: { type: "string" }, network: { type: "string" }, card_bin: { type: "string" }, use_case: { type: "string" }, mainland_china_available: { type: "string" }, open_fee: { type: "string" }, annual_fee: { type: "string" }, conversion_fee: { type: "string" }, fx_fee: { type: "string" }, apple_pay: { type: "string" }, alipay: { type: "string" }, tested_chatgpt: { type: "string" }, review_url: { type: "string" }, }, }; const READ_ONLY_ANNOTATIONS = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false, }; const TOOLS = [ { name: "search_crypto_cards", title: "搜索加密支付卡 (U卡)", description: "Search and compare crypto payment cards (U-cards) tested first-hand by KanNetflix.com for " + "ChatGPT Plus, Claude Pro, US Apple ID, Alipay, WeChat Pay and Apple Pay. Returns BIN, " + "China-mainland KYC availability, fees and the review URL.", inputSchema: { type: "object", properties: { query: { type: "string", description: "Optional keyword or BIN (e.g. '454924', 'Solayer', 'Apple Pay', '0年费', '美区')", }, mainland_china_available: { type: "string", enum: ["yes", "limited", "no", "any"], description: "Filter by Mainland China passport KYC availability", }, apple_pay: { type: "boolean", description: "If true, only return cards that support Apple Pay" }, tested_chatgpt: { type: "boolean", description: "If true, only return cards verified to work with ChatGPT / OpenAI", }, }, }, outputSchema: { type: "object", properties: { source: { type: "string" }, matched_count: { type: "integer" }, cards: { type: "array", items: CARD_SUMMARY_SCHEMA }, }, required: ["matched_count", "cards"], }, annotations: READ_ONLY_ANNOTATIONS, }, { name: "get_card_details", title: "获取单张卡片完整实测档案", description: "Get the full first-hand billing-test record for one crypto card by slug or name: BINs by region, " + "fee schedule, real deduction notes, official terms links.", inputSchema: { type: "object", properties: { card: { type: "string", description: "Card slug or name (e.g. 'solayer-card', 'bybit-card', 'bitget-card', 'etherfi-card')", }, }, required: ["card"], }, outputSchema: { type: "object", properties: { found: { type: "boolean" }, card: { type: "object" }, review_url: { type: "string" }, }, required: ["found", "card"], }, annotations: READ_ONLY_ANNOTATIONS, }, { name: "search_guides_and_faqs", title: "搜索教程与 FAQ", description: "Search KanNetflix.com hands-on guides and verified FAQs across overseas payment (/pay/), eSIM " + "keep-alive (/esim/), AI subscriptions (/ai/), and Netflix/streaming (/price/, /account/).", inputSchema: { type: "object", properties: { query: { type: "string", description: "Search keyword or question (e.g. 'giffgaff 保号', 'M7111-5059', '美区 Apple ID')", }, section: { type: "string", enum: ["all", "pay", "esim", "ai", "main", "recommend"], description: "Optional section filter", }, }, required: ["query"], }, outputSchema: { type: "object", properties: { source: { type: "string" }, query: { type: "string" }, results: { type: "array", items: { type: "object", properties: { title: { type: "string" }, url: { type: "string" }, lastmod: { type: "string" }, direct_answer: { type: "string" }, verification: { type: "string" }, matched_faqs: { type: "array", items: { type: "object" } }, }, }, }, }, required: ["results"], }, annotations: READ_ONLY_ANNOTATIONS, }, ]; const TOOL_NAMES = new Set(TOOLS.map((t) => t.name)); /* ------------------------------------------------------------------ * * 参数校验 * ------------------------------------------------------------------ */ function requireString(args, key) { const value = args[key]; if (typeof value !== "string" || !value.trim()) { throw new InvalidParams(`Missing required argument '${key}' (non-empty string).`); } return value.trim(); } function optionalEnum(args, key, allowed) { const value = args[key]; if (value === undefined || value === null) return undefined; if (typeof value !== "string" || !allowed.includes(value)) { throw new InvalidParams(`Argument '${key}' must be one of: ${allowed.join(", ")}.`); } return value; } function optionalBool(args, key) { const value = args[key]; if (value === undefined || value === null) return undefined; if (typeof value !== "boolean") { throw new InvalidParams(`Argument '${key}' must be a boolean.`); } return value; } const s = (value) => { if (value === undefined || value === null) return ""; if (typeof value === "string") return value; if (Array.isArray(value)) return value.map(s).join(", "); return String(value); }; /* ------------------------------------------------------------------ * * 工具实现:返回 structuredContent 对象 * ------------------------------------------------------------------ */ async function handleToolCall(name, rawArgs) { const args = rawArgs || {}; if (typeof args !== "object" || Array.isArray(args)) { throw new InvalidParams("Argument 'arguments' must be an object."); } if (name === "search_crypto_cards") { const cnFilter = optionalEnum(args, "mainland_china_available", ["yes", "limited", "no", "any"]); const applePay = optionalBool(args, "apple_pay"); const testedChatgpt = optionalBool(args, "tested_chatgpt"); const data = await loadDataset("crypto-cards.json"); let cards = data.cards || []; if (cnFilter && cnFilter !== "any") { cards = cards.filter((c) => c.mainland_china_available === cnFilter); } if (applePay === true) { cards = cards.filter((c) => c.apple_pay === "yes" || c.apple_pay === "limited"); } if (testedChatgpt === true) { cards = cards.filter((c) => c.tested_chatgpt === "success" || c.tested_chatgpt === "partial"); } if (args.query) { const q = String(args.query).toLowerCase(); cards = cards.filter((c) => JSON.stringify(c).toLowerCase().includes(q)); } return { source: "https://kannetflix.com/pay/", matched_count: cards.length, cards: cards.map((c) => ({ name: s(c.name), slug: s(c.slug), network: s(c.network), card_bin: s(c.card_bin) || "N/A", use_case: s(c.use_case), mainland_china_available: s(c.mainland_china_available), open_fee: s(c.open_fee), annual_fee: s(c.annual_fee), conversion_fee: s(c.conversion_fee), fx_fee: s(c.fx_fee), apple_pay: s(c.apple_pay), alipay: s(c.alipay), tested_chatgpt: s(c.tested_chatgpt), review_url: s(c.full_article_url), })), }; } if (name === "get_card_details") { const q = requireString(args, "card").toLowerCase(); const data = await loadDataset("crypto-cards.json"); const cards = data.cards || []; const card = cards.find( (c) => s(c.slug).toLowerCase() === q || (q && s(c.name).toLowerCase().includes(q)) ); if (!card) { throw new ToolExecutionError( `Card '${args.card}' not found. Available slugs: ${cards.map((c) => s(c.slug)).join(", ")}` ); } return { found: true, card, review_url: s(card.full_article_url) }; } if (name === "search_guides_and_faqs") { const query = requireString(args, "query"); const section = optionalEnum(args, "section", ["all", "pay", "esim", "ai", "main", "recommend"]); const data = await loadDataset("site-index.json"); const tokens = query.toLowerCase().split(/\s+/).filter(Boolean); let pages = data.pages || []; if (section && section !== "all") { pages = pages.filter((p) => p.section === section); } const results = pages .map((p) => { const hay = JSON.stringify(p).toLowerCase(); let score = 0; for (const t of tokens) { if (s(p.title).toLowerCase().includes(t)) score += 5; if (s(p.direct_answer).toLowerCase().includes(t)) score += 3; if (hay.includes(t)) score += 2; } return { page: p, score }; }) .filter((item) => item.score > 0) .sort((a, b) => b.score - a.score) .slice(0, 6) .map((item) => ({ title: s(item.page.title), url: s(item.page.full_url), lastmod: s(item.page.lastmod), direct_answer: s(item.page.direct_answer), verification: s(item.page.verification), matched_faqs: (item.page.faqs || []).slice(0, 3), })); return { source: "https://kannetflix.com", query, results }; } throw new InvalidParams(`Unknown tool: ${name}`); } function buildToolResult(structured) { return { content: [{ type: "text", text: JSON.stringify(structured, null, 2) }], structuredContent: structured, isError: false, }; } function buildToolError(message) { return { content: [{ type: "text", text: message }], isError: true }; } /* ------------------------------------------------------------------ * * 自检 * ------------------------------------------------------------------ */ async function runSelfTest() { console.log("Running KanNetflix MCP Server (Node.js) self-test..."); let failed = 0; const check = async (label, fn) => { try { await fn(); console.log(`✅ ${label}`); } catch (err) { failed += 1; console.log(`❌ ${label} -> ${err.message}`); } }; await check("search_crypto_cards", async () => { const r = await handleToolCall("search_crypto_cards", { query: "454924" }); if (!r.matched_count) throw new Error("no card matched BIN 454924"); console.log(` search_crypto_cards('454924') -> ${r.matched_count} card(s): ${r.cards.map((c) => c.name).join(", ")}`); }); await check("get_card_details", async () => { const r = await handleToolCall("get_card_details", { card: "solayer-card" }); if (!r.review_url) throw new Error("missing review_url"); console.log(` get_card_details('solayer-card') -> ${r.review_url}`); }); await check("search_guides_and_faqs", async () => { const r = await handleToolCall("search_guides_and_faqs", { query: "giffgaff 保号" }); if (!r.results.length) throw new Error("no result for 'giffgaff 保号'"); console.log(` search_guides_and_faqs('giffgaff 保号') -> ${r.results[0].url}`); }); if (failed) { console.log(`${failed} check(s) failed.`); process.exit(1); } console.log("All data-layer checks passed."); } /* ------------------------------------------------------------------ * * JSON-RPC 主循环 * ------------------------------------------------------------------ */ function negotiateVersion(params) { const requested = params && params.protocolVersion; if (typeof requested === "string" && SUPPORTED_VERSIONS.includes(requested)) return requested; return PROTOCOL_VERSION; } async function handleRequest(req) { const { id, method, params } = req; if (id === undefined || id === null) return null; // notification if (method === "initialize") { return { jsonrpc: "2.0", id, result: { protocolVersion: negotiateVersion(params), capabilities: { tools: { listChanged: false } }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS, }, }; } if (method === "ping") { return { jsonrpc: "2.0", id, result: {} }; } if (method === "tools/list") { return { jsonrpc: "2.0", id, result: { tools: TOOLS } }; } if (method === "tools/call") { const name = params && params.name; if (typeof name !== "string" || !TOOL_NAMES.has(name)) { return { jsonrpc: "2.0", id, error: { code: -32602, message: `Unknown tool: ${name}`, data: { available_tools: [...TOOL_NAMES].sort() }, }, }; } try { const structured = await handleToolCall(name, params.arguments); return { jsonrpc: "2.0", id, result: buildToolResult(structured) }; } catch (err) { if (err instanceof InvalidParams) { return { jsonrpc: "2.0", id, error: { code: -32602, message: err.message } }; } if (err instanceof ToolExecutionError) { return { jsonrpc: "2.0", id, result: buildToolError(err.message) }; } throw err; } } return { jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` }, }; } if (process.argv.includes("--self-test")) { runSelfTest().catch((err) => { console.error(err); process.exit(1); }); } else { // 强制 UTF-8,避免 Windows 非英文区域设置下中文乱码 process.stdin.setEncoding("utf8"); const rl = readline.createInterface({ input: process.stdin, terminal: false }); rl.on("line", async (line) => { if (!line.trim()) return; let req; try { req = JSON.parse(line); } catch { return; } if (!req || typeof req !== "object") return; let resp = null; try { resp = await handleRequest(req); } catch (err) { if (req.id !== undefined && req.id !== null) { resp = { jsonrpc: "2.0", id: req.id, error: { code: -32603, message: `Internal error: ${err && err.message ? err.message : err}` }, }; } } if (resp) process.stdout.write(JSON.stringify(resp) + "\n"); }); }