@scoheart/x-search-mcp 0.3.0 → 0.6.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 (105) hide show
  1. package/.env.example +7 -10
  2. package/README.md +29 -17
  3. package/THIRD_PARTY_NOTICES.md +4 -0
  4. package/TOOL.md +58 -77
  5. package/dist/evidence-licenses.txt +791 -0
  6. package/dist/evidence.html +170 -0
  7. package/dist/package.json +11 -3
  8. package/dist/src/auth.d.ts.map +1 -1
  9. package/dist/src/auth.js +67 -57
  10. package/dist/src/auth.js.map +1 -1
  11. package/dist/src/call-log.d.ts +5 -4
  12. package/dist/src/call-log.d.ts.map +1 -1
  13. package/dist/src/call-log.js +82 -54
  14. package/dist/src/call-log.js.map +1 -1
  15. package/dist/src/cli.d.ts.map +1 -1
  16. package/dist/src/cli.js +26 -19
  17. package/dist/src/cli.js.map +1 -1
  18. package/dist/src/config.d.ts.map +1 -1
  19. package/dist/src/config.js +12 -16
  20. package/dist/src/config.js.map +1 -1
  21. package/dist/src/device-login.d.ts +20 -0
  22. package/dist/src/device-login.d.ts.map +1 -0
  23. package/dist/src/device-login.js +110 -0
  24. package/dist/src/device-login.js.map +1 -0
  25. package/dist/src/events.d.ts +16 -0
  26. package/dist/src/events.d.ts.map +1 -0
  27. package/dist/src/events.js +128 -0
  28. package/dist/src/events.js.map +1 -0
  29. package/dist/src/evidence-app.d.ts +4 -0
  30. package/dist/src/evidence-app.d.ts.map +1 -0
  31. package/dist/src/evidence-app.js +17 -0
  32. package/dist/src/evidence-app.js.map +1 -0
  33. package/dist/src/http-server.d.ts +1 -0
  34. package/dist/src/http-server.d.ts.map +1 -1
  35. package/dist/src/http-server.js +6 -4
  36. package/dist/src/http-server.js.map +1 -1
  37. package/dist/src/http.d.ts +12 -15
  38. package/dist/src/http.d.ts.map +1 -1
  39. package/dist/src/http.js +78 -118
  40. package/dist/src/http.js.map +1 -1
  41. package/dist/src/index.d.ts +1 -0
  42. package/dist/src/index.d.ts.map +1 -1
  43. package/dist/src/index.js.map +1 -1
  44. package/dist/src/multi-user/service.d.ts.map +1 -1
  45. package/dist/src/multi-user/service.js +3 -2
  46. package/dist/src/multi-user/service.js.map +1 -1
  47. package/dist/src/search-input.d.ts +31 -0
  48. package/dist/src/search-input.d.ts.map +1 -0
  49. package/dist/src/search-input.js +102 -0
  50. package/dist/src/search-input.js.map +1 -0
  51. package/dist/src/search-response.d.ts +26 -0
  52. package/dist/src/search-response.d.ts.map +1 -0
  53. package/dist/src/search-response.js +128 -0
  54. package/dist/src/search-response.js.map +1 -0
  55. package/dist/src/search.d.ts +7 -20
  56. package/dist/src/search.d.ts.map +1 -1
  57. package/dist/src/search.js +129 -440
  58. package/dist/src/search.js.map +1 -1
  59. package/dist/src/server.d.ts +8 -9
  60. package/dist/src/server.d.ts.map +1 -1
  61. package/dist/src/server.js +110 -193
  62. package/dist/src/server.js.map +1 -1
  63. package/dist/src/tool-contract.d.ts +183 -0
  64. package/dist/src/tool-contract.d.ts.map +1 -0
  65. package/dist/src/tool-contract.js +88 -0
  66. package/dist/src/tool-contract.js.map +1 -0
  67. package/dist/src/types.d.ts +7 -37
  68. package/dist/src/types.d.ts.map +1 -1
  69. package/dist/src/watch-cli.d.ts +2 -0
  70. package/dist/src/watch-cli.d.ts.map +1 -0
  71. package/dist/src/watch-cli.js +41 -0
  72. package/dist/src/watch-cli.js.map +1 -0
  73. package/dist/src/watch-store.d.ts +41 -0
  74. package/dist/src/watch-store.d.ts.map +1 -0
  75. package/dist/src/watch-store.js +171 -0
  76. package/dist/src/watch-store.js.map +1 -0
  77. package/dist/ui/evidence.d.ts +2 -0
  78. package/dist/ui/evidence.d.ts.map +1 -0
  79. package/dist/ui/evidence.js +150 -0
  80. package/dist/ui/evidence.js.map +1 -0
  81. package/docs/events-and-apps.md +40 -0
  82. package/examples/codex.toml +6 -7
  83. package/examples/mcp.json +2 -6
  84. package/package.json +11 -3
  85. package/server.json +34 -0
  86. package/src/auth.ts +65 -57
  87. package/src/call-log.ts +83 -53
  88. package/src/cli.ts +26 -19
  89. package/src/config.ts +11 -13
  90. package/src/device-login.ts +120 -0
  91. package/src/events.ts +124 -0
  92. package/src/evidence-app.ts +19 -0
  93. package/src/http-server.ts +7 -4
  94. package/src/http.ts +83 -162
  95. package/src/index.ts +1 -0
  96. package/src/multi-user/service.ts +3 -2
  97. package/src/search-input.ts +109 -0
  98. package/src/search-response.ts +122 -0
  99. package/src/search.ts +131 -476
  100. package/src/server.ts +114 -207
  101. package/src/tool-contract.ts +96 -0
  102. package/src/types.ts +8 -40
  103. package/src/watch-cli.ts +35 -0
  104. package/src/watch-store.ts +182 -0
  105. package/tsconfig.json +2 -1
