@shyftai/ranq 0.1.0 → 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
@@ -4,6 +4,8 @@ The command line and MCP client for the ranq API. Your agent uses it to read cor
4
4
 
5
5
  Read more at https://ranq.sh
6
6
 
7
+ Quickstart: https://api.ranq.sh/quickstart
8
+
7
9
  ## Install
8
10
 
9
11
  Node 22.18 or later is necessary.
@@ -1,5 +1,5 @@
1
1
  import { AGENT_ENV, isValidAgentSlug } from "../mcp/server.js";
2
- import { TOOLS } from "../mcp/tools.js";
2
+ import { TOOLS, restRoute } from "../mcp/tools.js";
3
3
  import { stripControl } from "./control.js";
4
4
  import { json } from "./table.js";
5
5
  /** Tools the API exposes that stay operator acts on the CLI: refused here with the operator verb. */
@@ -11,9 +11,32 @@ export function apiToolUsage() {
11
11
  .map((t) => `${t.method ?? 'GET'}\t${t.name}`)
12
12
  .join('\n');
13
13
  }
14
+ const propsOf = (tool) => (tool.inputSchema.properties ?? {});
15
+ const flagList = (tool) => Object.keys(propsOf(tool)).map((n) => `--${n}`).join(', ') || 'none';
16
+ /** `ranq api <tool> --help`: the tool's arguments as flags, from the same catalogue MCP lists. */
17
+ export function toolHelp(tool) {
18
+ const props = propsOf(tool);
19
+ const required = new Set(tool.inputSchema.required ?? []);
20
+ const positional = props['project']?.type === 'string' ? ' <project>' : '';
21
+ const lines = Object.entries(props).map(([name, p]) => {
22
+ const type = Array.isArray(p.type) ? p.type.join('|') : p.type ?? 'string';
23
+ const shape = type === 'boolean' ? '' : type === 'object' || type === 'array' ? ` <JSON ${type}>` : ` <${type}>`;
24
+ return ` --${name}${shape}${required.has(name) ? ' (required)' : ''}${p.description ? `\n ${p.description}` : ''}`;
25
+ });
26
+ return [
27
+ `ranq api ${tool.name}${positional} [--flag value ...]`,
28
+ '',
29
+ tool.description,
30
+ '',
31
+ 'Flags',
32
+ ...(lines.length > 0 ? lines : [' (none)']),
33
+ '',
34
+ `REST: ${restRoute(tool)}`,
35
+ ].join('\n');
36
+ }
14
37
  /** Flags to tool arguments, typed by the tool's inputSchema. Returns an error string on a bad flag. */
