@scoheart/x-search-mcp 0.2.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 (105) hide show
  1. package/README.md +59 -75
  2. package/TOOL.md +28 -17
  3. package/dist/package.json +8 -1
  4. package/dist/src/auth.d.ts +14 -5
  5. package/dist/src/auth.d.ts.map +1 -1
  6. package/dist/src/auth.js +180 -118
  7. package/dist/src/auth.js.map +1 -1
  8. package/dist/src/call-log.d.ts.map +1 -1
  9. package/dist/src/call-log.js +52 -33
  10. package/dist/src/call-log.js.map +1 -1
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +9 -4
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/config.d.ts +3 -1
  15. package/dist/src/config.d.ts.map +1 -1
  16. package/dist/src/config.js +4 -4
  17. package/dist/src/config.js.map +1 -1
  18. package/dist/src/device-login.d.ts +46 -0
  19. package/dist/src/device-login.d.ts.map +1 -0
  20. package/dist/src/device-login.js +72 -0
  21. package/dist/src/device-login.js.map +1 -0
  22. package/dist/src/http-config.d.ts +9 -0
  23. package/dist/src/http-config.d.ts.map +1 -1
  24. package/dist/src/http-config.js +10 -5
  25. package/dist/src/http-config.js.map +1 -1
  26. package/dist/src/http-server.d.ts +10 -2
  27. package/dist/src/http-server.d.ts.map +1 -1
  28. package/dist/src/http-server.js +46 -15
  29. package/dist/src/http-server.js.map +1 -1
  30. package/dist/src/index.d.ts +3 -0
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +3 -0
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/multi-user/bindings.d.ts +21 -0
  35. package/dist/src/multi-user/bindings.d.ts.map +1 -0
  36. package/dist/src/multi-user/bindings.js +129 -0
  37. package/dist/src/multi-user/bindings.js.map +1 -0
  38. package/dist/src/multi-user/cli.d.ts +23 -0
  39. package/dist/src/multi-user/cli.d.ts.map +1 -0
  40. package/dist/src/multi-user/cli.js +82 -0
  41. package/dist/src/multi-user/cli.js.map +1 -0
  42. package/dist/src/multi-user/identity.d.ts +17 -0
  43. package/dist/src/multi-user/identity.d.ts.map +1 -0
  44. package/dist/src/multi-user/identity.js +78 -0
  45. package/dist/src/multi-user/identity.js.map +1 -0
  46. package/dist/src/multi-user/keys.d.ts +17 -0
  47. package/dist/src/multi-user/keys.d.ts.map +1 -0
  48. package/dist/src/multi-user/keys.js +54 -0
  49. package/dist/src/multi-user/keys.js.map +1 -0
  50. package/dist/src/multi-user/kms.d.ts +10 -0
  51. package/dist/src/multi-user/kms.d.ts.map +1 -0
  52. package/dist/src/multi-user/kms.js +83 -0
  53. package/dist/src/multi-user/kms.js.map +1 -0
  54. package/dist/src/multi-user/service.d.ts +13 -0
  55. package/dist/src/multi-user/service.d.ts.map +1 -0
  56. package/dist/src/multi-user/service.js +92 -0
  57. package/dist/src/multi-user/service.js.map +1 -0
  58. package/dist/src/multi-user/settings.d.ts +9 -0
  59. package/dist/src/multi-user/settings.d.ts.map +1 -0
  60. package/dist/src/multi-user/settings.js +323 -0
  61. package/dist/src/multi-user/settings.js.map +1 -0
  62. package/dist/src/search-input.d.ts +43 -0
  63. package/dist/src/search-input.d.ts.map +1 -0
  64. package/dist/src/search-input.js +105 -0
  65. package/dist/src/search-input.js.map +1 -0
  66. package/dist/src/search-response.d.ts +6 -0
  67. package/dist/src/search-response.d.ts.map +1 -0
  68. package/dist/src/search-response.js +125 -0
  69. package/dist/src/search-response.js.map +1 -0
  70. package/dist/src/search.d.ts +5 -20
  71. package/dist/src/search.d.ts.map +1 -1
  72. package/dist/src/search.js +67 -332
  73. package/dist/src/search.js.map +1 -1
  74. package/dist/src/server.d.ts +9 -1
  75. package/dist/src/server.d.ts.map +1 -1
  76. package/dist/src/server.js +88 -81
  77. package/dist/src/server.js.map +1 -1
  78. package/dist/src/tool-contract.d.ts +150 -0
  79. package/dist/src/tool-contract.d.ts.map +1 -0
  80. package/dist/src/tool-contract.js +83 -0
  81. package/dist/src/tool-contract.js.map +1 -0
  82. package/docs/multi-user.md +108 -0
  83. package/examples/codex.toml +1 -1
  84. package/examples/mcp.json +1 -1
  85. package/package.json +8 -1
  86. package/src/auth.ts +178 -125
  87. package/src/call-log.ts +52 -31
  88. package/src/cli.ts +9 -4
  89. package/src/config.ts +4 -4
  90. package/src/device-login.ts +84 -0
  91. package/src/http-config.ts +11 -5
  92. package/src/http-server.ts +55 -18
  93. package/src/index.ts +3 -0
  94. package/src/multi-user/bindings.ts +135 -0
  95. package/src/multi-user/cli.ts +78 -0
  96. package/src/multi-user/identity.ts +83 -0
  97. package/src/multi-user/keys.ts +66 -0
  98. package/src/multi-user/kms.ts +87 -0
  99. package/src/multi-user/service.ts +92 -0
  100. package/src/multi-user/settings.ts +329 -0
  101. package/src/search-input.ts +113 -0
  102. package/src/search-response.ts +127 -0
  103. package/src/search.ts +130 -426
  104. package/src/server.ts +97 -82
  105. package/src/tool-contract.ts +90 -0
