@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.
- package/.env.example +7 -10
- package/README.md +28 -16
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/TOOL.md +57 -78
- package/dist/evidence-licenses.txt +791 -0
- package/dist/evidence.html +170 -0
- package/dist/package.json +10 -3
- package/dist/src/auth.d.ts.map +1 -1
- package/dist/src/auth.js +6 -11
- package/dist/src/auth.js.map +1 -1
- package/dist/src/call-log.d.ts +5 -4
- package/dist/src/call-log.d.ts.map +1 -1
- package/dist/src/call-log.js +38 -29
- package/dist/src/call-log.js.map +1 -1
- package/dist/src/cli.d.ts.map +1 -1
- package/dist/src/cli.js +26 -19
- package/dist/src/cli.js.map +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +12 -16
- package/dist/src/config.js.map +1 -1
- package/dist/src/device-login.d.ts +15 -41
- package/dist/src/device-login.d.ts.map +1 -1
- package/dist/src/device-login.js +101 -63
- package/dist/src/device-login.js.map +1 -1
- package/dist/src/events.d.ts +16 -0
- package/dist/src/events.d.ts.map +1 -0
- package/dist/src/events.js +128 -0
- package/dist/src/events.js.map +1 -0
- package/dist/src/evidence-app.d.ts +4 -0
- package/dist/src/evidence-app.d.ts.map +1 -0
- package/dist/src/evidence-app.js +17 -0
- package/dist/src/evidence-app.js.map +1 -0
- package/dist/src/http-server.d.ts +1 -0
- package/dist/src/http-server.d.ts.map +1 -1
- package/dist/src/http-server.js +6 -4
- package/dist/src/http-server.js.map +1 -1
- package/dist/src/http.d.ts +12 -15
- package/dist/src/http.d.ts.map +1 -1
- package/dist/src/http.js +78 -118
- package/dist/src/http.js.map +1 -1
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/multi-user/service.d.ts.map +1 -1
- package/dist/src/multi-user/service.js +2 -1
- package/dist/src/multi-user/service.js.map +1 -1
- package/dist/src/search-input.d.ts +5 -17
- package/dist/src/search-input.d.ts.map +1 -1
- package/dist/src/search-input.js +5 -8
- package/dist/src/search-input.js.map +1 -1
- package/dist/src/search-response.d.ts +25 -5
- package/dist/src/search-response.d.ts.map +1 -1
- package/dist/src/search-response.js +97 -94
- package/dist/src/search-response.js.map +1 -1
- package/dist/src/search.d.ts +6 -3
- package/dist/src/search.d.ts.map +1 -1
- package/dist/src/search.js +131 -184
- package/dist/src/search.js.map +1 -1
- package/dist/src/server.d.ts +7 -10
- package/dist/src/server.d.ts.map +1 -1
- package/dist/src/server.js +109 -95
- package/dist/src/server.js.map +1 -1
- package/dist/src/tool-contract.d.ts +159 -126
- package/dist/src/tool-contract.d.ts.map +1 -1
- package/dist/src/tool-contract.js +78 -73
- package/dist/src/tool-contract.js.map +1 -1
- package/dist/src/types.d.ts +7 -37
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/watch-cli.d.ts +2 -0
- package/dist/src/watch-cli.d.ts.map +1 -0
- package/dist/src/watch-cli.js +41 -0
- package/dist/src/watch-cli.js.map +1 -0
- package/dist/src/watch-store.d.ts +41 -0
- package/dist/src/watch-store.d.ts.map +1 -0
- package/dist/src/watch-store.js +171 -0
- package/dist/src/watch-store.js.map +1 -0
- package/dist/ui/evidence.d.ts +2 -0
- package/dist/ui/evidence.d.ts.map +1 -0
- package/dist/ui/evidence.js +150 -0
- package/dist/ui/evidence.js.map +1 -0
- package/docs/events-and-apps.md +40 -0
- package/examples/codex.toml +6 -7
- package/examples/mcp.json +2 -6
- package/package.json +10 -3
- package/server.json +34 -0
- package/src/auth.ts +6 -11
- package/src/call-log.ts +39 -30
- package/src/cli.ts +26 -19
- package/src/config.ts +11 -13
- package/src/device-login.ts +107 -71
- package/src/events.ts +124 -0
- package/src/evidence-app.ts +19 -0
- package/src/http-server.ts +7 -4
- package/src/http.ts +83 -162
- package/src/index.ts +1 -0
- package/src/multi-user/service.ts +2 -1
- package/src/search-input.ts +5 -9
- package/src/search-response.ts +90 -95
- package/src/search.ts +126 -180
- package/src/server.ts +115 -104
- package/src/tool-contract.ts +82 -76
- package/src/types.ts +8 -40
- package/src/watch-cli.ts +35 -0
- package/src/watch-store.ts +182 -0
- package/tsconfig.json +2 -1
package/src/search.ts
CHANGED
|
@@ -1,223 +1,169 @@
|
|
|
1
|
-
import {
|
|
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
|
|
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
|
|
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
|
|
19
|
-
return
|
|
20
|
-
code:
|
|
21
|
-
|
|
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
|
|
27
|
-
return {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
/**
|
|
35
|
-
export async function executeSearch(rawParams:
|
|
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
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
let
|
|
43
|
-
let
|
|
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
|
-
|
|
46
|
-
|
|
79
|
+
async function post(credential: string) {
|
|
80
|
+
checkBudget();
|
|
47
81
|
try {
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
|
|
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
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
-
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
|
|
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
|
|
160
|
-
|
|
161
|
-
|
|
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
|
-
|
|
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
|
|
176
|
-
|
|
177
|
-
|
|
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
|
-
|
|
194
|
-
|
|
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
|
-
|
|
203
|
-
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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 {
|
|
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 {
|
|
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
|
|
14
|
-
type
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
19
|
+
return createSearchServer(personalSearch);
|
|
53
20
|
}
|
|
54
21
|
|
|
55
22
|
export function createStdioServer(): McpServer {
|
|
56
|
-
return
|
|
23
|
+
return createSearchServer(personalSearch, { deviceAuthorization: createDeviceAuthorization(), ownsAuthorization: true });
|
|
57
24
|
}
|
|
58
25
|
|
|
59
|
-
export function
|
|
60
|
-
|
|
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
|
-
|
|
64
|
-
|
|
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
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
|
78
|
-
+ (
|
|
79
|
-
|
|
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
|
-
|
|
83
|
-
|
|
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 =
|
|
88
|
-
|
|
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
|
-
|
|
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
|
|
140
|
+
const authorization = options.ownsAuthorization ? deviceAuthorization?.close() : undefined;
|
|
122
141
|
try {
|
|
123
142
|
await closeTransport();
|
|
124
143
|
} finally {
|
|
125
|
-
|
|
126
|
-
await
|
|
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
|
}
|