hat.drivers.mcp
1import base64 2import collections 3import typing 4 5import aiohttp.web 6 7from hat import aio 8from hat import json 9 10 11class Tool(typing.NamedTuple): 12 name: str 13 title: str | None 14 description: str | None 15 input_schema: json.Object 16 output_schema: json.Object | None 17 call_cb: aio.AsyncCallable[[json.Object | None], json.Object] 18 19 20class Server: 21 22 def __init__(self, 23 name: str, 24 version: str = '1.0.0', 25 path: str = '/', 26 cache_ttl: float = 60 * 60, 27 instructions: str | None = None): 28 self._instructions = instructions 29 self._meta = { 30 'io.modelcontextprotocol/serverInfo': {'name': name, 31 'version': version}} 32 self._route = aiohttp.web.post(path, self._process) 33 self._cache_ttl_ms = round(cache_ttl * 1000) 34 self._tools = {} 35 36 @property 37 def route(self) -> aiohttp.web.RouteDef: 38 return self._route 39 40 def add_tool(self, tool: Tool): 41 self._tools[tool.name] = tool 42 43 async def _process(self, req): 44 jsonrpc_id = None 45 46 try: 47 try: 48 body = await req.json() 49 50 except Exception: 51 raise _McpParseError() 52 53 if (not isinstance(body, dict) or 54 body.get('jsonrpc') != '2.0' or 55 not isinstance(body.get('method'), str)): 56 raise _McpInvalidRequestError() 57 58 if 'id' not in body: 59 return aiohttp.web.Response(status=202) 60 61 jsonrpc_id = body['id'] 62 if (not isinstance(jsonrpc_id, (str, int)) or 63 isinstance(jsonrpc_id, bool)): 64 raise _McpInvalidRequestError() 65 66 try: 67 meta = body['params']['_meta'] 68 if not isinstance(meta, dict): 69 raise Exception() 70 71 except Exception: 72 raise _McpInvalidRequestError() 73 74 try: 75 version = req.headers.getone('MCP-Protocol-Version') 76 77 if meta['io.modelcontextprotocol/protocolVersion'] != version: 78 raise Exception() 79 80 except Exception: 81 raise _McpHeaderMismatchError() 82 83 if version != _supported_version: 84 raise _McpUnsupportedProtocolVersionError(version) 85 86 try: 87 method = req.headers.getone('Mcp-Method') 88 89 if method != body['method']: 90 raise Exception() 91 92 except Exception: 93 raise _McpHeaderMismatchError() 94 95 try: 96 if body['method'] == 'server/discover': 97 result = self._process_server_discover() 98 99 elif body['method'] == 'tools/list': 100 result = self._process_tools_list() 101 102 elif body['method'] == 'tools/call': 103 result = await self._process_tools_call(req.headers, 104 body['params']) 105 106 else: 107 raise _McpMethodNotFoundError() 108 109 data = {'jsonrpc': '2.0', 110 'id': jsonrpc_id, 111 'result': { 112 '_meta': self._meta, 113 'resultType': 'complete', 114 **result}} 115 116 return aiohttp.web.json_response(data) 117 118 except _McpError: 119 raise 120 121 except Exception: 122 raise _McpInternalError() 123 124 except _McpError as e: 125 data = {'jsonrpc': '2.0', 126 'error': {'code': e.jsonrpc_code, 127 'message': e.message}} 128 129 if jsonrpc_id is not None: 130 data['id'] = jsonrpc_id 131 132 if e.data is not None: 133 data['error']['data'] = e.data 134 135 return aiohttp.web.json_response(data, status=e.http_code) 136 137 except Exception: 138 raise aiohttp.web.HTTPInternalServerError() 139 140 def _process_server_discover(self): 141 capabilities = {} 142 143 if self._tools: 144 capabilities['tools'] = {'listChanged': False} 145 146 result = {'supportedVersions': [_supported_version], 147 'capabilities': capabilities, 148 'ttlMs': self._cache_ttl_ms, 149 'cacheScope': 'public'} 150 151 if self._instructions is not None: 152 result['instructions'] = self._instructions 153 154 return result 155 156 def _process_tools_list(self): 157 tools = collections.deque() 158 159 for tool in self._tools.values(): 160 data = {'name': tool.name, 161 'inputSchema': tool.input_schema} 162 163 if tool.title is not None: 164 data['title'] = tool.title 165 166 if tool.description is not None: 167 data['description'] = tool.description 168 169 if tool.output_schema is not None: 170 data['outputSchema'] = tool.output_schema 171 172 tools.append(data) 173 174 return {'tools': list(tools), 175 'ttlMs': self._cache_ttl_ms, 176 'cacheScope': 'public'} 177 178 async def _process_tools_call(self, headers, params): 179 try: 180 tool = self._tools[params['name']] 181 182 args = params.get('arguments') 183 if args is not None and not isinstance(args, dict): 184 raise Exception() 185 186 except Exception: 187 raise _McpInvalidParamsError() 188 189 try: 190 name = _decode_header_value(headers.getone('Mcp-Name')) 191 192 if name != params['name']: 193 raise Exception() 194 195 except Exception: 196 raise _McpHeaderMismatchError() 197 198 try: 199 result = await aio.call(tool.call_cb, args) 200 201 except Exception as e: 202 return {'content': [{'type': 'text', 203 'text': str(e)}], 204 'isError': True} 205 206 if not isinstance(result, dict): 207 raise _McpInternalError() 208 209 return {'content': [{'type': 'text', 210 'text': json.encode(result)}], 211 'structuredContent': result} 212 213 214def _decode_header_value(value): 215 if value.startswith('=?base64?') and value.endswith('?='): 216 return base64.b64decode(value[9:-2]).decode('utf-8') 217 218 return value 219 220 221class _McpError(Exception): 222 223 def __init__(self, 224 http_code: int, 225 jsonrpc_code: int, 226 message: str, 227 data: json.Object | None = None): 228 super().__init__(message) 229 230 self._http_code = http_code 231 self._jsonrpc_code = jsonrpc_code 232 self._message = message 233 self._data = data 234 235 @property 236 def http_code(self) -> int: 237 return self._http_code 238 239 @property 240 def jsonrpc_code(self) -> int: 241 return self._jsonrpc_code 242 243 @property 244 def message(self) -> str: 245 return self._message 246 247 @property 248 def data(self) -> json.Object | None: 249 return self._data 250 251 252class _McpParseError(_McpError): 253 254 def __init__(self): 255 super().__init__(http_code=400, 256 jsonrpc_code=-32700, 257 message='Parse error') 258 259 260class _McpInvalidRequestError(_McpError): 261 262 def __init__(self): 263 super().__init__(http_code=400, 264 jsonrpc_code=-32600, 265 message='Invalid request') 266 267 268class _McpHeaderMismatchError(_McpError): 269 270 def __init__(self): 271 super().__init__(http_code=400, 272 jsonrpc_code=-32020, 273 message='Header mismatch') 274 275 276class _McpUnsupportedProtocolVersionError(_McpError): 277 278 def __init__(self, requested_version: str): 279 super().__init__(http_code=400, 280 jsonrpc_code=-32022, 281 message='Unsupported protocol version', 282 data={'supported': [_supported_version], 283 'requested': requested_version}) 284 285 286class _McpMethodNotFoundError(_McpError): 287 288 def __init__(self): 289 super().__init__(http_code=404, 290 jsonrpc_code=-32601, 291 message='Method not found') 292 293 294class _McpInvalidParamsError(_McpError): 295 296 def __init__(self): 297 super().__init__(http_code=400, 298 jsonrpc_code=-32602, 299 message='Invalid params') 300 301 302class _McpInternalError(_McpError): 303 304 def __init__(self): 305 super().__init__(http_code=500, 306 jsonrpc_code=-32603, 307 message='Internal error') 308 309 310_supported_version = '2026-07-28'
class
Tool(typing.NamedTuple):
12class Tool(typing.NamedTuple): 13 name: str 14 title: str | None 15 description: str | None 16 input_schema: json.Object 17 output_schema: json.Object | None 18 call_cb: aio.AsyncCallable[[json.Object | None], json.Object]
Tool(name, title, description, input_schema, output_schema, call_cb)
Tool( name: str, title: str | None, description: str | None, input_schema: Dict[str, ForwardRef('Data')], output_schema: Dict[str, ForwardRef('Data')] | None, call_cb: Callable[[Dict[str, ForwardRef('Data')] | None], Dict[str, ForwardRef('Data')] | Awaitable[Dict[str, ForwardRef('Data')]]])
Create new instance of Tool(name, title, description, input_schema, output_schema, call_cb)
class
Server:
21class Server: 22 23 def __init__(self, 24 name: str, 25 version: str = '1.0.0', 26 path: str = '/', 27 cache_ttl: float = 60 * 60, 28 instructions: str | None = None): 29 self._instructions = instructions 30 self._meta = { 31 'io.modelcontextprotocol/serverInfo': {'name': name, 32 'version': version}} 33 self._route = aiohttp.web.post(path, self._process) 34 self._cache_ttl_ms = round(cache_ttl * 1000) 35 self._tools = {} 36 37 @property 38 def route(self) -> aiohttp.web.RouteDef: 39 return self._route 40 41 def add_tool(self, tool: Tool): 42 self._tools[tool.name] = tool 43 44 async def _process(self, req): 45 jsonrpc_id = None 46 47 try: 48 try: 49 body = await req.json() 50 51 except Exception: 52 raise _McpParseError() 53 54 if (not isinstance(body, dict) or 55 body.get('jsonrpc') != '2.0' or 56 not isinstance(body.get('method'), str)): 57 raise _McpInvalidRequestError() 58 59 if 'id' not in body: 60 return aiohttp.web.Response(status=202) 61 62 jsonrpc_id = body['id'] 63 if (not isinstance(jsonrpc_id, (str, int)) or 64 isinstance(jsonrpc_id, bool)): 65 raise _McpInvalidRequestError() 66 67 try: 68 meta = body['params']['_meta'] 69 if not isinstance(meta, dict): 70 raise Exception() 71 72 except Exception: 73 raise _McpInvalidRequestError() 74 75 try: 76 version = req.headers.getone('MCP-Protocol-Version') 77 78 if meta['io.modelcontextprotocol/protocolVersion'] != version: 79 raise Exception() 80 81 except Exception: 82 raise _McpHeaderMismatchError() 83 84 if version != _supported_version: 85 raise _McpUnsupportedProtocolVersionError(version) 86 87 try: 88 method = req.headers.getone('Mcp-Method') 89 90 if method != body['method']: 91 raise Exception() 92 93 except Exception: 94 raise _McpHeaderMismatchError() 95 96 try: 97 if body['method'] == 'server/discover': 98 result = self._process_server_discover() 99 100 elif body['method'] == 'tools/list': 101 result = self._process_tools_list() 102 103 elif body['method'] == 'tools/call': 104 result = await self._process_tools_call(req.headers, 105 body['params']) 106 107 else: 108 raise _McpMethodNotFoundError() 109 110 data = {'jsonrpc': '2.0', 111 'id': jsonrpc_id, 112 'result': { 113 '_meta': self._meta, 114 'resultType': 'complete', 115 **result}} 116 117 return aiohttp.web.json_response(data) 118 119 except _McpError: 120 raise 121 122 except Exception: 123 raise _McpInternalError() 124 125 except _McpError as e: 126 data = {'jsonrpc': '2.0', 127 'error': {'code': e.jsonrpc_code, 128 'message': e.message}} 129 130 if jsonrpc_id is not None: 131 data['id'] = jsonrpc_id 132 133 if e.data is not None: 134 data['error']['data'] = e.data 135 136 return aiohttp.web.json_response(data, status=e.http_code) 137 138 except Exception: 139 raise aiohttp.web.HTTPInternalServerError() 140 141 def _process_server_discover(self): 142 capabilities = {} 143 144 if self._tools: 145 capabilities['tools'] = {'listChanged': False} 146 147 result = {'supportedVersions': [_supported_version], 148 'capabilities': capabilities, 149 'ttlMs': self._cache_ttl_ms, 150 'cacheScope': 'public'} 151 152 if self._instructions is not None: 153 result['instructions'] = self._instructions 154 155 return result 156 157 def _process_tools_list(self): 158 tools = collections.deque() 159 160 for tool in self._tools.values(): 161 data = {'name': tool.name, 162 'inputSchema': tool.input_schema} 163 164 if tool.title is not None: 165 data['title'] = tool.title 166 167 if tool.description is not None: 168 data['description'] = tool.description 169 170 if tool.output_schema is not None: 171 data['outputSchema'] = tool.output_schema 172 173 tools.append(data) 174 175 return {'tools': list(tools), 176 'ttlMs': self._cache_ttl_ms, 177 'cacheScope': 'public'} 178 179 async def _process_tools_call(self, headers, params): 180 try: 181 tool = self._tools[params['name']] 182 183 args = params.get('arguments') 184 if args is not None and not isinstance(args, dict): 185 raise Exception() 186 187 except Exception: 188 raise _McpInvalidParamsError() 189 190 try: 191 name = _decode_header_value(headers.getone('Mcp-Name')) 192 193 if name != params['name']: 194 raise Exception() 195 196 except Exception: 197 raise _McpHeaderMismatchError() 198 199 try: 200 result = await aio.call(tool.call_cb, args) 201 202 except Exception as e: 203 return {'content': [{'type': 'text', 204 'text': str(e)}], 205 'isError': True} 206 207 if not isinstance(result, dict): 208 raise _McpInternalError() 209 210 return {'content': [{'type': 'text', 211 'text': json.encode(result)}], 212 'structuredContent': result}
Server( name: str, version: str = '1.0.0', path: str = '/', cache_ttl: float = 3600, instructions: str | None = None)
23 def __init__(self, 24 name: str, 25 version: str = '1.0.0', 26 path: str = '/', 27 cache_ttl: float = 60 * 60, 28 instructions: str | None = None): 29 self._instructions = instructions 30 self._meta = { 31 'io.modelcontextprotocol/serverInfo': {'name': name, 32 'version': version}} 33 self._route = aiohttp.web.post(path, self._process) 34 self._cache_ttl_ms = round(cache_ttl * 1000) 35 self._tools = {}