From df7a13921450ef41ecc01550d6d88a82e26f0676 Mon Sep 17 00:00:00 2001 From: George Pickett Date: Mon, 16 Nov 2026 12:32:34 -0800 Subject: [PATCH] feat: add Parallel as a search provider --- README.md | 10 ++ package-lock.json | 1 + package.json | 1 + src/agent.ts | 9 +- src/tools/__tests__/parallel-search.test.ts | 172 ++++++++++++++++++++ src/tools/parallel-search.ts | 155 ++++++++++++++++++ 6 files changed, 346 insertions(+), 2 deletions(-) create mode 100644 src/tools/__tests__/parallel-search.test.ts create mode 100644 src/tools/parallel-search.ts diff --git a/README.md b/README.md index e02e8778..ec1b99f0 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,16 @@ export JINA_API_KEY=jina_... # free jina api key, get from https://jina.ai/read npm run dev $QUERY ``` +### Use Parallel for web search + +Set `defaults.search_provider` to `"parallel"` in `config.json` for the CLI and +self-hosted server. You can also send `"search_provider": "parallel"` in a +`POST /v1/chat/completions` request to select it for that request. Parallel +receives the search queries and returns excerpts for citations. It requires no +Parallel API key. + +Keep the Jina API key for page reads and citation ranking. + ### Official Site You can try it on [our official site](https://search.jina.ai). diff --git a/package-lock.json b/package-lock.json index 15314672..01e4bbfc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.7", "duck-duck-scrape": "^2.2.7", + "eventsource-parser": "^3.0.0", "express": "^4.21.2", "express-validator": "^7.2.1", "hjson": "^3.2.2", diff --git a/package.json b/package.json index ade2f56b..86a62e22 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.7", "duck-duck-scrape": "^2.2.7", + "eventsource-parser": "^3.0.0", "express": "^4.21.2", "express-validator": "^7.2.1", "hjson": "^3.2.2", diff --git a/src/agent.ts b/src/agent.ts index ff68b02e..b07e44a7 100644 --- a/src/agent.ts +++ b/src/agent.ts @@ -27,6 +27,7 @@ import { zodToJsonSchema } from "zod-to-json-schema"; import { ObjectGeneratorSafe } from "./utils/safe-generator"; import { CodeSandbox } from "./tools/code-sandbox"; import { serperSearch } from './tools/serper-search'; +import { parallelSearch } from './tools/parallel-search'; import { addToAllURLs, rankURLs, @@ -292,6 +293,7 @@ async function executeSearchQueries( const newKnowledge: KnowledgeItem[] = []; const searchedQueries: string[] = []; context.actionTracker.trackThink('search_for', SchemaGen.languageCode, { keywords: uniqQOnly.join(', ') }); + const provider = searchProvider || SEARCH_PROVIDER; let utilityScore = 0; for (const query of keywordsQueries) { let results: UnNormalizedSearchSnippet[] = []; @@ -302,7 +304,7 @@ async function executeSearchQueries( try { logDebug('Search query:', { query }); - switch (searchProvider || SEARCH_PROVIDER) { + switch (provider) { case 'jina': case 'arxiv': const num = meta ? undefined : 30; @@ -317,6 +319,9 @@ async function executeSearchQueries( case 'serper': results = (await serperSearch(query)).response.organic || []; break; + case 'parallel': + results = await parallelSearch(query); + break; default: results = []; } @@ -325,7 +330,7 @@ async function executeSearchQueries( throw new Error('No results found'); } } catch (error) { - logError(`${SEARCH_PROVIDER} search failed for query:`, { + logError(`${provider} search failed for query:`, { query, error: error instanceof Error ? error.message : String(error) }); diff --git a/src/tools/__tests__/parallel-search.test.ts b/src/tools/__tests__/parallel-search.test.ts new file mode 100644 index 00000000..e1cfa0d5 --- /dev/null +++ b/src/tools/__tests__/parallel-search.test.ts @@ -0,0 +1,172 @@ +import { createServer, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { gzipSync } from 'node:zlib'; +import { parallelSearch } from '../parallel-search'; +import { name, version } from '../../../package.json'; + +type Call = { + method: string; + headers: Record; + body: { method?: string; id?: number; params?: unknown }; +}; + +const result = { + results: [ + { + url: 'https://science.nasa.gov/mission/europa-clipper/', + title: null, + excerpts: ['First excerpt 📚\u2028and the same line.', 'Second excerpt.'], + publish_date: '2024-10-14', + }, + { url: 'file:///private', title: 'Invalid', excerpts: ['Discard this result'] }, + ], +}; + +function json(response: ServerResponse, id: number, result: unknown) { + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ jsonrpc: '2.0', id, result })); +} + +describe('Parallel search', () => { + let server: Server; + let redirectTarget: Server; + let redirectHits: number; + let calls: Call[]; + let handleSearch: (response: ServerResponse, id: number) => void; + let handleDelete: (response: ServerResponse) => void; + let fetchSpy: jest.SpyInstance; + + beforeEach(async () => { + calls = []; + redirectHits = 0; + handleDelete = response => response.writeHead(204).end(); + handleSearch = (response, id) => json(response, id, { structuredContent: result }); + + server = createServer(async (request, response) => { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(chunk); + const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : {}; + calls.push({ method: request.method || '', headers: request.headers, body }); + + if (body.method === 'initialize') { + response.setHeader('Mcp-Session-Id', 'fixture-session'); + json(response, body.id, { protocolVersion: '2025-06-18' }); + } else if (body.method === 'notifications/initialized') { + response.writeHead(202).end(); + } else if (body.method === 'tools/call') { + handleSearch(response, body.id); + } else if (request.method === 'DELETE') { + handleDelete(response); + } else { + response.writeHead(405).end(); + } + }); + redirectTarget = createServer((request, response) => { + redirectHits++; + request.resume(); + response.writeHead(204).end(); + }); + await Promise.all([server, redirectTarget].map(origin => + new Promise(resolve => origin.listen(0, '127.0.0.1', resolve)))); + const fetch = globalThis.fetch; + const address = server.address() as AddressInfo; + fetchSpy = jest.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { + if (input !== 'https://mcp.parallel.ai/mcp') throw new Error('Unexpected destination'); + return fetch('http://127.0.0.1:' + address.port + '/mcp', init); + }); + }); + + afterEach(async () => { + fetchSpy.mockRestore(); + await Promise.all([server, redirectTarget].map(origin => new Promise(resolve => { + origin.close(() => resolve()); + origin.closeAllConnections(); + }))); + }); + + it('sends project attribution and no authorization, then normalizes search results', async () => { + const q = 'Europa Clipper site:science.nasa.gov OR site:jpl.nasa.gov'; + const entries = await parallelSearch({ q, location: 'United States', tbs: 'qdr:w' }); + expect(entries).toEqual([{ + url: result.results[0].url, + title: result.results[0].url, + description: result.results[0].excerpts.join('\n\n'), + date: '2024-10-14', + }]); + expect(calls.map(call => call.body.method || call.method)) + .toEqual(['initialize', 'notifications/initialized', 'tools/call', 'DELETE']); + for (const [index, call] of calls.entries()) { + expect(call.headers['user-agent']).toBe(name + '/' + version); + expect(call.headers.authorization).toBeUndefined(); + if (index > 0) { + expect(call.headers['mcp-session-id']).toBe('fixture-session'); + expect(call.headers['mcp-protocol-version']).toBe('2025-06-18'); + } + } + expect(calls[2].body.params).toEqual({ + name: 'web_search', + arguments: { + objective: expect.stringContaining(q + '. United States. Between '), + search_queries: [q], + }, + }); + }); + + it('returns the matching SSE response while the server keeps the stream open', async () => { + handleSearch = (response, id) => { + response.writeHead(200, { 'Content-Type': 'Text/Event-Stream; charset=utf-8' }); + const body = Buffer.from([ + ': heartbeat\r\n\r\n', + 'data: {"jsonrpc":"2.0","id":999,"result":null}\r\n\r\n', + 'data: {"jsonrpc":"2.0","id":' + id + ',\r\n', + 'data: "result":' + JSON.stringify({ + content: [{ type: 'text', text: JSON.stringify(result) }], + }) + '}\r\n\r\n', + ].join('')); + const split = body.indexOf(Buffer.from('📚')) + 1; + response.write(body.subarray(0, split)); + setImmediate(() => response.write(body.subarray(split))); + }; + const entries = await parallelSearch({ q: 'Europa Clipper' }); + expect(entries[0].description).toContain('📚\u2028and the same line.'); + expect(calls.at(-1)?.method).toBe('DELETE'); + }, 4_000); + + it('returns the RPC error even when both the result stream and cleanup stay open', async () => { + handleSearch = (response, id) => { + response.writeHead(200, { 'Content-Type': 'text/event-stream' }); + response.write('data: ' + JSON.stringify({ + jsonrpc: '2.0', id, error: { code: -32603, message: 'Private detail' }, + }) + '\n\n'); + }; + handleDelete = response => response.writeHead(200); + await expect(parallelSearch({ q: 'Europa Clipper' })).rejects.toThrow('code -32603'); + expect(calls.at(-1)?.method).toBe('DELETE'); + }, 4_000); + + it('rejects redirects from the search and session cleanup', async () => { + const address = redirectTarget.address() as AddressInfo; + handleSearch = handleDelete = response => response.writeHead(307, { + Location: 'http://127.0.0.1:' + address.port + '/other', + }).end(); + await expect(parallelSearch({ q: 'Europa Clipper' })).rejects.toThrow(); + expect(calls.at(-1)?.method).toBe('DELETE'); + expect(redirectHits).toBe(0); + }); + + it('rejects a compressed response that exceeds the decoded size limit', async () => { + handleSearch = (response, id) => { + response.writeHead(200, { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' }); + response.end(gzipSync(JSON.stringify({ + jsonrpc: '2.0', id, result: 'x'.repeat(10 * 1024 * 1024), + }))); + }; + await expect(parallelSearch({ q: 'Europa Clipper' })).rejects.toThrow('response is too large'); + expect(calls.at(-1)?.method).toBe('DELETE'); + }); + + it('skips empty queries before making a connection', async () => { + await expect(parallelSearch({ q: ' ' })).resolves.toEqual([]); + expect(calls).toHaveLength(0); + }); +}); diff --git a/src/tools/parallel-search.ts b/src/tools/parallel-search.ts new file mode 100644 index 00000000..f4c16b82 --- /dev/null +++ b/src/tools/parallel-search.ts @@ -0,0 +1,155 @@ +import { createParser } from 'eventsource-parser'; +import { z } from 'zod'; +import { name, version } from '../../package.json'; +import type { SERPQuery, UnNormalizedSearchSnippet } from '../types'; +import { formatDateRange } from '../utils/date-tools'; + +const endpoint = 'https://mcp.parallel.ai/mcp'; +const protocolVersion = '2025-06-18'; +const maxResponseBytes = 10 * 1024 * 1024; + +const replySchema = z.object({ + jsonrpc: z.literal('2.0'), + id: z.number(), + result: z.unknown(), + error: z.object({ code: z.number() }).optional(), +}); + +const toolResultSchema = z.object({ + isError: z.boolean().optional(), + structuredContent: z.unknown(), + content: z.array(z.object({ type: z.string(), text: z.string().optional() })).optional(), +}); + +const searchResultsSchema = z.object({ results: z.array(z.unknown()) }); +const resultSchema = z.object({ + url: z.string().url().regex(/^https?:\/\//i), + title: z.string().nullish(), + excerpts: z.array(z.string()), + publish_date: z.string().nullish(), +}); + +function matchReply(text: string, id: number) { + const reply = replySchema.safeParse(JSON.parse(text)); + if (reply.success && reply.data.id === id && + (reply.data.error || reply.data.result !== undefined)) { + return reply.data; + } +} + +async function readReply(response: Response, id: number): Promise { + const mediaType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase(); + const reader = response.body?.getReader(); + if (!reader) throw new Error('Parallel MCP returned an empty response'); + + try { + if (mediaType !== 'text/event-stream' && mediaType !== 'application/json') { + throw new Error('Parallel MCP returned an unsupported response type'); + } + + let reply: ReturnType; + const parser = createParser({ + onEvent: ({ data }) => { reply ??= matchReply(data, id); }, + }); + const decoder = new TextDecoder(); + let receivedBytes = 0; + let json = ''; + + while (!reply) { + const { value, done } = await reader.read(); + if (done) break; + receivedBytes += value.byteLength; + if (receivedBytes > maxResponseBytes) throw new Error('Parallel MCP response is too large'); + + const text = decoder.decode(value, { stream: true }); + if (mediaType === 'text/event-stream') parser.feed(text); + else json += text; + } + + if (mediaType === 'application/json') reply = matchReply(json + decoder.decode(), id); + if (!reply) throw new Error('Parallel MCP did not return a reply'); + if (reply.error) throw new Error(`Parallel MCP request failed (code ${reply.error.code})`); + return reply.result; + } finally { + // An SSE stream can stay open after the matching reply. + void reader.cancel().catch(() => undefined); + reader.releaseLock(); + } +} + +function discardBody(response: Response) { + void response.body?.cancel().catch(() => undefined); +} + +export async function parallelSearch(query: SERPQuery): Promise { + const q = query.q.trim(); + if (!q) return []; + + const headers = new Headers({ + Accept: 'application/json, text/event-stream', + 'Content-Type': 'application/json', + 'User-Agent': `${name}/${version}`, + }); + const signal = AbortSignal.timeout(20_000); + + async function post(message: object): Promise { + const response = await fetch(endpoint, { + method: 'POST', + headers, + body: JSON.stringify({ jsonrpc: '2.0', ...message }), + redirect: 'error', + signal, + }); + if (!response.ok) { + discardBody(response); + throw new Error(`Parallel MCP returned HTTP ${response.status}`); + } + return response; + } + + try { + const initialization = await post({ + id: 1, + method: 'initialize', + params: { protocolVersion, capabilities: {}, clientInfo: { name, version } }, + }); + const sessionId = initialization.headers.get('mcp-session-id'); + if (sessionId) headers.set('Mcp-Session-Id', sessionId); + const initialized = z.object({ protocolVersion: z.literal(protocolVersion) }) + .parse(await readReply(initialization, 1)); + headers.set('MCP-Protocol-Version', initialized.protocolVersion); + + discardBody(await post({ method: 'notifications/initialized' })); + + const dateRange = formatDateRange(query); + const objective = [q, query.location, dateRange].filter(Boolean).join('. '); + const response = await post({ + id: 2, + method: 'tools/call', + params: { name: 'web_search', arguments: { objective, search_queries: [q] } }, + }); + const result = toolResultSchema.parse(await readReply(response, 2)); + if (result.isError) throw new Error('Parallel web_search failed'); + + const text = result.content?.find(item => item.type === 'text')?.text; + const payload = result.structuredContent ?? (text ? JSON.parse(text) : undefined); + return searchResultsSchema.parse(payload).results.flatMap(item => { + const parsed = resultSchema.safeParse(item); + if (!parsed.success) return []; + const { url, title, excerpts, publish_date } = parsed.data; + const description = excerpts.join('\n\n').trim(); + if (!description) return []; + return [{ url, title: title?.trim() || url, description, date: publish_date || undefined }]; + }); + } finally { + if (headers.has('Mcp-Session-Id')) { + const cleanup = await fetch(endpoint, { + method: 'DELETE', + headers, + redirect: 'error', + signal: AbortSignal.timeout(1_000), + }).catch(() => undefined); + if (cleanup) discardBody(cleanup); + } + } +}