@aisocialautomate/mcp 0.1.0 → 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/README.md CHANGED
@@ -9,7 +9,14 @@ Ask things like:
9
9
 
10
10
  ## Set up
11
11
 
12
- 1. Create an API key in the dashboard (Developer → API Keys). For research, give it `leads:read`, `leads:write` and `credits:read` only.
12
+ You need an AI Social Automate account with an active plan ([aisocialautomate.com](https://aisocialautomate.com)).
13
+
14
+ **Easiest: sign in, no key to paste (Claude, ChatGPT, Claude Code).** Add the hosted URL as a connector, sign in and click Allow. It offers the publishing tools (drafts, scheduling, publishing, media, accounts, analytics).
15
+ - Claude / ChatGPT: Settings → Connectors → add a custom connector with `https://mcp.aisocialautomate.com/mcp`.
16
+ - Claude Code: `claude mcp add --transport http aisocialautomate https://mcp.aisocialautomate.com/mcp`, then `/mcp` to sign in.
17
+
18
+ **With an API key (all tools, including research and leads).**
19
+ 1. Create an API key in the dashboard (Developer → API Keys). For research, give it `leads:read`, `leads:write` and `credits:read` only; for publishing add `publishing:read`, `publishing:write` and `connections:read`.
13
20
  2. Add the server to your client.
14
21
 
15
22
  **Claude Desktop / Claude Code / Codex (local, over stdio)**
@@ -26,7 +33,7 @@ Ask things like:
26
33
  ```
27
34
  Claude Code: `claude mcp add aisocialautomate -e SOCIAL_AUTOMATE_API_KEY=sk_live_... -- npx -y @aisocialautomate/mcp`
28
35
 
29
- **Hosted (Streamable HTTP):** run `node dist/http.js` (or deploy it) and point the client at `https://<host>/mcp` with the header `Authorization: Bearer sk_live_...`. The hosted server has built-in rate limits, request limits, a `/health` check and optional `/metrics`, configured with `MCP_*` environment variables.
36
+ **Hosted (Streamable HTTP):** point the client at `https://mcp.aisocialautomate.com/mcp`, either with OAuth sign-in (above) or the header `Authorization: Bearer sk_live_...`. To run your own, `node dist/http.js` (see DEPLOY.md); set `MCP_OAUTH_SECRET`, `MCP_PUBLIC_URL` and `MCP_CONSENT_ORIGIN` to turn on OAuth. The hosted server has built-in rate limits, request limits, a `/health` check and optional `/metrics`, configured with `MCP_*` environment variables.
30
37
 
31
38
  ## Usage limits and warnings
32
39
 
@@ -47,16 +54,17 @@ Credits are real money, so the server protects them:
47
54
 
48
55
  ## Tools
49
56
 
50
- Discover (free): `whoami`, `get_credit_balance`, `get_pricing`, `list_connected_accounts`, `connect_account` (gives a link to connect a social account), `list_brands`, `list_platforms`, `search_endpoints`, `describe_endpoint`, `usage_status`.
57
+ Discover (free): `whoami`, `get_credit_balance`, `get_pricing`, `list_connected_accounts`, `connect_account` (gives a link to connect a social account), `list_brands`, `usage_status`. Research helpers: `list_platforms`, `search_endpoints`, `describe_endpoint`.
51
58
  Research: `scrape` (one call), `start_bulk_scrape`, `get_run`, `list_runs`, `cancel_run`.
52
- Publishing: `list_posts`, `get_post`, `get_post_analytics`, `list_templates`, `get_tiktok_creator_info`, `search_instagram_music`, `upload_media`, `create_post` (draft / schedule / now), `update_post`, `cancel_post`, `restore_post`, `duplicate_post`, `delete_post`.
59
+ Publishing: `list_posts`, `get_post`, `get_post_analytics`, `list_templates`, `get_tiktok_creator_info`, `search_instagram_music`, `upload_media`, `create_draft`, `schedule_post`, `publish_now`, `update_post`, `cancel_post`, `restore_post`, `duplicate_post`, `delete_post`.
53
60
  Leads: `start_lead_job`, `get_lead_job`, `list_lead_jobs`, `cancel_lead_job`, `search_leads`, `export_leads`, `list_lead_lists`, `create_lead_list`, `add_leads_to_list`.
54
61
 
55
62
  About 200 endpoints (Instagram 30, Facebook 46, LinkedIn 36, TikTok 43, X 40, YouTube 3 placeholder) are reached through `scrape`/`start_bulk_scrape`; `search_endpoints` and `describe_endpoint` tell the model which key and parameters to use. The catalogue is generated from the website's endpoint docs: run `npm run catalog` after endpoints change.
56
63
 
57
64
  ## Publishing safety
58
65
 
59
- - `create_post` with `mode: "draft"` saves straight away. `"schedule"` and `"now"` return a preview (accounts, text, media, time) and only run after the user agrees and the call is repeated with `confirm: true`. `"now"` also warns that it is immediate and public.
66
+ - `create_draft` saves straight away. `schedule_post` and `publish_now` return a preview (accounts, text, media, time) and only run after the user agrees and the call is repeated with `confirm: true`. `publish_now` also warns that it is immediate and public.
67
+ - If a platform has no connected account (or its login expired), the reply is `NEEDS_CONNECTION` with a link; the user connects it and the assistant retries. `connect_account` returns the same link on request.
60
68
  - `restore_post` and `delete_post` ask first too; deleting is permanent.
61
69
  - Times are never guessed. `scheduled_at` must carry an offset or `Z`, or come with a `timezone` (IANA name such as `Asia/Kolkata`); a bare time with no zone is refused. The preview shows the time in the user's zone and in UTC.
62
70
  - Targets must be connected accounts of the workspace; disconnected ones are refused with a clear message.
package/dist/http-app.js CHANGED
@@ -10,6 +10,7 @@ import { createServer as createHttpServer } from 'node:http';
10
10
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
11
11
  import { Api } from './api.js';
12
12
  import { configFromEnv } from './config.js';
13
+ import { createOAuth } from './oauth.js';
13
14
  import { createServer } from './server.js';
14
15
  import { Usage } from './usage.js';
15
16
  const intEnv = (v, fallback) => {
@@ -126,6 +127,8 @@ export function createHttpApp(options = {}) {
126
127
  const origins = (env.MCP_ALLOWED_ORIGINS ?? '').split(',').map(s => s.trim()).filter(Boolean);
127
128
  const metricsToken = env.MCP_METRICS_TOKEN ?? '';
128
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);
129
132
  const trackers = new Map();
130
133
  /** One spending window per API key, so the cap holds across the many short requests a hosted client makes. */
131
134
  const usageFor = (id, mk) => {
@@ -170,6 +173,28 @@ export function createHttpApp(options = {}) {
170
173
  res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4' }).end(metrics.text());
171
174
  return;
172
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
+ }
173
198
  if (path !== '/mcp') {
174
199
  res.writeHead(404).end();
175
200
  return;
@@ -200,7 +225,9 @@ export function createHttpApp(options = {}) {
200
225
  return reject(403, -32000, 'Origin not allowed.', {}, 'origin');
201
226
  if (req.method !== 'POST')
202
227
  return reject(405, -32000, 'Method not allowed. Send MCP requests with POST.', { allow: 'POST' });
203
- const key = keyFrom(req.headers);
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;
204
231
  if (!key.startsWith('sk_')) {
205
232
  metrics.inc('mcp_auth_failures_total');
206
233
  const wait = authFails.hit(ip);
@@ -208,7 +235,9 @@ export function createHttpApp(options = {}) {
208
235
  metrics.inc('mcp_rate_limited_total', { kind: 'auth' });
209
236
  return reject(429, -32000, 'Too many requests without a valid key.', { 'retry-after': String(wait) }, 'auth-limit');
210
237
  }
211
- return reject(401, -32001, 'Send your API key: Authorization: Bearer sk_live_…', { 'www-authenticate': 'Bearer realm="aisocialautomate"' }, 'no-key');
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');
212
241
  }
213
242
  const id = sha(key);
214
243
  keyId = id.slice(0, 10);
package/dist/oauth.js ADDED
@@ -0,0 +1,339 @@
1
+ /**
2
+ * OAuth 2.1 for the hosted MCP server, so Claude, ChatGPT and other directory clients can connect with a normal
3
+ * "sign in and allow" flow instead of a pasted key.
4
+ *
5
+ * Stateless by design: client ids, authorization codes and tokens are AES-256-GCM sealed blobs that only this server can
6
+ * open, so nothing is stored except the short-lived pending sign-in requests in memory. The token carries the user's own
7
+ * API key (created by the dashboard when the user clicks Allow), so every call is still charged and scoped by that key
8
+ * and revoking the key in the dashboard cuts the connection off.
9
+ *
10
+ * client ─ /oauth/register ─▶ client_id (sealed)
11
+ * client ─ /oauth/authorize ─▶ redirect to the dashboard consent page (user signs in, clicks Allow)
12
+ * dashboard ─ POST /oauth/complete {request, key} ─▶ redirect back to the client with ?code=
13
+ * client ─ /oauth/token (PKCE) ─▶ access + refresh token
14
+ */
15
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto';
16
+ const ACCESS_TTL_S = 3600;
17
+ const REFRESH_TTL_S = 90 * 24 * 3600;
18
+ const CODE_TTL_S = 300;
19
+ const PENDING_TTL_MS = 10 * 60_000;
20
+ const MAX_FORM = 16_384;
21
+ const b64 = (b) => b.toString('base64url');
22
+ const nowS = () => Math.floor(Date.now() / 1000);
23
+ class Sealer {
24
+ enc;
25
+ mac;
26
+ constructor(secret) {
27
+ this.enc = Buffer.from(hkdfSync('sha256', secret, 'aisocialautomate-mcp', 'enc', 32));
28
+ this.mac = Buffer.from(hkdfSync('sha256', secret, 'aisocialautomate-mcp', 'mac', 32));
29
+ }
30
+ seal(obj) {
31
+ const iv = randomBytes(12);
32
+ const c = createCipheriv('aes-256-gcm', this.enc, iv);
33
+ const ct = Buffer.concat([c.update(JSON.stringify(obj), 'utf8'), c.final()]);
34
+ return b64(Buffer.concat([iv, c.getAuthTag(), ct]));
35
+ }
36
+ open(blob) {
37
+ try {
38
+ const raw = Buffer.from(blob, 'base64url');
39
+ if (raw.length < 29)
40
+ return null;
41
+ const d = createDecipheriv('aes-256-gcm', this.enc, raw.subarray(0, 12));
42
+ d.setAuthTag(raw.subarray(12, 28));
43
+ return JSON.parse(Buffer.concat([d.update(raw.subarray(28)), d.final()]).toString('utf8'));
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ /** Client ids are public, so they are signed rather than sealed. */
50
+ sign(obj) {
51
+ const body = b64(Buffer.from(JSON.stringify(obj)));
52
+ return `${body}.${b64(createHmac('sha256', this.mac).update(body).digest())}`;
53
+ }
54
+ verify(s) {
55
+ const [body, sig] = s.split('.');
56
+ if (!body || !sig)
57
+ return null;
58
+ const want = createHmac('sha256', this.mac).update(body).digest();
59
+ let got;
60
+ try {
61
+ got = Buffer.from(sig, 'base64url');
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ if (got.length !== want.length || !timingSafeEqual(got, want))
67
+ return null;
68
+ try {
69
+ return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ }
76
+ const json = (res, status, body, headers = {}) => {
77
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers });
78
+ res.end(JSON.stringify(body));
79
+ };
80
+ const oauthErr = (res, status, error, description, headers = {}) => json(res, status, { error, error_description: description }, headers);
81
+ async function readBody(req) {
82
+ const chunks = [];
83
+ let size = 0;
84
+ for await (const c of req) {
85
+ size += c.length;
86
+ if (size > MAX_FORM)
87
+ throw new Error('too large');
88
+ chunks.push(c);
89
+ }
90
+ return Buffer.concat(chunks).toString('utf8');
91
+ }
92
+ /** https, or http on a loopback address (local tools such as Claude Code). No fragments. */
93
+ export function validRedirect(u) {
94
+ try {
95
+ const url = new URL(u);
96
+ if (url.hash)
97
+ return false;
98
+ if (url.protocol === 'https:')
99
+ return true;
100
+ return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ /** Loopback redirects may use any port. */
107
+ const sameRedirect = (registered, given) => {
108
+ if (registered === given)
109
+ return true;
110
+ try {
111
+ const a = new URL(registered), b = new URL(given);
112
+ return a.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(a.hostname) && a.hostname === b.hostname && a.protocol === b.protocol && a.pathname === b.pathname && a.search === b.search;
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ };
118
+ export function createOAuth(env, fetchImpl = fetch) {
119
+ const secret = env.MCP_OAUTH_SECRET ?? '';
120
+ const publicUrl = (env.MCP_PUBLIC_URL ?? '').replace(/\/+$/, '');
121
+ const consentOrigin = (env.MCP_CONSENT_ORIGIN ?? 'https://aisocialautomate.com').replace(/\/+$/, '');
122
+ const apiBase = (env.SOCIAL_AUTOMATE_API_URL || 'https://aisocialautomate.com/api/v1').replace(/\/+$/, '');
123
+ const enabled = secret.length >= 32 && /^https:\/\//.test(publicUrl);
124
+ const metadataUrl = `${publicUrl}/.well-known/oauth-protected-resource`;
125
+ if (!enabled)
126
+ return { enabled: false, metadataUrl, handle: async () => false, resolveToken: () => null };
127
+ const sealer = new Sealer(secret);
128
+ const pending = new Map();
129
+ const usedCodes = new Map();
130
+ const prune = () => {
131
+ const t = Date.now();
132
+ for (const [k, v] of pending)
133
+ if (v.exp < t)
134
+ pending.delete(k);
135
+ for (const [k, v] of usedCodes)
136
+ if (v < t)
137
+ usedCodes.delete(k);
138
+ };
139
+ const protectedResource = { resource: `${publicUrl}/mcp`, authorization_servers: [publicUrl], bearer_methods_supported: ['header'], scopes_supported: ['mcp'], resource_name: 'AI Social Automate' };
140
+ const authServer = {
141
+ issuer: publicUrl, authorization_endpoint: `${publicUrl}/oauth/authorize`, token_endpoint: `${publicUrl}/oauth/token`, registration_endpoint: `${publicUrl}/oauth/register`,
142
+ response_types_supported: ['code'], grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
143
+ token_endpoint_auth_methods_supported: ['none'], scopes_supported: ['mcp'],
144
+ };
145
+ const cors = (req) => req.headers.origin === consentOrigin
146
+ ? { 'access-control-allow-origin': consentOrigin, 'access-control-allow-headers': 'content-type', 'access-control-allow-methods': 'GET, POST, OPTIONS', vary: 'Origin' }
147
+ : {};
148
+ const client = (cid) => { const c = sealer.verify(cid); return c && Array.isArray(c.r) ? c : null; };
149
+ const issue = (key, cid) => {
150
+ const access = 'mcp_at_' + sealer.seal({ k: key, t: 'a', exp: nowS() + ACCESS_TTL_S });
151
+ const refresh = 'mcp_rt_' + sealer.seal({ k: key, t: 'r', cid, exp: nowS() + REFRESH_TTL_S });
152
+ return { access_token: access, token_type: 'Bearer', expires_in: ACCESS_TTL_S, refresh_token: refresh, scope: 'mcp' };
153
+ };
154
+ async function keyIsValid(key) {
155
+ try {
156
+ const r = await fetchImpl(`${apiBase}/api-keys/self`, { headers: { Authorization: `ApiKey ${key}`, Accept: 'application/json' }, signal: AbortSignal.timeout(10_000) });
157
+ return r.ok;
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ }
163
+ return {
164
+ enabled, metadataUrl,
165
+ resolveToken(token) {
166
+ if (!token.startsWith('mcp_at_'))
167
+ return null;
168
+ const t = sealer.open(token.slice(7));
169
+ return t && t.t === 'a' && t.exp > nowS() && typeof t.k === 'string' ? t.k : null;
170
+ },
171
+ async handle(req, res, path, ip) {
172
+ void ip;
173
+ if (path === '/.well-known/oauth-protected-resource' || path === '/.well-known/oauth-protected-resource/mcp') {
174
+ json(res, 200, protectedResource, { 'cache-control': 'public, max-age=300' });
175
+ return true;
176
+ }
177
+ if (path === '/.well-known/oauth-authorization-server' || path === '/.well-known/openid-configuration') {
178
+ json(res, 200, authServer, { 'cache-control': 'public, max-age=300' });
179
+ return true;
180
+ }
181
+ if (!path.startsWith('/oauth/'))
182
+ return false;
183
+ prune();
184
+ const url = new URL(req.url ?? '', publicUrl);
185
+ if (req.method === 'OPTIONS') {
186
+ res.writeHead(204, cors(req)).end();
187
+ return true;
188
+ }
189
+ if (path === '/oauth/register' && req.method === 'POST') {
190
+ let body;
191
+ try {
192
+ body = JSON.parse(await readBody(req));
193
+ }
194
+ catch {
195
+ oauthErr(res, 400, 'invalid_client_metadata', 'Send JSON.');
196
+ return true;
197
+ }
198
+ const uris = Array.isArray(body?.redirect_uris) ? body.redirect_uris.map(String) : [];
199
+ if (!uris.length || uris.length > 10 || !uris.every(validRedirect)) {
200
+ oauthErr(res, 400, 'invalid_redirect_uri', 'redirect_uris must be 1 to 10 https links (or http on localhost).');
201
+ return true;
202
+ }
203
+ const name = String(body?.client_name ?? 'MCP client').replace(/[\u0000-\u001f<>]/g, '').slice(0, 80) || 'MCP client';
204
+ const cid = sealer.sign({ n: name, r: uris, iat: nowS() });
205
+ json(res, 201, { client_id: cid, client_name: name, redirect_uris: uris, grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', client_id_issued_at: nowS() });
206
+ return true;
207
+ }
208
+ if (path === '/oauth/authorize' && req.method === 'GET') {
209
+ const q = url.searchParams;
210
+ const c = client(q.get('client_id') ?? '');
211
+ const ru = q.get('redirect_uri') ?? '';
212
+ // Without a known client and an exact redirect we cannot safely redirect anywhere, so show the error here.
213
+ if (!c) {
214
+ oauthErr(res, 400, 'invalid_client', 'Unknown client_id.');
215
+ return true;
216
+ }
217
+ const reg = c.r.find(r => sameRedirect(r, ru));
218
+ if (!reg) {
219
+ oauthErr(res, 400, 'invalid_request', 'redirect_uri does not match the registered one.');
220
+ return true;
221
+ }
222
+ const back = (error, desc) => { const u = new URL(ru); u.searchParams.set('error', error); u.searchParams.set('error_description', desc); if (q.get('state'))
223
+ u.searchParams.set('state', q.get('state')); res.writeHead(302, { location: u.toString() }).end(); };
224
+ if (q.get('response_type') !== 'code')
225
+ return back('unsupported_response_type', 'Only response_type=code is supported.'), true;
226
+ const ch = q.get('code_challenge') ?? '';
227
+ if (q.get('code_challenge_method') !== 'S256' || !/^[A-Za-z0-9_-]{43,128}$/.test(ch))
228
+ return back('invalid_request', 'PKCE with code_challenge_method=S256 is required.'), true;
229
+ if (pending.size > 5000)
230
+ return back('temporarily_unavailable', 'Too many sign-ins in progress. Try again shortly.'), true;
231
+ const id = b64(randomBytes(24));
232
+ pending.set(id, { cid: q.get('client_id'), name: c.n, ru, state: q.get('state') ?? '', ch, exp: Date.now() + PENDING_TTL_MS });
233
+ res.writeHead(302, { location: `${consentOrigin}/authorize-assistant?request=${encodeURIComponent(id)}`, 'cache-control': 'no-store' }).end();
234
+ return true;
235
+ }
236
+ // What the consent page shows: who is asking and where they will be sent back.
237
+ if (path === '/oauth/request' && req.method === 'GET') {
238
+ const p = pending.get(url.searchParams.get('id') ?? '');
239
+ if (!p) {
240
+ json(res, 404, { error: 'expired' }, cors(req));
241
+ return true;
242
+ }
243
+ let host = '';
244
+ try {
245
+ host = new URL(p.ru).host;
246
+ }
247
+ catch { /* ignore */ }
248
+ json(res, 200, { client_name: p.name, redirect_host: host }, cors(req));
249
+ return true;
250
+ }
251
+ if (path === '/oauth/complete' && req.method === 'POST') {
252
+ const h = cors(req);
253
+ if (!h['access-control-allow-origin']) {
254
+ json(res, 403, { error: 'forbidden' });
255
+ return true;
256
+ }
257
+ let body;
258
+ try {
259
+ body = JSON.parse(await readBody(req));
260
+ }
261
+ catch {
262
+ json(res, 400, { error: 'invalid_request' }, h);
263
+ return true;
264
+ }
265
+ const p = pending.get(String(body?.request ?? ''));
266
+ if (!p) {
267
+ json(res, 404, { error: 'expired', message: 'This sign-in link expired. Start again from your assistant.' }, h);
268
+ return true;
269
+ }
270
+ pending.delete(String(body.request));
271
+ const u = new URL(p.ru);
272
+ if (p.state)
273
+ u.searchParams.set('state', p.state);
274
+ if (body?.deny) {
275
+ u.searchParams.set('error', 'access_denied');
276
+ json(res, 200, { redirect: u.toString() }, h);
277
+ return true;
278
+ }
279
+ const key = String(body?.key ?? '');
280
+ if (!key.startsWith('sk_') || !(await keyIsValid(key))) {
281
+ json(res, 400, { error: 'invalid_key', message: 'The access key was not accepted.' }, h);
282
+ return true;
283
+ }
284
+ const jti = b64(randomBytes(12));
285
+ u.searchParams.set('code', sealer.seal({ k: key, cid: p.cid, ru: p.ru, ch: p.ch, jti, exp: nowS() + CODE_TTL_S }));
286
+ json(res, 200, { redirect: u.toString() }, h);
287
+ return true;
288
+ }
289
+ if (path === '/oauth/token' && req.method === 'POST') {
290
+ let f;
291
+ try {
292
+ f = new URLSearchParams(await readBody(req));
293
+ }
294
+ catch {
295
+ oauthErr(res, 400, 'invalid_request', 'Body too large.');
296
+ return true;
297
+ }
298
+ const grant = f.get('grant_type');
299
+ if (grant === 'authorization_code') {
300
+ const c = sealer.open(f.get('code') ?? '');
301
+ if (!c || c.exp < nowS() || usedCodes.has(c.jti)) {
302
+ oauthErr(res, 400, 'invalid_grant', 'The code is invalid, expired or already used.');
303
+ return true;
304
+ }
305
+ usedCodes.set(c.jti, Date.now() + CODE_TTL_S * 1000);
306
+ if (f.get('client_id') !== c.cid || !sameRedirect(c.ru, f.get('redirect_uri') ?? '')) {
307
+ oauthErr(res, 400, 'invalid_grant', 'client_id or redirect_uri does not match.');
308
+ return true;
309
+ }
310
+ const ver = f.get('code_verifier') ?? '';
311
+ const calc = createHash('sha256').update(ver).digest('base64url');
312
+ if (!/^[A-Za-z0-9._~-]{43,128}$/.test(ver) || calc !== c.ch) {
313
+ oauthErr(res, 400, 'invalid_grant', 'PKCE verification failed.');
314
+ return true;
315
+ }
316
+ json(res, 200, issue(c.k, c.cid));
317
+ return true;
318
+ }
319
+ if (grant === 'refresh_token') {
320
+ const t = (f.get('refresh_token') ?? '').startsWith('mcp_rt_') ? sealer.open(f.get('refresh_token').slice(7)) : null;
321
+ if (!t || t.t !== 'r' || t.exp < nowS() || (f.get('client_id') && f.get('client_id') !== t.cid)) {
322
+ oauthErr(res, 400, 'invalid_grant', 'The refresh token is invalid or expired. Sign in again.');
323
+ return true;
324
+ }
325
+ if (!(await keyIsValid(t.k))) {
326
+ oauthErr(res, 400, 'invalid_grant', 'Access was revoked. Sign in again.');
327
+ return true;
328
+ }
329
+ json(res, 200, issue(t.k, t.cid));
330
+ return true;
331
+ }
332
+ oauthErr(res, 400, 'unsupported_grant_type', 'Use authorization_code or refresh_token.');
333
+ return true;
334
+ }
335
+ json(res, 404, { error: 'not_found' });
336
+ return true;
337
+ },
338
+ };
339
+ }
@@ -18,6 +18,8 @@ const failure = (e) => {
18
18
  };
19
19
  const SAFE = { readOnlyHint: true, openWorldHint: true };
20
20
  const WRITE = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
21
+ const CHANGE = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };
22
+ const CHANGE_LIVE = { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
21
23
  const LIVE = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
22
24
  const DESTROY = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };
23
25
  const mediaItem = z.object({ type: z.enum(['image', 'video']), object_path: z.string(), url: z.string(), mime_type: z.string() });
@@ -43,11 +45,25 @@ export function registerPublishing(server, svc) {
43
45
  return;
44
46
  const accounts = async () => (await api.request('GET', '/social-accounts')) ?? [];
45
47
  /** Resolve each target to a connected account and build the platform entries the API expects. */
46
- const buildTargets = async (targets) => {
48
+ let wsId;
49
+ /** The browser link that connects an account: the user must sign in to the platform themselves. */
50
+ const connectLink = async (platform, brandId) => {
51
+ wsId ??= (await api.request('GET', '/api-keys/self'))?.workspace_id;
52
+ if (!wsId)
53
+ return '';
54
+ const u = new URL(`${cfg.baseUrl}/connections/${platform}/connect`);
55
+ u.searchParams.set('workspace_id', wsId);
56
+ if (brandId)
57
+ u.searchParams.set('brand_id', brandId);
58
+ return u.toString();
59
+ };
60
+ const buildTargets = async (targets, brandId) => {
47
61
  const list = await accounts();
48
62
  const entries = [];
49
63
  const described = [];
50
64
  const problems = [];
65
+ let needsConnect = false;
66
+ const askConnect = async (platform) => { needsConnect = true; const l = await connectLink(platform, brandId); return l ? ` Give the user this link to connect it, then ask them to tell you when done and retry: ${l}` : ' Use connect_account to get a link.'; };
51
67
  for (const t of targets) {
52
68
  let acct;
53
69
  if (t.social_account_id)
@@ -55,7 +71,7 @@ export function registerPublishing(server, svc) {
55
71
  else
56
72
  acct = list.find(a => a.platform === t.platform && a.status === 'connected');
57
73
  if (!acct) {
58
- problems.push(`No connected ${t.platform} account${t.social_account_id ? ` with id ${t.social_account_id}` : ''}. Use list_connected_accounts.`);
74
+ problems.push(t.social_account_id ? `No ${t.platform} account with id ${t.social_account_id}. Use list_connected_accounts.` : `No ${t.platform} account is connected yet.` + await askConnect(t.platform));
59
75
  continue;
60
76
  }
61
77
  if (acct.platform !== t.platform) {
@@ -63,13 +79,13 @@ export function registerPublishing(server, svc) {
63
79
  continue;
64
80
  }
65
81
  if (acct.status !== 'connected') {
66
- problems.push(`${t.platform} account "${acct.display_name}" is ${acct.status}; reconnect it in the dashboard.`);
82
+ problems.push(`${t.platform} account "${acct.display_name}" is ${acct.status}; it needs to be reconnected.` + await askConnect(t.platform));
67
83
  continue;
68
84
  }
69
85
  entries.push({ platform: t.platform, social_account_id: acct.id, ...(t.format ? { format: t.format } : {}), ...(t.options ?? {}) });
70
86
  described.push(`${t.platform}: ${acct.display_name}${t.format ? ` (${t.format})` : ''}`);
71
87
  }
72
- return { entries, described, problems };
88
+ return { entries, described, problems, needsConnect };
73
89
  };
74
90
  const contentOf = (a) => {
75
91
  const c = {};
@@ -270,25 +286,16 @@ export function registerPublishing(server, svc) {
270
286
  }
271
287
  });
272
288
  // ── Create / change ────────────────────────────────────────────────────────
273
- server.registerTool('create_post', {
274
- title: 'Create post', description: 'Creates a post for one or more connected accounts. mode "draft" saves a draft (free, nothing goes live). mode "schedule" or "now" puts it live and ALWAYS needs the user\'s confirmation: the first call returns a preview, and only after the user agrees you repeat the call with confirm: true. Instagram and Facebook posts need at least one image or video (use upload_media first).',
275
- inputSchema: {
276
- mode: z.enum(['draft', 'schedule', 'now']), targets: z.array(target).min(1).max(10),
277
- caption: z.string().optional(), hashtags: z.array(z.string()).optional(), mention_accounts: z.array(z.string()).optional(), first_comment: z.string().optional(), location: z.record(z.any()).optional(),
278
- media: z.array(mediaItem).optional(), scheduled_at: z.string().optional().describe('ISO 8601, at least 5 minutes ahead. Required for mode "schedule". Use with timezone, or include an offset/Z'), timezone: TZ,
279
- brand_id: z.string().optional().describe('The brand this post belongs to (from list_brands). Omit to use the brand of the targeted accounts. Every target must belong to the same brand'),
280
- confirm: z.boolean().optional().describe('Set true only after the user approved the preview'), dry_run: z.boolean().optional().describe('Only validate and show the preview'),
281
- }, annotations: LIVE,
282
- }, async (a) => {
289
+ const createPost = async (a) => {
283
290
  try {
284
- const { entries, described, problems } = await buildTargets(a.targets);
291
+ const { entries, described, problems, needsConnect } = await buildTargets(a.targets, a.brand_id);
285
292
  if (problems.length)
286
- return failure(new ApiError(400, 'BAD_TARGETS', problems.join(' ')));
293
+ return failure(new ApiError(400, needsConnect ? 'NEEDS_CONNECTION' : 'BAD_TARGETS', problems.join(' ')));
287
294
  const tt = tiktokChecks(entries);
288
295
  if (tt.problems.length)
289
296
  return failure(new ApiError(400, 'BAD_TIKTOK_SETTINGS', tt.problems.join(' ')));
290
297
  const warnings = [...tt.warnings];
291
- const needsMedia = a.targets.some(t => t.platform === 'instagram' || t.platform === 'facebook');
298
+ const needsMedia = a.targets.some((t) => t.platform === 'instagram' || t.platform === 'facebook');
292
299
  if (needsMedia && !a.media?.length)
293
300
  warnings.push('Instagram and Facebook posts need at least one image or video; add one with upload_media.');
294
301
  let when = null;
@@ -318,7 +325,7 @@ export function registerPublishing(server, svc) {
318
325
  body.post_now = true;
319
326
  else
320
327
  body.scheduled_at = when.toISOString();
321
- const preview = { accounts: described, caption: a.caption ?? '', hashtags: a.hashtags ?? [], first_comment: a.first_comment, media: (a.media ?? []).map(m => `${m.type}: ${m.object_path}`), ...(tt.settings.length ? { tiktok: tt.settings } : {}), publishes: a.mode === 'now' ? 'IMMEDIATELY' : `${whenShown} (= ${when.toISOString()} UTC)` };
328
+ const preview = { accounts: described, caption: a.caption ?? '', hashtags: a.hashtags ?? [], first_comment: a.first_comment, media: (a.media ?? []).map((m) => `${m.type}: ${m.object_path}`), ...(tt.settings.length ? { tiktok: tt.settings } : {}), publishes: a.mode === 'now' ? 'IMMEDIATELY' : `${whenShown} (= ${when.toISOString()} UTC)` };
322
329
  if (a.mode === 'now')
323
330
  warnings.push('This publishes immediately and is public as soon as it goes out.');
324
331
  if (described.length > 3)
@@ -333,7 +340,28 @@ export function registerPublishing(server, svc) {
333
340
  catch (e) {
334
341
  return failure(e);
335
342
  }
336
- });
343
+ };
344
+ const common = {
345
+ targets: z.array(target).min(1).max(10),
346
+ caption: z.string().optional(), hashtags: z.array(z.string()).optional(), mention_accounts: z.array(z.string()).optional(), first_comment: z.string().optional(), location: z.record(z.any()).optional(),
347
+ media: z.array(mediaItem).optional(),
348
+ brand_id: z.string().optional().describe('The brand this post belongs to (from list_brands). Omit to use the brand of the targeted accounts. Every target must belong to the same brand'),
349
+ };
350
+ const needMedia = 'Instagram and Facebook posts need at least one image or video (use upload_media first). If a platform has no connected account, the reply is NEEDS_CONNECTION with a link: show it to the user, wait until they say they connected, then repeat the call.';
351
+ const confirmDoc = z.boolean().optional().describe('Set true only after the user approved the preview');
352
+ const dryDoc = z.boolean().optional().describe('Only validate and show the preview');
353
+ server.registerTool('create_draft', {
354
+ title: 'Create draft post', description: 'Saves a draft post for one or more connected accounts. Free, and nothing goes live. ' + needMedia,
355
+ inputSchema: { ...common, scheduled_at: z.string().optional().describe('Optional planned time, ISO 8601. Use with timezone, or include an offset/Z'), timezone: TZ, dry_run: dryDoc }, annotations: WRITE,
356
+ }, (a) => createPost({ ...a, mode: 'draft' }));
357
+ server.registerTool('schedule_post', {
358
+ title: 'Schedule post', description: 'Schedules a post to publish later on one or more connected accounts. ALWAYS needs the user\'s confirmation: the first call returns a preview, and only after the user agrees you repeat the call with confirm: true. ' + needMedia,
359
+ inputSchema: { ...common, scheduled_at: z.string().describe('When to publish, ISO 8601, at least 5 minutes ahead. Use with timezone, or include an offset/Z'), timezone: TZ, confirm: confirmDoc, dry_run: dryDoc }, annotations: LIVE,
360
+ }, (a) => createPost({ ...a, mode: 'schedule' }));
361
+ server.registerTool('publish_now', {
362
+ title: 'Publish post now', description: 'Publishes a post immediately and publicly on one or more connected accounts. ALWAYS needs the user\'s confirmation: the first call returns a preview, and only after the user agrees you repeat the call with confirm: true. ' + needMedia,
363
+ inputSchema: { ...common, confirm: confirmDoc, dry_run: dryDoc }, annotations: LIVE,
364
+ }, (a) => createPost({ ...a, mode: 'now' }));
337
365
  server.registerTool('update_post', {
338
366
  title: 'Update post', description: 'Edits a post; only the fields you send change. Editing a draft is free. Scheduling it (status "scheduled"), publishing it now (post_now) or changing the time of an already scheduled post needs the user\'s confirmation, exactly like create_post.',
339
367
  inputSchema: {
@@ -341,7 +369,7 @@ export function registerPublishing(server, svc) {
341
369
  targets: z.array(target).optional().describe('Replaces all targets'), media: z.array(mediaItem).optional().describe('Replaces all media'),
342
370
  scheduled_at: z.string().optional(), timezone: TZ, status: z.enum(['draft', 'scheduled']).optional(), post_now: z.boolean().optional(),
343
371
  confirm: z.boolean().optional(), dry_run: z.boolean().optional(),
344
- }, annotations: LIVE,
372
+ }, annotations: CHANGE_LIVE,
345
373
  }, async (a) => {
346
374
  try {
347
375
  const cur = await api.request('GET', `/scheduled-posts/${a.post_id}`);
@@ -353,7 +381,7 @@ export function registerPublishing(server, svc) {
353
381
  if (a.targets) {
354
382
  const t = await buildTargets(a.targets);
355
383
  if (t.problems.length)
356
- return failure(new ApiError(400, 'BAD_TARGETS', t.problems.join(' ')));
384
+ return failure(new ApiError(400, t.needsConnect ? 'NEEDS_CONNECTION' : 'BAD_TARGETS', t.problems.join(' ')));
357
385
  const tt = tiktokChecks(t.entries);
358
386
  if (tt.problems.length)
359
387
  return failure(new ApiError(400, 'BAD_TIKTOK_SETTINGS', tt.problems.join(' ')));
@@ -396,7 +424,7 @@ export function registerPublishing(server, svc) {
396
424
  });
397
425
  server.registerTool('cancel_post', {
398
426
  title: 'Cancel post', description: 'Stops a draft, scheduled or failed post from publishing (reversible with restore_post). Does not touch posts that are already published.',
399
- inputSchema: { post_id: z.string() }, annotations: WRITE,
427
+ inputSchema: { post_id: z.string() }, annotations: CHANGE,
400
428
  }, async ({ post_id }) => { try {
401
429
  return json(await api.request('POST', `/scheduled-posts/${post_id}/cancel`));
402
430
  }
@@ -405,7 +433,7 @@ export function registerPublishing(server, svc) {
405
433
  } });
406
434
  server.registerTool('restore_post', {
407
435
  title: 'Restore cancelled post', description: 'Moves a cancelled post back to scheduled (a past time is moved to 5 minutes from now). This can make it publish soon, so it needs the user\'s confirmation.',
408
- inputSchema: { post_id: z.string(), confirm: z.boolean().optional() }, annotations: LIVE,
436
+ inputSchema: { post_id: z.string(), confirm: z.boolean().optional() }, annotations: CHANGE_LIVE,
409
437
  }, async ({ post_id, confirm }) => {
410
438
  try {
411
439
  const cur = await api.request('GET', `/scheduled-posts/${post_id}`);
package/dist/server.js CHANGED
@@ -74,7 +74,7 @@ export function createServer(svc) {
74
74
  'AI Social Automate: find leads and research content on Instagram, Facebook, LinkedIn, TikTok and X.',
75
75
  'Start with search_endpoints (find the right endpoint) and describe_endpoint (exact parameters), then scrape for one call, start_bulk_scrape for many items, or start_lead_job to gather a lead list in the background.',
76
76
  'Everything that costs credits supports dry_run to show the estimate first. Large or risky actions come back as NEEDS_CONFIRMATION: tell the user the estimate and warnings, and only repeat the call with confirm: true after they say yes. Never set confirm on your own.',
77
- 'Publishing: create_post saves drafts freely, but scheduling or posting always returns a preview that the user must approve (confirm: true). It never messages anyone or follows accounts. Upload media first with upload_media.',
77
+ 'Publishing: create_draft saves drafts freely, but schedule_post and publish_now always returns a preview that the user must approve (confirm: true). It never messages anyone or follows accounts. Upload media first with upload_media.',
78
78
  UNTRUSTED,
79
79
  ].join('\n'),
80
80
  });
package/dist/toolsets.js CHANGED
@@ -1,10 +1,11 @@
1
1
  /** Which group each tool belongs to. Used to switch groups on or off (SOCIAL_AUTOMATE_TOOLSETS) and to build the docs. */
2
2
  export const TOOLSETS = ['discover', 'research', 'leads', 'publishing'];
3
3
  export const TOOL_TOOLSET = {
4
- whoami: 'discover', get_credit_balance: 'discover', get_pricing: 'discover', list_connected_accounts: 'discover', connect_account: 'discover', list_brands: 'discover', list_platforms: 'discover', search_endpoints: 'discover', describe_endpoint: 'discover', usage_status: 'discover',
4
+ whoami: 'discover', get_credit_balance: 'discover', get_pricing: 'discover', list_connected_accounts: 'discover', connect_account: 'discover', list_brands: 'discover', usage_status: 'discover',
5
+ list_platforms: 'research', search_endpoints: 'research', describe_endpoint: 'research',
5
6
  scrape: 'research', start_bulk_scrape: 'research', get_run: 'research', list_runs: 'research', cancel_run: 'research',
6
7
  start_lead_job: 'leads', get_lead_job: 'leads', list_lead_jobs: 'leads', cancel_lead_job: 'leads', search_leads: 'leads', export_leads: 'leads', list_lead_lists: 'leads', create_lead_list: 'leads', add_leads_to_list: 'leads',
7
- list_posts: 'publishing', get_post: 'publishing', get_post_analytics: 'publishing', list_templates: 'publishing', get_tiktok_creator_info: 'publishing', search_instagram_music: 'publishing', upload_media: 'publishing', create_post: 'publishing', update_post: 'publishing', cancel_post: 'publishing', restore_post: 'publishing', duplicate_post: 'publishing', delete_post: 'publishing',
8
+ list_posts: 'publishing', get_post: 'publishing', get_post_analytics: 'publishing', list_templates: 'publishing', get_tiktok_creator_info: 'publishing', search_instagram_music: 'publishing', upload_media: 'publishing', create_draft: 'publishing', schedule_post: 'publishing', publish_now: 'publishing', update_post: 'publishing', cancel_post: 'publishing', restore_post: 'publishing', duplicate_post: 'publishing', delete_post: 'publishing',
8
9
  };
9
10
  /** Descriptions for parameters, applied when a tool is registered (a schema's own .describe() wins). A "tool.param" key overrides the plain name. */
10
11
  export const PARAM_DOCS = {
@@ -46,11 +47,11 @@ export const PARAM_DOCS = {
46
47
  name: 'Name of the list (up to 200 characters).',
47
48
  list_id: 'The lead list id, from list_lead_lists.',
48
49
  lead_ids: 'Lead ids as returned by search_leads (up to 500).',
49
- post_id: 'The post id, from list_posts or create_post.',
50
+ post_id: 'The post id, from list_posts or a create tool.',
50
51
  query: 'Search text, such as a song or artist. Leave empty for trending audio.',
51
52
  type: '"music" or "original_sound".',
52
53
  social_account_id: 'Account id from list_connected_accounts. Omit to use the connected account.',
53
- brand_id: 'A brand id from list_brands. Omit for all brands (lists) or the targeted accounts\' brand (create_post).',
54
+ brand_id: 'A brand id from list_brands. Omit for all brands (lists) or the targeted accounts\' brand (create_draft, schedule_post, publish_now).',
54
55
  file_path: 'A file on this computer (local mode only).',
55
56
  url: 'A public http(s) link to the image or video.',
56
57
  filename: 'Name to store the file under. Its extension decides the type.',
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aisocialautomate/mcp",
3
- "version": "0.1.0",
4
- "description": "MCP server for AI Social Automate: find leads and research content across Instagram, Facebook, LinkedIn, TikTok and X from Claude, Codex or any MCP client.",
3
+ "version": "0.2.0",
4
+ "description": "MCP server for AI Social Automate: draft, schedule and publish posts to Instagram, Facebook, LinkedIn, TikTok and YouTube, and find leads and research content, from Claude, ChatGPT, Codex or any MCP client.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "aisocialautomate-mcp": "dist/stdio.js"