#!/usr/bin/env python3 """ KanNetflix.com Official MCP Server (Zero-dependency Python 3, stdio JSON-RPC 2.0) Protocol: MCP 2025-11-25 (with graceful downgrade to 2025-06-18 / 2025-03-26 / 2024-11-05) Tools: 1. `search_crypto_cards` — filter 14+ tested crypto payment cards (BIN, China KYC, FX fees, Apple Pay, ChatGPT). 2. `get_card_details` — full real-world test record for one card. 3. `search_guides_and_faqs`— search all guides & verified FAQs. Usage: python3 server.py python3 server.py --self-test """ from __future__ import annotations import io import json import sys from pathlib import Path from typing import Any, Dict, List, Optional, Tuple try: # Python 3.9+ from urllib.request import Request, urlopen except ImportError: # pragma: no cover from urllib2 import Request, urlopen # type: ignore # --------------------------------------------------------------------------- # 协议常量 # --------------------------------------------------------------------------- SERVER_NAME = "kannetflix-subscription-mcp" SERVER_VERSION = "1.1.0" PROTOCOL_VERSION = "2025-11-25" SUPPORTED_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") SERVER_INFO = { "name": SERVER_NAME, "title": "KanNetflix (看奈飞) Cross-border Subscription Data", "version": SERVER_VERSION, } 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." ) REMOTE_BASE = "https://kannetflix.com/api" _HERE = Path(__file__).resolve().parent # 兼容三种部署位置:仓库 tools/ 目录、static/mcp 发布目录、用户本地 ~/.mcp/kannetflix CANDIDATE_API_DIRS = [ _HERE / "api", _HERE.parent / "static" / "api", _HERE.parent.parent / "static" / "api", ] # --------------------------------------------------------------------------- # 输出 JSON Schema(MCP 2025-06-18+ 的 outputSchema / structuredContent) # --------------------------------------------------------------------------- _CARD_SUMMARY_PROPS = { "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"}, } def _obj(properties: Dict[str, Any], required: Optional[List[str]] = None) -> Dict[str, Any]: schema: Dict[str, Any] = {"type": "object", "properties": properties} if required: schema["required"] = required return schema CARD_SEARCH_OUTPUT = _obj( { "source": {"type": "string"}, "matched_count": {"type": "integer"}, "cards": {"type": "array", "items": _obj(_CARD_SUMMARY_PROPS)}, }, ["matched_count", "cards"], ) CARD_DETAIL_OUTPUT = _obj( { "found": {"type": "boolean"}, "card": {"type": "object"}, "review_url": {"type": "string"}, }, ["found", "card"], ) GUIDE_SEARCH_OUTPUT = _obj( { "source": {"type": "string"}, "query": {"type": "string"}, "results": { "type": "array", "items": _obj( { "title": {"type": "string"}, "url": {"type": "string"}, "lastmod": {"type": "string"}, "direct_answer": {"type": "string"}, "verification": {"type": "string"}, "matched_faqs": {"type": "array", "items": {"type": "object"}}, } ), }, }, ["results"], ) _READ_ONLY = { "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": False, } TOOLS: List[Dict[str, Any]] = [ { "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": _obj( { "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": CARD_SEARCH_OUTPUT, "annotations": _READ_ONLY, }, { "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": _obj( { "card": { "type": "string", "description": "Card slug or name (e.g. 'solayer-card', 'bybit-card', 'bitget-card', 'etherfi-card')", } }, ["card"], ), "outputSchema": CARD_DETAIL_OUTPUT, "annotations": _READ_ONLY, }, { "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": _obj( { "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", }, }, ["query"], ), "outputSchema": GUIDE_SEARCH_OUTPUT, "annotations": _READ_ONLY, }, ] TOOL_NAMES = {t["name"] for t in TOOLS} # --------------------------------------------------------------------------- # 错误类型 # --------------------------------------------------------------------------- class InvalidParams(Exception): """协议层错误 → JSON-RPC -32602""" class ToolExecutionError(Exception): """工具执行层错误 → result.isError = true,让模型有机会自我纠正""" # --------------------------------------------------------------------------- # 数据加载 # --------------------------------------------------------------------------- def _local_dataset(filename: str) -> Optional[Dict[str, Any]]: for directory in CANDIDATE_API_DIRS: candidate = directory / filename if candidate.is_file(): return json.loads(candidate.read_text(encoding="utf-8")) return None def load_dataset(filename: str) -> Dict[str, Any]: local = _local_dataset(filename) if local is not None: return local req = Request( "{}/{}".format(REMOTE_BASE, filename), headers={"User-Agent": "KanNetflix-MCP/{} (+https://kannetflix.com)".format(SERVER_VERSION)}, ) try: with urlopen(req, timeout=15) as resp: return json.loads(resp.read().decode("utf-8")) except Exception as exc: # noqa: BLE001 raise ToolExecutionError( "无法获取数据源 {}/{}(本地无缓存且网络请求失败:{})。" "请检查网络后重试,或改用网页版 https://kannetflix.com/api/{}。".format( REMOTE_BASE, filename, exc, filename ) ) def _s(value: Any) -> str: """把 None / 数字 / 列表统一成字符串,保证输出满足 outputSchema。""" if value is None: return "" if isinstance(value, str): return value if isinstance(value, (list, tuple)): return ", ".join(_s(v) for v in value) return str(value) # --------------------------------------------------------------------------- # 参数校验(不合规 → -32602) # --------------------------------------------------------------------------- def _require_str(args: Dict[str, Any], key: str) -> str: value = args.get(key) if not isinstance(value, str) or not value.strip(): raise InvalidParams("Missing required argument '{}' (non-empty string).".format(key)) return value.strip() def _optional_enum(args: Dict[str, Any], key: str, allowed: Tuple[str, ...]) -> Optional[str]: value = args.get(key) if value is None: return None if not isinstance(value, str) or value not in allowed: raise InvalidParams("Argument '{}' must be one of: {}.".format(key, ", ".join(allowed))) return value def _optional_bool(args: Dict[str, Any], key: str) -> Optional[bool]: value = args.get(key) if value is None: return None if not isinstance(value, bool): raise InvalidParams("Argument '{}' must be a boolean.".format(key)) return value # --------------------------------------------------------------------------- # 工具实现:返回 structuredContent 对象 # --------------------------------------------------------------------------- def handle_tool_call(name: str, args: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: args = args or {} if not isinstance(args, dict): raise InvalidParams("Argument 'arguments' must be an object.") if name == "search_crypto_cards": cn_filter = _optional_enum(args, "mainland_china_available", ("yes", "limited", "no", "any")) apple_pay = _optional_bool(args, "apple_pay") tested_chatgpt = _optional_bool(args, "tested_chatgpt") data = load_dataset("crypto-cards.json") cards = data.get("cards", []) if cn_filter and cn_filter != "any": cards = [c for c in cards if c.get("mainland_china_available") == cn_filter] if apple_pay is True: cards = [c for c in cards if c.get("apple_pay") in ("yes", "limited")] if tested_chatgpt is True: cards = [c for c in cards if c.get("tested_chatgpt") in ("success", "partial")] if args.get("query"): q = _s(args["query"]).lower() cards = [c for c in cards if q in json.dumps(c, ensure_ascii=False).lower()] summary = [ { "name": _s(c.get("name")), "slug": _s(c.get("slug")), "network": _s(c.get("network")), "card_bin": _s(c.get("card_bin")) or "N/A", "use_case": _s(c.get("use_case")), "mainland_china_available": _s(c.get("mainland_china_available")), "open_fee": _s(c.get("open_fee")), "annual_fee": _s(c.get("annual_fee")), "conversion_fee": _s(c.get("conversion_fee")), "fx_fee": _s(c.get("fx_fee")), "apple_pay": _s(c.get("apple_pay")), "alipay": _s(c.get("alipay")), "tested_chatgpt": _s(c.get("tested_chatgpt")), "review_url": _s(c.get("full_article_url")), } for c in cards ] return { "source": "https://kannetflix.com/pay/", "matched_count": len(summary), "cards": summary, } if name == "get_card_details": q = _require_str(args, "card").lower() data = load_dataset("crypto-cards.json") for card in data.get("cards", []): slug = _s(card.get("slug")).lower() if slug == q or (q and q in _s(card.get("name")).lower()): return { "found": True, "card": card, "review_url": _s(card.get("full_article_url")), } slugs = ", ".join(_s(c.get("slug")) for c in data.get("cards", [])) raise ToolExecutionError( "Card '{}' not found. Available slugs: {}".format(args.get("card"), slugs) ) if name == "search_guides_and_faqs": query = _require_str(args, "query") section = _optional_enum(args, "section", ("all", "pay", "esim", "ai", "main", "recommend")) data = load_dataset("site-index.json") tokens = [t for t in query.lower().split() if t] pages = data.get("pages", []) if section and section != "all": pages = [p for p in pages if p.get("section") == section] scored: List[Tuple[int, Dict[str, Any]]] = [] for page in pages: hay = json.dumps(page, ensure_ascii=False).lower() score = 0 for token in tokens: if token in _s(page.get("title")).lower(): score += 5 if token in _s(page.get("direct_answer")).lower(): score += 3 if token in hay: score += 2 if score > 0: scored.append((score, page)) scored.sort(key=lambda item: item[0], reverse=True) results = [ { "title": _s(p.get("title")), "url": _s(p.get("full_url")), "lastmod": _s(p.get("lastmod")), "direct_answer": _s(p.get("direct_answer")), "verification": _s(p.get("verification")), "matched_faqs": (p.get("faqs") or [])[:3], } for _, p in scored[:6] ] return { "source": "https://kannetflix.com", "query": query, "results": results, } raise InvalidParams("Unknown tool: {}".format(name)) def build_tool_result(structured: Dict[str, Any]) -> Dict[str, Any]: return { "content": [{"type": "text", "text": json.dumps(structured, ensure_ascii=False, indent=2)}], "structuredContent": structured, "isError": False, } def build_tool_error(message: str) -> Dict[str, Any]: return { "content": [{"type": "text", "text": message}], "isError": True, } # --------------------------------------------------------------------------- # 自检 # --------------------------------------------------------------------------- def run_self_test() -> int: print("Running KanNetflix MCP Server (Python) self-test...") failures = 0 def check(label: str, fn) -> None: nonlocal failures try: fn() print("✅ " + label) except Exception as exc: # noqa: BLE001 failures += 1 print("❌ {} -> {}".format(label, exc)) def t1() -> None: r = handle_tool_call("search_crypto_cards", {"query": "454924"}) assert r["matched_count"] >= 1, "no card matched BIN 454924" print(" search_crypto_cards('454924') -> {} card(s): {}".format( r["matched_count"], ", ".join(c["name"] for c in r["cards"]))) def t2() -> None: r = handle_tool_call("get_card_details", {"card": "solayer-card"}) assert r["review_url"], "missing review_url" print(" get_card_details('solayer-card') -> {}".format(r["review_url"])) def t3() -> None: r = handle_tool_call("search_guides_and_faqs", {"query": "giffgaff 保号"}) assert r["results"], "no result for 'giffgaff 保号'" print(" search_guides_and_faqs('giffgaff 保号') -> {}".format(r["results"][0]["url"])) check("search_crypto_cards", t1) check("get_card_details", t2) check("search_guides_and_faqs", t3) if failures: print("{} check(s) failed.".format(failures)) return 1 print("All data-layer checks passed.") return 0 # --------------------------------------------------------------------------- # JSON-RPC 主循环 # --------------------------------------------------------------------------- def _negotiate_version(params: Dict[str, Any]) -> str: requested = params.get("protocolVersion") if isinstance(requested, str) and requested in SUPPORTED_VERSIONS: return requested return PROTOCOL_VERSION def handle_request(req: Dict[str, Any]) -> Optional[Dict[str, Any]]: """返回 None 表示这是 notification,不需要响应。""" req_id = req.get("id") method = req.get("method") params = req.get("params") or {} if req_id is None: return None # notification:initialized / cancelled 等,无需响应 if method == "initialize": return { "jsonrpc": "2.0", "id": req_id, "result": { "protocolVersion": _negotiate_version(params), "capabilities": {"tools": {"listChanged": False}}, "serverInfo": SERVER_INFO, "instructions": INSTRUCTIONS, }, } if method == "ping": return {"jsonrpc": "2.0", "id": req_id, "result": {}} if method == "tools/list": return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}} if method == "tools/call": name = params.get("name") if not isinstance(name, str) or name not in TOOL_NAMES: return { "jsonrpc": "2.0", "id": req_id, "error": { "code": -32602, "message": "Unknown tool: {}".format(name), "data": {"available_tools": sorted(TOOL_NAMES)}, }, } try: structured = handle_tool_call(name, params.get("arguments")) except InvalidParams as exc: return { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": str(exc)}, } except ToolExecutionError as exc: return {"jsonrpc": "2.0", "id": req_id, "result": build_tool_error(str(exc))} return {"jsonrpc": "2.0", "id": req_id, "result": build_tool_result(structured)} return { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": "Method not found: {}".format(method)}, } def main() -> int: if "--self-test" in sys.argv: return run_self_test() # 强制 UTF-8:Windows 默认 cp936 会让中文 JSON 变成乱码 if hasattr(sys.stdin, "buffer"): sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace") if hasattr(sys.stdout, "buffer"): sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", newline="\n") for line in sys.stdin: line = line.strip() if not line: continue try: req = json.loads(line) except ValueError: continue if not isinstance(req, dict): continue try: resp = handle_request(req) except Exception as exc: # noqa: BLE001 req_id = req.get("id") resp = None if req_id is not None: resp = { "jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": "Internal error: {}".format(exc)}, } if resp is not None: sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n") sys.stdout.flush() return 0 if __name__ == "__main__": sys.exit(main())