@scoheart/x-search-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.env.example +9 -0
  2. package/README.md +36 -7
  3. package/TOOL.md +46 -9
  4. package/dist/package.json +64 -0
  5. package/dist/src/auth.d.ts +2 -2
  6. package/dist/src/auth.d.ts.map +1 -1
  7. package/dist/src/auth.js +50 -6
  8. package/dist/src/auth.js.map +1 -1
  9. package/dist/src/cli.d.ts.map +1 -1
  10. package/dist/src/cli.js +40 -1
  11. package/dist/src/cli.js.map +1 -1
  12. package/dist/src/http-config.d.ts +4 -0
  13. package/dist/src/http-config.d.ts.map +1 -0
  14. package/dist/src/http-config.js +65 -0
  15. package/dist/src/http-config.js.map +1 -0
  16. package/dist/src/http-server.d.ts +20 -0
  17. package/dist/src/http-server.d.ts.map +1 -0
  18. package/dist/src/http-server.js +189 -0
  19. package/dist/src/http-server.js.map +1 -0
  20. package/dist/src/http.d.ts.map +1 -1
  21. package/dist/src/http.js +6 -10
  22. package/dist/src/http.js.map +1 -1
  23. package/dist/src/index.d.ts +3 -0
  24. package/dist/src/index.d.ts.map +1 -1
  25. package/dist/src/index.js +3 -0
  26. package/dist/src/index.js.map +1 -1
  27. package/dist/src/search.d.ts.map +1 -1
  28. package/dist/src/search.js +6 -4
  29. package/dist/src/search.js.map +1 -1
  30. package/dist/src/server.d.ts +2 -0
  31. package/dist/src/server.d.ts.map +1 -1
  32. package/dist/src/server.js +31 -13
  33. package/dist/src/server.js.map +1 -1
  34. package/dist/src/version.d.ts +2 -0
  35. package/dist/src/version.d.ts.map +1 -0
  36. package/dist/src/version.js +3 -0
  37. package/dist/src/version.js.map +1 -0
  38. package/examples/codex.toml +1 -1
  39. package/examples/mcp.json +1 -1
  40. package/package.json +4 -1
  41. package/src/auth.ts +47 -6
  42. package/src/cli.ts +42 -1
  43. package/src/http-config.ts +48 -0
  44. package/src/http-server.ts +188 -0
  45. package/src/http.ts +6 -10
  46. package/src/index.ts +3 -0
  47. package/src/search.ts +5 -4
  48. package/src/server.ts +33 -20
  49. package/src/version.ts +3 -0
  50. package/tsconfig.json +2 -1
package/examples/mcp.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "--yes",
7
- "@scoheart/x-search-mcp@0.1.0"
7
+ "@scoheart/x-search-mcp@0.2.0"
8
8
  ],
9
9
  "env": {
10
10
  "X_SEARCH_AUTH_MODE": "auto",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scoheart/x-search-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Independent MCP service for x_search, inspired by Hermes Agent",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,6 +40,7 @@
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsc",
43
+ "test": "npm run build && node --test test/*.test.mjs",
43
44
  "prepack": "npm run build",
44
45
  "start": "node dist/bin/x-search-mcp.js"
45
46
  },
@@ -47,12 +48,14 @@
47
48
  "access": "public"
48
49
  },
49
50
  "dependencies": {
51
+ "@modelcontextprotocol/node": "2.1.2",
50
52
  "@modelcontextprotocol/server": "2.4.0",
51
53
  "proper-lockfile": "4.1.2",
52
54
  "undici": "8.12.4",
53
55
  "zod": "4.6.7"
54
56
  },
55
57
  "devDependencies": {
58
+ "@modelcontextprotocol/client": "2.4.0",
56
59
  "@types/node": "^22.13.0",
57
60
  "@types/proper-lockfile": "^4.1.4",
58
61
  "typescript": "^5.8.0"
package/src/auth.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import crypto from 'node:crypto';
4
+ import { setTimeout as delay } from 'node:timers/promises';
4
5
  import lockfile from 'proper-lockfile';
5
6
  import { sendHttpRequest, HttpError } from './http.js';
6
7
  import { loadConfig } from './config.js';
@@ -20,6 +21,36 @@ const LOCK_OPTIONS = {
20
21
  },
21
22
  };
22
23
 
