-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathserver.py
More file actions
235 lines (209 loc) · 8.04 KB
/
Copy pathserver.py
File metadata and controls
235 lines (209 loc) · 8.04 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/env python3
"""Minimal mock MCP server for E2E tests with optional OAuth support.
By default, requires Bearer authentication on every request (except /health).
Pass ``--no-auth`` to disable authentication and serve all requests openly.
Run as ``python server.py [--port PORT] [--no-auth]``; default port is 3000.
"""
import argparse
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import Any, Optional
# Standard OAuth-style challenge so the client can drive an OAuth flow
WWW_AUTHENTICATE = 'Bearer realm="mock-mcp", error="invalid_token"'
_TWO_NUMBER_SCHEMA: dict = {
"type": "object",
"properties": {
"a": {"type": "number", "description": "First operand"},
"b": {"type": "number", "description": "Second operand"},
},
"required": ["a", "b"],
}
def _math_tool_schemas() -> list[dict]:
"""Return MCP tool descriptors for the four arithmetic operations."""
return [
{
"name": "add",
"description": "Add two numbers",
"inputSchema": _TWO_NUMBER_SCHEMA,
},
{
"name": "subtract",
"description": "Subtract two numbers (a - b)",
"inputSchema": _TWO_NUMBER_SCHEMA,
},
{
"name": "multiply",
"description": "Multiply two numbers",
"inputSchema": _TWO_NUMBER_SCHEMA,
},
{
"name": "divide",
"description": "Divide two numbers (a / b)",
"inputSchema": _TWO_NUMBER_SCHEMA,
},
]
class Handler(BaseHTTPRequestHandler):
"""HTTP handler for MCP JSON-RPC with optional Bearer auth."""
require_auth: bool = True
def _require_oauth(self) -> None:
"""Send 401 with WWW-Authenticate."""
self.send_response(401)
self.send_header("WWW-Authenticate", WWW_AUTHENTICATE)
self.send_header("Content-Type", "application/json")
body = b'{"error":"unauthorized"}'
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _parse_auth(self) -> Optional[str]:
"""Return Bearer token if present, else None.
When ``require_auth`` is False, always returns a sentinel value so
every request is treated as authenticated.
"""
if not self.require_auth:
return "no-auth"
auth = self.headers.get("Authorization")
if auth and auth.startswith("Bearer ") and "invalid" not in auth:
return auth[7:].strip()
return None
def _json_response(self, data: dict) -> None:
"""Send JSON response."""
body = json.dumps(data).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self) -> None: # pylint: disable=invalid-name
"""Handle GET requests."""
path_only = self.path.split("?", 1)[0]
if path_only == "/health":
self._json_response({"status": "ok"})
elif self._parse_auth() is not None:
self._json_response({"status": "authorized"})
else:
self._require_oauth()
def do_POST(self) -> None: # pylint: disable=invalid-name
"""Handle POST requests."""
if self._parse_auth() is None:
self._require_oauth()
return
length = int(self.headers.get("Content-Length", 0))
raw = self.rfile.read(length) if length else b"{}"
try:
req = json.loads(raw.decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError):
req = {}
req_id = req.get("id", 1)
method = req.get("method", "")
if method == "initialize":
self._json_response(
{
"jsonrpc": "2.0",
"id": req_id,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "mock-mcp-e2e", "version": "1.0.0"},
},
}
)
elif method == "tools/list":
self._json_response(
{
"jsonrpc": "2.0",
"id": req_id,
"result": {
"tools": [
{
"name": "mock_tool_e2e",
"description": "Mock tool for E2E",
"inputSchema": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "Test message",
}
},
},
},
*_math_tool_schemas(),
],
},
}
)
elif method == "tools/call":
self._handle_tool_call(req, req_id)
else:
self._json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
def _handle_tool_call(self, req: dict, req_id: int) -> None:
"""Dispatch tools/call requests to the appropriate handler."""
params = req.get("params", {})
tool_name = params.get("name", "")
arguments = params.get("arguments", {})
ops = {
"add": lambda a, b: a + b,
"subtract": lambda a, b: a - b,
"multiply": lambda a, b: a * b,
"divide": lambda a, b: a / b,
}
if tool_name in ops:
a = arguments.get("a", 0)
b = arguments.get("b", 0)
if tool_name == "divide" and b == 0:
self._json_response(
{
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [
{"type": "text", "text": "Error: division by zero"}
],
"isError": True,
},
}
)
return
result = ops[tool_name](a, b)
self._json_response(
{
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [{"type": "text", "text": str(result)}],
},
}
)
else:
self._json_response(
{
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [
{"type": "text", "text": f"Unknown tool: {tool_name}"}
],
"isError": True,
},
}
)
def log_message(self, format: str, *args: Any) -> None:
"""Suppress request logging for minimal output."""
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Mock MCP server for E2E tests")
parser.add_argument("--port", type=int, default=3000, help="Port to listen on")
parser.add_argument(
"--no-auth",
action="store_true",
default=False,
help="Disable Bearer authentication",
)
# Legacy positional port for backward compatibility
parser.add_argument("legacy_port", nargs="?", type=int, default=None)
args = parser.parse_args()
port = args.legacy_port if args.legacy_port is not None else args.port
Handler.require_auth = not args.no_auth
mode = "open (no auth)" if args.no_auth else "auth required"
server = HTTPServer(("0.0.0.0", port), Handler)
print(f"Mock MCP server on :{port} [{mode}]")
server.serve_forever()