Skip to content

Your always-on AI coworkers that move between text, calls, and Slack.

TypeScript

feat: identify OpenDots requests to Parallel (#168)

Rowan Aldeanb4e77df7cf49
diff --git a/src/server/parallel.ts b/src/server/parallel.ts
index cf6f613..488a932 100644
--- a/src/server/parallel.ts
+++ b/src/server/parallel.ts
@@ -1,4 +1,7 @@
import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { z } from 'zod';
@@ -108,6 +111,36 @@ export function sourcesFromResult(
);
return sources;
}
+// src/server (tsx and tests) and dist/server/server (the production build) both
+// sit below the repository package.json. Walk up so either layout resolves it.
+function opendotsPackageVersion(): string {
+ let directory = dirname(fileURLToPath(import.meta.url));
+ for (let depth = 0; depth < 8; depth += 1) {
+ try {
+ const parsed: unknown = JSON.parse(
+ readFileSync(join(directory, 'package.json'), 'utf8'),
+ );
+ if (
+ parsed &&
+ typeof parsed === 'object' &&
+ 'name' in parsed &&
+ parsed.name === 'opendots' &&
+ 'version' in parsed &&
+ typeof parsed.version === 'string' &&
+ parsed.version.length > 0
+ )
+ return parsed.version;
+ } catch (error) {
+ const missing =
+ error instanceof Error && 'code' in error && error.code === 'ENOENT';
+ if (!missing) throw error;
+ }
+ const parent = dirname(directory);
+ if (parent === directory) break;
+ directory = parent;
+ }
+ throw new Error('Could not read the OpenDots version from package.json.');
+}
export async function parallelSources(
request: {
objective: string;
@@ -122,14 +155,19 @@ export async function parallelSources(
signal.throwIfAborted();
if ((config.webSearchProvider ?? 'parallel') !== 'parallel')
throw new Error('Parallel web research is disabled.');
- const client = new Client({ name: 'opendots', version: '0.1.0' });
+ const version = opendotsPackageVersion();
+ const client = new Client({ name: 'opendots', version });
const boundedSignal = AbortSignal.any([signal, AbortSignal.timeout(60_000)]);
+ // Identify aggregate project usage, without user or installation identifiers.
+ const headers: Record<string, string> = {
+ 'User-Agent': `opendots/${version}`,
+ };
+ if (config.parallelApiKey)
+ headers.Authorization = `Bearer ${config.parallelApiKey}`;
const transport = new StreamableHTTPClientTransport(
new URL('https://search.parallel.ai/mcp'),
{
- requestInit: config.parallelApiKey
- ? { headers: { Authorization: `Bearer ${config.parallelApiKey}` } }
- : undefined,
+ requestInit: { headers },
fetch: (url, init) =>
fetch(url, {
...init,
diff --git a/tests/parallel-user-agent.test.ts b/tests/parallel-user-agent.test.ts
new file mode 100644
index 0000000..84026d7
--- /dev/null
+++ b/tests/parallel-user-agent.test.ts
@@ -0,0 +1,152 @@
+import { once } from 'node:events';
+import { readFileSync } from 'node:fs';
+import { createServer, type IncomingHttpHeaders } from 'node:http';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { parallelSources } from '../src/server/parallel.js';
+
+const version = (
+ JSON.parse(
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
+ ) as {
+ version: string;
+ }
+).version;
+const userAgent = `opendots/${version}`;
+const page = {
+ title: 'Evidence',
+ url: 'https://example.com',
+ excerpts: ['Verified evidence.'],
+};
+
+async function captureParallelRequests() {
+ const requests: { headers: IncomingHttpHeaders; body: string }[] = [];
+ const server = createServer(async (request, response) => {
+ if (request.method !== 'POST') {
+ response.writeHead(405).end();
+ return;
+ }
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const body = Buffer.concat(chunks).toString('utf8');
+ requests.push({ headers: request.headers, body });
+ const message = JSON.parse(body) as { id?: number; method?: string };
+ if (message.id === undefined) {
+ response.writeHead(202).end();
+ return;
+ }
+ const result =
+ message.method === 'initialize'
+ ? {
+ protocolVersion: '2025-11-25',
+ capabilities: { tools: {} },
+ serverInfo: { name: 'fixture', version: '1.0.0' },
+ }
+ : {
+ content: [
+ { type: 'text', text: JSON.stringify({ results: [page] }) },
+ ],
+ structuredContent: { results: [page] },
+ };
+ response.writeHead(200, {
+ 'content-type': 'application/json',
+ 'mcp-session-id': 'session-1',
+ });
+ response.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }));
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const address = server.address();
+ if (!address || typeof address === 'string')
+ throw new Error('The mock Parallel server has no port.');
+ const original = globalThis.fetch;
+ vi.stubGlobal('fetch', (async (
+ url: RequestInfo | URL,
+ init?: RequestInit,
+ ) => {
+ const target = url instanceof Request ? url.url : String(url);
+ if (target === 'https://search.parallel.ai/mcp')
+ return original(`http://127.0.0.1:${address.port}/mcp`, init);
+ return original(url, init);
+ }) as typeof fetch);
+ return {
+ requests,
+ async close() {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ },
+ };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Parallel User-Agent', () => {
+ it('sends opendots/<package version> on MCP requests without a key', async () => {
+ const captured = await captureParallelRequests();
+ try {
+ const sources = await parallelSources(
+ {
+ objective: 'Read',
+ urls: ['https://example.com'],
+ sessionId: 'conversation-1',
+ },
+ {},
+ new AbortController().signal,
+ );
+ expect(sources).toEqual([
+ {
+ title: 'Evidence',
+ url: 'https://example.com',
+ text: 'Verified evidence.',
+ },
+ ]);
+ const calls = captured.requests.map((request) => ({
+ userAgent: request.headers['user-agent'],
+ authorization: request.headers.authorization,
+ message: JSON.parse(request.body) as {
+ method?: string;
+ params?: { clientInfo?: { name: string; version: string } };
+ },
+ }));
+ expect(calls.length).toBeGreaterThan(0);
+ expect(calls.map((call) => call.userAgent)).toEqual(
+ calls.map(() => userAgent),
+ );
+ expect(calls.map((call) => call.authorization)).toEqual(
+ calls.map(() => undefined),
+ );
+ expect(
+ calls.find((call) => call.message.method === 'initialize')?.message
+ .params?.clientInfo,
+ ).toEqual({ name: 'opendots', version });
+ expect(calls.some((call) => call.message.method === 'tools/call')).toBe(
+ true,
+ );
+ } finally {
+ await captured.close();
+ }
+ });
+
+ it('keeps the same User-Agent when a Parallel API key is configured', async () => {
+ const captured = await captureParallelRequests();
+ try {
+ await parallelSources(
+ {
+ objective: 'Read',
+ urls: ['https://example.com'],
+ sessionId: 'conversation-1',
+ },
+ { parallelApiKey: 'test-key' },
+ new AbortController().signal,
+ );
+ expect(captured.requests.length).toBeGreaterThan(0);
+ for (const request of captured.requests) {
+ expect(request.headers['user-agent']).toBe(userAgent);
+ expect(request.headers.authorization).toBe('Bearer test-key');
+ }
+ } finally {
+ await captured.close();
+ }
+ });
+});