@scoheart/x-search-mcp 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +3 -3
  2. package/TOOL.md +8 -6
  3. package/dist/package.json +2 -1
  4. package/dist/src/auth.d.ts.map +1 -1
  5. package/dist/src/auth.js +61 -46
  6. package/dist/src/auth.js.map +1 -1
  7. package/dist/src/call-log.d.ts.map +1 -1
  8. package/dist/src/call-log.js +52 -33
  9. package/dist/src/call-log.js.map +1 -1
  10. package/dist/src/device-login.d.ts +46 -0
  11. package/dist/src/device-login.d.ts.map +1 -0
  12. package/dist/src/device-login.js +72 -0
  13. package/dist/src/device-login.js.map +1 -0
  14. package/dist/src/multi-user/service.js +2 -2
  15. package/dist/src/multi-user/service.js.map +1 -1
  16. package/dist/src/search-input.d.ts +43 -0
  17. package/dist/src/search-input.d.ts.map +1 -0
  18. package/dist/src/search-input.js +105 -0
  19. package/dist/src/search-input.js.map +1 -0
  20. package/dist/src/search-response.d.ts +6 -0
  21. package/dist/src/search-response.d.ts.map +1 -0
  22. package/dist/src/search-response.js +125 -0
  23. package/dist/src/search-response.js.map +1 -0
  24. package/dist/src/search.d.ts +3 -19
  25. package/dist/src/search.d.ts.map +1 -1
  26. package/dist/src/search.js +54 -312
  27. package/dist/src/search.js.map +1 -1
  28. package/dist/src/server.d.ts +2 -0
  29. package/dist/src/server.d.ts.map +1 -1
  30. package/dist/src/server.js +61 -158
  31. package/dist/src/server.js.map +1 -1
  32. package/dist/src/tool-contract.d.ts +150 -0
  33. package/dist/src/tool-contract.d.ts.map +1 -0
  34. package/dist/src/tool-contract.js +83 -0
  35. package/dist/src/tool-contract.js.map +1 -0
  36. package/examples/codex.toml +1 -1
  37. package/examples/mcp.json +1 -1
  38. package/package.json +2 -1
  39. package/src/auth.ts +59 -46
  40. package/src/call-log.ts +52 -31
  41. package/src/device-login.ts +84 -0
  42. package/src/multi-user/service.ts +2 -2
  43. package/src/search-input.ts +113 -0
  44. package/src/search-response.ts +127 -0
  45. package/src/search.ts +127 -418
  46. package/src/server.ts +66 -170
  47. package/src/tool-contract.ts +90 -0
package/src/server.ts CHANGED
@@ -1,221 +1,117 @@
1
1
  import { McpServer, type ServerContext } from '@modelcontextprotocol/server';
2
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
- import { z } from 'zod';
4
- import { getAuthStatus, startDeviceFlow } from './auth.js';
3
+ import { createDeviceLogin } from './device-login.js';
5
4
  import { HttpError } from './http.js';
6
5
  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';
7
10
  import type { XSearchInput } from './types.js';
8
11
  import { version } from './version.js';
9
12
 
10
- const searchInputSchema = {
11
- query: z
12
- .string()
13
- .describe('Search query text, maximum 16000 characters'),
14
- allowed_x_handles: z
15
- .array(z.string())
16
- .max(10)
17
- .optional()
18
- .describe('Allowed X handles (max 10, without @), mutually exclusive with excluded_x_handles'),
19
- excluded_x_handles: z
20
- .array(z.string())
21
- .max(10)
22
- .optional()
23
- .describe('Excluded X handles (max 10, without @), mutually exclusive with allowed_x_handles'),
24
- from_date: z
25
- .string()
26
- .optional()
27
- .describe('Start date (YYYY-MM-DD), inclusive, real calendar date'),
28
- to_date: z
29
- .string()
30
- .optional()
31
- .describe('End date (YYYY-MM-DD), exclusive, real calendar date strictly later than from_date'),
32
- enable_image_understanding: z
33
- .boolean()
34
- .optional()
35
- .describe('Enable image understanding for image-containing posts'),
36
- enable_video_understanding: z
37
- .boolean()
38
- .optional()
39
- .describe('Enable video understanding for video-containing posts'),
40
- };
41
-
42
- const toolDefinition = {
43
- description: 'Search X (formerly Twitter) using the xAI Responses API with account filters and date ranges.',
44
- inputSchema: searchInputSchema,
45
- annotations: {
46
- readOnlyHint: true,
47
- destructiveHint: false,
48
- idempotentHint: false,
49
- openWorldHint: true,
50
- },
51
- };
52
-
53
13
  type SearchHandler = (params: XSearchInput, context: ServerContext) => ReturnType<typeof executeSearch>;
