@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +1185 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +12 -1
|
@@ -0,0 +1,2402 @@
|
|
|
1
|
+
/* mailchimp connector module (MIT License). Built from src/vendors/mailchimp; do not edit. */
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/core/errors.ts
|
|
5
|
+
var ToolFailure = class extends Error {
|
|
6
|
+
details;
|
|
7
|
+
constructor(message, details = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "ToolFailure";
|
|
10
|
+
this.details = details;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
var OutcomeUnknown = class extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "OutcomeUnknown";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/core/accounts.ts
|
|
21
|
+
function allowedAccounts(accounts, key) {
|
|
22
|
+
if (accounts === null) return null;
|
|
23
|
+
const list = accounts?.[key];
|
|
24
|
+
return Array.isArray(list) ? list.map(String) : [];
|
|
25
|
+
}
|
|
26
|
+
function requireAccounts(accounts, key, ids, label = "account") {
|
|
27
|
+
const allowed = allowedAccounts(accounts, key);
|
|
28
|
+
if (allowed === null) return;
|
|
29
|
+
const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
|
|
30
|
+
const refused = requested.filter((id) => !allowed.includes(id));
|
|
31
|
+
if (!refused.length) return;
|
|
32
|
+
throw new ToolFailure(
|
|
33
|
+
`The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/core/text.ts
|
|
38
|
+
var encoder = new TextEncoder();
|
|
39
|
+
var decoder = new TextDecoder();
|
|
40
|
+
function utf8Bytes(text) {
|
|
41
|
+
return encoder.encode(text);
|
|
42
|
+
}
|
|
43
|
+
function utf8Length(text) {
|
|
44
|
+
return encoder.encode(text).length;
|
|
45
|
+
}
|
|
46
|
+
function utf8Decode(bytes) {
|
|
47
|
+
return decoder.decode(bytes);
|
|
48
|
+
}
|
|
49
|
+
function base64Encode(bytes) {
|
|
50
|
+
let binary = "";
|
|
51
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
52
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
53
|
+
}
|
|
54
|
+
return btoa(binary);
|
|
55
|
+
}
|
|
56
|
+
function base64UrlEncode(bytes) {
|
|
57
|
+
return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
58
|
+
}
|
|
59
|
+
function base64UrlDecode(text) {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
61
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
62
|
+
const binary = atob(padded);
|
|
63
|
+
const bytes = new Uint8Array(binary.length);
|
|
64
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
65
|
+
return bytes;
|
|
66
|
+
}
|
|
67
|
+
function truncate(text, max) {
|
|
68
|
+
if (text.length <= max) return text;
|
|
69
|
+
const points = Array.from(text);
|
|
70
|
+
if (points.length <= max) return text;
|
|
71
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
72
|
+
}
|
|
73
|
+
function cleanVendorText(text, max = 300) {
|
|
74
|
+
if (typeof text !== "string") return void 0;
|
|
75
|
+
if (/^\s*</.test(text)) return void 0;
|
|
76
|
+
const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
77
|
+
return line ? truncate(line, max) : void 0;
|
|
78
|
+
}
|
|
79
|
+
function formatNumber(value) {
|
|
80
|
+
return value.toLocaleString("en-US");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/core/output.ts
|
|
84
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
85
|
+
function jsonSize(value) {
|
|
86
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
87
|
+
}
|
|
88
|
+
function cutStrings(value, max) {
|
|
89
|
+
if (typeof value === "string") return truncate(value, max);
|
|
90
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
91
|
+
if (typeof value === "object" && value !== null) {
|
|
92
|
+
const out = {};
|
|
93
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
99
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
100
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
101
|
+
const cut = cutStrings(value, max);
|
|
102
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
103
|
+
}
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
107
|
+
const build = (count) => {
|
|
108
|
+
const cut = count < input.items.length;
|
|
109
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
110
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
111
|
+
if (next) result2["nextCursor"] = next;
|
|
112
|
+
if (cut) result2["truncated"] = true;
|
|
113
|
+
return result2;
|
|
114
|
+
};
|
|
115
|
+
const all = build(input.items.length);
|
|
116
|
+
if (jsonSize(all) <= limit) return all;
|
|
117
|
+
let low = 1;
|
|
118
|
+
let high = input.items.length - 1;
|
|
119
|
+
while (low < high) {
|
|
120
|
+
const middle = Math.ceil((low + high) / 2);
|
|
121
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
122
|
+
else high = middle - 1;
|
|
123
|
+
}
|
|
124
|
+
const best = build(low);
|
|
125
|
+
if (jsonSize(best) <= limit) return best;
|
|
126
|
+
const shrunk = shrinkToFit(best, limit);
|
|
127
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
128
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
129
|
+
}
|
|
130
|
+
function encodeCursor(tool, state) {
|
|
131
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
132
|
+
}
|
|
133
|
+
function decodeCursor(tool, cursor) {
|
|
134
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
135
|
+
try {
|
|
136
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
137
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
138
|
+
return state;
|
|
139
|
+
}
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
throw new ToolFailure(
|
|
143
|
+
"The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/core/api-tools.ts
|
|
148
|
+
var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
|
|
149
|
+
var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
|
|
150
|
+
var NOTE_ROOM = 400;
|
|
151
|
+
var MAX_CUT_POINTS = 4e4;
|
|
152
|
+
function isQueryValue(value) {
|
|
153
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
154
|
+
}
|
|
155
|
+
function nothingSent(sentence) {
|
|
156
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
157
|
+
}
|
|
158
|
+
function fitReply(reply) {
|
|
159
|
+
if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
|
|
160
|
+
const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
|
|
161
|
+
if (shrunk) {
|
|
162
|
+
return {
|
|
163
|
+
...shrunk.value,
|
|
164
|
+
truncated: true,
|
|
165
|
+
note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
169
|
+
const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
|
|
170
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
171
|
+
const cut = (count) => ({
|
|
172
|
+
status: reply["status"],
|
|
173
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
174
|
+
truncated: true,
|
|
175
|
+
note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
|
|
176
|
+
text: points.slice(0, count).join("")
|
|
177
|
+
});
|
|
178
|
+
let low = 0;
|
|
179
|
+
let high = points.length;
|
|
180
|
+
while (low < high) {
|
|
181
|
+
const middle = Math.ceil((low + high) / 2);
|
|
182
|
+
if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
|
|
183
|
+
else high = middle - 1;
|
|
184
|
+
}
|
|
185
|
+
return cut(low);
|
|
186
|
+
}
|
|
187
|
+
function shapeReply(response, headerNames) {
|
|
188
|
+
const reply = { status: response.status };
|
|
189
|
+
const headers = {};
|
|
190
|
+
for (const name2 of headerNames) {
|
|
191
|
+
const value = response.headers.get(name2);
|
|
192
|
+
if (value) headers[name2] = truncate(value, 2e3);
|
|
193
|
+
}
|
|
194
|
+
if (Object.keys(headers).length) reply["headers"] = headers;
|
|
195
|
+
const type = response.headers.get("content-type") ?? "";
|
|
196
|
+
if (type && !TEXT_TYPES.test(type)) {
|
|
197
|
+
reply["contentType"] = truncate(type, 200);
|
|
198
|
+
reply["note"] = "The reply is a binary file and is not shown.";
|
|
199
|
+
return reply;
|
|
200
|
+
}
|
|
201
|
+
if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
|
|
202
|
+
return fitReply(reply);
|
|
203
|
+
}
|
|
204
|
+
function checkAccounts(rule, request, h) {
|
|
205
|
+
const label = rule.label ?? "account";
|
|
206
|
+
const allowed = allowedAccounts(h.ctx.accounts, rule.key);
|
|
207
|
+
if (allowed === null) return;
|
|
208
|
+
const namesNone = nothingSent(
|
|
209
|
+
`This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
|
|
210
|
+
);
|
|
211
|
+
if (rule.ids) {
|
|
212
|
+
const ids = rule.ids(request).map(String);
|
|
213
|
+
if (!ids.length) throw namesNone;
|
|
214
|
+
requireAccounts(h.ctx.accounts, rule.key, ids, label);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
|
|
218
|
+
}
|
|
219
|
+
function apiTools(options) {
|
|
220
|
+
const { label, basePath } = options;
|
|
221
|
+
const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
|
|
222
|
+
const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
|
|
223
|
+
const base = basePath?.replace(/\/+$/, "");
|
|
224
|
+
const pathSchema = {
|
|
225
|
+
type: "string",
|
|
226
|
+
minLength: 1,
|
|
227
|
+
maxLength: 2e3,
|
|
228
|
+
pattern: "^(?!.*//)/[^?#]*$",
|
|
229
|
+
description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
|
|
230
|
+
};
|
|
231
|
+
const querySchema = {
|
|
232
|
+
type: "object",
|
|
233
|
+
description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
|
|
234
|
+
};
|
|
235
|
+
const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
|
|
236
|
+
async function run(method, args, h) {
|
|
237
|
+
let origin = h.origins[0];
|
|
238
|
+
if (args.origin !== void 0) {
|
|
239
|
+
let wanted;
|
|
240
|
+
try {
|
|
241
|
+
wanted = new URL(args.origin).origin;
|
|
242
|
+
} catch {
|
|
243
|
+
}
|
|
244
|
+
if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
|
|
245
|
+
origin = wanted;
|
|
246
|
+
}
|
|
247
|
+
const url = new URL(args.path, origin);
|
|
248
|
+
if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
|
|
249
|
+
const path = url.pathname;
|
|
250
|
+
if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
|
|
251
|
+
let segments;
|
|
252
|
+
try {
|
|
253
|
+
segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
|
|
254
|
+
} catch {
|
|
255
|
+
throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
|
|
256
|
+
}
|
|
257
|
+
if (segments[segments.length - 1] === "") segments.pop();
|
|
258
|
+
const query = {};
|
|
259
|
+
const queryLists = {};
|
|
260
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
261
|
+
if (value === void 0 || value === null) continue;
|
|
262
|
+
const list = Array.isArray(value) ? value : [value];
|
|
263
|
+
if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
|
|
264
|
+
query[key] = Array.isArray(value) ? list : value;
|
|
265
|
+
queryLists[key] = list.map(String);
|
|
266
|
+
}
|
|
267
|
+
const request = { method, origin, path, query };
|
|
268
|
+
if (method !== "GET") {
|
|
269
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
|
|
270
|
+
if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
271
|
+
if (args.json !== void 0 && !args.content_type) {
|
|
272
|
+
request.json = args.json;
|
|
273
|
+
} else if (args.json !== void 0 || args.body !== void 0) {
|
|
274
|
+
request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
|
|
275
|
+
request.contentType = args.content_type;
|
|
276
|
+
}
|
|
277
|
+
request.write = true;
|
|
278
|
+
}
|
|
279
|
+
const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
|
|
280
|
+
if (options.accounts) checkAccounts(options.accounts, info, h);
|
|
281
|
+
await options.guard?.(info, h);
|
|
282
|
+
const response = options.send ? await options.send(request, h) : await h.api(request);
|
|
283
|
+
return shapeReply(response, headerNames);
|
|
284
|
+
}
|
|
285
|
+
return [
|
|
286
|
+
{
|
|
287
|
+
name: "api_get",
|
|
288
|
+
kind: "read",
|
|
289
|
+
title: `Call the ${label} API (GET)`,
|
|
290
|
+
description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
|
|
291
|
+
inputSchema: {
|
|
292
|
+
type: "object",
|
|
293
|
+
properties: { path: pathSchema, query: querySchema, ...originSchema },
|
|
294
|
+
required: ["path"],
|
|
295
|
+
additionalProperties: false
|
|
296
|
+
},
|
|
297
|
+
run: (args, h) => run("GET", args, h)
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
name: "api_request",
|
|
301
|
+
kind: "write",
|
|
302
|
+
check: "api_get",
|
|
303
|
+
title: `Send a request to the ${label} API`,
|
|
304
|
+
description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
|
|
305
|
+
inputSchema: {
|
|
306
|
+
type: "object",
|
|
307
|
+
properties: {
|
|
308
|
+
method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
|
|
309
|
+
path: pathSchema,
|
|
310
|
+
query: querySchema,
|
|
311
|
+
json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
|
|
312
|
+
body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
|
|
313
|
+
content_type: {
|
|
314
|
+
type: "string",
|
|
315
|
+
pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
|
|
316
|
+
maxLength: 200,
|
|
317
|
+
description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
|
|
318
|
+
},
|
|
319
|
+
...originSchema
|
|
320
|
+
},
|
|
321
|
+
required: ["method", "path"],
|
|
322
|
+
additionalProperties: false
|
|
323
|
+
},
|
|
324
|
+
run: (args, h) => run(args.method, args, h)
|
|
325
|
+
}
|
|
326
|
+
];
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/core/credentials.ts
|
|
330
|
+
function requiredAlternatives(module2) {
|
|
331
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
332
|
+
}
|
|
333
|
+
function unmetAlternatives(alternatives, has) {
|
|
334
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
335
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
336
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
337
|
+
}
|
|
338
|
+
function andList(items) {
|
|
339
|
+
if (items.length <= 2) return items.join(" and ");
|
|
340
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
341
|
+
}
|
|
342
|
+
function orList(items) {
|
|
343
|
+
if (items.length <= 1) return items.join("");
|
|
344
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// src/core/files.ts
|
|
348
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
349
|
+
var MAX_NAME = 200;
|
|
350
|
+
function fileLimitOf(ctx) {
|
|
351
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
352
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
353
|
+
}
|
|
354
|
+
function fileName(name2) {
|
|
355
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
356
|
+
const points = Array.from(clean);
|
|
357
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
358
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
359
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
360
|
+
}
|
|
361
|
+
function fileType(mimeType) {
|
|
362
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
363
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
364
|
+
}
|
|
365
|
+
function resourceBlock(file) {
|
|
366
|
+
return {
|
|
367
|
+
type: "resource",
|
|
368
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/core/http.ts
|
|
373
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
374
|
+
var USER_AGENT = "agent-connectors";
|
|
375
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
376
|
+
function errorCode(error) {
|
|
377
|
+
const code = error?.code;
|
|
378
|
+
return typeof code === "string" ? code : void 0;
|
|
379
|
+
}
|
|
380
|
+
function describe(error) {
|
|
381
|
+
const name2 = error?.name;
|
|
382
|
+
const code = errorCode(error);
|
|
383
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
384
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
385
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
386
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
387
|
+
}
|
|
388
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
389
|
+
const retryAfter = headers.get("retry-after");
|
|
390
|
+
if (retryAfter) {
|
|
391
|
+
const seconds = Number(retryAfter);
|
|
392
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
393
|
+
const date = Date.parse(retryAfter);
|
|
394
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
395
|
+
}
|
|
396
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
397
|
+
if (reset) {
|
|
398
|
+
const value = Number(reset);
|
|
399
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
400
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return void 0;
|
|
404
|
+
}
|
|
405
|
+
function vendorCode(data) {
|
|
406
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
407
|
+
for (const key of ["error", "code"]) {
|
|
408
|
+
const value = data[key];
|
|
409
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
410
|
+
}
|
|
411
|
+
return void 0;
|
|
412
|
+
}
|
|
413
|
+
function vendorMessage(data) {
|
|
414
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
415
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
416
|
+
const record = data;
|
|
417
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
418
|
+
const value = record[key];
|
|
419
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
420
|
+
const nested = value?.message;
|
|
421
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
422
|
+
}
|
|
423
|
+
if (Array.isArray(record["errors"])) {
|
|
424
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
425
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
426
|
+
}
|
|
427
|
+
return void 0;
|
|
428
|
+
}
|
|
429
|
+
var TooLarge = class extends Error {
|
|
430
|
+
constructor(limit) {
|
|
431
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
432
|
+
this.limit = limit;
|
|
433
|
+
}
|
|
434
|
+
limit;
|
|
435
|
+
};
|
|
436
|
+
async function readCapped(response, maxBytes) {
|
|
437
|
+
const declared = Number(response.headers.get("content-length"));
|
|
438
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
439
|
+
await response.body?.cancel().catch(() => {
|
|
440
|
+
});
|
|
441
|
+
throw new TooLarge(maxBytes);
|
|
442
|
+
}
|
|
443
|
+
if (!response.body) return new Uint8Array(0);
|
|
444
|
+
const reader = response.body.getReader();
|
|
445
|
+
const chunks = [];
|
|
446
|
+
let total = 0;
|
|
447
|
+
for (; ; ) {
|
|
448
|
+
const { done, value } = await reader.read();
|
|
449
|
+
if (done) break;
|
|
450
|
+
total += value.byteLength;
|
|
451
|
+
if (total > maxBytes) {
|
|
452
|
+
await reader.cancel().catch(() => {
|
|
453
|
+
});
|
|
454
|
+
throw new TooLarge(maxBytes);
|
|
455
|
+
}
|
|
456
|
+
chunks.push(value);
|
|
457
|
+
}
|
|
458
|
+
const bytes = new Uint8Array(total);
|
|
459
|
+
let offset = 0;
|
|
460
|
+
for (const chunk of chunks) {
|
|
461
|
+
bytes.set(chunk, offset);
|
|
462
|
+
offset += chunk.byteLength;
|
|
463
|
+
}
|
|
464
|
+
return bytes;
|
|
465
|
+
}
|
|
466
|
+
function parseBody(bytes, contentType) {
|
|
467
|
+
if (bytes.length === 0) return null;
|
|
468
|
+
const text = utf8Decode(bytes);
|
|
469
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
|
|
470
|
+
try {
|
|
471
|
+
return JSON.parse(text);
|
|
472
|
+
} catch {
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return text;
|
|
476
|
+
}
|
|
477
|
+
function createHttp(env) {
|
|
478
|
+
const { label, ctx } = env;
|
|
479
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
480
|
+
const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
|
|
481
|
+
function failureFor(status, headers, data, request) {
|
|
482
|
+
const message = vendorMessage(data);
|
|
483
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
484
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
485
|
+
const code = vendorCode(data);
|
|
486
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
487
|
+
const custom = request.errors?.[status];
|
|
488
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
489
|
+
if (status >= 500) {
|
|
490
|
+
if (request.write) {
|
|
491
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
492
|
+
}
|
|
493
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
494
|
+
}
|
|
495
|
+
if (status === 429) {
|
|
496
|
+
return new ToolFailure(
|
|
497
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
498
|
+
{ status, ...extra }
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
if (status === 401) {
|
|
502
|
+
return new ToolFailure(
|
|
503
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
504
|
+
{ status, ...extra }
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
508
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
509
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
510
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
511
|
+
}
|
|
512
|
+
async function api(request) {
|
|
513
|
+
const method = request.method ?? "GET";
|
|
514
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
515
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
516
|
+
}
|
|
517
|
+
const origin = request.origin ?? env.origins[0];
|
|
518
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
519
|
+
const url = new URL(request.path, origin);
|
|
520
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
521
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
522
|
+
if (value === void 0 || value === null) continue;
|
|
523
|
+
if (Array.isArray(value)) {
|
|
524
|
+
url.searchParams.delete(key);
|
|
525
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
526
|
+
} else {
|
|
527
|
+
url.searchParams.set(key, String(value));
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const headers = {
|
|
531
|
+
accept: "application/json",
|
|
532
|
+
"user-agent": USER_AGENT,
|
|
533
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
534
|
+
...request.headers
|
|
535
|
+
};
|
|
536
|
+
let body;
|
|
537
|
+
if (request.json !== void 0) {
|
|
538
|
+
body = JSON.stringify(request.json);
|
|
539
|
+
headers["content-type"] = "application/json";
|
|
540
|
+
} else if (request.body) {
|
|
541
|
+
body = request.body;
|
|
542
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
543
|
+
}
|
|
544
|
+
const started = Date.now();
|
|
545
|
+
if (request.write) env.onWriteSent();
|
|
546
|
+
let response;
|
|
547
|
+
try {
|
|
548
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
549
|
+
} catch (error) {
|
|
550
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
551
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
552
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
553
|
+
}
|
|
554
|
+
if (request.write) {
|
|
555
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
556
|
+
}
|
|
557
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
558
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
559
|
+
}
|
|
560
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
561
|
+
let bytes;
|
|
562
|
+
try {
|
|
563
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
564
|
+
} catch (error) {
|
|
565
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
566
|
+
throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
|
|
567
|
+
}
|
|
568
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
569
|
+
}
|
|
570
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
571
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
572
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
573
|
+
}
|
|
574
|
+
async function media(rawUrl, options) {
|
|
575
|
+
const { what } = options;
|
|
576
|
+
let url;
|
|
577
|
+
try {
|
|
578
|
+
url = new URL(rawUrl);
|
|
579
|
+
} catch {
|
|
580
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
581
|
+
}
|
|
582
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
583
|
+
const started = Date.now();
|
|
584
|
+
let response;
|
|
585
|
+
try {
|
|
586
|
+
response = await ctx.fetch(url.toString(), {
|
|
587
|
+
method: "GET",
|
|
588
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
589
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
590
|
+
});
|
|
591
|
+
} catch (error) {
|
|
592
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
593
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
594
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
595
|
+
}
|
|
596
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
597
|
+
}
|
|
598
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
await response.body?.cancel().catch(() => {
|
|
601
|
+
});
|
|
602
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
606
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
607
|
+
} catch (error) {
|
|
608
|
+
if (error instanceof TooLarge) {
|
|
609
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
610
|
+
}
|
|
611
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return { api, media };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/core/origins.ts
|
|
618
|
+
function parseSiteUrl(value) {
|
|
619
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
620
|
+
if (!text) return { ok: false, problem: "is empty" };
|
|
621
|
+
let url;
|
|
622
|
+
try {
|
|
623
|
+
url = new URL(text.includes("://") ? text : `https://${text}`);
|
|
624
|
+
} catch {
|
|
625
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
626
|
+
}
|
|
627
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
628
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
629
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
630
|
+
return { ok: true, url, origin: url.origin };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// src/core/schema.ts
|
|
634
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
635
|
+
function patternOf(source) {
|
|
636
|
+
let compiled = patterns.get(source);
|
|
637
|
+
if (!compiled) {
|
|
638
|
+
compiled = new RegExp(source, "u");
|
|
639
|
+
patterns.set(source, compiled);
|
|
640
|
+
}
|
|
641
|
+
return compiled;
|
|
642
|
+
}
|
|
643
|
+
function isPlainObject(value) {
|
|
644
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
645
|
+
}
|
|
646
|
+
function isHttpUrl(value) {
|
|
647
|
+
try {
|
|
648
|
+
const url = new URL(value);
|
|
649
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
650
|
+
} catch {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function name(path) {
|
|
655
|
+
return `\`${path}\``;
|
|
656
|
+
}
|
|
657
|
+
function child(path, key) {
|
|
658
|
+
return path ? `${path}.${key}` : key;
|
|
659
|
+
}
|
|
660
|
+
function checkValue(schema, value, path, issues) {
|
|
661
|
+
switch (schema.type) {
|
|
662
|
+
case "object":
|
|
663
|
+
checkObject(schema, value, path, issues);
|
|
664
|
+
return;
|
|
665
|
+
case "array": {
|
|
666
|
+
if (!Array.isArray(value)) {
|
|
667
|
+
issues.push(`${name(path)} must be an array`);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
671
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
672
|
+
}
|
|
673
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
674
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
675
|
+
}
|
|
676
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
677
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
678
|
+
}
|
|
679
|
+
if (schema.items) {
|
|
680
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
681
|
+
}
|
|
682
|
+
break;
|
|
683
|
+
}
|
|
684
|
+
case "string": {
|
|
685
|
+
if (typeof value !== "string") {
|
|
686
|
+
issues.push(`${name(path)} must be a string`);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
const length = Array.from(value).length;
|
|
690
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
691
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
692
|
+
}
|
|
693
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
694
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
695
|
+
}
|
|
696
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
697
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
698
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
699
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
700
|
+
}
|
|
701
|
+
break;
|
|
702
|
+
}
|
|
703
|
+
case "integer":
|
|
704
|
+
case "number": {
|
|
705
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
706
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
710
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
711
|
+
}
|
|
712
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
713
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
714
|
+
}
|
|
715
|
+
break;
|
|
716
|
+
}
|
|
717
|
+
case "boolean":
|
|
718
|
+
if (typeof value !== "boolean") {
|
|
719
|
+
issues.push(`${name(path)} must be true or false`);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
break;
|
|
723
|
+
default:
|
|
724
|
+
break;
|
|
725
|
+
}
|
|
726
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
727
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function checkObject(schema, value, path, issues) {
|
|
731
|
+
if (!isPlainObject(value)) {
|
|
732
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const properties = schema.properties ?? {};
|
|
736
|
+
for (const key of schema.required ?? []) {
|
|
737
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
738
|
+
}
|
|
739
|
+
const unknown = [];
|
|
740
|
+
for (const [key, item] of Object.entries(value)) {
|
|
741
|
+
const property = properties[key];
|
|
742
|
+
if (!property) {
|
|
743
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (item === void 0 || item === null) continue;
|
|
747
|
+
checkValue(property, item, child(path, key), issues);
|
|
748
|
+
}
|
|
749
|
+
if (unknown.length) {
|
|
750
|
+
const known = Object.keys(properties);
|
|
751
|
+
issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
function copyDefault(value) {
|
|
755
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
756
|
+
}
|
|
757
|
+
function validateArguments(schema, args) {
|
|
758
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
759
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
760
|
+
const value = { ...input };
|
|
761
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
762
|
+
const issues = [];
|
|
763
|
+
checkObject(schema, value, "", issues);
|
|
764
|
+
if (issues.length) return { ok: false, issues };
|
|
765
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
766
|
+
if (value[key] === null) delete value[key];
|
|
767
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
768
|
+
}
|
|
769
|
+
return { ok: true, value };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/core/upload-hosts.ts
|
|
773
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
774
|
+
function uploadHostProblem(entry) {
|
|
775
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
776
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
777
|
+
const labels = name2.split(".");
|
|
778
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
779
|
+
return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
|
|
780
|
+
}
|
|
781
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
782
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
783
|
+
return void 0;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/core/connector.ts
|
|
787
|
+
var ANNOTATIONS = {
|
|
788
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
789
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
790
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
791
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
792
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
793
|
+
};
|
|
794
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
795
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
796
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
797
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
798
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
799
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
800
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
801
|
+
function deepFreeze(value) {
|
|
802
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
803
|
+
Object.freeze(value);
|
|
804
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
805
|
+
}
|
|
806
|
+
return value;
|
|
807
|
+
}
|
|
808
|
+
function assertDefinition(def) {
|
|
809
|
+
const problem = (message) => {
|
|
810
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
811
|
+
};
|
|
812
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
813
|
+
if (!def.label?.trim()) problem("label is required");
|
|
814
|
+
const originFields = def.originFields ?? [];
|
|
815
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
816
|
+
for (const origin of def.origins) {
|
|
817
|
+
let url;
|
|
818
|
+
try {
|
|
819
|
+
url = new URL(origin);
|
|
820
|
+
} catch {
|
|
821
|
+
}
|
|
822
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
823
|
+
}
|
|
824
|
+
for (const name2 of def.credentials) {
|
|
825
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
826
|
+
}
|
|
827
|
+
for (const [index, name2] of originFields.entries()) {
|
|
828
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
829
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
830
|
+
}
|
|
831
|
+
const names = /* @__PURE__ */ new Set();
|
|
832
|
+
for (const tool of def.tools) {
|
|
833
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
834
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
835
|
+
names.add(tool.name);
|
|
836
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
837
|
+
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
838
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
839
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
840
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
for (const tool of def.tools) {
|
|
844
|
+
if (tool.kind === "read") continue;
|
|
845
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
846
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
847
|
+
}
|
|
848
|
+
assertUploadHosts(def, problem);
|
|
849
|
+
assertRequiredCredentials(def, problem);
|
|
850
|
+
assertAccountPickers(def, problem);
|
|
851
|
+
}
|
|
852
|
+
function assertUploadHosts(def, problem) {
|
|
853
|
+
const hosts = def.uploadHosts;
|
|
854
|
+
if (hosts === void 0) return;
|
|
855
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
856
|
+
hosts.forEach((entry, index) => {
|
|
857
|
+
const wrong = uploadHostProblem(entry);
|
|
858
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
859
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
function assertRequiredCredentials(def, problem) {
|
|
863
|
+
const required = def.requiredCredentials;
|
|
864
|
+
if (required === void 0) return;
|
|
865
|
+
if (!Array.isArray(required) || !required.length) {
|
|
866
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
867
|
+
}
|
|
868
|
+
required.forEach((list, index) => {
|
|
869
|
+
const which = `requiredCredentials[${index}]`;
|
|
870
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
871
|
+
list.forEach((name2, position) => {
|
|
872
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
873
|
+
if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
|
|
874
|
+
});
|
|
875
|
+
});
|
|
876
|
+
const lists = required;
|
|
877
|
+
lists.forEach((list, index) => {
|
|
878
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
879
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
880
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
881
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
function isDotPath(value) {
|
|
886
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
887
|
+
}
|
|
888
|
+
function assertAccountPickers(def, problem) {
|
|
889
|
+
const pickers = def.accountPickers;
|
|
890
|
+
if (pickers === void 0) return;
|
|
891
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
892
|
+
const keys = /* @__PURE__ */ new Set();
|
|
893
|
+
for (const item of pickers) {
|
|
894
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
895
|
+
const picker = item;
|
|
896
|
+
const key = picker["key"];
|
|
897
|
+
if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
898
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
899
|
+
keys.add(key);
|
|
900
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
901
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
902
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
903
|
+
const { label, description, multiple, legacyField } = picker;
|
|
904
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
905
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
906
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
907
|
+
}
|
|
908
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
909
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
910
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
911
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
912
|
+
for (const field of ["idField", "nameField"]) {
|
|
913
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
914
|
+
}
|
|
915
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
916
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function copyPicker(picker) {
|
|
921
|
+
return {
|
|
922
|
+
key: picker.key,
|
|
923
|
+
label: picker.label,
|
|
924
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
925
|
+
multiple: picker.multiple,
|
|
926
|
+
tool: picker.tool,
|
|
927
|
+
idField: picker.idField,
|
|
928
|
+
nameField: picker.nameField,
|
|
929
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
function result(payload, isError, files = []) {
|
|
933
|
+
return {
|
|
934
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
935
|
+
...isError ? { isError: true } : {}
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
function failure(message, details = {}) {
|
|
939
|
+
return result({ error: message, ...details }, true);
|
|
940
|
+
}
|
|
941
|
+
function trimmed(values) {
|
|
942
|
+
const out = {};
|
|
943
|
+
if (typeof values !== "object" || values === null) return out;
|
|
944
|
+
for (const [key, value] of Object.entries(values)) {
|
|
945
|
+
if (value === void 0 || value === null) continue;
|
|
946
|
+
const text = String(value).trim();
|
|
947
|
+
if (text) out[key] = text;
|
|
948
|
+
}
|
|
949
|
+
return out;
|
|
950
|
+
}
|
|
951
|
+
function defineConnector(def) {
|
|
952
|
+
assertDefinition(def);
|
|
953
|
+
const { label } = def;
|
|
954
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
955
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
956
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
957
|
+
const required = requiredAlternatives(def);
|
|
958
|
+
const notConnected = (unmet) => {
|
|
959
|
+
const [first] = unmet;
|
|
960
|
+
if (unmet.length === 1 && first) {
|
|
961
|
+
return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
|
|
962
|
+
}
|
|
963
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
964
|
+
};
|
|
965
|
+
const descriptors = def.tools.map((tool) => ({
|
|
966
|
+
name: tool.name,
|
|
967
|
+
title: tool.title,
|
|
968
|
+
description: tool.description,
|
|
969
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
970
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
971
|
+
}));
|
|
972
|
+
async function call(toolName, args, ctx) {
|
|
973
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
974
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
975
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
976
|
+
const log = (text) => {
|
|
977
|
+
try {
|
|
978
|
+
ctx.log?.(text);
|
|
979
|
+
} catch {
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
const given = trimmed(ctx.credentials);
|
|
983
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
984
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
985
|
+
const unmet = unmetAlternatives(required, has);
|
|
986
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
987
|
+
const complete = required.filter((list) => list.every(has));
|
|
988
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
989
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
990
|
+
for (const name2 of def.originFields ?? []) {
|
|
991
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
992
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
993
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
994
|
+
fieldOrigins.set(name2, site.origin);
|
|
995
|
+
}
|
|
996
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
997
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
998
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
999
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
1000
|
+
let writeSent = false;
|
|
1001
|
+
const fileLimit = fileLimitOf(ctx);
|
|
1002
|
+
const files = [];
|
|
1003
|
+
let fileBytes = 0;
|
|
1004
|
+
const http = createHttp({
|
|
1005
|
+
vendor: def.vendor,
|
|
1006
|
+
label,
|
|
1007
|
+
tool: tool.name,
|
|
1008
|
+
readOnly: tool.kind === "read",
|
|
1009
|
+
origins,
|
|
1010
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
1011
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
1012
|
+
ctx,
|
|
1013
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
1014
|
+
log,
|
|
1015
|
+
onWriteSent: () => {
|
|
1016
|
+
writeSent = true;
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
const helpers = {
|
|
1020
|
+
tool: tool.name,
|
|
1021
|
+
credentials: frozenCredentials,
|
|
1022
|
+
ctx,
|
|
1023
|
+
origins: Object.freeze([...origins]),
|
|
1024
|
+
originOf: (credential) => {
|
|
1025
|
+
const origin = fieldOrigins.get(credential);
|
|
1026
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
1027
|
+
return origin;
|
|
1028
|
+
},
|
|
1029
|
+
api: http.api,
|
|
1030
|
+
media: http.media,
|
|
1031
|
+
page: (input) => fitPage(input),
|
|
1032
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
1033
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
1034
|
+
fileLimit: () => fileLimit,
|
|
1035
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
1036
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
1037
|
+
const total = fileBytes + bytes.byteLength;
|
|
1038
|
+
if (total > fileLimit) {
|
|
1039
|
+
throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
|
|
1040
|
+
}
|
|
1041
|
+
fileBytes = total;
|
|
1042
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
1043
|
+
files.push({ ...info, bytes });
|
|
1044
|
+
return { ...info };
|
|
1045
|
+
},
|
|
1046
|
+
log
|
|
1047
|
+
};
|
|
1048
|
+
try {
|
|
1049
|
+
const data = await tool.run(parsed.value, helpers);
|
|
1050
|
+
const fitted = shrinkToFit(data ?? {});
|
|
1051
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
1052
|
+
const payload = fitted.value;
|
|
1053
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
if (error instanceof OutcomeUnknown) {
|
|
1056
|
+
return result({
|
|
1057
|
+
outcome: "unknown",
|
|
1058
|
+
check: tool.check,
|
|
1059
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
1060
|
+
}, true);
|
|
1061
|
+
}
|
|
1062
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
1063
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
1064
|
+
if (writeSent) {
|
|
1065
|
+
return result({
|
|
1066
|
+
outcome: "unknown",
|
|
1067
|
+
check: tool.check,
|
|
1068
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
1069
|
+
}, true);
|
|
1070
|
+
}
|
|
1071
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return deepFreeze({
|
|
1075
|
+
vendor: def.vendor,
|
|
1076
|
+
origins: [...def.origins],
|
|
1077
|
+
originFields: [...def.originFields ?? []],
|
|
1078
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
1079
|
+
credentials: [...def.credentials],
|
|
1080
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
1081
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
1082
|
+
tools: descriptors,
|
|
1083
|
+
call
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// src/core/jwt.ts
|
|
1088
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
1089
|
+
|
|
1090
|
+
// src/vendors/mailchimp/md5.ts
|
|
1091
|
+
var SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
|
1092
|
+
var K = new Uint32Array([
|
|
1093
|
+
3614090360,
|
|
1094
|
+
3905402710,
|
|
1095
|
+
606105819,
|
|
1096
|
+
3250441966,
|
|
1097
|
+
4118548399,
|
|
1098
|
+
1200080426,
|
|
1099
|
+
2821735955,
|
|
1100
|
+
4249261313,
|
|
1101
|
+
1770035416,
|
|
1102
|
+
2336552879,
|
|
1103
|
+
4294925233,
|
|
1104
|
+
2304563134,
|
|
1105
|
+
1804603682,
|
|
1106
|
+
4254626195,
|
|
1107
|
+
2792965006,
|
|
1108
|
+
1236535329,
|
|
1109
|
+
4129170786,
|
|
1110
|
+
3225465664,
|
|
1111
|
+
643717713,
|
|
1112
|
+
3921069994,
|
|
1113
|
+
3593408605,
|
|
1114
|
+
38016083,
|
|
1115
|
+
3634488961,
|
|
1116
|
+
3889429448,
|
|
1117
|
+
568446438,
|
|
1118
|
+
3275163606,
|
|
1119
|
+
4107603335,
|
|
1120
|
+
1163531501,
|
|
1121
|
+
2850285829,
|
|
1122
|
+
4243563512,
|
|
1123
|
+
1735328473,
|
|
1124
|
+
2368359562,
|
|
1125
|
+
4294588738,
|
|
1126
|
+
2272392833,
|
|
1127
|
+
1839030562,
|
|
1128
|
+
4259657740,
|
|
1129
|
+
2763975236,
|
|
1130
|
+
1272893353,
|
|
1131
|
+
4139469664,
|
|
1132
|
+
3200236656,
|
|
1133
|
+
681279174,
|
|
1134
|
+
3936430074,
|
|
1135
|
+
3572445317,
|
|
1136
|
+
76029189,
|
|
1137
|
+
3654602809,
|
|
1138
|
+
3873151461,
|
|
1139
|
+
530742520,
|
|
1140
|
+
3299628645,
|
|
1141
|
+
4096336452,
|
|
1142
|
+
1126891415,
|
|
1143
|
+
2878612391,
|
|
1144
|
+
4237533241,
|
|
1145
|
+
1700485571,
|
|
1146
|
+
2399980690,
|
|
1147
|
+
4293915773,
|
|
1148
|
+
2240044497,
|
|
1149
|
+
1873313359,
|
|
1150
|
+
4264355552,
|
|
1151
|
+
2734768916,
|
|
1152
|
+
1309151649,
|
|
1153
|
+
4149444226,
|
|
1154
|
+
3174756917,
|
|
1155
|
+
718787259,
|
|
1156
|
+
3951481745
|
|
1157
|
+
]);
|
|
1158
|
+
function md5Hex(text) {
|
|
1159
|
+
const bytes = new TextEncoder().encode(text);
|
|
1160
|
+
const length = bytes.length;
|
|
1161
|
+
const words = new Uint32Array(((length + 8 >>> 6) + 1) * 16);
|
|
1162
|
+
for (let i = 0; i < length; i++) words[i >>> 2] |= bytes[i] << i % 4 * 8;
|
|
1163
|
+
words[length >>> 2] |= 128 << length % 4 * 8;
|
|
1164
|
+
words[words.length - 2] = length * 8 >>> 0;
|
|
1165
|
+
words[words.length - 1] = Math.floor(length / 536870912);
|
|
1166
|
+
let a = 1732584193;
|
|
1167
|
+
let b = 4023233417;
|
|
1168
|
+
let c = 2562383102;
|
|
1169
|
+
let d = 271733878;
|
|
1170
|
+
for (let block = 0; block < words.length; block += 16) {
|
|
1171
|
+
let A = a;
|
|
1172
|
+
let B = b;
|
|
1173
|
+
let C = c;
|
|
1174
|
+
let D = d;
|
|
1175
|
+
for (let i = 0; i < 64; i++) {
|
|
1176
|
+
let f;
|
|
1177
|
+
let g;
|
|
1178
|
+
if (i < 16) {
|
|
1179
|
+
f = B & C | ~B & D;
|
|
1180
|
+
g = i;
|
|
1181
|
+
} else if (i < 32) {
|
|
1182
|
+
f = D & B | ~D & C;
|
|
1183
|
+
g = (5 * i + 1) % 16;
|
|
1184
|
+
} else if (i < 48) {
|
|
1185
|
+
f = B ^ C ^ D;
|
|
1186
|
+
g = (3 * i + 5) % 16;
|
|
1187
|
+
} else {
|
|
1188
|
+
f = C ^ (B | ~D);
|
|
1189
|
+
g = 7 * i % 16;
|
|
1190
|
+
}
|
|
1191
|
+
const sum = A + f + K[i] + words[block + g] >>> 0;
|
|
1192
|
+
const shift = SHIFTS[(i >>> 4) * 4 + i % 4];
|
|
1193
|
+
const next = D;
|
|
1194
|
+
D = C;
|
|
1195
|
+
C = B;
|
|
1196
|
+
B = B + (sum << shift | sum >>> 32 - shift) >>> 0;
|
|
1197
|
+
A = next;
|
|
1198
|
+
}
|
|
1199
|
+
a = a + A >>> 0;
|
|
1200
|
+
b = b + B >>> 0;
|
|
1201
|
+
c = c + C >>> 0;
|
|
1202
|
+
d = d + D >>> 0;
|
|
1203
|
+
}
|
|
1204
|
+
return [a, b, c, d].map((word) => [0, 8, 16, 24].map((offset) => (word >>> offset & 255).toString(16).padStart(2, "0")).join("")).join("");
|
|
1205
|
+
}
|
|
1206
|
+
function subscriberHash(email) {
|
|
1207
|
+
return md5Hex(email.trim().toLowerCase());
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// src/vendors/mailchimp/shape.ts
|
|
1211
|
+
function compact(value) {
|
|
1212
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
|
|
1213
|
+
}
|
|
1214
|
+
function stripLinks(value) {
|
|
1215
|
+
if (Array.isArray(value)) return value.map(stripLinks);
|
|
1216
|
+
if (typeof value === "object" && value !== null) {
|
|
1217
|
+
const out = {};
|
|
1218
|
+
for (const [key, item] of Object.entries(value)) if (key !== "_links") out[key] = stripLinks(item);
|
|
1219
|
+
return out;
|
|
1220
|
+
}
|
|
1221
|
+
return value;
|
|
1222
|
+
}
|
|
1223
|
+
var HTML_LIMIT = 2e4;
|
|
1224
|
+
function html(text) {
|
|
1225
|
+
return typeof text === "string" && text ? truncate(text, HTML_LIMIT) : void 0;
|
|
1226
|
+
}
|
|
1227
|
+
function nonEmpty(value) {
|
|
1228
|
+
if (Array.isArray(value)) return value.length ? value : void 0;
|
|
1229
|
+
if (typeof value === "object" && value !== null) return Object.keys(value).length ? value : void 0;
|
|
1230
|
+
return value;
|
|
1231
|
+
}
|
|
1232
|
+
function trimAudience(list) {
|
|
1233
|
+
const stats = list?.stats ?? {};
|
|
1234
|
+
return compact({
|
|
1235
|
+
id: list?.id,
|
|
1236
|
+
web_id: list?.web_id,
|
|
1237
|
+
name: list?.name,
|
|
1238
|
+
date_created: list?.date_created,
|
|
1239
|
+
double_optin: list?.double_optin,
|
|
1240
|
+
subscribe_url_short: list?.subscribe_url_short,
|
|
1241
|
+
campaign_defaults: list?.campaign_defaults,
|
|
1242
|
+
stats: compact({
|
|
1243
|
+
member_count: stats.member_count,
|
|
1244
|
+
unsubscribe_count: stats.unsubscribe_count,
|
|
1245
|
+
cleaned_count: stats.cleaned_count,
|
|
1246
|
+
member_count_since_send: stats.member_count_since_send,
|
|
1247
|
+
campaign_count: stats.campaign_count,
|
|
1248
|
+
campaign_last_sent: stats.campaign_last_sent,
|
|
1249
|
+
open_rate: stats.open_rate,
|
|
1250
|
+
click_rate: stats.click_rate,
|
|
1251
|
+
avg_sub_rate: stats.avg_sub_rate,
|
|
1252
|
+
avg_unsub_rate: stats.avg_unsub_rate,
|
|
1253
|
+
last_sub_date: stats.last_sub_date,
|
|
1254
|
+
last_unsub_date: stats.last_unsub_date
|
|
1255
|
+
})
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
function trimMember(member) {
|
|
1259
|
+
return compact({
|
|
1260
|
+
id: member?.id,
|
|
1261
|
+
email_address: member?.email_address,
|
|
1262
|
+
status: member?.status,
|
|
1263
|
+
full_name: member?.full_name,
|
|
1264
|
+
merge_fields: nonEmpty(member?.merge_fields),
|
|
1265
|
+
tags: Array.isArray(member?.tags) && member.tags.length ? member.tags.map((tag) => tag?.name) : void 0,
|
|
1266
|
+
interests: nonEmpty(member?.interests),
|
|
1267
|
+
vip: member?.vip,
|
|
1268
|
+
language: member?.language,
|
|
1269
|
+
member_rating: member?.member_rating,
|
|
1270
|
+
source: member?.source,
|
|
1271
|
+
timestamp_signup: member?.timestamp_signup,
|
|
1272
|
+
timestamp_opt: member?.timestamp_opt,
|
|
1273
|
+
last_changed: member?.last_changed,
|
|
1274
|
+
unsubscribe_reason: member?.unsubscribe_reason,
|
|
1275
|
+
avg_open_rate: member?.stats?.avg_open_rate,
|
|
1276
|
+
avg_click_rate: member?.stats?.avg_click_rate,
|
|
1277
|
+
country_code: member?.location?.country_code,
|
|
1278
|
+
list_id: member?.list_id
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
function trimCampaign(campaign) {
|
|
1282
|
+
const settings = campaign?.settings ?? {};
|
|
1283
|
+
const recipients = campaign?.recipients ?? {};
|
|
1284
|
+
const summary = campaign?.report_summary;
|
|
1285
|
+
return compact({
|
|
1286
|
+
id: campaign?.id,
|
|
1287
|
+
web_id: campaign?.web_id,
|
|
1288
|
+
type: campaign?.type,
|
|
1289
|
+
status: campaign?.status,
|
|
1290
|
+
create_time: campaign?.create_time,
|
|
1291
|
+
send_time: campaign?.send_time,
|
|
1292
|
+
emails_sent: campaign?.emails_sent,
|
|
1293
|
+
content_type: campaign?.content_type,
|
|
1294
|
+
archive_url: campaign?.long_archive_url ?? campaign?.archive_url,
|
|
1295
|
+
recipients: compact({
|
|
1296
|
+
list_id: recipients.list_id,
|
|
1297
|
+
list_name: recipients.list_name,
|
|
1298
|
+
segment_text: typeof recipients.segment_text === "string" && recipients.segment_text ? truncate(recipients.segment_text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(), 300) : void 0,
|
|
1299
|
+
recipient_count: recipients.recipient_count,
|
|
1300
|
+
saved_segment_id: recipients.segment_opts?.saved_segment_id
|
|
1301
|
+
}),
|
|
1302
|
+
settings: compact({
|
|
1303
|
+
subject_line: settings.subject_line,
|
|
1304
|
+
preview_text: settings.preview_text,
|
|
1305
|
+
title: settings.title,
|
|
1306
|
+
from_name: settings.from_name,
|
|
1307
|
+
reply_to: settings.reply_to,
|
|
1308
|
+
to_name: settings.to_name,
|
|
1309
|
+
template_id: settings.template_id
|
|
1310
|
+
}),
|
|
1311
|
+
report_summary: summary ? compact({
|
|
1312
|
+
opens: summary.opens,
|
|
1313
|
+
unique_opens: summary.unique_opens,
|
|
1314
|
+
open_rate: summary.open_rate,
|
|
1315
|
+
clicks: summary.clicks,
|
|
1316
|
+
subscriber_clicks: summary.subscriber_clicks,
|
|
1317
|
+
click_rate: summary.click_rate
|
|
1318
|
+
}) : void 0
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
function trimReport(report) {
|
|
1322
|
+
return compact({
|
|
1323
|
+
id: report?.id,
|
|
1324
|
+
campaign_title: report?.campaign_title,
|
|
1325
|
+
type: report?.type,
|
|
1326
|
+
list_id: report?.list_id,
|
|
1327
|
+
list_name: report?.list_name,
|
|
1328
|
+
subject_line: report?.subject_line,
|
|
1329
|
+
preview_text: report?.preview_text,
|
|
1330
|
+
send_time: report?.send_time,
|
|
1331
|
+
emails_sent: report?.emails_sent,
|
|
1332
|
+
abuse_reports: report?.abuse_reports,
|
|
1333
|
+
unsubscribed: report?.unsubscribed,
|
|
1334
|
+
bounces: report?.bounces,
|
|
1335
|
+
forwards: report?.forwards,
|
|
1336
|
+
opens: report?.opens,
|
|
1337
|
+
clicks: report?.clicks,
|
|
1338
|
+
list_stats: report?.list_stats,
|
|
1339
|
+
ecommerce: report?.ecommerce && Object.values(report.ecommerce).some((value) => value) ? report.ecommerce : void 0
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
async function offsetList(h, send, cursor, options) {
|
|
1343
|
+
const state = h.cursor(cursor);
|
|
1344
|
+
const offset = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1345
|
+
const count = typeof state?.["n"] === "number" ? state["n"] : options.count;
|
|
1346
|
+
const skip = typeof state?.["s"] === "number" ? state["s"] : 0;
|
|
1347
|
+
const field = options.listField ?? options.key;
|
|
1348
|
+
const { data } = await send({ path: options.path, query: { ...options.query, count, offset, exclude_fields: `_links,${field}._links` } });
|
|
1349
|
+
const items = Array.isArray(data?.[field]) ? data[field] : [];
|
|
1350
|
+
const total = typeof data?.total_items === "number" ? data.total_items : void 0;
|
|
1351
|
+
const more = total !== void 0 ? offset + items.length < total : items.length >= count;
|
|
1352
|
+
return h.page({
|
|
1353
|
+
key: options.key,
|
|
1354
|
+
items: items.map(options.trim).slice(skip),
|
|
1355
|
+
extra: { ...total !== void 0 ? { total_items: total } : {}, ...options.extra?.(data) },
|
|
1356
|
+
resumeAt: (index) => h.makeCursor({ o: offset, n: count, s: skip + index }),
|
|
1357
|
+
...more && items.length ? { nextPage: h.makeCursor({ o: offset + count, n: count, s: 0 }) } : {}
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// src/vendors/mailchimp/index.ts
|
|
1362
|
+
var LABEL2 = "Mailchimp";
|
|
1363
|
+
var DATA_CENTER = /^us([1-9]|[12][0-9]|30)$/;
|
|
1364
|
+
var ORIGINS = Array.from({ length: 30 }, (_, index) => `https://us${index + 1}.api.mailchimp.com`);
|
|
1365
|
+
function connection(credentials) {
|
|
1366
|
+
const server = (credentials["server"] ?? "").toLowerCase();
|
|
1367
|
+
if (credentials["access_token"] && server) {
|
|
1368
|
+
if (DATA_CENTER.test(server)) return { mode: "oauth", dc: server };
|
|
1369
|
+
if (!credentials["apikey"]) return "the data center (server) of the sign-in is not one Mailchimp names, such as us19; connect Mailchimp again";
|
|
1370
|
+
}
|
|
1371
|
+
const key = credentials["apikey"];
|
|
1372
|
+
if (key) {
|
|
1373
|
+
const suffix = /-([a-z]{2}\d{1,2})$/i.exec(key)?.[1]?.toLowerCase();
|
|
1374
|
+
if (suffix) return DATA_CENTER.test(suffix) ? { mode: "key", dc: suffix } : "the API key ends with a data center this connector does not know";
|
|
1375
|
+
if (DATA_CENTER.test(server)) return { mode: "key", dc: server };
|
|
1376
|
+
return "the API key lacks its last part after the dash (such as -us19), which names its data center; paste the whole key";
|
|
1377
|
+
}
|
|
1378
|
+
return "the sign-in has no data center (server); connect Mailchimp again";
|
|
1379
|
+
}
|
|
1380
|
+
function originFor(h) {
|
|
1381
|
+
const found = connection(h.credentials);
|
|
1382
|
+
if (typeof found === "string") throw new ToolFailure(`Mailchimp is not connected correctly: ${found}. Nothing was sent.`);
|
|
1383
|
+
return `https://${found.dc}.api.mailchimp.com`;
|
|
1384
|
+
}
|
|
1385
|
+
function mc(h) {
|
|
1386
|
+
return (request) => h.api({ ...request, origin: originFor(h) });
|
|
1387
|
+
}
|
|
1388
|
+
var EMAIL = {
|
|
1389
|
+
type: "string",
|
|
1390
|
+
minLength: 3,
|
|
1391
|
+
maxLength: 320,
|
|
1392
|
+
pattern: "^[^@\\s]+@[^@\\s]+$",
|
|
1393
|
+
description: "An email address."
|
|
1394
|
+
};
|
|
1395
|
+
var CURSOR = { type: "string", description: "nextCursor from the previous result; pass the other arguments unchanged." };
|
|
1396
|
+
var ID = { type: "string", minLength: 1, maxLength: 100, pattern: "^[A-Za-z0-9_-]+$", description: "A Mailchimp id." };
|
|
1397
|
+
var LIST_ID = { ...ID, description: "The audience (list) id, from list_audiences." };
|
|
1398
|
+
var CAMPAIGN_ID = { ...ID, description: "The campaign id, from list_campaigns." };
|
|
1399
|
+
var COUNT = (what, max = 1e3, fallback = 50) => ({
|
|
1400
|
+
type: "integer",
|
|
1401
|
+
minimum: 1,
|
|
1402
|
+
maximum: max,
|
|
1403
|
+
default: fallback,
|
|
1404
|
+
description: `${what} per page, 1 to ${max} (default ${fallback}).`
|
|
1405
|
+
});
|
|
1406
|
+
var DATE_TIME = (what) => ({
|
|
1407
|
+
type: "string",
|
|
1408
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?)?$",
|
|
1409
|
+
description: `${what}, as an ISO 8601 date or date-time, e.g. 2026-11-01T00:00:00Z.`
|
|
1410
|
+
});
|
|
1411
|
+
var STATUS = {
|
|
1412
|
+
type: "string",
|
|
1413
|
+
enum: ["subscribed", "unsubscribed", "cleaned", "pending", "transactional"],
|
|
1414
|
+
description: "subscribed, unsubscribed, cleaned, pending (sends a double opt-in email) or transactional."
|
|
1415
|
+
};
|
|
1416
|
+
var MERGE_FIELDS = {
|
|
1417
|
+
type: "object",
|
|
1418
|
+
description: 'Merge field values by tag, e.g. {"FNAME": "Jane", "LNAME": "Doe"}.'
|
|
1419
|
+
};
|
|
1420
|
+
function memberPath(listId, email) {
|
|
1421
|
+
return `/3.0/lists/${encodeURIComponent(listId)}/members/${subscriberHash(email)}`;
|
|
1422
|
+
}
|
|
1423
|
+
var SETTINGS_FIELDS = {
|
|
1424
|
+
subject_line: { type: "string", minLength: 1, maxLength: 150, description: "The subject line; merge tags like *|FNAME|* work." },
|
|
1425
|
+
preview_text: { type: "string", maxLength: 150, description: "The preview text shown after the subject in inboxes." },
|
|
1426
|
+
title: { type: "string", maxLength: 100, description: "The internal campaign title." },
|
|
1427
|
+
from_name: { type: "string", minLength: 1, maxLength: 100, description: "The From name." },
|
|
1428
|
+
reply_to: EMAIL,
|
|
1429
|
+
to_name: { type: "string", maxLength: 100, description: "The To name, e.g. *|FNAME|*." },
|
|
1430
|
+
template_id: { type: "integer", minimum: 1, description: "A template to start from (see list_templates)." }
|
|
1431
|
+
};
|
|
1432
|
+
function campaignParts(args) {
|
|
1433
|
+
if (args.saved_segment_id !== void 0 && args.segment_opts !== void 0) {
|
|
1434
|
+
throw new ToolFailure("Give saved_segment_id or segment_opts, not both. Nothing was changed.");
|
|
1435
|
+
}
|
|
1436
|
+
const segment = args.saved_segment_id !== void 0 ? { saved_segment_id: args.saved_segment_id } : args.segment_opts;
|
|
1437
|
+
const recipients = compact({ list_id: args.list_id, segment_opts: segment });
|
|
1438
|
+
const settings = compact({
|
|
1439
|
+
subject_line: args.subject_line,
|
|
1440
|
+
preview_text: args.preview_text,
|
|
1441
|
+
title: args.title,
|
|
1442
|
+
from_name: args.from_name,
|
|
1443
|
+
reply_to: args.reply_to,
|
|
1444
|
+
to_name: args.to_name,
|
|
1445
|
+
template_id: args.template_id
|
|
1446
|
+
});
|
|
1447
|
+
return compact({
|
|
1448
|
+
recipients: Object.keys(recipients).length ? recipients : void 0,
|
|
1449
|
+
settings: Object.keys(settings).length ? settings : void 0
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
var RECIPIENT_FIELDS = {
|
|
1453
|
+
list_id: LIST_ID,
|
|
1454
|
+
saved_segment_id: { type: "integer", minimum: 1, description: "Send to a saved segment or tag of the audience (see list_segments) instead of all of it." },
|
|
1455
|
+
segment_opts: { type: "object", description: 'Advanced: Mailchimp segment conditions, e.g. {"match": "all", "conditions": [...]}, instead of saved_segment_id.' }
|
|
1456
|
+
};
|
|
1457
|
+
var REPORT_DETAILS = {
|
|
1458
|
+
"click-details": "urls_clicked",
|
|
1459
|
+
"open-details": "members",
|
|
1460
|
+
unsubscribed: "unsubscribes",
|
|
1461
|
+
"email-activity": "emails",
|
|
1462
|
+
"sent-to": "sent_to",
|
|
1463
|
+
"domain-performance": "domains",
|
|
1464
|
+
locations: "locations",
|
|
1465
|
+
"abuse-reports": "abuse_reports",
|
|
1466
|
+
advice: "advice"
|
|
1467
|
+
};
|
|
1468
|
+
function routedParts(segments) {
|
|
1469
|
+
const parts = [];
|
|
1470
|
+
for (const piece of segments.join("/").split(/[\\/]/)) {
|
|
1471
|
+
const part = (piece.split(";")[0] ?? "").toLowerCase();
|
|
1472
|
+
if (part === "" || part === ".") continue;
|
|
1473
|
+
if (part === "..") parts.pop();
|
|
1474
|
+
else parts.push(part);
|
|
1475
|
+
}
|
|
1476
|
+
return parts;
|
|
1477
|
+
}
|
|
1478
|
+
var NO_AUTHORIZED_APPS = "Mailchimp's authorized apps are not available here. Nothing was sent.";
|
|
1479
|
+
function namesAuthorizedApps(path) {
|
|
1480
|
+
if (typeof path !== "string") return false;
|
|
1481
|
+
let segments;
|
|
1482
|
+
try {
|
|
1483
|
+
segments = (path.split(/[?#]/)[0] ?? "").split("/").map((segment) => decodeURIComponent(segment));
|
|
1484
|
+
} catch {
|
|
1485
|
+
throw new ToolFailure("A batch operation's path has a broken percent-escape (a % not followed by two hex digits). Nothing was sent.");
|
|
1486
|
+
}
|
|
1487
|
+
return routedParts(segments).includes("authorized-apps");
|
|
1488
|
+
}
|
|
1489
|
+
var connector = defineConnector({
|
|
1490
|
+
vendor: "mailchimp",
|
|
1491
|
+
label: LABEL2,
|
|
1492
|
+
origins: ORIGINS,
|
|
1493
|
+
credentials: ["access_token", "apikey", "server"],
|
|
1494
|
+
requiredCredentials: [["access_token", "server"], ["apikey"]],
|
|
1495
|
+
credentialLabels: {
|
|
1496
|
+
access_token: "Mailchimp access token",
|
|
1497
|
+
apikey: "Mailchimp API key",
|
|
1498
|
+
server: "Mailchimp data center (server)"
|
|
1499
|
+
},
|
|
1500
|
+
authHeaders: (credentials) => {
|
|
1501
|
+
const found = connection(credentials);
|
|
1502
|
+
if (typeof found === "string") return {};
|
|
1503
|
+
return found.mode === "oauth" ? { authorization: `Bearer ${credentials["access_token"]}` } : { authorization: `Basic ${btoa(`anystring:${credentials["apikey"]}`)}` };
|
|
1504
|
+
},
|
|
1505
|
+
tools: [
|
|
1506
|
+
{
|
|
1507
|
+
name: "get_account",
|
|
1508
|
+
kind: "read",
|
|
1509
|
+
title: "Get the Mailchimp account",
|
|
1510
|
+
description: "The connected Mailchimp account: name, login email, plan, time zone, total subscribers, industry benchmark rates, its data center and how it is connected. A quick connection check.",
|
|
1511
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1512
|
+
async run(_args, h) {
|
|
1513
|
+
const { data } = await mc(h)({ path: "/3.0/" });
|
|
1514
|
+
const found = connection(h.credentials);
|
|
1515
|
+
return compact({
|
|
1516
|
+
account_id: data?.account_id,
|
|
1517
|
+
account_name: data?.account_name,
|
|
1518
|
+
email: data?.email,
|
|
1519
|
+
first_name: data?.first_name,
|
|
1520
|
+
last_name: data?.last_name,
|
|
1521
|
+
role: data?.role,
|
|
1522
|
+
pricing_plan_type: data?.pricing_plan_type,
|
|
1523
|
+
account_timezone: data?.account_timezone,
|
|
1524
|
+
total_subscribers: data?.total_subscribers,
|
|
1525
|
+
industry_stats: data?.industry_stats,
|
|
1526
|
+
data_center: found.dc,
|
|
1527
|
+
connected_with: found.mode === "oauth" ? "sign-in" : "API key"
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
},
|
|
1531
|
+
{
|
|
1532
|
+
name: "list_audiences",
|
|
1533
|
+
kind: "read",
|
|
1534
|
+
title: "List Mailchimp audiences",
|
|
1535
|
+
description: "The audiences (lists) with their ids, member, unsubscribe and cleaned counts, open and click rates, last campaign and campaign defaults. Pass nextCursor back as cursor for more.",
|
|
1536
|
+
inputSchema: {
|
|
1537
|
+
type: "object",
|
|
1538
|
+
properties: { count: COUNT("Audiences", 1e3, 25), cursor: CURSOR },
|
|
1539
|
+
additionalProperties: false
|
|
1540
|
+
},
|
|
1541
|
+
async run(args, h) {
|
|
1542
|
+
return offsetList(h, mc(h), args.cursor, { key: "lists", path: "/3.0/lists", count: args.count, trim: trimAudience });
|
|
1543
|
+
}
|
|
1544
|
+
},
|
|
1545
|
+
{
|
|
1546
|
+
name: "create_audience",
|
|
1547
|
+
kind: "create",
|
|
1548
|
+
check: "list_audiences",
|
|
1549
|
+
title: "Create a Mailchimp audience",
|
|
1550
|
+
description: "Creates an audience (list) with its required contact address (shown in email footers), permission reminder and campaign defaults. Free plans allow one audience.",
|
|
1551
|
+
inputSchema: {
|
|
1552
|
+
type: "object",
|
|
1553
|
+
properties: {
|
|
1554
|
+
name: { type: "string", minLength: 1, maxLength: 100, description: "The audience name." },
|
|
1555
|
+
company: { type: "string", minLength: 1, maxLength: 100, description: "The company or organization in the footer." },
|
|
1556
|
+
address1: { type: "string", minLength: 1, maxLength: 100, description: "The street address." },
|
|
1557
|
+
address2: { type: "string", maxLength: 100, description: "More of the address." },
|
|
1558
|
+
city: { type: "string", minLength: 1, maxLength: 100, description: "The city." },
|
|
1559
|
+
state: { type: "string", maxLength: 100, description: "The state or region." },
|
|
1560
|
+
zip: { type: "string", maxLength: 20, description: "The postal code." },
|
|
1561
|
+
country: { type: "string", minLength: 2, maxLength: 2, description: "The two-letter country code, e.g. US." },
|
|
1562
|
+
permission_reminder: { type: "string", minLength: 1, maxLength: 500, description: 'Why people get these emails, e.g. "You signed up on our website."' },
|
|
1563
|
+
from_name: { type: "string", minLength: 1, maxLength: 100, description: "The default From name." },
|
|
1564
|
+
from_email: EMAIL,
|
|
1565
|
+
subject: { type: "string", maxLength: 150, description: "The default subject line." },
|
|
1566
|
+
language: { type: "string", minLength: 2, maxLength: 10, default: "en", description: "The default language, e.g. en." },
|
|
1567
|
+
email_type_option: { type: "boolean", default: false, description: "true to let subscribers choose HTML or plain text." },
|
|
1568
|
+
double_optin: { type: "boolean", description: "true to send a confirmation email before a signup counts." }
|
|
1569
|
+
},
|
|
1570
|
+
required: ["name", "company", "address1", "city", "country", "permission_reminder", "from_name", "from_email"],
|
|
1571
|
+
additionalProperties: false
|
|
1572
|
+
},
|
|
1573
|
+
async run(args, h) {
|
|
1574
|
+
const { data } = await mc(h)({
|
|
1575
|
+
method: "POST",
|
|
1576
|
+
path: "/3.0/lists",
|
|
1577
|
+
json: compact({
|
|
1578
|
+
name: args["name"],
|
|
1579
|
+
contact: compact({ company: args["company"], address1: args["address1"], address2: args["address2"], city: args["city"], state: args["state"] ?? "", zip: args["zip"] ?? "", country: args["country"] }),
|
|
1580
|
+
permission_reminder: args["permission_reminder"],
|
|
1581
|
+
campaign_defaults: { from_name: args["from_name"], from_email: args["from_email"], subject: args["subject"] ?? "", language: args["language"] },
|
|
1582
|
+
email_type_option: args["email_type_option"],
|
|
1583
|
+
double_optin: args["double_optin"]
|
|
1584
|
+
}),
|
|
1585
|
+
write: true,
|
|
1586
|
+
errors: { 400: "Mailchimp did not accept the audience" }
|
|
1587
|
+
});
|
|
1588
|
+
return trimAudience(data);
|
|
1589
|
+
}
|
|
1590
|
+
},
|
|
1591
|
+
{
|
|
1592
|
+
name: "list_members",
|
|
1593
|
+
kind: "read",
|
|
1594
|
+
title: "List Mailchimp audience members",
|
|
1595
|
+
description: "Members of an audience, most recently changed first, with status, merge fields, tags, rating and open and click rates. Filter by status, by when they changed, or VIPs only. Pass nextCursor back as cursor for more.",
|
|
1596
|
+
inputSchema: {
|
|
1597
|
+
type: "object",
|
|
1598
|
+
properties: {
|
|
1599
|
+
list_id: LIST_ID,
|
|
1600
|
+
status: { ...STATUS, description: "Only members with this status." },
|
|
1601
|
+
since_last_changed: DATE_TIME("Only members changed after this time"),
|
|
1602
|
+
before_last_changed: DATE_TIME("Only members changed before this time"),
|
|
1603
|
+
vip_only: { type: "boolean", description: "true for VIP members only." },
|
|
1604
|
+
count: COUNT("Members", 1e3, 50),
|
|
1605
|
+
cursor: CURSOR
|
|
1606
|
+
},
|
|
1607
|
+
required: ["list_id"],
|
|
1608
|
+
additionalProperties: false
|
|
1609
|
+
},
|
|
1610
|
+
async run(args, h) {
|
|
1611
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
1612
|
+
key: "members",
|
|
1613
|
+
path: `/3.0/lists/${encodeURIComponent(args.list_id)}/members`,
|
|
1614
|
+
count: args.count,
|
|
1615
|
+
query: {
|
|
1616
|
+
status: args.status,
|
|
1617
|
+
since_last_changed: args.since_last_changed,
|
|
1618
|
+
before_last_changed: args.before_last_changed,
|
|
1619
|
+
vip_only: args.vip_only,
|
|
1620
|
+
sort_field: "last_changed",
|
|
1621
|
+
sort_dir: "DESC"
|
|
1622
|
+
},
|
|
1623
|
+
trim: trimMember
|
|
1624
|
+
});
|
|
1625
|
+
}
|
|
1626
|
+
},
|
|
1627
|
+
{
|
|
1628
|
+
name: "get_member",
|
|
1629
|
+
kind: "read",
|
|
1630
|
+
title: "Get a Mailchimp audience member",
|
|
1631
|
+
description: "One member of an audience by email address: status, merge fields, tags, interests, rating, signup and opt-in times, open and click rates. The module computes Mailchimp's subscriber hash.",
|
|
1632
|
+
inputSchema: {
|
|
1633
|
+
type: "object",
|
|
1634
|
+
properties: { list_id: LIST_ID, email: EMAIL },
|
|
1635
|
+
required: ["list_id", "email"],
|
|
1636
|
+
additionalProperties: false
|
|
1637
|
+
},
|
|
1638
|
+
async run(args, h) {
|
|
1639
|
+
const { data } = await mc(h)({ path: memberPath(args.list_id, args.email), errors: { 404: "Mailchimp has no member with that email in this audience" } });
|
|
1640
|
+
return trimMember(data);
|
|
1641
|
+
}
|
|
1642
|
+
},
|
|
1643
|
+
{
|
|
1644
|
+
name: "search_members",
|
|
1645
|
+
kind: "read",
|
|
1646
|
+
title: "Search Mailchimp members",
|
|
1647
|
+
description: "Finds members by email address or name, across all audiences or in one: exact matches first, then the wider search.",
|
|
1648
|
+
inputSchema: {
|
|
1649
|
+
type: "object",
|
|
1650
|
+
properties: {
|
|
1651
|
+
query: { type: "string", minLength: 1, maxLength: 200, description: "An email address, part of one, or a name." },
|
|
1652
|
+
list_id: { ...LIST_ID, description: "Search only this audience." }
|
|
1653
|
+
},
|
|
1654
|
+
required: ["query"],
|
|
1655
|
+
additionalProperties: false
|
|
1656
|
+
},
|
|
1657
|
+
async run(args, h) {
|
|
1658
|
+
const { data } = await mc(h)({ path: "/3.0/search-members", query: { query: args.query, list_id: args.list_id, exclude_fields: "_links,exact_matches.members._links,full_search.members._links" } });
|
|
1659
|
+
const members = (part) => Array.isArray(part?.members) ? part.members.map(trimMember) : [];
|
|
1660
|
+
return {
|
|
1661
|
+
exact_matches: { total_items: data?.exact_matches?.total_items ?? 0, members: members(data?.exact_matches) },
|
|
1662
|
+
full_search: { total_items: data?.full_search?.total_items ?? 0, members: members(data?.full_search) }
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
},
|
|
1666
|
+
{
|
|
1667
|
+
name: "upsert_member",
|
|
1668
|
+
kind: "update",
|
|
1669
|
+
check: "get_member",
|
|
1670
|
+
title: "Add or update a Mailchimp member",
|
|
1671
|
+
description: "Adds a person to an audience with status_if_new, or updates the member with that email: merge fields, interests, language, VIP, and status when given. Use pending for double opt-in. Changing tags is update_member_tags.",
|
|
1672
|
+
inputSchema: {
|
|
1673
|
+
type: "object",
|
|
1674
|
+
properties: {
|
|
1675
|
+
list_id: LIST_ID,
|
|
1676
|
+
email: EMAIL,
|
|
1677
|
+
status_if_new: { ...STATUS, description: "The status if the person is not a member yet: subscribed, pending (double opt-in), transactional, unsubscribed or cleaned." },
|
|
1678
|
+
status: { ...STATUS, description: "A new status for an existing member too. Leave out to keep it." },
|
|
1679
|
+
merge_fields: MERGE_FIELDS,
|
|
1680
|
+
interests: { type: "object", description: 'Interest (group) ids set on or off, e.g. {"9143cf3bd1": true}.' },
|
|
1681
|
+
language: { type: "string", minLength: 2, maxLength: 10, description: "The member's language, e.g. en or fr." },
|
|
1682
|
+
vip: { type: "boolean", description: "true to mark the member as a VIP." },
|
|
1683
|
+
skip_merge_validation: { type: "boolean", default: false, description: "true to accept the member even when required merge fields are missing." }
|
|
1684
|
+
},
|
|
1685
|
+
required: ["list_id", "email", "status_if_new"],
|
|
1686
|
+
additionalProperties: false
|
|
1687
|
+
},
|
|
1688
|
+
async run(args, h) {
|
|
1689
|
+
const { data } = await mc(h)({
|
|
1690
|
+
method: "PUT",
|
|
1691
|
+
path: memberPath(args.list_id, args.email),
|
|
1692
|
+
query: { skip_merge_validation: args.skip_merge_validation || void 0 },
|
|
1693
|
+
json: compact({
|
|
1694
|
+
email_address: args.email,
|
|
1695
|
+
status_if_new: args.status_if_new,
|
|
1696
|
+
status: args.status,
|
|
1697
|
+
merge_fields: args.merge_fields,
|
|
1698
|
+
interests: args.interests,
|
|
1699
|
+
language: args.language,
|
|
1700
|
+
vip: args.vip
|
|
1701
|
+
}),
|
|
1702
|
+
write: true,
|
|
1703
|
+
errors: { 400: "Mailchimp did not accept the member" }
|
|
1704
|
+
});
|
|
1705
|
+
return trimMember(data);
|
|
1706
|
+
}
|
|
1707
|
+
},
|
|
1708
|
+
{
|
|
1709
|
+
name: "batch_upsert_members",
|
|
1710
|
+
kind: "update",
|
|
1711
|
+
check: "list_members",
|
|
1712
|
+
title: "Add or update Mailchimp members in bulk",
|
|
1713
|
+
description: "Adds up to 500 people to an audience in one call, and updates existing members when update_existing is true. Each member needs an email and a status (subscribed, pending, unsubscribed, cleaned or transactional). Returns the counts and each error.",
|
|
1714
|
+
inputSchema: {
|
|
1715
|
+
type: "object",
|
|
1716
|
+
properties: {
|
|
1717
|
+
list_id: LIST_ID,
|
|
1718
|
+
members: {
|
|
1719
|
+
type: "array",
|
|
1720
|
+
minItems: 1,
|
|
1721
|
+
maxItems: 500,
|
|
1722
|
+
description: 'The members, e.g. [{"email_address": "ann@example.com", "status": "subscribed", "merge_fields": {"FNAME": "Ann"}, "tags": ["VIP"]}].',
|
|
1723
|
+
items: {
|
|
1724
|
+
type: "object",
|
|
1725
|
+
properties: {
|
|
1726
|
+
email_address: EMAIL,
|
|
1727
|
+
status: STATUS,
|
|
1728
|
+
status_if_new: STATUS,
|
|
1729
|
+
merge_fields: MERGE_FIELDS,
|
|
1730
|
+
tags: { type: "array", items: { type: "string", minLength: 1, maxLength: 100 }, maxItems: 50, description: "Tags to add." },
|
|
1731
|
+
language: { type: "string", maxLength: 10 },
|
|
1732
|
+
vip: { type: "boolean" }
|
|
1733
|
+
},
|
|
1734
|
+
required: ["email_address"],
|
|
1735
|
+
additionalProperties: false
|
|
1736
|
+
}
|
|
1737
|
+
},
|
|
1738
|
+
update_existing: { type: "boolean", default: true, description: "true (default) to update members that exist; false leaves them unchanged and reports them as errors." }
|
|
1739
|
+
},
|
|
1740
|
+
required: ["list_id", "members"],
|
|
1741
|
+
additionalProperties: false
|
|
1742
|
+
},
|
|
1743
|
+
async run(args, h) {
|
|
1744
|
+
const missing = args.members.findIndex((member) => member["status"] === void 0 && member["status_if_new"] === void 0);
|
|
1745
|
+
if (missing !== -1) throw new ToolFailure(`members[${missing}] needs a status or a status_if_new. Nothing was changed.`);
|
|
1746
|
+
const { data } = await mc(h)({
|
|
1747
|
+
method: "POST",
|
|
1748
|
+
path: `/3.0/lists/${encodeURIComponent(args.list_id)}`,
|
|
1749
|
+
json: { members: args.members, update_existing: args.update_existing },
|
|
1750
|
+
write: true,
|
|
1751
|
+
errors: { 400: "Mailchimp did not accept the members" }
|
|
1752
|
+
});
|
|
1753
|
+
const emails = (items) => Array.isArray(items) ? items.map((member) => member?.email_address).filter(Boolean) : [];
|
|
1754
|
+
return compact({
|
|
1755
|
+
total_created: data?.total_created,
|
|
1756
|
+
total_updated: data?.total_updated,
|
|
1757
|
+
error_count: data?.error_count,
|
|
1758
|
+
new_members: emails(data?.new_members),
|
|
1759
|
+
updated_members: emails(data?.updated_members),
|
|
1760
|
+
errors: Array.isArray(data?.errors) && data.errors.length ? data.errors.map((error) => compact({ email_address: error?.email_address, error: error?.error, error_code: error?.error_code })) : void 0
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
},
|
|
1764
|
+
{
|
|
1765
|
+
name: "update_member_tags",
|
|
1766
|
+
kind: "update",
|
|
1767
|
+
check: "get_member",
|
|
1768
|
+
title: "Tag or untag a Mailchimp member",
|
|
1769
|
+
description: "Adds tags to and removes tags from one member of an audience. A tag that does not exist yet is created.",
|
|
1770
|
+
inputSchema: {
|
|
1771
|
+
type: "object",
|
|
1772
|
+
properties: {
|
|
1773
|
+
list_id: LIST_ID,
|
|
1774
|
+
email: EMAIL,
|
|
1775
|
+
add: { type: "array", items: { type: "string", minLength: 1, maxLength: 100 }, maxItems: 50, uniqueItems: true, description: "Tag names to add." },
|
|
1776
|
+
remove: { type: "array", items: { type: "string", minLength: 1, maxLength: 100 }, maxItems: 50, uniqueItems: true, description: "Tag names to remove." }
|
|
1777
|
+
},
|
|
1778
|
+
required: ["list_id", "email"],
|
|
1779
|
+
additionalProperties: false
|
|
1780
|
+
},
|
|
1781
|
+
async run(args, h) {
|
|
1782
|
+
const tags = [
|
|
1783
|
+
...(args.add ?? []).map((name2) => ({ name: name2, status: "active" })),
|
|
1784
|
+
...(args.remove ?? []).map((name2) => ({ name: name2, status: "inactive" }))
|
|
1785
|
+
];
|
|
1786
|
+
if (!tags.length) throw new ToolFailure("Give tags to add or to remove. Nothing was changed.");
|
|
1787
|
+
await mc(h)({
|
|
1788
|
+
method: "POST",
|
|
1789
|
+
path: `${memberPath(args.list_id, args.email)}/tags`,
|
|
1790
|
+
json: { tags },
|
|
1791
|
+
write: true,
|
|
1792
|
+
errors: { 404: "Mailchimp has no member with that email in this audience" }
|
|
1793
|
+
});
|
|
1794
|
+
return compact({ email: args.email, added: args.add, removed: args.remove });
|
|
1795
|
+
}
|
|
1796
|
+
},
|
|
1797
|
+
{
|
|
1798
|
+
name: "remove_member",
|
|
1799
|
+
kind: "delete",
|
|
1800
|
+
check: "get_member",
|
|
1801
|
+
title: "Archive or delete a Mailchimp member",
|
|
1802
|
+
description: "Archives a member of an audience (kept in Mailchimp, can be added back), or with permanent: true deletes the member and all their data for good (as for a privacy request); a permanently deleted address cannot be re-imported. To stop emails only, set status unsubscribed with upsert_member.",
|
|
1803
|
+
inputSchema: {
|
|
1804
|
+
type: "object",
|
|
1805
|
+
properties: {
|
|
1806
|
+
list_id: LIST_ID,
|
|
1807
|
+
email: EMAIL,
|
|
1808
|
+
permanent: { type: "boolean", default: false, description: "true to delete for good instead of archiving." }
|
|
1809
|
+
},
|
|
1810
|
+
required: ["list_id", "email"],
|
|
1811
|
+
additionalProperties: false
|
|
1812
|
+
},
|
|
1813
|
+
async run(args, h) {
|
|
1814
|
+
const path = memberPath(args.list_id, args.email);
|
|
1815
|
+
await mc(h)({
|
|
1816
|
+
method: args.permanent ? "POST" : "DELETE",
|
|
1817
|
+
path: args.permanent ? `${path}/actions/delete-permanent` : path,
|
|
1818
|
+
write: true,
|
|
1819
|
+
errors: { 404: "Mailchimp has no member with that email in this audience" }
|
|
1820
|
+
});
|
|
1821
|
+
return { email: args.email, [args.permanent ? "deleted" : "archived"]: true };
|
|
1822
|
+
}
|
|
1823
|
+
},
|
|
1824
|
+
{
|
|
1825
|
+
name: "list_campaigns",
|
|
1826
|
+
kind: "read",
|
|
1827
|
+
title: "List Mailchimp campaigns",
|
|
1828
|
+
description: "Campaigns, newest first, with status (save = draft, paused, schedule, sending, sent), subject, audience, recipients, send time and, for sent ones, opens and clicks. Filter by status, type, audience or send time. Pass nextCursor back as cursor for more.",
|
|
1829
|
+
inputSchema: {
|
|
1830
|
+
type: "object",
|
|
1831
|
+
properties: {
|
|
1832
|
+
status: { type: "string", enum: ["save", "paused", "schedule", "sending", "sent"], description: "save (drafts), paused, schedule, sending or sent." },
|
|
1833
|
+
type: { type: "string", enum: ["regular", "plaintext", "absplit", "rss", "variate"], description: "Only campaigns of this type." },
|
|
1834
|
+
list_id: { ...LIST_ID, description: "Only campaigns to this audience." },
|
|
1835
|
+
since_send_time: DATE_TIME("Only campaigns sent after this time"),
|
|
1836
|
+
before_send_time: DATE_TIME("Only campaigns sent before this time"),
|
|
1837
|
+
count: COUNT("Campaigns", 1e3, 25),
|
|
1838
|
+
cursor: CURSOR
|
|
1839
|
+
},
|
|
1840
|
+
additionalProperties: false
|
|
1841
|
+
},
|
|
1842
|
+
async run(args, h) {
|
|
1843
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
1844
|
+
key: "campaigns",
|
|
1845
|
+
path: "/3.0/campaigns",
|
|
1846
|
+
count: args.count,
|
|
1847
|
+
query: {
|
|
1848
|
+
status: args.status,
|
|
1849
|
+
type: args.type,
|
|
1850
|
+
list_id: args.list_id,
|
|
1851
|
+
since_send_time: args.since_send_time,
|
|
1852
|
+
before_send_time: args.before_send_time,
|
|
1853
|
+
sort_field: "create_time",
|
|
1854
|
+
sort_dir: "DESC"
|
|
1855
|
+
},
|
|
1856
|
+
trim: trimCampaign
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1859
|
+
},
|
|
1860
|
+
{
|
|
1861
|
+
name: "get_campaign",
|
|
1862
|
+
kind: "read",
|
|
1863
|
+
title: "Get a Mailchimp campaign",
|
|
1864
|
+
description: "One campaign with its settings, audience and segment, recipients, status and summary; include_content adds its HTML and plain text.",
|
|
1865
|
+
inputSchema: {
|
|
1866
|
+
type: "object",
|
|
1867
|
+
properties: {
|
|
1868
|
+
campaign_id: CAMPAIGN_ID,
|
|
1869
|
+
include_content: { type: "boolean", default: false, description: "true to add the HTML (cut at 20,000 characters) and plain text." }
|
|
1870
|
+
},
|
|
1871
|
+
required: ["campaign_id"],
|
|
1872
|
+
additionalProperties: false
|
|
1873
|
+
},
|
|
1874
|
+
async run(args, h) {
|
|
1875
|
+
const send = mc(h);
|
|
1876
|
+
const path = `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}`;
|
|
1877
|
+
const { data } = await send({ path, errors: { 404: "Mailchimp has no campaign with that id" } });
|
|
1878
|
+
const result2 = trimCampaign(data);
|
|
1879
|
+
if (args.include_content) {
|
|
1880
|
+
const content = await send({ path: `${path}/content` });
|
|
1881
|
+
result2["content"] = compact({ html: html(content.data?.html), plain_text: html(content.data?.plain_text) });
|
|
1882
|
+
}
|
|
1883
|
+
return result2;
|
|
1884
|
+
}
|
|
1885
|
+
},
|
|
1886
|
+
{
|
|
1887
|
+
name: "create_campaign",
|
|
1888
|
+
kind: "create",
|
|
1889
|
+
check: "list_campaigns",
|
|
1890
|
+
title: "Create a Mailchimp campaign",
|
|
1891
|
+
description: "Creates a draft campaign to an audience (or one of its segments) with its subject, preview text, From name and reply-to. Nothing is sent. Then set its body with set_campaign_content, check get_send_checklist, test with send_test_email, and send or schedule it.",
|
|
1892
|
+
inputSchema: {
|
|
1893
|
+
type: "object",
|
|
1894
|
+
properties: {
|
|
1895
|
+
type: {
|
|
1896
|
+
type: "string",
|
|
1897
|
+
enum: ["regular", "plaintext", "rss", "variate"],
|
|
1898
|
+
default: "regular",
|
|
1899
|
+
description: "regular (HTML, default), plaintext, rss (from a feed, with rss_opts) or variate (an A/B test, with variate_settings)."
|
|
1900
|
+
},
|
|
1901
|
+
...RECIPIENT_FIELDS,
|
|
1902
|
+
...SETTINGS_FIELDS,
|
|
1903
|
+
rss_opts: { type: "object", description: 'For rss: {"feed_url": "https://...", "frequency": "daily" | "weekly" | "monthly", "schedule": {...}}.' },
|
|
1904
|
+
variate_settings: { type: "object", description: 'For variate: {"winner_criteria": "opens" | "clicks" | "manual", "test_size": 20, "subject_lines": [...], ...}.' }
|
|
1905
|
+
},
|
|
1906
|
+
required: ["list_id", "subject_line", "from_name", "reply_to"],
|
|
1907
|
+
additionalProperties: false
|
|
1908
|
+
},
|
|
1909
|
+
async run(args, h) {
|
|
1910
|
+
if (args.type === "rss" && !args.rss_opts) throw new ToolFailure("An rss campaign needs rss_opts with its feed_url and frequency. Nothing was changed.");
|
|
1911
|
+
if (args.type === "variate" && !args.variate_settings) throw new ToolFailure("A variate campaign needs variate_settings. Nothing was changed.");
|
|
1912
|
+
const { data } = await mc(h)({
|
|
1913
|
+
method: "POST",
|
|
1914
|
+
path: "/3.0/campaigns",
|
|
1915
|
+
json: compact({ type: args.type, ...campaignParts(args), rss_opts: args.rss_opts, variate_settings: args.variate_settings }),
|
|
1916
|
+
write: true,
|
|
1917
|
+
errors: { 400: "Mailchimp did not accept the campaign" }
|
|
1918
|
+
});
|
|
1919
|
+
return trimCampaign(data);
|
|
1920
|
+
}
|
|
1921
|
+
},
|
|
1922
|
+
{
|
|
1923
|
+
name: "update_campaign",
|
|
1924
|
+
kind: "update",
|
|
1925
|
+
check: "get_campaign",
|
|
1926
|
+
title: "Update a Mailchimp campaign",
|
|
1927
|
+
description: "Changes a draft campaign's audience, segment or settings (subject, preview text, From name, reply-to, title): only the fields given.",
|
|
1928
|
+
inputSchema: {
|
|
1929
|
+
type: "object",
|
|
1930
|
+
properties: { campaign_id: CAMPAIGN_ID, ...RECIPIENT_FIELDS, ...SETTINGS_FIELDS },
|
|
1931
|
+
required: ["campaign_id"],
|
|
1932
|
+
additionalProperties: false
|
|
1933
|
+
},
|
|
1934
|
+
async run(args, h) {
|
|
1935
|
+
const body = campaignParts(args);
|
|
1936
|
+
if (!Object.keys(body).length) throw new ToolFailure("Nothing to change: give at least one setting or recipient field. Nothing was changed.");
|
|
1937
|
+
const { data } = await mc(h)({
|
|
1938
|
+
method: "PATCH",
|
|
1939
|
+
path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}`,
|
|
1940
|
+
json: body,
|
|
1941
|
+
write: true,
|
|
1942
|
+
errors: { 404: "Mailchimp has no campaign with that id", 400: "Mailchimp did not accept the change" }
|
|
1943
|
+
});
|
|
1944
|
+
return trimCampaign(data);
|
|
1945
|
+
}
|
|
1946
|
+
},
|
|
1947
|
+
{
|
|
1948
|
+
name: "set_campaign_content",
|
|
1949
|
+
kind: "update",
|
|
1950
|
+
check: "get_campaign",
|
|
1951
|
+
title: "Set a Mailchimp campaign's content",
|
|
1952
|
+
description: "Sets a draft campaign's body: HTML (with *|UNSUB|* for the unsubscribe link and merge tags like *|FNAME|*), plain text, a page Mailchimp imports from a URL, or a template with its editable sections. It replaces the current body.",
|
|
1953
|
+
inputSchema: {
|
|
1954
|
+
type: "object",
|
|
1955
|
+
properties: {
|
|
1956
|
+
campaign_id: CAMPAIGN_ID,
|
|
1957
|
+
html: { type: "string", minLength: 1, maxLength: 1e6, description: "The HTML body." },
|
|
1958
|
+
plain_text: { type: "string", minLength: 1, maxLength: 1e6, description: "The plain text body (generated from the HTML when left out)." },
|
|
1959
|
+
url: { type: "string", format: "uri", maxLength: 2e3, description: "A public page Mailchimp imports as the HTML body, instead of html." },
|
|
1960
|
+
template_id: { type: "integer", minimum: 1, description: "A template to use, instead of html (see list_templates)." },
|
|
1961
|
+
template_sections: { type: "object", description: 'With template_id: content for its mc:edit sections, e.g. {"body_content": "<p>Hello</p>"}.' }
|
|
1962
|
+
},
|
|
1963
|
+
required: ["campaign_id"],
|
|
1964
|
+
additionalProperties: false
|
|
1965
|
+
},
|
|
1966
|
+
async run(args, h) {
|
|
1967
|
+
const bodies = [args.html, args.url, args.template_id].filter((item) => item !== void 0).length;
|
|
1968
|
+
if (bodies > 1) throw new ToolFailure("Give one of html, url or template_id. Nothing was changed.");
|
|
1969
|
+
if (!bodies && args.plain_text === void 0) throw new ToolFailure("Give html, plain_text, url or template_id. Nothing was changed.");
|
|
1970
|
+
if (args.template_sections && args.template_id === void 0) throw new ToolFailure("template_sections go with a template_id. Nothing was changed.");
|
|
1971
|
+
const { data } = await mc(h)({
|
|
1972
|
+
method: "PUT",
|
|
1973
|
+
path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}/content`,
|
|
1974
|
+
json: compact({
|
|
1975
|
+
html: args.html,
|
|
1976
|
+
plain_text: args.plain_text,
|
|
1977
|
+
url: args.url,
|
|
1978
|
+
template: args.template_id !== void 0 ? compact({ id: args.template_id, sections: args.template_sections }) : void 0
|
|
1979
|
+
}),
|
|
1980
|
+
write: true,
|
|
1981
|
+
errors: { 404: "Mailchimp has no campaign with that id", 400: "Mailchimp did not accept the content" }
|
|
1982
|
+
});
|
|
1983
|
+
return compact({ campaign_id: args.campaign_id, updated: true, has_html: Boolean(data?.html), has_plain_text: Boolean(data?.plain_text) });
|
|
1984
|
+
}
|
|
1985
|
+
},
|
|
1986
|
+
{
|
|
1987
|
+
name: "get_send_checklist",
|
|
1988
|
+
kind: "read",
|
|
1989
|
+
title: "Check a Mailchimp campaign before sending",
|
|
1990
|
+
description: "Mailchimp's send checklist for a campaign: whether it is ready, and each item (audience, subject, content, sender) with its success, warning or error. Run it before send_campaign.",
|
|
1991
|
+
inputSchema: {
|
|
1992
|
+
type: "object",
|
|
1993
|
+
properties: { campaign_id: CAMPAIGN_ID },
|
|
1994
|
+
required: ["campaign_id"],
|
|
1995
|
+
additionalProperties: false
|
|
1996
|
+
},
|
|
1997
|
+
async run(args, h) {
|
|
1998
|
+
const { data } = await mc(h)({ path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}/send-checklist`, errors: { 404: "Mailchimp has no campaign with that id" } });
|
|
1999
|
+
const items = Array.isArray(data?.items) ? data.items : [];
|
|
2000
|
+
return { is_ready: data?.is_ready === true, items: items.map((item) => compact({ type: item?.type, heading: item?.heading, details: item?.details })) };
|
|
2001
|
+
}
|
|
2002
|
+
},
|
|
2003
|
+
{
|
|
2004
|
+
name: "send_test_email",
|
|
2005
|
+
kind: "create",
|
|
2006
|
+
check: "get_campaign",
|
|
2007
|
+
title: "Send a test of a Mailchimp campaign",
|
|
2008
|
+
description: "Sends a test of a campaign to up to 10 addresses, as HTML or plain text. Mailchimp limits how many tests an account may send a day.",
|
|
2009
|
+
inputSchema: {
|
|
2010
|
+
type: "object",
|
|
2011
|
+
properties: {
|
|
2012
|
+
campaign_id: CAMPAIGN_ID,
|
|
2013
|
+
emails: { type: "array", items: EMAIL, minItems: 1, maxItems: 10, uniqueItems: true, description: "Where to send the test." },
|
|
2014
|
+
send_type: { type: "string", enum: ["html", "plaintext"], default: "html", description: "html (default) or plaintext." }
|
|
2015
|
+
},
|
|
2016
|
+
required: ["campaign_id", "emails"],
|
|
2017
|
+
additionalProperties: false
|
|
2018
|
+
},
|
|
2019
|
+
async run(args, h) {
|
|
2020
|
+
await mc(h)({
|
|
2021
|
+
method: "POST",
|
|
2022
|
+
path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}/actions/test`,
|
|
2023
|
+
json: { test_emails: args.emails, send_type: args.send_type },
|
|
2024
|
+
write: true,
|
|
2025
|
+
errors: { 404: "Mailchimp has no campaign with that id", 400: "Mailchimp did not send the test" }
|
|
2026
|
+
});
|
|
2027
|
+
return { sent: true, campaign_id: args.campaign_id, to: args.emails };
|
|
2028
|
+
}
|
|
2029
|
+
},
|
|
2030
|
+
{
|
|
2031
|
+
name: "send_campaign",
|
|
2032
|
+
kind: "create",
|
|
2033
|
+
check: "get_campaign",
|
|
2034
|
+
title: "Send a Mailchimp campaign",
|
|
2035
|
+
description: "Sends a campaign to its audience right away. It cannot be undone. Run get_send_checklist first; a campaign that is not ready is refused by Mailchimp.",
|
|
2036
|
+
inputSchema: {
|
|
2037
|
+
type: "object",
|
|
2038
|
+
properties: { campaign_id: CAMPAIGN_ID },
|
|
2039
|
+
required: ["campaign_id"],
|
|
2040
|
+
additionalProperties: false
|
|
2041
|
+
},
|
|
2042
|
+
async run(args, h) {
|
|
2043
|
+
await mc(h)({
|
|
2044
|
+
method: "POST",
|
|
2045
|
+
path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}/actions/send`,
|
|
2046
|
+
write: true,
|
|
2047
|
+
errors: { 404: "Mailchimp has no campaign with that id", 400: "Mailchimp did not send the campaign" }
|
|
2048
|
+
});
|
|
2049
|
+
return { sent: true, campaign_id: args.campaign_id, note: "Mailchimp is sending it; get_campaign shows the status, get_campaign_report the results." };
|
|
2050
|
+
}
|
|
2051
|
+
},
|
|
2052
|
+
{
|
|
2053
|
+
name: "schedule_campaign",
|
|
2054
|
+
kind: "update",
|
|
2055
|
+
check: "get_campaign",
|
|
2056
|
+
title: "Schedule a Mailchimp campaign",
|
|
2057
|
+
description: "Schedules a campaign to send at a time on a quarter hour (:00, :15, :30 or :45), in UTC, at least 15 minutes ahead. timewarp sends at that local time in each subscriber's time zone (paid plans). unschedule_campaign stops it.",
|
|
2058
|
+
inputSchema: {
|
|
2059
|
+
type: "object",
|
|
2060
|
+
properties: {
|
|
2061
|
+
campaign_id: CAMPAIGN_ID,
|
|
2062
|
+
schedule_time: {
|
|
2063
|
+
type: "string",
|
|
2064
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:(00|15|30|45)(:00(\\.0+)?)?(Z|[+-]00:?00)$",
|
|
2065
|
+
description: "When to send, in UTC on a quarter hour, e.g. 2026-12-01T14:00:00Z."
|
|
2066
|
+
},
|
|
2067
|
+
timewarp: { type: "boolean", default: false, description: "true to send at that time in each subscriber's own time zone." }
|
|
2068
|
+
},
|
|
2069
|
+
required: ["campaign_id", "schedule_time"],
|
|
2070
|
+
additionalProperties: false
|
|
2071
|
+
},
|
|
2072
|
+
async run(args, h) {
|
|
2073
|
+
await mc(h)({
|
|
2074
|
+
method: "POST",
|
|
2075
|
+
path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}/actions/schedule`,
|
|
2076
|
+
json: { schedule_time: args.schedule_time, timewarp: args.timewarp },
|
|
2077
|
+
write: true,
|
|
2078
|
+
errors: { 404: "Mailchimp has no campaign with that id", 400: "Mailchimp did not schedule the campaign" }
|
|
2079
|
+
});
|
|
2080
|
+
return { scheduled: true, campaign_id: args.campaign_id, schedule_time: args.schedule_time };
|
|
2081
|
+
}
|
|
2082
|
+
},
|
|
2083
|
+
{
|
|
2084
|
+
name: "unschedule_campaign",
|
|
2085
|
+
kind: "update",
|
|
2086
|
+
check: "get_campaign",
|
|
2087
|
+
title: "Unschedule a Mailchimp campaign",
|
|
2088
|
+
description: "Stops a scheduled campaign from sending and turns it back into a draft.",
|
|
2089
|
+
inputSchema: {
|
|
2090
|
+
type: "object",
|
|
2091
|
+
properties: { campaign_id: CAMPAIGN_ID },
|
|
2092
|
+
required: ["campaign_id"],
|
|
2093
|
+
additionalProperties: false
|
|
2094
|
+
},
|
|
2095
|
+
async run(args, h) {
|
|
2096
|
+
await mc(h)({
|
|
2097
|
+
method: "POST",
|
|
2098
|
+
path: `/3.0/campaigns/${encodeURIComponent(args.campaign_id)}/actions/unschedule`,
|
|
2099
|
+
write: true,
|
|
2100
|
+
errors: { 404: "Mailchimp has no campaign with that id", 400: "Mailchimp could not unschedule the campaign" }
|
|
2101
|
+
});
|
|
2102
|
+
return { unscheduled: true, campaign_id: args.campaign_id };
|
|
2103
|
+
}
|
|
2104
|
+
},
|
|
2105
|
+
{
|
|
2106
|
+
name: "list_templates",
|
|
2107
|
+
kind: "read",
|
|
2108
|
+
title: "List Mailchimp templates",
|
|
2109
|
+
description: "Email templates with their ids, names, types and dates: your own (user, default), Mailchimp's base or gallery ones, or all. Pass nextCursor back as cursor for more.",
|
|
2110
|
+
inputSchema: {
|
|
2111
|
+
type: "object",
|
|
2112
|
+
properties: {
|
|
2113
|
+
type: { type: "string", enum: ["user", "base", "gallery"], default: "user", description: "user (default), base or gallery." },
|
|
2114
|
+
count: COUNT("Templates", 1e3, 50),
|
|
2115
|
+
cursor: CURSOR
|
|
2116
|
+
},
|
|
2117
|
+
additionalProperties: false
|
|
2118
|
+
},
|
|
2119
|
+
async run(args, h) {
|
|
2120
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
2121
|
+
key: "templates",
|
|
2122
|
+
path: "/3.0/templates",
|
|
2123
|
+
count: args.count,
|
|
2124
|
+
query: { type: args.type },
|
|
2125
|
+
trim: (template) => compact({
|
|
2126
|
+
id: template?.id,
|
|
2127
|
+
name: template?.name,
|
|
2128
|
+
type: template?.type,
|
|
2129
|
+
category: template?.category,
|
|
2130
|
+
drag_and_drop: template?.drag_and_drop,
|
|
2131
|
+
responsive: template?.responsive,
|
|
2132
|
+
active: template?.active,
|
|
2133
|
+
date_created: template?.date_created,
|
|
2134
|
+
date_edited: template?.date_edited
|
|
2135
|
+
})
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
},
|
|
2139
|
+
{
|
|
2140
|
+
name: "create_template",
|
|
2141
|
+
kind: "create",
|
|
2142
|
+
check: "list_templates",
|
|
2143
|
+
title: "Create a Mailchimp template",
|
|
2144
|
+
description: 'Creates an HTML email template. Editable areas are marked mc:edit="name"; *|UNSUB|* is the unsubscribe link and *|MC:SUBJECT|* the subject.',
|
|
2145
|
+
inputSchema: {
|
|
2146
|
+
type: "object",
|
|
2147
|
+
properties: {
|
|
2148
|
+
name: { type: "string", minLength: 1, maxLength: 50, description: "The template name, up to 50 characters." },
|
|
2149
|
+
html: { type: "string", minLength: 1, maxLength: 1e6, description: "The template HTML." },
|
|
2150
|
+
folder_id: { type: "string", maxLength: 100, description: "A template folder to put it in." }
|
|
2151
|
+
},
|
|
2152
|
+
required: ["name", "html"],
|
|
2153
|
+
additionalProperties: false
|
|
2154
|
+
},
|
|
2155
|
+
async run(args, h) {
|
|
2156
|
+
const { data } = await mc(h)({ method: "POST", path: "/3.0/templates", json: compact({ name: args.name, html: args.html, folder_id: args.folder_id }), write: true, errors: { 400: "Mailchimp did not accept the template" } });
|
|
2157
|
+
return compact({ id: data?.id, name: data?.name, type: data?.type, date_created: data?.date_created });
|
|
2158
|
+
}
|
|
2159
|
+
},
|
|
2160
|
+
{
|
|
2161
|
+
name: "list_segments",
|
|
2162
|
+
kind: "read",
|
|
2163
|
+
title: "List Mailchimp segments and tags",
|
|
2164
|
+
description: "The segments and tags of an audience with their ids, types (saved = conditions, static = tags or fixed lists) and member counts. Pass nextCursor back as cursor for more.",
|
|
2165
|
+
inputSchema: {
|
|
2166
|
+
type: "object",
|
|
2167
|
+
properties: {
|
|
2168
|
+
list_id: LIST_ID,
|
|
2169
|
+
type: { type: "string", enum: ["saved", "static", "fuzzy"], description: "Only saved segments, static ones (tags), or fuzzy ones." },
|
|
2170
|
+
count: COUNT("Segments", 1e3, 50),
|
|
2171
|
+
cursor: CURSOR
|
|
2172
|
+
},
|
|
2173
|
+
required: ["list_id"],
|
|
2174
|
+
additionalProperties: false
|
|
2175
|
+
},
|
|
2176
|
+
async run(args, h) {
|
|
2177
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
2178
|
+
key: "segments",
|
|
2179
|
+
path: `/3.0/lists/${encodeURIComponent(args.list_id)}/segments`,
|
|
2180
|
+
count: args.count,
|
|
2181
|
+
query: { type: args.type },
|
|
2182
|
+
trim: (segment) => compact({ id: segment?.id, name: segment?.name, type: segment?.type, member_count: segment?.member_count, created_at: segment?.created_at, updated_at: segment?.updated_at })
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
},
|
|
2186
|
+
{
|
|
2187
|
+
name: "create_segment",
|
|
2188
|
+
kind: "create",
|
|
2189
|
+
check: "list_segments",
|
|
2190
|
+
title: "Create a Mailchimp segment",
|
|
2191
|
+
description: 'Creates a segment in an audience: a static one (a tag) with the given member emails, or a saved one that matches conditions, e.g. {"match": "all", "conditions": [{"condition_type": "Aim", "field": "aim", "op": "open", "value": "any"}]}.',
|
|
2192
|
+
inputSchema: {
|
|
2193
|
+
type: "object",
|
|
2194
|
+
properties: {
|
|
2195
|
+
list_id: LIST_ID,
|
|
2196
|
+
name: { type: "string", minLength: 1, maxLength: 100, description: "The segment or tag name." },
|
|
2197
|
+
static_segment: { type: "array", items: EMAIL, maxItems: 500, uniqueItems: true, description: "Member emails for a static segment (tag); an empty list makes an empty tag." },
|
|
2198
|
+
options: { type: "object", description: 'Conditions for a saved segment: {"match": "any" | "all", "conditions": [...]}.' }
|
|
2199
|
+
},
|
|
2200
|
+
required: ["list_id", "name"],
|
|
2201
|
+
additionalProperties: false
|
|
2202
|
+
},
|
|
2203
|
+
async run(args, h) {
|
|
2204
|
+
if (args.static_segment === void 0 === (args.options === void 0)) throw new ToolFailure("Give static_segment or options (one of the two). Nothing was changed.");
|
|
2205
|
+
const { data } = await mc(h)({
|
|
2206
|
+
method: "POST",
|
|
2207
|
+
path: `/3.0/lists/${encodeURIComponent(args.list_id)}/segments`,
|
|
2208
|
+
json: compact({ name: args.name, static_segment: args.static_segment, options: args.options }),
|
|
2209
|
+
write: true,
|
|
2210
|
+
errors: { 400: "Mailchimp did not accept the segment" }
|
|
2211
|
+
});
|
|
2212
|
+
return compact({ id: data?.id, name: data?.name, type: data?.type, member_count: data?.member_count });
|
|
2213
|
+
}
|
|
2214
|
+
},
|
|
2215
|
+
{
|
|
2216
|
+
name: "update_segment_members",
|
|
2217
|
+
kind: "update",
|
|
2218
|
+
check: "list_segments",
|
|
2219
|
+
title: "Add or remove members of a Mailchimp static segment",
|
|
2220
|
+
description: "Adds members to and removes members from a static segment or tag, by email, up to 500 each. The people must already be members of the audience.",
|
|
2221
|
+
inputSchema: {
|
|
2222
|
+
type: "object",
|
|
2223
|
+
properties: {
|
|
2224
|
+
list_id: LIST_ID,
|
|
2225
|
+
segment_id: { type: "integer", minimum: 1, description: "The segment or tag id (see list_segments)." },
|
|
2226
|
+
add: { type: "array", items: EMAIL, maxItems: 500, uniqueItems: true, description: "Member emails to add." },
|
|
2227
|
+
remove: { type: "array", items: EMAIL, maxItems: 500, uniqueItems: true, description: "Member emails to remove." }
|
|
2228
|
+
},
|
|
2229
|
+
required: ["list_id", "segment_id"],
|
|
2230
|
+
additionalProperties: false
|
|
2231
|
+
},
|
|
2232
|
+
async run(args, h) {
|
|
2233
|
+
if (!args.add?.length && !args.remove?.length) throw new ToolFailure("Give emails to add or to remove. Nothing was changed.");
|
|
2234
|
+
const { data } = await mc(h)({
|
|
2235
|
+
method: "POST",
|
|
2236
|
+
path: `/3.0/lists/${encodeURIComponent(args.list_id)}/segments/${args.segment_id}`,
|
|
2237
|
+
json: compact({ members_to_add: args.add, members_to_remove: args.remove }),
|
|
2238
|
+
write: true,
|
|
2239
|
+
errors: { 404: "Mailchimp has no such segment in this audience", 400: "Mailchimp did not change the segment" }
|
|
2240
|
+
});
|
|
2241
|
+
const emails = (items) => Array.isArray(items) ? items.map((member) => member?.email_address).filter(Boolean) : void 0;
|
|
2242
|
+
return compact({
|
|
2243
|
+
total_added: data?.total_added,
|
|
2244
|
+
total_removed: data?.total_removed,
|
|
2245
|
+
error_count: data?.error_count,
|
|
2246
|
+
members_added: emails(data?.members_added),
|
|
2247
|
+
members_removed: emails(data?.members_removed),
|
|
2248
|
+
errors: Array.isArray(data?.errors) && data.errors.length ? data.errors : void 0
|
|
2249
|
+
});
|
|
2250
|
+
}
|
|
2251
|
+
},
|
|
2252
|
+
{
|
|
2253
|
+
name: "list_reports",
|
|
2254
|
+
kind: "read",
|
|
2255
|
+
title: "List Mailchimp campaign reports",
|
|
2256
|
+
description: "Results of sent campaigns, newest first: emails sent, opens and clicks with rates, bounces, unsubscribes, abuse reports and audience averages. Pass nextCursor back as cursor for more.",
|
|
2257
|
+
inputSchema: {
|
|
2258
|
+
type: "object",
|
|
2259
|
+
properties: {
|
|
2260
|
+
since_send_time: DATE_TIME("Only campaigns sent after this time"),
|
|
2261
|
+
before_send_time: DATE_TIME("Only campaigns sent before this time"),
|
|
2262
|
+
count: COUNT("Reports", 1e3, 20),
|
|
2263
|
+
cursor: CURSOR
|
|
2264
|
+
},
|
|
2265
|
+
additionalProperties: false
|
|
2266
|
+
},
|
|
2267
|
+
async run(args, h) {
|
|
2268
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
2269
|
+
key: "reports",
|
|
2270
|
+
path: "/3.0/reports",
|
|
2271
|
+
count: args.count,
|
|
2272
|
+
query: { since_send_time: args.since_send_time, before_send_time: args.before_send_time },
|
|
2273
|
+
trim: trimReport
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
},
|
|
2277
|
+
{
|
|
2278
|
+
name: "get_campaign_report",
|
|
2279
|
+
kind: "read",
|
|
2280
|
+
title: "Get a Mailchimp campaign report",
|
|
2281
|
+
description: "The results of one sent campaign: emails sent, opens and clicks (totals, unique, rates), bounces, unsubscribes, forwards, abuse reports, audience averages and e-commerce totals.",
|
|
2282
|
+
inputSchema: {
|
|
2283
|
+
type: "object",
|
|
2284
|
+
properties: { campaign_id: CAMPAIGN_ID },
|
|
2285
|
+
required: ["campaign_id"],
|
|
2286
|
+
additionalProperties: false
|
|
2287
|
+
},
|
|
2288
|
+
async run(args, h) {
|
|
2289
|
+
const { data } = await mc(h)({ path: `/3.0/reports/${encodeURIComponent(args.campaign_id)}`, errors: { 404: "Mailchimp has no report for that campaign (it may not be sent yet)" } });
|
|
2290
|
+
return trimReport(data);
|
|
2291
|
+
}
|
|
2292
|
+
},
|
|
2293
|
+
{
|
|
2294
|
+
name: "get_report_details",
|
|
2295
|
+
kind: "read",
|
|
2296
|
+
title: "Get details of a Mailchimp campaign report",
|
|
2297
|
+
description: "One part of a sent campaign's report: click-details (each link's clicks), open-details (who opened), unsubscribed, email-activity (each recipient's events), sent-to, domain-performance, locations, abuse-reports or advice. Pass nextCursor back as cursor for more.",
|
|
2298
|
+
inputSchema: {
|
|
2299
|
+
type: "object",
|
|
2300
|
+
properties: {
|
|
2301
|
+
campaign_id: CAMPAIGN_ID,
|
|
2302
|
+
kind: { type: "string", enum: Object.keys(REPORT_DETAILS), description: "Which part of the report." },
|
|
2303
|
+
count: COUNT("Items", 1e3, 50),
|
|
2304
|
+
cursor: CURSOR
|
|
2305
|
+
},
|
|
2306
|
+
required: ["campaign_id", "kind"],
|
|
2307
|
+
additionalProperties: false
|
|
2308
|
+
},
|
|
2309
|
+
async run(args, h) {
|
|
2310
|
+
const field = REPORT_DETAILS[args.kind];
|
|
2311
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
2312
|
+
key: field,
|
|
2313
|
+
path: `/3.0/reports/${encodeURIComponent(args.campaign_id)}/${args.kind}`,
|
|
2314
|
+
count: args.count,
|
|
2315
|
+
trim: (item) => {
|
|
2316
|
+
const plain = stripLinks(item);
|
|
2317
|
+
delete plain["campaign_id"];
|
|
2318
|
+
delete plain["list_id"];
|
|
2319
|
+
delete plain["list_is_active"];
|
|
2320
|
+
return compact(plain);
|
|
2321
|
+
}
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
},
|
|
2325
|
+
{
|
|
2326
|
+
name: "list_automations",
|
|
2327
|
+
kind: "read",
|
|
2328
|
+
title: "List Mailchimp classic automations",
|
|
2329
|
+
description: "Classic automations with their ids, titles, status (save, paused, sending), audience, emails sent and open and click rates. Pass nextCursor back as cursor for more.",
|
|
2330
|
+
inputSchema: {
|
|
2331
|
+
type: "object",
|
|
2332
|
+
properties: {
|
|
2333
|
+
status: { type: "string", enum: ["save", "paused", "sending"], description: "Only automations with this status." },
|
|
2334
|
+
count: COUNT("Automations", 1e3, 50),
|
|
2335
|
+
cursor: CURSOR
|
|
2336
|
+
},
|
|
2337
|
+
additionalProperties: false
|
|
2338
|
+
},
|
|
2339
|
+
async run(args, h) {
|
|
2340
|
+
return offsetList(h, mc(h), args.cursor, {
|
|
2341
|
+
key: "automations",
|
|
2342
|
+
path: "/3.0/automations",
|
|
2343
|
+
count: args.count,
|
|
2344
|
+
query: { status: args.status },
|
|
2345
|
+
trim: (automation) => compact({
|
|
2346
|
+
id: automation?.id,
|
|
2347
|
+
title: automation?.settings?.title,
|
|
2348
|
+
status: automation?.status,
|
|
2349
|
+
create_time: automation?.create_time,
|
|
2350
|
+
start_time: automation?.start_time,
|
|
2351
|
+
emails_sent: automation?.emails_sent,
|
|
2352
|
+
list_id: automation?.recipients?.list_id,
|
|
2353
|
+
list_name: automation?.recipients?.list_name,
|
|
2354
|
+
report_summary: automation?.report_summary
|
|
2355
|
+
})
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
},
|
|
2359
|
+
{
|
|
2360
|
+
name: "set_automation_state",
|
|
2361
|
+
kind: "update",
|
|
2362
|
+
check: "list_automations",
|
|
2363
|
+
title: "Pause or start a Mailchimp automation",
|
|
2364
|
+
description: "Pauses all emails of a classic automation, or starts them again.",
|
|
2365
|
+
inputSchema: {
|
|
2366
|
+
type: "object",
|
|
2367
|
+
properties: {
|
|
2368
|
+
automation_id: { ...ID, description: "The automation id (see list_automations)." },
|
|
2369
|
+
action: { type: "string", enum: ["pause", "start"], description: "pause or start all of its emails." }
|
|
2370
|
+
},
|
|
2371
|
+
required: ["automation_id", "action"],
|
|
2372
|
+
additionalProperties: false
|
|
2373
|
+
},
|
|
2374
|
+
async run(args, h) {
|
|
2375
|
+
await mc(h)({
|
|
2376
|
+
method: "POST",
|
|
2377
|
+
path: `/3.0/automations/${encodeURIComponent(args.automation_id)}/actions/${args.action}-all-emails`,
|
|
2378
|
+
write: true,
|
|
2379
|
+
errors: { 404: "Mailchimp has no automation with that id", 400: `Mailchimp could not ${args.action} the automation` }
|
|
2380
|
+
});
|
|
2381
|
+
return { automation_id: args.automation_id, [args.action === "pause" ? "paused" : "started"]: true };
|
|
2382
|
+
}
|
|
2383
|
+
},
|
|
2384
|
+
...apiTools({
|
|
2385
|
+
label: LABEL2,
|
|
2386
|
+
description: "The Mailchimp Marketing API 3.0 at the connection's data center (https://<dc>.api.mailchimp.com/3.0), with its credentials: paths start with /3.0/, such as /3.0/lists/{list_id}/merge-fields, /3.0/lists/{list_id}/interest-categories, /3.0/lists/{list_id}/activity, /3.0/automations/{id}/emails, /3.0/campaigns/{id}/actions/replicate or /3.0/file-manager/files. Members are addressed by the MD5 of the lower-cased email. Reference: https://mailchimp.com/developer/marketing/api/.",
|
|
2387
|
+
basePath: "/3.0/",
|
|
2388
|
+
send: (request, h) => h.api({ ...request, origin: originFor(h) }),
|
|
2389
|
+
guard(request) {
|
|
2390
|
+
const parts = routedParts(request.segments);
|
|
2391
|
+
if (parts[0] !== "3.0") throw new ToolFailure("The path must stay under /3.0/. Nothing was sent.");
|
|
2392
|
+
if (parts.includes("authorized-apps")) throw new ToolFailure(NO_AUTHORIZED_APPS);
|
|
2393
|
+
if (request.method === "POST" && parts[1] === "batches" && parts.length === 2) {
|
|
2394
|
+
if (!request.json) throw new ToolFailure("Send a Mailchimp batch as json, with its operations. Nothing was sent.");
|
|
2395
|
+
const operations = Array.isArray(request.json["operations"]) ? request.json["operations"] : [];
|
|
2396
|
+
if (operations.some((operation) => namesAuthorizedApps(operation?.path))) throw new ToolFailure(NO_AUTHORIZED_APPS);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
})
|
|
2400
|
+
]
|
|
2401
|
+
});
|
|
2402
|
+
module.exports = connector;
|