@taskade/cli 0.0.0-stage → 0.2.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.
@@ -0,0 +1,250 @@
1
+ // Read and change a JSON config file that holds MCP servers.
2
+ // The rules: keep every other key and server, write a backup first,
3
+ // write through a temp file and a rename, keep the file mode, and never
4
+ // overwrite a file that is not valid JSON.
5
+
6
+ import { chmodSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { dirname } from "node:path";
8
+
9
+ /**
10
+ * Read a JSON config file.
11
+ * Returns { exists, data, text, error }. `error` is set when the file exists
12
+ * but is not a JSON object, or when `key` is not an object.
13
+ */
14
+ export function readConfig(file, key) {
15
+ let text;
16
+ try {
17
+ text = readFileSync(file, "utf8");
18
+ } catch (err) {
19
+ if (err.code === "ENOENT") return { exists: false, data: {}, text: "" };
20
+ return { exists: true, error: `cannot read the file (${err.code || err.message})` };
21
+ }
22
+ if (text.trim() === "") return { exists: true, data: {}, text };
23
+ let data;
24
+ try {
25
+ data = JSON.parse(text);
26
+ } catch (err) {
27
+ return { exists: true, text, error: `the file is not valid JSON (${err.message})` };
28
+ }
29
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
30
+ return { exists: true, text, error: "the file does not hold a JSON object" };
31
+ }
32
+ const servers = data[key];
33
+ if (servers !== undefined && (servers === null || typeof servers !== "object" || Array.isArray(servers))) {
34
+ return { exists: true, text, error: `"${key}" in the file is not a JSON object` };
35
+ }
36
+ return { exists: true, data, text };
37
+ }
38
+
39
+ export function deepEqual(a, b) {
40
+ return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b));
41
+ }
42
+
43
+ function sortKeys(value) {
44
+ if (Array.isArray(value)) return value.map(sortKeys);
45
+ if (value && typeof value === "object") {
46
+ return Object.fromEntries(
47
+ Object.keys(value)
48
+ .sort()
49
+ .map((k) => [k, sortKeys(value[k])]),
50
+ );
51
+ }
52
+ return value;
53
+ }
54
+
55
+ /** The indent of the file: the whitespace of its first indented line, or 2 spaces. */
56
+ function detectIndent(text) {
57
+ const match = /^([ \t]+)\S/m.exec(text);
58
+ return match ? match[1] : " ";
59
+ }
60
+
61
+ /**
62
+ * The new text of the file with `data[key][name] = entry`.
63
+ * It changes only the text of that one entry, so the rest of the file keeps
64
+ * its format. If that edit does not give the expected data, it writes the
65
+ * whole file again with JSON.stringify.
66
+ */
67
+ export function mergedText(config, key, name, entry) {
68
+ const data = config.data;
69
+ const next = { ...data, [key]: { ...(data[key] || {}), [name]: entry } };
70
+ if (!config.exists || config.text.trim() === "") return JSON.stringify(next, null, " ") + "\n";
71
+ try {
72
+ const text = editInPlace(config.text, key, name, entry);
73
+ if (deepEqual(JSON.parse(text), next)) return text;
74
+ } catch {
75
+ // Fall back to a full write below.
76
+ }
77
+ const newline = config.text.endsWith("\n") ? "\n" : "";
78
+ return JSON.stringify(next, null, detectIndent(config.text)) + newline;
79
+ }
80
+
81
+ /** Parse valid JSON text into spans: each object holds its members with their positions. */
82
+ function parseSpans(text) {
83
+ let i = 0;
84
+ const skip = () => {
85
+ while (/\s/.test(text[i] || "")) i++;
86
+ };
87
+ const string = () => {
88
+ const start = i++;
89
+ while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
90
+ i++;
91
+ return { start, end: i };
92
+ };
93
+ const value = () => {
94
+ skip();
95
+ const start = i;
96
+ if (text[i] === "{" || text[i] === "[") {
97
+ const object = text[i] === "{";
98
+ const members = [];
99
+ i++;
100
+ skip();
101
+ if (text[i] === (object ? "}" : "]")) return { start, end: ++i, members };
102
+ for (;;) {
103
+ skip();
104
+ if (object) {
105
+ const k = string();
106
+ skip();
107
+ i++; // the colon
108
+ members.push({ key: JSON.parse(text.slice(k.start, k.end)), value: value() });
109
+ } else {
110
+ value();
111
+ }
112
+ skip();
113
+ if (text[i++] !== ",") return { start, end: i, members };
114
+ }
115
+ }
116
+ if (text[i] === '"') return string();
117
+ while (i < text.length && !/[\s,\]}]/.test(text[i])) i++;
118
+ return { start, end: i };
119
+ };
120
+ return value();
121
+ }
122
+
123
+ function lineIndent(text, pos) {
124
+ const lineStart = text.lastIndexOf("\n", pos - 1) + 1;
125
+ return /^[ \t]*/.exec(text.slice(lineStart))[0];
126
+ }
127
+
128
+ /** Indent every line after the first of a JSON text. */
129
+ function reindent(json, indent, eol) {
130
+ return json.replace(/\n/g, eol + indent);
131
+ }
132
+
133
+ /** Insert `"name": value` as the last member of the object at `span`. */
134
+ function insertMember(text, span, name, value, unit, eol) {
135
+ const outer = lineIndent(text, span.end - 1);
136
+ const inner = span.members.length ? lineIndent(text, span.members[0].value.start) : outer + unit;
137
+ const member = `${JSON.stringify(name)}: ${reindent(JSON.stringify(value, null, unit), inner, eol)}`;
138
+ const close = span.end - 1;
139
+ if (!span.members.length) return `${text.slice(0, span.start + 1)}${eol}${inner}${member}${eol}${outer}${text.slice(close)}`;
140
+ const last = span.members[span.members.length - 1].value.end;
141
+ return `${text.slice(0, last)},${eol}${inner}${member}${text.slice(last)}`;
142
+ }
143
+
144
+ function editInPlace(text, key, name, entry) {
145
+ const root = parseSpans(text);
146
+ const unit = detectIndent(text);
147
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
148
+ const servers = root.members.find((m) => m.key === key);
149
+ if (!servers) return insertMember(text, root, key, { [name]: entry }, unit, eol);
150
+ const existing = servers.value.members.find((m) => m.key === name);
151
+ if (!existing) return insertMember(text, servers.value, name, entry, unit, eol);
152
+ const indent = lineIndent(text, existing.value.start);
153
+ const json = reindent(JSON.stringify(entry, null, unit), indent, eol);
154
+ return text.slice(0, existing.value.start) + json + text.slice(existing.value.end);
155
+ }
156
+
157
+ /**
158
+ * A line diff of two texts, with 2 lines of context around each change.
159
+ * Lines that only the new text has start with "+", removed lines with "-".
160
+ */
161
+ export function lineDiff(oldText, newText) {
162
+ const a = oldText === "" ? [] : oldText.replace(/\r?\n$/, "").split(/\r?\n/);
163
+ const b = newText.replace(/\r?\n$/, "").split(/\r?\n/);
164
+ // Longest common subsequence table, built from the end.
165
+ const lcs = Array.from({ length: a.length + 1 }, () => new Uint32Array(b.length + 1));
166
+ for (let i = a.length - 1; i >= 0; i--) {
167
+ for (let j = b.length - 1; j >= 0; j--) {
168
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
169
+ }
170
+ }
171
+ const ops = [];
172
+ let i = 0;
173
+ let j = 0;
174
+ while (i < a.length || j < b.length) {
175
+ if (i < a.length && j < b.length && a[i] === b[j]) {
176
+ ops.push([" ", a[i]]);
177
+ i++;
178
+ j++;
179
+ } else if (i < a.length && (j === b.length || lcs[i + 1][j] >= lcs[i][j + 1])) {
180
+ // Show a removed line before the lines that replace it.
181
+ ops.push(["-", a[i]]);
182
+ i++;
183
+ } else {
184
+ ops.push(["+", b[j]]);
185
+ j++;
186
+ }
187
+ }
188
+ const keep = ops.map(([op], n) => ops.slice(Math.max(0, n - 2), n + 3).some(([o]) => o !== " "));
189
+ const lines = [];
190
+ let skipped = false;
191
+ ops.forEach(([op, text], n) => {
192
+ if (keep[n]) {
193
+ if (skipped) lines.push(" ...");
194
+ skipped = false;
195
+ lines.push(`${op} ${text}`);
196
+ } else {
197
+ skipped = true;
198
+ }
199
+ });
200
+ if (skipped) lines.push(" ...");
201
+ return lines.join("\n");
202
+ }
203
+
204
+ /** Never overwrite an older backup: add -2, -3 and on when the name is taken. */
205
+ function freeBackupPath(base) {
206
+ let candidate = base;
207
+ for (let n = 2; existsSync(candidate); n++) candidate = `${base}-${n}`;
208
+ return candidate;
209
+ }
210
+
211
+ function timestamp(date) {
212
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
213
+ }
214
+
215
+ /**
216
+ * Write `text` to `file`. Writes a backup of an existing file first, then a
217
+ * temp file beside it, then renames the temp file over the file.
218
+ * Keeps the mode of an existing file. A new file gets `newMode`.
219
+ * Returns the path of the backup, or null for a new file.
220
+ */
221
+ export function writeConfig(file, text, { newMode = 0o644, now = new Date() } = {}) {
222
+ let target = file;
223
+ let mode = newMode;
224
+ let backup = null;
225
+ try {
226
+ // Write through a symbolic link to the real file, as an editor does.
227
+ target = realpathSync(file);
228
+ mode = statSync(target).mode & 0o777;
229
+ backup = freeBackupPath(`${file}.bak-${timestamp(now)}`);
230
+ copyFileSync(target, backup, constants.COPYFILE_EXCL);
231
+ chmodSync(backup, mode);
232
+ } catch (err) {
233
+ if (err.code !== "ENOENT") throw err;
234
+ mkdirSync(dirname(file), { recursive: true });
235
+ }
236
+ const temp = `${target}.tmp-${process.pid}-${Date.now()}`;
237
+ try {
238
+ writeFileSync(temp, text, { mode });
239
+ chmodSync(temp, mode);
240
+ renameSync(temp, target);
241
+ } catch (err) {
242
+ try {
243
+ unlinkSync(temp);
244
+ } catch {
245
+ // The temp file was never written.
246
+ }
247
+ throw err;
248
+ }
249
+ return backup;
250
+ }
package/src/doctor.mjs ADDED
@@ -0,0 +1,373 @@
1
+ // `taskade doctor`: answer "why does my connection fail?" in plain lines.
2
+ // It changes nothing on the machine. It sends TASKADE_TOKEN only to the
3
+ // server URL, and it never follows a redirect with the token.
4
+ //
5
+ // Sign-in discovery follows the MCP authorization spec:
6
+ // https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization
7
+ // The token check follows the Streamable HTTP transport:
8
+ // https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http
9
+
10
+ import { CLIENTS, RUN, TOKEN_PAGE, clientEntries, serverUrl } from "./clients.mjs";
11
+ import { getEnv, tildify } from "./system.mjs";
12
+
13
+ const PROTOCOL_VERSION = "2025-06-18";
14
+ const TIMEOUT_MS = 15000;
15
+
16
+ export async function doctor(io, opts) {
17
+ const checks = [];
18
+ const add = (group, status, message, next) => checks.push({ group, status, message, ...(next ? { next } : {}) });
19
+ let tools;
20
+
21
+ let url;
22
+ try {
23
+ url = serverUrl(io);
24
+ } catch (err) {
25
+ add("server", "fail", err.message, "Unset TASKADE_MCP_URL, or set it to an https:// URL.");
26
+ }
27
+
28
+ const major = Number(process.versions.node.split(".")[0]);
29
+ if (major >= 18) add("machine", "ok", `Node.js ${process.version}. This CLI needs Node.js 18 or later.`);
30
+ else add("machine", "fail", `Node.js ${process.version} is too old.`, "Install Node.js 18 or later.");
31
+
32
+ if (url) {
33
+ await checkServer(url, add, io);
34
+ const token = (getEnv(io.env, "TASKADE_TOKEN") || "").trim();
35
+ if (!token) {
36
+ add("token", "skip", "TASKADE_TOKEN is not set, so the token check is skipped. Clients that sign in need no token.");
37
+ } else {
38
+ tools = await checkToken(url, token, add, io.version);
39
+ }
40
+ }
41
+
42
+ for (const client of CLIENTS) checkClient(io, client, add);
43
+
44
+ const ok = checks.every((c) => c.status !== "fail");
45
+ if (opts.json) {
46
+ const result = { ok, server: url || null, checks };
47
+ if (opts.verbose && tools) result.tools = tools;
48
+ io.stdout.write(JSON.stringify(result, null, 2) + "\n");
49
+ return ok ? 0 : 1;
50
+ }
51
+
52
+ const out = (text = "") => io.stdout.write(text + "\n");
53
+ const mark = { ok: "ok ", fail: "fail", skip: "-- " };
54
+ out(`Taskade doctor${url ? ` (server: ${url})` : ""}`);
55
+ let group = null;
56
+ for (const c of checks) {
57
+ if (c.group !== group) {
58
+ out();
59
+ if (c.group === "clients") out("Clients (read only):");
60
+ group = c.group;
61
+ }
62
+ out(`${mark[c.status]} ${c.message}`);
63
+ if (c.next) out(` Next: ${c.next}`);
64
+ if (c.group === "token" && c.status === "ok" && opts.verbose && tools) {
65
+ for (const name of tools) out(` - ${name}`);
66
+ }
67
+ }
68
+ out();
69
+ out(ok ? "Every check passed." : "A check failed. See the Next line under it.");
70
+ return ok ? 0 : 1;
71
+ }
72
+
73
+ function describeError(err) {
74
+ if (err?.name === "TimeoutError" || err?.name === "AbortError") return `no answer in ${TIMEOUT_MS / 1000} seconds`;
75
+ const cause = err?.cause?.code || err?.cause?.message;
76
+ return cause ? `${err.message} (${cause})` : String(err?.message || err);
77
+ }
78
+
79
+ async function readError(res) {
80
+ const text = await res.text().catch(() => "");
81
+ try {
82
+ const body = JSON.parse(text);
83
+ const message = body.error?.message || body.error_description || body.message || body.error;
84
+ if (typeof message === "string") return message;
85
+ } catch {
86
+ // Not JSON: show the text.
87
+ }
88
+ return text.trim().slice(0, 200) || res.statusText || "no message";
89
+ }
90
+
91
+ async function getJson(target) {
92
+ const res = await fetch(target, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) });
93
+ if (!res.ok) throw new Error(`${target} answered ${res.status}`);
94
+ try {
95
+ return await res.json();
96
+ } catch {
97
+ throw new Error(`${target} did not return JSON`);
98
+ }
99
+ }
100
+
101
+ function initializeBody(version) {
102
+ return {
103
+ jsonrpc: "2.0",
104
+ id: 1,
105
+ method: "initialize",
106
+ params: {
107
+ protocolVersion: PROTOCOL_VERSION,
108
+ capabilities: {},
109
+ clientInfo: { name: "taskade-cli", version: version || "0.0.0" },
110
+ },
111
+ };
112
+ }
113
+
114
+ async function checkServer(url, add, io) {
115
+ const next = "Check your network, proxy, or firewall, then run doctor again.";
116
+ let res;
117
+ try {
118
+ res = await fetch(url, {
119
+ method: "POST",
120
+ headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
121
+ body: JSON.stringify(initializeBody(io.version)),
122
+ redirect: "manual",
123
+ signal: AbortSignal.timeout(TIMEOUT_MS),
124
+ });
125
+ } catch (err) {
126
+ add("server", "fail", `Cannot reach ${url}: ${describeError(err)}.`, next);
127
+ return;
128
+ }
129
+ await res.body?.cancel().catch(() => {});
130
+ const header = res.headers.get("www-authenticate") || "";
131
+ const match = /resource_metadata="([^"]+)"/i.exec(header);
132
+ if (res.status !== 401 || !match) {
133
+ add(
134
+ "server",
135
+ "fail",
136
+ `Without sign-in the server must answer 401 and name its sign-in metadata. It answered ${res.status}${match ? "" : " with no resource_metadata"}.`,
137
+ "Check the server URL. The hosted server is https://www.taskade.com/mcp.",
138
+ );
139
+ return;
140
+ }
141
+ add("server", "ok", "The server answers. Without sign-in it returns 401 and names its sign-in metadata.");
142
+
143
+ let resource;
144
+ try {
145
+ resource = await getJson(match[1]);
146
+ } catch (err) {
147
+ add("server", "fail", `Cannot read the sign-in metadata: ${describeError(err)}.`, next);
148
+ return;
149
+ }
150
+ const servers = resource.authorization_servers;
151
+ if (typeof resource.resource !== "string" || !Array.isArray(servers) || typeof servers[0] !== "string") {
152
+ add("server", "fail", `The sign-in metadata at ${match[1]} lacks "resource" or "authorization_servers".`);
153
+ return;
154
+ }
155
+ if (resource.resource.replace(/\/$/, "") !== url.replace(/\/$/, "")) {
156
+ add(
157
+ "server",
158
+ "fail",
159
+ `The sign-in metadata names ${resource.resource}, not ${url}. Clients refuse to sign in for it.`,
160
+ "Use the URL that the metadata names.",
161
+ );
162
+ return;
163
+ }
164
+ add("server", "ok", `Sign-in metadata: ${match[1]}`);
165
+
166
+ const issuer = new URL(servers[0]);
167
+ const suffix = issuer.pathname === "/" ? "" : issuer.pathname.replace(/\/$/, "");
168
+ const candidates = [
169
+ `${issuer.origin}/.well-known/oauth-authorization-server${suffix}`,
170
+ `${issuer.origin}/.well-known/openid-configuration${suffix}`,
171
+ ];
172
+ let meta;
173
+ let metaUrl;
174
+ for (const candidate of candidates) {
175
+ try {
176
+ meta = await getJson(candidate);
177
+ metaUrl = candidate;
178
+ break;
179
+ } catch {
180
+ // Try the next well-known path.
181
+ }
182
+ }
183
+ if (!meta) {
184
+ add("server", "fail", `Cannot read the authorization server metadata of ${servers[0]}.`, next);
185
+ return;
186
+ }
187
+ const missing = ["issuer", "authorization_endpoint", "token_endpoint"].filter((k) => typeof meta[k] !== "string");
188
+ if (!(meta.code_challenge_methods_supported || []).includes("S256")) missing.push("code_challenge_methods_supported with S256");
189
+ if (!meta.registration_endpoint && meta.client_id_metadata_document_supported !== true) missing.push("registration_endpoint");
190
+ if (missing.length) {
191
+ add("server", "fail", `The authorization server metadata at ${metaUrl} lacks: ${missing.join(", ")}.`);
192
+ return;
193
+ }
194
+ add("server", "ok", `Authorization server: ${metaUrl}`);
195
+ }
196
+
197
+ /** Read the JSON-RPC answer with `id` from a JSON body or an event stream. */
198
+ async function readAnswer(res, id) {
199
+ const type = res.headers.get("content-type") || "";
200
+ if (type.includes("text/event-stream")) {
201
+ const reader = res.body.getReader();
202
+ const decoder = new TextDecoder();
203
+ let buffer = "";
204
+ for (;;) {
205
+ const { value, done } = await reader.read();
206
+ if (value) buffer += decoder.decode(value, { stream: true });
207
+ buffer = buffer.replace(/\r\n?/g, "\n");
208
+ if (done) buffer += "\n\n";
209
+ let end;
210
+ while ((end = buffer.indexOf("\n\n")) !== -1) {
211
+ const event = buffer.slice(0, end);
212
+ buffer = buffer.slice(end + 2);
213
+ const data = event
214
+ .split("\n")
215
+ .filter((line) => line.startsWith("data:"))
216
+ .map((line) => line.slice(5).replace(/^ /, ""))
217
+ .join("\n");
218
+ let message;
219
+ try {
220
+ message = JSON.parse(data);
221
+ } catch {
222
+ continue;
223
+ }
224
+ const found = [].concat(message).find((m) => m && m.id === id);
225
+ if (found) {
226
+ reader.cancel().catch(() => {});
227
+ return found;
228
+ }
229
+ }
230
+ if (done) throw new Error("the event stream ended with no answer");
231
+ }
232
+ }
233
+ const body = await res.json();
234
+ const found = [].concat(body).find((m) => m && m.id === id);
235
+ if (!found) throw new Error("the answer holds no JSON-RPC response");
236
+ return found;
237
+ }
238
+
239
+ async function checkToken(url, token, add, version) {
240
+ let sessionId = null;
241
+ let protocol = null;
242
+ const post = (body) => {
243
+ const headers = {
244
+ "Content-Type": "application/json",
245
+ Accept: "application/json, text/event-stream",
246
+ Authorization: `Bearer ${token}`,
247
+ };
248
+ if (sessionId) headers["Mcp-Session-Id"] = sessionId;
249
+ if (protocol) headers["MCP-Protocol-Version"] = protocol;
250
+ return fetch(url, {
251
+ method: "POST",
252
+ headers,
253
+ body: JSON.stringify(body),
254
+ redirect: "manual",
255
+ signal: AbortSignal.timeout(TIMEOUT_MS),
256
+ });
257
+ };
258
+
259
+ // Send one request and return its JSON-RPC answer, or null after a failed check.
260
+ const call = async (body, step) => {
261
+ let res;
262
+ try {
263
+ res = await post(body);
264
+ } catch (err) {
265
+ add("token", "fail", `Cannot reach the server for ${step}: ${describeError(err)}.`);
266
+ return null;
267
+ }
268
+ if (res.status >= 300 && res.status < 400) {
269
+ add("token", "fail", `The server answered ${step} with a redirect (${res.status}). The CLI does not send the token on.`);
270
+ return null;
271
+ }
272
+ if (res.status === 401) {
273
+ add(
274
+ "token",
275
+ "fail",
276
+ `The server refused the token (401: ${await readError(res)}).`,
277
+ `Create a new token at ${TOKEN_PAGE} and set TASKADE_TOKEN to it.`,
278
+ );
279
+ return null;
280
+ }
281
+ if (res.status === 403) {
282
+ add(
283
+ "token",
284
+ "fail",
285
+ `The server accepted the token but refused access (403: ${await readError(res)}).`,
286
+ "Use a workspace on a paid Taskade plan. Every paid plan includes the hosted MCP server.",
287
+ );
288
+ return null;
289
+ }
290
+ if (!res.ok) {
291
+ add("token", "fail", `The server answered ${step} with ${res.status}: ${await readError(res)}.`);
292
+ return null;
293
+ }
294
+ if (body.id === undefined) {
295
+ await res.body?.cancel().catch(() => {});
296
+ return {};
297
+ }
298
+ if (!sessionId) sessionId = res.headers.get("mcp-session-id");
299
+ let answer;
300
+ try {
301
+ answer = await readAnswer(res, body.id);
302
+ } catch (err) {
303
+ add("token", "fail", `Cannot read the answer to ${step}: ${describeError(err)}.`);
304
+ return null;
305
+ }
306
+ if (answer.error) {
307
+ add("token", "fail", `The server refused ${step}: ${answer.error.message} (code ${answer.error.code}).`);
308
+ return null;
309
+ }
310
+ return answer;
311
+ };
312
+
313
+ const init = await call(initializeBody(version), "initialize");
314
+ if (!init) return undefined;
315
+ protocol = init.result?.protocolVersion || PROTOCOL_VERSION;
316
+ if (!(await call({ jsonrpc: "2.0", method: "notifications/initialized" }, "notifications/initialized"))) return undefined;
317
+ const list = await call({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }, "tools/list");
318
+ if (sessionId) {
319
+ // End the session. The answer does not matter.
320
+ await fetch(url, {
321
+ method: "DELETE",
322
+ headers: { Authorization: `Bearer ${token}`, "Mcp-Session-Id": sessionId, "MCP-Protocol-Version": protocol },
323
+ redirect: "manual",
324
+ signal: AbortSignal.timeout(TIMEOUT_MS),
325
+ })
326
+ .then((r) => r.body?.cancel())
327
+ .catch(() => {});
328
+ }
329
+ if (!list) return undefined;
330
+ const names = (list.result?.tools || []).map((t) => t?.name).filter((n) => typeof n === "string");
331
+ if (names.length === 0) {
332
+ add("token", "fail", "The token works, but the server lists no tools.", "Use a workspace on a paid Taskade plan.");
333
+ return undefined;
334
+ }
335
+ add("token", "ok", "The token works and the server lists its tools.");
336
+ return names;
337
+ }
338
+
339
+ function checkClient(io, client, add) {
340
+ if (!client.detect(io)) {
341
+ add("clients", "skip", `${client.name}: not found on this machine.`);
342
+ return;
343
+ }
344
+ if (client.id === "claude-desktop") {
345
+ add(
346
+ "clients",
347
+ "skip",
348
+ `${client.name}: installed. Claude keeps connectors in your Claude account, so the CLI cannot read them.`,
349
+ "In Claude Desktop, open Customize, then Connectors, and look for Taskade.",
350
+ );
351
+ return;
352
+ }
353
+ const places = clientEntries(io, client.id);
354
+ const found = places.filter((p) => p.entry);
355
+ const broken = places.filter((p) => p.error);
356
+ for (const p of broken) {
357
+ add("clients", "fail", `${client.name}: ${tildify(io, p.file)}: ${p.error}.`, "Fix the file. The client cannot read it either.");
358
+ }
359
+ if (found.length) {
360
+ for (const p of found) {
361
+ const usesToken = Boolean(p.entry.headers?.Authorization || p.entry.bearer_token_env_var);
362
+ const target = p.entry.url || p.entry.serverUrl || "no url";
363
+ add(
364
+ "clients",
365
+ "ok",
366
+ `${client.name}: taskade server in ${tildify(io, p.file)} (${p.label}${usesToken ? ", token" : ", sign-in"}) points at ${target}.`,
367
+ );
368
+ }
369
+ return;
370
+ }
371
+ const where = client.id === "vscode" ? " in .vscode/mcp.json of this folder. The CLI cannot read the user profile" : "";
372
+ add("clients", "skip", `${client.name}: installed, no taskade server found${where}.`, `${RUN} plug ${client.id}`);
373
+ }