#!/usr/bin/env python3 """ 示例:用 Python 写的 MCP 服务(同时支持两种跑法)。 1) 桌面/服务器 —— stdio 模式:内核把它当子进程起,走标准输入输出收发 JSON-RPC { "name": "py-demo", "transport": "stdio", "command": "python", "args": ["C:\\\\path\\\\to\\\\tools\\\\mcp_python_example.py"] } 2) 安卓端 —— inproc 模式:手机上没有独立 python 可执行文件,起不了子进程。 内核(Chaquopy 内嵌的 CPython)会直接 import 这个文件,调用下面的 handle()。 { "name": "py-demo", "transport": "inproc", "path": "/sdcard/.../mcp_python_example.py" } 所以这个文件里:协议实现完全一样,只是入口不同 —— `handle()` 给 inproc 用, `main()` 给 stdio 用。你自己写 MCP 工具时照抄这个骨架即可。 """ import json import os import platform import sys import urllib.request PROTOCOL_VERSION = "2024-11-05" SERVER_INFO = {"name": "py-demo", "version": "0.1.0"} TOOLS = [ { "name": "word_count", "description": "统计一段文本的字数、词数和行数", "inputSchema": { "type": "object", "properties": {"text": {"type": "string", "description": "要统计的文本"}}, "required": ["text"], }, }, { "name": "http_get", "description": "用 Python 抓一个 URL 并返回前 2000 个字符(演示网络能力)", "inputSchema": { "type": "object", "properties": {"url": {"type": "string", "description": "http/https 地址"}}, "required": ["url"], }, }, { "name": "host_info", "description": "返回运行这个 MCP 服务的机器/手机信息", "inputSchema": {"type": "object", "properties": {}}, }, ] def call_tool(name, args): """真正干活的地方。返回字符串就是工具结果。""" if name == "word_count": text = str(args.get("text", "")) return json.dumps( { "chars": len(text), "chars_no_space": len(text.replace(" ", "").replace("\n", "")), "words": len(text.split()), "lines": len(text.splitlines()) or 1, }, ensure_ascii=False, ) if name == "http_get": url = str(args.get("url", "")) if not url.startswith(("http://", "https://")): raise ValueError("url 必须是 http/https") req = urllib.request.Request(url, headers={"User-Agent": "py-demo-mcp/0.1"}) with urllib.request.urlopen(req, timeout=20) as resp: body = resp.read(200_000).decode("utf-8", errors="replace") return body[:2000] if name == "host_info": return json.dumps( { "python": sys.version.split()[0], "os": f"{platform.system()} {platform.release()}", "machine": platform.machine(), "cwd": os.getcwd(), "android": "ANDROID_ROOT" in os.environ or "ANDROID_DATA" in os.environ, }, ensure_ascii=False, ) raise ValueError(f"未知工具:{name}") def handle(request: dict) -> dict: """ 处理一条 JSON-RPC 请求,返回响应 dict(通知类请求返回 None)。 安卓 inproc 模式直接调它;stdio 模式的 main() 也是调它。 """ method = request.get("method") req_id = request.get("id") params = request.get("params") or {} # 通知没有 id,不需要回 if req_id is None and method and method.startswith("notifications/"): return None def ok(result): return {"jsonrpc": "2.0", "id": req_id, "result": result} def err(code, message): return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}} if method == "initialize": return ok( { "protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}}, "serverInfo": SERVER_INFO, } ) if method == "ping": return ok({}) if method == "tools/list": return ok({"tools": TOOLS}) if method == "tools/call": name = params.get("name") args = params.get("arguments") or {} try: text = call_tool(name, args) return ok({"content": [{"type": "text", "text": text}], "isError": False}) except Exception as exc: # noqa: BLE001 - 错误要回给模型看 return ok({"content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}], "isError": True}) return err(-32601, f"不支持的方法:{method}") def main(): """stdio 模式:一行一条 JSON-RPC。""" for line in sys.stdin: line = line.strip() if not line: continue try: request = json.loads(line) except json.JSONDecodeError: continue response = handle(request) if response is not None: sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n") sys.stdout.flush() if __name__ == "__main__": main()