@@ -0,0 +1,125 @@
1
+ const xSearchToolNames = new Set([
2
+ 'x_search',
3
+ 'x_keyword_search',
4
+ 'x_semantic_search',
5
+ 'x_user_search',
6
+ 'x_thread_fetch',
7
+ ]);
8
+ function record(value) {
9
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
10
+ ? value : undefined;
11
+ }
12
+ function text(value) {
13
+ return typeof value === 'string' ? value.trim() : '';
14
+ }
15
+ function citationUrl(value) {
16
+ const candidate = text(value);
17
+ if (!/^https?:\/\//i.test(candidate) || /[\x00-\x1f\x7f]/.test(candidate))
18
+ return undefined;
19
+ try {
20
+ const url = new URL(candidate);
21
+ return url.username || url.password ? undefined : candidate;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ function citationOffset(value) {
28
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
29
+ }
30
+ function inlineCitation(value) {
31
+ const annotation = record(value);
32
+ if (!annotation || (annotation.type !== 'url_citation' && !annotation.url))
33
+ return undefined;
34
+ const nested = record(annotation.citation);
35
+ const url = citationUrl(annotation.url) ?? citationUrl(nested?.url);
36
+ if (!url)
37
+ return undefined;
38
+ return {
39
+ url,
40
+ title: text(annotation.title) || text(nested?.title) || null,
41
+ start_index: citationOffset(annotation.start_index),
42
+ end_index: citationOffset(annotation.end_index),
43
+ };
44
+ }
45
+ function hasXSearchUsage(usage) {
46
+ const details = record(record(usage)?.server_side_tool_usage_details);
47
+ return [details?.x_posts_fetched, details?.x_users_fetched].some(count => typeof count === 'number' && Number.isSafeInteger(count) && count > 0);
48
+ }
49
+ /** Normalize xAI's visible answer, citations and evidence independently of transport and credentials. */
50
+ export function normalizeSearchResponse(raw) {
51
+ const canonicalAnswer = text(raw.output_text);
52
+ const answerPieces = [];
53
+ const citations = new Set();
54
+ const inlineCitations = [];
55
+ const serverSideCalls = [];
56
+ let xSearchObserved = hasXSearchUsage(raw.usage);
57
+ for (const sources of [raw.citations, raw.sources]) {
58
+ if (!Array.isArray(sources))
59
+ continue;
60
+ for (const source of sources) {
61
+ const url = citationUrl(source);
62
+ if (url)
63
+ citations.add(url);
64
+ }
65
+ }
66
+ for (const value of Array.isArray(raw.output) ? raw.output : []) {
67
+ const item = record(value);
68
+ if (!item)
69
+ continue;
70
+ const name = text(item.name) || text(item.tool_name);
71
+ const callId = text(item.call_id) || text(item.id);
72
+ const isXSearch = xSearchToolNames.has(name) || callId.startsWith('xs_');
73
+ if (isXSearch)
74
+ xSearchObserved = true;
75
+ if ((isXSearch || item.type === 'custom_tool_call') && (name || callId)) {
76
+ serverSideCalls.push({
77
+ call_id: callId || null,
78
+ name: name || null,
79
+ arguments: item.arguments ?? item.input ?? null,
80
+ });
81
+ }
82
+ if (item.type !== 'message' && item.type !== undefined)
83
+ continue;
84
+ const message = record(item.message) ?? item;
85
+ const role = message.role ?? item.role;
86
+ if (role !== undefined && role !== 'assistant')
87
+ continue;
88
+ if (typeof message.content === 'string') {
89
+ const piece = text(message.content);
90
+ if (piece && !canonicalAnswer)
91
+ answerPieces.push(piece);
92
+ continue;
93
+ }
94
+ if (!Array.isArray(message.content))
95
+ continue;
96
+ for (const blockValue of message.content) {
97
+ const block = record(blockValue);
98
+ if (!block || (block.type !== undefined && block.type !== 'output_text' && block.type !== 'text'))
99
+ continue;
100
+ const piece = text(block.output_text) || text(block.text);
101
+ if (piece && !canonicalAnswer)
102
+ answerPieces.push(piece);
103
+ if (!Array.isArray(block.annotations))
104
+ continue;
105
+ for (const annotation of block.annotations) {
106
+ const citation = inlineCitation(annotation);
107
+ if (citation) {
108
+ inlineCitations.push(citation);
109
+ citations.add(citation.url);
110
+ }
111
+ }
112
+ }
113
+ }
114
+ return {
115
+ answer: canonicalAnswer || answerPieces.join('\n\n'),
116
+ citations: [...citations],
117
+ inline_citations: inlineCitations,
118
+ search_execution: xSearchObserved ? 'observed' : 'unreported',
119
+ server_side_calls: serverSideCalls,
120
+ response_status: text(raw.status) || 'completed',
121
+ incomplete_details: raw.incomplete_details ?? null,
122
+ usage: raw.usage ?? null,
123
+ };
124
+ }
125
+ //# sourceMappingURL=search-response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-response.js","sourceRoot":"","sources":["../../src/search-response.ts"],"names":[],"mappings":"AAEA,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,UAAU;IACV,kBAAkB;IAClB,mBAAmB;IACnB,eAAe;IACf,gBAAgB;CACjB,CAAC,CAAC;AAKH,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACzE,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,SAAS,CAAC;AACnD,CAAC;AAED,SAAS,IAAI,CAAC,KAAc;IAC1B,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACvD,CAAC;A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EAAE,CAAC,GAAG,SAAS,CAAC;QACzB,gBAAgB,EAAE,eAAe;QACjC,gBAAgB,EAAE,eAAe,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,YAAY;QAC7D,iBAAiB,EAAE,eAAe;QAClC,eAAe,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,WAAW;QAChD,kBAAkB,EAAE,GAAG,CAAC,kBAAkB,IAAI,IAAI;QAClD,KAAK,EAAE,GAAG,CAAC,KAAK,IAAI,IAAI;KACzB,CAAC;AACJ,CAAC"}
@@ -1,24 +1,9 @@
1
- import type { XSearchInput, XSearchResult } from './types.js';
2
- /**
3
- * Validate a real calendar date string formatted as YYYY-MM-DD.
4
- * Prevents JavaScript auto-rollover bugs (e.g. Feb 30 -> Mar 2).
5
- */
6
- export declare function validateCalendarDate(dateStr: string, fieldName: string): {
7
- year: number;
8
- month: number;
9
- day: number;
10
- };
11
- /**
12
- * Normalize and validate X handles.
13
- * Strips leading '@' and validates length and character set.
14
- */
15
- export declare function validateAndNormalizeHandles(handles: any[], fieldName: string): string[];
16
- /**
17
- * Validate all parameters strictly according to specification before resolving credentials.
18
- */
19
- export declare function validateSearchParams(params: Record<string, any>): XSearchInput;
1
+ import type { XSearchResult } from './types.js';
2
+ export { validateCalendarDate, validateAndNormalizeHandles, validateSearchParams } from './search-input.js';
20
3
  export interface ExecuteSearchOptions {
21
4
  signal?: AbortSignal;
5
+ resolveApiKey?: () => Promise<string>;
22
6
  }
23
- export declare function executeSearch(rawParams: Record<string, any>, { signal }?: ExecuteSearchOptions): Promise<XSearchResult>;
7
+ /** Execute x_search against the xAI Responses API. */
8
+ export declare function executeSearch(rawParams: Record<string, any>, { signal, resolveApiKey }?: ExecuteSearchOptions): Promise<XSearchResult>;
24
9
  //# sourceMappingURL=search.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/search.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,E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
  import { sendHttpRequest, HttpError } from './http.js';
2
2
  import { loadConfig } from './config.js';
3
3
  import { writeCallLog } from './call-log.js';
4
- import { getValidOAuthAccessToken, forceRefreshToken } from './auth.js';
4
+ import { getValidOAuthAccessToken, forceRefreshToken, oauthRequired } from './auth.js';
5
+ import { validateSearchParams } from './search-input.js';
6
+ import { normalizeSearchResponse } from './search-response.js';
7
+ export { validateCalendarDate, validateAndNormalizeHandles, validateSearchParams } from './search-input.js';
5
8
  const XAI_RESPONSES_URL = 'https://api.x.ai/v1/responses';
6
- const ALLOWED_PARAM_KEYS = new Set([
7
- 'query',
8
- 'allowed_x_handles',
9
- 'excluded_x_handles',
10
- 'from_date',
11
- 'to_date',
12
- 'enable_image_understanding',
13
- 'enable_video_understanding',
14
- 'auth_mode',
15
- ]);
16
- const X_SEARCH_INTERNAL_TOOLS = new Set([
17
- 'x_keyword_search',
18
- 'x_semantic_search',
19
- 'x_user_search',
20
- 'x_thread_fetch',
21
- ]);
22
- function isLeapYear(year) {
23
- return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
24
- }
25
- /**
26
- * Validate a real calendar date string formatted as YYYY-MM-DD.
27
- * Prevents JavaScript auto-rollover bugs (e.g. Feb 30 -> Mar 2).
28
- */
29
- export function validateCalendarDate(dateStr, fieldName) {
30
- if (typeof dateStr !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
31
- throw new Error(`Validation error: ${fieldName} must be formatted as YYYY-MM-DD, got: ${dateStr}`);
32
- }
33
- const [yStr, mStr, dStr] = dateStr.split('-');
34
- const year = Number.parseInt(yStr, 10);
35
- const month = Number.parseInt(mStr, 10);
36
- const day = Number.parseInt(dStr, 10);
37
- if (month < 1 || month > 12) {
38
- throw new Error(`Validation error: ${fieldName} has invalid month: ${month}`);
39
- }
40
- const daysInMonth = [
41
- 31,
42
- isLeapYear(year) ? 29 : 28,
43
- 31,
44
- 30,
45
- 31,
46
- 30,
47
- 31,
48
- 31,
49
- 30,
50
- 31,
51
- 30,
52
- 31,
53
- ];
54
- const maxDays = daysInMonth[month - 1];
55
- if (day < 1 || day > maxDays) {
56
- throw new Error(`Validation error: ${fieldName} has invalid day ${day} for month ${month} of year ${year}`);
57
- }
58
- return { year, month, day };
59
- }
60
- /**
61
- * Normalize and validate X handles.
62
- * Strips leading '@' and validates length and character set.
63
- */
64
- export function validateAndNormalizeHandles(handles, fieldName) {
65
- if (!Array.isArray(handles)) {
66
- throw new Error(`Validation error: ${fieldName} must be an array of strings`);
67
- }
68
- if (handles.length > 10) {
69
- throw new Error(`Validation error: ${fieldName} cannot exceed 10 handles`);
70
- }
71
- return handles.map((h, idx) => {
72
- if (typeof h !== 'string') {
73
- throw new Error(`Validation error: ${fieldName}[${idx}] must be a string`);
74
- }
75
- const clean = h.replace(/^@+/, '').trim();
76
- if (!/^[A-Za-z0-9_]{1,15}$/.test(clean)) {
77
- throw new Error(`Validation error: handle "${h}" in ${fieldName} must be 1-15 characters matching [A-Za-z0-9_]`);
78
- }
79
- return clean;
80
- });
81
- }
82
- /**
83
- * Validate all parameters strictly according to specification before resolving credentials.
84
- */
85
- export function validateSearchParams(params) {
86
- if (!params || typeof params !== 'object') {
87
- throw new Error('Validation error: parameters must be an object');
88
- }
89
- // Reject unknown fields
90
- for (const key of Object.keys(params)) {
91
- if (!ALLOWED_PARAM_KEYS.has(key)) {
92
- throw new Error(`Validation error: unknown field "${key}" is not allowed`);
93
- }
94
- }
95
- // Query validation
96
- if (typeof params.query !== 'string') {
97
- throw new Error('Validation error: "query" must be a string');
98
- }
99
- const trimmedQuery = params.query.trim();
100
- if (!trimmedQuery) {
101
- throw new Error('Validation error: "query" cannot be empty');
102
- }
103
- if (trimmedQuery.length > 16000) {
104
- throw new Error(`Validation error: "query" exceeds maximum length of 16000 characters (got ${trimmedQuery.length})`);
105
- }
106
- // Handle lists validation
107
- let allowed = undefined;
108
- if (params.allowed_x_handles !== undefined) {
109
- allowed = validateAndNormalizeHandles(params.allowed_x_handles, 'allowed_x_handles');
110
- }
111
- let excluded = undefined;
112
- if (params.excluded_x_handles !== undefined) {
113
- excluded = validateAndNormalizeHandles(params.excluded_x_handles, 'excluded_x_handles');
114
- }
115
- if (allowed && allowed.length > 0 && excluded && excluded.length > 0) {
116
- throw new Error('Validation error: allowed_x_handles and excluded_x_handles cannot both be non-empty');
117
- }
118
- // Date validation
119
- if (params.from_date !== undefined) {
120
- validateCalendarDate(params.from_date, 'from_date');
121
- }
122
- if (params.to_date !== undefined) {
123
- validateCalendarDate(params.to_date, 'to_date');
124
- }
125
- if (params.from_date && params.to_date) {
126
- if (params.from_date >= params.to_date) {
127
- throw new Error(`Validation error: from_date (${params.from_date}) must be strictly earlier than to_date (${params.to_date})`);
128
- }
129
- }
130
- if (params.from_date) {
131
- const todayUtc = new Date().toISOString().slice(0, 10);
132
- if (params.from_date > todayUtc) {
133
- throw new Error(`Validation error: from_date (${params.from_date}) cannot be later than today UTC (${todayUtc})`);
134
- }
135
- }
136
- // Media flags
137
- if (params.enable_image_understanding !== undefined && typeof params.enable_image_understanding !== 'boolean') {
138
- throw new Error('Validation error: enable_image_understanding must be a boolean');
139
- }
140
- if (params.enable_video_understanding !== undefined && typeof params.enable_video_understanding !== 'boolean') {
141
- throw new Error('Validation error: enable_video_understanding must be a boolean');
142
- }
143
- // Auth mode
144
- if (params.auth_mode !== undefined && !['auto', 'api_key', 'oauth'].includes(params.auth_mode)) {
145
- throw new Error(`Validation error: auth_mode must be one of 'auto', 'api_key', 'oauth', got: ${params.auth_mode}`);
146
- }
147
- return {
148
- query: trimmedQuery,
149
- allowed_x_handles: allowed,
150
- excluded_x_handles: excluded,
151
- from_date: params.from_date,
152
- to_date: params.to_date,
153
- enable_image_understanding: params.enable_image_understanding,
154
- enable_video_understanding: params.enable_video_understanding,
155
- auth_mode: params.auth_mode,
156
- };
157
- }
158
- function sanitizeUrls(rawUrls) {
159
- if (!Array.isArray(rawUrls))
160
- return [];
161
- const valid = [];
162
- for (const u of rawUrls) {
163
- if (typeof u === 'string') {
164
- try {
165
- const parsed = new URL(u);
166
- if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
167
- valid.push(u);
168
- }
169
- }
170
- catch {
171
- // Skip invalid URL
172
- }
173
- }
174
- }
175
- return [...new Set(valid)];
176
- }
177
- /**
178
- * Execute x_search call against xAI responses API.
179
- */
180
9
  function errorInfo(err) {
181
10
  return {
182
11
  code: err?.code || 'SEARCH_ERROR',
@@ -191,7 +20,8 @@ function attemptFromError(err) {
191
20
  error: errorInfo(err),
192
21
  };
193
22
  }
194
- export async function executeSearch(rawParams, { signal } = {}) {
23
+ /** Execute x_search against the xAI Responses API. */
24
+ export async function executeSearch(rawParams, { signal, resolveApiKey } = {}) {
195
25
  const startedAt = new Date().toISOString();
196
26
  const startedMs = Date.now();
197
27
  const attempts = [];
@@ -201,6 +31,8 @@ export async function executeSearch(rawParams, { signal } = {}) {
201
31
  let model = '';
202
32
  let query = typeof rawParams?.query === 'string' ? rawParams.query : '';
203
33
  const persist = async (outcome, error) => {
34
+ if (resolveApiKey)
35
+ return null;
204
36
  try {
205
37
  const logFile = await writeCallLog({
206
38
  started_at: startedAt,
@@ -225,15 +57,21 @@ export async function executeSearch(rawParams, { signal } = {}) {
225
57
  }
226
58
  };
227
59
  try {
228
- // Step 1: Strict parameter validation BEFORE credentials and network
229
- const validated = validateSearchParams(rawParams);
60
+ const managed = Boolean(resolveApiKey);
61
+ const validated = validateSearchParams(rawParams, { managed });
230
62
  query = validated.query;
231
- const config = loadConfig();
63
+ const config = loadConfig({ managed });
232
64
  model = config.model;
233
- // Step 2: Credential resolution
234
65
  const effectiveAuthMode = validated.auth_mode || config.authMode;
235
66
  let token;
236
- if (effectiveAuthMode === 'api_key') {
67
+ if (resolveApiKey) {
68
+ token = await resolveApiKey();
69
+ if (!token)
70
+ throw new HttpError('XAI_KEY_REQUIRED', 'Bind your xAI API key in Settings.', 409);
71
+ credentialSource = 'api_key';
72
+ billingMode = 'api_metered';
73
+ }
74
+ else if (effectiveAuthMode === 'api_key' || (effectiveAuthMode === 'auto' && config.apiKey)) {
237
75
  if (!config.apiKey) {
238
76
  throw new Error('Credential error: API key is required when auth_mode is "api_key", but neither XAI_API_KEY nor XAI_API_KEY_FILE was provided.');
239
77
  }
@@ -241,32 +79,11 @@ export async function executeSearch(rawParams, { signal } = {}) {
241
79
  credentialSource = 'api_key';
242
80
  billingMode = 'api_metered';
243
81
  }
244
- else if (effectiveAuthMode === 'oauth') {
82
+ else {
245
83
  token = await getValidOAuthAccessToken(signal);
246
84
  credentialSource = 'oauth';
247
85
  billingMode = 'subscription_oauth';
248
86
  }
249
- else {
250
- // Mode 'auto'
251
- if (config.apiKey) {
252
- token = config.apiKey;
253
- credentialSource = 'api_key';
254
- billingMode = 'api_metered';
255
- }
256
- else {
257
- try {
258
- token = await getValidOAuthAccessToken(signal);
259
- credentialSource = 'oauth';
260
- billingMode = 'subscription_oauth';
261
- }
262
- catch (error) {
263
- if (error instanceof HttpError && error.code === 'cancelled')
264
- throw error;
265
- throw new Error('Credential error: No valid credentials found. Provide XAI_API_KEY or authenticate via "x-search-mcp auth login".');
266
- }
267
- }
268
- }
269
- // Step 3: Construct request body
270
87
  const toolConfig = {
271
88
  type: 'x_search',
272
89
  };
@@ -299,142 +116,67 @@ export async function executeSearch(rawParams, { signal } = {}) {
299
116
  effort: config.reasoningEffort,
300
117
  };
301
118
  }
302
- // Step 4: Execute HTTP request with single OAuth 401 refresh retry
119
+ const serializedRequest = JSON.stringify(requestBody);
120
+ const requestWithCredential = (credential, retries) => sendHttpRequest({
121
+ url: XAI_RESPONSES_URL,
122
+ method: 'POST',
123
+ headers: {
124
+ Authorization: `Bearer ${credential}`,
125
+ 'Content-Type': 'application/json',
126
+ },
127
+ body: serializedRequest,
128
+ signal,
129
+ timeoutSeconds: config.timeoutSeconds,
130
+ retries,
131
+ });
303
132
  let httpRes;
304
133
  try {
305
- httpRes = await sendHttpRequest({
306
- url: XAI_RESPONSES_URL,
307
- method: 'POST',
308
- headers: {
309
- 'Authorization': `Bearer ${token}`,
310
- 'Content-Type': 'application/json',
311
- },
312
- body: JSON.stringify(requestBody),
313
- signal,
314
- timeoutSeconds: config.timeoutSeconds,
315
- retries: config.retries,
316
- });
134
+ // Managed requests must not retry an old key after it has been unbound.
135
+ httpRes = await requestWithCredential(token, managed ? 0 : config.retries);
317
136
  }
318
137
  catch (err) {
319
138
  attempts.push(attemptFromError(err));
320
- // If OAuth returns HTTP 401, force-refresh token once and retry once
321
- if (credentialSource === 'oauth' && err instanceof HttpError && err.status === 401) {
322
- const freshToken = await forceRefreshToken(token, signal);
323
- try {
324
- httpRes = await sendHttpRequest({
325
- url: XAI_RESPONSES_URL,
326
- method: 'POST',
327
- headers: {
328
- 'Authorization': `Bearer ${freshToken}`,
329
- 'Content-Type': 'application/json',
330
- },
331
- body: JSON.stringify(requestBody),
332
- signal,
333
- timeoutSeconds: config.timeoutSeconds,
334
- retries: 0,
335
- });
336
- }
337
- catch (retryErr) {
338
- attempts.push(attemptFromError(retryErr));
339
- throw retryErr;
340
- }
341
- }
342
- else {
139
+ if (credentialSource !== 'oauth' || !(err instanceof HttpError) || err.status !== 401)
343
140
  throw err;
141
+ const freshToken = await forceRefreshToken(token, signal);
142
+ try {
143
+ httpRes = await requestWithCredential(freshToken, 0);
144
+ }
145
+ catch (retryErr) {
146
+ attempts.push(attemptFromError(retryErr));
147
+ if (retryErr instanceof HttpError && retryErr.status === 401) {
148
+ throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
149
+ }
150
+ throw retryErr;
344
151
  }
345
152
  }
346
153
  const rawData = httpRes.data;
347
- if (!rawData || typeof rawData !== 'object') {
348
- attempts.push({
349
- http_status: httpRes.status ?? null,
350
- raw_response: rawData ?? null,
351
- error: {
352
- code: 'SEARCH_ERROR',
353
- message: 'Upstream xAI API returned empty or unparseable response data',
354
- status: httpRes.status ?? null,
355
- },
356
- });
357
- throw new Error('Upstream xAI API returned empty or unparseable response data');
358
- }
359
- attempts.push({ http_status: httpRes.status ?? null, raw_response: rawData, error: null });
360
- // Check for upstream error status
361
- if (rawData.status === 'failed' || rawData.error) {
362
- const errMsg = rawData.error?.message || 'Upstream xAI response status is failed';
363
- const upstreamError = new HttpError('UPSTREAM_SERVER_ERROR', errMsg, httpRes.status);
364
- attempts[attempts.length - 1].error = errorInfo(upstreamError);
154
+ const attempt = { http_status: httpRes.status, raw_response: rawData ?? null, error: null };
155
+ attempts.push(attempt);
156
+ if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) {
157
+ const invalid = new HttpError('SEARCH_ERROR', 'Upstream xAI returned empty or unparseable response data.');
158
+ attempt.error = errorInfo(invalid);
159
+ throw invalid;
160
+ }
161
+ const upstream = rawData;
162
+ if (upstream.status === 'failed' || upstream.error) {
163
+ const upstreamError = new HttpError('UPSTREAM_SERVER_ERROR', 'Upstream xAI reported a failed search.', httpRes.status);
164
+ attempt.error = errorInfo(upstreamError);
365
165
  throw upstreamError;
366
166
  }
367
- // Step 5: Extract answer, citations, inline citations, and tool execution details
368
- let answerText = '';
369
- if (typeof rawData.output_text === 'string' && rawData.output_text.trim()) {
370
- answerText = rawData.output_text.trim();
371
- }
372
- const collectedCitations = [];
373
- const inlineCitations = [];
374
- const serverSideCalls = [];
375
- // Top-level sources or citations
376
- if (Array.isArray(rawData.citations)) {
377
- collectedCitations.push(...rawData.citations);
378
- }
379
- if (Array.isArray(rawData.sources)) {
380
- collectedCitations.push(...rawData.sources);
381
- }
382
- // Parse output items
383
- if (Array.isArray(rawData.output)) {
384
- for (const item of rawData.output) {
385
- const callId = item.call_id || item.id || '';
386
- const toolName = item.name || item.tool_name || '';
387
- const isXSearchCall = callId.startsWith('xs_') || X_SEARCH_INTERNAL_TOOLS.has(toolName);
388
- if (item.type === 'custom_tool_call' || isXSearchCall) {
389
- serverSideCalls.push({
390
- call_id: callId || null,
391
- name: toolName || null,
392
- arguments: item.arguments || item.input || null,
393
- });
394
- }
395
- const message = item.message || item;
396
- if (message.content) {
397
- if (typeof message.content === 'string' && !answerText) {
398
- answerText += (answerText ? '\n\n' : '') + message.content.trim();
399
- }
400
- else if (Array.isArray(message.content)) {
401
- for (const block of message.content) {
402
- if (!answerText) {
403
- const textPiece = block.output_text || block.text;
404
- if (typeof textPiece === 'string') {
405
- answerText += (answerText ? '\n\n' : '') + textPiece.trim();
406
- }
407
- }
408
- if (Array.isArray(block.annotations)) {
409
- for (const ann of block.annotations) {
410
- if (ann && (ann.type === 'url_citation' || ann.url)) {
411
- const urlStr = ann.url || ann.citation?.url;
412
- if (typeof urlStr === 'string' && (urlStr.startsWith('http://') || urlStr.startsWith('https://'))) {
413
- inlineCitations.push({
414
- url: urlStr,
415
- title: ann.title || ann.citation?.title || null,
416
- start_index: typeof ann.start_index === 'number' ? ann.start_index : null,
417
- end_index: typeof ann.end_index === 'number' ? ann.end_index : null,
418
- });
419
- collectedCitations.push(urlStr);
420
- }
421
- }
422
- }
423
- }
424
- }
425
- }
426
- }
427
- }
428
- }
429
- const finalCitations = sanitizeUrls(collectedCitations);
430
- const hasCitations = finalCitations.length > 0 || inlineCitations.length > 0;
167
+ const response = normalizeSearchResponse(upstream);
168
+ const hasCitations = response.citations.length > 0;
431
169
  const degraded = !hasCitations;
432
170
  const degradedReason = degraded ? 'No source citations returned by upstream x_search' : null;
433
- if (!answerText && !hasCitations) {
434
- throw new Error('Upstream returned no answer and no citations');
171
+ if (!response.answer && !hasCitations) {
172
+ const empty = new HttpError('SEARCH_ERROR', 'Upstream xAI returned no answer or citations.');
173
+ attempt.error = errorInfo(empty);
174
+ throw empty;
435
175
  }
436
- const searchExecution = serverSideCalls.length > 0 ? 'observed' : 'unreported';
437
176
  const warnings = [];
177
+ if (response.response_status === 'incomplete') {
178
+ warnings.push('xAI returned an incomplete search response. Use the available citations and narrow the query if more coverage is needed.');
179
+ }
438
180
  if (credentialSource === 'oauth') {
439
181
  warnings.push('OAuth subscription search availability and quota are determined upstream by xAI; successful login does not guarantee search availability.');
440
182
  }
@@ -449,17 +191,10 @@ export async function executeSearch(rawParams, { signal } = {}) {
449
191
  query: validated.query,
450
192
  credential_source: credentialSource,
451
193
  billing_mode: billingMode,
452
- answer: answerText,
453
- citations: finalCitations,
454
- inline_citations: inlineCitations,
194
+ ...response,
455
195
  has_citations: hasCitations,
456
196
  degraded,
457
197
  degraded_reason: degradedReason,
458
- search_execution: searchExecution,
459
- server_side_calls: serverSideCalls,
460
- response_status: rawData.status || 'completed',
461
- incomplete_details: rawData.incomplete_details || null,
462
- usage: rawData.usage || null,
463
198
  warnings,
464
199
  log_file: null,
465
200
  };