apinoa-mcp 0.1.1 → 0.2.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.
package/dist/server.js CHANGED
@@ -1,155 +1,24 @@
1
1
  /**
2
- * The apinoa MCP server: a handful of tools named by what an assistant wants ("search products", "get a
3
- * social profile"), each taking a `platform`, rather than one tool per endpoint. Fewer tools are chosen
4
- * between more accurately, and the platform list and each platform's parameters come from the live
5
- * catalog, so a platform added to the API appears here without a new release.
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 { z } from "zod";
9
- import { ApiError, callOperation, download, fetchCatalog, translateImage } from "./api.js";
15
+ import { fetchCatalog, translateImage, download } from "./api.js";
10
16
  import SNAPSHOT from "./catalog.snapshot.js";
11
- export const VERSION = "0.1.1";
12
- /** Operations whose answer is a file, not data: reachable through the API and the SDKs, not as tool text. */
13
- const FILE_OPERATIONS = new Set(["tiktok/media"]);
14
- const TOOLS = [
15
- {
16
- name: "search_products",
17
- title: "Search products",
18
- operation: "search",
19
- summary: "Search a marketplace's products by keyword. Returns a SearchResult: items with title, price, rating, seller and url.",
20
- primary: { name: "query", description: "Keywords to search for.", required: true },
21
- paging: "For the next page pass params.page = 2, 3, … (or params.cursor where the platform returns one).",
22
- },
23
- {
24
- name: "get_product",
25
- title: "Get a product",
26
- operation: "product",
27
- summary: "One product in full: variants, images, specifications, seller, delivery and price.",
28
- 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 },
29
- },
30
- {
31
- name: "get_product_reviews",
32
- title: "Get product reviews",
33
- operation: "reviews",
34
- summary: "A product's reviews, one page at a time.",
35
- primary: { name: "id", description: "The product id, as get_product takes it.", required: true },
36
- paging: "For the next page pass params.page or params.cursor as the previous answer indicates.",
37
- },
38
- {
39
- name: "list_categories",
40
- title: "List categories",
41
- operation: "categories",
42
- 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.",
43
- },
44
- {
45
- name: "browse_category",
46
- title: "Browse a category",
47
- operation: "browse",
48
- summary: "The products in one category, with no keyword. Get category ids from list_categories.",
49
- paging: "For the next page pass params.page = 2, 3, …",
50
- },
51
- {
52
- name: "get_social_profile",
53
- title: "Get a social profile",
54
- operation: "profile",
55
- summary: "One account on a social platform: name, bio, follower counts, verification, links.",
56
- primary: { name: "username", description: "The handle, with or without @, or the profile URL.", required: false },
57
- },
58
- {
59
- name: "list_social_posts",
60
- title: "List social posts",
61
- operation: "posts",
62
- 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.",
63
- paging: "For the next page call again with params = { cursor } alone, using the cursor of the previous answer.",
64
- },
65
- {
66
- name: "get_social_post",
67
- title: "Get a social post",
68
- operation: "post",
69
- summary: "One post: text, author, media, counts, time.",
70
- primary: { name: "id", description: "The post id or shortcode, or its URL.", required: true },
71
- },
72
- {
73
- name: "get_social_comments",
74
- title: "Get comments",
75
- operation: "comments",
76
- summary: "A post's comments (params.post), one comment's replies (params.comment), or an account's comments.",
77
- paging: "For the next page call again with params = { cursor } alone.",
78
- },
79
- ];
80
- function describePlatform(e, operation) {
81
- const schema = e.params[operation];
82
- const props = Object.keys(schema?.properties ?? {});
83
- const required = new Set(schema?.required ?? []);
84
- const cost = e.cost?.[operation];
85
- const price = cost ? (cost.base === cost.max ? ` [${cost.base} unit${cost.base === 1 ? "" : "s"}]` : ` [${cost.base}–${cost.max} units]`) : "";
86
- return `- ${e.id}${price}: ${props.map((p) => (required.has(p) ? `${p}*` : p)).join(", ") || "(no parameters)"}`;
87
- }
88
- /**
89
- * A social post's media lists every rendition of each file (sizes, bitrates): on Threads that is three
90
- * quarters of a search answer. The model needs one, so each media keeps its main url, thumbnail and size,
91
- * and its `variants` are left out. Only media's: a product's `variants` (sizes, colours) are data.
92
- */
93
- function withoutRenditions(data) {
94
- if (Array.isArray(data))
95
- return data.map(withoutRenditions);
96
- if (data === null || typeof data !== "object")
97
- return data;
98
- const out = {};
99
- for (const [k, v] of Object.entries(data)) {
100
- out[k] =
101
- k === "media" && Array.isArray(v)
102
- ? v.map((m) => {
103
- if (m === null || typeof m !== "object")
104
- return m;
105
- const { variants: _renditions, ...rest } = m;
106
- return withoutRenditions(rest);
107
- })
108
- : withoutRenditions(v);
109
- }
110
- return out;
111
- }
112
- function result(raw, maxChars) {
113
- const data = withoutRenditions(raw);
114
- const text = JSON.stringify(data);
115
- if (text.length <= maxChars)
116
- return { content: [{ type: "text", text }] };
117
- // Too large: keep whole items, so the answer stays valid JSON — as many as fit, then say what is missing.
118
- const items = data?.items;
119
- if (Array.isArray(items) && items.length > 1) {
120
- const page = (n) => JSON.stringify({ ...data, items: items.slice(0, n) });
121
- let lo = 1;
122
- let hi = items.length - 1;
123
- while (lo < hi) {
124
- const mid = Math.ceil((lo + hi) / 2);
125
- if (page(mid).length <= maxChars)
126
- lo = mid;
127
- else
128
- hi = mid - 1;
129
- }
130
- if (page(lo).length <= maxChars) {
131
- return {
132
- content: [
133
- { type: "text", text: page(lo) },
134
- {
135
- type: "text",
136
- 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.`,
137
- },
138
- ],
139
- };
140
- }
141
- }
142
- return {
143
- 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]` }],
144
- };
145
- }
146
- function failure(e) {
147
- const text = e instanceof ApiError
148
- ? `${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" : ""}`
149
- : `apinoa: ${e instanceof Error ? e.message : String(e)}`;
150
- return { isError: true, content: [{ type: "text", text }] };
151
- }
152
- /** Build the server. Resolves the catalog first (live, else the bundled snapshot) so the tools can name the platforms. */
17
+ import { declarations, operations, overview, sandboxOperations, searchDocs } from "./code/docs.js";
18
+ import { Sandbox, denoRuns, findDeno } from "./code/sandbox.js";
19
+ import { failure, registerLegacyTools } from "./legacy.js";
20
+ export const VERSION = "0.2.0";
21
+ const DEFAULT_BUDGET = 500;
153
22
  export async function createApinoaServer(options = {}) {
154
23
  const api = {
155
24
  apiKey: options.apiKey ?? process.env.APINOA_API_KEY,
@@ -167,102 +36,25 @@ export async function createApinoaServer(options = {}) {
167
36
  catalog = SNAPSHOT;
168
37
  }
169
38
  }
170
- const server = new McpServer({ name: "apinoa", version: VERSION });
171
- const readOnly = { readOnlyHint: true, openWorldHint: true };
172
- for (const spec of TOOLS) {
173
- const platforms = catalog.filter((e) => e.operations.includes(spec.operation)).map((e) => e.id);
174
- if (platforms.length === 0)
175
- continue;
176
- const lines = catalog.filter((e) => platforms.includes(e.id)).map((e) => describePlatform(e, spec.operation));
177
- const description = [
178
- spec.summary,
179
- "",
180
- `Platforms and the params each accepts (* = required${spec.primary ? `; ${spec.primary.name} may be given at the top level` : ""}):`,
181
- ...lines,
182
- ...(spec.paging ? ["", spec.paging] : []),
183
- "",
184
- "Costs are in units of $0.001 at list price; a call that fails is not billed.",
185
- ].join("\n");
186
- const shape = {
187
- platform: z.enum(platforms).describe("Which platform to read."),
188
- };
189
- if (spec.primary) {
190
- const field = z.string().min(1).describe(spec.primary.description);
191
- shape[spec.primary.name] = spec.primary.required ? field : field.optional();
192
- }
193
- shape.params = z.record(z.unknown()).optional().describe("The platform's other parameters, by the names listed above.");
194
- server.registerTool(spec.name, { title: spec.title, description, inputSchema: shape, annotations: { title: spec.title, ...readOnly } }, async (args) => {
195
- try {
196
- const params = { ...(args.params ?? {}) };
197
- if (spec.primary && args[spec.primary.name] !== undefined)
198
- params[spec.primary.name] = args[spec.primary.name];
199
- return result(await callOperation(api, args.platform, spec.operation, params), maxChars);
200
- }
201
- catch (e) {
202
- return failure(e);
203
- }
204
- });
39
+ const asked = options.mode ?? (process.env.APINOA_MCP_MODE === "tools" ? "tools" : process.env.APINOA_MCP_MODE === "code" ? "code" : undefined);
40
+ // Code mode needs Deno, which the package installs for the platforms Deno ships for. Elsewhere, unless code
41
+ // mode was asked for by name, the server serves the tool set instead of a code tool that cannot run.
42
+ let mode = asked ?? "code";
43
+ if (!asked && !denoRuns(findDeno(options.sandbox?.deno))) {
44
+ mode = "tools";
45
+ console.error("apinoa-mcp: Deno was not found, so the per-operation tools are served instead of code mode. Install Deno (https://deno.com) or set APINOA_MCP_DENO to use code mode.");
205
46
  }
206
- const imagePlatforms = catalog.filter((e) => e.operations.includes("image-search")).map((e) => e.id);
207
- if (imagePlatforms.length)
208
- server.registerTool("search_products_by_image", {
209
- title: "Search products by image",
210
- 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: " +
211
- imagePlatforms.join(", "),
212
- inputSchema: {
213
- platform: z.enum(imagePlatforms).describe("Which marketplace to search."),
214
- image_url: z.string().url().describe("An http(s) URL of a JPEG or PNG photo."),
215
- params: z.record(z.unknown()).optional().describe("Other parameters of the platform's image-search (region, filters)."),
216
- },
217
- annotations: { title: "Search products by image", ...readOnly },
218
- }, async (args) => {
219
- try {
220
- const img = await download(api, args.image_url);
221
- const data = Buffer.from(img.bytes).toString("base64");
222
- return result(await callOperation(api, args.platform, "image-search", { ...(args.params ?? {}), image: { contentType: img.contentType, data } }), maxChars);
223
- }
224
- catch (e) {
225
- return failure(e);
226
- }
227
- });
228
- server.registerTool("call_apinoa", {
229
- title: "Call any apinoa operation",
230
- description: [
231
- "Call any operation of the apinoa API directly, for what the other tools do not cover (store catalogs, shipping quotes, groups, followers, LinkedIn jobs…).",
232
- "Every platform and its operations (params of each are listed by list_platforms):",
233
- ...catalog.map((e) => `- ${e.id}: ${e.operations.filter((op) => !FILE_OPERATIONS.has(`${e.id}/${op}`)).join(", ")}`),
234
- ].join("\n"),
235
- inputSchema: {
236
- platform: z.string().describe("Platform id, e.g. amazon, reddit."),
237
- operation: z.string().describe("Operation as written in the list, e.g. search, image-search, groups."),
238
- params: z.record(z.unknown()).optional().describe("The operation's parameters."),
239
- },
240
- annotations: { title: "Call any apinoa operation", ...readOnly },
241
- }, async (args) => {
242
- if (FILE_OPERATIONS.has(`${args.platform}/${args.operation}`)) {
243
- return failure(new ApiError(400, "FILE_OPERATION", `${args.platform}/${args.operation} returns a file; use the apinoa SDK or API for it`));
47
+ const server = new McpServer({ name: "apinoa", version: VERSION }, mode === "code"
48
+ ? {
49
+ instructions: "apinoa reads marketplaces (Amazon, Walmart, Shopify, TikTok Shop, AliExpress) and social platforms (TikTok, YouTube, Instagram, Threads, X, Reddit, LinkedIn). " +
50
+ "Find the operations and fields with search_docs, then call them from TypeScript in execute: fan out, page, filter and aggregate in the code, and return only the result.",
244
51
  }
245
- try {
246
- return result(await callOperation(api, args.platform, args.operation, args.params ?? {}), maxChars);
247
- }
248
- catch (e) {
249
- return failure(e);
250
- }
251
- });
252
- server.registerTool("list_platforms", {
253
- title: "List platforms",
254
- description: "Every platform apinoa serves, its operations, what each costs, and the parameters each operation accepts. Free, and needs no key.",
255
- inputSchema: {
256
- platform: z.string().optional().describe("Only this platform's details."),
257
- },
258
- annotations: { title: "List platforms", ...readOnly },
259
- }, async (args) => {
260
- const entries = catalog.filter((e) => !args.platform || e.id === args.platform);
261
- const text = entries
262
- .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"))
263
- .join("\n\n");
264
- return { content: [{ type: "text", text: text || `no platform ${args.platform}` }] };
265
- });
52
+ : undefined);
53
+ const readOnly = { readOnlyHint: true, openWorldHint: true };
54
+ if (mode === "tools")
55
+ registerLegacyTools(server, api, catalog, maxChars);
56
+ else
57
+ registerCodeTools(server, api, operations(catalog), options);
266
58
  server.registerTool("translate_image", {
267
59
  title: "Translate the text in an image",
268
60
  description: "Replace the text inside a product image with a translation, keeping fonts, colours and layout. Give the image as a URL. Returns the translated image.",
@@ -297,3 +89,62 @@ export async function createApinoaServer(options = {}) {
297
89
  });
298
90
  return server;
299
91
  }
92
+ const EXAMPLE = `const page = await apinoa.tiktok.posts({ hashtag: "glassskin", limit: 50 });
93
+ const authors = [...new Set(page.items.map((p) => p.author.handle))].slice(0, 10);
94
+ const recent = await many(authors, (u) => apinoa.tiktok.posts({ username: u, limit: 30 }));
95
+ return authors.map((u, i) => {
96
+ const views = (recent[i]?.items ?? []).map((p) => p.metrics?.views ?? 0).sort((a, b) => a - b);
97
+ return { author: u, median: views[Math.floor(views.length / 2)] ?? null };
98
+ });`;
99
+ function registerCodeTools(server, api, ops, options) {
100
+ const readOnly = { readOnlyHint: true, openWorldHint: true };
101
+ const sandbox = new Sandbox({ ...options.sandbox, api, userAgent: `apinoa-mcp/${VERSION} (code)` }, declarations(ops), sandboxOperations(ops));
102
+ const maxBudget = Number(process.env.APINOA_MCP_MAX_BUDGET ?? 20_000);
103
+ const platforms = [...new Set(ops.map((o) => o.platform))];
104
+ server.registerTool("search_docs", {
105
+ title: "Search the apinoa docs",
106
+ description: "Find how to do a task with apinoa: the matching operations as you call them in execute (e.g. apinoa.tiktok.posts({ hashtag })), every parameter, the cost per call, and the fields of what they return. " +
107
+ "Free: it calls nothing. Use it before writing code. Pass words ('tiktok hashtag videos', 'instagram reels of an account', 'amazon product reviews'), a platform, or a type name ('Post'); with neither you get the list of every operation.\n\n" +
108
+ `Platforms: ${platforms.join(", ")}.`,
109
+ inputSchema: {
110
+ query: z.string().optional().describe("What you want to do or read, in a few words, or a type name."),
111
+ platform: z.string().optional().describe("Only this platform's operations."),
112
+ },
113
+ annotations: { title: "Search the apinoa docs", readOnlyHint: true, openWorldHint: false },
114
+ }, async (args) => ({ content: [{ type: "text", text: searchDocs(ops, args.query ?? "", args.platform) }] }));
115
+ server.registerTool("execute", {
116
+ title: "Run code against apinoa",
117
+ description: [
118
+ "Run TypeScript that calls the apinoa API, and get back only what it prints or returns. Use it for every data task, from one call to thousands: fan out over accounts or posts, follow pages, then filter, count, rank and average in the code, so raw API answers never fill the conversation.",
119
+ "",
120
+ "The code is the body of an async function: use await, and `return` a small result (aggregate, slice, pick the fields you need). In scope:",
121
+ "- apinoa.<platform>.<operation>(params): one API call, returns the answer's data; throws ApinoaError (code, status) on a refusal. search_docs lists the parameters and the fields returned.",
122
+ "- pages(op, params, { maxPages }): every item of a paged operation, following cursors (default 5 pages).",
123
+ "- many(items, fn, { concurrency }): fn over every item, 8 at a time by default; a failed item comes back undefined.",
124
+ "- store.save(name, value) / store.load(name) / store.list() / store.saveFile(name, base64): data kept on this machine between runs.",
125
+ "- usage: { calls, units, budget } of this run.",
126
+ "The code is type-checked before it runs: an operation, parameter or field that does not exist fails there, before anything is billed.",
127
+ "Each call costs units (1 unit = $0.001, per search_docs); the run stops once budget_units are spent. Answers are cached for 10 minutes, so re-running after a fix costs nothing for calls already made. Only the API is reachable from the code.",
128
+ "",
129
+ "Example:",
130
+ EXAMPLE,
131
+ "",
132
+ overview(ops).split("\n\nHelpers")[0],
133
+ ].join("\n"),
134
+ inputSchema: {
135
+ code: z.string().min(1).describe("TypeScript: the body of an async function. Return the result."),
136
+ budget_units: z.number().int().positive().max(maxBudget).optional().describe(`Most units this run may spend (default ${DEFAULT_BUDGET}, at most ${maxBudget}).`),
137
+ timeout_seconds: z.number().int().positive().max(1800).optional().describe("Stop the run after this long (default 300)."),
138
+ },
139
+ annotations: { title: "Run code against apinoa", ...readOnly },
140
+ }, async (args, extra) => {
141
+ const token = extra?._meta?.progressToken;
142
+ const onProgress = token === undefined
143
+ ? undefined
144
+ : (s) => {
145
+ Promise.resolve(extra.sendNotification?.({ method: "notifications/progress", params: { progressToken: token, progress: s.calls, message: `${s.calls} calls, ${s.units} units` } })).catch(() => { });
146
+ };
147
+ const run = await sandbox.run(args.code, args.budget_units ?? DEFAULT_BUDGET, (args.timeout_seconds ?? 300) * 1000, onProgress);
148
+ return { content: [{ type: "text", text: run.text }], ...(run.ok ? {} : { isError: true }) };
149
+ });
150
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "apinoa-mcp",
3
- "version": "0.1.1",
4
- "description": "MCP server for apinoa: marketplace, social and image-translation data as tools for Claude, Cursor and any MCP client.",
3
+ "version": "0.2.0",
4
+ "description": "MCP server for apinoa: marketplace and social data for Claude, Cursor and any MCP client. Code mode: the model writes TypeScript against a typed client, run in a sandbox.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://apinoa.com/docs",
7
7
  "repository": {
@@ -9,7 +9,19 @@
9
9
  "url": "git+https://github.com/apinoahq/apinoa-mcp.git"
10
10
  },
11
11
  "bugs": "https://github.com/apinoahq/apinoa-mcp/issues",
12
- "keywords": ["mcp", "model-context-protocol", "apinoa", "amazon", "walmart", "shopify", "tiktok", "reddit", "youtube"],
12
+ "keywords": [
13
+ "mcp",
14
+ "model-context-protocol",
15
+ "code-mode",
16
+ "apinoa",
17
+ "amazon",
18
+ "walmart",
19
+ "shopify",
20
+ "tiktok",
21
+ "instagram",
22
+ "reddit",
23
+ "youtube"
24
+ ],
13
25
  "type": "module",
14
26
  "bin": {
15
27
  "apinoa-mcp": "dist/cli.js"
@@ -22,17 +34,21 @@
22
34
  "default": "./dist/server.js"
23
35
  }
24
36
  },
25
- "files": ["dist"],
37
+ "files": [
38
+ "dist"
39
+ ],
26
40
  "engines": {
27
41
  "node": ">=20"
28
42
  },
29
43
  "scripts": {
30
44
  "build": "rm -rf dist && tsc && chmod +x dist/cli.js",
31
45
  "test": "npm run build && node --test test/*.test.mjs",
32
- "test:live": "npm run build && node --test test/live/*.test.mjs"
46
+ "test:live": "npm run build && node --test test/live/*.test.mjs",
47
+ "gen:schema": "node scripts/gen-schema.mjs ../../apps/web/public/openapi.json"
33
48
  },
34
49
  "dependencies": {
35
50
  "@modelcontextprotocol/sdk": "^1.32.2",
51
+ "deno": "^2.9.6",
36
52
  "zod": "^3.25.76"
37
53
  },
38
54
  "devDependencies": {