@realytix/cli 0.0.0-stage → 0.1.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // Entry point of the `realytix` binary: wires the real dependencies and exits with run()'s code.
3
+ import { createRequire } from 'node:module';
4
+ import { auth } from '@modelcontextprotocol/sdk/client/auth.js';
5
+ import open from 'open';
6
+ import { startLoopbackServer } from './auth/loopback.js';
7
+ import { run } from './cli.js';
8
+ import { connect } from './client.js';
9
+ import { ConfigStore } from './config.js';
10
+ const { version } = createRequire(import.meta.url)('../package.json');
11
+ export function realDeps() {
12
+ const env = process.env;
13
+ const hasDisplay = process.platform === 'darwin' || process.platform === 'win32' || !!env.DISPLAY || !!env.WAYLAND_DISPLAY;
14
+ return {
15
+ env,
16
+ store: ConfigStore.fromEnv(env),
17
+ version,
18
+ stdout: (s) => process.stdout.write(`${s}\n`),
19
+ stderr: (s) => process.stderr.write(`${s}\n`),
20
+ connect,
21
+ openBrowser: async (url) => {
22
+ try {
23
+ const child = await open(url, { wait: false });
24
+ child.on('error', () => undefined);
25
+ return true;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ },
31
+ startLoopback: startLoopbackServer,
32
+ auth,
33
+ fetch: globalThis.fetch,
34
+ canOpenBrowser: hasDisplay && !env.SSH_CONNECTION && !env.SSH_TTY && !env.CI,
35
+ now: Date.now,
36
+ };
37
+ }
38
+ const code = await run(process.argv.slice(2), realDeps());
39
+ process.exitCode = code;
@@ -0,0 +1,127 @@
1
+ // Turn the generated OptionSpecs into commander options, and parsed options back into a tool input.
2
+ import { readFileSync } from 'node:fs';
3
+ import { Option } from 'commander';
4
+ import { UsageError } from './errors.js';
5
+ export const camel = (flag) => flag.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
6
+ export function parseJsonArg(raw, what) {
7
+ try {
8
+ return JSON.parse(raw);
9
+ }
10
+ catch (err) {
11
+ throw new UsageError(`${what} is not valid JSON: ${err.message}`);
12
+ }
13
+ }
14
+ function parseNumber(spec, raw) {
15
+ const n = spec.kind === 'integer' ? Number.parseInt(raw, 10) : Number(raw);
16
+ if (!Number.isFinite(n) || String(n) !== raw.trim() && spec.kind === 'integer' && !/^-?\d+$/.test(raw.trim())) {
17
+ throw new UsageError(`--${spec.flag} expects ${spec.kind === 'integer' ? 'an integer' : 'a number'}, got "${raw}".`);
18
+ }
19
+ if (spec.minimum !== undefined && n < spec.minimum)
20
+ throw new UsageError(`--${spec.flag} must be at least ${spec.minimum}.`);
21
+ if (spec.maximum !== undefined && n > spec.maximum)
22
+ throw new UsageError(`--${spec.flag} must be at most ${spec.maximum}.`);
23
+ return n;
24
+ }
25
+ export function helpText(spec) {
26
+ let text = spec.description;
27
+ if (spec.itemChoices)
28
+ text += ` Values: ${spec.itemChoices.join(', ')}.`;
29
+ if (spec.kind === 'integer|string' && spec.choices && !spec.choices.every((c) => text.includes(c)))
30
+ text += ` Integer or ${spec.choices.map((c) => `"${c}"`).join('/')}.`;
31
+ if (spec.minimum !== undefined || spec.maximum !== undefined) {
32
+ const range = [spec.minimum !== undefined ? `min ${spec.minimum}` : '', spec.maximum !== undefined ? `max ${spec.maximum}` : ''].filter(Boolean).join(', ');
33
+ text += ` (${range})`;
34
+ }
35
+ if (spec.default !== undefined)
36
+ text += ` [default: ${JSON.stringify(spec.default).replace(/^"|"$/g, '')}]`;
37
+ if (spec.required)
38
+ text = `(required) ${text}`;
39
+ return text;
40
+ }
41
+ export function buildOption(spec) {
42
+ const help = helpText(spec);
43
+ switch (spec.kind) {
44
+ case 'boolean':
45
+ return [new Option(`--${spec.flag}`, help), new Option(`--no-${spec.flag}`, `Turn off --${spec.flag}.`).hideHelp()];
46
+ case 'integer':
47
+ case 'number':
48
+ return [new Option(`--${spec.flag} <n>`, help).argParser((raw) => parseNumber(spec, raw))];
49
+ case 'integer|string':
50
+ return [
51
+ new Option(`--${spec.flag} <value>`, help).argParser((raw) => {
52
+ if (spec.choices?.includes(raw))
53
+ return raw;
54
+ if (/^-?\d+$/.test(raw.trim()))
55
+ return parseNumber({ ...spec, kind: 'integer' }, raw);
56
+ throw new UsageError(`--${spec.flag} expects an integer${spec.choices ? ` or one of ${spec.choices.join(', ')}` : ''}, got "${raw}".`);
57
+ }),
58
+ ];
59
+ case 'string[]':
60
+ return [
61
+ new Option(`--${spec.flag} <value>`, help).argParser((raw, prev) => {
62
+ const items = raw
63
+ .split(',')
64
+ .map((s) => s.trim())
65
+ .filter(Boolean);
66
+ if (spec.itemChoices) {
67
+ const bad = items.filter((i) => !spec.itemChoices.includes(i));
68
+ if (bad.length)
69
+ throw new UsageError(`--${spec.flag}: unknown value ${bad.map((b) => `"${b}"`).join(', ')}. Allowed: ${spec.itemChoices.join(', ')}.`);
70
+ }
71
+ return [...(prev ?? []), ...items];
72
+ }),
73
+ ];
74
+ case 'json':
75
+ return [new Option(`--${spec.flag} <json>`, help).argParser((raw) => parseJsonArg(raw, `--${spec.flag}`))];
76
+ case 'string':
77
+ default: {
78
+ const opt = new Option(`--${spec.flag} <value>`, help);
79
+ if (spec.choices)
80
+ opt.choices(spec.choices);
81
+ return [opt];
82
+ }
83
+ }
84
+ }
85
+ /** Options every tool command accepts in addition to its schema-derived ones. */
86
+ export function addInputOptions(cmd) {
87
+ return cmd
88
+ .option('--input-json <json>', 'Whole input as a JSON object; explicit options override its keys.')
89
+ .option('--input-file <path>', 'Read the JSON input object from a file (or "-" for stdin).');
90
+ }
91
+ export function readInputFile(path) {
92
+ const raw = path === '-' ? readFileSync(0, 'utf8') : readFileSync(path, 'utf8');
93
+ return parseJsonArg(raw, `--input-file ${path}`);
94
+ }
95
+ /**
96
+ * Merge --input-file < --input-json < explicit options into the tool input,
97
+ * then enforce the schema's required properties.
98
+ */
99
+ export function buildInput(tool, parsed, readFile = readInputFile) {
100
+ const input = {};
101
+ const layers = [];
102
+ if (typeof parsed.inputFile === 'string')
103
+ layers.push(readFile(parsed.inputFile));
104
+ if (typeof parsed.inputJson === 'string')
105
+ layers.push(parseJsonArg(parsed.inputJson, '--input-json'));
106
+ else if (parsed.inputJson !== undefined)
107
+ layers.push(parsed.inputJson);
108
+ for (const layer of layers) {
109
+ if (!layer || typeof layer !== 'object' || Array.isArray(layer))
110
+ throw new UsageError('The JSON input must be an object.');
111
+ Object.assign(input, layer);
112
+ }
113
+ for (const spec of tool.options) {
114
+ const v = parsed[camel(spec.flag)];
115
+ if (v !== undefined)
116
+ input[spec.property] = v;
117
+ }
118
+ const missing = tool.required.filter((p) => input[p] === undefined);
119
+ if (missing.length) {
120
+ const flags = missing.map((p) => {
121
+ const spec = tool.options.find((o) => o.property === p);
122
+ return spec ? `--${spec.flag}` : p;
123
+ });
124
+ throw new UsageError(`Missing required option${missing.length > 1 ? 's' : ''}: ${flags.join(', ')}`, `See \`realytix ${tool.command} --help\`.`);
125
+ }
126
+ return input;
127
+ }
package/dist/render.js ADDED
@@ -0,0 +1,110 @@
1
+ // Readable rendering of tool results for terminals.
2
+ // array of flat objects -> aligned table
3
+ // object -> key: value lines, nested blocks indented
4
+ // array of scalars -> comma list (short) or bullet list (long)
5
+ // Color is optional; `colors: false` yields plain text for tests and pipes.
6
+ import pc from 'picocolors';
7
+ const isScalar = (v) => v === null || v === undefined || ['string', 'number', 'boolean'].includes(typeof v);
8
+ const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
9
+ const isFlatObject = (v) => isPlainObject(v) && Object.values(v).every(isScalar);
10
+ export function render(value, opts = {}) {
11
+ const o = { colors: opts.colors ?? false, maxCell: opts.maxCell ?? 48, indent: opts.indent ?? '' };
12
+ return renderAny(value, o, '').replace(/\s+$/, '');
13
+ }
14
+ function paint(enabled, fn, s) {
15
+ return enabled ? fn(s) : s;
16
+ }
17
+ export function formatScalar(v) {
18
+ if (v === null || v === undefined)
19
+ return '-';
20
+ if (typeof v === 'boolean')
21
+ return v ? 'yes' : 'no';
22
+ if (typeof v === 'number')
23
+ return Number.isInteger(v) && Math.abs(v) >= 10_000 ? v.toLocaleString('en-US') : String(v);
24
+ return String(v);
25
+ }
26
+ function clip(s, max) {
27
+ const one = s.replace(/\s*\n\s*/g, ' ');
28
+ return one.length > max ? `${one.slice(0, max - 1)}…` : one;
29
+ }
30
+ function renderAny(value, o, indent) {
31
+ if (isScalar(value))
32
+ return `${indent}${formatScalar(value)}\n`;
33
+ if (Array.isArray(value))
34
+ return renderArray(value, o, indent);
35
+ if (isPlainObject(value))
36
+ return renderObject(value, o, indent);
37
+ return `${indent}${JSON.stringify(value)}\n`;
38
+ }
39
+ function renderObject(obj, o, indent) {
40
+ const keys = Object.keys(obj);
41
+ if (!keys.length)
42
+ return `${indent}(empty)\n`;
43
+ const width = Math.min(Math.max(...keys.map((k) => k.length)), 28);
44
+ let out = '';
45
+ for (const key of keys) {
46
+ const v = obj[key];
47
+ const label = paint(o.colors, pc.dim, key.padEnd(width));
48
+ if (isScalar(v)) {
49
+ out += `${indent}${label} ${formatScalar(v)}\n`;
50
+ }
51
+ else if (Array.isArray(v) && v.length === 0) {
52
+ out += `${indent}${label} (none)\n`;
53
+ }
54
+ else if (Array.isArray(v) && v.every(isScalar) && v.length <= 12) {
55
+ out += `${indent}${label} ${v.map(formatScalar).join(', ')}\n`;
56
+ }
57
+ else {
58
+ const count = Array.isArray(v) ? ` (${v.length})` : '';
59
+ out += `${indent}${paint(o.colors, pc.bold, key)}${count}\n`;
60
+ out += renderAny(v, o, `${indent} `);
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ function renderArray(arr, o, indent) {
66
+ if (!arr.length)
67
+ return `${indent}(none)\n`;
68
+ if (arr.every(isScalar)) {
69
+ if (arr.length <= 12)
70
+ return `${indent}${arr.map(formatScalar).join(', ')}\n`;
71
+ return arr.map((v) => `${indent}- ${formatScalar(v)}\n`).join('');
72
+ }
73
+ if (arr.every(isFlatObject))
74
+ return renderTable(arr, o, indent);
75
+ return arr
76
+ .map((item, i) => {
77
+ const head = `${indent}${paint(o.colors, pc.dim, `#${i + 1}`)}\n`;
78
+ return head + renderAny(item, o, `${indent} `);
79
+ })
80
+ .join('');
81
+ }
82
+ export function renderTable(rows, o, indent = '') {
83
+ const columns = [];
84
+ for (const row of rows)
85
+ for (const k of Object.keys(row))
86
+ if (!columns.includes(k))
87
+ columns.push(k);
88
+ const cells = rows.map((r) => columns.map((c) => clip(formatScalar(r[c]), o.maxCell)));
89
+ const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length)));
90
+ const numeric = columns.map((c) => rows.every((r) => r[c] === null || r[c] === undefined || typeof r[c] === 'number'));
91
+ const line = (vals, dim) => `${indent}${vals
92
+ .map((v, i) => (numeric[i] ? v.padStart(widths[i]) : v.padEnd(widths[i])))
93
+ .map((v) => (dim ? paint(o.colors, pc.dim, v) : v))
94
+ .join(' ')
95
+ .replace(/\s+$/, '')}\n`;
96
+ return line(columns, true) + line(widths.map((w) => '-'.repeat(w)), true) + cells.map((r) => line(r, false)).join('');
97
+ }
98
+ /** Rendering of a complete tool result for the default (non --json) mode. */
99
+ export function renderResult(structured, text, opts = {}) {
100
+ if (structured !== undefined && structured !== null)
101
+ return render(structured, opts);
102
+ if (text === undefined)
103
+ return '(no content)';
104
+ try {
105
+ return render(JSON.parse(text), opts);
106
+ }
107
+ catch {
108
+ return text.trim();
109
+ }
110
+ }
@@ -0,0 +1,49 @@
1
+ import { textOf } from './client.js';
2
+ import { parseToolErrorPayload, ToolCallError } from './errors.js';
3
+ import { renderResult } from './render.js';
4
+ export async function callTool(ctx, name, input) {
5
+ const client = await ctx.deps.connect({ serverUrl: ctx.serverUrl, store: ctx.deps.store, version: ctx.deps.version });
6
+ let raw;
7
+ try {
8
+ raw = await client.callTool(name, input);
9
+ }
10
+ finally {
11
+ await client.close();
12
+ }
13
+ const text = textOf(raw);
14
+ const structured = raw.structuredContent;
15
+ if (raw.isError)
16
+ throw new ToolCallError(name, parseToolErrorPayload(text, structured));
17
+ return { structured, text, raw };
18
+ }
19
+ /** Print a tool outcome: --json exact payload, --quiet nothing, default readable. */
20
+ export function emitOutcome(ctx, outcome) {
21
+ if (ctx.json) {
22
+ ctx.deps.stdout(outcome.structured !== undefined ? JSON.stringify(outcome.structured, null, 2) : (outcome.text ?? ''));
23
+ return;
24
+ }
25
+ if (ctx.quiet)
26
+ return;
27
+ ctx.deps.stdout(renderResult(outcome.structured, outcome.text, { colors: ctx.color }));
28
+ }
29
+ export async function runTool(ctx, name, input) {
30
+ const outcome = await callTool(ctx, name, input);
31
+ emitOutcome(ctx, outcome);
32
+ return outcome;
33
+ }
34
+ /** Deep search for an e-mail address under a key named `email` (account results). */
35
+ export function findEmail(value, depth = 0) {
36
+ if (!value || typeof value !== 'object' || depth > 3)
37
+ return undefined;
38
+ if (Array.isArray(value))
39
+ return undefined;
40
+ const obj = value;
41
+ if (typeof obj.email === 'string')
42
+ return obj.email;
43
+ for (const v of Object.values(obj)) {
44
+ const found = findEmail(v, depth + 1);
45
+ if (found)
46
+ return found;
47
+ }
48
+ return undefined;
49
+ }
package/install.sh ADDED
@@ -0,0 +1,40 @@
1
+ #!/bin/sh
2
+ # Installs the realytix CLI from npm (@realytix/cli). POSIX sh; needs Node.js 22 or newer.
3
+ # curl -fsSL https://realytix.io/cli/install.sh | sh
4
+ # REALYTIX_CLI_VERSION=0.2.0 sh install.sh # pin a version
5
+ set -eu
6
+
7
+ PKG="@realytix/cli"
8
+ VERSION="${REALYTIX_CLI_VERSION:-latest}"
9
+ MIN_NODE=22
10
+
11
+ say() { printf '%s\n' "$*" >&2; }
12
+ fail() { say "realytix install: $*"; exit 1; }
13
+
14
+ command -v node >/dev/null 2>&1 || fail "Node.js is not installed. Install Node.js $MIN_NODE or newer from https://nodejs.org and run this script again."
15
+ command -v npm >/dev/null 2>&1 || fail "npm is not available next to node. Reinstall Node.js from https://nodejs.org."
16
+
17
+ NODE_VERSION="$(node -p 'process.versions.node' 2>/dev/null || echo 0)"
18
+ NODE_MAJOR="${NODE_VERSION%%.*}"
19
+ case "$NODE_MAJOR" in
20
+ ''|*[!0-9]*) fail "Could not read the Node.js version (got '$NODE_VERSION')." ;;
21
+ esac
22
+ [ "$NODE_MAJOR" -ge "$MIN_NODE" ] || fail "Node.js $NODE_VERSION found; version $MIN_NODE or newer is required (nvm install $MIN_NODE, or https://nodejs.org)."
23
+
24
+ say "Installing $PKG@$VERSION with npm (Node.js $NODE_VERSION)…"
25
+ if ! npm install -g "$PKG@$VERSION" >/dev/null 2>&1; then
26
+ say "Global install failed. If it was a permission error, either fix npm's prefix"
27
+ say "(https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally)"
28
+ say "or rerun with sudo: sudo npm install -g $PKG@$VERSION"
29
+ exit 1
30
+ fi
31
+
32
+ if command -v realytix >/dev/null 2>&1; then
33
+ say "Installed: $(realytix --version) at $(command -v realytix)"
34
+ else
35
+ PREFIX_BIN="$(npm prefix -g 2>/dev/null)/bin"
36
+ say "Installed, but '$PREFIX_BIN' is not on your PATH. Add it, e.g.: export PATH=\"$PREFIX_BIN:\$PATH\""
37
+ fi
38
+ say ""
39
+ say "Next: realytix login (signs in to Realytix in your browser; Pro+AI plan required)"
40
+ say " realytix tools (lists the available tools)"
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@realytix/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Command-line client for the Realytix MCP server: Amazon product research tools for terminals and coding agents (Pro+AI plan).",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "bin": {
8
+ "realytix": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "install.sh"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "scripts": {
19
+ "gen": "node scripts/gen-commands.mts",
20
+ "build": "node scripts/gen-commands.mts && tsc -p tsconfig.json",
21
+ "typecheck": "tsc -p tsconfig.json --noEmit",
22
+ "test": "vitest run",
23
+ "lint:words": "node ../scripts/banned-words.mjs mcp/cli",
24
+ "prepack": "node scripts/gen-commands.mts && tsc -p tsconfig.json"
25
+ },
26
+ "dependencies": {
27
+ "@modelcontextprotocol/sdk": "1.32.2",
28
+ "commander": "^14.0.0",
29
+ "open": "^10.1.2",
30
+ "picocolors": "^1.1.1"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^22.15.0",
34
+ "typescript": "5.9.3",
35
+ "vitest": "^3.2.4",
36
+ "zod": "^3.25.76"
37
+ }
38
+ }