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/dist/http.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ClipCloud MCP server over HTTP (Streamable HTTP, stateless) for many users, for https://clipcloud.cliplabs.top/mcp.
|
|
4
|
+
* Every request carries the user's own ClipCloud key: "Authorization: Bearer clip-..." or "?apikey=clip-...".
|
|
5
|
+
* It never writes files and keeps no keys: only a short list of recent generations per key hash, in memory.
|
|
6
|
+
* Run it behind a reverse proxy (nginx) on 127.0.0.1.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { createServer as createHttpServer } from 'node:http';
|
|
10
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
11
|
+
import { DEFAULT_BASE, PANEL_URL, POLL_SECONDS } from './clipcloud.js';
|
|
12
|
+
import { REMOTE_URL, createServer, memoryHistory, version } from './server.js';
|
|
13
|
+
const HOST = process.env.HOST || '127.0.0.1';
|
|
14
|
+
const PORT = Number(process.env.PORT) || 8796;
|
|
15
|
+
const PATH = '/mcp';
|
|
16
|
+
const BASE = (process.env.CLIPCLOUD_BASE_URL ?? '').trim() || DEFAULT_BASE;
|
|
17
|
+
/** Only for tests: a shorter check interval than the 30 seconds the API asks for. */
|
|
18
|
+
const POLL_MS = Math.max(1, Number(process.env.CLIPCLOUD_POLL_SECONDS) || POLL_SECONDS) * 1000;
|
|
19
|
+
const MAX_BODY = 256 * 1024;
|
|
20
|
+
/** Requests handled at the same time, in total and per key (each waiting tool call holds one for up to two minutes). */
|
|
21
|
+
const MAX_ACTIVE = Number(process.env.MAX_ACTIVE) || 50;
|
|
22
|
+
const MAX_ACTIVE_PER_KEY = Number(process.env.MAX_ACTIVE_PER_KEY) || 6;
|
|
23
|
+
/** Requests per client IP: a bucket of RATE_BURST that refills by RATE_PER_SECOND. */
|
|
24
|
+
const RATE_BURST = Number(process.env.RATE_BURST) || 60;
|
|
25
|
+
const RATE_PER_SECOND = Number(process.env.RATE_PER_SECOND) || 1;
|
|
26
|
+
const HISTORY_TTL_MS = 6 * 60 * 60 * 1000;
|
|
27
|
+
const MAX_HISTORIES = 10_000;
|
|
28
|
+
const NO_KEY = `No ClipCloud API key was sent. Tell the user to get a free key (it starts with "clip-") in the web panel ${PANEL_URL} or in the Telegram bot @clipcloudbot, and to add it to this server's address in their AI app: ${REMOTE_URL}?apikey=clip-... (or send it as the header "Authorization: Bearer clip-...").`;
|
|
29
|
+
const BAD_KEY = `The ClipCloud API key sent to this server does not look right: it must start with "clip-" and contain no spaces. Tell the user to copy the key again from the web panel ${PANEL_URL} or @clipcloudbot and update the server address in their AI app: ${REMOTE_URL}?apikey=clip-...`;
|
|
30
|
+
const KEY_FORMAT = /^clip-[\x21-\x7e]{1,200}$/;
|
|
31
|
+
function baseUrlProblem() {
|
|
32
|
+
try {
|
|
33
|
+
const u = new URL(BASE);
|
|
34
|
+
if (u.protocol === 'https:')
|
|
35
|
+
return undefined;
|
|
36
|
+
if (u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname))
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// reported below
|
|
41
|
+
}
|
|
42
|
+
return `CLIPCLOUD_BASE_URL must be an https:// address (got "${BASE}").`;
|
|
43
|
+
}
|
|
44
|
+
const BASE_PROBLEM = baseUrlProblem();
|
|
45
|
+
const hash = (key) => createHash('sha256').update(key).digest('hex').slice(0, 32);
|
|
46
|
+
/** The key from the Authorization header, else from ?apikey= (or ?key=). */
|
|
47
|
+
function keyOf(req, url) {
|
|
48
|
+
const auth = req.headers.authorization?.trim();
|
|
49
|
+
const fromHeader = auth && /^bearer\s+/i.test(auth) ? auth.replace(/^bearer\s+/i, '').trim() : undefined;
|
|
50
|
+
const raw = fromHeader || url.searchParams.get('apikey')?.trim() || url.searchParams.get('key')?.trim();
|
|
51
|
+
if (!raw)
|
|
52
|
+
return { problem: NO_KEY };
|
|
53
|
+
return KEY_FORMAT.test(raw) ? { key: raw } : { problem: BAD_KEY };
|
|
54
|
+
}
|
|
55
|
+
// Recent generations per key hash, so get_image without a creation_id works across requests.
|
|
56
|
+
const histories = new Map();
|
|
57
|
+
function historyFor(key) {
|
|
58
|
+
if (!key)
|
|
59
|
+
return memoryHistory(0);
|
|
60
|
+
const id = hash(key);
|
|
61
|
+
let entry = histories.get(id);
|
|
62
|
+
if (!entry) {
|
|
63
|
+
if (histories.size >= MAX_HISTORIES)
|
|
64
|
+
histories.delete(histories.keys().next().value);
|
|
65
|
+
entry = { history: memoryHistory(20), touched: Date.now() };
|
|
66
|
+
}
|
|
67
|
+
entry.touched = Date.now();
|
|
68
|
+
// re-insert so the Map stays ordered from least to most recently used
|
|
69
|
+
histories.delete(id);
|
|
70
|
+
histories.set(id, entry);
|
|
71
|
+
return entry.history;
|
|
72
|
+
}
|
|
73
|
+
// Per-IP request buckets.
|
|
74
|
+
const buckets = new Map();
|
|
75
|
+
function allowed(ip) {
|
|
76
|
+
const now = Date.now();
|
|
77
|
+
const b = buckets.get(ip) ?? { tokens: RATE_BURST, at: now };
|
|
78
|
+
b.tokens = Math.min(RATE_BURST, b.tokens + ((now - b.at) / 1000) * RATE_PER_SECOND);
|
|
79
|
+
b.at = now;
|
|
80
|
+
buckets.set(ip, b);
|
|
81
|
+
if (b.tokens < 1)
|
|
82
|
+
return false;
|
|
83
|
+
b.tokens -= 1;
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
setInterval(() => {
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
for (const [id, e] of histories)
|
|
89
|
+
if (now - e.touched > HISTORY_TTL_MS)
|
|
90
|
+
histories.delete(id);
|
|
91
|
+
for (const [ip, b] of buckets)
|
|
92
|
+
if (b.tokens >= RATE_BURST - 1 && now - b.at > 60_000)
|
|
93
|
+
buckets.delete(ip);
|
|
94
|
+
}, 5 * 60 * 1000).unref();
|
|
95
|
+
let active = 0;
|
|
96
|
+
const activePerKey = new Map();
|
|
97
|
+
const CORS = {
|
|
98
|
+
'Access-Control-Allow-Origin': '*',
|
|
99
|
+
'Access-Control-Allow-Methods': 'POST, GET, DELETE, OPTIONS',
|
|
100
|
+
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID',
|
|
101
|
+
'Access-Control-Expose-Headers': 'Mcp-Session-Id',
|
|
102
|
+
'Access-Control-Max-Age': '86400',
|
|
103
|
+
};
|
|
104
|
+
function fail(res, status, message, extra = {}) {
|
|
105
|
+
if (res.headersSent)
|
|
106
|
+
return res.end();
|
|
107
|
+
res.writeHead(status, { 'Content-Type': 'application/json', ...CORS, ...extra });
|
|
108
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: status === 400 ? -32700 : -32000, message }, id: null }));
|
|
109
|
+
}
|
|
110
|
+
function readBody(req) {
|
|
111
|
+
return new Promise((resolveBody, reject) => {
|
|
112
|
+
let size = 0;
|
|
113
|
+
const chunks = [];
|
|
114
|
+
req.on('data', (chunk) => {
|
|
115
|
+
size += chunk.length;
|
|
116
|
+
if (size > MAX_BODY) {
|
|
117
|
+
// stop collecting; the answer is sent and the connection closed by the caller
|
|
118
|
+
if (size - chunk.length <= MAX_BODY)
|
|
119
|
+
reject(Object.assign(new Error('too large'), { status: 413 }));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
chunks.push(chunk);
|
|
123
|
+
});
|
|
124
|
+
req.on('end', () => resolveBody(Buffer.concat(chunks).toString('utf8')));
|
|
125
|
+
req.on('error', reject);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/** What a request asks for, for the log: "tools/call generate_image", "initialize", "batch". */
|
|
129
|
+
function describe(body) {
|
|
130
|
+
if (Array.isArray(body))
|
|
131
|
+
return 'batch';
|
|
132
|
+
const m = body;
|
|
133
|
+
if (typeof m?.method !== 'string')
|
|
134
|
+
return 'response';
|
|
135
|
+
const safe = (s) => s.slice(0, 40).replace(/[^\x21-\x7e]/g, '?');
|
|
136
|
+
return m.method === 'tools/call' && typeof m.params?.name === 'string' ? `tools/call ${safe(m.params.name)}` : safe(m.method);
|
|
137
|
+
}
|
|
138
|
+
const log = (line) => console.log(`${new Date().toISOString()} ${line}`);
|
|
139
|
+
async function handle(req, res) {
|
|
140
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
141
|
+
if (url.pathname !== PATH)
|
|
142
|
+
return fail(res, 404, 'Not found. The MCP endpoint is /mcp.');
|
|
143
|
+
if (req.method === 'OPTIONS') {
|
|
144
|
+
res.writeHead(204, CORS);
|
|
145
|
+
return res.end();
|
|
146
|
+
}
|
|
147
|
+
// Stateless server: no server-to-client stream (GET) and no sessions to delete (DELETE).
|
|
148
|
+
if (req.method !== 'POST')
|
|
149
|
+
return fail(res, 405, 'Method not allowed. Send MCP messages with POST.', { Allow: 'POST, OPTIONS' });
|
|
150
|
+
// Behind nginx on 127.0.0.1, the client address comes in X-Real-IP.
|
|
151
|
+
const ip = (req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1' ? req.headers['x-real-ip'] : undefined) || req.socket.remoteAddress || '?';
|
|
152
|
+
if (!allowed(ip))
|
|
153
|
+
return fail(res, 429, 'Too many requests. Wait a little and try again.', { 'Retry-After': '10' });
|
|
154
|
+
if (!/^application\/json\b/i.test(req.headers['content-type'] ?? ''))
|
|
155
|
+
return fail(res, 415, 'Content-Type must be application/json.');
|
|
156
|
+
let body;
|
|
157
|
+
try {
|
|
158
|
+
body = JSON.parse(await readBody(req));
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
const status = error.status;
|
|
162
|
+
return status === 413 ? fail(res, 413, 'Request too large.', { Connection: 'close' }) : fail(res, 400, 'Parse error: the body is not valid JSON.');
|
|
163
|
+
}
|
|
164
|
+
const { key, problem } = keyOf(req, url);
|
|
165
|
+
// Notifications (for example a cancelled call) are quick and must not be refused because of the limits below.
|
|
166
|
+
const notification = !Array.isArray(body) && typeof body?.method === 'string' && !('id' in body);
|
|
167
|
+
const keyId = key && !notification ? hash(key) : '';
|
|
168
|
+
if (!notification && active >= MAX_ACTIVE)
|
|
169
|
+
return fail(res, 503, 'The server is busy. Try again in a minute.', { 'Retry-After': '30' });
|
|
170
|
+
if (keyId && (activePerKey.get(keyId) ?? 0) >= MAX_ACTIVE_PER_KEY) {
|
|
171
|
+
return fail(res, 429, 'Too many requests at the same time with this API key. Wait for the running ones to finish.', { 'Retry-After': '30' });
|
|
172
|
+
}
|
|
173
|
+
if (!notification)
|
|
174
|
+
active++;
|
|
175
|
+
if (keyId)
|
|
176
|
+
activePerKey.set(keyId, (activePerKey.get(keyId) ?? 0) + 1);
|
|
177
|
+
const started = Date.now();
|
|
178
|
+
const what = describe(body);
|
|
179
|
+
for (const [name, value] of Object.entries(CORS))
|
|
180
|
+
res.setHeader(name, value);
|
|
181
|
+
const server = createServer({
|
|
182
|
+
mode: 'remote',
|
|
183
|
+
key,
|
|
184
|
+
keyProblem: problem,
|
|
185
|
+
base: BASE,
|
|
186
|
+
baseProblem: BASE_PROBLEM,
|
|
187
|
+
pollMs: POLL_MS,
|
|
188
|
+
history: historyFor(key),
|
|
189
|
+
});
|
|
190
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
191
|
+
let done = false;
|
|
192
|
+
const finish = () => {
|
|
193
|
+
if (done)
|
|
194
|
+
return;
|
|
195
|
+
done = true;
|
|
196
|
+
if (!notification)
|
|
197
|
+
active--;
|
|
198
|
+
if (keyId) {
|
|
199
|
+
const left = (activePerKey.get(keyId) ?? 1) - 1;
|
|
200
|
+
if (left > 0)
|
|
201
|
+
activePerKey.set(keyId, left);
|
|
202
|
+
else
|
|
203
|
+
activePerKey.delete(keyId);
|
|
204
|
+
}
|
|
205
|
+
transport.close().catch(() => undefined);
|
|
206
|
+
server.close().catch(() => undefined);
|
|
207
|
+
if (what.startsWith('tools/call'))
|
|
208
|
+
log(`${what} ${res.statusCode} ${Date.now() - started}ms`);
|
|
209
|
+
};
|
|
210
|
+
res.on('close', finish);
|
|
211
|
+
try {
|
|
212
|
+
await server.connect(transport);
|
|
213
|
+
await transport.handleRequest(req, res, body);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
log(`error in ${what}: ${error?.message ?? String(error)}`);
|
|
217
|
+
fail(res, 500, 'Internal error.');
|
|
218
|
+
finish();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const http = createHttpServer((req, res) => {
|
|
222
|
+
handle(req, res).catch(() => fail(res, 500, 'Internal error.'));
|
|
223
|
+
});
|
|
224
|
+
http.headersTimeout = 20_000;
|
|
225
|
+
http.requestTimeout = 60_000; // time to receive the request; nginx sends it only once complete
|
|
226
|
+
http.keepAliveTimeout = 5_000;
|
|
227
|
+
http.listen(PORT, HOST, () => log(`clipcloud-mcp ${version} remote server on http://${HOST}:${PORT}${PATH}${BASE_PROBLEM ? ` (${BASE_PROBLEM})` : ''}`));
|
|
228
|
+
function stop() {
|
|
229
|
+
log('stopping');
|
|
230
|
+
http.close(() => process.exit(0));
|
|
231
|
+
http.closeIdleConnections();
|
|
232
|
+
setTimeout(() => process.exit(0), 10_000).unref();
|
|
233
|
+
}
|
|
234
|
+
process.on('SIGTERM', stop);
|
|
235
|
+
process.on('SIGINT', stop);
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** ClipCloud MCP server for one user on their computer (stdio). Needs the CLIPCLOUD_API_KEY environment variable. */
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
|
+
import { DEFAULT_BASE, PANEL_URL, POLL_SECONDS } from './clipcloud.js';
|
|
5
|
+
import { absolute, createServer, memoryHistory } from './server.js';
|
|
6
|
+
const KEY = (process.env.CLIPCLOUD_API_KEY ?? '').trim();
|
|
7
|
+
const BASE = (process.env.CLIPCLOUD_BASE_URL ?? '').trim() || DEFAULT_BASE;
|
|
8
|
+
/** Only for tests: a shorter check interval than the 30 seconds the API asks for. */
|
|
9
|
+
const POLL_MS = Math.max(1, Number(process.env.CLIPCLOUD_POLL_SECONDS) || POLL_SECONDS) * 1000;
|
|
10
|
+
/** Optional default folder: when set, every finished image is also saved there. */
|
|
11
|
+
const RAW_SAVE_DIR = (process.env.CLIPCLOUD_SAVE_DIR ?? '').trim();
|
|
12
|
+
const SAVE_DIR = RAW_SAVE_DIR ? absolute(RAW_SAVE_DIR) : undefined;
|
|
13
|
+
const NO_KEY = `CLIPCLOUD_API_KEY is not set. Tell the user to get a free ClipCloud API key (it starts with "clip-") in the web panel ${PANEL_URL} or in the Telegram bot @clipcloudbot, add it as CLIPCLOUD_API_KEY to the env of the ClipCloud MCP server in their AI app settings, and restart the app.`;
|
|
14
|
+
function baseUrlProblem() {
|
|
15
|
+
try {
|
|
16
|
+
const u = new URL(BASE);
|
|
17
|
+
if (u.protocol === 'https:')
|
|
18
|
+
return undefined;
|
|
19
|
+
if (u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname))
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// reported below
|
|
24
|
+
}
|
|
25
|
+
return `CLIPCLOUD_BASE_URL must be an https:// address (got "${BASE}"). Remove it to use the default ${DEFAULT_BASE}.`;
|
|
26
|
+
}
|
|
27
|
+
const baseProblem = baseUrlProblem();
|
|
28
|
+
const server = createServer({
|
|
29
|
+
mode: 'local',
|
|
30
|
+
key: KEY || undefined,
|
|
31
|
+
keyProblem: KEY ? undefined : NO_KEY,
|
|
32
|
+
base: BASE,
|
|
33
|
+
baseProblem,
|
|
34
|
+
pollMs: POLL_MS,
|
|
35
|
+
history: memoryHistory(),
|
|
36
|
+
saveDir: SAVE_DIR,
|
|
37
|
+
// Claude Code tells stdio servers the project folder in this variable
|
|
38
|
+
projectDir: process.env.CLAUDE_PROJECT_DIR?.trim() || undefined,
|
|
39
|
+
});
|
|
40
|
+
await server.connect(new StdioServerTransport());
|
|
41
|
+
if (!KEY)
|
|
42
|
+
console.error(`clipcloud-mcp: ${NO_KEY}`);
|
|
43
|
+
if (baseProblem)
|
|
44
|
+
console.error(`clipcloud-mcp: ${baseProblem}`);
|
|
45
|
+
if (RAW_SAVE_DIR && !SAVE_DIR) {
|
|
46
|
+
console.error(`clipcloud-mcp: CLIPCLOUD_SAVE_DIR "${RAW_SAVE_DIR}" has a variable that could not be replaced, so images are not saved automatically. Use a full path.`);
|
|
47
|
+
}
|