54
-
55
- const loginTool = 'x_search_login';
56
- const authStatusTool = 'x_search_auth_status';
57
- type DevicePrompt = Awaited<ReturnType<typeof startDeviceFlow>>['prompt'];
58
-
59
- function toolResult(payload: Record<string, unknown>, isError = false) {
60
- return {
61
- content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],
62
- structuredContent: payload,
63
- ...(isError ? { isError: true } : {}),
64
- };
65
- }
66
-
67
- const deviceFailures: Record<string, { status: string; message: string }> = {
68
- DEVICE_LOGIN_DENIED: { status: 'denied', message: 'Grok authorization was declined.' },
69
- DEVICE_LOGIN_EXPIRED: { status: 'expired', message: 'The Grok device code expired.' },
70
- DEVICE_LOGIN_SUPERSEDED: { status: 'superseded', message: 'The local credential changed. Check its status before signing in again.' },
71
- DEVICE_LOGIN_INVALID_RESPONSE: { status: 'failed', message: 'xAI returned invalid device authorization data.' },
72
- cancelled: { status: 'cancelled', message: 'The login was cancelled.' },
73
- };
74
-
75
- function deviceLoginFailure(error: unknown) {
76
- const code = error instanceof HttpError ? error.code
77
- : error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'DEVICE_LOGIN_FAILED';
78
- const failure = deviceFailures[code];
79
- return {
80
- status: failure?.status ?? 'failed',
81
- error: {
82
- code,
83
- message: failure?.message ?? 'Could not complete Grok device authorization.',
84
- status: error instanceof HttpError ? error.status : null,
85
- },
86
- };
87
- }
88
-
89
- function pendingLogin(prompt: DevicePrompt) {
90
- return toolResult({
91
- status: 'pending',
92
- ...prompt,
93
- status_tool: authStatusTool,
94
- 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.',
95
- });
96
- }
97
-
98
- function createDeviceLogin() {
99
- const controller = new AbortController();
100
- let starting: Promise<ReturnType<typeof toolResult>> | undefined;
101
- let polling: Promise<void> | undefined;
102
- let prompt: DevicePrompt | undefined;
103
- let state: { status: string; expires_at?: string; error?: ReturnType<typeof deviceLoginFailure>['error'] } = { status: 'idle' };
104
-
105
- return {
106
- async start() {
107
- if (starting) return starting;
108
- if (prompt) return pendingLogin(prompt);
109
- state = { status: 'starting' };
110
- starting = startDeviceFlow(controller.signal).then(flow => {
111
- prompt = flow.prompt;
112
- state = { status: 'pending', expires_at: prompt.expires_at };
113
- polling = flow.waitForAuthorization().then(
114
- () => { state = { status: 'authorized' }; },
115
- error => { state = deviceLoginFailure(error); },
116
- ).finally(() => {
117
- prompt = undefined;
118
- polling = undefined;
119
- });
120
- return pendingLogin(prompt);
121
- }).catch(error => {
122
- state = deviceLoginFailure(error);
123
- return toolResult(state, true);
124
- }).finally(() => { starting = undefined; });
125
- return starting;
126
- },
127
- status() {
128
- const { hasOAuth, oauthExpiresAt, hasApiKey, defaultAuthMode } = getAuthStatus();
129
- const oauthState = !hasOAuth ? 'missing'
130
- : !oauthExpiresAt ? 'unknown'
131
- : Date.parse(oauthExpiresAt) > Date.now() ? 'unexpired' : 'expired';
132
- return toolResult({
133
- ...state,
134
- oauth_state: oauthState,
135
- oauth_expires_at: oauthExpiresAt,
136
- has_api_key: hasApiKey,
137
- auth_mode: defaultAuthMode,
138
- });
139
- },
140
- async close() {
141
- controller.abort();
142
- await starting;
143
- await polling;
144
- },
145
- };
146
- }
14
+ type Profile = { mode: 'stdio' } | { mode: 'personal-http' } | { mode: 'managed-http'; settingsUrl: string };
147
15
 
