@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +1 -1
@@ -0,0 +1,2188 @@
1
+ /* sendgrid connector module (MIT License). Built from src/vendors/sendgrid; 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/sendgrid/shape.ts
1091
+ function compact(value) {
1092
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1093
+ }
1094
+ var HTML_LIMIT = 2e4;
1095
+ function html(text) {
1096
+ return typeof text === "string" && text ? truncate(text, HTML_LIMIT) : void 0;
1097
+ }
1098
+ function isoFromUnix(value) {
1099
+ return typeof value === "number" && Number.isFinite(value) ? new Date(value * 1e3).toISOString() : void 0;
1100
+ }
1101
+ function trimContact(contact) {
1102
+ const custom = contact?.custom_fields && typeof contact.custom_fields === "object" && Object.keys(contact.custom_fields).length ? contact.custom_fields : void 0;
1103
+ return compact({
1104
+ id: contact?.id,
1105
+ email: contact?.email,
1106
+ first_name: contact?.first_name,
1107
+ last_name: contact?.last_name,
1108
+ phone_number: contact?.phone_number,
1109
+ external_id: contact?.external_id,
1110
+ alternate_emails: Array.isArray(contact?.alternate_emails) && contact.alternate_emails.length ? contact.alternate_emails : void 0,
1111
+ city: contact?.city,
1112
+ state_province_region: contact?.state_province_region,
1113
+ country: contact?.country,
1114
+ postal_code: contact?.postal_code,
1115
+ list_ids: Array.isArray(contact?.list_ids) && contact.list_ids.length ? contact.list_ids : void 0,
1116
+ segment_ids: Array.isArray(contact?.segment_ids) && contact.segment_ids.length ? contact.segment_ids : void 0,
1117
+ custom_fields: custom,
1118
+ created_at: contact?.created_at,
1119
+ updated_at: contact?.updated_at
1120
+ });
1121
+ }
1122
+ function trimSingleSend(send, options = {}) {
1123
+ const config = send?.email_config;
1124
+ return compact({
1125
+ id: send?.id,
1126
+ name: send?.name,
1127
+ status: send?.status,
1128
+ categories: Array.isArray(send?.categories) && send.categories.length ? send.categories : void 0,
1129
+ send_at: send?.send_at,
1130
+ send_to: send?.send_to,
1131
+ is_abtest: send?.is_abtest,
1132
+ created_at: send?.created_at,
1133
+ updated_at: send?.updated_at,
1134
+ email_config: config ? compact({
1135
+ subject: config.subject,
1136
+ sender_id: config.sender_id,
1137
+ suppression_group_id: config.suppression_group_id,
1138
+ custom_unsubscribe_url: config.custom_unsubscribe_url,
1139
+ design_id: config.design_id,
1140
+ editor: config.editor,
1141
+ ip_pool: config.ip_pool,
1142
+ generate_plain_content: config.generate_plain_content,
1143
+ html_content: options.html ? html(config.html_content) : void 0,
1144
+ plain_content: options.html ? html(config.plain_content) : void 0
1145
+ }) : void 0,
1146
+ warnings: Array.isArray(send?.warnings) && send.warnings.length ? send.warnings : void 0
1147
+ });
1148
+ }
1149
+ function trimTemplate(template, options = {}) {
1150
+ const versions = Array.isArray(template?.versions) ? template.versions : [];
1151
+ return compact({
1152
+ id: template?.id,
1153
+ name: template?.name,
1154
+ generation: template?.generation,
1155
+ updated_at: template?.updated_at,
1156
+ versions: versions.map((version) => compact({
1157
+ id: version?.id,
1158
+ name: version?.name,
1159
+ active: version?.active,
1160
+ subject: version?.subject,
1161
+ editor: version?.editor,
1162
+ updated_at: version?.updated_at,
1163
+ // The HTML of the version in use, when asked for: other versions are summarized.
1164
+ html_content: options.html && version?.active === 1 ? html(version?.html_content) : void 0,
1165
+ plain_content: options.html && version?.active === 1 ? html(version?.plain_content) : void 0
1166
+ }))
1167
+ });
1168
+ }
1169
+ function nextToken(next) {
1170
+ if (typeof next !== "string" || !next) return void 0;
1171
+ try {
1172
+ return new URL(next).searchParams.get("page_token") ?? void 0;
1173
+ } catch {
1174
+ return void 0;
1175
+ }
1176
+ }
1177
+ async function tokenList(h, cursor, options) {
1178
+ const state = h.cursor(cursor);
1179
+ const token = typeof state?.["p"] === "string" ? state["p"] : void 0;
1180
+ const size = typeof state?.["n"] === "number" ? state["n"] : options.pageSize;
1181
+ const skip = typeof state?.["s"] === "number" ? state["s"] : 0;
1182
+ const { data } = await h.api({ path: options.path, query: { ...options.query, page_size: size, page_token: token } });
1183
+ const items = Array.isArray(data?.[options.listField ?? "result"]) ? data[options.listField ?? "result"] : [];
1184
+ const next = nextToken(data?._metadata?.next);
1185
+ const count = typeof data?._metadata?.count === "number" ? data._metadata.count : void 0;
1186
+ return h.page({
1187
+ key: options.key,
1188
+ items: items.map(options.trim).slice(skip),
1189
+ extra: count !== void 0 ? { total: count } : {},
1190
+ resumeAt: (index) => h.makeCursor({ ...token ? { p: token } : {}, n: size, s: skip + index }),
1191
+ ...next && items.length ? { nextPage: h.makeCursor({ p: next, n: size, s: 0 }) } : {}
1192
+ });
1193
+ }
1194
+ async function offsetList(h, cursor, options) {
1195
+ const state = h.cursor(cursor);
1196
+ const offset = typeof state?.["o"] === "number" ? state["o"] : 0;
1197
+ const limit = typeof state?.["n"] === "number" ? state["n"] : options.limit;
1198
+ const skip = typeof state?.["s"] === "number" ? state["s"] : 0;
1199
+ const { data } = await h.api({ path: options.path, query: { ...options.query, limit, offset } });
1200
+ const items = options.list ? options.list(data) : Array.isArray(data) ? data : [];
1201
+ return h.page({
1202
+ key: options.key,
1203
+ items: items.map(options.trim).slice(skip),
1204
+ resumeAt: (index) => h.makeCursor({ o: offset, n: limit, s: skip + index }),
1205
+ ...items.length >= limit ? { nextPage: h.makeCursor({ o: offset + limit, n: limit, s: 0 }) } : {}
1206
+ });
1207
+ }
1208
+ function base64(bytes) {
1209
+ let binary = "";
1210
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
1211
+ return btoa(binary);
1212
+ }
1213
+ var TYPES = {
1214
+ pdf: "application/pdf",
1215
+ csv: "text/csv",
1216
+ txt: "text/plain",
1217
+ html: "text/html",
1218
+ ics: "text/calendar",
1219
+ json: "application/json",
1220
+ xml: "application/xml",
1221
+ zip: "application/zip",
1222
+ png: "image/png",
1223
+ jpg: "image/jpeg",
1224
+ jpeg: "image/jpeg",
1225
+ gif: "image/gif",
1226
+ webp: "image/webp",
1227
+ svg: "image/svg+xml",
1228
+ doc: "application/msword",
1229
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1230
+ xls: "application/vnd.ms-excel",
1231
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1232
+ ppt: "application/vnd.ms-powerpoint",
1233
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1234
+ mp3: "audio/mpeg",
1235
+ mp4: "video/mp4"
1236
+ };
1237
+ function typeFromName(name2) {
1238
+ const extension = /\.([A-Za-z0-9]{1,8})$/.exec(name2)?.[1]?.toLowerCase() ?? "";
1239
+ return TYPES[extension] ?? "application/octet-stream";
1240
+ }
1241
+
1242
+ // src/vendors/sendgrid/index.ts
1243
+ var LABEL2 = "SendGrid";
1244
+ var EMAIL = {
1245
+ type: "string",
1246
+ minLength: 3,
1247
+ maxLength: 320,
1248
+ pattern: "^[^@\\s]+@[^@\\s]+$",
1249
+ description: "An email address."
1250
+ };
1251
+ var PERSON = {
1252
+ type: "object",
1253
+ properties: { email: EMAIL, name: { type: "string", maxLength: 200, description: "The display name." } },
1254
+ required: ["email"],
1255
+ additionalProperties: false
1256
+ };
1257
+ var PEOPLE = (what, max) => ({
1258
+ type: "array",
1259
+ items: PERSON,
1260
+ maxItems: max,
1261
+ description: `${what}: [{"email": "ann@example.com", "name": "Ann"}], up to ${max}.`
1262
+ });
1263
+ var CURSOR = { type: "string", description: "nextCursor from the previous result; pass the other arguments unchanged." };
1264
+ var UUID = { type: "string", pattern: "^[A-Za-z0-9-]{8,64}$", description: "A SendGrid id." };
1265
+ var DATE = (what) => ({ type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: `${what}, as YYYY-MM-DD.` });
1266
+ var TEMPLATE_ID = {
1267
+ type: "string",
1268
+ pattern: "^(d-)?[A-Za-z0-9-]{8,64}$",
1269
+ description: "A template id, such as d-0123456789abcdef0123456789abcdef for a dynamic template (see list_templates)."
1270
+ };
1271
+ var ATTACHMENT_MAX = 10 * 1024 * 1024;
1272
+ var ATTACHMENTS_TOTAL_MAX = 20 * 1024 * 1024;
1273
+ var SUPPRESSIONS = ["bounces", "blocks", "spam_reports", "invalid_emails", "unsubscribes"];
1274
+ var SINGLE_SEND_FIELDS = {
1275
+ name: { type: "string", minLength: 1, maxLength: 100, description: "The Single Send name (recipients do not see it)." },
1276
+ subject: { type: "string", minLength: 1, maxLength: 500, description: "The subject line." },
1277
+ html_content: { type: "string", minLength: 1, maxLength: 1e6, description: "The HTML body; {{{unsubscribe}}} and {{{Weblink}}} work in it." },
1278
+ plain_content: { type: "string", maxLength: 1e6, description: "The plain text body (generated from the HTML when left out)." },
1279
+ design_id: { type: "string", maxLength: 100, description: "A saved design to use as the body, instead of html_content." },
1280
+ sender_id: { type: "integer", minimum: 1, description: "The verified sender (see list_senders)." },
1281
+ suppression_group_id: { type: "integer", minimum: 1, description: "The unsubscribe group (see list_unsubscribe_groups). Scheduling needs this or custom_unsubscribe_url." },
1282
+ custom_unsubscribe_url: { type: "string", format: "uri", maxLength: 2e3, description: "Your own unsubscribe page, instead of a suppression group." },
1283
+ list_ids: { type: "array", items: UUID, maxItems: 50, uniqueItems: true, description: "The lists to send to (see list_lists)." },
1284
+ segment_ids: { type: "array", items: UUID, maxItems: 10, uniqueItems: true, description: "Segments to send to." },
1285
+ send_to_all: { type: "boolean", description: "true to send to all contacts instead of lists or segments." },
1286
+ categories: { type: "array", items: { type: "string", minLength: 1, maxLength: 255 }, maxItems: 10, description: "Categories for statistics." },
1287
+ ip_pool: { type: "string", maxLength: 64, description: "The IP pool to send from." }
1288
+ };
1289
+ function singleSendBody(args) {
1290
+ const sendTo = compact({ list_ids: args.list_ids, segment_ids: args.segment_ids, all: args.send_to_all });
1291
+ const config = compact({
1292
+ subject: args.subject,
1293
+ html_content: args.html_content,
1294
+ plain_content: args.plain_content,
1295
+ generate_plain_content: args.html_content !== void 0 && args.plain_content === void 0 ? true : void 0,
1296
+ design_id: args.design_id,
1297
+ editor: args.html_content !== void 0 ? "code" : void 0,
1298
+ sender_id: args.sender_id,
1299
+ suppression_group_id: args.suppression_group_id,
1300
+ custom_unsubscribe_url: args.custom_unsubscribe_url,
1301
+ ip_pool: args.ip_pool
1302
+ });
1303
+ return compact({
1304
+ name: args.name,
1305
+ categories: args.categories,
1306
+ send_to: Object.keys(sendTo).length ? sendTo : void 0,
1307
+ email_config: Object.keys(config).length ? config : void 0
1308
+ });
1309
+ }
1310
+ async function attachmentsFor(h, attachments) {
1311
+ const out = [];
1312
+ let total = 0;
1313
+ for (const attachment of attachments) {
1314
+ if (attachment.disposition === "inline" && !attachment.content_id) {
1315
+ throw new ToolFailure(`The inline attachment ${attachment.filename} needs a content_id to be shown in the HTML (cid:...). Nothing was sent.`);
1316
+ }
1317
+ const { bytes } = await h.media(attachment.url, { what: `attachment ${attachment.filename}`, maxBytes: ATTACHMENT_MAX });
1318
+ total += bytes.byteLength;
1319
+ if (total > ATTACHMENTS_TOTAL_MAX) {
1320
+ throw new ToolFailure("The attachments together are larger than 20 MB, more than a SendGrid email can carry. Nothing was sent.");
1321
+ }
1322
+ out.push(compact({
1323
+ content: base64(bytes),
1324
+ filename: attachment.filename,
1325
+ type: attachment.type ?? typeFromName(attachment.filename),
1326
+ disposition: attachment.disposition,
1327
+ content_id: attachment.content_id
1328
+ }));
1329
+ }
1330
+ return out;
1331
+ }
1332
+ function routedParts(segments) {
1333
+ const parts = [];
1334
+ for (const piece of segments.join("/").split(/[\\/]/)) {
1335
+ const part = (piece.split(";")[0] ?? "").toLowerCase();
1336
+ if (part === "" || part === ".") continue;
1337
+ if (part === "..") parts.pop();
1338
+ else parts.push(part);
1339
+ }
1340
+ return parts;
1341
+ }
1342
+ var ADMIN_AREAS = /* @__PURE__ */ new Set(["teammates", "subusers", "access_settings", "sso", "scopes"]);
1343
+ var SIGN_IN_DETAILS = /* @__PURE__ */ new Set(["email", "username", "password"]);
1344
+ var connector = defineConnector({
1345
+ vendor: "sendgrid",
1346
+ label: LABEL2,
1347
+ origins: ["https://api.sendgrid.com"],
1348
+ credentials: ["apikey"],
1349
+ credentialLabels: { apikey: "SendGrid API key" },
1350
+ authHeaders: (credentials) => ({ authorization: `Bearer ${credentials["apikey"]}` }),
1351
+ tools: [
1352
+ {
1353
+ name: "get_account",
1354
+ kind: "read",
1355
+ title: "Check the SendGrid API key",
1356
+ description: "What the connected API key may do: its number of scopes and whether it can send mail, manage Marketing Campaigns, templates, senders, suppressions and statistics, plus the account type and sender reputation when the key may read them. A quick connection check.",
1357
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1358
+ async run(_args, h) {
1359
+ const { data } = await h.api({ path: "/v3/scopes" });
1360
+ const scopes = Array.isArray(data?.scopes) ? data.scopes.map(String) : [];
1361
+ const has = (prefix) => scopes.some((scope) => scope === prefix || scope.startsWith(`${prefix}.`));
1362
+ const result2 = {
1363
+ scopes: scopes.length,
1364
+ can: {
1365
+ send_mail: has("mail.send"),
1366
+ marketing: has("marketing"),
1367
+ templates: has("templates"),
1368
+ senders: has("verified_senders") || has("marketing.senders"),
1369
+ suppressions: has("suppression") || has("asm"),
1370
+ stats: has("stats"),
1371
+ email_activity: has("messages")
1372
+ }
1373
+ };
1374
+ if (scopes.includes("user.account.read")) {
1375
+ const account = await h.api({ path: "/v3/user/account" });
1376
+ result2["account"] = compact({ type: account.data?.type, reputation: account.data?.reputation });
1377
+ }
1378
+ return result2;
1379
+ }
1380
+ },
1381
+ {
1382
+ name: "send_email",
1383
+ kind: "create",
1384
+ check: "search_email_activity",
1385
+ title: "Send an email with SendGrid",
1386
+ description: "Sends one email: to up to 1,000 recipients (each gets their own copy unless separate_copies is false), with cc, bcc, reply-to, and a subject with a text and/or HTML body, or a dynamic template_id with dynamic_template_data. Attachments are public https URLs (up to 10 files, 20 MB in all). send_at schedules it up to 72 hours ahead; sandbox_mode checks the request without sending. Returns the message id.",
1387
+ inputSchema: {
1388
+ type: "object",
1389
+ properties: {
1390
+ from: { ...PERSON, description: "The sender: a verified sender or an address of an authenticated domain." },
1391
+ to: PEOPLE("The recipients", 1e3),
1392
+ cc: PEOPLE("Cc recipients", 100),
1393
+ bcc: PEOPLE("Bcc recipients", 100),
1394
+ separate_copies: {
1395
+ type: "boolean",
1396
+ default: true,
1397
+ description: "true (default): each address in to gets its own copy and sees only itself. false: one email to everyone in to, cc and bcc, as a mail program sends it."
1398
+ },
1399
+ reply_to: PERSON,
1400
+ subject: { type: "string", minLength: 1, maxLength: 998, description: "The subject line (a dynamic template has its own)." },
1401
+ text: { type: "string", minLength: 1, maxLength: 1e6, description: "The plain text body." },
1402
+ html: { type: "string", minLength: 1, maxLength: 1e6, description: "The HTML body." },
1403
+ template_id: TEMPLATE_ID,
1404
+ dynamic_template_data: { type: "object", description: `Values for the template's {{handlebars}}, e.g. {"first_name": "Ann"}, for every recipient.` },
1405
+ personalizations: {
1406
+ type: "array",
1407
+ maxItems: 1e3,
1408
+ items: { type: "object" },
1409
+ description: 'Advanced, instead of to/cc/bcc: SendGrid personalizations, e.g. [{"to": [{"email": "a@example.com"}], "dynamic_template_data": {"name": "Ann"}}].'
1410
+ },
1411
+ categories: { type: "array", items: { type: "string", minLength: 1, maxLength: 255 }, maxItems: 10, description: "Categories for statistics." },
1412
+ custom_args: { type: "object", description: 'Your own values that come back in event webhooks, e.g. {"order_id": "1234"}.' },
1413
+ send_at: { type: "integer", minimum: 0, description: "When to send, as a Unix time in seconds, up to 72 hours ahead." },
1414
+ asm_group_id: { type: "integer", minimum: 1, description: "The unsubscribe group (see list_unsubscribe_groups) the email belongs to." },
1415
+ headers: { type: "object", description: 'Extra email headers, e.g. {"X-Order": "1234"}.' },
1416
+ attachments: {
1417
+ type: "array",
1418
+ maxItems: 10,
1419
+ description: 'Files to attach, downloaded from public https URLs: [{"url": "https://...", "filename": "invoice.pdf"}].',
1420
+ items: {
1421
+ type: "object",
1422
+ properties: {
1423
+ url: { type: "string", format: "uri", maxLength: 2e3, description: "A public https URL of the file, up to 10 MB." },
1424
+ filename: { type: "string", minLength: 1, maxLength: 255, description: "The file name recipients see, with its extension." },
1425
+ type: { type: "string", maxLength: 255, description: "The media type, e.g. application/pdf (from the file name when left out)." },
1426
+ disposition: { type: "string", enum: ["attachment", "inline"], description: "attachment (default) or inline (shown in the HTML)." },
1427
+ content_id: { type: "string", maxLength: 255, description: "For inline files: the id the HTML uses as cid:<content_id>." }
1428
+ },
1429
+ required: ["url", "filename"],
1430
+ additionalProperties: false
1431
+ }
1432
+ },
1433
+ sandbox_mode: { type: "boolean", default: false, description: "true to have SendGrid check the request without sending anything." },
1434
+ ip_pool_name: { type: "string", maxLength: 64, description: "The IP pool to send from." }
1435
+ },
1436
+ required: ["from"],
1437
+ additionalProperties: false
1438
+ },
1439
+ async run(args, h) {
1440
+ if (args.personalizations?.length && (args.to?.length || args.cc?.length || args.bcc?.length)) {
1441
+ throw new ToolFailure("Give to/cc/bcc or personalizations, not both. Nothing was sent.");
1442
+ }
1443
+ if (!args.personalizations?.length && !args.to?.length) throw new ToolFailure("Give at least one recipient in to (or personalizations). Nothing was sent.");
1444
+ if (!args.template_id) {
1445
+ if (!args.subject) throw new ToolFailure("subject is required without template_id. Nothing was sent.");
1446
+ if (!args.text && !args.html) throw new ToolFailure("Give text or html, or a template_id. Nothing was sent.");
1447
+ }
1448
+ const to = args.to ?? [];
1449
+ const copied = Boolean(args.cc?.length || args.bcc?.length);
1450
+ if (!args.personalizations?.length && args.separate_copies && to.length > 1 && copied) {
1451
+ throw new ToolFailure("cc and bcc go on one shared email: set separate_copies to false, or send each recipient their own email. Nothing was sent.");
1452
+ }
1453
+ const shared = (recipients) => compact({
1454
+ to: recipients,
1455
+ cc: args.cc?.length ? args.cc : void 0,
1456
+ bcc: args.bcc?.length ? args.bcc : void 0,
1457
+ dynamic_template_data: args.dynamic_template_data
1458
+ });
1459
+ const personalizations = args.personalizations?.length ? args.personalizations : args.separate_copies && to.length > 1 ? to.map((recipient) => shared([recipient])) : [shared(to)];
1460
+ const content = [
1461
+ ...args.text ? [{ type: "text/plain", value: args.text }] : [],
1462
+ ...args.html ? [{ type: "text/html", value: args.html }] : []
1463
+ ];
1464
+ const attachments = args.attachments?.length ? await attachmentsFor(h, args.attachments) : void 0;
1465
+ const { status, headers } = await h.api({
1466
+ method: "POST",
1467
+ path: "/v3/mail/send",
1468
+ json: compact({
1469
+ personalizations,
1470
+ from: args.from,
1471
+ reply_to: args.reply_to,
1472
+ subject: args.subject,
1473
+ content: content.length ? content : void 0,
1474
+ template_id: args.template_id,
1475
+ categories: args.categories?.length ? args.categories : void 0,
1476
+ custom_args: args.custom_args,
1477
+ send_at: args.send_at,
1478
+ asm: args.asm_group_id !== void 0 ? { group_id: args.asm_group_id } : void 0,
1479
+ headers: args.headers,
1480
+ attachments,
1481
+ ip_pool_name: args.ip_pool_name,
1482
+ mail_settings: args.sandbox_mode ? { sandbox_mode: { enable: true } } : void 0
1483
+ }),
1484
+ write: true,
1485
+ errors: { 400: "SendGrid did not accept the email", 403: "SendGrid refused to send it (the API key may lack Mail Send, or the sender is not verified)" }
1486
+ });
1487
+ return compact({
1488
+ accepted: true,
1489
+ sandbox: args.sandbox_mode || void 0,
1490
+ status,
1491
+ messageId: headers.get("x-message-id") ?? void 0,
1492
+ recipients: personalizations.length,
1493
+ scheduled: args.send_at !== void 0 ? isoFromUnix(args.send_at) : void 0
1494
+ });
1495
+ }
1496
+ },
1497
+ {
1498
+ name: "search_email_activity",
1499
+ kind: "read",
1500
+ title: "Search SendGrid email activity",
1501
+ description: 'Recent emails with their status (delivered, not delivered, processing), opens and clicks, found with a SendGrid activity query such as to_email="ann@example.com" or subject="Your order". It shows whether an email went out. Needs the Email Activity history add-on.',
1502
+ inputSchema: {
1503
+ type: "object",
1504
+ properties: {
1505
+ query: { type: "string", minLength: 1, maxLength: 1e3, description: 'An activity query, e.g. to_email="ann@example.com" AND status="delivered".' },
1506
+ limit: { type: "integer", minimum: 1, maximum: 1e3, default: 20, description: "At most this many emails (default 20)." }
1507
+ },
1508
+ required: ["query"],
1509
+ additionalProperties: false
1510
+ },
1511
+ async run(args, h) {
1512
+ const { data } = await h.api({
1513
+ path: "/v3/messages",
1514
+ query: { query: args.query, limit: args.limit },
1515
+ errors: { 403: "SendGrid refused the activity search (it needs the Email Activity history add-on and the messages.read scope)" }
1516
+ });
1517
+ const messages = Array.isArray(data?.messages) ? data.messages : [];
1518
+ return h.page({
1519
+ key: "messages",
1520
+ items: messages.map((message) => compact({
1521
+ msg_id: message?.msg_id,
1522
+ to_email: message?.to_email,
1523
+ from_email: message?.from_email,
1524
+ subject: message?.subject,
1525
+ status: message?.status,
1526
+ opens_count: message?.opens_count,
1527
+ clicks_count: message?.clicks_count,
1528
+ last_event_time: message?.last_event_time
1529
+ })),
1530
+ resumeAt: () => ""
1531
+ });
1532
+ }
1533
+ },
1534
+ {
1535
+ name: "upsert_contacts",
1536
+ kind: "update",
1537
+ // A job_id comes back only with a clear answer, so an unclear one is checked on the contacts themselves.
1538
+ check: "search_contacts",
1539
+ title: "Add or update SendGrid contacts",
1540
+ description: "Adds contacts to Marketing Campaigns or updates those with the same email (or other identifier), optionally adding them to lists. Up to 1,000 at a time. SendGrid applies it in the background: the result has a job_id for get_import_status.",
1541
+ inputSchema: {
1542
+ type: "object",
1543
+ properties: {
1544
+ list_ids: { type: "array", items: UUID, maxItems: 50, uniqueItems: true, description: "Lists to add the contacts to (see list_lists)." },
1545
+ contacts: {
1546
+ type: "array",
1547
+ minItems: 1,
1548
+ maxItems: 1e3,
1549
+ description: 'The contacts: email (or phone_number_id, external_id or anonymous_id), first_name, last_name, city, country and other reserved fields, and custom_fields keyed by field id (see list_custom_fields), e.g. {"email": "ann@example.com", "first_name": "Ann", "custom_fields": {"e1_T": "VIP"}}.',
1550
+ items: {
1551
+ type: "object",
1552
+ properties: {
1553
+ email: EMAIL,
1554
+ first_name: { type: "string", maxLength: 50 },
1555
+ last_name: { type: "string", maxLength: 50 },
1556
+ custom_fields: { type: "object", description: "Custom field values keyed by field id." }
1557
+ }
1558
+ }
1559
+ }
1560
+ },
1561
+ required: ["contacts"],
1562
+ additionalProperties: false
1563
+ },
1564
+ async run(args, h) {
1565
+ const ids = ["email", "phone_number_id", "external_id", "anonymous_id"];
1566
+ const index = args.contacts.findIndex((contact) => !ids.some((key) => typeof contact[key] === "string" && contact[key]));
1567
+ if (index !== -1) throw new ToolFailure(`contacts[${index}] needs an email, phone_number_id, external_id or anonymous_id. Nothing was changed.`);
1568
+ const { status, data } = await h.api({
1569
+ method: "PUT",
1570
+ path: "/v3/marketing/contacts",
1571
+ json: compact({ list_ids: args.list_ids, contacts: args.contacts }),
1572
+ write: true,
1573
+ errors: { 400: "SendGrid did not accept the contacts" }
1574
+ });
1575
+ return compact({ accepted: status === 202 || status === 200, job_id: data?.job_id, contacts: args.contacts.length });
1576
+ }
1577
+ },
1578
+ {
1579
+ name: "get_import_status",
1580
+ kind: "read",
1581
+ title: "Get a SendGrid contacts job",
1582
+ description: "The status of a contacts import or delete job (pending, completed, errored, failed) with the counts of contacts requested, created, updated, deleted and in error.",
1583
+ inputSchema: {
1584
+ type: "object",
1585
+ properties: { job_id: { ...UUID, description: "The job_id from upsert_contacts or delete_contacts." } },
1586
+ required: ["job_id"],
1587
+ additionalProperties: false
1588
+ },
1589
+ async run(args, h) {
1590
+ const { data } = await h.api({ path: `/v3/marketing/contacts/imports/${encodeURIComponent(args.job_id)}`, errors: { 404: "SendGrid has no contacts job with that id" } });
1591
+ return compact({ id: data?.id, status: data?.status, job_type: data?.job_type, results: data?.results, started_at: data?.started_at, finished_at: data?.finished_at });
1592
+ }
1593
+ },
1594
+ {
1595
+ name: "search_contacts",
1596
+ kind: "read",
1597
+ title: "Search SendGrid contacts",
1598
+ description: "Finds Marketing Campaigns contacts with an SGQL query, e.g. email LIKE 'ann%' AND CONTAINS(list_ids, '<list id>'), first_name = 'Ann', contact_id = '<contact id>', or created_at > TIMESTAMP '2026-01-01T00:00:00Z'. Returns the number found and up to 50 of them.",
1599
+ inputSchema: {
1600
+ type: "object",
1601
+ properties: { query: { type: "string", minLength: 1, maxLength: 5e3, description: "The SGQL condition." } },
1602
+ required: ["query"],
1603
+ additionalProperties: false
1604
+ },
1605
+ async run(args, h) {
1606
+ const { data } = await h.api({ method: "POST", path: "/v3/marketing/contacts/search", json: { query: args.query }, safe: true });
1607
+ const contacts = Array.isArray(data?.result) ? data.result : [];
1608
+ return h.page({ key: "contacts", items: contacts.map(trimContact), extra: { contact_count: data?.contact_count }, resumeAt: () => "" });
1609
+ }
1610
+ },
1611
+ {
1612
+ name: "get_contacts_by_email",
1613
+ kind: "read",
1614
+ title: "Get SendGrid contacts by email",
1615
+ description: "Looks up Marketing Campaigns contacts by email address, up to 100 at a time, with their fields, lists and custom fields; addresses with no contact are named.",
1616
+ inputSchema: {
1617
+ type: "object",
1618
+ properties: { emails: { type: "array", items: EMAIL, minItems: 1, maxItems: 100, uniqueItems: true, description: "Email addresses." } },
1619
+ required: ["emails"],
1620
+ additionalProperties: false
1621
+ },
1622
+ async run(args, h) {
1623
+ const { data } = await h.api({
1624
+ method: "POST",
1625
+ path: "/v3/marketing/contacts/search/emails",
1626
+ json: { emails: args.emails },
1627
+ safe: true,
1628
+ errors: { 404: "SendGrid has no contact with any of these emails" }
1629
+ });
1630
+ const found = [];
1631
+ const missing = [];
1632
+ for (const [email, value] of Object.entries(data?.result ?? {})) {
1633
+ if (value?.contact) found.push(trimContact(value.contact));
1634
+ else missing.push(email);
1635
+ }
1636
+ return h.page({ key: "contacts", items: found, extra: missing.length ? { not_found: missing } : {}, resumeAt: () => "" });
1637
+ }
1638
+ },
1639
+ {
1640
+ name: "delete_contacts",
1641
+ kind: "delete",
1642
+ check: "search_contacts",
1643
+ title: "Delete SendGrid contacts",
1644
+ description: "Deletes Marketing Campaigns contacts by id (from search_contacts), up to 100 at a time. SendGrid deletes them in the background: the result has a job_id for get_import_status.",
1645
+ inputSchema: {
1646
+ type: "object",
1647
+ properties: { ids: { type: "array", items: UUID, minItems: 1, maxItems: 100, uniqueItems: true, description: "Contact ids." } },
1648
+ required: ["ids"],
1649
+ additionalProperties: false
1650
+ },
1651
+ async run(args, h) {
1652
+ const { data } = await h.api({ method: "DELETE", path: "/v3/marketing/contacts", query: { ids: args.ids.join(",") }, write: true });
1653
+ return compact({ accepted: true, job_id: data?.job_id, contacts: args.ids.length });
1654
+ }
1655
+ },
1656
+ {
1657
+ name: "list_custom_fields",
1658
+ kind: "read",
1659
+ title: "List SendGrid contact fields",
1660
+ description: "The custom fields of Marketing Campaigns contacts with their ids and types (custom_fields in upsert_contacts take these ids), and the reserved fields.",
1661
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1662
+ async run(_args, h) {
1663
+ const { data } = await h.api({ path: "/v3/marketing/field_definitions" });
1664
+ const fields = (items) => Array.isArray(items) ? items.map((field) => compact({ id: field?.id, name: field?.name, field_type: field?.field_type, read_only: field?.read_only })) : [];
1665
+ return { custom_fields: fields(data?.custom_fields), reserved_fields: fields(data?.reserved_fields) };
1666
+ }
1667
+ },
1668
+ {
1669
+ name: "list_lists",
1670
+ kind: "read",
1671
+ title: "List SendGrid contact lists",
1672
+ description: "Marketing Campaigns lists with their ids and contact counts. Pass nextCursor back as cursor for more.",
1673
+ inputSchema: {
1674
+ type: "object",
1675
+ properties: {
1676
+ page_size: { type: "integer", minimum: 1, maximum: 1e3, default: 100, description: "Lists per page, 1 to 1000 (default 100)." },
1677
+ cursor: CURSOR
1678
+ },
1679
+ additionalProperties: false
1680
+ },
1681
+ async run(args, h) {
1682
+ return tokenList(h, args.cursor, {
1683
+ key: "lists",
1684
+ path: "/v3/marketing/lists",
1685
+ pageSize: args.page_size,
1686
+ trim: (list) => compact({ id: list?.id, name: list?.name, contact_count: list?.contact_count })
1687
+ });
1688
+ }
1689
+ },
1690
+ {
1691
+ name: "create_list",
1692
+ kind: "create",
1693
+ check: "list_lists",
1694
+ title: "Create a SendGrid contact list",
1695
+ description: "Creates a Marketing Campaigns list and returns its id.",
1696
+ inputSchema: {
1697
+ type: "object",
1698
+ properties: { name: { type: "string", minLength: 1, maxLength: 100, description: "The list name." } },
1699
+ required: ["name"],
1700
+ additionalProperties: false
1701
+ },
1702
+ async run(args, h) {
1703
+ const { data } = await h.api({ method: "POST", path: "/v3/marketing/lists", json: { name: args.name }, write: true });
1704
+ return compact({ id: data?.id, name: data?.name ?? args.name, contact_count: data?.contact_count });
1705
+ }
1706
+ },
1707
+ {
1708
+ name: "delete_list",
1709
+ kind: "delete",
1710
+ check: "list_lists",
1711
+ title: "Delete a SendGrid contact list",
1712
+ description: "Deletes a list. Its contacts are kept unless delete_contacts is true, which deletes them too (for good).",
1713
+ inputSchema: {
1714
+ type: "object",
1715
+ properties: {
1716
+ list_id: { ...UUID, description: "The list id." },
1717
+ delete_contacts: { type: "boolean", default: false, description: "true to delete the list's contacts as well." }
1718
+ },
1719
+ required: ["list_id"],
1720
+ additionalProperties: false
1721
+ },
1722
+ async run(args, h) {
1723
+ const { data } = await h.api({
1724
+ method: "DELETE",
1725
+ path: `/v3/marketing/lists/${encodeURIComponent(args.list_id)}`,
1726
+ query: { delete_contacts: args.delete_contacts || void 0 },
1727
+ write: true,
1728
+ errors: { 404: "SendGrid has no list with that id" }
1729
+ });
1730
+ return compact({ deleted: true, id: args.list_id, job_id: data?.job_id });
1731
+ }
1732
+ },
1733
+ {
1734
+ name: "list_single_sends",
1735
+ kind: "read",
1736
+ title: "List SendGrid Single Sends",
1737
+ description: "Single Sends (marketing emails) with their status (draft, scheduled, triggered), send time and categories, newest first. Pass nextCursor back as cursor for more.",
1738
+ inputSchema: {
1739
+ type: "object",
1740
+ properties: {
1741
+ page_size: { type: "integer", minimum: 1, maximum: 100, default: 50, description: "Single Sends per page, 1 to 100 (default 50)." },
1742
+ cursor: CURSOR
1743
+ },
1744
+ additionalProperties: false
1745
+ },
1746
+ async run(args, h) {
1747
+ return tokenList(h, args.cursor, { key: "single_sends", path: "/v3/marketing/singlesends", pageSize: args.page_size, trim: (send) => trimSingleSend(send) });
1748
+ }
1749
+ },
1750
+ {
1751
+ name: "get_single_send",
1752
+ kind: "read",
1753
+ title: "Get a SendGrid Single Send",
1754
+ description: "One Single Send with its recipients, sender, unsubscribe setting, schedule, warnings and its HTML and text bodies (cut at 20,000 characters).",
1755
+ inputSchema: {
1756
+ type: "object",
1757
+ properties: { single_send_id: { ...UUID, description: "The Single Send id." } },
1758
+ required: ["single_send_id"],
1759
+ additionalProperties: false
1760
+ },
1761
+ async run(args, h) {
1762
+ const { data } = await h.api({ path: `/v3/marketing/singlesends/${encodeURIComponent(args.single_send_id)}`, errors: { 404: "SendGrid has no Single Send with that id" } });
1763
+ return trimSingleSend(data, { html: true });
1764
+ }
1765
+ },
1766
+ {
1767
+ name: "create_single_send",
1768
+ kind: "create",
1769
+ check: "list_single_sends",
1770
+ title: "Create a SendGrid Single Send",
1771
+ description: "Creates a Single Send (a marketing email) as a draft; nothing is sent until schedule_single_send. For sending later it needs a subject, an HTML body or design, a sender_id, recipients (list_ids, segment_ids or send_to_all) and a suppression_group_id or custom_unsubscribe_url.",
1772
+ inputSchema: { type: "object", properties: SINGLE_SEND_FIELDS, required: ["name"], additionalProperties: false },
1773
+ async run(args, h) {
1774
+ const { data } = await h.api({ method: "POST", path: "/v3/marketing/singlesends", json: singleSendBody(args), write: true, errors: { 400: "SendGrid did not accept the Single Send" } });
1775
+ return trimSingleSend(data);
1776
+ }
1777
+ },
1778
+ {
1779
+ name: "update_single_send",
1780
+ kind: "update",
1781
+ check: "get_single_send",
1782
+ title: "Update a SendGrid Single Send",
1783
+ description: "Changes a draft Single Send: only the fields given. A scheduled one must be unscheduled first.",
1784
+ inputSchema: {
1785
+ type: "object",
1786
+ properties: { single_send_id: { ...UUID, description: "The Single Send id." }, ...SINGLE_SEND_FIELDS },
1787
+ required: ["single_send_id"],
1788
+ additionalProperties: false
1789
+ },
1790
+ async run(args, h) {
1791
+ const body = singleSendBody(args);
1792
+ if (!Object.keys(body).length) throw new ToolFailure("Nothing to change: give at least one field. Nothing was changed.");
1793
+ const { data } = await h.api({
1794
+ method: "PATCH",
1795
+ path: `/v3/marketing/singlesends/${encodeURIComponent(args.single_send_id)}`,
1796
+ json: body,
1797
+ write: true,
1798
+ errors: { 404: "SendGrid has no Single Send with that id", 400: "SendGrid did not accept the change" }
1799
+ });
1800
+ return trimSingleSend(data);
1801
+ }
1802
+ },
1803
+ {
1804
+ name: "schedule_single_send",
1805
+ kind: "update",
1806
+ check: "get_single_send",
1807
+ title: "Schedule or send a SendGrid Single Send",
1808
+ description: 'Schedules a Single Send for a time, or sends it now with send_at "now". Sending cannot be undone; a scheduled send can be stopped with unschedule_single_send before it starts. Check it first with get_single_send.',
1809
+ inputSchema: {
1810
+ type: "object",
1811
+ properties: {
1812
+ single_send_id: { ...UUID, description: "The Single Send id." },
1813
+ send_at: {
1814
+ type: "string",
1815
+ pattern: "^(now|\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2}))$",
1816
+ description: '"now", or a future ISO 8601 date-time with a time zone, e.g. 2026-12-01T09:00:00Z.'
1817
+ }
1818
+ },
1819
+ required: ["single_send_id", "send_at"],
1820
+ additionalProperties: false
1821
+ },
1822
+ async run(args, h) {
1823
+ const { data } = await h.api({
1824
+ method: "PUT",
1825
+ path: `/v3/marketing/singlesends/${encodeURIComponent(args.single_send_id)}/schedule`,
1826
+ json: { send_at: args.send_at },
1827
+ write: true,
1828
+ errors: { 404: "SendGrid has no Single Send with that id", 400: "SendGrid did not schedule the Single Send" }
1829
+ });
1830
+ return compact({ id: args.single_send_id, status: data?.status, send_at: data?.send_at });
1831
+ }
1832
+ },
1833
+ {
1834
+ name: "unschedule_single_send",
1835
+ kind: "update",
1836
+ check: "get_single_send",
1837
+ title: "Unschedule a SendGrid Single Send",
1838
+ description: "Cancels a scheduled Single Send before it starts and turns it back into a draft.",
1839
+ inputSchema: {
1840
+ type: "object",
1841
+ properties: { single_send_id: { ...UUID, description: "The Single Send id." } },
1842
+ required: ["single_send_id"],
1843
+ additionalProperties: false
1844
+ },
1845
+ async run(args, h) {
1846
+ const { data } = await h.api({
1847
+ method: "DELETE",
1848
+ path: `/v3/marketing/singlesends/${encodeURIComponent(args.single_send_id)}/schedule`,
1849
+ write: true,
1850
+ errors: { 404: "SendGrid has no Single Send with that id" }
1851
+ });
1852
+ return compact({ id: args.single_send_id, status: data?.status ?? "draft" });
1853
+ }
1854
+ },
1855
+ {
1856
+ name: "delete_single_send",
1857
+ kind: "delete",
1858
+ check: "list_single_sends",
1859
+ title: "Delete a SendGrid Single Send",
1860
+ description: "Deletes a Single Send. Deleting a scheduled one cancels it; it cannot be undone.",
1861
+ inputSchema: {
1862
+ type: "object",
1863
+ properties: { single_send_id: { ...UUID, description: "The Single Send id." } },
1864
+ required: ["single_send_id"],
1865
+ additionalProperties: false
1866
+ },
1867
+ async run(args, h) {
1868
+ await h.api({
1869
+ method: "DELETE",
1870
+ path: `/v3/marketing/singlesends/${encodeURIComponent(args.single_send_id)}`,
1871
+ write: true,
1872
+ errors: { 404: "SendGrid has no Single Send with that id" }
1873
+ });
1874
+ return { deleted: true, id: args.single_send_id };
1875
+ }
1876
+ },
1877
+ {
1878
+ name: "get_single_send_stats",
1879
+ kind: "read",
1880
+ title: "Get SendGrid Single Send statistics",
1881
+ description: "Delivery and engagement of a sent Single Send: requests, delivered, opens and unique opens, clicks and unique clicks, bounces, blocks, spam reports and unsubscribes (per A/B variation when it had one).",
1882
+ inputSchema: {
1883
+ type: "object",
1884
+ properties: { single_send_id: { ...UUID, description: "The Single Send id." } },
1885
+ required: ["single_send_id"],
1886
+ additionalProperties: false
1887
+ },
1888
+ async run(args, h) {
1889
+ const { data } = await h.api({ path: `/v3/marketing/stats/singlesends/${encodeURIComponent(args.single_send_id)}`, query: { aggregated_by: "total" } });
1890
+ const results = Array.isArray(data?.results) ? data.results : [];
1891
+ return { id: args.single_send_id, results: results.map((row) => compact({ ab_variation: row?.ab_variation, ab_phase: row?.ab_phase, stats: row?.stats })) };
1892
+ }
1893
+ },
1894
+ {
1895
+ name: "list_templates",
1896
+ kind: "read",
1897
+ title: "List SendGrid templates",
1898
+ description: "Transactional templates (dynamic by default, or legacy) with their versions, which one is active, and their subjects. Pass nextCursor back as cursor for more.",
1899
+ inputSchema: {
1900
+ type: "object",
1901
+ properties: {
1902
+ generation: { type: "string", enum: ["dynamic", "legacy"], default: "dynamic", description: "dynamic (default) or legacy templates." },
1903
+ page_size: { type: "integer", minimum: 1, maximum: 200, default: 50, description: "Templates per page, 1 to 200 (default 50)." },
1904
+ cursor: CURSOR
1905
+ },
1906
+ additionalProperties: false
1907
+ },
1908
+ async run(args, h) {
1909
+ return tokenList(h, args.cursor, {
1910
+ key: "templates",
1911
+ path: "/v3/templates",
1912
+ query: { generations: args.generation },
1913
+ pageSize: args.page_size,
1914
+ trim: (template) => trimTemplate(template)
1915
+ });
1916
+ }
1917
+ },
1918
+ {
1919
+ name: "get_template",
1920
+ kind: "read",
1921
+ title: "Get a SendGrid template",
1922
+ description: "One template with its versions, and the active version's subject, HTML and text (cut at 20,000 characters).",
1923
+ inputSchema: {
1924
+ type: "object",
1925
+ properties: { template_id: TEMPLATE_ID },
1926
+ required: ["template_id"],
1927
+ additionalProperties: false
1928
+ },
1929
+ async run(args, h) {
1930
+ const { data } = await h.api({ path: `/v3/templates/${encodeURIComponent(args.template_id)}`, errors: { 404: "SendGrid has no template with that id" } });
1931
+ return trimTemplate(data, { html: true });
1932
+ }
1933
+ },
1934
+ {
1935
+ name: "create_template",
1936
+ kind: "create",
1937
+ check: "list_templates",
1938
+ title: "Create a SendGrid template",
1939
+ description: "Creates an empty transactional template (dynamic by default) and returns its id; add its content with create_template_version.",
1940
+ inputSchema: {
1941
+ type: "object",
1942
+ properties: {
1943
+ name: { type: "string", minLength: 1, maxLength: 100, description: "The template name." },
1944
+ generation: { type: "string", enum: ["dynamic", "legacy"], default: "dynamic", description: "dynamic (handlebars, default) or legacy." }
1945
+ },
1946
+ required: ["name"],
1947
+ additionalProperties: false
1948
+ },
1949
+ async run(args, h) {
1950
+ const { data } = await h.api({ method: "POST", path: "/v3/templates", json: { name: args.name, generation: args.generation }, write: true });
1951
+ return trimTemplate(data);
1952
+ }
1953
+ },
1954
+ {
1955
+ name: "create_template_version",
1956
+ kind: "create",
1957
+ check: "get_template",
1958
+ title: "Add a version to a SendGrid template",
1959
+ description: "Adds a version to a template: subject and HTML (with {{handlebars}} such as {{first_name}}, {{#if}} and {{#each}}), plain text, and whether it becomes the active version that emails use (default true).",
1960
+ inputSchema: {
1961
+ type: "object",
1962
+ properties: {
1963
+ template_id: TEMPLATE_ID,
1964
+ name: { type: "string", minLength: 1, maxLength: 100, description: "The version name, e.g. v2." },
1965
+ subject: { type: "string", minLength: 1, maxLength: 255, description: "The subject line; it can use handlebars." },
1966
+ html_content: { type: "string", minLength: 1, maxLength: 1e6, description: "The HTML body." },
1967
+ plain_content: { type: "string", maxLength: 1e6, description: "The plain text body (generated from the HTML when left out)." },
1968
+ active: { type: "boolean", default: true, description: "true (default) to make it the version in use." },
1969
+ test_data: { type: "object", description: "Sample values for previews in SendGrid." }
1970
+ },
1971
+ required: ["template_id", "name", "subject", "html_content"],
1972
+ additionalProperties: false
1973
+ },
1974
+ async run(args, h) {
1975
+ const { data } = await h.api({
1976
+ method: "POST",
1977
+ path: `/v3/templates/${encodeURIComponent(args.template_id)}/versions`,
1978
+ json: compact({
1979
+ name: args.name,
1980
+ subject: args.subject,
1981
+ html_content: args.html_content,
1982
+ plain_content: args.plain_content,
1983
+ generate_plain_content: args.plain_content === void 0 ? true : void 0,
1984
+ active: args.active ? 1 : 0,
1985
+ editor: "code",
1986
+ test_data: args.test_data ? JSON.stringify(args.test_data) : void 0
1987
+ }),
1988
+ write: true,
1989
+ errors: { 404: "SendGrid has no template with that id", 400: "SendGrid did not accept the version" }
1990
+ });
1991
+ return compact({ id: data?.id, template_id: data?.template_id ?? args.template_id, name: data?.name, active: data?.active, subject: data?.subject });
1992
+ }
1993
+ },
1994
+ {
1995
+ name: "list_senders",
1996
+ kind: "read",
1997
+ title: "List SendGrid verified senders",
1998
+ description: "Verified sender identities with their ids (the sender_id of Single Sends), from and reply-to addresses, and whether they are verified.",
1999
+ inputSchema: {
2000
+ type: "object",
2001
+ properties: {
2002
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 100, description: "Senders per page, 1 to 100 (default 100)." },
2003
+ cursor: CURSOR
2004
+ },
2005
+ additionalProperties: false
2006
+ },
2007
+ async run(args, h) {
2008
+ const state = h.cursor(args.cursor);
2009
+ const last = typeof state?.["l"] === "number" ? state["l"] : void 0;
2010
+ const skip = typeof state?.["s"] === "number" ? state["s"] : 0;
2011
+ const limit = typeof state?.["n"] === "number" ? state["n"] : args.limit;
2012
+ const { data } = await h.api({ path: "/v3/verified_senders", query: { limit, lastSeenID: last } });
2013
+ const senders = Array.isArray(data?.results) ? data.results : [];
2014
+ const lastId = senders[senders.length - 1]?.id;
2015
+ return h.page({
2016
+ key: "senders",
2017
+ items: senders.map((sender) => compact({
2018
+ id: sender?.id,
2019
+ nickname: sender?.nickname,
2020
+ from_email: sender?.from_email,
2021
+ from_name: sender?.from_name,
2022
+ reply_to: sender?.reply_to,
2023
+ verified: sender?.verified,
2024
+ locked: sender?.locked
2025
+ })).slice(skip),
2026
+ resumeAt: (index) => h.makeCursor({ ...last !== void 0 ? { l: last } : {}, n: limit, s: skip + index }),
2027
+ ...senders.length >= limit && typeof lastId === "number" ? { nextPage: h.makeCursor({ l: lastId, n: limit, s: 0 }) } : {}
2028
+ });
2029
+ }
2030
+ },
2031
+ {
2032
+ name: "create_sender",
2033
+ kind: "create",
2034
+ check: "list_senders",
2035
+ title: "Add a SendGrid verified sender",
2036
+ description: "Adds a sender identity. SendGrid emails the from address a verification link; the sender can send only once it is verified.",
2037
+ inputSchema: {
2038
+ type: "object",
2039
+ properties: {
2040
+ nickname: { type: "string", minLength: 1, maxLength: 100, description: "A name for the sender in SendGrid." },
2041
+ from_email: EMAIL,
2042
+ from_name: { type: "string", maxLength: 256, description: "The From name recipients see." },
2043
+ reply_to: EMAIL,
2044
+ reply_to_name: { type: "string", maxLength: 256, description: "The reply-to name." },
2045
+ address: { type: "string", minLength: 1, maxLength: 100, description: "The street address (anti-spam laws require one)." },
2046
+ address2: { type: "string", maxLength: 100, description: "More of the address." },
2047
+ city: { type: "string", minLength: 1, maxLength: 150, description: "The city." },
2048
+ state: { type: "string", maxLength: 2, description: "The two-letter state, for the US." },
2049
+ zip: { type: "string", maxLength: 10, description: "The postal code." },
2050
+ country: { type: "string", minLength: 1, maxLength: 100, description: "The country." }
2051
+ },
2052
+ required: ["nickname", "from_email", "reply_to", "address", "city", "country"],
2053
+ additionalProperties: false
2054
+ },
2055
+ async run(args, h) {
2056
+ const { data } = await h.api({ method: "POST", path: "/v3/verified_senders", json: compact({ ...args }), write: true, errors: { 400: "SendGrid did not accept the sender" } });
2057
+ return compact({ id: data?.id, nickname: data?.nickname, from_email: data?.from_email, verified: data?.verified, note: "SendGrid sent a verification email to the from address." });
2058
+ }
2059
+ },
2060
+ {
2061
+ name: "list_unsubscribe_groups",
2062
+ kind: "read",
2063
+ title: "List SendGrid unsubscribe groups",
2064
+ description: "Unsubscribe (suppression) groups with their ids, names, whether one is the default, and how many have unsubscribed. Single Sends and emails name one.",
2065
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
2066
+ async run(_args, h) {
2067
+ const { data } = await h.api({ path: "/v3/asm/groups" });
2068
+ const groups = Array.isArray(data) ? data : [];
2069
+ return { groups: groups.map((group) => compact({ id: group?.id, name: group?.name, description: group?.description, is_default: group?.is_default, unsubscribes: group?.unsubscribes })) };
2070
+ }
2071
+ },
2072
+ {
2073
+ name: "get_stats",
2074
+ kind: "read",
2075
+ title: "Get SendGrid email statistics",
2076
+ description: "Email statistics for a date range, in total and per day, week or month: requests, delivered, opens, clicks, bounces, blocks, drops, spam reports and unsubscribes, for the whole account or for up to 10 categories. Pass nextCursor back as cursor for more periods.",
2077
+ inputSchema: {
2078
+ type: "object",
2079
+ properties: {
2080
+ start_date: DATE("The first day"),
2081
+ end_date: DATE("The last day (default today)"),
2082
+ aggregated_by: { type: "string", enum: ["day", "week", "month"], default: "day", description: "Periods of a day (default), a week or a month." },
2083
+ categories: { type: "array", items: { type: "string", minLength: 1, maxLength: 255 }, maxItems: 10, uniqueItems: true, description: "Only these categories, each counted on its own." },
2084
+ cursor: CURSOR
2085
+ },
2086
+ required: ["start_date"],
2087
+ additionalProperties: false
2088
+ },
2089
+ async run(args, h) {
2090
+ const skip = (() => {
2091
+ const state = h.cursor(args.cursor);
2092
+ return typeof state?.["s"] === "number" ? state["s"] : 0;
2093
+ })();
2094
+ const { data } = await h.api({
2095
+ path: args.categories?.length ? "/v3/categories/stats" : "/v3/stats",
2096
+ query: { start_date: args.start_date, end_date: args.end_date, aggregated_by: args.aggregated_by, categories: args.categories }
2097
+ });
2098
+ const rows = Array.isArray(data) ? data : [];
2099
+ const totals = {};
2100
+ const periods = rows.map((row) => ({
2101
+ date: row?.date,
2102
+ stats: (Array.isArray(row?.stats) ? row.stats : []).map((stat) => {
2103
+ const name2 = typeof stat?.name === "string" ? stat.name : "all";
2104
+ const metrics = {};
2105
+ for (const [key, value] of Object.entries(stat?.metrics ?? {})) {
2106
+ if (typeof value !== "number") continue;
2107
+ totals[name2] ??= {};
2108
+ totals[name2][key] = (totals[name2][key] ?? 0) + value;
2109
+ if (value !== 0) metrics[key] = value;
2110
+ }
2111
+ return compact({ name: name2 === "all" ? void 0 : name2, metrics });
2112
+ })
2113
+ }));
2114
+ return h.page({
2115
+ key: "periods",
2116
+ items: periods.slice(skip),
2117
+ extra: { totals },
2118
+ resumeAt: (index) => h.makeCursor({ s: skip + index })
2119
+ });
2120
+ }
2121
+ },
2122
+ {
2123
+ name: "list_suppressions",
2124
+ kind: "read",
2125
+ title: "List SendGrid suppressions",
2126
+ description: "Addresses SendGrid will not send to: bounces, blocks, spam reports, invalid emails or global unsubscribes, newest first, with when and why. Filter by a time range or one email. Pass nextCursor back as cursor for more.",
2127
+ inputSchema: {
2128
+ type: "object",
2129
+ properties: {
2130
+ type: { type: "string", enum: [...SUPPRESSIONS], description: "bounces, blocks, spam_reports, invalid_emails or unsubscribes." },
2131
+ email: EMAIL,
2132
+ start_time: { type: "integer", minimum: 0, description: "Only entries since this Unix time (seconds)." },
2133
+ end_time: { type: "integer", minimum: 0, description: "Only entries up to this Unix time (seconds)." },
2134
+ limit: { type: "integer", minimum: 1, maximum: 500, default: 100, description: "Entries per page, 1 to 500 (default 100)." },
2135
+ cursor: CURSOR
2136
+ },
2137
+ required: ["type"],
2138
+ additionalProperties: false
2139
+ },
2140
+ async run(args, h) {
2141
+ return offsetList(h, args.cursor, {
2142
+ key: "suppressions",
2143
+ path: `/v3/suppression/${args.type}`,
2144
+ limit: args.limit,
2145
+ query: { email: args.email, start_time: args.start_time, end_time: args.end_time },
2146
+ trim: (entry) => compact({ email: entry?.email, created: isoFromUnix(entry?.created), reason: entry?.reason, status: entry?.status, ip: entry?.ip })
2147
+ });
2148
+ }
2149
+ },
2150
+ {
2151
+ name: "delete_suppression",
2152
+ kind: "delete",
2153
+ check: "list_suppressions",
2154
+ title: "Remove an address from a SendGrid suppression list",
2155
+ description: "Removes one email address from a suppression list (bounces, blocks, spam_reports, invalid_emails or unsubscribes), so SendGrid sends to it again. Only do this when the person asked for it or the address was fixed.",
2156
+ inputSchema: {
2157
+ type: "object",
2158
+ properties: {
2159
+ type: { type: "string", enum: [...SUPPRESSIONS], description: "The list to remove it from." },
2160
+ email: EMAIL
2161
+ },
2162
+ required: ["type", "email"],
2163
+ additionalProperties: false
2164
+ },
2165
+ async run(args, h) {
2166
+ const path = args.type === "unsubscribes" ? `/v3/asm/suppressions/global/${encodeURIComponent(args.email)}` : `/v3/suppression/${args.type}/${encodeURIComponent(args.email)}`;
2167
+ await h.api({ method: "DELETE", path, write: true, errors: { 404: `SendGrid has no such address in ${args.type}` } });
2168
+ return { removed: true, type: args.type, email: args.email };
2169
+ }
2170
+ },
2171
+ ...apiTools({
2172
+ label: LABEL2,
2173
+ description: "The SendGrid Web API v3 at https://api.sendgrid.com/v3, with the connected API key: paths start with /v3/, such as /v3/marketing/segments/2.0, /v3/marketing/contacts/count, /v3/marketing/lists/{id}, /v3/asm/groups/{id}/suppressions, /v3/user/webhooks/event/settings or /v3/whitelabel/domains. Reference: https://docs.sendgrid.com/api-reference.",
2174
+ basePath: "/v3/",
2175
+ guard(request) {
2176
+ const [base, area = "", detail = ""] = routedParts(request.segments);
2177
+ if (base !== "v3") throw new ToolFailure("The path must stay under /v3/. Nothing was sent.");
2178
+ if (area === "api_keys") throw new ToolFailure("SendGrid API keys are not available here. Nothing was sent.");
2179
+ if (request.method !== "GET" && (ADMIN_AREAS.has(area) || area === "user" && SIGN_IN_DETAILS.has(detail))) {
2180
+ throw new ToolFailure(
2181
+ "Changing SendGrid teammates, subusers, access settings, single sign-on or the account's email, username or password is not available here. Nothing was sent."
2182
+ );
2183
+ }
2184
+ }
2185
+ })
2186
+ ]
2187
+ });
2188
+ module.exports = connector;