Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat: add opt-in Parallel Search MCP backend (#1058)

George Picketta218edadbc33
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index eaeab83e..8f196b97 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -385,7 +385,8 @@ The search-source preference ladder, strict best-to-floor:
1. **Host web search** - whatever web-search capability the agent session already has: built-in search, a deferred web-search tool that must be loaded first, or an installed connector such as Brave, Firecrawl, Exa, Serper, or another provider. Best results; used automatically on hosts that have it. A failed lookup for one specific tool name is not fatal when another web-search capability is available. Signalled to the engine via `LAST30DAYS_NATIVE_SEARCH=1` (the skill sets this for you when your agent session has web search) so the engine does not run a worse search underneath it.
2. **Paid engine backend** - one of `BRAVE_API_KEY`, `EXA_API_KEY`, `SERPER_API_KEY`, `PARALLEL_API_KEY`, auto-detected in that order. Override per-run with `--web-backend=<name>`.
-3. **Keyless engine floor** - zero-key web search (DuckDuckGo, plus an optional SearXNG instance) and zero-key page fetch (Jina Reader). Runs only when the agent session has **no** host web search **and** no paid key is set, so headless/cron and hosts without a search tool still get general-web coverage. Force it explicitly with `--web-backend=keyless`.
+3. **Explicit hosted MCP** - `--web-backend=parallel-mcp` opts this run into the anonymous `https://search.parallel.ai/mcp` server. Search objectives and queries reach Parallel; the option is never auto-selected. The free path needs no key, while an existing `PARALLEL_API_KEY` is sent as optional Bearer authentication for higher limits.
+4. **Keyless engine floor** - zero-key web search (DuckDuckGo, plus an optional SearXNG instance) and zero-key page fetch (Jina Reader). Runs only when the agent session has **no** host web search **and** no paid key is set, so headless/cron and hosts without a search tool still get general-web coverage. Force it explicitly with `--web-backend=keyless`.
Relevant env vars:
diff --git a/changelog.d/+parallel-search-mcp.added.md b/changelog.d/+parallel-search-mcp.added.md
new file mode 100644
index 00000000..fa03cb2a
--- /dev/null
+++ b/changelog.d/+parallel-search-mcp.added.md
@@ -0,0 +1 @@
+Add an explicit `--web-backend=parallel-mcp` option for anonymous hosted Parallel web search.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 700d44be..ab5a395e 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -870,6 +870,7 @@ Before running the engine, determine which flags apply to this topic and resolve
| `--tiktok-creators={c1,c2,...}` | Step 0.55 | Creator / influencer / brand topics |
| `--ig-creators={c1,c2,...}` | Step 0.55 | Creator / brand topics |
| `--web-backend brave` | Step 0.45 Class 5 | **MANDATORY** for non-Latin-script topics (Hebrew, Arabic, CJK, etc.) — Brave is the only source that indexes non-English web |
+| `--web-backend parallel-mcp` | Explicit user request only | Use only when the user asks to use Parallel Search MCP. This opts the run into sending its search objective and queries to `https://search.parallel.ai/mcp`; never select it automatically. Anonymous use sends no authorization header; an existing `PARALLEL_API_KEY` is sent as Bearer auth. |
| `--auto-resolve` | Fallback | WebSearch is available but Step 0.55 could not resolve everything cleanly — use as belt-and-suspenders |
**Checkpoint before running the engine:** your Bash command must include every flag from the checklist that applies to this topic. For a person who ships code (the Peter Steinberger class), that is MINIMUM `--x-handle` AND `--github-user` AND `--subreddits`, and typically `--x-related` too. A command with only `--x-handle` on a person topic is a pre-flight skip and a Step 0.5 regression.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 3e01ddaf..99510391 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -756,9 +756,9 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--x-handle", help="X handle for targeted supplemental search")
parser.add_argument("--x-related", help="Comma-separated related X handles (searched with lower weight)")
parser.add_argument("--web-backend", default="auto",
- choices=["auto", "brave", "exa", "serper", "parallel", "keyless", "none"],
- help="Web search backend (default: auto, tries Brave then Exa then Serper then Parallel; "
- "keyless forces the zero-key DuckDuckGo/SearXNG floor)")
+ choices=["auto", "brave", "exa", "serper", "parallel", "parallel-mcp", "keyless", "none"],
+ help="Web search backend (default: auto; parallel-mcp explicitly opts into the "
+ "anonymous hosted MCP; keyless forces the zero-key floor)")
parser.add_argument("--deep-research", action="store_true",
help="Use at most one Perplexity Deep Research run. Direct PERPLEXITY_API_KEY uses the Agent API background path; OPENROUTER_API_KEY keeps the synchronous Sonar fallback; cannot be combined with competitor or vs-mode.")
parser.add_argument("--hiring-signals", action="store_true",
diff --git a/skills/last30days/scripts/lib/grounding.py b/skills/last30days/scripts/lib/grounding.py
index b91dd7f2..2dd6744b 100644
--- a/skills/last30days/scripts/lib/grounding.py
+++ b/skills/last30days/scripts/lib/grounding.py
@@ -8,7 +8,7 @@ from dataclasses import dataclass
from datetime import datetime
from urllib.parse import urlparse
-from . import dates, env, http, schema, web_search_keyless
+from . import dates, env, http, parallel_mcp, schema, web_search_keyless
@dataclass(frozen=True)
@@ -268,6 +268,10 @@ def web_search(
if not key:
raise RuntimeError("PARALLEL_API_KEY is required when web_backend='parallel'")
items, artifact = parallel_search(query, date_range, key)
+ elif backend == "parallel-mcp":
+ items, artifact = parallel_mcp.search(
+ query, date_range, config.get("PARALLEL_API_KEY")
+ )
elif backend == "keyless":
items, artifact = web_search_keyless.keyless_search(query, date_range, config)
elif backend != "none":
diff --git a/skills/last30days/scripts/lib/parallel_mcp.py b/skills/last30days/scripts/lib/parallel_mcp.py
new file mode 100644
index 00000000..51f27946
--- /dev/null
+++ b/skills/last30days/scripts/lib/parallel_mcp.py
@@ -0,0 +1,232 @@
+"""Opt-in Parallel Search MCP adapter using stdlib Streamable HTTP."""
+
+from __future__ import annotations
+
+import json
+import urllib.error
+import urllib.request
+from typing import Any
+from urllib.parse import urlparse
+
+from . import dates, http
+
+PARALLEL_MCP_URL = "https://search.parallel.ai/mcp"
+_PROTOCOL_VERSION = "2025-03-26"
+_MAX_RESPONSE_BYTES = 4 * 1024 * 1024
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ # The endpoint is fixed. Never forward credentials, session IDs, or
+ # search data to a redirect target, including an HTTPS downgrade.
+ return None
+
+
+def _matching_response(payload: bytes, request_id: int | None) -> dict[str, Any] | None:
+ value = json.loads(payload)
+ # The negotiated 2025-03-26 protocol permits batched SSE messages.
+ for message in value if isinstance(value, list) else [value]:
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
+ raise RuntimeError("Parallel MCP returned an invalid JSON-RPC response")
+ if message.get("id") == request_id and ("result" in message or "error" in message):
+ return message
+ return None
+
+
+def _read_response(response: Any, request_id: int | None) -> dict[str, Any]:
+ if "text/event-stream" not in response.headers.get("Content-Type", "").lower():
+ payload = response.read(_MAX_RESPONSE_BYTES + 1)
+ if len(payload) > _MAX_RESPONSE_BYTES:
+ raise RuntimeError("Parallel MCP response exceeded 4 MiB")
+ if request_id is None and not payload:
+ return {}
+ result = _matching_response(payload, request_id) if payload else None
+ if result is not None:
+ return result
+ else:
+ data = []
+ total = 0
+ while True:
+ line = response.readline(_MAX_RESPONSE_BYTES - total + 1)
+ total += len(line)
+ if total > _MAX_RESPONSE_BYTES:
+ raise RuntimeError("Parallel MCP response exceeded 4 MiB")
+ if not line:
+ break
+ line = line.rstrip(b"\r\n")
+ if not line and data:
+ result = _matching_response(b"\n".join(data), request_id)
+ if result is not None:
+ # A valid response completes the request, even if the
+ # server keeps the stream open or sends more notifications.
+ return result
+ data = []
+ elif line.startswith(b"data:"):
+ value = line[5:]
+ data.append(value[1:] if value.startswith(b" ") else value)
+ raise RuntimeError("Parallel MCP response is missing the requested JSON-RPC result")
+
+
+def _request(
+ message: dict[str, Any] | None, api_key: str | None, session_id: str | None = None,
+) -> tuple[dict[str, Any], str | None]:
+ headers = {
+ "Accept": "application/json, text/event-stream",
+ "Content-Type": "application/json",
+ "User-Agent": http.USER_AGENT,
+ }
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+ if session_id:
+ headers["Mcp-Session-Id"] = session_id
+ if message is None or message.get("method") != "initialize":
+ headers["MCP-Protocol-Version"] = _PROTOCOL_VERSION
+ request = urllib.request.Request(
+ PARALLEL_MCP_URL,
+ data=json.dumps(message, separators=(",", ":")).encode("utf-8") if message is not None else None,
+ headers=headers,
+ method="POST" if message is not None else "DELETE",
+ )
+ with urllib.request.build_opener(_NoRedirect()).open(request, timeout=http.DEFAULT_TIMEOUT) as response:
+ result = _read_response(response, message.get("id")) if message is not None else {}
+ return result, response.headers.get("Mcp-Session-Id") or session_id
+
+
+def _result(response: dict[str, Any]) -> dict[str, Any]:
+ if response.get("error"):
+ error = response["error"]
+ detail = error.get("message") if isinstance(error, dict) else str(error)
+ raise RuntimeError(f"Parallel MCP error: {detail}")
+ result = response.get("result")
+ if not isinstance(result, dict):
+ raise RuntimeError("Parallel MCP response is missing its result")
+ return result
+
+
+def _search_rows(tool_result: dict[str, Any]) -> list[dict[str, Any]]:
+ payloads = [tool_result.get("structuredContent")]
+ for content in tool_result.get("content") or []:
+ if not isinstance(content, dict) or content.get("type") != "text":
+ continue
+ try:
+ payloads.append(json.loads(content.get("text") or ""))
+ except (TypeError, ValueError):
+ continue
+ for candidates in payloads:
+ if isinstance(candidates, dict) and "data" in candidates and "results" not in candidates:
+ candidates = candidates["data"]
+ if isinstance(candidates, dict):
+ candidates = candidates.get("results")
+ if isinstance(candidates, list):
+ return [row for row in candidates if isinstance(row, dict)]
+ raise RuntimeError("Parallel MCP web_search returned no results array")
+
+
+def search(
+ query: str, date_range: tuple[str, str], api_key: str | None = None, count: int = 5,
+) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ """Discover and invoke hosted ``web_search`` after explicit dispatcher opt-in."""
+ initialized, session_id = _request(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": _PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "last30days-skill", "version": "3"},
+ },
+ },
+ api_key,
+ )
+ try:
+ if _result(initialized).get("protocolVersion") != _PROTOCOL_VERSION:
+ raise RuntimeError("Parallel MCP negotiated an unsupported protocol version")
+ _request(
+ {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}},
+ api_key,
+ session_id,
+ )
+ request_id = 2
+ params = {}
+ seen_cursors = set()
+ while True:
+ tools_response, _ = _request(
+ {"jsonrpc": "2.0", "id": request_id, "method": "tools/list", "params": params},
+ api_key,
+ session_id,
+ )
+ request_id += 1
+ page = _result(tools_response)
+ tools = page.get("tools") or []
+ if any(isinstance(tool, dict) and tool.get("name") == "web_search" for tool in tools):
+ break
+ cursor = page.get("nextCursor")
+ if not isinstance(cursor, str) or not cursor or cursor in seen_cursors or len(seen_cursors) >= 20:
+ raise RuntimeError("Parallel MCP did not advertise web_search")
+ seen_cursors.add(cursor)
+ params = {"cursor": cursor}
+ objective = f"Find useful public web evidence about {query} from {date_range[0]} through {date_range[1]}."
+ called, _ = _request(
+ {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "method": "tools/call",
+ "params": {
+ "name": "web_search",
+ "arguments": {"objective": objective, "search_queries": [query]},
+ },
+ },
+ api_key,
+ session_id,
+ )
+ finally:
+ if session_id:
+ try:
+ _request(None, api_key, session_id)
+ except urllib.error.HTTPError as error:
+ error.close()
+ except (OSError, RuntimeError, ValueError):
+ # Cleanup is best-effort: unsupported DELETEs or a network
+ # failure must not hide search results or the original error.
+ pass
+ tool_result = _result(called)
+ if tool_result.get("isError"):
+ raise RuntimeError("Parallel MCP web_search reported an error")
+ items = []
+ for row in _search_rows(tool_result):
+ if len(items) >= count:
+ break
+ url = str(row.get("url") or "")
+ try:
+ parsed_url = urlparse(url)
+ except ValueError:
+ continue
+ if parsed_url.scheme not in ("http", "https") or not parsed_url.netloc:
+ continue
+ raw_date = row.get("publish_date")
+ parsed_date = dates.parse_date(raw_date[:10]) if isinstance(raw_date, str) else None
+ pub_date = parsed_date.date().isoformat() if parsed_date else None
+ # Match the paid grounding backends: only dated evidence inside the
+ # requested window qualifies, including when --as-of is historical.
+ if not pub_date or not date_range[0] <= pub_date <= date_range[1]:
+ continue
+ excerpts = row.get("excerpts") or []
+ if isinstance(excerpts, str):
+ excerpts = [excerpts]
+ snippet = "\n".join(str(value) for value in excerpts if value) if isinstance(excerpts, list) else ""
+ items.append({
+ "id": f"WPM{len(items) + 1}",
+ "title": row.get("title") or parsed_url.netloc,
+ "url": url,
+ "source_domain": parsed_url.netloc.strip().lower(),
+ "snippet": snippet[:500],
+ "date": pub_date,
+ "relevance": 0.8,
+ "why_relevant": "Parallel Search MCP result",
+ })
+ return items, {
+ "label": "parallel-mcp",
+ "webSearchQueries": [query],
+ "resultCount": len(items),
+ }
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 3e16b249..4b04f886 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -2056,7 +2056,7 @@ def run(
available.append("corpus")
if web_backend == "none":
available = [s for s in available if s != "grounding"]
- elif web_backend in ("brave", "exa", "serper", "parallel", "keyless") and "grounding" not in available:
+ elif web_backend in ("brave", "exa", "serper", "parallel", "parallel-mcp", "keyless") and "grounding" not in available:
available.append("grounding")
if (
hiring_signals_mode
diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.py
index 4714fa65..f0a79ead 100644
--- a/tests/test_cli_v3.py
+++ b/tests/test_cli_v3.py
@@ -385,7 +385,7 @@ class CliV3Tests(unittest.TestCase):
def test_build_parser_still_accepts_other_web_backend_values(self):
parser = cli.build_parser()
- for value in ("auto", "brave", "exa", "serper", "parallel", "none"):
+ for value in ("auto", "brave", "exa", "serper", "parallel", "parallel-mcp", "none"):
args, extra = parser.parse_known_args(["--web-backend", value, "biosecurity"])
self.assertEqual(value, args.web_backend)
self.assertEqual([], extra)
diff --git a/tests/test_grounding_v3.py b/tests/test_grounding_v3.py
index f083845e..28cb4da3 100644
--- a/tests/test_grounding_v3.py
+++ b/tests/test_grounding_v3.py
@@ -1,7 +1,13 @@
+import io
+import json
+import threading
import unittest
+import urllib.error
+from contextlib import contextmanager
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest.mock import patch
-from lib import grounding
+from lib import grounding, parallel_mcp
class BraveSearchTests(unittest.TestCase):
@@ -379,5 +385,235 @@ class RedditEnrichmentIsolationTests(unittest.TestCase):
self.assertEqual(source_sink, [])
+class ParallelMCPRuntimeTests(unittest.TestCase):
+ class _Response:
+ def __init__(self, payload, session=None, content_type="application/json"):
+ raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode() if payload is not None else b""
+ self.body = io.BytesIO(raw)
+ self.headers = {"Content-Type": content_type}
+ if session:
+ self.headers["Mcp-Session-Id"] = session
+ def __enter__(self):
+ return self
+ def __exit__(self, *_args):
+ return False
+ def read(self, size=-1):
+ return self.body.read(size)
+ def readline(self, size=-1):
+ return self.body.readline(size)
+
+ def test_explicit_parallel_mcp_discovers_invokes_and_maps_anonymous_result(self):
+ responses = iter([
+ self._Response({"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-03-26"}}, "session-1"),
+ self._Response(None),
+ self._Response({"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "web_search"}, {"name": "web_fetch"}]}}),
+ self._Response({"jsonrpc": "2.0", "id": 3, "result": {"structuredContent": {"results": [{"url": "https://example.com/evidence", "title": None, "publish_date": "2026-08-01", "excerpts": ["Useful evidence"]}]}}}),
+ self._Response(None),
+ ])
+ requests = []
+ def open_response(request, timeout):
+ requests.append(request)
+ return next(responses)
+ with patch("lib.parallel_mcp.urllib.request.OpenerDirector.open", side_effect=open_response):
+ items, artifact = grounding.web_search(
+ "agent runtimes", ("2026-07-27", "2026-08-26"), {}, backend="parallel-mcp"
+ )
+ self.assertEqual("https://example.com/evidence", items[0]["url"])
+ self.assertEqual("Useful evidence", items[0]["snippet"])
+ self.assertEqual("2026-08-01", items[0]["date"])
+ self.assertEqual("parallel-mcp", artifact["label"])
+ self.assertTrue(all(request.get_header("Authorization") is None for request in requests))
+ self.assertTrue(all(request.get_header("Mcp-session-id") == "session-1" for request in requests[1:]))
+ self.assertTrue(all(request.get_header("Mcp-protocol-version") == "2025-03-26" for request in requests[1:]))
+ self.assertEqual("DELETE", requests[-1].method)
+ messages = [json.loads(request.data) for request in requests if request.data]
+ self.assertEqual(["initialize", "notifications/initialized", "tools/list", "tools/call"], [message["method"] for message in messages])
+ self.assertEqual("web_search", messages[-1]["params"]["name"])
+ self.assertEqual(["agent runtimes"], messages[-1]["params"]["arguments"]["search_queries"])
+ self.assertNotIn("max_results", messages[-1]["params"]["arguments"])
+
+ def test_parallel_mcp_rejects_oversized_response(self):
+ class OversizedResponse(self._Response):
+ def read(self, size=-1):
+ self.requested_size = size
+ return b"x" * size
+ response = OversizedResponse(None)
+ with patch("lib.parallel_mcp.urllib.request.OpenerDirector.open", return_value=response):
+ with self.assertRaisesRegex(RuntimeError, "exceeded 4 MiB"):
+ grounding.web_search(
+ "test", ("2026-07-27", "2026-08-26"), {}, backend="parallel-mcp"
+ )
+ self.assertEqual(4 * 1024 * 1024 + 1, response.requested_size)
+
+ def test_auto_without_opt_in_does_not_contact_parallel_mcp(self):
+ with patch("lib.grounding.parallel_mcp.search") as mcp_search, \
+ patch("lib.grounding.web_search_keyless.keyless_search", return_value=([], {})):
+ grounding.web_search("test", ("2026-07-27", "2026-08-26"), {}, backend="auto")
+ mcp_search.assert_not_called()
+
+ def test_explicit_parallel_mcp_preserves_optional_bearer_auth(self):
+ with patch("lib.grounding.parallel_mcp.search", return_value=([], {})) as mcp_search:
+ grounding.web_search(
+ "test", ("2026-07-27", "2026-08-26"),
+ {"PARALLEL_API_KEY": "test-key"}, backend="parallel-mcp",
+ )
+ mcp_search.assert_called_once_with("test", ("2026-07-27", "2026-08-26"), "test-key")
+
+ @contextmanager
+ def _server(self, handler):
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_port}"
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+ def test_redirects_never_forward_auth_session_or_search_data(self):
+ target_requests = []
+ original_requests = []
+
+ class Target(BaseHTTPRequestHandler):
+ def do_GET(self):
+ target_requests.append(dict(self.headers))
+ self.send_response(200)
+ self.end_headers()
+ do_POST = do_GET
+ def log_message(self, *_args):
+ pass
+
+ class Redirect(Target):
+ def do_POST(self):
+ original_requests.append(dict(self.headers))
+ self.rfile.read(int(self.headers.get("Content-Length", 0)))
+ self.send_response(int(self.path.strip("/")))
+ self.send_header("Location", target_url)
+ self.end_headers()
+
+ with self._server(Target) as target_url, self._server(Redirect) as source_url:
+ for status in (301, 302, 303, 307, 308):
+ with self.subTest(status=status), patch.object(parallel_mcp, "PARALLEL_MCP_URL", f"{source_url}/{status}"):
+ with self.assertRaises(urllib.error.HTTPError) as raised:
+ parallel_mcp._request(
+ {"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
+ "test-key", "test-session",
+ )
+ self.assertEqual(status, raised.exception.code)
+ raised.exception.close()
+ self.assertEqual([], target_requests)
+ self.assertEqual(5, len(original_requests))
+ self.assertTrue(all(headers["Authorization"] == "Bearer test-key" for headers in original_requests))
+ self.assertTrue(all(headers["Mcp-Session-Id"] == "test-session" for headers in original_requests))
+
+ def test_sse_matches_request_and_returns_without_waiting_for_eof(self):
+ class OpenStream(self._Response):
+ def read(self, size=-1):
+ raise AssertionError("SSE must not wait for the whole body")
+ def readline(self, size=-1):
+ line = super().readline(size)
+ if not line:
+ raise AssertionError("SSE must stop at the matching response")
+ return line
+
+ response = OpenStream(
+ b': heartbeat\r\n\r\n'
+ b'data: {"jsonrpc":"2.0","method":"notifications/progress"}\r\n\r\n'
+ b'data: {"jsonrpc":"2.0","id":99,"result":{}}\r\n\r\n'
+ b'event: message\r\ndata: {"jsonrpc":"2.0",\r\ndata: "id":3,"result":{"content":[]}}\r\n\r\n',
+ content_type="text/event-stream; charset=utf-8",
+ )
+ self.assertEqual({"content": []}, parallel_mcp._read_response(response, 3)["result"])
+
+ def test_sse_supports_batched_messages(self):
+ payload = b'data: [{"jsonrpc":"2.0","method":"notifications/progress"},{"jsonrpc":"2.0","id":3,"result":{}}]\n\n'
+ response = self._Response(payload, content_type="text/event-stream")
+ self.assertEqual(3, parallel_mcp._read_response(response, 3)["id"])
+
+ def test_sse_response_cap_includes_heartbeats_and_all_events(self):
+ for payload in (b":" + b"x" * 80, b": heartbeat\n\n" * 10):
+ with self.subTest(payload=payload), patch.object(parallel_mcp, "_MAX_RESPONSE_BYTES", 64):
+ response = self._Response(payload, content_type="text/event-stream")
+ with self.assertRaisesRegex(RuntimeError, "exceeded 4 MiB"):
+ parallel_mcp._read_response(response, 3)
+
+ def test_rejects_missing_or_mismatched_rpc_response(self):
+ for payload, content_type in (
+ ({"jsonrpc": "2.0", "id": 99, "result": {}}, "application/json"),
+ (None, "application/json"),
+ (b'data: {"jsonrpc":"2.0","method":"notifications/progress"}\n\n', "text/event-stream"),
+ ):
+ with self.subTest(payload=payload):
+ with self.assertRaisesRegex(RuntimeError, "missing the requested"):
+ parallel_mcp._read_response(self._Response(payload, content_type=content_type), 3)
+
+ def test_filters_dates_and_invalid_urls_before_applying_result_limit(self):
+ rows = [
+ {"url": "https://example.com/old", "publish_date": "2026-07-26"},
+ {"url": "https://example.com/future", "publish_date": "2026-08-27"},
+ {"url": "https://example.com/undated"},
+ {"url": "https://example.com/invalid-date", "publish_date": "not-a-date"},
+ {"url": "https:///missing-host", "publish_date": "2026-08-01"},
+ {"url": "https://[invalid", "publish_date": "2026-08-01"},
+ {"url": "https://example.com/start", "publish_date": "2026-07-27T12:00:00Z", "excerpts": "Start evidence"},
+ {"url": "https://example.com/end", "publish_date": "2026-08-26", "excerpts": ["End evidence"]},
+ {"url": "https://example.com/extra", "publish_date": "2026-08-01"},
+ ]
+ responses = [
+ ({"result": {"protocolVersion": "2025-03-26"}}, None),
+ ({}, None),
+ ({"result": {"tools": [{"name": "web_search"}]}}, None),
+ ({"result": {"content": [{"type": "text", "text": json.dumps({"results": rows})}]}}, None),
+ ]
+ with patch.object(parallel_mcp, "_request", side_effect=responses):
+ items, artifact = parallel_mcp.search("test", ("2026-07-27", "2026-08-26"), count=2)
+ self.assertEqual(["2026-07-27", "2026-08-26"], [item["date"] for item in items])
+ self.assertEqual(["Start evidence", "End evidence"], [item["snippet"] for item in items])
+ self.assertEqual(2, artifact["resultCount"])
+
+ def test_empty_results_are_distinct_from_malformed_payloads(self):
+ self.assertEqual([], parallel_mcp._search_rows({"structuredContent": {"results": []}}))
+ for value in (42, "invalid", {"results": 42}):
+ with self.subTest(value=value), self.assertRaisesRegex(RuntimeError, "no results array"):
+ parallel_mcp._search_rows({"structuredContent": value})
+
+ def test_discovers_web_search_on_later_page_and_cleanup_failure_is_nonfatal(self):
+ responses = [
+ ({"result": {"protocolVersion": "2025-03-26"}}, "session-1"),
+ ({}, "session-1"),
+ ({"result": {"tools": [{"name": "web_fetch"}], "nextCursor": "page-2"}}, "session-1"),
+ ({"result": {"tools": [{"name": "web_search"}]}}, "session-1"),
+ ({"result": {"structuredContent": {"results": []}}}, "session-1"),
+ urllib.error.HTTPError(parallel_mcp.PARALLEL_MCP_URL, 405, "Not allowed", {}, None),
+ ]
+ with patch.object(parallel_mcp, "_request", side_effect=responses) as request:
+ items, _ = parallel_mcp.search("test", ("2026-07-27", "2026-08-26"))
+ self.assertEqual([], items)
+ self.assertEqual({"cursor": "page-2"}, request.call_args_list[3].args[0]["params"])
+ self.assertEqual(4, request.call_args_list[4].args[0]["id"])
+ self.assertEqual((None, None, "session-1"), request.call_args_list[-1].args)
+
+ def test_failed_discovery_still_terminates_session_and_preserves_error(self):
+ responses = [
+ ({"result": {"protocolVersion": "2025-03-26"}}, "session-1"),
+ ({}, "session-1"),
+ ({"error": {"message": "Discovery failed"}}, "session-1"),
+ OSError("Cleanup failed"),
+ ]
+ with patch.object(parallel_mcp, "_request", side_effect=responses) as request:
+ with self.assertRaisesRegex(RuntimeError, "Discovery failed"):
+ parallel_mcp.search("test", ("2026-07-27", "2026-08-26"))
+ self.assertIsNone(request.call_args.args[0])
+
+ def test_unsupported_protocol_is_rejected_before_search(self):
+ responses = [({"result": {"protocolVersion": "unsupported"}}, "session-1"), ({}, None)]
+ with patch.object(parallel_mcp, "_request", side_effect=responses) as request:
+ with self.assertRaisesRegex(RuntimeError, "unsupported protocol version"):
+ parallel_mcp.search("test", ("2026-07-27", "2026-08-26"))
+ self.assertEqual(2, request.call_count)
+ self.assertIsNone(request.call_args.args[0])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index 82b4c592..316f26a1 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -120,6 +120,34 @@ class PipelineV3Tests(unittest.TestCase):
# error when its required backend key is unset.
self.assertIn("grounding", report.errors_by_source)
+ def test_parallel_mcp_enables_grounding_without_key_on_native_host(self):
+ def mcp_response(message, _api_key, _session_id=None):
+ results = {
+ "initialize": {"protocolVersion": "2025-03-26"},
+ "notifications/initialized": {},
+ "tools/list": {"tools": [{"name": "web_search"}]},
+ "tools/call": {"structuredContent": {"results": [{
+ "url": "https://example.com/update",
+ "title": "Test topic update",
+ "publish_date": "2026-08-01",
+ "excerpts": ["New evidence about test topic"],
+ }]}},
+ }
+ return {"result": results[message["method"]]}, None
+
+ with patch("lib.parallel_mcp._request", side_effect=mcp_response):
+ report = pipeline.run(
+ topic="test topic",
+ config={"LAST30DAYS_REASONING_PROVIDER": "auto", "LAST30DAYS_NATIVE_SEARCH": "1"},
+ depth="quick",
+ requested_sources=["grounding"],
+ web_backend="parallel-mcp",
+ as_of_date="2026-08-26",
+ )
+ self.assertNotIn("grounding", report.errors_by_source)
+ self.assertEqual(1, len(report.items_by_source["grounding"]))
+ self.assertEqual("2026-08-01", report.items_by_source["grounding"][0].published_at)
+
def test_hiring_signals_mode_enables_jobs_source_in_mock_run(self):
report = pipeline.run(
topic="Listen Labs",