148
16
  const toolHandler = async (
149
- search: SearchHandler, params: XSearchInput, context: ServerContext, settingsUrl?: string, deviceLoginEnabled = false,
17
+ search: SearchHandler, params: XSearchInput, context: ServerContext, profile: Profile,
150
18
  ) => {
19
+ const managed = profile.mode === 'managed-http';
151
20
  try {
152
21
  const result = await search(params, context);
153
- return toolResult({ ...result });
154
- } catch (err: any) {
155
- const needsLogin = deviceLoginEnabled && err.code === 'AUTH_REQUIRED';
156
- const errorPayload = {
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({
157
33
  success: false,
158
34
  provider: 'xai',
159
35
  tool: 'x_search',
160
- log_file: err.logFile || null,
161
- ...(settingsUrl && (err.code === 'XAI_KEY_REQUIRED' || err.code === 'UPSTREAM_AUTH_ERROR')
162
- ? { settings_url: settingsUrl } : {}),
36
+ log_file: !managed && typeof error.logFile === 'string' ? error.logFile : null,
37
+ ...(canBindKey ? { settings_url: profile.settingsUrl } : {}),
163
38
  ...(needsLogin ? { login_tool: loginTool, auth_status_tool: authStatusTool } : {}),
164
39
  error: {
165
- code: err.code || 'SEARCH_ERROR',
40
+ code,
166
41
  message: needsLogin ? 'Grok authorization is required. Call x_search_login to start device sign-in.'
167
- : err.message || 'Search execution failed',
168
- status: err.status || null,
42
+ : detail,
43
+ status: typeof error.status === 'number' && Number.isInteger(error.status) ? error.status : null,
169
44
  },
170
- };
171
-
172
- return toolResult(errorPayload, true);
45
+ }, true);
173
46
  }
174
47
  };
175
48
 
176
49
  const personalSearch: SearchHandler = (params, context) => executeSearch(params, { signal: context.mcpReq.signal });
177
50
 
178
51
  export function createServer(): McpServer {
179
- return createSearchServer(personalSearch);
52
+ return createProfileServer(personalSearch, { mode: 'personal-http' });
180
53
  }
181
54
 
182
55
  export function createStdioServer(): McpServer {
183
- return createSearchServer(personalSearch, undefined, true);
56
+ return createProfileServer(personalSearch, { mode: 'stdio' });
57
+ }
58
+
59
+ export function createManagedSearchServer(search: SearchHandler, settingsUrl: string): McpServer {
60
+ return createProfileServer(search, { mode: 'managed-http', settingsUrl });
184
61
  }
185
62
 
63
+ /** Compatibility factory for existing consumers. A settings URL selects managed HTTP. */
186
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' });
67
+ }
68
+
69
+ function createProfileServer(search: SearchHandler, profile: Profile): McpServer {
187
70
  const instance = new McpServer({ name: 'x-search-mcp', version });
188
- const deviceLogin = deviceLoginEnabled ? createDeviceLogin() : undefined;
71
+ const deviceLogin = profile.mode === 'stdio' ? createDeviceLogin() : undefined;
72
+ const managed = profile.mode === 'managed-http';
189
73
  const active = new Set<ReturnType<typeof toolHandler>>();
190
74
  let closing: Promise<void> | undefined;
191
- const definition = settingsUrl ? toolDefinition : {
192
- ...toolDefinition,
193
- description: 'Search X (formerly Twitter) using xAI responses API with real-time index, account filters, and date ranges. Each call saves a local log of the raw upstream response; the path is returned as log_file.'
194
- + (deviceLogin ? ' On AUTH_REQUIRED, use x_search_login to authorize a Grok subscription.' : ''),
195
- inputSchema: {
196
- ...searchInputSchema,
197
- auth_mode: z.enum(['auto', 'api_key', 'oauth']).optional()
198
- .describe('Credential selection mode: auto, api_key, or oauth'),
75
+ instance.registerTool('x_search', {
76
+ 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,
81
+ outputSchema: searchOutputSchema,
82
+ annotations: {
83
+ readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true,
199
84
  },
200
- };
201
- instance.registerTool('x_search', definition, (params, context) => {
85
+ }, (params, context) => {
202
86
  if (closing) throw new Error('MCP server is closing');
203
- const task = toolHandler(search, params, context, settingsUrl, deviceLoginEnabled);
87
+ const task = toolHandler(search, params, context, profile);
204
88
  active.add(task);
205
89
  void task.then(() => { active.delete(task); }, () => { active.delete(task); });
206
90
  return task;
207
91
  });
208
92
  if (deviceLogin) {
209
93
  instance.registerTool(loginTool, {
94
+ title: 'Start Grok sign-in',
210
95
  description: 'Start or resume Grok subscription device sign-in when x_search reports AUTH_REQUIRED or the user asks to sign in.',
211
- inputSchema: {},
96
+ inputSchema: noArguments,
97
+ outputSchema: loginOutputSchema,
212
98
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
213
- }, () => deviceLogin.start());
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
+ });
214
108
  instance.registerTool(authStatusTool, {
109
+ title: 'Check Grok sign-in',
215
110
  description: 'Check Grok device sign-in progress and local OAuth credential expiry. After authorization, retry the original search.',
216
- inputSchema: {},
111
+ inputSchema: noArguments,
112
+ outputSchema: authStatusOutputSchema,
217
113
  annotations: { readOnlyHint: true, openWorldHint: false },
218
- }, () => deviceLogin.status());
114
+ }, () => toolResult(deviceLogin.status()));
219
115
  }
