@uniquedivine/mcp-slack 4.5.2 → 4.5.3

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.
@@ -1,186 +1,103 @@
1
1
  # Troubleshooting Guide
2
2
 
3
- Common issues and their solutions.
3
+ Fixes for common problems with `@uniquedivine/mcp-slack`. If none of these
4
+ help, open an issue in
5
+ [Unique-Divine/jiyuu](https://github.com/Unique-Divine/jiyuu/issues) with
6
+ `mcp/slack` in the title.
4
7
 
5
- ---
8
+ ## Install Check
6
9
 
7
- ## Install Flow Sanity Check
8
-
9
- If first-run setup is failing, validate command resolution in a clean directory:
10
+ If first-run setup fails, check command resolution in an empty directory:
10
11
 
11
12
  ```bash
12
- tmpdir="$(mktemp -d)"
13
- cd "$tmpdir"
13
+ cd "$(mktemp -d)"
14
14
  bunx @uniquedivine/mcp-slack --version
15
15
  bunx @uniquedivine/mcp-slack --help
16
16
  bunx @uniquedivine/mcp-slack --doctor
17
17
  ```
18
18
 
19
- Expected:
20
- - `--version` and `--help` exit `0`
21
- - `--doctor` exits with one of:
22
- - `0` ready
23
- - `1` missing credentials
24
- - `2` invalid/expired credentials
25
- - `3` connectivity/runtime issue
26
- - `--status` is read-only and never attempts Chrome extraction.
27
-
28
- If `--version` fails here, the issue is install/runtime path, not Slack credentials.
29
-
30
- ---
19
+ Flag `--doctor` exits `0` when ready, `1` for missing credentials, `2` for
20
+ invalid or expired credentials, and `3` for a connectivity or runtime issue.
21
+ If `--version` fails, the problem is the Bun install or `PATH`, not Slack
22
+ credentials.
31
23
 
32
- ## Hosted Version
24
+ ## Expired Tokens
33
25
 
34
- The hosted version is live at [mcp.revasserlabs.com](https://mcp.revasserlabs.com). Free tier (no card) ships 2,000 requests/mo + 25 AI tool calls/mo + all 5 workflow profile types. Pro at $19/mo (or $190/yr) unlocks unlimited requests and AI tool calls, permanent OAuth (no 2-week token rotation), email support, and 2 workspaces. Team at $49/mo flat (or $490/yr) covers 5 workspaces with shared workflow profiles and 24h support. Safeguard at $199/mo (waitlist only) adds agent approval gates, the scheduled morning catch-up DM at 8am workspace time, and workspace memory — all *(in development)*.
26
+ **Symptom:** Tools return `invalid_auth`, `token_expired`, or
27
+ `slack_auth_expired`.
35
28
 
36
- The OSS package keeps the local-machine path. The hosted version adds the AI brain (smart_search, catch_me_up, triage) — these tools also appear in the OSS package as discoverable upgrade stubs that point at the hosted signup.
29
+ **Cause:** Slack rotates browser session tokens (`xoxc-` and `xoxd-`) every
30
+ one to two weeks.
37
31
 
38
- ---
32
+ The server looks for tokens in this order:
39
33
 
40
- ## DMs Not Showing Up
41
-
42
- **Symptom:** `slack_list_conversations` returns channels but no DMs.
34
+ 1. Environment variables `SLACK_TOKEN` and `SLACK_COOKIE`.
35
+ 2. File `~/.slack-mcp-tokens.json`.
36
+ 3. The macOS Keychain.
37
+ 4. Chrome extraction, on macOS only.
43
38
 
44
- **Cause:** Slack's `conversations.list` API doesn't return IMs when using xoxc browser tokens.
39
+ **Fix on macOS:** With Slack open in a Chrome tab, call tool
40
+ `slack_refresh_tokens`, or run
41
+ `bunx @uniquedivine/mcp-slack --refresh-tokens`.
45
42
 
46
- **Solution:** This is handled automatically. The server discovers DMs by calling `conversations.open` for each user in your workspace. This happens in `lib/handlers.js`.
43
+ **Fix everywhere else:** Chrome auto-refresh runs only on macOS. Sign in to
44
+ Slack in a browser, run `bunx @uniquedivine/mcp-slack --setup`, and paste
45
+ fresh values. [Manual Extraction](SETUP.md#manual-extraction) shows where to
46
+ find them. Then reconnect the MCP server.
47
47
 
48
- If DMs still don't appear:
49
- 1. Check you're requesting the right types: `slack_list_conversations types=im,mpim`
50
- 2. Verify the user exists: `slack_list_users`
48
+ If `SLACK_TOKEN` and `SLACK_COOKIE` are set, they win over the token file.
49
+ Update both or unset both; `--setup` alone has no effect while they are set.
51
50
 
52
- ---
51
+ ## Edit or Delete Refused
53
52
 
54
- ## Rate Limiting Errors
53
+ **`message_too_old`:** Tools `slack_update_message` and
54
+ `slack_delete_message` refuse messages older than 7 days. Set
55
+ `SLACK_MCP_EDIT_DELETE_MAX_AGE_HOURS` on the server to change the window, or
56
+ ask for `slack_update_message_unsafe` or `slack_delete_message_unsafe`, which
57
+ skip only the age check.
55
58
 
56
- **Symptom:** `{"error":"ratelimited"}` in API responses.
59
+ **`unknown_tool` for an `_unsafe` tool over HTTP:** The HTTP server hides
60
+ the `_unsafe` tools unless `SLACK_MCP_ENABLE_UNSAFE_TOOLS=true`.
57
61
 
58
- **Cause:** Slack limits API calls, especially when listing many users/DMs.
59
-
60
- **Solution:** The client (`lib/slack-client.js`) implements automatic retry with exponential backoff:
61
- - First retry: Wait 5 seconds
62
- - Second retry: Wait 10 seconds
63
- - Third retry: Wait 15 seconds
64
-
65
- If you still hit limits, reduce batch sizes:
66
- ```
67
- slack_list_conversations limit=50
68
- ```
69
-
70
- ---
71
-
72
- ## Token Expiration
73
-
74
- **Symptom:** `invalid_auth` or `token_expired` errors.
75
-
76
- **Cause:** Browser tokens (xoxc/xoxd) expire after 1-2 weeks.
77
-
78
- **Solution:** The server has 4 layers of token recovery:
79
-
80
- 1. **Environment variables** - From MCP config (Claude Desktop)
81
- 2. **Token file** - `~/.slack-mcp-tokens.json`
82
- 3. **macOS Keychain** - Encrypted persistent storage
83
- 4. **Chrome auto-extraction** - Fallback when all else fails
84
-
85
- **To refresh tokens:**
86
- ```bash
87
- # Option 1: In Claude Code/Desktop
88
- slack_refresh_tokens
62
+ **`not_own_message` or `text_mismatch`:** The tools act only on your own
63
+ messages, and argument `expected_text` must match the message's current text.
64
+ Re-read the message with `slack_conversations_history` or `slack_get_thread`
65
+ and pass its text.
89
66
 
90
- # Option 2: Package setup wizard
91
- bunx @uniquedivine/mcp-slack --setup
67
+ [API.md](API.md#slack_delete_message) lists every error code.
92
68
 
93
- # Option 3: Diagnostics check
94
- bunx @uniquedivine/mcp-slack --doctor
95
-
96
- # Option 4: Repo CLI
97
- npm run tokens:auto
98
-
99
- # Option 5: Manual
100
- npm run tokens:refresh
101
- ```
102
-
103
- ---
104
-
105
- ## Web Server Issues
106
-
107
- ### Server Stops When Terminal Closes
108
-
109
- **Solution:** Use LaunchAgent for persistence:
110
-
111
- ```bash
112
- # Create LaunchAgent
113
- cat > ~/Library/LaunchAgents/com.slack-web-api.plist << 'EOF'
114
- <?xml version="1.0" encoding="UTF-8"?>
115
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
116
- <plist version="1.0">
117
- <dict>
118
- <key>Label</key>
119
- <string>com.slack-web-api</string>
120
- <key>ProgramArguments</key>
121
- <array>
122
- <string>/Users/YOUR_USERNAME/.bun/bin/bunx</string>
123
- <string>@uniquedivine/mcp-slack@4.5.2</string>
124
- <string>web</string>
125
- </array>
126
- <key>RunAtLoad</key>
127
- <true/>
128
- <key>KeepAlive</key>
129
- <true/>
130
- </dict>
131
- </plist>
132
- EOF
133
-
134
- launchctl load ~/Library/LaunchAgents/com.slack-web-api.plist
135
- ```
136
-
137
- ### API Key Invalid
138
-
139
- The web server generates a unique API key on first run, stored in `~/.slack-mcp-api-key`.
140
-
141
- The key is printed to the console when you start the server:
142
- ```
143
- Dashboard: http://localhost:3000/?key=smcp_xxxxxxxxxxxx
144
- API Key: smcp_xxxxxxxxxxxx
145
- ```
69
+ ## DMs Missing
146
70
 
147
- You can also set a custom key:
148
- ```bash
149
- SLACK_API_KEY=your-custom-key npm run web
150
- ```
151
-
152
- ### Can't Connect to localhost:3000
153
-
154
- Check if the server is running:
155
- ```bash
156
- # Get your API key from ~/.slack-mcp-api-key
157
- curl http://localhost:3000/health -H "Authorization: Bearer $(cat ~/.slack-mcp-api-key)"
158
- ```
71
+ **Symptom:** `slack_list_conversations` returns channels but no DMs.
159
72
 
160
- Check LaunchAgent status:
161
- ```bash
162
- launchctl list | grep slack-web-api
163
- ```
73
+ Slack's `conversations.list` method doesn't return DMs for `xoxc-` tokens. By
74
+ default, `slack_list_conversations` adds DMs only from its cache in file
75
+ `~/.slack-mcp-dm-cache.json`, and the server ignores that cache once it is
76
+ more than 24 hours old. To rebuild it, call the tool with
77
+ `discover_dms: true` and `types: "im,mpim"`. The server then reads the first
78
+ 200 users from `users.list`, calls `conversations.open` for each one, 50 ms
79
+ apart, and saves the DMs it finds.
164
80
 
165
- Check logs:
166
- ```bash
167
- cat /tmp/slack-web-api.log
168
- cat /tmp/slack-web-api.error.log
169
- ```
81
+ Discovery is slow and can hit rate limits. It also calls `conversations.open`
82
+ for users you have never messaged, which can add empty DMs to your Slack
83
+ sidebar.
170
84
 
171
- ### Hosted HTTP `/mcp` Returns 503 or 401
85
+ ## Rate Limits
172
86
 
173
- If you run `bun src/server-http.js`, `/mcp` is protected by default.
87
+ **Symptom:** `ratelimited` errors.
174
88
 
175
- `503 http_auth_token_missing` means you did not set:
89
+ The Slack client in file `lib/slack-client.js` waits for Slack's
90
+ `Retry-After` header, or 5 seconds without one, and retries up to 3 times
91
+ with a longer wait each time. If you still hit limits, lower `limit` on list
92
+ calls.
176
93
 
177
- ```bash
178
- SLACK_MCP_HTTP_AUTH_TOKEN=change-this
179
- ```
94
+ ## HTTP Server Returns 503 or 401
180
95
 
181
- `401 unauthorized` means your request is missing or using the wrong bearer token.
96
+ Endpoint `/mcp` on the HTTP server (`bun src/cli.js http`) requires a bearer
97
+ token.
182
98
 
183
- Example request:
99
+ - `503 http_auth_token_missing`: set `SLACK_MCP_HTTP_AUTH_TOKEN`.
100
+ - `401 unauthorized`: the request has no bearer token or the wrong one.
184
101
 
185
102
  ```bash
186
103
  curl http://localhost:3000/mcp \
@@ -189,101 +106,47 @@ curl http://localhost:3000/mcp \
189
106
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}'
190
107
  ```
191
108
 
192
- For local-only testing (not remote exposure), you can opt out:
193
-
194
- ```bash
195
- SLACK_MCP_HTTP_INSECURE=1 bun src/server-http.js
196
- ```
197
-
198
- ---
199
-
200
- ## Claude Desktop Issues
201
-
202
- ### Slack Tools Not Appearing
203
-
204
- **Symptom:** Claude Desktop doesn't show Slack tools after adding config.
205
-
206
- **Solutions:**
207
-
208
- 1. **Fully restart Claude Desktop:**
209
- - Cmd+Q (don't just close window)
210
- - Reopen the app
211
-
212
- 2. **Check config syntax:**
213
- ```bash
214
- cat ~/Library/Application\ Support/Claude/claude_desktop_config.json | python -m json.tool
215
- ```
216
-
217
- 3. **Check MCP logs:**
218
- ```bash
219
- cat ~/Library/Logs/Claude/mcp-server-slack.log
220
- ```
109
+ For local testing only, `SLACK_MCP_HTTP_INSECURE=1` turns the check off.
221
110
 
222
- 4. **Verify the Bun path:**
223
- ```bash
224
- which bunx
225
- # Use this full path in config
226
- ```
111
+ ## Web Server Problems
227
112
 
228
- ### MCP Server Crashes on Start
113
+ The web server writes its API key to file `~/.slack-mcp-api-key`, and the
114
+ startup log masks all but the first 8 characters. If `SLACK_API_KEY` is set,
115
+ the server uses it instead of the file. This check picks the same key:
229
116
 
230
- **Check the log:**
231
117
  ```bash
232
- tail -50 ~/Library/Logs/Claude/mcp-server-slack.log
118
+ API_KEY="${SLACK_API_KEY:-$(cat ~/.slack-mcp-api-key)}"
119
+ curl http://localhost:3000/health -H "Authorization: Bearer $API_KEY"
233
120
  ```
234
121
 
235
- **Common causes:**
236
- - Bun not found (use the full path, such as `~/.bun/bin/bunx` or `/opt/homebrew/bin/bunx`)
237
- - Missing tokens in env section
238
- - Invalid JSON syntax in config
239
-
240
- ---
241
-
242
- ## Chrome Extraction Fails
243
-
244
- **Symptom:** `slack_refresh_tokens` returns "Could not extract from Chrome"
245
-
246
- **Requirements:**
247
- 1. Google Chrome must be running (not just in Dock)
248
- 2. Have a Slack tab open at `app.slack.com` (not desktop app)
249
- 3. Be logged into Slack in that tab
250
- 4. In Chrome menu, enable `View > Developer > Allow JavaScript from Apple Events`
251
- 5. Grant accessibility permissions to Terminal/Claude
252
-
253
- **Check permissions:**
254
- System Preferences → Privacy & Security → Accessibility → Ensure Terminal is enabled
255
-
256
- ---
257
-
258
- ## Why Browser Tokens Instead of Slack App?
259
-
260
- **Question:** Why not just create a Slack app with proper OAuth?
122
+ To keep it running after the terminal closes on macOS, use the LaunchAgent
123
+ in [WEB-API.md](WEB-API.md#auto-start-on-login).
261
124
 
262
- **Answer:** Slack apps cannot access DMs without explicit OAuth authorization for each conversation. This is by design for privacy.
125
+ ## Tools Missing in Claude Desktop
263
126
 
264
- Browser tokens (xoxc/xoxd) provide the same access you have in Slack's web interface - everything you can see, Claude can see.
127
+ 1. Quit Claude Desktop fully and reopen it.
128
+ 2. Check the config syntax:
129
+ `python3 -m json.tool ~/Library/Application\ Support/Claude/claude_desktop_config.json`.
130
+ 3. Read file `~/Library/Logs/Claude/mcp-server-slack.log`.
131
+ 4. If the log says Bun wasn't found, put the absolute path from
132
+ `which bunx` in `command`.
265
133
 
266
- **Trade-offs:**
267
- - ✅ Full access to all your conversations
268
- - ✅ No per-conversation authorization needed
269
- - ❌ Tokens expire every 1-2 weeks
270
- - ❌ Requires Chrome for token extraction
134
+ ## Chrome Extraction Fails (macOS)
271
135
 
272
- ---
136
+ **Symptom:** `slack_refresh_tokens` can't extract tokens from Chrome.
273
137
 
274
- ## Getting Help
138
+ Check that:
275
139
 
276
- 1. Check logs:
277
- - MCP: `~/Library/Logs/Claude/mcp-server-slack.log`
278
- - Web: `/tmp/slack-web-api.log`
140
+ 1. Chrome is running with a Slack tab at `app.slack.com`, not the desktop
141
+ app, and you are signed in.
142
+ 2. **View** > **Developer** > **Allow JavaScript from Apple Events** is on.
143
+ Or set `SLACK_MCP_EXTRACTION_MODE=leveldb` to skip AppleScript.
144
+ 3. If Chrome uses a non-default profile or location, set
145
+ `SLACK_MCP_CHROME_PROFILE` or `SLACK_MCP_CHROME_USER_DATA_DIR`.
279
146
 
280
- 2. Test manually:
281
- ```bash
282
- cd jiyuu/mcp/slack
283
- bun src/server.js # Should say "running"
284
- ```
147
+ ## Why Browser Tokens Instead of a Slack App?
285
148
 
286
- 3. Verify tokens:
287
- ```bash
288
- npm run tokens:status
289
- ```
149
+ A Slack app needs workspace approval and OAuth scopes, and it can't read your
150
+ DMs the way you see them. Session tokens give the server the same access you
151
+ have in Slack's web client. The cost is token rotation every one to two
152
+ weeks, which you refresh by hand off macOS.
@@ -8,11 +8,19 @@
8
8
  * tests fail when the copies drift apart.
9
9
  *
10
10
  * The server never updates itself: the client config pins an exact version,
11
- * so what runs is what was reviewed. At startup the server reads the npm
12
- * registry's latest version in the background (2 s timeout, 24 h cache,
13
- * silent on failure). The first successful tool result after that check
14
- * carries a one-line notice when the running version is behind. Set
15
- * JIYUU_MCP_NO_UPDATE_CHECK=1 to turn the check off.
11
+ * so what runs is what was reviewed. Two callers read the npm registry's
12
+ * latest version, each with a 2 s timeout:
13
+ *
14
+ * - At startup, in the background, through a 1 h cache. The first successful
15
+ * tool result after that check carries a one-line notice when the running
16
+ * version is behind. Failures are silent.
17
+ * - Tool mcp_info reads the registry on every call and rewrites the cache.
18
+ * When the registry can't be read, it reports the cached answer and marks
19
+ * it with source "cache".
20
+ *
21
+ * A cached latest version older than the running version is out of date, so
22
+ * both callers ignore it. Set JIYUU_MCP_NO_UPDATE_CHECK=1 to turn the check
23
+ * off.
16
24
  */
17
25
  import { execFile } from "node:child_process";
18
26
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
@@ -20,7 +28,7 @@ import { homedir } from "node:os";
20
28
  import { dirname, join, resolve, sep } from "node:path";
21
29
 
22
30
  export const OPT_OUT_ENV = "JIYUU_MCP_NO_UPDATE_CHECK";
23
- export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
31
+ export const CACHE_TTL_MS = 60 * 60 * 1000;
24
32
  export const FETCH_TIMEOUT_MS = 2000;
25
33
  /** Only names Jiyuu publishes are checked; upstream names are someone else's. */
26
34
  export const PUBLISHED_SCOPE = "@uniquedivine/";
@@ -44,6 +52,8 @@ export interface UpdateStatus {
44
52
  runningVersion: string;
45
53
  latestVersion: string;
46
54
  checkedAt: string;
55
+ /** "live" when this call read the registry; "cache" for a cached answer. */
56
+ source: "live" | "cache";
47
57
  }
48
58
 
49
59
  export interface GitState {
@@ -156,7 +166,7 @@ export function isNewer(candidate: string, running: string): boolean {
156
166
  return compareIdentifiers(c.prerelease, r.prerelease) > 0;
157
167
  }
158
168
 
159
- export function updateAvailable(status: UpdateStatus | null): boolean {
169
+ export function updateAvailable(status: UpdateStatus | null): status is UpdateStatus {
160
170
  return status !== null && isNewer(status.latestVersion, status.runningVersion);
161
171
  }
162
172
 
@@ -181,16 +191,26 @@ export function cacheFile(cacheDir: string, name: string): string {
181
191
  return join(cacheDir, `${name.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
182
192
  }
183
193
 
194
+ export interface CacheReadOptions {
195
+ /** A cached latest version older than this one is out of date. */
196
+ runningVersion?: string;
197
+ /** Maximum entry age; null accepts any age. */
198
+ maxAgeMs?: number | null;
199
+ }
200
+
184
201
  export function readCache(
185
202
  path: string,
186
203
  name: string,
187
204
  now: Date,
205
+ options: CacheReadOptions = {},
188
206
  ): { latestVersion: string; checkedAt: string } | null {
189
207
  try {
190
208
  const data = JSON.parse(readFileSync(path, "utf8"));
191
209
  if (data?.name !== name || typeof data.latestVersion !== "string") return null;
210
+ const { runningVersion, maxAgeMs = CACHE_TTL_MS } = options;
211
+ if (runningVersion !== undefined && isNewer(runningVersion, data.latestVersion)) return null;
192
212
  const age = now.getTime() - Date.parse(data.checkedAt);
193
- if (!(age >= 0 && age < CACHE_TTL_MS)) return null;
213
+ if (!(age >= 0 && (maxAgeMs === null || age < maxAgeMs))) return null;
194
214
  return { latestVersion: data.latestVersion, checkedAt: data.checkedAt };
195
215
  } catch {
196
216
  return null;
@@ -225,23 +245,15 @@ export interface CheckOptions {
225
245
  timeoutMs?: number;
226
246
  }
227
247
 
228
- /**
229
- * Return the latest published version, from cache or the registry. Returns
230
- * null when the check is off, the name isn't Jiyuu's, or the registry can't be
231
- * read. Never throws.
232
- */
233
- export async function checkForUpdate(
248
+ /** Read the registry and rewrite the cache; null on any failure. */
249
+ async function readRegistry(
234
250
  name: string,
235
251
  runningVersion: string,
236
- options: CheckOptions = {},
252
+ path: string,
253
+ now: Date,
254
+ options: CheckOptions,
237
255
  ): Promise<UpdateStatus | null> {
238
- const env = options.env ?? process.env;
239
- if (checkDisabled(env) || !isPublishedName(name)) return null;
240
256
  try {
241
- const now = options.now ?? new Date();
242
- const path = cacheFile(options.cacheDir ?? defaultCacheDir(env), name);
243
- const cached = readCache(path, name, now);
244
- if (cached) return { name, runningVersion, ...cached };
245
257
  const body = await (options.fetch ?? fetchText)(
246
258
  latestVersionUrl(name),
247
259
  options.timeoutMs ?? FETCH_TIMEOUT_MS,
@@ -250,12 +262,51 @@ export async function checkForUpdate(
250
262
  if (!latestVersion) return null;
251
263
  const checkedAt = now.toISOString().replace(/\.\d{3}Z$/, "Z");
252
264
  writeCache(path, { name, latestVersion, checkedAt });
253
- return { name, runningVersion, latestVersion, checkedAt };
265
+ return { name, runningVersion, latestVersion, checkedAt, source: "live" };
254
266
  } catch {
255
267
  return null;
256
268
  }
257
269
  }
258
270
 
271
+ /**
272
+ * The startup check: a fresh cache entry if one exists, else the registry.
273
+ * Returns null when the check is off, the name isn't Jiyuu's, or the registry
274
+ * can't be read. Never throws.
275
+ */
276
+ export async function checkForUpdate(
277
+ name: string,
278
+ runningVersion: string,
279
+ options: CheckOptions = {},
280
+ ): Promise<UpdateStatus | null> {
281
+ const env = options.env ?? process.env;
282
+ if (checkDisabled(env) || !isPublishedName(name)) return null;
283
+ const now = options.now ?? new Date();
284
+ const path = cacheFile(options.cacheDir ?? defaultCacheDir(env), name);
285
+ const cached = readCache(path, name, now, { runningVersion });
286
+ if (cached) return { name, runningVersion, ...cached, source: "cache" };
287
+ return await readRegistry(name, runningVersion, path, now, options);
288
+ }
289
+
290
+ /**
291
+ * The mcp_info check: always the registry, then the cache of any age when the
292
+ * registry can't be read. Returns null when the check is off, the name isn't
293
+ * Jiyuu's, or neither source has an answer. Never throws.
294
+ */
295
+ export async function checkLatest(
296
+ name: string,
297
+ runningVersion: string,
298
+ options: CheckOptions = {},
299
+ ): Promise<UpdateStatus | null> {
300
+ const env = options.env ?? process.env;
301
+ if (checkDisabled(env) || !isPublishedName(name)) return null;
302
+ const now = options.now ?? new Date();
303
+ const path = cacheFile(options.cacheDir ?? defaultCacheDir(env), name);
304
+ const live = await readRegistry(name, runningVersion, path, now, options);
305
+ if (live) return live;
306
+ const cached = readCache(path, name, now, { runningVersion, maxAgeMs: null });
307
+ return cached ? { name, runningVersion, ...cached, source: "cache" } : null;
308
+ }
309
+
259
310
  export function formatNotice(status: UpdateStatus): string {
260
311
  return (
261
312
  `Update available: ${status.name} ${status.latestVersion} ` +
@@ -351,7 +402,7 @@ export function buildMcpInfo(input: McpInfoInput): Record<string, unknown> {
351
402
  if (checkDisabled(env)) notChecked = `disabled by ${OPT_OUT_ENV}`;
352
403
  else if (!isPublishedName(identity.name))
353
404
  notChecked = `'${identity.name}' is not a name Jiyuu publishes`;
354
- else if (!status) notChecked = "no registry result yet (offline, pending, or failed)";
405
+ else if (!status) notChecked = "registry unreachable and no cached result";
355
406
  return {
356
407
  server: input.server,
357
408
  name: identity.name,
@@ -366,7 +417,9 @@ export function buildMcpInfo(input: McpInfoInput): Record<string, unknown> {
366
417
  latestVersion: status?.latestVersion ?? null,
367
418
  updateAvailable: updateAvailable(status),
368
419
  checkedAt: status?.checkedAt ?? null,
369
- pinCommand: status ? pinCommand(status.name, status.latestVersion) : null,
420
+ // Only an upgrade gets a command; a pin to an older release downgrades.
421
+ pinCommand: updateAvailable(status) ? pinCommand(status.name, status.latestVersion) : null,
422
+ source: status?.source ?? null,
370
423
  notChecked,
371
424
  },
372
425
  runtime: {
@@ -381,27 +434,36 @@ export function buildMcpInfo(input: McpInfoInput): Record<string, unknown> {
381
434
  };
382
435
  }
383
436
 
437
+ export interface JiyuuMcpInfoChecks {
438
+ /** The startup check behind the one-time notice; default checkForUpdate. */
439
+ startup?: () => Promise<UpdateStatus | null>;
440
+ /** The check each mcp_info call runs; default checkLatest. */
441
+ live?: (env: Env) => Promise<UpdateStatus | null>;
442
+ }
443
+
384
444
  /** Wire-up for one server process: identity, notifier and the tool body. */
385
445
  export class JiyuuMcpInfo {
386
446
  readonly identity: PackageIdentity;
387
447
  readonly notifier: UpdateNotifier;
448
+ private readonly liveCheck: (env: Env) => Promise<UpdateStatus | null>;
388
449
 
389
450
  constructor(
390
451
  private readonly server: string,
391
452
  packageRoot: string,
392
453
  private readonly envPrefixes: string[],
393
- check?: () => Promise<UpdateStatus | null>,
454
+ checks: JiyuuMcpInfoChecks = {},
394
455
  ) {
395
456
  this.identity = readPackageIdentity(packageRoot);
396
457
  const { name, version } = this.identity;
397
- this.notifier = new UpdateNotifier(check ?? (() => checkForUpdate(name, version)));
458
+ this.notifier = new UpdateNotifier(checks.startup ?? (() => checkForUpdate(name, version)));
459
+ this.liveCheck = checks.live ?? ((env) => checkLatest(name, version, { env }));
398
460
  }
399
461
 
400
462
  async callTool(env: Env = process.env) {
401
- this.notifier.start();
402
- const status = await this.notifier.status(FETCH_TIMEOUT_MS + 500);
403
- const git =
404
- this.identity.provenance === "source-checkout" ? await gitState(this.identity.root) : null;
463
+ const [status, git] = await Promise.all([
464
+ this.liveCheck(env).catch(() => null),
465
+ this.identity.provenance === "source-checkout" ? gitState(this.identity.root) : null,
466
+ ]);
405
467
  const report = buildMcpInfo({
406
468
  server: this.server,
407
469
  identity: this.identity,