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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +1 -1
@@ -4,10 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ConnectorFetchError = void 0;
7
+ exports.originsFromCredentials = originsFromCredentials;
7
8
  exports.createGuardedFetch = createGuardedFetch;
8
9
  const node_dns_1 = __importDefault(require("node:dns"));
9
10
  const node_https_1 = __importDefault(require("node:https"));
10
11
  const node_net_1 = __importDefault(require("node:net"));
12
+ const origins_js_1 = require("../core/origins.js");
13
+ const upload_hosts_js_1 = require("../core/upload-hosts.js");
11
14
  const ip_js_1 = require("./ip.js");
12
15
  class ConnectorFetchError extends Error {
13
16
  code;
@@ -19,28 +22,54 @@ class ConnectorFetchError extends Error {
19
22
  }
20
23
  exports.ConnectorFetchError = ConnectorFetchError;
21
24
  const DEFAULT_TIMEOUT_MS = 30_000;
22
- const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
25
+ // A file a tool hands back may come from an API origin (a stored file's
26
+ // download), so an API reply may be as large as the CLI's file limit.
27
+ const DEFAULT_MAX_RESPONSE_BYTES = 25 * 1024 * 1024;
23
28
  const DEFAULT_MAX_MEDIA_BYTES = 25 * 1024 * 1024;
29
+ const DEFAULT_MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
24
30
  const DEFAULT_MAX_REDIRECTS = 5;
25
31
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
26
32
  const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
27
- const MEDIA_HEADERS = new Set(['accept', 'user-agent']);
33
+ const MEDIA_HEADERS = new Set(['accept', 'user-agent', 'range']);
34
+ /** The Range a media download may carry: one byte range from a given first byte. */
35
+ const BYTE_RANGE = /^bytes=\d{1,15}-\d{0,15}$/;
36
+ /** Headers an upload never carries: its address holds its own signature, and credentials never go there. */
37
+ const CREDENTIAL_HEADERS = new Set(['authorization', 'proxy-authorization', 'cookie']);
28
38
  function refuse(message) {
29
39
  throw new ConnectorFetchError('URL_REFUSED', message);
30
40
  }
41
+ /**
42
+ * The https origins of a connection's originFields credentials, resolved with
43
+ * the rule the modules use (parseSiteUrl). A value that is not a usable site
44
+ * address is left out: the module refuses those calls itself, before sending.
45
+ * Pass the result to createGuardedFetch as credentialOrigins.
46
+ */
47
+ function originsFromCredentials(module, credentials) {
48
+ const origins = [];
49
+ for (const name of module.originFields ?? []) {
50
+ const value = credentials[name];
51
+ const site = typeof value === 'string' ? (0, origins_js_1.parseSiteUrl)(value) : undefined;
52
+ if (site?.ok && !origins.includes(site.origin))
53
+ origins.push(site.origin);
54
+ }
55
+ return origins;
56
+ }
31
57
  async function systemResolve(hostname) {
32
58
  return node_dns_1.default.promises.lookup(hostname, { all: true, verbatim: true });
33
59
  }
34
60
  /** HTTPS to the checked address only: the socket's lookup returns it, so DNS cannot change it in between. */
35
- const httpsTransport = ({ url, address, method, headers, signal }) => new Promise((resolve, reject) => {
61
+ const httpsTransport = ({ url, address, method, headers, body, signal }) => new Promise((resolve, reject) => {
36
62
  const hostname = url.hostname.replace(/^\[|\]$/g, '');
63
+ const outgoing = { ...headers };
64
+ if (body !== undefined)
65
+ outgoing['content-length'] = String(typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength);
37
66
  const request = node_https_1.default.request({
38
67
  protocol: 'https:',
39
68
  hostname,
40
69
  port: url.port || 443,
41
70
  path: `${url.pathname}${url.search}`,
42
71
  method,
43
- headers,
72
+ headers: outgoing,
44
73
  signal,
45
74
  agent: false,
46
75
  ...(node_net_1.default.isIP(hostname) ? {} : { servername: hostname }),
@@ -59,7 +88,7 @@ const httpsTransport = ({ url, address, method, headers, signal }) => new Promis
59
88
  });
60
89
  });
61
90
  request.on('error', reject);
62
- request.end();
91
+ request.end(body);
63
92
  });
64
93
  function timeoutSignal(timeoutMs, outer) {
65
94
  const timer = AbortSignal.timeout(timeoutMs);
@@ -105,14 +134,81 @@ function toHeaders(raw) {
105
134
  }
106
135
  return headers;
107
136
  }
137
+ /** Reads a reply up to `maxBytes`: `what` names it in the error, "file" or "reply". */
138
+ async function readReply(reply, maxBytes, what) {
139
+ const tooLarge = () => new ConnectorFetchError('TOO_LARGE', `the ${what} is larger than ${maxBytes} bytes`);
140
+ const declared = Number(reply.headers['content-length']);
141
+ if (Number.isFinite(declared) && declared > maxBytes) {
142
+ reply.destroy();
143
+ throw tooLarge();
144
+ }
145
+ const chunks = [];
146
+ let total = 0;
147
+ for await (const chunk of reply.body) {
148
+ total += chunk.byteLength;
149
+ if (total > maxBytes) {
150
+ reply.destroy();
151
+ throw tooLarge();
152
+ }
153
+ chunks.push(chunk);
154
+ }
155
+ const bytes = new Uint8Array(total);
156
+ let offset = 0;
157
+ for (const chunk of chunks) {
158
+ bytes.set(chunk, offset);
159
+ offset += chunk.byteLength;
160
+ }
161
+ return bytes;
162
+ }
108
163
  function createGuardedFetch(options) {
109
164
  const origins = new Set(options.origins);
165
+ const credentialOrigins = new Set();
166
+ for (const origin of options.credentialOrigins ?? []) {
167
+ let url;
168
+ try {
169
+ url = new URL(origin);
170
+ }
171
+ catch {
172
+ // reported below
173
+ }
174
+ if (!url || url.protocol !== 'https:' || url.origin !== origin)
175
+ throw new Error(`credential origin ${origin} must be an https origin like https://example.com`);
176
+ if (!origins.has(origin))
177
+ credentialOrigins.add(origin);
178
+ }
179
+ const uploadHosts = [...(options.uploadHosts ?? [])];
180
+ for (const entry of uploadHosts) {
181
+ const problem = (0, upload_hosts_js_1.uploadHostProblem)(entry);
182
+ if (problem)
183
+ throw new Error(`upload host ${JSON.stringify(entry)} ${problem}`);
184
+ }
110
185
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
111
186
  const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
112
187
  const maxMediaBytes = options.maxMediaBytes ?? DEFAULT_MAX_MEDIA_BYTES;
188
+ const maxUploadBytes = options.maxUploadBytes ?? DEFAULT_MAX_UPLOAD_BYTES;
113
189
  const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
114
190
  const resolve = options.resolve ?? systemResolve;
115
- const transport = options.mediaTransport ?? httpsTransport;
191
+ const transport = options.transport ?? options.mediaTransport ?? httpsTransport;
192
+ /** The address to connect to: every address of the host must be public. */
193
+ async function publicAddress(url) {
194
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
195
+ let addresses;
196
+ if (node_net_1.default.isIP(hostname)) {
197
+ addresses = [{ address: hostname, family: node_net_1.default.isIP(hostname) }];
198
+ }
199
+ else {
200
+ try {
201
+ addresses = await resolve(hostname);
202
+ }
203
+ catch {
204
+ throw new ConnectorFetchError('NETWORK', `${hostname} could not be resolved`);
205
+ }
206
+ }
207
+ if (!addresses.length || addresses.some((item) => !(0, ip_js_1.isPublicAddress)(item.address))) {
208
+ refuse(`${hostname} is not a public internet address`);
209
+ }
210
+ return addresses[0];
211
+ }
116
212
  async function api(url, init) {
117
213
  const apiFetch = options.apiFetch ?? globalThis.fetch;
118
214
  const timer = timeoutSignal(timeoutMs, init.signal);
@@ -137,6 +233,61 @@ function createGuardedFetch(options) {
137
233
  const body = response.body && !NULL_BODY_STATUSES.has(response.status) ? capStream(response.body, maxResponseBytes) : null;
138
234
  return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
139
235
  }
236
+ /**
237
+ * One request to a checked address that is never redirected: an API request
238
+ * to a credential origin, or an upload. The reply is capped like an API
239
+ * reply, and a redirect comes back as it is.
240
+ */
241
+ async function pinned(url, method, init) {
242
+ const timer = timeoutSignal(timeoutMs, init.signal);
243
+ try {
244
+ const address = await publicAddress(url);
245
+ const reply = await transport({
246
+ url,
247
+ address,
248
+ method,
249
+ headers: { ...init.headers },
250
+ ...(init.body !== undefined ? { body: init.body } : {}),
251
+ signal: timer.signal,
252
+ });
253
+ if (reply.status < 200 || reply.status > 599) {
254
+ reply.destroy();
255
+ throw new ConnectorFetchError('NETWORK', `an invalid HTTP status (${reply.status})`);
256
+ }
257
+ const empty = NULL_BODY_STATUSES.has(reply.status) || method === 'HEAD';
258
+ if (empty)
259
+ reply.destroy();
260
+ const bytes = empty ? null : await readReply(reply, maxResponseBytes, 'reply');
261
+ return new Response(bytes, { status: reply.status, headers: toHeaders(reply.headers) });
262
+ }
263
+ catch (error) {
264
+ throw failure(error, timer.timedOut(), init.signal);
265
+ }
266
+ }
267
+ /** An API request to a credential origin: checked like a media URL, sent to the checked address, never redirected. */
268
+ async function credentialApi(url, init) {
269
+ if (url.username || url.password)
270
+ refuse('URLs with a user name or password are not allowed');
271
+ return pinned(url, (init.method ?? 'GET').toUpperCase(), init);
272
+ }
273
+ /** An upload to one of the module's upload hosts: no credentials, checked like a media URL, sent to the checked address, never redirected. */
274
+ async function upload(url, method, init) {
275
+ if (url.protocol !== 'https:')
276
+ refuse(`only https uploads are allowed, not ${url.protocol}`);
277
+ if (url.port)
278
+ refuse('an upload goes to the default https port only');
279
+ if (url.username || url.password)
280
+ refuse('URLs with a user name or password are not allowed');
281
+ for (const name of Object.keys(init.headers ?? {})) {
282
+ if (CREDENTIAL_HEADERS.has(name.toLowerCase()))
283
+ refuse(`an upload to ${url.hostname} cannot carry the ${name.toLowerCase()} header`);
284
+ }
285
+ const body = init.body;
286
+ const size = typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength;
287
+ if (size > maxUploadBytes)
288
+ refuse(`the upload is larger than ${maxUploadBytes} bytes`);
289
+ return pinned(url, method, init);
290
+ }
140
291
  async function media(start, init) {
141
292
  const method = (init.method ?? 'GET').toUpperCase();
142
293
  if (method !== 'GET' && method !== 'HEAD')
@@ -145,8 +296,13 @@ function createGuardedFetch(options) {
145
296
  refuse('a media download cannot carry a body');
146
297
  const headers = {};
147
298
  for (const [name, value] of Object.entries(init.headers ?? {})) {
148
- if (MEDIA_HEADERS.has(name.toLowerCase()))
149
- headers[name.toLowerCase()] = value;
299
+ const key = name.toLowerCase();
300
+ if (!MEDIA_HEADERS.has(key))
301
+ continue;
302
+ // One Range header: a second name for it ("Range" and "range") is refused too, never picked from.
303
+ if (key === 'range' && (headers['range'] !== undefined || !BYTE_RANGE.test(value)))
304
+ refuse('a media download may ask for one byte range only, as bytes=FIRST-LAST');
305
+ headers[key] = value;
150
306
  }
151
307
  const timer = timeoutSignal(timeoutMs, init.signal);
152
308
  let url = start;
@@ -156,23 +312,8 @@ function createGuardedFetch(options) {
156
312
  refuse(`only https URLs can be downloaded, not ${url.protocol}`);
157
313
  if (url.username || url.password)
158
314
  refuse('URLs with a user name or password are not allowed');
159
- const hostname = url.hostname.replace(/^\[|\]$/g, '');
160
- let addresses;
161
- if (node_net_1.default.isIP(hostname)) {
162
- addresses = [{ address: hostname, family: node_net_1.default.isIP(hostname) }];
163
- }
164
- else {
165
- try {
166
- addresses = await resolve(hostname);
167
- }
168
- catch {
169
- throw new ConnectorFetchError('NETWORK', `${hostname} could not be resolved`);
170
- }
171
- }
172
- if (!addresses.length || addresses.some((item) => !(0, ip_js_1.isPublicAddress)(item.address))) {
173
- refuse(`${hostname} is not a public internet address`);
174
- }
175
- const reply = await transport({ url, address: addresses[0], method: method, headers, signal: timer.signal });
315
+ const address = await publicAddress(url);
316
+ const reply = await transport({ url, address, method, headers, signal: timer.signal });
176
317
  if (REDIRECTS.has(reply.status)) {
177
318
  reply.destroy();
178
319
  const location = reply.headers['location'];
@@ -187,34 +328,11 @@ function createGuardedFetch(options) {
187
328
  reply.destroy();
188
329
  throw new ConnectorFetchError('NETWORK', `an invalid HTTP status (${reply.status})`);
189
330
  }
190
- const declared = Number(reply.headers['content-length']);
191
- if (Number.isFinite(declared) && declared > maxMediaBytes) {
331
+ const empty = NULL_BODY_STATUSES.has(reply.status) || method === 'HEAD';
332
+ if (empty)
192
333
  reply.destroy();
193
- throw new ConnectorFetchError('TOO_LARGE', `the file is larger than ${maxMediaBytes} bytes`);
194
- }
195
- const chunks = [];
196
- let total = 0;
197
- if (method === 'GET') {
198
- for await (const chunk of reply.body) {
199
- total += chunk.byteLength;
200
- if (total > maxMediaBytes) {
201
- reply.destroy();
202
- throw new ConnectorFetchError('TOO_LARGE', `the file is larger than ${maxMediaBytes} bytes`);
203
- }
204
- chunks.push(chunk);
205
- }
206
- }
207
- else {
208
- reply.destroy();
209
- }
210
- const bytes = new Uint8Array(total);
211
- let offset = 0;
212
- for (const chunk of chunks) {
213
- bytes.set(chunk, offset);
214
- offset += chunk.byteLength;
215
- }
216
- const status = reply.status;
217
- return new Response(NULL_BODY_STATUSES.has(status) || method === 'HEAD' ? null : bytes, { status, headers: toHeaders(reply.headers) });
334
+ const bytes = empty ? null : await readReply(reply, maxMediaBytes, 'file');
335
+ return new Response(bytes, { status: reply.status, headers: toHeaders(reply.headers) });
218
336
  }
219
337
  }
220
338
  catch (error) {
@@ -231,6 +349,11 @@ function createGuardedFetch(options) {
231
349
  }
232
350
  if (origins.has(url.origin))
233
351
  return api(url, init);
352
+ if (credentialOrigins.has(url.origin))
353
+ return credentialApi(url, init);
354
+ const method = (init.method ?? 'GET').toUpperCase();
355
+ if ((method === 'PUT' || method === 'POST') && init.body !== undefined && (0, upload_hosts_js_1.isUploadHost)(url.hostname, uploadHosts))
356
+ return upload(url, method, init);
234
357
  return media(url, init);
235
358
  };
236
359
  }
@@ -1,9 +1,12 @@
1
- export { ACCOUNTS_ENV, accountsFromEnv, credentialsFromEnv, envNameFor } from './env.js';
1
+ export { ACCESS_TOKEN_CREDENTIAL, ACCOUNTS_ENV, accountsFromEnv, credentialsFromEnv, envNameFor } from './env.js';
2
2
  export type { EnvCredentials } from './env.js';
3
- export { ConnectorFetchError, createGuardedFetch } from './guarded-fetch.js';
4
- export type { ConnectorFetchErrorCode, GuardedFetchOptions, MediaReply, MediaTransport, ResolvedAddress } from './guarded-fetch.js';
3
+ export { ConnectorFetchError, createGuardedFetch, originsFromCredentials } from './guarded-fetch.js';
4
+ export type { ConnectorFetchErrorCode, GuardedFetchOptions, MediaReply, MediaTransport, PinnedReply, PinnedTransport, ResolvedAddress, } from './guarded-fetch.js';
5
5
  export { isPublicAddress } from './ip.js';
6
+ export { parseSiteUrl, siteOrigin } from '../core/origins.js';
7
+ export type { SiteUrl } from '../core/origins.js';
8
+ export { isUploadHost, uploadHostProblem } from '../core/upload-hosts.js';
6
9
  export { assertConnectorModule, DEFAULT_VENDORS_DIR, listVendors, loadConnector, VENDOR_PATTERN } from './load.js';
7
- export { createConnectorServer, serveStdio } from './server.js';
10
+ export { createConnectorServer, DEFAULT_MAX_FILE_BYTES, serveStdio } from './server.js';
8
11
  export type { ConnectorServerOptions } from './server.js';
9
- export type { CallToolResult, ConnectorAccounts, ConnectorFetch, ConnectorModule, ConnectorRequestInit, JsonSchema, TextContent, ToolAnnotations, ToolContext, ToolDescriptor, } from '../types.js';
12
+ export type { AccountPicker, CallToolResult, ConnectorAccounts, ConnectorFetch, ConnectorModule, ConnectorRequestInit, EmbeddedResource, JsonSchema, TextContent, ToolAnnotations, ToolContext, ToolDescriptor, } from '../types.js';
@@ -2,8 +2,9 @@
2
2
  // The host side of the package: what a program needs to run connector modules
3
3
  // itself, and what the stdio CLI is built from.
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.serveStdio = exports.createConnectorServer = exports.VENDOR_PATTERN = exports.loadConnector = exports.listVendors = exports.DEFAULT_VENDORS_DIR = exports.assertConnectorModule = exports.isPublicAddress = exports.createGuardedFetch = exports.ConnectorFetchError = exports.envNameFor = exports.credentialsFromEnv = exports.accountsFromEnv = exports.ACCOUNTS_ENV = void 0;
5
+ exports.serveStdio = exports.DEFAULT_MAX_FILE_BYTES = exports.createConnectorServer = exports.VENDOR_PATTERN = exports.loadConnector = exports.listVendors = exports.DEFAULT_VENDORS_DIR = exports.assertConnectorModule = exports.uploadHostProblem = exports.isUploadHost = exports.siteOrigin = exports.parseSiteUrl = exports.isPublicAddress = exports.originsFromCredentials = exports.createGuardedFetch = exports.ConnectorFetchError = exports.envNameFor = exports.credentialsFromEnv = exports.accountsFromEnv = exports.ACCOUNTS_ENV = exports.ACCESS_TOKEN_CREDENTIAL = void 0;
6
6
  var env_js_1 = require("./env.js");
7
+ Object.defineProperty(exports, "ACCESS_TOKEN_CREDENTIAL", { enumerable: true, get: function () { return env_js_1.ACCESS_TOKEN_CREDENTIAL; } });
7
8
  Object.defineProperty(exports, "ACCOUNTS_ENV", { enumerable: true, get: function () { return env_js_1.ACCOUNTS_ENV; } });
8
9
  Object.defineProperty(exports, "accountsFromEnv", { enumerable: true, get: function () { return env_js_1.accountsFromEnv; } });
9
10
  Object.defineProperty(exports, "credentialsFromEnv", { enumerable: true, get: function () { return env_js_1.credentialsFromEnv; } });
@@ -11,8 +12,17 @@ Object.defineProperty(exports, "envNameFor", { enumerable: true, get: function (
11
12
  var guarded_fetch_js_1 = require("./guarded-fetch.js");
12
13
  Object.defineProperty(exports, "ConnectorFetchError", { enumerable: true, get: function () { return guarded_fetch_js_1.ConnectorFetchError; } });
13
14
  Object.defineProperty(exports, "createGuardedFetch", { enumerable: true, get: function () { return guarded_fetch_js_1.createGuardedFetch; } });
15
+ Object.defineProperty(exports, "originsFromCredentials", { enumerable: true, get: function () { return guarded_fetch_js_1.originsFromCredentials; } });
14
16
  var ip_js_1 = require("./ip.js");
15
17
  Object.defineProperty(exports, "isPublicAddress", { enumerable: true, get: function () { return ip_js_1.isPublicAddress; } });
18
+ // The rule that turns a site or instance URL credential into an origin, for hosts with their own fetch.
19
+ var origins_js_1 = require("../core/origins.js");
20
+ Object.defineProperty(exports, "parseSiteUrl", { enumerable: true, get: function () { return origins_js_1.parseSiteUrl; } });
21
+ Object.defineProperty(exports, "siteOrigin", { enumerable: true, get: function () { return origins_js_1.siteOrigin; } });
22
+ // The rule that matches an address to a module's upload hosts, likewise.
23
+ var upload_hosts_js_1 = require("../core/upload-hosts.js");
24
+ Object.defineProperty(exports, "isUploadHost", { enumerable: true, get: function () { return upload_hosts_js_1.isUploadHost; } });
25
+ Object.defineProperty(exports, "uploadHostProblem", { enumerable: true, get: function () { return upload_hosts_js_1.uploadHostProblem; } });
16
26
  var load_js_1 = require("./load.js");
17
27
  Object.defineProperty(exports, "assertConnectorModule", { enumerable: true, get: function () { return load_js_1.assertConnectorModule; } });
18
28
  Object.defineProperty(exports, "DEFAULT_VENDORS_DIR", { enumerable: true, get: function () { return load_js_1.DEFAULT_VENDORS_DIR; } });
@@ -21,4 +31,5 @@ Object.defineProperty(exports, "loadConnector", { enumerable: true, get: functio
21
31
  Object.defineProperty(exports, "VENDOR_PATTERN", { enumerable: true, get: function () { return load_js_1.VENDOR_PATTERN; } });
22
32
  var server_js_1 = require("./server.js");
23
33
  Object.defineProperty(exports, "createConnectorServer", { enumerable: true, get: function () { return server_js_1.createConnectorServer; } });
34
+ Object.defineProperty(exports, "DEFAULT_MAX_FILE_BYTES", { enumerable: true, get: function () { return server_js_1.DEFAULT_MAX_FILE_BYTES; } });
24
35
  Object.defineProperty(exports, "serveStdio", { enumerable: true, get: function () { return server_js_1.serveStdio; } });
package/dist/host/load.js CHANGED
@@ -9,6 +9,7 @@ exports.assertConnectorModule = assertConnectorModule;
9
9
  exports.loadConnector = loadConnector;
10
10
  const node_fs_1 = __importDefault(require("node:fs"));
11
11
  const node_path_1 = __importDefault(require("node:path"));
12
+ const upload_hosts_js_1 = require("../core/upload-hosts.js");
12
13
  exports.VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
13
14
  /** dist/vendors, next to this package's dist/host. */
14
15
  exports.DEFAULT_VENDORS_DIR = node_path_1.default.resolve(__dirname, '..', 'vendors');
@@ -35,12 +36,41 @@ function assertConnectorModule(value, vendor) {
35
36
  else {
36
37
  if (module.vendor !== vendor)
37
38
  problems.push(`vendor is ${JSON.stringify(module.vendor)}`);
38
- if (!Array.isArray(module.origins) || !module.origins.length)
39
+ // A module built before originFields existed has none.
40
+ const originFields = module.originFields ?? [];
41
+ if (!Array.isArray(module.origins))
39
42
  problems.push('origins is missing');
43
+ if (!Array.isArray(originFields))
44
+ problems.push('originFields is not a list');
45
+ else if (Array.isArray(module.origins) && !module.origins.length && !originFields.length)
46
+ problems.push('it names no origins');
40
47
  if (!Array.isArray(module.credentials))
41
48
  problems.push('credentials is missing');
49
+ else if (Array.isArray(originFields) && originFields.some((name) => !module.credentials?.includes(name))) {
50
+ problems.push('an origin field is not one of its credentials');
51
+ }
52
+ // A module built before uploadHosts existed sends no uploads.
53
+ const uploadHosts = module.uploadHosts ?? [];
54
+ if (!Array.isArray(uploadHosts) || uploadHosts.some((entry) => (0, upload_hosts_js_1.uploadHostProblem)(entry) !== undefined) || new Set(uploadHosts).size !== uploadHosts.length) {
55
+ problems.push('uploadHosts is not a list of distinct host names');
56
+ }
57
+ // A module built before requiredCredentials and accountPickers existed has
58
+ // neither: every credential is required, and it offers no picker.
59
+ const credentials = Array.isArray(module.credentials) ? module.credentials : [];
60
+ const required = module.requiredCredentials ?? [credentials];
61
+ if (!Array.isArray(required) || !required.length
62
+ || !required.every((list) => Array.isArray(list) && list.every((name) => credentials.includes(name)))) {
63
+ problems.push('requiredCredentials is not a list of lists of its credentials');
64
+ }
42
65
  if (!Array.isArray(module.tools))
43
66
  problems.push('tools is missing');
67
+ const toolNames = Array.isArray(module.tools) ? module.tools.map((tool) => tool?.name) : [];
68
+ const pickers = module.accountPickers ?? [];
69
+ if (!Array.isArray(pickers))
70
+ problems.push('accountPickers is not a list');
71
+ else if (!pickers.every((picker) => typeof picker?.key === 'string' && toolNames.includes(picker.tool))) {
72
+ problems.push('an account picker has no key or names none of its tools');
73
+ }
44
74
  if (typeof module.call !== 'function')
45
75
  problems.push('call is missing');
46
76
  }
@@ -1,20 +1,31 @@
1
1
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
2
  import type { ConnectorAccounts, ConnectorFetch, ConnectorModule } from '../types.js';
3
+ /** The most bytes of files one call may hand back through the CLI. */
4
+ export declare const DEFAULT_MAX_FILE_BYTES: number;
3
5
  export interface ConnectorServerOptions {
4
6
  credentials: Record<string, string>;
5
7
  accounts: ConnectorAccounts;
6
- /** Defaults to a guarded fetch locked to the module's origins. */
8
+ /** Defaults to a guarded fetch locked to the module's origins, the origins of its originFields credentials and its upload hosts. */
7
9
  fetch?: ConnectorFetch;
8
10
  /** Where log lines go (default: stderr). Never stdout: that is the protocol. */
9
11
  log?: (text: string) => void;
10
12
  /** Answer for a credential the host knows is missing, e.g. naming the environment variable. */
11
13
  missingCredentials?: string;
12
14
  version?: string;
15
+ /**
16
+ * The most bytes of files one call may hand back (default 25 MiB), given to
17
+ * each call as ctx.files. They reach the MCP client unchanged, as embedded
18
+ * resources after the JSON text. null takes no files. A file may be a whole
19
+ * API reply, so the guarded fetch the server builds reads API replies up to
20
+ * this size when it is above 25 MiB; a fetch passed in must allow it itself.
21
+ */
22
+ maxFileBytes?: number | null;
13
23
  }
14
24
  /**
15
25
  * An MCP server for one connector module. The server is named after the
16
26
  * vendor, lists the module's tools as they are, and runs every call through
17
- * module.call with a fresh context.
27
+ * module.call with a fresh context. A tool's result goes back as it is, with
28
+ * the files it hands back.
18
29
  */
19
30
  export declare function createConnectorServer(module: ConnectorModule, options: ConnectorServerOptions): Server;
20
31
  /** Serves one connector module over stdio until stdin closes. */
@@ -1,22 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_MAX_FILE_BYTES = void 0;
3
4
  exports.createConnectorServer = createConnectorServer;
4
5
  exports.serveStdio = serveStdio;
5
6
  const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
6
7
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
7
8
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
8
9
  const guarded_fetch_js_1 = require("./guarded-fetch.js");
10
+ /** The most bytes of files one call may hand back through the CLI. */
11
+ exports.DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024;
9
12
  function errorResult(message) {
10
13
  return { content: [{ type: 'text', text: JSON.stringify({ error: message }) }], isError: true };
11
14
  }
12
15
  /**
13
16
  * An MCP server for one connector module. The server is named after the
14
17
  * vendor, lists the module's tools as they are, and runs every call through
15
- * module.call with a fresh context.
18
+ * module.call with a fresh context. A tool's result goes back as it is, with
19
+ * the files it hands back.
16
20
  */
17
21
  function createConnectorServer(module, options) {
18
22
  const log = options.log ?? ((text) => process.stderr.write(`${text}\n`));
19
- const fetch = options.fetch ?? (0, guarded_fetch_js_1.createGuardedFetch)({ origins: module.origins });
23
+ const maxFileBytes = options.maxFileBytes === undefined ? exports.DEFAULT_MAX_FILE_BYTES : options.maxFileBytes;
24
+ const fetch = options.fetch ?? (0, guarded_fetch_js_1.createGuardedFetch)({
25
+ origins: module.origins,
26
+ credentialOrigins: (0, guarded_fetch_js_1.originsFromCredentials)(module, options.credentials),
27
+ // A module built before uploadHosts existed sends no uploads.
28
+ uploadHosts: module.uploadHosts ?? [],
29
+ // A stored file's download is one API reply: let it be as large as the files a call may hand back.
30
+ ...(maxFileBytes && maxFileBytes > exports.DEFAULT_MAX_FILE_BYTES ? { maxResponseBytes: maxFileBytes } : {}),
31
+ });
20
32
  const server = new index_js_1.Server({ name: module.vendor, version: options.version ?? '0.0.0' }, { capabilities: { tools: {} } });
21
33
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: module.tools.map((tool) => ({ ...tool })) }));
22
34
  server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
@@ -34,6 +46,7 @@ function createConnectorServer(module, options) {
34
46
  fetch,
35
47
  signal: extra.signal,
36
48
  log,
49
+ ...(maxFileBytes ? { files: { maxBytes: maxFileBytes } } : {}),
37
50
  });
38
51
  }
39
52
  catch {
package/dist/types.d.ts CHANGED
@@ -37,9 +37,26 @@ export interface TextContent {
37
37
  type: 'text';
38
38
  text: string;
39
39
  }
40
- /** An MCP CallToolResult. Modules return a single JSON text block. */
40
+ /**
41
+ * A file a tool hands to its host: an MCP embedded resource whose uri is
42
+ * "attachment:///" and the file's name, percent-encoded, and whose blob holds
43
+ * the bytes in base64.
44
+ */
45
+ export interface EmbeddedResource {
46
+ type: 'resource';
47
+ resource: {
48
+ uri: string;
49
+ mimeType: string;
50
+ blob: string;
51
+ };
52
+ }
53
+ /**
54
+ * An MCP CallToolResult. Modules return one JSON text block first, then one
55
+ * embedded resource per file the tool hands to its host (most tools hand none,
56
+ * and an error never does).
57
+ */
41
58
  export interface CallToolResult {
42
- content: TextContent[];
59
+ content: Array<TextContent | EmbeddedResource>;
43
60
  isError?: boolean;
44
61
  }
45
62
  /** What a module may pass to ctx.fetch. */
@@ -51,8 +68,16 @@ export interface ConnectorRequestInit {
51
68
  }
52
69
  /**
53
70
  * The host's guarded fetch. A request to one of the module's origins is an API
54
- * call; any other URL is a media download (GET only, public https addresses
55
- * only). It resolves to a standard Response or rejects; a rejection whose
71
+ * call. A request to the origin of one of its originFields credentials (a site
72
+ * or instance URL the user gave) is an API call too, checked like a media URL:
73
+ * https, public addresses only, connected to the checked address, and its
74
+ * redirects are not followed. A PUT or POST with a body to a host in its
75
+ * uploadHosts is an upload, checked the same way, on the default https port
76
+ * and with no Authorization, Proxy-Authorization or Cookie header. Any other
77
+ * URL is a media download (GET only, public https addresses only, no headers
78
+ * but Accept, User-Agent and one byte range as `Range: bytes=FIRST-LAST`,
79
+ * whose 206 reply comes back as it is; the host's size cap applies to each
80
+ * request). It resolves to a standard Response or rejects; a rejection whose
56
81
  * `code` is "URL_REFUSED" means nothing was sent.
57
82
  */
58
83
  export type ConnectorFetch = (url: string, init?: ConnectorRequestInit) => Promise<Response>;
@@ -63,20 +88,86 @@ export type ConnectorFetch = (url: string, init?: ConnectorRequestInit) => Promi
63
88
  export type ConnectorAccounts = Record<string, string[]> | null;
64
89
  /** Passed to every call. Nothing in it outlives the call inside the module, except cached sessions. */
65
90
  export interface ToolContext {
91
+ /**
92
+ * The connection's credentials, by the names the module declares. For an
93
+ * OAuth connection, `access_token` holds the host's current access token:
94
+ * the host refreshes it, and the module never stores it.
95
+ */
66
96
  credentials: Record<string, string>;
67
97
  accounts: ConnectorAccounts;
68
98
  fetch: ConnectorFetch;
69
99
  signal?: AbortSignal;
70
100
  log(text: string): void;
101
+ /**
102
+ * Given by a host that takes files with a result: the most bytes the files
103
+ * of one call may hold in all (the stdio CLI: 25 MiB). A host that takes no
104
+ * files leaves it out, and tools then hand none back.
105
+ */
106
+ files?: {
107
+ maxBytes: number;
108
+ };
109
+ }
110
+ /**
111
+ * An account selection a host offers once a connection is made, e.g. the
112
+ * Pages an agent may post to. The host runs `tool` with no arguments (and
113
+ * then with `cursor` set to the result's nextCursor, while there is one),
114
+ * reads the id and the name of each item in the list it returns at `idField`
115
+ * and `nameField`, and passes the chosen ids on every call as
116
+ * ctx.accounts[key]. The module's account lock refuses any other account.
117
+ */
118
+ export interface AccountPicker {
119
+ /** The ctx.accounts key, ^[a-z][a-z0-9_]{0,63}$, e.g. "pages". */
120
+ key: string;
121
+ /** What is chosen, e.g. "Facebook Pages". */
122
+ label: string;
123
+ /** A sentence for the person choosing, e.g. "The Pages the agent may post to." */
124
+ description?: string;
125
+ /** true when several may be chosen, false when one is. */
126
+ multiple: boolean;
127
+ /** The module's read tool that lists the candidates; it takes no required argument. */
128
+ tool: string;
129
+ /** The dot path of an item's id, e.g. "id" or "account.id". */
130
+ idField: string;
131
+ /** The dot path of an item's display name, e.g. "name". */
132
+ nameField: string;
133
+ /** The field an older setup kept this selection in, for a host that migrates it, e.g. "pageid". */
134
+ legacyField?: string;
71
135
  }
72
136
  /** What dist/vendors/<vendor>.js exports. */
73
137
  export interface ConnectorModule {
74
138
  /** ^[a-z][a-z0-9-]{1,29}$, equal to the file name. */
75
139
  vendor: string;
76
- /** The only API origins the module calls, e.g. ["https://dev.to"]. */
140
+ /** The fixed API origins the module calls, e.g. ["https://dev.to"]. */
77
141
  origins: string[];
142
+ /**
143
+ * Credentials whose value is a site or instance URL, e.g. ["instance_url"]
144
+ * (empty when unused). Per call, the module may also reach the https origin
145
+ * of each such value; hosts resolve it the same way (parseSiteUrl) and apply
146
+ * their SSRF rules to it.
147
+ */
148
+ originFields: string[];
149
+ /**
150
+ * The hosts the module may send an upload to: a PUT or POST with a body to
151
+ * an address its vendor's API returned, such as a pre-signed part address
152
+ * (empty when unused). An entry with a leading dot matches every host under
153
+ * it (".blobstore.apple.com" matches store-030.blobstore.apple.com, not
154
+ * blobstore.apple.com), one without only that host; lowercase host names of
155
+ * at least two labels, no IP addresses, none twice. Hosts send no
156
+ * credentials there, check its addresses like a media URL's and never follow
157
+ * its redirects. A module built before it existed has none.
158
+ */
159
+ uploadHosts: string[];
78
160
  /** The ctx.credentials names the module reads, e.g. ["api_key"]. */
79
161
  credentials: string[];
162
+ /**
163
+ * The credentials a call needs, as alternatives: a call goes ahead when
164
+ * every credential of at least one list has a value, e.g. [["access_token"],
165
+ * ["system_user_token"]]. A credential in no list is optional. By default
166
+ * one list of every credential, so all are required.
167
+ */
168
+ requiredCredentials: string[][];
169
+ /** The account selections a host offers after connecting (empty when none). */
170
+ accountPickers: AccountPicker[];
80
171
  tools: ToolDescriptor[];
81
172
  call(toolName: string, args: unknown, ctx: ToolContext): Promise<CallToolResult>;
82
173
  }