@aisocialautomate/mcp 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +87 -2
- package/catalog/endpoints.json +5555 -0
- package/dist/api.js +83 -0
- package/dist/catalog.js +60 -0
- package/dist/config.js +24 -0
- package/dist/http-app.js +292 -0
- package/dist/http.js +13 -0
- package/dist/net-guard.js +155 -0
- package/dist/oauth.js +339 -0
- package/dist/publishing.js +479 -0
- package/dist/server.js +494 -0
- package/dist/slim.js +69 -0
- package/dist/stdio.js +12 -0
- package/dist/time.js +56 -0
- package/dist/toolsets.js +68 -0
- package/dist/usage.js +130 -0
- package/package.json +54 -4
package/dist/api.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
export class ApiError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
details;
|
|
6
|
+
constructor(status, code, message, details) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.details = details;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class Api {
|
|
14
|
+
cfg;
|
|
15
|
+
fetchImpl;
|
|
16
|
+
constructor(cfg, fetchImpl = fetch) {
|
|
17
|
+
this.cfg = cfg;
|
|
18
|
+
this.fetchImpl = fetchImpl;
|
|
19
|
+
}
|
|
20
|
+
async request(method, path, opts = {}) {
|
|
21
|
+
if (!this.cfg.apiKey)
|
|
22
|
+
throw new ApiError(401, 'NO_API_KEY', 'No API key configured. Set SOCIAL_AUTOMATE_API_KEY (create one in the dashboard under Developer → API Keys).');
|
|
23
|
+
const url = new URL(this.cfg.baseUrl + '/' + path.replace(/^\/+/, ''));
|
|
24
|
+
for (const [k, v] of Object.entries(opts.query ?? {}))
|
|
25
|
+
if (v !== undefined && v !== '')
|
|
26
|
+
url.searchParams.set(k, String(v));
|
|
27
|
+
const headers = { Authorization: `ApiKey ${this.cfg.apiKey}`, Accept: 'application/json', 'User-Agent': 'aisocialautomate-mcp/0.1' };
|
|
28
|
+
if (opts.body !== undefined && !opts.form)
|
|
29
|
+
headers['Content-Type'] = 'application/json';
|
|
30
|
+
if (method !== 'GET')
|
|
31
|
+
headers['Idempotency-Key'] = randomUUID();
|
|
32
|
+
let res;
|
|
33
|
+
try {
|
|
34
|
+
res = await this.fetchImpl(url, { method, headers, body: opts.form ?? (opts.body === undefined ? undefined : JSON.stringify(opts.body)), signal: AbortSignal.timeout(opts.timeoutMs ?? 90_000) });
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
if (e?.name === 'TimeoutError' || e?.name === 'AbortError')
|
|
38
|
+
throw new ApiError(0, 'TIMEOUT', 'The request took too long. Slow endpoints (LinkedIn) can need up to 60 seconds; try again or use a bulk run.');
|
|
39
|
+
throw new ApiError(0, 'NETWORK', `Could not reach the API: ${e?.message ?? e}`);
|
|
40
|
+
}
|
|
41
|
+
const raw = await res.text();
|
|
42
|
+
if (!res.ok)
|
|
43
|
+
throw toApiError(res, raw);
|
|
44
|
+
if (opts.text)
|
|
45
|
+
return raw;
|
|
46
|
+
try {
|
|
47
|
+
return (raw ? JSON.parse(raw) : {});
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { raw };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function toApiError(res, raw) {
|
|
55
|
+
let code = '', message = '', details;
|
|
56
|
+
try {
|
|
57
|
+
const j = JSON.parse(raw);
|
|
58
|
+
code = j?.error?.code ?? '';
|
|
59
|
+
message = j?.error?.message ?? j?.detail ?? '';
|
|
60
|
+
details = j?.error?.details;
|
|
61
|
+
}
|
|
62
|
+
catch { /* not JSON: Cloudflare error page, plain text */ }
|
|
63
|
+
const s = res.status;
|
|
64
|
+
if (!message) {
|
|
65
|
+
if (s === 502 || s === 524)
|
|
66
|
+
message = 'The data provider returned no data for this request, or the gateway timed out. You were not charged for an empty result.';
|
|
67
|
+
else
|
|
68
|
+
message = raw.slice(0, 200) || res.statusText;
|
|
69
|
+
}
|
|
70
|
+
if (s === 401)
|
|
71
|
+
message = 'The API key was rejected (missing, wrong or revoked). ' + message;
|
|
72
|
+
if (s === 403)
|
|
73
|
+
message = `This key is not allowed to do that${code ? ` (${code})` : ''}. Check its scopes with whoami; create a key with the needed scope in the dashboard. ${message}`.trim();
|
|
74
|
+
if (s === 402)
|
|
75
|
+
message = 'Not enough credits for this action. ' + message;
|
|
76
|
+
if (s === 429) {
|
|
77
|
+
const ra = res.headers.get('retry-after');
|
|
78
|
+
message = `Rate limited${ra ? `; retry in ${ra}s` : ''}. ` + message;
|
|
79
|
+
}
|
|
80
|
+
if (s === 503 && code === 'PROVIDER_QUOTA_EXCEEDED')
|
|
81
|
+
message = 'The data provider for this platform is out of quota this month, so this call cannot run until it renews. ' + message;
|
|
82
|
+
return new ApiError(s, code || `HTTP_${s}`, message, details);
|
|
83
|
+
}
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
export const PLATFORMS = ['instagram', 'facebook', 'linkedin', 'tiktok', 'twitter', 'youtube'];
|
|
5
|
+
// Used only if the live rate card cannot be read.
|
|
6
|
+
export const FALLBACK_CALL_COST = { instagram: 1, facebook: 2, linkedin: 8, tiktok: 0.05, twitter: 1, youtube: 0 };
|
|
7
|
+
export const DEFAULT_PAGE_SIZE = 20;
|
|
8
|
+
let cached = null;
|
|
9
|
+
export function loadCatalog() {
|
|
10
|
+
if (cached)
|
|
11
|
+
return cached;
|
|
12
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
for (const p of [join(here, '..', 'catalog', 'endpoints.json'), join(here, '..', '..', 'catalog', 'endpoints.json')]) {
|
|
14
|
+
try {
|
|
15
|
+
cached = JSON.parse(readFileSync(p, 'utf8'));
|
|
16
|
+
return cached;
|
|
17
|
+
}
|
|
18
|
+
catch { /* try next */ }
|
|
19
|
+
}
|
|
20
|
+
throw new Error('catalog/endpoints.json not found; run `npm run catalog`');
|
|
21
|
+
}
|
|
22
|
+
export function findEndpoint(platform, key) {
|
|
23
|
+
return loadCatalog().platforms[platform]?.endpoints.find(e => e.key === key);
|
|
24
|
+
}
|
|
25
|
+
const STOP = new Set(['of', 'a', 'an', 'the', 'for', 'to', 'in', 'on', 'by', 'and', 'or', 'get', 'list', 'all', 'my', 'me', 'from', 'with', 'about', 'find', 'show']);
|
|
26
|
+
const stem = (t) => (t.length > 3 ? t.replace(/(ings|ing|ers|er|s)$/, '') : t);
|
|
27
|
+
const tokens = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter(t => t.length > 1 && !STOP.has(t)).map(stem);
|
|
28
|
+
/** Simple keyword search over key, title, description and parameter names. */
|
|
29
|
+
export function searchEndpoints(query, platform, limit = 15) {
|
|
30
|
+
const cat = loadCatalog();
|
|
31
|
+
const q = tokens(query);
|
|
32
|
+
const rows = [];
|
|
33
|
+
for (const [p, def] of Object.entries(cat.platforms)) {
|
|
34
|
+
if (platform && p !== platform)
|
|
35
|
+
continue;
|
|
36
|
+
for (const e of def.endpoints) {
|
|
37
|
+
const hay = `${e.key} ${e.title} ${e.description} ${e.params.map(x => x.name).join(' ')}`.toLowerCase();
|
|
38
|
+
let score = q.length ? 0 : 1, hits = 0;
|
|
39
|
+
const key = e.key.toLowerCase(), title = e.title.toLowerCase();
|
|
40
|
+
for (const t of q) {
|
|
41
|
+
let h = 0;
|
|
42
|
+
if (key.includes(t))
|
|
43
|
+
h += 4;
|
|
44
|
+
if (title.includes(t))
|
|
45
|
+
h += 3;
|
|
46
|
+
if (hay.includes(t))
|
|
47
|
+
h += 1;
|
|
48
|
+
if (h)
|
|
49
|
+
hits++;
|
|
50
|
+
score += h;
|
|
51
|
+
}
|
|
52
|
+
// Reward endpoints that match every word of the goal, not just one common word like "profile".
|
|
53
|
+
if (q.length > 1 && hits === q.length)
|
|
54
|
+
score += 6;
|
|
55
|
+
if (score > 0)
|
|
56
|
+
rows.push({ platform: p, e, score });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return rows.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
60
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const num = (v, fallback) => {
|
|
2
|
+
const n = Number(v);
|
|
3
|
+
return v !== undefined && v.trim() !== '' && Number.isFinite(n) && n >= 0 ? n : fallback;
|
|
4
|
+
};
|
|
5
|
+
const ALL_TOOLSETS = ['discover', 'research', 'leads', 'publishing'];
|
|
6
|
+
function parseToolsets(v) {
|
|
7
|
+
const picked = (v ?? '').split(',').map(x => x.trim().toLowerCase()).filter(x => ALL_TOOLSETS.includes(x));
|
|
8
|
+
// Discover is always on: the other tools are hard to use without it.
|
|
9
|
+
return picked.length ? Array.from(new Set(['discover', ...picked])) : ALL_TOOLSETS;
|
|
10
|
+
}
|
|
11
|
+
export function configFromEnv(env = process.env, apiKey) {
|
|
12
|
+
const key = (apiKey ?? env.SOCIAL_AUTOMATE_API_KEY ?? '').trim();
|
|
13
|
+
return {
|
|
14
|
+
apiKey: key,
|
|
15
|
+
baseUrl: (env.SOCIAL_AUTOMATE_API_URL || 'https://aisocialautomate.com/api/v1').replace(/\/+$/, ''),
|
|
16
|
+
sessionCap: num(env.SOCIAL_AUTOMATE_SESSION_CAP, 25),
|
|
17
|
+
confirmAbove: num(env.SOCIAL_AUTOMATE_CONFIRM_ABOVE, 10),
|
|
18
|
+
lowBalance: num(env.SOCIAL_AUTOMATE_LOW_BALANCE, 50),
|
|
19
|
+
publishing: ['on', 'drafts', 'off'].includes(String(env.SOCIAL_AUTOMATE_PUBLISHING)) ? env.SOCIAL_AUTOMATE_PUBLISHING : 'on',
|
|
20
|
+
maxLivePosts: num(env.SOCIAL_AUTOMATE_MAX_POSTS, 10),
|
|
21
|
+
toolsets: parseToolsets(env.SOCIAL_AUTOMATE_TOOLSETS),
|
|
22
|
+
localFiles: apiKey === undefined,
|
|
23
|
+
};
|
|
24
|
+
}
|
package/dist/http-app.js
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hosted mode: Streamable HTTP, stateless. The caller sends their own API key (Authorization: Bearer sk_live_… or
|
|
3
|
+
* X-API-Key); nothing is stored on the server except a per-key spending window and short-lived rate-limit counters.
|
|
4
|
+
*
|
|
5
|
+
* Built to sit behind Cloudflare: body and time limits, per-key and per-address rate limits, a cap on requests in
|
|
6
|
+
* flight, structured logs that never contain the key, a health check and Prometheus metrics.
|
|
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 { Api } from './api.js';
|
|
12
|
+
import { configFromEnv } from './config.js';
|
|
13
|
+
import { createOAuth } from './oauth.js';
|
|
14
|
+
import { createServer } from './server.js';
|
|
15
|
+
import { Usage } from './usage.js';
|
|
16
|
+
const intEnv = (v, fallback) => {
|
|
17
|
+
const n = Number(v);
|
|
18
|
+
return v !== undefined && v.trim() !== '' && Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
|
|
19
|
+
};
|
|
20
|
+
const sha = (s) => createHash('sha256').update(s).digest('hex');
|
|
21
|
+
/** A fixed-window counter per id. Cheap, and good enough to stop a runaway client. */
|
|
22
|
+
class WindowLimiter {
|
|
23
|
+
limit;
|
|
24
|
+
windowMs;
|
|
25
|
+
hits = new Map();
|
|
26
|
+
constructor(limit, windowMs) {
|
|
27
|
+
this.limit = limit;
|
|
28
|
+
this.windowMs = windowMs;
|
|
29
|
+
}
|
|
30
|
+
/** Counts one hit. Returns 0 when allowed, otherwise the seconds to wait. */
|
|
31
|
+
hit(id, now = Date.now()) {
|
|
32
|
+
if (this.limit <= 0)
|
|
33
|
+
return 0;
|
|
34
|
+
const h = this.hits.get(id);
|
|
35
|
+
if (!h || now - h.start >= this.windowMs) {
|
|
36
|
+
this.hits.set(id, { start: now, count: 1 });
|
|
37
|
+
if (this.hits.size > 20_000)
|
|
38
|
+
this.prune(now);
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
h.count++;
|
|
42
|
+
return h.count > this.limit ? Math.max(1, Math.ceil((h.start + this.windowMs - now) / 1000)) : 0;
|
|
43
|
+
}
|
|
44
|
+
prune(now) { for (const [k, v] of this.hits)
|
|
45
|
+
if (now - v.start >= this.windowMs)
|
|
46
|
+
this.hits.delete(k); }
|
|
47
|
+
}
|
|
48
|
+
class Metrics {
|
|
49
|
+
counters = new Map();
|
|
50
|
+
inFlight = 0;
|
|
51
|
+
startedAt = Date.now();
|
|
52
|
+
inc(name, labels = {}) {
|
|
53
|
+
const l = Object.entries(labels).map(([k, v]) => `${k}="${String(v).replace(/["\\\n]/g, '')}"`).join(',');
|
|
54
|
+
const key = l ? `${name}{${l}}` : name;
|
|
55
|
+
this.counters.set(key, (this.counters.get(key) ?? 0) + 1);
|
|
56
|
+
}
|
|
57
|
+
text() {
|
|
58
|
+
const lines = [
|
|
59
|
+
'# TYPE mcp_requests_total counter', '# TYPE mcp_tool_calls_total counter', '# TYPE mcp_rate_limited_total counter',
|
|
60
|
+
'# TYPE mcp_auth_failures_total counter', '# TYPE mcp_in_flight gauge', '# TYPE mcp_uptime_seconds gauge',
|
|
61
|
+
...[...this.counters].map(([k, v]) => `${k} ${v}`),
|
|
62
|
+
`mcp_in_flight ${this.inFlight}`,
|
|
63
|
+
`mcp_uptime_seconds ${Math.round((Date.now() - this.startedAt) / 1000)}`,
|
|
64
|
+
];
|
|
65
|
+
return lines.join('\n') + '\n';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const rpcError = (code, message) => JSON.stringify({ jsonrpc: '2.0', error: { code, message }, id: null });
|
|
69
|
+
function send(res, status, body, headers = {}, done) {
|
|
70
|
+
if (res.headersSent) {
|
|
71
|
+
res.end();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
res.writeHead(status, { 'content-type': 'application/json', ...headers });
|
|
75
|
+
res.end(body, done);
|
|
76
|
+
}
|
|
77
|
+
class BodyTooLarge extends Error {
|
|
78
|
+
}
|
|
79
|
+
class BadJson extends Error {
|
|
80
|
+
}
|
|
81
|
+
async function readJson(req, max) {
|
|
82
|
+
if (Number(req.headers['content-length'] ?? 0) > max)
|
|
83
|
+
throw new BodyTooLarge();
|
|
84
|
+
const chunks = [];
|
|
85
|
+
let size = 0;
|
|
86
|
+
for await (const c of req) {
|
|
87
|
+
size += c.length;
|
|
88
|
+
if (size > max)
|
|
89
|
+
throw new BodyTooLarge();
|
|
90
|
+
chunks.push(c);
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new BadJson();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Names of the tools a request calls, for the logs and metrics. */
|
|
100
|
+
function rpcSummary(body) {
|
|
101
|
+
const items = Array.isArray(body) ? body : [body];
|
|
102
|
+
const methods = new Set();
|
|
103
|
+
const tools = [];
|
|
104
|
+
for (const m of items) {
|
|
105
|
+
if (typeof m?.method === 'string')
|
|
106
|
+
methods.add(m.method);
|
|
107
|
+
if (m?.method === 'tools/call' && typeof m?.params?.name === 'string')
|
|
108
|
+
tools.push(m.params.name);
|
|
109
|
+
}
|
|
110
|
+
return { method: [...methods].join(',') || 'unknown', tools };
|
|
111
|
+
}
|
|
112
|
+
const keyFrom = (h) => {
|
|
113
|
+
const auth = String(h.authorization ?? '');
|
|
114
|
+
const bearer = /^(?:Bearer|ApiKey)\s+(\S+)/i.exec(auth)?.[1];
|
|
115
|
+
return (bearer ?? String(h['x-api-key'] ?? '')).trim();
|
|
116
|
+
};
|
|
117
|
+
export function createHttpApp(options = {}) {
|
|
118
|
+
const env = options.env ?? process.env;
|
|
119
|
+
const log = options.log ?? (e => console.log(JSON.stringify({ ts: new Date().toISOString(), ...e })));
|
|
120
|
+
const windowMs = intEnv(env.SOCIAL_AUTOMATE_SESSION_WINDOW_MINUTES, 60) * 60_000;
|
|
121
|
+
const maxBody = intEnv(env.MCP_MAX_BODY_BYTES, 1_048_576);
|
|
122
|
+
const maxInFlight = intEnv(env.MCP_MAX_IN_FLIGHT, 200);
|
|
123
|
+
const requestTimeoutMs = intEnv(env.MCP_REQUEST_TIMEOUT_MS, 200_000);
|
|
124
|
+
const perKey = new WindowLimiter(intEnv(env.MCP_RATE_LIMIT_PER_MINUTE, 120), 60_000);
|
|
125
|
+
const authFails = new WindowLimiter(intEnv(env.MCP_AUTH_FAIL_PER_MINUTE, 20), 60_000);
|
|
126
|
+
const trustProxy = /^(1|true|yes|cloudflare)$/i.test(env.MCP_TRUST_PROXY ?? '');
|
|
127
|
+
const origins = (env.MCP_ALLOWED_ORIGINS ?? '').split(',').map(s => s.trim()).filter(Boolean);
|
|
128
|
+
const metricsToken = env.MCP_METRICS_TOKEN ?? '';
|
|
129
|
+
const metrics = new Metrics();
|
|
130
|
+
const oauth = createOAuth(env, options.fetch);
|
|
131
|
+
const oauthHits = new WindowLimiter(intEnv(env.MCP_OAUTH_PER_MINUTE, 120), 60_000);
|
|
132
|
+
const trackers = new Map();
|
|
133
|
+
/** One spending window per API key, so the cap holds across the many short requests a hosted client makes. */
|
|
134
|
+
const usageFor = (id, mk) => {
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const t = trackers.get(id);
|
|
137
|
+
if (t && now - t.since < windowMs)
|
|
138
|
+
return t.usage;
|
|
139
|
+
const fresh = { usage: mk(), since: now };
|
|
140
|
+
trackers.set(id, fresh);
|
|
141
|
+
if (trackers.size > 5000)
|
|
142
|
+
for (const [k, v] of trackers)
|
|
143
|
+
if (now - v.since >= windowMs)
|
|
144
|
+
trackers.delete(k);
|
|
145
|
+
return fresh.usage;
|
|
146
|
+
};
|
|
147
|
+
const clientIp = (req) => {
|
|
148
|
+
if (trustProxy) {
|
|
149
|
+
const cf = req.headers['cf-connecting-ip'];
|
|
150
|
+
if (typeof cf === 'string' && cf)
|
|
151
|
+
return cf.trim();
|
|
152
|
+
const xff = req.headers['x-forwarded-for'];
|
|
153
|
+
if (typeof xff === 'string' && xff)
|
|
154
|
+
return xff.split(',')[0].trim();
|
|
155
|
+
}
|
|
156
|
+
return req.socket.remoteAddress ?? 'unknown';
|
|
157
|
+
};
|
|
158
|
+
let draining = false;
|
|
159
|
+
const server = createHttpServer(async (req, res) => {
|
|
160
|
+
const started = Date.now();
|
|
161
|
+
const path = (req.url ?? '').split('?')[0];
|
|
162
|
+
const ip = clientIp(req);
|
|
163
|
+
if (path === '/health' || path === '/healthz') {
|
|
164
|
+
send(res, draining ? 503 : 200, JSON.stringify({ ok: !draining, uptime_s: Math.round((Date.now() - metrics.startedAt) / 1000) }));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (path === '/metrics') {
|
|
168
|
+
const given = String(req.headers.authorization ?? '').replace(/^Bearer\s+/i, '');
|
|
169
|
+
if (!metricsToken || given !== metricsToken) {
|
|
170
|
+
res.writeHead(404).end();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4' }).end(metrics.text());
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
// OpenAI's directory proves domain ownership with a plain-text token served here (set MCP_OPENAI_CHALLENGE to the token it shows).
|
|
177
|
+
if (path === '/.well-known/openai-apps-challenge' && env.MCP_OPENAI_CHALLENGE) {
|
|
178
|
+
res.writeHead(200, { 'content-type': 'text/plain' }).end(env.MCP_OPENAI_CHALLENGE.trim());
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (oauth.enabled && (path.startsWith('/.well-known/') || path.startsWith('/oauth/'))) {
|
|
182
|
+
const wait = oauthHits.hit(ip);
|
|
183
|
+
if (wait) {
|
|
184
|
+
metrics.inc('mcp_rate_limited_total', { kind: 'oauth' });
|
|
185
|
+
send(res, 429, JSON.stringify({ error: 'rate_limited' }), { 'retry-after': String(wait) });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
if (await oauth.handle(req, res, path, ip))
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
if (!res.headersSent)
|
|
194
|
+
send(res, 500, JSON.stringify({ error: 'server_error' }));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (path !== '/mcp') {
|
|
199
|
+
res.writeHead(404).end();
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
let status = 0;
|
|
203
|
+
let rpc = { method: '-', tools: [] };
|
|
204
|
+
let keyId = '-';
|
|
205
|
+
let note = '';
|
|
206
|
+
res.on('close', () => {
|
|
207
|
+
status = status || res.statusCode;
|
|
208
|
+
metrics.inFlight--;
|
|
209
|
+
metrics.inc('mcp_requests_total', { status });
|
|
210
|
+
for (const t of rpc.tools)
|
|
211
|
+
metrics.inc('mcp_tool_calls_total', { tool: t });
|
|
212
|
+
log({ level: status >= 500 ? 'error' : 'info', msg: 'request', ip, key: keyId, rpc: rpc.method, tools: rpc.tools, status, ms: Date.now() - started, ...(note ? { note } : {}) });
|
|
213
|
+
});
|
|
214
|
+
metrics.inFlight++;
|
|
215
|
+
const reject = (s, code, message, headers = {}, why = '') => { status = s; note = why; send(res, s, rpcError(code, message), headers); };
|
|
216
|
+
if (draining)
|
|
217
|
+
return reject(503, -32000, 'The server is restarting. Try again in a moment.', { 'retry-after': '5', connection: 'close' }, 'draining');
|
|
218
|
+
if (metrics.inFlight > maxInFlight) {
|
|
219
|
+
metrics.inc('mcp_rate_limited_total', { kind: 'overload' });
|
|
220
|
+
return reject(503, -32000, 'The server is busy. Try again in a moment.', { 'retry-after': '2' }, 'overload');
|
|
221
|
+
}
|
|
222
|
+
// Browsers send Origin; this server is meant for MCP clients, so a browser page may only call it if the operator allowed it.
|
|
223
|
+
const origin = req.headers.origin;
|
|
224
|
+
if (origin && !origins.includes(String(origin)))
|
|
225
|
+
return reject(403, -32000, 'Origin not allowed.', {}, 'origin');
|
|
226
|
+
if (req.method !== 'POST')
|
|
227
|
+
return reject(405, -32000, 'Method not allowed. Send MCP requests with POST.', { allow: 'POST' });
|
|
228
|
+
const given = keyFrom(req.headers);
|
|
229
|
+
// Directory clients send an OAuth access token (mcp_at_…) that carries the user's key; developers send sk_live_… directly.
|
|
230
|
+
const key = given.startsWith('mcp_at_') ? (oauth.resolveToken(given) ?? '') : given;
|
|
231
|
+
if (!key.startsWith('sk_')) {
|
|
232
|
+
metrics.inc('mcp_auth_failures_total');
|
|
233
|
+
const wait = authFails.hit(ip);
|
|
234
|
+
if (wait) {
|
|
235
|
+
metrics.inc('mcp_rate_limited_total', { kind: 'auth' });
|
|
236
|
+
return reject(429, -32000, 'Too many requests without a valid key.', { 'retry-after': String(wait) }, 'auth-limit');
|
|
237
|
+
}
|
|
238
|
+
const expired = given.startsWith('mcp_at_');
|
|
239
|
+
const challenge = oauth.enabled ? `Bearer realm="aisocialautomate", resource_metadata="${oauth.metadataUrl}"${expired ? ', error="invalid_token"' : ''}` : 'Bearer realm="aisocialautomate"';
|
|
240
|
+
return reject(401, -32001, expired ? 'The access token expired. Reconnect to continue.' : 'Sign in to AI Social Automate, or send your API key: Authorization: Bearer sk_live_…', { 'www-authenticate': challenge }, expired ? 'bad-token' : 'no-key');
|
|
241
|
+
}
|
|
242
|
+
const id = sha(key);
|
|
243
|
+
keyId = id.slice(0, 10);
|
|
244
|
+
const wait = perKey.hit(id);
|
|
245
|
+
if (wait) {
|
|
246
|
+
metrics.inc('mcp_rate_limited_total', { kind: 'key' });
|
|
247
|
+
return reject(429, -32000, `Too many requests for this key; retry in ${wait}s.`, { 'retry-after': String(wait) }, 'key-limit');
|
|
248
|
+
}
|
|
249
|
+
let body;
|
|
250
|
+
try {
|
|
251
|
+
body = await readJson(req, maxBody);
|
|
252
|
+
}
|
|
253
|
+
catch (e) {
|
|
254
|
+
if (e instanceof BodyTooLarge) {
|
|
255
|
+
status = 413;
|
|
256
|
+
note = 'too-large';
|
|
257
|
+
send(res, 413, rpcError(-32600, 'Request too large.'), { connection: 'close' }, () => req.destroy());
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
return reject(400, -32700, 'Parse error: the body must be JSON.');
|
|
261
|
+
}
|
|
262
|
+
rpc = rpcSummary(body);
|
|
263
|
+
const timer = setTimeout(() => { status = 504; note = 'timeout'; send(res, 504, rpcError(-32603, 'The request took too long.')); }, requestTimeoutMs);
|
|
264
|
+
res.on('close', () => clearTimeout(timer));
|
|
265
|
+
const cfg = configFromEnv(env, key);
|
|
266
|
+
const mcp = createServer({ cfg, api: new Api(cfg), usage: usageFor(id, () => new Usage(cfg)) });
|
|
267
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
268
|
+
res.on('close', () => { transport.close(); mcp.close(); });
|
|
269
|
+
try {
|
|
270
|
+
await mcp.connect(transport);
|
|
271
|
+
await transport.handleRequest(req, res, body);
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
note = `error:${String(e?.message ?? e).slice(0, 120)}`;
|
|
275
|
+
if (!res.headersSent) {
|
|
276
|
+
status = 500;
|
|
277
|
+
send(res, 500, rpcError(-32603, 'Internal error'));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
// Receive limits (Slowloris) and keep-alive longer than the proxy's idle time so it never reuses a closed socket.
|
|
282
|
+
server.headersTimeout = 15_000;
|
|
283
|
+
server.requestTimeout = 30_000;
|
|
284
|
+
server.keepAliveTimeout = 75_000;
|
|
285
|
+
const shutdown = (graceMs = 25_000) => new Promise(resolve => {
|
|
286
|
+
draining = true;
|
|
287
|
+
const force = setTimeout(() => { server.closeAllConnections(); resolve(); }, graceMs);
|
|
288
|
+
server.close(() => { clearTimeout(force); resolve(); });
|
|
289
|
+
server.closeIdleConnections();
|
|
290
|
+
});
|
|
291
|
+
return { server, metrics, shutdown };
|
|
292
|
+
}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Hosted entry point. The server itself lives in http-app.ts so it can be tested. */
|
|
3
|
+
import { createHttpApp } from './http-app.js';
|
|
4
|
+
const port = Number(process.env.PORT ?? 8787);
|
|
5
|
+
const app = createHttpApp();
|
|
6
|
+
app.server.listen(port, '0.0.0.0', 1024, () => console.log(JSON.stringify({ ts: new Date().toISOString(), level: 'info', msg: 'listening', port })));
|
|
7
|
+
// Platforms stop a container with SIGTERM: finish the requests in flight, then exit.
|
|
8
|
+
for (const sig of ['SIGTERM', 'SIGINT']) {
|
|
9
|
+
process.on(sig, () => {
|
|
10
|
+
console.log(JSON.stringify({ ts: new Date().toISOString(), level: 'info', msg: 'shutting down', signal: sig }));
|
|
11
|
+
app.shutdown().then(() => process.exit(0));
|
|
12
|
+
});
|
|
13
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetching a link the caller supplied, safely. The hosted server runs next to private services, so a caller must not be
|
|
3
|
+
* able to make it read internal addresses (cloud metadata, localhost, the private network) and hand the result back.
|
|
4
|
+
*
|
|
5
|
+
* Every connection is checked at connect time (not just once before it), so a name that resolves to a public address
|
|
6
|
+
* first and a private one later (DNS rebinding) is still refused. Redirects are followed by hand and re-checked.
|
|
7
|
+
*/
|
|
8
|
+
import dns from 'node:dns';
|
|
9
|
+
import http from 'node:http';
|
|
10
|
+
import https from 'node:https';
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
export class GuardError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function v4Private(a, b) {
|
|
20
|
+
return a === 0 || a === 10 || a === 127 || a >= 224
|
|
21
|
+
|| (a === 100 && b >= 64 && b <= 127) // carrier-grade NAT
|
|
22
|
+
|| (a === 169 && b === 254) // link-local, cloud metadata
|
|
23
|
+
|| (a === 172 && b >= 16 && b <= 31)
|
|
24
|
+
|| (a === 192 && b === 168)
|
|
25
|
+
|| (a === 192 && b === 0)
|
|
26
|
+
|| (a === 198 && (b === 18 || b === 19));
|
|
27
|
+
}
|
|
28
|
+
/** Expands an IPv6 text address into 8 groups, or null when it is not valid. */
|
|
29
|
+
function groups6(addr) {
|
|
30
|
+
let s = addr.split('%')[0];
|
|
31
|
+
const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(s);
|
|
32
|
+
if (tail) {
|
|
33
|
+
const p = tail[1].split('.').map(Number);
|
|
34
|
+
s = s.slice(0, -tail[1].length) + ((p[0] << 8) | p[1]).toString(16) + ':' + ((p[2] << 8) | p[3]).toString(16);
|
|
35
|
+
}
|
|
36
|
+
const halves = s.split('::');
|
|
37
|
+
if (halves.length > 2)
|
|
38
|
+
return null;
|
|
39
|
+
const head = halves[0] ? halves[0].split(':') : [];
|
|
40
|
+
const rest = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
|
41
|
+
const missing = 8 - head.length - rest.length;
|
|
42
|
+
if (halves.length === 2 ? missing < 0 : missing !== 0)
|
|
43
|
+
return null;
|
|
44
|
+
const all = [...head, ...Array(halves.length === 2 ? missing : 0).fill('0'), ...rest].map(g => parseInt(g, 16));
|
|
45
|
+
return all.length === 8 && all.every(n => Number.isInteger(n) && n >= 0 && n <= 0xffff) ? all : null;
|
|
46
|
+
}
|
|
47
|
+
/** True for any address that is not a normal public internet address. Anything unparseable counts as private. */
|
|
48
|
+
export function isPrivateAddress(addr) {
|
|
49
|
+
if (net.isIPv4(addr)) {
|
|
50
|
+
const [a, b] = addr.split('.').map(Number);
|
|
51
|
+
return v4Private(a, b);
|
|
52
|
+
}
|
|
53
|
+
if (net.isIPv6(addr)) {
|
|
54
|
+
const g = groups6(addr);
|
|
55
|
+
if (!g)
|
|
56
|
+
return true;
|
|
57
|
+
const first = g[0];
|
|
58
|
+
const embedded = (hi) => v4Private(hi >> 8, hi & 255); // the IPv4 address tucked into the last 32 bits
|
|
59
|
+
if (g.slice(0, 5).every(n => n === 0) && g[5] === 0xffff)
|
|
60
|
+
return embedded(g[6]); // ::ffff:a.b.c.d
|
|
61
|
+
if (g[0] === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every(n => n === 0))
|
|
62
|
+
return embedded(g[6]); // NAT64
|
|
63
|
+
if (g.every(n => n === 0) || (g.slice(0, 7).every(n => n === 0) && g[7] === 1))
|
|
64
|
+
return true; // :: and ::1
|
|
65
|
+
if ((first & 0xfe00) === 0xfc00)
|
|
66
|
+
return true; // unique local
|
|
67
|
+
if ((first & 0xffc0) === 0xfe80)
|
|
68
|
+
return true; // link-local
|
|
69
|
+
if ((first & 0xff00) === 0xff00)
|
|
70
|
+
return true; // multicast
|
|
71
|
+
if (first === 0x2001 && g[1] === 0x0db8)
|
|
72
|
+
return true; // documentation
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
const guardedLookup = (host, options, cb) => {
|
|
78
|
+
dns.lookup(host, { ...options, all: true }, (err, addrs) => {
|
|
79
|
+
if (err)
|
|
80
|
+
return cb(err);
|
|
81
|
+
const list = addrs;
|
|
82
|
+
if (!list.length || list.some(a => isPrivateAddress(a.address))) {
|
|
83
|
+
return cb(Object.assign(new Error('That address is not allowed.'), { code: 'URL_NOT_ALLOWED' }));
|
|
84
|
+
}
|
|
85
|
+
if (options?.all)
|
|
86
|
+
return cb(null, list);
|
|
87
|
+
return cb(null, list[0].address, list[0].family);
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
91
|
+
export async function fetchPublic(input, opts) {
|
|
92
|
+
const timeoutMs = opts.timeoutMs ?? 60_000;
|
|
93
|
+
const deadline = Date.now() + timeoutMs;
|
|
94
|
+
let url = new URL(input);
|
|
95
|
+
for (let hop = 0;; hop++) {
|
|
96
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
97
|
+
throw new GuardError('URL_NOT_ALLOWED', 'Only http(s) links can be fetched.');
|
|
98
|
+
if (url.username || url.password)
|
|
99
|
+
throw new GuardError('URL_NOT_ALLOWED', 'Links with a username or password are not allowed.');
|
|
100
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
101
|
+
if (net.isIP(host) && isPrivateAddress(host))
|
|
102
|
+
throw new GuardError('URL_NOT_ALLOWED', 'That address is not allowed.');
|
|
103
|
+
const left = deadline - Date.now();
|
|
104
|
+
if (left <= 0)
|
|
105
|
+
throw new GuardError('FETCH_FAILED', 'The download took too long.');
|
|
106
|
+
const res = await get(url, left);
|
|
107
|
+
if (REDIRECTS.has(res.statusCode ?? 0) && res.headers.location) {
|
|
108
|
+
res.resume();
|
|
109
|
+
if (hop >= (opts.maxRedirects ?? 3))
|
|
110
|
+
throw new GuardError('FETCH_FAILED', 'Too many redirects.');
|
|
111
|
+
url = new URL(res.headers.location, url);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const declared = Number(res.headers['content-length'] ?? 0);
|
|
115
|
+
if (declared > opts.maxBytes) {
|
|
116
|
+
res.destroy();
|
|
117
|
+
throw new GuardError('FILE_TOO_LARGE', 'That file is too large for this upload.');
|
|
118
|
+
}
|
|
119
|
+
const chunks = [];
|
|
120
|
+
let size = 0;
|
|
121
|
+
try {
|
|
122
|
+
for await (const chunk of res) {
|
|
123
|
+
size += chunk.length;
|
|
124
|
+
if (size > opts.maxBytes) {
|
|
125
|
+
res.destroy();
|
|
126
|
+
throw new GuardError('FILE_TOO_LARGE', 'That file is too large for this upload.');
|
|
127
|
+
}
|
|
128
|
+
chunks.push(chunk);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
if (e instanceof GuardError)
|
|
133
|
+
throw e;
|
|
134
|
+
throw new GuardError('FETCH_FAILED', 'The download was interrupted.');
|
|
135
|
+
}
|
|
136
|
+
return { status: res.statusCode ?? 0, bytes: Buffer.concat(chunks), finalUrl: url };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function get(url, timeoutMs) {
|
|
140
|
+
return new Promise((resolve, reject) => {
|
|
141
|
+
const mod = url.protocol === 'https:' ? https : http;
|
|
142
|
+
const req = mod.request(url, { method: 'GET', lookup: guardedLookup, headers: { 'user-agent': 'aisocialautomate-mcp/0.1', accept: '*/*' } }, resolve);
|
|
143
|
+
const timer = setTimeout(() => req.destroy(Object.assign(new Error('timeout'), { code: 'ETIMEDOUT' })), timeoutMs);
|
|
144
|
+
req.on('close', () => clearTimeout(timer));
|
|
145
|
+
req.on('error', (e) => {
|
|
146
|
+
if (e?.code === 'URL_NOT_ALLOWED')
|
|
147
|
+
reject(new GuardError('URL_NOT_ALLOWED', 'That address is not allowed.'));
|
|
148
|
+
else if (e?.code === 'ETIMEDOUT')
|
|
149
|
+
reject(new GuardError('FETCH_FAILED', 'The download took too long.'));
|
|
150
|
+
else
|
|
151
|
+
reject(new GuardError('FETCH_FAILED', 'Could not download that link.'));
|
|
152
|
+
});
|
|
153
|
+
req.end();
|
|
154
|
+
});
|
|
155
|
+
}
|