apinoa-mcp 0.1.1 → 0.2.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 +55 -24
- package/dist/api.js +1 -1
- package/dist/catalog.snapshot.js +6 -6
- package/dist/code/docs.d.ts +32 -0
- package/dist/code/docs.js +216 -0
- package/dist/code/sandbox.d.ts +50 -0
- package/dist/code/sandbox.js +265 -0
- package/dist/legacy.d.ts +10 -0
- package/dist/legacy.js +245 -0
- package/dist/sandbox/prelude.d.ts +8 -0
- package/dist/sandbox/prelude.js +304 -0
- package/dist/schema.snapshot.d.ts +2 -0
- package/dist/schema.snapshot.js +77 -0
- package/dist/server.d.ts +18 -8
- package/dist/server.js +92 -241
- package/package.json +22 -6
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs code from `execute` in a Deno subprocess: type-checked against the generated declarations first, then
|
|
3
|
+
* run with network access to the API host only, read and write access to the data directory only, no
|
|
4
|
+
* environment, no subprocesses. The API key reaches it on stdin, never through the environment or the code.
|
|
5
|
+
*/
|
|
6
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import { homedir, tmpdir } from "node:os";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
14
|
+
import { download } from "../api.js";
|
|
15
|
+
// Lines of main.ts above the user's code: line numbers in errors are shifted back by this many.
|
|
16
|
+
const HEADER_LINES = 4;
|
|
17
|
+
export function findDeno(explicit) {
|
|
18
|
+
if (explicit)
|
|
19
|
+
return explicit;
|
|
20
|
+
if (process.env.APINOA_MCP_DENO)
|
|
21
|
+
return process.env.APINOA_MCP_DENO;
|
|
22
|
+
try {
|
|
23
|
+
const require = createRequire(import.meta.url);
|
|
24
|
+
const dir = dirname(require.resolve("deno/package.json"));
|
|
25
|
+
const exe = join(dir, process.platform === "win32" ? "deno.exe" : "deno");
|
|
26
|
+
if (existsSync(exe))
|
|
27
|
+
return exe;
|
|
28
|
+
// The package's postinstall did not run (npm --ignore-scripts): its own installer finds the binary.
|
|
29
|
+
return require("deno/install_api.cjs").runInstall();
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return "deno";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Whether the deno at `path` runs. */
|
|
36
|
+
export function denoRuns(path) {
|
|
37
|
+
try {
|
|
38
|
+
return spawnSync(path, ["--version"], { stdio: "ignore", timeout: 15_000 }).status === 0;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export class Sandbox {
|
|
45
|
+
opts;
|
|
46
|
+
declarations;
|
|
47
|
+
operations;
|
|
48
|
+
deno;
|
|
49
|
+
dataDir;
|
|
50
|
+
runtimeDir;
|
|
51
|
+
prelude;
|
|
52
|
+
host;
|
|
53
|
+
prepared;
|
|
54
|
+
constructor(opts, declarations, operations) {
|
|
55
|
+
this.opts = opts;
|
|
56
|
+
this.declarations = declarations;
|
|
57
|
+
this.operations = operations;
|
|
58
|
+
this.deno = findDeno(opts.deno);
|
|
59
|
+
this.dataDir = opts.dataDir ?? process.env.APINOA_MCP_DATA_DIR ?? join(homedir(), ".apinoa-mcp");
|
|
60
|
+
const hash = createHash("sha256").update(declarations).digest("hex").slice(0, 12);
|
|
61
|
+
this.runtimeDir = join(tmpdir(), `apinoa-mcp-${hash}`);
|
|
62
|
+
this.prelude = join(dirname(fileURLToPath(import.meta.url)), "..", "sandbox", "prelude.js");
|
|
63
|
+
const u = new URL(opts.api.baseUrl);
|
|
64
|
+
this.host = u.host;
|
|
65
|
+
}
|
|
66
|
+
prepare() {
|
|
67
|
+
return (this.prepared ??= (async () => {
|
|
68
|
+
await mkdir(this.runtimeDir, { recursive: true });
|
|
69
|
+
await writeFile(join(this.runtimeDir, "apinoa.d.ts"), this.declarations);
|
|
70
|
+
// Not strict: the check is there to catch methods, parameters and fields that do not exist, not to make
|
|
71
|
+
// the model prove every optional field is present.
|
|
72
|
+
await writeFile(join(this.runtimeDir, "deno.json"), JSON.stringify({ compilerOptions: { strict: false, noImplicitAny: false } }));
|
|
73
|
+
for (const d of ["cache", "store", "files"])
|
|
74
|
+
await mkdir(join(this.dataDir, d), { recursive: true });
|
|
75
|
+
await pruneCache(join(this.dataDir, "cache"), this.cacheTtlMs);
|
|
76
|
+
})());
|
|
77
|
+
}
|
|
78
|
+
get cacheTtlMs() {
|
|
79
|
+
return this.opts.cacheTtlMs ?? Number(process.env.APINOA_MCP_CACHE_TTL_S ?? 600) * 1000;
|
|
80
|
+
}
|
|
81
|
+
async run(code, budget, timeoutMs, onProgress) {
|
|
82
|
+
await this.prepare();
|
|
83
|
+
const runDir = await mkdtemp(join(tmpdir(), "apinoa-run-"));
|
|
84
|
+
const nonce = randomBytes(9).toString("hex");
|
|
85
|
+
const main = [
|
|
86
|
+
`/// <reference types="${pathToFileURL(join(this.runtimeDir, "apinoa.d.ts")).href}" />`,
|
|
87
|
+
`// @ts-ignore: the runtime is plain JavaScript`,
|
|
88
|
+
`import { __run } from "${pathToFileURL(this.prelude).href}";`,
|
|
89
|
+
`await __run(async () => {`,
|
|
90
|
+
code,
|
|
91
|
+
`});`,
|
|
92
|
+
"",
|
|
93
|
+
].join("\n");
|
|
94
|
+
await writeFile(join(runDir, "main.ts"), main);
|
|
95
|
+
const args = [
|
|
96
|
+
"run", "--check", "--quiet", "--no-prompt", "--no-remote", "--no-npm",
|
|
97
|
+
`--config=${join(this.runtimeDir, "deno.json")}`,
|
|
98
|
+
`--allow-net=${this.host}`,
|
|
99
|
+
`--allow-read=${this.dataDir}`,
|
|
100
|
+
`--allow-write=${this.dataDir}`,
|
|
101
|
+
"--v8-flags=--max-old-space-size=1024",
|
|
102
|
+
join(runDir, "main.ts"),
|
|
103
|
+
];
|
|
104
|
+
const child = spawn(this.deno, args, {
|
|
105
|
+
cwd: runDir,
|
|
106
|
+
env: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? homedir(), NO_COLOR: "1", ...(process.env.DENO_DIR ? { DENO_DIR: process.env.DENO_DIR } : {}) },
|
|
107
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
108
|
+
});
|
|
109
|
+
child.stdin.write(JSON.stringify({
|
|
110
|
+
key: this.opts.api.apiKey ?? "",
|
|
111
|
+
baseUrl: this.opts.api.baseUrl,
|
|
112
|
+
budget,
|
|
113
|
+
concurrency: this.opts.concurrency ?? Number(process.env.APINOA_MCP_CONCURRENCY ?? 16),
|
|
114
|
+
cacheTtlMs: this.cacheTtlMs,
|
|
115
|
+
dataDir: this.dataDir,
|
|
116
|
+
nonce,
|
|
117
|
+
userAgent: this.opts.userAgent,
|
|
118
|
+
operations: this.operations,
|
|
119
|
+
}) + "\n");
|
|
120
|
+
const maxOut = this.opts.maxOutputChars ?? Number(process.env.APINOA_MCP_MAX_OUTPUT ?? 40_000);
|
|
121
|
+
let printed = "";
|
|
122
|
+
let printedTotal = 0;
|
|
123
|
+
let stderr = "";
|
|
124
|
+
let done;
|
|
125
|
+
let lastStats = { calls: 0, cached: 0, units: 0, failed: 0, errors: [] };
|
|
126
|
+
let buf = "";
|
|
127
|
+
const marker = (kind) => `@@APINOA_${kind}_${nonce}@@ `;
|
|
128
|
+
const onLine = (line) => {
|
|
129
|
+
if (line.startsWith(marker("DONE"))) {
|
|
130
|
+
done = JSON.parse(line.slice(marker("DONE").length));
|
|
131
|
+
}
|
|
132
|
+
else if (line.startsWith(marker("PROGRESS"))) {
|
|
133
|
+
lastStats = JSON.parse(line.slice(marker("PROGRESS").length));
|
|
134
|
+
onProgress?.(lastStats);
|
|
135
|
+
}
|
|
136
|
+
else if (line.startsWith(marker("RPC"))) {
|
|
137
|
+
void this.answer(JSON.parse(line.slice(marker("RPC").length)), (reply) => {
|
|
138
|
+
if (!child.stdin.destroyed)
|
|
139
|
+
child.stdin.write(JSON.stringify(reply) + "\n");
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
printedTotal += line.length + 1;
|
|
144
|
+
if (printed.length < maxOut)
|
|
145
|
+
printed += line + "\n";
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
child.stdout.setEncoding("utf8");
|
|
149
|
+
child.stdout.on("data", (chunk) => {
|
|
150
|
+
buf += chunk;
|
|
151
|
+
let i;
|
|
152
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
153
|
+
onLine(buf.slice(0, i));
|
|
154
|
+
buf = buf.slice(i + 1);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
child.stderr.setEncoding("utf8");
|
|
158
|
+
child.stderr.on("data", (chunk) => {
|
|
159
|
+
if (stderr.length < 20_000)
|
|
160
|
+
stderr += chunk;
|
|
161
|
+
});
|
|
162
|
+
let timedOut = false;
|
|
163
|
+
const timer = setTimeout(() => {
|
|
164
|
+
timedOut = true;
|
|
165
|
+
child.kill("SIGKILL");
|
|
166
|
+
}, timeoutMs);
|
|
167
|
+
const started = Date.now();
|
|
168
|
+
const exit = await new Promise((resolve) => {
|
|
169
|
+
child.on("close", (c) => resolve(c));
|
|
170
|
+
child.on("error", (e) => {
|
|
171
|
+
stderr += `\n${e.message}`;
|
|
172
|
+
resolve(-1);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
if (buf)
|
|
177
|
+
onLine(buf);
|
|
178
|
+
await rm(runDir, { recursive: true, force: true });
|
|
179
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(1);
|
|
180
|
+
if (exit === -1 && /ENOENT/.test(stderr)) {
|
|
181
|
+
return fail(`Code mode needs Deno, and none was found (looked for ${this.deno}). Install it (npm i -g deno, or https://deno.com) or set APINOA_MCP_DENO to its path.`, lastStats);
|
|
182
|
+
}
|
|
183
|
+
const stats = done?.stats ?? lastStats;
|
|
184
|
+
const usage = usageLine(stats, budget, seconds);
|
|
185
|
+
const out = clip(printed.replace(/\n+$/, ""), printedTotal, maxOut);
|
|
186
|
+
if (!done) {
|
|
187
|
+
const typeErrors = typeCheckErrors(stderr);
|
|
188
|
+
if (typeErrors)
|
|
189
|
+
return fail(`The code did not type-check, so nothing ran and nothing was billed:\n${typeErrors}\n\nsearch_docs shows each call's parameters and the fields it returns.`, stats);
|
|
190
|
+
if (timedOut)
|
|
191
|
+
return fail(`The run was stopped after ${Math.round(timeoutMs / 1000)} s.${out ? `\n\nPrinted before it stopped:\n${out}` : ""}\n\n${usage}\nFor long jobs: keep each run shorter (fewer items, or store.save progress and continue in another run; cached answers are free).`, stats);
|
|
192
|
+
return fail(`The run failed: ${cleanError(stderr) || `exit code ${exit}`}${out ? `\n\nPrinted:\n${out}` : ""}\n\n${usage}`, stats);
|
|
193
|
+
}
|
|
194
|
+
if (!done.ok) {
|
|
195
|
+
const where = lineOf(done.stack);
|
|
196
|
+
return fail(`Error${where ? ` (line ${where})` : ""}: ${done.error}${out ? `\n\nPrinted before the error:\n${out}` : ""}\n\n${usage}`, stats);
|
|
197
|
+
}
|
|
198
|
+
const result = done.result === null || done.result === undefined ? "" : JSON.stringify(done.result, null, 1);
|
|
199
|
+
const shown = clip(result, result.length, Math.max(2000, maxOut - out.length));
|
|
200
|
+
const parts = [out && `Printed:\n${out}`, shown && `Returned:\n${shown}`, usage].filter(Boolean);
|
|
201
|
+
return { ok: true, text: parts.join("\n\n"), stats };
|
|
202
|
+
}
|
|
203
|
+
/** A request from the sandbox: only the image download image-search needs. */
|
|
204
|
+
async answer(req, reply) {
|
|
205
|
+
if (req.method !== "download" || typeof req.url !== "string")
|
|
206
|
+
return reply({ id: req.id, ok: false, error: `unknown request ${req.method}` });
|
|
207
|
+
try {
|
|
208
|
+
const img = await download(this.opts.api, req.url);
|
|
209
|
+
if (!img.contentType.startsWith("image/"))
|
|
210
|
+
throw new Error(`the URL is ${img.contentType}, not an image`);
|
|
211
|
+
reply({ id: req.id, ok: true, contentType: img.contentType, data: Buffer.from(img.bytes).toString("base64") });
|
|
212
|
+
}
|
|
213
|
+
catch (e) {
|
|
214
|
+
reply({ id: req.id, ok: false, error: e.message.replace(/^[A-Z_]+: /, "") });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function fail(text, stats) {
|
|
219
|
+
return { ok: false, text, stats };
|
|
220
|
+
}
|
|
221
|
+
function usageLine(s, budget, seconds) {
|
|
222
|
+
const errs = s.failed ? `, ${s.failed} failed (${s.errors.slice(0, 3).join("; ")})` : "";
|
|
223
|
+
return `[apinoa: ${s.calls} call${s.calls === 1 ? "" : "s"}${s.cached ? ` + ${s.cached} from cache` : ""}, ${s.units} of ${budget} units ($${(s.units / 1000).toFixed(3)}), ${seconds} s${errs}]`;
|
|
224
|
+
}
|
|
225
|
+
function clip(text, total, max) {
|
|
226
|
+
if (text.length <= max && total <= max + 1)
|
|
227
|
+
return text;
|
|
228
|
+
return `${text.slice(0, max)}\n…[cut: ${total} characters, ${max} shown. Return or print less: aggregate in the code, or store.save the full data and return a summary]`;
|
|
229
|
+
}
|
|
230
|
+
/** Deno's type errors, with line numbers counted in the user's code. */
|
|
231
|
+
export function typeCheckErrors(stderr) {
|
|
232
|
+
const clean = stderr.replace(/\x1b\[[0-9;]*m/g, "");
|
|
233
|
+
if (!/TS\d+ \[ERROR\]/.test(clean))
|
|
234
|
+
return "";
|
|
235
|
+
const errors = [];
|
|
236
|
+
const re = /TS(\d+) \[ERROR\]: ([\s\S]*?)\n\s+at [^\n]*main\.ts:(\d+):(\d+)/g;
|
|
237
|
+
let m;
|
|
238
|
+
while ((m = re.exec(clean)) && errors.length < 10) {
|
|
239
|
+
const line = Number(m[3]) - HEADER_LINES;
|
|
240
|
+
const msg = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !/^\d+\s*\|/.test(l) && !/^~+$/.test(l) && !/^\^/.test(l)).join(" ");
|
|
241
|
+
errors.push(`- line ${line}: ${msg} (TS${m[1]})`);
|
|
242
|
+
}
|
|
243
|
+
return errors.length ? errors.join("\n") : clean.slice(0, 2000);
|
|
244
|
+
}
|
|
245
|
+
function lineOf(stack) {
|
|
246
|
+
const m = /main\.ts:(\d+):\d+/.exec(stack ?? "");
|
|
247
|
+
return m ? Number(m[1]) - HEADER_LINES : undefined;
|
|
248
|
+
}
|
|
249
|
+
function cleanError(stderr) {
|
|
250
|
+
return stderr.replace(/\x1b\[[0-9;]*m/g, "").replace(/file:\/\/\S*main\.ts:(\d+)/g, (_m, l) => `line ${Number(l) - HEADER_LINES}`).trim().slice(0, 2000);
|
|
251
|
+
}
|
|
252
|
+
async function pruneCache(dir, ttlMs) {
|
|
253
|
+
try {
|
|
254
|
+
const now = Date.now();
|
|
255
|
+
for (const f of await readdir(dir)) {
|
|
256
|
+
const p = join(dir, f);
|
|
257
|
+
const s = await stat(p);
|
|
258
|
+
if (now - s.mtimeMs > Math.max(ttlMs, 60_000))
|
|
259
|
+
await rm(p, { force: true });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// nothing to prune
|
|
264
|
+
}
|
|
265
|
+
}
|
package/dist/legacy.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The 0.1 tool set (APINOA_MCP_MODE=tools): a handful of tools named by intent, each one API call, each taking
|
|
3
|
+
* a `platform`. Kept for clients that cannot run code mode; code mode is the default.
|
|
4
|
+
*/
|
|
5
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { type ApiOptions, type CatalogEntry } from "./api.js";
|
|
8
|
+
export declare function failure(e: unknown): CallToolResult;
|
|
9
|
+
/** Registers the 0.1 tools on `server`. */
|
|
10
|
+
export declare function registerLegacyTools(server: McpServer, api: ApiOptions, catalog: CatalogEntry[], maxChars: number): void;
|
package/dist/legacy.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { ApiError, callOperation, download } from "./api.js";
|
|
3
|
+
/** Operations whose answer is a file, not data: reachable through the API, the SDKs and code mode, not as tool text. */
|
|
4
|
+
const FILE_OPERATIONS = new Set(["tiktok/media"]);
|
|
5
|
+
const TOOLS = [
|
|
6
|
+
{
|
|
7
|
+
name: "search_products",
|
|
8
|
+
title: "Search products",
|
|
9
|
+
operation: "search",
|
|
10
|
+
summary: "Search a marketplace's products by keyword. Returns a SearchResult: items with title, price, rating, seller and url.",
|
|
11
|
+
primary: { name: "query", description: "Keywords to search for.", required: true },
|
|
12
|
+
paging: "For the next page pass params.page = 2, 3, … (or params.cursor where the platform returns one).",
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
name: "get_product",
|
|
16
|
+
title: "Get a product",
|
|
17
|
+
operation: "product",
|
|
18
|
+
summary: "One product in full: variants, images, specifications, seller, delivery and price.",
|
|
19
|
+
primary: { name: "id", description: "The product id as the platform's search results carry it (an ASIN, a numeric id, shop/handle…), or its URL where accepted.", required: true },
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: "get_product_reviews",
|
|
23
|
+
title: "Get product reviews",
|
|
24
|
+
operation: "reviews",
|
|
25
|
+
summary: "A product's reviews, one page at a time.",
|
|
26
|
+
primary: { name: "id", description: "The product id, as get_product takes it.", required: true },
|
|
27
|
+
paging: "For the next page pass params.page or params.cursor as the previous answer indicates.",
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: "list_categories",
|
|
31
|
+
title: "List categories",
|
|
32
|
+
operation: "categories",
|
|
33
|
+
summary: "One level of a marketplace's category tree. Omit params.categoryId for the top level; pass an id for its children. Ids feed browse_category.",
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "browse_category",
|
|
37
|
+
title: "Browse a category",
|
|
38
|
+
operation: "browse",
|
|
39
|
+
summary: "The products in one category, with no keyword. Get category ids from list_categories.",
|
|
40
|
+
paging: "For the next page pass params.page = 2, 3, …",
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "get_social_profile",
|
|
44
|
+
title: "Get a social profile",
|
|
45
|
+
operation: "profile",
|
|
46
|
+
summary: "One account on a social platform: name, bio, follower counts, verification, links.",
|
|
47
|
+
primary: { name: "username", description: "The handle, with or without @, or the profile URL.", required: false },
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: "list_social_posts",
|
|
51
|
+
title: "List social posts",
|
|
52
|
+
operation: "posts",
|
|
53
|
+
summary: "Posts from a social platform. What you pass in params picks the source: an account's (username), a search (query), a hashtag, community, sound, company, playlist, posts related to one (relatedTo) — or nothing for the trending feed.",
|
|
54
|
+
paging: "For the next page call again with params = { cursor } alone, using the cursor of the previous answer.",
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
name: "get_social_post",
|
|
58
|
+
title: "Get a social post",
|
|
59
|
+
operation: "post",
|
|
60
|
+
summary: "One post: text, author, media, counts, time.",
|
|
61
|
+
primary: { name: "id", description: "The post id or shortcode, or its URL.", required: true },
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: "get_social_comments",
|
|
65
|
+
title: "Get comments",
|
|
66
|
+
operation: "comments",
|
|
67
|
+
summary: "A post's comments (params.post), one comment's replies (params.comment), or an account's comments.",
|
|
68
|
+
paging: "For the next page call again with params = { cursor } alone.",
|
|
69
|
+
},
|
|
70
|
+
];
|
|
71
|
+
function describePlatform(e, operation) {
|
|
72
|
+
const schema = e.params[operation];
|
|
73
|
+
const props = Object.keys(schema?.properties ?? {});
|
|
74
|
+
const required = new Set(schema?.required ?? []);
|
|
75
|
+
const cost = e.cost?.[operation];
|
|
76
|
+
const price = cost ? (cost.base === cost.max ? ` [${cost.base} unit${cost.base === 1 ? "" : "s"}]` : ` [${cost.base}–${cost.max} units]`) : "";
|
|
77
|
+
return `- ${e.id}${price}: ${props.map((p) => (required.has(p) ? `${p}*` : p)).join(", ") || "(no parameters)"}`;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A social post's media lists every rendition of each file (sizes, bitrates): on Threads that is three
|
|
81
|
+
* quarters of a search answer. The model needs one, so each media keeps its main url, thumbnail and size,
|
|
82
|
+
* and its `variants` are left out. Only media's: a product's `variants` (sizes, colours) are data.
|
|
83
|
+
*/
|
|
84
|
+
function withoutRenditions(data) {
|
|
85
|
+
if (Array.isArray(data))
|
|
86
|
+
return data.map(withoutRenditions);
|
|
87
|
+
if (data === null || typeof data !== "object")
|
|
88
|
+
return data;
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const [k, v] of Object.entries(data)) {
|
|
91
|
+
out[k] =
|
|
92
|
+
k === "media" && Array.isArray(v)
|
|
93
|
+
? v.map((m) => {
|
|
94
|
+
if (m === null || typeof m !== "object")
|
|
95
|
+
return m;
|
|
96
|
+
const { variants: _renditions, ...rest } = m;
|
|
97
|
+
return withoutRenditions(rest);
|
|
98
|
+
})
|
|
99
|
+
: withoutRenditions(v);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
function result(raw, maxChars) {
|
|
104
|
+
const data = withoutRenditions(raw);
|
|
105
|
+
const text = JSON.stringify(data);
|
|
106
|
+
if (text.length <= maxChars)
|
|
107
|
+
return { content: [{ type: "text", text }] };
|
|
108
|
+
// Too large: keep whole items, so the answer stays valid JSON — as many as fit, then say what is missing.
|
|
109
|
+
const items = data?.items;
|
|
110
|
+
if (Array.isArray(items) && items.length > 1) {
|
|
111
|
+
const page = (n) => JSON.stringify({ ...data, items: items.slice(0, n) });
|
|
112
|
+
let lo = 1;
|
|
113
|
+
let hi = items.length - 1;
|
|
114
|
+
while (lo < hi) {
|
|
115
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
116
|
+
if (page(mid).length <= maxChars)
|
|
117
|
+
lo = mid;
|
|
118
|
+
else
|
|
119
|
+
hi = mid - 1;
|
|
120
|
+
}
|
|
121
|
+
if (page(lo).length <= maxChars) {
|
|
122
|
+
return {
|
|
123
|
+
content: [
|
|
124
|
+
{ type: "text", text: page(lo) },
|
|
125
|
+
{
|
|
126
|
+
type: "text",
|
|
127
|
+
text: `Showing ${lo} of the ${items.length} items on this page: the whole page is ${text.length} characters, over the ${maxChars} limit. For the other ${items.length - lo}, ask again with a smaller params.limit where the platform takes one, or a narrower query.`,
|
|
128
|
+
},
|
|
129
|
+
],
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
content: [{ type: "text", text: `${text.slice(0, maxChars)}\n…[cut at ${maxChars} of ${text.length} characters; ask for fewer items (params.limit) or a narrower query]` }],
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export function failure(e) {
|
|
138
|
+
const text = e instanceof ApiError
|
|
139
|
+
? `${e.message}${e.requestId ? ` (requestId ${e.requestId})` : ""}${e.status === 402 ? " — the apinoa balance is used up; top up at https://apinoa.com/dashboard/balance" : ""}${e.status === 401 ? " — set APINOA_API_KEY to a key from https://apinoa.com/dashboard" : ""}`
|
|
140
|
+
: `apinoa: ${e instanceof Error ? e.message : String(e)}`;
|
|
141
|
+
return { isError: true, content: [{ type: "text", text }] };
|
|
142
|
+
}
|
|
143
|
+
/** Registers the 0.1 tools on `server`. */
|
|
144
|
+
export function registerLegacyTools(server, api, catalog, maxChars) {
|
|
145
|
+
const readOnly = { readOnlyHint: true, openWorldHint: true };
|
|
146
|
+
// Answers are already cut to maxChars here; this asks Claude Code to keep them in the conversation up to that
|
|
147
|
+
// size instead of moving them to a file the model may have no tool to read.
|
|
148
|
+
const _meta = { "anthropic/maxResultSizeChars": maxChars + 2000 };
|
|
149
|
+
for (const spec of TOOLS) {
|
|
150
|
+
const platforms = catalog.filter((e) => e.operations.includes(spec.operation)).map((e) => e.id);
|
|
151
|
+
if (platforms.length === 0)
|
|
152
|
+
continue;
|
|
153
|
+
const lines = catalog.filter((e) => platforms.includes(e.id)).map((e) => describePlatform(e, spec.operation));
|
|
154
|
+
const description = [
|
|
155
|
+
spec.summary,
|
|
156
|
+
"",
|
|
157
|
+
`Platforms and the params each accepts (* = required${spec.primary ? `; ${spec.primary.name} may be given at the top level` : ""}):`,
|
|
158
|
+
...lines,
|
|
159
|
+
...(spec.paging ? ["", spec.paging] : []),
|
|
160
|
+
"",
|
|
161
|
+
"Costs are in units of $0.001 at list price; a call that fails is not billed.",
|
|
162
|
+
].join("\n");
|
|
163
|
+
const shape = {
|
|
164
|
+
platform: z.enum(platforms).describe("Which platform to read."),
|
|
165
|
+
};
|
|
166
|
+
if (spec.primary) {
|
|
167
|
+
const field = z.string().min(1).describe(spec.primary.description);
|
|
168
|
+
shape[spec.primary.name] = spec.primary.required ? field : field.optional();
|
|
169
|
+
}
|
|
170
|
+
shape.params = z.record(z.string(), z.unknown()).optional().describe("The platform's other parameters, by the names listed above.");
|
|
171
|
+
server.registerTool(spec.name, { title: spec.title, description, inputSchema: shape, annotations: { title: spec.title, ...readOnly }, _meta }, async (args) => {
|
|
172
|
+
try {
|
|
173
|
+
const params = { ...(args.params ?? {}) };
|
|
174
|
+
if (spec.primary && args[spec.primary.name] !== undefined)
|
|
175
|
+
params[spec.primary.name] = args[spec.primary.name];
|
|
176
|
+
return result(await callOperation(api, args.platform, spec.operation, params), maxChars);
|
|
177
|
+
}
|
|
178
|
+
catch (e) {
|
|
179
|
+
return failure(e);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
const imagePlatforms = catalog.filter((e) => e.operations.includes("image-search")).map((e) => e.id);
|
|
184
|
+
if (imagePlatforms.length)
|
|
185
|
+
server.registerTool("search_products_by_image", {
|
|
186
|
+
title: "Search products by image",
|
|
187
|
+
description: "Find a marketplace's products that match a photo. Give the photo as a URL; it is downloaded and sent as the search image.\n\nPlatforms: " +
|
|
188
|
+
imagePlatforms.join(", "),
|
|
189
|
+
inputSchema: {
|
|
190
|
+
platform: z.enum(imagePlatforms).describe("Which marketplace to search."),
|
|
191
|
+
image_url: z.string().url().describe("An http(s) URL of a JPEG or PNG photo."),
|
|
192
|
+
params: z.record(z.string(), z.unknown()).optional().describe("Other parameters of the platform's image-search (region, filters)."),
|
|
193
|
+
},
|
|
194
|
+
annotations: { title: "Search products by image", ...readOnly },
|
|
195
|
+
_meta,
|
|
196
|
+
}, async (args) => {
|
|
197
|
+
try {
|
|
198
|
+
const img = await download(api, args.image_url);
|
|
199
|
+
const data = Buffer.from(img.bytes).toString("base64");
|
|
200
|
+
return result(await callOperation(api, args.platform, "image-search", { ...(args.params ?? {}), image: { contentType: img.contentType, data } }), maxChars);
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
return failure(e);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
server.registerTool("call_apinoa", {
|
|
207
|
+
title: "Call any apinoa operation",
|
|
208
|
+
description: [
|
|
209
|
+
"Call any operation of the apinoa API directly, for what the other tools do not cover (store catalogs, shipping quotes, groups, followers, LinkedIn jobs…).",
|
|
210
|
+
"Every platform and its operations (params of each are listed by list_platforms):",
|
|
211
|
+
...catalog.map((e) => `- ${e.id}: ${e.operations.filter((op) => !FILE_OPERATIONS.has(`${e.id}/${op}`)).join(", ")}`),
|
|
212
|
+
].join("\n"),
|
|
213
|
+
inputSchema: {
|
|
214
|
+
platform: z.string().describe("Platform id, e.g. amazon, reddit."),
|
|
215
|
+
operation: z.string().describe("Operation as written in the list, e.g. search, image-search, groups."),
|
|
216
|
+
params: z.record(z.string(), z.unknown()).optional().describe("The operation's parameters."),
|
|
217
|
+
},
|
|
218
|
+
annotations: { title: "Call any apinoa operation", ...readOnly },
|
|
219
|
+
_meta,
|
|
220
|
+
}, async (args) => {
|
|
221
|
+
if (FILE_OPERATIONS.has(`${args.platform}/${args.operation}`)) {
|
|
222
|
+
return failure(new ApiError(400, "FILE_OPERATION", `${args.platform}/${args.operation} returns a file; use the apinoa SDK or API for it`));
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
return result(await callOperation(api, args.platform, args.operation, args.params ?? {}), maxChars);
|
|
226
|
+
}
|
|
227
|
+
catch (e) {
|
|
228
|
+
return failure(e);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
server.registerTool("list_platforms", {
|
|
232
|
+
title: "List platforms",
|
|
233
|
+
description: "Every platform apinoa serves, its operations, what each costs, and the parameters each operation accepts. Free, and needs no key.",
|
|
234
|
+
inputSchema: {
|
|
235
|
+
platform: z.string().optional().describe("Only this platform's details."),
|
|
236
|
+
},
|
|
237
|
+
annotations: { title: "List platforms", ...readOnly },
|
|
238
|
+
}, async (args) => {
|
|
239
|
+
const entries = catalog.filter((e) => !args.platform || e.id === args.platform);
|
|
240
|
+
const text = entries
|
|
241
|
+
.map((e) => [`## ${e.id} (${e.kind})${e.regions?.length ? ` — regions: ${e.regions.join(", ")}` : ""}`, ...e.operations.map((op) => describePlatform(e, op).replace(`- ${e.id}`, `- ${op}`))].join("\n"))
|
|
242
|
+
.join("\n\n");
|
|
243
|
+
return { content: [{ type: "text", text: text || `no platform ${args.platform}` }] };
|
|
244
|
+
});
|
|
245
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare class ApinoaError extends Error {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly requestId?: string | undefined;
|
|
5
|
+
constructor(code: string, message: string, status: number, requestId?: string | undefined);
|
|
6
|
+
}
|
|
7
|
+
/** Runs the code: waits for the config, sets up the globals, then reports the result or the error, and the usage. */
|
|
8
|
+
export declare function __run(fn: () => Promise<unknown>): Promise<void>;
|