@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
@@ -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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evidence.js","sourceRoot":"","sources":["../../ui/evidence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AAIrD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;AACxE,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAuB,SAAS,CAAE,CAAC;AACxE,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAmB,UAAU,CAAE,CAAC;AACnE,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAmB,SAAS,CAAE,CAAC;AACpE,MAAM,WAAW,GAAG,QAAQ,CAAC,aAAa,CAAoB,MAAM,CAAE,CAAC;AACvE,MAAM,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAoB,gBAAgB,CAAE,CAAC;AACnF,MAAM,QAAQ,GAAG,QAAQ,CAAC,aAAa,CAAiB,WAAW,CAAE,CAAC;AACtE,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAuB,SAAS,CAAE,CAAC;AACxE,IAAI,OAAO,GAAa,EAAE,CAAC;AAC3B,IAAI,eAAmC,CAAC;AACxC,IAAI,MAAM,GAAG,KAAK,CAAC;AACnB,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;AAEnC,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,SAAS,CAAC;AACpH,CAAC;AAED,SAAS,OAA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,CAAC,CAAC,oCAAoC,CAAC;IAClH,CAAC;AACH,CAAC,CAAC;AAEF,GAAG,CAAC,eAAe,GAAG,GAAG,EAAE,GAAG,MAAM,CAAC,WAAW,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;AAC1E,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,WAAW,GAAG,uDAAuD,CAAC,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,40 @@
1
+ # MCP Apps 与 MCP Events
2
+
3
+ ## 引用审阅
4
+
5
+ 支持 MCP Apps 的宿主会在调用 `x_search` 后加载 `ui://x-search/evidence.html`。可以按账号、帖子 ID 和网站筛选,打开原帖,再选择要加入对话上下文的来源。界面只使用现有结果。只有点击「Use selected sources」才会将所选来源通过 `ui/update-model-context` 交给宿主。
6
+
7
+ 界面使用同一份 `structuredContent.sources`,以沙箱资源分发并声明空的网络、资源和 iframe 域列表。原帖由宿主通过 `ui/open-link` 打开。宿主需要分别支持 MCP 2026-07-28 和 Apps。[Apps 规范](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx)
8
+
9
+ ## 观察公开证据
10
+
11
+ 在本机添加观察规则,显式给定间隔和尝试次数。CLI 返回一条记录和可用于订阅的 `id`。HTTP 仍要求以独立的服务 Bearer 凭据连接。
12
+
13
+ ```sh
14
+ x-search-mcp watch add "Grok release announcements" --every-minutes 15 --runs 8
15
+ x-search-mcp watch list
16
+ x-search-mcp http --events
17
+ ```
18
+
19
+ 规则在首个间隔到期后执行。同一监听器一次执行一个观察,重启后捡起到期规则,每次检查消耗一次预算,即使上游失败。支持 5 到 1440 分钟的间隔、每条最多 48 次及最长 7 天。每次成功搜索只记录新出现的 X 帖子 ID 与规范链接。结果代表搜索发现的证据。
20
+
21
+ 通过 `x-search-mcp watch remove <id>` 删除规则和结果。可用 `X_SEARCH_EVENTS_DB` 指向私有目录内的数据库文件。默认文件是 `~/.config/x-search-mcp/events/watches.sqlite`。观察器在带有 `--events` 的个人回环 HTTP 监听器上运行。
22
+
23
+ ### MCP Events 客户端
24
+
25
+ `server/discover` 宣告 `io.modelcontextprotocol/events`,`events/list` 返回事件类型、参数 schema、结果 schema 和 `poll` 投递模式。以 `events/poll` 订阅,使用事件名和对应规则 ID。
26
+
27
+ ```json
28
+ {
29
+ "name": "x_search.evidence_found",
30
+ "arguments": { "watch_id": "replace-with-watch-id" },
31
+ "cursor": null,
32
+ "maxEvents": 20
33
+ }
34
+ ```
35
+
36
+ 第一个 `null` 游标从当前进度开始。保存结果的 `cursor`,下一次请求带回。如果 `hasMore` 为 true,可以立即翻页。否则按 `nextPollMs` 等待。默认可重放最近七天,通过 `maxAgeMs` 可进一步缩短窗口,跳过历史时会返回 `truncated: true`。HTTP polling 依照规范发送 `Mcp-Name: x_search.evidence_found`。观察规则配置保存在服务端,订阅游标由客户端保存。[Events Beta 规范](https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx)
37
+
38
+ ## 后续扩展
39
+
40
+ 有 X Post Lookup 权限后,可以在界面按帖子 ID 加载原文并验证删除、限流与隔离行为。需要托管多用户观察时,再为各主体分配独立规则、凭据与预算。目标宿主采用签名 webhook 时,单独验证回调签名、续期和退订。[X Post Lookup](https://docs.x.com/x-api/posts/lookup/introduction) · [Events 客户端矩阵](https://modelcontextprotocol.io/extensions/client-matrix)
@@ -1,8 +1,7 @@
1
- [mcp_servers.x-search]
2
- command = "npx"
3
- args = ["--yes", "@scoheart/x-search-mcp@0.4.0"]
4
- tool_timeout_sec = 600
1
+ [features]
2
+ mcp_2026_07_28 = true
5
3
 
6
- [mcp_servers.x-search.env]
7
- X_SEARCH_AUTH_MODE = "auto"
8
- X_SEARCH_MODEL = "grok-4.5"
4
+ [mcp_servers.x-search]
5
+ url = "http://127.0.0.1:8000/mcp"
6
+ bearer_token_env_var = "X_SEARCH_HTTP_TOKEN"
7
+ tool_timeout_sec = 120
package/examples/mcp.json CHANGED
@@ -2,15 +2,11 @@
2
2
  "mcpServers": {
3
3
  "x-search": {
4
4
  "command": "npx",
5
- "args": [
6
- "--yes",
7
- "@scoheart/x-search-mcp@0.4.0"
8
- ],
5
+ "args": ["--yes", "@scoheart/x-search-mcp@0.6.0"],
9
6
  "env": {
10
7
  "X_SEARCH_AUTH_MODE": "auto",
11
8
  "X_SEARCH_MODEL": "grok-4.5"
12
- },
13
- "timeout": 600
9
+ }
14
10
  }
15
11
  }