package/src/http.ts CHANGED
@@ -1,197 +1,118 @@
1
- import { request, EnvHttpProxyAgent } from 'undici';
1
+ import { request, EnvHttpProxyAgent, type Dispatcher } from 'undici';
2
2
  import { version } from './version.js';
3
3
 
4
- // Global HTTP proxy agent reading standard environment variables: HTTP_PROXY, HTTPS_PROXY, NO_PROXY
5
4
  const proxyAgent = new EnvHttpProxyAgent();
5
+ const maxAuthResponseBytes = 64 * 1024;
6
6
 
7
7
  export class HttpError extends Error {
8
- code: string;
9
- status: number | null;
10
- data?: any;
11
-
12
- constructor(code: string, message: string, status: number | null = null, data?: any) {
8
+ constructor(
9
+ readonly code: string,
10
+ message: string,
11
+ readonly status: number | null = null,
12
+ readonly data?: any,
13
+ readonly retryAfterMs?: number,
14
+ ) {
13
15
  super(message);
14
16
  this.name = 'HttpError';
15
- this.code = code;
16
- this.status = status;
17
- this.data = data;
18
17
  }
19
18
  }
20
19
 
21
- /**
22
- * Maps HTTP status code to sanitized local error.
23
- * Prevents leaking any credentials that might be echoed in raw upstream response bodies.
24
- */
25
- export function createSanitizedHttpError(status: number, data?: any): HttpError {
26
- if (status === 401) {
27
- return new HttpError('UPSTREAM_AUTH_ERROR', 'Authentication failed with upstream xAI API (HTTP 401)', 401, data);
28
- }
29
- if (status === 403) {
30
- return new HttpError(
31
- 'UPSTREAM_FORBIDDEN',
32
- 'Access forbidden (HTTP 403). The account may lack required API balance or X Search subscription entitlements.',
33
- 403,
34
- data
35
- );
36
- }
37
- if (status === 404) {
38
- return new HttpError('UPSTREAM_NOT_FOUND', 'Requested resource not found on upstream xAI API (HTTP 404)', 404, data);
39
- }
40
- if (status === 429) {
41
- return new HttpError('UPSTREAM_RATE_LIMITED', 'Upstream xAI rate limit exceeded (HTTP 429)', 429, data);
42
- }
43
- if (status >= 500 && status < 600) {
44
- return new HttpError(
45
- 'UPSTREAM_SERVER_ERROR',
46
- `Upstream xAI service encountered a server error (HTTP ${status})`,
47
- status,
48
- data
49
- );
50
- }
51
- return new HttpError('UPSTREAM_HTTP_ERROR', `Upstream xAI returned HTTP error ${status}`, status, data);
20
+ export function abortError(signal: AbortSignal): HttpError {
21
+ return signal.reason instanceof HttpError
22
+ ? signal.reason
23
+ : new HttpError('CANCELLED', 'The request was cancelled.');
52
24
  }
53
25
 
54
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
55
- return new Promise((resolve, reject) => {
56
- if (signal?.aborted) {
57
- return reject(new HttpError('cancelled', 'Request was cancelled by client'));
58
- }
59
- const timer = setTimeout(() => {
60
- signal?.removeEventListener('abort', onAbort);
61
- resolve();
62
- }, ms);
63
-
64
- function onAbort() {
65
- clearTimeout(timer);
66
- reject(new HttpError('cancelled', 'Request was cancelled by client'));
67
- }
26
+ function parseRetryAfter(value: string | string[] | undefined): number | undefined {
27
+ if (typeof value !== 'string') return undefined;
28
+ const header = value.trim();
29
+ if (/^\d+$/.test(header)) {
30
+ const ms = Number(header) * 1000;
31
+ return Number.isSafeInteger(ms) ? ms : undefined;
32
+ }
33
+ const date = /^[A-Za-z]{3}, /.test(header) ? Date.parse(header) : NaN;
34
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
35
+ }
68
36
 
69
- signal?.addEventListener('abort', onAbort, { once: true });
70
- });
37
+ function httpStatusError(status: number, data: unknown, retryAfterMs?: number): HttpError {
38
+ switch (status) {
39
+ case 401: return new HttpError('UPSTREAM_AUTH_ERROR', 'xAI rejected the credential (HTTP 401).', status, data);
40
+ case 403: return new HttpError('UPSTREAM_FORBIDDEN', 'xAI denied access. Check API balance or X Search subscription entitlement.', status, data);
41
+ case 429: return new HttpError('UPSTREAM_RATE_LIMITED', 'xAI rate-limited this request.', status, data, retryAfterMs);
42
+ default:
43
+ return new HttpError(status >= 500 ? 'UPSTREAM_SERVER_ERROR' : 'UPSTREAM_HTTP_ERROR',
44
+ `xAI returned HTTP ${status}.`, status, data);
45
+ }
71
46
  }
72
47
 
73
48
  export interface SendHttpOptions {
74
49
  url: string;
75
- method?: string;
50
+ method?: Dispatcher.HttpMethod;
76
51
  headers?: Record<string, string>;
77
52
  body?: string | Buffer | null;
78
53
  signal?: AbortSignal;
79
- timeoutSeconds?: number;
80
- retries?: number;
81
- isRefresh?: boolean;
54
+ timeoutMs?: number;
55
+ maxResponseBytes?: number;
82
56
  }
83
57
 
84
58
  export interface SendHttpResponse {
85
59
  status: number;
86
- headers: Record<string, any>;
87
60
  data: any;
88
61
  }
89
62
 
90
- export async function sendHttpRequest({
91
- url,
92
- method = 'GET',
93
- headers = {},
94
- body = null,
95
- signal,
96
- timeoutSeconds = 180,
97
- retries = 2,
98
- isRefresh = false,
99
- }: SendHttpOptions): Promise<SendHttpResponse> {
100
- const maxRetries = isRefresh ? 0 : retries;
101
- let attempt = 0;
102
-
103
- while (true) {
104
- if (signal?.aborted) {
105
- throw new HttpError('cancelled', 'Request was cancelled by client');
63
+ async function readBody(response: Dispatcher.ResponseData, limit: number): Promise<string> {
64
+ const chunks: Buffer[] = [];
65
+ let bytes = 0;
66
+ try {
67
+ const contentLength = response.headers['content-length'];
68
+ if (Number(contentLength) > limit) {
69
+ throw new HttpError('UPSTREAM_RESPONSE_TOO_LARGE', 'xAI response exceeded the byte limit.', response.statusCode);
106
70
  }
107
-
108
- const timeoutController = new AbortController();
109
- const timeoutId = setTimeout(() => {
110
- timeoutController.abort(new Error('TIMEOUT'));
111
- }, timeoutSeconds * 1000);
112
-
113
- const abortHandler = () => {
114
- timeoutController.abort(new Error('CANCELLED'));
115
- };
116
- signal?.addEventListener('abort', abortHandler, { once: true });
117
-
118
- let response: any;
119
- let responseText = '';
120
- let timedOut = false;
121
- let cancelled = false;
122
-
123
- try {
124
- response = await request(url, {
125
- method: method as any,
126
- headers: {
127
- 'User-Agent': `x-search-mcp/${version}`,
128
- ...headers,
129
- },
130
- body: body as any,
131
- dispatcher: proxyAgent,
132
- signal: timeoutController.signal,
133
- });
134
- // Keep the deadline and client cancellation attached through body consumption.
135
- responseText = await response.body.text();
136
- } catch (err: any) {
137
- if (signal?.aborted || err?.message === 'CANCELLED') {
138
- cancelled = true;
139
- } else if (timeoutController.signal.aborted || err?.name === 'AbortError' || err?.message === 'TIMEOUT') {
140
- timedOut = true;
71
+ for await (const chunk of response.body) {
72
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
73
+ bytes += buffer.length;
74
+ if (bytes > limit) {
75
+ throw new HttpError('UPSTREAM_RESPONSE_TOO_LARGE', 'xAI response exceeded the byte limit.', response.statusCode);
141
76
  }
142
-
143
- clearTimeout(timeoutId);
144
- signal?.removeEventListener('abort', abortHandler);
145
-
146
- if (cancelled) {
147
- throw new HttpError('cancelled', 'Request was cancelled by client');
148
- }
149
-
150
- const isNetworkOrTimeout = timedOut || !err.status;
151
- if (isNetworkOrTimeout && attempt < maxRetries) {
152
- attempt++;
153
- const backoffMs = Math.min(1500 * attempt, 5000);
154
- await sleep(backoffMs, signal);
155
- continue;
156
- }
157
-
158
- if (timedOut) {
159
- throw new HttpError('TIMEOUT', `Request timed out after ${timeoutSeconds} seconds`);
160
- }
161
- throw new HttpError('NETWORK_ERROR', `Network connection error: ${err.message}`);
162
- } finally {
163
- clearTimeout(timeoutId);
164
- signal?.removeEventListener('abort', abortHandler);
165
- }
166
-
167
- const status = response.statusCode;
168
-
169
- // Retry on 5xx errors if remaining retries
170
- if (status >= 500 && status < 600 && attempt < maxRetries) {
171
- attempt++;
172
- const backoffMs = Math.min(1500 * attempt, 5000);
173
- await sleep(backoffMs, signal);
174
- continue;
77
+ chunks.push(buffer);
175
78
  }
79
+ return Buffer.concat(chunks, bytes).toString('utf8');
80
+ } finally {
81
+ response.body.destroy();
82
+ }
83
+ }
176
84
 
177
- let parsedData: any = null;
178
- const contentType = response.headers['content-type'] || '';
179
- if (typeof contentType === 'string' && (contentType.includes('application/json') || responseText.trim().startsWith('{'))) {
180
- try {
181
- parsedData = JSON.parse(responseText);
182
- } catch {
183
- // Fallback to text
184
- }
85
+ /** Send a single HTTP request, consuming at most the configured number of bytes. */
86
+ export async function sendHttpRequest({
87
+ url, method = 'GET', headers = {}, body = null, signal, timeoutMs, maxResponseBytes = maxAuthResponseBytes,
88
+ }: SendHttpOptions): Promise<SendHttpResponse> {
89
+ const timeout = timeoutMs === undefined ? undefined : new AbortController();
90
+ const timer = timeout && setTimeout(
91
+ () => timeout.abort(new HttpError('TIMEOUT', 'The xAI HTTP exchange timed out.')), timeoutMs,
92
+ );
93
+ const requestSignal = signal && timeout ? AbortSignal.any([signal, timeout.signal]) : signal ?? timeout?.signal;
94
+ try {
95
+ if (requestSignal?.aborted) throw abortError(requestSignal);
96
+ const response = await request(url, {
97
+ method, headers: { 'User-Agent': `x-search-mcp/${version}`, ...headers }, body,
98
+ dispatcher: proxyAgent, signal: requestSignal,
99
+ });
100
+ const text = await readBody(response, maxResponseBytes);
101
+ const contentType = response.headers['content-type'];
102
+ let data: unknown = text;
103
+ if (String(contentType ?? '').includes('application/json') || text.trimStart().startsWith('{')) {
104
+ try { data = JSON.parse(text); } catch { /* Keep the bounded body for opt-in diagnostics. */ }
185
105
  }
186
-
187
- if (status >= 400) {
188
- throw createSanitizedHttpError(status, parsedData ?? responseText);
106
+ const status = response.statusCode;
107
+ if (status < 200 || status >= 300) {
108
+ throw httpStatusError(status, data, parseRetryAfter(response.headers['retry-after']));
189
109
  }
190
-
191
- return {
192
- status,
193
- headers: response.headers,
194
- data: parsedData ?? responseText,
195
- };
110
+ return { status, data };
111
+ } catch (error) {
112
+ if (requestSignal?.aborted) throw abortError(requestSignal);
113
+ if (error instanceof HttpError) throw error;
114
+ throw new HttpError('NETWORK_ERROR', 'The connection to xAI ended before a complete response was received.');
115
+ } finally {
116
+ clearTimeout(timer);
196
117
  }
197
118
  }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
+ export type { SearchSource, XSearchResult } from './tool-contract.js';
2
3
  export * from './config.js';
3
4
  export * from './http.js';
4
5
  export * from './auth.js';
@@ -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, trackCleanup) => {
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 };
@@ -57,6 +57,7 @@ export async function startMultiUserHttp(options: MultiUserOptions, store: Bindi
57
57
  try {
58
58
  return await executeSearch(params, {
59
59
  signal: request.mcpReq.signal,
60
+ trackCleanup,
60
61
  resolveApiKey: async () => {
61
62
  let key: string | null;
62
63
  try { key = await store.get(user); }
@@ -0,0 +1,109 @@
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 searchInputSchema = 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
+ detail: z.enum(['concise', 'detailed']).optional().describe('Concise by default. Use detailed for a longer answer and more evidence.'),
20
+ });
21
+
22
+ function invalidInput(message: string): HttpError {
23
+ return new HttpError('INVALID_ARGUMENT', `Validation error: ${message}`);
24
+ }
25
+
26
+ function isLeapYear(year: number): boolean {
27
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
28
+ }
29
+
30
+ /** Validate a real calendar date before comparing ISO date strings. */
31
+ export function validateCalendarDate(dateStr: string, fieldName: string): { year: number; month: number; day: number } {
32
+ if (typeof dateStr !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
33
+ throw invalidInput(`${fieldName} must be formatted as YYYY-MM-DD`);
34
+ }
35
+ const [year, month, day] = dateStr.split('-').map(Number);
36
+ if (month < 1 || month > 12) {
37
+ throw invalidInput(`${fieldName} has invalid month: ${month}`);
38
+ }
39
+ const daysInMonth = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
40
+ if (day < 1 || day > daysInMonth[month - 1]) {
41
+ throw invalidInput(`${fieldName} has invalid day ${day} for month ${month} of year ${year}`);
42
+ }
43
+ return { year, month, day };
44
+ }
45
+
46
+ /** Strip leading @ and validate the X handle length and character set. */
47
+ export function validateAndNormalizeHandles(handles: unknown[], fieldName: string): string[] {
48
+ if (!Array.isArray(handles)) {
49
+ throw invalidInput(`${fieldName} must be an array of strings`);
50
+ }
51
+ if (handles.length > handleLimit) {
52
+ throw invalidInput(`${fieldName} cannot exceed ${handleLimit} handles`);
53
+ }
54
+ return handles.map((handle, index) => {
55
+ if (typeof handle !== 'string') {
56
+ throw invalidInput(`${fieldName}[${index}] must be a string`);
57
+ }
58
+ const clean = handle.replace(/^@+/, '').trim();
59
+ if (!/^[A-Za-z0-9_]{1,15}$/.test(clean)) {
60
+ throw invalidInput(`${fieldName}[${index}] must be 1-15 characters matching [A-Za-z0-9_]`);
61
+ }
62
+ return clean;
63
+ });
64
+ }
65
+
66
+ /** Apply the same search rules before credentials are looked up or xAI is called. */
67
+ export function validateSearchParams(rawParams: unknown): XSearchInput {
68
+ const parsed = searchInputSchema.safeParse(rawParams);
69
+ if (!parsed.success) {
70
+ const detail = parsed.error.issues.map(issue =>
71
+ issue.path.length ? `${issue.path.join('.')}: ${issue.message}` : issue.message).join('; ');
72
+ throw invalidInput(detail);
73
+ }
74
+ const params: XSearchInput = parsed.data;
75
+ const query = params.query.trim();
76
+ if (!query) throw invalidInput('"query" cannot be empty');
77
+ if (query.length > queryLimit) {
78
+ throw invalidInput(`"query" exceeds maximum length of ${queryLimit} characters (got ${query.length})`);
79
+ }
80
+
81
+ const allowed = params.allowed_x_handles && validateAndNormalizeHandles(params.allowed_x_handles, 'allowed_x_handles');
82
+ const excluded = params.excluded_x_handles && validateAndNormalizeHandles(params.excluded_x_handles, 'excluded_x_handles');
83
+ if (allowed?.length && excluded?.length) {
84
+ throw invalidInput('allowed_x_handles and excluded_x_handles cannot both be non-empty');
85
+ }
86
+ const { from_date: from, to_date: to } = params;
87
+ if (from !== undefined) validateCalendarDate(from, 'from_date');
88
+ if (to !== undefined) validateCalendarDate(to, 'to_date');
89
+ if (from && to && from >= to) {
90
+ throw invalidInput(`from_date (${from}) must be strictly earlier than to_date (${to})`);
91
+ }
92
+ if (from) {
93
+ const todayUtc = new Date().toISOString().slice(0, 10);
94
+ if (from > todayUtc) {
95
+ throw invalidInput(`from_date (${from}) cannot be later than today UTC (${todayUtc})`);
96
+ }
97
+ }
98
+
99
+ return {
100
+ query,
101
+ allowed_x_handles: allowed,
102
+ excluded_x_handles: excluded,
103
+ from_date: from,
104
+ to_date: to,
105
+ enable_image_understanding: params.enable_image_understanding,
106
+ enable_video_understanding: params.enable_video_understanding,
107
+ detail: params.detail ?? 'concise',
108
+ };
109
+ }
@@ -0,0 +1,122 @@
1
+ import type { SearchSource, XSearchResult } from './tool-contract.js';
2
+ import type { SearchDetail } from './types.js';
3
+
4
+ const xSearchTools = new Set(['x_search', 'x_keyword_search', 'x_semantic_search', 'x_user_search', 'x_thread_fetch']);
5
+ const xHosts = new Set(['x.com', 'www.x.com', 'mobile.x.com', 'twitter.com', 'www.twitter.com', 'mobile.twitter.com']);
6
+ const limits = {
7
+ concise: { answerBytes: 3000, sources: 8 },
8
+ detailed: { answerBytes: 16000, sources: 24 },
9
+ };
10
+
11
+ function record(value: unknown): Record<string, unknown> | undefined {
12
+ return value && typeof value === 'object' && !Array.isArray(value)
13
+ ? value as Record<string, unknown> : undefined;
14
+ }
15
+
16
+ function text(value: unknown): string {
17
+ return typeof value === 'string' ? value.trim() : '';
18
+ }
19
+
20
+ function count(value: unknown): number | null {
21
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
22
+ }
23
+
24
+ function normalizeSource(value: unknown): SearchSource | undefined {
25
+ const candidate = text(value);
26
+ if (candidate.length > 1024 || !/^https?:\/\//i.test(candidate) || /[\x00-\x1f\x7f]/.test(candidate)) return;
27
+ let url: URL;
28
+ try { url = new URL(candidate); } catch { return; }
29
+ if (url.username || url.password) return;
30
+ if (!url.port && xHosts.has(url.hostname)) {
31
+ const match = /^\/([A-Za-z0-9_]{1,15})\/status\/(\d{1,20})(?:\/(?:photo|video)\/\d+)?\/?$/.exec(url.pathname);
32
+ const id = match?.[2] ?? /^\/i\/web\/status\/(\d{1,20})\/?$/.exec(url.pathname)?.[1];
33
+ if (id) {
34
+ const handle = match?.[1].toLowerCase() === 'i' ? undefined : match?.[1];
35
+ return { kind: 'x_post', url: `https://x.com/${handle ?? 'i'}/status/${id}`, post_id: id, ...(handle ? { handle } : {}) };
36
+ }
37
+ }
38
+ url.hash = '';
39
+ if (url.href.length <= 1024) return { kind: 'web', url: url.href };
40
+ }
41
+
42
+ function boundedAnswer(answer: string, limit: number): string {
43
+ const bytes = Buffer.from(answer);
44
+ if (bytes.length <= limit) return answer;
45
+ let end = limit;
46
+ while ((bytes[end] & 0xc0) === 0x80) end--;
47
+ return bytes.subarray(0, end).toString('utf8').trimEnd();
48
+ }
49
+
50
+ /** Project upstream data into bounded answer, checked source links and usage counts. */
51
+ export function normalizeSearchResponse(raw: Record<string, unknown>, detail: SearchDetail) {
52
+ const canonicalAnswer = text(raw.output_text);
53
+ const parts: string[] = [];
54
+ const sources = new Map<string, SearchSource>();
55
+ const calls = new Set<string>();
56
+ let callsWithoutId = 0;
57
+
58
+ function addSource(value: unknown, cited = false): void {
59
+ const source = normalizeSource(value);
60
+ if (!source) return;
61
+ const key = source.kind === 'x_post' ? `post:${source.post_id}` : source.url;
62
+ const existing = sources.get(key);
63
+ const preferred = existing?.kind === 'x_post' && existing.handle ? existing : source;
64
+ sources.set(key, { ...preferred, ...(existing?.cited_in_answer || cited ? { cited_in_answer: true as const } : {}) });
65
+ }
66
+
67
+ for (const list of [raw.citations, raw.sources]) {
68
+ if (!Array.isArray(list)) continue;
69
+ for (const entry of list) addSource(record(entry)?.url ?? entry);
70
+ }
71
+
72
+ for (const entry of Array.isArray(raw.output) ? raw.output : []) {
73
+ const item = record(entry);
74
+ if (!item) continue;
75
+ const name = text(item.name) || text(item.tool_name);
76
+ const id = text(item.call_id) || text(item.id);
77
+ if (xSearchTools.has(name) || id.startsWith('xs_')) {
78
+ if (id) calls.add(id);
79
+ else callsWithoutId++;
80
+ }
81
+ if (item.type !== 'message' || item.role !== 'assistant' || !Array.isArray(item.content)) continue;
82
+ for (const entry of item.content) {
83
+ const block = record(entry);
84
+ if (block?.type !== 'output_text' || typeof block.text !== 'string') continue;
85
+ if (block.text.trim()) parts.push(block.text.trim());
86
+ if (!Array.isArray(block.annotations)) continue;
87
+ for (const value of block.annotations) {
88
+ const annotation = record(value);
89
+ if (annotation?.type !== 'url_citation') continue;
90
+ const start = count(annotation.start_index);
91
+ const end = count(annotation.end_index);
92
+ addSource(annotation.url ?? record(annotation.citation)?.url,
93
+ start !== null && end !== null && start < end && end <= block.text.length);
94
+ }
95
+ }
96
+ }
97
+
98
+ const fullAnswer = canonicalAnswer || parts.join('\n\n');
99
+ const limit = limits[detail];
100
+ const answer = boundedAnswer(fullAnswer, limit.answerBytes);
101
+ const ranked = [...sources.values()].sort((a, b) =>
102
+ Number(b.kind === 'x_post') - Number(a.kind === 'x_post')
103
+ || Number(Boolean(b.cited_in_answer)) - Number(Boolean(a.cited_in_answer)));
104
+ const usage = record(raw.usage);
105
+ const tools = record(usage?.server_side_tool_usage_details);
106
+ const status: XSearchResult['status'] = raw.status === 'incomplete' ? 'partial'
107
+ : ranked.some(source => source.kind === 'x_post') ? 'complete' : 'unverified';
108
+
109
+ return {
110
+ status,
111
+ answer,
112
+ sources: ranked.slice(0, limit.sources),
113
+ truncated: answer !== fullAnswer || ranked.length > limit.sources,
114
+ usage: {
115
+ x_search_calls: (calls.size + callsWithoutId) || null,
116
+ x_posts_fetched: count(tools?.x_posts_fetched),
117
+ x_users_fetched: count(tools?.x_users_fetched),
118
+ input_tokens: count(usage?.input_tokens),
119
+ output_tokens: count(usage?.output_tokens),
120
+ },
121
+ };
122
+ }