@scoheart/x-search-mcp 0.4.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 +28 -16
  3. package/THIRD_PARTY_NOTICES.md +4 -0
  4. package/TOOL.md +57 -78
  5. package/dist/evidence-licenses.txt +791 -0
  6. package/dist/evidence.html +170 -0
  7. package/dist/package.json +10 -3
  8. package/dist/src/auth.d.ts.map +1 -1
  9. package/dist/src/auth.js +6 -11
  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 +38 -29
  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 +15 -41
  22. package/dist/src/device-login.d.ts.map +1 -1
  23. package/dist/src/device-login.js +101 -63
  24. package/dist/src/device-login.js.map +1 -1
  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 +2 -1
  46. package/dist/src/multi-user/service.js.map +1 -1
  47. package/dist/src/search-input.d.ts +5 -17
  48. package/dist/src/search-input.d.ts.map +1 -1
  49. package/dist/src/search-input.js +5 -8
  50. package/dist/src/search-input.js.map +1 -1
  51. package/dist/src/search-response.d.ts +25 -5
  52. package/dist/src/search-response.d.ts.map +1 -1
  53. package/dist/src/search-response.js +97 -94
  54. package/dist/src/search-response.js.map +1 -1
  55. package/dist/src/search.d.ts +6 -3
  56. package/dist/src/search.d.ts.map +1 -1
  57. package/dist/src/search.js +131 -184
  58. package/dist/src/search.js.map +1 -1
  59. package/dist/src/server.d.ts +7 -10
  60. package/dist/src/server.d.ts.map +1 -1
  61. package/dist/src/server.js +109 -95
  62. package/dist/src/server.js.map +1 -1
  63. package/dist/src/tool-contract.d.ts +159 -126
  64. package/dist/src/tool-contract.d.ts.map +1 -1
  65. package/dist/src/tool-contract.js +78 -73
  66. package/dist/src/tool-contract.js.map +1 -1
  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 +10 -3
  85. package/server.json +34 -0
  86. package/src/auth.ts +6 -11
  87. package/src/call-log.ts +39 -30
  88. package/src/cli.ts +26 -19
  89. package/src/config.ts +11 -13
  90. package/src/device-login.ts +107 -71
  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 +2 -1
  97. package/src/search-input.ts +5 -9
  98. package/src/search-response.ts +90 -95
  99. package/src/search.ts +126 -180
  100. package/src/server.ts +115 -104
  101. package/src/tool-contract.ts +82 -76
  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/search.ts CHANGED
@@ -1,223 +1,169 @@
1
- import { sendHttpRequest, HttpError, type SendHttpResponse } from './http.js';
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { abortError, HttpError, sendHttpRequest } from './http.js';
2
3
  import { loadConfig } from './config.js';
3
4
  import { writeCallLog } from './call-log.js';
4
5
  import { getValidOAuthAccessToken, forceRefreshToken, oauthRequired } from './auth.js';
5
6
  import { validateSearchParams } from './search-input.js';
6
7
  import { normalizeSearchResponse } from './search-response.js';
7
- import type { XSearchResult, CallLogAttempt } from './types.js';
8
+ import type { XSearchResult } from './tool-contract.js';
9
+ import type { AuthMode, CallLogAttempt, CallLogEntry } from './types.js';
8
10
 
9
11
  export { validateCalendarDate, validateAndNormalizeHandles, validateSearchParams } from './search-input.js';
10
12
 
11
- const XAI_RESPONSES_URL = 'https://api.x.ai/v1/responses';
13
+ const endpoint = 'https://api.x.ai/v1/responses';
12
14
 
13
15
  export interface ExecuteSearchOptions {
14
16
  signal?: AbortSignal;
17
+ authMode?: AuthMode;
15
18
  resolveApiKey?: () => Promise<string>;
19
+ trackCleanup?: (task: Promise<unknown>) => void;
16
20
  }
17
21
 
