Files
zhiyejineng-exam/mcp-from-scratch-mytry.py

76 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""只用 sys + json,从零实现一个 MCP Server
提供 calculate_bmi(height, weight) 工具。
"""
import sys
import json
def process(request):
if request.get("method") == "ping":
result = {
"jsonrpc": "2.0",
"id": request.get("id"),
"result": "pong"
}
return result
if request.get("method") == "tools/list":
result = {
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "calculate_bmi",
"description": "Calculate BMI from height and weight",
"inputSchema": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
}
},
"required": [
"height",
"weight"
]
}
}
]
}
}
return result
if request.get("method") == "tools/call":
name = request.get("params", {}).get("name")
arguments = request.get("params", {}).get("arguments", {})
if name == "calculate_bmi":
height = arguments.get("height")
weight = arguments.get("weight")
if height is not None and weight is not None:
bmi = weight / (height ** 2)
result = {
"jsonrpc": "2.0",
"id": request.get("id"),
"result": {
"resultType": "complete",
"content": [
{
"type": "text",
"text": str(bmi)
}
],
"isError": False
}
}
return result
return None
for line in sys.stdin:
request = json.loads(line)
output = process(request)
if output is not None:
print(json.dumps(output, ensure_ascii=False), flush=True)