Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(search): Parallel search first (keyless MCP), existing engines as fallback
Salman Qureshi0155399ad8b4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex de38d0e4..ba63b5c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,7 @@## Unreleased### Web search+- **Parallel search first.** `web_search` now asks [Parallel's public search](https://search.parallel.ai/mcp) first, for web and news: a keyless MCP endpoint built for agents that answers in about a second with excerpts and publish dates. Brave, DuckDuckGo, Wikipedia, Hacker News and the news feeds stay as fallbacks, in that order. News keeps only links to individual articles, so section fronts like "/kashmir" are dropped and Bing News fills in.- **News links open the article.** News search used Google News first, whose links are Google redirects (`news.google.com/rss/articles/…`) that can't be turned into the publisher's address. Bing News now comes first and its links are unwrapped to the real article; Google News is the fallback, and its links are marked as redirects.- **Two web indexes, combined.** Brave and DuckDuckGo (its html and lite pages) both answer some automated requests and block others, by client fingerprint and rate. `web_search` now asks them in turn, retries a DuckDuckGo challenge once after a short pause, and combines relevant results until it has enough, instead of stopping at the first engine with one hit.- **Search never depends on the model.** Results come only from Mercury's own search tools, never from a provider's built-in web search, so search works the same with every model.diff --git a/src/capabilities/web/search-redirect.test.ts b/src/capabilities/web/search-redirect.test.tsindex 338de212..b99b8be0 100644--- a/src/capabilities/web/search-redirect.test.ts+++ b/src/capabilities/web/search-redirect.test.ts@@ -17,6 +17,9 @@ vi.mock('../../utils/ssrf.js', () => ({}));import { createFetchUrlTool } from './fetch-url.js';++// Parallel, the first search engine, uses the global fetch: unavailable here.+vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 503 })));import { guardedFetch } from '../../utils/ssrf.js';import { isBrokenSearchSkill } from '../../skills/loader.js';diff --git a/src/capabilities/web/web-search.test.ts b/src/capabilities/web/web-search.test.tsindex 60f856af..b3aa782c 100644--- a/src/capabilities/web/web-search.test.ts+++ b/src/capabilities/web/web-search.test.ts@@ -44,12 +44,20 @@ const defaultFetch = routes({ 'search.brave.com': BRAVE, 'news.google.com': GOOGvi.mock('../../utils/ssrf.js', () => ({ guardedFetch: vi.fn() }));-import { createWebSearchTool, directLink, parseBrave, parseDdg, parseRss, relevant, resetBraveCooldown, searchQueryFromUrl, webSearch } from './web-search.js';+import { createWebSearchTool, directLink, looksLikeArticle, parseBrave, parseDdg, parseParallel, parseRss, relevant, resetBraveCooldown, searchQueryFromUrl, webSearch } from './web-search.js';import { guardedFetch } from '../../utils/ssrf.js';vi.mocked(guardedFetch).mockImplementation(defaultFetch as never);++// Parallel (the first engine) is called with the global fetch. By default it+// is unavailable here, so the older tests exercise the fallback chain; the+// Parallel tests below answer it.+const parallelDown = async () => new Response('', { status: 503 });+const fetchMock = vi.fn(parallelDown);+vi.stubGlobal('fetch', fetchMock);+const parallelReply = (results: unknown[]) => new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: '{}' }], structuredContent: { search_id: 's', results } } }), { status: 200 });// Tests that swap the fetch mock must not leak it (or a Brave cooldown) into the next test.-afterEach(() => { vi.mocked(guardedFetch).mockClear(); vi.mocked(guardedFetch).mockImplementation(defaultFetch as never); resetBraveCooldown(); });+afterEach(() => { vi.mocked(guardedFetch).mockClear(); vi.mocked(guardedFetch).mockImplementation(defaultFetch as never); resetBraveCooldown(); fetchMock.mockReset(); fetchMock.mockImplementation(parallelDown); });describe('web_search', () => {it('parses Google News items, strips the source suffix, keeps the date', () => {@@ -148,7 +156,7 @@ describe('web_search', () => {const out = await t.execute({ query: '', kind: 'news' }, {});expect(out).toMatch(/News results from Google News[\s\S]*1\. Envoy meets leader in Moscow \(BBC · Wed, 21 Oct 2026\)/);vi.mocked(guardedFetch).mockImplementation(async () => new Response('', { status: 500 }));- expect(await t.execute({ query: 'x' }, {})).toMatch(/^Error: web search found nothing: no source found anything \(Brave: HTTP 500; DuckDuckGo: HTTP 500/);+ expect(await t.execute({ query: 'x' }, {})).toMatch(/^Error: web search found nothing: no source found anything \(Parallel: HTTP 503; Brave: HTTP 500; DuckDuckGo: HTTP 500/);});it('parses DuckDuckGo html and lite pages: real links out of the redirect, ads dropped', () => {@@ -183,13 +191,13 @@ describe('web_search', () => {const r = await webSearch('typescript satisfies operator', { max: 8 });expect(r.engine).toBe('Brave + DuckDuckGo');expect(r.results).toHaveLength(4);- expect(r.trail).toEqual(['Brave: 1 result', 'DuckDuckGo: 3 results']);+ expect(r.trail).toEqual(['Parallel: HTTP 503', 'Brave: 1 result', 'DuckDuckGo: 3 results']);});it('a bot challenge reads as "blocked" in the trail', async () => {vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': 429, 'duckduckgo.com': '<html>anomaly</html>', 'wikipedia.org': WIKI }) as never);const r = await webSearch('canberra');- expect(r.trail.slice(0, 4)).toEqual(['Brave: blocked (HTTP 429)', 'DuckDuckGo: blocked (bot challenge)', 'DuckDuckGo Lite: blocked (bot challenge)', 'Wikipedia: 2 results']);+ expect(r.trail.slice(0, 5)).toEqual(['Parallel: HTTP 503', 'Brave: blocked (HTTP 429)', 'DuckDuckGo: blocked (bot challenge)', 'DuckDuckGo Lite: blocked (bot challenge)', 'Wikipedia: 2 results']);});@@ -205,6 +213,49 @@ describe('web_search', () => {const r = await webSearch('canberra');expect(ddgCalls).toBe(2);expect(r.engine).toBe('DuckDuckGo');- expect(r.trail).toEqual(['Brave: blocked (HTTP 429)', 'DuckDuckGo: 4 results']);+ expect(r.trail).toEqual(['Parallel: HTTP 503', 'Brave: blocked (HTTP 429)', 'DuckDuckGo: 4 results']);+ });++ it('Parallel answers first: one keyless MCP tools/call, results with excerpts and dates', async () => {+ fetchMock.mockImplementation(async () => parallelReply([+ { url: 'https://www.linkedin.com/company/cosmic-stack', title: 'Cosmic Stack', publish_date: '2026-05-14', excerpts: ['* Name: Cosmic Stack\n * description\n - Cosmic Stack is a technology company focused on agentic AI, building [Mercury Agent](https://mercuryagent.sh).'] },+ { url: 'https://cosmicstack.ai', title: 'Cosmic Stack', publish_date: null, excerpts: ['Cosmic Stack builds open agentic AI.'] },+ { url: 'https://github.com/cosmicstack-labs', title: 'Cosmic Stack Labs', excerpts: [] },+ { url: 'https://x.com/cosmicstack', title: 'Cosmic Stack on X', excerpts: ['Cosmic Stack news'] },+ ]));+ const r = await webSearch('cosmic stack linkedin');+ expect(r.engine).toBe('Parallel');+ expect(r.trail).toEqual(['Parallel: 4 results']);+ expect(r.results[0]).toEqual({ title: 'Cosmic Stack', url: 'https://www.linkedin.com/company/cosmic-stack', date: '2026-05-14', snippet: 'Name: Cosmic Stack description - Cosmic Stack is a technology company focused on agentic AI, building Mercury Agent.' });+ // Nothing else was asked: Parallel had enough.+ expect(vi.mocked(guardedFetch)).not.toHaveBeenCalled();+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://search.parallel.ai/mcp');+ const body = JSON.parse(String(init.body));+ expect(body).toMatchObject({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'web_search', arguments: { objective: 'cosmic stack linkedin', search_queries: ['cosmic stack linkedin'] } } });+ });++ it('parses Parallel replies sent as server-sent events, and surfaces MCP errors', () => {+ const sse = `event: message\ndata: ${JSON.stringify({ jsonrpc: '2.0', id: 1, result: { structuredContent: { results: [{ url: 'https://nodejs.org/en/blog/release', title: 'Node.js releases' }] } } })}\n\n`;+ expect(parseParallel(sse, 5)).toEqual([{ title: 'Node.js releases', url: 'https://nodejs.org/en/blog/release', snippet: '', date: undefined }]);+ expect(() => parseParallel(JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32000, message: 'rate limited' } }), 5)).toThrow('rate limited');+ });++ it('news from Parallel keeps article links and drops section fronts; Bing News fills in', async () => {+ expect(looksLikeArticle('https://www.greaterkashmir.com/kashmir')).toBe(false);+ expect(looksLikeArticle('https://www.greaterkashmir.com/latest-news')).toBe(false);+ expect(looksLikeArticle('https://www.democracynow.org/2026/10/23/headlines')).toBe(true);+ expect(looksLikeArticle('https://kashmirlife.net/jammu-kashmir-government-warns-officers-over-delays')).toBe(false);+ expect(looksLikeArticle('https://kashmirlife.net/news/jammu-kashmir-government-warns-officers-over-delays')).toBe(true);+ expect(looksLikeArticle('https://www.greaterkashmir.com/kashmir/attacks-on-infrastructure-unacceptable-12742822')).toBe(true);+ fetchMock.mockImplementation(async () => parallelReply([+ { url: 'https://www.greaterkashmir.com/kashmir', title: 'Kashmir News: Live Breaking News' },+ { url: 'https://www.greaterkashmir.com/kashmir/power-shutdown-in-kashmir-announced-12742577', title: 'Kashmir power shutdown announced', publish_date: '2026-10-23' },+ ]));+ const bingNewsFeed = `<rss><channel><item><title>Kashmir story</title><link>http://www.bing.com/news/apiclick.aspx?url=https%3a%2f%2fkashmirlife.net%2fstory</link></item></channel></rss>`;+ vi.mocked(guardedFetch).mockImplementation(routes({ 'bing.com/news': bingNewsFeed }) as never);+ const r = await webSearch('kashmir', { kind: 'news' });+ expect(r.engine).toBe('Parallel + Bing News');+ expect(r.results.map((x) => x.url)).toEqual(['https://www.greaterkashmir.com/kashmir/power-shutdown-in-kashmir-announced-12742577', 'https://kashmirlife.net/story']);});});diff --git a/src/capabilities/web/web-search.ts b/src/capabilities/web/web-search.tsindex e58f1ca8..62a9f5de 100644--- a/src/capabilities/web/web-search.ts+++ b/src/capabilities/web/web-search.ts@@ -5,10 +5,11 @@ import { guardedFetch } from '../../utils/ssrf.js';/*** web_search: free, keyless search for the model.*- * web → Brave Search, DuckDuckGo (html, then lite), then Wikipedia, Hacker News,- * Bing News, Google News, Bing RSS- * news → Bing News (direct article links), then Google News (top stories, or- * when Bing has nothing; its links are Google redirects), Hacker News+ * web → Parallel (search.parallel.ai, keyless MCP), then Brave Search,+ * DuckDuckGo (html, then lite), Wikipedia, Hacker News, Bing News,+ * Google News, Bing RSS+ * news → Parallel, then Bing News (direct article links), Google News (its+ * links are Google redirects), Hacker News** Every answer must mention the query (relevant()); an engine serving junk* counts as empty and the next one is tried.@@ -141,6 +142,89 @@ export function parseBrave(html: string, max: number): SearchResult[] {return out;}+/**+ * Parallel's public search over MCP (https://search.parallel.ai/mcp): a real+ * web index built for agents, keyless, answering in about a second with+ * excerpts and publish dates. Plain JSON-RPC over HTTP: one tools/call to+ * its web_search tool, no session needed. A fixed public HTTPS endpoint, so+ * it is called directly rather than through guardedFetch (GET-only).+ */+export const PARALLEL_MCP_URL = 'https://search.parallel.ai/mcp';++interface ParallelHit { url?: string; title?: string; publish_date?: string | null; excerpts?: string[] }++/** The MCP reply, as plain JSON or as a server-sent-events body. */+export function parseParallel(body: string, max: number): SearchResult[] {+ let text = body.trim();+ if (!text.startsWith('{')) {+ const data = text.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).filter(Boolean);+ text = data[data.length - 1] ?? '';+ }+ const msg = JSON.parse(text) as { error?: { message?: string }; result?: { isError?: boolean; structuredContent?: { results?: ParallelHit[] }; content?: Array<{ type?: string; text?: string }> } };+ if (msg.error) throw new Error(msg.error.message ?? 'MCP error');+ if (msg.result?.isError) throw new Error(msg.result.content?.[0]?.text?.slice(0, 160) ?? 'search error');+ let hits = msg.result?.structuredContent?.results;+ if (!hits) {+ const t = msg.result?.content?.find((c) => c.type === 'text')?.text;+ hits = t ? (JSON.parse(t) as { results?: ParallelHit[] }).results : undefined;+ }+ return (hits ?? []).filter((h) => h.url && /^https?:\/\//.test(h.url)).slice(0, max).map((h) => ({+ title: (h.title ?? h.url!).replace(/\s+/g, ' ').trim(),+ url: h.url!,+ // Excerpts are markdown cut from the page: flatten links and markup.+ snippet: (h.excerpts?.[0] ?? '').replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[#*>`_]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 300),+ date: h.publish_date ?? undefined,+ }));+}++async function parallelSearch(objective: string, queries: string[], max: number): Promise<SearchResult[]> {+ const ac = new AbortController();+ const timer = setTimeout(() => ac.abort(), TIMEOUT_MS);+ try {+ const res = await fetch(PARALLEL_MCP_URL, {+ method: 'POST',+ signal: ac.signal,+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-06-18', 'User-Agent': 'Mercury-Agent' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'web_search', arguments: { objective: objective.slice(0, 400), search_queries: queries } } }),+ });+ if (res.status === 429) throw new Error('rate-limited (HTTP 429)');+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return parseParallel(await res.text(), max);+ } finally {+ clearTimeout(timer);+ }+}++/** Keyword queries for Parallel: the query itself, cut to its first eight words. */+function parallelQueries(query: string): string[] {+ return [query.replace(/["']/g, '').split(/\s+/).filter(Boolean).slice(0, 8).join(' ')];+}++async function parallel(query: string, max: number): Promise<SearchResult[]> {+ if (!query.trim()) return [];+ return parallelSearch(query, parallelQueries(query), max);+}++/**+ * A link to one story rather than a section front ("/kashmir", "/latest-news"):+ * a dated path, or at least two path segments with a long slug. News answers+ * should open the article.+ */+export function looksLikeArticle(url: string): boolean {+ let path: string;+ try { path = new URL(url).pathname; } catch { return false; }+ const parts = path.split('/').filter(Boolean);+ if (/\/(19|20)\d{2}\/\d{1,2}\//.test(path) || /\d{5,}/.test(path)) return true;+ const last = parts[parts.length - 1] ?? '';+ return parts.length >= 2 && (last.split('-').length >= 4 || last.length >= 30);+}++async function parallelNews(query: string, max: number): Promise<SearchResult[]> {+ const q = query.trim() || 'top news today';+ const hits = await parallelSearch(`Latest news articles about: ${q}. Prefer individual articles published in the last few days, from news sites.`, [...parallelQueries(q), `${parallelQueries(q)[0]} news`], max * 2);+ return hits.filter((h) => looksLikeArticle(h.url)).slice(0, max);+}+/*** DuckDuckGo's no-JavaScript result pages (html. and lite.). Links come as* duckduckgo.com/l/?uddg=<the page>; ads point back at duckduckgo.com and@@ -360,8 +444,8 @@ export async function webSearch(query: string, opts: { kind?: 'web' | 'news'; ma// source never decides the answer. Every engine tried is recorded in the// trail, so "nothing found" and "everything was blocked" read differently.const engines: Array<[string, (q: string, n: number) => Promise<SearchResult[]>]> = opts.kind === 'news'- ? [['Bing News', bingNews], ['Google News', googleNews], ['Hacker News', hackerNews]]- : [['Brave', brave], ['DuckDuckGo', ddgHtml], ['DuckDuckGo Lite', ddgLite], ['Wikipedia', wikipedia], ['Hacker News', hackerNews], ['Bing News', bingNews], ['Google News', googleNews], ['Bing', bing]];+ ? [['Parallel', parallelNews], ['Bing News', bingNews], ['Google News', googleNews], ['Hacker News', hackerNews]]+ : [['Parallel', parallel], ['Brave', brave], ['DuckDuckGo', ddgHtml], ['DuckDuckGo Lite', ddgLite], ['Wikipedia', wikipedia], ['Hacker News', hackerNews], ['Bing News', bingNews], ['Google News', googleNews], ['Bing', bing]];const want = Math.min(ENOUGH, max);const trail: string[] = [];const used: string[] = [];