24
+ function throwIfCancelled(signal?: AbortSignal): void {
25
+ if (signal?.aborted) throw new HttpError('cancelled', 'Request was cancelled by client');
26
+ }
27
+
28
+ /** Keep the cross-process lease, but own its retry timers so a cancelled waiter stops. */
29
+ async function acquireAuthLock(file: string, signal?: AbortSignal): Promise<() => Promise<void>> {
30
+ for (let attempt = 0; ; attempt++) {
31
+ throwIfCancelled(signal);
32
+ let release: () => Promise<void>;
33
+ try {
34
+ release = await lockfile.lock(file, { ...LOCK_OPTIONS, retries: 0 });
35
+ } catch (error) {
36
+ throwIfCancelled(signal);
37
+ if ((error as NodeJS.ErrnoException).code !== 'ELOCKED' || attempt >= LOCK_OPTIONS.retries.retries) throw error;
38
+ const wait = Math.min(LOCK_OPTIONS.retries.maxTimeout,
39
+ LOCK_OPTIONS.retries.minTimeout * LOCK_OPTIONS.retries.factor ** attempt);
40
+ try { await delay(wait, undefined, { signal }); } catch (error) {
41
+ throwIfCancelled(signal);
42
+ throw error;
43
+ }
44
+ continue;
45
+ }
46
+ if (signal?.aborted) {
47
+ await release();
48
+ throwIfCancelled(signal);
49
+ }
50
+ return release;
51
+ }
52
+ }
53
+
23
54
  /**
24
55
  * Validate that an OAuth URL is secure and points strictly to an authorized x.ai domain.
25
56
  */
@@ -302,6 +333,8 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
302
333
  refresh_token: refreshToken,
303
334
  });
304
335
 
