|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import http.client |
| 4 | +import json |
| 5 | +from typing import Any, Optional |
| 6 | +from urllib.parse import urlparse |
| 7 | + |
| 8 | +from teaagent.mcp_http import MCP_PATH, SESSION_HEADER |
| 9 | + |
| 10 | + |
| 11 | +class MCPClientError(RuntimeError): |
| 12 | + pass |
| 13 | + |
| 14 | + |
| 15 | +class MCPHTTPClient: |
| 16 | + """Small stdlib client for TeaAgent's Streamable HTTP MCP transport.""" |
| 17 | + |
| 18 | + def __init__(self, endpoint: str, *, auth_token: Optional[str] = None) -> None: |
| 19 | + parsed = urlparse(endpoint) |
| 20 | + if parsed.scheme not in {'http', 'https'} or not parsed.hostname: |
| 21 | + raise ValueError('endpoint must be an http(s) URL') |
| 22 | + self.endpoint = endpoint.rstrip('/') |
| 23 | + self.auth_token = auth_token |
| 24 | + self.session_id: Optional[str] = None |
| 25 | + self._scheme = parsed.scheme |
| 26 | + self._host = parsed.hostname |
| 27 | + self._port = parsed.port or (443 if parsed.scheme == 'https' else 80) |
| 28 | + self._path = parsed.path or MCP_PATH |
| 29 | + |
| 30 | + def initialize(self) -> dict[str, Any]: |
| 31 | + payload = self._post({'jsonrpc': '2.0', 'id': 1, 'method': 'initialize'}) |
| 32 | + if self.session_id is None: |
| 33 | + raise MCPClientError('initialize response missing session id') |
| 34 | + return payload['result'] |
| 35 | + |
| 36 | + def list_tools(self) -> list[dict[str, Any]]: |
| 37 | + payload = self._post({'jsonrpc': '2.0', 'id': 2, 'method': 'tools/list'}) |
| 38 | + return list(payload['result']['tools']) |
| 39 | + |
| 40 | + def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: |
| 41 | + payload = self._post( |
| 42 | + { |
| 43 | + 'jsonrpc': '2.0', |
| 44 | + 'id': 3, |
| 45 | + 'method': 'tools/call', |
| 46 | + 'params': {'name': name, 'arguments': arguments}, |
| 47 | + } |
| 48 | + ) |
| 49 | + result = payload['result'] |
| 50 | + if result.get('isError'): |
| 51 | + content = result.get('content', []) |
| 52 | + message = ( |
| 53 | + content[0].get('text') |
| 54 | + if content and isinstance(content[0], dict) |
| 55 | + else 'tool call failed' |
| 56 | + ) |
| 57 | + raise MCPClientError(str(message)) |
| 58 | + return result |
| 59 | + |
| 60 | + def close(self) -> None: |
| 61 | + if self.session_id is None: |
| 62 | + return |
| 63 | + status, _headers, body = self._request('DELETE', None) |
| 64 | + self.session_id = None |
| 65 | + if status not in {204, 404}: |
| 66 | + raise MCPClientError(f'MCP close failed with HTTP {status}: {body!r}') |
| 67 | + |
| 68 | + def _post(self, payload: dict[str, Any]) -> dict[str, Any]: |
| 69 | + body = json.dumps(payload).encode('utf-8') |
| 70 | + status, headers, data = self._request('POST', body) |
| 71 | + if status != 200: |
| 72 | + raise MCPClientError(f'MCP request failed with HTTP {status}: {data!r}') |
| 73 | + if SESSION_HEADER in headers: |
| 74 | + self.session_id = headers[SESSION_HEADER] |
| 75 | + try: |
| 76 | + response = json.loads(data.decode('utf-8')) |
| 77 | + except (json.JSONDecodeError, UnicodeDecodeError) as exc: |
| 78 | + raise MCPClientError('MCP response was not valid JSON') from exc |
| 79 | + if 'error' in response: |
| 80 | + error = response['error'] |
| 81 | + message = error.get('message') if isinstance(error, dict) else str(error) |
| 82 | + raise MCPClientError(str(message)) |
| 83 | + return response |
| 84 | + |
| 85 | + def _request( |
| 86 | + self, method: str, body: Optional[bytes] |
| 87 | + ) -> tuple[int, dict[str, str], bytes]: |
| 88 | + connection_cls = ( |
| 89 | + http.client.HTTPSConnection |
| 90 | + if self._scheme == 'https' |
| 91 | + else http.client.HTTPConnection |
| 92 | + ) |
| 93 | + headers = self._headers(body) |
| 94 | + conn = connection_cls(self._host, self._port, timeout=10) |
| 95 | + try: |
| 96 | + conn.request(method, self._path, body=body, headers=headers) |
| 97 | + response = conn.getresponse() |
| 98 | + return response.status, dict(response.getheaders()), response.read() |
| 99 | + finally: |
| 100 | + conn.close() |
| 101 | + |
| 102 | + def _headers(self, body: Optional[bytes]) -> dict[str, str]: |
| 103 | + headers: dict[str, str] = {} |
| 104 | + if body is not None: |
| 105 | + headers['Content-Type'] = 'application/json' |
| 106 | + headers['Content-Length'] = str(len(body)) |
| 107 | + if self.auth_token is not None: |
| 108 | + headers['Authorization'] = f'Bearer {self.auth_token}' |
| 109 | + if self.session_id is not None: |
| 110 | + headers[SESSION_HEADER] = self.session_id |
| 111 | + return headers |
0 commit comments