"""MCP server (stdio, stdlib only) exposing the SCUT-SS RAG library to AI coding tools. Lets an external/cloud model (CodeBuddy, Cursor, Claude Desktop, Cherry Studio, ...) call local retrieval directly — no local model needed on the student's machine. Register it in your client's MCP config, e.g.: { "mcpServers": { "scut-ss": { "command": "python", "args": ["D:/Projects/其他项目/创作空间/MySpace/SCUT-SS/scripts/mcp_server.py"] } } } Manual smoke test: (echo {"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}; echo {...}) | python scripts/mcp_server.py """ import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from vectorstore import Index # noqa: E402 ROOT = Path(__file__).resolve().parent.parent INDEX_DIR = ROOT / "vectorstore" PAGES = ROOT / "data" / "dataset" / "pages.jsonl" SERVER_INFO = {"name": "scut-ss-rag", "version": "0.2.0"} PROTOCOL_VERSION = "2025-06-18" TOOLS = [ { "name": "search_materials", "description": ( "检索华南理工软件学院课程复习资料(软件体系结构/软件测试/数据库系统/软件项目管理/C++/线性代数/历年卷等)。" "提问前先调用它拿到真实资料,再基于资料回答;不要凭记忆编造考点。" ), "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "检索问题或关键词"}, "k": {"type": "integer", "description": "返回条数,默认 5", "default": 5}, "course": {"type": "string", "description": "可选,限定课程关键词,如 软件测试 / 数据库系统", "default": ""}, }, "required": ["query"], }, }, { "name": "list_courses", "description": "列出资料库包含的课程/分类及各自的资料篇数。", "inputSchema": {"type": "object", "properties": {}}, }, { "name": "get_material", "description": "按标题关键词取回一篇完整资料(页面级全文,超出长度会截断)。", "inputSchema": { "type": "object", "properties": { "title": {"type": "string", "description": "资料标题关键词"}, "max_chars": {"type": "integer", "description": "最大字符数,默认 8000", "default": 8000}, }, "required": ["title"], }, }, ] _state = {} def get_index(): if "index" not in _state: _state["index"] = Index(INDEX_DIR) return _state["index"] def load_pages(): if "pages" not in _state: pages = [] if PAGES.exists(): for line in PAGES.open(encoding="utf-8"): if line.strip(): pages.append(json.loads(line)) _state["pages"] = pages return _state["pages"] def tool_search(args): query = args.get("query", "").strip() if not query: return "请提供检索关键词。" k = int(args.get("k") or 5) course = (args.get("course") or "").strip() index = get_index() hits = index.search(query, k=max(k * 6, 20)) if course: filtered = [h for h in hits if course in (h[0].get("course") or "") or course in (h[0].get("path") or "")] hits = filtered or hits hits = hits[:k] if not hits: return f"资料库中没有检索到与「{query}」相关的内容。" out = [f"检索到 {len(hits)} 条资料(backend={index.meta['backend']}):\n"] for i, (chunk, score) in enumerate(hits, 1): out.append( f"[{i}] {chunk['path']}" + (f" · {chunk['section']}" if chunk.get("section") else "") + f"\n来源URL: {chunk.get('url', '')}\n相关度: {score:.3f}\n{chunk['text']}\n" ) return "\n".join(out) def tool_courses(_args): pages = load_pages() counts = {} for p in pages: counts.setdefault(p["course"], 0) counts[p["course"]] += 1 lines = [f"资料库共 {len(pages)} 篇资料,{sum(len(p['text']) for p in pages)} 字符。\n"] for course, n in sorted(counts.items(), key=lambda kv: -kv[1]): lines.append(f"- {course}:{n} 篇") return "\n".join(lines) def tool_get(args): title = (args.get("title") or "").strip() max_chars = int(args.get("max_chars") or 8000) pages = load_pages() hits = [p for p in pages if title in p["title"] or title in (p.get("path") or "")] if not hits: return f"没有找到标题包含「{title}」的资料,可先用 search_materials 检索。" p = max(hits, key=lambda x: len(x["text"])) text = p["text"][:max_chars] tail = "\n\n...(已截断,完整内容见 data/dataset/pages.jsonl)" if len(p["text"]) > max_chars else "" return f"# {p['title']}\n路径: {p['path']}\nURL: {p.get('url','')}\n\n{text}{tail}" HANDLERS = { "search_materials": tool_search, "list_courses": tool_courses, "get_material": tool_get, } def handle(req): method = req.get("method") params = req.get("params") or {} if method == "initialize": return { "protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {"listChanged": False}}, "serverInfo": SERVER_INFO, } if method == "tools/list": return {"tools": TOOLS} if method == "tools/call": name = params.get("name") handler = HANDLERS.get(name) if not handler: return {"content": [{"type": "text", "text": f"unknown tool: {name}"}], "isError": True} try: text = handler(params.get("arguments") or {}) except Exception as exc: # noqa: BLE001 return {"content": [{"type": "text", "text": f"tool error: {exc}"}], "isError": True} return {"content": [{"type": "text", "text": text}]} if method in ("ping", "notifications/initialized"): return {} return {} def main(): for _s in (sys.stdout, sys.stderr): try: _s.reconfigure(encoding="utf-8", errors="replace") except Exception: # noqa: BLE001 pass for line in sys.stdin: line = line.strip() if not line: continue try: req = json.loads(line) except json.JSONDecodeError: continue if "id" not in req: # notification continue resp = {"jsonrpc": "2.0", "id": req["id"], "result": handle(req)} sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n") sys.stdout.flush() if __name__ == "__main__": main()