336
+ // A refresh can rotate the refresh token upstream. Once sent, finish and save it
337
+ // even if the caller disconnects; the owning MCP server drains this task on close.
305
338
  const res = await sendHttpRequest({
306
339
  url: tokenEndpoint,
307
340
  method: 'POST',
@@ -344,7 +377,8 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
344
377
  * Get valid OAuth access token, refreshing preemptively if expiring within 120s.
345
378
  * Concurrency-safe: shares auth.json across multiple agent processes using proper-lockfile.
346
379
  */
347
- export async function getValidOAuthAccessToken(): Promise<string> {
380
+ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<string> {
381
+ throwIfCancelled(signal);
348
382
  const config = loadConfig();
349
383
  const authFilePath = config.authFile;
350
384
 
@@ -361,8 +395,9 @@ export async function getValidOAuthAccessToken(): Promise<string> {
361
395
  }
362
396
 
363
397
  ensureAuthFileExists(authFilePath);
364
- const release = await lockfile.lock(authFilePath, LOCK_OPTIONS);
398
+ const release = await acquireAuthLock(authFilePath, signal);
365
399
  try {
400
+ throwIfCancelled(signal);
366
401
  authData = readAuthData(authFilePath);
367
402
  const updatedRemaining = (authData?.expires_at || 0) - Date.now();
368
403
  if (updatedRemaining > 120_000 && authData?.tokens?.access_token) {
@@ -373,7 +408,9 @@ export async function getValidOAuthAccessToken(): Promise<string> {
373
408
  throw new Error('Authentication data was deleted during token refresh.');
374
409
  }
375
410
 
376
- return await performTokenRefreshUnderLock(authData, authFilePath);
411
+ const token = await performTokenRefreshUnderLock(authData, authFilePath);
412
+ throwIfCancelled(signal);
413
+ return token;
377
414
  } finally {
378
415
  await release();
379
416
  }
@@ -383,13 +420,15 @@ export async function getValidOAuthAccessToken(): Promise<string> {
383
420
  * Force refresh token on HTTP 401 error.
384
421
  * If another concurrent process has already rotated the token, the new token is reused.
385
422
  */
386
- export async function forceRefreshToken(rejectedAccessToken: string): Promise<string> {
423
+ export async function forceRefreshToken(rejectedAccessToken: string, signal?: AbortSignal): Promise<string> {
424
+ throwIfCancelled(signal);
387
425
  const config = loadConfig();
388
426
  const authFilePath = config.authFile;
389
427
 
390
428
  ensureAuthFileExists(authFilePath);
391
- const release = await lockfile.lock(authFilePath, LOCK_OPTIONS);
429
+ const release = await acquireAuthLock(authFilePath, signal);
392
430
  try {
431
+ throwIfCancelled(signal);
393
432
  const authData = readAuthData(authFilePath);
394
433
  if (!authData || !authData.tokens) {
395
434
  throw new Error('OAuth authentication file is missing or corrupted.');
@@ -399,7 +438,9 @@ export async function forceRefreshToken(rejectedAccessToken: string): Promise<st
399
438
  return authData.tokens.access_token;
400
439
  }
401
440
 
402
- return await performTokenRefreshUnderLock(authData, authFilePath);
441
+ const token = await performTokenRefreshUnderLock(authData, authFilePath);
442
+ throwIfCancelled(signal);
443
+ return token;
403
444
  } finally {
404
445
  await release();
405
446
  }
package/src/cli.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import path from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
- import { startStdio } from './server.js';
3
+ import { createServer, startStdio } from './server.js';
4
+ import { startHttp } from './http-server.js';
5
+ import { loadHttpOptions } from './http-config.js';
4
6
  import { loginWithDeviceCode, getAuthStatus, logout } from './auth.js';
5
7
  import { executeSearch } from './search.js';
6
8
  import { listCallLogs } from './call-log.js';
@@ -9,6 +11,44 @@ import { loadConfig } from './config.js';
9
11
  export async function runCli(argv = process.argv.slice(2)): Promise<void> {
10
12
  const [command, subCommand, ...rest] = argv;
11
13
 
14
+ if (command === '--help' || command === '-h' || command === 'help'
15
+ || ((command === 'http' || command === '--http') && argv.slice(1).some(value => value === '--help' || value === '-h'))) {
16
+ console.log(`Usage: x-search-mcp [--stdio] | http [options] | auth <login|status|logout> | config | search "<query>" | logs
17
+
18
+ Default: start the stdio MCP server. Use http (or --http) for native Streamable HTTP.
19
+
20
+ HTTP options:
21
+ --host <address> Bind address (default: 127.0.0.1)
22
+ --port <number> TCP port (default: 8000; 0 chooses an available port)
23
+ --path <path> MCP endpoint (default: /mcp)
24
+ --token-file <file> Private file containing the HTTP bearer token
25
+ --allowed-host <hostname> Allow an additional Host hostname; repeatable, no ports
26
+ --allowed-origin <url> Allow an exact browser origin; repeatable
27
+
28
+ HTTP credentials: X_SEARCH_HTTP_TOKEN or X_SEARCH_HTTP_TOKEN_FILE.
29
+ Other HTTP environment defaults: X_SEARCH_HTTP_HOST, X_SEARCH_HTTP_PORT,
30
+ X_SEARCH_HTTP_PATH, X_SEARCH_HTTP_ALLOWED_HOSTS, X_SEARCH_HTTP_ALLOWED_ORIGINS.
31
+ Grok credentials remain server-side; HTTP access uses its own bearer token.`);
32
+ return;
33
+ }
34
+
35
+ if (command === 'http' || command === '--http') {
36
+ const service = await startHttp(createServer, loadHttpOptions(argv.slice(1)));
37
+ const stop = () => {
38
+ void service.close().catch(() => {
39
+ console.error('Could not shut down the HTTP MCP service cleanly');
40
+ process.exitCode = 1;
41
+ }).finally(() => {
42
+ process.off('SIGINT', stop);
43
+ process.off('SIGTERM', stop);
44
+ });
45
+ };
46
+ process.on('SIGINT', stop);
47
+ process.on('SIGTERM', stop);
48
+ console.error(`x-search-mcp HTTP listening at ${service.url}`);
49
+ return;
50
+ }
51
+
12
52
  // Default: run stdio MCP server
13
53
  if (!command || command === '--stdio') {
14
54
  await startStdio();
@@ -121,6 +161,7 @@ export async function runCli(argv = process.argv.slice(2)): Promise<void> {
121
161
  console.error(`Unknown command: ${command}`);
122
162
  console.error('Available commands:');
123
163
  console.error(' x-search-mcp [--stdio] Start MCP server over stdio');
164
+ console.error(' x-search-mcp http [options] Start authenticated Streamable HTTP');
124
165
  console.error(' x-search-mcp auth login Login with xAI OAuth Device Flow');
125
166
  console.error(' x-search-mcp auth status Show credentials status (safe)');
126
167
  console.error(' x-search-mcp auth logout Delete local OAuth token file');
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { normalizeAllowedHost, normalizeAllowedOrigin, normalizeHttpPath, type HttpServerOptions } from './http-server.js';
3
+
4
+ /** CLI flags override environment defaults; an explicit token file wins over env credentials. */
5
+ export function loadHttpOptions(args: string[], env: NodeJS.ProcessEnv = process.env): HttpServerOptions {
6
+ let host = env.X_SEARCH_HTTP_HOST ?? '127.0.0.1';
7
+ let port = env.X_SEARCH_HTTP_PORT ?? '8000';
8
+ let path = env.X_SEARCH_HTTP_PATH ?? '/mcp';
9
+ let tokenFile: string | undefined;
10
+ const hosts: string[] = [];
11
+ const origins: string[] = [];
12
+ const supported = new Set(['--host', '--port', '--path', '--token-file', '--allowed-host', '--allowed-origin']);
13
+ for (let index = 0; index < args.length; index++) {
14
+ const argument = args[index]!;
15
+ const equals = argument.indexOf('=');
16
+ const flag = equals < 0 ? argument : argument.slice(0, equals);
17
+ if (!supported.has(flag)) throw new Error('Unknown HTTP option; see x-search-mcp http --help');
18
+ const value = equals < 0 ? args[++index] : argument.slice(equals + 1);
19
+ if (value === undefined || !value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
20
+ switch (flag) {
21
+ case '--host': host = value; break;
22
+ case '--port': port = value; break;
23
+ case '--path': path = value; break;
24
+ case '--token-file': tokenFile = value; break;
25
+ case '--allowed-host': hosts.push(value); break;
26
+ case '--allowed-origin': origins.push(value); break;
27
+ }
28
+ }
29
+ if (!/^\d+$/.test(port) || !Number.isInteger(Number(port)) || Number(port) > 65535) {
30
+ throw new Error('HTTP port must be an integer between 0 and 65535');
31
+ }
32
+ const parseList = (value: string | undefined) => value?.split(',').map(item => item.trim()).filter(Boolean) ?? [];
33
+ const allowedHosts = (hosts.length ? hosts : parseList(env.X_SEARCH_HTTP_ALLOWED_HOSTS)).map(normalizeAllowedHost);
34
+ const allowedOrigins = (origins.length ? origins : parseList(env.X_SEARCH_HTTP_ALLOWED_ORIGINS)).map(normalizeAllowedOrigin);
35
+ const endpoint = normalizeHttpPath(path);
36
+ let token = env.X_SEARCH_HTTP_TOKEN?.trim();
37
+ const file = tokenFile ?? (!token ? env.X_SEARCH_HTTP_TOKEN_FILE : undefined);
38
+ if (file !== undefined) {
39
+ try { token = readFileSync(file, 'utf8').trim(); } catch (error) {
40
+ const code = (error as NodeJS.ErrnoException).code ?? 'READ_ERROR';
41
+ throw new Error(`Cannot read HTTP token file (${code})`);
42
+ }
43
+ }
44
+ if (!token || /\s/.test(token)) {
45
+ throw new Error('Set X_SEARCH_HTTP_TOKEN or a non-empty HTTP token file via --token-file / X_SEARCH_HTTP_TOKEN_FILE');
46
+ }
47
+ return { host, port: Number(port), path: endpoint, token, allowedHosts, allowedOrigins };
48
+ }
@@ -0,0 +1,188 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { createServer as createNodeServer, type ServerResponse } from 'node:http';
3
+ import { isIP } from 'node:net';
4
+ import { createMcpHandler, McpServer, type McpServerFactory } from '@modelcontextprotocol/server';
5
+ import { hostHeaderValidation, originValidation, toNodeHandler } from '@modelcontextprotocol/node';
6
+
7
+ export interface HttpServerOptions {
8
+ token: string;
9
+ host?: string;
10
+ port?: number;
11
+ path?: string;
12
+ allowedHosts?: string[];
13
+ allowedOrigins?: string[];
14
+ maxRequestBodyBytes?: number;
15
+ }
16
+
17
+ export interface RunningHttpServer {
18
+ url: string;
19
+ close(): Promise<void>;
20
+ }
21
+
22
+ export function normalizeHttpPath(value: string): string {
23
+ if (!value.startsWith('/') || value.startsWith('//') || /[?#\\\s]/.test(value)
24
+ || new URL(value, 'http://localhost').pathname !== value) {
25
+ throw new Error('HTTP path must be a normalized URL path such as /mcp');
26
+ }
27
+ return value;
28
+ }
29
+
30
+ export function normalizeAllowedHost(value: string): string {
31
+ let parsed: URL;
32
+ try { parsed = new URL(`http://${value}`); } catch { throw new Error('Allowed HTTP hosts must be hostnames without ports or paths'); }
33
+ if (parsed.username || parsed.password || parsed.port || parsed.pathname !== '/' || parsed.search || parsed.hash
34
+ || value.includes('*') || value.includes('://') || !parsed.hostname) {
35
+ throw new Error('Allowed HTTP hosts must be hostnames without ports or paths');
36
+ }
37
+ return parsed.hostname;
38
+ }
39
+
40
+ export function normalizeAllowedOrigin(value: string): string {
41
+ let parsed: URL;
42
+ try { parsed = new URL(value); } catch { throw new Error('Allowed HTTP origins must be http:// or https:// origins'); }
43
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password
44
+ || parsed.pathname !== '/' || parsed.search || parsed.hash || parsed.hostname.includes('*')) {
45
+ throw new Error('Allowed HTTP origins must be http:// or https:// origins without paths');
46
+ }
47
+ return parsed.origin;
48
+ }
49
+
50
+ function json(response: ServerResponse, status: number, message: string): void {
51
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
52
+ response.end(JSON.stringify({ error: message }));
53
+ }
54
+
55
+ /** Owns one listener and the SDK's stateless per-request handler. */
56
+ export async function startHttp(factory: McpServerFactory, options: HttpServerOptions): Promise<RunningHttpServer> {
57
+ if (typeof options.token !== 'string' || !options.token.trim() || /\s/.test(options.token)) {
58
+ throw new Error('A non-empty HTTP bearer token without whitespace is required');
59
+ }
60
+ const host = options.host ?? '127.0.0.1';
61
+ if (!host || host !== host.trim() || /[\s/\\?#]/.test(host)) throw new Error('Invalid HTTP bind host');
62
+ const port = options.port ?? 8000;
63
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('HTTP port must be an integer between 0 and 65535');
64
+ const endpointPath = normalizeHttpPath(options.path ?? '/mcp');
65
+ const maxBody = options.maxRequestBodyBytes ?? 1024 * 1024;
66
+ if (!Number.isSafeInteger(maxBody) || maxBody <= 0) throw new Error('HTTP request body limit must be a positive integer');
67
+ const loopback = ['localhost', '127.0.0.1', '[::1]'];
68
+ const boundHost = isIP(host) === 6 ? `[${host}]` : host;
69
+ const specificBind = ['0.0.0.0', '::'].includes(host) ? [] : [normalizeAllowedHost(boundHost)];
70
+ const allowedHosts = [...new Set([...loopback, ...specificBind, ...(options.allowedHosts ?? []).map(normalizeAllowedHost)])];
71
+ const allowedOrigins = (options.allowedOrigins ?? []).map(normalizeAllowedOrigin);
72
+ const validateHost = hostHeaderValidation(allowedHosts);
73
+ const validateOrigin = originValidation(allowedOrigins.length ? allowedOrigins.map(value => new URL(value).hostname) : loopback);
74
+ const expectedToken = Buffer.from(options.token);
75
+ type Product = Awaited<ReturnType<McpServerFactory>>;
76
+ const products = new Set<Product>();
77
+ const creating = new Set<Promise<Product>>();
78
+ let stopping = false;
79
+ const ownedFactory: McpServerFactory = context => {
80
+ if (stopping) throw new Error('HTTP MCP service is closing');
81
+ const pending = Promise.resolve().then(() => factory(context)).then(async product => {
82
+ const core = product instanceof McpServer ? product.server : product;
83
+ const originalClose = core.close.bind(core);
84
+ let closed: Promise<void> | undefined;
85
+ core.close = () => {
86
+ closed ??= Promise.resolve().then(originalClose).finally(() => { products.delete(product); });
87
+ return closed;
88
+ };
89
+ products.add(product);
90
+ if (stopping) {
91
+ await product.close();
92
+ throw new Error('HTTP MCP service is closing');
93
+ }
94
+ return product;
95
+ });
96
+ creating.add(pending);
97
+ void pending.then(() => { creating.delete(pending); }, () => { creating.delete(pending); });
98
+ return pending;
99
+ };
100
+ const handler = createMcpHandler(ownedFactory, { legacy: 'stateless', maxRequestBodySize: maxBody });
101
+ const nodeHandler = toNodeHandler(handler, { maxRequestBodySize: maxBody });
102
+
103
+ const listener = createNodeServer((request, response) => {
104
+ if (!validateHost(request, response) || !validateOrigin(request, response)) return;
105
+ const origin = request.headers.origin;
106
+ if (origin && allowedOrigins.length && !allowedOrigins.includes(origin)) {
107
+ json(response, 403, 'Origin is not allowed');
108
+ return;
109
+ }
110
+ let pathname: string;
111
+ try { pathname = new URL(request.url ?? '/', 'http://localhost').pathname; } catch {
112
+ json(response, 400, 'Invalid request URL');
113
+ return;
114
+ }
115
+ if (pathname !== endpointPath) {
116
+ json(response, 404, 'Not found');
117
+ return;
118
+ }
119
+ if (origin && allowedOrigins.includes(origin)) {
120
+ response.setHeader('Access-Control-Allow-Origin', origin);
121
+ response.setHeader('Vary', 'Origin');
122
+ response.setHeader('Access-Control-Expose-Headers', 'MCP-Protocol-Version, MCP-Session-Id');
123
+ }
124
+ if (request.method === 'OPTIONS' && origin && allowedOrigins.includes(origin)) {
125
+ if (request.headers['access-control-request-method'] !== 'POST') {
126
+ response.setHeader('Allow', 'POST, OPTIONS');
127
+ json(response, 405, 'Only MCP POST preflight requests are supported');
128
+ return;
129
+ }
130
+ const requestedHeaders = (request.headers['access-control-request-headers'] ?? '').split(',')
131
+ .map(value => value.trim().toLowerCase()).filter(Boolean);
132
+ const baseHeaders = new Set(['authorization', 'content-type', 'accept', 'last-event-id']);
133
+ if (requestedHeaders.some(value => !/^[a-z0-9-]+$/.test(value) || (!baseHeaders.has(value) && !value.startsWith('mcp-')))) {
134
+ json(response, 403, 'Requested browser headers are not allowed');
135
+ return;
136
+ }
137
+ response.writeHead(204, {
138
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
139
+ 'Access-Control-Allow-Headers': requestedHeaders.join(', ') || 'Authorization, Content-Type, Accept, MCP-Protocol-Version',
140
+ 'Vary': 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers',
141
+ 'Cache-Control': 'no-store',
142
+ });
143
+ response.end();
144
+ return;
145
+ }
146
+ const authorization = request.headers.authorization;
147
+ const supplied = typeof authorization === 'string' ? /^Bearer\s+(\S+)$/i.exec(authorization)?.[1] : undefined;
148
+ const candidate = Buffer.from(supplied ?? '');
149
+ if (candidate.length !== expectedToken.length || !timingSafeEqual(candidate, expectedToken)) {
150
+ response.setHeader('WWW-Authenticate', 'Bearer realm="x-search-mcp"');
151
+ json(response, 401, 'Valid MCP bearer credentials are required');
152
+ return;
153
+ }
154
+ void nodeHandler(request, response).catch(() => {
155
+ if (response.destroyed) return;
156
+ if (response.headersSent) response.destroy();
157
+ else json(response, 500, 'MCP HTTP request failed');
158
+ });
159
+ });
160
+
161
+ try {
162
+ await new Promise<void>((resolve, reject) => {
163
+ listener.once('error', reject);
164
+ listener.listen(port, host, () => { listener.removeListener('error', reject); resolve(); });
165
+ });
166
+ } catch (error) {
167
+ await handler.close();
168
+ throw error;
169
+ }
170
+ const address = listener.address();
171
+ if (!address || typeof address === 'string') throw new Error('HTTP listener did not expose a TCP address');
172
+ let closing: Promise<void> | undefined;
173
+ return {
174
+ url: `http://${boundHost}:${address.port}${endpointPath}`,
175
+ close() {
176
+ closing ??= (async () => {
177
+ stopping = true;
178
+ const stopped = new Promise<void>((resolve, reject) => listener.close(error => error ? reject(error) : resolve()));
179
+ listener.closeAllConnections();
180
+ await Promise.allSettled([...creating]);
181
+ // The SDK's legacy leg starts per-request teardown without awaiting it.
182
+ // Drain every owned product as well as the modern handler's exchanges.
183
+ await Promise.all([handler.close(), ...[...products].map(product => product.close()), stopped]);
184
+ })();
185
+ return closing;
186
+ },
187
+ };
188
+ }
package/src/http.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { request, EnvHttpProxyAgent } from 'undici';
2
+ import { version } from './version.js';
2
3
 
3
4
  // Global HTTP proxy agent reading standard environment variables: HTTP_PROXY, HTTPS_PROXY, NO_PROXY
4
5
  const proxyAgent = new EnvHttpProxyAgent();
@@ -115,6 +116,7 @@ export async function sendHttpRequest({
115
116
  signal?.addEventListener('abort', abortHandler, { once: true });
116
117
 
117
118
  let response: any;
119
+ let responseText = '';
118
120
  let timedOut = false;
119
121
  let cancelled = false;
120
122
 
@@ -122,13 +124,15 @@ export async function sendHttpRequest({
122
124
  response = await request(url, {
123
125
  method: method as any,
124
126
  headers: {
125
- 'User-Agent': 'x-search-mcp/0.1.0',
127
+ 'User-Agent': `x-search-mcp/${version}`,
126
128
  ...headers,
127
129
  },
128
130
  body: body as any,
129
131
  dispatcher: proxyAgent,
130
132
  signal: timeoutController.signal,
131
133
  });
134
+ // Keep the deadline and client cancellation attached through body consumption.
135
+ responseText = await response.body.text();
132
136
  } catch (err: any) {
133
137
  if (signal?.aborted || err?.message === 'CANCELLED') {
134
138
  cancelled = true;
@@ -165,19 +169,11 @@ export async function sendHttpRequest({
165
169
  // Retry on 5xx errors if remaining retries
166
170
  if (status >= 500 && status < 600 && attempt < maxRetries) {
167
171
  attempt++;
168
- await response.body.dump();
169
172
  const backoffMs = Math.min(1500 * attempt, 5000);
170
173
  await sleep(backoffMs, signal);
171
174
  continue;
172
175
  }
173
176
 
174
- let responseText = '';
175
- try {
176
- responseText = await response.body.text();
177
- } catch (readErr: any) {
178
- throw new HttpError('NETWORK_ERROR', `Failed reading response body: ${readErr.message}`);
179
- }
180
-
181
177
  let parsedData: any = null;
182
178
  const contentType = response.headers['content-type'] || '';
183
179
  if (typeof contentType === 'string' && (contentType.includes('application/json') || responseText.trim().startsWith('{'))) {
@@ -189,7 +185,7 @@ export async function sendHttpRequest({
189
185
  }
190
186
 
191
187
  if (status >= 400) {
192
- throw createSanitizedHttpError(status, parsedData);
188
+ throw createSanitizedHttpError(status, parsedData ?? responseText);
193
189
  }
194
190
 
195
191
  return {
package/src/index.ts CHANGED
@@ -5,4 +5,7 @@ export * from './auth.js';
5
5
  export * from './search.js';
6
6
  export * from './call-log.js';
7
7
  export * from './server.js';
8
+ export * from './http-server.js';
9
+ export * from './http-config.js';
10
+ export * from './version.js';
8
11
  export * from './cli.js';
package/src/search.ts CHANGED
@@ -280,7 +280,7 @@ export async function executeSearch(rawParams: Record<string, any>, { signal }:
280
280
  credentialSource = 'api_key';
281
281
  billingMode = 'api_metered';
282
282
  } else if (effectiveAuthMode === 'oauth') {
283
- token = await getValidOAuthAccessToken();
283
+ token = await getValidOAuthAccessToken(signal);
284
284
  credentialSource = 'oauth';
285
285
  billingMode = 'subscription_oauth';
286
286
  } else {
@@ -291,10 +291,11 @@ export async function executeSearch(rawParams: Record<string, any>, { signal }:
291
291
  billingMode = 'api_metered';
292
292
  } else {
293
293
  try {
294
- token = await getValidOAuthAccessToken();
294
+ token = await getValidOAuthAccessToken(signal);
295
295
  credentialSource = 'oauth';
296
296
  billingMode = 'subscription_oauth';
297
- } catch {
297
+ } catch (error) {
298
+ if (error instanceof HttpError && error.code === 'cancelled') throw error;
298
299
  throw new Error('Credential error: No valid credentials found. Provide XAI_API_KEY or authenticate via "x-search-mcp auth login".');
299
300
  }
300
301
  }
@@ -349,7 +350,7 @@ export async function executeSearch(rawParams: Record<string, any>, { signal }:
349
350
  attempts.push(attemptFromError(err));
350
351
  // If OAuth returns HTTP 401, force-refresh token once and retry once
351
352
  if (credentialSource === 'oauth' && err instanceof HttpError && err.status === 401) {
352
- const freshToken = await forceRefreshToken(token);
353
+ const freshToken = await forceRefreshToken(token, signal);
353
354
  try {
354
355
  httpRes = await sendHttpRequest({
355
356
  url: XAI_RESPONSES_URL,
package/src/server.ts CHANGED
@@ -1,12 +1,9 @@
1
- import { McpServer } from '@modelcontextprotocol/server';
1
+ import { McpServer, type ServerContext } from '@modelcontextprotocol/server';
2
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
3
  import { z } from 'zod';
4
4
  import { executeSearch } from './search.js';
5
-
6
- export const server = new McpServer({
7
- name: 'x-search-mcp',
8
- version: '0.1.0',
9
- });
5
+ import type { XSearchInput } from './types.js';
6
+ import { version } from './version.js';
10
7
 
11
8
  const searchInputSchema = {
12
9
  query: z
@@ -55,9 +52,9 @@ const toolDefinition = {
55
52
  },
56
53
  };
57
54
 
58
- const toolHandler = async (params: any, extra: any) => {
55
+ const toolHandler = async (params: XSearchInput, context: ServerContext) => {
59
56
  try {
60
- const signal = extra?.signal as AbortSignal | undefined;
57
+ const signal = context.mcpReq.signal;
61
58
  const result = await executeSearch(params, { signal });
62
59
  return {
63
60
  content: [
@@ -66,7 +63,7 @@ const toolHandler = async (params: any, extra: any) => {
66
63
  text: JSON.stringify(result, null, 2),
67
64
  },
68
65
  ],
69
- structuredContent: result,
66
+ structuredContent: { ...result },
70
67
  };
71
68
  } catch (err: any) {
72
69
  const errorPayload = {
@@ -94,23 +91,39 @@ const toolHandler = async (params: any, extra: any) => {
94
91
  }
95
92
  };
96
93
 
97
- if (typeof (server as any).registerTool === 'function') {
98
- (server as any).registerTool('x_search', toolDefinition, toolHandler);
99
- } else if (typeof (server as any).tool === 'function') {
100
- (server as any).tool(
101
- 'x_search',
102
- toolDefinition.description,
103
- toolDefinition.inputSchema,
104
- toolDefinition.annotations,
105
- toolHandler
106
- );
94
+ export function createServer(): McpServer {
95
+ const instance = new McpServer({ name: 'x-search-mcp', version });
96
+ const active = new Set<ReturnType<typeof toolHandler>>();
97
+ let closing: Promise<void> | undefined;
98
+ instance.registerTool('x_search', toolDefinition, (params, context) => {
99
+ if (closing) throw new Error('MCP server is closing');
100
+ const task = toolHandler(params, context);
101
+ active.add(task);
102
+ void task.then(() => { active.delete(task); }, () => { active.delete(task); });
103
+ return task;
104
+ });
105
+ // The modern SDK closes the underlying Server directly; legacy code closes
106
+ // McpServer. Owning the underlying close covers both entry points.
107
+ const closeTransport = instance.server.close.bind(instance.server);
108
+ instance.server.close = () => {
109
+ closing ??= Promise.resolve().then(async () => {
110
+ await closeTransport();
111
+ // Cancel queued/search work, but finish any already accepted credential rotation.
112
+ await Promise.allSettled([...active]);
113
+ });
114
+ return closing;
115
+ };
116
+ return instance;
107
117
  }
108
118
 
119
+ /** @deprecated Create a fresh server with createServer() for each transport. */
120
+ export const server = createServer();
121
+
109
122
  /**
110
123
  * Launch stdio server.
111
124
  * stdout is strictly reserved for JSON-RPC MCP messages.
112
125
  * Diagnostic logs are written to stderr.
113
126
  */
114
127
  export function startStdio() {
115
- return serveStdio(() => server);
128
+ return serveStdio(createServer);
116
129
  }
package/src/version.ts ADDED
@@ -0,0 +1,3 @@
1
+ import metadata from '../package.json' with { type: 'json' };
2
+
3
+ export const version = metadata.version;
package/tsconfig.json CHANGED
@@ -12,7 +12,8 @@
12
12
  "esModuleInterop": true,
13
13
  "skipLibCheck": true,
14
14
  "forceConsistentCasingInFileNames": true,
15
- "verbatimModuleSyntax": true
15
+ "verbatimModuleSyntax": true,
16
+ "resolveJsonModule": true
16
17
  },
17
18
  "include": [
18
19
  "src/**/*",