@shyftai/ranq 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Typed client for the REST API (#14, feat/i14-rest-mcp-v3). Payload types
3
+ * mirror that branch's src/api/queries.ts handler output exactly:
4
+ * GET /v1/projects -> listProjects
5
+ * GET /v1/projects/:project -> getProject
6
+ * GET /v1/projects/:project/visibility -> getVisibility
7
+ * GET /v1/projects/:project/visibility/history -> getVisibilityHistory
8
+ * GET /v1/projects/:project/presence-gap -> getPresenceGap
9
+ * GET /v1/projects/:project/corpus -> getCorpus
10
+ * There is no runs route in #107, so no run-history method exists here.
11
+ * The typed methods are reads; `call` is the one generic route for `ranq api <tool>`, whose
12
+ * project-write POST tools stay dry runs unless the caller sends execute: true (checkout tools
13
+ * create a session directly; start_scan takes mode). `run` is refused client-side.
14
+ */
15
+ import { restFetch, stripTrailingSlash } from "./rest.js";
16
+ export class MissingApiConfigError extends Error {
17
+ name = 'MissingApiConfigError';
18
+ constructor(message = 'MissingApiConfigError: RANQ_API_URL and RANQ_API_KEY are required (or --api-url/--api-key)') {
19
+ super(message);
20
+ }
21
+ }
22
+ export class ApiError extends Error {
23
+ name = 'ApiError';
24
+ status;
25
+ code;
26
+ constructor(status, message, code) { super(message); this.status = status; this.code = code; }
27
+ }
28
+ export class InsecureApiUrlError extends Error {
29
+ name = 'InsecureApiUrlError';
30
+ constructor(detail) {
31
+ super(`InsecureApiUrlError: RANQ_API_URL / --api-url ${detail}; refusing to send the API key`);
32
+ }
33
+ }
34
+ export class ApiUnreachableError extends Error {
35
+ name = 'ApiUnreachableError';
36
+ constructor(cause) {
37
+ super('ApiUnreachableError: could not reach the API', cause === undefined ? undefined : { cause });
38
+ }
39
+ }
40
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
41
+ export function isHttpRedirectStatus(status) { return REDIRECT_STATUSES.has(status); }
42
+ export class ApiRedirectRefusedError extends Error {
43
+ name = 'ApiRedirectRefusedError';
44
+ status;
45
+ constructor(status) {
46
+ super(isHttpRedirectStatus(status)
47
+ ? `ApiRedirectRefusedError: the API answered with an HTTP ${status} redirect, which is refused (the API key must never follow a redirect)`
48
+ : `the API answered with an unexpected 3xx status (HTTP ${status}), which is refused`);
49
+ this.status = status;
50
+ }
51
+ }
52
+ export class ApiPayloadError extends Error {
53
+ name = 'ApiPayloadError';
54
+ constructor(detail) { super(`ApiPayloadError: ${detail}`); }
55
+ }
56
+ /** #107 caps list endpoints at 100 rows unless an explicit limit is given. */
57
+ export const API_LIST_LIMIT = 100;
58
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
59
+ function safeOrigin(url) { return `${url.protocol}//${url.host}`; }
60
+ export function assertSecureBaseUrl(baseUrl) {
61
+ let url;
62
+ try {
63
+ url = new URL(baseUrl);
64
+ }
65
+ catch {
66
+ throw new InsecureApiUrlError('is not a parseable URL');
67
+ }
68
+ // Credentials in the URL are never accepted and never echoed back.
69
+ if (url.username || url.password)
70
+ throw new InsecureApiUrlError(`must not contain a username or password (got ${safeOrigin(url)})`);
71
+ if (url.protocol === 'https:')
72
+ return;
73
+ if (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))
74
+ return;
75
+ throw new InsecureApiUrlError(`must use https unless the host is loopback (got ${safeOrigin(url)})`);
76
+ }
77
+ function listQuery(opts = {}) {
78
+ const params = new URLSearchParams();
79
+ if (opts.state !== undefined)
80
+ params.set('state', opts.state);
81
+ if (opts.limit !== undefined)
82
+ params.set('limit', String(opts.limit));
83
+ if (opts.market !== undefined)
84
+ params.set('market', opts.market);
85
+ const qs = params.toString();
86
+ return qs ? `?${qs}` : '';
87
+ }
88
+ function isRec(v) { return typeof v === 'object' && v !== null && !Array.isArray(v); }
89
+ function isStr(v) { return typeof v === 'string'; }
90
+ function isNum(v) { return typeof v === 'number' && Number.isFinite(v); }
91
+ function isBool(v) { return typeof v === 'boolean'; }
92
+ function isNullableStr(v) { return v === null || typeof v === 'string'; }
93
+ function isNullableNum(v) { return v === null || isNum(v); }
94
+ function isStrArr(v) { return Array.isArray(v) && v.every(isStr); }
95
+ function isProjectSummary(v) {
96
+ return isRec(v) && isStr(v.id) && isStr(v.slug) && isStr(v.name) && isStr(v.domain) && isStr(v.category)
97
+ && isNullableStr(v.entityDescription) && isStrArr(v.brandAliases) && isStrArr(v.competitorDomains)
98
+ && isBool(v.active) && isNullableStr(v.createdAt) && isNullableStr(v.updatedAt);
99
+ }
100
+ function isPresenceRate(v) {
101
+ return isRec(v) && isNum(v.definitionVersion) && isNum(v.corpusPages) && isNum(v.checkedPages) && isNum(v.presentPages)
102
+ && isNum(v.ambiguousPages) && isNum(v.absentPages) && isNum(v.uncheckedPages) && isNullableNum(v.rate);
103
+ }
104
+ function isSnapshotPoint(v) {
105
+ return isRec(v) && isStr(v.engine) && isStr(v.promptType) && isNum(v.runs) && isNum(v.visible) && isNullableNum(v.rate) && isNullableStr(v.lastRunAt);
106
+ }
107
+ function isHistoryPoint(v) {
108
+ return isRec(v) && isStr(v.weekStart) && isStr(v.engine) && isStr(v.promptType) && isNum(v.runs) && isNum(v.visible) && isNullableNum(v.rate);
109
+ }
110
+ function isGapRow(v) {
111
+ return isRec(v) && isStr(v.corpusPageId) && isStr(v.url) && isStr(v.domain) && isStr(v.pageType) && isStr(v.state)
112
+ && isNum(v.citationFrequency) && isNum(v.score) && isStr(v.actionability) && isNullableStr(v.lastCheckedAt);
113
+ }
114
+ function isCorpusPage(v) {
115
+ return isRec(v) && isNum(v.rank) && isStr(v.url) && isStr(v.domain) && isStr(v.pageType) && isStr(v.state)
116
+ && isNum(v.citationRuns) && isNullableStr(v.lastCitedAt) && isNullableStr(v.discoveredAt) && isNullableStr(v.enteredAt)
117
+ && isNullableStr(v.lastVerifiedAt) && isBool(v.due);
118
+ }
119
+ function isMentionSnapshot(v) {
120
+ return isRec(v) && isStr(v.market) && isStr(v.platform) && isStr(v.keyword) && isStr(v.kind)
121
+ && isNullableStr(v.target) && isNullableNum(v.mentionsCount) && isStr(v.status);
122
+ }
123
+ function isPromptDemand(v) {
124
+ return isRec(v) && isStr(v.market) && isStr(v.promptId) && isStr(v.collectedOn)
125
+ && isNullableNum(v.aiSearchVolume) && isStr(v.status);
126
+ }
127
+ export class RanqClient {
128
+ #baseUrl;
129
+ #apiKey;
130
+ #fetch;
131
+ constructor(opts) {
132
+ if (!opts.baseUrl || !opts.apiKey)
133
+ throw new MissingApiConfigError();
134
+ assertSecureBaseUrl(opts.baseUrl);
135
+ this.#baseUrl = stripTrailingSlash(opts.baseUrl);
136
+ this.#apiKey = opts.apiKey;
137
+ this.#fetch = opts.fetchImpl ?? fetch;
138
+ }
139
+ static fromEnv(env, overrides = {}) {
140
+ const baseUrl = overrides.baseUrl ?? env.RANQ_API_URL;
141
+ const apiKey = overrides.apiKey ?? env.RANQ_API_KEY;
142
+ if (!baseUrl || !apiKey)
143
+ throw new MissingApiConfigError();
144
+ return new RanqClient({ baseUrl, apiKey });
145
+ }
146
+ async #get(path) { return this.call('GET', path); }
147
+ /**
148
+ * Any REST route, for `ranq api <tool>` (src/cli/api-tool.ts): same key, URL and redirect
149
+ * guards as the typed reads. The payload is returned as the API sent it; the API owns its shape.
150
+ */
151
+ async call(method, path, init = {}) {
152
+ if (!this.#apiKey)
153
+ throw new MissingApiConfigError();
154
+ assertSecureBaseUrl(this.#baseUrl);
155
+ let res;
156
+ try {
157
+ // Structural redirect refusal: never follow, never sniff error text.
158
+ // With redirect:'manual' a 3xx comes back as a response, not a throw,
159
+ // so the status check below is the only redirect path.
160
+ res = await restFetch({ baseUrl: this.#baseUrl, apiKey: this.#apiKey, fetchImpl: this.#fetch }, path, {
161
+ method,
162
+ headers: { accept: 'application/json', ...init.headers },
163
+ body: init.body,
164
+ redirect: 'manual',
165
+ });
166
+ }
167
+ catch (error) {
168
+ throw new ApiUnreachableError(error);
169
+ }
170
+ if (res.status >= 300 && res.status < 400)
171
+ throw new ApiRedirectRefusedError(res.status);
172
+ if (!res.ok) {
173
+ let code;
174
+ try {
175
+ const body = (await res.json());
176
+ if (typeof body?.error === 'string')
177
+ code = body.error;
178
+ }
179
+ 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);
181
+ }
182
+ try {
183
+ return await res.json();
184
+ }
185
+ catch {
186
+ throw new ApiPayloadError(`${method} ${path} returned a body that is not valid JSON`);
187
+ }
188
+ }
189
+ #shape(data, path, ok) {
190
+ if (typeof data !== 'object' || data === null || !ok(data)) {
191
+ throw new ApiPayloadError(`GET ${path} returned an unexpected payload shape`);
192
+ }
193
+ return data;
194
+ }
195
+ async listProjects() {
196
+ const path = '/v1/projects';
197
+ return this.#shape(await this.#get(path), path, (d) => Array.isArray(d.projects) && d.projects.every(isProjectSummary));
198
+ }
199
+ async getProject(project) {
200
+ const path = `/v1/projects/${encodeURIComponent(project)}`;
201
+ return this.#shape(await this.#get(path), path, (d) => isProjectSummary(d.project) && isPresenceRate(d.visibility) && isNum(d.corpusPages) && isNullableStr(d.lastRunAt));
202
+ }
203
+ async getVisibility(project) {
204
+ const path = `/v1/projects/${encodeURIComponent(project)}/visibility`;
205
+ return this.#shape(await this.#get(path), path, (d) => typeof d.project === 'string' && Array.isArray(d.snapshot) && d.snapshot.every(isSnapshotPoint) && isPresenceRate(d.presence));
206
+ }
207
+ async getVisibilityHistory(project) {
208
+ const path = `/v1/projects/${encodeURIComponent(project)}/visibility/history`;
209
+ return this.#shape(await this.#get(path), path, (d) => typeof d.project === 'string' && Array.isArray(d.history) && d.history.every(isHistoryPoint));
210
+ }
211
+ async getPresenceGap(project, opts = {}) {
212
+ const path = `/v1/projects/${encodeURIComponent(project)}/presence-gap${listQuery({ limit: opts.limit, market: opts.market })}`;
213
+ return this.#shape(await this.#get(path), path, (d) => typeof d.project === 'string' && isNum(d.definitionVersion) && isNum(d.uncheckedPages) && Array.isArray(d.gaps) && d.gaps.every(isGapRow));
214
+ }
215
+ async getCorpus(project, opts = {}) {
216
+ const path = `/v1/projects/${encodeURIComponent(project)}/corpus${listQuery(opts)}`;
217
+ return this.#shape(await this.#get(path), path, (d) => typeof d.project === 'string' && Array.isArray(d.pages) && d.pages.every(isCorpusPage));
218
+ }
219
+ async getMentions(project, opts = {}) {
220
+ const path = `/v1/projects/${encodeURIComponent(project)}/mentions${listQuery({ market: opts.market })}`;
221
+ return this.#shape(await this.#get(path), path, (d) => typeof d.project === 'string' && typeof d.market === 'string' && Array.isArray(d.snapshots) && d.snapshots.every(isMentionSnapshot));
222
+ }
223
+ async getDemand(project, opts = {}) {
224
+ const path = `/v1/projects/${encodeURIComponent(project)}/demand${listQuery({ market: opts.market })}`;
225
+ return this.#shape(await this.#get(path), path, (d) => typeof d.project === 'string' && typeof d.market === 'string' && Array.isArray(d.demand) && d.demand.every(isPromptDemand));
226
+ }
227
+ }
@@ -0,0 +1,16 @@
1
+ export const stripTrailingSlash = (baseUrl) => baseUrl.replace(/\/$/, '');
2
+ export function restFetch(transport, path, init = {}) {
3
+ const headers = { authorization: `Bearer ${transport.apiKey}`, ...init.headers };
4
+ let body;
5
+ if (init.body !== undefined) {
6
+ headers['content-type'] = 'application/json';
7
+ body = JSON.stringify(init.body);
8
+ }
9
+ const doFetch = transport.fetchImpl ?? fetch;
10
+ return doFetch(`${stripTrailingSlash(transport.baseUrl)}${path}`, {
11
+ method: init.method ?? 'GET',
12
+ headers,
13
+ body,
14
+ ...(init.redirect !== undefined ? { redirect: init.redirect } : {}),
15
+ });
16
+ }
@@ -0,0 +1,154 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { restFetch } from "../client/rest.js";
3
+ import { TOOLS } from "./tools.js";
4
+ import { CLIENT_VERSION } from "../version.js";
5
+ export const AGENT_ENV = 'RANQ_AGENT';
6
+ const AGENT_SLUG_RE = /^[a-z0-9-]{1,40}$/;
7
+ export const isValidAgentSlug = (value) => typeof value === 'string' && AGENT_SLUG_RE.test(value);
8
+ /** Validate `RANQ_AGENT` at startup: unset is allowed (reads still work, write
9
+ * tools refuse per call); a set-but-invalid value refuses startup. */
10
+ export function agentFromEnv(env) {
11
+ const raw = env[AGENT_ENV];
12
+ if (raw === undefined || raw === '')
13
+ return undefined;
14
+ if (!isValidAgentSlug(raw)) {
15
+ throw new Error(`${AGENT_ENV} must be a slug matching [a-z0-9-]{1,40}, got an invalid value`);
16
+ }
17
+ return raw;
18
+ }
19
+ /** The revision the HTTP transport implements (src/mcp/http.ts); first is the answer to an unknown version. */
20
+ export const PROTOCOL_VERSIONS = ['2025-03-26', '2024-11-05'];
21
+ const PROTOCOL_VERSION = PROTOCOL_VERSIONS[0];
22
+ export function createMcpServer(deps) {
23
+ if (deps.agent !== undefined && !isValidAgentSlug(deps.agent)) {
24
+ throw new Error(deps.hosted
25
+ ? 'x-ranq-agent must be a slug matching [a-z0-9-]{1,40}'
26
+ : `${AGENT_ENV} must be a slug matching [a-z0-9-]{1,40}`);
27
+ }
28
+ async function callRest(path, init = {}) {
29
+ const headers = {};
30
+ if (init.write) {
31
+ if (!deps.agent) {
32
+ throw new Error(deps.hosted
33
+ ? 'x-ranq-agent header is required: write tools require the x-ranq-agent header (agent slug) so the placement ledger can record actor agent:<slug>'
34
+ : `${AGENT_ENV} is not set: write tools require ${AGENT_ENV} (agent slug) so the placement ledger can record actor agent:<slug>`);
35
+ }
36
+ headers['x-ranq-agent'] = deps.agent;
37
+ }
38
+ const res = await restFetch({ baseUrl: deps.baseUrl, apiKey: deps.apiKey ?? '', fetchImpl: deps.fetch }, path, {
39
+ method: init.method,
40
+ headers,
41
+ body: init.body,
42
+ });
43
+ const parsed = await res.json().catch(() => null);
44
+ if (!res.ok) {
45
+ const code = parsed && typeof parsed === 'object' && 'error' in parsed ? String(parsed.error) : res.statusText;
46
+ throw new Error(`ranq API ${res.status}: ${code}`);
47
+ }
48
+ return parsed;
49
+ }
50
+ return {
51
+ async handleMessage(message) {
52
+ const { id, method, params } = message;
53
+ const reply = (result) => ({ jsonrpc: '2.0', id: id ?? null, result });
54
+ const fail = (code, text) => ({
55
+ jsonrpc: '2.0',
56
+ id: id ?? null,
57
+ error: { code, message: text },
58
+ });
59
+ if (id === undefined)
60
+ return null; // notification: nothing to answer
61
+ switch (method) {
62
+ case 'initialize':
63
+ // MCP lifecycle: echo the client's version when supported, else answer ours
64
+ return reply({
65
+ protocolVersion: PROTOCOL_VERSIONS.includes(params?.['protocolVersion'])
66
+ ? params?.['protocolVersion']
67
+ : PROTOCOL_VERSION,
68
+ capabilities: { tools: {} },
69
+ serverInfo: { name: 'ranq', version: CLIENT_VERSION },
70
+ });
71
+ case 'ping':
72
+ return reply({});
73
+ case 'tools/list':
74
+ return reply({
75
+ tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
76
+ });
77
+ case 'tools/call': {
78
+ const name = params?.['name'];
79
+ const tool = TOOLS.find((t) => t.name === name);
80
+ if (!tool)
81
+ return fail(-32602, `unknown tool: ${String(name)}`);
82
+ const args = (params?.['arguments'] ?? {});
83
+ try {
84
+ const isWrite = tool.method === 'POST';
85
+ const data = await callRest(tool.path(args), {
86
+ method: tool.method ?? 'GET',
87
+ body: tool.body ? tool.body(args) : undefined,
88
+ write: isWrite,
89
+ });
90
+ return reply({ content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data });
91
+ }
92
+ catch (error) {
93
+ return reply({
94
+ content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }],
95
+ isError: true,
96
+ });
97
+ }
98
+ }
99
+ default:
100
+ return fail(-32601, `method not found: ${String(method)}`);
101
+ }
102
+ },
103
+ };
104
+ }
105
+ export function createMcpClient(server) {
106
+ let nextId = 1;
107
+ async function request(method, params) {
108
+ const response = await server.handleMessage({ jsonrpc: '2.0', id: nextId++, method, params });
109
+ if (!response)
110
+ throw new Error(`no response to ${method}`);
111
+ if (response['error'])
112
+ throw new Error(`MCP ${method}: ${JSON.stringify(response['error'])}`);
113
+ return response['result'];
114
+ }
115
+ return {
116
+ async initialize() {
117
+ await request('initialize', {
118
+ protocolVersion: PROTOCOL_VERSION,
119
+ capabilities: {},
120
+ clientInfo: { name: 'ranq-test-client', version: '0.0.0' },
121
+ });
122
+ },
123
+ async listTools() {
124
+ const result = await request('tools/list');
125
+ return result.tools;
126
+ },
127
+ async callTool(name, args) {
128
+ const result = await request('tools/call', { name, arguments: args });
129
+ if (result.isError)
130
+ throw new Error(result.content?.[0]?.text ?? `tool ${name} failed`);
131
+ return result.structuredContent;
132
+ },
133
+ };
134
+ }
135
+ /** Newline-delimited JSON-RPC over stdio, the MCP stdio transport. Streams are
136
+ * injectable so tests can drive the real transport without a child process. */
137
+ export function runMcpStdio(server, input = process.stdin, output = process.stdout) {
138
+ const lines = createInterface({ input });
139
+ lines.on('line', (line) => {
140
+ if (!line.trim())
141
+ return;
142
+ void (async () => {
143
+ let response;
144
+ try {
145
+ response = await server.handleMessage(JSON.parse(line));
146
+ }
147
+ catch {
148
+ response = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } };
149
+ }
150
+ if (response)
151
+ output.write(`${JSON.stringify(response)}\n`);
152
+ })();
153
+ });
154
+ }