| 1 | """Opt-in Parallel Search MCP adapter using stdlib Streamable HTTP.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import http.client as http_client |
| 6 | import json |
| 7 | import re |
| 8 | import socket |
| 9 | import threading |
| 10 | import time |
| 11 | import urllib.error |
| 12 | import urllib.request |
| 13 | from concurrent.futures import Future |
| 14 | from contextvars import ContextVar |
| 15 | from typing import Any |
| 16 | from urllib.parse import urlparse |
| 17 | |
| 18 | from . import dates, http, usage |
| 19 | |
| 20 | PARALLEL_MCP_URL = "https://search.parallel.ai/mcp" |
| 21 | _PROTOCOL_VERSION = "2025-03-26" |
| 22 | _MAX_RESPONSE_BYTES = 4 * 1024 * 1024 |
| 23 | _MAX_SSE_LINES = 10_000 |
| 24 | _MAX_SSE_EVENTS = 1_000 |
| 25 | _MAX_TOOLS_LIST_PAGES = 5 |
| 26 | _MAX_SESSION_REQUESTS = 9 |
| 27 | _DEFAULT_SEARCH_TIMEOUT = 60.0 |
| 28 | _CLEANUP_TIMEOUT = 3.0 |
| 29 | _READ_CHUNK_BYTES = 65_536 |
| 30 | _DEADLINE_JITTER_SECONDS = 0.05 |
| 31 | |
| 32 | _BEARER_TOKEN_RE = re.compile(r"\b(Bearer\s+)\S+", re.IGNORECASE) |
| 33 | |
| 34 | # Threads the shared search deadline/cancel/timeout budget into _request without |
| 35 | # adding extra kwargs to search()'s _request calls (preserving 3-arg test mocks). |
| 36 | _REQUEST_BUDGET: ContextVar[tuple[float | None, threading.Event | None, float | None] | None] = ContextVar( |
| 37 | "last30days_parallel_mcp_budget", |
| 38 | default=None, |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | class _NoRedirect(urllib.request.HTTPRedirectHandler): |
| 43 | def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 44 | # The endpoint is fixed. Never forward credentials, session IDs, or |
| 45 | # search data to a redirect target, including an HTTPS downgrade. |
| 46 | return None |
| 47 | |
| 48 | |
| 49 | def _scrub_secret_text(text: Any, redactions: frozenset[str] = frozenset()) -> str: |
| 50 | cleaned = str(text or "") |
| 51 | cleaned = http._URL_USERINFO_RE.sub(r"\1", cleaned) |
| 52 | cleaned = _BEARER_TOKEN_RE.sub(r"\1<redacted>", cleaned) |
| 53 | if redactions: |
| 54 | cleaned = http._scrub_fixture_value(cleaned, redactions=redactions) |
| 55 | return cleaned[:500] |
| 56 | |
| 57 | |
| 58 | def _remaining_seconds( |
| 59 | deadline_monotonic: float | None, |
| 60 | cancel: threading.Event | None, |
| 61 | ) -> float | None: |
| 62 | if cancel is not None and cancel.is_set(): |
| 63 | raise http.DeadlineExceeded() |
| 64 | if deadline_monotonic is None: |
| 65 | return None |
| 66 | remaining = deadline_monotonic - time.monotonic() |
| 67 | if remaining <= 0: |
| 68 | raise http.DeadlineExceeded() |
| 69 | return remaining |
| 70 | |
| 71 | |
| 72 | def _response_socket(response: Any) -> Any: |
| 73 | fp = getattr(response, "fp", None) |
| 74 | raw = getattr(fp, "raw", None) |
| 75 | return getattr(raw, "_sock", None) or getattr(fp, "_sock", None) or getattr(response, "_sock", None) |
| 76 | |
| 77 | |
| 78 | def _shutdown_socket(sock: Any) -> None: |
| 79 | if sock is not None and hasattr(sock, "shutdown"): |
| 80 | try: |
| 81 | sock.shutdown(socket.SHUT_RDWR) |
| 82 | except OSError: |
| 83 | pass |
| 84 | |
| 85 | |
| 86 | def _effective_socket_timeout( |
| 87 | request_timeout: float | None, |
| 88 | remaining: float | None, |
| 89 | ) -> tuple[float | None, bool]: |
| 90 | """Return ``(socket_timeout, clamped_to_deadline)`` bounded by both limits.""" |
| 91 | if request_timeout is None and remaining is None: |
| 92 | return None, False |
| 93 | if request_timeout is None: |
| 94 | return max(0.001, remaining), True |
| 95 | if remaining is None: |
| 96 | return max(0.001, request_timeout), False |
| 97 | clamped = remaining <= request_timeout |
| 98 | return max(0.001, min(request_timeout, remaining)), clamped |
| 99 | |
| 100 | |
| 101 | def _set_response_timeout( |
| 102 | response: Any, |
| 103 | remaining: float | None = None, |
| 104 | *, |
| 105 | request_timeout: float | None = None, |
| 106 | ) -> bool: |
| 107 | """Clamp response socket timeout to ``min(request_timeout, remaining)``.""" |
| 108 | timeout_val, clamped = _effective_socket_timeout(request_timeout, remaining) |
| 109 | if timeout_val is None: |
| 110 | return False |
| 111 | sock = _response_socket(response) |
| 112 | if sock is not None and hasattr(sock, "settimeout"): |
| 113 | try: |
| 114 | sock.settimeout(timeout_val) |
| 115 | except OSError: |
| 116 | pass |
| 117 | return clamped |
| 118 | |
| 119 | |
| 120 | def _is_deadline_timeout( |
| 121 | deadline_monotonic: float | None, |
| 122 | cancel: threading.Event | None, |
| 123 | *, |
| 124 | clamped_to_deadline: bool = True, |
| 125 | ) -> bool: |
| 126 | if cancel is not None and cancel.is_set(): |
| 127 | return True |
| 128 | if deadline_monotonic is None: |
| 129 | return False |
| 130 | now = time.monotonic() |
| 131 | if now >= deadline_monotonic: |
| 132 | return True |
| 133 | return clamped_to_deadline and now >= (deadline_monotonic - _DEADLINE_JITTER_SECONDS) |
| 134 | |
| 135 | |
| 136 | def _abort_response(response: Any) -> None: |
| 137 | """Unblock a worker thread waiting in recv() without taking BufferedReader's lock.""" |
| 138 | if response is None: |
| 139 | return |
| 140 | _shutdown_socket(_response_socket(response)) |
| 141 | |
| 142 | |
| 143 | class _AbortState: |
| 144 | """Tracks active socket/response across TCP connect, headers, and body reads.""" |
| 145 | |
| 146 | def __init__(self) -> None: |
| 147 | self._lock = threading.Lock() |
| 148 | self._aborted = False |
| 149 | self._sock: Any = None |
| 150 | self._response: Any = None |
| 151 | |
| 152 | def register_socket(self, sock: Any) -> None: |
| 153 | with self._lock: |
| 154 | self._sock = sock |
| 155 | aborted = self._aborted |
| 156 | if aborted: |
| 157 | _shutdown_socket(sock) |
| 158 | raise http.DeadlineExceeded() |
| 159 | |
| 160 | def register_response(self, response: Any) -> None: |
| 161 | with self._lock: |
| 162 | self._response = response |
| 163 | sock = _response_socket(response) |
| 164 | if sock is not None: |
| 165 | self._sock = sock |
| 166 | aborted = self._aborted |
| 167 | if aborted: |
| 168 | _abort_response(response) |
| 169 | _shutdown_socket(sock) |
| 170 | raise http.DeadlineExceeded() |
| 171 | |
| 172 | def clear(self) -> None: |
| 173 | with self._lock: |
| 174 | self._response = None |
| 175 | self._sock = None |
| 176 | |
| 177 | def abort(self) -> None: |
| 178 | with self._lock: |
| 179 | self._aborted = True |
| 180 | sock = self._sock |
| 181 | response = self._response |
| 182 | _shutdown_socket(sock) |
| 183 | if response is not None: |
| 184 | _abort_response(response) |
| 185 | |
| 186 | |
| 187 | def _make_abortable_handlers(abort_state: _AbortState) -> list[Any]: |
| 188 | def _create_tracked_connection( |
| 189 | address: tuple[str, int], |
| 190 | timeout: Any = socket._GLOBAL_DEFAULT_TIMEOUT, |
| 191 | source_address: Any = None, |
| 192 | ) -> socket.socket: |
| 193 | sock = socket.create_connection(address, timeout, source_address) |
| 194 | try: |
| 195 | abort_state.register_socket(sock) |
| 196 | except BaseException: |
| 197 | sock.close() |
| 198 | raise |
| 199 | return sock |
| 200 | |
| 201 | class _AbortableHTTPConnection(http_client.HTTPConnection): |
| 202 | def __init__(self, *args, **kwargs): |
| 203 | super().__init__(*args, **kwargs) |
| 204 | self._create_connection = _create_tracked_connection |
| 205 | |
| 206 | def connect(self) -> None: |
| 207 | super().connect() |
| 208 | abort_state.register_socket(self.sock) |
| 209 | |
| 210 | class _AbortableHTTPHandler(urllib.request.HTTPHandler): |
| 211 | def http_open(self, req): |
| 212 | return self.do_open(_AbortableHTTPConnection, req) |
| 213 | |
| 214 | handlers: list[Any] = [_NoRedirect(), _AbortableHTTPHandler()] |
| 215 | if hasattr(http_client, "HTTPSConnection"): |
| 216 | class _AbortableHTTPSConnection(http_client.HTTPSConnection): |
| 217 | def __init__(self, *args, **kwargs): |
| 218 | super().__init__(*args, **kwargs) |
| 219 | self._create_connection = _create_tracked_connection |
| 220 | |
| 221 | def connect(self) -> None: |
| 222 | # Open TCP (and optional CONNECT tunnel) first via HTTPConnection.connect(), |
| 223 | # which already registers the raw TCP socket with abort_state. |
| 224 | http_client.HTTPConnection.connect(self) |
| 225 | server_hostname = self._tunnel_host if self._tunnel_host else self.host |
| 226 | raw_sock = self.sock |
| 227 | try: |
| 228 | tls_sock = self._context.wrap_socket( |
| 229 | raw_sock, |
| 230 | server_hostname=server_hostname, |
| 231 | do_handshake_on_connect=False, |
| 232 | ) |
| 233 | except BaseException: |
| 234 | self.sock = None |
| 235 | try: |
| 236 | raw_sock.close() |
| 237 | except OSError: |
| 238 | pass |
| 239 | raise |
| 240 | self.sock = tls_sock |
| 241 | try: |
| 242 | # Register the TLS socket before starting the handshake so |
| 243 | # cancel/deadline abort can shut it down if ServerHello stalls. |
| 244 | abort_state.register_socket(tls_sock) |
| 245 | tls_sock.do_handshake() |
| 246 | except BaseException: |
| 247 | self.sock = None |
| 248 | try: |
| 249 | tls_sock.close() |
| 250 | except OSError: |
| 251 | pass |
| 252 | raise |
| 253 | |
| 254 | class _AbortableHTTPSHandler(urllib.request.HTTPSHandler): |
| 255 | def https_open(self, req): |
| 256 | return self.do_open(_AbortableHTTPSConnection, req, context=self._context) |
| 257 | |
| 258 | handlers.append(_AbortableHTTPSHandler()) |
| 259 | return handlers |
| 260 | |
| 261 | |
| 262 | def _matching_response(payload: bytes, request_id: int | None) -> dict[str, Any] | None: |
| 263 | try: |
| 264 | value = json.loads(payload) |
| 265 | except (UnicodeDecodeError, json.JSONDecodeError) as exc: |
| 266 | raise RuntimeError("Parallel MCP returned an invalid JSON-RPC response") from exc |
| 267 | # The negotiated 2025-03-26 protocol permits batched SSE messages. |
| 268 | for message in value if isinstance(value, list) else [value]: |
| 269 | if not isinstance(message, dict) or message.get("jsonrpc") != "2.0": |
| 270 | raise RuntimeError("Parallel MCP returned an invalid JSON-RPC response") |
| 271 | if message.get("id") == request_id and ("result" in message or "error" in message): |
| 272 | return message |
| 273 | return None |
| 274 | |
| 275 | |
| 276 | def _read_response( |
| 277 | response: Any, |
| 278 | request_id: int | None, |
| 279 | *, |
| 280 | deadline_monotonic: float | None = None, |
| 281 | cancel: threading.Event | None = None, |
| 282 | request_timeout: float | None = None, |
| 283 | ) -> dict[str, Any]: |
| 284 | if "text/event-stream" not in response.headers.get("Content-Type", "").lower(): |
| 285 | remaining = _remaining_seconds(deadline_monotonic, cancel) |
| 286 | clamped = _set_response_timeout(response, remaining, request_timeout=request_timeout) |
| 287 | if hasattr(response, "read1"): |
| 288 | chunks: list[bytes] = [] |
| 289 | total = 0 |
| 290 | while True: |
| 291 | remaining = _remaining_seconds(deadline_monotonic, cancel) |
| 292 | clamped = _set_response_timeout(response, remaining, request_timeout=request_timeout) |
| 293 | to_read = min(_READ_CHUNK_BYTES, _MAX_RESPONSE_BYTES - total + 1) |
| 294 | try: |
| 295 | chunk = response.read1(to_read) |
| 296 | except TimeoutError as exc: |
| 297 | if _is_deadline_timeout(deadline_monotonic, cancel, clamped_to_deadline=clamped): |
| 298 | raise http.DeadlineExceeded() from exc |
| 299 | raise |
| 300 | if not chunk: |
| 301 | break |
| 302 | total += len(chunk) |
| 303 | if total > _MAX_RESPONSE_BYTES: |
| 304 | raise RuntimeError("Parallel MCP response exceeded 4 MiB") |
| 305 | chunks.append(chunk) |
| 306 | payload = b"".join(chunks) |
| 307 | else: |
| 308 | try: |
| 309 | payload = response.read(_MAX_RESPONSE_BYTES + 1) |
| 310 | except TimeoutError as exc: |
| 311 | if _is_deadline_timeout(deadline_monotonic, cancel, clamped_to_deadline=clamped): |
| 312 | raise http.DeadlineExceeded() from exc |
| 313 | raise |
| 314 | if len(payload) > _MAX_RESPONSE_BYTES: |
| 315 | raise RuntimeError("Parallel MCP response exceeded 4 MiB") |
| 316 | _remaining_seconds(deadline_monotonic, cancel) |
| 317 | if request_id is None and not payload: |
| 318 | return {} |
| 319 | result = _matching_response(payload, request_id) if payload else None |
| 320 | if result is not None: |
| 321 | return result |
| 322 | else: |
| 323 | data: list[bytes] = [] |
| 324 | total = 0 |
| 325 | lines_seen = 0 |
| 326 | events_seen = 0 |
| 327 | |
| 328 | def _process_line(raw_line: bytes) -> dict[str, Any] | None: |
| 329 | nonlocal lines_seen, events_seen, data |
| 330 | lines_seen += 1 |
| 331 | if lines_seen > _MAX_SSE_LINES: |
| 332 | raise RuntimeError("Parallel MCP SSE stream exceeded line limit") |
| 333 | line = raw_line.rstrip(b"\r\n") |
| 334 | if not line and data: |
| 335 | events_seen += 1 |
| 336 | if events_seen > _MAX_SSE_EVENTS: |
| 337 | raise RuntimeError("Parallel MCP SSE stream exceeded event limit") |
| 338 | result = _matching_response(b"\n".join(data), request_id) |
| 339 | if result is not None: |
| 340 | # A valid response completes the request, even if the |
| 341 | # server keeps the stream open or sends more notifications. |
| 342 | return result |
| 343 | data = [] |
| 344 | elif line.startswith(b"data:"): |
| 345 | value = line[5:] |
| 346 | data.append(value[1:] if value.startswith(b" ") else value) |
| 347 | return None |
| 348 | |
| 349 | if hasattr(response, "read1"): |
| 350 | buf = bytearray() |
| 351 | scan_pos = 0 |
| 352 | while True: |
| 353 | line_start = 0 |
| 354 | while True: |
| 355 | nl = buf.find(b"\n", scan_pos) |
| 356 | if nl < 0: |
| 357 | if line_start: |
| 358 | del buf[:line_start] |
| 359 | scan_pos = len(buf) |
| 360 | break |
| 361 | raw_line = bytes(buf[line_start:nl + 1]) |
| 362 | line_start = nl + 1 |
| 363 | scan_pos = line_start |
| 364 | result = _process_line(raw_line) |
| 365 | if result is not None: |
| 366 | return result |
| 367 | remaining = _remaining_seconds(deadline_monotonic, cancel) |
| 368 | clamped = _set_response_timeout( |
| 369 | response, remaining, request_timeout=request_timeout, |
| 370 | ) |
| 371 | to_read = min(_READ_CHUNK_BYTES, _MAX_RESPONSE_BYTES - total + 1) |
| 372 | try: |
| 373 | chunk = response.read1(to_read) |
| 374 | except TimeoutError as exc: |
| 375 | if _is_deadline_timeout( |
| 376 | deadline_monotonic, cancel, clamped_to_deadline=clamped, |
| 377 | ): |
| 378 | raise http.DeadlineExceeded() from exc |
| 379 | raise |
| 380 | if not chunk: |
| 381 | if buf: |
| 382 | result = _process_line(bytes(buf)) |
| 383 | if result is not None: |
| 384 | return result |
| 385 | break |
| 386 | total += len(chunk) |
| 387 | if total > _MAX_RESPONSE_BYTES: |
| 388 | raise RuntimeError("Parallel MCP response exceeded 4 MiB") |
| 389 | buf.extend(chunk) |
| 390 | else: |
| 391 | while True: |
| 392 | remaining = _remaining_seconds(deadline_monotonic, cancel) |
| 393 | clamped = _set_response_timeout( |
| 394 | response, remaining, request_timeout=request_timeout, |
| 395 | ) |
| 396 | try: |
| 397 | raw_line = response.readline(_MAX_RESPONSE_BYTES - total + 1) |
| 398 | except TimeoutError as exc: |
| 399 | if _is_deadline_timeout( |
| 400 | deadline_monotonic, cancel, clamped_to_deadline=clamped, |
| 401 | ): |
| 402 | raise http.DeadlineExceeded() from exc |
| 403 | raise |
| 404 | total += len(raw_line) |
| 405 | if total > _MAX_RESPONSE_BYTES: |
| 406 | raise RuntimeError("Parallel MCP response exceeded 4 MiB") |
| 407 | if not raw_line: |
| 408 | break |
| 409 | result = _process_line(raw_line) |
| 410 | if result is not None: |
| 411 | return result |
| 412 | raise RuntimeError("Parallel MCP response is missing the requested JSON-RPC result") |
| 413 | |
| 414 | |
| 415 | def _request( |
| 416 | message: dict[str, Any] | None, |
| 417 | api_key: str | None, |
| 418 | session_id: str | None = None, |
| 419 | *, |
| 420 | deadline_monotonic: float | None = None, |
| 421 | cancel: threading.Event | None = None, |
| 422 | timeout: float | None = None, |
| 423 | ) -> tuple[dict[str, Any], str | None]: |
| 424 | budget = _REQUEST_BUDGET.get() |
| 425 | if budget is not None: |
| 426 | if deadline_monotonic is None: |
| 427 | deadline_monotonic = budget[0] |
| 428 | if cancel is None: |
| 429 | cancel = budget[1] |
| 430 | if timeout is None: |
| 431 | timeout = budget[2] |
| 432 | http._check_http_scheme(PARALLEL_MCP_URL) |
| 433 | remaining = _remaining_seconds(deadline_monotonic, cancel) |
| 434 | base_timeout = float(http.DEFAULT_TIMEOUT if timeout is None else timeout) |
| 435 | effective_timeout, clamped_to_deadline = _effective_socket_timeout(base_timeout, remaining) |
| 436 | redactions = frozenset({api_key}) if isinstance(api_key, str) and len(api_key) >= 4 else frozenset() |
| 437 | |
| 438 | headers = { |
| 439 | "Accept": "application/json, text/event-stream", |
| 440 | "Content-Type": "application/json", |
| 441 | "User-Agent": http.USER_AGENT, |
| 442 | } |
| 443 | if api_key: |
| 444 | headers["Authorization"] = f"Bearer {api_key}" |
| 445 | if session_id: |
| 446 | headers["Mcp-Session-Id"] = session_id |
| 447 | if message is None or message.get("method") != "initialize": |
| 448 | headers["MCP-Protocol-Version"] = _PROTOCOL_VERSION |
| 449 | request = urllib.request.Request( |
| 450 | PARALLEL_MCP_URL, |
| 451 | data=json.dumps(message, separators=(",", ":")).encode("utf-8") if message is not None else None, |
| 452 | headers=headers, |
| 453 | method="POST" if message is not None else "DELETE", |
| 454 | ) |
| 455 | if api_key and message is not None and message.get("method") == "tools/call": |
| 456 | usage.begin("parallel") |
| 457 | |
| 458 | def _do_request(abort_state: _AbortState) -> tuple[dict[str, Any], str | None]: |
| 459 | try: |
| 460 | with urllib.request.build_opener(*_make_abortable_handlers(abort_state)).open( |
| 461 | request, timeout=max(0.001, effective_timeout or base_timeout), |
| 462 | ) as response: |
| 463 | abort_state.register_response(response) |
| 464 | try: |
| 465 | if cancel is not None and cancel.is_set(): |
| 466 | raise http.DeadlineExceeded() |
| 467 | result = ( |
| 468 | _read_response( |
| 469 | response, |
| 470 | message.get("id"), |
| 471 | deadline_monotonic=deadline_monotonic, |
| 472 | cancel=cancel, |
| 473 | request_timeout=base_timeout, |
| 474 | ) |
| 475 | if message is not None |
| 476 | else {} |
| 477 | ) |
| 478 | return result, response.headers.get("Mcp-Session-Id") or session_id |
| 479 | finally: |
| 480 | abort_state.clear() |
| 481 | except urllib.error.HTTPError as exc: |
| 482 | clean_reason = _scrub_secret_text(exc.reason, redactions) |
| 483 | clean_url = _scrub_secret_text(exc.url, redactions) |
| 484 | if clean_reason != str(exc.reason or "") or clean_url != str(exc.url or ""): |
| 485 | try: |
| 486 | exc.close() |
| 487 | except Exception: |
| 488 | pass |
| 489 | raise urllib.error.HTTPError( |
| 490 | clean_url, exc.code, clean_reason, exc.headers, None, |
| 491 | ) from None |
| 492 | raise |
| 493 | except TimeoutError as exc: |
| 494 | if _is_deadline_timeout( |
| 495 | deadline_monotonic, cancel, clamped_to_deadline=clamped_to_deadline, |
| 496 | ): |
| 497 | raise http.DeadlineExceeded() from exc |
| 498 | raise |
| 499 | except urllib.error.URLError as exc: |
| 500 | reason = getattr(exc, "reason", None) |
| 501 | if ( |
| 502 | _is_deadline_timeout( |
| 503 | deadline_monotonic, cancel, clamped_to_deadline=clamped_to_deadline, |
| 504 | ) |
| 505 | and (isinstance(reason, TimeoutError) or "timed out" in str(reason).lower()) |
| 506 | ): |
| 507 | raise http.DeadlineExceeded() from exc |
| 508 | clean_reason = _scrub_secret_text(reason, redactions) |
| 509 | if clean_reason != str(reason or ""): |
| 510 | raise urllib.error.URLError(clean_reason) from None |
| 511 | raise |
| 512 | finally: |
| 513 | abort_state.clear() |
| 514 | |
| 515 | if deadline_monotonic is None and cancel is None: |
| 516 | return _do_request(_AbortState()) |
| 517 | |
| 518 | abort_state = _AbortState() |
| 519 | future: Future = Future() |
| 520 | |
| 521 | def _worker() -> None: |
| 522 | try: |
| 523 | if cancel is not None and cancel.is_set(): |
| 524 | raise http.DeadlineExceeded() |
| 525 | future.set_result(_do_request(abort_state)) |
| 526 | except BaseException as exc: |
| 527 | future.set_exception(exc) |
| 528 | |
| 529 | threading.Thread(target=_worker, name="parallel-mcp-request", daemon=True).start() |
| 530 | wait_deadline = ( |
| 531 | deadline_monotonic |
| 532 | if deadline_monotonic is not None |
| 533 | else (time.monotonic() + (effective_timeout or base_timeout)) |
| 534 | ) |
| 535 | while True: |
| 536 | if cancel is not None and cancel.is_set(): |
| 537 | abort_state.abort() |
| 538 | raise http.DeadlineExceeded() |
| 539 | rem = wait_deadline - time.monotonic() |
| 540 | if rem <= 0: |
| 541 | if future.done(): |
| 542 | return future.result() |
| 543 | abort_state.abort() |
| 544 | raise http.DeadlineExceeded() |
| 545 | poll = min(rem, 0.05) if cancel is not None else rem |
| 546 | try: |
| 547 | return future.result(timeout=poll) |
| 548 | except TimeoutError: |
| 549 | if future.done(): |
| 550 | return future.result() |
| 551 | if cancel is None: |
| 552 | abort_state.abort() |
| 553 | raise http.DeadlineExceeded() |
| 554 | |
| 555 | |
| 556 | def _result(response: dict[str, Any], *, redactions: frozenset[str] = frozenset()) -> dict[str, Any]: |
| 557 | if response.get("error"): |
| 558 | error = response["error"] |
| 559 | detail = error.get("message") if isinstance(error, dict) else str(error) |
| 560 | safe_detail = _scrub_secret_text(detail, redactions) |
| 561 | raise RuntimeError(f"Parallel MCP error: {safe_detail}") |
| 562 | result = response.get("result") |
| 563 | if not isinstance(result, dict): |
| 564 | raise RuntimeError("Parallel MCP response is missing its result") |
| 565 | return result |
| 566 | |
| 567 | |
| 568 | def _search_rows(tool_result: dict[str, Any]) -> list[dict[str, Any]]: |
| 569 | payloads = [tool_result.get("structuredContent")] |
| 570 | for content in tool_result.get("content") or []: |
| 571 | if not isinstance(content, dict) or content.get("type") != "text": |
| 572 | continue |
| 573 | try: |
| 574 | payloads.append(json.loads(content.get("text") or "")) |
| 575 | except (TypeError, ValueError): |
| 576 | continue |
| 577 | for candidates in payloads: |
| 578 | if isinstance(candidates, dict) and "data" in candidates and "results" not in candidates: |
| 579 | candidates = candidates["data"] |
| 580 | if isinstance(candidates, dict): |
| 581 | candidates = candidates.get("results") |
| 582 | if isinstance(candidates, list): |
| 583 | return [row for row in candidates if isinstance(row, dict)] |
| 584 | raise RuntimeError("Parallel MCP web_search returned no results array") |
| 585 | |
| 586 | |
| 587 | def search( |
| 588 | query: str, |
| 589 | date_range: tuple[str, str], |
| 590 | api_key: str | None = None, |
| 591 | count: int = 5, |
| 592 | *, |
| 593 | deadline_monotonic: float | None = None, |
| 594 | cancel: threading.Event | None = None, |
| 595 | ) -> tuple[list[dict[str, Any]], dict[str, Any]]: |
| 596 | """Discover and invoke hosted ``web_search`` after explicit dispatcher opt-in.""" |
| 597 | default_deadline = time.monotonic() + _DEFAULT_SEARCH_TIMEOUT |
| 598 | effective_deadline = ( |
| 599 | min(deadline_monotonic, default_deadline) |
| 600 | if deadline_monotonic is not None |
| 601 | else default_deadline |
| 602 | ) |
| 603 | redactions = frozenset({api_key}) if isinstance(api_key, str) and len(api_key) >= 4 else frozenset() |
| 604 | requests_issued = 0 |
| 605 | |
| 606 | def _issue(message: dict[str, Any], session_id: str | None = None) -> tuple[dict[str, Any], str | None]: |
| 607 | nonlocal requests_issued |
| 608 | _remaining_seconds(effective_deadline, cancel) |
| 609 | if requests_issued >= _MAX_SESSION_REQUESTS - 1: |
| 610 | raise RuntimeError("Parallel MCP session request limit exceeded") |
| 611 | requests_issued += 1 |
| 612 | if session_id is None and message.get("method") == "initialize": |
| 613 | return _request(message, api_key) |
| 614 | return _request(message, api_key, session_id) |
| 615 | |
| 616 | token = _REQUEST_BUDGET.set((effective_deadline, cancel, None)) |
| 617 | session_id: str | None = None |
| 618 | try: |
| 619 | initialized, session_id = _issue( |
| 620 | { |
| 621 | "jsonrpc": "2.0", |
| 622 | "id": 1, |
| 623 | "method": "initialize", |
| 624 | "params": { |
| 625 | "protocolVersion": _PROTOCOL_VERSION, |
| 626 | "capabilities": {}, |
| 627 | "clientInfo": {"name": "last30days-skill", "version": "3"}, |
| 628 | }, |
| 629 | }, |
| 630 | ) |
| 631 | if _result(initialized, redactions=redactions).get("protocolVersion") != _PROTOCOL_VERSION: |
| 632 | raise RuntimeError("Parallel MCP negotiated an unsupported protocol version") |
| 633 | _issue( |
| 634 | {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}, |
| 635 | session_id, |
| 636 | ) |
| 637 | request_id = 2 |
| 638 | params: dict[str, Any] = {} |
| 639 | seen_cursors: set[str] = set() |
| 640 | pages_fetched = 0 |
| 641 | while True: |
| 642 | tools_response, _ = _issue( |
| 643 | {"jsonrpc": "2.0", "id": request_id, "method": "tools/list", "params": params}, |
| 644 | session_id, |
| 645 | ) |
| 646 | request_id += 1 |
| 647 | pages_fetched += 1 |
| 648 | page = _result(tools_response, redactions=redactions) |
| 649 | tools = page.get("tools") or [] |
| 650 | if any(isinstance(tool, dict) and tool.get("name") == "web_search" for tool in tools): |
| 651 | break |
| 652 | cursor = page.get("nextCursor") |
| 653 | if ( |
| 654 | not isinstance(cursor, str) |
| 655 | or not cursor |
| 656 | or cursor in seen_cursors |
| 657 | or pages_fetched >= _MAX_TOOLS_LIST_PAGES |
| 658 | ): |
| 659 | raise RuntimeError("Parallel MCP did not advertise web_search") |
| 660 | seen_cursors.add(cursor) |
| 661 | params = {"cursor": cursor} |
| 662 | objective = f"Find useful public web evidence about {query} from {date_range[0]} through {date_range[1]}." |
| 663 | called, _ = _issue( |
| 664 | { |
| 665 | "jsonrpc": "2.0", |
| 666 | "id": request_id, |
| 667 | "method": "tools/call", |
| 668 | "params": { |
| 669 | "name": "web_search", |
| 670 | "arguments": {"objective": objective, "search_queries": [query]}, |
| 671 | }, |
| 672 | }, |
| 673 | session_id, |
| 674 | ) |
| 675 | finally: |
| 676 | try: |
| 677 | if session_id and (cancel is None or not cancel.is_set()): |
| 678 | rem = effective_deadline - time.monotonic() |
| 679 | if rem > 0: |
| 680 | cleanup_timeout = min(_CLEANUP_TIMEOUT, rem) |
| 681 | cleanup_token = _REQUEST_BUDGET.set( |
| 682 | (time.monotonic() + cleanup_timeout, cancel, cleanup_timeout) |
| 683 | ) |
| 684 | try: |
| 685 | _request(None, api_key, session_id) |
| 686 | except urllib.error.HTTPError as error: |
| 687 | error.close() |
| 688 | except (OSError, RuntimeError, ValueError, http.HTTPError, http_client.HTTPException): |
| 689 | # Cleanup is best-effort: unsupported DELETEs, malformed responses, |
| 690 | # or a network failure must not hide search results or the original error. |
| 691 | pass |
| 692 | finally: |
| 693 | _REQUEST_BUDGET.reset(cleanup_token) |
| 694 | finally: |
| 695 | _REQUEST_BUDGET.reset(token) |
| 696 | |
| 697 | tool_result = _result(called, redactions=redactions) |
| 698 | if tool_result.get("isError"): |
| 699 | raise RuntimeError("Parallel MCP web_search reported an error") |
| 700 | items = [] |
| 701 | for row in _search_rows(tool_result): |
| 702 | if len(items) >= count: |
| 703 | break |
| 704 | url = str(row.get("url") or "") |
| 705 | try: |
| 706 | parsed_url = urlparse(url) |
| 707 | except ValueError: |
| 708 | continue |
| 709 | if parsed_url.scheme not in ("http", "https") or not parsed_url.netloc: |
| 710 | continue |
| 711 | raw_date = row.get("publish_date") |
| 712 | parsed_date = dates.parse_date(raw_date[:10]) if isinstance(raw_date, str) else None |
| 713 | pub_date = parsed_date.date().isoformat() if parsed_date else None |
| 714 | # Match the paid grounding backends: only dated evidence inside the |
| 715 | # requested window qualifies, including when --as-of is historical. |
| 716 | if not pub_date or not date_range[0] <= pub_date <= date_range[1]: |
| 717 | continue |
| 718 | excerpts = row.get("excerpts") or [] |
| 719 | if isinstance(excerpts, str): |
| 720 | excerpts = [excerpts] |
| 721 | snippet = "\n".join(str(value) for value in excerpts if value) if isinstance(excerpts, list) else "" |
| 722 | items.append({ |
| 723 | "id": f"WPM{len(items) + 1}", |
| 724 | "title": row.get("title") or parsed_url.netloc, |
| 725 | "url": url, |
| 726 | "source_domain": parsed_url.netloc.strip().lower(), |
| 727 | "snippet": snippet[:500], |
| 728 | "date": pub_date, |
| 729 | "relevance": 0.8, |
| 730 | "why_relevant": "Parallel Search MCP result", |
| 731 | }) |
| 732 | return items, { |
| 733 | "label": "parallel-mcp", |
| 734 | "webSearchQueries": [query], |
| 735 | "resultCount": len(items), |
| 736 | } |
| 737 |