@foldbun/stack-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-11-23
4
+
5
+ Published to npm as `@foldbun/stack-mcp`; the command is still `foldbun-stack-mcp`.
6
+
7
+
8
+ - First version: MCP stdio server with `stack_ocr`, `stack_segment`, `stack_remove_background`, `stack_parse_document`, `stack_embed`, `stack_usage` and `stack_register_agent_project`.
9
+ - Credential chain: `FOLDBUN_API_KEY`, `FOLDBUN_PROJECT_ID`, saved agent project; no built-in project ID and no automatic registration.
10
+ - Results are written to files; the claim link of an agent project is shown once and never stored.
11
+ - `HTTPS_PROXY` / `HTTP_PROXY` / `NO_PROXY` and `FOLDBUN_BASE_URL` supported.
12
+ - Image input in every image tool as a local path, an `http(s)` URL (downloaded by the server with SSRF guards, a size cap, redirect limit and content-type and magic-byte checks), a `data:` URL or raw base64.
13
+ - Inline image results: `stack_remove_background` and `stack_segment` attach their picture as an MCP image block (cap 1 MiB, PNG previews downscaled to 1,024 px); `returnImage: false` turns it off. `stack_segment` now writes a raster PNG overlay (drawn on the picture for PNG inputs) next to the SVG, with a pure-JavaScript PNG codec.
14
+ - `stack_batch`: one operation over a folder or list of files, resumable, with `summary.csv`, Retry-After handling, a time budget and progress notifications.
15
+ - `stack_product_photo`, `stack_annotate`, `stack_document_to_markdown` and `stack_image_search` (local siglip2 index, incremental).
16
+ - Rate-limit line now says "per minute" and when the window is full again; daily limits are only reported by `stack_usage`.
17
+ - Test that the image tools are listed even before a credential exists.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Foldbun Technologies Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
1
+ # Foldbun Stack MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [MCP](https://modelcontextprotocol.io) server that gives AI agents and coding assistants precise image tools from [Foldbun Stack](https://stack.foldbun.com/): text recognition (OCR), document page parsing, object segmentation with SAM 3, background removal and embeddings.
4
+
5
+ Foldbun Stack analyses images; it is **not** a vision-language model. It cannot describe a picture or answer open questions about it. It reads text, finds and outlines what you name, and cuts subjects out. Use it next to a vision-language model, not instead of one.
6
+
7
+ > Package: [`@foldbun/stack-mcp`](https://www.npmjs.com/package/@foldbun/stack-mcp) on npm. The command it installs is `foldbun-stack-mcp`.
8
+
9
+ ## Requirements
10
+
11
+ - Node.js 24.9 or newer.
12
+ - Network access to `https://api.stack.foldbun.com` (see [Network and mainland China](#network-and-mainland-china)).
13
+
14
+ ## Install and configure
15
+
16
+ The server speaks MCP over stdio. Use the same command in any client:
17
+
18
+ ```
19
+ npx -y @foldbun/stack-mcp
20
+ ```
21
+
22
+ ### Claude Code
23
+
24
+ ```
25
+ claude mcp add foldbun-stack -- npx -y @foldbun/stack-mcp
26
+ ```
27
+
28
+ With a credential (see [Credentials](#credentials)):
29
+
30
+ ```
31
+ claude mcp add foldbun-stack -e FOLDBUN_API_KEY="$FOLDBUN_API_KEY" -- npx -y @foldbun/stack-mcp
32
+ ```
33
+
34
+ ### Cursor
35
+
36
+ Add to `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (global):
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "foldbun-stack": {
42
+ "command": "npx",
43
+ "args": ["-y", "@foldbun/stack-mcp"],
44
+ "env": { "FOLDBUN_API_KEY": "${env:FOLDBUN_API_KEY}" }
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ ### Other MCP clients
51
+
52
+ Register a stdio server whose command is `npx -y @foldbun/stack-mcp`, and pass credentials through the server's environment. Most clients take a JSON block like the one above. Prefer your client's environment-variable interpolation over pasting a key into a config file.
53
+
54
+ ### DeepSeek Harness
55
+
56
+ See [`@foldbun/dsh-stack`](https://www.npmjs.com/package/@foldbun/dsh-stack), a bundle that mounts this server in DSH.
57
+
58
+ ## Credentials
59
+
60
+ The server looks for a credential in this order and uses the first it finds:
61
+
62
+ 1. `FOLDBUN_API_KEY` (starts with `fbs_`): paid use, billed to your account. Create a key in the [console](https://stack.foldbun.com/console/keys).
63
+ 2. `FOLDBUN_PROJECT_ID` (starts with `fbp_`): the free tier of a project. A project ID is public, not a secret.
64
+ 3. An agent project saved by an earlier registration (see below), stored in the user config directory.
65
+ 4. Nothing. Calls then fail with a message that lists these options, and the tool `stack_register_agent_project` is offered to the model.
66
+
67
+ There is no built-in project ID, and the server never registers anything by itself. It sends either an `Authorization` header (key) or an `X-Foldbun-Project` header (project), never both as credentials.
68
+
69
+ ### Agent projects
70
+
71
+ An AI agent that is developing or evaluating on behalf of an operator and has no credentials may call `stack_register_agent_project` with a truthful purpose. The result is a restricted free-tier project with limits shared per network, meant for development and evaluation, not production traffic or software you ship. The call returns a **claim link once**: the agent should hand it to its operator, who opens it and signs in to Foldbun ID to turn the project into one of their own. The server does not write the claim link to any file or log. The project ID (not the claim link) is saved to `agent-project.json` in the config directory with mode 0600 and is used for later calls.
72
+
73
+ ## Tools
74
+
75
+ Every image tool takes `image` in any of these forms (JPEG, PNG or static WebP): a local file path, an `http(s)` URL, a `data:` URL, or raw base64. Results are written to files and the tool returns their paths, so large payloads stay out of the model's context; tools that produce pictures also attach them as an inline image when small enough (see below). This makes the server usable by agents that have no shell and no local files, for example a chat bot or an agent that can only run code in a sandbox.
76
+
77
+ | Tool | What it does | Main inputs | Output |
78
+ |---|---|---|---|
79
+ | `stack_ocr` | Reads text with ppocr-v6 (mixed Chinese, Japanese and English work well). Lines in rough top-to-bottom order; no layout analysis. | `image`; `minConfidence` (0 to 1, default 0.5); `boxes` (list line boxes); `words` (word boxes in the JSON) | Recognised lines inside a block marked as untrusted data; full JSON file |
80
+ | `stack_segment` | Finds and outlines objects with SAM 3 or sam-lite. | `image`; `prompts` (text, sam3 only); `boxes` (exemplar boxes for sam3, object boxes for sam-lite); `points`; `model` (`sam3` default, `sam-lite`); `minScore`; `maxInstances`; `masks`; `returnImage` | Instance list with labels, scores, boxes, areas and polygon sizes; JSON with polygons; an overlay PNG (inline image) and an SVG overlay; optional grayscale mask PNGs |
81
+ | `stack_remove_background` | Cuts the main subject out with BiRefNet. | `image`; `output` (`cutout` default, `matte`); `format` (`png` default, `webp`); `size` (long side, default 2048); `returnImage` | A PNG or WebP file, also attached as an inline image when small |
82
+ | `stack_parse_document` | Layout analysis and recognition of one document page with paddleocr-vl: Markdown (tables as HTML, formulas as LaTeX) plus layout blocks in reading order. One page image per call, no PDFs. Not offered to agent projects; needs a project claimed by an operator or an API key. | `image`; `blocks` (default true) | Markdown (shown inline up to 8,000 characters, untrusted data), a Markdown file and a JSON file with blocks and boxes |
83
+ | `stack_embed` | L2-normalised embeddings. `siglip2` puts images and texts in one vector space; `dinov3` embeds images for image-to-image similarity. | exactly one of `image` or `texts` (1 to 64 strings); `model` (`siglip2` default, `dinov3`) | Dimension and a short preview; vectors in a JSON file |
84
+ | `stack_batch` | One operation over a whole folder (or a list of files or URLs): `ocr`, `remove_background`, `segment`, `parse_document` or `embed`. Resumable and rate-limit aware. | `operation`; `inputDir` or `files`; `recursive`; `outputDir`; `prompts` (segment); `model`, `format`, `size`, `minConfidence`, `minScore`; `maxFiles` (default 200), `maxSeconds` (default 240), `concurrency` (API key only), `overwrite` | Per-image output files plus `summary.csv` (file, status, error code, detail, request ID, output); a compact text summary |
85
+ | `stack_product_photo` | Remove the background, crop to the subject and place it on white, a colour or a transparent canvas. | `image`; `background` (`white`, `transparent`, hex); `padding` (fraction, default 0.1); `square`; `crop`; `size`; `returnImage` | PNG file and inline image |
86
+ | `stack_annotate` | Find objects by text prompt and draw a numbered, labelled box on each. | `image`; `prompts`; `outlines`; `minScore`; `maxInstances`; `returnImage` | Annotated PNG (file and inline), list of labels and boxes, JSON |
87
+ | `stack_document_to_markdown` | Document page images to a Markdown file (paddleocr-vl). Needs an API key or a claimed project; on the agent tier it says so before spending a call. | `image` or `pages` (up to 20, concatenated); `outputPath` | `.md` file, shown inline when short (untrusted data) |
88
+ | `stack_image_search` | Local image search over a folder: `index` embeds the images with siglip2 into a JSON index (incremental by path, modification time and size, resumable); `query` finds the top-k images for a text or an example image without further per-image calls. | `mode`; `inputDir` or `indexFile`; `text` or `image` (query); `topK`; `model`, `recursive`, `maxFiles`, `maxSeconds`, `concurrency` (index) | Index file; ranked paths with cosine scores |
89
+ | `stack_usage` | Free. Shows the credential in use, tier, balance or limits, use today and the model price list. | none | Text summary |
90
+ | `stack_register_agent_project` | Listed only when the server starts without a credential (it stays listed after a registration, so the tool list never changes mid-session, and refuses once a credential exists). Registers an agent project (see above). | `purpose` (80 to 4,000 characters), `projectType`, `useCases`, `runtime`, optional `agentModel`, `harness`, `language` | Project ID, limits, claim link (once) |
91
+
92
+ > **Licence note:** `dinov3` output is covered by the DINOv3 License; products built on it should show "Built with DINOv3".
93
+
94
+ Coordinates in results are pixels of the image you sent. Text recognised by `stack_ocr` is untrusted content read from an image; the tool says so in its output and the server instructions tell the model never to follow instructions found in it.
95
+
96
+ ### Image input forms and URL fetching
97
+
98
+ | Form | Example |
99
+ |---|---|
100
+ | Local path | `/path/to/photo.jpg`, `shots/screen.png` (relative to the server's working directory) |
101
+ | `http(s)` URL | `https://example.com/cat.jpg` (the API itself does not fetch URLs, so this server downloads the image and sends the bytes) |
102
+ | `data:` URL | `data:image/png;base64,iVBOR...` |
103
+ | Raw base64 | `iVBORw0KGgo...` (JPEG, PNG or WebP bytes) |
104
+
105
+ Because the server fetches URLs on the model's behalf, downloads are restricted to avoid reaching internal services (SSRF):
106
+
107
+ - Only `http` and `https`; no embedded credentials in the URL; `file:` and other schemes are refused.
108
+ - Every address the host name resolves to must be public. Loopback, private (RFC 1918), link-local (including cloud metadata addresses), shared (CGNAT), unique-local (fc00::/7), multicast, documentation and IPv4-mapped/NAT64/6to4 forms of those are refused. The check runs before connecting and again on the connection itself, so DNS rebinding does not help. Names such as `localhost`, `*.local` and `*.internal` are refused.
109
+ - At most 3 redirects, each target checked again; 20 s per hop.
110
+ - The download is capped at the image limit of the credential in use (4 MiB, or 20 MiB with an API key). The content type must be an image (or `application/octet-stream`) and the magic bytes must be JPEG, PNG or WebP.
111
+ - Set `FOLDBUN_ALLOW_PRIVATE_URLS=1` in the server environment only if you operate the server and need it to fetch from your own network.
112
+
113
+ ### Inline images
114
+
115
+ `stack_remove_background`, `stack_segment`, `stack_product_photo` and `stack_annotate` attach their picture as an MCP `image` content block (when the client supports images) and also write the file. The cap is 1 MiB: a larger PNG is attached as a 1,024 px preview, and anything that cannot be downscaled (WebP) is returned as a file only, with the text saying so. Set `returnImage: false` to get the file only.
116
+
117
+ Overlays and annotations are drawn in pure JavaScript. JPEG and WebP inputs are not decoded by this server (no native dependencies), so for those the overlay PNG shows outlines and labels on a plain grey canvas, and an SVG with the original picture is written next to it. Convert the input to PNG to get the boxes drawn on the picture. Bitmap labels use a small upper-case font; a non-ASCII label is drawn with `?` and listed correctly in the text.
118
+
119
+ ### Batches and long jobs
120
+
121
+ `stack_batch` and the `index` mode of `stack_image_search` process at most 200 images and run for at most 240 s per call by default (`maxFiles`, `maxSeconds`). They stop cleanly, say how many are left and can be called again with the same arguments: finished images are skipped (outputs exist, or the index entry matches path, modification time and size). Free credentials run one call at a time and wait out rate limits (`Retry-After`); a daily limit, an authorisation failure or a missing balance stops the run instead of failing every file. Progress notifications are sent when the client asks for them, and cancelling the call stops the queue. Many clients abort a tool call after about 60 s unless progress is reported, so on slow credentials use a smaller `maxSeconds`.
122
+
123
+ Output files go to `.foldbun-stack/` in the directory the server runs in (set `FOLDBUN_OUTPUT_DIR` to change it). Add that directory to your `.gitignore`.
124
+
125
+ ## Limits
126
+
127
+ - Free and agent tiers accept images up to 4 MiB; with an API key the limit is 20 MiB. The server does not resize: downscale large images first (a long side of about 2,000 px is plenty for most uses).
128
+ - Free and agent tiers have per-minute and daily limits (see `stack_usage`). Agent-project limits are shared by network. Daily counts reset at 00:00 UTC.
129
+ - Send one call at a time (batches do this for you). On a retryable error the server waits the time the API states (up to 15 s) and retries once; after that it reports the error with its request ID and does not loop.
130
+ - Prices are per call and listed by `stack_usage`. Free-tier calls are not charged.
131
+
132
+ ## Configuration
133
+
134
+ | Variable | Meaning | Default |
135
+ |---|---|---|
136
+ | `FOLDBUN_API_KEY` | Paid API key (`fbs_...`) | unset |
137
+ | `FOLDBUN_PROJECT_ID` | Free-tier project ID (`fbp_...`) | unset |
138
+ | `FOLDBUN_BASE_URL` | API endpoint, for example a reverse proxy you operate | `https://api.stack.foldbun.com` |
139
+ | `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | Outbound proxy (lower-case names also work) | unset |
140
+ | `FOLDBUN_OUTPUT_DIR` | Where result files are written | `./.foldbun-stack` |
141
+ | `FOLDBUN_STATE_DIR` | Where the saved agent project lives | `$XDG_CONFIG_HOME/foldbun-stack-mcp` (`~/.config/foldbun-stack-mcp`) |
142
+ | `FOLDBUN_TIMEOUT_MS` | Per-request timeout | `120000` |
143
+ | `FOLDBUN_ALLOW_PRIVATE_URLS` | Set to `1` to let image URL downloads reach private and loopback addresses (see above) | unset |
144
+ | `FOLDBUN_SOURCE_PROJECT` | Optional project ID recorded as the source of paid calls, for usage statistics | unset |
145
+
146
+ ## Data handling
147
+
148
+ The images you send are uploaded to Foldbun Stack servers (storage in Hong Kong, GPU servers in mainland China). They are not used for training and are deleted within 7 days. Do not send images you are not allowed to share with a third-party service, and tell your user before sending sensitive ones. See the [privacy policy](https://foldbun.com/privacy/). The server stores nothing except result files in the output directory and, for agent projects, the public project ID.
149
+
150
+ ## Network and mainland China
151
+
152
+ Access to `api.stack.foldbun.com` from mainland China is not guaranteed. If connections fail or time out, set `HTTPS_PROXY` (and `NO_PROXY` for hosts that must stay direct), or point `FOLDBUN_BASE_URL` at an endpoint you can reach. Network failures are reported as `network_unreachable` or `client_timeout` with this advice.
153
+
154
+ ## Development
155
+
156
+ ```
157
+ npm install
158
+ npm test # offline tests against a mock API
159
+ npm run smoke:live # opt-in: registers a throw-away agent project and calls the real API once per tool
160
+ ```
161
+
162
+ `scripts/live-smoke.mjs` uses scratch directories, redacts the claim link and is not part of `npm test`.
163
+
164
+ ## License
165
+
166
+ MIT
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/server.js'
3
+
4
+ main().catch((err) => {
5
+ // stdout carries the MCP protocol; diagnostics go to stderr only (never credentials).
6
+ process.stderr.write(`foldbun-stack-mcp: ${err?.message ?? err}\n`)
7
+ process.exit(1)
8
+ })
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@foldbun/stack-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MCP server for Foldbun Stack: OCR, segmentation, background removal and document parsing for AI agents.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "foldbun-stack-mcp": "bin/foldbun-stack-mcp.mjs"
9
+ },
10
+ "main": "src/index.js",
11
+ "exports": {
12
+ ".": "./src/index.js",
13
+ "./server": "./src/server.js"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE"
21
+ ],
22
+ "engines": {
23
+ "node": ">=24.9.0"
24
+ },
25
+ "scripts": {
26
+ "test": "node --test \"test/*.test.mjs\"",
27
+ "smoke:live": "node scripts/live-smoke.mjs"
28
+ },
29
+ "dependencies": {
30
+ "@modelcontextprotocol/sdk": "1.32.2",
31
+ "zod": "4.6.7"
32
+ },
33
+ "keywords": [
34
+ "mcp",
35
+ "model-context-protocol",
36
+ "ocr",
37
+ "segmentation",
38
+ "sam3",
39
+ "background-removal",
40
+ "foldbun-stack"
41
+ ],
42
+ "homepage": "https://stack.foldbun.com/",
43
+ "author": "Foldbun Technologies Limited",
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
package/src/batch.js ADDED
@@ -0,0 +1,129 @@
1
+ // Helpers for multi-file work: listing images, a retrying work queue that honours Retry-After
2
+ // and a deadline, and a minimal CSV reader/writer for summary.csv.
3
+
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import crypto from 'node:crypto'
7
+ import { StackError } from './client.js'
8
+ import { UserError } from './files.js'
9
+
10
+ export const IMAGE_EXT = /\.(jpe?g|png|webp)$/i
11
+
12
+ /** Sorted image files of a directory (hidden files skipped). Returns [{ abs, name }], name relative with "/". */
13
+ export function listImages(dir, recursive = false) {
14
+ const root = path.resolve(dir)
15
+ let st
16
+ try {
17
+ st = fs.statSync(root)
18
+ } catch {
19
+ throw new UserError(`Directory not found: ${root}`)
20
+ }
21
+ if (!st.isDirectory()) throw new UserError(`Not a directory: ${root}`)
22
+ const out = []
23
+ const walk = (d, rel) => {
24
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
25
+ if (e.name.startsWith('.')) continue
26
+ if (e.isDirectory()) {
27
+ if (recursive) walk(path.join(d, e.name), rel ? `${rel}/${e.name}` : e.name)
28
+ } else if (e.isFile() && IMAGE_EXT.test(e.name)) {
29
+ out.push({ abs: path.join(d, e.name), name: rel ? `${rel}/${e.name}` : e.name })
30
+ }
31
+ }
32
+ }
33
+ walk(root, '')
34
+ return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
35
+ }
36
+
37
+ export const shortHash = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 6)
38
+
39
+ /** A file-system safe, flat name for an item: "sub/a.jpg" becomes "sub__a.jpg". */
40
+ export const flatName = (name) => name.replace(/[\\/]+/g, '__').replace(/[^\w.\- ]+/g, '_')
41
+
42
+ // ---- CSV ----
43
+
44
+ const needsQuote = /[",\r\n]/
45
+ export const csvLine = (fields) => fields.map((f) => { const s = String(f ?? ''); return needsQuote.test(s) ? `"${s.replace(/"/g, '""')}"` : s }).join(',')
46
+
47
+ export function parseCsv(textIn) {
48
+ const rows = []
49
+ let row = []
50
+ let field = ''
51
+ let q = false
52
+ for (let i = 0; i < textIn.length; i++) {
53
+ const c = textIn[i]
54
+ if (q) {
55
+ if (c === '"' && textIn[i + 1] === '"') { field += '"'; i++ } else if (c === '"') q = false
56
+ else field += c
57
+ } else if (c === '"') q = true
58
+ else if (c === ',') { row.push(field); field = '' }
59
+ else if (c === '\n' || c === '\r') {
60
+ if (c === '\r' && textIn[i + 1] === '\n') i++
61
+ row.push(field); field = ''
62
+ if (row.length > 1 || row[0] !== '') rows.push(row)
63
+ row = []
64
+ } else field += c
65
+ }
66
+ if (field !== '' || row.length) { row.push(field); rows.push(row) }
67
+ return rows
68
+ }
69
+
70
+ // ---- queue ----
71
+
72
+ export const sleep = (ms, signal) => new Promise((resolve, reject) => {
73
+ if (signal?.aborted) return reject(signal.reason ?? new Error('aborted'))
74
+ const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve() }, ms)
75
+ const onAbort = () => { clearTimeout(t); reject(signal.reason ?? new Error('aborted')) }
76
+ signal?.addEventListener('abort', onAbort, { once: true })
77
+ })
78
+
79
+ /** Errors that make every further file fail the same way: stop the run instead of burning calls. */
80
+ export function isFatal(err) {
81
+ return err instanceof StackError && (err.code === 'daily_limit_reached' || err.status === 401 || err.status === 402 || err.status === 403)
82
+ }
83
+
84
+ /**
85
+ * Call fn(); on a retryable StackError wait the stated time and try again (up to `attempts`).
86
+ * The wait must fit before `deadline` (ms timestamp) and `maxWaitMs`, else the error is rethrown.
87
+ */
88
+ export async function withRetry(fn, { signal, deadline = Infinity, attempts = 3, maxWaitMs = 90_000 } = {}) {
89
+ for (let i = 1; ; i++) {
90
+ try {
91
+ return await fn()
92
+ } catch (err) {
93
+ if (!(err instanceof StackError) || !err.retryable || i >= attempts) throw err
94
+ const wait = Math.max(err.retryAfterMs || 0, 1000)
95
+ if (wait > maxWaitMs || Date.now() + wait > deadline) throw err
96
+ await sleep(wait, signal)
97
+ }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Run worker(item) over items with `concurrency` workers. Stops taking new items at the deadline,
103
+ * on abort, or after a fatal error. Returns { results: Map(item -> {ok, value|error}), stopped }
104
+ * where stopped is undefined or one of 'deadline' | 'cancelled' | 'fatal'.
105
+ */
106
+ export async function runQueue(items, worker, { concurrency = 1, deadline = Infinity, signal, onDone } = {}) {
107
+ const results = new Map()
108
+ let next = 0
109
+ let stopped
110
+ const lane = async () => {
111
+ while (!stopped) {
112
+ if (signal?.aborted) { stopped = 'cancelled'; return }
113
+ if (Date.now() >= deadline) { stopped = 'deadline'; return }
114
+ const i = next++
115
+ if (i >= items.length) return
116
+ const item = items[i]
117
+ try {
118
+ results.set(item, { ok: true, value: await worker(item) })
119
+ } catch (err) {
120
+ if (signal?.aborted) { stopped = 'cancelled'; return }
121
+ results.set(item, { ok: false, error: err })
122
+ if (isFatal(err)) stopped = 'fatal'
123
+ }
124
+ onDone?.(item, results.size)
125
+ }
126
+ }
127
+ await Promise.all(Array.from({ length: Math.max(1, concurrency) }, lane))
128
+ return { results, stopped }
129
+ }
package/src/client.js ADDED
@@ -0,0 +1,179 @@
1
+ // HTTP client for the Foldbun Stack API: auth headers, one bounded retry, error mapping.
2
+
3
+ import http from 'node:http'
4
+ import { VERSION } from './config.js'
5
+
6
+ let proxyConfigured = false
7
+ /** Make fetch honour HTTPS_PROXY / HTTP_PROXY / NO_PROXY (Node built-in, no extra dependency). */
8
+ export function configureProxyFromEnv(env = process.env) {
9
+ if (proxyConfigured) return false
10
+ const wanted = env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy
11
+ if (!wanted || typeof http.setGlobalProxyFromEnv !== 'function') return false
12
+ http.setGlobalProxyFromEnv(env)
13
+ proxyConfigured = true
14
+ return true
15
+ }
16
+
17
+ export class StackError extends Error {
18
+ constructor({ code, message, status, retryable = false, retryAfterMs = 0, requestId, help }) {
19
+ super(message)
20
+ this.name = 'StackError'
21
+ this.code = code
22
+ this.status = status
23
+ this.retryable = retryable
24
+ this.retryAfterMs = retryAfterMs
25
+ this.requestId = requestId
26
+ this.help = help
27
+ }
28
+ }
29
+
30
+ /** Render an error for the model: stable code, message, retry guidance, request ID, server help text. */
31
+ export function describeError(err) {
32
+ if (!(err instanceof StackError)) return `Error: ${err?.message ?? String(err)}`
33
+ const lines = [`Foldbun Stack error ${err.code}${err.status ? ` (HTTP ${err.status})` : ''}: ${err.message}`]
34
+ if (err.retryable) {
35
+ const wait = err.retryAfterMs > 0 ? ` after about ${Math.ceil(err.retryAfterMs / 1000)} s` : ''
36
+ lines.push(`This error is retryable: try the same call again${wait}. Do not retry in a loop.`)
37
+ } else if (err.code === 'daily_limit_reached') {
38
+ lines.push('Not retryable until 00:00 UTC (the daily free limit is used up); an API key lifts it.')
39
+ } else if (err.status) {
40
+ lines.push('Not retryable unchanged.')
41
+ }
42
+ const help = err.help
43
+ if (help && typeof help === 'object') {
44
+ // Relay the server's own guidance for the operator as is.
45
+ const parts = []
46
+ if (typeof help.message === 'string') parts.push(help.message)
47
+ if (help.register?.url) parts.push(`Register an agent project: ${help.register.method ?? 'POST'} ${help.register.url}`)
48
+ if (help.claim?.console) parts.push(`Operator claim console: ${help.claim.console}`)
49
+ if (help.claim?.docs) parts.push(`Claiming: ${help.claim.docs}`)
50
+ if (help.paid?.docs) parts.push(`Paid use: ${help.paid.docs}`)
51
+ if (help.docs) parts.push(`Guide: ${help.docs}`)
52
+ if (parts.length) lines.push(`Help: ${parts.join(' | ')}`)
53
+ }
54
+ if (err.requestId) lines.push(`Request ID: ${err.requestId} (quote it in support requests)`)
55
+ return lines.join('\n')
56
+ }
57
+
58
+ function parseRetryAfter(headers, body) {
59
+ const ms = body?.error?.retryAfterMs
60
+ if (Number.isFinite(ms) && ms > 0) return ms
61
+ const h = Number.parseInt(headers.get('retry-after') ?? '', 10)
62
+ return Number.isFinite(h) && h > 0 ? h * 1000 : 0
63
+ }
64
+
65
+ function networkError(err, config) {
66
+ const cause = err?.cause?.code ?? err?.code ?? err?.name
67
+ const timedOut = err?.name === 'TimeoutError' || err?.name === 'AbortError'
68
+ const hint = timedOut
69
+ ? `The request timed out after ${config.timeoutMs} ms (FOLDBUN_TIMEOUT_MS).`
70
+ : `Could not reach ${config.baseUrl} (${cause ?? 'network error'}).`
71
+ return new StackError({
72
+ code: timedOut ? 'client_timeout' : 'network_unreachable',
73
+ message: `${hint} This is most likely a network problem on this machine, not an API error: check connectivity, set HTTPS_PROXY if a proxy is needed, or point FOLDBUN_BASE_URL at a reachable endpoint. Access from mainland China is not guaranteed.`,
74
+ retryable: true,
75
+ retryAfterMs: 2000,
76
+ })
77
+ }
78
+
79
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
80
+
81
+ export class StackClient {
82
+ /**
83
+ * @param {object} config result of loadConfig()
84
+ * @param {() => {headers: object}} authProvider returns the current auth (re-read each call,
85
+ * so a project registered during the session takes effect immediately)
86
+ */
87
+ constructor(config, authProvider, { maxRetryWaitMs = 15_000 } = {}) {
88
+ this.config = config
89
+ this.authProvider = authProvider
90
+ this.maxRetryWaitMs = maxRetryWaitMs
91
+ }
92
+
93
+ async request(method, pathname, { body, auth = true, signal } = {}) {
94
+ const first = await this.#once(method, pathname, { body, auth, signal })
95
+ if (first.error?.retryable && first.error.retryAfterMs <= this.maxRetryWaitMs) {
96
+ await sleep(Math.max(first.error.retryAfterMs, 500))
97
+ const second = await this.#once(method, pathname, { body, auth, signal })
98
+ if (second.error) throw second.error
99
+ return second.result
100
+ }
101
+ if (first.error) throw first.error
102
+ return first.result
103
+ }
104
+
105
+ async #once(method, pathname, { body, auth, signal }) {
106
+ const headers = {
107
+ Accept: 'application/json',
108
+ 'User-Agent': `foldbun-stack-mcp/${VERSION}`,
109
+ ...(auth ? this.authProvider().headers : {}),
110
+ }
111
+ let payload
112
+ if (body !== undefined) {
113
+ headers['Content-Type'] = 'application/json'
114
+ payload = JSON.stringify(body)
115
+ }
116
+ const timeout = AbortSignal.timeout(this.config.timeoutMs)
117
+ let res
118
+ try {
119
+ res = await fetch(this.config.baseUrl + pathname, {
120
+ method,
121
+ headers,
122
+ body: payload,
123
+ redirect: 'error',
124
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
125
+ })
126
+ } catch (err) {
127
+ return { error: networkError(err, this.config) }
128
+ }
129
+ const requestId = res.headers.get('x-request-id') ?? undefined
130
+ let text
131
+ try {
132
+ text = await res.text()
133
+ } catch (err) {
134
+ return { error: networkError(err, this.config) }
135
+ }
136
+ let json
137
+ try {
138
+ json = text ? JSON.parse(text) : undefined
139
+ } catch {
140
+ json = undefined
141
+ }
142
+ const rate = {
143
+ limit: res.headers.get('x-ratelimit-limit') ?? undefined,
144
+ remaining: res.headers.get('x-ratelimit-remaining') ?? undefined,
145
+ reset: res.headers.get('x-ratelimit-reset') ?? undefined,
146
+ scope: res.headers.get('x-ratelimit-scope') ?? undefined,
147
+ }
148
+ if (res.ok) {
149
+ if (json === undefined) {
150
+ return { error: new StackError({ code: 'bad_response', message: 'The server answered with a body that is not JSON.', status: res.status, requestId }) }
151
+ }
152
+ return { result: { status: res.status, json, requestId, rate } }
153
+ }
154
+ const e = json?.error
155
+ if (e && typeof e === 'object') {
156
+ return {
157
+ error: new StackError({
158
+ code: String(e.code ?? 'unknown_error'),
159
+ message: String(e.message ?? res.statusText),
160
+ status: res.status,
161
+ retryable: e.retryable === true,
162
+ retryAfterMs: parseRetryAfter(res.headers, json),
163
+ requestId,
164
+ help: e.help,
165
+ }),
166
+ }
167
+ }
168
+ return {
169
+ error: new StackError({
170
+ code: 'http_error',
171
+ message: `HTTP ${res.status} ${res.statusText}${text ? `: ${text.slice(0, 200)}` : ''}`,
172
+ status: res.status,
173
+ retryable: res.status >= 502 && res.status <= 504,
174
+ retryAfterMs: parseRetryAfter(res.headers),
175
+ requestId,
176
+ }),
177
+ }
178
+ }
179
+ }
package/src/common.js ADDED
@@ -0,0 +1,59 @@
1
+ // Helpers shared by the tool modules: result builders and the guarded handler wrapper.
2
+
3
+ import { StackError, describeError } from './client.js'
4
+ import { NOT_CONFIGURED_TEXT, ConfigError } from './config.js'
5
+ import { UserError, resolveImage } from './files.js'
6
+
7
+ export const text = (t) => ({ content: [{ type: 'text', text: t }] })
8
+ export const fail = (t) => ({ content: [{ type: 'text', text: t }], isError: true })
9
+
10
+ /** A text result followed by MCP image content blocks. */
11
+ export const withImages = (t, images) => ({
12
+ content: [{ type: 'text', text: t }, ...images.map((i) => ({ type: 'image', data: i.base64, mimeType: i.mimeType }))],
13
+ })
14
+
15
+ export function money(n) {
16
+ return typeof n === 'number' ? `${Number(n.toFixed(6))} credits` : 'n/a'
17
+ }
18
+
19
+ export function callLine(json, requestId) {
20
+ const bits = [`model ${json.model}`]
21
+ if (json.billing?.tier === 'free' || json.cost === 0) bits.push('free tier, nothing charged')
22
+ else bits.push(`cost ${money(json.cost)}`)
23
+ if (typeof json.balance === 'number') bits.push(`balance ${money(json.balance)}`)
24
+ if (requestId) bits.push(`request ${requestId}`)
25
+ return bits.join(', ')
26
+ }
27
+
28
+ /**
29
+ * X-RateLimit-Limit is calls per minute for the tightest limit that applied, -Remaining what is
30
+ * left in that window and -Reset the seconds until it is full again. Daily limits are not in
31
+ * these headers (stack_usage reports them), so the wording says "per minute" explicitly.
32
+ */
33
+ export function rateNote(rate) {
34
+ if (!rate?.remaining) return ''
35
+ const scope = rate.scope ? `, scope ${rate.scope}` : ''
36
+ const reset = Number.parseFloat(rate.reset ?? '')
37
+ const full = Number.isFinite(reset) && reset >= 0 ? `, full again in ${Math.ceil(reset)} s` : ''
38
+ return ` Rate limit (per minute${scope}): ${rate.remaining} of ${rate.limit ?? '?'} left${full}.`
39
+ }
40
+
41
+ export const IMAGE_ARG = 'A local file path, an http(s) URL (downloaded by this server; public addresses only), a data: URL, or raw base64 of a JPEG, PNG or WebP image.'
42
+
43
+ /** Shared per-server helpers. ctx = { config, client, getAuth, onRegistered } */
44
+ export function makeHelpers(ctx) {
45
+ /** Wrap a handler: credential check, error mapping. */
46
+ const guarded = (fn, { needsAuth = true } = {}) => async (args, extra) => {
47
+ try {
48
+ const auth = ctx.getAuth()
49
+ if (needsAuth && auth.kind === 'none') return fail(NOT_CONFIGURED_TEXT)
50
+ return await fn(args, { auth, signal: extra?.signal, extra })
51
+ } catch (err) {
52
+ if (err instanceof UserError || err instanceof ConfigError) return fail(err.message)
53
+ if (err instanceof StackError) return fail(describeError(err))
54
+ return fail(`Unexpected error: ${err?.message ?? err}`)
55
+ }
56
+ }
57
+ const getImage = (input, auth, signal) => resolveImage(input, auth.kind, { signal, allowPrivateUrls: ctx.config.allowPrivateUrls })
58
+ return { guarded, getImage }
59
+ }