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,304 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
const decoder = new TextDecoder();
|
|
3
|
+
// Taken before the code runs: code that replaces globalThis.fetch never sees the key the client sends.
|
|
4
|
+
const realFetch = globalThis.fetch.bind(globalThis);
|
|
5
|
+
// Codes worth another try (https://apinoa.com/docs/errors#retrying). Every other failure fails the same way again.
|
|
6
|
+
const RETRYABLE = new Set([
|
|
7
|
+
"CAPACITY_SATURATED", "MARKETPLACE_SATURATED", "RATE_LIMITED", "SERVICE_UNAVAILABLE", "INTERNAL_ERROR",
|
|
8
|
+
"UPSTREAM_ERROR", "UPSTREAM_READ_FAILED", "UPSTREAM_TIMEOUT", "UPSTREAM_UNAVAILABLE",
|
|
9
|
+
]);
|
|
10
|
+
// Failures no other call will get past: they end the run instead of being skipped by many().
|
|
11
|
+
const FATAL = new Set(["UNAUTHORIZED", "INSUFFICIENT_BALANCE", "ACCOUNT_SUSPENDED", "FORBIDDEN", "QUOTA_EXCEEDED", "BUDGET_EXCEEDED"]);
|
|
12
|
+
export class ApinoaError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
status;
|
|
15
|
+
requestId;
|
|
16
|
+
constructor(code, message, status, requestId) {
|
|
17
|
+
super(`${code}: ${message}`);
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.requestId = requestId;
|
|
21
|
+
this.name = "ApinoaError";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
let config;
|
|
25
|
+
const stats = { calls: 0, cached: 0, units: 0, failed: 0, errors: [] };
|
|
26
|
+
const pending = new Map();
|
|
27
|
+
let rpcId = 0;
|
|
28
|
+
function send(kind, payload) {
|
|
29
|
+
Deno.stdout.writeSync(encoder.encode(`\n@@APINOA_${kind}_${config.nonce}@@ ${JSON.stringify(payload)}\n`));
|
|
30
|
+
}
|
|
31
|
+
/** Lines on stdin: the config first, then the server's replies to RPC requests. */
|
|
32
|
+
async function readStdin(onConfig) {
|
|
33
|
+
let buf = "";
|
|
34
|
+
let first = true;
|
|
35
|
+
for await (const chunk of Deno.stdin.readable) {
|
|
36
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
37
|
+
let i;
|
|
38
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
39
|
+
const line = buf.slice(0, i);
|
|
40
|
+
buf = buf.slice(i + 1);
|
|
41
|
+
if (!line.trim())
|
|
42
|
+
continue;
|
|
43
|
+
const msg = JSON.parse(line);
|
|
44
|
+
if (first) {
|
|
45
|
+
first = false;
|
|
46
|
+
onConfig(msg);
|
|
47
|
+
}
|
|
48
|
+
else
|
|
49
|
+
pending.get(msg.id)?.(msg);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function rpc(method, params) {
|
|
54
|
+
const id = ++rpcId;
|
|
55
|
+
return new Promise((resolve) => {
|
|
56
|
+
pending.set(id, (reply) => {
|
|
57
|
+
pending.delete(id);
|
|
58
|
+
resolve(reply);
|
|
59
|
+
});
|
|
60
|
+
send("RPC", { id, method, ...params });
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
// ---- calls ---------------------------------------------------------------------------------------------
|
|
64
|
+
let active = 0;
|
|
65
|
+
const waiting = [];
|
|
66
|
+
async function slot(f) {
|
|
67
|
+
if (active >= config.concurrency)
|
|
68
|
+
await new Promise((r) => waiting.push(r));
|
|
69
|
+
active++;
|
|
70
|
+
try {
|
|
71
|
+
return await f();
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
active--;
|
|
75
|
+
waiting.shift()?.();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
79
|
+
function toQuery(params) {
|
|
80
|
+
const q = new URLSearchParams();
|
|
81
|
+
for (const [k, v] of Object.entries(params)) {
|
|
82
|
+
if (v === undefined || v === null || v === "")
|
|
83
|
+
continue;
|
|
84
|
+
q.set(k, Array.isArray(v) ? v.join(",") : String(v));
|
|
85
|
+
}
|
|
86
|
+
return q.toString();
|
|
87
|
+
}
|
|
88
|
+
async function sha256(text) {
|
|
89
|
+
const d = await crypto.subtle.digest("SHA-256", encoder.encode(text));
|
|
90
|
+
return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
91
|
+
}
|
|
92
|
+
async function cacheRead(key) {
|
|
93
|
+
if (config.cacheTtlMs <= 0)
|
|
94
|
+
return undefined;
|
|
95
|
+
try {
|
|
96
|
+
const hit = JSON.parse(await Deno.readTextFile(`${config.dataDir}/cache/${key}.json`));
|
|
97
|
+
return Date.now() - hit.t < config.cacheTtlMs ? hit.data : undefined;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function cacheWrite(key, data) {
|
|
104
|
+
if (config.cacheTtlMs <= 0)
|
|
105
|
+
return;
|
|
106
|
+
try {
|
|
107
|
+
const text = JSON.stringify({ t: Date.now(), data });
|
|
108
|
+
// A file (a video's bytes) is not kept: store.saveFile is the place for it.
|
|
109
|
+
if (text.length > 2_000_000)
|
|
110
|
+
return;
|
|
111
|
+
await Deno.writeTextFile(`${config.dataDir}/cache/${key}.json`, text);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// a full disk costs a cache entry, never the call
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function record(e) {
|
|
118
|
+
stats.failed++;
|
|
119
|
+
if (stats.errors.length < 5)
|
|
120
|
+
stats.errors.push(e instanceof Error ? e.message : String(e));
|
|
121
|
+
}
|
|
122
|
+
async function call(platform, operation, params = {}) {
|
|
123
|
+
const p = { ...params };
|
|
124
|
+
// An image may be given by URL; the server downloads it, since this sandbox reaches only the API.
|
|
125
|
+
if (typeof p.image === "string" || (p.image && typeof p.image === "object" && "url" in p.image)) {
|
|
126
|
+
const url = typeof p.image === "string" ? p.image : p.image.url;
|
|
127
|
+
const got = await rpc("download", { url });
|
|
128
|
+
if (!got.ok)
|
|
129
|
+
throw new ApinoaError("IMAGE_DOWNLOAD_FAILED", got.error, 400);
|
|
130
|
+
p.image = { contentType: got.contentType, data: got.data };
|
|
131
|
+
}
|
|
132
|
+
const post = Object.values(p).some((v) => v !== null && typeof v === "object" && !Array.isArray(v));
|
|
133
|
+
const path = `/v1/${encodeURIComponent(platform)}/${encodeURIComponent(operation)}`;
|
|
134
|
+
const query = post ? "" : toQuery(p);
|
|
135
|
+
const key = post ? "" : await sha256(`${path}?${query}`);
|
|
136
|
+
if (key) {
|
|
137
|
+
const hit = await cacheRead(key);
|
|
138
|
+
if (hit !== undefined) {
|
|
139
|
+
stats.cached++;
|
|
140
|
+
return hit;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return slot(async () => {
|
|
144
|
+
for (let attempt = 0;; attempt++) {
|
|
145
|
+
if (stats.units >= config.budget) {
|
|
146
|
+
throw new ApinoaError("BUDGET_EXCEEDED", `the run's budget of ${config.budget} units is spent (${stats.calls} calls). Run again with a larger budget_units, or save progress with store.save and continue in the next run.`, 402);
|
|
147
|
+
}
|
|
148
|
+
let res;
|
|
149
|
+
try {
|
|
150
|
+
res = await realFetch(config.baseUrl + path + (query ? `?${query}` : ""), {
|
|
151
|
+
method: post ? "POST" : "GET",
|
|
152
|
+
headers: { "x-api-key": config.key, "user-agent": config.userAgent, ...(post ? { "content-type": "application/json" } : {}) },
|
|
153
|
+
body: post ? JSON.stringify(p) : undefined,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
if (attempt < 2) {
|
|
158
|
+
await sleep(1000 * 2 ** attempt);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
throw new ApinoaError("NETWORK_ERROR", e instanceof Error ? e.message : String(e), 0);
|
|
162
|
+
}
|
|
163
|
+
stats.calls++;
|
|
164
|
+
stats.units += Number(res.headers.get("x-apinoa-cost")) || 0;
|
|
165
|
+
const text = await res.text();
|
|
166
|
+
let body;
|
|
167
|
+
try {
|
|
168
|
+
body = JSON.parse(text);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
body = undefined;
|
|
172
|
+
}
|
|
173
|
+
if (res.ok && body?.success !== false && body?.data !== undefined) {
|
|
174
|
+
if (key)
|
|
175
|
+
await cacheWrite(key, body.data);
|
|
176
|
+
return body.data;
|
|
177
|
+
}
|
|
178
|
+
const code = body?.error?.code ?? (res.status >= 500 ? "UPSTREAM_ERROR" : `HTTP_${res.status}`);
|
|
179
|
+
const message = body?.error?.message ?? (text.slice(0, 200) || res.statusText);
|
|
180
|
+
if ((RETRYABLE.has(code) || res.status === 429 || res.status >= 500) && attempt < 2) {
|
|
181
|
+
const after = Number(res.headers.get("retry-after"));
|
|
182
|
+
await sleep(Math.min(10_000, (after > 0 ? after : 2 ** attempt) * 1000));
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
throw new ApinoaError(code, message, res.status, body?.requestId ?? res.headers.get("x-request-id") ?? undefined);
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
function client() {
|
|
190
|
+
const out = {};
|
|
191
|
+
for (const [platform, ops] of Object.entries(config.operations)) {
|
|
192
|
+
out[platform] = {};
|
|
193
|
+
for (const [operation, [method]] of Object.entries(ops)) {
|
|
194
|
+
out[platform][method] = (params) => call(platform, operation, params ?? {});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
// ---- helpers -------------------------------------------------------------------------------------------
|
|
200
|
+
async function pages(op, params = {}, options = {}) {
|
|
201
|
+
const maxPages = options.maxPages ?? 5;
|
|
202
|
+
const maxItems = options.maxItems ?? Infinity;
|
|
203
|
+
const items = [];
|
|
204
|
+
let page = await op(params);
|
|
205
|
+
for (let n = 1;; n++) {
|
|
206
|
+
items.push(...(page?.items ?? []));
|
|
207
|
+
if (items.length >= maxItems || n >= maxPages || !page?.cursor || !(page?.items ?? []).length)
|
|
208
|
+
break;
|
|
209
|
+
page = await op({ cursor: page.cursor });
|
|
210
|
+
}
|
|
211
|
+
return Number.isFinite(maxItems) ? items.slice(0, maxItems) : items;
|
|
212
|
+
}
|
|
213
|
+
async function many(items, fn, options = {}) {
|
|
214
|
+
const out = new Array(items.length);
|
|
215
|
+
let next = 0;
|
|
216
|
+
const worker = async () => {
|
|
217
|
+
while (next < items.length) {
|
|
218
|
+
const i = next++;
|
|
219
|
+
try {
|
|
220
|
+
out[i] = await fn(items[i], i);
|
|
221
|
+
}
|
|
222
|
+
catch (e) {
|
|
223
|
+
if (e instanceof ApinoaError && FATAL.has(e.code))
|
|
224
|
+
throw e;
|
|
225
|
+
record(e);
|
|
226
|
+
out[i] = undefined;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 8, items.length)) }, worker));
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
const safeName = (name) => {
|
|
234
|
+
const n = String(name).replace(/[^\w.-]+/g, "_").replace(/^\.+/, "");
|
|
235
|
+
if (!n)
|
|
236
|
+
throw new Error("store: give a name of letters, digits, '.', '-' or '_'");
|
|
237
|
+
return n;
|
|
238
|
+
};
|
|
239
|
+
const store = {
|
|
240
|
+
async save(name, value) {
|
|
241
|
+
const path = `${config.dataDir}/store/${safeName(name)}.json`;
|
|
242
|
+
await Deno.writeTextFile(path, JSON.stringify(value));
|
|
243
|
+
return path;
|
|
244
|
+
},
|
|
245
|
+
async load(name) {
|
|
246
|
+
try {
|
|
247
|
+
return JSON.parse(await Deno.readTextFile(`${config.dataDir}/store/${safeName(name)}.json`));
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
async list() {
|
|
254
|
+
const names = [];
|
|
255
|
+
for await (const e of Deno.readDir(`${config.dataDir}/store`))
|
|
256
|
+
if (e.isFile && e.name.endsWith(".json"))
|
|
257
|
+
names.push(e.name.slice(0, -5));
|
|
258
|
+
return names.sort();
|
|
259
|
+
},
|
|
260
|
+
async saveFile(name, base64) {
|
|
261
|
+
const bin = atob(base64);
|
|
262
|
+
const bytes = new Uint8Array(bin.length);
|
|
263
|
+
for (let i = 0; i < bin.length; i++)
|
|
264
|
+
bytes[i] = bin.charCodeAt(i);
|
|
265
|
+
const path = `${config.dataDir}/files/${safeName(name)}`;
|
|
266
|
+
await Deno.writeFile(path, bytes);
|
|
267
|
+
return path;
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
function serialize(value) {
|
|
271
|
+
if (value === undefined)
|
|
272
|
+
return null;
|
|
273
|
+
try {
|
|
274
|
+
return JSON.parse(JSON.stringify(value, (_k, v) => (typeof v === "bigint" ? v.toString() : v)));
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return String(value);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/** Runs the code: waits for the config, sets up the globals, then reports the result or the error, and the usage. */
|
|
281
|
+
export async function __run(fn) {
|
|
282
|
+
const ready = new Promise((resolve) => {
|
|
283
|
+
readStdin((c) => {
|
|
284
|
+
config = c;
|
|
285
|
+
resolve();
|
|
286
|
+
}).catch(() => { });
|
|
287
|
+
});
|
|
288
|
+
await ready;
|
|
289
|
+
for (const d of ["cache", "store", "files"])
|
|
290
|
+
await Deno.mkdir(`${config.dataDir}/${d}`, { recursive: true });
|
|
291
|
+
Object.assign(globalThis, { apinoa: client(), pages, many, store, ApinoaError, usage: { get calls() { return stats.calls; }, get units() { return stats.units; }, get budget() { return config.budget; } } });
|
|
292
|
+
const ticker = setInterval(() => send("PROGRESS", stats), 2000);
|
|
293
|
+
let report;
|
|
294
|
+
try {
|
|
295
|
+
report = { ok: true, result: serialize(await fn()) };
|
|
296
|
+
}
|
|
297
|
+
catch (e) {
|
|
298
|
+
const err = e;
|
|
299
|
+
report = { ok: false, error: err instanceof ApinoaError ? err.message : `${err?.name ?? "Error"}: ${err?.message ?? String(e)}`, stack: err?.stack ?? "" };
|
|
300
|
+
}
|
|
301
|
+
clearInterval(ticker);
|
|
302
|
+
send("DONE", { ...report, stats });
|
|
303
|
+
Deno.exit(0);
|
|
304
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// GENERATED by scripts/gen-schema.mjs from the OpenAPI document (tools/public/generate-sdks.sh). Do not edit.
|
|
2
|
+
// The response types code in `execute` is checked against, and the type each operation returns.
|
|
3
|
+
export const SCHEMA_TYPES = "interface Account {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n id?: string;\n handle: string;\n displayName?: string;\n bio?: string;\n url: string;\n avatarUrl?: string;\n bannerUrl?: string;\n verified?: boolean;\n createdAt?: string;\n counts?: {\n followers?: number;\n following?: number;\n posts?: number;\n };\n links?: Link[];\n private?: boolean;\n category?: string;\n ext?: Record<string, unknown>;\n}\ninterface AccountPage {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n items: Account[];\n cursor?: string;\n total?: number;\n ext?: Record<string, unknown>;\n}\ninterface AccountRef {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n id?: string;\n handle?: string;\n displayName?: string;\n url?: string;\n avatarUrl?: string;\n verified?: boolean;\n counts?: {\n followers?: number;\n following?: number;\n posts?: number;\n };\n ext?: Record<string, unknown>;\n}\ninterface Attribute {\n name: string;\n value: string;\n}\ninterface Audio {\n id?: string;\n title?: string;\n artist?: string;\n url?: string;\n}\ninterface Broadcast {\n status: \"scheduled\" | \"live\" | \"ended\";\n scheduledAt?: string;\n startedAt?: string;\n endedAt?: string;\n}\ninterface Catalog {\n marketplaces: ({\n id: string;\n kind: \"marketplace\" | \"sns\";\n operations: string[];\n regions?: string[];\n cost?: Record<string, unknown>;\n /** Each operation's input, as JSON Schema. */\n params?: Record<string, unknown>;\n })[];\n pricing?: Record<string, unknown>;\n}\ninterface CategoryList {\n marketplace: string;\n path: CategoryStep[];\n categories: CategoryNode[];\n}\ninterface CategoryNode {\n id: string;\n name: string;\n parentId?: string;\n hasChildren?: boolean;\n browsable?: boolean;\n productCount?: number;\n ext?: Ext;\n}\ninterface CategoryStep {\n id?: string;\n name?: string;\n}\ninterface Comment {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n id: string;\n url?: string;\n postId: string;\n parentId?: string;\n author: AccountRef;\n text: string;\n createdAt?: string;\n editedAt?: string;\n lang?: string;\n pinned?: boolean;\n byAuthor?: boolean;\n likedByAuthor?: boolean;\n metrics?: {\n likes?: number;\n replies?: number;\n };\n media?: SocialMedia[];\n replies: Comment[];\n moreReplies?: {\n count?: number;\n ids?: string[];\n cursor?: string;\n ext?: Record<string, unknown>;\n };\n ext?: Record<string, unknown>;\n}\ninterface CommentPage {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n items: Comment[];\n cursor?: string;\n total?: number;\n ext?: Record<string, unknown>;\n}\ninterface DeliveryOption {\n carrier?: string;\n code?: string;\n estimate?: string;\n cost?: Money;\n free?: boolean;\n minDays?: number;\n maxDays?: number;\n guaranteedDays?: number;\n handlingDays?: number;\n cutoff?: string;\n condition?: string;\n available?: boolean;\n membership?: string;\n minimumOrder?: Money;\n tracking?: boolean;\n shipsFrom?: string;\n}\ninterface Entities {\n mentions?: Mention[];\n urls?: Url[];\n hashtags?: string[];\n}\ntype Ext = Record<string, unknown>;\ninterface Facet {\n id: string;\n name: string;\n kind: \"select\" | \"range\";\n values: FacetValue[];\n min?: number;\n max?: number;\n maps_to?: string;\n}\ninterface FacetValue {\n value: string;\n name: string;\n count?: number;\n selected?: boolean;\n}\ninterface Group {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n kind: \"community\" | \"channel\" | \"company\" | \"hashtag\" | \"sound\" | \"topic\" | \"location\" | \"list\";\n id: string;\n name: string;\n url: string;\n description?: string;\n avatarUrl?: string;\n bannerUrl?: string;\n createdAt?: string;\n counts?: {\n members?: number;\n posts?: number;\n };\n sensitive?: boolean;\n ext?: Record<string, unknown>;\n}\ninterface GroupPage {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n items: Group[];\n cursor?: string;\n total?: number;\n ext?: Record<string, unknown>;\n}\ninterface Identifiers {\n gtin?: string;\n mpn?: string;\n model?: string;\n}\ninterface InReplyTo {\n id: string;\n url?: string;\n author?: AccountRef;\n}\ninterface Job {\n platform: \"linkedin\";\n id: string;\n url: string;\n title: string;\n company: {\n name: string;\n slug?: string;\n url?: string;\n logoUrl?: string;\n };\n location?: string;\n postedText?: string;\n applicants?: number;\n applicantsAtLeast?: number;\n seniority?: string;\n employmentType?: string;\n jobFunction?: string;\n industries?: string;\n description?: string;\n descriptionHtml?: string;\n}\ninterface JobPage {\n platform: \"linkedin\";\n items: {\n platform: \"linkedin\";\n id: string;\n url: string;\n title: string;\n company: {\n name: string;\n url?: string;\n };\n location?: string;\n listedAt?: string;\n logoUrl?: string;\n }[];\n cursor?: string;\n}\ninterface Link {\n url: string;\n title?: string;\n}\ninterface LinkPreview {\n url: string;\n title?: string;\n description?: string;\n thumbnailUrl?: string;\n domain?: string;\n}\ninterface Media {\n images: string[];\n videos: MediaVideo[];\n}\ninterface MediaFile {\n platform: string;\n postId: string;\n /** The file's MIME type, e.g. video/mp4 or image/jpeg. */\n contentType: string;\n /** The decoded file's size in bytes. */\n bytes: number;\n encoding: \"base64\";\n /** The file, base64-encoded. */\n data: string;\n /** Photo posts: which picture this is, 1-based. */\n index?: number;\n /** Photo posts: how many pictures the post has. */\n count?: number;\n}\ninterface MediaVariant {\n url: string;\n width?: number;\n height?: number;\n bitrate?: number;\n contentType?: string;\n}\ninterface MediaVideo {\n thumbnailUrl?: string;\n url?: string;\n title?: string;\n duration?: string;\n creator?: string;\n}\ninterface Mention {\n handle: string;\n id?: string;\n displayName?: string;\n}\ninterface Money {\n currency: string;\n amount: number;\n}\ninterface OcrResult {\n regions: TextRegion[];\n regions_found?: number;\n src_w?: number;\n src_h?: number;\n}\ninterface Offer {\n seller?: Seller;\n price: Money;\n listPrice?: Money;\n condition?: string;\n conditionNote?: string;\n fulfilledBy?: string;\n inStock?: boolean;\n status?: string;\n delivery?: DeliveryOption;\n ext?: Ext;\n}\ninterface Option {\n id: string;\n name: string;\n values: OptionValue[];\n}\ninterface OptionValue {\n id: string;\n name: string;\n imageUrl?: string;\n}\ninterface Page {\n index: number;\n size: number;\n total?: number;\n}\ninterface Place {\n name: string;\n id?: string;\n lat?: number;\n lng?: number;\n address?: string;\n city?: string;\n region?: string;\n postalCode?: string;\n country?: string;\n}\ninterface Poll {\n options: {\n text: string;\n votes?: number;\n }[];\n totalVotes?: number;\n endsAt?: string;\n}\ninterface Post {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n id: string;\n url: string;\n author: AccountRef;\n title?: string;\n text?: string;\n createdAt?: string;\n editedAt?: string;\n lang?: string;\n media: SocialMedia[];\n metrics?: {\n likes?: number;\n comments?: number;\n shares?: number;\n views?: number;\n reposts?: number;\n quotes?: number;\n saves?: number;\n liveViewers?: number;\n };\n entities?: Entities;\n linkPreview?: LinkPreview;\n poll?: Poll;\n place?: Place;\n audio?: Audio;\n live?: boolean;\n broadcast?: Broadcast;\n repostOf?: Post;\n quoteOf?: Post;\n inReplyTo?: InReplyTo;\n sponsored?: boolean;\n pinned?: boolean;\n aiGenerated?: boolean;\n sensitive?: boolean;\n ext?: Record<string, unknown>;\n}\ninterface PostPage {\n platform: \"reddit\" | \"linkedin\" | \"tiktok\" | \"youtube\" | \"instagram\" | \"threads\" | \"x\";\n items: Post[];\n cursor?: string;\n total?: number;\n ext?: Record<string, unknown>;\n}\ninterface Product {\n marketplace: string;\n id: string;\n url?: string;\n title: string;\n price?: Money;\n listPrice?: Money;\n condition?: string;\n conditionNote?: string;\n unitPrice?: {\n price: Money;\n unit?: string;\n };\n brand?: string;\n rating?: Rating;\n seller?: Seller;\n salesCount?: number;\n salesLabel?: string;\n inStock?: boolean;\n status?: string;\n delivery?: ShippingOption;\n shippingOptions?: ShippingOption[];\n stock?: number;\n identifiers?: Identifiers;\n listingFormat?: string;\n paymentOptions?: string[];\n returnsPolicy?: string;\n badges: string[];\n promotions: string[];\n groupId?: string;\n attributes: Attribute[];\n offersSummary?: {\n count?: number;\n fromPrice?: Money;\n url?: string;\n };\n priceRange?: {\n min: Money;\n max: Money;\n };\n endsAt?: string;\n purchaseLimit?: number;\n listedAt?: string;\n deliveryTo?: {\n label?: string;\n country?: string;\n postalCode?: string;\n };\n ext?: Ext;\n description?: string;\n features: string[];\n media: Media;\n category: CategoryStep[];\n options: Option[];\n variants: Variant[];\n offers: Offer[];\n subscriptionPrice?: Money;\n reviewSummary?: string;\n reviewAspects: {\n name: string;\n mentions?: number;\n positive?: number;\n negative?: number;\n }[];\n boxContents: string[];\n brandUrl?: string;\n fulfilledBy?: string;\n replacedBy?: string;\n reviews: Review[];\n package?: {\n lengthCm?: number;\n widthCm?: number;\n heightCm?: number;\n weightKg?: number;\n soldInLot?: boolean;\n };\n wholesale?: boolean;\n included?: string[];\n}\ninterface Rating {\n average: number;\n count?: number;\n distribution?: Record<string, unknown>;\n grouped?: boolean;\n}\ninterface Review {\n id?: string;\n author?: string;\n rating: number;\n title?: string;\n body?: string;\n date?: string;\n country?: string;\n verified?: boolean;\n helpfulCount?: number;\n variant?: string;\n images: string[];\n incentivized?: boolean;\n reply?: {\n body: string;\n date?: string;\n author?: string;\n };\n ext?: Ext;\n}\ninterface ReviewPage {\n marketplace: string;\n productId: string;\n summary?: Rating;\n page: Page;\n reviews: Review[];\n cursor?: string;\n grouped?: boolean;\n ext?: Ext;\n}\ninterface SearchItem {\n marketplace: string;\n id: string;\n url?: string;\n title: string;\n price?: Money;\n listPrice?: Money;\n condition?: string;\n conditionNote?: string;\n unitPrice?: {\n price: Money;\n unit?: string;\n };\n brand?: string;\n rating?: Rating;\n seller?: Seller;\n salesCount?: number;\n salesLabel?: string;\n inStock?: boolean;\n status?: string;\n delivery?: ShippingOption;\n shippingOptions?: ShippingOption[];\n stock?: number;\n identifiers?: Identifiers;\n listingFormat?: string;\n paymentOptions?: string[];\n returnsPolicy?: string;\n badges: string[];\n promotions: string[];\n groupId?: string;\n attributes: Attribute[];\n offersSummary?: {\n count?: number;\n fromPrice?: Money;\n url?: string;\n };\n priceRange?: {\n min: Money;\n max: Money;\n };\n endsAt?: string;\n purchaseLimit?: number;\n listedAt?: string;\n deliveryTo?: {\n label?: string;\n country?: string;\n postalCode?: string;\n };\n ext?: Ext;\n imageUrl?: string;\n sponsored?: boolean;\n variantCount?: number;\n category?: CategoryStep[];\n matchScore?: number;\n}\ninterface SearchResult {\n marketplace: string;\n query?: string;\n page: Page;\n items: SearchItem[];\n cursor?: string;\n facets?: Facet[];\n}\ninterface Seller {\n id?: string;\n name?: string;\n url?: string;\n rating?: Rating;\n country?: string;\n detailedRatings?: {\n itemAsDescribed?: number;\n communication?: number;\n shippingSpeed?: number;\n };\n positivePercent?: number;\n ext?: Ext;\n}\ninterface ShippingOption {\n carrier?: string;\n code?: string;\n estimate?: string;\n cost?: Money;\n free?: boolean;\n minDays?: number;\n maxDays?: number;\n guaranteedDays?: number;\n handlingDays?: number;\n cutoff?: string;\n condition?: string;\n available?: boolean;\n membership?: string;\n minimumOrder?: Money;\n tracking?: boolean;\n shipsFrom?: string;\n}\ninterface ShippingQuote {\n marketplace: string;\n productId: string;\n skuId?: string;\n region: string;\n quantity: number;\n available: boolean;\n options: ShippingOption[];\n}\ninterface SocialMedia {\n type: \"image\" | \"gif\" | \"video\" | \"embed\";\n url: string;\n width?: number;\n height?: number;\n thumbnailUrl?: string;\n durationSec?: number;\n variants?: MediaVariant[];\n altText?: string;\n caption?: string;\n ext?: Record<string, unknown>;\n}\ninterface SupportedFonts {\n fontsByLanguage?: Record<string, unknown>;\n defaultByLanguage?: Record<string, unknown>;\n allFonts?: string[];\n allWeights?: string[];\n supportedSourceLanguages?: string[];\n userFonts?: Record<string, unknown>[];\n}\ninterface TextRegion {\n /** The region's number, starting at 0. */\n index: number;\n /** Four corner points, in the original image's coordinates. */\n polygon: number[][];\n bbox: {\n x: number;\n y: number;\n w: number;\n h: number;\n };\n /** The text that was read. */\n text: string;\n /** Recognition confidence, 0–1. */\n confidence?: number;\n text_color?: {\n r: number;\n g: number;\n b: number;\n };\n bg_color?: {\n r: number;\n g: number;\n b: number;\n };\n /** How uneven the background is behind the text; near 0 is a flat colour. */\n bg_std?: number;\n font_weight?: string;\n /** True for text on a filled label, such as a price tag. */\n is_badge?: boolean;\n}\ninterface TranslatedRegion {\n /** The region's number, starting at 0. */\n index: number;\n /** Four corner points, in the original image's coordinates. */\n polygon: number[][];\n bbox: {\n x: number;\n y: number;\n w: number;\n h: number;\n };\n /** The text that was read. */\n text: string;\n /** Recognition confidence, 0–1. */\n confidence?: number;\n text_color?: {\n r: number;\n g: number;\n b: number;\n };\n bg_color?: {\n r: number;\n g: number;\n b: number;\n };\n /** How uneven the background is behind the text; near 0 is a flat colour. */\n bg_std?: number;\n font_weight?: string;\n /** True for text on a filled label, such as a price tag. */\n is_badge?: boolean;\n /** The translation, in target_language (the field name is historical). */\n text_kr?: string;\n}\ninterface TranslatedRegions {\n /** The image with the source text removed, as a base64 JPEG. */\n inpainted_base64: string;\n regions: TranslatedRegion[];\n regions_count?: number;\n}\ninterface Url {\n url: string;\n displayUrl?: string;\n}\ninterface Variant {\n id: string;\n productId?: string;\n sku?: string;\n price?: Money;\n listPrice?: Money;\n bulkPrice?: Money;\n purchaseLimit?: number;\n taxIncluded?: boolean;\n inStock?: boolean;\n stock?: number;\n selections: VariantSelection[];\n identifiers?: Identifiers;\n weightKg?: number;\n ext?: Ext;\n}\ninterface VariantSelection {\n optionId: string;\n valueId: string;\n optionName: string;\n valueName: string;\n}";
|
|
4
|
+
export const RETURNS = {
|
|
5
|
+
"aliexpress/search": "SearchResult",
|
|
6
|
+
"aliexpress/browse": "SearchResult",
|
|
7
|
+
"aliexpress/categories": "CategoryList",
|
|
8
|
+
"aliexpress/image-search": "SearchResult",
|
|
9
|
+
"aliexpress/product": "Product",
|
|
10
|
+
"aliexpress/shipping": "ShippingQuote",
|
|
11
|
+
"amazon/search": "SearchResult",
|
|
12
|
+
"amazon/image-search": "SearchResult",
|
|
13
|
+
"amazon/browse": "SearchResult",
|
|
14
|
+
"amazon/categories": "CategoryList",
|
|
15
|
+
"amazon/product": "Product",
|
|
16
|
+
"instagram/profile": "Account",
|
|
17
|
+
"instagram/post": "Post",
|
|
18
|
+
"instagram/posts": "PostPage",
|
|
19
|
+
"instagram/comments": "CommentPage",
|
|
20
|
+
"instagram/group": "Group",
|
|
21
|
+
"instagram/groups": "GroupPage",
|
|
22
|
+
"linkedin/profile": "Account",
|
|
23
|
+
"linkedin/post": "Post",
|
|
24
|
+
"linkedin/posts": "PostPage",
|
|
25
|
+
"linkedin/comments": "CommentPage",
|
|
26
|
+
"linkedin/group": "Group",
|
|
27
|
+
"linkedin/job": "Job",
|
|
28
|
+
"linkedin/jobs": "JobPage",
|
|
29
|
+
"reddit/profile": "Account",
|
|
30
|
+
"reddit/profiles": "AccountPage",
|
|
31
|
+
"reddit/post": "Post",
|
|
32
|
+
"reddit/posts": "PostPage",
|
|
33
|
+
"reddit/comments": "CommentPage",
|
|
34
|
+
"reddit/group": "Group",
|
|
35
|
+
"reddit/groups": "GroupPage",
|
|
36
|
+
"shopify/search": "SearchResult",
|
|
37
|
+
"shopify/image-search": "SearchResult",
|
|
38
|
+
"shopify/catalog": "SearchResult",
|
|
39
|
+
"shopify/product": "Product",
|
|
40
|
+
"shopify/reviews": "ReviewPage",
|
|
41
|
+
"threads/profile": "Account",
|
|
42
|
+
"threads/post": "Post",
|
|
43
|
+
"threads/posts": "PostPage",
|
|
44
|
+
"threads/comments": "CommentPage",
|
|
45
|
+
"tiktok/profile": "Account",
|
|
46
|
+
"tiktok/profiles": "AccountPage",
|
|
47
|
+
"tiktok/post": "Post",
|
|
48
|
+
"tiktok/posts": "PostPage",
|
|
49
|
+
"tiktok/comments": "CommentPage",
|
|
50
|
+
"tiktok/group": "Group",
|
|
51
|
+
"tiktok/groups": "GroupPage",
|
|
52
|
+
"tiktok/media": "MediaFile",
|
|
53
|
+
"tiktokshop/search": "SearchResult",
|
|
54
|
+
"tiktokshop/browse": "SearchResult",
|
|
55
|
+
"tiktokshop/categories": "CategoryList",
|
|
56
|
+
"tiktokshop/catalog": "SearchResult",
|
|
57
|
+
"tiktokshop/product": "Product",
|
|
58
|
+
"tiktokshop/reviews": "ReviewPage",
|
|
59
|
+
"walmart/search": "SearchResult",
|
|
60
|
+
"walmart/browse": "SearchResult",
|
|
61
|
+
"walmart/categories": "CategoryList",
|
|
62
|
+
"walmart/product": "Product",
|
|
63
|
+
"walmart/reviews": "ReviewPage",
|
|
64
|
+
"x/profile": "Account",
|
|
65
|
+
"x/post": "Post",
|
|
66
|
+
"x/posts": "PostPage",
|
|
67
|
+
"x/group": "Group",
|
|
68
|
+
"youtube/profile": "Account",
|
|
69
|
+
"youtube/profiles": "AccountPage",
|
|
70
|
+
"youtube/post": "Post",
|
|
71
|
+
"youtube/posts": "PostPage",
|
|
72
|
+
"youtube/comments": "CommentPage",
|
|
73
|
+
"youtube/groups": "GroupPage",
|
|
74
|
+
"image-translate/translate": "TranslatedRegions",
|
|
75
|
+
"image-translate/ocr": "OcrResult",
|
|
76
|
+
"image-translate/supported-fonts": "SupportedFonts"
|
|
77
|
+
};
|
package/dist/server.d.ts
CHANGED
|
@@ -1,22 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The apinoa MCP server
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* The apinoa MCP server.
|
|
3
|
+
*
|
|
4
|
+
* Code mode (the default) exposes three tools: `search_docs` finds the operations for a task with their
|
|
5
|
+
* parameters, costs and the fields they return; `execute` runs TypeScript the model writes against a typed
|
|
6
|
+
* `apinoa` client in a sandbox, so a task of hundreds of calls is one tool call and only the result enters the
|
|
7
|
+
* conversation; `translate_image` returns an image, which code cannot. APINOA_MCP_MODE=tools serves the 0.1
|
|
8
|
+
* tool set instead (one tool call per API call).
|
|
9
|
+
*
|
|
10
|
+
* The platforms, operations and parameters come from the live catalog, so a platform added to apinoa appears
|
|
11
|
+
* here without a new release.
|
|
6
12
|
*/
|
|
7
13
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
8
14
|
import { type CatalogEntry } from "./api.js";
|
|
9
|
-
|
|
15
|
+
import { type SandboxOptions } from "./code/sandbox.js";
|
|
16
|
+
export declare const VERSION = "0.2.0";
|
|
10
17
|
export interface ServerOptions {
|
|
11
|
-
/** Defaults to APINOA_API_KEY.
|
|
18
|
+
/** Defaults to APINOA_API_KEY. Docs work without one; every data call needs it. */
|
|
12
19
|
apiKey?: string;
|
|
13
20
|
baseUrl?: string;
|
|
14
21
|
fetch?: typeof fetch;
|
|
15
22
|
timeoutMs?: number;
|
|
16
23
|
/** Use this catalog instead of fetching the live one (tests, offline use). */
|
|
17
24
|
catalog?: CatalogEntry[];
|
|
18
|
-
/** The most characters
|
|
25
|
+
/** The most characters one tool answer may carry before it is cut, to protect the model's context. */
|
|
19
26
|
maxResultChars?: number;
|
|
27
|
+
/** "code" (default) or "tools" (the 0.1 tool set). Defaults to APINOA_MCP_MODE. */
|
|
28
|
+
mode?: "code" | "tools";
|
|
29
|
+
/** Code mode: where the cache and store live, the deno binary, and the run limits. */
|
|
30
|
+
sandbox?: Partial<Omit<SandboxOptions, "api" | "userAgent">>;
|
|
20
31
|
}
|
|
21
|
-
/** Build the server. Resolves the catalog first (live, else the bundled snapshot) so the tools can name the platforms. */
|
|
22
32
|
export declare function createApinoaServer(options?: ServerOptions): Promise<McpServer>;
|