From 44f03076151a4b343b6d1d60ccea615b7269800a Mon Sep 17 00:00:00 2001 From: "Chief (agent)" <25110505+Lexus2016@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:11:17 +0000 Subject: [PATCH] external api: a token-authenticated MCP surface for outside agents (#150) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An agent outside CCS (another Claude Code session, MCPHub, a monitoring script) could only reach the internal /api/internal/task-manager door, with a per-process secret that changes on every restart, no projects and no contract. This is stage 1 of #150 — projects and tasks. Chats stay stage 2: send_message and stop_turn need a documented server contract before a wrapper can expose them. What is added: - mcp-ccs.js: a self-contained stdio MCP server (zero dependencies, http or https, CCS_URL + CCS_TOKEN) exposing list_projects, list_tasks, get_task, get_task_result, create_task and cancel_task. - api-token.js: scoped, revocable tokens. The plaintext is shown once, only its SHA-256 is stored in data/api-tokens.json (0600); scopes read|full; at most 20. - /api/external/v1/*: the whole external contract, registered in front of the session wall so an external token cannot reach chats, files, settings or terminals. A request carrying an Origin header is refused. - create_task requires an explicit project and defaults to status "backlog": an outside caller never inherits a workdir and never starts a run by accident. - scripts/api-token.js: create/list/revoke from a shell, which is the Docker path. Tests: test/api-token.test.js (store: hashed at rest, revocation immediate, a malformed file fails closed) and test/external-api.test.js, which drives the REST surface and then runs mcp-ccs.js as a real stdio MCP client — initialize, tools/list, tools/call — against a booted server. Docs: docs/EXTERNAL-API.md. --- README.md | 3 + api-token.js | 163 +++++++++++++++++ docs/EXTERNAL-API.md | 121 +++++++++++++ mcp-ccs.js | 336 +++++++++++++++++++++++++++++++++++ package.json | 2 +- scripts/api-token.js | 77 ++++++++ server.js | 249 ++++++++++++++++++++++++++ test/api-token.test.js | 112 ++++++++++++ test/asar-helpers.test.js | 6 +- test/external-api.test.js | 240 +++++++++++++++++++++++++ test/task-text-limit.test.js | 11 +- 11 files changed, 1316 insertions(+), 4 deletions(-) create mode 100644 api-token.js create mode 100644 docs/EXTERNAL-API.md create mode 100644 mcp-ccs.js create mode 100644 scripts/api-token.js create mode 100644 test/api-token.test.js create mode 100644 test/external-api.test.js diff --git a/README.md b/README.md index c0ccf0b2..9dd9d314 100644 --- a/README.md +++ b/README.md @@ -504,6 +504,7 @@ npx github:Lexus2016/claude-code-studio # launch as usual | **Kanban** | Task queue, parallel + sequential, cross-tab sync, drag-and-drop tabs, dependency graphs, engine + model + effort per task/chain | | **Scheduler** | One-time + recurring (hourly/daily/weekly/monthly), 5 parallel workers, Run Now, SQLite-persisted, engine + model + effort per task, watchdog auto-recovery | | **Task Manager** | Autonomous child tasks, chains, context passing, result reporting, cancellation, board-only cards (import a plan without running it) (MCP) | +| **External API** | Drive CCS from an agent outside it: the `ccs` MCP server ([mcp-ccs.js](mcp-ccs.js)) lists projects, creates and follows tasks, reads results, cancels — plus a token-authenticated REST surface (`/api/external/v1`), scoped `read`/`full`, revocable, hashed at rest ([docs](docs/EXTERNAL-API.md)) | | **Telegram** | Bot control, push notifications, ask_user forwarding (+ file answers), session bridge, Forum Mode, inline stop, deep-link navigation, rich action buttons (localized EN/UA/RU/FR/HE), Write button, file attachments, interrupt queue while busy | | **Delegation** | Cross-agent handoff/sync (Codex, Antigravity, opencode), CONTEXT.md + DIALOG.md protocol, fs.watch + polling, persistent across restarts, Windows support, sidebar agents manager, auto-seeded defaults, test button | | **Agents** | Single, Multi (2–5 in-chat, schema-validated planning), Dispatch (Kanban), Room (project bots take serial turns on one message), auto-retry, cascade cancellation, effort propagation | @@ -533,6 +534,8 @@ claude-cli.js — spawns `claude` subprocess, parses JSON stream telegram-bot.js — Telegram bot (Direct Mode) telegram-bot-forum.js — Forum Mode standalone module (composition pattern) mcp-task-manager.js — MCP server for autonomous task management +api-token.js — scoped, revocable tokens for the external API (hashed at rest) +mcp-ccs.js — MCP client for OUTSIDE agents: projects + tasks over /api/external/v1 mcp-notify.js — MCP server for non-blocking notifications public/index.html — entire frontend (HTML + CSS + JS) config.json — MCP servers + skills catalog diff --git a/api-token.js b/api-token.js new file mode 100644 index 00000000..4bc48ac4 --- /dev/null +++ b/api-token.js @@ -0,0 +1,163 @@ +'use strict'; +// ─── External API tokens (issue #150) ───────────────────────────────────────── +// The web UI authenticates with a 30-day session token held in a cookie. An +// external client (mcp-ccs.js on a laptop, MCPHub in another container) needs +// something different: a credential that +// +// - lives for months without a browser in the loop, +// - can be revoked without logging the owner out (revokeToken() would also +// kill their own session), +// - is not the per-process TASK_MANAGER_SECRET, which is random on every +// restart and therefore unusable outside this process, +// - carries a SCOPE, because "create a task" is code execution in the +// container and a monitoring client should not have that. +// +// So this module is the whole token store: `data/api-tokens.json`, 0600, and +// only a SHA-256 of each token on disk. The plaintext is returned once, by +// createToken(), and never written or logged anywhere. A token is a high-entropy +// random value, not a password, so a plain hash is the right primitive here — +// bcrypt would only buy a work factor against guessing a 192-bit value. +// +// Tokens are opt-in by existing: an install with no tokens cannot call the +// external API at all, and nothing else in the app reads this file. +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const APP_DIR = process.env.APP_DIR || __dirname; +const TOKENS_FILE = path.join(APP_DIR, 'data', 'api-tokens.json'); + +// `ccs_` makes a leaked token greppable in logs and secret scanners, which is +// the one place an opaque 48-hex string would be invisible. +const TOKEN_PREFIX = 'ccs_'; +const SCOPES = ['read', 'full']; +// Same ceiling as auth.js's session cap: past this, a list of tokens stops being +// something a person can read, and nothing legitimate needs it. +const MAX_TOKENS = 20; +// lastUsedAt is in-memory and flushed at most this often — an external client +// polls, and a writeFileSync per request would rewrite the file in a loop. +const LAST_USED_FLUSH_INTERVAL = 5 * 60 * 1000; + +function hashHex(token) { + return crypto.createHash('sha256').update(String(token), 'utf8').digest('hex'); +} + +function isHashString(v) { + return typeof v === 'string' && /^[0-9a-f]{64}$/.test(v); +} + +function isRecord(r) { + return r !== null && typeof r === 'object' && !Array.isArray(r) && + typeof r.id === 'string' && r.id.length > 0 && + isHashString(r.hash) && + SCOPES.includes(r.scope) && + typeof r.created_at === 'string'; +} + +// No cache: unlike the sessions file (read on every HTTP request) this one is +// read only by the external surface and the token management endpoints, and a +// stale read here would mean a revoked token that still works. +function loadTokens() { + let parsed; + try { parsed = JSON.parse(fs.readFileSync(TOKENS_FILE, 'utf-8')); } + catch { return []; } + if (!Array.isArray(parsed)) return []; + // Accept only records this module writes; a hand-edited file must fail closed, + // not turn every request into a throw. + return parsed.filter(isRecord); +} + +function saveTokens(list) { + const dir = path.dirname(TOKENS_FILE); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + const tmp = TOKENS_FILE + '.tmp'; + // 0600: token hashes are not the token, but they are still credential material + // on a shared host — the same reason auth.json is written this way. + fs.writeFileSync(tmp, JSON.stringify(list, null, 2), { mode: 0o600 }); + try { fs.chmodSync(tmp, 0o600); } catch {} + fs.renameSync(tmp, TOKENS_FILE); +} + +function sanitizeName(name) { + // eslint-disable-next-line no-control-regex + const cleaned = String(name == null ? '' : name) + .replace(/[\x00-\x1F\x7F\u0080-\u009F\u200B-\u200F\u2028\u2029\u202A-\u202E\uFEFF]/g, '') + .trim() + .slice(0, 60); + return cleaned; +} + +function publicRecord(r) { + return { id: r.id, name: r.name, scope: r.scope, created_at: r.created_at, last_used_at: r.last_used_at || null }; +} + +/** Metadata only — never the hash, never the token. */ +function listTokens() { + return loadTokens().map(publicRecord); +} + +/** + * Mint a token. Returns { token, record } — `token` is the only time the + * plaintext exists; the caller (HTTP response or scripts/api-token.js) is + * responsible for showing it once. + */ +function createToken({ name, scope } = {}) { + const cleanName = sanitizeName(name) || 'external client'; + if (!SCOPES.includes(scope)) throw new Error(`scope must be one of: ${SCOPES.join(', ')}`); + const tokens = loadTokens(); + if (tokens.length >= MAX_TOKENS) throw new Error(`token limit reached (${MAX_TOKENS}); revoke one first`); + + // 24 random bytes = 192 bits. The prefix is stripped before hashing so the + // stored value is over the secret alone. + const token = TOKEN_PREFIX + crypto.randomBytes(24).toString('hex'); + const record = { + id: crypto.randomBytes(8).toString('hex'), + name: cleanName, + scope, + hash: hashHex(token), + created_at: new Date().toISOString(), + last_used_at: null, + }; + tokens.push(record); + saveTokens(tokens); + return { token, record: publicRecord(record) }; +} + +function revokeToken(id) { + if (!id) return false; + const tokens = loadTokens(); + const kept = tokens.filter(t => t.id !== id); + if (kept.length === tokens.length) return false; + saveTokens(kept); + return true; +} + +/** + * Verify a presented bearer token. Returns { id, name, scope } or null. + * Constant-time on the hash: comparing hex strings with === would leak the + * matching prefix of a token an attacker is guessing. + */ +function verifyToken(plain) { + if (typeof plain !== 'string' || !plain.startsWith(TOKEN_PREFIX)) return null; + const presented = crypto.createHash('sha256').update(plain, 'utf8').digest(); + const tokens = loadTokens(); + let match = null; + for (const t of tokens) { + const stored = Buffer.from(t.hash, 'hex'); + if (stored.length === presented.length && crypto.timingSafeEqual(stored, presented)) match = t; + } + if (!match) return null; + + const now = Date.now(); + const last = Date.parse(match.last_used_at || '') || 0; + if (now - last > LAST_USED_FLUSH_INTERVAL) { + match.last_used_at = new Date(now).toISOString(); + try { saveTokens(tokens); } catch { /* a read path must not fail on a stats write */ } + } + return { id: match.id, name: match.name, scope: match.scope }; +} + +module.exports = { + TOKENS_FILE, TOKEN_PREFIX, SCOPES, + listTokens, createToken, revokeToken, verifyToken, +}; diff --git a/docs/EXTERNAL-API.md b/docs/EXTERNAL-API.md new file mode 100644 index 00000000..e7fb991c --- /dev/null +++ b/docs/EXTERNAL-API.md @@ -0,0 +1,121 @@ +# External API and the `ccs` MCP server (issue #150) + +Drive Claude Code Studio **from outside**: another Claude Code session, an MCP hub, +a monitoring script, a CI job. This document covers stage 1 — projects and tasks. +Chats (create a chat, send a message, read the reply, stop a turn) are stage 2, +because `send_message`/`stop_turn` have no documented server contract yet. + +Two pieces: + +- `mcp-ccs.js` — a self-contained stdio MCP server (zero dependencies) that talks to + the HTTP API over `http` or `https`. Copy it anywhere; it needs no sibling files. +- `/api/external/v1/*` — a small, token-authenticated REST surface. It is the entire + contract an external client gets; chats, files, settings and terminals are not + reachable with an external token. + +## 1. Create a token + +Tokens are opt-in: with none on disk, every call to the external API is `401`. + +```bash +# in the CCS data directory (or a container: docker exec -it claude-code-studio …) +node scripts/api-token.js create --name mcphub --scope read +``` + +The plaintext is printed **once**. Only a SHA-256 is stored, in `data/api-tokens.json` +(mode 0600), so a lost token is revoked and replaced, never recovered. + +```bash +node scripts/api-token.js list # metadata + last use, never the secret +node scripts/api-token.js revoke # effective on the next request +``` + +Scopes: + +| scope | may | +| --- | --- | +| `read` (default) | list projects, list/read tasks, read results | +| `full` | the above, plus create and cancel tasks | + +`full` is code execution: a created task runs `claude` with the description as its +prompt, in the project workdir, with the container's permissions. Use `read` for +monitoring. Revoking a token does not affect the owner's browser session, and a +session logout does not revoke tokens. + +The same operations exist over HTTP for a logged-in client: +`GET /api/api-tokens`, `POST /api/api-tokens {name, scope}`, `DELETE /api/api-tokens/`. + +## 2. Point a client at it + +Claude Code (`~/.claude.json` or `.mcp.json`): + +```json +{ + "mcpServers": { + "ccs": { + "command": "node", + "args": ["/path/to/claude-code-studio/mcp-ccs.js"], + "env": { + "CCS_URL": "http://127.0.0.1:3000", + "CCS_TOKEN": "ccs_…" + } + } + } +} +``` + +MCPHub or any host that runs stdio servers in its own container: mount or copy +`mcp-ccs.js`, then set the same two variables. `CCS_URL` may be any address the +container can reach (`http://claude-code-studio:3000` on a compose network, or an +`https://` reverse proxy) and may include a path prefix (`https://host/ccs`). + +| variable | default | meaning | +| --- | --- | --- | +| `CCS_URL` | `http://127.0.0.1:3000` | server base URL, `http` or `https`, without `/api` | +| `CCS_TOKEN` | — | token from step 1; without it every tool call explains what is missing | + +## 3. Tools + +| tool | scope | notes | +| --- | --- | --- | +| `list_projects` | read | returns `id`, `name`, `workdir`, `isRemote` | +| `list_tasks` | read | filters: `project`, `status`, `limit` (default 20, max 100), newest first | +| `get_task` | read | one task, with its description | +| `get_task_result` | read | the structured result a finished run reported | +| `create_task` | full | **requires `project`**; defaults to `status: "backlog"` | +| `cancel_task` | full | refuses a completed task; idempotent otherwise | + +`create_task` never inherits a workdir — an outside caller has no parent task, and +guessing one would start an unattended run in an arbitrary tree. A card created +without `status` lands in `backlog` and nothing runs; pass `status: "todo"` to queue +a run now (optionally with `scheduled_at`). Tasks get their own git worktree, the +same as a card created in the UI. + +## 4. REST surface + +All endpoints take `Authorization: Bearer ccs_…` and return JSON. + +| method | path | scope | +| --- | --- | --- | +| GET | `/api/external/v1/me` | read | +| GET | `/api/external/v1/projects` | read | +| GET | `/api/external/v1/tasks?project=&status=&limit=` | read | +| GET | `/api/external/v1/tasks/:id` | read | +| GET | `/api/external/v1/tasks/:id/result` | read | +| POST | `/api/external/v1/tasks` | full | +| POST | `/api/external/v1/tasks/:id/cancel` | full | + +`project` accepts an id or an exact name (case-insensitive). An ambiguous name is +refused with the candidate ids instead of resolved to whichever came first. + +## 5. Boundaries + +- A request carrying an `Origin` header is refused (`403`). Browsers attach one to + every cross-site fetch; MCP clients never send one. This keeps a page the owner + visits from spending a token that is sitting in a shell. +- Tokens are a fixed bearer credential, not a session: no expiry, revocable at any + time, at most 20 at once. +- Remote (SSH) projects are not writable through this API yet; they are listed, and + creating a task in one returns `400`. +- The external API is a local/trusted-network surface. Terminate TLS in front of it + if it crosses an untrusted network; the server itself speaks plain HTTP. diff --git a/mcp-ccs.js b/mcp-ccs.js new file mode 100644 index 00000000..39224d04 --- /dev/null +++ b/mcp-ccs.js @@ -0,0 +1,336 @@ +#!/usr/bin/env node +// ─── External MCP server: ccs ──────────────────────────────────────────────── +// Drive Claude Code Studio from an OUTSIDE agent (issue #150, stage 1): any MCP +// client — another Claude Code session, MCPHub, a monitoring script — can list +// projects, create tasks, follow them and read results without opening the web UI. +// +// Raw JSON-RPC 2.0 over stdio, newline delimited, zero external dependencies, and +// deliberately SELF-CONTAINED: it is meant to be copied into another image (or run +// with `npx`) and kept in sync with CCS releases, so it must not require a sibling +// file. The only place that would have pulled one in is the task text limit; the +// literal below is pinned to task-text-limit.js by test/task-text-limit.test.js. +// +// Usage (client config `env`): +// CCS_URL base URL of the server, http or https, no trailing /api. +// Default http://127.0.0.1:3000. Set it to the container/reverse-proxy +// address when this process does not run next to the server. +// CCS_TOKEN a token created with scripts/api-token.js (or POST /api/api-tokens). +// scope "read" = list/read only; "full" = also create and cancel. +// +// Nothing is inherited from a parent task: `project` is required on create_task, +// because this client has no workdir of its own. create_task defaults to +// status "backlog" so a card lands on the board without starting a run; pass +// status "todo" to queue it now. + +const http = require('http'); +const https = require('https'); +const { StringDecoder } = require('string_decoder'); + +// Same limit the HTTP API enforces. Kept as a literal on purpose — see the header. +const MAX_TASK_TEXT = 20000; +const MAX_STDIN_BUFFER = 10 * 1024 * 1024; // 10 MB + +const CCS_URL = (process.env.CCS_URL || 'http://127.0.0.1:3000').replace(/\/+$/, ''); +const CCS_TOKEN = process.env.CCS_TOKEN || ''; + +// ─── JSON-RPC helpers ──────────────────────────────────────────────────────── + +function sendResponse(id, result) { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); +} + +function sendError(id, code, message) { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n'); +} + +function toolText(id, text, isError) { + sendResponse(id, { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) }); +} + +// ─── HTTP to the CCS external API ──────────────────────────────────────────── + +function request(method, apiPath, body) { + return new Promise((resolve, reject) => { + let base; + try { base = new URL(CCS_URL); } + catch { return reject(new Error(`CCS_URL is not a valid URL: ${CCS_URL}`)); } + if (base.protocol !== 'http:' && base.protocol !== 'https:') { + return reject(new Error(`CCS_URL must be http or https, got ${base.protocol}`)); + } + const mod = base.protocol === 'https:' ? https : http; + const payload = body === undefined ? null : JSON.stringify(body); + const prefix = base.pathname.replace(/\/+$/, ''); + const options = { + hostname: base.hostname, + port: base.port || (base.protocol === 'https:' ? 443 : 80), + path: prefix + apiPath, + method, + headers: { + Authorization: `Bearer ${CCS_TOKEN}`, + Accept: 'application/json', + ...(payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {}), + }, + timeout: 20000, + }; + + const req = mod.request(options, (res) => { + let responseBody = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { responseBody += chunk; }); + res.on('end', () => { + let parsed = null; + try { parsed = JSON.parse(responseBody); } catch { /* non-JSON body below */ } + if (res.statusCode >= 400) { + const detail = (parsed && parsed.error) || responseBody.slice(0, 300) || `HTTP ${res.statusCode}`; + let hint = ''; + if (res.statusCode === 401) hint = ' — check CCS_TOKEN (scripts/api-token.js creates one)'; + if (res.statusCode === 403 && /read-only/.test(String(detail))) hint = ' — this token has scope "read"; create a "full" token to change anything'; + return reject(new Error(`${detail} (HTTP ${res.statusCode})${hint}`)); + } + if (parsed === null) return reject(new Error(`expected JSON from ${apiPath}, got: ${responseBody.slice(0, 200)}`)); + resolve(parsed); + }); + }); + req.on('error', (err) => reject(new Error(`cannot reach ${CCS_URL}: ${err.message}`))); + req.on('timeout', () => { req.destroy(); reject(new Error(`request to ${CCS_URL} timed out`)); }); + if (payload) req.write(payload); + req.end(); + }); +} + +// ─── Tool definitions ──────────────────────────────────────────────────────── + +const TOOLS = [ + { + name: 'list_projects', + description: 'List the projects registered in Claude Code Studio. Pass a returned `id` (or its exact name) as `project` to any tool that needs one.', + inputSchema: { type: 'object', properties: {} }, + }, + { + name: 'create_task', + description: 'Create a Kanban card in a project. `project` is required — this client has no workdir to inherit, so the task is placed in the named project. Default status "backlog" adds a card WITHOUT starting a run; pass status "todo" to queue it for an unattended run now (that runs claude with the description as the prompt).', + inputSchema: { + type: 'object', + properties: { + project: { type: 'string', description: 'Project id or exact name (see list_projects)' }, + title: { type: 'string', description: 'Short task title (max 200 chars)' }, + description: { type: 'string', description: `Task prompt/description (max ${MAX_TASK_TEXT} chars)` }, + status: { type: 'string', enum: ['backlog', 'todo'], description: 'backlog = card only, nothing runs (default). todo = queue an unattended run now.' }, + model: { type: 'string', description: 'Model for the run (default "sonnet")' }, + max_turns: { type: 'number', description: 'Max turns for the run (default 30)' }, + scheduled_at: { type: 'string', description: 'ISO 8601 datetime — a "todo" task waits until then' }, + depends_on: { type: 'array', items: { type: 'string' }, description: 'Task ids that must finish first' }, + }, + required: ['project', 'title'], + }, + }, + { + name: 'list_tasks', + description: 'List tasks, newest first. Filter by project, status, or both. Use this to follow work created here or in the UI.', + inputSchema: { + type: 'object', + properties: { + project: { type: 'string', description: 'Project id or exact name; omit for all projects' }, + status: { type: 'string', enum: ['backlog', 'todo', 'in_progress', 'done', 'cancelled'], description: 'Filter by status' }, + limit: { type: 'number', description: 'Max results (default 20, max 100)' }, + }, + }, + }, + { + name: 'get_task', + description: 'Read one task: title, description, status, project, timestamps, failure reason.', + inputSchema: { + type: 'object', + properties: { task_id: { type: 'string', description: 'Task id' } }, + required: ['task_id'], + }, + }, + { + name: 'get_task_result', + description: 'Read the structured result a finished run reported (the data a dependent task would receive). Empty until the run stores one.', + inputSchema: { + type: 'object', + properties: { task_id: { type: 'string', description: 'Task id' } }, + required: ['task_id'], + }, + }, + { + name: 'cancel_task', + description: 'Cancel a pending or running task. Needed a token with scope "full".', + inputSchema: { + type: 'object', + properties: { + task_id: { type: 'string', description: 'Task id' }, + reason: { type: 'string', description: 'Why it is being cancelled' }, + }, + required: ['task_id'], + }, + }, +]; + +// ─── Formatting ────────────────────────────────────────────────────────────── + +function formatTask(t) { + const proj = t.project_name ? ` [${t.project_name}]` : ''; + return ` - [${t.status}] "${t.title}" (ID: ${t.id})${proj}`; +} + +function formatProjects(projects) { + if (!projects.length) return 'No projects are registered.'; + return `Projects (${projects.length}):\n` + projects.map(p => + ` - ${p.name} (id: ${p.id})${p.isRemote ? ' — remote' : ''} — ${p.workdir}`).join('\n'); +} + +// ─── Message handling ──────────────────────────────────────────────────────── + +let _initialized = false; + +async function handleMessage(msg) { + const { id, method, params } = msg; + // Notifications (no id) are acknowledged silently. + if (id === undefined || id === null) return; + + switch (method) { + case 'initialize': + _initialized = true; + sendResponse(id, { + protocolVersion: '2024-11-05', + capabilities: { tools: {} }, + serverInfo: { name: 'ccs', version: '1.0.0' }, + }); + break; + + case 'tools/list': + if (!_initialized) { sendError(id, -32002, 'Server not initialized'); return; } + sendResponse(id, { tools: TOOLS }); + break; + + case 'ping': + sendResponse(id, {}); + break; + + case 'tools/call': { + if (!_initialized) { sendError(id, -32002, 'Server not initialized'); return; } + const name = params?.name; + const args = params?.arguments || {}; + if (!TOOLS.some(t => t.name === name)) { sendError(id, -32602, `Unknown tool: ${name}`); return; } + if (!CCS_TOKEN) { + toolText(id, 'CCS_TOKEN is not set. Create a token with `node scripts/api-token.js create --name --scope read` and put it in this server\'s env as CCS_TOKEN.', true); + return; + } + + try { + switch (name) { + case 'list_projects': { + const projects = await request('GET', '/api/external/v1/projects'); + toolText(id, formatProjects(projects)); + break; + } + case 'create_task': { + if (!args.project) throw new Error('project is required — call list_projects and pass an id or exact name'); + if (!args.title) throw new Error('title is required'); + const body = { + project: args.project, + title: args.title, + description: args.description || '', + status: args.status === 'todo' ? 'todo' : 'backlog', + }; + if (args.model) body.model = args.model; + if (args.max_turns) body.max_turns = Number(args.max_turns); + if (args.scheduled_at) body.scheduled_at = args.scheduled_at; + if (Array.isArray(args.depends_on) && args.depends_on.length) body.depends_on = args.depends_on; + const task = await request('POST', '/api/external/v1/tasks', body); + const what = task.status === 'todo' + ? 'queued for an unattended run' + : 'added to the board (backlog — nothing runs until it is set to todo)'; + toolText(id, `Task created: "${task.title}" (ID: ${task.id}) in ${task.project_name || task.project_id}, status ${task.status} — ${what}.`); + break; + } + case 'list_tasks': { + const q = new URLSearchParams(); + if (args.project) q.set('project', String(args.project)); + if (args.status) q.set('status', String(args.status)); + if (args.limit) q.set('limit', String(args.limit)); + const qs = q.toString(); + const tasks = await request('GET', '/api/external/v1/tasks' + (qs ? `?${qs}` : '')); + toolText(id, tasks.length ? `Tasks (${tasks.length}):\n${tasks.map(formatTask).join('\n')}` : 'No tasks matched.'); + break; + } + case 'get_task': { + if (!args.task_id) throw new Error('task_id is required'); + const t = await request('GET', `/api/external/v1/tasks/${encodeURIComponent(args.task_id)}`); + toolText(id, [ + `ID: ${t.id}`, + `Title: ${t.title}`, + `Project: ${t.project_name || t.project_id || '(none)'}`, + `Status: ${t.status}`, + t.failure_reason ? `Failure: ${t.failure_reason}` : null, + `Model: ${t.model} · max turns: ${t.max_turns}`, + `Created: ${t.created_at} · Updated: ${t.updated_at}`, + t.depends_on && t.depends_on.length ? `Depends on: ${t.depends_on.join(', ')}` : null, + '', + t.description || '(no description)', + ].filter(l => l !== null).join('\n')); + break; + } + case 'get_task_result': { + if (!args.task_id) throw new Error('task_id is required'); + const r = await request('GET', `/api/external/v1/tasks/${encodeURIComponent(args.task_id)}/result`); + const output = r.output === null || r.output === undefined ? '(no result stored yet)' : (typeof r.output === 'string' ? r.output : JSON.stringify(r.output, null, 2)); + toolText(id, `"${r.title}" (ID: ${r.task_id}) — status ${r.status}${r.completed_at ? `, completed ${r.completed_at}` : ''}\n${output}`); + break; + } + case 'cancel_task': { + if (!args.task_id) throw new Error('task_id is required'); + const body = args.reason ? { reason: String(args.reason) } : {}; + const r = await request('POST', `/api/external/v1/tasks/${encodeURIComponent(args.task_id)}/cancel`, body); + toolText(id, `Task ${r.task_id} is ${r.status}.`); + break; + } + default: + sendError(id, -32602, `Unknown tool: ${name}`); + } + } catch (err) { + toolText(id, `Error: ${err.message}`, true); + } + break; + } + + default: + sendError(id, -32601, `Method not found: ${method}`); + } +} + +// ─── Stdin line reader ─────────────────────────────────────────────────────── + +const decoder = new StringDecoder('utf8'); +let buffer = ''; + +process.stdin.on('data', (chunk) => { + buffer += decoder.write(chunk); + if (buffer.length > MAX_STDIN_BUFFER) { + process.stderr.write('[mcp-ccs] stdin buffer overflow, resetting\n'); + buffer = ''; + return; + } + const lines = buffer.split(/\r?\n/); + buffer = lines.pop() || ''; + for (const line of lines) { + if (!line.trim()) continue; + try { + const msg = JSON.parse(line); + handleMessage(msg).catch((err) => process.stderr.write(`mcp-ccs error: ${err.message}\n`)); + } catch { /* ignore unparseable lines */ } + } +}); + +process.stdin.on('end', () => { + const remaining = buffer + decoder.end(); + if (remaining.trim()) { + try { handleMessage(JSON.parse(remaining)).catch(() => {}); } catch {} + } + process.exit(0); +}); + +process.on('SIGTERM', () => process.exit(0)); +process.on('SIGINT', () => process.exit(0)); diff --git a/package.json b/package.json index 7b57671c..a3a6bb0b 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "start": "node server.js", "dev": "node --watch server.js", - "test": "node --test test/render/*.test.mjs && node test/overload-detector.test.js && node test/usage-limit.test.js && node test/auth-errors.test.js && node test/env-load-order.test.js && node test/multi-agent-result.test.js && node test/terminal-session.test.js && node test/terminal-schema.test.js && node test/bots.test.js && node test/bot-inbox.test.js && node test/bots-api.test.js && node test/running-sessions.test.js && node test/session-liveness.test.js && node test/terminal-bridge.integration.test.js && node test/tmux-composite.test.js && node test/engine-spawn-cmd.test.js && node test/claude-firstrun.test.js && node test/telegram-format.test.js && node test/telegram-behaviour.test.js && node test/ask-user-question.test.js && node test/delegate-terminal.test.js && node test/agent-catalog.test.js && node test/update-flow.test.js && node test/kanban-schedule.test.js && node test/kanban-run-badges.test.js && node test/task-backlog.test.js && node test/i18n-completeness.test.js && node test/config-resolve.test.js && node test/chat-defaults.test.js && node test/chat-defaults-api.test.js && node test/run-continuation.test.js && node test/worktree-manager.test.js && node test/session-expiry.test.js && node test/setup-gate.test.js && node test/path-guard.test.js && node test/subscribe-nocatchup.test.js && node test/cli-import-remote.test.js && node test/remote-list-parse.test.js && node test/config-migrate.test.js && node test/engine-pane.test.js && node test/engine-idle-reaper.test.js && node test/pane-busy.test.js && node test/engine-prompts.test.js && node test/engine-prompt-replay.test.js && node test/prompt-answer.test.js && node test/global-workspace.test.js && node test/ssh-secret.test.js && node test/agent-dag.test.js && node test/ssh-parser.test.js && node test/ssh-termination.test.js && node test/session-restart.test.js && node test/remote-env.test.js && node test/remote-files.test.js && node test/remote-files-api.test.js && node test/auth-token.test.js && node test/cmd-model.test.js && node test/origin-guard.test.js && node test/interrupted-recovery.test.js && node test/queue-persistence.test.js && node test/interrupt-idle-config.test.js && node test/agents-md.test.js && node test/editor-links.test.js && node test/editor-open-api.test.js && node test/interrupt-delivery.test.js && node test/terminal-pane-guard.integration.test.js && node test/composer-terminal.test.js && node test/claude-cli-status.test.js && node test/asar-helpers.test.js && node test/mac-signing.test.js && node test/release-mac.test.js && node test/task-workers.test.js && node test/git-clone.test.js && node test/responsive-ui.test.js && node test/kanban-delegation.test.js && node test/kanban-group-button.test.js && node test/terminal-keys.test.js && node test/electron-navigation.test.js && node test/cli-runtime.test.js && node test/worktree-safety.test.js && node test/auth-boundary.test.js && node test/cli-process-tree.test.js && node test/schedule-actions.test.js && node test/install-hooks.test.js && node test/frontend-recovery.test.js && node test/db-revisions.test.js && node test/frontend-refresh-races.test.js && node test/release-gate.test.js && node test/focused-workspace.test.js && node test/secondary-navigation.test.js && node test/section-controls-ux.test.js && node test/settings-ux.test.js && node test/team-forms-ux.test.js && node test/page-forms-ux.test.js && node test/sidebar-ux.test.js && node test/task-text-limit.test.js && node test/terminal-clipboard.test.js && node test/terminal-addons.test.js && node test/file-preview-copy.test.js && node test/telegram-lang.test.js", + "test": "node --test test/render/*.test.mjs && node test/overload-detector.test.js && node test/usage-limit.test.js && node test/auth-errors.test.js && node test/env-load-order.test.js && node test/multi-agent-result.test.js && node test/terminal-session.test.js && node test/terminal-schema.test.js && node test/bots.test.js && node test/bot-inbox.test.js && node test/bots-api.test.js && node test/running-sessions.test.js && node test/session-liveness.test.js && node test/terminal-bridge.integration.test.js && node test/tmux-composite.test.js && node test/engine-spawn-cmd.test.js && node test/claude-firstrun.test.js && node test/telegram-format.test.js && node test/telegram-behaviour.test.js && node test/ask-user-question.test.js && node test/delegate-terminal.test.js && node test/agent-catalog.test.js && node test/update-flow.test.js && node test/kanban-schedule.test.js && node test/kanban-run-badges.test.js && node test/task-backlog.test.js && node test/i18n-completeness.test.js && node test/config-resolve.test.js && node test/chat-defaults.test.js && node test/chat-defaults-api.test.js && node test/run-continuation.test.js && node test/worktree-manager.test.js && node test/session-expiry.test.js && node test/setup-gate.test.js && node test/path-guard.test.js && node test/subscribe-nocatchup.test.js && node test/cli-import-remote.test.js && node test/remote-list-parse.test.js && node test/config-migrate.test.js && node test/engine-pane.test.js && node test/engine-idle-reaper.test.js && node test/pane-busy.test.js && node test/engine-prompts.test.js && node test/engine-prompt-replay.test.js && node test/prompt-answer.test.js && node test/global-workspace.test.js && node test/ssh-secret.test.js && node test/agent-dag.test.js && node test/ssh-parser.test.js && node test/ssh-termination.test.js && node test/session-restart.test.js && node test/remote-env.test.js && node test/remote-files.test.js && node test/remote-files-api.test.js && node test/auth-token.test.js && node test/cmd-model.test.js && node test/origin-guard.test.js && node test/interrupted-recovery.test.js && node test/queue-persistence.test.js && node test/interrupt-idle-config.test.js && node test/agents-md.test.js && node test/editor-links.test.js && node test/editor-open-api.test.js && node test/interrupt-delivery.test.js && node test/terminal-pane-guard.integration.test.js && node test/composer-terminal.test.js && node test/claude-cli-status.test.js && node test/asar-helpers.test.js && node test/mac-signing.test.js && node test/release-mac.test.js && node test/task-workers.test.js && node test/git-clone.test.js && node test/responsive-ui.test.js && node test/kanban-delegation.test.js && node test/kanban-group-button.test.js && node test/terminal-keys.test.js && node test/electron-navigation.test.js && node test/cli-runtime.test.js && node test/worktree-safety.test.js && node test/auth-boundary.test.js && node test/cli-process-tree.test.js && node test/schedule-actions.test.js && node test/install-hooks.test.js && node test/frontend-recovery.test.js && node test/db-revisions.test.js && node test/frontend-refresh-races.test.js && node test/release-gate.test.js && node test/focused-workspace.test.js && node test/secondary-navigation.test.js && node test/section-controls-ux.test.js && node test/settings-ux.test.js && node test/team-forms-ux.test.js && node test/page-forms-ux.test.js && node test/sidebar-ux.test.js && node test/task-text-limit.test.js && node test/terminal-clipboard.test.js && node test/terminal-addons.test.js && node test/file-preview-copy.test.js && node test/telegram-lang.test.js && node test/api-token.test.js && node test/external-api.test.js", "postinstall": "node scripts/install-hooks.js", "release": "node scripts/release.js", "release:mac": "node scripts/release-mac.js", diff --git a/scripts/api-token.js b/scripts/api-token.js new file mode 100644 index 00000000..9351eb96 --- /dev/null +++ b/scripts/api-token.js @@ -0,0 +1,77 @@ +#!/usr/bin/env node +'use strict'; +// ─── api-token: create / list / revoke external API tokens (issue #150) ────── +// The same token store the web UI manages over /api/api-tokens, reachable from a +// shell instead of a browser. That matters in Docker, where the client that needs +// the token (MCPHub, a laptop) has no session in the CCS web UI and the natural +// place to mint one is `docker exec`. +// +// Usage: +// node scripts/api-token.js create --name mcphub --scope read +// node scripts/api-token.js list +// node scripts/api-token.js revoke +// +// Prints the plaintext token exactly once, on create. It is not stored anywhere — +// only its SHA-256 is — so a lost token is revoked and replaced, never recovered. + +const path = require('path'); +const fs = require('fs'); + +// Same convention as bin/cli.js: a global/npx install keeps data in the directory +// the command is run from, unless APP_DIR already points somewhere. +if (!process.env.APP_DIR) process.env.APP_DIR = process.cwd(); +const dataDir = path.join(process.env.APP_DIR, 'data'); +if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true }); + +const apiToken = require('../api-token.js'); + +function usage() { + console.log(`usage: + node scripts/api-token.js create --name