@scoheart/x-search-mcp 0.3.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 +29 -17
- package/THIRD_PARTY_NOTICES.md +4 -0
- package/TOOL.md +58 -77
- package/dist/evidence-licenses.txt +791 -0
- package/dist/evidence.html +170 -0
- package/dist/package.json +11 -3
- package/dist/src/auth.d.ts.map +1 -1
- package/dist/src/auth.js +67 -57
- 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 +82 -54
- 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 +20 -0
- package/dist/src/device-login.d.ts.map +1 -0
- package/dist/src/device-login.js +110 -0
- package/dist/src/device-login.js.map +1 -0
- 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 +3 -2
- package/dist/src/multi-user/service.js.map +1 -1
- package/dist/src/search-input.d.ts +31 -0
- package/dist/src/search-input.d.ts.map +1 -0
- package/dist/src/search-input.js +102 -0
- package/dist/src/search-input.js.map +1 -0
- package/dist/src/search-response.d.ts +26 -0
- package/dist/src/search-response.d.ts.map +1 -0
- package/dist/src/search-response.js +128 -0
- package/dist/src/search-response.js.map +1 -0
- package/dist/src/search.d.ts +7 -20
- package/dist/src/search.d.ts.map +1 -1
- package/dist/src/search.js +129 -440
- package/dist/src/search.js.map +1 -1
- package/dist/src/server.d.ts +8 -9
- package/dist/src/server.d.ts.map +1 -1
- package/dist/src/server.js +110 -193
- package/dist/src/server.js.map +1 -1
- package/dist/src/tool-contract.d.ts +183 -0
- package/dist/src/tool-contract.d.ts.map +1 -0
- package/dist/src/tool-contract.js +88 -0
- package/dist/src/tool-contract.js.map +1 -0
- 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 +11 -3
- package/server.json +34 -0
- package/src/auth.ts +65 -57
- package/src/call-log.ts +83 -53
- package/src/cli.ts +26 -19
- package/src/config.ts +11 -13
- package/src/device-login.ts +120 -0
- 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 +3 -2
- package/src/search-input.ts +109 -0
- package/src/search-response.ts +122 -0
- package/src/search.ts +131 -476
- package/src/server.ts +114 -207
- package/src/tool-contract.ts +96 -0
- 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/cli.ts
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import {
|
|
4
|
-
import { startHttp } from './http-server.js';
|
|
3
|
+
import { startPersonalHttp, startStdio } from './server.js';
|
|
5
4
|
import { loadHttpOptions } from './http-config.js';
|
|
6
5
|
import { loginWithDeviceCode, getAuthStatus, logout } from './auth.js';
|
|
7
6
|
import { executeSearch } from './search.js';
|
|
8
7
|
import { listCallLogs } from './call-log.js';
|
|
9
8
|
import { loadConfig } from './config.js';
|
|
9
|
+
import { searchFailure } from './tool-contract.js';
|
|
10
|
+
import { authModeSchema } from './search-input.js';
|
|
10
11
|
|
|
11
12
|
export async function runCli(argv = process.argv.slice(2)): Promise<void> {
|
|
12
13
|
const [command, subCommand, ...rest] = argv;
|
|
13
14
|
|
|
14
15
|
if (command === '--help' || command === '-h' || command === 'help'
|
|
15
16
|
|| ((command === 'http' || command === '--http') && argv.slice(1).some(value => value === '--help' || value === '-h'))) {
|
|
16
|
-
console.log(`Usage: x-search-mcp [--stdio] | http [options] | auth <login|status|logout> | config | search "<query>" | logs
|
|
17
|
+
console.log(`Usage: x-search-mcp [--stdio] | http [options] | auth <login|status|logout> | watch <add|list|remove> | config | search "<query>" | logs
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
MCP 2026-07-28 over stdio or Streamable HTTP.
|
|
19
20
|
|
|
20
21
|
HTTP options:
|
|
21
22
|
--host <address> Bind address (default: 127.0.0.1)
|
|
@@ -24,6 +25,8 @@ HTTP options:
|
|
|
24
25
|
--token-file <file> Private file containing the single-account HTTP bearer token
|
|
25
26
|
--allowed-host <hostname> Allow an additional single-account Host hostname; repeatable, no ports
|
|
26
27
|
--allowed-origin <url> Allow an exact browser origin; repeatable
|
|
28
|
+
--interactive-login Enable Grok elicitation for a personal loopback listener
|
|
29
|
+
--events Serve durable MCP Events polling and run configured watches on loopback
|
|
27
30
|
--multi-user Require per-user OAuth and encrypted xAI API key bindings
|
|
28
31
|
--dev-local-key Use a local wrapping key for multi-user development
|
|
29
32
|
|
|
@@ -36,9 +39,16 @@ Multi-user settings use X_SEARCH_MULTI_USER_*; see docs/multi-user.md.`);
|
|
|
36
39
|
|
|
37
40
|
if (command === 'http' || command === '--http') {
|
|
38
41
|
const args = argv.slice(1);
|
|
39
|
-
const
|
|
42
|
+
const managed = args.includes('--multi-user');
|
|
43
|
+
const wantsEvents = args.includes('--events');
|
|
44
|
+
if (managed && wantsEvents) throw new Error('--events requires a personal loopback listener.');
|
|
45
|
+
const service = managed
|
|
40
46
|
? await (await import('./multi-user/cli.js')).startMultiUserCli(args.filter(argument => argument !== '--multi-user'))
|
|
41
|
-
: await
|
|
47
|
+
: await startPersonalHttp({
|
|
48
|
+
...loadHttpOptions(args.filter(argument => argument !== '--interactive-login' && argument !== '--events')),
|
|
49
|
+
interactiveLogin: args.includes('--interactive-login'),
|
|
50
|
+
eventsDatabase: wantsEvents ? (await import('./watch-store.js')).watchDatabasePath() : undefined,
|
|
51
|
+
});
|
|
42
52
|
const stop = () => {
|
|
43
53
|
void service.close().catch(() => {
|
|
44
54
|
console.error('Could not shut down the HTTP MCP service cleanly');
|
|
@@ -60,6 +70,11 @@ Multi-user settings use X_SEARCH_MULTI_USER_*; see docs/multi-user.md.`);
|
|
|
60
70
|
return;
|
|
61
71
|
}
|
|
62
72
|
|
|
73
|
+
if (command === 'watch') {
|
|
74
|
+
(await import('./watch-cli.js')).runWatchCommand(argv.slice(1));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
63
78
|
// auth command group
|
|
64
79
|
if (command === 'auth') {
|
|
65
80
|
if (subCommand === 'login') {
|
|
@@ -131,7 +146,7 @@ Multi-user settings use X_SEARCH_MULTI_USER_*; see docs/multi-user.md.`);
|
|
|
131
146
|
process.exit(1);
|
|
132
147
|
}
|
|
133
148
|
|
|
134
|
-
let authMode:
|
|
149
|
+
let authMode: string | undefined;
|
|
135
150
|
for (let i = 0; i < rest.length; i++) {
|
|
136
151
|
if (rest[i] === '--auth' && rest[i + 1]) {
|
|
137
152
|
authMode = rest[i + 1];
|
|
@@ -140,19 +155,11 @@ Multi-user settings use X_SEARCH_MULTI_USER_*; see docs/multi-user.md.`);
|
|
|
140
155
|
}
|
|
141
156
|
|
|
142
157
|
try {
|
|
143
|
-
const result = await executeSearch({ query,
|
|
158
|
+
const result = await executeSearch({ query }, { authMode: authModeSchema.optional().parse(authMode) });
|
|
144
159
|
console.log(JSON.stringify(result, null, 2));
|
|
145
|
-
} catch (
|
|
146
|
-
console.error(JSON.stringify(
|
|
147
|
-
|
|
148
|
-
log_file: err.logFile || null,
|
|
149
|
-
error: {
|
|
150
|
-
code: err.code || 'SEARCH_ERROR',
|
|
151
|
-
message: err.message,
|
|
152
|
-
status: err.status || null,
|
|
153
|
-
},
|
|
154
|
-
}, null, 2));
|
|
155
|
-
process.exit(1);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
console.error(JSON.stringify(searchFailure(error), null, 2));
|
|
162
|
+
process.exitCode = 1;
|
|
156
163
|
}
|
|
157
164
|
return;
|
|
158
165
|
}
|
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
|
|
51
|
-
if (Number.
|
|
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
|
|
66
|
-
if (
|
|
67
|
-
|
|
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
|
-
|
|
96
|
-
|
|
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
|
-
|
|
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',
|
|
105
|
-
logMaxBytes: parseBoundedInt(process.env.X_SEARCH_LOG_MAX_BYTES, 'X_SEARCH_LOG_MAX_BYTES', 4096,
|
|
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
|
}
|
|
@@ -0,0 +1,120 @@
|
|
|
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';
|
|
9
|
+
|
|
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
|
+
);
|
|
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
|
+
}
|
|
29
|
+
|
|
30
|
+
return {
|
|
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;
|
|
35
|
+
},
|
|
36
|
+
|
|
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;
|
|
40
|
+
|
|
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
|
+
});
|
|
68
|
+
},
|
|
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
|
+
}
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
async close() {
|
|
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;
|
|
118
|
+
},
|
|
119
|
+
};
|
|
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
|
+
}
|
package/src/http-server.ts
CHANGED
|
@@ -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: '
|
|
113
|
-
const
|
|
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
|
-
//
|
|
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
|
})();
|