1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
| #!/usr/bin/env python3
"""MCP stdio server 模板"""
import sys
import json
def handle(req):
mid = req.get("id")
method = req.get("method")
params = req.get("params", {})
# 必须处理的协议方法
if method == "initialize":
return {
"jsonrpc": "2.0", "id": mid,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "my-server", "version": "1.0.0"}
}
}
if method == "notifications/initialized":
return None
if method == "ping":
return {"jsonrpc": "2.0", "id": mid, "result": {}}
if method == "tools/list":
return {
"jsonrpc": "2.0", "id": mid,
"result": {
"tools": [
{
"name": "hello",
"description": "打招呼",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "名字"
}
}
}
}
]
}
}
if method == "tools/call":
tool = params.get("name")
args = params.get("arguments", {})
if tool == "hello":
name = args.get("name", "World")
return {
"jsonrpc": "2.0", "id": mid,
"result": {
"content": [{"type": "text", "text": f"Hello, {name}!"}]
}
}
return {
"jsonrpc": "2.0", "id": mid,
"error": {"code": -32601, "message": f"Unknown tool: {tool}"}
}
return {
"jsonrpc": "2.0", "id": mid,
"error": {"code": -32601, "message": f"Unknown method: {method}"}
}
def main():
sys.stderr.write("my-server: ready\n")
sys.stderr.flush()
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
req = json.loads(line)
resp = handle(req)
if resp is not None:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
sys.stdout.flush()
except json.JSONDecodeError:
continue
except (BrokenPipeError, EOFError):
break
if __name__ == "__main__":
main()
|