16
12
  }
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@scoheart/x-search-mcp",
3
- "version": "0.4.0",
4
- "description": "Independent MCP service for x_search, inspired by Hermes Agent",
3
+ "version": "0.6.0",
4
+ "mcpName": "io.github.scoheart/x-search-mcp",
5
+ "description": "Search X with Grok, review sources with MCP Apps, and poll durable evidence events",
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "git+https://github.com/Scoheart/x-search-mcp.git"
@@ -12,6 +13,8 @@
12
13
  },
13
14
  "keywords": [
14
15
  "mcp",
16
+ "mcp-apps",
17
+ "mcp-events",
15
18
  "x-search",
16
19
  "xai",
17
20
  "grok",
@@ -32,15 +35,17 @@
32
35
  "THIRD_PARTY_NOTICES.md",
33
36
  "examples",
34
37
  "docs/multi-user.md",
38
+ "docs/events-and-apps.md",
35
39
  ".env.example",
36
40
  "README.md",
41
+ "server.json",
37
42
  "tsconfig.json"
38
43
  ],
39
44
  "engines": {
40
45
  "node": ">=22.19.0"
41
46
  },
42
47
  "scripts": {
43
- "build": "tsc",
48
+ "build": "tsc && node scripts/build-app.mjs",
44
49
  "test": "npm run build && node --test test/*.test.mjs",
45
50
  "verify:package": "node test/packaged-cli.check.mjs",
46
51
  "prepack": "npm run build",
@@ -63,8 +68,10 @@
63
68
  },
