@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/config.ts CHANGED
@@ -47,8 +47,8 @@ function parseBoundedInt(val: string | undefined, name: string, min: number, max
47
47
  if (val === undefined || val === null || val === '') {
48
48
  return defaultVal;
49
49
  }
50
- const parsed = Number.parseInt(val, 10);
51
- if (Number.isNaN(parsed) || parsed < min || parsed > max) {
50
+ const parsed = Number(val);
51
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
52
52
  throw new Error(`Configuration error: ${name} must be an integer between ${min} and ${max}, got: ${val}`);
53
53
  }
54
54
  return parsed;
@@ -62,12 +62,9 @@ function parseAuthMode(val: string | undefined): AuthMode {
62
62
  return mode;
63
63
  }
64
64
 
65
- function parseEnabled(val: string | undefined, name: string, defaultVal: boolean): boolean {
66
- if (val === undefined || val === null || val === '') return defaultVal;
67
- const normalized = val.trim().toLowerCase();
68
- if (['1', 'true', 'on', 'yes'].includes(normalized)) return true;
69
- if (['0', 'false', 'off', 'no'].includes(normalized)) return false;
70
- throw new Error(`Configuration error: ${name} must be on or off, got: ${val}`);
65
+ function parseLogMode(value = 'metadata'): Config['logMode'] {
66
+ if (value === 'off' || value === 'metadata' || value === 'debug') return value;
67
+ throw new Error('X_SEARCH_LOG must be off, metadata, or debug.');
71
68
  }
72
69
 
73
70
  function parseReasoningEffort(val: string | undefined): ReasoningEffort | undefined {
@@ -92,16 +89,17 @@ export function loadConfig({ managed = false }: { managed?: boolean } = {}): Con
92
89
  authDir: path.dirname(authFile),
93
90
  oauthClientId: process.env.XAI_OAUTH_CLIENT_ID || 'b1a00492-073a-47ea-816f-4c329264a828',
94
91
  model: process.env.X_SEARCH_MODEL || 'grok-4.5',
95
- timeoutSeconds: parseBoundedInt(process.env.X_SEARCH_TIMEOUT_SECONDS, 'X_SEARCH_TIMEOUT_SECONDS', 5, 600, 180),
96
- retries: parseBoundedInt(process.env.X_SEARCH_RETRIES, 'X_SEARCH_RETRIES', 0, 3, 2),
92
+ deadlineMs: parseBoundedInt(process.env.X_SEARCH_DEADLINE_MS, 'X_SEARCH_DEADLINE_MS', 100, 600_000, 90_000),
93
+ maxResponseBytes: parseBoundedInt(process.env.X_SEARCH_MAX_RESPONSE_BYTES, 'X_SEARCH_MAX_RESPONSE_BYTES', 1024, 16_777_216, 2_097_152),
97
94
  maxTurns: parseBoundedInt(process.env.X_SEARCH_MAX_TURNS, 'X_SEARCH_MAX_TURNS', 1, 20, 4),
98
95
  reasoningEffort: parseReasoningEffort(process.env.X_SEARCH_REASONING_EFFORT),
99
96
  apiKey: managed ? null : getApiKey(),
100
- logEnabled: !managed && parseEnabled(process.env.X_SEARCH_LOG, 'X_SEARCH_LOG', true),
97
+ logMode: managed ? 'off' : parseLogMode(process.env.X_SEARCH_LOG),
101
98
  logDir: process.env.X_SEARCH_LOG_DIR
102
99
  ? path.resolve(process.env.X_SEARCH_LOG_DIR)
103
100
  : path.join(defaultAuthDir, 'logs'),
104
- logKeep: parseBoundedInt(process.env.X_SEARCH_LOG_KEEP, 'X_SEARCH_LOG_KEEP', 0, 10000, 100),
105
- logMaxBytes: parseBoundedInt(process.env.X_SEARCH_LOG_MAX_BYTES, 'X_SEARCH_LOG_MAX_BYTES', 4096, 33554432, 8388608),
101
+ logKeep: parseBoundedInt(process.env.X_SEARCH_LOG_KEEP, 'X_SEARCH_LOG_KEEP', 1, 10000, 100),
102
+ logMaxBytes: parseBoundedInt(process.env.X_SEARCH_LOG_MAX_BYTES, 'X_SEARCH_LOG_MAX_BYTES', 4096, 1_048_576, 65_536),
103
+ logTotalBytes: parseBoundedInt(process.env.X_SEARCH_LOG_TOTAL_BYTES, 'X_SEARCH_LOG_TOTAL_BYTES', 65_536, 268_435_456, 33_554_432),
106
104
  };
107
105
  }
@@ -1,84 +1,120 @@
1
- import { getAuthStatus, startDeviceFlow } from './auth.js';
2
- import { HttpError } from './http.js';
1
+ import { randomUUID } from 'node:crypto';
2
+ import {
3
+ CLIENT_CAPABILITIES_META_KEY, acceptedContent, inputRequired, type ClientCapabilities, type ServerContext,
4
+ } from '@modelcontextprotocol/server';
5
+ import { z } from 'zod';
6
+ import { startDeviceFlow } from './auth.js';
7
+ import { abortError, HttpError } from './http.js';
8
+ import type { AuthorizationPending } from './tool-contract.js';
3
9
 
4
- type DevicePrompt = Awaited<ReturnType<typeof startDeviceFlow>>['prompt'];
5
- export const deviceFailureStatuses = ['denied', 'expired', 'superseded', 'failed', 'cancelled'] as const;
6
- type DeviceFailureStatus = typeof deviceFailureStatuses[number];
7
- type DeviceFailure = { status: DeviceFailureStatus; error: { code: string; message: string; status: number | null } };
8
- type DeviceState = { status: 'idle' | 'starting' | 'authorized' }
9
- | { status: 'pending'; expires_at: string }
10
- | DeviceFailure;
11
- type DeviceStart = ({ status: 'pending' } & DevicePrompt) | DeviceFailure;
10
+ const confirmation = z.strictObject({ authorize: z.boolean() });
11
+ const confirmInput = 'grok_consent';
12
+ type Request = ServerContext['mcpReq'];
13
+ type State = { queryKey: string } & (
14
+ { phase: 'confirm'; id: string; expiresAt: number } |
15
+ { phase: 'starting'; controller: AbortController } |
16
+ { phase: 'pending'; controller: AbortController; result: AuthorizationPending; polling?: Promise<void> } |
17
+ { phase: 'failed'; error: unknown; expiresAt: number }
18
+ );
12
19
 
13
- const deviceFailures: Record<string, { status: DeviceFailureStatus; message: string }> = {
14
- DEVICE_LOGIN_DENIED: { status: 'denied', message: 'Grok authorization was declined.' },
15
- DEVICE_LOGIN_EXPIRED: { status: 'expired', message: 'The Grok device code expired.' },
16
- DEVICE_LOGIN_SUPERSEDED: { status: 'superseded', message: 'The local credential changed. Check its status before signing in again.' },
17
- DEVICE_LOGIN_INVALID_RESPONSE: { status: 'failed', message: 'xAI returned invalid device authorization data.' },
18
- cancelled: { status: 'cancelled', message: 'The login was cancelled.' },
19
- };
20
+ /** One consent and device grant at a time, scoped to the original search. */
21
+ export function createDeviceAuthorization() {
22
+ let state: State | undefined;
23
+
24
+ function expire() {
25
+ if ((state?.phase === 'confirm' || state?.phase === 'failed') && state.expiresAt <= Date.now()) {
26
+ state = undefined;
27
+ }
28
+ }
20
29
 
21
- function deviceLoginFailure(error: unknown): DeviceFailure {
22
- const code = error instanceof HttpError ? error.code
23
- : error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'DEVICE_LOGIN_FAILED';
24
- const failure = Object.hasOwn(deviceFailures, code) ? deviceFailures[code] : undefined;
25
30
  return {
26
- status: failure?.status ?? 'failed',
27
- error: {
28
- code,
29
- message: failure?.message ?? 'Could not complete Grok device authorization.',
30
- status: error instanceof HttpError ? error.status : null,
31
+ verify(id: string) {
32
+ expire();
33
+ if (state?.phase !== 'confirm' || state.id !== id) throw new Error('Unknown Grok sign-in continuation.');
34
+ return id;
31
35
  },
32
- };
33
- }
34
36
 
35
- export function createDeviceLogin() {
36
- const controller = new AbortController();
37
- let starting: Promise<DeviceStart> | undefined;
38
- let polling: Promise<void> | undefined;
39
- let pending: ({ status: 'pending' } & DevicePrompt) | undefined;
40
- let state: DeviceState = { status: 'idle' };
37
+ begin(queryKey: string, request: Request) {
38
+ const envelope = request.envelope as Record<string, ClientCapabilities | undefined> | undefined;
39
+ if (!envelope?.[CLIENT_CAPABILITIES_META_KEY]?.elicitation?.form) return undefined;
41
40
 
42
- return {
43
- async start(): Promise<DeviceStart> {
44
- if (starting) return starting;
45
- if (pending) return pending;
46
- state = { status: 'starting' };
47
- starting = startDeviceFlow(controller.signal).then((flow): DeviceStart => {
48
- pending = { status: 'pending', ...flow.prompt };
49
- state = { status: 'pending', expires_at: pending.expires_at };
50
- polling = flow.waitForAuthorization().then(
51
- () => { state = { status: 'authorized' }; },
52
- error => { state = deviceLoginFailure(error); },
53
- ).finally(() => {
54
- pending = undefined;
55
- polling = undefined;
56
- });
57
- return pending;
58
- }).catch(error => {
59
- const failure = deviceLoginFailure(error);
60
- state = failure;
61
- return failure;
62
- }).finally(() => { starting = undefined; });
63
- return starting;
41
+ expire();
42
+ if (state?.phase === 'failed') {
43
+ const failure = state;
44
+ state = undefined;
45
+ if (failure.queryKey === queryKey) throw failure.error;
46
+ }
47
+ if (state?.phase === 'pending' && state.queryKey === queryKey) return state.result;
48
+ if (state) {
49
+ throw new HttpError('AUTHORIZATION_IN_PROGRESS', 'Finish the current Grok sign-in before starting another.');
50
+ }
51
+
52
+ const id = randomUUID();
53
+ state = { id, queryKey, expiresAt: Date.now() + 120_000, phase: 'confirm' };
54
+ return inputRequired({
55
+ requestState: id,
56
+ inputRequests: {
57
+ [confirmInput]: inputRequired.elicit({
58
+ mode: 'form',
59
+ message: 'Sign in to your Grok subscription to run this X search?',
60
+ requestedSchema: {
61
+ type: 'object',
62
+ properties: { authorize: { type: 'boolean', title: 'Authorize Grok' } },
63
+ required: ['authorize'],
64
+ },
65
+ }),
66
+ },
67
+ });
64
68
  },
65
- status() {
66
- const { hasOAuth, oauthExpiresAt, hasApiKey, defaultAuthMode } = getAuthStatus();
67
- const oauthState = !hasOAuth ? 'missing'
68
- : !oauthExpiresAt ? 'unknown'
69
- : Date.parse(oauthExpiresAt) > Date.now() ? 'unexpired' : 'expired';
70
- return {
71
- ...state,
72
- oauth_state: oauthState,
73
- oauth_expires_at: oauthExpiresAt,
74
- has_api_key: hasApiKey,
75
- auth_mode: defaultAuthMode,
76
- };
69
+
70
+ async resume(queryKey: string, request: Request): Promise<AuthorizationPending> {
71
+ expire();
72
+ if (state?.phase !== 'confirm' || request.requestState<string>() !== state.id || queryKey !== state.queryKey) {
73
+ throw new HttpError('INVALID_AUTHORIZATION_STATE', 'This Grok sign-in request expired or does not match this search.');
74
+ }
75
+ state = undefined;
76
+ if (acceptedContent(request.inputResponses, confirmInput, confirmation)?.authorize !== true) {
77
+ throw new HttpError('AUTHORIZATION_DECLINED', 'Grok sign-in was declined.');
78
+ }
79
+ if (request.signal.aborted) throw abortError(request.signal);
80
+
81
+ const controller = new AbortController();
82
+ const starting = { queryKey, controller, phase: 'starting' as const };
83
+ state = starting;
84
+ const cancel = () => controller.abort(request.signal.reason);
85
+ request.signal.addEventListener('abort', cancel, { once: true });
86
+ try {
87
+ const { prompt, waitForAuthorization } = await startDeviceFlow(controller.signal);
88
+ if (controller.signal.aborted) throw abortError(controller.signal);
89
+ const result: AuthorizationPending = {
90
+ status: 'authorization_pending',
91
+ action: {
92
+ type: 'verify_device',
93
+ url: prompt.verification_uri_complete ?? prompt.verification_uri,
94
+ user_code: prompt.user_code,
95
+ expires_at: prompt.expires_at,
96
+ },
97
+ };
98
+ const pending: State = { queryKey, result, controller, phase: 'pending' };
99
+ state = pending;
100
+ pending.polling = waitForAuthorization().then(
101
+ () => { if (state === pending) state = undefined; },
102
+ error => {
103
+ if (state === pending) state = { queryKey, error, expiresAt: Date.now() + 120_000, phase: 'failed' };
104
+ },
105
+ );
106
+ return result;
107
+ } finally {
108
+ request.signal.removeEventListener('abort', cancel);
109
+ if (state === starting) state = undefined;
110
+ }
77
111
  },
112
+
78
113
  async close() {
79
- controller.abort();
80
- await starting;
81
- await polling;
114
+ const current = state;
115
+ state = undefined;
116
+ if (current?.phase === 'pending' || current?.phase === 'starting') current.controller.abort();
117
+ if (current?.phase === 'pending') await current.polling;
82
118
  },
83
119
  };
84
120
  }
package/src/events.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { McpServer, ProtocolError } from '@modelcontextprotocol/server';
2
+ import { z } from 'zod';
3
+ import { executeSearch } from './search.js';
4
+ import { HttpError } from './http.js';
5
+ import { InvalidWatchRequest, WatchStore } from './watch-store.js';
6
+ export { WatchStore, watchDatabasePath } from './watch-store.js';
7
+
8
+ export const eventsExtension = 'io.modelcontextprotocol/events';
9
+ const eventName = 'x_search.evidence_found';
10
+ const watchArguments = z.strictObject({ watch_id: z.uuid() });
11
+ const pollRequest = z.strictObject({
12
+ name: z.string().min(1).max(128),
13
+ arguments: watchArguments,
14
+ cursor: z.string().max(256).nullish(),
15
+ maxAgeMs: z.int().nonnegative().optional(),
16
+ maxEvents: z.int().positive().optional(),
17
+ });
18
+ const payload = z.strictObject({
19
+ watch_id: z.uuid(),
20
+ post_id: z.string().regex(/^\d{1,20}$/),
21
+ url: z.url(),
22
+ });
23
+
24
+ export function registerEvents(instance: McpServer, store: WatchStore) {
25
+ const core = instance.server;
26
+ core.registerCapabilities({ extensions: { [eventsExtension]: {} } });
27
+ core.setRequestHandler('events/list', { params: z.strictObject({ cursor: z.string().optional() }) }, params => {
28
+ if (params.cursor !== undefined) throw new ProtocolError(-32602, 'Invalid event list cursor.');
29
+ return {
30
+ events: [{
31
+ name: eventName,
32
+ description: 'A configured watch found new X post evidence.',
33
+ delivery: ['poll'],
34
+ inputSchema: z.toJSONSchema(watchArguments),
35
+ payloadSchema: z.toJSONSchema(payload),
36
+ }],
37
+ };
38
+ });
39
+ core.setRequestHandler('events/poll', { params: pollRequest }, params => {
40
+ if (params.name !== eventName) throw new ProtocolError(-32023, 'Event not found.', { kind: 'event' });
41
+ const id = params.arguments.watch_id;
42
+ try {
43
+ const { rows, ...state } = store.poll(id, params.cursor ?? null, Math.min(params.maxEvents ?? 20, 50), params.maxAgeMs);
44
+ return {
45
+ ...state,
46
+ nextPollMs: 30_000,
47
+ events: rows.map(row => ({
48
+ eventId: row.post_id,
49
+ name: eventName,
50
+ timestamp: new Date(row.observed_at).toISOString(),
51
+ data: { watch_id: id, post_id: row.post_id, url: row.url },
52
+ })),
53
+ };
54
+ } catch (error) {
55
+ if (error instanceof InvalidWatchRequest) throw new ProtocolError(-32602, error.message);
56
+ throw error;
57
+ }
58
+ });
59
+ }
60
+
61
+ /** The Events binding adds Mcp-Name to the SDK's core routing-header checks. */
62
+ export async function validateEventHeaders(request: Request): Promise<Response | undefined> {
63
+ if (request.method !== 'POST' || request.headers.get('Mcp-Method') !== 'events/poll') return;
64
+ const body = await request.clone().json().catch(() => undefined);
65
+ const name = body?.method === 'events/poll' ? body.params?.name : undefined;
66
+ if (typeof name !== 'string') return;
67
+ const header = request.headers.get('Mcp-Name');
68
+ const encoded = '=?base64?' + Buffer.from(name).toString('base64') + '?=';
69
+ if (header === name || header === encoded) return;
70
+ const id = typeof body.id === 'string' || typeof body.id === 'number' ? body.id : null;
71
+ return Response.json({ jsonrpc: '2.0', id,
72
+ error: { code: -32020, message: 'Mcp-Name must match the event name.' },
73
+ }, { status: 400 });
74
+ }
75
+
76
+ export async function runDueWatch(
77
+ store: WatchStore,
78
+ options: { signal?: AbortSignal; now?: number; search?: typeof executeSearch; trackCleanup?: (task: Promise<unknown>) => void } = {},
79
+ ) {
80
+ if (options.signal?.aborted) return;
81
+ const watch = store.claim(options.now);
82
+ if (!watch) return;
83
+ try {
84
+ const result = await (options.search ?? executeSearch)({ query: watch.query }, {
85
+ signal: options.signal, trackCleanup: options.trackCleanup,
86
+ });
87
+ if (!options.signal?.aborted) {
88
+ store.record(watch.id, result.status, result.sources.filter(source => source.kind === 'x_post'), options.now);
89
+ }
90
+ } catch (error) {
91
+ if (!options.signal?.aborted) {
92
+ store.record(watch.id, error instanceof HttpError ? error.code : 'SEARCH_ERROR', [], options.now);
93
+ }
94
+ }
95
+ }
96
+
97
+ export function startWatchScheduler(store: WatchStore) {
98
+ const controller = new AbortController();
99
+ const cleanup = new Set<Promise<unknown>>();
100
+ let timer: NodeJS.Timeout | undefined;
101
+ let running: Promise<void>;
102
+ function schedule() {
103
+ if (controller.signal.aborted) return;
104
+ running = runDueWatch(store, {
105
+ signal: controller.signal,
106
+ trackCleanup(task) {
107
+ cleanup.add(task);
108
+ void task.then(() => cleanup.delete(task), () => cleanup.delete(task));
109
+ },
110
+ }).catch(() => { console.error('x-search-mcp watch database operation failed.'); }).finally(() => {
111
+ if (!controller.signal.aborted) {
112
+ timer = setTimeout(schedule, 5000);
113
+ timer.unref();
114
+ }
115
+ });
116
+ }
117
+ schedule();
118
+ return async () => {
119
+ controller.abort();
120
+ clearTimeout(timer);
121
+ await running;
122
+ await Promise.allSettled(cleanup);
123
+ };
124
+ }
@@ -0,0 +1,19 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import type { McpServer } from '@modelcontextprotocol/server';
3
+
4
+ export const evidenceUri = 'ui://x-search/evidence.html';
5
+ const mimeType = 'text/html;profile=mcp-app';
6
+ const ui = { csp: { connectDomains: [], resourceDomains: [], frameDomains: [] } };
7
+ const file = new URL('../evidence.html', import.meta.url);
8
+ let document: Promise<string> | undefined;
9
+
10
+ export function registerEvidenceApp(server: McpServer) {
11
+ server.registerResource('x-search-evidence', evidenceUri, {
12
+ title: 'X Search sources',
13
+ mimeType,
14
+ _meta: { ui },
15
+ }, async uri => {
16
+ document ??= readFile(file, 'utf8');
17
+ return { contents: [{ uri: uri.href, mimeType, text: await document, _meta: { ui } }] };
18
+ });
19
+ }
@@ -13,6 +13,7 @@ export interface HttpServerOptions {
13
13
  allowedHosts?: string[];
14
14
  allowedOrigins?: string[];
15
15
  maxRequestBodyBytes?: number;
16
+ guardRequest?: (request: Request) => Promise<Response | undefined>;
16
17
  }
17
18
 
18
19
  export interface HttpAuthentication {
@@ -109,8 +110,11 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
109
110
  void pending.then(() => { creating.delete(pending); }, () => { creating.delete(pending); });
110
111
  return pending;
111
112
  };
112
- const handler = createMcpHandler(ownedFactory, { legacy: 'stateless', maxRequestBodySize: maxBody });
113
- const nodeHandler = toNodeHandler(handler, { maxRequestBodySize: maxBody });
113
+ const handler = createMcpHandler(ownedFactory, { legacy: 'reject', maxRequestBodySize: maxBody });
114
+ const guard = options.guardRequest;
115
+ const nodeHandler = toNodeHandler(guard ? {
116
+ fetch: async (request, context) => await guard(request) ?? handler.fetch(request, context),
117
+ } : handler, { maxRequestBodySize: maxBody });
114
118
  const requests = new Set<Promise<void>>();
115
119
 
116
120
  async function handleRequest(request: IncomingMessage & { auth?: AuthInfo }, response: ServerResponse) {
@@ -214,8 +218,7 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
214
218
  const stopped = new Promise<void>((resolve, reject) => listener.close(error => error ? reject(error) : resolve()));
215
219
  listener.closeAllConnections();
216
220
  await Promise.allSettled([...creating]);
217
- // The SDK's legacy leg starts per-request teardown without awaiting it.
218
- // Drain every owned product as well as the modern handler's exchanges.
221
+ // Drain owned servers, including accepted credential work, with the HTTP exchanges.
219
222
  await Promise.all([handler.close(), ...[...products].map(product => product.close()), stopped]);
220
223
  await Promise.allSettled([...requests]);
221
224
  })();