@scoheart/x-search-mcp 0.3.0 → 0.4.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 (47) hide show
  1. package/README.md +3 -3
  2. package/TOOL.md +8 -6
  3. package/dist/package.json +2 -1
  4. package/dist/src/auth.d.ts.map +1 -1
  5. package/dist/src/auth.js +61 -46
  6. package/dist/src/auth.js.map +1 -1
  7. package/dist/src/call-log.d.ts.map +1 -1
  8. package/dist/src/call-log.js +52 -33
  9. package/dist/src/call-log.js.map +1 -1
  10. package/dist/src/device-login.d.ts +46 -0
  11. package/dist/src/device-login.d.ts.map +1 -0
  12. package/dist/src/device-login.js +72 -0
  13. package/dist/src/device-login.js.map +1 -0
  14. package/dist/src/multi-user/service.js +2 -2
  15. package/dist/src/multi-user/service.js.map +1 -1
  16. package/dist/src/search-input.d.ts +43 -0
  17. package/dist/src/search-input.d.ts.map +1 -0
  18. package/dist/src/search-input.js +105 -0
  19. package/dist/src/search-input.js.map +1 -0
  20. package/dist/src/search-response.d.ts +6 -0
  21. package/dist/src/search-response.d.ts.map +1 -0
  22. package/dist/src/search-response.js +125 -0
  23. package/dist/src/search-response.js.map +1 -0
  24. package/dist/src/search.d.ts +3 -19
  25. package/dist/src/search.d.ts.map +1 -1
  26. package/dist/src/search.js +54 -312
  27. package/dist/src/search.js.map +1 -1
  28. package/dist/src/server.d.ts +2 -0
  29. package/dist/src/server.d.ts.map +1 -1
  30. package/dist/src/server.js +61 -158
  31. package/dist/src/server.js.map +1 -1
  32. package/dist/src/tool-contract.d.ts +150 -0
  33. package/dist/src/tool-contract.d.ts.map +1 -0
  34. package/dist/src/tool-contract.js +83 -0
  35. package/dist/src/tool-contract.js.map +1 -0
  36. package/examples/codex.toml +1 -1
  37. package/examples/mcp.json +1 -1
  38. package/package.json +2 -1
  39. package/src/auth.ts +59 -46
  40. package/src/call-log.ts +52 -31
  41. package/src/device-login.ts +84 -0
  42. package/src/multi-user/service.ts +2 -2
  43. package/src/search-input.ts +113 -0
  44. package/src/search-response.ts +127 -0
  45. package/src/search.ts +127 -418
  46. package/src/server.ts +66 -170
  47. package/src/tool-contract.ts +90 -0
package/src/auth.ts CHANGED
@@ -9,6 +9,7 @@ import type { AuthRecord, AuthStatus, DiscoveryMetadata } from './types.js';
9
9
 
10
10
  const DISCOVERY_URL = 'https://auth.x.ai/.well-known/openid-configuration';
11
11
  const DEFAULT_SCOPE = 'openid profile email offline_access grok-cli:access api:access';
