clipcloud-mcp 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +282 -2
- package/dist/clipcloud.js +374 -0
- package/dist/http.js +235 -0
- package/dist/index.js +47 -0
- package/dist/server.js +575 -0
- package/integration/GUIDE.md +69 -0
- package/integration/clipcloud.mjs +84 -0
- package/integration/clipcloud.php +123 -0
- package/integration/clipcloud.py +95 -0
- package/integration/curl.sh +29 -0
- package/package.json +56 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ClipLabs
|
|
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,283 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ClipCloud MCP server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Make AI images right from Claude, Cursor, VS Code and other AI apps. Ask for a picture in plain words: the assistant writes the prompt, picks one of 35 [ClipCloud](https://clipcloud.cliplabs.top/) styles (photo, anime, watercolor, pixel art, Full HD, 4K and more) and saves the image to your folder.
|
|
4
|
+
|
|
5
|
+
Every ClipCloud key gets **25 free images a day**. Paid images start at $0.0005.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## What you can ask
|
|
10
|
+
|
|
11
|
+
> Make a watercolor picture of a fox in an autumn forest and save it to my Desktop
|
|
12
|
+
|
|
13
|
+
> I need a wide header image for a blog post about winter hiking. Save it to the images folder of this project as hero
|
|
14
|
+
|
|
15
|
+
> How much would 10 Full HD images cost? How many free images do I have left today?
|
|
16
|
+
|
|
17
|
+
> Add AI cover images for new posts to my blog app
|
|
18
|
+
|
|
19
|
+
For the last kind of request, the assistant gets a guide to the ClipCloud API with tested code for JavaScript, Python and PHP, and writes the integration for your project.
|
|
20
|
+
|
|
21
|
+
## 1. Get a ClipCloud key
|
|
22
|
+
|
|
23
|
+
The key is free and starts with `clip-`. Get it in one of two places:
|
|
24
|
+
|
|
25
|
+
- the [ClipCloud web panel](https://clipcloud.cliplabs.top/panel/): sign in or create a free account, and the key is in your account;
|
|
26
|
+
- the Telegram bot [@clipcloudbot](https://t.me/clipcloudbot).
|
|
27
|
+
|
|
28
|
+
Keep the key private, like a password. You top up the balance in the same places.
|
|
29
|
+
|
|
30
|
+
## 2. Connect it to your AI app
|
|
31
|
+
|
|
32
|
+
Pick your app below. In every example, replace `clip-your-key` with your key.
|
|
33
|
+
|
|
34
|
+
All apps except the Claude Desktop extension need **Node.js 20 or newer** (22 or 24 is best). To check, run `node -v` in a terminal. If the command is not found or the version is lower, install the LTS version from [nodejs.org](https://nodejs.org/).
|
|
35
|
+
|
|
36
|
+
<details open>
|
|
37
|
+
<summary><b>Claude Desktop</b> (easiest: one click, no Node.js needed)</summary>
|
|
38
|
+
|
|
39
|
+
1. Download [clipcloud.mcpb](https://github.com/alexmrgit/clipcloud-mcp/releases/latest/download/clipcloud.mcpb).
|
|
40
|
+
2. Double-click the file (or drag it into the Claude window). Claude Desktop shows the install screen.
|
|
41
|
+
3. Paste your key. Check the folder for images (Downloads/ClipCloud by default) and click Install.
|
|
42
|
+
|
|
43
|
+
That's it. Ask Claude for a picture.
|
|
44
|
+
|
|
45
|
+
If you prefer to edit the config by hand: open Claude Desktop **Settings > Developer > Edit Config** and add this to `claude_desktop_config.json`, then quit Claude completely and open it again.
|
|
46
|
+
|
|
47
|
+
```json
|
|
48
|
+
{
|
|
49
|
+
"mcpServers": {
|
|
50
|
+
"clipcloud": {
|
|
51
|
+
"command": "npx",
|
|
52
|
+
"args": ["-y", "clipcloud-mcp"],
|
|
53
|
+
"env": { "CLIPCLOUD_API_KEY": "clip-your-key" }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
</details>
|
|
60
|
+
|
|
61
|
+
<details>
|
|
62
|
+
<summary><b>Claude Code</b></summary>
|
|
63
|
+
|
|
64
|
+
Run in a terminal:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
claude mcp add --scope user --env CLIPCLOUD_API_KEY=clip-your-key --transport stdio clipcloud -- npx -y clipcloud-mcp
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Check with `claude mcp list`, or `/mcp` inside Claude Code.
|
|
71
|
+
|
|
72
|
+
</details>
|
|
73
|
+
|
|
74
|
+
<details>
|
|
75
|
+
<summary><b>Cursor</b></summary>
|
|
76
|
+
|
|
77
|
+
[](https://cursor.com/install-mcp?name=clipcloud&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImNsaXBjbG91ZC1tY3AiXSwiZW52Ijp7IkNMSVBDTE9VRF9BUElfS0VZIjoiWU9VUl9BUElfS0VZIn19)
|
|
78
|
+
|
|
79
|
+
After the click, replace `YOUR_API_KEY` with your key in Cursor's MCP settings.
|
|
80
|
+
|
|
81
|
+
Or add this to `~/.cursor/mcp.json` (for all projects) or `.cursor/mcp.json` (for one project):
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"mcpServers": {
|
|
86
|
+
"clipcloud": {
|
|
87
|
+
"command": "npx",
|
|
88
|
+
"args": ["-y", "clipcloud-mcp"],
|
|
89
|
+
"env": { "CLIPCLOUD_API_KEY": "clip-your-key" }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
</details>
|
|
96
|
+
|
|
97
|
+
<details>
|
|
98
|
+
<summary><b>VS Code</b> (GitHub Copilot)</summary>
|
|
99
|
+
|
|
100
|
+
Open the Command Palette (Ctrl+Shift+P, or Cmd+Shift+P on a Mac), run **MCP: Open User Configuration** and add:
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"inputs": [
|
|
105
|
+
{ "type": "promptString", "id": "clipcloud-key", "description": "ClipCloud API key", "password": true }
|
|
106
|
+
],
|
|
107
|
+
"servers": {
|
|
108
|
+
"clipcloud": {
|
|
109
|
+
"type": "stdio",
|
|
110
|
+
"command": "npx",
|
|
111
|
+
"args": ["-y", "clipcloud-mcp"],
|
|
112
|
+
"env": { "CLIPCLOUD_API_KEY": "${input:clipcloud-key}" }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
VS Code asks for the key once and stores it securely.
|
|
119
|
+
|
|
120
|
+
</details>
|
|
121
|
+
|
|
122
|
+
<details>
|
|
123
|
+
<summary><b>Windsurf / Devin Desktop</b></summary>
|
|
124
|
+
|
|
125
|
+
Open **Customize > MCPs**, open the config file and add the same block as for Cursor:
|
|
126
|
+
|
|
127
|
+
```json
|
|
128
|
+
{
|
|
129
|
+
"mcpServers": {
|
|
130
|
+
"clipcloud": {
|
|
131
|
+
"command": "npx",
|
|
132
|
+
"args": ["-y", "clipcloud-mcp"],
|
|
133
|
+
"env": { "CLIPCLOUD_API_KEY": "clip-your-key" }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Then press the refresh button in the MCP list.
|
|
140
|
+
|
|
141
|
+
</details>
|
|
142
|
+
|
|
143
|
+
<details>
|
|
144
|
+
<summary><b>OpenAI Codex CLI</b></summary>
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
codex mcp add clipcloud --env CLIPCLOUD_API_KEY=clip-your-key -- npx -y clipcloud-mcp
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Codex stops a tool call after 60 seconds by default. That is fine: the server answers within 45 seconds. To let it wait longer for big images, add `tool_timeout_sec = 300` under `[mcp_servers.clipcloud]` in `~/.codex/config.toml`.
|
|
151
|
+
|
|
152
|
+
</details>
|
|
153
|
+
|
|
154
|
+
<details>
|
|
155
|
+
<summary><b>Gemini CLI</b></summary>
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
gemini mcp add -s user -e CLIPCLOUD_API_KEY=clip-your-key clipcloud npx -y clipcloud-mcp
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
</details>
|
|
162
|
+
|
|
163
|
+
<details>
|
|
164
|
+
<summary><b>Any other MCP app</b></summary>
|
|
165
|
+
|
|
166
|
+
Command `npx`, arguments `-y clipcloud-mcp`, environment variable `CLIPCLOUD_API_KEY` with your key. Most apps take this JSON:
|
|
167
|
+
|
|
168
|
+
```json
|
|
169
|
+
{
|
|
170
|
+
"mcpServers": {
|
|
171
|
+
"clipcloud": {
|
|
172
|
+
"command": "npx",
|
|
173
|
+
"args": ["-y", "clipcloud-mcp"],
|
|
174
|
+
"env": { "CLIPCLOUD_API_KEY": "clip-your-key" }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
</details>
|
|
181
|
+
|
|
182
|
+
<details>
|
|
183
|
+
<summary><b>Without installing: the remote server</b> (claude.ai, ChatGPT and other apps that connect by address)</summary>
|
|
184
|
+
|
|
185
|
+
The same server runs at `https://clipcloud.cliplabs.top/mcp`. No Node.js is needed. It cannot save files to your computer: it shows the images and gives links, so download the images you want to keep.
|
|
186
|
+
|
|
187
|
+
**Apps where you only paste an address** (for example custom connectors in claude.ai or ChatGPT): put your key into the address and keep it private, like a password:
|
|
188
|
+
|
|
189
|
+
```
|
|
190
|
+
https://clipcloud.cliplabs.top/mcp?apikey=clip-your-key
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
**Apps that can send headers** send the key as `Authorization: Bearer clip-your-key`. Claude Code:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
claude mcp add --scope user --transport http clipcloud https://clipcloud.cliplabs.top/mcp --header "Authorization: Bearer clip-your-key"
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Cursor (`~/.cursor/mcp.json`):
|
|
200
|
+
|
|
201
|
+
```json
|
|
202
|
+
{
|
|
203
|
+
"mcpServers": {
|
|
204
|
+
"clipcloud": {
|
|
205
|
+
"url": "https://clipcloud.cliplabs.top/mcp",
|
|
206
|
+
"headers": { "Authorization": "Bearer clip-your-key" }
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
</details>
|
|
213
|
+
|
|
214
|
+
## 3. Check that it works
|
|
215
|
+
|
|
216
|
+
Ask your assistant: **"What is my ClipCloud balance?"** It should answer with your balance and the free images left today. Then ask for a picture.
|
|
217
|
+
|
|
218
|
+
## Good to know
|
|
219
|
+
|
|
220
|
+
- **It takes a minute or more.** Small styles are usually ready in 1 to 5 minutes. Full HD, 4K and upscaled styles can take 15 minutes or more at busy times. The ClipCloud API returns a generation ID at once, and the server then checks the result every 30 seconds (as the API docs ask) for up to 45 seconds within the same request, so quick images come back in one step. If the image is not ready by then, the assistant gets the generation ID and keeps checking the same generation, so just wait. The server tells the assistant not to start a new one, so you are not charged twice.
|
|
221
|
+
- **Save the files.** Image links expire. Ask the assistant to save images to a folder (in Claude Code, Cursor and VS Code a folder of the open project works), or set `CLIPCLOUD_SAVE_DIR` (see below) so every image is saved automatically. Existing files are never replaced. Images are WebP files.
|
|
222
|
+
- **Previews.** The assistant sees small previews of up to 2 finished images, which uses some chat space. Ask it to skip previews if you make many images.
|
|
223
|
+
- **Cost.** Images are paid from your key's balance in credits, shown as 🖼️ in the ClipCloud panel and bot (1 credit = $0.0025, [prices by style](https://clipcloud.cliplabs.top/pricing/)). When the paid balance is empty, up to 25 free images a day are used. Ask the assistant for a price before a big batch; every result also shows what it cost.
|
|
224
|
+
- **Prompts** work in any language. English gives the best results, and assistants usually translate for you.
|
|
225
|
+
|
|
226
|
+
## Settings
|
|
227
|
+
|
|
228
|
+
| Variable | Required | What it does |
|
|
229
|
+
|---|---|---|
|
|
230
|
+
| `CLIPCLOUD_API_KEY` | yes | Your ClipCloud key, starts with `clip-`. |
|
|
231
|
+
| `CLIPCLOUD_SAVE_DIR` | no | A folder where every finished image is saved, for example `/Users/me/Pictures/ClipCloud`. Folders the assistant names without a full path are created inside it. |
|
|
232
|
+
| `CLIPCLOUD_BASE_URL` | no | Leave unset. Set to `https://clipcloud-rumirror.clipai.pro` only if the main API address is not reachable from your network. |
|
|
233
|
+
|
|
234
|
+
## Tools
|
|
235
|
+
|
|
236
|
+
| Tool | What it does |
|
|
237
|
+
|---|---|
|
|
238
|
+
| `generate_image` | Starts a generation from a prompt in a style and waits up to 45 seconds for it. Shows the images, returns links and saves files if asked. If the images are not ready yet, returns the generation ID. |
|
|
239
|
+
| `get_image` | Gets the images of a generation by its ID, waiting again if needed. Without an ID, takes the latest generation of this session. |
|
|
240
|
+
| `list_styles` | Lists the 35 styles with their sizes. |
|
|
241
|
+
| `estimate_cost` | Tells the price of a generation before making it. Nothing is charged. |
|
|
242
|
+
| `get_balance` | Shows the paid balance and the free images left today. |
|
|
243
|
+
| `get_integration_guide` | Gives the assistant the ClipCloud API guide and tested code, so it can add image generation to your own app. |
|
|
244
|
+
|
|
245
|
+
## Use ClipCloud in your own code
|
|
246
|
+
|
|
247
|
+
The [integration](integration/) folder has the same guide the assistant gets and ready clients for [JavaScript](integration/clipcloud.mjs), [Python](integration/clipcloud.py), [PHP](integration/clipcloud.php) and [curl](integration/curl.sh). They handle the waiting, temporary errors and downloads the right way. Full API docs: [clipcloud.cliplabs.top/docs](https://clipcloud.cliplabs.top/docs/).
|
|
248
|
+
|
|
249
|
+
## Commands
|
|
250
|
+
|
|
251
|
+
Apps that show MCP prompts as commands (Claude Code, VS Code and others) get three ready requests:
|
|
252
|
+
|
|
253
|
+
| Command | What it does |
|
|
254
|
+
|---|---|
|
|
255
|
+
| `image` | Makes a picture from a short description, optionally in a given style and folder. |
|
|
256
|
+
| `cover` | Makes a wide cover image for an article or a page, without text in it. |
|
|
257
|
+
| `integrate` | Adds ClipCloud image generation to the code of your app, site or bot. |
|
|
258
|
+
|
|
259
|
+
In Claude Code they look like `/mcp__clipcloud__image`.
|
|
260
|
+
|
|
261
|
+
## Troubleshooting
|
|
262
|
+
|
|
263
|
+
- **"CLIPCLOUD_API_KEY is not set"**: the key is missing from the app's MCP settings. Add it and restart the app.
|
|
264
|
+
- **"Invalid API Key"**: check that the key is copied whole, starting with `clip-`, without spaces.
|
|
265
|
+
- **"Not enough balance"**: the free images for today are used and the paid balance is empty. Top up in the [web panel](https://clipcloud.cliplabs.top/panel/) or [@clipcloudbot](https://t.me/clipcloudbot), or wait until tomorrow.
|
|
266
|
+
- **The server does not start, or "npx not found" / "spawn npx ENOENT"**: install Node.js 20+ from [nodejs.org](https://nodejs.org/) and restart the app. If you use nvm or fnm, desktop apps may not see that Node.js: put the full path from `which npx` (on Windows: `where npx`) in `command`.
|
|
267
|
+
- **Claude Desktop on Windows, an error that mentions `${APPDATA}`**: add `"APPDATA": "C:\\Users\\<your user>\\AppData\\Roaming"` to `env` next to the key.
|
|
268
|
+
- **Logs**: Claude Desktop writes the server's messages to `mcp-server-clipcloud.log` in `~/Library/Logs/Claude` (Mac) or `%APPDATA%\Claude\logs` (Windows).
|
|
269
|
+
|
|
270
|
+
## Privacy
|
|
271
|
+
|
|
272
|
+
The server you install runs on your computer, and your key is sent only to the ClipCloud API. The remote server (`clipcloud.cliplabs.top/mcp`) passes your requests to the ClipCloud API with your key; it does not store the key, does not log keys or prompts and does not save images. Your prompts go to ClipCloud to make the images; images are saved only where you or the assistant choose. See the [privacy policy](https://clipai.pro/en/privacy/) and the [image use rules](https://clipai.pro/en/faq/image-use-rules/).
|
|
273
|
+
|
|
274
|
+
## More from ClipCloud
|
|
275
|
+
|
|
276
|
+
- [API docs](https://clipcloud.cliplabs.top/docs/) and [prices](https://clipcloud.cliplabs.top/pricing/)
|
|
277
|
+
- [WordPress plugin](https://wordpress.org/plugins/clipcloud-image-generation/)
|
|
278
|
+
- [n8n node](https://www.npmjs.com/package/n8n-nodes-clipcloud)
|
|
279
|
+
- Support: support@clipcloud.cliplabs.top
|
|
280
|
+
|
|
281
|
+
## License
|
|
282
|
+
|
|
283
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
/** Small client for the ClipCloud REST API. Docs: https://clipcloud.cliplabs.top/docs/ */
|
|
2
|
+
export const DEFAULT_BASE = 'https://clipcloud.clipai.pro';
|
|
3
|
+
export const CREDIT_USD = 0.0025;
|
|
4
|
+
export const PANEL_URL = 'https://clipcloud.cliplabs.top/panel/';
|
|
5
|
+
export const PRICING_URL = 'https://clipcloud.cliplabs.top/pricing/';
|
|
6
|
+
export const TOP_UP = `Top up the balance in the ClipCloud web panel (${PANEL_URL}) or in the Telegram bot @clipcloudbot.`;
|
|
7
|
+
/** The API asks to check a generation every 30 seconds. */
|
|
8
|
+
export const POLL_SECONDS = 30;
|
|
9
|
+
/** Short notes for each style. The live list with sizes comes from GET /api/styles. */
|
|
10
|
+
export const STYLE_NOTES = {
|
|
11
|
+
lowquality: 'draft, fastest and cheapest',
|
|
12
|
+
'standard-512': 'fast, low quality',
|
|
13
|
+
standard: 'fast, low quality',
|
|
14
|
+
smallHQ: 'high quality, small',
|
|
15
|
+
'HD-HQ': 'high quality, square, good default',
|
|
16
|
+
'FullHD-HQ-h': 'best quality, horizontal',
|
|
17
|
+
'FullHD-HQ-v': 'best quality, vertical',
|
|
18
|
+
'standard-2': 'high quality (alternative model), wide',
|
|
19
|
+
'standard-2-FullHD': 'high quality (alternative model), wide Full HD',
|
|
20
|
+
'photorealistic-1': 'realistic photo',
|
|
21
|
+
'photo-horizontal': 'realistic photo, large and wide',
|
|
22
|
+
'photo-portrait': 'photo portrait',
|
|
23
|
+
anime: 'anime',
|
|
24
|
+
graffiti: 'graffiti on a wall',
|
|
25
|
+
illustration: 'book illustration',
|
|
26
|
+
oldphoto: 'vintage photo',
|
|
27
|
+
baroque: 'baroque painting',
|
|
28
|
+
aquarelle: 'watercolor',
|
|
29
|
+
'pixel-art': 'pixel art',
|
|
30
|
+
'pop-art': 'pop art',
|
|
31
|
+
'pop-art-512': 'pop art, small',
|
|
32
|
+
'neon-lines': 'neon line art',
|
|
33
|
+
'neon-noir': 'neon noir',
|
|
34
|
+
'tilt-shift': 'miniature effect, best for views from above',
|
|
35
|
+
'HQ-4K-h': '4K horizontal, upscaled, output 3840x2048, slow',
|
|
36
|
+
'HQ-768-512-h': 'high quality, horizontal',
|
|
37
|
+
'HQ-832-448-h': 'high quality, horizontal',
|
|
38
|
+
'HQ-832-640-h': 'high quality, horizontal',
|
|
39
|
+
'HQ-1024-640-h': 'high quality, horizontal',
|
|
40
|
+
'HQ-1200-640-h': 'high quality, horizontal',
|
|
41
|
+
'HQ-1280-720-h': 'high quality, horizontal',
|
|
42
|
+
'HQ-1920-1024-h': 'high quality, horizontal, upscaled',
|
|
43
|
+
'HQ-512-768-v': 'high quality, vertical',
|
|
44
|
+
'HQ-640-1024-v': 'high quality, vertical',
|
|
45
|
+
'HQ-1024-1920-v': 'high quality, vertical, upscaled',
|
|
46
|
+
};
|
|
47
|
+
/** An error whose message is safe and useful to show to the user and the AI assistant. */
|
|
48
|
+
export class ClipCloudError extends Error {
|
|
49
|
+
}
|
|
50
|
+
/** A temporary problem (network, 429, 502-504): the generation may still be fine, check again later. */
|
|
51
|
+
export class TransientError extends ClipCloudError {
|
|
52
|
+
}
|
|
53
|
+
/** "1.9 credits ($0.0048)"; amounts of a dollar or more are shown to the cent. */
|
|
54
|
+
export function credits(value) {
|
|
55
|
+
const amount = Math.round(value * 100) / 100;
|
|
56
|
+
const usd = value * CREDIT_USD;
|
|
57
|
+
const digits = usd >= 1 ? 2 : 4;
|
|
58
|
+
return `${amount} credits ($${(Math.round(usd * 10 ** digits) / 10 ** digits).toFixed(digits)})`;
|
|
59
|
+
}
|
|
60
|
+
/** AbortSignal.any exists from Node 20.3; this also works on older versions. */
|
|
61
|
+
function anySignal(signals) {
|
|
62
|
+
const any = AbortSignal.any;
|
|
63
|
+
if (any)
|
|
64
|
+
return any(signals);
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
for (const s of signals) {
|
|
67
|
+
if (s.aborted) {
|
|
68
|
+
controller.abort(s.reason);
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
s.addEventListener('abort', () => controller.abort(s.reason), { once: true });
|
|
72
|
+
}
|
|
73
|
+
return controller.signal;
|
|
74
|
+
}
|
|
75
|
+
function withTimeout(ms, signal) {
|
|
76
|
+
const timeout = AbortSignal.timeout(Math.max(1000, ms));
|
|
77
|
+
return signal ? anySignal([signal, timeout]) : timeout;
|
|
78
|
+
}
|
|
79
|
+
export const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
80
|
+
if (signal?.aborted)
|
|
81
|
+
return reject(new ClipCloudError('Cancelled.'));
|
|
82
|
+
const t = setTimeout(resolve, Math.max(0, ms));
|
|
83
|
+
signal?.addEventListener('abort', () => {
|
|
84
|
+
clearTimeout(t);
|
|
85
|
+
reject(new ClipCloudError('Cancelled.'));
|
|
86
|
+
}, { once: true });
|
|
87
|
+
});
|
|
88
|
+
/** API text without zero-width characters and the "Error!" prefix. */
|
|
89
|
+
export function clean(text) {
|
|
90
|
+
return String(text ?? '')
|
|
91
|
+
.replace(/[\u200B-\u200D\uFEFF]/g, '')
|
|
92
|
+
.replace(/^Error!\s*/i, '')
|
|
93
|
+
.trim();
|
|
94
|
+
}
|
|
95
|
+
function sentence(text) {
|
|
96
|
+
const t = text.trim();
|
|
97
|
+
return /[.!?]$/.test(t) ? t : `${t}.`;
|
|
98
|
+
}
|
|
99
|
+
function failure(reply, what) {
|
|
100
|
+
let text = clean(reply.body.message) || `${what} (HTTP ${reply.status})`;
|
|
101
|
+
if (reply.body.errors && typeof reply.body.errors === 'object') {
|
|
102
|
+
const details = Object.values(reply.body.errors)
|
|
103
|
+
.flat()
|
|
104
|
+
.map(String)
|
|
105
|
+
.join(' ');
|
|
106
|
+
if (details)
|
|
107
|
+
text = `${sentence(text)} ${details}`;
|
|
108
|
+
}
|
|
109
|
+
text = sentence(text);
|
|
110
|
+
if (reply.status === 401) {
|
|
111
|
+
text += ` The API key is wrong or missing. Check the ClipCloud key in the AI app's settings for this MCP server (the CLIPCLOUD_API_KEY variable, or apikey= in the server address): it starts with "clip-". Get a key at ${PANEL_URL} or in @clipcloudbot.`;
|
|
112
|
+
}
|
|
113
|
+
if (reply.status === 429)
|
|
114
|
+
text += ' Too many requests. Wait a minute and try again.';
|
|
115
|
+
return new ClipCloudError(text);
|
|
116
|
+
}
|
|
117
|
+
const MAYBE_STARTED = 'The generation may or may not have started, and it may be charged. Do not repeat the request automatically: tell the user, and check get_balance before trying again.';
|
|
118
|
+
const BLOCKED = 'All images were blocked by the content filter. Rephrase the prompt and ask the user before trying again.';
|
|
119
|
+
/** When each generation was last checked, so repeated calls keep to the 30-second rhythm the API asks for. */
|
|
120
|
+
const lastCheck = new Map();
|
|
121
|
+
/** Old entries are dropped so a long-running (remote) server does not keep every ID forever. */
|
|
122
|
+
function markChecked(id) {
|
|
123
|
+
const now = Date.now();
|
|
124
|
+
lastCheck.set(id, now);
|
|
125
|
+
if (lastCheck.size > 2000) {
|
|
126
|
+
for (const [key, at] of lastCheck)
|
|
127
|
+
if (now - at > 2 * 60 * 60 * 1000)
|
|
128
|
+
lastCheck.delete(key);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
export class ClipCloud {
|
|
132
|
+
key;
|
|
133
|
+
base;
|
|
134
|
+
userAgent;
|
|
135
|
+
constructor(key, base = DEFAULT_BASE,
|
|
136
|
+
/** Sent as User-Agent, for example "clipcloud-mcp/0.1.0". */
|
|
137
|
+
userAgent = 'clipcloud-mcp') {
|
|
138
|
+
this.key = key;
|
|
139
|
+
this.base = base;
|
|
140
|
+
this.userAgent = userAgent;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* One API call. Network failures are retried only for GET (a POST may already have started a paid generation),
|
|
144
|
+
* and never past the deadline.
|
|
145
|
+
*/
|
|
146
|
+
async call(method, path, body, opts = {}) {
|
|
147
|
+
for (let attempt = 0;; attempt++) {
|
|
148
|
+
const left = opts.deadline ? opts.deadline - Date.now() : 60000;
|
|
149
|
+
try {
|
|
150
|
+
const res = await fetch(`${this.base.replace(/\/+$/, '')}${path}`, {
|
|
151
|
+
method,
|
|
152
|
+
headers: {
|
|
153
|
+
Authorization: `Bearer ${this.key}`,
|
|
154
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
155
|
+
'User-Agent': this.userAgent,
|
|
156
|
+
},
|
|
157
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
158
|
+
signal: withTimeout(Math.min(60000, left), opts.signal),
|
|
159
|
+
});
|
|
160
|
+
const text = await res.text();
|
|
161
|
+
let parsed;
|
|
162
|
+
try {
|
|
163
|
+
const value = JSON.parse(text);
|
|
164
|
+
parsed = value && typeof value === 'object' && !Array.isArray(value) ? value : { message: text.slice(0, 300) };
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
parsed = { message: text.slice(0, 300), notJson: true };
|
|
168
|
+
}
|
|
169
|
+
return { status: res.status, body: parsed };
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (opts.signal?.aborted)
|
|
173
|
+
throw new ClipCloudError('Cancelled.');
|
|
174
|
+
const reason = error.message;
|
|
175
|
+
if (method !== 'GET')
|
|
176
|
+
throw new ClipCloudError(`Could not reach ClipCloud (${reason}). ${MAYBE_STARTED}`);
|
|
177
|
+
const pause = 3000 * 2 ** attempt;
|
|
178
|
+
const deadline = opts.deadline ?? Infinity;
|
|
179
|
+
if (attempt >= 3 || Date.now() + pause >= deadline) {
|
|
180
|
+
throw new TransientError(`Could not reach ClipCloud (${reason}). Check the internet connection.`);
|
|
181
|
+
}
|
|
182
|
+
await sleep(pause, opts.signal);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
async balance() {
|
|
187
|
+
const reply = await this.call('GET', '/api/users/mybalance');
|
|
188
|
+
if (reply.status !== 200 || reply.body.balance === undefined)
|
|
189
|
+
throw failure(reply, 'Could not get the balance');
|
|
190
|
+
return {
|
|
191
|
+
balance: Number(reply.body.balance),
|
|
192
|
+
freeLeft: reply.body.free_balance === undefined ? undefined : Number(reply.body.free_balance),
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
async styles() {
|
|
196
|
+
const reply = await this.call('GET', '/api/styles');
|
|
197
|
+
if (reply.status !== 200 || !Array.isArray(reply.body.styles))
|
|
198
|
+
throw failure(reply, 'Could not get the styles');
|
|
199
|
+
return reply.body.styles.map((s) => ({
|
|
200
|
+
name: String(s.name),
|
|
201
|
+
width: Number(s.width),
|
|
202
|
+
height: Number(s.height),
|
|
203
|
+
}));
|
|
204
|
+
}
|
|
205
|
+
/** Errors for a POST /api/creation: clear 4xx answers, or a warning that the generation may have started. */
|
|
206
|
+
startError(reply, what, startsGeneration) {
|
|
207
|
+
const message = clean(reply.body.message);
|
|
208
|
+
if (reply.status === 400 && /not enough|balance|free generations/i.test(message)) {
|
|
209
|
+
return new ClipCloudError(`Not enough balance: the 25 free images for today are used and the paid balance is empty. ${TOP_UP} The free images come back tomorrow. Do not retry.`);
|
|
210
|
+
}
|
|
211
|
+
if (reply.status === 400 && /style/i.test(message)) {
|
|
212
|
+
return new ClipCloudError(`${sentence(message)} Call list_styles to see the valid style names.`);
|
|
213
|
+
}
|
|
214
|
+
if (reply.status >= 400 && reply.status < 500)
|
|
215
|
+
return failure(reply, what);
|
|
216
|
+
if (!startsGeneration)
|
|
217
|
+
return new ClipCloudError(`${what}: ClipCloud gave an unexpected answer (HTTP ${reply.status}). Try again later.`);
|
|
218
|
+
return new ClipCloudError(`ClipCloud gave an unexpected answer to the request (HTTP ${reply.status}). ${MAYBE_STARTED}`);
|
|
219
|
+
}
|
|
220
|
+
/** Paid-mode price of a request, without starting it. */
|
|
221
|
+
async estimate(request) {
|
|
222
|
+
const reply = await this.call('POST', '/api/creation', { ...request, check_cost: true });
|
|
223
|
+
if (reply.status !== 200 || reply.body.success !== true || typeof reply.body.cost !== 'number') {
|
|
224
|
+
throw this.startError(reply, 'Could not estimate the cost', false);
|
|
225
|
+
}
|
|
226
|
+
return reply.body.cost;
|
|
227
|
+
}
|
|
228
|
+
/** Starts a generation and returns its ID. */
|
|
229
|
+
async start(request) {
|
|
230
|
+
const reply = await this.call('POST', '/api/creation', request);
|
|
231
|
+
const id = reply.body.creation_id;
|
|
232
|
+
if (reply.status !== 200 || reply.body.success !== true || typeof id !== 'string' || !id) {
|
|
233
|
+
throw this.startError(reply, 'Could not start the generation', true);
|
|
234
|
+
}
|
|
235
|
+
markChecked(id);
|
|
236
|
+
return id;
|
|
237
|
+
}
|
|
238
|
+
/** Reads the state of a generation once. Throws TransientError for temporary problems. */
|
|
239
|
+
async check(id, opts = {}) {
|
|
240
|
+
markChecked(id);
|
|
241
|
+
const reply = await this.call('GET', `/api/creation/${encodeURIComponent(id)}`, undefined, opts);
|
|
242
|
+
if (reply.status === 429 || reply.status === 502 || reply.status === 503 || reply.status === 504) {
|
|
243
|
+
throw new TransientError(`ClipCloud is busy or temporarily unavailable (HTTP ${reply.status}).`);
|
|
244
|
+
}
|
|
245
|
+
if (reply.status === 404 || reply.status === 500) {
|
|
246
|
+
throw new ClipCloudError(`ClipCloud could not return generation ${id} (HTTP ${reply.status}). The ID may be unknown or expired, or the server had a temporary error. Do not start a new generation automatically: try get_image again later, or ask the user.`);
|
|
247
|
+
}
|
|
248
|
+
if (reply.status === 400) {
|
|
249
|
+
throw new ClipCloudError(`${failure(reply, 'Invalid request').message} Use the creation_id exactly as generate_image returned it.`);
|
|
250
|
+
}
|
|
251
|
+
if (reply.status !== 200)
|
|
252
|
+
throw failure(reply, 'Could not check the generation');
|
|
253
|
+
const b = reply.body;
|
|
254
|
+
const censored = Number(b.censored ?? 0) || 0;
|
|
255
|
+
if (Array.isArray(b.results)) {
|
|
256
|
+
const images = b.results.map(String).filter(Boolean);
|
|
257
|
+
if (images.length) {
|
|
258
|
+
return {
|
|
259
|
+
state: 'done',
|
|
260
|
+
creationId: id,
|
|
261
|
+
images,
|
|
262
|
+
censored,
|
|
263
|
+
costCredits: typeof b.cost === 'number' ? b.cost : undefined,
|
|
264
|
+
freeImagesUsed: typeof b.free_cost === 'number' ? b.free_cost : undefined,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
state: 'failed',
|
|
269
|
+
creationId: id,
|
|
270
|
+
images: [],
|
|
271
|
+
censored,
|
|
272
|
+
message: censored > 0 ? BLOCKED : 'The generation finished without images and ClipCloud gave no reason. Ask the user before trying again.',
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
if (b.success === true && b.status === 'in_progress')
|
|
276
|
+
return { state: 'running', creationId: id, images: [], censored };
|
|
277
|
+
if (b.success === false && !b.notJson) {
|
|
278
|
+
return {
|
|
279
|
+
state: 'failed',
|
|
280
|
+
creationId: id,
|
|
281
|
+
images: [],
|
|
282
|
+
censored,
|
|
283
|
+
message: censored > 0 ? BLOCKED : `${sentence(clean(b.message) || 'The images were not made')} Ask the user before trying again.`,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
throw new TransientError('ClipCloud gave an unexpected answer.');
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Waits for a generation until it is done or failed, or until the deadline (a timestamp).
|
|
290
|
+
* Keeps at least intervalMs between checks of the same generation, also across tool calls.
|
|
291
|
+
* Temporary errors do not end the wait; if the deadline comes first, the generation is reported as running.
|
|
292
|
+
*/
|
|
293
|
+
async waitFor(id, deadline, opts) {
|
|
294
|
+
let note;
|
|
295
|
+
let checked = false;
|
|
296
|
+
const since = lastCheck.get(id);
|
|
297
|
+
let next = since === undefined ? Date.now() : Math.max(Date.now(), since + opts.intervalMs);
|
|
298
|
+
for (;;) {
|
|
299
|
+
if (next > deadline) {
|
|
300
|
+
// a direct request for the result checks once even when there is no time to wait
|
|
301
|
+
if (opts.checkAtLeastOnce && !checked)
|
|
302
|
+
next = Date.now();
|
|
303
|
+
else
|
|
304
|
+
return { state: 'running', creationId: id, images: [], censored: 0, message: note };
|
|
305
|
+
}
|
|
306
|
+
while (Date.now() < next) {
|
|
307
|
+
await sleep(Math.min(10000, next - Date.now()), opts.signal);
|
|
308
|
+
await opts.onTick?.();
|
|
309
|
+
}
|
|
310
|
+
checked = true;
|
|
311
|
+
try {
|
|
312
|
+
const gen = await this.check(id, { signal: opts.signal, deadline: Math.max(deadline, Date.now() + 15000) });
|
|
313
|
+
if (gen.state !== 'running')
|
|
314
|
+
return gen;
|
|
315
|
+
note = undefined;
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
if (!(error instanceof TransientError))
|
|
319
|
+
throw error;
|
|
320
|
+
note = error.message;
|
|
321
|
+
}
|
|
322
|
+
next = Date.now() + opts.intervalMs;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const IMAGE_TYPES = { 'image/webp': 'webp', 'image/png': 'png', 'image/jpeg': 'jpg' };
|
|
327
|
+
/** The image type from the first bytes of the file. */
|
|
328
|
+
function sniff(data) {
|
|
329
|
+
if (data.length >= 12 && data.toString('latin1', 0, 4) === 'RIFF' && data.toString('latin1', 8, 12) === 'WEBP')
|
|
330
|
+
return 'image/webp';
|
|
331
|
+
if (data.length >= 8 && data[0] === 0x89 && data.toString('latin1', 1, 4) === 'PNG')
|
|
332
|
+
return 'image/png';
|
|
333
|
+
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff)
|
|
334
|
+
return 'image/jpeg';
|
|
335
|
+
return undefined;
|
|
336
|
+
}
|
|
337
|
+
export function extensionFor(mime) {
|
|
338
|
+
return IMAGE_TYPES[mime] ?? 'webp';
|
|
339
|
+
}
|
|
340
|
+
/** Downloads an image within the deadline. Returns the bytes and the image type. */
|
|
341
|
+
export async function download(url, opts) {
|
|
342
|
+
let reason = 'no time left';
|
|
343
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
344
|
+
const left = opts.deadline - Date.now();
|
|
345
|
+
if (left < 1500)
|
|
346
|
+
break;
|
|
347
|
+
try {
|
|
348
|
+
const res = await fetch(url, { signal: withTimeout(Math.min(20000, left), opts.signal) });
|
|
349
|
+
if (res.status === 404)
|
|
350
|
+
throw new ClipCloudError(`The image link has expired (HTTP 404): ${url}`);
|
|
351
|
+
if (!res.ok)
|
|
352
|
+
throw new Error(`HTTP ${res.status}`);
|
|
353
|
+
const data = Buffer.from(await res.arrayBuffer());
|
|
354
|
+
const expected = Number(res.headers.get('content-length') ?? 0);
|
|
355
|
+
if (expected && !res.headers.get('content-encoding') && data.length !== expected)
|
|
356
|
+
throw new Error('incomplete download');
|
|
357
|
+
const header = (res.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
|
|
358
|
+
const mime = sniff(data) ?? (IMAGE_TYPES[header] ? header : undefined);
|
|
359
|
+
if (!mime)
|
|
360
|
+
throw new ClipCloudError(`The link did not return an image (${header || 'unknown type'}): ${url}`);
|
|
361
|
+
return { data, mime };
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
if (opts.signal?.aborted)
|
|
365
|
+
throw new ClipCloudError('Cancelled.');
|
|
366
|
+
if (error instanceof ClipCloudError)
|
|
367
|
+
throw error;
|
|
368
|
+
reason = error.message;
|
|
369
|
+
if (attempt === 0 && opts.deadline - Date.now() > 3000)
|
|
370
|
+
await sleep(1500, opts.signal);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
throw new ClipCloudError(`Could not download the image in time (${reason}).`);
|
|
374
|
+
}
|