@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.
Files changed (105) hide show
  1. package/.env.example +7 -10
  2. package/README.md +29 -17
  3. package/THIRD_PARTY_NOTICES.md +4 -0
  4. package/TOOL.md +58 -77
  5. package/dist/evidence-licenses.txt +791 -0
  6. package/dist/evidence.html +170 -0
  7. package/dist/package.json +11 -3
  8. package/dist/src/auth.d.ts.map +1 -1
  9. package/dist/src/auth.js +67 -57
  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 +82 -54
  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 +20 -0
  22. package/dist/src/device-login.d.ts.map +1 -0
  23. package/dist/src/device-login.js +110 -0
  24. package/dist/src/device-login.js.map +1 -0
  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 +3 -2
  46. package/dist/src/multi-user/service.js.map +1 -1
  47. package/dist/src/search-input.d.ts +31 -0
  48. package/dist/src/search-input.d.ts.map +1 -0
  49. package/dist/src/search-input.js +102 -0
  50. package/dist/src/search-input.js.map +1 -0
  51. package/dist/src/search-response.d.ts +26 -0
  52. package/dist/src/search-response.d.ts.map +1 -0
  53. package/dist/src/search-response.js +128 -0
  54. package/dist/src/search-response.js.map +1 -0
  55. package/dist/src/search.d.ts +7 -20
  56. package/dist/src/search.d.ts.map +1 -1
  57. package/dist/src/search.js +129 -440
  58. package/dist/src/search.js.map +1 -1
  59. package/dist/src/server.d.ts +8 -9
  60. package/dist/src/server.d.ts.map +1 -1
  61. package/dist/src/server.js +110 -193
  62. package/dist/src/server.js.map +1 -1
  63. package/dist/src/tool-contract.d.ts +183 -0
  64. package/dist/src/tool-contract.d.ts.map +1 -0
  65. package/dist/src/tool-contract.js +88 -0
  66. package/dist/src/tool-contract.js.map +1 -0
  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 +11 -3
  85. package/server.json +34 -0
  86. package/src/auth.ts +65 -57
  87. package/src/call-log.ts +83 -53
  88. package/src/cli.ts +26 -19
  89. package/src/config.ts +11 -13
  90. package/src/device-login.ts +120 -0
  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 +3 -2
  97. package/src/search-input.ts +109 -0
  98. package/src/search-response.ts +122 -0
  99. package/src/search.ts +131 -476
  100. package/src/server.ts +114 -207
  101. package/src/tool-contract.ts +96 -0
  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 @@
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,eAAm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,CAAC,CAAC,EAAE,2BAA2B,CAAC;IAC9G,CAAC;SAAM,IAAI,MAAM,EAAE,MAAM,KAAK,OAAO,EAAE,CAAC;QACtC,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;QAChD,MAAM,CAAC,WAAW,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,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.3.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.3.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.3.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,16 +35,19 @@
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",
50
+ "verify:package": "node test/packaged-cli.check.mjs",
45
51
  "prepack": "npm run build",
46
52
  "start": "node dist/bin/x-search-mcp.js"
47
53
  },
@@ -62,8 +68,10 @@
62
68
  },
63
69
  "devDependencies": {
64
70
  "@modelcontextprotocol/client": "2.4.0",
71
+ "@modelcontextprotocol/ext-apps": "2.0.4",
65
72
  "@types/node": "^22.13.0",
66
73
  "@types/proper-lockfile": "^4.1.4",
74
+ "esbuild": "0.28.2",
67
75
  "typescript": "^5.8.0"
68
76
  },
69
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,12 +3,13 @@ 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
 
10
10
  const DISCOVERY_URL = 'https://auth.x.ai/.well-known/openid-configuration';
11
11
  const DEFAULT_SCOPE = 'openid profile email offline_access grok-cli:access api:access';
