@realytix/cli 0.0.0-stage → 0.1.0

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,146 @@
1
+ // login · logout · whoami
2
+ import { discoverOAuthServerInfo } from '@modelcontextprotocol/sdk/client/auth.js';
3
+ import pc from 'picocolors';
4
+ import { FileOAuthClientProvider } from '../auth/provider.js';
5
+ import { AuthRequiredError, CliError, EXIT_AUTH } from '../errors.js';
6
+ import { callTool, emitOutcome, findEmail } from '../run-tool.js';
7
+ export async function login(ctx, opts) {
8
+ const { deps, serverUrl } = ctx;
9
+ const say = (s) => {
10
+ if (!ctx.quiet)
11
+ deps.stderr(s);
12
+ };
13
+ // Make this server the default for later commands.
14
+ deps.store.updateConfig({ server_url: serverUrl });
15
+ let provider;
16
+ const loopback = await deps.startLoopback({ expectedState: () => provider?.expectedState });
17
+ const wantBrowser = opts.browser && deps.canOpenBrowser;
18
+ provider = new FileOAuthClientProvider({
19
+ store: deps.store,
20
+ serverUrl,
21
+ version: deps.version,
22
+ redirectUrl: loopback.redirectUrl,
23
+ now: deps.now,
24
+ onRedirect: async (url) => {
25
+ let opened = false;
26
+ if (wantBrowser)
27
+ opened = await deps.openBrowser(url.toString()).catch(() => false);
28
+ if (opened)
29
+ say(`Opening your browser to sign in to Realytix. If nothing happens, open:\n ${url}`);
30
+ else
31
+ say(`Open this link to sign in to Realytix:\n ${url}`);
32
+ say('Waiting for the sign-in to complete…');
33
+ },
34
+ });
35
+ let refreshedOnly = false;
36
+ try {
37
+ const first = await deps.auth(provider, { serverUrl });
38
+ if (first === 'AUTHORIZED') {
39
+ refreshedOnly = true;
40
+ }
41
+ else {
42
+ const code = await loopback.waitForCode();
43
+ const second = await deps.auth(provider, { serverUrl, authorizationCode: code });
44
+ if (second !== 'AUTHORIZED')
45
+ throw new CliError('Sign-in did not complete.', EXIT_AUTH);
46
+ }
47
+ }
48
+ catch (err) {
49
+ if (err instanceof CliError)
50
+ throw err;
51
+ throw new CliError(`Sign-in failed: ${err.message}`, EXIT_AUTH);
52
+ }
53
+ finally {
54
+ await loopback.close();
55
+ }
56
+ // Confirm the identity with get_account and remember the e-mail.
57
+ const client = await deps.connect({ serverUrl, store: deps.store, version: deps.version, provider });
58
+ let account;
59
+ try {
60
+ account = await client.callTool('get_account', {});
61
+ }
62
+ finally {
63
+ await client.close();
64
+ }
65
+ const structured = account.structuredContent;
66
+ const email = findEmail(structured);
67
+ const creds = deps.store.readCredentials();
68
+ if (creds && email)
69
+ deps.store.writeCredentials({ ...creds, email });
70
+ if (ctx.json) {
71
+ deps.stdout(JSON.stringify({ signed_in: true, email: email ?? null, server: serverUrl, refreshed_existing_session: refreshedOnly, account: structured ?? null }, null, 2));
72
+ return;
73
+ }
74
+ if (ctx.quiet)
75
+ return;
76
+ const who = email ? `Signed in as ${pc.bold(email)}` : 'Signed in';
77
+ deps.stdout(refreshedOnly ? `${who} (existing session refreshed; run \`realytix logout\` to switch accounts).` : `${who}.`);
78
+ }
79
+ export async function logout(ctx) {
80
+ const { deps, serverUrl } = ctx;
81
+ const creds = deps.store.readCredentials();
82
+ if (!creds) {
83
+ if (!ctx.quiet)
84
+ deps.stdout(ctx.json ? JSON.stringify({ signed_out: false, reason: 'not_signed_in' }) : 'Not signed in.');
85
+ return;
86
+ }
87
+ let revoked = false;
88
+ const refresh = creds.tokens.refresh_token;
89
+ if (refresh) {
90
+ try {
91
+ const config = deps.store.readConfig();
92
+ let endpoint = revocationEndpoint(config?.discovery?.authorizationServerMetadata);
93
+ let issuer = config?.discovery?.authorizationServerUrl;
94
+ if (!endpoint) {
95
+ const info = await discoverOAuthServerInfo(serverUrl, { fetchFn: deps.fetch });
96
+ endpoint = revocationEndpoint(info.authorizationServerMetadata);
97
+ issuer = info.authorizationServerUrl;
98
+ }
99
+ if (!endpoint && issuer)
100
+ endpoint = new URL('/revoke', issuer).toString();
101
+ if (endpoint) {
102
+ const body = new URLSearchParams({ token: refresh, token_type_hint: 'refresh_token' });
103
+ const clientId = config?.client_information?.client_id;
104
+ if (clientId)
105
+ body.set('client_id', clientId);
106
+ const res = await deps.fetch(endpoint, {
107
+ method: 'POST',
108
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
109
+ body,
110
+ signal: AbortSignal.timeout(8_000),
111
+ });
112
+ revoked = res.ok;
113
+ }
114
+ }
115
+ catch {
116
+ revoked = false; // best effort: the local session is removed regardless
117
+ }
118
+ }
119
+ deps.store.deleteCredentials();
120
+ if (ctx.json) {
121
+ deps.stdout(JSON.stringify({ signed_out: true, revoked, email: creds.email ?? null }, null, 2));
122
+ return;
123
+ }
124
+ if (ctx.quiet)
125
+ return;
126
+ deps.stdout(revoked ? 'Signed out. The connection was revoked on the server.' : 'Signed out locally. The server could not be reached to revoke the connection; you can also remove it from Account → Connected apps on realytix.io.');
127
+ }
128
+ /** RFC 7009 endpoint; OpenID-flavoured metadata types omit it, so read it loosely. */
129
+ function revocationEndpoint(metadata) {
130
+ const v = metadata?.revocation_endpoint;
131
+ return typeof v === 'string' ? v : undefined;
132
+ }
133
+ export async function whoami(ctx) {
134
+ const creds = ctx.deps.store.readCredentials();
135
+ if (!creds)
136
+ throw new AuthRequiredError('Not signed in.');
137
+ const outcome = await callTool(ctx, 'get_account', {});
138
+ if (ctx.json || ctx.quiet) {
139
+ emitOutcome(ctx, outcome);
140
+ return;
141
+ }
142
+ const email = findEmail(outcome.structured) ?? creds.email;
143
+ if (email)
144
+ ctx.deps.stdout(`Signed in as ${pc.bold(email)} (${ctx.serverUrl})`);
145
+ emitOutcome(ctx, outcome);
146
+ }
@@ -0,0 +1,180 @@
1
+ import pc from 'picocolors';
2
+ import { AuthRequiredError, CliError, UsageError } from '../errors.js';
3
+ import { CATALOG } from '../generated/commands.js';
4
+ import { buildInput, helpText, readInputFile } from '../options.js';
5
+ import { runTool } from '../run-tool.js';
6
+ const paint = (on, fn, s) => (on ? fn(s) : s);
7
+ const toCommand = (name) => name.replace(/_/g, '-');
8
+ export function findCatalogTool(nameOrCommand) {
9
+ const key = nameOrCommand.trim();
10
+ return CATALOG.tools.find((t) => t.name === key || t.command === key || t.command === toCommand(key));
11
+ }
12
+ function groupTitle(key) {
13
+ return CATALOG.groups.find((g) => g.key === key)?.title ?? 'Other tools';
14
+ }
15
+ function fromCatalog(t) {
16
+ return { name: t.name, command: t.command, group: t.group, groupTitle: groupTitle(t.group), title: t.title, access: t.access, cost: t.cost, description: t.description, inputSchema: t.inputSchema, live: false };
17
+ }
18
+ function fromServer(t) {
19
+ const local = findCatalogTool(t.name);
20
+ const access = local?.access ?? (t.annotations?.readOnlyHint ? 'read' : undefined);
21
+ return {
22
+ name: t.name,
23
+ command: local?.command ?? toCommand(t.name),
24
+ group: local?.group ?? 'other',
25
+ groupTitle: groupTitle(local?.group ?? 'other'),
26
+ title: t.title ?? local?.title ?? t.name,
27
+ access,
28
+ cost: local?.cost,
29
+ description: t.description ?? local?.description ?? '',
30
+ inputSchema: t.inputSchema,
31
+ live: true,
32
+ };
33
+ }
34
+ /** Live tools from the server, or the bundled catalog when not signed in. */
35
+ export async function listTools(ctx) {
36
+ try {
37
+ const client = await ctx.deps.connect({ serverUrl: ctx.serverUrl, store: ctx.deps.store, version: ctx.deps.version });
38
+ try {
39
+ const tools = await client.listTools();
40
+ return { tools: tools.map(fromServer), live: true };
41
+ }
42
+ finally {
43
+ await client.close();
44
+ }
45
+ }
46
+ catch (err) {
47
+ if (err instanceof AuthRequiredError) {
48
+ if (!ctx.quiet)
49
+ ctx.deps.stderr('Showing the bundled tool catalog. Run `realytix login` to read the live definitions from the server.');
50
+ return { tools: CATALOG.tools.map(fromCatalog), live: false };
51
+ }
52
+ throw err;
53
+ }
54
+ }
55
+ export function costLabel(cost) {
56
+ if (!cost || cost.kind === 'none')
57
+ return 'no cost';
58
+ if (cost.kind === 'research_credit')
59
+ return `${cost.amount ?? 1} keyword-research credit`;
60
+ return `${cost.amount ?? ''} AI credit${cost.amount === 1 ? '' : 's'}`.trim();
61
+ }
62
+ function firstSentence(text, max = 88) {
63
+ const s = text.split(/(?<=\.)\s/)[0] ?? text;
64
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
65
+ }
66
+ export async function tools(ctx) {
67
+ const { tools, live } = await listTools(ctx);
68
+ if (ctx.json) {
69
+ ctx.deps.stdout(JSON.stringify({ server: ctx.serverUrl, live, tools: tools.map(({ groupTitle: _g, live: _l, ...t }) => t) }, null, 2));
70
+ return;
71
+ }
72
+ if (ctx.quiet)
73
+ return;
74
+ const order = [...CATALOG.groups.map((g) => g.key), 'other'];
75
+ const lines = [`Realytix MCP tools (${tools.length})${live ? '' : ' from the bundled catalog'}`, ''];
76
+ const width = Math.max(...tools.map((t) => t.command.length));
77
+ for (const key of order) {
78
+ const inGroup = tools.filter((t) => t.group === key);
79
+ if (!inGroup.length)
80
+ continue;
81
+ lines.push(paint(ctx.color, pc.bold, groupTitle(key)));
82
+ for (const t of inGroup) {
83
+ const badge = t.access === 'write' ? paint(ctx.color, pc.yellow, 'write') : paint(ctx.color, pc.dim, 'read ');
84
+ const cost = t.cost && t.cost.kind !== 'none' ? ` ${paint(ctx.color, pc.cyan, `[${costLabel(t.cost)}]`)}` : '';
85
+ lines.push(` ${t.command.padEnd(width)} ${badge} ${firstSentence(t.description)}${cost}`);
86
+ }
87
+ lines.push('');
88
+ }
89
+ lines.push('Run `realytix tool <name>` for a tool\'s full description and options, `realytix <command> --help` for its usage.');
90
+ ctx.deps.stdout(lines.join('\n'));
91
+ }
92
+ export async function tool(ctx, nameOrCommand) {
93
+ const local = findCatalogTool(nameOrCommand);
94
+ const { tools } = await listTools(ctx);
95
+ const listed = tools.find((t) => t.name === nameOrCommand || t.command === nameOrCommand || t.command === toCommand(nameOrCommand)) ?? (local ? fromCatalog(local) : undefined);
96
+ if (!listed)
97
+ throw new UsageError(`Unknown tool "${nameOrCommand}".`, 'Run `realytix tools` to list them.');
98
+ if (ctx.json) {
99
+ ctx.deps.stdout(JSON.stringify({ ...listed, options: local?.options ?? [] }, null, 2));
100
+ return;
101
+ }
102
+ if (ctx.quiet)
103
+ return;
104
+ const b = (s) => paint(ctx.color, pc.bold, s);
105
+ const dim = (s) => paint(ctx.color, pc.dim, s);
106
+ const lines = [];
107
+ lines.push(`${b(listed.name)} ${dim(`realytix ${listed.command}`)}`);
108
+ lines.push(`${listed.title} · ${listed.groupTitle} · ${listed.access ?? 'read'} · ${costLabel(listed.cost)}`);
109
+ lines.push('');
110
+ lines.push(wrap(listed.description, 100));
111
+ lines.push('');
112
+ if (local && local.options.length) {
113
+ lines.push(b('Options'));
114
+ const width = Math.max(...local.options.map((o) => o.flag.length + 2));
115
+ for (const o of local.options) {
116
+ const flag = o.kind === 'boolean' ? `--${o.flag}` : `--${o.flag} <${o.kind === 'json' ? 'json' : o.kind === 'integer' || o.kind === 'number' ? 'n' : 'value'}>`;
117
+ lines.push(` ${flag.padEnd(width + 8)} ${helpText(o)}`);
118
+ }
119
+ lines.push(` ${'--input-json <json>'.padEnd(width + 8)} Whole input as JSON; explicit options override its keys.`);
120
+ lines.push('');
121
+ }
122
+ else if (local) {
123
+ lines.push(dim('This tool takes no input.'));
124
+ lines.push('');
125
+ }
126
+ lines.push(b('Input schema'));
127
+ lines.push(JSON.stringify(listed.inputSchema, null, 2));
128
+ ctx.deps.stdout(lines.join('\n'));
129
+ }
130
+ export async function call(ctx, toolName, opts) {
131
+ const local = findCatalogTool(toolName);
132
+ const name = local?.name ?? toolName.replace(/-/g, '_');
133
+ let input;
134
+ if (local) {
135
+ input = buildInput(local, { inputJson: opts.inputJson, inputFile: opts.inputFile });
136
+ }
137
+ else {
138
+ input = {};
139
+ const layers = [];
140
+ if (opts.inputFile)
141
+ layers.push(readInputFile(opts.inputFile));
142
+ if (opts.inputJson) {
143
+ try {
144
+ layers.push(JSON.parse(opts.inputJson));
145
+ }
146
+ catch (err) {
147
+ throw new UsageError(`--input-json is not valid JSON: ${err.message}`);
148
+ }
149
+ }
150
+ for (const layer of layers) {
151
+ if (!layer || typeof layer !== 'object' || Array.isArray(layer))
152
+ throw new UsageError('The JSON input must be an object.');
153
+ Object.assign(input, layer);
154
+ }
155
+ }
156
+ try {
157
+ await runTool(ctx, name, input);
158
+ }
159
+ catch (err) {
160
+ if (err instanceof CliError)
161
+ throw err;
162
+ throw err;
163
+ }
164
+ }
165
+ export function wrap(text, width) {
166
+ const words = text.split(/\s+/);
167
+ const lines = [];
168
+ let line = '';
169
+ for (const w of words) {
170
+ if ((line + ' ' + w).trim().length > width) {
171
+ lines.push(line.trim());
172
+ line = w;
173
+ }
174
+ else
175
+ line = `${line} ${w}`;
176
+ }
177
+ if (line.trim())
178
+ lines.push(line.trim());
179
+ return lines.join('\n');
180
+ }
@@ -0,0 +1,49 @@
1
+ // mcp-config: ready-to-paste connection snippets for the common AI clients.
2
+ import pc from 'picocolors';
3
+ export function mcpConfigSnippets(serverUrl) {
4
+ const cursorJson = JSON.stringify({ mcpServers: { realytix: { url: serverUrl } } }, null, 2);
5
+ return {
6
+ server_url: serverUrl,
7
+ claude_code: `claude mcp add --transport http realytix ${serverUrl}`,
8
+ claude_code_cli: 'npm i -g @realytix/cli && realytix login',
9
+ cursor: { file: '~/.cursor/mcp.json (or .cursor/mcp.json in a project)', json: cursorJson },
10
+ codex: { file: '~/.codex/config.toml', toml: `[mcp_servers.realytix]\nurl = "${serverUrl}"` },
11
+ claude_ai: { where: 'claude.ai → Settings → Connectors → Add custom connector', url: serverUrl },
12
+ chatgpt: { where: 'ChatGPT → Settings → Connectors → Create (developer mode)', url: serverUrl },
13
+ };
14
+ }
15
+ export function mcpConfig(ctx) {
16
+ const s = mcpConfigSnippets(ctx.serverUrl);
17
+ if (ctx.json) {
18
+ ctx.deps.stdout(JSON.stringify(s, null, 2));
19
+ return;
20
+ }
21
+ if (ctx.quiet)
22
+ return;
23
+ const b = (t) => (ctx.color ? pc.bold(t) : t);
24
+ const dim = (t) => (ctx.color ? pc.dim(t) : t);
25
+ const out = [
26
+ `Realytix MCP server: ${s.server_url} ${dim('(Pro+AI plan, OAuth sign-in in the browser, no API key)')}`,
27
+ '',
28
+ b('Claude Code (MCP)'),
29
+ ` ${s.claude_code}`,
30
+ ` ${dim('Then run /mcp inside Claude Code to sign in.')}`,
31
+ '',
32
+ b('Claude Code or Codex (CLI, recommended for coding agents)'),
33
+ ` ${s.claude_code_cli}`,
34
+ ` ${dim('Agents then call `realytix <tool> --json`; `realytix tools --json` lists the tools.')}`,
35
+ '',
36
+ b(`Cursor ${dim(s.cursor.file)}`),
37
+ ...s.cursor.json.split('\n').map((l) => ` ${l}`),
38
+ '',
39
+ b(`Codex (MCP) ${dim(s.codex.file)}`),
40
+ ...s.codex.toml.split('\n').map((l) => ` ${l}`),
41
+ '',
42
+ b('Claude.ai'),
43
+ ` ${s.claude_ai.where}: ${s.claude_ai.url}`,
44
+ '',
45
+ b('ChatGPT'),
46
+ ` ${s.chatgpt.where}: ${s.chatgpt.url}`,
47
+ ];
48
+ ctx.deps.stdout(out.join('\n'));
49
+ }
package/dist/config.js ADDED
@@ -0,0 +1,105 @@
1
+ // Where the CLI keeps its state and how it is written.
2
+ // <config dir>/config.json server URL, OAuth client registration, cached discovery (0600)
3
+ // <config dir>/credentials.json OAuth tokens (0600)
4
+ // <config dir> = $REALYTIX_CONFIG_DIR, else $XDG_CONFIG_HOME/realytix, else ~/.config/realytix.
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+ export const DEFAULT_SERVER_URL = 'https://mcp.realytix.io/mcp';
9
+ export function configDir(env = process.env) {
10
+ if (env.REALYTIX_CONFIG_DIR)
11
+ return env.REALYTIX_CONFIG_DIR;
12
+ if (env.XDG_CONFIG_HOME)
13
+ return join(env.XDG_CONFIG_HOME, 'realytix');
14
+ return join(env.HOME || homedir(), '.config', 'realytix');
15
+ }
16
+ export function resolveServerUrl(explicit, env = process.env, stored) {
17
+ const raw = explicit || env.REALYTIX_MCP_URL || stored || DEFAULT_SERVER_URL;
18
+ const url = new URL(raw);
19
+ // Accept the server origin alone (https://mcp.realytix.io) as well as the full /mcp endpoint.
20
+ if (url.pathname === '/' || url.pathname === '')
21
+ url.pathname = '/mcp';
22
+ return url.toString().replace(/\/$/, '');
23
+ }
24
+ export class ConfigStore {
25
+ dir;
26
+ configPath;
27
+ credentialsPath;
28
+ constructor(dir) {
29
+ this.dir = dir;
30
+ this.configPath = join(dir, 'config.json');
31
+ this.credentialsPath = join(dir, 'credentials.json');
32
+ }
33
+ static fromEnv(env = process.env) {
34
+ return new ConfigStore(configDir(env));
35
+ }
36
+ readConfig() {
37
+ return readJson(this.configPath);
38
+ }
39
+ writeConfig(config) {
40
+ writePrivateJson(this.configPath, config);
41
+ }
42
+ updateConfig(patch) {
43
+ const current = this.readConfig();
44
+ const next = { version: 1, ...(current ?? {}), ...patch };
45
+ this.writeConfig(next);
46
+ return next;
47
+ }
48
+ readCredentials() {
49
+ tightenMode(this.credentialsPath);
50
+ return readJson(this.credentialsPath);
51
+ }
52
+ writeCredentials(creds) {
53
+ writePrivateJson(this.credentialsPath, creds);
54
+ }
55
+ deleteCredentials() {
56
+ if (!existsSync(this.credentialsPath))
57
+ return false;
58
+ rmSync(this.credentialsPath, { force: true });
59
+ return true;
60
+ }
61
+ /** Forget the client registration and discovery cache (keeps the server URL). */
62
+ clearClient() {
63
+ const current = this.readConfig();
64
+ if (!current)
65
+ return;
66
+ const { client_information: _c, discovery: _d, ...rest } = current;
67
+ this.writeConfig({ ...rest, version: 1 });
68
+ }
69
+ }
70
+ /** Credentials written by hand or copied over keep their secrets: force 0600 on read. */
71
+ function tightenMode(path) {
72
+ try {
73
+ if (existsSync(path) && (statSync(path).mode & 0o077) !== 0)
74
+ chmodSync(path, 0o600);
75
+ }
76
+ catch {
77
+ /* best effort */
78
+ }
79
+ }
80
+ function readJson(path) {
81
+ if (!existsSync(path))
82
+ return undefined;
83
+ try {
84
+ return JSON.parse(readFileSync(path, 'utf8'));
85
+ }
86
+ catch {
87
+ return undefined;
88
+ }
89
+ }
90
+ /** Write JSON atomically with mode 0600 inside a 0700 directory. */
91
+ export function writePrivateJson(path, value) {
92
+ const dir = dirname(path);
93
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
94
+ try {
95
+ if ((statSync(dir).mode & 0o077) !== 0)
96
+ chmodSync(dir, 0o700);
97
+ }
98
+ catch {
99
+ /* best effort */
100
+ }
101
+ const tmp = `${path}.${process.pid}.tmp`;
102
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
103
+ chmodSync(tmp, 0o600);
104
+ renameSync(tmp, path);
105
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/errors.js ADDED
@@ -0,0 +1,109 @@
1
+ // Exit codes and error classes shared by every command.
2
+ // 0 ok · 1 tool error · 2 usage · 3 auth needed
3
+ export const EXIT_OK = 0;
4
+ export const EXIT_TOOL_ERROR = 1;
5
+ export const EXIT_USAGE = 2;
6
+ export const EXIT_AUTH = 3;
7
+ export const PRICING_URL = 'https://realytix.io/pricing#plan-ai';
8
+ export const LOGIN_HINT = 'Run `realytix login`.';
9
+ export class CliError extends Error {
10
+ exitCode;
11
+ hint;
12
+ constructor(message, exitCode = EXIT_TOOL_ERROR, hint) {
13
+ super(message);
14
+ this.exitCode = exitCode;
15
+ this.hint = hint;
16
+ this.name = 'CliError';
17
+ }
18
+ }
19
+ export class UsageError extends CliError {
20
+ constructor(message, hint) {
21
+ super(message, EXIT_USAGE, hint);
22
+ this.name = 'UsageError';
23
+ }
24
+ }
25
+ export class AuthRequiredError extends CliError {
26
+ constructor(message = 'Not signed in.') {
27
+ super(message, EXIT_AUTH, LOGIN_HINT);
28
+ this.name = 'AuthRequiredError';
29
+ }
30
+ }
31
+ /** A tool answered with `isError` and a structured error. */
32
+ export class ToolCallError extends CliError {
33
+ tool;
34
+ payload;
35
+ constructor(tool, payload) {
36
+ super(payload.message, exitCodeForToolError(payload.code), hintForToolError(payload.code));
37
+ this.tool = tool;
38
+ this.payload = payload;
39
+ this.name = 'ToolCallError';
40
+ }
41
+ }
42
+ export function exitCodeForToolError(code) {
43
+ if (code === 'unauthorized')
44
+ return EXIT_AUTH;
45
+ if (code === 'invalid_input')
46
+ return EXIT_USAGE;
47
+ return EXIT_TOOL_ERROR;
48
+ }
49
+ export function hintForToolError(code) {
50
+ switch (code) {
51
+ case 'plan_required':
52
+ return `Realytix MCP and CLI are included in the Pro+AI plan. Upgrade at ${PRICING_URL}`;
53
+ case 'unauthorized':
54
+ return LOGIN_HINT;
55
+ case 'no_ai_credit':
56
+ return 'Your monthly AI allowance is used up. Add AI credit or wait for the reset date shown by `realytix get-account`.';
57
+ case 'daily_cap_reached':
58
+ return 'The daily AI cap is reached; try again tomorrow.';
59
+ case 'no_research_credit':
60
+ return 'No keyword-research credit left this month. `realytix get-account` shows the balance.';
61
+ case 'extension_offline':
62
+ return 'Live Amazon reads run through your Realytix Chrome extension. Open Chrome, make sure the extension is signed in, then retry.';
63
+ case 'rate_limited':
64
+ return 'Too many requests. Wait a moment and retry.';
65
+ case 'temporarily_unavailable':
66
+ return 'The data behind this tool is temporarily unavailable. Retry in a minute.';
67
+ case 'marketplace_unsupported':
68
+ return 'See `realytix tool <name>` for the marketplaces this tool covers.';
69
+ default:
70
+ return undefined;
71
+ }
72
+ }
73
+ /** Parse the body of an isError result: JSON `{error:{code,message,details}}`, or plain text. */
74
+ export function parseToolErrorPayload(text, structured) {
75
+ const fromStructured = extractError(structured);
76
+ if (fromStructured)
77
+ return fromStructured;
78
+ if (text) {
79
+ try {
80
+ const parsed = JSON.parse(text);
81
+ const fromText = extractError(parsed);
82
+ if (fromText)
83
+ return fromText;
84
+ }
85
+ catch {
86
+ /* not JSON */
87
+ }
88
+ }
89
+ const plain = text?.trim() || 'The tool returned an error without details.';
90
+ // SDK-level input validation arrives as plain text ("MCP error -32602: Input validation error: …").
91
+ if (/^MCP error -32602\b|Input validation error|Invalid arguments for tool/i.test(plain)) {
92
+ return { code: 'invalid_input', message: plain.replace(/^MCP error -?\d+:\s*/, '') };
93
+ }
94
+ return { code: 'internal', message: plain };
95
+ }
96
+ function extractError(value) {
97
+ if (!value || typeof value !== 'object')
98
+ return undefined;
99
+ const v = value;
100
+ const err = (v.error && typeof v.error === 'object' ? v.error : typeof v.code === 'string' && typeof v.message === 'string' ? v : undefined);
101
+ if (!err || typeof err.code !== 'string')
102
+ return undefined;
103
+ const payload = { code: err.code, message: typeof err.message === 'string' ? err.message : err.code };
104
+ if (err.details && typeof err.details === 'object')
105
+ payload.details = err.details;
106
+ if (typeof err.retryable === 'boolean')
107
+ payload.retryable = err.retryable;
108
+ return payload;
109
+ }