@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/README.md CHANGED
@@ -1,3 +1,175 @@
1
- # Temporary Holding Version
1
+ # realytix — command-line client for the Realytix MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `realytix` puts the Realytix product-research tools in your terminal and in the hands of
4
+ coding agents (Claude Code, Codex, Cursor's agent, shell scripts). It is an MCP client of
5
+ `https://mcp.realytix.io/mcp`: same tools, same account, same credits as the Realytix
6
+ connector for Claude, ChatGPT and Cursor. It needs the **Pro+AI** plan.
7
+
8
+ ```sh
9
+ npm i -g @realytix/cli # or: curl -fsSL https://realytix.io/cli/install.sh | sh
10
+ realytix login # opens the browser once, saves the session
11
+ realytix get-product --asin B0ABCDEFGH --marketplace de
12
+ realytix get-product --asin B0ABCDEFGH --json | jq .estimated_monthly_revenue
13
+ ```
14
+
15
+ Node.js 22 or newer is required.
16
+
17
+ ## Sign in
18
+
19
+ ```
20
+ realytix login Sign in with OAuth in your browser. Pass --no-browser to print the link
21
+ (headless machines, SSH): open it anywhere, the terminal completes the login.
22
+ realytix whoami Plan, AI allowance used this month, credits, marketplaces (get_account).
23
+ realytix logout Revoke the session on the server and delete the local credentials.
24
+ ```
25
+
26
+ How it works: `login` registers the CLI with the server once, starts a loopback listener on
27
+ `http://127.0.0.1:<random port>/callback`, opens the authorization page (you confirm on
28
+ realytix.io), exchanges the returned code with PKCE and stores the tokens. Access tokens last one
29
+ hour and are refreshed transparently; the refresh token rotates on each refresh. There is no API
30
+ key to copy or leak. When a refresh is refused (session revoked from Account → Connected apps, or
31
+ after a long idle period) commands exit with code 3 and ask you to run `realytix login` again.
32
+
33
+ Files, all created with mode `0600`:
34
+
35
+ | File | Content |
36
+ |---|---|
37
+ | `~/.config/realytix/config.json` | server URL, OAuth client registration, discovery cache |
38
+ | `~/.config/realytix/credentials.json` | access and refresh tokens, expiry, your e-mail |
39
+
40
+ `$XDG_CONFIG_HOME/realytix` is used when set; `REALYTIX_CONFIG_DIR` overrides the directory
41
+ entirely (handy for CI or several accounts). `REALYTIX_MCP_URL` or `--server <url>` points the CLI
42
+ at another server (staging, local development); the URL used at login becomes the default.
43
+
44
+ ## Tools
45
+
46
+ Every tool of the server is a subcommand: the MCP name `get_product_history` is the command
47
+ `get-product-history` (the snake_case form is accepted too). Each input property is an option:
48
+
49
+ | Schema | Option form | Example |
50
+ |---|---|---|
51
+ | string, integer, boolean | `--asin B0…`, `--limit 50`, `--include-dossier` / `--no-include-dossier` | `--marketplace fr` |
52
+ | enum | choices shown in `--help` | `--status pass` |
53
+ | integer or word | either | `--days 90`, `--days all` |
54
+ | array of strings | repeat or comma-separate | `--asins B0…,B0…` `--asins B0…` |
55
+ | object, array of objects | `--<name>-json '<json>'` | `--products-json '[{"asin":"B0…"}]'` |
56
+ | whole input | `--input-json '{…}'` or `--input-file in.json` (`-` = stdin) | explicit options override |
57
+
58
+ Required options are enforced before any request is sent; schema defaults are shown in the help
59
+ and applied by the server.
60
+
61
+ ```
62
+ realytix tools Grouped list of the server's tools (bundled catalog when signed out).
63
+ realytix tools --json Machine-readable: name, command, group, access, cost, description, inputSchema.
64
+ realytix tool <name> Full description, options and JSON input schema of one tool.
65
+ realytix call <tool> --input-json '{…}'
66
+ Call any tool by name, including tools newer than this CLI.
67
+ realytix <command> --help Usage of one tool command.
68
+ realytix mcp-config Connection snippets for Claude Code, Cursor, Codex, Claude.ai, ChatGPT.
69
+ ```
70
+
71
+ Tool groups: Account · Products (facts, history, compare, listing snapshots) · Keywords (search
72
+ volume, reverse lookup, related ideas, interest trend) · Market Intel reports · Lists and research
73
+ dossiers · Pulse trackers · Launch Workspace · Realytix AI. Write tools and tools that spend credit
74
+ are marked in `realytix --help`; the cost is also returned with each result.
75
+
76
+ ## Output and exit codes
77
+
78
+ Default output is readable text: tables for lists of records, `key value` lines for objects. Add
79
+ `--json` to print the tool's `structuredContent` exactly (agents and `jq`), `--quiet` to print
80
+ nothing on success, `--no-color` to strip colors (`NO_COLOR` is honored).
81
+
82
+ | Exit | Meaning | stderr |
83
+ |---|---|---|
84
+ | 0 | success | |
85
+ | 1 | the tool returned an error | `<code>: <message>`, a hint when useful, the full `{"error":…}` JSON with `--json` |
86
+ | 2 | usage: unknown command or option, missing required option, invalid JSON or value | the problem and a pointer to `--help` |
87
+ | 3 | sign-in needed: no session, expired and not refreshable, or revoked | `Run \`realytix login\`.` |
88
+
89
+ Error codes you will meet: `plan_required` (the account is not on Pro+AI; the hint links to
90
+ https://realytix.io/pricing#plan-ai), `not_found`, `invalid_input`, `limit_reached`,
91
+ `no_ai_credit`, `daily_cap_reached`, `no_research_credit`, `rate_limited`,
92
+ `marketplace_unsupported`, `temporarily_unavailable`, `conflict`, `unauthorized` (exit 3).
93
+
94
+ ## Examples
95
+
96
+ ```sh
97
+ # Who are the newcomers on page 1 of a niche, and how do they compare
98
+ realytix compare-products --asins B0A…,B0B…,B0C… --marketplace com
99
+
100
+ # Twelve months of price and rank, only those two series, as JSON
101
+ realytix get-product-history --asin B0A… --days 365 --metrics price,rank --json
102
+
103
+ # Demand check for the main keyword and its variations
104
+ realytix get-keyword-volume --keywords "garlic press,garlic crusher,garlic mincer"
105
+ realytix get-keyword-trend --keyword "garlic press" --time-range past_5_years
106
+
107
+ # Workspace: find ids, then save products into a list at the right stage
108
+ realytix get-workspace-overview
109
+ realytix add-to-list --list-id 7c1f… --stage market_check \
110
+ --products-json '[{"asin":"B0A…","keyword":"garlic press"},{"asin":"B0B…"}]'
111
+ realytix update-research-check --list-id 7c1f… --asin B0A… --check m2_maturity --status pass \
112
+ --note "First listings date from 2019"
113
+
114
+ # Ask the AI mentor with a report as context (spends 1 AI credit)
115
+ realytix ask-realytix-ai --message "Is this niche worth entering?" \
116
+ --context-json '{"report_id":"3b9e…"}'
117
+ ```
118
+
119
+ ### Claude Code
120
+
121
+ Two ways to use Realytix from Claude Code:
122
+
123
+ 1. **MCP connector** (chat-style tool use):
124
+ `claude mcp add --transport http realytix https://mcp.realytix.io/mcp`, then `/mcp` to sign in.
125
+ 2. **CLI** (recommended when Claude Code works in a terminal and scripts things): install the CLI,
126
+ run `realytix login` once, and tell Claude Code in your `CLAUDE.md`:
127
+
128
+ ```markdown
129
+ ## Amazon product research
130
+ Use the `realytix` CLI (Pro+AI account already signed in). `realytix tools --json` lists the tools,
131
+ `realytix <command> --help` their options. Always pass `--json` and read structuredContent.
132
+ Exit 3 means run `realytix login`; exit 1 prints `<code>: <message>` on stderr.
133
+ Tools marked write or with a cost change my workspace or spend credit: ask before running them.
134
+ ```
135
+
136
+ ### Codex
137
+
138
+ Install the CLI and sign in once, then add to `AGENTS.md`:
139
+
140
+ ```markdown
141
+ ## Amazon product research
142
+ `realytix` is installed and signed in. Discover tools with `realytix tools --json`; call them with
143
+ `realytix <command> … --json`. Prefer read tools; confirm with me before `create-*`, `add-*`,
144
+ `move-*`, `update-*`, `remove-*`, `track-*`, `run-launch-tool` or `ask-realytix-ai` (they write
145
+ or spend credit).
146
+ ```
147
+
148
+ Codex can also use the MCP server directly: in `~/.codex/config.toml`
149
+
150
+ ```toml
151
+ [mcp_servers.realytix]
152
+ url = "https://mcp.realytix.io/mcp"
153
+ ```
154
+
155
+ `realytix mcp-config` prints these snippets with the server URL in use.
156
+
157
+ ## Development
158
+
159
+ ```sh
160
+ export PATH=~/.nvm/versions/node/v22.23.3/bin:$PATH
161
+ cd mcp/cli
162
+ bun install # npm works as well once installed
163
+ npm run gen # regenerate src/generated/commands.ts from ../contract/tools.json
164
+ npm run typecheck
165
+ npm test
166
+ npm run build # gen + tsc -> dist/
167
+ node dist/index.js --help
168
+ npm run lint:words # source-neutral wording check (node ../scripts/banned-words.mjs mcp/cli)
169
+ ```
170
+
171
+ `src/generated/commands.ts` is committed so the package builds without the contract file; the
172
+ test suite fails when it drifts from `mcp/contract/tools.json`. Publishing to npm is a separate,
173
+ explicit step (`npm version`, then `npm publish --access public` from `mcp/cli`); nothing here
174
+ publishes automatically. The npm account `realytix` uses a passkey for 2FA, so run the publish in a
175
+ real terminal (not a non-interactive shell): npm prints a link to approve it in the browser.
@@ -0,0 +1,76 @@
1
+ // Loopback HTTP server that receives the OAuth redirect during `realytix login`.
2
+ // Listens on 127.0.0.1 with a random port; answers /callback once and ignores the rest.
3
+ import { createServer } from 'node:http';
4
+ const PAGE = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>
5
+ <style>body{font-family:system-ui,sans-serif;background:#0b0f14;color:#e6edf3;display:grid;place-items:center;height:100vh;margin:0}
6
+ main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{color:#9aa4b2;margin:0}</style></head>
7
+ <body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;
8
+ export function startLoopbackServer(opts) {
9
+ const host = opts.host ?? '127.0.0.1';
10
+ const timeoutMs = opts.timeoutMs ?? 5 * 60_000;
11
+ let settle;
12
+ let outcome;
13
+ const deliver = (result) => {
14
+ if (outcome)
15
+ return;
16
+ outcome = result;
17
+ if (settle)
18
+ result.code !== undefined ? settle.resolve(result.code) : settle.reject(result.error);
19
+ };
20
+ const server = createServer((req, res) => {
21
+ const url = new URL(req.url ?? '/', `http://${host}`);
22
+ if (url.pathname !== '/callback') {
23
+ res.writeHead(404, { 'content-type': 'text/plain' }).end('Not found');
24
+ return;
25
+ }
26
+ const error = url.searchParams.get('error');
27
+ const code = url.searchParams.get('code');
28
+ const state = url.searchParams.get('state');
29
+ const expected = opts.expectedState();
30
+ if (error) {
31
+ const description = url.searchParams.get('error_description') ?? '';
32
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' }).end(PAGE('Sign-in was not completed', description || error));
33
+ deliver({ error: new Error(`Authorization refused: ${error}${description ? ` (${description})` : ''}`) });
34
+ return;
35
+ }
36
+ if (!code) {
37
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' }).end(PAGE('Missing code', 'The redirect did not carry an authorization code.'));
38
+ return;
39
+ }
40
+ if (expected && state !== expected) {
41
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' }).end(PAGE('State mismatch', 'This redirect does not belong to the running sign-in. Start again from the terminal.'));
42
+ deliver({ error: new Error('OAuth state mismatch: the redirect did not come from this login attempt.') });
43
+ return;
44
+ }
45
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(PAGE('Realytix CLI is signed in', 'You can close this tab and return to the terminal.'));
46
+ deliver({ code });
47
+ });
48
+ return new Promise((resolve, reject) => {
49
+ server.once('error', reject);
50
+ server.listen(opts.port ?? 0, host, () => {
51
+ const { port } = server.address();
52
+ const redirectUrl = new URL(`http://${host}:${port}/callback`);
53
+ const close = () => new Promise((done) => server.close(() => done()));
54
+ resolve({
55
+ port,
56
+ redirectUrl,
57
+ close,
58
+ waitForCode: () => new Promise((res, rej) => {
59
+ if (outcome)
60
+ return outcome.code !== undefined ? res(outcome.code) : rej(outcome.error);
61
+ const timer = setTimeout(() => deliver({ error: new Error(`No sign-in completed within ${Math.round(timeoutMs / 60_000)} minutes.`) }), timeoutMs);
62
+ settle = {
63
+ resolve: (c) => {
64
+ clearTimeout(timer);
65
+ res(c);
66
+ },
67
+ reject: (e) => {
68
+ clearTimeout(timer);
69
+ rej(e);
70
+ },
71
+ };
72
+ }),
73
+ });
74
+ });
75
+ });
76
+ }
@@ -0,0 +1,126 @@
1
+ // OAuthClientProvider backed by the config store.
2
+ // client registration + discovery cache -> config.json
3
+ // tokens -> credentials.json
4
+ // PKCE verifier + state -> memory of the login process only
5
+ // Outside `realytix login` the provider never opens a browser: when the SDK asks
6
+ // for a redirect (no tokens, or refresh refused) it throws AuthRequiredError -> exit 3.
7
+ import { randomBytes } from 'node:crypto';
8
+ import { AuthRequiredError } from '../errors.js';
9
+ export const SCOPES = 'research:read workspace:read workspace:write ai:run';
10
+ export const CLIENT_NAME = 'Realytix CLI';
11
+ export const CLIENT_URI = 'https://realytix.io';
12
+ /** Placeholder loopback redirect used for registration and for non-interactive runs. */
13
+ export const LOOPBACK_PLACEHOLDER = 'http://127.0.0.1/callback';
14
+ /** Refresh this many ms before the recorded expiry. */
15
+ export const EXPIRY_SKEW_MS = 30_000;
16
+ export class FileOAuthClientProvider {
17
+ store;
18
+ serverUrl;
19
+ version;
20
+ _redirectUrl;
21
+ onRedirect;
22
+ now;
23
+ verifier;
24
+ _state;
25
+ constructor(opts) {
26
+ this.store = opts.store;
27
+ this.serverUrl = opts.serverUrl;
28
+ this.version = opts.version;
29
+ this._redirectUrl = new URL(opts.redirectUrl ?? LOOPBACK_PLACEHOLDER);
30
+ this.onRedirect = opts.onRedirect;
31
+ this.now = opts.now ?? Date.now;
32
+ }
33
+ get redirectUrl() {
34
+ return this._redirectUrl;
35
+ }
36
+ get clientMetadata() {
37
+ return {
38
+ redirect_uris: [this._redirectUrl.toString()],
39
+ token_endpoint_auth_method: 'none',
40
+ grant_types: ['authorization_code', 'refresh_token'],
41
+ response_types: ['code'],
42
+ client_name: CLIENT_NAME,
43
+ client_uri: CLIENT_URI,
44
+ scope: SCOPES,
45
+ software_id: 'realytix-cli',
46
+ software_version: this.version,
47
+ };
48
+ }
49
+ state() {
50
+ this._state = randomBytes(16).toString('hex');
51
+ return this._state;
52
+ }
53
+ /** The `state` sent with the last authorization request (login verifies the callback against it). */
54
+ get expectedState() {
55
+ return this._state;
56
+ }
57
+ sameServer(record) {
58
+ if (!record)
59
+ return undefined;
60
+ return record.server_url === this.serverUrl ? record : undefined;
61
+ }
62
+ clientInformation() {
63
+ return this.sameServer(this.store.readConfig())?.client_information;
64
+ }
65
+ saveClientInformation(clientInformation) {
66
+ const current = this.sameServer(this.store.readConfig());
67
+ this.store.writeConfig({ version: 1, ...(current ?? {}), server_url: this.serverUrl, client_information: clientInformation });
68
+ }
69
+ tokens() {
70
+ return this.sameServer(this.store.readCredentials())?.tokens;
71
+ }
72
+ saveTokens(tokens) {
73
+ const current = this.sameServer(this.store.readCredentials());
74
+ const expires_at = typeof tokens.expires_in === 'number' ? this.now() + tokens.expires_in * 1000 : undefined;
75
+ this.store.writeCredentials({
76
+ version: 1,
77
+ server_url: this.serverUrl,
78
+ tokens,
79
+ expires_at,
80
+ email: current?.email,
81
+ saved_at: new Date(this.now()).toISOString(),
82
+ });
83
+ }
84
+ /** True when the stored access token is past (or within EXPIRY_SKEW_MS of) its recorded expiry. */
85
+ accessTokenExpired() {
86
+ const creds = this.sameServer(this.store.readCredentials());
87
+ if (!creds?.expires_at)
88
+ return false;
89
+ return this.now() + EXPIRY_SKEW_MS >= creds.expires_at;
90
+ }
91
+ async redirectToAuthorization(authorizationUrl) {
92
+ if (!this.onRedirect)
93
+ throw new AuthRequiredError('Your session has ended or no session is saved.');
94
+ await this.onRedirect(authorizationUrl);
95
+ }
96
+ saveCodeVerifier(codeVerifier) {
97
+ this.verifier = codeVerifier;
98
+ }
99
+ codeVerifier() {
100
+ if (!this.verifier)
101
+ throw new Error('No PKCE code verifier in this login session.');
102
+ return this.verifier;
103
+ }
104
+ invalidateCredentials(scope) {
105
+ if (scope === 'all' || scope === 'tokens')
106
+ this.store.deleteCredentials();
107
+ if (scope === 'all' || scope === 'client')
108
+ this.store.clearClient();
109
+ if (scope === 'all' || scope === 'verifier')
110
+ this.verifier = undefined;
111
+ if (scope === 'all' || scope === 'discovery') {
112
+ const current = this.sameServer(this.store.readConfig());
113
+ if (current?.discovery) {
114
+ const { discovery: _d, ...rest } = current;
115
+ this.store.writeConfig(rest);
116
+ }
117
+ }
118
+ }
119
+ saveDiscoveryState(state) {
120
+ const current = this.sameServer(this.store.readConfig());
121
+ this.store.writeConfig({ version: 1, ...(current ?? {}), server_url: this.serverUrl, discovery: state });
122
+ }
123
+ discoveryState() {
124
+ return this.sameServer(this.store.readConfig())?.discovery;
125
+ }
126
+ }
@@ -0,0 +1,4 @@
1
+ // Shape of the generated command catalog (src/generated/commands.ts).
2
+ // The generator (scripts/gen-lib.mts) derives one CLI option per input-schema
3
+ // property of every tool in mcp/contract/tools.json.
4
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,157 @@
1
+ // Program assembly: global options, utility commands, one subcommand per contract tool.
2
+ // `run(argv, deps)` returns the exit code; index.ts wires the real dependencies.
3
+ import { Command, CommanderError } from 'commander';
4
+ import pc from 'picocolors';
5
+ import { CATALOG } from './generated/commands.js';
6
+ import { resolveServerUrl } from './config.js';
7
+ import { CliError, EXIT_OK, EXIT_TOOL_ERROR, EXIT_USAGE, ToolCallError } from './errors.js';
8
+ import { addInputOptions, buildInput, buildOption } from './options.js';
9
+ import { runTool } from './run-tool.js';
10
+ import { login, logout, whoami } from './commands/account.js';
11
+ import { call, costLabel, tool, tools, wrap } from './commands/catalog.js';
12
+ import { mcpConfig } from './commands/mcp-config.js';
13
+ export const RESERVED_FLAGS = ['json', 'quiet', 'server', 'color', 'input-json', 'input-file', 'help', 'version'];
14
+ function makeCtx(deps, cmd) {
15
+ const g = cmd.optsWithGlobals();
16
+ const stored = deps.store.readConfig()?.server_url;
17
+ const color = g.color !== false && !deps.env.NO_COLOR && (deps.env.FORCE_COLOR !== undefined || !!process.stdout.isTTY);
18
+ return {
19
+ deps,
20
+ json: !!g.json,
21
+ quiet: !!g.quiet,
22
+ server: g.server,
23
+ color,
24
+ serverUrl: resolveServerUrl(g.server, deps.env, stored),
25
+ };
26
+ }
27
+ function registerToolCommand(program, deps, t) {
28
+ const cmd = program
29
+ .command(t.command, { hidden: true })
30
+ .summary(t.title)
31
+ .description(`${t.description}\n\nAccess: ${t.access} · Cost: ${costLabel(t.cost)} · MCP tool: ${t.name}`);
32
+ if (t.name !== t.command)
33
+ cmd.alias(t.name);
34
+ for (const spec of t.options)
35
+ for (const opt of buildOption(spec))
36
+ cmd.addOption(opt);
37
+ addInputOptions(cmd);
38
+ cmd.action(async (opts, self) => {
39
+ const ctx = makeCtx(deps, self);
40
+ const input = buildInput(t, opts);
41
+ await runTool(ctx, t.name, input);
42
+ });
43
+ }
44
+ function toolGroupsHelp() {
45
+ const width = Math.max(...CATALOG.tools.map((t) => t.command.length));
46
+ const lines = ['Tool commands (one per MCP tool; `realytix tool <name>` shows details):', ''];
47
+ for (const g of CATALOG.groups) {
48
+ const inGroup = CATALOG.tools.filter((t) => t.group === g.key);
49
+ if (!inGroup.length)
50
+ continue;
51
+ lines.push(` ${g.title}`);
52
+ for (const t of inGroup) {
53
+ const mark = t.access === 'write' ? '*' : ' ';
54
+ const cost = t.cost.kind !== 'none' ? ` [${costLabel(t.cost)}]` : '';
55
+ lines.push(` ${t.command.padEnd(width)} ${mark} ${t.title}${cost}`);
56
+ }
57
+ lines.push('');
58
+ }
59
+ lines.push(' * = writes to your workspace or spends credit. Every command accepts --json, --quiet, --input-json.');
60
+ lines.push(' Exit codes: 0 ok · 1 tool error · 2 usage · 3 sign-in needed (run `realytix login`).');
61
+ return lines.join('\n');
62
+ }
63
+ export function createProgram(deps) {
64
+ const program = new Command('realytix');
65
+ program
66
+ .description(`${CATALOG.server.description}\nCommand-line client of the Realytix MCP server; sign in once with \`realytix login\`.`)
67
+ .version(deps.version, '-V, --version', 'Print the CLI version.')
68
+ .option('--json', 'Print the tool result as JSON (structuredContent), for scripts and agents.')
69
+ .option('-q, --quiet', 'Print nothing on success; rely on the exit code.')
70
+ .option('--server <url>', 'MCP server URL (default: $REALYTIX_MCP_URL, then the URL used at login, then https://mcp.realytix.io/mcp).')
71
+ .option('--no-color', 'Disable colors.')
72
+ .helpOption('-h, --help', 'Show help.')
73
+ .showHelpAfterError('(run with --help for usage)')
74
+ .showSuggestionAfterError(true)
75
+ .enablePositionalOptions(false)
76
+ .allowExcessArguments(false)
77
+ .configureOutput({ writeOut: (s) => deps.stdout(s.replace(/\n$/, '')), writeErr: (s) => deps.stderr(s.replace(/\n$/, '')) })
78
+ .configureHelp({ sortSubcommands: false, helpWidth: 100 })
79
+ .exitOverride();
80
+ program.addHelpText('after', `\n${toolGroupsHelp()}`);
81
+ program
82
+ .command('login')
83
+ .description('Sign in to Realytix in your browser (OAuth, loopback redirect) and save the session.')
84
+ .option('--no-browser', 'Print the sign-in link instead of opening a browser.')
85
+ .action(async (opts, self) => {
86
+ await login(makeCtx(deps, self), { browser: opts.browser });
87
+ });
88
+ program
89
+ .command('logout')
90
+ .description('Revoke the saved session on the server and delete the local credentials.')
91
+ .action(async (_opts, self) => {
92
+ await logout(makeCtx(deps, self));
93
+ });
94
+ program
95
+ .command('whoami')
96
+ .description('Show the signed-in account: plan, AI allowance, credits, marketplaces (get_account).')
97
+ .action(async (_opts, self) => {
98
+ await whoami(makeCtx(deps, self));
99
+ });
100
+ program
101
+ .command('tools')
102
+ .description('List the server\'s tools, grouped. --json gives a machine-readable catalog.')
103
+ .action(async (_opts, self) => {
104
+ await tools(makeCtx(deps, self));
105
+ });
106
+ program
107
+ .command('tool <name>')
108
+ .description('Full description, options and input schema of one tool (name or command form).')
109
+ .action(async (name, _opts, self) => {
110
+ await tool(makeCtx(deps, self), name);
111
+ });
112
+ addInputOptions(program.command('call <tool>').description('Call any tool by name with a JSON input object.')).action(async (toolName, opts, self) => {
113
+ await call(makeCtx(deps, self), toolName, opts);
114
+ });
115
+ program
116
+ .command('mcp-config')
117
+ .description('Print ready-to-paste MCP connection snippets for Claude Code, Cursor, Codex, Claude.ai and ChatGPT.')
118
+ .action(async (_opts, self) => {
119
+ mcpConfig(makeCtx(deps, self));
120
+ });
121
+ for (const t of CATALOG.tools)
122
+ registerToolCommand(program, deps, t);
123
+ return program;
124
+ }
125
+ /** Parse and execute; never throws, returns the process exit code. */
126
+ export async function run(argv, deps) {
127
+ const program = createProgram(deps);
128
+ const wantsJson = argv.includes('--json');
129
+ try {
130
+ await program.parseAsync(argv, { from: 'user' });
131
+ return EXIT_OK;
132
+ }
133
+ catch (err) {
134
+ if (err instanceof CommanderError) {
135
+ if (err.exitCode === 0)
136
+ return EXIT_OK; // --help, --version
137
+ return EXIT_USAGE;
138
+ }
139
+ if (err instanceof ToolCallError) {
140
+ deps.stderr(`${err.payload.code}: ${err.payload.message}`);
141
+ if (err.hint)
142
+ deps.stderr(err.hint);
143
+ if (wantsJson)
144
+ deps.stderr(JSON.stringify({ error: { ...err.payload, tool: err.tool } }, null, 2));
145
+ return err.exitCode;
146
+ }
147
+ if (err instanceof CliError) {
148
+ deps.stderr(`${pc.red('error')}: ${err.message}`);
149
+ if (err.hint)
150
+ deps.stderr(err.hint);
151
+ return err.exitCode;
152
+ }
153
+ const message = err instanceof Error ? err.message : String(err);
154
+ deps.stderr(`${pc.red('error')}: ${wrap(message, 100)}`);
155
+ return EXIT_TOOL_ERROR;
156
+ }
157
+ }
package/dist/client.js ADDED
@@ -0,0 +1,70 @@
1
+ // MCP client wiring: Streamable HTTP transport + file-backed OAuth provider.
2
+ // Token refresh is transparent: the SDK refreshes on 401, and we refresh ahead of
3
+ // a recorded expiry. When refresh fails the provider raises AuthRequiredError (exit 3).
4
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
6
+ import { auth, UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
7
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
8
+ import { FileOAuthClientProvider } from './auth/provider.js';
9
+ import { AuthRequiredError, CliError, UsageError } from './errors.js';
10
+ /** Wrap an SDK Client so tests can substitute one connected over InMemoryTransport. */
11
+ export function wrapClient(client) {
12
+ return {
13
+ async listTools() {
14
+ const tools = [];
15
+ let cursor;
16
+ do {
17
+ const page = await mapAuthErrors(() => client.listTools(cursor ? { cursor } : undefined));
18
+ tools.push(...page.tools);
19
+ cursor = page.nextCursor;
20
+ } while (cursor);
21
+ return tools;
22
+ },
23
+ async callTool(name, args) {
24
+ return (await mapAuthErrors(() => client.callTool({ name, arguments: args })));
25
+ },
26
+ async close() {
27
+ await client.close().catch(() => undefined);
28
+ },
29
+ };
30
+ }
31
+ export async function connect(opts) {
32
+ const provider = opts.provider ?? new FileOAuthClientProvider({ store: opts.store, serverUrl: opts.serverUrl, version: opts.version });
33
+ if (!provider.tokens())
34
+ throw new AuthRequiredError('Not signed in.');
35
+ if (provider.accessTokenExpired()) {
36
+ // Refresh ahead of time so the first request already carries a valid token.
37
+ await mapAuthErrors(async () => {
38
+ const result = await auth(provider, { serverUrl: opts.serverUrl });
39
+ if (result !== 'AUTHORIZED')
40
+ throw new AuthRequiredError('Your session has ended.');
41
+ });
42
+ }
43
+ const client = new Client({ name: 'realytix-cli', version: opts.version });
44
+ const transport = new StreamableHTTPClientTransport(new URL(opts.serverUrl), { authProvider: provider });
45
+ await mapAuthErrors(() => client.connect(transport));
46
+ return wrapClient(client);
47
+ }
48
+ async function mapAuthErrors(fn) {
49
+ try {
50
+ return await fn();
51
+ }
52
+ catch (err) {
53
+ if (err instanceof CliError)
54
+ throw err;
55
+ if (err instanceof UnauthorizedError)
56
+ throw new AuthRequiredError('Your session has ended or was revoked.');
57
+ if (err instanceof McpError && err.code === ErrorCode.InvalidParams) {
58
+ throw new UsageError(`invalid_input: ${err.message.replace(/^MCP error -?\d+:\s*/, '')}`);
59
+ }
60
+ if (err instanceof Error && /fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(err.message)) {
61
+ throw new CliError(`Cannot reach the Realytix MCP server (${err.message}).`, 1, 'Check your connection, or REALYTIX_MCP_URL if you set it.');
62
+ }
63
+ throw err;
64
+ }
65
+ }
66
+ /** Text content of a tool result, joined. */
67
+ export function textOf(result) {
68
+ const parts = (result.content ?? []).filter((c) => c.type === 'text').map((c) => c.text);
69
+ return parts.length ? parts.join('\n') : undefined;
70
+ }