12
+ const maxDateMilliseconds = 8.64e15;
12
13
  const LOCK_OPTIONS = {
13
14
  realpath: false,
14
15
  stale: 60000,
@@ -22,7 +23,7 @@ const LOCK_OPTIONS = {
22
23
  };
23
24
 
24
25
  function throwIfCancelled(signal?: AbortSignal): void {
25
- if (signal?.aborted) throw new HttpError('cancelled', 'Request was cancelled by client');
26
+ if (signal?.aborted) throw abortError(signal);
26
27
  }
27
28
 
28
29
  /** Keep the cross-process lease, but own its retry timers so a cancelled waiter stops. */
@@ -92,8 +93,7 @@ export async function getDiscoveryMetadata(signal?: AbortSignal): Promise<Discov
92
93
  url: DISCOVERY_URL,
93
94
  method: 'GET',
94
95
  signal,
95
- timeoutSeconds: 30,
96
- retries: 2,
96
+ timeoutMs: 30_000,
97
97
  });
98
98
 
99
99
  const data = typeof res.data === 'object' && res.data !== null ? res.data : {};
@@ -123,7 +123,8 @@ export function extractJwtExpiry(jwtToken: string | undefined): number | null {
123
123
  const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf8');
124
124
  const payload = JSON.parse(payloadJson);
125
125
  if (typeof payload.exp === 'number') {
126
- return payload.exp * 1000;
126
+ const expiry = payload.exp * 1000;
127
+ if (expiry > 0 && expiry <= maxDateMilliseconds) return expiry;
127
128
  }
128
129
  } catch {
129
130
  // Return null if unparseable
@@ -133,18 +134,10 @@ export function extractJwtExpiry(jwtToken: string | undefined): number | null {
133
134
 
134
135
  function ensureAuthFileExists(authFilePath: string): void {
135
136
  const dir = path.dirname(authFilePath);
136
- if (!fs.existsSync(dir)) {
137
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
138
- } else {
139
- try {
140
- fs.chmodSync(dir, 0o700);
141
- } catch {
142
- // Best effort chmod
143
- }
144
- }
137
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
145
138
 
146
139
  if (!fs.existsSync(authFilePath)) {
147
- fs.writeFileSync(authFilePath, '', { mode: 0o600 });
140
+ fs.writeFileSync(authFilePath, '', { flag: 'a', mode: 0o600 });
148
141
  } else {
149
142
  try {
150
143
  fs.chmodSync(authFilePath, 0o600);
@@ -164,8 +157,17 @@ export function saveAuthDataAtomic(authFilePath: string, data: AuthRecord): void
164
157
  const tempFilePath = path.join(dir, `.auth.${Date.now()}.${randomSuffix}.tmp`);
165
158
 
166
159
  const content = JSON.stringify(data, null, 2);
167
- fs.writeFileSync(tempFilePath, content, { mode: 0o600, encoding: 'utf8' });
168
- fs.renameSync(tempFilePath, authFilePath);
160
+ try {
161
+ fs.writeFileSync(tempFilePath, content, { mode: 0o600, encoding: 'utf8' });
162
+ fs.renameSync(tempFilePath, authFilePath);
163
+ } catch (error) {
164
+ try {
165
+ fs.rmSync(tempFilePath, { force: true });
166
+ } catch {
167
+ // Preserve the original write error.
168
+ }
169
+ throw error;
170
+ }
169
171
 
170
172
  try {
171
173
  fs.chmodSync(authFilePath, 0o600);
@@ -199,6 +201,38 @@ function invalidDeviceResponse(): HttpError {
199
201
  return new HttpError('DEVICE_LOGIN_INVALID_RESPONSE', 'xAI returned invalid device authorization data.');
200
202
  }
201
203
 
204
+ function isOAuthToken(value: unknown): value is string {
205
+ return typeof value === 'string' && value.length > 0 && !/[\s\x00-\x1f\x7f]/.test(value);
206
+ }
207
+
208
+ function parseTokenGrant(payload: unknown, invalidResponse: () => HttpError): Pick<AuthRecord, 'tokens' | 'expires_at'> {
209
+ if (!payload || typeof payload !== 'object') throw invalidResponse();
210
+ const data = payload as Record<string, unknown>;
211
+ const accessToken = data.access_token;
212
+ const refreshToken = data.refresh_token ?? '';
213
+ if (!isOAuthToken(accessToken) || (refreshToken !== '' && !isOAuthToken(refreshToken))) {
214
+ throw invalidResponse();
215
+ }
216
+
217
+ const now = Date.now();
218
+ const rawSeconds = data.expires_in;
219
+ let expiresAt: number;
220
+ if (rawSeconds === undefined || rawSeconds === null) {
221
+ expiresAt = extractJwtExpiry(accessToken) ?? now + 3_600_000;
222
+ } else {
223
+ const seconds = typeof rawSeconds === 'string' && /^\d+(?:\.\d+)?$/.test(rawSeconds.trim())
224
+ ? Number(rawSeconds) : rawSeconds;
225
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) throw invalidResponse();
226
+ expiresAt = now + seconds * 1000;
227
+ }
228
+ if (expiresAt <= now || expiresAt > maxDateMilliseconds) throw invalidResponse();
229
+
230
+ return {
231
+ tokens: { access_token: accessToken, ...(refreshToken ? { refresh_token: refreshToken } : {}) },
232
+ expires_at: expiresAt,
233
+ };
234
+ }
235
+
202
236
  function verifyBrowserUrl(value: unknown, deviceCode: string): string {
203
237
  if (typeof value === 'string') {
204
238
  try {
@@ -231,8 +265,7 @@ export async function startDeviceFlow(signal?: AbortSignal) {
231
265
  },
232
266
  body: deviceParams.toString(),
233
267
  signal,
234
- timeoutSeconds: 30,
235
- retries: 0,
268
+ timeoutMs: 30_000,
236
269
  });
237
270
 
238
271
  const deviceData = deviceRes.data;
@@ -280,8 +313,7 @@ export async function startDeviceFlow(signal?: AbortSignal) {
280
313
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
281
314
  body: tokenParams.toString(),
282
315
  signal,
283
- timeoutSeconds: Math.min(30, Math.ceil((expiresAt - Date.now()) / 1000)),
284
- retries: 0,
316
+ timeoutMs: Math.min(30_000, Math.max(1, expiresAt - Date.now())),
285
317
  });
286
318
  } catch (error) {
287
319
  const code = oauthErrorCode(error);
@@ -301,22 +333,11 @@ export async function startDeviceFlow(signal?: AbortSignal) {
301
333
  throw error;
302
334
  }
303
335
 
304
- const tokenData = response.data;
305
- if (typeof tokenData?.access_token !== 'string' || !tokenData.access_token) {
306
- throw invalidDeviceResponse();
307
- }
308
- const tokenExpiresAt = tokenData.expires_in
309
- ? Date.now() + tokenData.expires_in * 1000
310
- : extractJwtExpiry(tokenData.access_token) || Date.now() + 3600 * 1000;
311
336
  const record: AuthRecord = {
312
337
  version: 1,
313
338
  client_id: config.oauthClientId,
314
339
  token_endpoint: discovery.token_endpoint,
315
- tokens: {
316
- access_token: tokenData.access_token,
317
- refresh_token: tokenData.refresh_token,
318
- },
319
- expires_at: tokenExpiresAt,
340
+ ...parseTokenGrant(response.data, invalidDeviceResponse),
320
341
  };
321
342
 
322
343
  throwIfCancelled(signal);
@@ -357,7 +378,7 @@ export async function loginWithDeviceCode(): Promise<void> {
357
378
 
358
379
  async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath: string): Promise<string> {
359
380
  const refreshToken = authData?.tokens?.refresh_token;
360
- if (!refreshToken) {
381
+ if (!isOAuthToken(refreshToken)) {
361
382
  throw oauthRequired('No Grok OAuth refresh token is available.');
362
383
  }
363
384
 
@@ -379,9 +400,7 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
379
400
  'Content-Type': 'application/x-www-form-urlencoded',
380
401
  },
381
402
  body: refreshParams.toString(),
382
- timeoutSeconds: 30,
383
- retries: 0,
384
- isRefresh: true, // Auto-retry strictly disabled for refresh requests
403
+ timeoutMs: 30_000,
385
404
  }).catch((error: unknown) => {
386
405
  if (error instanceof HttpError && oauthErrorCode(error) === 'invalid_grant') {
387
406
  throw oauthRequired('xAI rejected the Grok OAuth refresh grant.', error.status);
@@ -389,26 +408,15 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
389
408
  throw error;
390
409
  });
391
410
 
392
- const data = res.data;
393
- if (!data || !data.access_token) {
394
- throw new Error('Token refresh response did not contain an access_token');
395
- }
396
-
397
- let expiresAt = data.expires_in ? Date.now() + data.expires_in * 1000 : null;
398
- if (!expiresAt) {
399
- expiresAt = extractJwtExpiry(data.access_token);
400
- }
401
- if (!expiresAt) {
402
- expiresAt = Date.now() + 3600 * 1000;
403
- }
404
-
411
+ const grant = parseTokenGrant(res.data, () =>
412
+ new HttpError('OAUTH_INVALID_TOKEN_RESPONSE', 'xAI returned an invalid OAuth token response.', res.status));
405
413
  const updatedRecord: AuthRecord = {
406
414
  ...authData,
415
+ ...grant,
407
416
  tokens: {
408
- access_token: data.access_token,
409
- refresh_token: data.refresh_token || refreshToken,
417
+ access_token: grant.tokens.access_token,
418
+ refresh_token: grant.tokens.refresh_token ?? refreshToken,
410
419
  },
411
- expires_at: expiresAt,
412
420
  };
413
421
 
414
422
  saveAuthDataAtomic(authFilePath, updatedRecord);
@@ -425,7 +433,7 @@ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<st
425
433
  const authFilePath = config.authFile;
426
434
 
427
435
  let authData = readAuthData(authFilePath);
428
- if (!authData || !authData.tokens || !authData.tokens.access_token) {
436
+ if (!authData || !isOAuthToken(authData.tokens?.access_token)) {
429
437
  throw oauthRequired('No Grok OAuth credential is available.');
430
438
  }
431
439
 
@@ -442,7 +450,7 @@ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<st
442
450
  throwIfCancelled(signal);
443
451
  authData = readAuthData(authFilePath);
444
452
  const updatedRemaining = (authData?.expires_at || 0) - Date.now();
445
- if (updatedRemaining > 120_000 && authData?.tokens?.access_token) {
453
+ if (updatedRemaining > 120_000 && isOAuthToken(authData?.tokens?.access_token)) {
446
454
  return authData.tokens.access_token;
447
455
  }
448
456
 
@@ -476,7 +484,7 @@ export async function forceRefreshToken(rejectedAccessToken: string, signal?: Ab
476
484
  throw oauthRequired('The Grok OAuth credential is missing or corrupted.');
477
485
  }
478
486
 
479
- if (authData.tokens.access_token && authData.tokens.access_token !== rejectedAccessToken) {
487
+ if (isOAuthToken(authData.tokens.access_token) && authData.tokens.access_token !== rejectedAccessToken) {
480
488
  return authData.tokens.access_token;
481
489
  }
482
490
 
@@ -496,7 +504,7 @@ export function getAuthStatus(): AuthStatus {
496
504
  const authData = readAuthData(config.authFile);
497
505
 
498
506
  const hasApiKey = Boolean(config.apiKey);
499
- const hasOAuth = Boolean(authData?.tokens?.access_token);
507
+ const hasOAuth = isOAuthToken(authData?.tokens?.access_token);
500
508
 
501
509
  const expiry = new Date(authData?.expires_at ?? NaN);
502
510
  const oauthExpiresAt = hasOAuth && Number.isFinite(expiry.getTime()) ? expiry.toISOString() : null;
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',
@@ -21,13 +21,21 @@ const SENSITIVE_KEYS = new Set([
21
21
  const BEARER = /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi;
22
22
  const XAI_KEY = /xai-[A-Za-z0-9_-]{16,}/g;
23
23
 
24
+ function redactText(value: string): string {
25
+ return value.replace(BEARER, 'Bearer [redacted]').replace(XAI_KEY, 'xai-[redacted]');
26
+ }
27
+
28
+ function redactLogError(error: CallLogEntry['error']): CallLogEntry['error'] {
29
+ return error && { code: redactText(error.code), message: redactText(error.message), status: error.status };
30
+ }
31
+
24
32
  /**
25
33
  * Remove credential-shaped values before a call log is written.
26
34
  * Post text is preserved; only known secret keys and token formats are replaced.
27
35
  */
28
36
  export function redactForLog(value: unknown, seen = new WeakSet<object>()): unknown {
29
37
  if (typeof value === 'string') {
30
- return value.replace(BEARER, 'Bearer [redacted]').replace(XAI_KEY, 'xai-[redacted]');
38
+ return redactText(value);
31
39
  }
32
40
  if (value === null || typeof value !== 'object') {
33
41
  return value;
@@ -39,7 +47,7 @@ export function redactForLog(value: unknown, seen = new WeakSet<object>()): unkn
39
47
  if (Array.isArray(value)) {
40
48
  return value.map((item) => redactForLog(item, seen));
41
49
  }
42
- const output: Record<string, unknown> = {};
50
+ const output: Record<string, unknown> = Object.create(null);
43
51
  for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
44
52
  output[key] = SENSITIVE_KEYS.has(key.toLowerCase()) ? '[redacted]' : redactForLog(item, seen);
45
53
  }
@@ -69,54 +77,81 @@ function stamp(): string {
69
77
  return new Date().toISOString().replace(/[-:]/g, '').replace('.', '');
70
78
  }
71
79
 
72
- async function pruneCallLogs(dir: string, keep: number): Promise<void> {
73
- if (keep <= 0) return;
74
- const names = (await fs.promises.readdir(dir)).filter((name) => /^call-.*\.json$/.test(name));
75
- if (names.length <= keep) return;
76
- const ranked = await Promise.all(names.map(async (name) => {
77
- const full = path.join(dir, name);
78
- const stat = await fs.promises.stat(full);
79
- return { full, mtime: stat.mtimeMs };
80
+ async function callLogPaths(dir: string): Promise<string[]> {
81
+ try {
82
+ const names = await fs.promises.readdir(dir);
83
+ return names.filter(name => /^call-.*\.json$/.test(name)).map(name => path.join(dir, name));
84
+ } catch (error) {
85
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ async function recentCallLogFiles(paths: string[]) {
91
+ const files = await Promise.all(paths.map(async file => {
92
+ try {
93
+ const stat = await fs.promises.lstat(file);
94
+ return stat.isFile() ? { file, bytes: stat.size, mtimeMs: stat.mtimeMs } : null;
95
+ } catch (error) {
96
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
97
+ throw error;
98
+ }
80
99
  }));
81
- ranked.sort((left, right) => right.mtime - left.mtime);
82
- await Promise.all(ranked.slice(keep).map((item) => fs.promises.rm(item.full, { force: true })));
100
+ return files.filter(file => file !== null).sort((left, right) => right.mtimeMs - left.mtimeMs);
101
+ }
102
+
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 })));
83
117
  }
84
118
 
85
119
  /**
86
- * Persist one search call, including the raw upstream body.
120
+ * Persist search timings and counts. Capture request and upstream bodies in debug mode.
87
121
  * Returns the log path, or null when logging is disabled or the write fails.
88
122
  * A write failure must not replace the original search error.
89
123
  */
90
124
  export async function writeCallLog(entry: CallLogEntry): Promise<string | null> {
91
125
  const config = loadConfig();
92
- if (!config.logEnabled) return null;
93
-
94
- const redactedAttempts: CallLogAttempt[] = entry.attempts.map((attempt) => {
95
- const bounded = boundForLog(redactForLog(attempt.raw_response), config.logMaxBytes);
96
- return {
97
- ...attempt,
98
- raw_response: bounded.value,
99
- raw_response_truncated: bounded.truncated,
100
- raw_response_bytes: bounded.bytes,
101
- };
102
- });
126
+ if (config.logMode === 'off') return null;
103
127
  const record = {
104
- schema_version: 1 as const,
128
+ schema_version: 2 as const,
105
129
  id: `call-${stamp()}-${crypto.randomBytes(3).toString('hex')}`,
106
130
  started_at: entry.started_at,
107
131
  completed_at: new Date().toISOString(),
108
132
  elapsed_ms: entry.elapsed_ms,
109
133
  endpoint: entry.endpoint,
110
134
  model: entry.model,
111
- query: entry.query,
112
135
  credential_source: entry.credential_source,
113
136
  billing_mode: entry.billing_mode,
114
- request: redactForLog(entry.request),
115
- attempts: redactedAttempts,
116
- 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
+ })),
117
142
  outcome: entry.outcome,
118
- error: entry.error,
143
+ error: redactLogError(entry.error),
119
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
+ }
120
155
 
121
156
  const dir = config.logDir;
122
157
  const filename = `${record.id}.json`;
@@ -124,39 +159,34 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
124
159
  const temporary = path.join(dir, `.${filename}.${process.pid}.tmp`);
125
160
  try {
126
161
  await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
127
- await fs.promises.chmod(dir, 0o700);
128
- await fs.promises.writeFile(temporary, JSON.stringify(record, null, 2), { mode: 0o600 });
162
+ await fs.promises.writeFile(temporary, serialized, { mode: 0o600 });
129
163
  await fs.promises.chmod(temporary, 0o600);
130
164
  await fs.promises.rename(temporary, destination);
131
- await fs.promises.chmod(destination, 0o600);
132
- await pruneCallLogs(dir, config.logKeep);
133
- return destination;
134
- } catch (err: any) {
135
- console.error(`x-search-mcp call_log_error=${err?.message || 'failed to write call log'}`);
165
+ } catch (error) {
166
+ const message = error instanceof Error ? redactText(error.message) : 'failed to write call log';
167
+ console.error(`x-search-mcp call_log_error=${message}`);
136
168
  await fs.promises.rm(temporary, { force: true }).catch(() => undefined);
137
169
  return null;
138
170
  }
171
+ try {
172
+ await pruneCallLogs(dir, config.logKeep, config.logTotalBytes);
173
+ } catch (error) {
174
+ const message = error instanceof Error ? redactText(error.message) : 'failed to prune call logs';
175
+ console.error(`x-search-mcp call_log_prune_error=${message}`);
176
+ }
177
+ return destination;
139
178
  }
140
179
 
141
- 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) {
142
181
  const config = loadConfig();
143
182
  const bounded = Math.max(1, Math.min(limit, 100));
144
- let names: string[] = [];
145
- try {
146
- names = (await fs.promises.readdir(config.logDir)).filter((name) => /^call-.*\.json$/.test(name));
147
- } catch (err: any) {
148
- if (err?.code !== 'ENOENT') throw err;
149
- }
150
- const ranked = await Promise.all(names.map(async (name) => {
151
- const full = path.join(config.logDir, name);
152
- const stat = await fs.promises.stat(full);
153
- return { file: full, bytes: stat.size, mtimeMs: stat.mtimeMs, mtime: stat.mtime.toISOString() };
154
- }));
155
- ranked.sort((left, right) => right.mtimeMs - left.mtimeMs);
183
+ const ranked = await recentCallLogFiles(await callLogPaths(config.logDir));
156
184
  return {
157
- enabled: config.logEnabled,
185
+ mode: config.logMode,
158
186
  directory: config.logDir,
159
187
  keep: config.logKeep,
160
- files: ranked.slice(0, bounded).map(({ file, bytes, mtime }) => ({ file, bytes, mtime })),
188
+ total_bytes_limit: config.logTotalBytes,
189
+ files: ranked.slice(0, bounded).map(({ file, bytes, mtimeMs }) =>
190
+ ({ file, bytes, mtime: new Date(mtimeMs).toISOString() })),
161
191
  };
162
192
  }