18
- function errorInfo(err: any): { code: string; message: string; status: number | null } {
19
- return {
20
- code: err?.code || 'SEARCH_ERROR',
21
- message: err?.message || 'Search execution failed',
22
- status: err?.status ?? null,
23
- };
22
+ function logError(error: unknown): NonNullable<CallLogEntry['error']> {
23
+ return error instanceof HttpError
24
+ ? { code: error.code, message: error.message, status: error.status }
25
+ : { code: 'SEARCH_ERROR', message: 'The search could not be completed.', status: null };
24
26
  }
25
27
 
26
- function attemptFromError(err: any): CallLogAttempt {
27
- return {
28
- http_status: err?.status ?? null,
29
- raw_response: err instanceof HttpError ? err.data ?? null : null,
30
- error: errorInfo(err),
31
- };
28
+ function untilAborted<T>(task: Promise<T>, signal: AbortSignal): Promise<T> {
29
+ return new Promise((resolve, reject) => {
30
+ const abort = () => reject(abortError(signal));
31
+ signal.addEventListener('abort', abort, { once: true });
32
+ task.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
33
+ if (signal.aborted) abort();
34
+ });
32
35
  }
33
36
 
34
- /** Execute x_search against the xAI Responses API. */
35
- export async function executeSearch(rawParams: Record<string, any>, { signal, resolveApiKey }: ExecuteSearchOptions = {}): Promise<XSearchResult> {
37
+ /** One time budget covers key lookup, any credential refresh, rate limiting and response reads. */
38
+ export async function executeSearch(rawParams: unknown, options: ExecuteSearchOptions = {}): Promise<XSearchResult> {
39
+ const started = performance.now();
40
+ const params = validateSearchParams(rawParams);
41
+ const managed = Boolean(options.resolveApiKey);
42
+ const config = loadConfig({ managed });
36
43
  const startedAt = new Date().toISOString();
37
- const startedMs = Date.now();
44
+ const deadline = started + config.deadlineMs;
45
+ const budget = new AbortController();
46
+ const deadlineError = new HttpError('SEARCH_DEADLINE_EXCEEDED', 'The search exceeded its total time budget.');
47
+ const timer = setTimeout(() => budget.abort(deadlineError), Math.max(0, deadline - performance.now()));
48
+ const signal = options.signal ? AbortSignal.any([options.signal, budget.signal]) : budget.signal;
49
+
50
+ function checkBudget() {
51
+ if (!signal.aborted && performance.now() >= deadline) budget.abort(deadlineError);
52
+ if (signal.aborted) throw abortError(signal);
53
+ }
54
+
55
+ const { query, detail, ...filters } = params;
56
+ const body = {
57
+ model: config.model,
58
+ input: [{ role: 'user', content: query }],
59
+ tools: [{ type: 'x_search', ...filters }],
60
+ store: false,
61
+ max_turns: config.maxTurns,
62
+ ...(config.reasoningEffort ? { reasoning: { effort: config.reasoningEffort } } : {}),
63
+ };
64
+ const serialized = JSON.stringify(body);
38
65
  const attempts: CallLogAttempt[] = [];
39
- let requestBody: Record<string, unknown> | null = null;
40
- let credentialSource: 'api_key' | 'oauth' | null = null;
41
- let billingMode: 'api_metered' | 'subscription_oauth' | null = null;
42
- let model = '';
43
- let query = typeof rawParams?.query === 'string' ? rawParams.query : '';
66
+ const mode = options.authMode ?? config.authMode;
67
+ const usesOAuth = !managed && (mode === 'oauth' || (mode === 'auto' && !config.apiKey));
68
+ const credentialSource = usesOAuth ? 'oauth' : 'api_key';
69
+ let failure: CallLogEntry['error'] = null;
70
+ let xSearchCalls: number | null = null;
71
+
72
+ function waitForCredential(task: Promise<string>): Promise<string> {
73
+ // A submitted refresh can rotate the token. Let it persist under the lock
74
+ // while freeing the search caller on timeout or disconnection.
75
+ options.trackCleanup?.(task);
76
+ return untilAborted(task, signal);
77
+ }
44
78
 
45
- const persist = async (outcome: 'success' | 'error', error: { code: string; message: string; status: number | null } | null) => {
46
- if (resolveApiKey) return null;
79
+ async function post(credential: string) {
80
+ checkBudget();
47
81
  try {
48
- const logFile = await writeCallLog({
49
- started_at: startedAt,
50
- elapsed_ms: Date.now() - startedMs,
51
- endpoint: XAI_RESPONSES_URL,
52
- model,
53
- query,
54
- credential_source: credentialSource,
55
- billing_mode: billingMode,
56
- request: requestBody,
57
- attempts,
58
- outcome,
59
- error,
82
+ const response = await sendHttpRequest({
83
+ url: endpoint, method: 'POST', body: serialized, signal, maxResponseBytes: config.maxResponseBytes,
84
+ headers: { Authorization: `Bearer ${credential}`, 'Content-Type': 'application/json' },
85
+ });
86
+ attempts.push({ http_status: response.status, raw_response: config.logMode === 'debug' ? response.data : null, error: null });
87
+ return response;
88
+ } catch (error) {
89
+ const info = logError(error);
90
+ attempts.push({
91
+ http_status: info.status,
92
+ raw_response: config.logMode === 'debug' && error instanceof HttpError ? error.data ?? null : null,
93
+ error: info,
60
94
  });
61
- if (logFile) console.error(`x-search-mcp call_log=${logFile}`);
62
- return logFile;
63
- } catch (err: any) {
64
- console.error(`x-search-mcp call_log_error=${err?.message || 'failed to write call log'}`);
65
- return null;
95
+ throw error;
66
96
  }
67
- };
97
+ }
68
98
 
69
99
  try {
70
- const managed = Boolean(resolveApiKey);
71
- const validated = validateSearchParams(rawParams, { managed });
72
- query = validated.query;
73
- const config = loadConfig({ managed });
74
- model = config.model;
75
-
76
- const effectiveAuthMode = validated.auth_mode || config.authMode;
77
- let token: string;
78
-
79
- if (resolveApiKey) {
80
- token = await resolveApiKey();
81
- if (!token) throw new HttpError('XAI_KEY_REQUIRED', 'Bind your xAI API key in Settings.', 409);
82
- credentialSource = 'api_key';
83
- billingMode = 'api_metered';
84
- } else if (effectiveAuthMode === 'api_key' || (effectiveAuthMode === 'auto' && config.apiKey)) {
85
- if (!config.apiKey) {
86
- 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.');
87
- }
88
- token = config.apiKey;
89
- credentialSource = 'api_key';
90
- billingMode = 'api_metered';
91
- } else {
92
- token = await getValidOAuthAccessToken(signal);
93
- credentialSource = 'oauth';
94
- billingMode = 'subscription_oauth';
100
+ checkBudget();
101
+ const credential = options.resolveApiKey ? await waitForCredential(options.resolveApiKey())
102
+ : usesOAuth ? await waitForCredential(getValidOAuthAccessToken(signal))
103
+ : config.apiKey;
104
+ if (!credential) {
105
+ throw managed ? new HttpError('XAI_KEY_REQUIRED', 'Bind an xAI API key in Settings.', 409)
106
+ : new HttpError('API_KEY_REQUIRED', 'Configure XAI_API_KEY or XAI_API_KEY_FILE.');
95
107
  }
96
108
 
97
- const toolConfig: Record<string, unknown> = {
98
- type: 'x_search',
99
- };
100
- if (validated.allowed_x_handles) toolConfig.allowed_x_handles = validated.allowed_x_handles;
101
- if (validated.excluded_x_handles) toolConfig.excluded_x_handles = validated.excluded_x_handles;
102
- if (validated.from_date) toolConfig.from_date = validated.from_date;
103
- if (validated.to_date) toolConfig.to_date = validated.to_date;
104
- if (validated.enable_image_understanding !== undefined) toolConfig.enable_image_understanding = validated.enable_image_understanding;
105
- if (validated.enable_video_understanding !== undefined) toolConfig.enable_video_understanding = validated.enable_video_understanding;
106
-
107
- requestBody = {
108
- model: config.model,
109
- input: [
110
- {
111
- role: 'user',
112
- content: validated.query,
113
- },
114
- ],
115
- tools: [toolConfig],
116
- store: false,
117
- max_turns: config.maxTurns,
118
- };
119
-
120
- if (config.reasoningEffort) {
121
- requestBody.reasoning = {
122
- effort: config.reasoningEffort,
123
- };
124
- }
125
-
126
- const serializedRequest = JSON.stringify(requestBody);
127
- const requestWithCredential = (credential: string, retries: number) => sendHttpRequest({
128
- url: XAI_RESPONSES_URL,
129
- method: 'POST',
130
- headers: {
131
- Authorization: `Bearer ${credential}`,
132
- 'Content-Type': 'application/json',
133
- },
134
- body: serializedRequest,
135
- signal,
136
- timeoutSeconds: config.timeoutSeconds,
137
- retries,
138
- });
139
-
140
- let httpRes: SendHttpResponse;
109
+ let response;
141
110
  try {
142
- // Managed requests must not retry an old key after it has been unbound.
143
- httpRes = await requestWithCredential(token, managed ? 0 : config.retries);
144
- } catch (err) {
145
- attempts.push(attemptFromError(err));
146
- if (credentialSource !== 'oauth' || !(err instanceof HttpError) || err.status !== 401) throw err;
147
- const freshToken = await forceRefreshToken(token, signal);
148
- try {
149
- httpRes = await requestWithCredential(freshToken, 0);
150
- } catch (retryErr) {
151
- attempts.push(attemptFromError(retryErr));
152
- if (retryErr instanceof HttpError && retryErr.status === 401) {
153
- throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
111
+ response = await post(credential);
112
+ } catch (error) {
113
+ if (!(error instanceof HttpError)) throw error;
114
+ if (usesOAuth && error.status === 401) {
115
+ const fresh = await waitForCredential(forceRefreshToken(credential, signal));
116
+ try { response = await post(fresh); } catch (retryError) {
117
+ if (retryError instanceof HttpError && retryError.status === 401) {
118
+ throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
119
+ }
120
+ throw retryError;
154
121
  }
155
- throw retryErr;
122
+ } else if (!managed && error.status === 429 && error.retryAfterMs !== undefined
123
+ && error.retryAfterMs < deadline - performance.now()) {
124
+ if (error.retryAfterMs > 0) await delay(error.retryAfterMs, undefined, { signal });
125
+ response = await post(credential);
126
+ } else {
127
+ throw error;
156
128
  }
157
129
  }
158
130
 
159
- const rawData: unknown = httpRes.data;
160
- const attempt: CallLogAttempt = { http_status: httpRes.status, raw_response: rawData ?? null, error: null };
161
- attempts.push(attempt);
162
- if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) {
163
- const invalid = new HttpError('SEARCH_ERROR', 'Upstream xAI returned empty or unparseable response data.');
164
- attempt.error = errorInfo(invalid);
165
- throw invalid;
131
+ const data = response.data as unknown;
132
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
133
+ throw new HttpError('INVALID_UPSTREAM_RESPONSE', 'xAI did not return a search response object.', response.status);
166
134
  }
167
-
168
- const upstream = rawData as Record<string, unknown>;
135
+ const upstream = data as Record<string, unknown>;
169
136
  if (upstream.status === 'failed' || upstream.error) {
170
- const upstreamError = new HttpError('UPSTREAM_SERVER_ERROR', 'Upstream xAI reported a failed search.', httpRes.status);
171
- attempt.error = errorInfo(upstreamError);
172
- throw upstreamError;
137
+ throw new HttpError('UPSTREAM_SERVER_ERROR', 'xAI reported a failed search.', response.status);
173
138
  }
174
139
 
175
- const response = normalizeSearchResponse(upstream);
176
- const hasCitations = response.citations.length > 0;
177
- const degraded = !hasCitations;
178
- const degradedReason = degraded ? 'No source citations returned by upstream x_search' : null;
179
-
180
- if (!response.answer && !hasCitations) {
181
- const empty = new HttpError('SEARCH_ERROR', 'Upstream xAI returned no answer or citations.');
182
- attempt.error = errorInfo(empty);
183
- throw empty;
184
- }
185
-
186
- const warnings: string[] = [];
187
- if (response.response_status === 'incomplete') {
188
- warnings.push('xAI returned an incomplete search response. Use the available citations and narrow the query if more coverage is needed.');
189
- }
190
- if (credentialSource === 'oauth') {
191
- warnings.push('OAuth subscription search availability and quota are determined upstream by xAI; successful login does not guarantee search availability.');
140
+ const normalized = normalizeSearchResponse(upstream, detail ?? 'concise');
141
+ if (!normalized.answer && !normalized.sources.length) {
142
+ throw new HttpError('EMPTY_SEARCH_RESPONSE', 'xAI returned no answer or sources.', response.status);
192
143
  }
193
- if (degraded) {
194
- warnings.push('Result contains no source citations and cannot be treated as grounded search evidence.');
195
- }
196
-
197
- const result: XSearchResult = {
198
- success: true,
199
- provider: 'xai',
200
- tool: 'x_search',
144
+ checkBudget();
145
+ xSearchCalls = normalized.usage.x_search_calls;
146
+ return {
147
+ ...normalized,
201
148
  model: config.model,
202
- query: validated.query,
203
- credential_source: credentialSource,
204
- billing_mode: billingMode,
205
- ...response,
206
- has_citations: hasCitations,
207
- degraded,
208
- degraded_reason: degradedReason,
209
- warnings,
210
- log_file: null,
149
+ usage: { ...normalized.usage, requests: attempts.length },
150
+ elapsed_ms: Math.round(performance.now() - started),
211
151
  };
212
- result.log_file = await persist('success', null);
213
- if (config.logEnabled && !result.log_file) {
214
- result.warnings.push('Call log could not be written.');
152
+ } catch (error) {
153
+ const cause = signal.aborted ? abortError(signal) : error;
154
+ failure = logError(cause);
155
+ throw cause;
156
+ } finally {
157
+ clearTimeout(timer);
158
+ if (config.logMode !== 'off') {
159
+ const log = writeCallLog({
160
+ started_at: startedAt,
161
+ elapsed_ms: Math.round(performance.now() - started),
162
+ endpoint, model: config.model, query, credential_source: credentialSource,
163
+ billing_mode: usesOAuth ? 'subscription_oauth' : 'api_metered',
164
+ request: body, attempts, outcome: failure ? 'error' : 'success', error: failure, x_search_calls: xSearchCalls,
165
+ }).catch(() => null);
166
+ options.trackCleanup?.(log);
215
167
  }
216
- return result;
217
- } catch (err: any) {
218
- const info = errorInfo(err);
219
- const logFile = await persist('error', info);
220
- if (err && typeof err === 'object') err.logFile = logFile;
221
- throw err;
222
168
  }
223
169
  }
package/src/server.ts CHANGED
@@ -1,129 +1,148 @@
1
1
  import { McpServer, type ServerContext } from '@modelcontextprotocol/server';
2
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
- import { createDeviceLogin } from './device-login.js';
3
+ import { createDeviceAuthorization } from './device-login.js';
4
+ import { evidenceUri, registerEvidenceApp } from './evidence-app.js';
4
5
  import { HttpError } from './http.js';
6
+ import { startHttp, type HttpServerOptions, type RunningHttpServer } from './http-server.js';
5
7
  import { executeSearch } from './search.js';
6
- import { managedSearchInputSchema, personalSearchInputSchema } from './search-input.js';
7
- import {
8
- authStatusOutputSchema, authStatusTool, loginOutputSchema, loginTool, noArguments, searchOutputSchema, toolResult,
9
- } from './tool-contract.js';
8
+ import { searchInputSchema } from './search-input.js';
9
+ import { searchFailure, searchOutputSchema, searchToolResult } from './tool-contract.js';
10
10
  import type { XSearchInput } from './types.js';
11
11
  import { version } from './version.js';
12
12
 
13
- type SearchHandler = (params: XSearchInput, context: ServerContext) => ReturnType<typeof executeSearch>;
14
- type Profile = { mode: 'stdio' } | { mode: 'personal-http' } | { mode: 'managed-http'; settingsUrl: string };
15
-
16
- const toolHandler = async (
17
- search: SearchHandler, params: XSearchInput, context: ServerContext, profile: Profile,
18
- ) => {
19
- const managed = profile.mode === 'managed-http';
20
- try {
21
- const result = await search(params, context);
22
- return toolResult({ ...result, log_file: managed ? null : result.log_file });
23
- } catch (failure: unknown) {
24
- const error = (failure && typeof failure === 'object' ? failure : {}) as {
25
- code?: unknown; message?: unknown; status?: unknown; logFile?: unknown;
26
- };
27
- const code = typeof error.code === 'string' && error.code ? error.code : 'SEARCH_ERROR';
28
- const needsLogin = profile.mode === 'stdio' && code === 'AUTH_REQUIRED';
29
- const canBindKey = managed && (code === 'XAI_KEY_REQUIRED' || code === 'UPSTREAM_AUTH_ERROR');
30
- const detail = (!managed || failure instanceof HttpError) && typeof error.message === 'string'
31
- ? error.message : 'Search execution failed';
32
- return toolResult({
33
- success: false,
34
- provider: 'xai',
35
- tool: 'x_search',
36
- log_file: !managed && typeof error.logFile === 'string' ? error.logFile : null,
37
- ...(canBindKey ? { settings_url: profile.settingsUrl } : {}),
38
- ...(needsLogin ? { login_tool: loginTool, auth_status_tool: authStatusTool } : {}),
39
- error: {
40
- code,
41
- message: needsLogin ? 'Grok authorization is required. Call x_search_login to start device sign-in.'
42
- : detail,
43
- status: typeof error.status === 'number' && Number.isInteger(error.status) ? error.status : null,
44
- },
45
- }, true);
46
- }
47
- };
48
-
49
- const personalSearch: SearchHandler = (params, context) => executeSearch(params, { signal: context.mcpReq.signal });
13
+ type TrackCleanup = (task: Promise<unknown>) => void;
14
+ type SearchHandler = (params: XSearchInput, context: ServerContext, trackCleanup: TrackCleanup) => ReturnType<typeof executeSearch>;
15
+ const personalSearch: SearchHandler = (params, context, trackCleanup) =>
16
+ executeSearch(params, { signal: context.mcpReq.signal, trackCleanup });
50
17
 
51
18
  export function createServer(): McpServer {
52
- return createProfileServer(personalSearch, { mode: 'personal-http' });
19
+ return createSearchServer(personalSearch);
53
20
  }
54
21
 
55
22
  export function createStdioServer(): McpServer {
56
- return createProfileServer(personalSearch, { mode: 'stdio' });
23
+ return createSearchServer(personalSearch, { deviceAuthorization: createDeviceAuthorization(), ownsAuthorization: true });
57
24
  }
58
25
 
59
- export function createManagedSearchServer(search: SearchHandler, settingsUrl: string): McpServer {
60
- return createProfileServer(search, { mode: 'managed-http', settingsUrl });
26
+ export async function startPersonalHttp(options: HttpServerOptions & {
27
+ interactiveLogin?: boolean;
28
+ eventsDatabase?: string;
29
+ }): Promise<RunningHttpServer> {
30
+ if (!options.interactiveLogin && !options.eventsDatabase) return startHttp(createServer, options);
31
+ if (!['127.0.0.1', '::1'].includes(options.host ?? '127.0.0.1')
32
+ || options.allowedHosts?.length || options.allowedOrigins?.length || options.authentication) {
33
+ throw new Error('Interactive login and Events require a personal loopback listener with no extra hosts or origins.');
34
+ }
35
+
36
+ // Modern HTTP constructs a fresh MCP server for each round. The listener
37
+ // owns the continuation, and every round presents the same service credential.
38
+ const deviceAuthorization = options.interactiveLogin ? createDeviceAuthorization() : undefined;
39
+ const eventModule = options.eventsDatabase ? await import('./events.js') : undefined;
40
+ const store = eventModule && new eventModule.WatchStore(options.eventsDatabase!);
41
+ let service: RunningHttpServer;
42
+ try {
43
+ service = await startHttp(() => {
44
+ const server = createSearchServer(personalSearch, { deviceAuthorization });
45
+ if (store) eventModule.registerEvents(server, store);
46
+ return server;
47
+ }, {
48
+ ...options,
49
+ guardRequest: eventModule?.validateEventHeaders ?? options.guardRequest,
50
+ });
51
+ } catch (error) {
52
+ store?.close();
53
+ throw error;
54
+ }
55
+ const stopWatching = store && eventModule.startWatchScheduler(store);
56
+ let closing: Promise<void> | undefined;
57
+ return {
58
+ url: service.url,
59
+ close() {
60
+ closing ??= Promise.allSettled([deviceAuthorization?.close(), stopWatching?.(), service.close()]).then(results => {
61
+ store?.close();
62
+ const rejected = results.find(result => result.status === 'rejected');
63
+ if (rejected?.status === 'rejected') throw rejected.reason;
64
+ });
65
+ return closing;
66
+ },
67
+ };
61
68
  }
62
69
 
63
- /** Compatibility factory for existing consumers. A settings URL selects managed HTTP. */
64
- export function createSearchServer(search: SearchHandler, settingsUrl?: string, deviceLoginEnabled = false): McpServer {
65
- if (settingsUrl) return createManagedSearchServer(search, settingsUrl);
66
- return createProfileServer(search, { mode: deviceLoginEnabled ? 'stdio' : 'personal-http' });
70
+ export function createManagedSearchServer(search: SearchHandler, settingsUrl: string): McpServer {
71
+ return createSearchServer(search, { settingsUrl });
67
72
  }
68
73
 
69
- function createProfileServer(search: SearchHandler, profile: Profile): McpServer {
70
- const instance = new McpServer({ name: 'x-search-mcp', version });
71
- const deviceLogin = profile.mode === 'stdio' ? createDeviceLogin() : undefined;
72
- const managed = profile.mode === 'managed-http';
73
- const active = new Set<ReturnType<typeof toolHandler>>();
74
+ function createSearchServer(search: SearchHandler, options: {
75
+ settingsUrl?: string;
76
+ deviceAuthorization?: ReturnType<typeof createDeviceAuthorization>;
77
+ ownsAuthorization?: boolean;
78
+ } = {}): McpServer {
79
+ const { deviceAuthorization, settingsUrl } = options;
80
+ const instance = new McpServer({ name: 'x-search-mcp', version }, {
81
+ supportedProtocolVersions: ['2026-07-28'],
82
+ inputRequired: { legacyShim: false },
83
+ requestState: {
84
+ verify(state) {
85
+ if (!deviceAuthorization) throw new Error('This server has no Grok sign-in continuation.');
86
+ return deviceAuthorization.verify(state);
87
+ },
88
+ },
89
+ });
90
+ registerEvidenceApp(instance);
91
+ const active = new Set<Promise<unknown>>();
74
92
  let closing: Promise<void> | undefined;
93
+
94
+ function trackCleanup(task: Promise<unknown>) {
95
+ active.add(task);
96
+ void task.then(() => { active.delete(task); }, () => { active.delete(task); });
97
+ }
98
+
99
+ async function runSearch(params: XSearchInput, context: ServerContext) {
100
+ const request = context.mcpReq;
101
+ const resuming = request.requestState() !== undefined || request.inputResponses !== undefined;
102
+ const queryKey = JSON.stringify(params);
103
+ try {
104
+ if (resuming) {
105
+ if (!deviceAuthorization) throw new HttpError('INVALID_AUTHORIZATION_STATE', 'This search does not have a pending sign-in.');
106
+ return searchToolResult(await deviceAuthorization.resume(queryKey, request));
107
+ }
108
+ return searchToolResult(await search(params, context, trackCleanup));
109
+ } catch (error) {
110
+ if (!resuming && error instanceof HttpError && error.code === 'AUTH_REQUIRED') {
111
+ try {
112
+ const next = deviceAuthorization?.begin(queryKey, request);
113
+ if (next) return 'resultType' in next ? next : searchToolResult(next);
114
+ } catch (authorizationError) {
115
+ return searchToolResult(searchFailure(authorizationError));
116
+ }
117
+ }
118
+ return searchToolResult(searchFailure(error, settingsUrl));
119
+ }
120
+ }
121
+
75
122
  instance.registerTool('x_search', {
76
123
  title: 'Search X',
77
- description: 'Search public posts on X using xAI with account filters and date ranges. Returns an answer, source URLs, and a degraded flag when citations are missing.'
78
- + (deviceLogin ? ' On AUTH_REQUIRED, call x_search_login to authorize a Grok subscription.' : '')
79
- + (managed ? ' On XAI_KEY_REQUIRED or UPSTREAM_AUTH_ERROR, send the user to settings_url.' : ''),
80
- inputSchema: managed ? managedSearchInputSchema : personalSearchInputSchema,
124
+ description: 'Search public X posts by query, account and date. Returns a bounded answer, canonical sources and usage counts.'
125
+ + (deviceAuthorization ? ' Can ask the user to sign in to Grok when needed.' : ''),
126
+ inputSchema: searchInputSchema,
81
127
  outputSchema: searchOutputSchema,
82
- annotations: {
83
- readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true,
84
- },
128
+ _meta: { ui: { resourceUri: evidenceUri } },
129
+ annotations: { readOnlyHint: !deviceAuthorization, destructiveHint: false, idempotentHint: false, openWorldHint: true },
85
130
  }, (params, context) => {
86
- if (closing) throw new Error('MCP server is closing');
87
- const task = toolHandler(search, params, context, profile);
88
- active.add(task);
89
- void task.then(() => { active.delete(task); }, () => { active.delete(task); });
131
+ if (closing) throw new Error('MCP server is closing.');
132
+ const task = runSearch(params, context);
133
+ trackCleanup(task);
90
134
  return task;
91
135
  });
92
- if (deviceLogin) {
93
- instance.registerTool(loginTool, {
94
- title: 'Start Grok sign-in',
95
- description: 'Start or resume Grok subscription device sign-in when x_search reports AUTH_REQUIRED or the user asks to sign in.',
96
- inputSchema: noArguments,
97
- outputSchema: loginOutputSchema,
98
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
99
- }, async () => {
100
- const result = await deviceLogin.start();
101
- if (result.status !== 'pending') return toolResult(result, true);
102
- return toolResult({
103
- ...result,
104
- status_tool: authStatusTool,
105
- message: 'Show the verification URL and code to the user. Ask them to verify their account and complete authorization in the browser, then check the status.',
106
- });
107
- });
108
- instance.registerTool(authStatusTool, {
109
- title: 'Check Grok sign-in',
110
- description: 'Check Grok device sign-in progress and local OAuth credential expiry. After authorization, retry the original search.',
111
- inputSchema: noArguments,
112
- outputSchema: authStatusOutputSchema,
113
- annotations: { readOnlyHint: true, openWorldHint: false },
114
- }, () => toolResult(deviceLogin.status()));
115
- }
116
- // The modern SDK closes the underlying Server directly; legacy code closes
117
- // McpServer. Owning the underlying close covers both entry points.
136
+
118
137
  const closeTransport = instance.server.close.bind(instance.server);
119
138
  instance.server.close = () => {
120
139
  closing ??= Promise.resolve().then(async () => {
121
- const loginWork = deviceLogin?.close();
140
+ const authorization = options.ownsAuthorization ? deviceAuthorization?.close() : undefined;
122
141
  try {
123
142
  await closeTransport();
124
143
  } finally {
125
- // Cancel queued work and drain any accepted refresh before shutting down.
126
- await Promise.allSettled([...active, loginWork]);
144
+ while (active.size) await Promise.allSettled(active);
145
+ await authorization;
127
146
  }
128
147
  });
129
148
  return closing;
@@ -131,14 +150,6 @@ function createProfileServer(search: SearchHandler, profile: Profile): McpServer
131
150
  return instance;
132
151
  }
133
152
 
134
- /** @deprecated Create a fresh server with createServer() for each transport. */
135
- export const server = createServer();
136
-
137
- /**
138
- * Launch stdio server.
139
- * stdout is strictly reserved for JSON-RPC MCP messages.
140
- * Diagnostic logs are written to stderr.
141
- */
142
153
  export function startStdio() {
143
- return serveStdio(createStdioServer);
154
+ return serveStdio(createStdioServer, { legacy: 'reject' });
144
155
  }