15
38
  export function toolArgs(tool, positional, flags) {
16
- const props = (tool.inputSchema.properties ?? {});
39
+ const props = propsOf(tool);
17
40
  const args = {};
18
41
  if (positional.length > 1)
19
42
  return `ranq api ${tool.name} takes at most one positional argument (the project)`;
@@ -28,7 +51,7 @@ export function toolArgs(tool, positional, flags) {
28
51
  const name = Object.hasOwn(props, flag) ? flag : flag.replaceAll('-', '_');
29
52
  const type = Object.hasOwn(props, name) ? props[name].type : undefined;
30
53
  if (type === undefined)
31
- return `unknown flag --${flag} for "ranq api ${tool.name}"`;
54
+ return `unknown flag --${flag} for "ranq api ${tool.name}"; its flags are ${flagList(tool)} (ranq api ${tool.name} --help)`;
32
55
  if (Object.hasOwn(args, name))
33
56
  return `--${flag} duplicates an argument already given`;
34
57
  if (type === 'boolean') {
@@ -71,12 +94,12 @@ export async function apiTool(positional, flags, io, withClient) {
71
94
  io.err('ranq api list takes no arguments');
72
95
  return 2;
73
96
  }
74
- const bad = [...flags.keys()].find((f) => f !== 'json');
97
+ const bad = [...flags.keys()].find((f) => f !== 'json' && f !== 'help');
75
98
  if (bad !== undefined) {
76
99
  io.err(stripControl(`unknown flag --${bad} for "ranq api list"`));
77
100
  return 2;
78
101
  }
79
- io.out(apiToolUsage());
102
+ io.out(apiToolUsage() + (flags.has('help') ? '\n\nranq api <tool> --help shows one tool\'s flags' : ''));
80
103
  return 0;
81
104
  }
82
105
  if (Object.hasOwn(OPERATOR_ONLY_TOOLS, name)) {
@@ -88,6 +111,10 @@ export async function apiTool(positional, flags, io, withClient) {
88
111
  io.err(stripControl(`unknown API tool: ${name}`) + '\n\nranq api list shows every tool');
89
112
  return 2;
90
113
  }
114
+ if (flags.has('help')) {
115
+ io.out(toolHelp(tool));
116
+ return 0;
117
+ }
91
118
  const args = toolArgs(tool, rest, flags);
92
119
  if (typeof args === 'string') {
93
120
  io.err(stripControl(args));
@@ -95,7 +122,7 @@ export async function apiTool(positional, flags, io, withClient) {
95
122
  }
96
123
  for (const required of tool.inputSchema.required ?? []) {
97
124
  if (args[required] === undefined || args[required] === '') {
98
- io.err(`--${required} is required for "ranq api ${tool.name}"`);
125
+ io.err(`--${required} is required for "ranq api ${tool.name}" (ranq api ${tool.name} --help shows its flags)`);
99
126
  return 2;
100
127
  }
101
128
  }
@@ -13,6 +13,7 @@ export const CLIENT_USAGE = `usage
13
13
  ranq api list List the API tools.
14
14
  ranq api <tool> [project] [--flag value ...]
15
15
  Call one API tool. The output is JSON.
16
+ ranq api <tool> --help Show one tool's flags and its REST route.
16
17
  ranq --version Show the client version.
17
18
  ranq --help Show this help.
18
19
 
@@ -30,7 +31,8 @@ export async function clientMain(argv, io) {
30
31
  io.err('--api-key is not accepted: a key on the command line leaks into shell history and the process list. Set RANQ_API_KEY in the environment instead');
31
32
  return 2;
32
33
  }
33
- if (flags.has('help') || command === 'help') {
34
+ // `ranq api <tool> --help` is the tool's own help (api-tool.ts)
35
+ if ((flags.has('help') && command !== 'api') || command === 'help') {
34
36
  io.out(CLIENT_USAGE);
35
37
  return 0;
36
38
  }
@@ -12,7 +12,7 @@
12
12
  * project-write POST tools stay dry runs unless the caller sends execute: true (checkout tools
13
13
  * create a session directly; start_scan takes mode). `run` is refused client-side.
14
14
  */
15
- import { restFetch, stripTrailingSlash } from "./rest.js";
15
+ import { issueLines, restFetch, stripTrailingSlash } from "./rest.js";
16
16
  export class MissingApiConfigError extends Error {
17
17
  name = 'MissingApiConfigError';
18
18
  constructor(message = 'MissingApiConfigError: RANQ_API_URL and RANQ_API_KEY are required (or --api-url/--api-key)') {
@@ -171,13 +171,15 @@ export class RanqClient {
171
171
  throw new ApiRedirectRefusedError(res.status);
172
172
  if (!res.ok) {
173
173
  let code;
174
+ let detail = '';
174
175
  try {
175
176
  const body = (await res.json());
176
177
  if (typeof body?.error === 'string')
177
178
  code = body.error;
179
+ detail = issueLines(body);
178
180
  }
179
181
  catch { /* non-JSON error body: status alone is enough */ }
180
- throw new ApiError(res.status, `ApiError: ${method} ${path} failed with ${res.status}${code ? `: ${code}` : ''}`, code);
182
+ throw new ApiError(res.status, `ApiError: ${method} ${path} failed with ${res.status}${code ? `: ${code}` : ''}${detail}`, code);
181
183
  }
182
184
  try {
183
185
  return await res.json();
@@ -14,3 +14,22 @@ export function restFetch(transport, path, init = {}) {
14
14
  ...(init.redirect !== undefined ? { redirect: init.redirect } : {}),
15
15
  });
16
16
  }
17
+ /**
18
+ * The field-level `issues` of an API refusal (invalid_project, invalid_prompts), one line each, so the
19
+ * MCP tool text and the CLI error carry what REST returns (dry run 1128: both dropped it). Empty when
20
+ * the body has none.
21
+ */
22
+ export function issueLines(body) {
23
+ const issues = body !== null && typeof body === 'object' ? body.issues : undefined;
24
+ if (!Array.isArray(issues))
25
+ return '';
26
+ return issues
27
+ .map((raw) => {
28
+ const i = (raw !== null && typeof raw === 'object' ? raw : {});
29
+ const where = typeof i['path'] === 'string' ? ` ${i['path']}` : typeof i['index'] === 'number' ? ` prompts[${i['index']}]` : '';
30
+ const message = typeof i['message'] === 'string' ? `: ${i['message']}` : '';
31
+ const fix = typeof i['fix'] === 'string' ? ` Fix: ${i['fix']}` : '';
32
+ return `\n ${String(i['code'])}${where}${message}${fix}`;
33
+ })
34
+ .join('');
35
+ }
@@ -1,6 +1,6 @@
1
1
  import { createInterface } from 'node:readline';
2
- import { restFetch } from "../client/rest.js";
3
- import { TOOLS } from "./tools.js";
2
+ import { issueLines, restFetch } from "../client/rest.js";
3
+ import { MCP_TOOLS } from "./tools.js";
4
4
  import { CLIENT_VERSION } from "../version.js";
5
5
  export const AGENT_ENV = 'RANQ_AGENT';
6
6
  const AGENT_SLUG_RE = /^[a-z0-9-]{1,40}$/;
@@ -43,7 +43,7 @@ export function createMcpServer(deps) {
43
43
  const parsed = await res.json().catch(() => null);
44
44
  if (!res.ok) {
45
45
  const code = parsed && typeof parsed === 'object' && 'error' in parsed ? String(parsed.error) : res.statusText;
46
- throw new Error(`ranq API ${res.status}: ${code}`);
46
+ throw Object.assign(new Error(`ranq API ${res.status}: ${code}${issueLines(parsed)}`), { body: parsed });
47
47
  }
48
48
  return parsed;
49
49
  }
@@ -72,11 +72,11 @@ export function createMcpServer(deps) {
72
72
  return reply({});
73
73
  case 'tools/list':
74
74
  return reply({
75
- tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
75
+ tools: MCP_TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
76
76
  });
77
77
  case 'tools/call': {
78
78
  const name = params?.['name'];
79
- const tool = TOOLS.find((t) => t.name === name);
79
+ const tool = MCP_TOOLS.find((t) => t.name === name);
80
80
  if (!tool)
81
81
  return fail(-32602, `unknown tool: ${String(name)}`);
82
82
  const args = (params?.['arguments'] ?? {});
@@ -90,8 +90,11 @@ export function createMcpServer(deps) {
90
90
  return reply({ content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data });
91
91
  }
92
92
  catch (error) {
93
+ // the refusal body (issues, retry_after_seconds, ...) as data too, the same object REST returns
94
+ const body = error.body;
93
95
  return reply({
94
96
  content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }],
97
+ ...(body !== null && typeof body === 'object' ? { structuredContent: body } : {}),
95
98
  isError: true,
96
99
  });
97
100
  }
@@ -441,6 +441,12 @@ export const TOOLS = [
441
441
  inputSchema: { type: 'object', properties: {} },
442
442
  path: () => '/v1/markets',
443
443
  },
444
+ {
445
+ name: 'get_prices',
446
+ description: 'Every action that spends credits, with its credits, its unit, its dollar value at each credit pack, and whether a failed or blocked result is free. Free tools are not listed. monthly_fees: each prepaid monthly fee (connection, partner_inbox, own_inbox) in USD and in credits per month at today\'s pack rate. To see what one call costs before it spends, run that tool without execute: true. Its dry run returns quote: the credits execute would reserve, your available credits, frozen, and key_cap (null: no per-key cap yet).',
447
+ inputSchema: { type: 'object', properties: {} },
448
+ path: () => '/v1/prices',
449
+ },
444
450
  {
445
451
  name: 'get_project_markets',
446
452
  description: 'The concrete markets one project measures. History is per market. A market change takes effect at the next collection and does not rewrite history.',
@@ -513,16 +519,60 @@ export const TOOLS = [
513
519
  description: 'A Stripe Checkout URL to buy one credit pack for this key\'s workspace: pack 9 (500 credits), 49 (2,800), 199 (12,500) or 499 (37,000), USD, valid 12 months. Nothing is granted until Stripe confirms the payment. 1 credit = 1 answer (one prompt, one engine, one market). Tenant zero is not billed (not_billed); a frozen workspace is refused (workspace_frozen).',
514
520
  inputSchema: {
515
521
  type: 'object',
516
- properties: { pack: { type: 'string', description: '9 | 49 | 199 | 499 (USD)' } },
522
+ properties: {
523
+ pack: { type: 'string', description: '9 | 49 | 199 | 499 (USD)' },
524
+ save_card: { type: 'boolean', description: 'the buyer consents to Ranq saving the card for auto top-up (off-session charges); default false' },
525
+ },
517
526
  required: ['pack'],
518
527
  },
519
528
  path: () => '/v1/billing/checkout',
520
529
  method: 'POST',
521
- body: (a) => ({ pack: a['pack'] }),
530
+ body: (a) => ({ pack: a['pack'], ...('save_card' in a ? { save_card: a['save_card'] } : {}) }),
531
+ },
532
+ {
533
+ name: 'get_auto_topup',
534
+ description: 'This workspace\'s auto top-up: whether a card is saved, enabled, threshold_credits, pack, daily_cap, and why it was last disabled (a declined or 3-D Secure charge turns it off; it is never retried).',
535
+ inputSchema: { type: 'object', properties: {} },
536
+ path: () => '/v1/billing/auto-topup',
537
+ },
538
+ {
539
+ name: 'set_auto_topup',
540
+ description: 'Set auto top-up: when a charge takes the balance below threshold_credits, Ranq charges the saved card for one pack (9 | 49 | 199 | 499), at most daily_cap times a UTC day (default 3). Needs a card saved by create_checkout with save_card: true (no_saved_card). Credits land when Stripe confirms the payment.',
541
+ inputSchema: {
542
+ type: 'object',
543
+ properties: {
544
+ enabled: { type: 'boolean' },
545
+ threshold_credits: { type: 'number' },
546
+ pack: { type: 'string', description: '9 | 49 | 199 | 499 (USD)' },
547
+ daily_cap: { type: 'number', description: '1-24, default 3' },
548
+ },
549
+ required: ['enabled'],
550
+ },
551
+ path: () => '/v1/billing/auto-topup',
552
+ method: 'POST',
553
+ body: (a) => Object.fromEntries(['enabled', 'threshold_credits', 'pack', 'daily_cap'].filter((k) => k in a).map((k) => [k, a[k]])),
554
+ },
555
+ {
556
+ name: 'list_fees',
557
+ description: 'This workspace\'s prepaid monthly fees (connections and inboxes): kind, external_ref, status (active | cancel_pending | cancelled | lapsed), the paid period, and next_renewal (when, credits at today\'s price, USD) or null if it will not renew. Ranq debits next month\'s credits 3 days before the period ends; a short balance or a frozen workspace lapses the item instead.',
558
+ inputSchema: { type: 'object', properties: {} },
559
+ path: () => '/v1/billing/fees',
560
+ },
561
+ {
562
+ name: 'cancel_fee',
563
+ description: 'Cancel one monthly fee: it stops the next renewal only. The paid period runs to its end (status cancel_pending, then cancelled); nothing is refunded. A second cancel changes nothing.',
564
+ inputSchema: {
565
+ type: 'object',
566
+ properties: { fee: { type: 'string', description: 'fee id from list_fees' } },
567
+ required: ['fee'],
568
+ },
569
+ path: (a) => `/v1/billing/fees/${encodeURIComponent(str(a, 'fee'))}/cancel`,
570
+ method: 'POST',
571
+ body: () => ({}),
522
572
  },
523
573
  {
524
574
  name: 'get_balance',
525
- description: 'This workspace\'s credits: available (what a new paid call may reserve), balance, held, granted, settled, reversed, expired, adjusted, and whether spending is frozen. A paid call is refused with credits_exhausted when available is short.',
575
+ description: 'This workspace\'s credits: available (what a new paid call may reserve), balance, held, granted, settled, reversed, expired, adjusted, and whether spending is frozen. A paid call is refused with credits_exhausted when available is short. The workspace is shared: projects breaks held, settled and released down by project and by actor (agent:<your agent slug> for your own calls, run_visibility_check included, or ranq:collect for the weekly background collection), and unattributed holds the rest (monthly fees). A background collection hold can move available mid-session; use projects or get_ledger to tell your spend from it.',
526
576
  inputSchema: { type: 'object', properties: {} },
527
577
  path: () => '/v1/billing/balance',
528
578
  },
@@ -631,7 +681,7 @@ export const TOOLS = [
631
681
  },
632
682
  {
633
683
  name: 'run_visibility_check',
634
- description: "Collect fresh answers now for one project on ONE engine (every active prompt x every project market), extract their citations, and return the project's visibility on that engine in get_visibility's shape, one entry per market. Paid in credits (1 per answer), held before the first provider call and settled on the answers delivered. max_usd may only lower the per-call ceiling, never raise it (max_usd_above_default). At most one executed check per project and engine per hour: a second is refused with visibility_check_rate_limited and retry_after_seconds; a dry run reports rate_limited instead. This call is a dry run unless execute: true: without it nothing is called, reserved or written and the result shows the prompt count, estimated cost, the ceiling in force and the credit cost.",
684
+ description: "Collect fresh answers now for one project on ONE engine (every active prompt x every project market) and extract their citations. Paid in credits (1 per answer), held before the first provider call and settled on the answers delivered. Execute returns at once (HTTP 202) with check_id and status running, once the credits are held; collecting can take minutes. Poll get_visibility_check with that check_id until status is succeeded (its result has collection and visibility, one get_visibility entry per market) or failed. max_usd may only lower the per-call ceiling, never raise it (max_usd_above_default). At most one executed check per project and engine per hour: running it again inside the hour returns the same check with reused: true and charges nothing new; after any other collection in that hour it is refused with visibility_check_rate_limited and retry_after_seconds. A dry run reports rate_limited instead. This call is a dry run unless execute: true: without it nothing is called, reserved or written and the result shows the prompt count, estimated cost, the ceiling in force and the credit cost.",
635
685
  inputSchema: {
636
686
  type: 'object',
637
687
  properties: {
@@ -650,6 +700,19 @@ export const TOOLS = [
650
700
  execute: a['execute'] === true,
651
701
  }),
652
702
  },
703
+ {
704
+ name: 'get_visibility_check',
705
+ description: "Progress of one run_visibility_check execute: status running | succeeded | failed | abandoned (still running after its process stopped; the hold is released on the next reservation), credits_held, created_at, finished_at, and once succeeded collection (runs, succeeded, failed, credits_settled) and visibility (one get_visibility entry per market). Free. Poll every 10 to 30 seconds. Another project's or workspace's check is visibility_check_not_found.",
706
+ inputSchema: {
707
+ type: 'object',
708
+ properties: {
709
+ project: { type: 'string', description: 'project slug or uuid' },
710
+ check: { type: 'string', description: 'the check_id run_visibility_check returned' },
711
+ },
712
+ required: ['project', 'check'],
713
+ },
714
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/visibility-checks/${encodeURIComponent(str(a, 'check'))}`,
715
+ },
653
716
  {
654
717
  name: 'get_page_evidence',
655
718
  description: 'Read-only page evidence for a project URL, query, and market. It fetches no pages and calls no provider. Top results are not collected yet, so top is usually empty and the response has unpaid: true. That is a normal result, not an error.',
@@ -754,14 +817,106 @@ export const TOOLS = [
754
817
  return out;
755
818
  },
756
819
  },
820
+ {
821
+ name: 'list_site_connections',
822
+ description: "A project's site connections: provider (gsc = Google Search Console, ga4 = Google Analytics 4, posthog), status pending|active|lapsed|disconnected (lapsed: the monthly fee was not paid, so Ranq disconnected it), external_id (the connected account, or the PostHog project id), host (PostHog), connected_at, last_read_at, last_error of the weekly read, and needs_reconnect (true: Ranq cannot use the stored PostHog key; call connect_site again with the key). A PostHog key is never returned. Scoped to the key's own workspace.",
823
+ inputSchema: projectArg,
824
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/connections`,
825
+ },
826
+ {
827
+ name: 'connect_site',
828
+ surface: 'api',
829
+ description: "Start a Search Console (gsc) or GA4 (ga4) connection for a project through Ranq's connection service. Ranq checks the workspace can pay the monthly connection fee in credits (credits_exhausted or workspace_frozen if not), then returns auth_url: send the site owner there to sign in with Google. The connection service then redirects to redirect_url (https) with accountId, or with step=select_site|select_property and a pendingDataToken when the Google account reads several; finish with complete_site_connection. The fee is taken when complete_site_connection makes the connection active. For posthog, give host, project_id and api_key (a personal API key, phx_...) instead of redirect_url: Ranq checks the key at PostHog, stores it encrypted, takes the fee and makes the connection active in one step. Ranq never returns the key. On an active posthog connection this replaces the key, with no new fee. This call is a dry run unless execute: true.",
830
+ inputSchema: {
831
+ type: 'object',
832
+ properties: {
833
+ project: { type: 'string', description: 'project slug or uuid' },
834
+ provider: { type: 'string', description: 'gsc, ga4 or posthog' },
835
+ redirect_url: { type: 'string', description: 'gsc and ga4: https URL the connection service sends the site owner back to' },
836
+ host: { type: 'string', description: 'posthog: https://us.posthog.com or https://eu.posthog.com' },
837
+ project_id: { type: 'string', description: 'posthog: the PostHog project id (digits)' },
838
+ api_key: { type: 'string', description: 'posthog: a personal API key (phx_...) that can read the project; stored encrypted, never returned' },
839
+ execute: { type: 'boolean', description: 'must be true to connect; otherwise dry run' },
840
+ },
841
+ required: ['project', 'provider'],
842
+ },
843
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/connections`,
844
+ method: 'POST',
845
+ body: (a) => {
846
+ const out = { provider: a['provider'], execute: a['execute'] === true };
847
+ for (const key of ['redirect_url', 'host', 'project_id', 'api_key'])
848
+ if (a[key] !== undefined)
849
+ out[key] = a[key];
850
+ return out;
851
+ },
852
+ },
853
+ {
854
+ name: 'complete_site_connection',
855
+ surface: 'api',
856
+ description: "Finish a pending connection after the Google sign-in. With pending_data_token and no choice: returns choices, the sites or GA4 property ids to pick from (reads only). With pending_data_token and choice: selects it. Then Ranq finds the account in this workspace's own connection profile (account_id from the redirect, or the only one) and marks the connection active, taking the first month's monthly connection fee in credits in the same step (credits_exhausted or workspace_frozen if it cannot be paid, and nothing changes). An account outside this workspace is refused with account_not_in_workspace. This call is a dry run unless execute: true.",
857
+ inputSchema: {
858
+ type: 'object',
859
+ properties: {
860
+ project: { type: 'string', description: 'project slug or uuid' },
861
+ provider: { type: 'string', description: 'gsc or ga4' },
862
+ account_id: { type: 'string', description: 'accountId from the sign-in redirect' },
863
+ pending_data_token: { type: 'string', description: 'pendingDataToken from the sign-in redirect (pick step)' },
864
+ choice: { type: 'string', description: 'the siteUrl or GA4 propertyId to connect' },
865
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
866
+ },
867
+ required: ['project', 'provider'],
868
+ },
869
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/connections/${encodeURIComponent(str(a, 'provider'))}/complete`,
870
+ method: 'POST',
871
+ body: (a) => {
872
+ const out = { execute: a['execute'] === true };
873
+ for (const key of ['account_id', 'pending_data_token', 'choice'])
874
+ if (a[key] !== undefined)
875
+ out[key] = a[key];
876
+ return out;
877
+ },
878
+ },
879
+ {
880
+ name: 'disconnect_site',
881
+ surface: 'api',
882
+ description: 'Stop a site connection. An active one: the monthly fee stops renewing, no refund for the current month; it stays active and is read until the paid month ends, then Ranq disconnects it at the connection service. A pending or lapsed one is disconnected now, in Ranq only (a lapsed one was already disconnected at the connection service). A posthog key is deleted at once; the connection is then not read. This call is a dry run unless execute: true.',
883
+ inputSchema: {
884
+ type: 'object',
885
+ properties: {
886
+ project: { type: 'string', description: 'project slug or uuid' },
887
+ provider: { type: 'string', description: 'gsc, ga4 or posthog' },
888
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
889
+ },
890
+ required: ['project', 'provider'],
891
+ },
892
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/connections/${encodeURIComponent(str(a, 'provider'))}/disconnect`,
893
+ method: 'POST',
894
+ body: (a) => ({ execute: a['execute'] === true }),
895
+ },
896
+ {
897
+ name: 'get_site_report',
898
+ description: "Per page of the project's own domain for one ISO week: ai_citations (Ranq's AI answers that cited the page), gsc_clicks, gsc_impressions and gsc_position (Search Console), ai_referral_sessions (GA4 sessions from AI assistants such as chatgpt.com or perplexity.ai) and ai_referral_pageviews (PostHog pageviews from them). null means not measured, never zero. suggested_prompts lists the week's Search Console queries that are not prompts yet; nothing is added. week is a Monday (YYYY-MM-DD); default the latest week read.",
899
+ inputSchema: {
900
+ type: 'object',
901
+ properties: {
902
+ project: { type: 'string', description: 'project slug or uuid' },
903
+ week: { type: 'string', description: 'Monday of the ISO week, YYYY-MM-DD' },
904
+ },
905
+ required: ['project'],
906
+ },
907
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/site-report${typeof a['week'] === 'string' ? `?week=${encodeURIComponent(a['week'])}` : ''}`,
908
+ },
757
909
  {
758
910
  name: 'create_project',
759
- description: 'Create or update one project in a workspace. This call is a dry run unless execute: true: without it nothing is written and the result describes what would happen (create or update, and for an update the prompt count before and after, since the prompt set is replaced). A workspace key writes only its own workspace: omit workspace or name your own; any other workspace is refused with create_project_workspace_mismatch. The operator key must name the workspace (slug or uuid). Tenant zero is refused for every caller with create_project_tenant_zero. project is one project as in config/portfolio.json (slug, name, domain, category, entityDescription, brandAliases, competitors, source, prompts; active defaults to true), validated per field (invalid_project with issues). An existing slug in that workspace is updated, not duplicated, and its prompt set replaced; no other project is ever deactivated. If no prompt carries a cluster, placement gets a control group automatically: every prompt goes to treated cluster C1, round(10%) of them (at least 1; unbranded only, chosen by a stable hash of the text, so the same prompts give the same set) are held out in C9, and control_cluster is set to C9; the result shows control: {cluster, prompts, auto: true}. Under 3 prompts nothing is held out and control: {auto: false, reason} says how to tag prompts and call set_control_cluster. Tag any prompt (with clusters declared) and nothing is automatic; if the project had the automatic C9 and the new prompts no longer carry one, control_cluster is cleared (placement fails closed until set_control_cluster). Starts no collection and makes no paid call. Every refusal fires on a dry run too.',
911
+ description: 'Create or update one project in a workspace. This call is a dry run unless execute: true: without it nothing is written and the result describes what would happen (create or update, and for an update the prompt count before and after, since the prompt set is replaced). A workspace key writes only its own workspace: omit workspace or name your own; any other workspace is refused with create_project_workspace_mismatch. The operator key must name the workspace (slug or uuid). Tenant zero is refused for every caller with create_project_tenant_zero. project is one project (slug, name, domain, category, entityDescription, brandAliases, competitors, source, prompts, optional clusters; active defaults to true; see the project argument for the shape), validated per field: invalid_project returns issues, each with code, path, message and fix. An existing slug in that workspace is updated, not duplicated, and its prompt set replaced; no other project is ever deactivated. If no prompt carries a cluster, placement gets a control group automatically: every prompt goes to treated cluster C1, round(10%) of them (at least 1; unbranded only, chosen by a stable hash of the text, so the same prompts give the same set) are held out in C9, and control_cluster is set to C9; the result shows control: {cluster, prompts, auto: true}. Under 3 prompts nothing is held out and control: {auto: false, reason} says how to tag prompts and call set_control_cluster. Tag any prompt (with clusters declared) and nothing is automatic; if the project had the automatic C9 and the new prompts no longer carry one, control_cluster is cleared (placement fails closed until set_control_cluster). Starts no collection and makes no paid call. Every refusal fires on a dry run too.',
760
912
  inputSchema: {
761
913
  type: 'object',
762
914
  properties: {
763
915
  workspace: { type: 'string', description: 'target workspace slug or uuid; a workspace key may omit it (its own) and may name no other; never tenant zero' },
764
- project: { type: 'object', description: 'one project, same shape as a config/portfolio.json projects[] entry' },
916
+ project: {
917
+ type: 'object',
918
+ description: 'one project: {slug, name, domain (bare host, e.g. acme.com), category, entityDescription (one sentence), brandAliases (e.g. ["Acme", "acme.com"]), source (where the facts came from), competitors (["rival.com"] or [{name, domain}]), prompts: [{text, branded?: true, cluster?: "C1", allowBrandWord?: true}], clusters? ({"C1": "treated", "C9": "control"}; optional, tagging a prompt declares its cluster)}. At least 60% of prompts unbranded; an unbranded prompt may not name the brand or a competitor (allowBrandWord: true when a brand alias is also an ordinary word). Each refusal is in issues with code, path, message and fix.',
919
+ },
765
920
  execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
766
921
  },
767
922
  required: ['project'],
@@ -830,3 +985,11 @@ export const TOOLS = [
830
985
  body: (a) => ({ sha256: a['sha256'], recipients: a['recipients'], execute: a['execute'] === true }),
831
986
  },
832
987
  ];
988
+ /** The tools MCP lists and calls: every tool but the REST/CLI-only setup tools (`surface: 'api'`). */
989
+ export const MCP_TOOLS = TOOLS.filter((t) => t.surface !== 'api');
990
+ /** The REST route of a tool with its required arguments as `:name` placeholders, e.g. `POST /v1/projects/:project/prompts`. */
991
+ export function restRoute(tool) {
992
+ const schema = tool.inputSchema;
993
+ const args = Object.fromEntries((schema.required ?? []).map((name) => [name, `:${name}`]));
994
+ return `${tool.method ?? 'GET'} ${decodeURIComponent(tool.path(args))}`;
995
+ }
@@ -1,2 +1,2 @@
1
1
  /** The public client version (packages/ranq-client): `ranq --version` and the MCP serverInfo. test/client-pack.test.ts keeps it equal to packages/ranq-client/package.json. */
2
- export const CLIENT_VERSION = '0.1.0';
2
+ export const CLIENT_VERSION = '0.1.1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shyftai/ranq",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Command line and MCP client for the ranq API: corpus, presence rate and citation history for your agent.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ranq.sh",