12
+ const maxDateMilliseconds = 8.64e15;
12
13
  const LOCK_OPTIONS = {
13
14
  realpath: false,
14
15
  stale: 60000,
@@ -123,7 +124,8 @@ export function extractJwtExpiry(jwtToken: string | undefined): number | null {
123
124
  const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf8');
124
125
  const payload = JSON.parse(payloadJson);
125
126
  if (typeof payload.exp === 'number') {
126
- return payload.exp * 1000;
127
+ const expiry = payload.exp * 1000;
128
+ if (expiry > 0 && expiry <= maxDateMilliseconds) return expiry;
127
129
  }
128
130
  } catch {
129
131
  // Return null if unparseable
@@ -133,18 +135,10 @@ export function extractJwtExpiry(jwtToken: string | undefined): number | null {
133
135
 
134
136
  function ensureAuthFileExists(authFilePath: string): void {
135
137
  const dir = path.dirname(authFilePath);
136
- if (!fs.existsSync(dir)) {
137
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
138
- } else {
139
- try {
140
- fs.chmodSync(dir, 0o700);
141
- } catch {
142
- // Best effort chmod
143
- }
144
- }
138
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
145
139
 
146
140
  if (!fs.existsSync(authFilePath)) {
147
- fs.writeFileSync(authFilePath, '', { mode: 0o600 });
141
+ fs.writeFileSync(authFilePath, '', { flag: 'a', mode: 0o600 });
148
142
  } else {
149
143
  try {
150
144
  fs.chmodSync(authFilePath, 0o600);
@@ -164,8 +158,17 @@ export function saveAuthDataAtomic(authFilePath: string, data: AuthRecord): void
164
158
  const tempFilePath = path.join(dir, `.auth.${Date.now()}.${randomSuffix}.tmp`);
165
159
 
166
160
  const content = JSON.stringify(data, null, 2);
167
- fs.writeFileSync(tempFilePath, content, { mode: 0o600, encoding: 'utf8' });
168
- fs.renameSync(tempFilePath, authFilePath);
161
+ try {
162
+ fs.writeFileSync(tempFilePath, content, { mode: 0o600, encoding: 'utf8' });
163
+ fs.renameSync(tempFilePath, authFilePath);
164
+ } catch (error) {
165
+ try {
166
+ fs.rmSync(tempFilePath, { force: true });
167
+ } catch {
168
+ // Preserve the original write error.
169
+ }
170
+ throw error;
171
+ }
169
172
 
170
173
  try {
171
174
  fs.chmodSync(authFilePath, 0o600);
@@ -199,6 +202,38 @@ function invalidDeviceResponse(): HttpError {
199
202
  return new HttpError('DEVICE_LOGIN_INVALID_RESPONSE', 'xAI returned invalid device authorization data.');
200
203
  }
201
204
 
205
+ function isOAuthToken(value: unknown): value is string {
206
+ return typeof value === 'string' && value.length > 0 && !/[\s\x00-\x1f\x7f]/.test(value);
207
+ }
208
+
209
+ function parseTokenGrant(payload: unknown, invalidResponse: () => HttpError): Pick<AuthRecord, 'tokens' | 'expires_at'> {
210
+ if (!payload || typeof payload !== 'object') throw invalidResponse();
211
+ const data = payload as Record<string, unknown>;
212
+ const accessToken = data.access_token;
213
+ const refreshToken = data.refresh_token ?? '';
214
+ if (!isOAuthToken(accessToken) || (refreshToken !== '' && !isOAuthToken(refreshToken))) {
215
+ throw invalidResponse();
216
+ }
217
+
218
+ const now = Date.now();
219
+ const rawSeconds = data.expires_in;
220
+ let expiresAt: number;
221
+ if (rawSeconds === undefined || rawSeconds === null) {
222
+ expiresAt = extractJwtExpiry(accessToken) ?? now + 3_600_000;
223
+ } else {
224
+ const seconds = typeof rawSeconds === 'string' && /^\d+(?:\.\d+)?$/.test(rawSeconds.trim())
225
+ ? Number(rawSeconds) : rawSeconds;
226
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) throw invalidResponse();
227
+ expiresAt = now + seconds * 1000;
228
+ }
229
+ if (expiresAt <= now || expiresAt > maxDateMilliseconds) throw invalidResponse();
230
+
231
+ return {
232
+ tokens: { access_token: accessToken, ...(refreshToken ? { refresh_token: refreshToken } : {}) },
233
+ expires_at: expiresAt,
234
+ };
235
+ }
236
+
202
237
  function verifyBrowserUrl(value: unknown, deviceCode: string): string {
203
238
  if (typeof value === 'string') {
204
239
  try {
@@ -301,22 +336,11 @@ export async function startDeviceFlow(signal?: AbortSignal) {
301
336
  throw error;
302
337
  }
303
338
 
304
- const tokenData = response.data;
305
- if (typeof tokenData?.access_token !== 'string' || !tokenData.access_token) {
306
- throw invalidDeviceResponse();
307
- }
308
- const tokenExpiresAt = tokenData.expires_in
309
- ? Date.now() + tokenData.expires_in * 1000
310
- : extractJwtExpiry(tokenData.access_token) || Date.now() + 3600 * 1000;
311
339
  const record: AuthRecord = {
312
340
  version: 1,
313
341
  client_id: config.oauthClientId,
314
342
  token_endpoint: discovery.token_endpoint,
315
- tokens: {
316
- access_token: tokenData.access_token,
317
- refresh_token: tokenData.refresh_token,
318
- },
319
- expires_at: tokenExpiresAt,
343
+ ...parseTokenGrant(response.data, invalidDeviceResponse),
320
344
  };
321
345
 
322
346
  throwIfCancelled(signal);
@@ -357,7 +381,7 @@ export async function loginWithDeviceCode(): Promise<void> {
357
381
 
358
382
  async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath: string): Promise<string> {
359
383
  const refreshToken = authData?.tokens?.refresh_token;
360
- if (!refreshToken) {
384
+ if (!isOAuthToken(refreshToken)) {
361
385
  throw oauthRequired('No Grok OAuth refresh token is available.');
362
386
  }
363
387
 
@@ -389,26 +413,15 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
389
413
  throw error;
390
414
  });
391
415
 
392
- const data = res.data;
393
- if (!data || !data.access_token) {
394
- throw new Error('Token refresh response did not contain an access_token');
395
- }
396
-
397
- let expiresAt = data.expires_in ? Date.now() + data.expires_in * 1000 : null;
398
- if (!expiresAt) {
399
- expiresAt = extractJwtExpiry(data.access_token);
400
- }
401
- if (!expiresAt) {
402
- expiresAt = Date.now() + 3600 * 1000;
403
- }
404
-
416
+ const grant = parseTokenGrant(res.data, () =>
417
+ new HttpError('OAUTH_INVALID_TOKEN_RESPONSE', 'xAI returned an invalid OAuth token response.', res.status));
405
418
  const updatedRecord: AuthRecord = {
406
419
  ...authData,
420
+ ...grant,
407
421
  tokens: {
408
- access_token: data.access_token,
409
- refresh_token: data.refresh_token || refreshToken,
422
+ access_token: grant.tokens.access_token,
423
+ refresh_token: grant.tokens.refresh_token ?? refreshToken,
410
424
  },
411
- expires_at: expiresAt,
412
425
  };
413
426
 
414
427
  saveAuthDataAtomic(authFilePath, updatedRecord);
@@ -425,7 +438,7 @@ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<st
425
438
  const authFilePath = config.authFile;
426
439
 
427
440
  let authData = readAuthData(authFilePath);
428
- if (!authData || !authData.tokens || !authData.tokens.access_token) {
441
+ if (!authData || !isOAuthToken(authData.tokens?.access_token)) {
429
442
  throw oauthRequired('No Grok OAuth credential is available.');
430
443
  }
431
444
 
@@ -442,7 +455,7 @@ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<st
442
455
  throwIfCancelled(signal);
443
456
  authData = readAuthData(authFilePath);
444
457
  const updatedRemaining = (authData?.expires_at || 0) - Date.now();
445
- if (updatedRemaining > 120_000 && authData?.tokens?.access_token) {
458
+ if (updatedRemaining > 120_000 && isOAuthToken(authData?.tokens?.access_token)) {
446
459
  return authData.tokens.access_token;
447
460
  }
448
461
 
@@ -476,7 +489,7 @@ export async function forceRefreshToken(rejectedAccessToken: string, signal?: Ab
476
489
  throw oauthRequired('The Grok OAuth credential is missing or corrupted.');
477
490
  }
478
491
 
479
- if (authData.tokens.access_token && authData.tokens.access_token !== rejectedAccessToken) {
492
+ if (isOAuthToken(authData.tokens.access_token) && authData.tokens.access_token !== rejectedAccessToken) {
480
493
  return authData.tokens.access_token;
481
494
  }
482
495
 
@@ -496,7 +509,7 @@ export function getAuthStatus(): AuthStatus {
496
509
  const authData = readAuthData(config.authFile);
497
510
 
498
511
  const hasApiKey = Boolean(config.apiKey);
499
- const hasOAuth = Boolean(authData?.tokens?.access_token);
512
+ const hasOAuth = isOAuthToken(authData?.tokens?.access_token);
500
513
 
501
514
  const expiry = new Date(authData?.expires_at ?? NaN);
502
515
  const oauthExpiresAt = hasOAuth && Number.isFinite(expiry.getTime()) ? expiry.toISOString() : null;
package/src/call-log.ts CHANGED
@@ -21,13 +21,21 @@ const SENSITIVE_KEYS = new Set([
21
21
  const BEARER = /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi;
22
22
  const XAI_KEY = /xai-[A-Za-z0-9_-]{16,}/g;
23
23
 
24
+ function redactText(value: string): string {
25
+ return value.replace(BEARER, 'Bearer [redacted]').replace(XAI_KEY, 'xai-[redacted]');
26
+ }
27
+
28
+ function redactLogError(error: CallLogEntry['error']): CallLogEntry['error'] {
29
+ return error && { code: redactText(error.code), message: redactText(error.message), status: error.status };
30
+ }
31
+
24
32
  /**
25
33
  * Remove credential-shaped values before a call log is written.
26
34
  * Post text is preserved; only known secret keys and token formats are replaced.
27
35
  */
28
36
  export function redactForLog(value: unknown, seen = new WeakSet<object>()): unknown {
29
37
  if (typeof value === 'string') {
30
- return value.replace(BEARER, 'Bearer [redacted]').replace(XAI_KEY, 'xai-[redacted]');
38
+ return redactText(value);
31
39
  }
32
40
  if (value === null || typeof value !== 'object') {
33
41
  return value;
@@ -69,17 +77,35 @@ function stamp(): string {
69
77
  return new Date().toISOString().replace(/[-:]/g, '').replace('.', '');
70
78
  }
71
79
 
80
+ async function callLogPaths(dir: string): Promise<string[]> {
81
+ try {
82
+ const names = await fs.promises.readdir(dir);
83
+ return names.filter(name => /^call-.*\.json$/.test(name)).map(name => path.join(dir, name));
84
+ } catch (error) {
85
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ async function recentCallLogFiles(paths: string[]) {
91
+ const files = await Promise.all(paths.map(async file => {
92
+ try {
93
+ const stat = await fs.promises.lstat(file);
94
+ return stat.isFile() ? { file, bytes: stat.size, mtimeMs: stat.mtimeMs } : null;
95
+ } catch (error) {
96
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
97
+ throw error;
98
+ }
99
+ }));
100
+ return files.filter(file => file !== null).sort((left, right) => right.mtimeMs - left.mtimeMs);
101
+ }
102
+
72
103
  async function pruneCallLogs(dir: string, keep: number): Promise<void> {
73
104
  if (keep <= 0) return;
74
- const names = (await fs.promises.readdir(dir)).filter((name) => /^call-.*\.json$/.test(name));
75
- if (names.length <= keep) return;
76
- const ranked = await Promise.all(names.map(async (name) => {
77
- const full = path.join(dir, name);
78
- const stat = await fs.promises.stat(full);
79
- return { full, mtime: stat.mtimeMs };
80
- }));
81
- ranked.sort((left, right) => right.mtime - left.mtime);
82
- await Promise.all(ranked.slice(keep).map((item) => fs.promises.rm(item.full, { force: true })));
105
+ const paths = await callLogPaths(dir);
106
+ if (paths.length <= keep) return;
107
+ const ranked = await recentCallLogFiles(paths);
108
+ await Promise.all(ranked.slice(keep).map(({ file }) => fs.promises.rm(file, { force: true })));
83
109
  }
84
110
 
85
111
  /**
@@ -95,6 +121,7 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
95
121
  const bounded = boundForLog(redactForLog(attempt.raw_response), config.logMaxBytes);
96
122
  return {
97
123
  ...attempt,
124
+ error: redactLogError(attempt.error),
98
125
  raw_response: bounded.value,
99
126
  raw_response_truncated: bounded.truncated,
100
127
  raw_response_bytes: bounded.bytes,
@@ -108,14 +135,14 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
108
135
  elapsed_ms: entry.elapsed_ms,
109
136
  endpoint: entry.endpoint,
110
137
  model: entry.model,
111
- query: entry.query,
138
+ query: redactText(entry.query),
112
139
  credential_source: entry.credential_source,
113
140
  billing_mode: entry.billing_mode,
114
141
  request: redactForLog(entry.request),
115
142
  attempts: redactedAttempts,
116
143
  raw_response: redactedAttempts.length > 0 ? redactedAttempts[redactedAttempts.length - 1].raw_response : null,
117
144
  outcome: entry.outcome,
118
- error: entry.error,
145
+ error: redactLogError(entry.error),
119
146
  };
120
147
 
121
148
  const dir = config.logDir;
@@ -124,39 +151,33 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
124
151
  const temporary = path.join(dir, `.${filename}.${process.pid}.tmp`);
125
152
  try {
126
153
  await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
127
- await fs.promises.chmod(dir, 0o700);
128
154
  await fs.promises.writeFile(temporary, JSON.stringify(record, null, 2), { mode: 0o600 });
129
155
  await fs.promises.chmod(temporary, 0o600);
130
156
  await fs.promises.rename(temporary, destination);
131
- await fs.promises.chmod(destination, 0o600);
132
- await pruneCallLogs(dir, config.logKeep);
133
- return destination;
134
- } catch (err: any) {
135
- console.error(`x-search-mcp call_log_error=${err?.message || 'failed to write call log'}`);
157
+ } catch (error) {
158
+ const message = error instanceof Error ? redactText(error.message) : 'failed to write call log';
159
+ console.error(`x-search-mcp call_log_error=${message}`);
136
160
  await fs.promises.rm(temporary, { force: true }).catch(() => undefined);
137
161
  return null;
138
162
  }
163
+ try {
164
+ await pruneCallLogs(dir, config.logKeep);
165
+ } catch (error) {
166
+ const message = error instanceof Error ? redactText(error.message) : 'failed to prune call logs';
167
+ console.error(`x-search-mcp call_log_prune_error=${message}`);
168
+ }
169
+ return destination;
139
170
  }
140
171
 
141
172
  export async function listCallLogs(limit = 20): Promise<{ enabled: boolean; directory: string; keep: number; files: Array<{ file: string; bytes: number; mtime: string }> }> {
142
173
  const config = loadConfig();
143
174
  const bounded = Math.max(1, Math.min(limit, 100));
144
- let names: string[] = [];
145
- try {
146
- names = (await fs.promises.readdir(config.logDir)).filter((name) => /^call-.*\.json$/.test(name));
147
- } catch (err: any) {
148
- if (err?.code !== 'ENOENT') throw err;
149
- }
150
- const ranked = await Promise.all(names.map(async (name) => {
151
- const full = path.join(config.logDir, name);
152
- const stat = await fs.promises.stat(full);
153
- return { file: full, bytes: stat.size, mtimeMs: stat.mtimeMs, mtime: stat.mtime.toISOString() };
154
- }));
155
- ranked.sort((left, right) => right.mtimeMs - left.mtimeMs);
175
+ const ranked = await recentCallLogFiles(await callLogPaths(config.logDir));
156
176
  return {
157
177
  enabled: config.logEnabled,
158
178
  directory: config.logDir,
159
179
  keep: config.logKeep,
160
- files: ranked.slice(0, bounded).map(({ file, bytes, mtime }) => ({ file, bytes, mtime })),
180
+ files: ranked.slice(0, bounded).map(({ file, bytes, mtimeMs }) =>
181
+ ({ file, bytes, mtime: new Date(mtimeMs).toISOString() })),
161
182
  };
162
183
  }
@@ -0,0 +1,84 @@
1
+ import { getAuthStatus, startDeviceFlow } from './auth.js';
2
+ import { HttpError } from './http.js';
3
+
4
+ type DevicePrompt = Awaited<ReturnType<typeof startDeviceFlow>>['prompt'];
5
+ export const deviceFailureStatuses = ['denied', 'expired', 'superseded', 'failed', 'cancelled'] as const;
6
+ type DeviceFailureStatus = typeof deviceFailureStatuses[number];
7
+ type DeviceFailure = { status: DeviceFailureStatus; error: { code: string; message: string; status: number | null } };
8
+ type DeviceState = { status: 'idle' | 'starting' | 'authorized' }
9
+ | { status: 'pending'; expires_at: string }
10
+ | DeviceFailure;
11
+ type DeviceStart = ({ status: 'pending' } & DevicePrompt) | DeviceFailure;
12
+
13
+ const deviceFailures: Record<string, { status: DeviceFailureStatus; message: string }> = {
14
+ DEVICE_LOGIN_DENIED: { status: 'denied', message: 'Grok authorization was declined.' },
15
+ DEVICE_LOGIN_EXPIRED: { status: 'expired', message: 'The Grok device code expired.' },
16
+ DEVICE_LOGIN_SUPERSEDED: { status: 'superseded', message: 'The local credential changed. Check its status before signing in again.' },
17
+ DEVICE_LOGIN_INVALID_RESPONSE: { status: 'failed', message: 'xAI returned invalid device authorization data.' },
18
+ cancelled: { status: 'cancelled', message: 'The login was cancelled.' },
19
+ };
20
+
21
+ function deviceLoginFailure(error: unknown): DeviceFailure {
22
+ const code = error instanceof HttpError ? error.code
23
+ : error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'DEVICE_LOGIN_FAILED';
24
+ const failure = Object.hasOwn(deviceFailures, code) ? deviceFailures[code] : undefined;
25
+ return {
26
+ status: failure?.status ?? 'failed',
27
+ error: {
28
+ code,
29
+ message: failure?.message ?? 'Could not complete Grok device authorization.',
30
+ status: error instanceof HttpError ? error.status : null,
31
+ },
32
+ };
33
+ }
34
+
35
+ export function createDeviceLogin() {
36
+ const controller = new AbortController();
37
+ let starting: Promise<DeviceStart> | undefined;
38
+ let polling: Promise<void> | undefined;
39
+ let pending: ({ status: 'pending' } & DevicePrompt) | undefined;
40
+ let state: DeviceState = { status: 'idle' };
41
+
42
+ return {
43
+ async start(): Promise<DeviceStart> {
44
+ if (starting) return starting;
45
+ if (pending) return pending;
46
+ state = { status: 'starting' };
47
+ starting = startDeviceFlow(controller.signal).then((flow): DeviceStart => {
48
+ pending = { status: 'pending', ...flow.prompt };
49
+ state = { status: 'pending', expires_at: pending.expires_at };
50
+ polling = flow.waitForAuthorization().then(
51
+ () => { state = { status: 'authorized' }; },
52
+ error => { state = deviceLoginFailure(error); },
53
+ ).finally(() => {
54
+ pending = undefined;
55
+ polling = undefined;
56
+ });
57
+ return pending;
58
+ }).catch(error => {
59
+ const failure = deviceLoginFailure(error);
60
+ state = failure;
61
+ return failure;
62
+ }).finally(() => { starting = undefined; });
63
+ return starting;
64
+ },
65
+ status() {
66
+ const { hasOAuth, oauthExpiresAt, hasApiKey, defaultAuthMode } = getAuthStatus();
67
+ const oauthState = !hasOAuth ? 'missing'
68
+ : !oauthExpiresAt ? 'unknown'
69
+ : Date.parse(oauthExpiresAt) > Date.now() ? 'unexpired' : 'expired';
70
+ return {
71
+ ...state,
72
+ oauth_state: oauthState,
73
+ oauth_expires_at: oauthExpiresAt,
74
+ has_api_key: hasApiKey,
75
+ auth_mode: defaultAuthMode,
76
+ };
77
+ },
78
+ async close() {
79
+ controller.abort();
80
+ await starting;
81
+ await polling;
82
+ },
83
+ };
84
+ }
@@ -1,6 +1,6 @@
1
1
  import { startHttp, normalizeHttpPath, type RunningHttpServer } from '../http-server.js';
2
2
  import { HttpError } from '../http.js';
3
- import { createSearchServer } from '../server.js';
3
+ import { createManagedSearchServer } from '../server.js';
4
4
  import { executeSearch } from '../search.js';
5
5
  import type { BindingStore } from './bindings.js';
6
6
  import { createIdentity, httpsUrl, principalFrom, type IdentityOptions } from './identity.js';
@@ -43,7 +43,7 @@ export async function startMultiUserHttp(options: MultiUserOptions, store: Bindi
43
43
 
44
44
  return startHttp(context => {
45
45
  const user = principalFrom(context.authInfo);
46
- return createSearchServer(async (params, request) => {
46
+ return createManagedSearchServer(async (params, request) => {
47
47
  if (!user) throw new HttpError('MCP_AUTH_REQUIRED', 'Sign in to this MCP server.', 401);
48
48
  const now = Date.now();
49
49
  const rate = rates.get(user.subject) ?? { starts: [], active: 0 };
@@ -0,0 +1,113 @@
1
+ import { z } from 'zod';
2
+ import { HttpError } from './http.js';
3
+ import type { XSearchInput } from './types.js';
4
+
5
+ const queryLimit = 16_000;
6
+ const handleLimit = 10;
7
+ export const authModeSchema = z.enum(['auto', 'api_key', 'oauth']);
8
+
9
+ export const managedSearchInputSchema = z.strictObject({
10
+ query: z.string().describe('Search query, maximum 16000 characters after trimming'),
11
+ allowed_x_handles: z.array(z.string()).max(handleLimit).optional()
12
+ .describe('Only search these X handles, max 10. Mutually exclusive with excluded_x_handles.'),
13
+ excluded_x_handles: z.array(z.string()).max(handleLimit).optional()
14
+ .describe('Exclude these X handles, max 10. Mutually exclusive with allowed_x_handles.'),
15
+ from_date: z.string().optional().describe('Inclusive start date in YYYY-MM-DD, at most today UTC'),
16
+ to_date: z.string().optional().describe('Exclusive end date in YYYY-MM-DD, later than from_date'),
17
+ enable_image_understanding: z.boolean().optional().describe('Analyze images in matching posts'),
18
+ enable_video_understanding: z.boolean().optional().describe('Analyze videos in matching posts'),
19
+ });
20
+
21
+ export const personalSearchInputSchema = managedSearchInputSchema.extend({
22
+ auth_mode: authModeSchema.optional().describe('Override the configured credential selection mode'),
23
+ });
24
+
25
+ function invalidInput(message: string): HttpError {
26
+ return new HttpError('INVALID_ARGUMENT', `Validation error: ${message}`);
27
+ }
28
+
29
+ function isLeapYear(year: number): boolean {
30
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
31
+ }
32
+
33
+ /** Validate a real calendar date before comparing ISO date strings. */
34
+ export function validateCalendarDate(dateStr: string, fieldName: string): { year: number; month: number; day: number } {
35
+ if (typeof dateStr !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
36
+ throw invalidInput(`${fieldName} must be formatted as YYYY-MM-DD`);
37
+ }
38
+ const [year, month, day] = dateStr.split('-').map(Number);
39
+ if (month < 1 || month > 12) {
40
+ throw invalidInput(`${fieldName} has invalid month: ${month}`);
41
+ }
42
+ const daysInMonth = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
43
+ if (day < 1 || day > daysInMonth[month - 1]) {
44
+ throw invalidInput(`${fieldName} has invalid day ${day} for month ${month} of year ${year}`);
45
+ }
46
+ return { year, month, day };
47
+ }
48
+
49
+ /** Strip leading @ and validate the X handle length and character set. */
50
+ export function validateAndNormalizeHandles(handles: unknown[], fieldName: string): string[] {
51
+ if (!Array.isArray(handles)) {
52
+ throw invalidInput(`${fieldName} must be an array of strings`);
53
+ }
54
+ if (handles.length > handleLimit) {
55
+ throw invalidInput(`${fieldName} cannot exceed ${handleLimit} handles`);
56
+ }
57
+ return handles.map((handle, index) => {
58
+ if (typeof handle !== 'string') {
59
+ throw invalidInput(`${fieldName}[${index}] must be a string`);
60
+ }
61
+ const clean = handle.replace(/^@+/, '').trim();
62
+ if (!/^[A-Za-z0-9_]{1,15}$/.test(clean)) {
63
+ throw invalidInput(`${fieldName}[${index}] must be 1-15 characters matching [A-Za-z0-9_]`);
64
+ }
65
+ return clean;
66
+ });
67
+ }
68
+
69
+ /** Apply the same search rules before credentials are looked up or xAI is called. */
70
+ export function validateSearchParams(rawParams: unknown, { managed = false } = {}): XSearchInput {
71
+ const shape = managed ? managedSearchInputSchema : personalSearchInputSchema;
72
+ const parsed = shape.safeParse(rawParams);
73
+ if (!parsed.success) {
74
+ const detail = parsed.error.issues.map(issue =>
75
+ issue.path.length ? `${issue.path.join('.')}: ${issue.message}` : issue.message).join('; ');
76
+ throw invalidInput(detail);
77
+ }
78
+ const params: XSearchInput = parsed.data;
79
+ const query = params.query.trim();
80
+ if (!query) throw invalidInput('"query" cannot be empty');
81
+ if (query.length > queryLimit) {
82
+ throw invalidInput(`"query" exceeds maximum length of ${queryLimit} characters (got ${query.length})`);
83
+ }
84
+
85
+ const allowed = params.allowed_x_handles && validateAndNormalizeHandles(params.allowed_x_handles, 'allowed_x_handles');
86
+ const excluded = params.excluded_x_handles && validateAndNormalizeHandles(params.excluded_x_handles, 'excluded_x_handles');
87
+ if (allowed?.length && excluded?.length) {
88
+ throw invalidInput('allowed_x_handles and excluded_x_handles cannot both be non-empty');
89
+ }
90
+ const { from_date: from, to_date: to } = params;
91
+ if (from !== undefined) validateCalendarDate(from, 'from_date');
92
+ if (to !== undefined) validateCalendarDate(to, 'to_date');
93
+ if (from && to && from >= to) {
94
+ throw invalidInput(`from_date (${from}) must be strictly earlier than to_date (${to})`);
95
+ }
96
+ if (from) {
97
+ const todayUtc = new Date().toISOString().slice(0, 10);
98
+ if (from > todayUtc) {
99
+ throw invalidInput(`from_date (${from}) cannot be later than today UTC (${todayUtc})`);
100
+ }
101
+ }
102
+
103
+ return {
104
+ query,
105
+ allowed_x_handles: allowed,
106
+ excluded_x_handles: excluded,
107
+ from_date: from,
108
+ to_date: to,
109
+ enable_image_understanding: params.enable_image_understanding,
110
+ enable_video_understanding: params.enable_video_understanding,
111
+ auth_mode: params.auth_mode,
112
+ };
113
+ }