-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
71 lines (59 loc) · 2.05 KB
/
server.py
File metadata and controls
71 lines (59 loc) · 2.05 KB
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
#!/usr/bin/env python3
"""
MCP Server - Calculator Tool
Exposes a calculator through Model Context Protocol (MCP)
"""
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
# Create MCP server
app = Server("calculator-server")
# Step 1: Define available tools
@app.list_tools()
async def list_tools() -> list[Tool]:
"""Register the calculator tool with its JSON schema"""
return [
Tool(
name="calculator",
description="Performs arithmetic: add, subtract, multiply, divide",
inputSchema={
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["add", "subtract", "multiply", "divide"],
"description": "The operation to perform"
},
"a": {"type": "number", "description": "First number"},
"b": {"type": "number", "description": "Second number"}
},
"required": ["operation", "a", "b"]
}
)
]
# Step 2: Handle tool execution
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
"""Execute the calculator tool and return result"""
if name != "calculator":
raise ValueError(f"Unknown tool: {name}")
op = arguments["operation"]
a = arguments["a"]
b = arguments["b"]
# Perform the calculation
if op == "add":
result = a + b
elif op == "subtract":
result = a - b
elif op == "multiply":
result = a * b
elif op == "divide":
result = a / b if b != 0 else "Error: Division by zero"
return [TextContent(type="text", text=f"{a} {op} {b} = {result}")]
# Step 3: Run the server
async def main():
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())