64
69
  "devDependencies": {
65
70
  "@modelcontextprotocol/client": "2.4.0",
71
+ "@modelcontextprotocol/ext-apps": "2.0.4",
66
72
  "@types/node": "^22.13.0",
67
73
  "@types/proper-lockfile": "^4.1.4",
74
+ "esbuild": "0.28.2",
68
75
  "typescript": "^5.8.0"
69
76
  },
70
77
  "license": "MIT"
package/server.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.scoheart/x-search-mcp",
4
+ "title": "X Search",
5
+ "description": "Search X with Grok, review sources with MCP Apps, and poll durable evidence events",
6
+ "repository": {
7
+ "url": "https://github.com/Scoheart/x-search-mcp",
8
+ "source": "github"
9
+ },
10
+ "version": "0.6.0",
11
+ "packages": [
12
+ {
13
+ "registryType": "npm",
14
+ "identifier": "@scoheart/x-search-mcp",
15
+ "version": "0.6.0",
16
+ "transport": { "type": "stdio" },
17
+ "environmentVariables": [
18
+ {
19
+ "name": "X_SEARCH_AUTH_MODE",
20
+ "description": "Choose auto, api_key, or oauth.",
21
+ "format": "string",
22
+ "isRequired": false
23
+ },
24
+ {
25
+ "name": "XAI_API_KEY",
26
+ "description": "Optional key for xAI API billing. Personal Grok sign-in is also available.",
27
+ "format": "string",
28
+ "isSecret": true,
29
+ "isRequired": false
30
+ }
31
+ ]
32
+ }
33
+ ]
34
+ }
package/src/auth.ts CHANGED
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import crypto from 'node:crypto';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  import lockfile from 'proper-lockfile';
6
- import { sendHttpRequest, HttpError, type SendHttpResponse } from './http.js';
6
+ import { sendHttpRequest, HttpError, abortError, type SendHttpResponse } from './http.js';
7
7
  import { loadConfig } from './config.js';
8
8
  import type { AuthRecord, AuthStatus, DiscoveryMetadata } from './types.js';
9
9
 
@@ -23,7 +23,7 @@ const LOCK_OPTIONS = {
23
23
  };
24
24
 
25
25
  function throwIfCancelled(signal?: AbortSignal): void {
26
- if (signal?.aborted) throw new HttpError('cancelled', 'Request was cancelled by client');
26
+ if (signal?.aborted) throw abortError(signal);
27
27
  }
28
28
 
29
29
  /** Keep the cross-process lease, but own its retry timers so a cancelled waiter stops. */
@@ -93,8 +93,7 @@ export async function getDiscoveryMetadata(signal?: AbortSignal): Promise<Discov
93
93
  url: DISCOVERY_URL,
94
94
  method: 'GET',
95
95
  signal,
96
- timeoutSeconds: 30,
97
- retries: 2,
96
+ timeoutMs: 30_000,
98
97
  });
99
98
 
100
99
  const data = typeof res.data === 'object' && res.data !== null ? res.data : {};
@@ -266,8 +265,7 @@ export async function startDeviceFlow(signal?: AbortSignal) {
266
265
  },
267
266
  body: deviceParams.toString(),
268
267
  signal,
269
- timeoutSeconds: 30,
270
- retries: 0,
268
+ timeoutMs: 30_000,
271
269
  });
272
270
 
273
271
  const deviceData = deviceRes.data;
@@ -315,8 +313,7 @@ export async function startDeviceFlow(signal?: AbortSignal) {
315
313
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
316
314
  body: tokenParams.toString(),
317
315
  signal,
318
- timeoutSeconds: Math.min(30, Math.ceil((expiresAt - Date.now()) / 1000)),
319
- retries: 0,
316
+ timeoutMs: Math.min(30_000, Math.max(1, expiresAt - Date.now())),
320
317
  });
321
318
  } catch (error) {
322
319
  const code = oauthErrorCode(error);
@@ -403,9 +400,7 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
403
400
  'Content-Type': 'application/x-www-form-urlencoded',
404
401
  },
405
402
  body: refreshParams.toString(),
