@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.
- package/CHANGELOG.md +29 -0
- package/README.md +1131 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1950 @@
|
|
|
1
|
+
/* notion connector module (MIT License). Built from src/vendors/notion; 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/notion/format.ts
|
|
1091
|
+
function compact(value) {
|
|
1092
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
|
|
1093
|
+
}
|
|
1094
|
+
function notionId(value, name2, block = false) {
|
|
1095
|
+
const text = String(value ?? "").trim();
|
|
1096
|
+
let path = text;
|
|
1097
|
+
let fragment = "";
|
|
1098
|
+
try {
|
|
1099
|
+
if (/^https?:\/\//i.test(text)) {
|
|
1100
|
+
const url = new URL(text);
|
|
1101
|
+
path = url.pathname;
|
|
1102
|
+
fragment = url.hash.slice(1);
|
|
1103
|
+
}
|
|
1104
|
+
} catch {
|
|
1105
|
+
}
|
|
1106
|
+
path = path.split(/[?#]/)[0] ?? "";
|
|
1107
|
+
const last = path.split("/").filter(Boolean).pop() ?? "";
|
|
1108
|
+
const fromFragment = block ? /^([0-9a-f]{32})$/i.exec(fragment.replace(/-/g, "")) : null;
|
|
1109
|
+
const match = fromFragment ?? /([0-9a-f]{32})$/i.exec(last.replace(/-/g, ""));
|
|
1110
|
+
if (!match?.[1]) {
|
|
1111
|
+
throw new ToolFailure(
|
|
1112
|
+
`${name2} is not a Notion ID or link. Use the 32 hexadecimal characters at the end of the page's link, such as 1429989fe8ac4effbc8f57f56486db54, or the whole link. Nothing was sent.`
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
const hex = match[1].toLowerCase();
|
|
1116
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1117
|
+
}
|
|
1118
|
+
function plain(richText) {
|
|
1119
|
+
if (!Array.isArray(richText)) return "";
|
|
1120
|
+
return richText.map((item) => typeof item?.plain_text === "string" ? item.plain_text : typeof item?.text?.content === "string" ? item.text.content : "").join("");
|
|
1121
|
+
}
|
|
1122
|
+
function parentOf(item) {
|
|
1123
|
+
const parent = item?.parent;
|
|
1124
|
+
if (!parent || typeof parent !== "object" || typeof parent.type !== "string") return void 0;
|
|
1125
|
+
if (parent.type === "workspace") return { type: "workspace" };
|
|
1126
|
+
return compact({
|
|
1127
|
+
type: parent.type,
|
|
1128
|
+
id: typeof parent[parent.type] === "string" ? parent[parent.type] : void 0,
|
|
1129
|
+
database_id: parent.type === "data_source_id" && typeof parent.database_id === "string" ? parent.database_id : void 0
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
function pageTitle(page) {
|
|
1133
|
+
const properties = page?.properties;
|
|
1134
|
+
if (!properties || typeof properties !== "object") return "";
|
|
1135
|
+
for (const property of Object.values(properties)) {
|
|
1136
|
+
if (property?.type === "title") return plain(property.title);
|
|
1137
|
+
}
|
|
1138
|
+
return "";
|
|
1139
|
+
}
|
|
1140
|
+
function person(user) {
|
|
1141
|
+
if (!user || typeof user !== "object") return void 0;
|
|
1142
|
+
return compact({ id: user.id, name: typeof user.name === "string" ? user.name : void 0 });
|
|
1143
|
+
}
|
|
1144
|
+
function scalar(value) {
|
|
1145
|
+
if (value === void 0) return null;
|
|
1146
|
+
return value;
|
|
1147
|
+
}
|
|
1148
|
+
function formulaValue(formula) {
|
|
1149
|
+
if (!formula || typeof formula !== "object") return null;
|
|
1150
|
+
const value = formula[formula.type];
|
|
1151
|
+
if (formula.type === "date") return value ? compact({ start: value.start, end: value.end }) : null;
|
|
1152
|
+
return scalar(value);
|
|
1153
|
+
}
|
|
1154
|
+
function rollupValue(rollup) {
|
|
1155
|
+
if (!rollup || typeof rollup !== "object") return null;
|
|
1156
|
+
if (rollup.type === "array") return { items: Array.isArray(rollup.array) ? rollup.array.length : 0 };
|
|
1157
|
+
if (rollup.type === "date") return rollup.date ? compact({ start: rollup.date.start, end: rollup.date.end }) : null;
|
|
1158
|
+
return scalar(rollup[rollup.type]);
|
|
1159
|
+
}
|
|
1160
|
+
function propertyValue(property) {
|
|
1161
|
+
if (!property || typeof property !== "object") return null;
|
|
1162
|
+
switch (property.type) {
|
|
1163
|
+
case "title":
|
|
1164
|
+
case "rich_text":
|
|
1165
|
+
return truncate(plain(property[property.type]), 2e3);
|
|
1166
|
+
case "number":
|
|
1167
|
+
return scalar(property.number);
|
|
1168
|
+
case "select":
|
|
1169
|
+
case "status":
|
|
1170
|
+
return property[property.type]?.name ?? null;
|
|
1171
|
+
case "multi_select":
|
|
1172
|
+
return Array.isArray(property.multi_select) ? property.multi_select.map((option) => option?.name) : [];
|
|
1173
|
+
case "date":
|
|
1174
|
+
return property.date ? compact({ start: property.date.start, end: property.date.end, time_zone: property.date.time_zone }) : null;
|
|
1175
|
+
case "checkbox":
|
|
1176
|
+
return property.checkbox === true;
|
|
1177
|
+
case "url":
|
|
1178
|
+
case "email":
|
|
1179
|
+
case "phone_number":
|
|
1180
|
+
return scalar(property[property.type]);
|
|
1181
|
+
case "people":
|
|
1182
|
+
return Array.isArray(property.people) ? property.people.map(person) : [];
|
|
1183
|
+
case "relation":
|
|
1184
|
+
return Array.isArray(property.relation) ? property.relation.map((item) => item?.id) : [];
|
|
1185
|
+
case "files":
|
|
1186
|
+
return Array.isArray(property.files) ? property.files.map((file) => compact({ name: file?.name, url: file?.external?.url ?? file?.file?.url })) : [];
|
|
1187
|
+
case "formula":
|
|
1188
|
+
return formulaValue(property.formula);
|
|
1189
|
+
case "rollup":
|
|
1190
|
+
return rollupValue(property.rollup);
|
|
1191
|
+
case "created_time":
|
|
1192
|
+
case "last_edited_time":
|
|
1193
|
+
return scalar(property[property.type]);
|
|
1194
|
+
case "created_by":
|
|
1195
|
+
case "last_edited_by":
|
|
1196
|
+
return person(property[property.type]) ?? null;
|
|
1197
|
+
case "unique_id": {
|
|
1198
|
+
const id = property.unique_id;
|
|
1199
|
+
if (!id || typeof id.number !== "number") return null;
|
|
1200
|
+
return id.prefix ? `${id.prefix}-${id.number}` : id.number;
|
|
1201
|
+
}
|
|
1202
|
+
case "verification":
|
|
1203
|
+
return property.verification?.state ?? null;
|
|
1204
|
+
default:
|
|
1205
|
+
return `(${String(property.type ?? "unknown")} value)`;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
function pageProperties(page, flat, only) {
|
|
1209
|
+
const out = {};
|
|
1210
|
+
const properties = page?.properties;
|
|
1211
|
+
if (!properties || typeof properties !== "object") return out;
|
|
1212
|
+
for (const [name2, property] of Object.entries(properties)) {
|
|
1213
|
+
if (only && only.length && property?.type !== "title" && !only.includes(name2)) continue;
|
|
1214
|
+
out[name2] = flat ? propertyValue(property) : { type: property?.type, value: propertyValue(property) };
|
|
1215
|
+
}
|
|
1216
|
+
return out;
|
|
1217
|
+
}
|
|
1218
|
+
function trimPage(page, properties = "typed", only) {
|
|
1219
|
+
return compact({
|
|
1220
|
+
id: page?.id,
|
|
1221
|
+
title: truncate(pageTitle(page), 500) || "(untitled)",
|
|
1222
|
+
url: page?.url,
|
|
1223
|
+
parent: parentOf(page),
|
|
1224
|
+
in_trash: page?.in_trash === true ? true : void 0,
|
|
1225
|
+
created_time: page?.created_time,
|
|
1226
|
+
last_edited_time: page?.last_edited_time,
|
|
1227
|
+
properties: properties === "none" ? void 0 : pageProperties(page, properties === "flat", only)
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
function trimSearchResult(item) {
|
|
1231
|
+
const title = item?.object === "page" ? pageTitle(item) : plain(item?.title);
|
|
1232
|
+
return compact({
|
|
1233
|
+
object: item?.object,
|
|
1234
|
+
id: item?.id,
|
|
1235
|
+
title: truncate(title, 300) || "(untitled)",
|
|
1236
|
+
url: item?.url,
|
|
1237
|
+
parent: parentOf(item),
|
|
1238
|
+
last_edited_time: item?.last_edited_time,
|
|
1239
|
+
in_trash: item?.in_trash === true ? true : void 0
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
var URL_BLOCKS = /* @__PURE__ */ new Set(["bookmark", "embed", "link_preview", "video", "pdf", "file", "audio", "image"]);
|
|
1243
|
+
function trimBlock(block) {
|
|
1244
|
+
const type = typeof block?.type === "string" ? block.type : "unknown";
|
|
1245
|
+
const body = block?.[type] ?? {};
|
|
1246
|
+
const text = plain(body?.rich_text);
|
|
1247
|
+
return compact({
|
|
1248
|
+
id: block?.id,
|
|
1249
|
+
type,
|
|
1250
|
+
text: text ? truncate(text, 1e3) : void 0,
|
|
1251
|
+
checked: type === "to_do" ? body?.checked === true : void 0,
|
|
1252
|
+
language: type === "code" ? body?.language : void 0,
|
|
1253
|
+
title: type === "child_page" || type === "child_database" ? body?.title : void 0,
|
|
1254
|
+
url: URL_BLOCKS.has(type) ? body?.url ?? body?.external?.url ?? body?.file?.url : void 0,
|
|
1255
|
+
caption: URL_BLOCKS.has(type) && plain(body?.caption) ? truncate(plain(body.caption), 300) : void 0,
|
|
1256
|
+
icon: type === "callout" ? body?.icon?.emoji : void 0,
|
|
1257
|
+
expression: type === "equation" ? body?.expression : void 0,
|
|
1258
|
+
table_width: type === "table" ? body?.table_width : void 0,
|
|
1259
|
+
has_column_header: type === "table" ? body?.has_column_header : void 0,
|
|
1260
|
+
cells: type === "table_row" && Array.isArray(body?.cells) ? body.cells.map((cell) => truncate(plain(cell), 300)) : void 0,
|
|
1261
|
+
unsupported_type: type === "unsupported" ? body?.block_type : void 0,
|
|
1262
|
+
has_children: block?.has_children === true ? true : void 0,
|
|
1263
|
+
in_trash: block?.in_trash === true ? true : void 0
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
function schemaProperties(dataSource) {
|
|
1267
|
+
const properties = dataSource?.properties;
|
|
1268
|
+
if (!properties || typeof properties !== "object") return [];
|
|
1269
|
+
const readOnly = /* @__PURE__ */ new Set(["formula", "rollup", "created_time", "created_by", "last_edited_time", "last_edited_by", "unique_id", "button"]);
|
|
1270
|
+
const rows = Object.entries(properties).map(([name2, property]) => {
|
|
1271
|
+
const type = property?.type;
|
|
1272
|
+
const options = ["select", "multi_select", "status"].includes(type) && Array.isArray(property?.[type]?.options) ? property[type].options.map((option) => option?.name) : void 0;
|
|
1273
|
+
return compact({
|
|
1274
|
+
name: name2,
|
|
1275
|
+
type,
|
|
1276
|
+
id: property?.id,
|
|
1277
|
+
options,
|
|
1278
|
+
links_to: type === "relation" ? property?.relation?.data_source_id ?? property?.relation?.database_id : void 0,
|
|
1279
|
+
read_only: readOnly.has(type) ? true : void 0
|
|
1280
|
+
});
|
|
1281
|
+
});
|
|
1282
|
+
return rows.sort((a, b) => Number(b["type"] === "title") - Number(a["type"] === "title"));
|
|
1283
|
+
}
|
|
1284
|
+
var TEXT_WINDOW_BYTES = 24e3;
|
|
1285
|
+
function textWindow(text, offset, budget = TEXT_WINDOW_BYTES) {
|
|
1286
|
+
const start = Math.max(0, Math.min(Math.floor(offset), text.length));
|
|
1287
|
+
const rest = text.length - start;
|
|
1288
|
+
const size = (count2) => utf8Length(JSON.stringify(text.slice(start, start + count2)));
|
|
1289
|
+
let count = Math.min(rest, budget);
|
|
1290
|
+
if (size(count) > budget) {
|
|
1291
|
+
let low = 0;
|
|
1292
|
+
let high = count;
|
|
1293
|
+
while (low < high) {
|
|
1294
|
+
const middle = Math.ceil((low + high) / 2);
|
|
1295
|
+
if (size(middle) <= budget) low = middle;
|
|
1296
|
+
else high = middle - 1;
|
|
1297
|
+
}
|
|
1298
|
+
count = low;
|
|
1299
|
+
}
|
|
1300
|
+
if (count < rest) {
|
|
1301
|
+
const lineBreak = text.lastIndexOf("\n", start + count - 1);
|
|
1302
|
+
if (lineBreak >= start + Math.floor(count / 2)) count = lineBreak + 1 - start;
|
|
1303
|
+
const code = text.charCodeAt(start + count - 1);
|
|
1304
|
+
if (code >= 55296 && code <= 56319) count -= 1;
|
|
1305
|
+
}
|
|
1306
|
+
const end = start + Math.max(count, 0);
|
|
1307
|
+
return { text: text.slice(start, end), offset: start, ...end < text.length ? { next: end } : {} };
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// src/vendors/notion/index.ts
|
|
1311
|
+
var NOTION_VERSION = "2026-03-11";
|
|
1312
|
+
var LARGE_REPLY_BYTES = 8 * 1024 * 1024;
|
|
1313
|
+
var NOT_SHARED = "Notion found nothing with that ID that this connection can see. Check the ID; if it is right, the page is not shared with the connection: in Notion, open the page, click \u2022\u2022\u2022 > Connections > + Add connection and pick the connection";
|
|
1314
|
+
var WRITE_REFUSED = "Notion refused the change: the connection may lack the Update content or Insert content capability (the connection's Configuration tab in Notion's Developer portal), or a Free workspace with several members has used up its block limit";
|
|
1315
|
+
var ID_SCHEMA = { type: "string", minLength: 32, maxLength: 2e3 };
|
|
1316
|
+
var CURSOR_SCHEMA = { type: "string", description: "nextCursor from the previous result; pass the same other arguments again." };
|
|
1317
|
+
var MARKDOWN_HELP = 'Notion-flavored Markdown: # to #### headings, lists, - [ ] to-dos, > quotes, fenced code with a language, --- dividers,  images on their own line, pipe tables, <callout icon="\u{1F4A1}">...</callout> and <toggle>...</toggle> blocks. Write \\< for a literal < outside code.';
|
|
1318
|
+
function cursorState(h, cursor) {
|
|
1319
|
+
const state = h.cursor(cursor);
|
|
1320
|
+
return {
|
|
1321
|
+
...typeof state?.["c"] === "string" && state["c"] ? { start: state["c"] } : {},
|
|
1322
|
+
skip: typeof state?.["o"] === "number" ? state["o"] : 0
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
function notionPage(h, key, data, items, start, skip, extra) {
|
|
1326
|
+
const next = data?.has_more === true && typeof data?.next_cursor === "string" ? data.next_cursor : void 0;
|
|
1327
|
+
return h.page({
|
|
1328
|
+
key,
|
|
1329
|
+
items: items.slice(skip),
|
|
1330
|
+
...extra ? { extra } : {},
|
|
1331
|
+
resumeAt: (index) => h.makeCursor({ ...start ? { c: start } : {}, o: skip + index }),
|
|
1332
|
+
...next ? { nextPage: h.makeCursor({ c: next, o: 0 }) } : {}
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
function incompleteNote(data) {
|
|
1336
|
+
const status = data?.request_status;
|
|
1337
|
+
if (status?.type !== "incomplete") return void 0;
|
|
1338
|
+
return `Notion stopped the list early (${String(status.incomplete_reason ?? "incomplete")}): narrow the query or the filter.`;
|
|
1339
|
+
}
|
|
1340
|
+
function titleProperty(title) {
|
|
1341
|
+
return { title: [{ type: "text", text: { content: title } }] };
|
|
1342
|
+
}
|
|
1343
|
+
function hasTitleValue(properties) {
|
|
1344
|
+
return Object.values(properties ?? {}).some((value) => typeof value === "object" && value !== null && "title" in value);
|
|
1345
|
+
}
|
|
1346
|
+
function assertObjects(list, name2) {
|
|
1347
|
+
(list ?? []).forEach((item, index) => {
|
|
1348
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) {
|
|
1349
|
+
throw new ToolFailure(`${name2}[${index}] must be a Notion block object, such as {"type":"paragraph","paragraph":{"rich_text":[...]}}. Nothing was sent.`);
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
function markdownResult(id, data, extra) {
|
|
1354
|
+
const warnings = Array.isArray(data?.warnings) ? data.warnings.slice(0, 10).map((item) => (typeof item === "string" ? item : JSON.stringify(item)).slice(0, 300)) : void 0;
|
|
1355
|
+
return compact({
|
|
1356
|
+
id,
|
|
1357
|
+
...extra,
|
|
1358
|
+
page_markdown_length: typeof data?.markdown === "string" ? data.markdown.length : void 0,
|
|
1359
|
+
warnings: warnings?.length ? warnings : void 0
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
async function patchMarkdown(h, id, body, refused) {
|
|
1363
|
+
return h.api({
|
|
1364
|
+
method: "PATCH",
|
|
1365
|
+
path: `/v1/pages/${id}/markdown`,
|
|
1366
|
+
json: { ...body, markdown_version: "v2" },
|
|
1367
|
+
write: true,
|
|
1368
|
+
errors: { 400: refused, 403: WRITE_REFUSED, 404: NOT_SHARED }
|
|
1369
|
+
});
|
|
1370
|
+
}
|
|
1371
|
+
var connector = defineConnector({
|
|
1372
|
+
vendor: "notion",
|
|
1373
|
+
label: "Notion",
|
|
1374
|
+
origins: ["https://api.notion.com"],
|
|
1375
|
+
credentials: ["token"],
|
|
1376
|
+
credentialLabels: { token: "Notion API token" },
|
|
1377
|
+
normalizeCredentials: (credentials) => ({ ...credentials, token: (credentials["token"] ?? "").replace(/^Bearer\s+/i, "") }),
|
|
1378
|
+
authHeaders: (credentials) => ({
|
|
1379
|
+
authorization: `Bearer ${credentials["token"]}`,
|
|
1380
|
+
"notion-version": NOTION_VERSION
|
|
1381
|
+
}),
|
|
1382
|
+
tools: [
|
|
1383
|
+
{
|
|
1384
|
+
name: "get_connection",
|
|
1385
|
+
kind: "read",
|
|
1386
|
+
title: "Check the Notion connection",
|
|
1387
|
+
description: "Checks that the Notion token works and says what it is: the connection's name, its workspace, and whether it is an internal connection (it sees only the pages shared with it) or acts as a person.",
|
|
1388
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1389
|
+
async run(_args, h) {
|
|
1390
|
+
const { data } = await h.api({ path: "/v1/users/me" });
|
|
1391
|
+
const ownerType = data?.bot?.owner?.type;
|
|
1392
|
+
const kind = data?.type === "person" || ownerType === "user" ? "acts as a person: reaches what that person can open" : "internal connection: reaches only the pages and databases shared with it";
|
|
1393
|
+
return compact({
|
|
1394
|
+
id: data?.id,
|
|
1395
|
+
name: data?.name ?? void 0,
|
|
1396
|
+
type: data?.type,
|
|
1397
|
+
workspace_name: data?.bot?.workspace_name ?? void 0,
|
|
1398
|
+
owner_type: ownerType,
|
|
1399
|
+
reach: kind
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
},
|
|
1403
|
+
{
|
|
1404
|
+
name: "search",
|
|
1405
|
+
kind: "read",
|
|
1406
|
+
title: "Search Notion pages and databases",
|
|
1407
|
+
description: "Searches the pages and data sources (databases) this connection can see, by title (not page text), most recently edited first by default. Leave query out to list everything shared with the connection. Each result has its type, ID, title, link, parent and last edit. Pass nextCursor back as cursor for more.",
|
|
1408
|
+
inputSchema: {
|
|
1409
|
+
type: "object",
|
|
1410
|
+
properties: {
|
|
1411
|
+
query: { type: "string", maxLength: 500, description: "Words in the title. Leave out to list everything." },
|
|
1412
|
+
filter: { type: "string", enum: ["page", "data_source"], description: "page for pages only, data_source for databases only; leave out for both." },
|
|
1413
|
+
sort: { type: "string", enum: ["descending", "ascending"], default: "descending", description: "By last edit time: descending (default) or ascending." },
|
|
1414
|
+
page_size: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Results per page, 1 to 100 (default 20)." },
|
|
1415
|
+
cursor: CURSOR_SCHEMA
|
|
1416
|
+
},
|
|
1417
|
+
additionalProperties: false
|
|
1418
|
+
},
|
|
1419
|
+
async run(args, h) {
|
|
1420
|
+
const { start, skip } = cursorState(h, args.cursor);
|
|
1421
|
+
const { data } = await h.api({
|
|
1422
|
+
method: "POST",
|
|
1423
|
+
path: "/v1/search",
|
|
1424
|
+
safe: true,
|
|
1425
|
+
json: compact({
|
|
1426
|
+
query: args.query,
|
|
1427
|
+
filter: args.filter ? { property: "object", value: args.filter } : void 0,
|
|
1428
|
+
sort: { timestamp: "last_edited_time", direction: args.sort },
|
|
1429
|
+
page_size: args.page_size,
|
|
1430
|
+
start_cursor: start
|
|
1431
|
+
})
|
|
1432
|
+
});
|
|
1433
|
+
const results = Array.isArray(data?.results) ? data.results.map(trimSearchResult) : [];
|
|
1434
|
+
const note = results.length || skip ? incompleteNote(data) : "Nothing found. A connection sees only the pages and databases shared with it (in Notion: \u2022\u2022\u2022 > Connections > + Add connection on the page).";
|
|
1435
|
+
return notionPage(h, "results", data, results, start, skip, note ? { note } : void 0);
|
|
1436
|
+
}
|
|
1437
|
+
},
|
|
1438
|
+
{
|
|
1439
|
+
name: "get_page",
|
|
1440
|
+
kind: "read",
|
|
1441
|
+
title: "Get a Notion page",
|
|
1442
|
+
description: "Reads one page (or database row) by its ID or link: title, link, parent, trash state, last edit, and every property with its type and value. The page body is read with read_page_markdown or list_block_children.",
|
|
1443
|
+
inputSchema: {
|
|
1444
|
+
type: "object",
|
|
1445
|
+
properties: { page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." } },
|
|
1446
|
+
required: ["page_id"],
|
|
1447
|
+
additionalProperties: false
|
|
1448
|
+
},
|
|
1449
|
+
async run(args, h) {
|
|
1450
|
+
const id = notionId(args.page_id, "page_id");
|
|
1451
|
+
const { data } = await h.api({ path: `/v1/pages/${id}`, errors: { 404: NOT_SHARED } });
|
|
1452
|
+
return trimPage(data, "typed");
|
|
1453
|
+
}
|
|
1454
|
+
},
|
|
1455
|
+
{
|
|
1456
|
+
name: "read_page_markdown",
|
|
1457
|
+
kind: "read",
|
|
1458
|
+
title: "Read a Notion page as Markdown",
|
|
1459
|
+
description: "Reads a page's body as Notion-flavored Markdown, the shortest way to read or quote a page. A long body comes in windows of about 24 KB: pass nextCursor back as cursor for the next one. Blocks Notion left out (a very long page, or content not shared with the connection) are listed by ID.",
|
|
1460
|
+
inputSchema: {
|
|
1461
|
+
type: "object",
|
|
1462
|
+
properties: {
|
|
1463
|
+
page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." },
|
|
1464
|
+
include_transcript: { type: "boolean", default: false, description: "Include meeting notes transcripts (default false)." },
|
|
1465
|
+
cursor: CURSOR_SCHEMA
|
|
1466
|
+
},
|
|
1467
|
+
required: ["page_id"],
|
|
1468
|
+
additionalProperties: false
|
|
1469
|
+
},
|
|
1470
|
+
async run(args, h) {
|
|
1471
|
+
const id = notionId(args.page_id, "page_id");
|
|
1472
|
+
const state = h.cursor(args.cursor);
|
|
1473
|
+
const offset = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1474
|
+
const { data } = await h.api({
|
|
1475
|
+
path: `/v1/pages/${id}/markdown`,
|
|
1476
|
+
query: { markdown_version: "v2", include_transcript: args.include_transcript ? true : void 0 },
|
|
1477
|
+
maxBytes: LARGE_REPLY_BYTES,
|
|
1478
|
+
errors: { 404: NOT_SHARED }
|
|
1479
|
+
});
|
|
1480
|
+
const markdown = typeof data?.markdown === "string" ? data.markdown : "";
|
|
1481
|
+
const window = textWindow(markdown, offset, TEXT_WINDOW_BYTES);
|
|
1482
|
+
const unknown = Array.isArray(data?.unknown_block_ids) ? data.unknown_block_ids.map(String) : [];
|
|
1483
|
+
return compact({
|
|
1484
|
+
id,
|
|
1485
|
+
markdown: window.text,
|
|
1486
|
+
offset: window.offset || void 0,
|
|
1487
|
+
length: markdown.length,
|
|
1488
|
+
nextCursor: window.next !== void 0 ? h.makeCursor({ o: window.next }) : void 0,
|
|
1489
|
+
left_out_block_ids: unknown.length ? unknown.slice(0, 50) : void 0,
|
|
1490
|
+
note: data?.truncated === true || unknown.length ? `Notion left ${unknown.length} block(s) out${data?.truncated === true ? " (the page is too long for one read)" : ""}: read each with read_page_markdown on its ID, or with list_block_children.` : void 0
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
},
|
|
1494
|
+
{
|
|
1495
|
+
name: "list_block_children",
|
|
1496
|
+
kind: "read",
|
|
1497
|
+
title: "List the blocks of a Notion page",
|
|
1498
|
+
description: "Lists one level of a page's or block's child blocks, up to 100 per page, each with its ID, type and text: the IDs to append after a block, update one or move one to the trash. A block with has_children (a toggle, a nested list, a child page) is read with the same tool on its own ID. Pass nextCursor back as cursor for more.",
|
|
1499
|
+
inputSchema: {
|
|
1500
|
+
type: "object",
|
|
1501
|
+
properties: {
|
|
1502
|
+
block_id: { ...ID_SCHEMA, description: "The page or block ID, or the page's Notion link." },
|
|
1503
|
+
page_size: { type: "integer", minimum: 1, maximum: 100, default: 100, description: "Blocks per page, 1 to 100 (default 100)." },
|
|
1504
|
+
cursor: CURSOR_SCHEMA
|
|
1505
|
+
},
|
|
1506
|
+
required: ["block_id"],
|
|
1507
|
+
additionalProperties: false
|
|
1508
|
+
},
|
|
1509
|
+
async run(args, h) {
|
|
1510
|
+
const id = notionId(args.block_id, "block_id", true);
|
|
1511
|
+
const { start, skip } = cursorState(h, args.cursor);
|
|
1512
|
+
const { data } = await h.api({
|
|
1513
|
+
path: `/v1/blocks/${id}/children`,
|
|
1514
|
+
query: { page_size: args.page_size, start_cursor: start },
|
|
1515
|
+
errors: { 404: NOT_SHARED }
|
|
1516
|
+
});
|
|
1517
|
+
const blocks = Array.isArray(data?.results) ? data.results.map(trimBlock) : [];
|
|
1518
|
+
return notionPage(h, "blocks", data, blocks, start, skip, { parent_id: id });
|
|
1519
|
+
}
|
|
1520
|
+
},
|
|
1521
|
+
{
|
|
1522
|
+
name: "get_block",
|
|
1523
|
+
kind: "read",
|
|
1524
|
+
title: "Get a Notion block",
|
|
1525
|
+
description: "Reads one block by its ID: its type, text, to-do state and whether it has children or is in the trash.",
|
|
1526
|
+
inputSchema: {
|
|
1527
|
+
type: "object",
|
|
1528
|
+
properties: { block_id: { ...ID_SCHEMA, description: "The block ID (list_block_children lists them), or a link to the block." } },
|
|
1529
|
+
required: ["block_id"],
|
|
1530
|
+
additionalProperties: false
|
|
1531
|
+
},
|
|
1532
|
+
async run(args, h) {
|
|
1533
|
+
const id = notionId(args.block_id, "block_id", true);
|
|
1534
|
+
const { data } = await h.api({ path: `/v1/blocks/${id}`, errors: { 404: NOT_SHARED } });
|
|
1535
|
+
return compact({ ...trimBlock(data), parent: parentOf(data) });
|
|
1536
|
+
}
|
|
1537
|
+
},
|
|
1538
|
+
{
|
|
1539
|
+
name: "get_database",
|
|
1540
|
+
kind: "read",
|
|
1541
|
+
title: "Get a Notion database",
|
|
1542
|
+
description: "Reads a database by its ID or link: its title, link and the data sources inside it. Queries, new rows and the schema use a data source ID from this list, never the database ID.",
|
|
1543
|
+
inputSchema: {
|
|
1544
|
+
type: "object",
|
|
1545
|
+
properties: { database_id: { ...ID_SCHEMA, description: "The database ID, or its Notion link (the part before ?v=)." } },
|
|
1546
|
+
required: ["database_id"],
|
|
1547
|
+
additionalProperties: false
|
|
1548
|
+
},
|
|
1549
|
+
async run(args, h) {
|
|
1550
|
+
const id = notionId(args.database_id, "database_id");
|
|
1551
|
+
const { data } = await h.api({ path: `/v1/databases/${id}`, errors: { 404: NOT_SHARED } });
|
|
1552
|
+
return compact({
|
|
1553
|
+
id: data?.id,
|
|
1554
|
+
title: plain(data?.title) || "(untitled)",
|
|
1555
|
+
url: data?.url,
|
|
1556
|
+
parent: parentOf(data),
|
|
1557
|
+
in_trash: data?.in_trash === true ? true : void 0,
|
|
1558
|
+
data_sources: Array.isArray(data?.data_sources) ? data.data_sources.map((source) => compact({ id: source?.id, name: source?.name || "(untitled)" })) : []
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
},
|
|
1562
|
+
{
|
|
1563
|
+
name: "get_data_source",
|
|
1564
|
+
kind: "read",
|
|
1565
|
+
title: "Get a Notion data source schema",
|
|
1566
|
+
description: "Reads a data source's schema: every property with its type and ID (the title property first), the option names of select, multi-select and status properties, relation targets, and which properties Notion computes. Read it before writing rows: property names are case-sensitive and option names must match exactly.",
|
|
1567
|
+
inputSchema: {
|
|
1568
|
+
type: "object",
|
|
1569
|
+
properties: { data_source_id: { ...ID_SCHEMA, description: "The data source ID, from get_database or search." } },
|
|
1570
|
+
required: ["data_source_id"],
|
|
1571
|
+
additionalProperties: false
|
|
1572
|
+
},
|
|
1573
|
+
async run(args, h) {
|
|
1574
|
+
const id = notionId(args.data_source_id, "data_source_id");
|
|
1575
|
+
const { data } = await h.api({ path: `/v1/data_sources/${id}`, errors: { 404: NOT_SHARED } });
|
|
1576
|
+
return compact({
|
|
1577
|
+
id: data?.id,
|
|
1578
|
+
title: plain(data?.title) || "(untitled)",
|
|
1579
|
+
database_id: data?.parent?.database_id,
|
|
1580
|
+
properties: schemaProperties(data)
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
},
|
|
1584
|
+
{
|
|
1585
|
+
name: "query_data_source",
|
|
1586
|
+
kind: "read",
|
|
1587
|
+
title: "Query a Notion database",
|
|
1588
|
+
description: 'Lists the rows of a data source, with an optional Notion filter and sorts, e.g. filter {"and":[{"property":"Status","status":{"does_not_equal":"Done"}},{"property":"Due","date":{"on_or_before":"2026-11-28"}}]} and sorts [{"property":"Due","direction":"ascending"}]. Each row has its ID, title, link and property values; properties keeps only the named ones. Pass nextCursor back as cursor (with the same filter) for more. Notion allows about 3 queries a second.',
|
|
1589
|
+
inputSchema: {
|
|
1590
|
+
type: "object",
|
|
1591
|
+
properties: {
|
|
1592
|
+
data_source_id: { ...ID_SCHEMA, description: "The data source ID, from get_database or search." },
|
|
1593
|
+
filter: { type: "object", description: "A Notion filter object; the key of each condition is the property's type." },
|
|
1594
|
+
sorts: { type: "array", maxItems: 10, items: { type: "object" }, description: "Notion sort objects; the first sort wins." },
|
|
1595
|
+
properties: { type: "array", maxItems: 50, items: { type: "string", minLength: 1, maxLength: 200 }, description: "Property names to return (default: all)." },
|
|
1596
|
+
page_size: { type: "integer", minimum: 1, maximum: 100, default: 50, description: "Rows per page, 1 to 100 (default 50)." },
|
|
1597
|
+
cursor: CURSOR_SCHEMA
|
|
1598
|
+
},
|
|
1599
|
+
required: ["data_source_id"],
|
|
1600
|
+
additionalProperties: false
|
|
1601
|
+
},
|
|
1602
|
+
async run(args, h) {
|
|
1603
|
+
const id = notionId(args.data_source_id, "data_source_id");
|
|
1604
|
+
const { start, skip } = cursorState(h, args.cursor);
|
|
1605
|
+
const { data } = await h.api({
|
|
1606
|
+
method: "POST",
|
|
1607
|
+
path: `/v1/data_sources/${id}/query`,
|
|
1608
|
+
safe: true,
|
|
1609
|
+
json: compact({ filter: args.filter, sorts: args.sorts, page_size: args.page_size, start_cursor: start }),
|
|
1610
|
+
errors: { 404: NOT_SHARED }
|
|
1611
|
+
});
|
|
1612
|
+
const rows = Array.isArray(data?.results) ? data.results.map((row) => {
|
|
1613
|
+
const { parent: _parent, created_time: _created, ...rest } = trimPage(row, "flat", args.properties);
|
|
1614
|
+
const properties = { ...rest["properties"] };
|
|
1615
|
+
for (const [name2, value] of Object.entries(row?.properties ?? {})) {
|
|
1616
|
+
if (value?.type === "title") delete properties[name2];
|
|
1617
|
+
}
|
|
1618
|
+
return { ...rest, properties };
|
|
1619
|
+
}) : [];
|
|
1620
|
+
const note = incompleteNote(data) ?? (rows.length || skip ? void 0 : "No rows match.");
|
|
1621
|
+
return notionPage(h, "rows", data, rows, start, skip, note ? { data_source_id: id, note } : { data_source_id: id });
|
|
1622
|
+
}
|
|
1623
|
+
},
|
|
1624
|
+
{
|
|
1625
|
+
name: "list_users",
|
|
1626
|
+
kind: "read",
|
|
1627
|
+
title: "List Notion workspace members",
|
|
1628
|
+
description: "Lists the people and bots of the workspace with their IDs, to fill a person property by name. It needs a user information capability on the connection, and personal access tokens cannot use it. Pass nextCursor back as cursor for more.",
|
|
1629
|
+
inputSchema: {
|
|
1630
|
+
type: "object",
|
|
1631
|
+
properties: {
|
|
1632
|
+
page_size: { type: "integer", minimum: 1, maximum: 100, default: 100, description: "Users per page, 1 to 100 (default 100)." },
|
|
1633
|
+
cursor: CURSOR_SCHEMA
|
|
1634
|
+
},
|
|
1635
|
+
additionalProperties: false
|
|
1636
|
+
},
|
|
1637
|
+
async run(args, h) {
|
|
1638
|
+
const { start, skip } = cursorState(h, args.cursor);
|
|
1639
|
+
const { data } = await h.api({
|
|
1640
|
+
path: "/v1/users",
|
|
1641
|
+
query: { page_size: args.page_size, start_cursor: start },
|
|
1642
|
+
errors: { 403: "Notion refused to list users: the connection needs a user information capability, and personal access tokens cannot list users" }
|
|
1643
|
+
});
|
|
1644
|
+
const users = Array.isArray(data?.results) ? data.results.map((user) => compact({ id: user?.id, name: user?.name ?? void 0, type: user?.type, email: user?.person?.email })) : [];
|
|
1645
|
+
return notionPage(h, "users", data, users, start, skip);
|
|
1646
|
+
}
|
|
1647
|
+
},
|
|
1648
|
+
{
|
|
1649
|
+
name: "create_page",
|
|
1650
|
+
kind: "create",
|
|
1651
|
+
// Search lags behind changes; a parent page's children do not.
|
|
1652
|
+
check: "list_block_children",
|
|
1653
|
+
title: "Create a Notion page",
|
|
1654
|
+
description: "Creates a page under a parent page, or a row in a data source with its properties, with a body in Markdown or as blocks (up to 100; append the rest with append_blocks). Under a page, a Markdown body's first # heading becomes the title when title is left out. workspace: true makes a private top-level page, for personal access tokens only. Returns the new page with its link. When the outcome is unknown, look before creating it again: a page under a parent shows up at once as a child_page block in list_block_children of the parent; check a row with query_data_source and a filter on its title; only a workspace page needs search, which can lag behind.",
|
|
1655
|
+
inputSchema: {
|
|
1656
|
+
type: "object",
|
|
1657
|
+
properties: {
|
|
1658
|
+
parent_page_id: { ...ID_SCHEMA, description: "Create the page under this page (its ID or link)." },
|
|
1659
|
+
data_source_id: { ...ID_SCHEMA, description: "Create a row in this data source (from get_database); set its properties." },
|
|
1660
|
+
workspace: { type: "boolean", description: "true: a private page at the top of the workspace (personal access tokens only)." },
|
|
1661
|
+
title: { type: "string", minLength: 1, maxLength: 2e3, description: "The page title." },
|
|
1662
|
+
properties: {
|
|
1663
|
+
type: "object",
|
|
1664
|
+
description: 'Property values keyed by name, as Notion takes them: {"Status":{"status":{"name":"Draft"}},"Due":{"date":{"start":"2026-11-28"}},"Tags":{"multi_select":[{"name":"Q4"}]}}. Read get_data_source first for names and options.'
|
|
1665
|
+
},
|
|
1666
|
+
markdown: { type: "string", minLength: 1, maxLength: 4e5, description: `The body. ${MARKDOWN_HELP} Up to 5,000 blocks.` },
|
|
1667
|
+
children: { type: "array", minItems: 1, maxItems: 100, items: { type: "object" }, description: "The body as Notion block objects instead of markdown." },
|
|
1668
|
+
icon: { type: "string", minLength: 1, maxLength: 16, description: "An emoji for the page icon." },
|
|
1669
|
+
cover_url: { type: "string", format: "uri", maxLength: 2e3, description: "A public https image URL for the page cover." }
|
|
1670
|
+
},
|
|
1671
|
+
additionalProperties: false
|
|
1672
|
+
},
|
|
1673
|
+
async run(args, h) {
|
|
1674
|
+
const parents = [args.parent_page_id !== void 0, args.data_source_id !== void 0, args.workspace === true].filter(Boolean).length;
|
|
1675
|
+
if (parents !== 1) throw new ToolFailure("Give exactly one parent: parent_page_id, data_source_id, or workspace: true. Nothing was sent.");
|
|
1676
|
+
if (args.markdown !== void 0 && args.children !== void 0) throw new ToolFailure("Give markdown or children, not both. Nothing was sent.");
|
|
1677
|
+
assertObjects(args.children, "children");
|
|
1678
|
+
const parent = args.parent_page_id !== void 0 ? { page_id: notionId(args.parent_page_id, "parent_page_id") } : args.data_source_id !== void 0 ? { type: "data_source_id", data_source_id: notionId(args.data_source_id, "data_source_id") } : { workspace: true };
|
|
1679
|
+
const properties = { ...args.properties ?? {} };
|
|
1680
|
+
if (args.title !== void 0 && !hasTitleValue(properties)) properties["title"] = titleProperty(args.title);
|
|
1681
|
+
const { data } = await h.api({
|
|
1682
|
+
method: "POST",
|
|
1683
|
+
path: "/v1/pages",
|
|
1684
|
+
json: compact({
|
|
1685
|
+
parent,
|
|
1686
|
+
properties: Object.keys(properties).length ? properties : void 0,
|
|
1687
|
+
markdown: args.markdown,
|
|
1688
|
+
markdown_version: args.markdown !== void 0 ? "v2" : void 0,
|
|
1689
|
+
children: args.children,
|
|
1690
|
+
icon: args.icon !== void 0 ? { type: "emoji", emoji: args.icon } : void 0,
|
|
1691
|
+
cover: args.cover_url !== void 0 ? { type: "external", external: { url: args.cover_url } } : void 0
|
|
1692
|
+
}),
|
|
1693
|
+
write: true,
|
|
1694
|
+
errors: { 403: WRITE_REFUSED, 404: NOT_SHARED }
|
|
1695
|
+
});
|
|
1696
|
+
return trimPage(data, "typed");
|
|
1697
|
+
}
|
|
1698
|
+
},
|
|
1699
|
+
{
|
|
1700
|
+
name: "append_markdown",
|
|
1701
|
+
kind: "create",
|
|
1702
|
+
check: "read_page_markdown",
|
|
1703
|
+
title: "Add Markdown to a Notion page",
|
|
1704
|
+
description: "Adds Markdown at the end of a page (or at its start). Sending it twice adds it twice. If Notion refuses the Markdown insert, append_blocks adds blocks instead.",
|
|
1705
|
+
inputSchema: {
|
|
1706
|
+
type: "object",
|
|
1707
|
+
properties: {
|
|
1708
|
+
page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." },
|
|
1709
|
+
markdown: { type: "string", minLength: 1, maxLength: 4e5, description: `What to add. ${MARKDOWN_HELP}` },
|
|
1710
|
+
position: { type: "string", enum: ["end", "start"], default: "end", description: "end (default) or start of the page." }
|
|
1711
|
+
},
|
|
1712
|
+
required: ["page_id", "markdown"],
|
|
1713
|
+
additionalProperties: false
|
|
1714
|
+
},
|
|
1715
|
+
async run(args, h) {
|
|
1716
|
+
const id = notionId(args.page_id, "page_id");
|
|
1717
|
+
const { data } = await patchMarkdown(h, id, {
|
|
1718
|
+
type: "insert_content",
|
|
1719
|
+
insert_content: { content: args.markdown, position: { type: args.position } }
|
|
1720
|
+
}, "Notion did not accept the Markdown insert; append_blocks adds the same content as blocks");
|
|
1721
|
+
return markdownResult(id, data, { appended: true, position: args.position });
|
|
1722
|
+
}
|
|
1723
|
+
},
|
|
1724
|
+
{
|
|
1725
|
+
name: "append_blocks",
|
|
1726
|
+
kind: "create",
|
|
1727
|
+
check: "list_block_children",
|
|
1728
|
+
title: "Add blocks to a Notion page",
|
|
1729
|
+
description: "Adds up to 100 Notion block objects to a page or inside a block (a toggle, a list item), at the end by default, at the start, or right after a block whose ID list_block_children gave. Blocks nest at most two levels per call; send longer content in further calls, in order. Returns the new blocks with their IDs.",
|
|
1730
|
+
inputSchema: {
|
|
1731
|
+
type: "object",
|
|
1732
|
+
properties: {
|
|
1733
|
+
block_id: { ...ID_SCHEMA, description: "The page or block to add to (ID or the page's link)." },
|
|
1734
|
+
children: {
|
|
1735
|
+
type: "array",
|
|
1736
|
+
minItems: 1,
|
|
1737
|
+
maxItems: 100,
|
|
1738
|
+
items: { type: "object" },
|
|
1739
|
+
description: 'Notion block objects, e.g. {"type":"to_do","to_do":{"rich_text":[{"type":"text","text":{"content":"Ship it"}}],"checked":false}}.'
|
|
1740
|
+
},
|
|
1741
|
+
position: { type: "string", enum: ["end", "start"], default: "end", description: "end (default) or start; ignored with after_block_id." },
|
|
1742
|
+
after_block_id: { ...ID_SCHEMA, description: "Put the blocks right after this child block." }
|
|
1743
|
+
},
|
|
1744
|
+
required: ["block_id", "children"],
|
|
1745
|
+
additionalProperties: false
|
|
1746
|
+
},
|
|
1747
|
+
async run(args, h) {
|
|
1748
|
+
const id = notionId(args.block_id, "block_id", true);
|
|
1749
|
+
assertObjects(args.children, "children");
|
|
1750
|
+
const position = args.after_block_id !== void 0 ? { type: "after_block", after_block: { id: notionId(args.after_block_id, "after_block_id", true) } } : { type: args.position };
|
|
1751
|
+
const { data } = await h.api({
|
|
1752
|
+
method: "PATCH",
|
|
1753
|
+
path: `/v1/blocks/${id}/children`,
|
|
1754
|
+
json: { children: args.children, position },
|
|
1755
|
+
write: true,
|
|
1756
|
+
errors: { 403: WRITE_REFUSED, 404: NOT_SHARED }
|
|
1757
|
+
});
|
|
1758
|
+
const blocks = Array.isArray(data?.results) ? data.results.map(trimBlock) : [];
|
|
1759
|
+
return { parent_id: id, appended: args.children.length, blocks };
|
|
1760
|
+
}
|
|
1761
|
+
},
|
|
1762
|
+
{
|
|
1763
|
+
name: "update_page_text",
|
|
1764
|
+
// Not idempotent: when new_text contains old_text, sending the same edit twice changes the page twice.
|
|
1765
|
+
kind: "write",
|
|
1766
|
+
check: "read_page_markdown",
|
|
1767
|
+
title: "Edit text in a Notion page",
|
|
1768
|
+
description: "Changes words in place: each old_text is replaced with new_text in the page's Markdown. old_text must match exactly one place, case-sensitive (copy it from read_page_markdown and make it longer until it is unique), unless replace_all is true. An edit that would remove a child page or database is refused by Notion.",
|
|
1769
|
+
inputSchema: {
|
|
1770
|
+
type: "object",
|
|
1771
|
+
properties: {
|
|
1772
|
+
page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." },
|
|
1773
|
+
edits: {
|
|
1774
|
+
type: "array",
|
|
1775
|
+
minItems: 1,
|
|
1776
|
+
maxItems: 50,
|
|
1777
|
+
items: {
|
|
1778
|
+
type: "object",
|
|
1779
|
+
properties: {
|
|
1780
|
+
old_text: { type: "string", minLength: 1, maxLength: 1e5, description: "The exact passage to replace." },
|
|
1781
|
+
new_text: { type: "string", maxLength: 1e5, description: "The new passage (empty removes the old one)." },
|
|
1782
|
+
replace_all: { type: "boolean", description: "Replace every match instead of exactly one." }
|
|
1783
|
+
},
|
|
1784
|
+
required: ["old_text", "new_text"],
|
|
1785
|
+
additionalProperties: false
|
|
1786
|
+
},
|
|
1787
|
+
description: "The replacements, applied in order."
|
|
1788
|
+
}
|
|
1789
|
+
},
|
|
1790
|
+
required: ["page_id", "edits"],
|
|
1791
|
+
additionalProperties: false
|
|
1792
|
+
},
|
|
1793
|
+
async run(args, h) {
|
|
1794
|
+
const id = notionId(args.page_id, "page_id");
|
|
1795
|
+
const { data } = await patchMarkdown(h, id, {
|
|
1796
|
+
type: "update_content",
|
|
1797
|
+
update_content: {
|
|
1798
|
+
content_updates: args.edits.map((edit) => compact({ old_str: edit.old_text, new_str: edit.new_text, replace_all_matches: edit.replace_all }))
|
|
1799
|
+
}
|
|
1800
|
+
}, "Notion did not apply the edits (each old_text must match exactly one place, case-sensitive, unless replace_all is set: copy it from read_page_markdown)");
|
|
1801
|
+
return markdownResult(id, data, { edits_applied: args.edits.length });
|
|
1802
|
+
}
|
|
1803
|
+
},
|
|
1804
|
+
{
|
|
1805
|
+
name: "replace_page_markdown",
|
|
1806
|
+
kind: "update",
|
|
1807
|
+
check: "read_page_markdown",
|
|
1808
|
+
title: "Replace a Notion page body",
|
|
1809
|
+
description: "Replaces the whole body of a page with new Markdown. The old body is gone from the page (Notion's page history keeps it). Child pages and databases are never deleted: Notion refuses a replacement that would remove them.",
|
|
1810
|
+
inputSchema: {
|
|
1811
|
+
type: "object",
|
|
1812
|
+
properties: {
|
|
1813
|
+
page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." },
|
|
1814
|
+
markdown: { type: "string", minLength: 1, maxLength: 4e5, description: `The new body. ${MARKDOWN_HELP}` }
|
|
1815
|
+
},
|
|
1816
|
+
required: ["page_id", "markdown"],
|
|
1817
|
+
additionalProperties: false
|
|
1818
|
+
},
|
|
1819
|
+
async run(args, h) {
|
|
1820
|
+
const id = notionId(args.page_id, "page_id");
|
|
1821
|
+
const { data } = await patchMarkdown(h, id, {
|
|
1822
|
+
type: "replace_content",
|
|
1823
|
+
replace_content: { new_str: args.markdown }
|
|
1824
|
+
}, "Notion did not replace the body (a replacement that would remove a child page or database is refused)");
|
|
1825
|
+
return markdownResult(id, data, { replaced: true });
|
|
1826
|
+
}
|
|
1827
|
+
},
|
|
1828
|
+
{
|
|
1829
|
+
name: "update_page",
|
|
1830
|
+
kind: "update",
|
|
1831
|
+
check: "get_page",
|
|
1832
|
+
title: "Update a Notion page's properties",
|
|
1833
|
+
description: `Renames a page or changes a database row's properties, icon or cover. Only what is given changes; a multi-select, people or relation value replaces the whole list, and null clears a value ({"Due":{"date":null}}). silent: true sends no notifications, for bulk updates.`,
|
|
1834
|
+
inputSchema: {
|
|
1835
|
+
type: "object",
|
|
1836
|
+
properties: {
|
|
1837
|
+
page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." },
|
|
1838
|
+
title: { type: "string", minLength: 1, maxLength: 2e3, description: "A new title." },
|
|
1839
|
+
properties: { type: "object", description: "Property values keyed by name, as in create_page." },
|
|
1840
|
+
icon: { type: "string", minLength: 1, maxLength: 16, description: "An emoji for the page icon." },
|
|
1841
|
+
cover_url: { type: "string", format: "uri", maxLength: 2e3, description: "A public https image URL for the cover." },
|
|
1842
|
+
silent: { type: "boolean", default: false, description: "true: no notifications to people (default false)." }
|
|
1843
|
+
},
|
|
1844
|
+
required: ["page_id"],
|
|
1845
|
+
additionalProperties: false
|
|
1846
|
+
},
|
|
1847
|
+
async run(args, h) {
|
|
1848
|
+
const id = notionId(args.page_id, "page_id");
|
|
1849
|
+
const properties = { ...args.properties ?? {} };
|
|
1850
|
+
if (args.title !== void 0 && !hasTitleValue(properties)) properties["title"] = titleProperty(args.title);
|
|
1851
|
+
const body = compact({
|
|
1852
|
+
properties: Object.keys(properties).length ? properties : void 0,
|
|
1853
|
+
icon: args.icon !== void 0 ? { type: "emoji", emoji: args.icon } : void 0,
|
|
1854
|
+
cover: args.cover_url !== void 0 ? { type: "external", external: { url: args.cover_url } } : void 0
|
|
1855
|
+
});
|
|
1856
|
+
if (!Object.keys(body).length) throw new ToolFailure("Nothing to change: give title, properties, icon or cover_url. Nothing was changed.");
|
|
1857
|
+
if (args.silent) body["notifications"] = { mode: "silent" };
|
|
1858
|
+
const { data } = await h.api({ method: "PATCH", path: `/v1/pages/${id}`, json: body, write: true, errors: { 403: WRITE_REFUSED, 404: NOT_SHARED } });
|
|
1859
|
+
return trimPage(data, "typed");
|
|
1860
|
+
}
|
|
1861
|
+
},
|
|
1862
|
+
{
|
|
1863
|
+
name: "update_block",
|
|
1864
|
+
kind: "update",
|
|
1865
|
+
check: "get_block",
|
|
1866
|
+
title: "Update a Notion block",
|
|
1867
|
+
description: `Changes one block, e.g. ticks a to-do with {"to_do":{"checked":true}} or rewrites a paragraph with {"paragraph":{"rich_text":[{"type":"text","text":{"content":"New text"}}]}}. A field left out keeps its value; new text replaces the block's whole text.`,
|
|
1868
|
+
inputSchema: {
|
|
1869
|
+
type: "object",
|
|
1870
|
+
properties: {
|
|
1871
|
+
block_id: { ...ID_SCHEMA, description: "The block ID (list_block_children lists them), or a link to the block." },
|
|
1872
|
+
block: { type: "object", description: "The change, keyed by the block's type." }
|
|
1873
|
+
},
|
|
1874
|
+
required: ["block_id", "block"],
|
|
1875
|
+
additionalProperties: false
|
|
1876
|
+
},
|
|
1877
|
+
async run(args, h) {
|
|
1878
|
+
const id = notionId(args.block_id, "block_id", true);
|
|
1879
|
+
if (!Object.keys(args.block).length) throw new ToolFailure("Nothing to change: block is empty. Nothing was changed.");
|
|
1880
|
+
if ("in_trash" in args.block || "archived" in args.block) {
|
|
1881
|
+
throw new ToolFailure("Use trash_block to move a block to the trash. Nothing was changed.");
|
|
1882
|
+
}
|
|
1883
|
+
const { data } = await h.api({ method: "PATCH", path: `/v1/blocks/${id}`, json: args.block, write: true, errors: { 403: WRITE_REFUSED, 404: NOT_SHARED } });
|
|
1884
|
+
return trimBlock(data);
|
|
1885
|
+
}
|
|
1886
|
+
},
|
|
1887
|
+
{
|
|
1888
|
+
name: "trash_page",
|
|
1889
|
+
kind: "delete",
|
|
1890
|
+
check: "get_page",
|
|
1891
|
+
title: "Move a Notion page to the trash",
|
|
1892
|
+
description: "Moves a page or a database row to Notion's Trash. It can be restored with restore_page (a top-level private page only from Notion's Trash). Notion's API cannot delete anything for good.",
|
|
1893
|
+
inputSchema: {
|
|
1894
|
+
type: "object",
|
|
1895
|
+
properties: { page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." } },
|
|
1896
|
+
required: ["page_id"],
|
|
1897
|
+
additionalProperties: false
|
|
1898
|
+
},
|
|
1899
|
+
async run(args, h) {
|
|
1900
|
+
const id = notionId(args.page_id, "page_id");
|
|
1901
|
+
const { data } = await h.api({ method: "PATCH", path: `/v1/pages/${id}`, json: { in_trash: true }, write: true, errors: { 403: WRITE_REFUSED, 404: NOT_SHARED } });
|
|
1902
|
+
return compact({ id: data?.id ?? id, title: pageTitle(data) || void 0, url: data?.url, in_trash: data?.in_trash ?? true });
|
|
1903
|
+
}
|
|
1904
|
+
},
|
|
1905
|
+
{
|
|
1906
|
+
name: "restore_page",
|
|
1907
|
+
kind: "update",
|
|
1908
|
+
check: "get_page",
|
|
1909
|
+
title: "Restore a Notion page from the trash",
|
|
1910
|
+
description: "Takes a page or a database row out of Notion's Trash.",
|
|
1911
|
+
inputSchema: {
|
|
1912
|
+
type: "object",
|
|
1913
|
+
properties: { page_id: { ...ID_SCHEMA, description: "The page ID or its Notion link." } },
|
|
1914
|
+
required: ["page_id"],
|
|
1915
|
+
additionalProperties: false
|
|
1916
|
+
},
|
|
1917
|
+
async run(args, h) {
|
|
1918
|
+
const id = notionId(args.page_id, "page_id");
|
|
1919
|
+
const { data } = await h.api({ method: "PATCH", path: `/v1/pages/${id}`, json: { in_trash: false }, write: true, errors: { 403: WRITE_REFUSED, 404: NOT_SHARED } });
|
|
1920
|
+
return compact({ id: data?.id ?? id, title: pageTitle(data) || void 0, url: data?.url, in_trash: data?.in_trash ?? false });
|
|
1921
|
+
}
|
|
1922
|
+
},
|
|
1923
|
+
{
|
|
1924
|
+
name: "trash_block",
|
|
1925
|
+
kind: "delete",
|
|
1926
|
+
check: "get_block",
|
|
1927
|
+
title: "Move a Notion block to the trash",
|
|
1928
|
+
description: "Moves one block to Notion's Trash; it is restored from Notion's Trash in the app. Notion's API cannot delete anything for good.",
|
|
1929
|
+
inputSchema: {
|
|
1930
|
+
type: "object",
|
|
1931
|
+
properties: { block_id: { ...ID_SCHEMA, description: "The block ID (list_block_children lists them), or a link to the block." } },
|
|
1932
|
+
required: ["block_id"],
|
|
1933
|
+
additionalProperties: false
|
|
1934
|
+
},
|
|
1935
|
+
async run(args, h) {
|
|
1936
|
+
const id = notionId(args.block_id, "block_id", true);
|
|
1937
|
+
const { data } = await h.api({ method: "DELETE", path: `/v1/blocks/${id}`, write: true, errors: { 403: WRITE_REFUSED, 404: NOT_SHARED } });
|
|
1938
|
+
return compact({ ...trimBlock(data), id: data?.id ?? id, in_trash: data?.in_trash ?? true });
|
|
1939
|
+
}
|
|
1940
|
+
},
|
|
1941
|
+
// The rest of the Notion API: comments, file uploads, data source and database changes, moving pages.
|
|
1942
|
+
...apiTools({
|
|
1943
|
+
label: "Notion",
|
|
1944
|
+
description: "The Notion API at https://api.notion.com/v1, with the connected token and Notion-Version 2026-03-11: paths start with /v1/, such as /v1/comments (with block_id in query), /v1/blocks/{id} or /v1/data_sources/{id}. Reference: https://developers.notion.com/reference.",
|
|
1945
|
+
basePath: "/v1/",
|
|
1946
|
+
methods: ["POST", "PATCH", "DELETE"]
|
|
1947
|
+
})
|
|
1948
|
+
]
|
|
1949
|
+
});
|
|
1950
|
+
module.exports = connector;
|