220
116
  // The modern SDK closes the underlying Server directly; legacy code closes
221
117
  // McpServer. Owning the underlying close covers both entry points.
@@ -0,0 +1,90 @@
1
+ import { z } from 'zod';
2
+ import { deviceFailureStatuses } from './device-login.js';
3
+ import { authModeSchema } from './search-input.js';
4
+
5
+ export const loginTool = 'x_search_login';
6
+ export const authStatusTool = 'x_search_auth_status';
7
+ export const noArguments = z.strictObject({});
8
+
9
+ const searchIdentity = { provider: z.literal('xai'), tool: z.literal('x_search'), log_file: z.string().nullable() };
10
+ const toolError = z.strictObject({ code: z.string(), message: z.string(), status: z.number().int().nullable() });
11
+ const citationOffset = z.number().int().nonnegative().nullable();
12
+ const inlineCitation = z.strictObject({
13
+ url: z.string(),
14
+ title: z.string().nullable(),
15
+ start_index: citationOffset,
16
+ end_index: citationOffset,
17
+ });
18
+ const serverSideCall = z.strictObject({
19
+ call_id: z.string().nullable(),
20
+ name: z.string().nullable(),
21
+ arguments: z.unknown(),
22
+ });
23
+
24
+ // Legacy MCP projections require an explicit object root even for object unions.
25
+ export const searchOutputSchema = z.discriminatedUnion('success', [
26
+ z.strictObject({
27
+ ...searchIdentity,
28
+ success: z.literal(true),
29
+ model: z.string(),
30
+ query: z.string(),
31
+ credential_source: z.enum(['api_key', 'oauth']),
32
+ billing_mode: z.enum(['api_metered', 'subscription_oauth']),
33
+ answer: z.string(),
34
+ citations: z.array(z.string()),
35
+ inline_citations: z.array(inlineCitation),
36
+ has_citations: z.boolean(),
37
+ degraded: z.boolean(),
38
+ degraded_reason: z.string().nullable(),
39
+ search_execution: z.enum(['observed', 'unreported']),
40
+ server_side_calls: z.array(serverSideCall),
41
+ response_status: z.string(),
42
+ incomplete_details: z.unknown(),
43
+ usage: z.unknown(),
44
+ warnings: z.array(z.string()),
45
+ }),
46
+ z.strictObject({
47
+ ...searchIdentity,
48
+ success: z.literal(false),
49
+ error: toolError,
50
+ login_tool: z.literal(loginTool).optional(),
51
+ auth_status_tool: z.literal(authStatusTool).optional(),
52
+ settings_url: z.string().optional(),
53
+ }),
54
+ ]).meta({ type: 'object' });
55
+
56
+ const deviceFailure = { status: z.enum(deviceFailureStatuses), error: toolError };
57
+ const pendingDevice = { status: z.literal('pending'), expires_at: z.iso.datetime() };
58
+
59
+ export const loginOutputSchema = z.discriminatedUnion('status', [
60
+ z.strictObject({
61
+ ...pendingDevice,
62
+ verification_uri: z.url({ protocol: /^https$/ }),
63
+ verification_uri_complete: z.url({ protocol: /^https$/ }).optional(),
64
+ user_code: z.string(),
65
+ status_tool: z.literal(authStatusTool),
66
+ message: z.string(),
67
+ }),
68
+ z.strictObject(deviceFailure),
69
+ ]).meta({ type: 'object' });
70
+
71
+ const credentialStatus = {
72
+ oauth_state: z.enum(['missing', 'unknown', 'unexpired', 'expired']),
73
+ oauth_expires_at: z.iso.datetime().nullable(),
74
+ has_api_key: z.boolean(),
75
+ auth_mode: authModeSchema,
76
+ };
77
+
78
+ export const authStatusOutputSchema = z.discriminatedUnion('status', [
79
+ z.strictObject({ ...credentialStatus, status: z.enum(['idle', 'starting', 'authorized']) }),
80
+ z.strictObject({ ...credentialStatus, ...pendingDevice }),
81
+ z.strictObject({ ...credentialStatus, ...deviceFailure }),
82
+ ]).meta({ type: 'object' });
83
+
84
+ export function toolResult(payload: Record<string, unknown>, isError = false) {
85
+ return {
86
+ content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],
87
+ structuredContent: payload,
88
+ ...(isError ? { isError: true } : {}),
89
+ };
90
+ }