@shyftai/ranq 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.
@@ -0,0 +1,995 @@
1
+ const projectArg = {
2
+ type: 'object',
3
+ properties: { project: { type: 'string', description: 'project slug or uuid' } },
4
+ required: ['project'],
5
+ };
6
+ function str(args, name) {
7
+ const value = args[name];
8
+ if (typeof value !== 'string' || value.length === 0)
9
+ throw new Error(`${name} is required`);
10
+ // encodeURIComponent leaves "." and ".." intact and the URL parser normalises them away, so a
11
+ // path segment of ".." would reach another route (/v1/projects/p/approvals/.. is /v1/projects/p).
12
+ if (value === '.' || value === '..')
13
+ throw new Error(`${name} must not be '.' or '..'`);
14
+ return value;
15
+ }
16
+ function query(pairs) {
17
+ const params = new URLSearchParams();
18
+ for (const [key, value] of Object.entries(pairs)) {
19
+ if (value !== undefined && value !== null && value !== '')
20
+ params.set(key, String(value));
21
+ }
22
+ const text = params.toString();
23
+ return text ? `?${text}` : '';
24
+ }
25
+ export const TOOLS = [
26
+ {
27
+ name: 'list_projects',
28
+ description: 'List every project (brand) with its domain, category and competitor domains.',
29
+ inputSchema: { type: 'object', properties: {} },
30
+ path: () => '/v1/projects',
31
+ },
32
+ {
33
+ name: 'get_project',
34
+ description: 'Full state of one project, including its latest presence (visibility) snapshot and control_cluster (null = unset, so placements and approval sends fail closed; "config" = tenant zero, set in config/portfolio.json).',
35
+ inputSchema: projectArg,
36
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}`,
37
+ },
38
+ {
39
+ name: 'get_visibility',
40
+ description: 'Current visibility by engine and prompt type: succeeded runs, runs citing the brand domain, and the presence rate. Pass market (e.g. se-sv) to read one market; multi-market projects refuse without it (market_required) so markets never mix.',
41
+ inputSchema: {
42
+ type: 'object',
43
+ properties: {
44
+ project: { type: 'string' },
45
+ engine: { type: 'string' },
46
+ prompt_type: { type: 'string' },
47
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
48
+ },
49
+ required: ['project'],
50
+ },
51
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/visibility${query({ engine: a['engine'], prompt_type: a['prompt_type'], market: a['market'] })}`,
52
+ },
53
+ {
54
+ name: 'get_visibility_history',
55
+ description: 'Weekly visibility time series by engine and prompt type. Pass market (e.g. se-sv) for one market; multi-market projects refuse without it (market_required).',
56
+ inputSchema: {
57
+ type: 'object',
58
+ properties: {
59
+ project: { type: 'string' },
60
+ engine: { type: 'string' },
61
+ prompt_type: { type: 'string' },
62
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
63
+ },
64
+ required: ['project'],
65
+ },
66
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/visibility/history${query({ engine: a['engine'], prompt_type: a['prompt_type'], market: a['market'] })}`,
67
+ },
68
+ {
69
+ name: 'diff_visibility',
70
+ description: 'Period over period: citation URLs that appeared or disappeared versus the preceding equal-length period. Requires from and to as ISO instants in the exact format YYYY-MM-DDTHH:mm:ss[.fff](Z|+HH:MM|-HH:MM), for example 2026-01-01T00:00:00Z or 2026-01-01T00:00:00+01:00: seconds are required, fractional seconds (1 to 9 digits) are optional, and the instant ends in Z or a UTC offset with a colon. Date-only values, missing seconds and a space instead of T are refused (400 from_and_to_are_required_iso_instants). The span from from to to must not exceed 366 days.',
71
+ inputSchema: {
72
+ type: 'object',
73
+ properties: {
74
+ project: { type: 'string' },
75
+ from: {
76
+ type: 'string',
77
+ description: 'Start instant, format YYYY-MM-DDTHH:mm:ss[.fff](Z|+HH:MM|-HH:MM), e.g. 2026-01-01T00:00:00Z; seconds are required, the optional fraction takes 1 to 9 fraction digits.',
78
+ },
79
+ to: {
80
+ type: 'string',
81
+ description: 'End instant, format YYYY-MM-DDTHH:mm:ss[.fff](Z|+HH:MM|-HH:MM), e.g. 2026-01-01T00:00:00Z; seconds are required, the optional fraction takes 1 to 9 fraction digits. At most 366 days after from.',
82
+ },
83
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
84
+ },
85
+ required: ['project', 'from', 'to'],
86
+ },
87
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/visibility/diff${query({ from: a['from'], to: a['to'], market: a['market'] })}`,
88
+ },
89
+ {
90
+ name: 'get_corpus',
91
+ description: 'The ranked corpus pages that decide this category, strongest citation evidence first.',
92
+ inputSchema: {
93
+ type: 'object',
94
+ properties: {
95
+ project: { type: 'string' },
96
+ state: { type: 'string', description: 'candidate | active | stale | removed' },
97
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
98
+ },
99
+ required: ['project'],
100
+ },
101
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/corpus${query({ state: a['state'], market: a['market'] })}`,
102
+ },
103
+ {
104
+ name: 'get_presence_gap',
105
+ description: 'Corpus pages where the brand is checked absent, scored by citation frequency and page type. Unchecked pages are counted, never listed. Pass market (e.g. se-sv) for one market; multi-market projects refuse without it (market_required).',
106
+ inputSchema: {
107
+ type: 'object',
108
+ properties: { project: { type: 'string' }, limit: { type: 'number' }, market: { type: 'string', description: 'market key, e.g. se-sv' } },
109
+ required: ['project'],
110
+ },
111
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/presence-gap${query({ limit: a['limit'], market: a['market'] })}`,
112
+ },
113
+ {
114
+ name: 'get_competitor_presence',
115
+ description: 'Where competitors are cited and which of their corpus pages name (or omit) the brand. Pages are capped per competitor (default 100); pagesTruncated: true on a competitor means it has more pages than were returned. Pass market (e.g. se-sv) for one market; multi-market projects refuse without it (market_required).',
116
+ inputSchema: {
117
+ type: 'object',
118
+ properties: { project: { type: 'string' }, market: { type: 'string', description: 'market key, e.g. se-sv' } },
119
+ required: ['project'],
120
+ },
121
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/competitor-presence${query({ market: a['market'] })}`,
122
+ },
123
+ {
124
+ name: 'get_mentions',
125
+ description: 'Stored LLM mention snapshots for one market (platform, keyword, kind, target, mentionsCount, status). A null mentionsCount means the provider had no figure, never 0. Pass market (e.g. se-sv) for one market; multi-market projects refuse without it (market_required).',
126
+ inputSchema: {
127
+ type: 'object',
128
+ properties: {
129
+ project: { type: 'string' },
130
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
131
+ },
132
+ required: ['project'],
133
+ },
134
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/mentions${query({ market: a['market'] })}`,
135
+ },
136
+ {
137
+ name: 'get_demand',
138
+ description: 'Stored per-prompt AI search volume readings for one market (promptId, collectedOn, aiSearchVolume, status). A null aiSearchVolume means the provider had no figure, never 0. Pass market (e.g. se-sv) for one market; multi-market projects refuse without it (market_required).',
139
+ inputSchema: {
140
+ type: 'object',
141
+ properties: {
142
+ project: { type: 'string' },
143
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
144
+ },
145
+ required: ['project'],
146
+ },
147
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/demand${query({ market: a['market'] })}`,
148
+ },
149
+ {
150
+ name: 'check_page_presence',
151
+ description: 'Whether the brand is named on one URL, read from stored presence checks. Never fetches the page; an unknown URL reports found: false.',
152
+ inputSchema: {
153
+ type: 'object',
154
+ properties: { project: { type: 'string' }, url: { type: 'string' } },
155
+ required: ['project', 'url'],
156
+ },
157
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/page-presence${query({ url: a['url'] })}`,
158
+ },
159
+ {
160
+ name: 'list_placements',
161
+ description: 'List placement ledger rows for a project (status, route, page URL, public owner route, gap score, verification state, link attribution from the latest check, and timestamps), optionally filtered by status.',
162
+ inputSchema: {
163
+ type: 'object',
164
+ properties: {
165
+ project: { type: 'string', description: 'project slug or uuid' },
166
+ status: {
167
+ type: 'string',
168
+ description: 'target | contacted | following_up | needs_client | placed | verified | declined | abandoned',
169
+ },
170
+ limit: { type: 'number' },
171
+ offset: { type: 'number' },
172
+ },
173
+ required: ['project'],
174
+ },
175
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/placements${query({ status: a['status'], limit: a['limit'], offset: a['offset'] })}`,
176
+ },
177
+ {
178
+ name: 'add_placement',
179
+ description: 'Add a placement target for a checked-absent corpus page. This call is a dry run unless execute: true: without it nothing is written and the result describes what would be created.',
180
+ inputSchema: {
181
+ type: 'object',
182
+ properties: {
183
+ project: { type: 'string', description: 'project slug or uuid' },
184
+ url: { type: 'string' },
185
+ route: { type: 'string', description: 'listing | pr_to_list | outreach_editor | community_answer' },
186
+ owner_route: { type: 'string' },
187
+ next_action_at: { type: 'string', description: 'ISO instant' },
188
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
189
+ },
190
+ required: ['project', 'url', 'route'],
191
+ },
192
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/placements`,
193
+ method: 'POST',
194
+ body: (a) => ({
195
+ url: a['url'],
196
+ route: a['route'],
197
+ ...('owner_route' in a ? { owner_route: a['owner_route'] } : {}),
198
+ ...('next_action_at' in a ? { next_action_at: a['next_action_at'] } : {}),
199
+ execute: a['execute'] === true,
200
+ }),
201
+ },
202
+ {
203
+ name: 'set_placement_status',
204
+ description: 'Move a placement to a new status and record a status event. This call is a dry run unless execute: true: without it nothing is written and the result describes what would change.',
205
+ inputSchema: {
206
+ type: 'object',
207
+ properties: {
208
+ project: { type: 'string', description: 'project slug or uuid' },
209
+ url: { type: 'string' },
210
+ status: {
211
+ type: 'string',
212
+ description: 'target | contacted | following_up | needs_client | placed | verified | declined | abandoned',
213
+ },
214
+ note: { type: 'string' },
215
+ next_action_at: { type: 'string', description: 'ISO instant' },
216
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
217
+ },
218
+ required: ['project', 'url', 'status'],
219
+ },
220
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/placements/status`,
221
+ method: 'POST',
222
+ body: (a) => ({
223
+ url: a['url'],
224
+ status: a['status'],
225
+ note: a['note'] ?? null,
226
+ ...('next_action_at' in a ? { next_action_at: a['next_action_at'] } : {}),
227
+ execute: a['execute'] === true,
228
+ }),
229
+ },
230
+ {
231
+ name: 'verify_placements',
232
+ description: 'List the placed/verified placements that verification would recheck (plan mode). This call is a dry run unless execute: true, and execute: true is refused by the API (verify_execute_not_available_via_api) because page fetching stays CLI-only.',
233
+ inputSchema: {
234
+ type: 'object',
235
+ properties: {
236
+ project: { type: 'string', description: 'project slug or uuid' },
237
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run. Refused by the API for this tool.' },
238
+ },
239
+ required: ['project'],
240
+ },
241
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/placements/verify`,
242
+ method: 'POST',
243
+ body: (a) => ({ execute: a['execute'] === true }),
244
+ },
245
+ {
246
+ name: 'get_placement_events',
247
+ description: 'Read one placement target (including its latest link attribution) and its append-only status transition event history by placement uuid or target page URL.',
248
+ inputSchema: {
249
+ type: 'object',
250
+ properties: {
251
+ project: { type: 'string', description: 'project slug or uuid' },
252
+ placement: { type: 'string', description: 'placement uuid or target page URL' },
253
+ limit: { type: 'number' },
254
+ },
255
+ required: ['project', 'placement'],
256
+ },
257
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/placements/${encodeURIComponent(str(a, 'placement'))}/events${query({ limit: a['limit'] })}`,
258
+ },
259
+ {
260
+ name: 'record_action',
261
+ description: 'Record an action you took for a page (append-only action log), so get_report can show whether citations moved after it. action: listed | submitted | skipped | published | updated. This call is a dry run unless execute: true. Refused: contact data in any field, a page the control cluster cites, a future time.',
262
+ inputSchema: {
263
+ type: 'object',
264
+ properties: {
265
+ project: { type: 'string', description: 'project slug or uuid' },
266
+ action: { type: 'string', description: 'listed | submitted | skipped | published | updated' },
267
+ target: { type: 'string', description: 'the page acted on: an http or https URL' },
268
+ result: { type: 'string', description: 'short outcome text, no contact data' },
269
+ gap_pages: { type: 'array', items: { type: 'string' }, description: 'gap page URLs this action is meant to move' },
270
+ at: { type: 'string', description: 'ISO instant; now when omitted' },
271
+ ref: { type: 'string', description: 'id this action belongs to (brief, approval, placement event)' },
272
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
273
+ },
274
+ required: ['project', 'action', 'target', 'result'],
275
+ },
276
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/actions`,
277
+ method: 'POST',
278
+ body: (a) => ({
279
+ action: a['action'],
280
+ target: a['target'],
281
+ result: a['result'],
282
+ ...('gap_pages' in a ? { gap_pages: a['gap_pages'] } : {}),
283
+ ...('at' in a ? { at: a['at'] } : {}),
284
+ ...('ref' in a ? { ref: a['ref'] } : {}),
285
+ execute: a['execute'] === true,
286
+ }),
287
+ },
288
+ {
289
+ name: 'list_actions',
290
+ description: 'The project action log, oldest first: every recorded action and every placement status change, from since on when given.',
291
+ inputSchema: {
292
+ type: 'object',
293
+ properties: {
294
+ project: { type: 'string', description: 'project slug or uuid' },
295
+ since: { type: 'string', description: 'ISO instant' },
296
+ limit: { type: 'number' },
297
+ },
298
+ required: ['project'],
299
+ },
300
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/actions${query({ since: a['since'], limit: a['limit'] })}`,
301
+ },
302
+ {
303
+ name: 'get_report',
304
+ description: 'Outcome report since an instant: placements by status, verified mentions, presence-rate change, and each action in the window with its page presence before and after. A side with no check is null and missing says why; nothing is guessed.',
305
+ inputSchema: {
306
+ type: 'object',
307
+ properties: {
308
+ project: { type: 'string', description: 'project slug or uuid' },
309
+ since: { type: 'string', description: 'ISO instant: the start of the window' },
310
+ },
311
+ required: ['project', 'since'],
312
+ },
313
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/report${query({ since: str(a, 'since') })}`,
314
+ },
315
+ {
316
+ name: 'get_project_events',
317
+ description: 'What changed in one project since a cursor, oldest first: runs finished or failed, corpus pages added, removed or changed state, presence verdicts changed, placement status changes, weekly collection and presence jobs finished. Poll with since = the previous next_cursor (omit it to start from the beginning); has_more true means call again at once. Each event has a stable id, at, a type from a closed list (docs/EVENTS.md), subject, summary and ref (the REST path to read). limit defaults to 100, max 500. A cursor this feed did not issue is invalid_cursor.',
318
+ inputSchema: {
319
+ type: 'object',
320
+ properties: {
321
+ project: { type: 'string', description: 'project slug or uuid' },
322
+ since: { type: 'string', description: 'next_cursor from the previous call; omit to start from the beginning' },
323
+ limit: { type: 'number', description: 'default 100, max 500' },
324
+ },
325
+ required: ['project'],
326
+ },
327
+ path: (a) => {
328
+ const q = query({ since: a['since'], limit: a['limit'] });
329
+ // query() drops '', but an empty since must reach REST and be invalid_cursor there, not a page from the start
330
+ const since = a['since'] === '' ? `${q ? `${q}&` : '?'}since=` : q;
331
+ return `/v1/projects/${encodeURIComponent(str(a, 'project'))}/events${since}`;
332
+ },
333
+ },
334
+ {
335
+ name: 'list_prompts',
336
+ description: 'The prompts one project measures, each with its default-language text and every reviewed wording by language (translations). History and collection are per market; a non-English market sends its own language wording.',
337
+ inputSchema: projectArg,
338
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/prompts`,
339
+ },
340
+ {
341
+ name: 'add_prompts',
342
+ description: 'Add prompts to a project in bulk (at most 50 per call). This call is a dry run unless execute: true: without it nothing is written and the result shows the counts that would change. Each prompt is { type: unbranded | branded | comparative, text, comparator? }: a branded prompt must name the brand, an unbranded one must not, a comparative one names its comparator in the text. Each prompt may name a cluster; on a project with the automatic control (create_project: control_cluster C9 with C1 prompts) an untagged new prompt goes to treated cluster C1, and a reactivated one keeps its own cluster, so the control set never changes unless you tag a prompt C9. A prompt that already exists is left as is; a removed one with the same type and text is reactivated, keeping its history. Never removes another prompt. Refuses a set whose unbranded share would fall below 0.6 (unbranded_share_below_floor), and tenant-zero projects (prompts_tenant_zero: they are managed in config/portfolio.json). Starts no collection.',
343
+ inputSchema: {
344
+ type: 'object',
345
+ properties: {
346
+ project: { type: 'string', description: 'project slug or uuid' },
347
+ prompts: {
348
+ type: 'array',
349
+ description: 'prompts to add',
350
+ items: {
351
+ type: 'object',
352
+ properties: {
353
+ type: { type: 'string', enum: ['unbranded', 'branded', 'comparative'] },
354
+ text: { type: 'string' },
355
+ comparator: { type: 'string', description: 'competitor name; comparative only' },
356
+ cluster: { type: 'string', description: 'cluster id, e.g. C7; lets the control guard place pages this prompt cites' },
357
+ },
358
+ required: ['type', 'text'],
359
+ },
360
+ },
361
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
362
+ },
363
+ required: ['project', 'prompts'],
364
+ },
365
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/prompts`,
366
+ method: 'POST',
367
+ body: (a) => ({ prompts: a['prompts'], execute: a['execute'] === true }),
368
+ },
369
+ {
370
+ name: 'remove_prompt',
371
+ description: 'Stop measuring one prompt: it is deactivated, never deleted, so its runs and history stay. This call is a dry run unless execute: true. Removing an inactive prompt is a no-op (deactivated: false). Refuses a removal that drops the unbranded share below 0.6 (unbranded_share_below_floor), and tenant-zero projects (prompts_tenant_zero).',
372
+ inputSchema: {
373
+ type: 'object',
374
+ properties: {
375
+ project: { type: 'string', description: 'project slug or uuid' },
376
+ prompt: { type: 'string', description: 'prompt uuid (from list_prompts)' },
377
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
378
+ },
379
+ required: ['project', 'prompt'],
380
+ },
381
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/prompts/${encodeURIComponent(str(a, 'prompt'))}/remove`,
382
+ method: 'POST',
383
+ body: (a) => ({ execute: a['execute'] === true }),
384
+ },
385
+ {
386
+ name: 'list_keywords',
387
+ description: 'The classic SEO keywords one project tracks for rank position, each with locale and device.',
388
+ inputSchema: projectArg,
389
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/keywords`,
390
+ },
391
+ {
392
+ name: 'add_keywords',
393
+ description: 'Add classic SEO keywords to track for rank position (at most 100 per call). This call is a dry run unless execute: true. Each entry is a term, or { term, locale?, device? } with locale like en-US (default) and device desktop (default) or mobile. A keyword already tracked for that locale and device is reported under existing and left as is. Makes no paid call.',
394
+ inputSchema: {
395
+ type: 'object',
396
+ properties: {
397
+ project: { type: 'string', description: 'project slug or uuid' },
398
+ keywords: {
399
+ type: 'array',
400
+ description: 'terms, or { term, locale?, device? }',
401
+ items: {
402
+ oneOf: [
403
+ { type: 'string' },
404
+ {
405
+ type: 'object',
406
+ properties: { term: { type: 'string' }, locale: { type: 'string' }, device: { type: 'string', enum: ['desktop', 'mobile'] } },
407
+ required: ['term'],
408
+ },
409
+ ],
410
+ },
411
+ },
412
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
413
+ },
414
+ required: ['project', 'keywords'],
415
+ },
416
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/keywords`,
417
+ method: 'POST',
418
+ body: (a) => ({ keywords: a['keywords'], execute: a['execute'] === true }),
419
+ },
420
+ {
421
+ name: 'set_prompt_translation',
422
+ description: 'Set one prompt\'s human-reviewed wording for a language (ISO 639-1). This call is a dry run unless execute: true: without it nothing is written. Wordings are never machine-generated; add the wording before adding a market in that language (set_project_markets refuses with prompt_translation_missing otherwise).',
423
+ inputSchema: {
424
+ type: 'object',
425
+ properties: {
426
+ project: { type: 'string', description: 'project slug or uuid' },
427
+ prompt: { type: 'string', description: 'prompt uuid' },
428
+ language: { type: 'string', description: 'ISO 639-1 lowercase, e.g. es' },
429
+ text: { type: 'string', description: 'the reviewed wording in that language' },
430
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
431
+ },
432
+ required: ['project', 'prompt', 'language', 'text'],
433
+ },
434
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/prompts/${encodeURIComponent(str(a, 'prompt'))}/translations`,
435
+ method: 'POST',
436
+ body: (a) => ({ language: a['language'], text: a['text'], execute: a['execute'] === true }),
437
+ },
438
+ {
439
+ name: 'list_markets',
440
+ description: 'Supported market countries (with location codes), named regions, and per-engine market coverage. A market change takes effect at the next collection and does not rewrite history.',
441
+ inputSchema: { type: 'object', properties: {} },
442
+ path: () => '/v1/markets',
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
+ },
450
+ {
451
+ name: 'get_project_markets',
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.',
453
+ inputSchema: projectArg,
454
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/markets`,
455
+ },
456
+ {
457
+ name: 'set_project_markets',
458
+ description: 'Replace a project\'s market list (concrete markets and/or regions with a language). This call is a dry run unless execute: true: without it nothing is written. Refuses with prompt_translation_missing (dry run included) when the new list introduces a language active prompts have no reviewed wording for. A market change takes effect at the next collection and does not rewrite history.',
459
+ inputSchema: {
460
+ type: 'object',
461
+ properties: {
462
+ project: { type: 'string', description: 'project slug or uuid' },
463
+ markets: {
464
+ type: 'array',
465
+ description: 'concrete markets, e.g. [{country: SE, language: sv}]',
466
+ items: { type: 'object', properties: { country: { type: 'string' }, language: { type: 'string' } } },
467
+ },
468
+ regions: {
469
+ type: 'array',
470
+ description: 'region rules, e.g. [{region: nordics, language: en}]',
471
+ items: { type: 'object', properties: { region: { type: 'string' }, language: { type: 'string' } } },
472
+ },
473
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
474
+ },
475
+ required: ['project'],
476
+ },
477
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/markets`,
478
+ method: 'POST',
479
+ body: (a) => ({
480
+ ...(Array.isArray(a['markets']) ? { markets: a['markets'] } : {}),
481
+ ...(Array.isArray(a['regions']) ? { regions: a['regions'] } : {}),
482
+ execute: a['execute'] === true,
483
+ }),
484
+ },
485
+ {
486
+ name: 'start_scan',
487
+ description: 'Start the USD 1 scan of a domain (operator only: any workspace key is refused with scan_operator_only). mode plan (default) returns the steps and the cost estimate and writes nothing (on a domain already scanned it also says what a request would do to that scan); draft reads the site and makes one drafting call, storing the draft; execute drafts if needed, then creates the scan project, collects 10 prompts x 3 engines under the per-scan ceiling, and builds the report. One scan per domain: a second one is refused with scan_exists and the existing id, except that a failed (or stale) scan gets one free retry of the same scan, redoing only what did not succeed; after that, scan_exists with retry_used. Poll get_scan for progress.',
488
+ inputSchema: {
489
+ type: 'object',
490
+ properties: {
491
+ domain: { type: 'string', description: 'the domain to scan, e.g. acme.com' },
492
+ market: { type: 'string', description: 'one English-language market, e.g. US-en (default)' },
493
+ mode: { type: 'string', description: 'plan | draft | execute (default plan)' },
494
+ max_usd: { type: 'number', description: 'lower the per-scan USD ceiling; never above the default' },
495
+ },
496
+ required: ['domain'],
497
+ },
498
+ path: () => '/v1/scans',
499
+ method: 'POST',
500
+ body: (a) => ({
501
+ domain: a['domain'],
502
+ ...('market' in a ? { market: a['market'] } : {}),
503
+ ...('mode' in a ? { mode: a['mode'] } : {}),
504
+ ...('max_usd' in a ? { max_usd: a['max_usd'] } : {}),
505
+ }),
506
+ },
507
+ {
508
+ name: 'get_scan',
509
+ description: 'One scan (operator only): status, each step with timestamps, the draft, the spend, and when it succeeded the report (visibility per engine, prompts lost, top 5 pages to get on).',
510
+ inputSchema: {
511
+ type: 'object',
512
+ properties: { scan: { type: 'string', description: 'scan uuid' } },
513
+ required: ['scan'],
514
+ },
515
+ path: (a) => `/v1/scans/${encodeURIComponent(str(a, 'scan'))}`,
516
+ },
517
+ {
518
+ name: 'create_checkout',
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).',
520
+ inputSchema: {
521
+ type: 'object',
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
+ },
526
+ required: ['pack'],
527
+ },
528
+ path: () => '/v1/billing/checkout',
529
+ method: 'POST',
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: () => ({}),
572
+ },
573
+ {
574
+ name: 'get_balance',
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.',
576
+ inputSchema: { type: 'object', properties: {} },
577
+ path: () => '/v1/billing/balance',
578
+ },
579
+ {
580
+ name: 'get_ledger',
581
+ description: 'This workspace\'s append-only credit ledger, newest first: grant, reserve, settle, release, reversal, expiry and adjustment rows. Paged with limit (1-500, default 100) and offset.',
582
+ inputSchema: {
583
+ type: 'object',
584
+ properties: { limit: { type: 'number' }, offset: { type: 'number' } },
585
+ },
586
+ path: (a) => `/v1/billing/ledger${query({ limit: a['limit'], offset: a['offset'] })}`,
587
+ },
588
+ {
589
+ name: 'create_scan_checkout',
590
+ description: 'A Stripe Checkout URL for the USD 1 scan of a domain (card, 3-D Secure). The scan starts when Stripe confirms the payment; read it with get_scan_by_session and the Checkout session id. One scan per domain (scan_exists); one paid scan per card per 24 hours (a second is refunded with card_scan_limit). Rate limited per client.',
591
+ inputSchema: {
592
+ type: 'object',
593
+ properties: { domain: { type: 'string', description: 'the domain to scan, e.g. acme.com' } },
594
+ required: ['domain'],
595
+ },
596
+ path: () => '/v1/public/scans/checkout',
597
+ method: 'POST',
598
+ body: (a) => ({ domain: a['domain'] }),
599
+ },
600
+ {
601
+ name: 'get_scan_by_session',
602
+ description: 'The paid scan bought with one Stripe Checkout session id (cs_...): payment state, the scan status per step, and when done the report. Only that session\'s scan.',
603
+ inputSchema: {
604
+ type: 'object',
605
+ properties: { session: { type: 'string', description: 'Stripe Checkout session id, cs_...' } },
606
+ required: ['session'],
607
+ },
608
+ path: (a) => `/v1/public/scans/by-session/${encodeURIComponent(str(a, 'session'))}`,
609
+ },
610
+ {
611
+ name: 'set_competitors',
612
+ description: 'Replace a project\'s competitor domains. This call is a dry run unless execute: true: without it nothing is written and the result shows the previous and would-be list. Each entry is a bare domain or URL, normalised to a lowercase host without www. Refuses an empty list, a duplicate after normalisation, the project\'s own domain, a non-domain, and more than 50 entries.',
613
+ inputSchema: {
614
+ type: 'object',
615
+ properties: {
616
+ project: { type: 'string', description: 'project slug or uuid' },
617
+ competitors: { type: 'array', description: 'the full competitor list, e.g. [rival.com]', items: { type: 'string' } },
618
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
619
+ },
620
+ required: ['project', 'competitors'],
621
+ },
622
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/competitors`,
623
+ method: 'POST',
624
+ body: (a) => ({ competitors: a['competitors'], execute: a['execute'] === true }),
625
+ },
626
+ {
627
+ name: 'set_prompt_cluster',
628
+ description: 'Tag one existing prompt of a project in your workspace with a cluster id (e.g. C7). The control guard refuses any page an untagged prompt cites (control_prompt_untagged), so tag the prompts that cite a page before placing it. This call is a dry run unless execute: true. Refuses tenant-zero projects (prompts_tenant_zero: clusters come from config/portfolio.json). 404 for a prompt not in the project.',
629
+ inputSchema: {
630
+ type: 'object',
631
+ properties: {
632
+ project: { type: 'string', description: 'project slug or uuid' },
633
+ prompt: { type: 'string', description: 'the prompt id' },
634
+ cluster: { type: 'string', description: 'the cluster id, e.g. C7' },
635
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
636
+ },
637
+ required: ['project', 'prompt', 'cluster'],
638
+ },
639
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/prompts/${encodeURIComponent(str(a, 'prompt'))}/cluster`,
640
+ method: 'POST',
641
+ body: (a) => ({ cluster: a['cluster'], execute: a['execute'] === true }),
642
+ },
643
+ {
644
+ name: 'set_control_cluster',
645
+ description: 'Name the held-out control cluster of a project in your workspace: the prompt cluster id (e.g. C7) whose prompts nobody treats. Placements, outreach and approval sends refuse any page those prompts cite, and fail closed with control_cluster_unconfigured until one is set. Pass cluster: null to clear it. This call is a dry run unless execute: true: without it nothing is written and the result shows the previous and would-be cluster. Refuses an id no prompt of the project carries, and tenant zero (its control cluster comes from config/portfolio.json).',
646
+ inputSchema: {
647
+ type: 'object',
648
+ properties: {
649
+ project: { type: 'string', description: 'project slug or uuid' },
650
+ cluster: { type: ['string', 'null'], description: 'the prompt cluster id, e.g. C7; null clears it (the guard fails closed again)' },
651
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
652
+ },
653
+ required: ['project', 'cluster'],
654
+ },
655
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/control-cluster`,
656
+ method: 'POST',
657
+ body: (a) => ({ cluster: a['cluster'], execute: a['execute'] === true }),
658
+ },
659
+ {
660
+ name: 'create_publish_brief',
661
+ description: 'The publish brief for one citation gap: what page to publish so the engines that skip this brand for a prompt have a page of the brand to cite. Takes a prompt (id or exact text), a market and optionally the engines, on which the brand domain must not be cited (not_a_gap otherwise). Reads the pages the engines cite, the top 10 Google Organic results and the brand\'s own pages, and returns keywords, entities, a section outline, questions, gaps, claims (each linked to a page on the brand\'s own domain) and a ready prompt for a coding agent. Costs a fixed number of credits per brief, settled on what was delivered. This call is a dry run unless execute: true: without it nothing is fetched, billed or written and the result shows the cost and the cited pages.',
662
+ inputSchema: {
663
+ type: 'object',
664
+ properties: {
665
+ project: { type: 'string', description: 'project slug or uuid' },
666
+ prompt: { type: 'string', description: 'the gap prompt: its id or its exact text' },
667
+ market: { type: 'string', description: 'market key, e.g. us-en; required on a multi-market project' },
668
+ engines: { type: 'array', items: { type: 'string' }, description: 'engine slugs; default every engine with an answer for the prompt' },
669
+ execute: { type: 'boolean', description: 'must be true to fetch and bill; otherwise dry run' },
670
+ },
671
+ required: ['project', 'prompt'],
672
+ },
673
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/briefs`,
674
+ method: 'POST',
675
+ body: (a) => ({
676
+ prompt: a['prompt'],
677
+ ...('market' in a ? { market: a['market'] } : {}),
678
+ ...('engines' in a ? { engines: a['engines'] } : {}),
679
+ execute: a['execute'] === true,
680
+ }),
681
+ },
682
+ {
683
+ name: 'run_visibility_check',
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.",
685
+ inputSchema: {
686
+ type: 'object',
687
+ properties: {
688
+ project: { type: 'string', description: 'project slug or uuid' },
689
+ engine: { type: 'string', description: 'one engine slug, e.g. chatgpt' },
690
+ max_usd: { type: 'number', description: 'lower the per-call USD ceiling; above the default is refused' },
691
+ execute: { type: 'boolean', description: 'must be true to collect and bill; otherwise dry run' },
692
+ },
693
+ required: ['project', 'engine'],
694
+ },
695
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/visibility-check`,
696
+ method: 'POST',
697
+ body: (a) => ({
698
+ engine: a['engine'],
699
+ ...('max_usd' in a ? { max_usd: a['max_usd'] } : {}),
700
+ execute: a['execute'] === true,
701
+ }),
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
+ },
716
+ {
717
+ name: 'get_page_evidence',
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.',
719
+ inputSchema: {
720
+ type: 'object',
721
+ properties: {
722
+ project: { type: 'string', description: 'project slug or uuid' },
723
+ url: { type: 'string', description: 'page URL to inspect' },
724
+ query: { type: 'string', description: 'search query' },
725
+ market: { type: 'string', description: 'market key, e.g. se-sv' },
726
+ },
727
+ required: ['project', 'url', 'query', 'market'],
728
+ },
729
+ path: (a) => {
730
+ const project = str(a, 'project');
731
+ // tools/call does not enforce inputSchema.required. The route answers 400
732
+ // without these, so refuse here and never fetch.
733
+ const url = str(a, 'url');
734
+ const searchQuery = str(a, 'query');
735
+ const market = str(a, 'market');
736
+ return `/v1/projects/${encodeURIComponent(project)}/page-evidence${query({
737
+ url,
738
+ query: searchQuery,
739
+ market,
740
+ })}`;
741
+ },
742
+ },
743
+ {
744
+ name: 'refresh_corpus',
745
+ description: 'Run the DB-only corpus staleness pass for a project: active pages past verify_interval become stale, stale pages past twice verify_interval become removed, and the result reports the due re-verification queue (due count and duePages). The RQ1-3 re-verification fetch pass is not run by this tool; it fetches no pages and makes no paid calls. This call is a dry run unless execute: true: without it nothing is written and the result describes what would change.',
746
+ inputSchema: {
747
+ type: 'object',
748
+ properties: {
749
+ project: { type: 'string', description: 'project slug or uuid' },
750
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
751
+ },
752
+ required: ['project'],
753
+ },
754
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/corpus/refresh`,
755
+ method: 'POST',
756
+ body: (a) => ({ execute: a['execute'] === true }),
757
+ },
758
+ {
759
+ name: 'process_project',
760
+ description: "Process a project's collected runs: extract citations from every run not yet extracted, build the corpus, then score the presence gap, so get_corpus, get_presence_gap and create_publish_brief have data. Scoped to the key's own workspace: another workspace's project is project_not_found. Zero provider spend: no paid search call and no page fetch; presence page fetches are check_presence's (paid, per page). This call is a dry run unless execute: true: without it nothing is written and the result lists the steps that would run and the current counts (collected and pending runs, corpus pages, opportunities, last build). Refusals: no_collections (nothing collected yet), process_running with running_id (one run per project at a time). With nothing new since the last build, execute is a no-op (noop: true) with the same result shape.",
761
+ inputSchema: {
762
+ type: 'object',
763
+ properties: {
764
+ project: { type: 'string', description: 'project slug or uuid' },
765
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
766
+ },
767
+ required: ['project'],
768
+ },
769
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/process`,
770
+ method: 'POST',
771
+ body: (a) => ({ execute: a['execute'] === true }),
772
+ },
773
+ {
774
+ name: 'check_presence',
775
+ description: "Check presence for a project's due corpus pages: fetch each page and record whether the brand appears, so get_presence_gap and create_publish_brief have data (run process_project afterwards to rescore the gap). Paid: billed in credits per page that got a verdict, reserved before the first fetch and settled after; a page that could not be read (blocked, js_required, auth_wall, an error status) gets no verdict and is not billed. max_pages is required (1 to 50, the hard cap: max_pages_above_cap); due pages past it stay due for the next call. This call is a dry run unless execute: true: without it nothing is fetched or billed and the result shows due, pages, credits and available. Refusals before any fetch: credits_exhausted, workspace_frozen, max_pages_required, invalid_max_pages, max_pages_above_cap. Scoped to the key's own workspace: another workspace's project is project_not_found. Tenant zero is refused with presence_tenant_zero.",
776
+ inputSchema: {
777
+ type: 'object',
778
+ properties: {
779
+ project: { type: 'string', description: 'project slug or uuid' },
780
+ max_pages: { type: 'number', description: 'required: at most this many due pages are fetched (1 to 50)' },
781
+ execute: { type: 'boolean', description: 'must be true to fetch and bill; otherwise dry run' },
782
+ },
783
+ required: ['project', 'max_pages'],
784
+ },
785
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/presence/check`,
786
+ method: 'POST',
787
+ body: (a) => ({ max_pages: a['max_pages'], execute: a['execute'] === true }),
788
+ },
789
+ {
790
+ name: 'get_collection_schedule',
791
+ description: "A project's weekly collection schedule, or schedule: null when it has none: engines, max_credits_per_run, enabled, who created it, and last_run (at, status ran|failed|refused|skipped, reason, job_id) once the weekly workspaces job has fired. Scoped to the key's own workspace: another workspace's project is project_not_found. Tenant zero is refused with schedule_tenant_zero (its cadence is the operator's config).",
792
+ inputSchema: projectArg,
793
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/schedule`,
794
+ },
795
+ {
796
+ name: 'set_collection_schedule',
797
+ description: "Create or update a project's weekly collection: every Monday the workspaces job collects the named engines for every active prompt and market, billed in credits, then processes the runs (as process_project). max_credits_per_run is the per-run cap: a run whose estimate exceeds it is refused and recorded in last_run, never cut down. A frozen workspace is skipped, a short one refused, both recorded. Omitted fields keep their value; a new schedule needs engines and max_credits_per_run. cadence is weekly only. This call is a dry run unless execute: true: without it nothing is written, and the result shows before, after and estimate (credits the next run needs now, and within_cap). Scoped to the key's own workspace; tenant zero is refused with schedule_tenant_zero.",
798
+ inputSchema: {
799
+ type: 'object',
800
+ properties: {
801
+ project: { type: 'string', description: 'project slug or uuid' },
802
+ engines: { type: 'array', items: { type: 'string' }, description: 'engine slugs, e.g. ["chatgpt","perplexity","google-ai-mode"]' },
803
+ max_credits_per_run: { type: 'number', description: 'integer >= 1: a run needing more is refused' },
804
+ enabled: { type: 'boolean', description: 'false pauses the schedule; default true' },
805
+ cadence: { type: 'string', description: 'weekly (the only cadence)' },
806
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
807
+ },
808
+ required: ['project'],
809
+ },
810
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/schedule`,
811
+ method: 'POST',
812
+ body: (a) => {
813
+ const out = { execute: a['execute'] === true };
814
+ for (const key of ['engines', 'max_credits_per_run', 'enabled', 'cadence'])
815
+ if (a[key] !== undefined)
816
+ out[key] = a[key];
817
+ return out;
818
+ },
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
+ },
909
+ {
910
+ name: 'create_project',
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.',
912
+ inputSchema: {
913
+ type: 'object',
914
+ properties: {
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' },
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
+ },
920
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
921
+ },
922
+ required: ['project'],
923
+ },
924
+ path: () => '/v1/projects',
925
+ method: 'POST',
926
+ body: (a) => ({ workspace: a['workspace'], project: a['project'], execute: a['execute'] === true }),
927
+ },
928
+ // Approvals (G4). An agent requests and reads; it can never grant or reject: only the operator
929
+ // CLI (`ranq approvals grant|reject`) decides, so no tool here takes a decision (D3).
930
+ {
931
+ name: 'request_approval',
932
+ description: 'Stage an outreach send for human approval. This call is a dry run unless execute: true: without it nothing is written and the result is the payload sha256. kind is outreach_send; manifest is a filled outreach manifest (version 1, project, projectId, stagedAt, items with placementId, url, ownerRouteLabel and a draft subject/body, no contact data); account_id is the outreach inbox uuid; recipients maps exactly the manifest placement ids to addresses and is hashed, never stored. One item per approval (no approve-all): a manifest with more items is invalid_approval; a NUL byte or a stagedAt that is not a real instant is invalid_manifest. Returns the approval id and payload_sha256. A human grants it outside this API; poll get_approval for status granted.',
933
+ inputSchema: {
934
+ type: 'object',
935
+ properties: {
936
+ project: { type: 'string', description: 'project slug or uuid' },
937
+ kind: { type: 'string', description: 'outreach_send' },
938
+ manifest: { type: 'object' },
939
+ account_id: { type: 'string' },
940
+ recipients: { type: 'object', description: '{ "<placementId>": "<address>" }' },
941
+ execute: { type: 'boolean', description: 'must be true to write; otherwise dry run' },
942
+ },
943
+ required: ['project', 'kind', 'manifest', 'account_id', 'recipients'],
944
+ },
945
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/approvals`,
946
+ method: 'POST',
947
+ body: (a) => ({ kind: a['kind'], manifest: a['manifest'], account_id: a['account_id'], recipients: a['recipients'], execute: a['execute'] === true }),
948
+ },
949
+ {
950
+ name: 'list_approvals',
951
+ description: 'List this project\'s approval requests, newest first (at most 200). status filters: pending | granted | rejected | expired | consumed.',
952
+ inputSchema: {
953
+ type: 'object',
954
+ properties: { project: { type: 'string', description: 'project slug or uuid' }, status: { type: 'string' } },
955
+ required: ['project'],
956
+ },
957
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/approvals${query({ status: a['status'] })}`,
958
+ },
959
+ {
960
+ name: 'get_approval',
961
+ description: 'One approval request: status (pending | granted | rejected | expired | consumed), payload, payload_sha256, who decided and when. approval_not_found for an id outside this workspace.',
962
+ inputSchema: {
963
+ type: 'object',
964
+ properties: { project: { type: 'string', description: 'project slug or uuid' }, id: { type: 'string' } },
965
+ required: ['project', 'id'],
966
+ },
967
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/approvals/${encodeURIComponent(str(a, 'id'))}`,
968
+ },
969
+ {
970
+ name: 'send_approved',
971
+ description: 'Send a granted approval. This call is a dry run unless execute: true: without it every check runs and nothing is consumed or sent. sha256 must equal the approval payload_sha256 and recipients must hash to its recipients_sha256. Refused with approval_pending (not yet granted), approval_not_granted (rejected), approval_expired, approval_consumed (each approval sends at most once) or approval_sha_mismatch.',
972
+ inputSchema: {
973
+ type: 'object',
974
+ properties: {
975
+ project: { type: 'string', description: 'project slug or uuid' },
976
+ id: { type: 'string' },
977
+ sha256: { type: 'string' },
978
+ recipients: { type: 'object', description: '{ "<placementId>": "<address>" }' },
979
+ execute: { type: 'boolean', description: 'must be true to send; otherwise dry run' },
980
+ },
981
+ required: ['project', 'id', 'sha256', 'recipients'],
982
+ },
983
+ path: (a) => `/v1/projects/${encodeURIComponent(str(a, 'project'))}/approvals/${encodeURIComponent(str(a, 'id'))}/send`,
984
+ method: 'POST',
985
+ body: (a) => ({ sha256: a['sha256'], recipients: a['recipients'], execute: a['execute'] === true }),
986
+ },
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
+ }