97 lines
3.4 KiB
Python
97 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""mcp_call.py — 通过 stdio 驱动 dcloud-mcp(无需重启本会话)
|
|
用法:
|
|
python3 mcp_call.py list # 列全部工具
|
|
python3 mcp_call.py call <tool_name> '<json_arguments>' # 调用工具
|
|
"""
|
|
import json, subprocess, sys, threading, os
|
|
|
|
BIN = os.path.expanduser("~/.local/bin/dcloud-mcp")
|
|
|
|
class MCP:
|
|
def __init__(self):
|
|
self.p = subprocess.Popen([BIN], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL, text=True, bufsize=1)
|
|
self.id = 0
|
|
self.lock = threading.Lock()
|
|
|
|
def _read_msg(self):
|
|
line = self.p.stdout.readline()
|
|
if not line:
|
|
raise RuntimeError("dcloud-mcp 进程退出")
|
|
return json.loads(line)
|
|
|
|
def request(self, method, params=None, timeout=120):
|
|
with self.lock:
|
|
self.id += 1
|
|
mid = self.id
|
|
msg = {"jsonrpc": "2.0", "id": mid, "method": method}
|
|
if params is not None:
|
|
msg["params"] = params
|
|
self.p.stdin.write(json.dumps(msg) + "\n")
|
|
self.p.stdin.flush()
|
|
import queue
|
|
q = queue.Queue()
|
|
def reader():
|
|
try:
|
|
while True:
|
|
m = self._read_msg()
|
|
q.put(m)
|
|
if m.get("id") == mid:
|
|
break
|
|
except Exception as e:
|
|
q.put({"error": str(e)})
|
|
t = threading.Thread(target=reader, daemon=True)
|
|
t.start()
|
|
try:
|
|
while True:
|
|
m = q.get(timeout=timeout)
|
|
if m.get("id") == mid:
|
|
return m
|
|
# 忽略通知(日志等)
|
|
except queue.Empty:
|
|
raise RuntimeError(f"{method} 超时 {timeout}s")
|
|
|
|
def init(self):
|
|
r = self.request("initialize", {
|
|
"protocolVersion": "2024-11-05",
|
|
"capabilities": {},
|
|
"clientInfo": {"name": "jev-train-cli", "version": "0.1"}}, timeout=30)
|
|
self.p.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
|
|
self.p.stdin.flush()
|
|
return r
|
|
|
|
def list_tools(self):
|
|
r = self.request("tools/list", {}, timeout=60)
|
|
return r.get("result", {}).get("tools", [])
|
|
|
|
def call(self, name, args, timeout=300):
|
|
r = self.request("tools/call", {"name": name, "arguments": args}, timeout=timeout)
|
|
res = r.get("result", {})
|
|
if res.get("isError"):
|
|
return {"ERROR": True, "content": res.get("content")}
|
|
return res.get("content")
|
|
|
|
def close(self):
|
|
self.p.stdin.close()
|
|
self.p.wait(timeout=10)
|
|
|
|
def main():
|
|
mcp = MCP()
|
|
mcp.init()
|
|
if sys.argv[1] == "list":
|
|
for t in mcp.list_tools():
|
|
desc = (t.get("description") or "").strip().split("\n")[0][:90]
|
|
print(f"{t['name']:<40} {desc}")
|
|
elif sys.argv[1] == "call":
|
|
out = mcp.call(sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {})
|
|
for c in (out if isinstance(out, list) else [out]):
|
|
if isinstance(c, dict) and c.get("type") == "text":
|
|
print(c.get("text", ""))
|
|
else:
|
|
print(json.dumps(c, ensure_ascii=False) if c is not None else "")
|
|
mcp.close()
|
|
|
|
if __name__ == "__main__":
|
|
main()
|