@wiro-ai/wiro-agent-connectors 0.1.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 ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ The first release: three connectors, and the stdio CLI that runs them.
6
+
7
+ - `serper`: `web_search`, Google results through Serper with the answer box, knowledge graph, related questions and related searches.
8
+ - `devto`: `list_my_articles`, `create_draft_article` and `update_article`, draft-first publishing on dev.to with the AI disclosure dev.to asks for.
9
+ - `bluesky`: `get_profile`, `list_my_posts` and `create_post`, with clickable links, mentions and hashtags and an optional image with alt text.
10
+ - Each connector is one dependency-free CommonJS file, `dist/vendors/<vendor>.js`, that exports `{ vendor, origins, credentials, tools, call }` and makes every request through the host's `ctx.fetch`.
11
+ - `npx @wiro-ai/wiro-agent-connectors <vendor>` serves a connector over stdio, with credentials from `<VENDOR>_<CREDENTIAL>` environment variables and a guarded fetch: origin lock, timeouts, size caps and an SSRF guard for media URLs.
12
+ - Results stay under 32 KB with a cursor for more, rate limits come back with `retryAfter`, and writes are never retried: an unclear outcome is reported as unknown, with the read tool to check.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wiro AI, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,190 @@
1
+ <div align="center">
2
+
3
+ <img src="https://raw.githubusercontent.com/wiroai/Wiro-Agent-Connectors/main/.github/assets/wiro-logo.png" alt="Wiro AI" width="240">
4
+
5
+ # Wiro Agent Connectors
6
+
7
+ MCP connectors for services that have no official MCP server. One small, dependency-free module per service, ready for Claude, Cursor and any other MCP client.
8
+
9
+ [![npm](https://img.shields.io/npm/v/@wiro-ai/wiro-agent-connectors?style=for-the-badge&color=111111)](https://www.npmjs.com/package/@wiro-ai/wiro-agent-connectors) [![Node.js 22+](https://img.shields.io/badge/Node.js-22%2B-111111?style=for-the-badge&color=111111)](#quick-start) [![MCP server](https://img.shields.io/badge/MCP-server-111111?style=for-the-badge&color=111111)](https://modelcontextprotocol.io/) [![License: MIT](https://img.shields.io/badge/license-MIT-111111?style=for-the-badge&color=111111)](./LICENSE)
10
+
11
+ [Website](https://wiro.ai) · [Add your connector](./CONTRIBUTING.md) · [Wiro MCP](https://github.com/wiroai/Wiro-MCP) · [All Wiro AI open source](https://wiroai.github.io)
12
+
13
+ <img src="https://wiro.ai/images/koala/accent-heavy-koala.png" alt="Wiro AI koala mascot" width="60" />
14
+
15
+ </div>
16
+
17
+ Many services an AI agent should work with, such as a blog platform, a social network or a search API, have a good HTTP API and no MCP server. This repository closes that gap with one connector per service. Each connector is a single file with a list of tools and a `call` function, and it has no dependencies: every request goes through a `fetch` that the host hands it, so the host decides where it may connect. Run any connector locally over stdio with `npx`, or load the modules into your own MCP host. Your credentials stay with you: they come from your environment on each call, and a connector never stores or logs them.
18
+
19
+ ## Connectors
20
+
21
+ | Connector | What it can do | Auth | Status |
22
+ | --- | --- | --- | --- |
23
+ | `serper` | Google search results through [Serper](https://serper.dev): organic results, answer box, knowledge graph, related questions | Serper API key | Available |
24
+ | `devto` | [dev.to](https://dev.to) articles: list your articles with their stats, save drafts, publish and edit | dev.to API key | Available |
25
+ | `bluesky` | [Bluesky](https://bsky.app): read profiles, list your recent posts, post text with clickable links, mentions and hashtags, and an optional image | Handle and app password | Available |
26
+
27
+ Missing a service? [Add your connector](#add-your-connector) or [ask for one](https://github.com/wiroai/Wiro-Agent-Connectors/issues/new?template=new_connector.yml).
28
+
29
+ ## Quick start
30
+
31
+ Requires Node.js 22 or later. Start a connector by name; it reads its credentials from environment variables named `<VENDOR>_<CREDENTIAL>`:
32
+
33
+ ```bash
34
+ DEVTO_API_KEY=your-key npx -y @wiro-ai/wiro-agent-connectors devto
35
+ ```
36
+
37
+ `npx -y @wiro-ai/wiro-agent-connectors --list` prints every connector with its tools and variables.
38
+
39
+ | Connector | Environment variables | Where to get them |
40
+ | --- | --- | --- |
41
+ | `serper` | `SERPER_API_KEY` | The API key on your [serper.dev](https://serper.dev) dashboard. |
42
+ | `devto` | `DEVTO_API_KEY` | dev.to → Settings → Extensions → DEV Community API Keys → Generate API Key. |
43
+ | `bluesky` | `BLUESKY_IDENTIFIER`, `BLUESKY_APP_PASSWORD` | Your handle (such as `alice.bsky.social`) and an app password from Bluesky → Settings → Privacy and security → App passwords. Never your account password. Accounts hosted by Bluesky only. |
44
+
45
+ A connector without its variables still starts and lists its tools; each call then answers with the variable to set.
46
+
47
+ ### Claude Desktop
48
+
49
+ Add to `claude_desktop_config.json`:
50
+
51
+ ```json
52
+ {
53
+ "mcpServers": {
54
+ "devto": {
55
+ "type": "stdio",
56
+ "command": "npx",
57
+ "args": ["-y", "@wiro-ai/wiro-agent-connectors", "devto"],
58
+ "env": {
59
+ "DEVTO_API_KEY": "your-dev-to-api-key"
60
+ }
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ ### Claude Code
67
+
68
+ ```bash
69
+ claude mcp add --transport stdio bluesky \
70
+ --env BLUESKY_IDENTIFIER=alice.bsky.social \
71
+ --env BLUESKY_APP_PASSWORD=xxxx-xxxx-xxxx-xxxx \
72
+ -- npx -y @wiro-ai/wiro-agent-connectors bluesky
73
+ ```
74
+
75
+ ### Cursor
76
+
77
+ Add to `~/.cursor/mcp.json`, or to `.cursor/mcp.json` in a project:
78
+
79
+ ```json
80
+ {
81
+ "mcpServers": {
82
+ "serper": {
83
+ "command": "npx",
84
+ "args": ["-y", "@wiro-ai/wiro-agent-connectors", "serper"],
85
+ "env": {
86
+ "SERPER_API_KEY": "your-serper-api-key"
87
+ }
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ Run several connectors side by side by adding one entry per connector.
94
+
95
+ ## Tools
96
+
97
+ Every tool carries honest MCP annotations, derived from what it does: a read tool can only send GET requests (or a request that changes nothing, such as a sign-in or a search sent by POST), and each write tool says whether it adds, overwrites or removes.
98
+
99
+ ### serper
100
+
101
+ | Tool | Kind | What it does |
102
+ | --- | --- | --- |
103
+ | `web_search` | read | Google results for a query: title, link, snippet, position and date of each result, plus the answer box, knowledge graph, related questions and related searches. Options for country, language and freshness (past hour to past year). |
104
+
105
+ ### devto
106
+
107
+ | Tool | Kind | What it does |
108
+ | --- | --- | --- |
109
+ | `list_my_articles` | read | Your drafts and published articles, newest first, with URLs, edit links, tags, page views, reactions and comments. |
110
+ | `create_draft_article` | create | Saves an unpublished draft: title, Markdown body, up to 4 tags, cover image, canonical URL, series, organization, and the AI disclosure dev.to asks for. Nothing becomes public. |
111
+ | `update_article` | update | Publishes a draft, turns an article back into a draft, or changes its fields. Only the fields given change. |
112
+
113
+ ### bluesky
114
+
115
+ | Tool | Kind | What it does |
116
+ | --- | --- | --- |
117
+ | `get_profile` | read | A profile with its counts; the connected account by default. |
118
+ | `list_my_posts` | read | Your recent posts with likes, reposts, replies and quotes. |
119
+ | `create_post` | create | Posts right away: up to 300 characters, with links, mentions and hashtags made clickable, and optionally one JPEG, PNG or WebP image from a public https URL with alt text. |
120
+
121
+ ## How it works
122
+
123
+ A connector is one CommonJS file, `dist/vendors/<vendor>.js`, built from `src/vendors/<vendor>/`. It uses web-standard globals only (no `require`, no Node APIs), so a host can load it without `node_modules`:
124
+
125
+ ```js
126
+ module.exports = {
127
+ vendor: 'devto', // ^[a-z][a-z0-9-]{1,29}$
128
+ origins: ['https://dev.to'], // the only API origins it calls
129
+ credentials: ['api_key'], // the names it reads from ctx.credentials
130
+ tools: [{ name, title, description, inputSchema, annotations }],
131
+ async call(toolName, args, ctx) {} // returns an MCP CallToolResult
132
+ };
133
+ // ctx = { credentials, accounts, fetch, signal, log }
134
+ ```
135
+
136
+ `ctx.fetch` is the host's guarded fetch. A request to one of the module's `origins` is an API call; any other URL is a media download (for example an image to post), which the host allows only as a GET to a public https address. A host refuses anything else before sending it and rejects with `code: "URL_REFUSED"`, which tells the module nothing was sent.
137
+
138
+ The stdio CLI is one such host. You can be another: the package exports the modules and the CLI's building blocks.
139
+
140
+ ```js
141
+ const { loadConnector, createGuardedFetch } = require('@wiro-ai/wiro-agent-connectors');
142
+
143
+ const devto = loadConnector('devto'); // or require('@wiro-ai/wiro-agent-connectors/vendors/devto')
144
+ const result = await devto.call('list_my_articles', { per_page: 5 }, {
145
+ credentials: { api_key: process.env.DEVTO_API_KEY },
146
+ accounts: null, // no account lock
147
+ fetch: createGuardedFetch({ origins: devto.origins }),
148
+ log: (line) => console.error(line),
149
+ });
150
+ ```
151
+
152
+ Results are a single JSON text block, trimmed to the fields an agent needs and kept under 32 KB. A longer list comes back in pages: pass `nextCursor` back as `cursor`. Errors come back as results with `isError: true` and a sentence that says what happened, plus the vendor's HTTP `status` and, for a rate limit, `retryAfter` in seconds.
153
+
154
+ ### Account lock
155
+
156
+ Tools that act on one of several accounts (pages, ad accounts, channels) check the account against `ctx.accounts`, for example `{ "pages": ["123"] }`, before sending anything. In the CLI, set `CONNECTOR_ACCOUNTS` to that JSON to apply a lock; without it there is none. None of the current connectors takes an account argument yet.
157
+
158
+ ## Security
159
+
160
+ - **Credentials are never stored or logged.** They arrive with each call, from your environment in the CLI. The one thing kept in memory is a Bluesky session token, for up to 10 minutes, keyed by a SHA-256 hash of the credentials, because Bluesky allows only 30 sign-ins per 5 minutes and 300 per day. Log lines carry the connector, tool, HTTP method, status and duration, never arguments, credentials or content.
161
+ - **Origin lock.** A connector only reaches its declared origins; the host refuses any other API URL.
162
+ - **SSRF guard on media.** A media URL must be https, must resolve to public addresses only (no loopback, private, link-local, carrier-grade NAT or reserved ranges, IPv4 and IPv6 alike), and every redirect is checked the same way, at most 5. The connection goes to the address that was checked, and no credential header is sent with it.
163
+ - **Limits.** Requests time out after 30 seconds, API replies are capped at 8 MiB by the CLI and 4 MiB by the modules, and media downloads at 25 MiB (Bluesky images at 2,000,000 bytes).
164
+ - **Writes are never retried.** When a write gets no clear answer (a timeout, a broken connection, a 5xx), the result is `{ "outcome": "unknown", "check": "<read tool>" }`, so the agent checks before trying again instead of posting twice. Rate limits are passed back with `retryAfter`, never queued.
165
+ - **White-label.** Tool names, descriptions and messages name only the service.
166
+
167
+ Found a vulnerability? Please report it privately, see [SECURITY.md](./SECURITY.md).
168
+
169
+ ## Add your connector
170
+
171
+ New connectors are welcome. Copy `src/vendors/_template/`, declare the service's origins and credentials, write the tools, and test them against recorded responses; the template and [CONTRIBUTING.md](./CONTRIBUTING.md) walk you through it, and the build checks the rest. A good connector is one file, has no runtime dependencies, sends every request through `ctx.fetch`, and has honest annotations.
172
+
173
+ **[Read the contributing guide →](./CONTRIBUTING.md)**
174
+
175
+ ## Development
176
+
177
+ ```bash
178
+ npm ci
179
+ npm run typecheck
180
+ npm test # builds, then runs every test with mocked HTTP
181
+ npm run build
182
+ npm run smoke -- devto # one live read with your own account (credentials from the environment or .env)
183
+ npm run smoke -- devto --write # plus one live write
184
+ ```
185
+
186
+ `npm run build` writes the CLI to `dist/` and each connector to `dist/vendors/<vendor>.js`.
187
+
188
+ ## License
189
+
190
+ MIT, see [LICENSE](./LICENSE).
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // wiro-agent-connectors <vendor>: serves one connector over stdio, with the
4
+ // vendor's credentials read from the environment.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const index_js_1 = require("./host/index.js");
7
+ // The package version, for the MCP server info and --version.
8
+ const { version } = require('../package.json');
9
+ const USAGE = `Usage: wiro-agent-connectors <vendor>
10
+
11
+ Serves one connector as an MCP server over stdio. Each connector reads its
12
+ credentials from environment variables named <VENDOR>_<CREDENTIAL>.
13
+
14
+ Options:
15
+ --list List the connectors with their tools and environment variables
16
+ --version Print the version
17
+ --help Print this help`;
18
+ function describeVendors() {
19
+ return (0, index_js_1.listVendors)()
20
+ .map((vendor) => {
21
+ const module = (0, index_js_1.loadConnector)(vendor);
22
+ const env = module.credentials.map((name) => (0, index_js_1.envNameFor)(vendor, name)).join(', ');
23
+ return `${vendor}\n env: ${env || '(none)'}\n tools: ${module.tools.map((tool) => tool.name).join(', ')}`;
24
+ })
25
+ .join('\n\n');
26
+ }
27
+ async function main(argv) {
28
+ const [first] = argv;
29
+ if (!first || first === '--help' || first === '-h') {
30
+ process.stdout.write(`${USAGE}\n`);
31
+ if (!first)
32
+ process.exitCode = 1;
33
+ return;
34
+ }
35
+ if (first === '--version' || first === '-v') {
36
+ process.stdout.write(`${version}\n`);
37
+ return;
38
+ }
39
+ if (first === '--list') {
40
+ process.stdout.write(`${describeVendors()}\n`);
41
+ return;
42
+ }
43
+ let module;
44
+ try {
45
+ module = (0, index_js_1.loadConnector)(first);
46
+ }
47
+ catch (error) {
48
+ process.stderr.write(`${error.message} Available: ${(0, index_js_1.listVendors)().join(', ')}.\n`);
49
+ process.exitCode = 1;
50
+ return;
51
+ }
52
+ const { credentials, missing } = (0, index_js_1.credentialsFromEnv)(module, process.env);
53
+ const accounts = (0, index_js_1.accountsFromEnv)(process.env);
54
+ if (missing.length) {
55
+ process.stderr.write(`${module.vendor}: ${missing.join(' and ')} ${missing.length > 1 ? 'are' : 'is'} not set; tools will answer with an error until ${missing.length > 1 ? 'they are' : 'it is'}.\n`);
56
+ }
57
+ await (0, index_js_1.serveStdio)(module, {
58
+ credentials,
59
+ accounts,
60
+ version,
61
+ ...(missing.length
62
+ ? { missingCredentials: `This server has no credentials for ${module.vendor}: set ${missing.join(' and ')} in its environment and restart it.` }
63
+ : {}),
64
+ });
65
+ }
66
+ main(process.argv.slice(2)).catch((error) => {
67
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
68
+ process.exit(1);
69
+ });
@@ -0,0 +1,16 @@
1
+ import type { ConnectorAccounts, ConnectorModule } from '../types.js';
2
+ /** The environment variable a credential is read from: <VENDOR>_<CREDENTIAL>, e.g. DEVTO_API_KEY. */
3
+ export declare function envNameFor(vendor: string, credential: string): string;
4
+ export interface EnvCredentials {
5
+ credentials: Record<string, string>;
6
+ /** The variables that are not set, e.g. ["DEVTO_API_KEY"]. */
7
+ missing: string[];
8
+ }
9
+ export declare function credentialsFromEnv(module: Pick<ConnectorModule, 'vendor' | 'credentials'>, env: NodeJS.ProcessEnv): EnvCredentials;
10
+ /** The variable that limits account-scoped arguments in the CLI. */
11
+ export declare const ACCOUNTS_ENV = "CONNECTOR_ACCOUNTS";
12
+ /**
13
+ * Account selections from CONNECTOR_ACCOUNTS: JSON such as {"pages":["123"]},
14
+ * or the same JSON in base64url. Unset means no account lock (null).
15
+ */
16
+ export declare function accountsFromEnv(env: NodeJS.ProcessEnv): ConnectorAccounts;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ACCOUNTS_ENV = void 0;
4
+ exports.envNameFor = envNameFor;
5
+ exports.credentialsFromEnv = credentialsFromEnv;
6
+ exports.accountsFromEnv = accountsFromEnv;
7
+ /** The environment variable a credential is read from: <VENDOR>_<CREDENTIAL>, e.g. DEVTO_API_KEY. */
8
+ function envNameFor(vendor, credential) {
9
+ return `${vendor}_${credential}`.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
10
+ }
11
+ function credentialsFromEnv(module, env) {
12
+ const credentials = {};
13
+ const missing = [];
14
+ for (const name of module.credentials) {
15
+ const variable = envNameFor(module.vendor, name);
16
+ const value = env[variable]?.trim();
17
+ if (value)
18
+ credentials[name] = value;
19
+ else
20
+ missing.push(variable);
21
+ }
22
+ return { credentials, missing };
23
+ }
24
+ /** The variable that limits account-scoped arguments in the CLI. */
25
+ exports.ACCOUNTS_ENV = 'CONNECTOR_ACCOUNTS';
26
+ /**
27
+ * Account selections from CONNECTOR_ACCOUNTS: JSON such as {"pages":["123"]},
28
+ * or the same JSON in base64url. Unset means no account lock (null).
29
+ */
30
+ function accountsFromEnv(env) {
31
+ const raw = env[exports.ACCOUNTS_ENV]?.trim();
32
+ if (!raw)
33
+ return null;
34
+ let parsed;
35
+ try {
36
+ parsed = JSON.parse(raw.startsWith('{') ? raw : Buffer.from(raw, 'base64url').toString('utf8'));
37
+ }
38
+ catch {
39
+ throw new Error(`${exports.ACCOUNTS_ENV} must be JSON like {"pages":["123"]} (or that JSON in base64url).`);
40
+ }
41
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
42
+ throw new Error(`${exports.ACCOUNTS_ENV} must be a JSON object of lists, like {"pages":["123"]}.`);
43
+ }
44
+ const accounts = {};
45
+ for (const [key, value] of Object.entries(parsed)) {
46
+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string' || typeof item === 'number')) {
47
+ throw new Error(`${exports.ACCOUNTS_ENV}: "${key}" must be a list of ids.`);
48
+ }
49
+ accounts[key] = value.map(String);
50
+ }
51
+ return accounts;
52
+ }
@@ -0,0 +1,40 @@
1
+ import type { ConnectorFetch } from '../types.js';
2
+ export type ConnectorFetchErrorCode = 'URL_REFUSED' | 'TOO_LARGE' | 'TIMEOUT' | 'ABORTED' | 'NETWORK';
3
+ export declare class ConnectorFetchError extends Error {
4
+ readonly code: ConnectorFetchErrorCode;
5
+ constructor(code: ConnectorFetchErrorCode, message: string);
6
+ }
7
+ export interface ResolvedAddress {
8
+ address: string;
9
+ family: number;
10
+ }
11
+ export interface MediaReply {
12
+ status: number;
13
+ headers: Record<string, string | string[] | undefined>;
14
+ body: AsyncIterable<Uint8Array>;
15
+ destroy(): void;
16
+ }
17
+ /** One HTTPS request to an already checked address. */
18
+ export type MediaTransport = (request: {
19
+ url: URL;
20
+ address: ResolvedAddress;
21
+ method: 'GET' | 'HEAD';
22
+ headers: Record<string, string>;
23
+ signal: AbortSignal;
24
+ }) => Promise<MediaReply>;
25
+ export interface GuardedFetchOptions {
26
+ /** The module's origins. */
27
+ origins: readonly string[];
28
+ /** Per request, API and media alike (default 30 s). */
29
+ timeoutMs?: number;
30
+ /** The largest API reply (default 8 MiB). */
31
+ maxResponseBytes?: number;
32
+ /** The largest media download (default 25 MiB). */
33
+ maxMediaBytes?: number;
34
+ maxRedirects?: number;
35
+ /** Replacements for tests: the API fetch, the DNS lookup and the media transport. */
36
+ apiFetch?: typeof fetch;
37
+ resolve?: (hostname: string) => Promise<ResolvedAddress[]>;
38
+ mediaTransport?: MediaTransport;
39
+ }
40
+ export declare function createGuardedFetch(options: GuardedFetchOptions): ConnectorFetch;
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ConnectorFetchError = void 0;
7
+ exports.createGuardedFetch = createGuardedFetch;
8
+ const node_dns_1 = __importDefault(require("node:dns"));
9
+ const node_https_1 = __importDefault(require("node:https"));
10
+ const node_net_1 = __importDefault(require("node:net"));
11
+ const ip_js_1 = require("./ip.js");
12
+ class ConnectorFetchError extends Error {
13
+ code;
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = 'ConnectorFetchError';
18
+ }
19
+ }
20
+ exports.ConnectorFetchError = ConnectorFetchError;
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
23
+ const DEFAULT_MAX_MEDIA_BYTES = 25 * 1024 * 1024;
24
+ const DEFAULT_MAX_REDIRECTS = 5;
25
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
26
+ const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
27
+ const MEDIA_HEADERS = new Set(['accept', 'user-agent']);
28
+ function refuse(message) {
29
+ throw new ConnectorFetchError('URL_REFUSED', message);
30
+ }
31
+ async function systemResolve(hostname) {
32
+ return node_dns_1.default.promises.lookup(hostname, { all: true, verbatim: true });
33
+ }
34
+ /** 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) => {
36
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
37
+ const request = node_https_1.default.request({
38
+ protocol: 'https:',
39
+ hostname,
40
+ port: url.port || 443,
41
+ path: `${url.pathname}${url.search}`,
42
+ method,
43
+ headers,
44
+ signal,
45
+ agent: false,
46
+ ...(node_net_1.default.isIP(hostname) ? {} : { servername: hostname }),
47
+ lookup: (_host, options, callback) => {
48
+ if (options?.all)
49
+ callback(null, [{ address: address.address, family: address.family }]);
50
+ else
51
+ callback(null, address.address, address.family);
52
+ },
53
+ }, (response) => {
54
+ resolve({
55
+ status: response.statusCode ?? 0,
56
+ headers: response.headers,
57
+ body: response,
58
+ destroy: () => response.destroy(),
59
+ });
60
+ });
61
+ request.on('error', reject);
62
+ request.end();
63
+ });
64
+ function timeoutSignal(timeoutMs, outer) {
65
+ const timer = AbortSignal.timeout(timeoutMs);
66
+ return {
67
+ signal: outer ? AbortSignal.any([outer, timer]) : timer,
68
+ timedOut: () => timer.aborted,
69
+ };
70
+ }
71
+ function failure(error, timedOut, outer) {
72
+ if (error instanceof ConnectorFetchError)
73
+ return error;
74
+ if (timedOut)
75
+ return new ConnectorFetchError('TIMEOUT', 'the request timed out');
76
+ if (outer?.aborted)
77
+ return new ConnectorFetchError('ABORTED', 'the request was cancelled');
78
+ const cause = error?.cause?.code ?? error?.code;
79
+ return new ConnectorFetchError('NETWORK', typeof cause === 'string' ? `network error (${cause})` : 'network error');
80
+ }
81
+ /** A stream that errors once more than `maxBytes` pass through it. */
82
+ function capStream(body, maxBytes) {
83
+ let total = 0;
84
+ return body.pipeThrough(new TransformStream({
85
+ transform(chunk, controller) {
86
+ total += chunk.byteLength;
87
+ if (total > maxBytes)
88
+ controller.error(new ConnectorFetchError('TOO_LARGE', `the reply is larger than ${maxBytes} bytes`));
89
+ else
90
+ controller.enqueue(chunk);
91
+ },
92
+ }));
93
+ }
94
+ function toHeaders(raw) {
95
+ const headers = new Headers();
96
+ for (const [name, value] of Object.entries(raw)) {
97
+ for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) {
98
+ try {
99
+ headers.append(name, item);
100
+ }
101
+ catch {
102
+ // a header a Response cannot carry is left out
103
+ }
104
+ }
105
+ }
106
+ return headers;
107
+ }
108
+ function createGuardedFetch(options) {
109
+ const origins = new Set(options.origins);
110
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
111
+ const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
112
+ const maxMediaBytes = options.maxMediaBytes ?? DEFAULT_MAX_MEDIA_BYTES;
113
+ const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
114
+ const resolve = options.resolve ?? systemResolve;
115
+ const transport = options.mediaTransport ?? httpsTransport;
116
+ async function api(url, init) {
117
+ const apiFetch = options.apiFetch ?? globalThis.fetch;
118
+ const timer = timeoutSignal(timeoutMs, init.signal);
119
+ let response;
120
+ try {
121
+ response = await apiFetch(url, {
122
+ method: init.method ?? 'GET',
123
+ ...(init.headers ? { headers: init.headers } : {}),
124
+ ...(init.body !== undefined ? { body: init.body } : {}),
125
+ signal: timer.signal,
126
+ redirect: 'manual',
127
+ });
128
+ }
129
+ catch (error) {
130
+ throw failure(error, timer.timedOut(), init.signal);
131
+ }
132
+ const declared = Number(response.headers.get('content-length'));
133
+ if (Number.isFinite(declared) && declared > maxResponseBytes) {
134
+ await response.body?.cancel().catch(() => { });
135
+ throw new ConnectorFetchError('TOO_LARGE', `the reply is larger than ${maxResponseBytes} bytes`);
136
+ }
137
+ const body = response.body && !NULL_BODY_STATUSES.has(response.status) ? capStream(response.body, maxResponseBytes) : null;
138
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
139
+ }
140
+ async function media(start, init) {
141
+ const method = (init.method ?? 'GET').toUpperCase();
142
+ if (method !== 'GET' && method !== 'HEAD')
143
+ refuse(`only GET and HEAD may go to ${start.origin}, which is not an API origin of this connector`);
144
+ if (init.body !== undefined)
145
+ refuse('a media download cannot carry a body');
146
+ const headers = {};
147
+ for (const [name, value] of Object.entries(init.headers ?? {})) {
148
+ if (MEDIA_HEADERS.has(name.toLowerCase()))
149
+ headers[name.toLowerCase()] = value;
150
+ }
151
+ const timer = timeoutSignal(timeoutMs, init.signal);
152
+ let url = start;
153
+ try {
154
+ for (let hop = 0;; hop++) {
155
+ if (url.protocol !== 'https:')
156
+ refuse(`only https URLs can be downloaded, not ${url.protocol}`);
157
+ if (url.username || url.password)
158
+ 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 });
176
+ if (REDIRECTS.has(reply.status)) {
177
+ reply.destroy();
178
+ const location = reply.headers['location'];
179
+ if (typeof location !== 'string' || !location)
180
+ throw new ConnectorFetchError('NETWORK', `a redirect (HTTP ${reply.status}) without a location`);
181
+ if (hop >= maxRedirects)
182
+ refuse(`more than ${maxRedirects} redirects`);
183
+ url = new URL(location, url);
184
+ continue;
185
+ }
186
+ if (reply.status < 200 || reply.status > 599) {
187
+ reply.destroy();
188
+ throw new ConnectorFetchError('NETWORK', `an invalid HTTP status (${reply.status})`);
189
+ }
190
+ const declared = Number(reply.headers['content-length']);
191
+ if (Number.isFinite(declared) && declared > maxMediaBytes) {
192
+ 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) });
218
+ }
219
+ }
220
+ catch (error) {
221
+ throw failure(error, timer.timedOut(), init.signal);
222
+ }
223
+ }
224
+ return async function guardedFetch(input, init = {}) {
225
+ let url;
226
+ try {
227
+ url = new URL(input);
228
+ }
229
+ catch {
230
+ refuse('not a valid URL');
231
+ }
232
+ if (origins.has(url.origin))
233
+ return api(url, init);
234
+ return media(url, init);
235
+ };
236
+ }
@@ -0,0 +1,9 @@
1
+ export { ACCOUNTS_ENV, accountsFromEnv, credentialsFromEnv, envNameFor } from './env.js';
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';
5
+ export { isPublicAddress } from './ip.js';
6
+ export { assertConnectorModule, DEFAULT_VENDORS_DIR, listVendors, loadConnector, VENDOR_PATTERN } from './load.js';
7
+ export { createConnectorServer, serveStdio } from './server.js';
8
+ export type { ConnectorServerOptions } from './server.js';
9
+ export type { CallToolResult, ConnectorAccounts, ConnectorFetch, ConnectorModule, ConnectorRequestInit, JsonSchema, TextContent, ToolAnnotations, ToolContext, ToolDescriptor, } from '../types.js';