mdshare 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,539 @@
1
+ #!/usr/bin/env node
2
+ // mdshare-cli — portable, dependency-free CLI for the mdshare agent (bearer-token) API.
3
+ // No MCP client required: works from any machine with Node >=18 and plain `fetch`.
4
+ //
5
+ // Security (AGENT-SEARCH-PLAN.md, 2026-10-08): the bearer token is NEVER accepted as a CLI
6
+ // argument/flag — only from the MDSHARE_AGENT_TOKEN environment variable, or from a file via
7
+ // MDSHARE_AGENT_TOKEN_FILE (env) / --token-file <path> (flag). A token passed as a bare CLI
8
+ // argument would be visible in `ps`, shell history, and process-list snapshots on shared
9
+ // machines — that risk is deliberately not offered here, matching the parent instruction
10
+ // ("never expose tokens in args/stdout/logs"). The resolved token value is never printed, logged,
11
+ // or included in any error message produced by this script; upstream API error bodies are
12
+ // passed through as-is (the mdshare API itself never echoes the Authorization header back).
13
+ //
14
+ // Usage:
15
+ // mdshare-cli status
16
+ // mdshare-cli search "<text>" [--limit N] [--offset N] [--json] (full text, Chinese too)
17
+ // mdshare-cli search [--q TERM] [--kind paste|diagram|archify|all] [--limit N] [--offset N] (catalog)
18
+ // mdshare-cli recent [--kind K] [--limit N] [--offset N] (alias for search with no --q)
19
+ // mdshare-cli read <id | /v/ /raw/ /d/ /a/ link> [--kind paste|diagram|archify]
20
+ // mdshare-cli create <kind> <file> [--ttl SECONDS] [--title TITLE] (kind: paste|diagram|archify)
21
+ // mdshare-cli publish <id> --kind K --public true|false
22
+ // mdshare-cli create paste <file> --keep --parent ID --origin SESSION [--strict]
23
+ // [--lang zh|en] [--translation-of ID] [--collection SLUG]
24
+ // mdshare-cli translate <id> --of <original id> [--lang zh|en] | translate <id> --unlink
25
+ // mdshare-cli collection <id> <slug> | collection <id> --none | collections [<slug>] [--json]
26
+ // mdshare-cli feedback [<doc id>] [--status S] | resolve <fb_id>... --in <id> | reads [ids] | versions <id>
27
+ //
28
+ // Token resolution (first match wins): MDSHARE_AGENT_TOKEN env var, then MDSHARE_AGENT_TOKEN_FILE
29
+ // env var, then --token-file <path> flag, then DEFAULT_TOKEN_FILE (~/.mdshare/token, the file
30
+ // `login` writes by default) if it exists. No match at any step -> '' (anonymous), same as
31
+ // before this default-file fallback existed. Base URL: MDSHARE_BASE_URL env var, default the
32
+ // public hosted instance (same default as mcp/src/index.ts).
33
+ import { readFileSync, writeFileSync, chmodSync, mkdirSync } from 'node:fs';
34
+ import { homedir, hostname } from 'node:os';
35
+ import { join, dirname } from 'node:path';
36
+
37
+ const BASE_URL = (process.env.MDSHARE_BASE_URL || 'https://mdshare-rileylins-projects.vercel.app').replace(/\/$/, '');
38
+ const DEFAULT_TOKEN_FILE = join(homedir(), '.mdshare', 'token');
39
+
40
+ const READ_WRITE_PATH = { paste: '/api/share', diagram: '/api/diagram', archify: '/api/archify' };
41
+
42
+ function parseArgs(argv) {
43
+ const positional = [];
44
+ const flags = {};
45
+ for (let i = 0; i < argv.length; i++) {
46
+ const a = argv[i];
47
+ if (a.startsWith('--')) {
48
+ const key = a.slice(2);
49
+ const next = argv[i + 1];
50
+ if (next !== undefined && !next.startsWith('--')) { flags[key] = next; i++; }
51
+ else flags[key] = true;
52
+ } else {
53
+ positional.push(a);
54
+ }
55
+ }
56
+ return { positional, flags };
57
+ }
58
+
59
+ function resolveToken(flags) {
60
+ if (process.env.MDSHARE_AGENT_TOKEN) return process.env.MDSHARE_AGENT_TOKEN;
61
+ const explicitFilePath = process.env.MDSHARE_AGENT_TOKEN_FILE || flags['token-file'];
62
+ if (explicitFilePath && typeof explicitFilePath === 'string') {
63
+ try { return readFileSync(explicitFilePath, 'utf8').trim(); } catch (e) {
64
+ fail(`Could not read token file: ${explicitFilePath} (${e.code || e.message})`);
65
+ }
66
+ }
67
+ // No explicit token source given (no env var, no MDSHARE_AGENT_TOKEN_FILE, no --token-file) --
68
+ // fall back to the default file `login` writes to (DEFAULT_TOKEN_FILE, ~/.mdshare/token by
69
+ // default). Unlike an explicit path above, a missing/unreadable default file is NOT an error:
70
+ // it just means the owner never ran `login` (or ran it with a custom --token-file), so every
71
+ // command keeps working exactly as before this fallback existed -- anonymous, empty token.
72
+ try { return readFileSync(DEFAULT_TOKEN_FILE, 'utf8').trim(); } catch { return ''; }
73
+ }
74
+
75
+ function authHeaders(flags) {
76
+ const headers = { 'Content-Type': 'application/json' };
77
+ const token = resolveToken(flags);
78
+ if (token) headers.Authorization = `Bearer ${token}`;
79
+ return headers;
80
+ }
81
+
82
+ function fail(message) {
83
+ // Throws rather than calling process.exit() directly, so every cmd* function below is a plain
84
+ // async function that can be imported and unit-tested (mocked global.fetch, no real network—
85
+ // this sandbox's exec egress proxy blocks even loopback traffic, so a real spawned-subprocess-
86
+ // against-a-local-server test is not viable here; see tests/cli-login.test.mjs). Only the
87
+ // actual CLI entrypoint (main(), guarded below) converts this into a stderr message + exit
88
+ // code 1 — observable behavior for a real invocation is unchanged.
89
+ throw new CliError(String(message));
90
+ }
91
+
92
+ class CliError extends Error {}
93
+
94
+ function printJson(value) {
95
+ process.stdout.write(JSON.stringify(value, null, 2) + '\n');
96
+ }
97
+
98
+ // Hidden password prompt for `login`. Never a CLI argument/flag — either read from the
99
+ // MDSHARE_OWNER_PASSWORD env var (for scripted/non-interactive setup), or typed interactively
100
+ // with echo suppressed via raw-mode stdin (nothing is printed back, not even asterisks — same
101
+ // convention as a typical `sudo`-style prompt). Prompt text and the trailing newline both go to
102
+ // stderr, never stdout, so stdout stays clean for `--stdout` secret-piping mode even during
103
+ // login. If stdin isn't a TTY (piped), reads the first line verbatim — masking a pipe is
104
+ // meaningless, but this still keeps the password out of argv/ps.
105
+ function readHiddenPassword(promptText) {
106
+ if (process.env.MDSHARE_OWNER_PASSWORD) return Promise.resolve(process.env.MDSHARE_OWNER_PASSWORD);
107
+ return new Promise((resolve) => {
108
+ const stdin = process.stdin;
109
+ process.stderr.write(promptText);
110
+ if (!stdin.isTTY) {
111
+ let data = '';
112
+ stdin.setEncoding('utf8');
113
+ stdin.on('data', (c) => { data += c; });
114
+ stdin.on('end', () => resolve(data.split('\n')[0].trim()));
115
+ return;
116
+ }
117
+ stdin.setRawMode(true);
118
+ stdin.resume();
119
+ stdin.setEncoding('utf8');
120
+ let input = '';
121
+ const onData = (char) => {
122
+ if (char === '\n' || char === '\r' || char === '\u0004') {
123
+ stdin.setRawMode(false);
124
+ stdin.pause();
125
+ stdin.removeListener('data', onData);
126
+ process.stderr.write('\n');
127
+ resolve(input);
128
+ } else if (char === '\u0003') { // Ctrl+C
129
+ stdin.setRawMode(false);
130
+ process.stderr.write('\n');
131
+ process.exit(130);
132
+ } else if (char === '\u007f' || char === '\b') { // backspace
133
+ input = input.slice(0, -1);
134
+ } else {
135
+ input += char;
136
+ }
137
+ };
138
+ stdin.on('data', onData);
139
+ });
140
+ }
141
+
142
+ // `login`: new-machine setup flow (added 2026-10-08, same-evening follow-up). Hidden password
143
+ // prompt -> POST /api/auth (owner password login) -> use the resulting session cookie to POST
144
+ // /api/auth {action:'create_token', scopes} -> write ONLY the raw token to a 0600 file (default
145
+ // ~/.mdshare/token, overridable via --token-file). The owner password is never a CLI
146
+ // argument/flag, never logged, never written anywhere; the issued token is never printed to
147
+ // stdout/stderr in the default (file) mode. `--stdout` is an explicit opt-in for piping the raw
148
+ // token straight into another program (e.g. a protected secrets-store CLI) instead of writing a
149
+ // file — in that mode ONLY the token goes to stdout (newline-terminated), every other message
150
+ // goes to stderr, so `TOKEN=$(mdshare-cli login --stdout ...)` or a direct pipe both work cleanly
151
+ // without the secret ever touching a log line.
152
+ async function cmdLogin(flags) {
153
+ const password = await readHiddenPassword('mdshare owner password: ');
154
+ if (!password) fail('No password provided');
155
+
156
+ const loginRes = await fetch(`${BASE_URL}/api/auth`, {
157
+ method: 'POST',
158
+ headers: { 'Content-Type': 'application/json' },
159
+ body: JSON.stringify({ password }),
160
+ });
161
+ const loginData = await loginRes.json().catch(() => ({}));
162
+ if (!loginRes.ok) fail(`login failed (${loginRes.status}): ${loginData.error || 'wrong password?'}`);
163
+ const setCookie = loginRes.headers.get('set-cookie');
164
+ if (!setCookie) fail('login succeeded but no session cookie was returned');
165
+ const cookie = setCookie.split(';')[0];
166
+
167
+ const name = flags.name || `cli-${hostname()}`;
168
+ const scopes = flags.scopes ? String(flags.scopes).split(',').map((s) => s.trim()).filter(Boolean) : undefined;
169
+ const createBody = { action: 'create_token', name };
170
+ if (scopes && scopes.length) createBody.scopes = scopes;
171
+ if (flags['never-expires']) createBody.never_expires = true;
172
+ else if (flags.days) createBody.expires_in_days = Number(flags.days);
173
+
174
+ const createRes = await fetch(`${BASE_URL}/api/auth`, {
175
+ method: 'POST',
176
+ headers: { 'Content-Type': 'application/json', Cookie: cookie },
177
+ body: JSON.stringify(createBody),
178
+ });
179
+ const createData = await createRes.json().catch(() => ({}));
180
+ if (!createRes.ok) fail(`token creation failed (${createRes.status}): ${createData.error || 'unknown error'}`);
181
+ const token = createData.token;
182
+ if (!token) fail('server did not return a token');
183
+
184
+ if (flags.stdout) {
185
+ process.stderr.write(`Issued token "${createData.name}" (id ${createData.id}, scopes: ${JSON.stringify(createData.scopes ?? [])}, expires ${createData.expires_at}). Token on stdout for piping — nowhere else.\n`);
186
+ process.stdout.write(token + '\n');
187
+ return;
188
+ }
189
+
190
+ const tokenFile = flags['token-file'] || DEFAULT_TOKEN_FILE;
191
+ mkdirSync(dirname(tokenFile), { recursive: true, mode: 0o700 });
192
+ writeFileSync(tokenFile, token + '\n', { mode: 0o600 });
193
+ chmodSync(tokenFile, 0o600); // belt-and-suspenders against umask overriding the mode above
194
+ printJson({ ok: true, id: createData.id, name: createData.name, scopes: createData.scopes ?? [], expires_at: createData.expires_at, token_file: tokenFile });
195
+ }
196
+
197
+ async function cmdStatus(flags) {
198
+ const res = await fetch(`${BASE_URL}/api/auth?action=whoami`, { headers: authHeaders(flags) });
199
+ const data = await res.json().catch(() => ({}));
200
+ if (!res.ok) fail(`status failed (${res.status}): ${data.error || 'unknown error'}`);
201
+ printJson(data);
202
+ }
203
+
204
+ // Full-text search (GET /api/doc?action=search, documents:read): `search "<text>"`. Prints one
205
+ // line per hit (id, title, link, snippet) or the raw JSON with --json. The older flag form
206
+ // (`search --q TERM --kind K`) is the catalog listing below and keeps working unchanged.
207
+ async function cmdFullTextSearch(text, flags) {
208
+ const params = new URLSearchParams({ action: 'search', q: text });
209
+ if (flags.limit) params.set('limit', String(flags.limit));
210
+ if (flags.offset) params.set('offset', String(flags.offset));
211
+ const res = await fetch(`${BASE_URL}/api/doc?${params.toString()}`, { headers: authHeaders(flags) });
212
+ const data = await res.json().catch(() => ({}));
213
+ if (!res.ok) fail(`search failed (${res.status}): ${data.error || 'unknown error'}${data.hint ? ` — ${data.hint}` : ''}`);
214
+ if (flags.json) return printJson(data);
215
+ const results = Array.isArray(data.results) ? data.results : [];
216
+ if (!results.length) { process.stdout.write(`no documents contain "${text}"\n`); return; }
217
+ const lines = results.map((r) => `${r.id} ${r.title}${r.kept ? ' ⭐' : ''}${r.is_public ? ' (public)' : ''}\n ${BASE_URL}/v/${r.id}\n ${r.snippet || ''}`);
218
+ process.stdout.write(`${lines.join('\n')}\n${data.total} match${data.total === 1 ? '' : 'es'}${data.next_offset != null ? ` · more: --offset ${data.next_offset}` : ''}\n`);
219
+ }
220
+
221
+ async function cmdSearch(flagsOrPositional, maybeFlags) {
222
+ // search "<text>" -> full text; search --q/--kind (flags only) -> catalog, as before.
223
+ if (Array.isArray(flagsOrPositional)) {
224
+ const flags = maybeFlags || {};
225
+ if (flagsOrPositional.length) return cmdFullTextSearch(flagsOrPositional.join(' '), flags);
226
+ return cmdSearch(flags);
227
+ }
228
+ const flags = flagsOrPositional || {};
229
+ const params = new URLSearchParams();
230
+ if (flags.q) params.set('q', flags.q);
231
+ if (flags.kind) params.set('kind', flags.kind);
232
+ if (flags.limit) params.set('limit', flags.limit);
233
+ if (flags.offset) params.set('offset', flags.offset);
234
+ const res = await fetch(`${BASE_URL}/api/pastes?${params.toString()}`, { headers: authHeaders(flags) });
235
+ const data = await res.json().catch(() => ({}));
236
+ if (!res.ok) fail(`search failed (${res.status}): ${data.error || 'unknown error'} — requires a bearer token with the documents:read scope`);
237
+ printJson(data);
238
+ }
239
+
240
+ // `read` takes an id or a full link (/v/<id>, /raw/<id>, /d/<id>, /a/<id>). A link on another host
241
+ // is refused: the token is only ever sent to MDSHARE_BASE_URL, never to a host named in an argument.
242
+ const LINK_KIND = { v: 'paste', raw: 'paste', d: 'diagram', a: 'archify' };
243
+ function parseReadTarget(arg, flags) {
244
+ const s = String(arg || '').trim();
245
+ if (/^https?:\/\//i.test(s)) {
246
+ let u;
247
+ try { u = new URL(s); } catch { fail(`not a valid link: ${s}`); }
248
+ const base = new URL(BASE_URL);
249
+ if (u.host !== base.host || u.protocol !== base.protocol) fail(`that link is on ${u.origin}, but this CLI talks to ${base.origin}; set MDSHARE_BASE_URL=${u.origin} to read it (the token is only sent to MDSHARE_BASE_URL)`);
250
+ const m = u.pathname.match(/^\/(v|raw|d|a)\/([A-Za-z0-9_-]{1,64})\/?$/);
251
+ if (!m) fail(`not a document link (expected /v/<id>, /raw/<id>, /d/<id> or /a/<id>): ${s}`);
252
+ if (flags.kind && flags.kind !== LINK_KIND[m[1]]) fail(`--kind ${flags.kind} does not match a /${m[1]}/ link`);
253
+ return { id: m[2], kind: LINK_KIND[m[1]] };
254
+ }
255
+ const m = s.match(/^\/?(v|raw|d|a)\/([A-Za-z0-9_-]{1,64})\/?$/);
256
+ if (m) return { id: m[2], kind: flags.kind || LINK_KIND[m[1]] };
257
+ return { id: s, kind: flags.kind || 'paste' };
258
+ }
259
+
260
+ async function cmdRead(positional, flags) {
261
+ if (!positional[0]) fail('usage: mdshare-cli read <id or link> [--kind paste|diagram|archify]');
262
+ const { id, kind } = parseReadTarget(positional[0], flags);
263
+ if (!id) fail('usage: mdshare-cli read <id or link> [--kind paste|diagram|archify]');
264
+ const path = READ_WRITE_PATH[kind];
265
+ if (!path) fail(`unknown kind: ${kind}`);
266
+ const res = await fetch(`${BASE_URL}${path}?id=${encodeURIComponent(id)}`, { headers: authHeaders(flags) });
267
+ if (!res.ok) {
268
+ const data = await res.json().catch(() => ({}));
269
+ fail(`read failed (${res.status}): ${data.error || 'unknown error'}${data.hint ? ` — ${data.hint}` : ''}`);
270
+ }
271
+ const text = await res.text();
272
+ process.stdout.write(text.endsWith('\n') ? text : text + '\n');
273
+ }
274
+
275
+ async function cmdCreate(positional, flags) {
276
+ const [kind, file] = positional;
277
+ const path = READ_WRITE_PATH[kind];
278
+ if (!path || !file) fail('usage: mdshare-cli create paste|diagram|archify <file> [--ttl SECONDS] [--title TITLE]');
279
+ let content;
280
+ try { content = readFileSync(file, 'utf8'); } catch (e) { fail(`could not read file: ${file} (${e.code || e.message})`); }
281
+
282
+ const body = {};
283
+ if (kind === 'paste') body.markdown = content;
284
+ if (kind === 'diagram') { body.svg = content; if (flags.title) body.title = flags.title; }
285
+ if (kind === 'archify') fail('create for kind=archify requires html+kind+ir fields not expressible as a single file via this CLI; use the MCP tools or POST /api/archify directly');
286
+ if (flags.ttl) body.ttl = Number(flags.ttl);
287
+ if (flags.keep) body.keep = true;
288
+ if (kind === 'paste' && typeof flags.parent === 'string') body.parent = flags.parent;
289
+ if (kind === 'paste' && typeof flags.origin === 'string') body.origin = flags.origin;
290
+ if (kind === 'paste' && typeof flags.lang === 'string') body.lang = flags.lang;
291
+ if (kind === 'paste' && typeof flags['translation-of'] === 'string') body.translation_of = flags['translation-of'];
292
+ if (kind === 'paste' && typeof flags.collection === 'string') body.collection = flags.collection;
293
+
294
+ const res = await fetch(`${BASE_URL}${path}`, { method: 'POST', headers: authHeaders(flags), body: JSON.stringify(body) });
295
+ const data = await res.json().catch(() => ({}));
296
+ if (!res.ok) fail(`create failed (${res.status}): ${data.error || 'unknown error'}`);
297
+ printJson(data);
298
+ // Publish checks (paste only): a one-line summary on stderr so a script sees problems even when
299
+ // it only parses stdout. --strict makes a "warn" a non-zero exit (the document still exists).
300
+ if (data.checks && Array.isArray(data.checks.warnings)) {
301
+ const warns = data.checks.warnings.filter((w) => w.severity === 'warn');
302
+ process.stderr.write(warns.length ? `checks: ${warns.length} problem(s): ${warns.map((w) => `line ${w.line} ${w.rule}`).join('; ')}\n` : 'checks: ok\n');
303
+ if (warns.length && flags.strict) fail('publish checks found problems (see "checks" above); fix and create again with --parent ' + data.id);
304
+ }
305
+ if (data.keep_ignored) process.stderr.write(`keep: ${data.keep_ignored}\n`);
306
+ if (data.collection_ignored) process.stderr.write(`collection: ${data.collection_ignored}\n`);
307
+ }
308
+
309
+ // Reading loop (2026-11-25): GET/POST /api/doc. Needs activity:read / activity:write /
310
+ // documents:read scopes on the token (see `login --scopes`).
311
+ async function docApi(flags, method, query, body) {
312
+ const res = await fetch(`${BASE_URL}/api/doc?${new URLSearchParams(query).toString()}`, {
313
+ method, headers: authHeaders(flags), ...(body ? { body: JSON.stringify(body) } : {}),
314
+ });
315
+ const data = res.status === 204 ? {} : await res.json().catch(() => ({}));
316
+ if (!res.ok) fail(`${query.action} failed (${res.status}): ${data.error || 'unknown error'}`);
317
+ return data;
318
+ }
319
+ async function cmdFeedback(positional, flags) {
320
+ const q = { action: 'feedback' };
321
+ if (positional[0]) q.id = positional[0];
322
+ if (typeof flags.status === 'string') q.status = flags.status;
323
+ else if (!positional[0]) q.status = 'open';
324
+ printJson(await docApi(flags, 'GET', q));
325
+ }
326
+ async function cmdResolve(positional, flags) {
327
+ if (!positional.length) fail('usage: mdshare-cli resolve <fb_id> [<fb_id> ...] [--in <new doc id>] [--status resolved|dismissed|open]');
328
+ printJson(await docApi(flags, 'POST', { action: 'resolve' }, { ids: positional, status: typeof flags.status === 'string' ? flags.status : 'resolved', resolved_in: typeof flags.in === 'string' ? flags.in : null }));
329
+ }
330
+ async function cmdReads(positional, flags) {
331
+ const q = positional.length ? { action: 'reads', ids: positional.join(',') } : { action: 'reads', unread: '1', days: String(flags.days || 7) };
332
+ printJson(await docApi(flags, 'GET', q));
333
+ }
334
+ async function cmdVersions(positional, flags) {
335
+ if (!positional[0]) fail('usage: mdshare-cli versions <id>');
336
+ printJson(await docApi(flags, 'GET', { action: 'versions', id: positional[0] }));
337
+ }
338
+
339
+ // Translations + collections (migration 012): POST/GET /api/doc?action=translation|collection.
340
+ // Changing them needs documents:write or documents:publish, and a token may change only documents
341
+ // it created; listing needs documents:read.
342
+ async function cmdTranslate(positional, flags) {
343
+ const [id] = positional;
344
+ if (!id || (typeof flags.of !== 'string' && !flags.unlink && typeof flags.lang !== 'string')) fail('usage: mdshare-cli translate <id> --of <original id> [--lang zh|en] | translate <id> --unlink');
345
+ const body = { id };
346
+ if (typeof flags.of === 'string') body.translation_of = flags.of;
347
+ if (flags.unlink) body.translation_of = null;
348
+ if (typeof flags.lang === 'string') body.lang = flags.lang;
349
+ printJson(await docApi(flags, 'POST', { action: 'translation' }, body));
350
+ }
351
+ async function cmdCollection(positional, flags) {
352
+ const [id, slug] = positional;
353
+ if (!id || (!slug && !flags.none)) fail('usage: mdshare-cli collection <id> <slug> | collection <id> --none');
354
+ printJson(await docApi(flags, 'POST', { action: 'collection' }, { id, collection: flags.none ? null : slug }));
355
+ }
356
+ async function cmdCollections(positional, flags) {
357
+ const data = await docApi(flags, 'GET', positional[0] ? { action: 'collection', slug: positional[0] } : { action: 'collection' });
358
+ if (flags.json) return printJson(data);
359
+ if (positional[0]) {
360
+ for (const e of data.items || []) process.stdout.write(`${e.opened ? 'read ' : 'unread'} ${e.kept ? '⭐' : ' '} ${String(e.updated_at || '').slice(0, 10)} ${e.title || 'Untitled'} ${e.links.map((l) => `${l.lang || '?'}:${BASE_URL}/v/${l.id}`).join(' ')}\n`);
361
+ if (!(data.items || []).length) process.stdout.write('(empty)\n');
362
+ return;
363
+ }
364
+ for (const c of data.collections || []) process.stdout.write(`${c.slug}\t${c.count}\t${String(c.updated_at || '').slice(0, 10)}\t${BASE_URL}/c/${c.slug}\n`);
365
+ if (!(data.collections || []).length) process.stdout.write('(no collections)\n');
366
+ }
367
+
368
+ async function cmdPublish(positional, flags) {
369
+ const [id] = positional;
370
+ const kind = flags.kind;
371
+ const isPublicRaw = flags.public;
372
+ if (!id || !kind || isPublicRaw === undefined) {
373
+ fail('usage: mdshare-cli publish <id> --kind paste|diagram|archify --public true|false');
374
+ }
375
+ const is_public = String(isPublicRaw) === 'true';
376
+ const res = await fetch(`${BASE_URL}/api/pin`, {
377
+ method: 'PATCH',
378
+ headers: authHeaders(flags),
379
+ body: JSON.stringify({ id, kind, is_public }),
380
+ });
381
+ const data = await res.json().catch(() => ({}));
382
+ if (!res.ok) fail(`publish failed (${res.status}): ${data.error || 'unknown error'} — requires documents:publish on a document this token itself created`);
383
+ printJson(data);
384
+ }
385
+
386
+ // `setup <agent>` (added 2026-12-01, agent-install kit): prints a copy-paste MCP config snippet
387
+ // for one coding agent. Never reads or prints a real token -- the snippet always uses the literal
388
+ // placeholder <your-token>, which the reader substitutes themselves after minting one (Settings ->
389
+ // API tokens, or `mdshare-cli login --scopes ...`). The tool names listed in each snippet's comment
390
+ // come from the MCP server's own TOOLS export (mcp/dist/tools.js), not a hand-copied list, so this
391
+ // command can't silently drift from what the server actually exposes; tests/agents-page.test.mjs
392
+ // enforces the same thing for the public /agents page.
393
+ const SETUP_AGENTS = ['claude-code', 'codex', 'cursor', 'openclaw', 'curl'];
394
+
395
+ async function mcpToolNames() {
396
+ const fallback = ['share_markdown', 'share_diagram', 'auth_status', 'search_documents', 'read_document', 'publish_document', 'list_feedback', 'resolve_feedback'];
397
+ try {
398
+ const mod = await import(new URL('../dist/tools.js', import.meta.url).href);
399
+ return Array.isArray(mod.TOOLS) ? mod.TOOLS.map((t) => t.name) : fallback;
400
+ } catch {
401
+ return fallback; // dist/ not built yet (e.g. running straight from source) -- still useful output.
402
+ }
403
+ }
404
+
405
+ async function cmdSetup(positional, flags) {
406
+ const agent = positional[0];
407
+ if (!agent || !SETUP_AGENTS.includes(agent)) {
408
+ fail(`usage: mdshare-cli setup <${SETUP_AGENTS.join('|')}> [--base-url URL]`);
409
+ }
410
+ const base = flags['base-url'] || BASE_URL;
411
+ const tools = await mcpToolNames();
412
+ const toolsLine = `# Tools this gives the agent: ${tools.join(', ')}`;
413
+ const lines = [
414
+ `# mdshare setup for ${agent}`,
415
+ `# 1. Get a token: ${base}/settings -> "API tokens" -> Create token. Pick scopes for what`,
416
+ "# this agent should do: documents:write to publish, documents:read + activity:read to",
417
+ "# read feedback back, activity:write to resolve it after a revision.",
418
+ "# Or from a terminal: npx -y -p mdshare mdshare-cli login --scopes documents:read,documents:write,documents:publish,activity:read,activity:write",
419
+ "# 2. Put the token ONLY in the agent's own env/config below -- never in a chat message, a",
420
+ "# file you commit, or a bare CLI argument. Replace <your-token> with the real mds_... value.",
421
+ '',
422
+ ];
423
+ if (agent === 'claude-code') {
424
+ lines.push('claude mcp add mdshare --env MDSHARE_AGENT_TOKEN=<your-token> -- npx -y mdshare', '', toolsLine);
425
+ } else if (agent === 'codex') {
426
+ lines.push(
427
+ '# ~/.codex/config.toml',
428
+ '[mcp_servers.mdshare]',
429
+ 'command = "npx"',
430
+ 'args = ["-y", "mdshare"]',
431
+ 'env = { MDSHARE_AGENT_TOKEN = "<your-token>" }',
432
+ '',
433
+ toolsLine,
434
+ );
435
+ } else if (agent === 'cursor') {
436
+ lines.push(
437
+ '// .cursor/mcp.json',
438
+ JSON.stringify({ mcpServers: { mdshare: { command: 'npx', args: ['-y', 'mdshare'], env: { MDSHARE_AGENT_TOKEN: '<your-token>' } } } }, null, 2),
439
+ '',
440
+ toolsLine,
441
+ );
442
+ } else if (agent === 'openclaw') {
443
+ lines.push(
444
+ 'openclaw mcp add mdshare --command npx --arg -y --arg mdshare --env MDSHARE_AGENT_TOKEN=<your-token>',
445
+ 'openclaw mcp doctor mdshare --probe',
446
+ '',
447
+ toolsLine,
448
+ );
449
+ } else if (agent === 'curl') {
450
+ lines.push(
451
+ 'export MDSHARE_AGENT_TOKEN=<your-token>',
452
+ `curl -sS -X POST ${base}/api/share -H "Authorization: Bearer $MDSHARE_AGENT_TOKEN" -H "Content-Type: application/json" \\`,
453
+ ` -d '{"markdown":"# Report\\n\\nbody", "keep": true}'`,
454
+ '# -> {"url": ".../v/<id>", "id": "<id>", ...} -- send the url, not the pasted text',
455
+ `curl -sS "${base}/api/doc?action=feedback&status=open" -H "Authorization: Bearer $MDSHARE_AGENT_TOKEN"`,
456
+ );
457
+ }
458
+ process.stdout.write(lines.join('\n') + '\n');
459
+ }
460
+
461
+
462
+ async function main() {
463
+ const [, , command, ...rest] = process.argv;
464
+ const { positional, flags } = parseArgs(rest);
465
+
466
+ switch (command) {
467
+ case 'login': return cmdLogin(flags);
468
+ case 'status': return cmdStatus(flags);
469
+ case 'search': return cmdSearch(positional, flags);
470
+ case 'recent': return cmdSearch({ ...flags, q: undefined });
471
+ case 'read': return cmdRead(positional, flags);
472
+ case 'create': return cmdCreate(positional, flags);
473
+ case 'publish': return cmdPublish(positional, flags);
474
+ case 'setup': return cmdSetup(positional, flags);
475
+ case 'feedback': return cmdFeedback(positional, flags);
476
+ case 'resolve': return cmdResolve(positional, flags);
477
+ case 'reads': return cmdReads(positional, flags);
478
+ case 'versions': return cmdVersions(positional, flags);
479
+ case 'translate': return cmdTranslate(positional, flags);
480
+ case 'collection': return cmdCollection(positional, flags);
481
+ case 'collections': return cmdCollections(positional, flags);
482
+ default:
483
+ process.stderr.write([
484
+ 'mdshare-cli — portable CLI for the mdshare agent API',
485
+ '',
486
+ 'Commands:',
487
+ ' login [--name NAME] [--scopes documents:read,documents:write,...] [--days N]',
488
+ ' [--token-file PATH] [--stdout] [--never-expires]',
489
+ ' New-machine setup: hidden password prompt -> owner login -> issues a scoped',
490
+ ' token -> writes it to a 0600 file (default ~/.mdshare/token). --stdout prints',
491
+ ' ONLY the token to stdout (for piping into e.g. a secrets-store CLI) instead of',
492
+ ' writing a file. Never pass the password as an argument — type it when prompted,',
493
+ ' or set MDSHARE_OWNER_PASSWORD for non-interactive use.',
494
+ ' status',
495
+ ' search "<text>" [--limit N] [--offset N] [--json] full text over titles + bodies (中文 too)',
496
+ ' search [--q TERM] [--kind paste|diagram|archify|all] [--limit N] [--offset N] catalog',
497
+ ' recent [--kind K] [--limit N] [--offset N]',
498
+ ' read <id | https://<site>/v/<id> link> [--kind paste|diagram|archify]',
499
+ ' create paste|diagram <file> [--ttl SECONDS] [--title TITLE] [--keep]',
500
+ ' [--parent ID] [--origin SESSION] [--strict] (prints publish checks to stderr)',
501
+ ' [--lang zh|en] [--translation-of ID] [--collection SLUG]',
502
+ ' --translation-of links the same text in the other language (中文/English switch on both',
503
+ ' pages); --collection files it under /c/<slug>. Versions keep both.',
504
+ ' translate <id> --of <original id> [--lang zh|en] | translate <id> --unlink',
505
+ ' collection <id> <slug> | collection <id> --none (the whole version family)',
506
+ ' collections [<slug>] [--json] list collections, or one collection\'s contents',
507
+ ' feedback [<doc id>] [--status open|resolved|dismissed] (default: all open feedback)',
508
+ ' resolve <fb_id>... [--in <new doc id>] [--status resolved|dismissed|open]',
509
+ ' reads [<doc id>...] [--days N] (no ids: documents the owner has not opened yet)',
510
+ ' versions <id>',
511
+ ' publish <id> --kind K --public true|false',
512
+ ' setup <claude-code|codex|cursor|openclaw|curl> [--base-url URL] print a copy-paste MCP',
513
+ ' config snippet for that agent (never a real token -- always the <your-token> placeholder)',
514
+ '',
515
+ 'Token: set MDSHARE_AGENT_TOKEN or MDSHARE_AGENT_TOKEN_FILE (env), or --token-file <path>.',
516
+ 'Never pass a token as a bare CLI argument.',
517
+ ].join('\n') + '\n');
518
+ process.exit(command ? 1 : 0);
519
+ }
520
+ }
521
+
522
+ // Only actually run as a CLI (parse real process.argv, call process.exit on error/usage) when
523
+ // this file is the process entrypoint. Importing it as a module (tests/cli-login.test.mjs) must
524
+ // never trigger argv parsing or process.exit — it only wants the exported functions below with
525
+ // global.fetch mocked.
526
+ const isDirectRun = process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
527
+ if (isDirectRun) {
528
+ main().catch((err) => {
529
+ process.stderr.write((err && err.message ? err.message : String(err)) + '\n');
530
+ process.exit(1);
531
+ });
532
+ }
533
+
534
+ export {
535
+ parseArgs, resolveToken, authHeaders, readHiddenPassword,
536
+ cmdLogin, cmdStatus, cmdSearch, cmdFullTextSearch, cmdRead, parseReadTarget, cmdCreate, cmdPublish, cmdFeedback, cmdResolve, cmdReads, cmdVersions,
537
+ cmdTranslate, cmdCollection, cmdCollections, cmdSetup, mcpToolNames, SETUP_AGENTS, main,
538
+ DEFAULT_TOKEN_FILE, CliError,
539
+ };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- export {};
2
+ export { TOOLS, callTool, resolveAgentToken } from "./tools.js";
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAaA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,84 +1,37 @@
1
1
  #!/usr/bin/env node
