@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
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { basename, extname } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { resolveTime, TimeError } from './time.js';
|
|
5
|
+
import { ApiError } from './api.js';
|
|
6
|
+
import { fetchPublic, GuardError } from './net-guard.js';
|
|
7
|
+
import { slim } from './slim.js';
|
|
8
|
+
const PUB_PLATFORMS = ['instagram', 'facebook', 'linkedin', 'tiktok', 'youtube'];
|
|
9
|
+
const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
|
|
10
|
+
const MIME = {
|
|
11
|
+
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
|
|
12
|
+
mp4: 'video/mp4', mov: 'video/quicktime', m4v: 'video/x-m4v', webm: 'video/webm',
|
|
13
|
+
};
|
|
14
|
+
const json = (payload) => ({ content: [{ type: 'text', text: JSON.stringify(payload, null, 1) }] });
|
|
15
|
+
const failure = (e) => {
|
|
16
|
+
const err = e instanceof ApiError ? { error: e.code, status: e.status, message: e.message } : { error: 'INTERNAL', message: String(e?.message ?? e) };
|
|
17
|
+
return { isError: true, content: [{ type: 'text', text: JSON.stringify(err, null, 1) }] };
|
|
18
|
+
};
|
|
19
|
+
const SAFE = { readOnlyHint: true, openWorldHint: true };
|
|
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 };
|
|
23
|
+
const LIVE = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
|
|
24
|
+
const DESTROY = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };
|
|
25
|
+
const mediaItem = z.object({ type: z.enum(['image', 'video']), object_path: z.string(), url: z.string(), mime_type: z.string() });
|
|
26
|
+
const target = z.object({
|
|
27
|
+
platform: z.enum(PUB_PLATFORMS),
|
|
28
|
+
social_account_id: z.string().optional().describe('From list_connected_accounts. Omit to use the workspace\'s connected account for that platform'),
|
|
29
|
+
format: z.string().optional().describe('e.g. "Reel", "Story", "Carousel", "Post". Platform dependent'),
|
|
30
|
+
options: z.record(z.any()).optional().describe('Platform-specific fields passed through. YouTube: title, description, privacy, tags, category_id, audience. Instagram Reel: music. TikTok: privacy_level (PUBLIC_TO_EVERYONE, MUTUAL_FOLLOW_FRIENDS, FOLLOWER_OF_CREATOR or SELF_ONLY; get_tiktok_creator_info lists what the account allows), disable_comment, disable_duet, disable_stitch, brand_organic_toggle (promotes the creator\'s own brand), brand_content_toggle (paid partnership; cannot be SELF_ONLY), auto_add_music'),
|
|
31
|
+
});
|
|
32
|
+
const TZ = z.string().optional().describe('IANA time zone of scheduled_at, e.g. "Asia/Kolkata". Required when scheduled_at has no offset or Z. Ask the user; never assume.');
|
|
33
|
+
const when_ = (value, tz) => { try {
|
|
34
|
+
return resolveTime(value, tz);
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
if (e instanceof TimeError)
|
|
38
|
+
throw new ApiError(400, 'BAD_TIME', e.message);
|
|
39
|
+
throw e;
|
|
40
|
+
} };
|
|
41
|
+
export function registerPublishing(server, svc) {
|
|
42
|
+
const { cfg, api, usage } = svc;
|
|
43
|
+
const mode = cfg.publishing;
|
|
44
|
+
if (mode === 'off')
|
|
45
|
+
return;
|
|
46
|
+
const accounts = async () => (await api.request('GET', '/social-accounts')) ?? [];
|
|
47
|
+
/** Resolve each target to a connected account and build the platform entries the API expects. */
|
|
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) => {
|
|
61
|
+
const list = await accounts();
|
|
62
|
+
const entries = [];
|
|
63
|
+
const described = [];
|
|
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.'; };
|
|
67
|
+
for (const t of targets) {
|
|
68
|
+
let acct;
|
|
69
|
+
if (t.social_account_id)
|
|
70
|
+
acct = list.find(a => a.id === t.social_account_id);
|
|
71
|
+
else
|
|
72
|
+
acct = list.find(a => a.platform === t.platform && a.status === 'connected');
|
|
73
|
+
if (!acct) {
|
|
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));
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (acct.platform !== t.platform) {
|
|
78
|
+
problems.push(`Account ${acct.id} is ${acct.platform}, not ${t.platform}.`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (acct.status !== 'connected') {
|
|
82
|
+
problems.push(`${t.platform} account "${acct.display_name}" is ${acct.status}; it needs to be reconnected.` + await askConnect(t.platform));
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
entries.push({ platform: t.platform, social_account_id: acct.id, ...(t.format ? { format: t.format } : {}), ...(t.options ?? {}) });
|
|
86
|
+
described.push(`${t.platform}: ${acct.display_name}${t.format ? ` (${t.format})` : ''}`);
|
|
87
|
+
}
|
|
88
|
+
return { entries, described, problems, needsConnect };
|
|
89
|
+
};
|
|
90
|
+
const contentOf = (a) => {
|
|
91
|
+
const c = {};
|
|
92
|
+
if (a.caption !== undefined)
|
|
93
|
+
c.caption = a.caption;
|
|
94
|
+
if (a.hashtags !== undefined)
|
|
95
|
+
c.hashtags = a.hashtags;
|
|
96
|
+
if (a.mention_accounts !== undefined)
|
|
97
|
+
c.mention_accounts = a.mention_accounts;
|
|
98
|
+
if (a.first_comment !== undefined)
|
|
99
|
+
c.first_comment = a.first_comment;
|
|
100
|
+
if (a.location !== undefined)
|
|
101
|
+
c.location = a.location;
|
|
102
|
+
return c;
|
|
103
|
+
};
|
|
104
|
+
/** TikTok requires the user to choose visibility and disclose commercial content, so show those choices in the preview and refuse what TikTok refuses. */
|
|
105
|
+
const tiktokChecks = (entries) => {
|
|
106
|
+
const warnings = [];
|
|
107
|
+
const problems = [];
|
|
108
|
+
const settings = [];
|
|
109
|
+
for (const e of entries.filter(x => x.platform === 'tiktok')) {
|
|
110
|
+
const privacy = { public: 'PUBLIC_TO_EVERYONE', friends: 'MUTUAL_FOLLOW_FRIENDS', private: 'SELF_ONLY' }[e.privacy_level] ?? e.privacy_level;
|
|
111
|
+
if (e.brand_content_toggle === true && privacy === 'SELF_ONLY')
|
|
112
|
+
problems.push('TikTok does not allow branded content (paid partnership) to be "Only me". Choose another visibility or turn the disclosure off.');
|
|
113
|
+
if (!privacy)
|
|
114
|
+
warnings.push('No TikTok visibility was chosen, so the post would be public. Ask the user who can see it (get_tiktok_creator_info lists what the account allows) and whether it promotes a brand or is a paid partnership.');
|
|
115
|
+
settings.push({
|
|
116
|
+
visibility: privacy ?? 'PUBLIC_TO_EVERYONE (default)',
|
|
117
|
+
comments: e.disable_comment === true ? 'off' : 'on', duet: e.disable_duet === true ? 'off' : 'on', stitch: e.disable_stitch === true ? 'off' : 'on',
|
|
118
|
+
promotes_own_brand: e.brand_organic_toggle === true, paid_partnership: e.brand_content_toggle === true,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return { warnings, problems, settings };
|
|
122
|
+
};
|
|
123
|
+
const postView = (p) => ({
|
|
124
|
+
id: p.id, status: p.status, scheduled_at: p.scheduled_at, brand_id: p.brand_id ?? undefined,
|
|
125
|
+
caption: typeof p.caption === 'string' ? p.caption.slice(0, 200) : undefined,
|
|
126
|
+
hashtags: p.hashtags?.length ? p.hashtags : undefined,
|
|
127
|
+
platforms: (p.platforms ?? []).map((x) => ({ platform: x.platform, social_account_id: x.social_account_id, format: x.format })),
|
|
128
|
+
media_count: p.media?.length ?? 0,
|
|
129
|
+
results: (p.published_results ?? []).map((r) => ({ platform: r.platform, ok: !r.error, url: r.url, error: r.error, first_comment_status: r.first_comment_status })),
|
|
130
|
+
});
|
|
131
|
+
/** The confirmation step for anything that goes live. */
|
|
132
|
+
const liveGate = (preview, warnings, args, what) => {
|
|
133
|
+
if (mode !== 'on')
|
|
134
|
+
return failure(new ApiError(403, 'PUBLISHING_DRAFTS_ONLY', 'This MCP server is set to drafts only (SOCIAL_AUTOMATE_PUBLISHING=drafts). Save a draft and schedule it from the dashboard, or ask the user to change the setting.'));
|
|
135
|
+
if (usage.livePosts + 1 > cfg.maxLivePosts) {
|
|
136
|
+
return json({ started: false, status: 'POST_CAP_EXCEEDED', message: `This session already scheduled or published ${usage.livePosts} posts, the limit is ${cfg.maxLivePosts}. Only the user can raise SOCIAL_AUTOMATE_MAX_POSTS.`, usage: usage.snapshot() });
|
|
137
|
+
}
|
|
138
|
+
if (usage.livePosts + 1 >= cfg.maxLivePosts * 0.8)
|
|
139
|
+
warnings.push(`This is post ${usage.livePosts + 1} of the session's ${cfg.maxLivePosts}-post limit.`);
|
|
140
|
+
if (args.dry_run)
|
|
141
|
+
return json({ dry_run: true, action: what, preview, warnings, would_need_confirmation: true });
|
|
142
|
+
if (!args.confirm) {
|
|
143
|
+
return json({
|
|
144
|
+
started: false, status: 'NEEDS_CONFIRMATION', action: what, preview, warnings,
|
|
145
|
+
message: 'Nothing was posted or scheduled. Show the user this preview (accounts, text, media, time) in plain words and ask whether to go ahead. Only after they say yes, call this tool again with confirm: true.',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return null;
|
|
149
|
+
};
|
|
150
|
+
// ── Read ────────────────────────────────────────────────────────────────────
|
|
151
|
+
server.registerTool('list_posts', {
|
|
152
|
+
title: 'List posts', description: 'Posts in the workspace (every status, up to 100, oldest schedule first). Filter by status.',
|
|
153
|
+
inputSchema: { status: z.enum(['draft', 'scheduled', 'published', 'partial', 'failed', 'cancelled']).optional(), limit: z.number().int().min(1).max(100).optional(), brand_id: z.string().optional() }, annotations: SAFE,
|
|
154
|
+
}, async ({ status, limit, brand_id }) => {
|
|
155
|
+
try {
|
|
156
|
+
let posts = (await api.request('GET', '/scheduled-posts', { query: { brand_id } })) ?? [];
|
|
157
|
+
if (status)
|
|
158
|
+
posts = posts.filter(p => p.status === status);
|
|
159
|
+
return json({ total: posts.length, posts: posts.slice(0, limit ?? 20).map(postView) });
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
return failure(e);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
server.registerTool('get_post', {
|
|
166
|
+
title: 'Get post', description: 'One post with its content, media and the outcome per platform (published_results).',
|
|
167
|
+
inputSchema: { post_id: z.string() }, annotations: SAFE,
|
|
168
|
+
}, async ({ post_id }) => { try {
|
|
169
|
+
const p = await api.request('GET', `/scheduled-posts/${post_id}`);
|
|
170
|
+
return json({ ...postView(p), full: slim(p, { maxString: 300, maxItems: 10 }) });
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
return failure(e);
|
|
174
|
+
} });
|
|
175
|
+
server.registerTool('get_post_analytics', {
|
|
176
|
+
title: 'Post analytics', description: 'Live engagement metrics (reach, likes, comments...) from each platform the post was published to.',
|
|
177
|
+
inputSchema: { post_id: z.string() }, annotations: SAFE,
|
|
178
|
+
}, async ({ post_id }) => { try {
|
|
179
|
+
return json(slim(await api.request('GET', `/scheduled-posts/${post_id}/analytics`), { maxItems: 20 }));
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
return failure(e);
|
|
183
|
+
} });
|
|
184
|
+
server.registerTool('list_templates', {
|
|
185
|
+
title: 'List post templates', description: 'Reusable post templates from the dashboard\'s Posts library.',
|
|
186
|
+
inputSchema: { brand_id: z.string().optional() }, annotations: SAFE,
|
|
187
|
+
}, async ({ brand_id }) => { try {
|
|
188
|
+
return json(slim(await api.request('GET', '/post-templates', { query: { brand_id } }), { maxItems: 30, maxString: 160 }));
|
|
189
|
+
}
|
|
190
|
+
catch (e) {
|
|
191
|
+
return failure(e);
|
|
192
|
+
} });
|
|
193
|
+
server.registerTool('get_tiktok_creator_info', {
|
|
194
|
+
title: 'TikTok creator info', description: 'What TikTok allows a connected TikTok account to post right now: the visibility options it offers, which comments/duets/stitches the creator has turned off, and the maximum video length. Call this before posting to TikTok so the user can choose visibility. If ok is false, TikTok says this account cannot post at the moment; tell the user why.',
|
|
195
|
+
inputSchema: { social_account_id: z.string().optional().describe('TikTok account id from list_connected_accounts. Omit to use the connected TikTok account') }, annotations: SAFE,
|
|
196
|
+
}, async ({ social_account_id }) => {
|
|
197
|
+
try {
|
|
198
|
+
let id = social_account_id;
|
|
199
|
+
if (!id) {
|
|
200
|
+
const acct = (await accounts()).find(a => a.platform === 'tiktok' && a.status === 'connected');
|
|
201
|
+
if (!acct)
|
|
202
|
+
return failure(new ApiError(400, 'BAD_TARGETS', 'No connected tiktok account. Use list_connected_accounts.'));
|
|
203
|
+
id = acct.id;
|
|
204
|
+
}
|
|
205
|
+
return json(slim(await api.request('GET', `/social-accounts/${id}/tiktok/creator-info`), { maxItems: 20, maxString: 200 }));
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
return failure(e);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
server.registerTool('search_instagram_music', {
|
|
212
|
+
title: 'Search Instagram music', description: 'Search Instagram\'s audio library for a Reel soundtrack (or leave the query empty for trending). Use the result as options.music on an Instagram Reel target.',
|
|
213
|
+
inputSchema: { query: z.string().optional(), type: z.enum(['music', 'original_sound']).optional(), social_account_id: z.string().optional() }, annotations: SAFE,
|
|
214
|
+
}, async ({ query, type, social_account_id }) => {
|
|
215
|
+
try {
|
|
216
|
+
return json(slim(await api.request('GET', '/music/instagram', { query: { query, type, social_account_id } }), { maxItems: 15, maxString: 120 }));
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
return failure(e);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
// ── Media ───────────────────────────────────────────────────────────────────
|
|
223
|
+
server.registerTool('upload_media', {
|
|
224
|
+
title: 'Upload media', description: `Uploads an image or video (up to ${MAX_UPLOAD_BYTES / 1024 / 1024} MB) to the workspace's media storage and returns the media item to put in a post. Give either file_path (a file on this computer; local mode only) or url (a public http(s) link).`,
|
|
225
|
+
inputSchema: { file_path: z.string().optional(), url: z.string().url().optional(), filename: z.string().optional() }, annotations: WRITE,
|
|
226
|
+
}, async ({ file_path, url, filename }) => {
|
|
227
|
+
try {
|
|
228
|
+
if (!!file_path === !!url)
|
|
229
|
+
return failure(new ApiError(400, 'BAD_REQUEST', 'Give exactly one of file_path or url.'));
|
|
230
|
+
let bytes;
|
|
231
|
+
let name = filename ?? '';
|
|
232
|
+
if (file_path) {
|
|
233
|
+
if (!cfg.localFiles)
|
|
234
|
+
return failure(new ApiError(400, 'LOCAL_FILES_UNAVAILABLE', 'Reading files from disk only works with the local (stdio) server. Use a public url instead.'));
|
|
235
|
+
const st = await stat(file_path);
|
|
236
|
+
if (st.size > MAX_UPLOAD_BYTES)
|
|
237
|
+
return failure(new ApiError(400, 'FILE_TOO_LARGE', `File is ${Math.round(st.size / 1048576)} MB; the limit here is ${MAX_UPLOAD_BYTES / 1048576} MB.`));
|
|
238
|
+
bytes = await readFile(file_path);
|
|
239
|
+
name = name || basename(file_path);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
const u = new URL(url);
|
|
243
|
+
if (!/^https?:$/.test(u.protocol))
|
|
244
|
+
return failure(new ApiError(400, 'BAD_REQUEST', 'Only http(s) links can be fetched.'));
|
|
245
|
+
let finalPath = u.pathname;
|
|
246
|
+
if (cfg.localFiles) {
|
|
247
|
+
// Local mode runs on the user's own machine, so any link they ask for is theirs to fetch.
|
|
248
|
+
const res = await fetch(u, { signal: AbortSignal.timeout(60_000) });
|
|
249
|
+
if (!res.ok)
|
|
250
|
+
return failure(new ApiError(400, 'FETCH_FAILED', `Could not download that link (HTTP ${res.status}).`));
|
|
251
|
+
const len = Number(res.headers.get('content-length') ?? 0);
|
|
252
|
+
if (len > MAX_UPLOAD_BYTES)
|
|
253
|
+
return failure(new ApiError(400, 'FILE_TOO_LARGE', 'That file is too large for this upload.'));
|
|
254
|
+
bytes = Buffer.from(await res.arrayBuffer());
|
|
255
|
+
if (bytes.length > MAX_UPLOAD_BYTES)
|
|
256
|
+
return failure(new ApiError(400, 'FILE_TOO_LARGE', 'That file is too large for this upload.'));
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
// Hosted mode: refuse private and internal addresses so a link cannot be used to read our network.
|
|
260
|
+
try {
|
|
261
|
+
const got = await fetchPublic(u, { maxBytes: MAX_UPLOAD_BYTES, timeoutMs: 60_000 });
|
|
262
|
+
if (got.status < 200 || got.status > 299)
|
|
263
|
+
return failure(new ApiError(400, 'FETCH_FAILED', `Could not download that link (HTTP ${got.status}).`));
|
|
264
|
+
bytes = got.bytes;
|
|
265
|
+
finalPath = got.finalUrl.pathname;
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
if (e instanceof GuardError)
|
|
269
|
+
return failure(new ApiError(400, e.code, e.message));
|
|
270
|
+
throw e;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
name = name || basename(finalPath) || 'upload';
|
|
274
|
+
}
|
|
275
|
+
const ext = extname(name).slice(1).toLowerCase();
|
|
276
|
+
const mime = MIME[ext];
|
|
277
|
+
if (!mime)
|
|
278
|
+
return failure(new ApiError(400, 'UNSUPPORTED_TYPE', `Unsupported file type ".${ext}". Use ${Object.keys(MIME).join(', ')}.`));
|
|
279
|
+
const form = new FormData();
|
|
280
|
+
form.append('file', new Blob([new Uint8Array(bytes)], { type: mime }), name);
|
|
281
|
+
const r = await api.request('POST', '/scheduled-posts/presign-upload', { form, timeoutMs: 180_000 });
|
|
282
|
+
return json({ media_item: { type: mime.startsWith('video') ? 'video' : 'image', object_path: r.object_path, url: r.public_url, mime_type: mime }, size_kb: Math.round(bytes.length / 1024), next: 'Pass media_item in the media array of create_post.' });
|
|
283
|
+
}
|
|
284
|
+
catch (e) {
|
|
285
|
+
return failure(e);
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
// ── Create / change ────────────────────────────────────────────────────────
|
|
289
|
+
const createPost = async (a) => {
|
|
290
|
+
try {
|
|
291
|
+
const { entries, described, problems, needsConnect } = await buildTargets(a.targets, a.brand_id);
|
|
292
|
+
if (problems.length)
|
|
293
|
+
return failure(new ApiError(400, needsConnect ? 'NEEDS_CONNECTION' : 'BAD_TARGETS', problems.join(' ')));
|
|
294
|
+
const tt = tiktokChecks(entries);
|
|
295
|
+
if (tt.problems.length)
|
|
296
|
+
return failure(new ApiError(400, 'BAD_TIKTOK_SETTINGS', tt.problems.join(' ')));
|
|
297
|
+
const warnings = [...tt.warnings];
|
|
298
|
+
const needsMedia = a.targets.some((t) => t.platform === 'instagram' || t.platform === 'facebook');
|
|
299
|
+
if (needsMedia && !a.media?.length)
|
|
300
|
+
warnings.push('Instagram and Facebook posts need at least one image or video; add one with upload_media.');
|
|
301
|
+
let when = null;
|
|
302
|
+
let whenShown = '';
|
|
303
|
+
if (a.mode === 'schedule' && !a.scheduled_at)
|
|
304
|
+
return failure(new ApiError(400, 'BAD_REQUEST', 'mode "schedule" needs scheduled_at (e.g. 2026-12-01T09:00:00) and the user\'s timezone.'));
|
|
305
|
+
const at = a.scheduled_at ? when_(a.scheduled_at, a.timezone) : null;
|
|
306
|
+
if (a.mode === 'schedule') {
|
|
307
|
+
when = at.date;
|
|
308
|
+
whenShown = at.shown;
|
|
309
|
+
if (when.getTime() < Date.now() + 5 * 60_000)
|
|
310
|
+
return failure(new ApiError(400, 'BAD_REQUEST', 'scheduled_at must be at least 5 minutes from now.'));
|
|
311
|
+
}
|
|
312
|
+
const body = { platforms: entries, content: contentOf(a), media: a.media ?? [] };
|
|
313
|
+
if (a.brand_id)
|
|
314
|
+
body.brand_id = a.brand_id;
|
|
315
|
+
if (a.mode === 'draft') {
|
|
316
|
+
body.status = 'draft';
|
|
317
|
+
if (at)
|
|
318
|
+
body.scheduled_at = at.utc;
|
|
319
|
+
if (a.dry_run)
|
|
320
|
+
return json({ dry_run: true, mode: 'draft', targets: described, warnings });
|
|
321
|
+
const r = await api.request('POST', '/scheduled-posts', { body });
|
|
322
|
+
return json({ created: true, post_id: r.id, status: r.status, targets: described, warnings, note: 'Saved as a draft. Nothing was published.' });
|
|
323
|
+
}
|
|
324
|
+
if (a.mode === 'now')
|
|
325
|
+
body.post_now = true;
|
|
326
|
+
else
|
|
327
|
+
body.scheduled_at = when.toISOString();
|
|
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)` };
|
|
329
|
+
if (a.mode === 'now')
|
|
330
|
+
warnings.push('This publishes immediately and is public as soon as it goes out.');
|
|
331
|
+
if (described.length > 3)
|
|
332
|
+
warnings.push(`This posts to ${described.length} accounts at once.`);
|
|
333
|
+
const held = liveGate(preview, warnings, a, `${a.mode} post to ${described.join(', ')}`);
|
|
334
|
+
if (held)
|
|
335
|
+
return held;
|
|
336
|
+
const r = await api.request('POST', '/scheduled-posts', { body });
|
|
337
|
+
usage.livePosts++;
|
|
338
|
+
return json({ created: true, post_id: r.id, status: r.status, publishes: preview.publishes, targets: described, warnings, usage: usage.snapshot() });
|
|
339
|
+
}
|
|
340
|
+
catch (e) {
|
|
341
|
+
return failure(e);
|
|
342
|
+
}
|
|
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' }));
|
|
365
|
+
server.registerTool('update_post', {
|
|
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.',
|
|
367
|
+
inputSchema: {
|
|
368
|
+
post_id: z.string(), 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(),
|
|
369
|
+
targets: z.array(target).optional().describe('Replaces all targets'), media: z.array(mediaItem).optional().describe('Replaces all media'),
|
|
370
|
+
scheduled_at: z.string().optional(), timezone: TZ, status: z.enum(['draft', 'scheduled']).optional(), post_now: z.boolean().optional(),
|
|
371
|
+
confirm: z.boolean().optional(), dry_run: z.boolean().optional(),
|
|
372
|
+
}, annotations: CHANGE_LIVE,
|
|
373
|
+
}, async (a) => {
|
|
374
|
+
try {
|
|
375
|
+
const cur = await api.request('GET', `/scheduled-posts/${a.post_id}`);
|
|
376
|
+
const body = {};
|
|
377
|
+
const content = contentOf(a);
|
|
378
|
+
if (Object.keys(content).length)
|
|
379
|
+
body.content = content;
|
|
380
|
+
let described = [];
|
|
381
|
+
if (a.targets) {
|
|
382
|
+
const t = await buildTargets(a.targets);
|
|
383
|
+
if (t.problems.length)
|
|
384
|
+
return failure(new ApiError(400, t.needsConnect ? 'NEEDS_CONNECTION' : 'BAD_TARGETS', t.problems.join(' ')));
|
|
385
|
+
const tt = tiktokChecks(t.entries);
|
|
386
|
+
if (tt.problems.length)
|
|
387
|
+
return failure(new ApiError(400, 'BAD_TIKTOK_SETTINGS', tt.problems.join(' ')));
|
|
388
|
+
body.platforms = t.entries;
|
|
389
|
+
described = t.described;
|
|
390
|
+
}
|
|
391
|
+
if (a.media)
|
|
392
|
+
body.media = a.media;
|
|
393
|
+
let shown = '';
|
|
394
|
+
if (a.scheduled_at) {
|
|
395
|
+
const r = when_(a.scheduled_at, a.timezone);
|
|
396
|
+
body.scheduled_at = r.utc;
|
|
397
|
+
shown = `${r.shown} (= ${r.utc} UTC)`;
|
|
398
|
+
}
|
|
399
|
+
if (a.status)
|
|
400
|
+
body.status = a.status;
|
|
401
|
+
if (a.post_now)
|
|
402
|
+
body.post_now = true;
|
|
403
|
+
const goesLive = !!a.post_now || a.status === 'scheduled' || (cur.status === 'scheduled' && !!a.scheduled_at);
|
|
404
|
+
if (goesLive) {
|
|
405
|
+
const warnings = [];
|
|
406
|
+
if (a.post_now)
|
|
407
|
+
warnings.push('This publishes immediately and is public as soon as it goes out.');
|
|
408
|
+
const preview = { post_id: a.post_id, current_status: cur.status, caption: a.caption ?? cur.caption, accounts: described.length ? described : (cur.platforms ?? []).map((x) => x.platform), publishes: a.post_now ? 'IMMEDIATELY' : (shown || cur.scheduled_at) };
|
|
409
|
+
const held = liveGate(preview, warnings, a, `update ${a.post_id}`);
|
|
410
|
+
if (held)
|
|
411
|
+
return held;
|
|
412
|
+
const r = await api.request('PATCH', `/scheduled-posts/${a.post_id}`, { body });
|
|
413
|
+
usage.livePosts++;
|
|
414
|
+
return json({ updated: true, post_id: r.id, status: r.status, usage: usage.snapshot() });
|
|
415
|
+
}
|
|
416
|
+
if (a.dry_run)
|
|
417
|
+
return json({ dry_run: true, would_change: Object.keys(body) });
|
|
418
|
+
const r = await api.request('PATCH', `/scheduled-posts/${a.post_id}`, { body });
|
|
419
|
+
return json({ updated: true, post_id: r.id, status: r.status });
|
|
420
|
+
}
|
|
421
|
+
catch (e) {
|
|
422
|
+
return failure(e);
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
server.registerTool('cancel_post', {
|
|
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.',
|
|
427
|
+
inputSchema: { post_id: z.string() }, annotations: CHANGE,
|
|
428
|
+
}, async ({ post_id }) => { try {
|
|
429
|
+
return json(await api.request('POST', `/scheduled-posts/${post_id}/cancel`));
|
|
430
|
+
}
|
|
431
|
+
catch (e) {
|
|
432
|
+
return failure(e);
|
|
433
|
+
} });
|
|
434
|
+
server.registerTool('restore_post', {
|
|
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.',
|
|
436
|
+
inputSchema: { post_id: z.string(), confirm: z.boolean().optional() }, annotations: CHANGE_LIVE,
|
|
437
|
+
}, async ({ post_id, confirm }) => {
|
|
438
|
+
try {
|
|
439
|
+
const cur = await api.request('GET', `/scheduled-posts/${post_id}`);
|
|
440
|
+
if (cur.status !== 'cancelled')
|
|
441
|
+
return failure(new ApiError(404, 'NOT_CANCELLED', `The post is ${cur.status}, not cancelled.`));
|
|
442
|
+
const held = liveGate({ post_id, caption: (cur.caption ?? '').slice(0, 200), accounts: (cur.platforms ?? []).map((x) => x.platform), originally_for: cur.scheduled_at }, ['Restoring schedules it again; if its time has passed it publishes about 5 minutes from now.'], { confirm }, `restore ${post_id}`);
|
|
443
|
+
if (held)
|
|
444
|
+
return held;
|
|
445
|
+
const r = await api.request('POST', `/scheduled-posts/${post_id}/restore`);
|
|
446
|
+
usage.livePosts++;
|
|
447
|
+
return json(r);
|
|
448
|
+
}
|
|
449
|
+
catch (e) {
|
|
450
|
+
return failure(e);
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
server.registerTool('duplicate_post', {
|
|
454
|
+
title: 'Duplicate post', description: 'Copies a post (for example a published one) into a new draft with the same content, media and accounts. Free; nothing goes live.',
|
|
455
|
+
inputSchema: { post_id: z.string() }, annotations: WRITE,
|
|
456
|
+
}, async ({ post_id }) => { try {
|
|
457
|
+
const r = await api.request('POST', `/scheduled-posts/${post_id}/duplicate`);
|
|
458
|
+
return json({ created: true, ...postView(r) });
|
|
459
|
+
}
|
|
460
|
+
catch (e) {
|
|
461
|
+
return failure(e);
|
|
462
|
+
} });
|
|
463
|
+
server.registerTool('delete_post', {
|
|
464
|
+
title: 'Delete post permanently', description: 'Permanently removes a draft, cancelled or failed post. This cannot be undone, so it needs the user\'s confirmation. Published posts stay on the platform; this only removes the record.',
|
|
465
|
+
inputSchema: { post_id: z.string(), confirm: z.boolean().optional() }, annotations: DESTROY,
|
|
466
|
+
}, async ({ post_id, confirm }) => {
|
|
467
|
+
try {
|
|
468
|
+
const cur = await api.request('GET', `/scheduled-posts/${post_id}`);
|
|
469
|
+
if (!confirm)
|
|
470
|
+
return json({ deleted: false, status: 'NEEDS_CONFIRMATION', post: postView(cur), message: 'Not deleted. This removes the post permanently. Tell the user which post it is and ask; only after they say yes, call again with confirm: true.' });
|
|
471
|
+
if (cur.status !== 'cancelled')
|
|
472
|
+
await api.request('DELETE', `/scheduled-posts/${post_id}`);
|
|
473
|
+
return json(await api.request('DELETE', `/scheduled-posts/${post_id}`));
|
|
474
|
+
}
|
|
475
|
+
catch (e) {
|
|
476
|
+
return failure(e);
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
}
|