diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f61e09e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + name: Node ${{ matrix.node }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + node: [18, 20, 22, 24] + include: + # Paths, PATH lookup, and the clipboard differ on these systems. + - os: macos-latest + node: 22 + - os: windows-latest + node: 22 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ matrix.node }} + package-manager-cache: false + - run: npm test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..4d4efeb --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,42 @@ +# Publish to npm when a GitHub release is published. +# It uses npm trusted publishing (OIDC), so the repository holds no npm token. +# npm creates the provenance statement for the package. +# Before the first run: publish 0.2.0 once by hand and add this workflow as the +# trusted publisher of @taskade/cli on npmjs.com. See "For maintainers" in README.md. + +name: Release + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + # Trusted publishing needs npm 11.5.1 or later. Node 24 includes it. + node-version: 24 + registry-url: https://registry.npmjs.org + package-manager-cache: false + - name: Check that the tag equals the package version + env: + TAG: ${{ github.event.release.tag_name }} + run: | + VERSION="$(node -p "require('./package.json').version")" + if [ "$TAG" != "v$VERSION" ]; then + echo "::error::The release tag is $TAG, but package.json has version $VERSION. The tag must be v$VERSION." + exit 1 + fi + - run: npm test + - run: npm publish --provenance --access public diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..454f6f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +## 0.2.0 + +### Added + +- `plug ` connects Claude Code, Codex, Cursor, VS Code, or Claude Desktop to `https://www.taskade.com/mcp`. The default is the browser sign-in (OAuth), with no token. +- For Claude Code, Codex, and VS Code, `plug` shows the command of the client and runs it after a "y". +- For Cursor and for `vscode --project`, `plug` merges one `taskade` entry into the JSON config file. It shows a diff, writes a backup, writes atomically, keeps the file mode and the format of the rest of the file, and refuses a file that is not valid JSON. +- For Claude Desktop, `plug` prints the 3 steps for the Connectors screen and copies the URL to the clipboard. +- `plug` with no client lists the clients on the machine and changes nothing. +- `--yes`, `--print`, `--project`, and `--token`. `--token` reads a personal access token from `TASKADE_TOKEN` only, and never prints the full token. +- `doctor` checks the Node.js version, the server and its sign-in metadata, the token with an MCP `initialize` and `tools/list` request, and the client config files. `--json` prints the result as JSON. `--verbose` prints the tool names. +- `connect` is an alias of `plug`. `claude` is an alias of `claude-code`. +- `--version`. +- CI on Node.js 18, 20, 22, and 24 on Linux, and Node.js 22 on macOS and Windows. +- A release workflow that publishes to npm with provenance through npm trusted publishing. +- `SECURITY.md`. + +### Changed + +- `whoami` is now an alias of `doctor`. The old `whoami` called an API path that does not exist and always failed with 404. +- `plug` no longer asks for a token, and the default config holds no token. +- `npm test` lists the test files, so it works on every supported Node.js version. +- The copyright holder in `LICENSE` is TASKCADE INC. + +### Removed + +- `TASKADE_API_URL`. `TASKADE_MCP_URL` sets another server URL for tests. + +## 0.1.0 + +- `plug [cursor|claude]` printed a config block with a personal access token. +- `whoami` called an API path that does not exist. diff --git a/LICENSE b/LICENSE index 4bbb1ca..adbc262 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Taskade +Copyright (c) 2026 TASKCADE INC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 0e17b55..023e626 100644 --- a/README.md +++ b/README.md @@ -1,99 +1,158 @@ # @taskade/cli -Thin CLI for Taskade MCP plug-and-play. It prints the config block that connects Cursor or Claude Code to your Taskade workspace with a personal access token. +Connect your AI client to Taskade with one command: -> **Not on npm yet.** The package `@taskade/cli` is not published, so `npx @taskade/cli` fails. Run the CLI from GitHub with `npx github:taskade/cli`. +```bash +npx github:taskade/cli plug +``` -Most clients do not need this CLI or a token. They connect to `https://www.taskade.com/mcp` and sign in with OAuth. See [taskade/mcp](https://github.com/taskade/mcp) for the steps for each client. Use this CLI when a client cannot sign in with OAuth. +The command lists the MCP clients on your machine and the command to run for each. It changes nothing. -## Quick Start +> **Not on npm yet.** Until the first npm release, run the CLI from GitHub with `npx github:taskade/cli`. After that release, `npx @taskade/cli` works too. -```bash -# 1. Create a personal access token at https://www.taskade.com/settings/api (it starts with tskdp_) +## Most people need no CLI -# 2. Connect Cursor -npx github:taskade/cli plug cursor +Paste this line into your agent. The agent reads the steps and connects itself: + +```text +Set up Taskade for me. Read and follow https://www.taskade.com/SKILL.md +``` + +- The Taskade skills: [taskade/skills](https://github.com/taskade/skills) +- The Taskade MCP server and plugin: [taskade/mcp](https://github.com/taskade/mcp) +- The hosted server guide: [Hosted Taskade MCP](https://www.taskade.com/docs/mcp/hosted-mcp) -# 3. Connect Claude Code -npx github:taskade/cli plug claude +The hosted server is `https://www.taskade.com/mcp`. It is part of every paid Taskade plan. Clients sign in with your Taskade account in the browser (OAuth), so you need no token. + +## Connect a client: `plug` + +```bash +npx github:taskade/cli plug claude-code +npx github:taskade/cli plug codex +npx github:taskade/cli plug cursor +npx github:taskade/cli plug vscode +npx github:taskade/cli plug claude-desktop ``` -## What This Does +Each command shows the change first. In a terminal, it asks for a "y" before it changes anything. On a pipe or in CI, it only prints. `connect` is an alias of `plug`, and `claude` is an alias of `claude-code`. + +| Client | What the CLI does | What changes on your machine | +| --- | --- | --- | +| `claude-code` | Runs `claude mcp add --transport http --scope user taskade https://www.taskade.com/mcp`. | Claude Code adds the server to `~/.claude.json`. With `--project`, it writes `.mcp.json` in the current folder. | +| `codex` | Runs `codex mcp add taskade --url https://www.taskade.com/mcp`, then `codex mcp login taskade` if the add step did not sign you in. | Codex adds the server to `~/.codex/config.toml` and keeps the sign-in. | +| `cursor` | Merges one `taskade` entry into the Cursor config file. | `~/.cursor/mcp.json`, or `.cursor/mcp.json` in the current folder with `--project`. | +| `vscode` | Runs `code --add-mcp` with the `taskade` entry. With `--project`, merges one entry into the file. | Your VS Code user profile, or `.vscode/mcp.json` in the current folder with `--project`. | +| `claude-desktop` | Prints the 3 steps for the Connectors screen and copies the URL to the clipboard. | Only the clipboard. Claude keeps connectors in your Claude account, not in a file, so the CLI cannot add one for you. | + +When a client command (`claude`, `codex`, `code`) is not on your PATH, the CLI prints the command and the install step, and exits 0. + +When the CLI changes a JSON file, it: -This CLI prints the MCP server config block you need to paste into your AI agent client (Cursor or Claude Code). The block holds your token. Do not commit a file that holds your token. +- Shows the file and the exact change as a diff. +- Keeps every other key and every other server, and the format of the rest of the file. +- Writes a backup copy beside the file first (`.bak-`). +- Writes a temp file, then renames it over the file. The file keeps its mode. +- Refuses a file that is not valid JSON and leaves it unchanged. (JSON with comments counts as not valid.) +- Says "Already connected" and changes nothing when an equal `taskade` entry exists. When a different entry exists, it shows both and asks. -**The token is the product.** You do not need this CLI to use Taskade MCP - you can copy the config block manually from [https://www.taskade.com/settings/api](https://www.taskade.com/settings/api). This CLI just makes it one command instead of five clicks. +Run `plug` with no client name to see which clients are on your machine. -## Commands +### Options for `plug` -### `taskade plug [cursor|claude]` +| Option | Effect | +| --- | --- | +| `--yes`, `-y` | Apply the change with no question. | +| `--print` | Show the command or the config block. Change nothing. This is the default on a pipe or in CI. | +| `--project` | Write the project file of the current folder, not the user file (Claude Code, Cursor, VS Code). | +| `--token` | Use a personal access token in place of the browser sign-in. See below. | -Prints the MCP server config block. +### A machine with no browser: `--token` + +A headless machine cannot sign in with a browser. Create a personal access token at [https://www.taskade.com/settings/api](https://www.taskade.com/settings/api), put it in the environment variable `TASKADE_TOKEN`, and add `--token`: ```bash -npx github:taskade/cli plug cursor # Cursor format with instructions -npx github:taskade/cli plug claude # Claude Code format with instructions -npx github:taskade/cli plug # Raw JSON, no client wrapper +export TASKADE_TOKEN=... # your token +npx github:taskade/cli plug cursor --token ``` -Output (raw JSON): - -```json -{ - "mcpServers": { - "taskade": { - "url": "https://www.taskade.com/mcp", - "headers": { - "Authorization": "Bearer tskdp_..." - } - } - } -} +- The CLI reads the token only from `TASKADE_TOKEN`. It refuses a token on the command line, because your shell history keeps it. +- The CLI never prints the full token. It shows the first 6 characters and "…". +- The config file then holds your token, and anyone who can read the file can use your Taskade account. A new file gets mode 600. Do not commit a project file that holds a token. +- Codex keeps only the name `TASKADE_TOKEN` in its config and reads the token from the environment each time it starts. +- Claude Desktop takes no token from the CLI. + +## Check a connection: `doctor` + +```bash +npx github:taskade/cli doctor ``` -`plug claude` adds `"type": "http"` to the block. Claude Code needs this field for a remote server. +`doctor` answers "why does my connection fail?" in plain lines. Each line starts with `ok`, `fail`, or `--` (skipped), and a failed line gives the next step. It changes nothing on your machine. `whoami` is an alias of `doctor`. -For Claude Desktop, add `https://www.taskade.com/mcp` in **Settings > Connectors** and sign in. Claude Desktop does not need a token. +It checks: -### `taskade whoami` +1. The Node.js version. +2. The server: a request with no sign-in must return 401 with a `www-authenticate` header that names the sign-in metadata. It then reads that metadata and the metadata of the authorization server. +3. With `TASKADE_TOKEN` set: an MCP `initialize` request and a `tools/list` request with your token. It reports that the token works and the server lists its tools, or the exact refusal of the server. +4. The clients on your machine, and whether each one has a `taskade` server entry. It only reads the files. -> **This command does not work today.** It calls `GET /api/v2/user`, and the Taskade public API has no such path. The command prints `API returned 404 Not Found` for every token. +Example, with a token that the server does not accept: -```bash -npx github:taskade/cli whoami +```text +ok The server answers. Without sign-in it returns 401 and names its sign-in metadata. +ok Sign-in metadata: https://www.taskade.com/mcp/.well-known/oauth-protected-resource +ok Authorization server: https://www.taskade.com/.well-known/oauth-authorization-server + +fail The server refused the token (401: Invalid or expired token). + Next: Create a new token at https://www.taskade.com/settings/api and set TASKADE_TOKEN to it. ``` -## Environment Variables +| Option | Effect | +| --- | --- | +| `--json` | Print the result as JSON, for scripts. | +| `--verbose` | Print the names of the tools that the server lists. | + +The exit code is 0 when every check passes and 1 when a check fails. `doctor` sends your token only to the server URL, and it does not follow a redirect with the token. -| Variable | Default | Description | -|----------|---------|-------------| -| `TASKADE_TOKEN` | (prompt) | Your personal access token (`tskdp_...`). Create one at [https://www.taskade.com/settings/api](https://www.taskade.com/settings/api) | -| `TASKADE_API_URL` | `https://www.taskade.com` | API base URL for `whoami` | +## Environment + +| Variable | Use | +| --- | --- | +| `TASKADE_TOKEN` | A personal access token. `plug` reads it only with `--token`. `doctor` uses it for the token check. | +| `TASKADE_MCP_URL` | Another server URL, for tests. It must use `https://`, except for `localhost` and `127.0.0.1`. | + +## Other commands + +| Command | Effect | +| --- | --- | +| `help`, `--help`, `-h` | Show the help. | +| `--version`, `-v` | Show the version. | + +An unknown command prints a short message and exits 1. ## Requirements -- Node.js 18+ (uses built-in `fetch`) +Node.js 18 or later. The CLI has no dependencies. + +## For maintainers + +Run the tests with `npm test`. The tests use a temporary HOME and PATH, fake client commands, and a fake MCP server on `127.0.0.1`. They never touch the config of your machine. -## Hosted MCP and the local package +To release a version: -| | Hosted MCP | Local package (stdio) | -|---|-----------|-------------| -| Run | `https://www.taskade.com/mcp` | `npx @taskade/mcp-server` | -| Auth | OAuth sign-in, or a personal access token (`tskdp_...`) | Personal access token (`tskdp_...`) | -| Plan | Every paid plan | See [taskade/mcp](https://github.com/taskade/mcp) | -| Best for | Clients that support remote servers | Clients that support only stdio servers | +1. Set the version in `package.json` and add a section to `CHANGELOG.md`. +2. Change the examples in this README and the `RUN` constant in `src/clients.mjs` from `npx github:taskade/cli` to `npx @taskade/cli` (once, with the first npm release). +3. Publish a GitHub release with the tag `v`. The `Release` workflow checks that the tag equals the version, runs the tests, and publishes to npm with provenance. -Both need network access to taskade.com. The local package calls the Taskade public API. [taskade/mcp](https://github.com/taskade/mcp) lists the tools of each. +The `Release` workflow uses npm trusted publishing (OIDC), so the repository holds no npm token. It cannot work before these two steps, which an owner of the npm scope must do once: -**Use hosted MCP** when your client supports remote servers. +1. Publish the first version by hand from a clean checkout: `npm publish --access public`. +2. On npmjs.com, open the settings of `@taskade/cli` and add a trusted publisher: GitHub Actions, organization `taskade`, repository `cli`, workflow `release.yml`. -## Related +## Security -- [Hosted MCP](https://www.taskade.com/mcp) - the server this CLI configures -- [API v2 docs](https://www.taskade.com/api/documentation/v2) - the REST API the MCP wraps -- [taskade/mcp](https://github.com/taskade/mcp) - the MCP server repo -- [taskade/docs](https://github.com/taskade/docs) - developer documentation +Report a vulnerability to security@taskade.com. See [SECURITY.md](SECURITY.md). ## License -MIT +MIT. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..fe72322 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,24 @@ +# Security policy + +## Report a vulnerability + +Send an email to security@taskade.com. Do not open a public issue for a vulnerability. + +Include: + +- The version of `@taskade/cli` and of Node.js. +- The steps to reproduce the problem. +- The effect that you saw. + +We answer each report, and we tell you when a release includes the fix. + +## Supported versions + +We fix security problems in the newest release only. + +## How the CLI handles a token + +- The CLI reads a personal access token only from the environment variable `TASKADE_TOKEN`. It refuses a token on the command line. +- It never prints the full token. +- It sends the token only to the server URL, only over `https://` (or to `localhost` for tests), and it does not follow a redirect with the token. +- `plug --token` writes the token into the config file of the client. Treat that file as a secret. diff --git a/bin/cli.mjs b/bin/cli.mjs index 54f9f35..c6f209b 100755 --- a/bin/cli.mjs +++ b/bin/cli.mjs @@ -1,221 +1,25 @@ #!/usr/bin/env node -/** - * @taskade/cli - Thin CLI for Taskade MCP plug-and-play. - * - * Commands: - * taskade plug [cursor|claude] Print the MCP server config block for your client. - * taskade whoami Does not work today: GET /api/v2/user does not exist. - * taskade help Show this help. - * - * Usage: - * npx github:taskade/cli plug cursor # copy-paste into Cursor's MCP config - * (The package is not on npm yet. `npx @taskade/cli` fails.) - * - * Environment: - * TASKADE_TOKEN Your Personal Access Token (tskdp_...). If unset, you will be - * prompted to paste it. Get one at https://www.taskade.com/settings/api - * TASKADE_API_URL API base URL for whoami (default: https://www.taskade.com) - */ - -const DEFAULT_API_URL = "https://www.taskade.com"; -const MCP_SERVER_URL = "https://www.taskade.com/mcp"; - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -/** Read a line from stdin (used for token prompt). */ -function readLine() { - return new Promise((resolve) => { - process.stdin.resume(); - process.stdin.setEncoding("utf8"); - if (process.stdin.isTTY) { - // Interactive: wait for a single line (Enter key) - process.stdin.once("data", (data) => { - process.stdin.pause(); - resolve(data.trim()); - }); - } else { - // Non-interactive (pipe): read all of stdin, resolve on end - let data = ""; - process.stdin.on("data", (chunk) => { - data += chunk; - }); - process.stdin.on("end", () => { - process.stdin.pause(); - resolve(data.trim()); - }); - } - }); -} - -/** Get the token from env or prompt. */ -async function getToken() { - if (process.env.TASKADE_TOKEN) return process.env.TASKADE_TOKEN; - process.stderr.write("Paste your Taskade PAT (tskdp_...): "); - return readLine(); -} - -// --------------------------------------------------------------------------- -// Commands -// --------------------------------------------------------------------------- - -/** `taskade plug [cursor|claude]` - print the MCP config block. */ -async function cmdPlug(client) { - const token = await getToken(); - if (!token) { - process.stderr.write("No token provided. Get one at https://www.taskade.com/settings/api\n"); - process.exit(1); - } - - const config = { - mcpServers: { - taskade: { - url: MCP_SERVER_URL, - headers: { - Authorization: `Bearer ${token}`, - }, - }, - }, - }; - - const json = JSON.stringify(config, null, 2); - - if (client === "cursor") { - // Cursor reads ~/.cursor/mcp.json or project .cursor/mcp.json - process.stdout.write(`# Add this to your Cursor MCP config\n`); - process.stdout.write(`# ~/.cursor/mcp.json or .cursor/mcp.json in your project\n\n`); - process.stdout.write(json); - process.stdout.write("\n"); - } else if (client === "claude") { - // Claude Code reads a remote server from .mcp.json only with "type": "http". - // Claude Desktop adds a remote server in Settings > Connectors, not from a file. - const claudeConfig = { - mcpServers: { - taskade: { type: "http", ...config.mcpServers.taskade }, - }, - }; - process.stdout.write(`# Claude Code: add this to .mcp.json in your project root\n`); - process.stdout.write(`# Claude Desktop: add ${MCP_SERVER_URL} in Settings > Connectors and sign in\n\n`); - process.stdout.write(JSON.stringify(claudeConfig, null, 2)); - process.stdout.write("\n"); - } else { - // No client specified - just print the raw JSON - process.stdout.write(json); - process.stdout.write("\n"); - } -} - -/** `taskade whoami` - verify the PAT works. */ -async function cmdWhoami() { - const token = await getToken(); - if (!token) { - process.stderr.write("No token provided. Get one at https://www.taskade.com/settings/api\n"); - process.exit(1); - } - - const apiUrl = process.env.TASKADE_API_URL || DEFAULT_API_URL; - const url = `${apiUrl}/api/v2/user`; - - try { - const res = await fetch(url, { - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/json", - }, - }); - - if (res.status === 401) { - process.stderr.write("Token is invalid or expired. Get a new one at https://www.taskade.com/settings/api\n"); - process.exit(1); - } - - if (res.status === 403) { - process.stderr.write("Token is valid but lacks access. Check your plan at https://taskade.com/settings/billing\n"); - process.exit(1); - } - - if (!res.ok) { - process.stderr.write(`API returned ${res.status} ${res.statusText}\n`); - process.exit(1); - } - - const data = await res.json(); - const name = data.full_name || data.name || data.email || "unknown"; - const email = data.email || ""; - process.stdout.write(`Token works.\n`); - process.stdout.write(` User: ${name}\n`); - if (email) process.stdout.write(` Email: ${email}\n`); - process.stdout.write(` Plan: ${data.plan || "unknown"}\n`); - process.stdout.write(`\nMCP server URL: ${MCP_SERVER_URL}\n`); - } catch (err) { - process.stderr.write(`Request failed: ${err.message}\n`); - process.exit(1); - } -} - -/** `taskade help` - show usage. */ -function cmdHelp() { - process.stdout.write(` -@taskade/cli - Thin CLI for Taskade MCP plug-and-play - -USAGE - taskade [options] - -COMMANDS - plug [cursor|claude] Print the MCP server config block for your client - whoami Does not work today (GET /api/v2/user does not exist) - help Show this help message - -EXAMPLES - npx github:taskade/cli plug cursor # config block for Cursor - npx github:taskade/cli plug claude # config block for Claude Code - npx github:taskade/cli plug # raw JSON, no client wrapper - - The package is not on npm yet, so npx @taskade/cli fails. - -ENVIRONMENT - TASKADE_TOKEN Your PAT (tskdp_...). Get one at https://www.taskade.com/settings/api - TASKADE_API_URL API base URL (default: https://www.taskade.com) - -LEARN MORE - Hosted MCP: https://www.taskade.com/mcp - API docs: https://www.taskade.com/api/documentation/v2 - GitHub: https://github.com/taskade/cli -`); -} - -// --------------------------------------------------------------------------- -// Entry point -// --------------------------------------------------------------------------- - -async function main() { - const [cmd, ...args] = process.argv.slice(2); - - switch (cmd) { - case "plug": - await cmdPlug(args[0]); - break; - case "whoami": - await cmdWhoami(); - break; - case "help": - case "--help": - case "-h": - cmdHelp(); - break; - case undefined: - cmdHelp(); - break; - default: - process.stderr.write(`Unknown command: ${cmd}\n\n`); - cmdHelp(); - process.exit(1); - } -} - -main().catch((err) => { - process.stderr.write(`Error: ${err.message}\n`); - process.exit(1); -}); +// @taskade/cli: connect an MCP client to Taskade, and check the connection. +// Run `taskade help` for the commands. + +import { main } from "../src/cli.mjs"; +import { askOnTerminal } from "../src/system.mjs"; + +main(process.argv.slice(2), { + env: process.env, + cwd: process.cwd(), + platform: process.platform, + interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY), + stdout: process.stdout, + stderr: process.stderr, + ask: askOnTerminal, +}).then( + (code) => { + process.exitCode = code; + }, + (err) => { + process.stderr.write(`Error: ${err.message}\n`); + process.exitCode = 1; + }, +); diff --git a/package.json b/package.json index c8bd49e..241d8d2 100644 --- a/package.json +++ b/package.json @@ -1,32 +1,39 @@ { "name": "@taskade/cli", - "version": "0.1.0", - "description": "Thin CLI for Taskade MCP plug-and-play. One command to connect Cursor/Claude to your Taskade workspace.", + "version": "0.2.0", + "description": "Connect Claude Code, Codex, Cursor, VS Code, or Claude Desktop to the hosted Taskade MCP server, and check the connection.", "type": "module", "bin": { "taskade": "./bin/cli.mjs" }, "files": [ - "bin/" + "bin/", + "src/" ], "scripts": { - "test": "node --test test/*.test.mjs" + "test": "node --test test/cli.test.mjs test/plug.test.mjs test/doctor.test.mjs test/system.test.mjs" }, "keywords": [ "taskade", "mcp", "cli", + "claude-code", + "codex", "cursor", - "claude", + "vscode", "ai-agent" ], "license": "MIT", "homepage": "https://github.com/taskade/cli", + "bugs": "https://github.com/taskade/cli/issues", "repository": { "type": "git", "url": "git+https://github.com/taskade/cli.git" }, "engines": { "node": ">=18" + }, + "publishConfig": { + "access": "public" } } diff --git a/src/cli.mjs b/src/cli.mjs new file mode 100644 index 0000000..cf78104 --- /dev/null +++ b/src/cli.mjs @@ -0,0 +1,146 @@ +// Parse the command line and run one command. +// `main` takes all input from `io`, so that the tests can run it in process. + +import { readFileSync } from "node:fs"; +import { CLIENTS, DEFAULT_SERVER_URL, RUN, findClient } from "./clients.mjs"; +import { doctor } from "./doctor.mjs"; +import { plug } from "./plug.mjs"; + +export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version; + +const FLAGS = { + "--yes": "yes", + "-y": "yes", + "--print": "print", + "--project": "project", + "--token": "token", + "--json": "json", + "--verbose": "verbose", + "--help": "help", + "-h": "help", + "--version": "version", + "-v": "version", +}; + +const COMMAND_FLAGS = { + plug: ["yes", "print", "project", "token"], + doctor: ["json", "verbose"], +}; + +const TOKEN_REFUSAL = + "Never pass a token on the command line. It stays in your shell history.\n" + + "Set the environment variable TASKADE_TOKEN, then add --token."; + +export function helpText() { + const clients = CLIENTS.map((c) => c.id + (c.aliases.length ? ` (${c.aliases.join(", ")})` : "")).join(", "); + return `taskade ${VERSION}: connect an MCP client to Taskade + +USAGE + ${RUN} [options] + +COMMANDS + plug [client] Connect a client to ${DEFAULT_SERVER_URL}. + With no client, list the clients on this machine. + Alias: connect + doctor Check why a connection fails. Changes nothing. + Alias: whoami + help Show this help. + +CLIENTS + ${clients} + +PLUG OPTIONS + --yes Apply the change with no question. + --print Show the command or the config block. Change nothing. + This is the default when the CLI does not run in a terminal. + --project Write the project file of this folder, not the user file. + --token Send a personal access token from TASKADE_TOKEN in a header, + for a machine that cannot sign in with a browser. + +DOCTOR OPTIONS + --json Print the result as JSON. + --verbose Print the names of the tools that the server lists. + +OTHER OPTIONS + --help, -h Show this help. + --version, -v Show the version. + +ENVIRONMENT + TASKADE_TOKEN A personal access token, read only with --token and by doctor. + Create one at https://www.taskade.com/settings/api + TASKADE_MCP_URL Another server URL, for tests. https:// only, except + for localhost and 127.0.0.1. + +Most people need no CLI. Paste this into your agent: + Set up Taskade for me. Read and follow https://www.taskade.com/SKILL.md +`; +} + +export function parseArgs(argv) { + const opts = {}; + const positionals = []; + for (const arg of argv) { + if (arg.startsWith("--token=")) return { error: TOKEN_REFUSAL }; + if (/^tskdp_/i.test(arg)) return { error: TOKEN_REFUSAL }; + if (arg.startsWith("-")) { + const flag = FLAGS[arg]; + if (!flag) return { error: `Unknown option: ${arg}` }; + opts[flag] = true; + } else { + positionals.push(arg); + } + } + return { opts, positionals }; +} + +/** + * Run the CLI. `io` holds: env, cwd, platform, interactive, version, + * stdout and stderr (objects with a write method), and ask (question -> Promise). + * Returns the exit code. + */ +export async function main(argv, io) { + io = { version: VERSION, ...io }; + const parsed = parseArgs(argv); + if (parsed.error) { + io.stderr.write(parsed.error + "\n"); + return 1; + } + const { opts, positionals } = parsed; + if (opts.version) { + io.stdout.write(VERSION + "\n"); + return 0; + } + const [command, ...rest] = positionals; + if (opts.help || command === undefined || command === "help") { + io.stdout.write(helpText()); + return 0; + } + + const name = { connect: "plug", whoami: "doctor" }[command] || command; + if (!COMMAND_FLAGS[name]) { + io.stderr.write(`Unknown command: ${command}\nRun "${RUN} help" to see the commands.\n`); + return 1; + } + const wrong = Object.keys(opts).find((flag) => !COMMAND_FLAGS[name].includes(flag)); + if (wrong) { + io.stderr.write(`The option --${wrong} does not apply to ${command}.\n`); + return 1; + } + // With --token, a word that is not a client name can be the token itself. Do not echo it. + if (opts.token && (rest.length > 1 || (rest[0] && !findClient(rest[0])))) { + io.stderr.write(TOKEN_REFUSAL + "\n"); + return 1; + } + const maxArgs = name === "plug" ? 1 : 0; + if (rest.length > maxArgs) { + io.stderr.write(`Too many arguments for ${command}: ${rest.slice(maxArgs).join(" ")}\n`); + return 1; + } + if (opts.print && opts.yes) { + io.stderr.write("Use --print or --yes, not both.\n"); + return 1; + } + + if (name === "plug") return plug(io, { ...opts, client: rest[0] }); + return doctor(io, opts); +} diff --git a/src/clients.mjs b/src/clients.mjs new file mode 100644 index 0000000..6f0434b --- /dev/null +++ b/src/clients.mjs @@ -0,0 +1,176 @@ +// The MCP clients that this CLI supports, how to find them on the machine, +// and where each one keeps its MCP servers. Each client cites the public +// documentation that shows its config shape and file location. + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { readConfig } from "./config-file.mjs"; +import { exists, getEnv, homeDir, which } from "./system.mjs"; + +export const SERVER_NAME = "taskade"; +export const DEFAULT_SERVER_URL = "https://www.taskade.com/mcp"; +// The command that runs this CLI. Change it to `npx @taskade/cli` after the first npm release. +export const RUN = "npx github:taskade/cli"; +export const TOKEN_PAGE = "https://www.taskade.com/settings/api"; + +/** + * The server URL: TASKADE_MCP_URL, or the hosted Taskade server. + * Only https is allowed, except for localhost and 127.0.0.1 (for tests). + */ +export function serverUrl(io) { + const raw = getEnv(io.env, "TASKADE_MCP_URL") || DEFAULT_SERVER_URL; + let url; + try { + url = new URL(raw); + } catch { + throw new Error(`TASKADE_MCP_URL is not a URL: ${raw}`); + } + const local = url.hostname === "localhost" || url.hostname === "127.0.0.1"; + if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) { + throw new Error(`The server URL must use https:// (http:// only for localhost or 127.0.0.1): ${raw}`); + } + return raw; +} + +export const CLIENTS = [ + { + id: "claude-code", + name: "Claude Code", + aliases: ["claude"], + // Command, scopes, ~/.claude.json and .mcp.json: https://code.claude.com/docs/en/mcp + docs: "https://code.claude.com/docs/en/mcp", + detect: (io) => Boolean(which(io, "claude")), + }, + { + id: "claude-desktop", + name: "Claude Desktop", + aliases: [], + // A remote server is a custom connector in the app, not an entry in a file: + // https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp + docs: "https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp", + detect: (io) => { + if (io.platform === "darwin") return exists(join(homeDir(io), "Library", "Application Support", "Claude")); + if (io.platform === "win32") { + const appData = getEnv(io.env, "APPDATA"); + return Boolean(appData) && exists(join(appData, "Claude")); + } + return false; + }, + }, + { + id: "cursor", + name: "Cursor", + aliases: [], + // ~/.cursor/mcp.json and .cursor/mcp.json, a remote server has "url": https://cursor.com/docs/context/mcp + docs: "https://cursor.com/docs/context/mcp", + detect: (io) => Boolean(which(io, "cursor")) || exists(join(homeDir(io), ".cursor")), + }, + { + id: "codex", + name: "Codex", + aliases: [], + // `codex mcp add --url`, `codex mcp login`, ~/.codex/config.toml: https://developers.openai.com/codex/mcp + // --bearer-token-env-var: https://github.com/openai/codex/blob/main/codex-rs/cli/src/mcp_cmd.rs + docs: "https://developers.openai.com/codex/mcp", + detect: (io) => Boolean(which(io, "codex")), + }, + { + id: "vscode", + name: "VS Code", + aliases: ["code"], + // .vscode/mcp.json with "servers" and "type": "http", and `code --add-mcp`: + // https://code.visualstudio.com/docs/copilot/reference/mcp-configuration + docs: "https://code.visualstudio.com/docs/copilot/reference/mcp-configuration", + detect: (io) => Boolean(which(io, "code")), + }, +]; + +export function findClient(name) { + return CLIENTS.find((c) => c.id === name || c.aliases.includes(name)) || null; +} + +/** The entry that each client keeps for the Taskade server. */ +export function expectedEntry(clientId, url, token) { + const headers = token ? { headers: { Authorization: `Bearer ${token}` } } : {}; + switch (clientId) { + case "claude-code": + case "vscode": + return { type: "http", url, ...headers }; + case "cursor": + return { url, ...headers }; + case "codex": + return token ? { url, bearer_token_env_var: "TASKADE_TOKEN" } : { url }; + default: + return null; + } +} + +export function claudeUserFile(io) { + return join(homeDir(io), ".claude.json"); +} + +export function codexConfigFile(io) { + return join(getEnv(io.env, "CODEX_HOME") || join(homeDir(io), ".codex"), "config.toml"); +} + +/** + * Read the [mcp_servers.taskade] table of a Codex config.toml. + * Reads only the plain `key = "value"` lines that this CLI compares. + */ +export function readCodexEntry(file) { + let text; + try { + text = readFileSync(file, "utf8"); + } catch { + return null; + } + const lines = text.split(/\r?\n/); + const start = lines.findIndex((l) => /^\s*\[\s*mcp_servers\.(taskade|"taskade")\s*\]\s*(#.*)?$/.test(l)); + if (start === -1) return null; + const entry = {}; + for (const line of lines.slice(start + 1)) { + if (/^\s*\[/.test(line)) break; + const m = /^\s*([A-Za-z_]+)\s*=\s*"([^"]*)"\s*(#.*)?$/.exec(line); + if (m && (m[1] === "url" || m[1] === "bearer_token_env_var")) entry[m[1]] = m[2]; + } + return entry; +} + +function jsonEntry(file, key) { + const config = readConfig(file, key); + if (!config.exists) return { file, missing: true }; + if (config.error) return { file, error: config.error }; + return { file, entry: config.data[key]?.[SERVER_NAME] }; +} + +/** + * Every place where a client can hold a Taskade server entry. Read only. + * Returns a list of { file, entry, error, missing, label }. + */ +export function clientEntries(io, clientId) { + const home = homeDir(io); + switch (clientId) { + case "claude-code": { + const user = jsonEntry(claudeUserFile(io), "mcpServers"); + const found = [{ ...user, label: "user" }]; + const config = readConfig(claudeUserFile(io), "mcpServers"); + const local = config.data?.projects?.[io.cwd]?.mcpServers?.[SERVER_NAME]; + if (local) found.push({ file: claudeUserFile(io), entry: local, label: "local" }); + found.push({ ...jsonEntry(join(io.cwd, ".mcp.json"), "mcpServers"), label: "project" }); + return found; + } + case "cursor": + return [ + { ...jsonEntry(join(home, ".cursor", "mcp.json"), "mcpServers"), label: "user" }, + { ...jsonEntry(join(io.cwd, ".cursor", "mcp.json"), "mcpServers"), label: "project" }, + ]; + case "codex": { + const file = codexConfigFile(io); + return [{ file, entry: readCodexEntry(file) || undefined, missing: !exists(file), label: "user" }]; + } + case "vscode": + return [{ ...jsonEntry(join(io.cwd, ".vscode", "mcp.json"), "servers"), label: "project" }]; + default: + return []; + } +} diff --git a/src/config-file.mjs b/src/config-file.mjs new file mode 100644 index 0000000..c5a561a --- /dev/null +++ b/src/config-file.mjs @@ -0,0 +1,250 @@ +// Read and change a JSON config file that holds MCP servers. +// The rules: keep every other key and server, write a backup first, +// write through a temp file and a rename, keep the file mode, and never +// overwrite a file that is not valid JSON. + +import { chmodSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; + +/** + * Read a JSON config file. + * Returns { exists, data, text, error }. `error` is set when the file exists + * but is not a JSON object, or when `key` is not an object. + */ +export function readConfig(file, key) { + let text; + try { + text = readFileSync(file, "utf8"); + } catch (err) { + if (err.code === "ENOENT") return { exists: false, data: {}, text: "" }; + return { exists: true, error: `cannot read the file (${err.code || err.message})` }; + } + if (text.trim() === "") return { exists: true, data: {}, text }; + let data; + try { + data = JSON.parse(text); + } catch (err) { + return { exists: true, text, error: `the file is not valid JSON (${err.message})` }; + } + if (data === null || typeof data !== "object" || Array.isArray(data)) { + return { exists: true, text, error: "the file does not hold a JSON object" }; + } + const servers = data[key]; + if (servers !== undefined && (servers === null || typeof servers !== "object" || Array.isArray(servers))) { + return { exists: true, text, error: `"${key}" in the file is not a JSON object` }; + } + return { exists: true, data, text }; +} + +export function deepEqual(a, b) { + return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b)); +} + +function sortKeys(value) { + if (Array.isArray(value)) return value.map(sortKeys); + if (value && typeof value === "object") { + return Object.fromEntries( + Object.keys(value) + .sort() + .map((k) => [k, sortKeys(value[k])]), + ); + } + return value; +} + +/** The indent of the file: the whitespace of its first indented line, or 2 spaces. */ +function detectIndent(text) { + const match = /^([ \t]+)\S/m.exec(text); + return match ? match[1] : " "; +} + +/** + * The new text of the file with `data[key][name] = entry`. + * It changes only the text of that one entry, so the rest of the file keeps + * its format. If that edit does not give the expected data, it writes the + * whole file again with JSON.stringify. + */ +export function mergedText(config, key, name, entry) { + const data = config.data; + const next = { ...data, [key]: { ...(data[key] || {}), [name]: entry } }; + if (!config.exists || config.text.trim() === "") return JSON.stringify(next, null, " ") + "\n"; + try { + const text = editInPlace(config.text, key, name, entry); + if (deepEqual(JSON.parse(text), next)) return text; + } catch { + // Fall back to a full write below. + } + const newline = config.text.endsWith("\n") ? "\n" : ""; + return JSON.stringify(next, null, detectIndent(config.text)) + newline; +} + +/** Parse valid JSON text into spans: each object holds its members with their positions. */ +function parseSpans(text) { + let i = 0; + const skip = () => { + while (/\s/.test(text[i] || "")) i++; + }; + const string = () => { + const start = i++; + while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1; + i++; + return { start, end: i }; + }; + const value = () => { + skip(); + const start = i; + if (text[i] === "{" || text[i] === "[") { + const object = text[i] === "{"; + const members = []; + i++; + skip(); + if (text[i] === (object ? "}" : "]")) return { start, end: ++i, members }; + for (;;) { + skip(); + if (object) { + const k = string(); + skip(); + i++; // the colon + members.push({ key: JSON.parse(text.slice(k.start, k.end)), value: value() }); + } else { + value(); + } + skip(); + if (text[i++] !== ",") return { start, end: i, members }; + } + } + if (text[i] === '"') return string(); + while (i < text.length && !/[\s,\]}]/.test(text[i])) i++; + return { start, end: i }; + }; + return value(); +} + +function lineIndent(text, pos) { + const lineStart = text.lastIndexOf("\n", pos - 1) + 1; + return /^[ \t]*/.exec(text.slice(lineStart))[0]; +} + +/** Indent every line after the first of a JSON text. */ +function reindent(json, indent, eol) { + return json.replace(/\n/g, eol + indent); +} + +/** Insert `"name": value` as the last member of the object at `span`. */ +function insertMember(text, span, name, value, unit, eol) { + const outer = lineIndent(text, span.end - 1); + const inner = span.members.length ? lineIndent(text, span.members[0].value.start) : outer + unit; + const member = `${JSON.stringify(name)}: ${reindent(JSON.stringify(value, null, unit), inner, eol)}`; + const close = span.end - 1; + if (!span.members.length) return `${text.slice(0, span.start + 1)}${eol}${inner}${member}${eol}${outer}${text.slice(close)}`; + const last = span.members[span.members.length - 1].value.end; + return `${text.slice(0, last)},${eol}${inner}${member}${text.slice(last)}`; +} + +function editInPlace(text, key, name, entry) { + const root = parseSpans(text); + const unit = detectIndent(text); + const eol = text.includes("\r\n") ? "\r\n" : "\n"; + const servers = root.members.find((m) => m.key === key); + if (!servers) return insertMember(text, root, key, { [name]: entry }, unit, eol); + const existing = servers.value.members.find((m) => m.key === name); + if (!existing) return insertMember(text, servers.value, name, entry, unit, eol); + const indent = lineIndent(text, existing.value.start); + const json = reindent(JSON.stringify(entry, null, unit), indent, eol); + return text.slice(0, existing.value.start) + json + text.slice(existing.value.end); +} + +/** + * A line diff of two texts, with 2 lines of context around each change. + * Lines that only the new text has start with "+", removed lines with "-". + */ +export function lineDiff(oldText, newText) { + const a = oldText === "" ? [] : oldText.replace(/\r?\n$/, "").split(/\r?\n/); + const b = newText.replace(/\r?\n$/, "").split(/\r?\n/); + // Longest common subsequence table, built from the end. + const lcs = Array.from({ length: a.length + 1 }, () => new Uint32Array(b.length + 1)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + } + const ops = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + ops.push([" ", a[i]]); + i++; + j++; + } else if (i < a.length && (j === b.length || lcs[i + 1][j] >= lcs[i][j + 1])) { + // Show a removed line before the lines that replace it. + ops.push(["-", a[i]]); + i++; + } else { + ops.push(["+", b[j]]); + j++; + } + } + const keep = ops.map(([op], n) => ops.slice(Math.max(0, n - 2), n + 3).some(([o]) => o !== " ")); + const lines = []; + let skipped = false; + ops.forEach(([op, text], n) => { + if (keep[n]) { + if (skipped) lines.push(" ..."); + skipped = false; + lines.push(`${op} ${text}`); + } else { + skipped = true; + } + }); + if (skipped) lines.push(" ..."); + return lines.join("\n"); +} + +/** Never overwrite an older backup: add -2, -3 and on when the name is taken. */ +function freeBackupPath(base) { + let candidate = base; + for (let n = 2; existsSync(candidate); n++) candidate = `${base}-${n}`; + return candidate; +} + +function timestamp(date) { + return date.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z"); +} + +/** + * Write `text` to `file`. Writes a backup of an existing file first, then a + * temp file beside it, then renames the temp file over the file. + * Keeps the mode of an existing file. A new file gets `newMode`. + * Returns the path of the backup, or null for a new file. + */ +export function writeConfig(file, text, { newMode = 0o644, now = new Date() } = {}) { + let target = file; + let mode = newMode; + let backup = null; + try { + // Write through a symbolic link to the real file, as an editor does. + target = realpathSync(file); + mode = statSync(target).mode & 0o777; + backup = freeBackupPath(`${file}.bak-${timestamp(now)}`); + copyFileSync(target, backup, constants.COPYFILE_EXCL); + chmodSync(backup, mode); + } catch (err) { + if (err.code !== "ENOENT") throw err; + mkdirSync(dirname(file), { recursive: true }); + } + const temp = `${target}.tmp-${process.pid}-${Date.now()}`; + try { + writeFileSync(temp, text, { mode }); + chmodSync(temp, mode); + renameSync(temp, target); + } catch (err) { + try { + unlinkSync(temp); + } catch { + // The temp file was never written. + } + throw err; + } + return backup; +} diff --git a/src/doctor.mjs b/src/doctor.mjs new file mode 100644 index 0000000..119af7a --- /dev/null +++ b/src/doctor.mjs @@ -0,0 +1,373 @@ +// `taskade doctor`: answer "why does my connection fail?" in plain lines. +// It changes nothing on the machine. It sends TASKADE_TOKEN only to the +// server URL, and it never follows a redirect with the token. +// +// Sign-in discovery follows the MCP authorization spec: +// https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization +// The token check follows the Streamable HTTP transport: +// https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http + +import { CLIENTS, RUN, TOKEN_PAGE, clientEntries, serverUrl } from "./clients.mjs"; +import { getEnv, tildify } from "./system.mjs"; + +const PROTOCOL_VERSION = "2025-06-18"; +const TIMEOUT_MS = 15000; + +export async function doctor(io, opts) { + const checks = []; + const add = (group, status, message, next) => checks.push({ group, status, message, ...(next ? { next } : {}) }); + let tools; + + let url; + try { + url = serverUrl(io); + } catch (err) { + add("server", "fail", err.message, "Unset TASKADE_MCP_URL, or set it to an https:// URL."); + } + + const major = Number(process.versions.node.split(".")[0]); + if (major >= 18) add("machine", "ok", `Node.js ${process.version}. This CLI needs Node.js 18 or later.`); + else add("machine", "fail", `Node.js ${process.version} is too old.`, "Install Node.js 18 or later."); + + if (url) { + await checkServer(url, add, io); + const token = (getEnv(io.env, "TASKADE_TOKEN") || "").trim(); + if (!token) { + add("token", "skip", "TASKADE_TOKEN is not set, so the token check is skipped. Clients that sign in need no token."); + } else { + tools = await checkToken(url, token, add, io.version); + } + } + + for (const client of CLIENTS) checkClient(io, client, add); + + const ok = checks.every((c) => c.status !== "fail"); + if (opts.json) { + const result = { ok, server: url || null, checks }; + if (opts.verbose && tools) result.tools = tools; + io.stdout.write(JSON.stringify(result, null, 2) + "\n"); + return ok ? 0 : 1; + } + + const out = (text = "") => io.stdout.write(text + "\n"); + const mark = { ok: "ok ", fail: "fail", skip: "-- " }; + out(`Taskade doctor${url ? ` (server: ${url})` : ""}`); + let group = null; + for (const c of checks) { + if (c.group !== group) { + out(); + if (c.group === "clients") out("Clients (read only):"); + group = c.group; + } + out(`${mark[c.status]} ${c.message}`); + if (c.next) out(` Next: ${c.next}`); + if (c.group === "token" && c.status === "ok" && opts.verbose && tools) { + for (const name of tools) out(` - ${name}`); + } + } + out(); + out(ok ? "Every check passed." : "A check failed. See the Next line under it."); + return ok ? 0 : 1; +} + +function describeError(err) { + if (err?.name === "TimeoutError" || err?.name === "AbortError") return `no answer in ${TIMEOUT_MS / 1000} seconds`; + const cause = err?.cause?.code || err?.cause?.message; + return cause ? `${err.message} (${cause})` : String(err?.message || err); +} + +async function readError(res) { + const text = await res.text().catch(() => ""); + try { + const body = JSON.parse(text); + const message = body.error?.message || body.error_description || body.message || body.error; + if (typeof message === "string") return message; + } catch { + // Not JSON: show the text. + } + return text.trim().slice(0, 200) || res.statusText || "no message"; +} + +async function getJson(target) { + const res = await fetch(target, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) }); + if (!res.ok) throw new Error(`${target} answered ${res.status}`); + try { + return await res.json(); + } catch { + throw new Error(`${target} did not return JSON`); + } +} + +function initializeBody(version) { + return { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: "taskade-cli", version: version || "0.0.0" }, + }, + }; +} + +async function checkServer(url, add, io) { + const next = "Check your network, proxy, or firewall, then run doctor again."; + let res; + try { + res = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, + body: JSON.stringify(initializeBody(io.version)), + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + } catch (err) { + add("server", "fail", `Cannot reach ${url}: ${describeError(err)}.`, next); + return; + } + await res.body?.cancel().catch(() => {}); + const header = res.headers.get("www-authenticate") || ""; + const match = /resource_metadata="([^"]+)"/i.exec(header); + if (res.status !== 401 || !match) { + add( + "server", + "fail", + `Without sign-in the server must answer 401 and name its sign-in metadata. It answered ${res.status}${match ? "" : " with no resource_metadata"}.`, + "Check the server URL. The hosted server is https://www.taskade.com/mcp.", + ); + return; + } + add("server", "ok", "The server answers. Without sign-in it returns 401 and names its sign-in metadata."); + + let resource; + try { + resource = await getJson(match[1]); + } catch (err) { + add("server", "fail", `Cannot read the sign-in metadata: ${describeError(err)}.`, next); + return; + } + const servers = resource.authorization_servers; + if (typeof resource.resource !== "string" || !Array.isArray(servers) || typeof servers[0] !== "string") { + add("server", "fail", `The sign-in metadata at ${match[1]} lacks "resource" or "authorization_servers".`); + return; + } + if (resource.resource.replace(/\/$/, "") !== url.replace(/\/$/, "")) { + add( + "server", + "fail", + `The sign-in metadata names ${resource.resource}, not ${url}. Clients refuse to sign in for it.`, + "Use the URL that the metadata names.", + ); + return; + } + add("server", "ok", `Sign-in metadata: ${match[1]}`); + + const issuer = new URL(servers[0]); + const suffix = issuer.pathname === "/" ? "" : issuer.pathname.replace(/\/$/, ""); + const candidates = [ + `${issuer.origin}/.well-known/oauth-authorization-server${suffix}`, + `${issuer.origin}/.well-known/openid-configuration${suffix}`, + ]; + let meta; + let metaUrl; + for (const candidate of candidates) { + try { + meta = await getJson(candidate); + metaUrl = candidate; + break; + } catch { + // Try the next well-known path. + } + } + if (!meta) { + add("server", "fail", `Cannot read the authorization server metadata of ${servers[0]}.`, next); + return; + } + const missing = ["issuer", "authorization_endpoint", "token_endpoint"].filter((k) => typeof meta[k] !== "string"); + if (!(meta.code_challenge_methods_supported || []).includes("S256")) missing.push("code_challenge_methods_supported with S256"); + if (!meta.registration_endpoint && meta.client_id_metadata_document_supported !== true) missing.push("registration_endpoint"); + if (missing.length) { + add("server", "fail", `The authorization server metadata at ${metaUrl} lacks: ${missing.join(", ")}.`); + return; + } + add("server", "ok", `Authorization server: ${metaUrl}`); +} + +/** Read the JSON-RPC answer with `id` from a JSON body or an event stream. */ +async function readAnswer(res, id) { + const type = res.headers.get("content-type") || ""; + if (type.includes("text/event-stream")) { + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + for (;;) { + const { value, done } = await reader.read(); + if (value) buffer += decoder.decode(value, { stream: true }); + buffer = buffer.replace(/\r\n?/g, "\n"); + if (done) buffer += "\n\n"; + let end; + while ((end = buffer.indexOf("\n\n")) !== -1) { + const event = buffer.slice(0, end); + buffer = buffer.slice(end + 2); + const data = event + .split("\n") + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).replace(/^ /, "")) + .join("\n"); + let message; + try { + message = JSON.parse(data); + } catch { + continue; + } + const found = [].concat(message).find((m) => m && m.id === id); + if (found) { + reader.cancel().catch(() => {}); + return found; + } + } + if (done) throw new Error("the event stream ended with no answer"); + } + } + const body = await res.json(); + const found = [].concat(body).find((m) => m && m.id === id); + if (!found) throw new Error("the answer holds no JSON-RPC response"); + return found; +} + +async function checkToken(url, token, add, version) { + let sessionId = null; + let protocol = null; + const post = (body) => { + const headers = { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + Authorization: `Bearer ${token}`, + }; + if (sessionId) headers["Mcp-Session-Id"] = sessionId; + if (protocol) headers["MCP-Protocol-Version"] = protocol; + return fetch(url, { + method: "POST", + headers, + body: JSON.stringify(body), + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + }; + + // Send one request and return its JSON-RPC answer, or null after a failed check. + const call = async (body, step) => { + let res; + try { + res = await post(body); + } catch (err) { + add("token", "fail", `Cannot reach the server for ${step}: ${describeError(err)}.`); + return null; + } + if (res.status >= 300 && res.status < 400) { + add("token", "fail", `The server answered ${step} with a redirect (${res.status}). The CLI does not send the token on.`); + return null; + } + if (res.status === 401) { + add( + "token", + "fail", + `The server refused the token (401: ${await readError(res)}).`, + `Create a new token at ${TOKEN_PAGE} and set TASKADE_TOKEN to it.`, + ); + return null; + } + if (res.status === 403) { + add( + "token", + "fail", + `The server accepted the token but refused access (403: ${await readError(res)}).`, + "Use a workspace on a paid Taskade plan. Every paid plan includes the hosted MCP server.", + ); + return null; + } + if (!res.ok) { + add("token", "fail", `The server answered ${step} with ${res.status}: ${await readError(res)}.`); + return null; + } + if (body.id === undefined) { + await res.body?.cancel().catch(() => {}); + return {}; + } + if (!sessionId) sessionId = res.headers.get("mcp-session-id"); + let answer; + try { + answer = await readAnswer(res, body.id); + } catch (err) { + add("token", "fail", `Cannot read the answer to ${step}: ${describeError(err)}.`); + return null; + } + if (answer.error) { + add("token", "fail", `The server refused ${step}: ${answer.error.message} (code ${answer.error.code}).`); + return null; + } + return answer; + }; + + const init = await call(initializeBody(version), "initialize"); + if (!init) return undefined; + protocol = init.result?.protocolVersion || PROTOCOL_VERSION; + if (!(await call({ jsonrpc: "2.0", method: "notifications/initialized" }, "notifications/initialized"))) return undefined; + const list = await call({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }, "tools/list"); + if (sessionId) { + // End the session. The answer does not matter. + await fetch(url, { + method: "DELETE", + headers: { Authorization: `Bearer ${token}`, "Mcp-Session-Id": sessionId, "MCP-Protocol-Version": protocol }, + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }) + .then((r) => r.body?.cancel()) + .catch(() => {}); + } + if (!list) return undefined; + const names = (list.result?.tools || []).map((t) => t?.name).filter((n) => typeof n === "string"); + if (names.length === 0) { + add("token", "fail", "The token works, but the server lists no tools.", "Use a workspace on a paid Taskade plan."); + return undefined; + } + add("token", "ok", "The token works and the server lists its tools."); + return names; +} + +function checkClient(io, client, add) { + if (!client.detect(io)) { + add("clients", "skip", `${client.name}: not found on this machine.`); + return; + } + if (client.id === "claude-desktop") { + add( + "clients", + "skip", + `${client.name}: installed. Claude keeps connectors in your Claude account, so the CLI cannot read them.`, + "In Claude Desktop, open Customize, then Connectors, and look for Taskade.", + ); + return; + } + const places = clientEntries(io, client.id); + const found = places.filter((p) => p.entry); + const broken = places.filter((p) => p.error); + for (const p of broken) { + add("clients", "fail", `${client.name}: ${tildify(io, p.file)}: ${p.error}.`, "Fix the file. The client cannot read it either."); + } + if (found.length) { + for (const p of found) { + const usesToken = Boolean(p.entry.headers?.Authorization || p.entry.bearer_token_env_var); + const target = p.entry.url || p.entry.serverUrl || "no url"; + add( + "clients", + "ok", + `${client.name}: taskade server in ${tildify(io, p.file)} (${p.label}${usesToken ? ", token" : ", sign-in"}) points at ${target}.`, + ); + } + return; + } + const where = client.id === "vscode" ? " in .vscode/mcp.json of this folder. The CLI cannot read the user profile" : ""; + add("clients", "skip", `${client.name}: installed, no taskade server found${where}.`, `${RUN} plug ${client.id}`); +} diff --git a/src/plug.mjs b/src/plug.mjs new file mode 100644 index 0000000..0de0186 --- /dev/null +++ b/src/plug.mjs @@ -0,0 +1,354 @@ +// `taskade plug `: connect one MCP client to the Taskade server. +// Sign-in (OAuth) is the default, and no token goes anywhere. +// `--token` puts a personal access token from TASKADE_TOKEN in a header. + +import { join } from "node:path"; +import { + CLIENTS, + RUN, + SERVER_NAME, + TOKEN_PAGE, + claudeUserFile, + codexConfigFile, + expectedEntry, + findClient, + readCodexEntry, + serverUrl, +} from "./clients.mjs"; +import { deepEqual, lineDiff, mergedText, readConfig, writeConfig } from "./config-file.mjs"; +import { copyToClipboard, getEnv, homeDir, mask, runCommand, tildify, which } from "./system.mjs"; + +/** Replace every Bearer value in a text with its first 6 characters. */ +export function redact(text) { + return String(text).replace(/(Bearer\s+)([^\s"'\\]+)/g, (_, prefix, secret) => prefix + mask(secret)); +} + +function show(value) { + return JSON.stringify(value, null, 2) + .split("\n") + .map((line) => " " + line) + .join("\n"); +} + +function commandLine(file, args) { + return [file, ...args].map((a) => (/^[\w\-.:/=@]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`)).join(" "); +} + +export async function plug(io, opts) { + const out = (text = "") => io.stdout.write(redact(text) + "\n"); + const fail = (text) => { + io.stderr.write(redact(text) + "\n"); + return 1; + }; + + if (!opts.client) return listClients(io, out); + + const client = findClient(opts.client); + if (!client) { + return fail(`Unknown client: ${opts.client}\nKnown clients: ${CLIENTS.map((c) => c.id).join(", ")}`); + } + + let url; + try { + url = serverUrl(io); + } catch (err) { + return fail(err.message); + } + + let token = null; + if (opts.token) { + if (client.id === "claude-desktop") { + return fail("Claude Desktop signs in through your browser. It takes no token from this CLI."); + } + token = (getEnv(io.env, "TASKADE_TOKEN") || "").trim(); + if (!token) return fail(`--token reads the token from TASKADE_TOKEN, and TASKADE_TOKEN is not set.\nCreate a token at ${TOKEN_PAGE}`); + if (/\s/.test(token)) return fail("TASKADE_TOKEN holds a space or a line break. Set it to the token only."); + } + + const mode = opts.print ? "print" : opts.yes ? "yes" : io.interactive ? "ask" : "print"; + const flags = [opts.project && "--project", opts.token && "--token"].filter(Boolean); + const applyHint = `Nothing changed. To apply it, run: ${[RUN, "plug", client.id, ...flags, "--yes"].join(" ")}`; + const ctx = { io, opts, out, fail, url, token, mode, applyHint, client }; + + switch (client.id) { + case "claude-code": + return plugClaudeCode(ctx); + case "codex": + return plugCodex(ctx); + case "cursor": + return plugJsonFile(ctx, { + file: join(opts.project ? io.cwd : homeDir(io), ".cursor", "mcp.json"), + key: "mcpServers", + next: token + ? "Next: open Cursor Settings, then MCP. Cursor sends your token, so no sign-in is needed." + : "Next: open Cursor Settings, then MCP. Find taskade and sign in when Cursor asks.", + }); + case "vscode": + if (opts.project) { + return plugJsonFile(ctx, { + file: join(io.cwd, ".vscode", "mcp.json"), + key: "servers", + next: token + ? "Next: open .vscode/mcp.json in VS Code and click Start above taskade. VS Code sends your token." + : "Next: open .vscode/mcp.json in VS Code, click Start above taskade, and sign in when VS Code asks.", + }); + } + return plugVsCodeUser(ctx); + case "claude-desktop": + return plugClaudeDesktop(ctx); + default: + return fail(`Unknown client: ${opts.client}`); + } +} + +function listClients(io, out) { + const found = CLIENTS.filter((c) => c.detect(io)); + const missing = CLIENTS.filter((c) => !found.includes(c)); + if (found.length === 0) { + out("No supported MCP client found on this machine."); + } else { + out("MCP clients on this machine:"); + const width = Math.max(...found.map((c) => c.name.length)); + for (const c of found) out(` ${c.name.padEnd(width)} ${RUN} plug ${c.id}`); + } + if (missing.length) out(`Not found: ${missing.map((c) => `${c.name} (${c.id})`).join(", ")}.`); + out(); + out("Each command shows the change first and asks before it changes anything."); + out("Nothing changed."); + return 0; +} + +function tokenWarning(ctx, file, isProject) { + ctx.out(`Warning: ${file} will hold your token. Anyone who can read the file can use your Taskade account.`); + if (isProject) ctx.out(`Do not commit ${file}. Add it to .gitignore.`); +} + +async function confirm(ctx, question) { + if (ctx.mode === "yes") return true; + const ok = await ctx.io.ask(`${question} [y/N] `); + if (!ok) ctx.out("Nothing changed."); + return ok; +} + +// Claude Code: its own command. The default scope is "user", so the server +// works in every project. --project uses the "project" scope (.mcp.json). +async function plugClaudeCode(ctx) { + const { io, opts, out, fail, url, token } = ctx; + const scope = opts.project ? "project" : "user"; + const args = ["mcp", "add", "--transport", "http", "--scope", scope, SERVER_NAME, url]; + if (token) args.push("--header", `Authorization: Bearer ${token}`); + const file = opts.project ? join(io.cwd, ".mcp.json") : claudeUserFile(io); + const config = readConfig(file, "mcpServers"); + const existing = config.data?.mcpServers?.[SERVER_NAME]; + const expected = expectedEntry("claude-code", url, token); + + out("Claude Code adds the server with its own command:"); + out(` ${commandLine("claude", args)}`); + out( + opts.project + ? "Claude Code writes the server to .mcp.json in this folder, to share with your team." + : "Claude Code keeps the server in ~/.claude.json, for all of your projects.", + ); + if (token) tokenWarning(ctx, tildify(io, file), opts.project); + const signIn = token + ? "Claude Code sends your token, so no sign-in is needed." + : "Next: start Claude Code, type /mcp, select taskade, and sign in."; + + if (existing && deepEqual(existing, expected)) { + out("Claude Code already has this taskade server. Already connected. Nothing changed."); + if (!token) out(signIn.replace("Next: ", "To sign in again: ")); + return 0; + } + if (existing) { + out(`Claude Code already has a different server named taskade in ${tildify(io, file)}.`); + out("Current entry:"); + out(show(existing)); + out("New entry:"); + out(show(expected)); + out(`The CLI removes the current entry first: claude mcp remove --scope ${scope} taskade`); + } + + const bin = which(io, "claude"); + if (!bin) { + out("The claude command is not on your PATH."); + out("Install Claude Code (https://code.claude.com/docs/en/setup), then run the command above."); + return 0; + } + if (ctx.mode === "print") { + out(ctx.applyHint); + return 0; + } + if (!(await confirm(ctx, existing ? "Replace the entry and run this command?" : "Run this command?"))) return 0; + + if (existing) { + const removed = await runCommand(io, bin, ["mcp", "remove", "--scope", scope, SERVER_NAME]); + if (removed.code !== 0) return fail(`claude mcp remove failed (${removed.error || `exit code ${removed.code}`}).`); + } + const added = await runCommand(io, bin, args); + if (added.code !== 0) return fail(`claude mcp add failed (${added.error || `exit code ${added.code}`}).`); + out(`Done. ${signIn}`); + return 0; +} + +// Codex: `codex mcp add` then `codex mcp login`. A new Codex starts the +// sign-in inside `mcp add`. Then the CLI does not run `mcp login` again. +async function plugCodex(ctx) { + const { io, opts, out, fail, url, token } = ctx; + if (opts.project) return fail("Codex has no --project option here. Codex keeps MCP servers in ~/.codex/config.toml."); + const args = ["mcp", "add", SERVER_NAME, "--url", url]; + if (token) args.push("--bearer-token-env-var", "TASKADE_TOKEN"); + const login = ["mcp", "login", SERVER_NAME]; + const file = codexConfigFile(io); + const existing = readCodexEntry(file); + const expected = expectedEntry("codex", url, token); + + out("Codex adds the server with its own commands:"); + out(` ${commandLine("codex", args)}`); + if (!token) out(` ${commandLine("codex", login)}`); + if (token) { + out("Codex reads the token from TASKADE_TOKEN each time it starts. The config file holds only the variable name."); + out("Set TASKADE_TOKEN in the environment where Codex runs."); + } + + if (existing && deepEqual(existing, expected)) { + out("Codex already has this taskade server. Already connected. Nothing changed."); + if (!token) out("If Codex asks you to sign in, run: codex mcp login taskade"); + return 0; + } + if (existing) { + out(`Codex already has a different server named taskade in ${tildify(io, file)}.`); + out("Current entry:"); + out(show(existing)); + out("New entry:"); + out(show(expected)); + out("codex mcp add replaces the current entry."); + } + + const bin = which(io, "codex"); + if (!bin) { + out("The codex command is not on your PATH."); + out("Install Codex (npm install -g @openai/codex, see https://github.com/openai/codex), then run the commands above."); + return 0; + } + if (ctx.mode === "print") { + out(ctx.applyHint); + return 0; + } + if (!(await confirm(ctx, existing ? "Replace the entry and run these commands?" : "Run these commands?"))) return 0; + + const added = await runCommand(io, bin, args, { capture: true }); + if (added.code !== 0) return fail(`codex mcp add failed (${added.error || `exit code ${added.code}`}).`); + if (!token && !/logged in/i.test(added.out)) { + const signedIn = await runCommand(io, bin, login); + if (signedIn.code !== 0) { + return fail("The sign-in did not finish. The server is added. Run this to sign in: codex mcp login taskade"); + } + } + out("Done. Start Codex and type /mcp to see the taskade server."); + return 0; +} + +// VS Code without --project: its own command adds the server to the user profile. +async function plugVsCodeUser(ctx) { + const { io, out, fail, url, token } = ctx; + const entry = { name: SERVER_NAME, ...expectedEntry("vscode", url, token) }; + const args = ["--add-mcp", JSON.stringify(entry)]; + + out("VS Code adds the server to your user profile with its own command:"); + out(` ${commandLine("code", args)}`); + if (token) tokenWarning(ctx, "your VS Code user profile", false); + + const bin = which(io, "code"); + if (!bin) { + out("The code command is not on your PATH."); + out("Add it (https://code.visualstudio.com/docs/configure/command-line), then run the command above."); + out(`Or write .vscode/mcp.json in this folder: ${RUN} plug vscode --project`); + return 0; + } + if (ctx.mode === "print") { + out(ctx.applyHint); + return 0; + } + if (!(await confirm(ctx, "Run this command?"))) return 0; + const added = await runCommand(io, bin, args); + if (added.code !== 0) return fail(`code --add-mcp failed (${added.error || `exit code ${added.code}`}).`); + out( + token + ? "Done. Open VS Code and use the Taskade tools in Copilot Chat agent mode." + : "Done. In VS Code, run MCP: List Servers, start taskade, and sign in when VS Code asks.", + ); + return 0; +} + +// Claude Desktop keeps a remote server as a connector in the Claude account. +// No supported file entry adds a remote server with sign-in, so the CLI +// gives the steps and copies the URL. +async function plugClaudeDesktop(ctx) { + const { io, opts, out, fail, url, mode } = ctx; + if (opts.project) return fail("Claude Desktop has no project file."); + out("Claude Desktop adds a remote server as a custom connector in the app. Do these 3 steps:"); + out(" 1. In Claude Desktop, open Customize, then Connectors. Older versions: Settings, then Connectors."); + out(` 2. Click "+ Add", then "Add custom connector". Type Taskade as the name and paste ${url} as the URL.`); + out(' Keep the default sign-in settings and click "Continue" until you can click "Add".'); + out(" 3. Click Connect, sign in to Taskade, and allow access."); + out("Claude keeps connectors in your Claude account, not in a file on this machine. This CLI cannot add one for you."); + if (mode === "print") return 0; + const tool = await copyToClipboard(io, url); + out(tool ? `Copied ${url} to the clipboard (${tool}).` : "No clipboard command found. Copy the URL from step 2."); + return 0; +} + +// A client that reads a JSON file: merge one entry and keep everything else. +async function plugJsonFile(ctx, { file, key, next }) { + const { io, opts, out, fail, url, token, client, mode } = ctx; + const entry = expectedEntry(client.id, url, token); + const shown = tildify(io, file); + const block = JSON.stringify({ [key]: { [SERVER_NAME]: entry } }, null, 2); + const config = readConfig(file, key); + + out(`${client.name} reads ${shown}.`); + if (config.error) { + fail(`${shown}: ${config.error}. Nothing changed.`); + fail("Fix the file, or add this entry by hand:"); + fail(block); + return 1; + } + const existing = config.data[key]?.[SERVER_NAME]; + if (existing && deepEqual(existing, entry)) { + out("The file already has this taskade entry. Already connected. Nothing changed."); + return 0; + } + if (token) tokenWarning(ctx, shown, opts.project); + + if (mode === "print") { + if (existing) { + out("The file has a different taskade entry:"); + out(show(existing)); + out("Replace it with this entry:"); + } else { + out(config.exists ? "Add this entry to the file:" : "Create the file with this content:"); + } + out(block); + if (token) out("The block shows only the start of your token. Write the file with --yes to put the full token in it."); + out(next); + out(ctx.applyHint); + return 0; + } + + const text = mergedText(config, key, SERVER_NAME, entry); + out(config.exists ? "The change:" : "The new file:"); + if (existing) out("The file has a different taskade entry. The - lines show it and the + lines show the new entry."); + out(lineDiff(config.exists ? config.text : "", text)); + if (!(await confirm(ctx, `Write ${shown}?`))) return 0; + + let backup; + try { + backup = writeConfig(file, text, { newMode: token ? 0o600 : 0o644 }); + } catch (err) { + return fail(`Cannot write ${shown}: ${err.message}. Nothing changed.`); + } + out(`Wrote ${shown}.`); + if (backup) out(`Backup: ${tildify(io, backup)}`); + out(next); + return 0; +} diff --git a/src/system.mjs b/src/system.mjs new file mode 100644 index 0000000..64db889 --- /dev/null +++ b/src/system.mjs @@ -0,0 +1,142 @@ +// Small helpers that touch the machine: PATH lookup, child processes, +// the terminal prompt, the clipboard, and paths in the home folder. +// Every helper reads the environment from `io.env`, not from `process.env`, +// so that the tests can give the CLI a temporary HOME and PATH. + +import { spawn } from "node:child_process"; +import { existsSync, statSync } from "node:fs"; +import { homedir } from "node:os"; +import { delimiter, join } from "node:path"; +import { createInterface } from "node:readline"; + +/** Read an environment variable without regard to case on Windows. */ +export function getEnv(env, name) { + if (env[name] !== undefined) return env[name]; + const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase()); + return key === undefined ? undefined : env[key]; +} + +/** The home folder of the user. HOME on macOS and Linux, USERPROFILE on Windows. */ +export function homeDir(io) { + const value = io.platform === "win32" ? getEnv(io.env, "USERPROFILE") : getEnv(io.env, "HOME"); + return value || homedir(); +} + +/** Show a path with ~ for the home folder. */ +export function tildify(io, file) { + const home = homeDir(io); + return file.startsWith(home + (io.platform === "win32" ? "\\" : "/")) ? "~" + file.slice(home.length) : file; +} + +/** Find a command on PATH. Returns the full path, or null. */ +export function which(io, name) { + const dirs = (getEnv(io.env, "PATH") || "").split(io.platform === "win32" ? ";" : delimiter).filter(Boolean); + const exts = + io.platform === "win32" ? (getEnv(io.env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""]; + for (const dir of dirs) { + for (const ext of exts) { + const candidate = join(dir, name + ext.toLowerCase()); + try { + if (statSync(candidate).isFile()) return candidate; + } catch { + // Not in this folder. + } + } + } + return null; +} + +export function exists(file) { + return existsSync(file); +} + +// cmd.exe gives a special meaning to these characters even inside quotes. +const CMD_UNSAFE = /[%^&|<>!\r\n]/; + +function quoteForCmd(arg) { + if (/^[\w\-.:/=@]+$/.test(arg)) return arg; + return '"' + arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1") + '"'; +} + +/** + * Run a command with the terminal of the user. Returns the exit code and, + * when `capture` is true, the text that the command wrote to stdout. + * The captured text is also shown to the user as it arrives. + */ +export function runCommand(io, file, args, { capture = false } = {}) { + return new Promise((resolve) => { + let child; + const stdio = ["inherit", capture ? "pipe" : "inherit", "inherit"]; + // Windows runs a .cmd or .bat file only through cmd.exe. + if (io.platform === "win32" && /\.(cmd|bat)$/i.test(file)) { + if ([file, ...args].some((a) => CMD_UNSAFE.test(a))) { + resolve({ code: -1, out: "", error: "an argument holds a character that cmd.exe changes" }); + return; + } + const line = [file, ...args].map(quoteForCmd).join(" "); + child = spawn(line, { env: io.env, cwd: io.cwd, stdio, shell: true, windowsHide: true }); + } else { + child = spawn(file, args, { env: io.env, cwd: io.cwd, stdio }); + } + let out = ""; + if (capture) { + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + out += chunk; + io.stdout.write(chunk); + }); + } + child.on("error", (err) => resolve({ code: -1, out, error: err.message })); + child.on("close", (code) => resolve({ code: code ?? -1, out })); + }); +} + +/** Copy text to the clipboard. Returns the name of the command, or null. */ +export async function copyToClipboard(io, text) { + const candidates = + io.platform === "darwin" + ? [["pbcopy", []]] + : io.platform === "win32" + ? [["clip", []]] + : [ + ["wl-copy", []], + ["xclip", ["-selection", "clipboard"]], + ]; + for (const [name, args] of candidates) { + if (name === "wl-copy" && !getEnv(io.env, "WAYLAND_DISPLAY")) continue; + const file = which(io, name); + if (!file) continue; + const ok = await new Promise((resolve) => { + const shell = io.platform === "win32" && /\.(cmd|bat)$/i.test(file); + const child = spawn(shell ? `"${file}"` : file, args, { + env: io.env, + stdio: ["pipe", "ignore", "ignore"], + shell, + windowsHide: true, + }); + child.on("error", () => resolve(false)); + child.on("close", (code) => resolve(code === 0)); + child.stdin.end(text); + }); + if (ok) return name; + } + return null; +} + +/** Ask a yes or no question on the terminal. Only "y" or "yes" is a yes. */ +export function askOnTerminal(question, input = process.stdin, output = process.stderr) { + return new Promise((resolve) => { + const rl = createInterface({ input, output }); + // Resolve before close: close() emits "close" at once, and that handler means "no answer". + rl.question(question, (answer) => { + resolve(/^y(es)?$/i.test(answer.trim())); + rl.close(); + }); + rl.on("close", () => resolve(false)); + }); +} + +/** Show the first 6 characters of a secret and an ellipsis. */ +export function mask(secret) { + return secret.slice(0, 6) + "…"; +} diff --git a/test/cli.test.mjs b/test/cli.test.mjs index 27bccae..ed1ebcb 100644 --- a/test/cli.test.mjs +++ b/test/cli.test.mjs @@ -1,96 +1,69 @@ -import { test } from "node:test"; import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; -import { dirname, join } from "node:path"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { runCli, sandbox } from "./helpers.mjs"; -const __dirname = dirname(fileURLToPath(import.meta.url)); -const CLI = join(__dirname, "..", "bin", "cli.mjs"); +const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); -function runCli(args, env = {}, input = "") { - try { - const output = execFileSync("node", [CLI, ...args], { - encoding: "utf8", - env: { ...process.env, ...env }, - timeout: 5000, - input, - }); - return { stdout: output, stderr: "", exitCode: 0 }; - } catch (err) { - return { - stdout: err.stdout || "", - stderr: err.stderr || "", - exitCode: err.status || 1, - }; +test("help prints the commands, the clients, and the setup prompt", async (t) => { + const box = sandbox(t); + for (const args of [["help"], ["--help"], ["-h"], []]) { + const r = await runCli(box, args); + assert.equal(r.code, 0, args.join(" ")); + for (const word of ["plug", "doctor", "connect", "whoami", "claude-desktop", "--token", "SKILL.md"]) { + assert.ok(r.stdout.includes(word), `${args.join(" ")}: ${word}`); + } } -} - -test("help command prints usage", () => { - const { stdout, exitCode } = runCli(["help"]); - assert.equal(exitCode, 0); - assert.match(stdout, /@taskade\/cli/); - assert.match(stdout, /USAGE/); - assert.match(stdout, /plug/); - assert.match(stdout, /whoami/); }); -test("no args prints help", () => { - const { stdout, exitCode } = runCli([]); - assert.equal(exitCode, 0); - assert.match(stdout, /USAGE/); -}); - -test("--help flag prints help", () => { - const { stdout, exitCode } = runCli(["--help"]); - assert.equal(exitCode, 0); - assert.match(stdout, /USAGE/); +test("--version and -v print the package version", async (t) => { + const box = sandbox(t); + for (const flag of ["--version", "-v"]) { + const r = await runCli(box, [flag]); + assert.equal(r.code, 0); + assert.equal(r.stdout.trim(), pkg.version); + } }); -test("unknown command exits 1", () => { - const { exitCode } = runCli(["nonexistent"]); - assert.equal(exitCode, 1); +test("an unknown command prints a short message and exits 1", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["nonexistent"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /Unknown command: nonexistent/); + assert.ok(r.stderr.split("\n").length <= 3, "the message is short"); }); -test("plug with token outputs valid JSON", () => { - const { stdout, exitCode } = runCli(["plug"], { - TASKADE_TOKEN: "tskdp_test123", - }); - assert.equal(exitCode, 0); - const parsed = JSON.parse(stdout); - assert.ok(parsed.mcpServers); - assert.ok(parsed.mcpServers.taskade); - assert.equal(parsed.mcpServers.taskade.url, "https://www.taskade.com/mcp"); - assert.equal(parsed.mcpServers.taskade.headers.Authorization, "Bearer tskdp_test123"); +test("an unknown option exits 1", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--force"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /Unknown option: --force/); }); -test("plug cursor includes Cursor instructions", () => { - const { stdout, exitCode } = runCli(["plug", "cursor"], { - TASKADE_TOKEN: "tskdp_test123", - }); - assert.equal(exitCode, 0); - assert.match(stdout, /Cursor/); - assert.match(stdout, /\.cursor\/mcp\.json/); +test("an option of another command exits 1", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["doctor", "--yes"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /--yes does not apply to doctor/); }); -test("plug claude includes Claude instructions", () => { - const { stdout, exitCode } = runCli(["plug", "claude"], { - TASKADE_TOKEN: "tskdp_test123", - }); - assert.equal(exitCode, 0); - assert.match(stdout, /Claude Code/); - assert.match(stdout, /\.mcp\.json/); - const parsed = JSON.parse(stdout.slice(stdout.indexOf("{"))); - assert.equal(parsed.mcpServers.taskade.type, "http"); - assert.equal(parsed.mcpServers.taskade.url, "https://www.taskade.com/mcp"); - assert.equal(parsed.mcpServers.taskade.headers.Authorization, "Bearer tskdp_test123"); +test("--print and --yes together exit 1", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--print", "--yes"]); + assert.equal(r.code, 1); }); -test("plug without token exits 1", () => { - const { exitCode } = runCli(["plug"], { TASKADE_TOKEN: "" }); - assert.equal(exitCode, 1); +test("an unknown client exits 1 and lists the known clients", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "notepad"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /Unknown client: notepad/); + assert.match(r.stderr, /claude-code, claude-desktop, cursor, codex, vscode/); }); -test("whoami without token exits 1", () => { - const { exitCode } = runCli(["whoami"], { TASKADE_TOKEN: "" }); - assert.equal(exitCode, 1); +test("TASKADE_MCP_URL must be https, except for localhost", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--print"], { TASKADE_MCP_URL: "http://example.com/mcp" }); + assert.equal(r.code, 1); + assert.match(r.stderr, /must use https:\/\//); }); diff --git a/test/doctor.test.mjs b/test/doctor.test.mjs new file mode 100644 index 0000000..d21c6f5 --- /dev/null +++ b/test/doctor.test.mjs @@ -0,0 +1,166 @@ +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { join } from "node:path"; +import { test } from "node:test"; +import { downUrl, fakeMcpServer, runCli, sandbox } from "./helpers.mjs"; + +const GOOD = "tskdp_good_token_123"; +const BAD = "tskdp_fake_token_000000"; + +test("doctor with no token: the server answers 401 with sign-in metadata", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: server.url }); + assert.equal(r.code, 0, r.stdout + r.stderr); + assert.match(r.stdout, /^ok\s+Node\.js/m); + assert.match(r.stdout, /^ok\s+The server answers/m); + assert.match(r.stdout, /^ok\s+Sign-in metadata: http:\/\/127\.0\.0\.1:\d+\/mcp\/\.well-known\/oauth-protected-resource/m); + assert.match(r.stdout, /^ok\s+Authorization server: .*\/\.well-known\/oauth-authorization-server/m); + assert.match(r.stdout, /^--\s+TASKADE_TOKEN is not set/m); + assert.match(r.stdout, /Every check passed/); + assert.ok(server.requests.every((q) => !q.headers.authorization), "no request carries a token"); +}); + +test("whoami is an alias of doctor", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + const r = await runCli(box, ["whoami"], { TASKADE_MCP_URL: server.url }); + assert.equal(r.code, 0); + assert.match(r.stdout, /Taskade doctor/); +}); + +test("doctor with a bad token reports the refusal and exits 1", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: server.url, TASKADE_TOKEN: BAD }); + assert.equal(r.code, 1); + assert.match(r.stdout, /^fail\s+The server refused the token \(401: Invalid or expired token\)/m); + assert.match(r.stdout, /Next: Create a new token at https:\/\/www\.taskade\.com\/settings\/api/); + assert.ok(!r.stdout.includes(BAD) && !r.stderr.includes(BAD)); +}); + +for (const mode of ["json", "sse"]) { + test(`doctor with a working token, ${mode} answers: initialize and tools/list`, async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t, mode); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: server.url, TASKADE_TOKEN: GOOD }); + assert.equal(r.code, 0, r.stdout + r.stderr); + assert.match(r.stdout, /^ok\s+The token works and the server lists its tools\./m); + assert.doesNotMatch(r.stdout, /list_spaces/, "tool names only with --verbose"); + assert.ok(!r.stdout.includes(GOOD)); + + const posts = server.requests.filter((q) => q.method === "POST" && q.headers.authorization); + assert.deepEqual( + posts.map((q) => JSON.parse(q.body).method), + ["initialize", "notifications/initialized", "tools/list"], + ); + assert.equal(posts[2].headers["mcp-session-id"], "session-1"); + assert.equal(posts[2].headers["mcp-protocol-version"], "2025-06-18"); + assert.match(posts[0].headers.accept, /application\/json/); + assert.match(posts[0].headers.accept, /text\/event-stream/); + const withToken = server.requests.filter((q) => q.headers.authorization); + assert.ok(withToken.every((q) => q.url === "/mcp"), "the token goes only to the server URL"); + }); +} + +test("doctor --verbose prints the tool names", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + const r = await runCli(box, ["doctor", "--verbose"], { TASKADE_MCP_URL: server.url, TASKADE_TOKEN: GOOD }); + assert.equal(r.code, 0); + assert.match(r.stdout, /- list_spaces/); + assert.match(r.stdout, /- create_task/); +}); + +test("doctor --json prints the result as JSON", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + const r = await runCli(box, ["doctor", "--json"], { TASKADE_MCP_URL: server.url, TASKADE_TOKEN: GOOD }); + assert.equal(r.code, 0); + const result = JSON.parse(r.stdout); + assert.equal(result.ok, true); + assert.equal(result.server, server.url); + assert.ok(result.checks.some((c) => c.group === "token" && c.status === "ok")); + assert.equal(result.tools, undefined); + + const bad = await runCli(box, ["doctor", "--json", "--verbose"], { TASKADE_MCP_URL: server.url, TASKADE_TOKEN: BAD }); + assert.equal(bad.code, 1); + assert.equal(JSON.parse(bad.stdout).ok, false); +}); + +test("doctor reports a 403 with the plan step", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t, "forbidden"); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: server.url, TASKADE_TOKEN: GOOD }); + assert.equal(r.code, 1); + assert.match(r.stdout, /refused access \(403: MCP access is not available/); + assert.match(r.stdout, /Next: Use a workspace on a paid Taskade plan/); +}); + +test("doctor reports a server that is down", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: await downUrl() }); + assert.equal(r.code, 1); + assert.match(r.stdout, /^fail\s+Cannot reach http:\/\/127\.0\.0\.1:\d+\/mcp/m); +}); + +test("doctor never sends the token on through a redirect", async (t) => { + const box = sandbox(t); + const seen = []; + const other = createServer((req, res) => { + seen.push(req.headers.authorization); + res.end(); + }); + await new Promise((resolve) => other.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => other.close(resolve))); + const redirecting = createServer((req, res) => { + if (!req.headers.authorization) { + const base = `http://127.0.0.1:${redirecting.address().port}`; + res.writeHead(401, { "www-authenticate": `Bearer resource_metadata="${base}/meta"` }); + return res.end(); + } + res.writeHead(307, { location: `http://127.0.0.1:${other.address().port}/mcp` }); + res.end(); + }); + await new Promise((resolve) => redirecting.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => redirecting.close(resolve))); + const r = await runCli(box, ["doctor"], { + TASKADE_MCP_URL: `http://127.0.0.1:${redirecting.address().port}/mcp`, + TASKADE_TOKEN: GOOD, + }); + assert.equal(r.code, 1); + assert.match(r.stdout, /redirect \(307\)/); + assert.ok(seen.every((h) => h === undefined), "the other host never gets the token"); +}); + +test("doctor refuses an http URL that is not localhost and sends nothing", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: "http://example.com/mcp", TASKADE_TOKEN: GOOD }); + assert.equal(r.code, 1); + assert.match(r.stdout, /must use https:\/\//); + assert.doesNotMatch(r.stdout, /Cannot reach/); +}); + +test("doctor lists the clients and their taskade entries, read only", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + mkdirSync(join(box.home, ".cursor")); + writeFileSync(join(box.home, ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { taskade: { url: server.url } } })); + mkdirSync(join(box.cwd, ".vscode")); + writeFileSync(join(box.cwd, ".vscode", "mcp.json"), "{ not json"); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: server.url }); + assert.match(r.stdout, /^ok\s+Cursor: taskade server in ~[\\/]\.cursor[\\/]mcp\.json \(user, sign-in\)/m); + assert.match(r.stdout, /^--\s+Codex: not found on this machine\./m); + assert.equal(r.code, 0, "an invalid file of a client that is not installed is not checked"); +}); + +test("doctor fails on an invalid config file of an installed client", async (t) => { + const box = sandbox(t); + const server = await fakeMcpServer(t); + mkdirSync(join(box.home, ".cursor")); + writeFileSync(join(box.home, ".cursor", "mcp.json"), "{ not json"); + const r = await runCli(box, ["doctor"], { TASKADE_MCP_URL: server.url }); + assert.equal(r.code, 1); + assert.match(r.stdout, /^fail\s+Cursor: .*not valid JSON/m); +}); diff --git a/test/fixtures/fake-client.mjs b/test/fixtures/fake-client.mjs new file mode 100644 index 0000000..8e7958a --- /dev/null +++ b/test/fixtures/fake-client.mjs @@ -0,0 +1,17 @@ +// A fake client command (claude, codex, code) or clipboard command for the tests. +// It records its arguments and its stdin in FAKE_LOG_DIR/.log, one JSON line +// for each call, prints FAKE__STDOUT, and exits with FAKE__EXIT. + +import { appendFileSync } from "node:fs"; +import { join } from "node:path"; + +const [name, ...args] = process.argv.slice(2); +const key = name.toUpperCase().replace(/[^A-Z0-9]/g, "_"); + +let input = ""; +if (process.env[`FAKE_${key}_STDIN`] === "1") { + for await (const chunk of process.stdin) input += chunk; +} +appendFileSync(join(process.env.FAKE_LOG_DIR, `${name}.log`), JSON.stringify({ args, input }) + "\n"); +if (process.env[`FAKE_${key}_STDOUT`]) process.stdout.write(process.env[`FAKE_${key}_STDOUT`] + "\n"); +process.exitCode = Number(process.env[`FAKE_${key}_EXIT`] || 0); diff --git a/test/helpers.mjs b/test/helpers.mjs new file mode 100644 index 0000000..73d008c --- /dev/null +++ b/test/helpers.mjs @@ -0,0 +1,173 @@ +// Test helpers. Every test runs in a temporary folder with its own HOME, +// USERPROFILE, APPDATA, and PATH, so no test reads or writes a real client config. + +import { spawn } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { main } from "../src/cli.mjs"; + +const here = dirname(fileURLToPath(import.meta.url)); +export const CLI = join(here, "..", "bin", "cli.mjs"); +const FAKE = join(here, "fixtures", "fake-client.mjs"); +const IS_WINDOWS = process.platform === "win32"; + +const SCRUB = /^(path|home|userprofile|appdata|localappdata|xdg_config_home|codex_home|taskade_token|taskade_mcp_url|wayland_display|display)$/i; + +/** A temporary folder with home/, work/ (the current folder) and bin/ (the only PATH entry). */ +export function sandbox(t) { + const root = mkdtempSync(join(tmpdir(), "taskade-cli-test-")); + const home = join(root, "home"); + const cwd = join(root, "work"); + const bin = join(root, "bin"); + const logs = join(root, "logs"); + for (const dir of [home, cwd, bin, logs]) mkdirSync(dir, { recursive: true }); + const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !SCRUB.test(k))); + Object.assign(env, { + PATH: bin, + HOME: home, + USERPROFILE: home, + APPDATA: join(home, "AppData", "Roaming"), + LOCALAPPDATA: join(home, "AppData", "Local"), + FAKE_LOG_DIR: logs, + }); + t.after(() => rmSync(root, { recursive: true, force: true })); + return { root, home, cwd, bin, logs, env }; +} + +/** Put a fake command on the PATH of the sandbox. */ +export function fakeCommand(box, name) { + if (IS_WINDOWS) { + writeFileSync(join(box.bin, `${name}.cmd`), `@"${process.execPath}" "${FAKE}" ${name} %*\r\n`); + } else { + const file = join(box.bin, name); + writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${FAKE}" ${name} "$@"\n`); + chmodSync(file, 0o755); + } +} + +/** The calls that a fake command recorded. */ +export function calls(box, name) { + const file = join(box.logs, `${name}.log`); + if (!existsSync(file)) return []; + return readFileSync(file, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line)); +} + +/** Run the CLI as a child process. Its stdin is a pipe, so it is not interactive. */ +export function runCli(box, args, extraEnv = {}) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [CLI, ...args], { + cwd: box.cwd, + env: { ...box.env, ...extraEnv }, + stdio: ["pipe", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (d) => (stdout += d)); + child.stderr.on("data", (d) => (stderr += d)); + child.stdin.end(); + child.on("close", (code) => resolve({ code, stdout, stderr })); + }); +} + +/** Run the CLI in this process as if in a terminal. `answer` is the reply to each question. */ +export async function runInTerminal(box, args, { answer = false, extraEnv = {} } = {}) { + let stdout = ""; + let stderr = ""; + const questions = []; + const code = await main(args, { + env: { ...box.env, ...extraEnv }, + cwd: box.cwd, + platform: process.platform, + interactive: true, + stdout: { write: (s) => (stdout += s) }, + stderr: { write: (s) => (stderr += s) }, + ask: async (q) => { + questions.push(q); + return answer; + }, + }); + return { code, stdout, stderr, questions }; +} + +/** + * A fake MCP server on 127.0.0.1. `mode` sets the answer for the good token: + * "json", "sse", or "forbidden". The good token is "tskdp_good_token_123". + * Every request is recorded in `requests`. + */ +export async function fakeMcpServer(t, mode = "json") { + const requests = []; + const server = createServer(async (req, res) => { + let body = ""; + for await (const chunk of req) body += chunk; + requests.push({ method: req.method, url: req.url, headers: req.headers, body }); + const base = `http://127.0.0.1:${server.address().port}`; + const json = (status, value, headers = {}) => { + res.writeHead(status, { "content-type": "application/json", ...headers }); + res.end(JSON.stringify(value)); + }; + + if (req.method === "GET" && req.url === "/mcp/.well-known/oauth-protected-resource") { + return json(200, { resource: `${base}/mcp`, authorization_servers: [base], scopes_supported: ["mcp"] }); + } + if (req.method === "GET" && req.url === "/.well-known/oauth-authorization-server") { + return json(200, { + issuer: base, + authorization_endpoint: `${base}/oauth2/authorize`, + token_endpoint: `${base}/oauth2/token`, + registration_endpoint: `${base}/oauth2/register`, + code_challenge_methods_supported: ["S256"], + }); + } + if (req.url !== "/mcp") return json(404, { error: "Not found" }); + + const auth = req.headers.authorization; + const challenge = { "www-authenticate": `Bearer realm="mcp", resource_metadata="${base}/mcp/.well-known/oauth-protected-resource"` }; + if (!auth) return json(401, { error: "Unauthorized" }, challenge); + if (auth !== "Bearer tskdp_good_token_123") return json(401, { error: "Invalid or expired token" }, challenge); + if (mode === "forbidden") return json(403, { error: "MCP access is not available on this workspace's current plan." }); + if (req.method === "DELETE") { + res.writeHead(204); + return res.end(); + } + + const message = JSON.parse(body); + if (message.id === undefined) { + res.writeHead(202); + return res.end(); + } + if (message.method !== "initialize" && req.headers["mcp-session-id"] !== "session-1") { + return json(400, { jsonrpc: "2.0", id: message.id, error: { code: -32000, message: "No valid session" } }); + } + const result = + message.method === "initialize" + ? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "fake", version: "1" } } + : { tools: [{ name: "list_spaces" }, { name: "create_task" }] }; + const answer = { jsonrpc: "2.0", id: message.id, result }; + const headers = message.method === "initialize" ? { "mcp-session-id": "session-1" } : {}; + if (mode === "sse") { + res.writeHead(200, { "content-type": "text/event-stream", ...headers }); + res.write(": comment\n\n"); + res.write(`event: message\ndata: ${JSON.stringify(answer)}\n\n`); + return res.end(); + } + return json(200, answer, headers); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + return { url: `http://127.0.0.1:${server.address().port}/mcp`, requests }; +} + +/** A URL on 127.0.0.1 where nothing listens. */ +export async function downUrl() { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address(); + await new Promise((resolve) => server.close(resolve)); + return `http://127.0.0.1:${port}/mcp`; +} diff --git a/test/plug.test.mjs b/test/plug.test.mjs new file mode 100644 index 0000000..dbaf880 --- /dev/null +++ b/test/plug.test.mjs @@ -0,0 +1,485 @@ +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import { calls, fakeCommand, runCli, runInTerminal, sandbox } from "./helpers.mjs"; + +const SERVER = "https://www.taskade.com/mcp"; +const TOKEN = "tskdp_secret_value_0123456789"; +const POSIX = process.platform !== "win32"; + +function cursorFile(box) { + return join(box.home, ".cursor", "mcp.json"); +} + +function writeJson(file, value, text) { + mkdirSync(join(file, ".."), { recursive: true }); + writeFileSync(file, text ?? JSON.stringify(value, null, 2) + "\n"); +} + +function backups(file) { + const dir = join(file, ".."); + const base = file.split(/[\\/]/).pop(); + return readdirSync(dir).filter((f) => f.startsWith(`${base}.bak-`)); +} + +function noTokenIn(r) { + assert.ok(!r.stdout.includes(TOKEN), "stdout must not hold the full token"); + assert.ok(!r.stderr.includes(TOKEN), "stderr must not hold the full token"); +} + +// --print for each client + +test("plug claude-code --print shows the command and runs nothing", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const r = await runCli(box, ["plug", "claude-code", "--print"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /claude mcp add --transport http --scope user taskade https:\/\/www\.taskade\.com\/mcp/); + assert.match(r.stdout, /Nothing changed/); + assert.deepEqual(calls(box, "claude"), []); +}); + +test("plug claude is an alias of claude-code", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "claude", "--print"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /claude mcp add --transport http --scope user taskade/); +}); + +test("plug codex --print shows both commands", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "codex", "--print"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /codex mcp add taskade --url https:\/\/www\.taskade\.com\/mcp/); + assert.match(r.stdout, /codex mcp login taskade/); +}); + +test("plug cursor --print shows the block and writes nothing", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--print"]); + assert.equal(r.code, 0); + const block = JSON.parse(r.stdout.slice(r.stdout.indexOf("{"), r.stdout.lastIndexOf("}") + 1)); + assert.deepEqual(block, { mcpServers: { taskade: { url: SERVER } } }); + assert.throws(() => statSync(cursorFile(box))); +}); + +test("plug vscode --print shows the code --add-mcp command", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "vscode", "--print"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /code --add-mcp '\{"name":"taskade","type":"http","url":"https:\/\/www\.taskade\.com\/mcp"\}'/); +}); + +test("plug vscode --project --print shows the .vscode/mcp.json block with servers", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "vscode", "--project", "--print"]); + assert.equal(r.code, 0); + const block = JSON.parse(r.stdout.slice(r.stdout.indexOf("{"), r.stdout.lastIndexOf("}") + 1)); + assert.deepEqual(block, { servers: { taskade: { type: "http", url: SERVER } } }); +}); + +test("plug claude-desktop --print gives the 3 steps and copies nothing", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "claude-desktop", "--print"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /1\. .*Connectors/); + assert.match(r.stdout, /2\. .*Add custom connector.*https:\/\/www\.taskade\.com\/mcp/); + assert.match(r.stdout, /3\. .*sign in/); + assert.match(r.stdout, /cannot add one for you/); + assert.doesNotMatch(r.stdout, /Copied/); +}); + +test("on a pipe with no flag, plug only prints", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const a = await runCli(box, ["plug", "claude-code"]); + const b = await runCli(box, ["plug", "cursor"]); + assert.equal(a.code, 0); + assert.equal(b.code, 0); + assert.match(b.stdout, /--yes/); + assert.deepEqual(calls(box, "claude"), []); + assert.throws(() => statSync(cursorFile(box))); +}); + +// plug with no client + +test("plug with no client lists the clients on the machine and changes nothing", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + mkdirSync(join(box.home, ".cursor")); + const r = await runCli(box, ["plug"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /Claude Code\s+npx github:taskade\/cli plug claude-code/); + assert.match(r.stdout, /Cursor\s+npx github:taskade\/cli plug cursor/); + assert.match(r.stdout, /Not found: .*Codex/); + assert.deepEqual(calls(box, "claude"), []); + assert.deepEqual(readdirSync(join(box.home, ".cursor")), []); +}); + +test("connect is an alias of plug", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["connect"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /No supported MCP client found/); +}); + +// JSON merge + +test("cursor: --yes creates a new file", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(JSON.parse(readFileSync(cursorFile(box), "utf8")), { mcpServers: { taskade: { url: SERVER } } }); + assert.deepEqual(backups(cursorFile(box)), []); + assert.match(r.stdout, /Wrote ~[\\/]\.cursor[\\/]mcp\.json/); +}); + +test("cursor: --yes keeps other servers and other keys, and writes a backup", async (t) => { + const box = sandbox(t); + const before = { theme: "dark", mcpServers: { github: { url: "https://example.com/mcp" }, local: { command: "x" } } }; + const original = JSON.stringify(before, null, 4) + "\n"; + writeJson(cursorFile(box), null, original); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 0, r.stderr); + const text = readFileSync(cursorFile(box), "utf8"); + assert.deepEqual(JSON.parse(text), { + theme: "dark", + mcpServers: { github: { url: "https://example.com/mcp" }, local: { command: "x" }, taskade: { url: SERVER } }, + }); + assert.match(text, /^ {4}"theme"/m, "keeps the indent of the file"); + const [backup] = backups(cursorFile(box)); + assert.ok(backup, "a backup is written"); + assert.equal(readFileSync(join(box.home, ".cursor", backup), "utf8"), original); + assert.match(r.stdout, /\+\s+"taskade"/); +}); + +test("cursor: the merge changes only the lines of the taskade entry", async (t) => { + const box = sandbox(t); + const cases = [ + [ + '{\n "mcpServers": {\n "github": { "url": "https://example.com/mcp" }\n }\n}\n', + '{\n "mcpServers": {\n "github": { "url": "https://example.com/mcp" },\n "taskade": {\n "url": "https://www.taskade.com/mcp"\n }\n }\n}\n', + ], + [ + '{\n "theme": "dark"\n}\n', + '{\n "theme": "dark",\n "mcpServers": {\n "taskade": {\n "url": "https://www.taskade.com/mcp"\n }\n }\n}\n', + ], + [ + '{\n "mcpServers": {\n "taskade": { "url": "https://old.example.com" },\n "x": { "url": "https://x.example.com" }\n }\n}', + '{\n "mcpServers": {\n "taskade": {\n "url": "https://www.taskade.com/mcp"\n },\n "x": { "url": "https://x.example.com" }\n }\n}', + ], + ['{"mcpServers":{}}', '{"mcpServers":{\n "taskade": {\n "url": "https://www.taskade.com/mcp"\n }\n}}'], + [ + '{\r\n "mcpServers": {\r\n "a": { "url": "https://a.example.com" }\r\n }\r\n}\r\n', + '{\r\n "mcpServers": {\r\n "a": { "url": "https://a.example.com" },\r\n "taskade": {\r\n "url": "https://www.taskade.com/mcp"\r\n }\r\n }\r\n}\r\n', + ], + ]; + for (const [before, after] of cases) { + writeJson(cursorFile(box), null, before); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.equal(readFileSync(cursorFile(box), "utf8"), after); + } +}); + +test("cursor: an equal entry says already connected and changes nothing", async (t) => { + const box = sandbox(t); + const text = JSON.stringify({ mcpServers: { taskade: { url: SERVER } } }); + writeJson(cursorFile(box), null, text); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /Already connected/); + assert.equal(readFileSync(cursorFile(box), "utf8"), text); + assert.deepEqual(backups(cursorFile(box)), []); +}); + +test("cursor: a different entry is shown and replaced only after a yes", async (t) => { + const box = sandbox(t); + const old = { mcpServers: { taskade: { url: "https://old.example.com/mcp" } } }; + writeJson(cursorFile(box), old); + + const no = await runInTerminal(box, ["plug", "cursor"], { answer: false }); + assert.equal(no.code, 0); + assert.equal(no.questions.length, 1); + assert.match(no.stdout, /-\s+"url": "https:\/\/old\.example\.com\/mcp"/); + assert.match(no.stdout, /\+\s+"url": "https:\/\/www\.taskade\.com\/mcp"/); + assert.deepEqual(JSON.parse(readFileSync(cursorFile(box), "utf8")), old); + + const yes = await runInTerminal(box, ["plug", "cursor"], { answer: true }); + assert.equal(yes.code, 0); + assert.deepEqual(JSON.parse(readFileSync(cursorFile(box), "utf8")), { mcpServers: { taskade: { url: SERVER } } }); + assert.equal(backups(cursorFile(box)).length, 1); +}); + +test("cursor: invalid JSON is refused and left unchanged", async (t) => { + const box = sandbox(t); + const text = '{ "mcpServers": { // a comment\n } }\n'; + writeJson(cursorFile(box), null, text); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /not valid JSON/); + assert.match(r.stderr, /Nothing changed/); + assert.equal(readFileSync(cursorFile(box), "utf8"), text); + assert.deepEqual(backups(cursorFile(box)), []); +}); + +test("cursor: a non-object mcpServers is refused", async (t) => { + const box = sandbox(t); + writeJson(cursorFile(box), { mcpServers: [] }); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /"mcpServers" in the file is not a JSON object/); +}); + +test("cursor: the file mode is kept", { skip: !POSIX }, async (t) => { + const box = sandbox(t); + writeJson(cursorFile(box), { mcpServers: {} }); + chmodSync(cursorFile(box), 0o640); + const r = await runCli(box, ["plug", "cursor", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.equal(statSync(cursorFile(box)).mode & 0o777, 0o640); + const [backup] = backups(cursorFile(box)); + assert.equal(statSync(join(box.home, ".cursor", backup)).mode & 0o777, 0o640); +}); + +test("cursor --project writes .cursor/mcp.json in the current folder", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--project", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(JSON.parse(readFileSync(join(box.cwd, ".cursor", "mcp.json"), "utf8")), { + mcpServers: { taskade: { url: SERVER } }, + }); + assert.throws(() => statSync(cursorFile(box))); +}); + +test("vscode --project --yes writes .vscode/mcp.json with the servers key", async (t) => { + const box = sandbox(t); + writeJson(join(box.cwd, ".vscode", "mcp.json"), { servers: { other: { type: "stdio", command: "x" } }, inputs: [] }); + const r = await runCli(box, ["plug", "vscode", "--project", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(JSON.parse(readFileSync(join(box.cwd, ".vscode", "mcp.json"), "utf8")), { + servers: { other: { type: "stdio", command: "x" }, taskade: { type: "http", url: SERVER } }, + inputs: [], + }); +}); + +// --token + +test("--token writes the token to the file but never prints it", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--token", "--yes"], { TASKADE_TOKEN: TOKEN }); + assert.equal(r.code, 0, r.stderr); + noTokenIn(r); + assert.match(r.stdout, /tskdp_…/); + assert.match(r.stdout, /Warning: .* will hold your token/); + const data = JSON.parse(readFileSync(cursorFile(box), "utf8")); + assert.deepEqual(data.mcpServers.taskade, { url: SERVER, headers: { Authorization: `Bearer ${TOKEN}` } }); + if (POSIX) assert.equal(statSync(cursorFile(box)).mode & 0o777, 0o600); +}); + +test("--token --print masks the token in the block", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--token", "--print", "--project"], { TASKADE_TOKEN: TOKEN }); + assert.equal(r.code, 0); + noTokenIn(r); + assert.match(r.stdout, /"Authorization": "Bearer tskdp_…"/); + assert.match(r.stdout, /Do not commit/); +}); + +test("--token with no TASKADE_TOKEN exits 1", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "cursor", "--token", "--yes"]); + assert.equal(r.code, 1); + assert.match(r.stderr, /TASKADE_TOKEN is not set/); +}); + +test("a token passed as an argument is refused and never echoed", async (t) => { + const box = sandbox(t); + for (const args of [ + ["plug", "cursor", `--token=${TOKEN}`], + ["plug", "cursor", TOKEN], + ["plug", "--token", TOKEN], + ["plug", "--token", "abc123notaclient"], + ["plug", "cursor", "--token", "abc123notaclient"], + ["doctor", TOKEN], + ]) { + const r = await runCli(box, args); + assert.equal(r.code, 1, args.join(" ")); + assert.match(r.stderr, /Never pass a token on the command line/, args.join(" ")); + assert.ok(!r.stderr.includes(TOKEN) && !r.stderr.includes("abc123notaclient"), args.join(" ")); + assert.ok(!r.stdout.includes(TOKEN), args.join(" ")); + } + assert.throws(() => statSync(cursorFile(box))); +}); + +test("claude-desktop refuses --token", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "claude-desktop", "--token"], { TASKADE_TOKEN: TOKEN }); + assert.equal(r.code, 1); + noTokenIn(r); +}); + +// Command clients, with fake commands on a temporary PATH + +test("claude-code --yes runs claude mcp add with user scope", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const r = await runCli(box, ["plug", "claude-code", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual( + calls(box, "claude").map((c) => c.args), + [["mcp", "add", "--transport", "http", "--scope", "user", "taskade", SERVER]], + ); + assert.match(r.stdout, /type \/mcp/); +}); + +test("claude-code --project uses the project scope", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const r = await runCli(box, ["plug", "claude-code", "--project", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(calls(box, "claude")[0].args.slice(4, 6), ["--scope", "project"]); +}); + +test("claude-code asks in a terminal, and a no runs nothing", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const r = await runInTerminal(box, ["plug", "claude-code"], { answer: false }); + assert.equal(r.code, 0); + assert.deepEqual(r.questions, ["Run this command? [y/N] "]); + assert.deepEqual(calls(box, "claude"), []); +}); + +test("claude-code with an equal entry in ~/.claude.json runs nothing", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + writeJson(join(box.home, ".claude.json"), { mcpServers: { taskade: { type: "http", url: SERVER } } }); + const r = await runCli(box, ["plug", "claude-code", "--yes"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /Already connected/); + assert.deepEqual(calls(box, "claude"), []); +}); + +test("claude-code with a different entry removes it, then adds", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + writeJson(join(box.home, ".claude.json"), { + mcpServers: { taskade: { type: "http", url: SERVER, headers: { Authorization: `Bearer ${TOKEN}` } } }, + }); + const r = await runCli(box, ["plug", "claude-code", "--yes"]); + assert.equal(r.code, 0, r.stderr); + noTokenIn(r); + assert.match(r.stdout, /Current entry/); + assert.deepEqual( + calls(box, "claude").map((c) => c.args.slice(0, 2)), + [ + ["mcp", "remove"], + ["mcp", "add"], + ], + ); +}); + +test("claude-code --token passes the header to claude and masks it on screen", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const r = await runCli(box, ["plug", "claude-code", "--token", "--yes"], { TASKADE_TOKEN: TOKEN }); + assert.equal(r.code, 0, r.stderr); + noTokenIn(r); + assert.deepEqual(calls(box, "claude")[0].args.slice(-2), ["--header", `Authorization: Bearer ${TOKEN}`]); +}); + +test("claude-code not on PATH prints the command and the install step, exit 0", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "claude-code", "--yes"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /not on your PATH/); + assert.match(r.stdout, /code\.claude\.com\/docs\/en\/setup/); +}); + +test("a failed client command exits 1", async (t) => { + const box = sandbox(t); + fakeCommand(box, "claude"); + const r = await runCli(box, ["plug", "claude-code", "--yes"], { FAKE_CLAUDE_EXIT: "3" }); + assert.equal(r.code, 1); + assert.match(r.stderr, /claude mcp add failed \(exit code 3\)/); +}); + +test("codex --yes runs mcp add, then mcp login", async (t) => { + const box = sandbox(t); + fakeCommand(box, "codex"); + const r = await runCli(box, ["plug", "codex", "--yes"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual( + calls(box, "codex").map((c) => c.args), + [ + ["mcp", "add", "taskade", "--url", SERVER], + ["mcp", "login", "taskade"], + ], + ); +}); + +test("codex: no second sign-in when mcp add already signed in", async (t) => { + const box = sandbox(t); + fakeCommand(box, "codex"); + const r = await runCli(box, ["plug", "codex", "--yes"], { FAKE_CODEX_STDOUT: "Successfully logged in." }); + assert.equal(r.code, 0, r.stderr); + assert.equal(calls(box, "codex").length, 1); +}); + +test("codex --token uses --bearer-token-env-var and no sign-in", async (t) => { + const box = sandbox(t); + fakeCommand(box, "codex"); + const r = await runCli(box, ["plug", "codex", "--token", "--yes"], { TASKADE_TOKEN: TOKEN }); + assert.equal(r.code, 0, r.stderr); + noTokenIn(r); + assert.deepEqual( + calls(box, "codex").map((c) => c.args), + [["mcp", "add", "taskade", "--url", SERVER, "--bearer-token-env-var", "TASKADE_TOKEN"]], + ); +}); + +test("codex with an equal entry in config.toml runs nothing", async (t) => { + const box = sandbox(t); + fakeCommand(box, "codex"); + mkdirSync(join(box.home, ".codex")); + writeFileSync(join(box.home, ".codex", "config.toml"), `model = "x"\n\n[mcp_servers.taskade]\nurl = "${SERVER}"\n`); + const r = await runCli(box, ["plug", "codex", "--yes"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /Already connected/); + assert.deepEqual(calls(box, "codex"), []); +}); + +test("codex --project exits 1", async (t) => { + const box = sandbox(t); + const r = await runCli(box, ["plug", "codex", "--project", "--yes"]); + assert.equal(r.code, 1); +}); + +test("vscode --yes runs code --add-mcp with the JSON entry", async (t) => { + const box = sandbox(t); + fakeCommand(box, "code"); + const r = await runCli(box, ["plug", "vscode", "--yes"]); + assert.equal(r.code, 0, r.stderr); + const [call] = calls(box, "code"); + assert.equal(call.args[0], "--add-mcp"); + assert.deepEqual(JSON.parse(call.args[1]), { name: "taskade", type: "http", url: SERVER }); +}); + +test("claude-desktop copies the URL when a clipboard command exists", async (t) => { + const box = sandbox(t); + const tool = { darwin: "pbcopy", win32: "clip" }[process.platform] || "xclip"; + fakeCommand(box, tool); + const key = tool.toUpperCase(); + const r = await runInTerminal(box, ["plug", "claude-desktop"], { extraEnv: { [`FAKE_${key}_STDIN`]: "1" } }); + assert.equal(r.code, 0, r.stderr); + assert.match(r.stdout, new RegExp(`Copied .* to the clipboard \\(${tool}\\)`)); + assert.equal(calls(box, tool)[0].input, SERVER); +}); + +test("claude-desktop says so when no clipboard command exists", async (t) => { + const box = sandbox(t); + const r = await runInTerminal(box, ["plug", "claude-desktop"]); + assert.equal(r.code, 0); + assert.match(r.stdout, /No clipboard command found/); +}); diff --git a/test/system.test.mjs b/test/system.test.mjs new file mode 100644 index 0000000..b38d3cf --- /dev/null +++ b/test/system.test.mjs @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import { PassThrough } from "node:stream"; +import { test } from "node:test"; +import { askOnTerminal, mask } from "../src/system.mjs"; + +async function ask(typed) { + const input = new PassThrough(); + const output = new PassThrough(); + const answer = askOnTerminal("Write? [y/N] ", input, output); + if (typed === null) input.end(); + else input.write(typed); + return answer; +} + +test("the prompt takes only y or yes as a yes", async () => { + assert.equal(await ask("y\n"), true); + assert.equal(await ask("YES\n"), true); + assert.equal(await ask("n\n"), false); + assert.equal(await ask("\n"), false); + assert.equal(await ask("yep\n"), false); + assert.equal(await ask(null), false, "end of input is a no"); +}); + +test("mask shows only the first 6 characters", () => { + assert.equal(mask("tskdp_abcdefghijkl"), "tskdp_…"); +});