406
- timeoutSeconds: 30,
407
- retries: 0,
408
- isRefresh: true, // Auto-retry strictly disabled for refresh requests
403
+ timeoutMs: 30_000,
409
404
  }).catch((error: unknown) => {
410
405
  if (error instanceof HttpError && oauthErrorCode(error) === 'invalid_grant') {
411
406
  throw oauthRequired('xAI rejected the Grok OAuth refresh grant.', error.status);
package/src/call-log.ts CHANGED
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { loadConfig } from './config.js';
5
- import type { CallLogEntry, CallLogAttempt } from './types.js';
5
+ import type { CallLogEntry } from './types.js';
6
6
 
7
7
  const SENSITIVE_KEYS = new Set([
8
8
  'authorization',
@@ -47,7 +47,7 @@ export function redactForLog(value: unknown, seen = new WeakSet<object>()): unkn
47
47
  if (Array.isArray(value)) {
48
48
  return value.map((item) => redactForLog(item, seen));
49
49
  }
50
- const output: Record<string, unknown> = {};
50
+ const output: Record<string, unknown> = Object.create(null);
51
51
  for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
52
52
  output[key] = SENSITIVE_KEYS.has(key.toLowerCase()) ? '[redacted]' : redactForLog(item, seen);
53
53
  }
@@ -100,50 +100,58 @@ async function recentCallLogFiles(paths: string[]) {
100
100
  return files.filter(file => file !== null).sort((left, right) => right.mtimeMs - left.mtimeMs);
101
101
  }
102
102
 
103
- async function pruneCallLogs(dir: string, keep: number): Promise<void> {
104
- if (keep <= 0) return;
105
- const paths = await callLogPaths(dir);
106
- if (paths.length <= keep) return;
107
- const ranked = await recentCallLogFiles(paths);
108
- await Promise.all(ranked.slice(keep).map(({ file }) => fs.promises.rm(file, { force: true })));
103
+ async function pruneCallLogs(dir: string, keep: number, totalBytes: number): Promise<void> {
104
+ const ranked = await recentCallLogFiles(await callLogPaths(dir));
105
+ let bytes = 0;
106
+ let count = 0;
107
+ const expired: string[] = [];
108
+ for (const item of ranked) {
109
+ if (count < keep && bytes + item.bytes <= totalBytes) {
110
+ bytes += item.bytes;
111
+ count++;
112
+ } else {
113
+ expired.push(item.file);
114
+ }
115
+ }
116
+ await Promise.all(expired.map(file => fs.promises.rm(file, { force: true })));
109
117
  }
110
118
 
111
119
  /**
112
- * Persist one search call, including the raw upstream body.
120
+ * Persist search timings and counts. Capture request and upstream bodies in debug mode.
113
121
  * Returns the log path, or null when logging is disabled or the write fails.
114
122
  * A write failure must not replace the original search error.
115
123
  */
116
124
  export async function writeCallLog(entry: CallLogEntry): Promise<string | null> {
117
125
  const config = loadConfig();
118
- if (!config.logEnabled) return null;
119
-
120
- const redactedAttempts: CallLogAttempt[] = entry.attempts.map((attempt) => {
121
- const bounded = boundForLog(redactForLog(attempt.raw_response), config.logMaxBytes);
122
- return {
123
- ...attempt,
124
- error: redactLogError(attempt.error),
125
- raw_response: bounded.value,
126
- raw_response_truncated: bounded.truncated,
127
- raw_response_bytes: bounded.bytes,
128
- };
129
- });
126
+ if (config.logMode === 'off') return null;
130
127
  const record = {
131
- schema_version: 1 as const,
128
+ schema_version: 2 as const,
132
129
  id: `call-${stamp()}-${crypto.randomBytes(3).toString('hex')}`,
133
130
  started_at: entry.started_at,
134
131
  completed_at: new Date().toISOString(),
135
132
  elapsed_ms: entry.elapsed_ms,
136
133
  endpoint: entry.endpoint,
137
134
  model: entry.model,
138
- query: redactText(entry.query),
139
135
  credential_source: entry.credential_source,
140
136
  billing_mode: entry.billing_mode,
141
- request: redactForLog(entry.request),
142
- attempts: redactedAttempts,
143
- raw_response: redactedAttempts.length > 0 ? redactedAttempts[redactedAttempts.length - 1].raw_response : null,
137
+ requests: entry.attempts.length,
138
+ x_search_calls: entry.x_search_calls ?? null,
139
+ attempts: entry.attempts.map(attempt => ({
140
+ http_status: attempt.http_status, error: redactLogError(attempt.error),
141
+ })),
144
142
  outcome: entry.outcome,
145
143
  error: redactLogError(entry.error),
146
144
  };
145
+ let serialized = JSON.stringify(record);
146
+ if (config.logMode === 'debug') {
147
+ const debug = {
148
+ query: redactText(entry.query),
149
+ request: redactForLog(entry.request),
150
+ responses: entry.attempts.map(attempt => boundForLog(redactForLog(attempt.raw_response), config.logMaxBytes)),
151
+ };
152
+ const bounded = boundForLog(debug, Math.min(config.logMaxBytes, config.logTotalBytes / 4));
153
+ serialized = JSON.stringify({ ...record, debug: bounded.value });
154
+ }
147
155
 
148
156
  const dir = config.logDir;
149
157
  const filename = `${record.id}.json`;
@@ -151,7 +159,7 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
151
159
  const temporary = path.join(dir, `.${filename}.${process.pid}.tmp`);
152
160
  try {
153
161
  await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
154
- await fs.promises.writeFile(temporary, JSON.stringify(record, null, 2), { mode: 0o600 });
162
+ await fs.promises.writeFile(temporary, serialized, { mode: 0o600 });
155
163
  await fs.promises.chmod(temporary, 0o600);
156
164
  await fs.promises.rename(temporary, destination);
157
165
  } catch (error) {
@@ -161,7 +169,7 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
161
169
  return null;
162
170
  }
163
171
  try {
164
- await pruneCallLogs(dir, config.logKeep);
172
+ await pruneCallLogs(dir, config.logKeep, config.logTotalBytes);
165
173
  } catch (error) {
166
174
  const message = error instanceof Error ? redactText(error.message) : 'failed to prune call logs';
167
175
  console.error(`x-search-mcp call_log_prune_error=${message}`);
@@ -169,14 +177,15 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
169
177
  return destination;
170
178
  }
171
179
 
172
- export async function listCallLogs(limit = 20): Promise<{ enabled: boolean; directory: string; keep: number; files: Array<{ file: string; bytes: number; mtime: string }> }> {
180
+ export async function listCallLogs(limit = 20) {
173
181
  const config = loadConfig();
174
182
  const bounded = Math.max(1, Math.min(limit, 100));
175
183
  const ranked = await recentCallLogFiles(await callLogPaths(config.logDir));
176
184
  return {
177
- enabled: config.logEnabled,
185
+ mode: config.logMode,
178
186
  directory: config.logDir,
179
187
  keep: config.logKeep,
188
+ total_bytes_limit: config.logTotalBytes,
180
189
  files: ranked.slice(0, bounded).map(({ file, bytes, mtimeMs }) =>
181
190
  ({ file, bytes, mtime: new Date(mtimeMs).toISOString() })),
182
191
  };
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 { createServer, startStdio } from './server.js';
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
- Default: start the stdio MCP server. Use http (or --http) for native Streamable HTTP.
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 service = args.includes('--multi-user')
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 startHttp(createServer, loadHttpOptions(args));
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: any = undefined;
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, auth_mode: authMode });
158
+ const result = await executeSearch({ query }, { authMode: authModeSchema.optional().parse(authMode) });
144
159
  console.log(JSON.stringify(result, null, 2));
145
- } catch (err: any) {
146
- console.error(JSON.stringify({
147
- success: false,
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
  }