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
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@ An [MCP](https://modelcontextprotocol.io) server for [apinoa](https://apinoa.com
|
|
|
4
4
|
and any other MCP client live product data from Amazon, Walmart, Shopify, TikTok Shop and AliExpress,
|
|
5
5
|
social data from TikTok, YouTube, Instagram, Threads, X, Reddit and LinkedIn, and image translation.
|
|
6
6
|
|
|
7
|
-
Ask things like *"
|
|
8
|
-
|
|
7
|
+
Ask things like *"which of @duolingo's last 30 TikToks got 3x its usual views"*, *"compare the cheapest
|
|
8
|
+
Stanley 40 oz on Amazon and Walmart"* or *"translate the text on this product photo into Korean"*.
|
|
9
9
|
|
|
10
10
|
## Setup
|
|
11
11
|
|
|
@@ -33,28 +33,56 @@ claude mcp add apinoa -e APINOA_API_KEY=your_key -- npx -y apinoa-mcp
|
|
|
33
33
|
}
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
Requires Node.js 20 or later.
|
|
36
|
+
Requires Node.js 20 or later. The package installs [Deno](https://deno.com), which runs the model's code.
|
|
37
37
|
|
|
38
38
|
## Tools
|
|
39
39
|
|
|
40
40
|
| Tool | What it does |
|
|
41
41
|
|---|---|
|
|
42
|
-
| `
|
|
43
|
-
| `
|
|
44
|
-
| `
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
42
|
+
| `search_docs` | Finds the operations for a task: how to call each, every parameter, the cost, and the fields it returns. Free |
|
|
43
|
+
| `execute` | Runs TypeScript the model writes against the API, and returns only what the code returns or prints |
|
|
44
|
+
| `translate_image` | Replaces the text in an image with a translation; returns the image |
|
|
45
|
+
|
|
46
|
+
Instead of one tool call per API call, the model writes a short program. Fanning out over 50 accounts,
|
|
47
|
+
following pages, filtering and averaging happen in the code, and only the answer comes back into the
|
|
48
|
+
conversation:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const page = await apinoa.tiktok.posts({ username: "duolingo", limit: 30 });
|
|
52
|
+
const views = page.items.map((p) => p.metrics?.views ?? 0).sort((a, b) => a - b);
|
|
53
|
+
const median = views[Math.floor(views.length / 2)];
|
|
54
|
+
return page.items.filter((p) => (p.metrics?.views ?? 0) >= 3 * median).map((p) => p.url);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Inside `execute`:
|
|
58
|
+
|
|
59
|
+
- `apinoa.<platform>.<operation>(params)`: one API call; returns the answer's `data`, throws `ApinoaError`
|
|
60
|
+
(`code`, `status`) on a refusal.
|
|
61
|
+
- `pages(op, params, { maxPages })`: every item of a paged operation, following cursors.
|
|
62
|
+
- `many(items, fn, { concurrency })`: `fn` over every item, 8 at a time; an item that fails comes back
|
|
63
|
+
`undefined` and is counted.
|
|
64
|
+
- `store.save / load / list / saveFile`: data kept on your machine between runs (videos from
|
|
65
|
+
`apinoa.tiktok.media`, for example).
|
|
66
|
+
- `usage`: this run's calls and units.
|
|
67
|
+
|
|
68
|
+
The code is type-checked against the API's types before it runs, so an operation, parameter or field that
|
|
69
|
+
does not exist fails there, before anything is billed. Each run has a budget (500 units by default, set per
|
|
70
|
+
run with `budget_units`) and stops once it is spent. Answers are cached for 10 minutes, so running fixed
|
|
71
|
+
code again costs nothing for the calls already made.
|
|
72
|
+
|
|
73
|
+
The code runs in a Deno subprocess that can reach only the apinoa API and read and write only its data
|
|
74
|
+
folder: no other hosts, no other files, no environment variables, no programs. The API key never enters
|
|
75
|
+
the code; the sandbox adds it to each request.
|
|
76
|
+
|
|
77
|
+
The platforms, operations and parameters are read from the live API catalog when the server starts, so a
|
|
78
|
+
platform added to apinoa appears without updating this package.
|
|
79
|
+
|
|
80
|
+
### The tool set
|
|
81
|
+
|
|
82
|
+
`APINOA_MCP_MODE=tools` serves the 0.1 tools instead: one tool per kind of read (`search_products`,
|
|
83
|
+
`get_product`, `list_social_posts`, `get_social_comments`, `call_apinoa`, `list_platforms`, …), one API call
|
|
84
|
+
per tool call. The server falls back to it by itself where Deno cannot run. An answer over 100,000
|
|
85
|
+
characters keeps as many whole items as fit, with a note saying how many were left out.
|
|
58
86
|
|
|
59
87
|
## Options
|
|
60
88
|
|
|
@@ -62,10 +90,13 @@ Every tool only reads data.
|
|
|
62
90
|
|---|---|---|
|
|
63
91
|
| `APINOA_API_KEY` | — | Required for every data call. |
|
|
64
92
|
| `APINOA_BASE_URL` | `https://gateway.apinoa.com` | |
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
93
|
+
| `APINOA_MCP_MODE` | `code` | `tools` for the 0.1 tool set. |
|
|
94
|
+
| `APINOA_MCP_DATA_DIR` | `~/.apinoa-mcp` | Where the cache, `store` and saved files live. |
|
|
95
|
+
| `APINOA_MCP_MAX_BUDGET` | `20000` | The most units one run may be given. |
|
|
96
|
+
| `APINOA_MCP_CONCURRENCY` | `16` | API calls in flight at once within a run. |
|
|
97
|
+
| `APINOA_MCP_CACHE_TTL_S` | `600` | How long an answer is reused; `0` turns the cache off. |
|
|
98
|
+
| `APINOA_MCP_MAX_OUTPUT` | `40000` | The most characters of output one run hands back to the model. |
|
|
99
|
+
| `APINOA_MCP_DENO` | the bundled one | Path to another `deno`. |
|
|
69
100
|
|
|
70
101
|
## Use as a library
|
|
71
102
|
|
|
@@ -78,7 +109,7 @@ const server = await createApinoaServer({ apiKey: process.env.APINOA_API_KEY });
|
|
|
78
109
|
|
|
79
110
|
## Related
|
|
80
111
|
|
|
81
|
-
- [apinoa](https://www.npmjs.com/package/
|
|
112
|
+
- [@apinoa/sdk](https://www.npmjs.com/package/@apinoa/sdk): the TypeScript SDK
|
|
82
113
|
- [apinoa on PyPI](https://pypi.org/project/apinoa/): the Python SDK
|
|
83
114
|
- [API documentation](https://apinoa.com/docs)
|
|
84
115
|
|
package/dist/api.js
CHANGED
|
@@ -83,7 +83,7 @@ export async function translateImage(o, image, contentType, query) {
|
|
|
83
83
|
export async function download(o, url, maxBytes = 20 * 1024 * 1024) {
|
|
84
84
|
if (!/^https?:\/\//i.test(url))
|
|
85
85
|
throw new ApiError(400, "INVALID_IMAGE_URL", "image_url must be an http(s) URL");
|
|
86
|
-
const res = await o.fetch(url, { signal: AbortSignal.timeout(30_000) });
|
|
86
|
+
const res = await o.fetch(url, { signal: AbortSignal.timeout(30_000), headers: { "user-agent": "apinoa-mcp (+https://apinoa.com)", accept: "image/*" } });
|
|
87
87
|
if (!res.ok)
|
|
88
88
|
throw new ApiError(400, "IMAGE_DOWNLOAD_FAILED", `the image URL answered ${res.status}`);
|
|
89
89
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
package/dist/catalog.snapshot.js
CHANGED
|
@@ -1922,8 +1922,8 @@ const snapshot = [
|
|
|
1922
1922
|
"limit": {
|
|
1923
1923
|
"type": "integer",
|
|
1924
1924
|
"minimum": 1,
|
|
1925
|
-
"maximum":
|
|
1926
|
-
"description": "Items per page, 1–
|
|
1925
|
+
"maximum": 30,
|
|
1926
|
+
"description": "Items per page, 1–30."
|
|
1927
1927
|
},
|
|
1928
1928
|
"cursor": {
|
|
1929
1929
|
"type": "string",
|
|
@@ -1991,8 +1991,8 @@ const snapshot = [
|
|
|
1991
1991
|
"limit": {
|
|
1992
1992
|
"type": "integer",
|
|
1993
1993
|
"minimum": 1,
|
|
1994
|
-
"maximum":
|
|
1995
|
-
"description": "Items per page, 1–
|
|
1994
|
+
"maximum": 30,
|
|
1995
|
+
"description": "Items per page, 1–30."
|
|
1996
1996
|
},
|
|
1997
1997
|
"cursor": {
|
|
1998
1998
|
"type": "string",
|
|
@@ -2071,8 +2071,8 @@ const snapshot = [
|
|
|
2071
2071
|
"limit": {
|
|
2072
2072
|
"type": "integer",
|
|
2073
2073
|
"minimum": 1,
|
|
2074
|
-
"maximum":
|
|
2075
|
-
"description": "Items per page, 1–
|
|
2074
|
+
"maximum": 30,
|
|
2075
|
+
"description": "Items per page, 1–30."
|
|
2076
2076
|
},
|
|
2077
2077
|
"cursor": {
|
|
2078
2078
|
"type": "string",
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What code mode tells the model: the typed `apinoa` client (for the type check and for search_docs), built
|
|
3
|
+
* from the live catalog so a new platform or parameter appears without a release, and the response types
|
|
4
|
+
* from the OpenAPI snapshot.
|
|
5
|
+
*/
|
|
6
|
+
import type { CatalogEntry } from "../api.js";
|
|
7
|
+
type Param = {
|
|
8
|
+
name: string;
|
|
9
|
+
type: string;
|
|
10
|
+
required: boolean;
|
|
11
|
+
description: string;
|
|
12
|
+
};
|
|
13
|
+
export interface Operation {
|
|
14
|
+
platform: string;
|
|
15
|
+
operation: string;
|
|
16
|
+
method: string;
|
|
17
|
+
returns: string;
|
|
18
|
+
cost: {
|
|
19
|
+
base: number;
|
|
20
|
+
max: number;
|
|
21
|
+
} | undefined;
|
|
22
|
+
params: Param[];
|
|
23
|
+
paged: boolean;
|
|
24
|
+
}
|
|
25
|
+
export declare function operations(catalog: CatalogEntry[]): Operation[];
|
|
26
|
+
/** The declarations code in \`execute\` is type-checked against. */
|
|
27
|
+
export declare function declarations(ops: Operation[]): string;
|
|
28
|
+
/** What the sandbox needs to build the client: platform → operation → [method, cost]. */
|
|
29
|
+
export declare function sandboxOperations(ops: Operation[]): Record<string, Record<string, [string, number]>>;
|
|
30
|
+
export declare function searchDocs(ops: Operation[], query?: string, platform?: string, limit?: number): string;
|
|
31
|
+
export declare function overview(ops: Operation[]): string;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { RETURNS, SCHEMA_TYPES } from "../schema.snapshot.js";
|
|
2
|
+
const camel = (s) => s.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
|
|
3
|
+
const pascal = (s) => camel(s).replace(/^./, (c) => c.toUpperCase());
|
|
4
|
+
// When the OpenAPI snapshot predates an operation, its shape still follows the shared vocabulary.
|
|
5
|
+
const BY_NAME = {
|
|
6
|
+
profile: "Account", profiles: "AccountPage", post: "Post", posts: "PostPage", comments: "CommentPage",
|
|
7
|
+
group: "Group", groups: "GroupPage", job: "Job", jobs: "JobPage", media: "MediaFile", search: "SearchResult",
|
|
8
|
+
browse: "SearchResult", "image-search": "SearchResult", product: "Product", reviews: "ReviewPage",
|
|
9
|
+
categories: "CategoryList", shipping: "ShippingQuote", catalog: "Catalog",
|
|
10
|
+
};
|
|
11
|
+
const TYPE_NAMES = new Set([...SCHEMA_TYPES.matchAll(/^(?:interface|type) (\w+)/gm)].map((m) => m[1]));
|
|
12
|
+
function paramType(s) {
|
|
13
|
+
if (!s || typeof s !== "object")
|
|
14
|
+
return "unknown";
|
|
15
|
+
if (s.enum)
|
|
16
|
+
return s.enum.map((v) => JSON.stringify(v)).join(" | ");
|
|
17
|
+
if (s.anyOf || s.oneOf)
|
|
18
|
+
return [...new Set((s.anyOf ?? s.oneOf).map(paramType))].join(" | ");
|
|
19
|
+
switch (s.type) {
|
|
20
|
+
case "string": return "string";
|
|
21
|
+
case "integer":
|
|
22
|
+
case "number": return "number";
|
|
23
|
+
case "boolean": return "boolean";
|
|
24
|
+
case "array": return `${paramType(s.items)}[]`;
|
|
25
|
+
// The one object input is an image: bytes, or a URL the server downloads.
|
|
26
|
+
case "object": return "string | { url: string } | { contentType: string; data: string }";
|
|
27
|
+
default: return "unknown";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function operations(catalog) {
|
|
31
|
+
const out = [];
|
|
32
|
+
for (const e of catalog) {
|
|
33
|
+
for (const op of e.operations) {
|
|
34
|
+
const schema = (e.params?.[op] ?? {});
|
|
35
|
+
const required = new Set(schema.required ?? []);
|
|
36
|
+
const params = Object.entries(schema.properties ?? {}).map(([name, s]) => ({
|
|
37
|
+
name,
|
|
38
|
+
type: paramType(s),
|
|
39
|
+
required: required.has(name),
|
|
40
|
+
description: String(s?.description ?? "").replace(/\s+/g, " ").trim(),
|
|
41
|
+
}));
|
|
42
|
+
const declared = RETURNS[`${e.id}/${op}`] ?? BY_NAME[op];
|
|
43
|
+
out.push({
|
|
44
|
+
platform: e.id,
|
|
45
|
+
operation: op,
|
|
46
|
+
method: camel(op),
|
|
47
|
+
returns: declared && TYPE_NAMES.has(declared) ? declared : "any",
|
|
48
|
+
cost: e.cost?.[op],
|
|
49
|
+
params,
|
|
50
|
+
paged: params.some((p) => p.name === "cursor") || /Page$/.test(declared ?? ""),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
const price = (c) => (c ? (c.base === c.max ? `${c.base} unit${c.base === 1 ? "" : "s"}` : `${c.base}–${c.max} units`) : "price in the catalog");
|
|
57
|
+
const paramsName = (o) => `${pascal(o.platform)}${pascal(o.method)}Params`;
|
|
58
|
+
const comment = (text, pad) => (text ? `${pad}/** ${text.replace(/\*\//g, "* /")} */\n` : "");
|
|
59
|
+
function paramsInterface(o) {
|
|
60
|
+
const fields = o.params.map((p) => `${comment(p.description, " ")} ${/^[A-Za-z_$][\w$]*$/.test(p.name) ? p.name : JSON.stringify(p.name)}${p.required ? "" : "?"}: ${p.type};`);
|
|
61
|
+
return `interface ${paramsName(o)} {\n${fields.join("\n")}\n}`;
|
|
62
|
+
}
|
|
63
|
+
const signature = (o) => `${o.method}(params${o.params.some((p) => p.required) ? "" : "?"}: ${paramsName(o)}): Promise<${o.returns}>`;
|
|
64
|
+
const HELPERS = `/** An API refusal: \`code\` is the stable code (NOT_FOUND, INVALID_PARAMS, …), \`status\` the HTTP status. */
|
|
65
|
+
declare class ApinoaError extends Error {
|
|
66
|
+
readonly code: string;
|
|
67
|
+
readonly status: number;
|
|
68
|
+
readonly requestId?: string;
|
|
69
|
+
}
|
|
70
|
+
/** Every page of a paged operation (anything returning a *Page), following \`cursor\`. Default at most 5 pages. */
|
|
71
|
+
declare function pages<P, T>(op: (params: P) => Promise<{ items: T[]; cursor?: string }>, params: P, options?: { maxPages?: number; maxItems?: number }): Promise<T[]>;
|
|
72
|
+
/** fn over every item, \`concurrency\` at a time (default 8). An item whose call fails comes back undefined and is counted in the usage line; a fatal error (no balance, budget spent) stops the run. */
|
|
73
|
+
declare function many<I, R>(items: readonly I[], fn: (item: I, index: number) => Promise<R>, options?: { concurrency?: number }): Promise<(R | undefined)[]>;
|
|
74
|
+
/** JSON kept on this machine between runs (and sessions), and files such as downloaded videos. */
|
|
75
|
+
declare const store: {
|
|
76
|
+
save(name: string, value: unknown): Promise<string>;
|
|
77
|
+
load<T = any>(name: string): Promise<T | undefined>;
|
|
78
|
+
list(): Promise<string[]>;
|
|
79
|
+
/** Writes base64 bytes (e.g. a MediaFile's data) to a file; returns its path. */
|
|
80
|
+
saveFile(name: string, base64: string): Promise<string>;
|
|
81
|
+
};
|
|
82
|
+
/** This run's spend so far. */
|
|
83
|
+
declare const usage: { readonly calls: number; readonly units: number; readonly budget: number };`;
|
|
84
|
+
/** The declarations code in \`execute\` is type-checked against. */
|
|
85
|
+
export function declarations(ops) {
|
|
86
|
+
const platforms = [...new Set(ops.map((o) => o.platform))];
|
|
87
|
+
const client = platforms
|
|
88
|
+
.map((p) => {
|
|
89
|
+
const methods = ops
|
|
90
|
+
.filter((o) => o.platform === p)
|
|
91
|
+
.map((o) => ` /** ${o.platform}/${o.operation}: ${price(o.cost)} a call. */\n ${signature(o)};`);
|
|
92
|
+
return ` ${p}: {\n${methods.join("\n")}\n };`;
|
|
93
|
+
})
|
|
94
|
+
.join("\n");
|
|
95
|
+
return [
|
|
96
|
+
"// Types for code run by apinoa-mcp's execute tool. Generated from the API catalog and OpenAPI document.",
|
|
97
|
+
SCHEMA_TYPES,
|
|
98
|
+
...ops.map(paramsInterface),
|
|
99
|
+
`/** The apinoa API, one method per operation. Each call returns the answer's \`data\`; a refusal throws ApinoaError. */\ndeclare const apinoa: {\n${client}\n};`,
|
|
100
|
+
HELPERS,
|
|
101
|
+
].join("\n\n");
|
|
102
|
+
}
|
|
103
|
+
/** What the sandbox needs to build the client: platform → operation → [method, cost]. */
|
|
104
|
+
export function sandboxOperations(ops) {
|
|
105
|
+
const out = {};
|
|
106
|
+
for (const o of ops)
|
|
107
|
+
(out[o.platform] ??= {})[o.operation] = [o.method, o.cost?.base ?? 1];
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
// ---- search_docs ---------------------------------------------------------------------------------------
|
|
111
|
+
const SYNONYMS = {
|
|
112
|
+
posts: ["video", "videos", "reel", "reels", "short", "shorts", "tweet", "tweets", "thread", "threads", "feed", "trending", "uploads", "content", "hashtag", "sound"],
|
|
113
|
+
profile: ["account", "user", "creator", "channel", "followers", "follower", "bio", "handle", "page"],
|
|
114
|
+
profiles: ["followers", "following", "channels"],
|
|
115
|
+
comments: ["comment", "replies", "reply", "discussion"],
|
|
116
|
+
search: ["find", "keyword", "products", "shop", "shopping", "price", "prices"],
|
|
117
|
+
product: ["item", "details", "variants", "asin", "price"],
|
|
118
|
+
reviews: ["review", "ratings", "rating", "stars"],
|
|
119
|
+
media: ["download", "mp4", "file", "video"],
|
|
120
|
+
groups: ["playlists", "communities", "subreddits"],
|
|
121
|
+
group: ["community", "subreddit", "hashtag", "sound"],
|
|
122
|
+
};
|
|
123
|
+
const words = (s) => s.toLowerCase().split(/[^a-z0-9@#_-]+/).map((w) => w.replace(/^[#@]/, "")).filter((w) => w.length > 1);
|
|
124
|
+
function score(o, query) {
|
|
125
|
+
let s = 0;
|
|
126
|
+
const syn = SYNONYMS[o.operation] ?? [];
|
|
127
|
+
for (const w of query) {
|
|
128
|
+
const stem = w.replace(/s$/, "");
|
|
129
|
+
if (w === o.platform || (o.platform === "x" && w === "twitter") || (o.platform === "youtube" && w === "yt"))
|
|
130
|
+
s += 4;
|
|
131
|
+
if (w === o.operation || stem === o.operation.replace(/s$/, "") || w === o.method.toLowerCase())
|
|
132
|
+
s += 4;
|
|
133
|
+
if (syn.includes(w))
|
|
134
|
+
s += 2;
|
|
135
|
+
for (const p of o.params) {
|
|
136
|
+
if (p.name.toLowerCase() === w || p.name.toLowerCase() === stem)
|
|
137
|
+
s += 2;
|
|
138
|
+
else if (p.description.toLowerCase().includes(w))
|
|
139
|
+
s += 0.3;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return s;
|
|
143
|
+
}
|
|
144
|
+
/** The referenced response types, breadth-first from the operations' return types, up to a size. */
|
|
145
|
+
function typesFor(roots, maxChars = 9000) {
|
|
146
|
+
const blocks = new Map();
|
|
147
|
+
for (const m of SCHEMA_TYPES.matchAll(/^(?:\/\*\*[^\n]*\*\/\n)?(?:interface|type) (\w+)[\s\S]*?(?=^(?:\/\*\*|interface |type )|(?![\s\S]))/gm)) {
|
|
148
|
+
blocks.set(m[1], m[0].trimEnd());
|
|
149
|
+
}
|
|
150
|
+
const seen = new Set();
|
|
151
|
+
const queue = roots.filter((r) => blocks.has(r));
|
|
152
|
+
const out = [];
|
|
153
|
+
let size = 0;
|
|
154
|
+
const skipped = [];
|
|
155
|
+
while (queue.length) {
|
|
156
|
+
const name = queue.shift();
|
|
157
|
+
if (seen.has(name))
|
|
158
|
+
continue;
|
|
159
|
+
seen.add(name);
|
|
160
|
+
const block = blocks.get(name);
|
|
161
|
+
if (size + block.length > maxChars && out.length) {
|
|
162
|
+
skipped.push(name);
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
out.push(block);
|
|
166
|
+
size += block.length;
|
|
167
|
+
for (const ref of block.matchAll(/\b([A-Z]\w+)\b/g))
|
|
168
|
+
if (blocks.has(ref[1]) && !seen.has(ref[1]))
|
|
169
|
+
queue.push(ref[1]);
|
|
170
|
+
}
|
|
171
|
+
const more = skipped.length ? `\n// Not shown (ask search_docs for them by name): ${[...new Set(skipped)].join(", ")}` : "";
|
|
172
|
+
return out.join("\n") + more;
|
|
173
|
+
}
|
|
174
|
+
function describe(o) {
|
|
175
|
+
const params = o.params.map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type}${p.description ? ` — ${p.description}` : ""}`).join("\n");
|
|
176
|
+
const paging = o.paged
|
|
177
|
+
? `\n Next page: apinoa.${o.platform}.${o.method}({ cursor }) with the previous answer's cursor alone, or pages(apinoa.${o.platform}.${o.method}, { … }, { maxPages }).`
|
|
178
|
+
: "";
|
|
179
|
+
return `apinoa.${o.platform}.${o.method}(params) → ${o.returns} [${price(o.cost)} per call]\n params:\n${params || " (none)"}${paging}`;
|
|
180
|
+
}
|
|
181
|
+
export function searchDocs(ops, query = "", platform, limit = 6) {
|
|
182
|
+
const q = words(query);
|
|
183
|
+
const typeAsked = query.match(/\b([A-Z][A-Za-z]+)\b/g)?.filter((t) => TYPE_NAMES.has(t)) ?? [];
|
|
184
|
+
let pool = platform ? ops.filter((o) => o.platform === platform.toLowerCase()) : ops;
|
|
185
|
+
if (platform && !pool.length)
|
|
186
|
+
return `No platform "${platform}". Platforms: ${[...new Set(ops.map((o) => o.platform))].join(", ")}.`;
|
|
187
|
+
// A query that names platforms is about those platforms only.
|
|
188
|
+
const named = new Set(q.map((w) => (w === "twitter" ? "x" : w === "yt" ? "youtube" : w)).filter((w) => pool.some((o) => o.platform === w)));
|
|
189
|
+
if (!platform && named.size)
|
|
190
|
+
pool = pool.filter((o) => named.has(o.platform));
|
|
191
|
+
if (!q.length && !platform && !typeAsked.length)
|
|
192
|
+
return overview(ops);
|
|
193
|
+
let picked = pool;
|
|
194
|
+
if (q.length) {
|
|
195
|
+
const ranked = pool.map((o) => ({ o, s: score(o, q) })).filter((x) => x.s > 0).sort((a, b) => b.s - a.s);
|
|
196
|
+
picked = ranked.slice(0, platform ? Math.max(limit, 8) : limit).map((x) => x.o);
|
|
197
|
+
}
|
|
198
|
+
if (!picked.length && !typeAsked.length)
|
|
199
|
+
return `Nothing matched "${query}".\n\n${overview(ops)}`;
|
|
200
|
+
const types = typesFor([...typeAsked, ...new Set(picked.map((o) => o.returns))]);
|
|
201
|
+
return [
|
|
202
|
+
picked.map(describe).join("\n\n"),
|
|
203
|
+
types ? `Types the calls return (fields not listed here do not exist; ext holds platform-only extras as unknown):\n${types}` : "",
|
|
204
|
+
].filter(Boolean).join("\n\n");
|
|
205
|
+
}
|
|
206
|
+
export function overview(ops) {
|
|
207
|
+
const byPlatform = new Map();
|
|
208
|
+
for (const o of ops)
|
|
209
|
+
byPlatform.set(o.platform, [...(byPlatform.get(o.platform) ?? []), o.method]);
|
|
210
|
+
return [
|
|
211
|
+
"Operations (call search_docs with words or a platform for parameters, costs and the fields returned):",
|
|
212
|
+
...[...byPlatform].map(([p, m]) => `- apinoa.${p}: ${m.join(", ")}`),
|
|
213
|
+
"",
|
|
214
|
+
"Helpers inside execute: pages(op, params, { maxPages }) follows cursors; many(items, fn, { concurrency }) fans out; store.save/load/list/saveFile keep data on this machine between runs; usage shows this run's units.",
|
|
215
|
+
].join("\n");
|
|
216
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type ApiOptions } from "../api.js";
|
|
2
|
+
export interface SandboxOptions {
|
|
3
|
+
api: ApiOptions;
|
|
4
|
+
userAgent: string;
|
|
5
|
+
/** Cache and store live here; defaults to APINOA_MCP_DATA_DIR or ~/.apinoa-mcp. */
|
|
6
|
+
dataDir?: string;
|
|
7
|
+
/** Parallel API calls in one run. */
|
|
8
|
+
concurrency?: number;
|
|
9
|
+
/** How long an answer may be reused, in ms (0 turns the cache off). */
|
|
10
|
+
cacheTtlMs?: number;
|
|
11
|
+
/** Most characters of output (printed text and the returned value) handed back to the model. */
|
|
12
|
+
maxOutputChars?: number;
|
|
13
|
+
/** The deno executable; found in the package's own dependency, then on PATH. */
|
|
14
|
+
deno?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface RunStats {
|
|
17
|
+
calls: number;
|
|
18
|
+
cached: number;
|
|
19
|
+
units: number;
|
|
20
|
+
failed: number;
|
|
21
|
+
errors: string[];
|
|
22
|
+
}
|
|
23
|
+
export interface RunResult {
|
|
24
|
+
ok: boolean;
|
|
25
|
+
/** The text the model sees. */
|
|
26
|
+
text: string;
|
|
27
|
+
stats: RunStats;
|
|
28
|
+
}
|
|
29
|
+
export declare function findDeno(explicit?: string): string;
|
|
30
|
+
/** Whether the deno at `path` runs. */
|
|
31
|
+
export declare function denoRuns(path: string): boolean;
|
|
32
|
+
export declare class Sandbox {
|
|
33
|
+
private readonly opts;
|
|
34
|
+
private readonly declarations;
|
|
35
|
+
private readonly operations;
|
|
36
|
+
private readonly deno;
|
|
37
|
+
private readonly dataDir;
|
|
38
|
+
private readonly runtimeDir;
|
|
39
|
+
private readonly prelude;
|
|
40
|
+
private readonly host;
|
|
41
|
+
private prepared?;
|
|
42
|
+
constructor(opts: SandboxOptions, declarations: string, operations: Record<string, Record<string, [string, number]>>);
|
|
43
|
+
private prepare;
|
|
44
|
+
private get cacheTtlMs();
|
|
45
|
+
run(code: string, budget: number, timeoutMs: number, onProgress?: (s: RunStats) => void): Promise<RunResult>;
|
|
46
|
+
/** A request from the sandbox: only the image download image-search needs. */
|
|
47
|
+
private answer;
|
|
48
|
+
}
|
|
49
|
+
/** Deno's type errors, with line numbers counted in the user's code. */
|
|
50
|
+
export declare function typeCheckErrors(stderr: string): string;
|