@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
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { HttpError } from './http.js';
|
|
3
|
+
const citation = {
|
|
4
|
+
url: z.string(),
|
|
5
|
+
cited_in_answer: z.literal(true).optional(),
|
|
6
|
+
};
|
|
7
|
+
const sourceSchema = z.discriminatedUnion('kind', [
|
|
8
|
+
z.strictObject({ kind: z.literal('x_post'), ...citation, post_id: z.string(), handle: z.string().optional() }),
|
|
9
|
+
z.strictObject({ kind: z.literal('web'), ...citation }),
|
|
10
|
+
]);
|
|
11
|
+
const count = z.number().int().nonnegative();
|
|
12
|
+
export const searchSuccessSchema = z.strictObject({
|
|
13
|
+
status: z.enum(['complete', 'partial', 'unverified']),
|
|
14
|
+
model: z.string(),
|
|
15
|
+
answer: z.string(),
|
|
16
|
+
sources: z.array(sourceSchema),
|
|
17
|
+
truncated: z.boolean(),
|
|
18
|
+
usage: z.strictObject({
|
|
19
|
+
requests: count,
|
|
20
|
+
x_search_calls: count.nullable(),
|
|
21
|
+
x_posts_fetched: count.nullable(),
|
|
22
|
+
x_users_fetched: count.nullable(),
|
|
23
|
+
input_tokens: count.nullable(),
|
|
24
|
+
output_tokens: count.nullable(),
|
|
25
|
+
}),
|
|
26
|
+
elapsed_ms: count,
|
|
27
|
+
});
|
|
28
|
+
const recoverySchema = z.discriminatedUnion('type', [
|
|
29
|
+
z.strictObject({ type: z.literal('cli_login'), command: z.literal('x-search-mcp auth login') }),
|
|
30
|
+
z.strictObject({ type: z.literal('bind_key'), url: z.string() }),
|
|
31
|
+
]);
|
|
32
|
+
const searchFailureSchema = z.strictObject({
|
|
33
|
+
status: z.literal('error'),
|
|
34
|
+
error: z.strictObject({
|
|
35
|
+
code: z.string(),
|
|
36
|
+
message: z.string(),
|
|
37
|
+
http_status: z.number().int().optional(),
|
|
38
|
+
retry_after_ms: count.optional(),
|
|
39
|
+
}),
|
|
40
|
+
action: recoverySchema.optional(),
|
|
41
|
+
});
|
|
42
|
+
const authorizationPendingSchema = z.strictObject({
|
|
43
|
+
status: z.literal('authorization_pending'),
|
|
44
|
+
action: z.strictObject({
|
|
45
|
+
type: z.literal('verify_device'),
|
|
46
|
+
url: z.string(),
|
|
47
|
+
user_code: z.string(),
|
|
48
|
+
expires_at: z.string(),
|
|
49
|
+
}),
|
|
50
|
+
});
|
|
51
|
+
export const searchOutputSchema = z.discriminatedUnion('status', [
|
|
52
|
+
searchSuccessSchema, searchFailureSchema, authorizationPendingSchema,
|
|
53
|
+
]);
|
|
54
|
+
export function searchFailure(cause, settingsUrl) {
|
|
55
|
+
if (!(cause instanceof HttpError)) {
|
|
56
|
+
return { status: 'error', error: { code: 'SEARCH_ERROR', message: 'The search could not be completed.' } };
|
|
57
|
+
}
|
|
58
|
+
const result = {
|
|
59
|
+
status: 'error',
|
|
60
|
+
error: {
|
|
61
|
+
code: cause.code,
|
|
62
|
+
message: cause.message,
|
|
63
|
+
...(cause.status === null ? {} : { http_status: cause.status }),
|
|
64
|
+
...(cause.retryAfterMs === undefined ? {} : { retry_after_ms: cause.retryAfterMs }),
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
if (cause.code === 'AUTH_REQUIRED') {
|
|
68
|
+
result.action = { type: 'cli_login', command: 'x-search-mcp auth login' };
|
|
69
|
+
}
|
|
70
|
+
else if (settingsUrl && ['XAI_KEY_REQUIRED', 'UPSTREAM_AUTH_ERROR'].includes(cause.code)) {
|
|
71
|
+
result.action = { type: 'bind_key', url: settingsUrl };
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
export function searchToolResult(result) {
|
|
76
|
+
// A concise transcript entry keeps the structured answer and sources together
|
|
77
|
+
// without serializing the entire result a second time in the MCP content.
|
|
78
|
+
const text = result.status === 'error' ? result.error.message
|
|
79
|
+
: result.status === 'authorization_pending'
|
|
80
|
+
? `Open ${result.action.url} and verify code ${result.action.user_code}. Retry this search after approving in Grok.`
|
|
81
|
+
: result.sources.length ? `X search returned ${result.sources.length} sources.` : 'X search returned no verifiable sources.';
|
|
82
|
+
return {
|
|
83
|
+
content: [{ type: 'text', text }],
|
|
84
|
+
structuredContent: result,
|
|
85
|
+
...(result.status === 'error' ? { isError: true } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=tool-contract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-contract.js","sourceRoot":"","sources":["../../src/tool-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,QAAQ,GAAG;IACf,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE;IACf,eAAe,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE;CAC5C,CAAC;AACF,MAAM,YAAY,GAAG,CAAC,CAAC,kBAAkB,CAAC,MAAM,EAAE;IAChD,CAAC,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,GAAG,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC9G,CAAC,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,GAAG,QAAQ,EAAE,CAAC;CACxD,CAAC,CAAC;AAEH,MAAM,KAAK,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC;AAC7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AAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACxD,CAAC;AACJ,CAAC"}
|
package/dist/src/types.d.ts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
export type AuthMode = 'auto' | 'api_key' | 'oauth';
|
|
2
2
|
export type ReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh';
|
|
3
|
+
export type SearchDetail = 'concise' | 'detailed';
|
|
3
4
|
export interface Config {
|
|
4
5
|
authMode: AuthMode;
|
|
5
6
|
authFile: string;
|
|
6
7
|
authDir: string;
|
|
7
8
|
oauthClientId: string;
|
|
8
9
|
model: string;
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
deadlineMs: number;
|
|
11
|
+
maxResponseBytes: number;
|
|
11
12
|
maxTurns: number;
|
|
12
13
|
reasoningEffort?: ReasoningEffort;
|
|
13
14
|
apiKey: string | null;
|
|
14
|
-
|
|
15
|
+
logMode: 'off' | 'metadata' | 'debug';
|
|
15
16
|
logDir: string;
|
|
16
17
|
logKeep: number;
|
|
17
18
|
logMaxBytes: number;
|
|
19
|
+
logTotalBytes: number;
|
|
18
20
|
}
|
|
19
21
|
export interface XSearchInput {
|
|
20
22
|
query: string;
|
|
@@ -24,18 +26,7 @@ export interface XSearchInput {
|
|
|
24
26
|
to_date?: string;
|
|
25
27
|
enable_image_understanding?: boolean;
|
|
26
28
|
enable_video_understanding?: boolean;
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
export interface InlineCitation {
|
|
30
|
-
url: string;
|
|
31
|
-
title: string | null;
|
|
32
|
-
start_index: number | null;
|
|
33
|
-
end_index: number | null;
|
|
34
|
-
}
|
|
35
|
-
export interface ServerSideCall {
|
|
36
|
-
call_id: string | null;
|
|
37
|
-
name: string | null;
|
|
38
|
-
arguments: any;
|
|
29
|
+
detail?: SearchDetail;
|
|
39
30
|
}
|
|
40
31
|
export interface CallLogAttempt {
|
|
41
32
|
http_status: number | null;
|
|
@@ -59,34 +50,13 @@ export interface CallLogEntry {
|
|
|
59
50
|
request: unknown;
|
|
60
51
|
attempts: CallLogAttempt[];
|
|
61
52
|
outcome: 'success' | 'error';
|
|
53
|
+
x_search_calls?: number | null;
|
|
62
54
|
error: {
|
|
63
55
|
code: string;
|
|
64
56
|
message: string;
|
|
65
57
|
status: number | null;
|
|
66
58
|
} | null;
|
|
67
59
|
}
|
|
68
|
-
export interface XSearchResult {
|
|
69
|
-
success: boolean;
|
|
70
|
-
provider: 'xai';
|
|
71
|
-
tool: 'x_search';
|
|
72
|
-
model: string;
|
|
73
|
-
query: string;
|
|
74
|
-
credential_source: 'api_key' | 'oauth';
|
|
75
|
-
billing_mode: 'api_metered' | 'subscription_oauth';
|
|
76
|
-
answer: string;
|
|
77
|
-
citations: string[];
|
|
78
|
-
inline_citations: InlineCitation[];
|
|
79
|
-
has_citations: boolean;
|
|
80
|
-
degraded: boolean;
|
|
81
|
-
degraded_reason: string | null;
|
|
82
|
-
search_execution: 'observed' | 'unreported';
|
|
83
|
-
server_side_calls: ServerSideCall[];
|
|
84
|
-
response_status: string;
|
|
85
|
-
incomplete_details: any;
|
|
86
|
-
usage: any;
|
|
87
|
-
warnings: string[];
|
|
88
|
-
log_file: string | null;
|
|
89
|
-
}
|
|
90
60
|
export interface AuthTokens {
|
|
91
61
|
access_token: string;
|
|
92
62
|
refresh_token?: string;
|
package/dist/src/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC;AAEpD,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,MAAM;IACrB,QAAQ,EAAE,QAAQ,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,C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IACnB,oBAAoB,EAAE,sBAAsB,GAAG,UAAU,GAAG,IAAI,CAAC;IACjE,QAAQ,EAAE,OAAO,CAAC;IAClB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,eAAe,EAAE,QAAQ,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,iBAAiB;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,6BAA6B,EAAE,MAAM,CAAC;CACvC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watch-cli.d.ts","sourceRoot":"","sources":["../../src/watch-cli.ts"],"names":[],"mappings":"AAIA,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,QA8B7C"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { WatchStore, watchDatabasePath } from './watch-store.js';
|
|
2
|
+
const usage = 'Usage: x-search-mcp watch add "<query>" --every-minutes <5–1440> --runs <1–48> | watch list | watch remove <id>';
|
|
3
|
+
export function runWatchCommand(args) {
|
|
4
|
+
const [command, value, ...options] = args;
|
|
5
|
+
if (command === '--help' || command === 'help') {
|
|
6
|
+
console.log(usage);
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
const commandValid = (command === 'add' && value && options.length === 4)
|
|
10
|
+
|| (command === 'remove' && value && !options.length)
|
|
11
|
+
|| (command === 'list' && value === undefined);
|
|
12
|
+
if (!commandValid)
|
|
13
|
+
throw new Error(usage);
|
|
14
|
+
const store = new WatchStore(watchDatabasePath());
|
|
15
|
+
try {
|
|
16
|
+
switch (command) {
|
|
17
|
+
case 'list':
|
|
18
|
+
console.log(JSON.stringify(store.list(), null, 2));
|
|
19
|
+
break;
|
|
20
|
+
case 'add': {
|
|
21
|
+
const [flag1, value1, flag2, value2] = options;
|
|
22
|
+
const flags = new Map([[flag1, value1], [flag2, value2]]);
|
|
23
|
+
const every = flags.get('--every-minutes');
|
|
24
|
+
const runs = flags.get('--runs');
|
|
25
|
+
if (!every || !runs || !/^\d+$/.test(every) || !/^\d+$/.test(runs))
|
|
26
|
+
throw new Error(usage);
|
|
27
|
+
console.log(JSON.stringify(store.add(value, Number(every), Number(runs)), null, 2));
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
case 'remove':
|
|
31
|
+
if (!store.remove(value))
|
|
32
|
+
throw new Error('Watch not found.');
|
|
33
|
+
console.log(JSON.stringify({ removed: value }));
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
store.close();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=watch-cli.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watch-cli.js","sourceRoot":"","sources":["../../src/watch-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAEjE,MAAM,KAAK,GAAG,iHAAiH,CAAC;AAEhI,MAAM,UAAU,eAAe,CAAC,IAAc;IAC5C,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1C,IAAI,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,MAAM,EAAE,CAAC;QAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAAC,OAAO;IAAC,CAAC;IAC/E,MAAM,YAAY,GAAG,CAAC,OAAO,KAAK,KAAK,IAAI,KAAK,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC;WACpE,CAAC,OAAO,KAAK,QAAQ,IAAI,KAAK,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;WAClD,CAAC,OAAO,KAAK,MAAM,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC;IACjD,IAAI,CAAC,YAAY;QAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,MAAM,KAAK,GAAG,I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OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBAChD,MAAM;QACV,CAAC;IACH,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { SearchSource } from './tool-contract.js';
|
|
2
|
+
type Watch = {
|
|
3
|
+
id: string;
|
|
4
|
+
query: string;
|
|
5
|
+
interval_ms: number;
|
|
6
|
+
runs_left: number;
|
|
7
|
+
next_run_at: number;
|
|
8
|
+
expires_at: number;
|
|
9
|
+
last_status: string | null;
|
|
10
|
+
};
|
|
11
|
+
type Post = Extract<SearchSource, {
|
|
12
|
+
kind: 'x_post';
|
|
13
|
+
}>;
|
|
14
|
+
type Evidence = {
|
|
15
|
+
seq: number;
|
|
16
|
+
observed_at: number;
|
|
17
|
+
post_id: string;
|
|
18
|
+
url: string;
|
|
19
|
+
};
|
|
20
|
+
export declare class InvalidWatchRequest extends Error {
|
|
21
|
+
}
|
|
22
|
+
export declare function watchDatabasePath(): string;
|
|
23
|
+
export declare class WatchStore {
|
|
24
|
+
private readonly db;
|
|
25
|
+
constructor(file: string);
|
|
26
|
+
add(query: string, intervalMinutes: number, runs: number, now?: number): Watch;
|
|
27
|
+
list(now?: number): Watch[];
|
|
28
|
+
remove(id: string): boolean;
|
|
29
|
+
claim(now?: number): Pick<Watch, 'id' | 'query'> | undefined;
|
|
30
|
+
record(id: string, status: string, posts?: readonly Post[], now?: number): void;
|
|
31
|
+
poll(id: string, cursor: string | null, maxEvents: number, maxAgeMs?: number, now?: number): {
|
|
32
|
+
rows: Evidence[];
|
|
33
|
+
hasMore: boolean;
|
|
34
|
+
truncated: boolean;
|
|
35
|
+
cursor: string;
|
|
36
|
+
};
|
|
37
|
+
private prune;
|
|
38
|
+
close(): void;
|
|
39
|
+
}
|
|
40
|
+
export {};
|
|
41
|
+
//# sourceMappingURL=watch-store.d.ts.map
|
|
@@ -0,0 +1 @@
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;IAkBhF,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,GAAG,SAAa;;;;;;IA4B9F,OAAO,CAAC,KAAK;IAIb,KAAK;CACN"}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { randomBytes, randomUUID, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, fstatSync, mkdirSync, openSync, statSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
6
|
+
import { validateSearchParams } from './search-input.js';
|
|
7
|
+
const day = 86_400_000;
|
|
8
|
+
const retention = 7 * day;
|
|
9
|
+
const columns = 'id, query, interval_ms, runs_left, next_run_at, expires_at, last_status';
|
|
10
|
+
export class InvalidWatchRequest extends Error {
|
|
11
|
+
}
|
|
12
|
+
export function watchDatabasePath() {
|
|
13
|
+
return resolve(process.env.X_SEARCH_EVENTS_DB ?? resolve(homedir(), '.config/x-search-mcp/events/watches.sqlite'));
|
|
14
|
+
}
|
|
15
|
+
function privateFile(file) {
|
|
16
|
+
const directory = dirname(file);
|
|
17
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
18
|
+
const parent = statSync(directory);
|
|
19
|
+
const uid = process.getuid?.();
|
|
20
|
+
if (!parent.isDirectory() || (uid !== undefined && (parent.mode & 0o077 || parent.uid !== uid))) {
|
|
21
|
+
throw new Error('The watch database requires a private, user-owned directory.');
|
|
22
|
+
}
|
|
23
|
+
const fd = openSync(file, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
|
|
24
|
+
try {
|
|
25
|
+
const info = fstatSync(fd);
|
|
26
|
+
if (!info.isFile() || (uid !== undefined && (info.mode & 0o077 || info.uid !== uid))) {
|
|
27
|
+
throw new Error('The watch database must be a private, user-owned file.');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
closeSync(fd);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function cursorFor(key, seq) {
|
|
35
|
+
const position = String(seq);
|
|
36
|
+
const signature = createHmac('sha256', key).update(position).digest('base64url');
|
|
37
|
+
return position + '.' + signature;
|
|
38
|
+
}
|
|
39
|
+
function parseCursor(key, cursor) {
|
|
40
|
+
const seq = Number(cursor.split('.')[0]);
|
|
41
|
+
if (!Number.isSafeInteger(seq) || seq < 0)
|
|
42
|
+
throw new InvalidWatchRequest('Invalid event cursor for this watch.');
|
|
43
|
+
const expected = Buffer.from(cursorFor(key, seq));
|
|
44
|
+
const received = Buffer.from(cursor);
|
|
45
|
+
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
|
|
46
|
+
throw new InvalidWatchRequest('Invalid event cursor for this watch.');
|
|
47
|
+
}
|
|
48
|
+
return seq;
|
|
49
|
+
}
|
|
50
|
+
export class WatchStore {
|
|
51
|
+
db;
|
|
52
|
+
constructor(file) {
|
|
53
|
+
privateFile(file);
|
|
54
|
+
this.db = new DatabaseSync(file);
|
|
55
|
+
try {
|
|
56
|
+
this.db.exec(`
|
|
57
|
+
PRAGMA busy_timeout = 1000;
|
|
58
|
+
PRAGMA foreign_keys = ON;
|
|
59
|
+
PRAGMA secure_delete = ON;
|
|
60
|
+
CREATE TABLE IF NOT EXISTS watches (
|
|
61
|
+
id TEXT PRIMARY KEY, query TEXT NOT NULL, interval_ms INTEGER NOT NULL,
|
|
62
|
+
runs_left INTEGER NOT NULL, next_run_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,
|
|
63
|
+
last_status TEXT, cursor_key TEXT NOT NULL
|
|
64
|
+
) STRICT;
|
|
65
|
+
CREATE TABLE IF NOT EXISTS evidence (
|
|
66
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT, watch_id TEXT NOT NULL REFERENCES watches(id) ON DELETE CASCADE,
|
|
67
|
+
observed_at INTEGER NOT NULL, post_id TEXT NOT NULL, url TEXT NOT NULL,
|
|
68
|
+
UNIQUE(watch_id, post_id)
|
|
69
|
+
) STRICT;
|
|
70
|
+
CREATE INDEX IF NOT EXISTS evidence_by_watch ON evidence(watch_id, seq);
|
|
71
|
+
`);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
this.db.close();
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
add(query, intervalMinutes, runs, now = Date.now()) {
|
|
79
|
+
const input = validateSearchParams({ query });
|
|
80
|
+
const interval = intervalMinutes * 60_000;
|
|
81
|
+
if (!Number.isSafeInteger(intervalMinutes) || intervalMinutes < 5 || intervalMinutes > 1440
|
|
82
|
+
|| !Number.isSafeInteger(runs) || runs < 1 || runs > 48 || runs * interval > retention) {
|
|
83
|
+
throw new Error('Choose an interval of 5–1440 minutes and 1–48 checks within seven days.');
|
|
84
|
+
}
|
|
85
|
+
this.prune(now);
|
|
86
|
+
const id = randomUUID();
|
|
87
|
+
const watch = {
|
|
88
|
+
id, query: input.query, interval_ms: interval, runs_left: runs,
|
|
89
|
+
next_run_at: now + interval, expires_at: now + retention, last_status: null,
|
|
90
|
+
};
|
|
91
|
+
const inserted = this.db.prepare(`
|
|
92
|
+
INSERT INTO watches (id, query, interval_ms, runs_left, next_run_at, expires_at, cursor_key)
|
|
93
|
+
SELECT ?, ?, ?, ?, ?, ?, ?
|
|
94
|
+
WHERE (SELECT count(*) FROM watches) < 64
|
|
95
|
+
AND (SELECT count(*) FROM watches WHERE runs_left > 0 AND expires_at > ?) < 8
|
|
96
|
+
`).run(id, watch.query, interval, runs, watch.next_run_at, watch.expires_at, randomBytes(32).toString('hex'), now);
|
|
97
|
+
if (!inserted.changes)
|
|
98
|
+
throw new Error('Remove an existing watch before adding another.');
|
|
99
|
+
return watch;
|
|
100
|
+
}
|
|
101
|
+
list(now = Date.now()) {
|
|
102
|
+
this.prune(now);
|
|
103
|
+
return this.db.prepare(`SELECT ${columns} FROM watches ORDER BY next_run_at, id`).all();
|
|
104
|
+
}
|
|
105
|
+
remove(id) {
|
|
106
|
+
return this.db.prepare('DELETE FROM watches WHERE id = ?').run(id).changes > 0;
|
|
107
|
+
}
|
|
108
|
+
claim(now = Date.now()) {
|
|
109
|
+
this.prune(now);
|
|
110
|
+
return this.db.prepare(`
|
|
111
|
+
UPDATE watches SET runs_left = runs_left - 1, next_run_at = ? + interval_ms, last_status = 'running'
|
|
112
|
+
WHERE id = (SELECT id FROM watches WHERE runs_left > 0 AND next_run_at <= ? AND expires_at > ?
|
|
113
|
+
ORDER BY next_run_at, id LIMIT 1)
|
|
114
|
+
RETURNING id, query
|
|
115
|
+
`).get(now, now, now);
|
|
116
|
+
}
|
|
117
|
+
record(id, status, posts = [], now = Date.now()) {
|
|
118
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
119
|
+
try {
|
|
120
|
+
const watch = this.db.prepare('UPDATE watches SET last_status = ? WHERE id = ?').run(status, id);
|
|
121
|
+
if (watch.changes) {
|
|
122
|
+
const insert = this.db.prepare(`
|
|
123
|
+
INSERT INTO evidence (watch_id, observed_at, post_id, url) VALUES (?, ?, ?, ?)
|
|
124
|
+
ON CONFLICT(watch_id, post_id) DO NOTHING
|
|
125
|
+
`);
|
|
126
|
+
for (const post of posts.slice(0, 8))
|
|
127
|
+
insert.run(id, now, post.post_id, post.url);
|
|
128
|
+
}
|
|
129
|
+
this.db.exec('COMMIT');
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
this.db.exec('ROLLBACK');
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
poll(id, cursor, maxEvents, maxAgeMs, now = Date.now()) {
|
|
137
|
+
const watch = this.db.prepare('SELECT cursor_key FROM watches WHERE id = ? AND expires_at > ?')
|
|
138
|
+
.get(id, now - retention);
|
|
139
|
+
if (!watch)
|
|
140
|
+
throw new InvalidWatchRequest('Unknown or removed watch.');
|
|
141
|
+
const latest = this.db.prepare('SELECT coalesce(max(seq), 0) AS seq FROM evidence WHERE watch_id = ?')
|
|
142
|
+
.get(id);
|
|
143
|
+
if (cursor === null)
|
|
144
|
+
return { rows: [], cursor: cursorFor(watch.cursor_key, latest.seq), truncated: false, hasMore: false };
|
|
145
|
+
const position = parseCursor(watch.cursor_key, cursor);
|
|
146
|
+
if (position > latest.seq)
|
|
147
|
+
throw new InvalidWatchRequest('Invalid event cursor for this watch.');
|
|
148
|
+
const ageFloor = now - Math.min(maxAgeMs ?? retention, retention);
|
|
149
|
+
const skipped = this.db.prepare(`
|
|
150
|
+
SELECT coalesce(max(seq), 0) AS seq FROM evidence
|
|
151
|
+
WHERE watch_id = ? AND seq > ? AND seq <= ? AND observed_at < ?
|
|
152
|
+
`).get(id, position, latest.seq, ageFloor);
|
|
153
|
+
const start = Math.max(position, skipped.seq);
|
|
154
|
+
const rows = this.db.prepare(`
|
|
155
|
+
SELECT seq, observed_at, post_id, url FROM evidence WHERE watch_id = ? AND seq > ? AND seq <= ?
|
|
156
|
+
ORDER BY seq LIMIT ?
|
|
157
|
+
`).all(id, start, latest.seq, maxEvents + 1);
|
|
158
|
+
const hasMore = rows.length > maxEvents;
|
|
159
|
+
if (hasMore)
|
|
160
|
+
rows.pop();
|
|
161
|
+
return {
|
|
162
|
+
rows, hasMore, truncated: start > position,
|
|
163
|
+
cursor: cursorFor(watch.cursor_key, hasMore ? rows.at(-1).seq : latest.seq),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
prune(now) {
|
|
167
|
+
this.db.prepare('DELETE FROM watches WHERE expires_at <= ?').run(now - retention);
|
|
168
|
+
}
|
|
169
|
+
close() { this.db.close(); }
|
|
170
|
+
}
|
|
171
|
+
//# sourceMappingURL=watch-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"watch-store.js","sourceRoot":"","sources":["../../src/watch-store.ts"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K,GAAG,QAAQ;YAC1C,MAAM,EAAE,SAAS,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;SAC7E,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,GAAW;QACvB,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,2CAA2C,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,SAAS,CAAC,CAAC;IACpF,CAAC;IAED,KAAK,KAAK,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;CAC7B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"evidence.d.ts","sourceRoot":"","sources":["../../ui/evidence.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { App } from '@modelcontextprotocol/ext-apps';
|
|
2
|
+
const app = new App({ name: 'X Search sources', version: '1.0.0' }, {});
|
|
3
|
+
const notice = document.querySelector('#notice');
|
|
4
|
+
const list = document.querySelector('#sources');
|
|
5
|
+
const filter = document.querySelector('#filter');
|
|
6
|
+
const useSelected = document.querySelector('#use');
|
|
7
|
+
const authorization = document.querySelector('#authorization');
|
|
8
|
+
const controls = document.querySelector('#controls');
|
|
9
|
+
const status = document.querySelector('#status');
|
|
10
|
+
let sources = [];
|
|
11
|
+
let verificationUrl;
|
|
12
|
+
let saving = false;
|
|
13
|
+
const selected = new Set();
|
|
14
|
+
function asObject(value) {
|
|
15
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
16
|
+
}
|
|
17
|
+
function httpUrl(value) {
|
|
18
|
+
if (typeof value !== 'string' || value.length > 2048)
|
|
19
|
+
return;
|
|
20
|
+
try {
|
|
21
|
+
const url = new URL(value);
|
|
22
|
+
if (['http:', 'https:'].includes(url.protocol) && !url.username && !url.password)
|
|
23
|
+
return url;
|
|
24
|
+
}
|
|
25
|
+
catch { /* Ignore malformed source data. */ }
|
|
26
|
+
}
|
|
27
|
+
function sourceFrom(value) {
|
|
28
|
+
const item = asObject(value);
|
|
29
|
+
const url = httpUrl(item?.url);
|
|
30
|
+
if (!url || (item?.kind !== 'x_post' && item?.kind !== 'web'))
|
|
31
|
+
return;
|
|
32
|
+
const source = { kind: item.kind, url: url.href };
|
|
33
|
+
if (item.kind === 'x_post') {
|
|
34
|
+
if (url.hostname !== 'x.com' || typeof item.post_id !== 'string'
|
|
35
|
+
|| !/^\d{1,20}$/.test(item.post_id) || !url.pathname.endsWith('/status/' + item.post_id))
|
|
36
|
+
return;
|
|
37
|
+
source.post_id = item.post_id;
|
|
38
|
+
if (typeof item.handle === 'string' && /^[\w]{1,15}$/.test(item.handle))
|
|
39
|
+
source.handle = item.handle;
|
|
40
|
+
}
|
|
41
|
+
if (item.cited_in_answer === true)
|
|
42
|
+
source.cited_in_answer = true;
|
|
43
|
+
return source;
|
|
44
|
+
}
|
|
45
|
+
function updateSelection() {
|
|
46
|
+
useSelected.textContent = selected.size ? `Use selected sources (${selected.size})` : 'Use selected sources';
|
|
47
|
+
useSelected.disabled = saving || selected.size === 0 || !app.getHostCapabilities()?.updateModelContext;
|
|
48
|
+
}
|
|
49
|
+
async function openLink(url) {
|
|
50
|
+
try {
|
|
51
|
+
if (!app.getHostCapabilities()?.openLinks)
|
|
52
|
+
throw new Error('Opening links unavailable');
|
|
53
|
+
const reply = await app.openLink({ url });
|
|
54
|
+
if (reply.isError)
|
|
55
|
+
throw new Error('Opening link declined');
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
status.textContent = 'The host could not open this link.';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function renderSources() {
|
|
62
|
+
const query = filter.value.trim().toLowerCase();
|
|
63
|
+
list.replaceChildren();
|
|
64
|
+
for (const source of sources) {
|
|
65
|
+
const label = source.handle ? '@' + source.handle : new URL(source.url).hostname;
|
|
66
|
+
if (![label, source.post_id, source.url].join(' ').toLowerCase().includes(query))
|
|
67
|
+
continue;
|
|
68
|
+
const row = document.createElement('li');
|
|
69
|
+
const group = document.createElement('label');
|
|
70
|
+
group.className = 'source';
|
|
71
|
+
const check = document.createElement('input');
|
|
72
|
+
check.type = 'checkbox';
|
|
73
|
+
check.checked = selected.has(source.url);
|
|
74
|
+
check.setAttribute('aria-label', source.post_id ? `Select post ${source.post_id} from ${label}` : `Select ${label}`);
|
|
75
|
+
check.addEventListener('change', () => {
|
|
76
|
+
if (check.checked)
|
|
77
|
+
selected.add(source.url);
|
|
78
|
+
else
|
|
79
|
+
selected.delete(source.url);
|
|
80
|
+
status.textContent = '';
|
|
81
|
+
updateSelection();
|
|
82
|
+
});
|
|
83
|
+
const text = document.createElement('span');
|
|
84
|
+
const title = document.createElement('strong');
|
|
85
|
+
title.textContent = label;
|
|
86
|
+
text.append(title, [source.post_id && 'Post ' + source.post_id, source.cited_in_answer && 'Cited in the answer'].filter(Boolean).join(' · '));
|
|
87
|
+
group.append(check, text);
|
|
88
|
+
const open = document.createElement('button');
|
|
89
|
+
open.type = 'button';
|
|
90
|
+
open.textContent = source.kind === 'x_post' ? 'Open post' : 'Open link';
|
|
91
|
+
open.addEventListener('click', () => void openLink(source.url));
|
|
92
|
+
row.append(group, open);
|
|
93
|
+
list.append(row);
|
|
94
|
+
}
|
|
95
|
+
notice.textContent = sources.length
|
|
96
|
+
? `${list.childElementCount} of ${sources.length} sources`
|
|
97
|
+
: 'No source links were returned.';
|
|
98
|
+
if (query && !list.childElementCount && sources.length)
|
|
99
|
+
notice.textContent = 'No sources match the filter.';
|
|
100
|
+
}
|
|
101
|
+
filter.addEventListener('input', renderSources);
|
|
102
|
+
authorization.addEventListener('click', () => { if (verificationUrl)
|
|
103
|
+
void openLink(verificationUrl); });
|
|
104
|
+
useSelected.addEventListener('click', async () => {
|
|
105
|
+
if (saving || !selected.size)
|
|
106
|
+
return;
|
|
107
|
+
saving = true;
|
|
108
|
+
updateSelection();
|
|
109
|
+
const used = sources.filter(source => selected.has(source.url));
|
|
110
|
+
try {
|
|
111
|
+
await app.updateModelContext({ structuredContent: { sources: used } });
|
|
112
|
+
status.textContent = `${used.length} selected sources added to the conversation context.`;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
status.textContent = 'The host could not add the selected sources.';
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
saving = false;
|
|
119
|
+
updateSelection();
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
app.ontoolresult = params => {
|
|
123
|
+
const result = asObject(params.structuredContent);
|
|
124
|
+
authorization.hidden = true;
|
|
125
|
+
verificationUrl = undefined;
|
|
126
|
+
selected.clear();
|
|
127
|
+
status.textContent = '';
|
|
128
|
+
filter.value = '';
|
|
129
|
+
sources = Array.isArray(result?.sources) ? result.sources.slice(0, 24).flatMap(value => sourceFrom(value) ?? []) : [];
|
|
130
|
+
renderSources();
|
|
131
|
+
controls.hidden = list.hidden = !sources.length;
|
|
132
|
+
updateSelection();
|
|
133
|
+
if (result?.status === 'authorization_pending') {
|
|
134
|
+
const action = asObject(result.action);
|
|
135
|
+
const url = httpUrl(action?.url);
|
|
136
|
+
const code = typeof action?.user_code === 'string' ? action.user_code.slice(0, 64) : '';
|
|
137
|
+
if (url?.protocol === 'https:' && (url.hostname === 'x.ai' || url.hostname.endsWith('.x.ai'))) {
|
|
138
|
+
verificationUrl = url.href;
|
|
139
|
+
authorization.hidden = false;
|
|
140
|
+
}
|
|
141
|
+
notice.textContent = `Verify your Grok account${code ? ' with code ' + code : ''}, then repeat the search.`;
|
|
142
|
+
}
|
|
143
|
+
else if (result?.status === 'error') {
|
|
144
|
+
const message = asObject(result.error)?.message;
|
|
145
|
+
notice.textContent = typeof message === 'string' ? message.slice(0, 500) : 'The search could not be completed.';
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
app.ontoolcancelled = () => { notice.textContent = 'Search cancelled.'; };
|
|
149
|
+
void app.connect().catch(() => { notice.textContent = 'Connect to an MCP Apps host to review search sources.'; });
|
|
150
|
+
//# sourceMappingURL=evidence.js.map
|