2
+ // mcp/src/index.ts — the stdio MCP server entrypoint. All actual tool definitions/logic live in
3
+ // ./tools.ts (zero npm dependencies, so tests can import them without mcp/'s own node_modules —
4
+ // see that file's header comment). This file only wires TOOLS/callTool up to the
5
+ // @modelcontextprotocol/sdk Server + stdio transport.
2
6
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
7
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
8
  import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
5
- const MDSHARE_API = "https://mdshare-rileylins-projects.vercel.app/api/share";
9
+ import { TOOLS, callTool } from "./tools.js";
10
+ export { TOOLS, callTool, resolveAgentToken } from "./tools.js";
6
11
  const server = new Server({
7
- name: "mdshare-mcp",
8
- version: "1.0.0",
12
+ name: "mdshare",
13
+ version: "1.0.1",
9
14
  }, {
10
15
  capabilities: {
11
16
  tools: {},
12
17
  },
13
18
  });
14
- server.setRequestHandler(ListToolsRequestSchema, async () => {
15
- return {
16
- tools: [
17
- {
18
- name: "share_markdown",
19
- description: "Share markdown as a beautifully rendered web page. Returns a URL you can send in any chat app.",
20
- inputSchema: {
21
- type: "object",
22
- properties: {
23
- markdown: {
24
- type: "string",
25
- description: "The markdown content to render and share",
26
- },
27
- ttl: {
28
- type: "number",
29
- description: "Time-to-live in seconds (optional, default: 86400 = 24h)",
30
- },
31
- },
32
- required: ["markdown"],
33
- },
34
- },
35
- ],
36
- };
37
- });
19
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
38
20
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
39
- if (request.params.name !== "share_markdown") {
40
- throw new Error(`Unknown tool: ${request.params.name}`);
41
- }
42
- const args = request.params.arguments;
43
- if (!args.markdown || typeof args.markdown !== "string") {
44
- throw new Error("markdown argument is required and must be a string");
45
- }
46
- const body = {
47
- markdown: args.markdown,
48
- };
49
- if (args.ttl !== undefined) {
50
- body.ttl = args.ttl;
51
- }
52
- const response = await fetch(MDSHARE_API, {
53
- method: "POST",
54
- headers: {
55
- "Content-Type": "application/json",
56
- },
57
- body: JSON.stringify(body),
58
- });
59
- if (!response.ok) {
60
- const errorText = await response.text().catch(() => "unknown error");
61
- throw new Error(`mdshare API error: ${response.status} ${response.statusText} — ${errorText}`);
62
- }
63
- const data = (await response.json());
64
- if (!data.url) {
65
- throw new Error("mdshare API returned no URL");
66
- }
67
- return {
68
- content: [
69
- {
70
- type: "text",
71
- text: data.url,
72
- },
73
- ],
74
- };
21
+ return callTool(request.params.name, request.params.arguments || {});
75
22
  });
76
23
  async function main() {
77
24
  const transport = new StdioServerTransport();
78
25
  await server.connect(transport);
79
26
  }
80
- main().catch((err) => {
81
- console.error("mdshare-mcp fatal error:", err);
82
- process.exit(1);
83
- });
27
+ // Only actually connect the stdio transport when this file is the process entrypoint (matches
28
+ // mcp/bin/mdshare-cli.mjs's convention) — importing TOOLS/callTool from a test must never start a
29
+ // server or touch stdio.
30
+ const isDirectRun = process.argv[1] != null && import.meta.url === `file://${process.argv[1]}`;
31
+ if (isDirectRun) {
32
+ main().catch((err) => {
33
+ console.error("mdshare fatal error:", err);
34
+ process.exit(1);
35
+ });
36
+ }
84
37
  //# sourceMappingURL=index.js.map