mcp-controld 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fundryi
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,237 @@
1
+ # Control D MCP Server
2
+
3
+ Manage your [Control D](https://controld.com) DNS setup by talking to an AI assistant. `mcp-controld` wraps the Control D REST API as MCP tools and speaks stdio, so it works with Claude Code, Claude Desktop, Codex CLI, Cursor, and any other MCP client.
4
+
5
+ [![CI](https://github.com/Fundryi/MCP-ControlD/actions/workflows/ci.yml/badge.svg)](https://github.com/Fundryi/MCP-ControlD/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ ![Node](https://img.shields.io/badge/node-%3E%3D22-brightgreen)
8
+
9
+ **Status:** working, pre-1.0.
10
+
11
+ ## What you can ask for
12
+
13
+ Read-only, out of the box:
14
+
15
+ - "List my Control D profiles and show which filters are on for the main one."
16
+ - "Why would `example.com` be blocked on profile 1234567890?"
17
+ - "What IPs have been talking to device `abcdefghij` lately?"
18
+ - "Is the Control D network having problems right now?"
19
+
20
+ With writes enabled:
21
+
22
+ - "Block `example.com` on my kids profile."
23
+ - "Create a rule folder called Work and put these five domains in it."
24
+ - "Turn on the malware filter for every profile."
25
+
26
+ ## Requirements
27
+
28
+ - Node.js 22 or newer. Node 20 is past end of life.
29
+ - A Control D account and an API token
30
+
31
+ ## Get an API token
32
+
33
+ Create a token in the Control D dashboard. Tokens are scoped **read** or **write**, and they can be locked to specific IP addresses. See the [Control D API docs](https://docs.controld.com/reference/get-started) for details.
34
+
35
+ Start with a read token. That alone is enough to run the server, and it cannot change anything. Add a separate write token later if you want the server to make changes.
36
+
37
+ ## Configuration
38
+
39
+ Everything comes from environment variables, supplied by your MCP client. The server reads no config files and accepts no command-line flags for secrets, because flags show up in process lists and shell history.
40
+
41
+ | Variable | Required | What it does |
42
+ |---|---|---|
43
+ | `CONTROLD_API_TOKEN_READ` | yes | Read token. Every GET uses it. The server will not start without it. |
44
+ | `CONTROLD_API_TOKEN_WRITE` | no | Write token. Without a write credential, write tools are never registered and the server cannot change anything. |
45
+ | `CONTROLD_ORG_ID` | no | Sent as `X-Force-Org-Id` on every request. Organization accounts only. A per-call `sub_org_id` overrides it. |
46
+ | `CONTROLD_API_BASE_URL` | no | Defaults to `https://api.controld.com`. Must be https, unless it points at a loopback host for local testing. |
47
+ | `CONTROLD_API_TOKEN` | no | Older single-token setup. Still works. On its own it grants reads only. Add `CONTROLD_ENABLE_WRITES=1` to also allow writes. |
48
+
49
+ Splitting the tokens is the point: reads keep using a read-scoped credential even on a server that can write, so a read tool cannot mutate anything even if something goes wrong upstream of it.
50
+
51
+ ## Setup
52
+
53
+ There is nothing to install and no setup command to run. Point your MCP client at `npx mcp-controld` and it fetches and starts the server for you.
54
+
55
+ ### Claude Code
56
+
57
+ ```sh
58
+ claude mcp add controld -e CONTROLD_API_TOKEN_READ=YOUR_API_TOKEN -- npx -y mcp-controld
59
+ ```
60
+
61
+ ### Claude Desktop
62
+
63
+ In `claude_desktop_config.json`:
64
+
65
+ ```json
66
+ {
67
+ "mcpServers": {
68
+ "controld": {
69
+ "command": "npx",
70
+ "args": ["-y", "mcp-controld"],
71
+ "env": {
72
+ "CONTROLD_API_TOKEN_READ": "YOUR_API_TOKEN"
73
+ }
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ ### Codex CLI
80
+
81
+ In `~/.codex/config.toml` or a project `.codex/config.toml`:
82
+
83
+ ```toml
84
+ [mcp_servers.controld]
85
+ command = "npx"
86
+ args = ["-y", "mcp-controld"]
87
+
88
+ [mcp_servers.controld.env]
89
+ CONTROLD_API_TOKEN_READ = "YOUR_API_TOKEN"
90
+ ```
91
+
92
+ ### Cursor
93
+
94
+ In `mcp.json`:
95
+
96
+ ```json
97
+ {
98
+ "mcpServers": {
99
+ "controld": {
100
+ "command": "npx",
101
+ "args": ["-y", "mcp-controld"],
102
+ "env": {
103
+ "CONTROLD_API_TOKEN_READ": "YOUR_API_TOKEN"
104
+ }
105
+ }
106
+ }
107
+ }
108
+ ```
109
+
110
+ Keep these config files out of version control. They contain your token.
111
+
112
+ ### Running from a clone instead
113
+
114
+ If you would rather pin a local copy or you want to change the code:
115
+
116
+ ```sh
117
+ git clone https://github.com/Fundryi/MCP-ControlD.git
118
+ cd MCP-ControlD
119
+ npm install
120
+ ```
121
+
122
+ `npm install` builds the server for you. Then swap the command in any config above for `"command": "node"` with the absolute path to `dist/index.js` as the only argument.
123
+
124
+ ## Turning on write tools
125
+
126
+ Add a write token. That is the whole switch:
127
+
128
+ ```json
129
+ "env": {
130
+ "CONTROLD_API_TOKEN_READ": "YOUR_API_TOKEN",
131
+ "CONTROLD_API_TOKEN_WRITE": "YOUR_API_TOKEN"
132
+ }
133
+ ```
134
+
135
+ With no write token the write tools do not exist. Your client cannot list them and a prompt cannot call them, so a bad prompt cannot change your DNS setup.
136
+
137
+ ## Tool reference
138
+
139
+ Profile, device, access, and log tools accept an optional `sub_org_id` when you are acting on a sub-organization.
140
+
141
+ ### Read tools
142
+
143
+ | Tool | Description |
144
+ |---|---|
145
+ | `controld_list_profiles` | List profiles. |
146
+ | `controld_get_profile_config` | Read filters, external filters, services, folders, rules, or the default rule for a profile. Section `all` returns every section in one call. |
147
+ | `controld_list_catalog` | List Control D metadata such as device types, services, proxies, and analytics options. |
148
+ | `controld_list_devices` | List devices. |
149
+ | `controld_get_account` | Read account information. |
150
+ | `controld_get_billing` | Read products, subscriptions, or payments. |
151
+ | `controld_get_organization` | Read organization information, members, or sub-organizations. |
152
+
153
+ ### Diagnostic tools
154
+
155
+ | Tool | Description |
156
+ |---|---|
157
+ | `controld_list_known_ips` | List known IPs for a device. |
158
+ | `controld_get_request_ip` | Get the caller IP address and handling datacenter. |
159
+ | `controld_get_network_status` | Get Control D network incident status. |
160
+ | `controld_export_dns_query_logs` | Export a bounded window of DNS query logs as CSV. |
161
+ | `controld_explain_domain` | Walk a profile's rules, services, native filters, and external filters to explain how a domain is handled. |
162
+ | `controld_request_read` | Escape hatch. GET any Control D path, including undocumented ones such as `/devices/users`. |
163
+
164
+ ### Write tools
165
+
166
+ Registered only when a write credential is configured: either `CONTROLD_API_TOKEN_WRITE`, or the older `CONTROLD_API_TOKEN` together with `CONTROLD_ENABLE_WRITES=1`.
167
+
168
+ | Tool | Description |
169
+ |---|---|
170
+ | `controld_create_profile` | Create a profile. |
171
+ | `controld_update_profile` | Update a profile. |
172
+ | `controld_delete_profile` | Delete an orphaned profile. |
173
+ | `controld_set_profile_option` | Set a profile option. |
174
+ | `controld_set_filters` | Set profile filters in a batch. |
175
+ | `controld_set_service_rule` | Set a service rule. |
176
+ | `controld_set_default_rule` | Set a profile's default rule. |
177
+ | `controld_create_custom_rules` | Create custom rules in bulk. |
178
+ | `controld_update_custom_rules` | Update custom rules, selected by hostname. |
179
+ | `controld_delete_custom_rule` | Delete a custom rule. |
180
+ | `controld_create_rule_folder` | Create a rule folder. |
181
+ | `controld_update_rule_folder` | Update a rule folder. |
182
+ | `controld_delete_rule_folder` | Delete a rule folder and every rule in it. |
183
+ | `controld_create_device` | Create a device. |
184
+ | `controld_update_device` | Update a device. |
185
+ | `controld_delete_device` | Delete a device, which can break its DNS resolution. |
186
+ | `controld_authorize_ips` | Authorize IP addresses. |
187
+ | `controld_deauthorize_ips` | Deauthorize IP addresses. |
188
+ | `controld_create_suborg` | Create a sub-organization. |
189
+ | `controld_update_organization` | Modify an organization's contact and policy details. |
190
+ | `controld_request_write` | Escape hatch. Send any mutating request to any Control D path. |
191
+
192
+ ## Limits and caveats
193
+
194
+ `controld_export_dns_query_logs` uses Control D's CSV analytics endpoint, because there is no documented JSON REST API for dashboard query logs. It needs Full Analytics on the device, takes a bounded time window, and caps the response size. It works on personal accounts, where the analytics endpoint is discovered from the account record.
195
+
196
+ `controld_explain_domain` walks your configuration; it does not resolve DNS. Control D has not formally documented its precedence rules, so the tool reports what it matched in a plausible order and says outright which sections it could not evaluate. Treat it as a research aid, not an authoritative answer.
197
+
198
+ `controld_update_organization` covers `PUT /organizations`. Control D documents the fields but no identifier parameter, and does not say how the target organization is chosen. This tool has not been verified against a live organization account. Treat the target as unconfirmed and check what changed afterwards. If that is not acceptable, make the change in the Control D dashboard instead.
199
+
200
+ The two escape hatches, `controld_request_read` and `controld_request_write`, exist because Control D has endpoints its docs do not cover. They validate the path and nothing else. The named tools check their inputs against the documented schema; the escape hatches hand your arguments straight to the API. Reach for them last.
201
+
202
+ ## Safety
203
+
204
+ - Reads and writes use separate credentials. A GET always uses the read token, so it cannot mutate anything even if the server also holds a write token.
205
+ - Write tools are not registered without a write token. There is nothing for a prompt to call.
206
+ - Delete tools have their own names, need explicit identifiers, and carry destructive MCP annotations so your client can prompt you. `controld_request_write` is annotated destructive too, because it can be.
207
+ - No read tool can trigger a write as a side effect. The server checks its own annotations at startup and refuses to run if a tool is labeled wrong.
208
+ - Tokens are read from the environment only. They are never logged, never returned in an MCP error, and authorization headers are redacted before any error text is passed on.
209
+ - Paths are host-relative and validated. A path such as `//example.com/x` cannot retarget the request at another host. The CSV export checks the hostname before attaching credentials, so the token only ever goes to Control D or to a host you configured yourself in `CONTROLD_API_BASE_URL`.
210
+ - Tool output is capped at 1 MiB, with a truncation notice, so a huge response cannot flood your client's context.
211
+ - Every request has a timeout, so a hung API call cannot stall your session. Only GET is ever retried. A write is never replayed, because a failure can arrive after the change already took effect.
212
+ - Releases are published from CI with npm provenance, so you can verify a published version was built from this repository at a specific commit.
213
+
214
+ Found a security problem? See [SECURITY.md](SECURITY.md).
215
+
216
+ ## Troubleshooting
217
+
218
+ **`CONTROLD_API_TOKEN_READ (or CONTROLD_API_TOKEN) is required.`** The server started without a token. Check that your client config sets it in the `env` block, not in your shell.
219
+
220
+ **Write tools are missing.** Set `CONTROLD_API_TOKEN_WRITE` and restart your MCP client. Clients cache the tool list from startup, so a restart is required. On the older single-token setup, set `CONTROLD_ENABLE_WRITES=1` instead.
221
+
222
+ **A write fails with a permission error.** The token in `CONTROLD_API_TOKEN_WRITE` is read-scoped. The server cannot tell the two apart, so Control D rejects it at request time instead. Create a write token in the dashboard.
223
+
224
+ **Organization tools return an error.** Personal accounts have no organization. Those endpoints only work on org accounts.
225
+
226
+ ## Development
227
+
228
+ ```sh
229
+ npm test # run the test suite
230
+ npm run build # compile to dist/
231
+ ```
232
+
233
+ Tests use fixtures and a stubbed `fetch`. Nothing in the suite touches a live account.
234
+
235
+ ## License
236
+
237
+ [MIT](LICENSE)
package/dist/client.js ADDED
@@ -0,0 +1,320 @@
1
+ const DEFAULT_BASE_URL = "https://api.controld.com";
2
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
3
+ const REQUEST_TIMEOUT_MS = 30_000;
4
+ const RAW_GET_TIMEOUT_MS = 120_000;
5
+ const MAX_ATTEMPTS = 3;
6
+ const BACKOFF_MS = [500, 1500];
7
+ const MAX_RETRY_AFTER_MS = 10_000;
8
+ function trimmed(value) {
9
+ const text = value?.trim();
10
+ return text === "" ? undefined : text;
11
+ }
12
+ /**
13
+ * Only https is accepted, apart from loopback hosts for local testing. The base
14
+ * URL decides where the bearer token is sent, so a plaintext or arbitrary
15
+ * override would be a credential leak.
16
+ */
17
+ export function resolveBaseUrl(raw) {
18
+ const value = trimmed(raw);
19
+ if (value === undefined)
20
+ return DEFAULT_BASE_URL;
21
+ let url;
22
+ try {
23
+ url = new URL(value);
24
+ }
25
+ catch {
26
+ throw new Error("CONTROLD_API_BASE_URL must be an absolute URL.");
27
+ }
28
+ if (url.protocol !== "https:" && !LOOPBACK_HOSTS.has(url.hostname)) {
29
+ throw new Error("CONTROLD_API_BASE_URL must use https, unless it points at a loopback host for testing.");
30
+ }
31
+ if (url.search !== "" || url.hash !== "") {
32
+ throw new Error("CONTROLD_API_BASE_URL must not contain a query string or fragment.");
33
+ }
34
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
35
+ }
36
+ /**
37
+ * Read and write credentials are separate so that read tools keep using a
38
+ * read-scoped token even on a server that can write. `CONTROLD_API_TOKEN` stays
39
+ * supported: on its own it grants reads only, and it grants writes only when
40
+ * `CONTROLD_ENABLE_WRITES=1`, so an existing setup never gains write tools by
41
+ * upgrading.
42
+ */
43
+ export function resolveConfig(env = process.env) {
44
+ const shared = trimmed(env.CONTROLD_API_TOKEN);
45
+ const readToken = trimmed(env.CONTROLD_API_TOKEN_READ) ?? shared;
46
+ if (!readToken) {
47
+ throw new Error("CONTROLD_API_TOKEN_READ (or CONTROLD_API_TOKEN) is required.");
48
+ }
49
+ const writeToken = trimmed(env.CONTROLD_API_TOKEN_WRITE)
50
+ ?? (env.CONTROLD_ENABLE_WRITES === "1" ? shared : undefined);
51
+ return {
52
+ readToken,
53
+ writeToken,
54
+ baseUrl: resolveBaseUrl(env.CONTROLD_API_BASE_URL),
55
+ orgId: trimmed(env.CONTROLD_ORG_ID),
56
+ };
57
+ }
58
+ function isRecord(value) {
59
+ return typeof value === "object" && value !== null;
60
+ }
61
+ function formBody(values) {
62
+ const params = new URLSearchParams();
63
+ for (const [key, value] of Object.entries(values)) {
64
+ if (value === undefined)
65
+ continue;
66
+ if (Array.isArray(value)) {
67
+ for (const item of value)
68
+ params.append(`${key}[]`, String(item));
69
+ }
70
+ else {
71
+ params.append(key, String(value));
72
+ }
73
+ }
74
+ return params;
75
+ }
76
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
77
+ /**
78
+ * Only GET is ever retried. A write may already have taken effect before the
79
+ * failure reached us, and 429 does not promise the request was rejected before
80
+ * it ran (RFC 6585 section 4 defines no such guarantee), so a replayed write
81
+ * could duplicate a profile or a rule.
82
+ */
83
+ function shouldRetry(status, method) {
84
+ if (method !== "GET")
85
+ return false;
86
+ return status === 429 || (status >= 500 && status <= 599);
87
+ }
88
+ /** Retry-After is either a delay in seconds or an HTTP date (RFC 9110 10.2.3). */
89
+ function retryDelay(response, attempt, now) {
90
+ const header = response.headers.get("retry-after");
91
+ if (header !== null) {
92
+ const seconds = Number(header);
93
+ if (Number.isFinite(seconds) && seconds >= 0) {
94
+ return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);
95
+ }
96
+ const at = Date.parse(header);
97
+ if (Number.isFinite(at)) {
98
+ return Math.min(Math.max(at - now, 0), MAX_RETRY_AFTER_MS);
99
+ }
100
+ }
101
+ return BACKOFF_MS[attempt] ?? BACKOFF_MS[BACKOFF_MS.length - 1];
102
+ }
103
+ /** Frees the connection held by a response we are about to throw away. */
104
+ async function discard(response) {
105
+ try {
106
+ await response.body?.cancel();
107
+ }
108
+ catch {
109
+ // A body that cannot be cancelled is already finished with.
110
+ }
111
+ }
112
+ const REPLACEMENT_BYTES = [0xef, 0xbf, 0xbd];
113
+ /**
114
+ * Decodes bytes that may end mid-character. A trailing U+FFFD is dropped only
115
+ * when it came from a split character, never when the source really ended with
116
+ * one.
117
+ */
118
+ export function decodeTruncated(bytes) {
119
+ const text = new TextDecoder().decode(bytes);
120
+ if (!text.endsWith("�"))
121
+ return text;
122
+ const tail = bytes.subarray(Math.max(0, bytes.length - REPLACEMENT_BYTES.length));
123
+ const wasEncoded = tail.length === REPLACEMENT_BYTES.length
124
+ && REPLACEMENT_BYTES.every((byte, index) => tail[index] === byte);
125
+ return wasEncoded ? text : text.slice(0, -1);
126
+ }
127
+ const API_DOMAIN = "controld.com";
128
+ /**
129
+ * The bearer token must never leave Control D. `rawGet` takes a whole URL, so
130
+ * the host is checked here rather than trusted from the caller: a future tool
131
+ * that builds a URL carelessly must not be able to post the token elsewhere.
132
+ * The configured base URL is allowed too, so a test or proxy host still works.
133
+ */
134
+ export function assertAllowedHost(url, baseUrl) {
135
+ const { hostname } = url;
136
+ const allowed = hostname === API_DOMAIN
137
+ || hostname.endsWith(`.${API_DOMAIN}`)
138
+ || hostname === new URL(baseUrl).hostname;
139
+ if (!allowed) {
140
+ throw new Error(`Refusing to send credentials to ${hostname}.`);
141
+ }
142
+ if (url.protocol !== "https:" && !LOOPBACK_HOSTS.has(hostname)) {
143
+ throw new Error("Refusing to send credentials over an insecure connection.");
144
+ }
145
+ }
146
+ export function redact(text, tokens) {
147
+ let result = text.replace(/authorization\s*:\s*(?:Bearer\s+)?[^\s,;}\]]+/gi, "authorization: [REDACTED]");
148
+ for (const token of tokens) {
149
+ if (token)
150
+ result = result.split(token).join("[REDACTED]");
151
+ }
152
+ return result;
153
+ }
154
+ function safeError(error, tokens) {
155
+ if (isRecord(error) && error.name === "TimeoutError") {
156
+ return new Error("Control D API request timed out.");
157
+ }
158
+ const originalMessage = error instanceof Error ? error.message : "Control D API request failed.";
159
+ const safe = new Error(redact(originalMessage, tokens));
160
+ if (isRecord(error)) {
161
+ if (typeof error.code === "string")
162
+ safe.code = redact(error.code, tokens);
163
+ else if (typeof error.code === "number")
164
+ safe.code = error.code;
165
+ }
166
+ return safe;
167
+ }
168
+ export function createControlDClient(options = {}) {
169
+ const fetchImpl = options.fetch ?? globalThis.fetch;
170
+ const explicit = options.token ?? options.readToken ?? options.writeToken;
171
+ const config = explicit === undefined
172
+ ? resolveConfig()
173
+ : {
174
+ readToken: options.readToken ?? options.token ?? "",
175
+ writeToken: options.writeToken ?? options.token,
176
+ baseUrl: resolveBaseUrl(options.baseUrl),
177
+ orgId: options.orgId,
178
+ };
179
+ if (!config.readToken)
180
+ throw new Error("A read token is required.");
181
+ const tokens = [config.readToken, config.writeToken];
182
+ const tokenFor = (method) => {
183
+ if (method === "GET")
184
+ return config.readToken;
185
+ if (!config.writeToken) {
186
+ throw new Error("This operation needs a write token. Set CONTROLD_API_TOKEN_WRITE to enable writes.");
187
+ }
188
+ return config.writeToken;
189
+ };
190
+ return {
191
+ async request(path, options = {}) {
192
+ try {
193
+ const method = options.method ?? "GET";
194
+ const headers = new Headers({
195
+ accept: "application/json",
196
+ authorization: `Bearer ${tokenFor(method)}`,
197
+ });
198
+ let body;
199
+ const orgId = options.subOrgId ?? config.orgId;
200
+ if (orgId)
201
+ headers.set("X-Force-Org-Id", orgId);
202
+ if (options.body?.encoding === "form") {
203
+ headers.set("content-type", "application/x-www-form-urlencoded");
204
+ body = formBody(options.body.value);
205
+ }
206
+ else if (options.body?.encoding === "json") {
207
+ headers.set("content-type", "application/json");
208
+ body = JSON.stringify(options.body.value);
209
+ }
210
+ // Concatenated, not resolved against a base: `new URL(path, base)` would
211
+ // let a protocol-relative path such as "//example.com/x" retarget the
212
+ // request at another host and send the token there.
213
+ const url = new URL(`${config.baseUrl}${path}`);
214
+ let response;
215
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
216
+ response = await fetchImpl(url, {
217
+ method,
218
+ headers,
219
+ body,
220
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
221
+ });
222
+ if (attempt === MAX_ATTEMPTS - 1 || !shouldRetry(response.status, method))
223
+ break;
224
+ const delay = retryDelay(response, attempt, Date.now());
225
+ await discard(response);
226
+ await sleep(delay);
227
+ }
228
+ const responseText = await response.text();
229
+ let envelope;
230
+ try {
231
+ envelope = JSON.parse(responseText);
232
+ }
233
+ catch {
234
+ throw new Error(`Control D API request failed (HTTP ${response.status}).`);
235
+ }
236
+ if (!isRecord(envelope) || typeof envelope.success !== "boolean") {
237
+ throw new Error("Control D API returned an invalid response.");
238
+ }
239
+ if (!envelope.success) {
240
+ const apiError = isRecord(envelope.error) ? envelope.error : undefined;
241
+ const message = typeof apiError?.message === "string"
242
+ ? apiError.message
243
+ : "Control D API request failed.";
244
+ const error = new Error(message);
245
+ if (typeof apiError?.code === "string" || typeof apiError?.code === "number") {
246
+ error.code = apiError.code;
247
+ }
248
+ throw error;
249
+ }
250
+ if (!response.ok)
251
+ throw new Error(`Control D API request failed (HTTP ${response.status}).`);
252
+ return envelope.body;
253
+ }
254
+ catch (error) {
255
+ throw safeError(error, tokens);
256
+ }
257
+ },
258
+ async rawGet(url, options = {}) {
259
+ try {
260
+ const headers = new Headers({ authorization: `Bearer ${config.readToken}` });
261
+ const orgId = options.subOrgId ?? config.orgId;
262
+ if (orgId)
263
+ headers.set("X-Force-Org-Id", orgId);
264
+ assertAllowedHost(url, config.baseUrl);
265
+ let response;
266
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
267
+ response = await fetchImpl(url, {
268
+ method: "GET",
269
+ headers,
270
+ signal: AbortSignal.timeout(RAW_GET_TIMEOUT_MS),
271
+ });
272
+ if (attempt === MAX_ATTEMPTS - 1 || !shouldRetry(response.status, "GET"))
273
+ break;
274
+ const delay = retryDelay(response, attempt, Date.now());
275
+ await discard(response);
276
+ await sleep(delay);
277
+ }
278
+ if (!response.ok) {
279
+ throw new Error(`Control D request failed (HTTP ${response.status}).`);
280
+ }
281
+ if (options.maxBytes === undefined) {
282
+ return { text: await response.text(), truncated: false };
283
+ }
284
+ const reader = response.body?.getReader();
285
+ if (!reader)
286
+ return { text: "", truncated: false };
287
+ const chunks = [];
288
+ let length = 0;
289
+ let truncated = false;
290
+ while (true) {
291
+ const { done, value } = await reader.read();
292
+ if (done)
293
+ break;
294
+ const remaining = options.maxBytes - length;
295
+ if (value.byteLength > remaining) {
296
+ if (remaining > 0)
297
+ chunks.push(value.subarray(0, remaining));
298
+ length += Math.max(remaining, 0);
299
+ truncated = true;
300
+ await reader.cancel();
301
+ break;
302
+ }
303
+ chunks.push(value);
304
+ length += value.byteLength;
305
+ }
306
+ const bytes = new Uint8Array(length);
307
+ let offset = 0;
308
+ for (const chunk of chunks) {
309
+ bytes.set(chunk, offset);
310
+ offset += chunk.byteLength;
311
+ }
312
+ const text = decodeTruncated(bytes);
313
+ return { text, truncated };
314
+ }
315
+ catch (error) {
316
+ throw safeError(error, tokens);
317
+ }
318
+ },
319
+ };
320
+ }
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { createControlDClient, resolveConfig } from "./client.js";
5
+ import { registerTools } from "./tools.js";
6
+ let config;
7
+ let client;
8
+ try {
9
+ config = resolveConfig();
10
+ client = createControlDClient(config);
11
+ }
12
+ catch (error) {
13
+ // Config errors name the variable, never its value.
14
+ console.error(error instanceof Error ? error.message : String(error));
15
+ process.exit(1);
16
+ }
17
+ const server = new McpServer({ name: "mcp-controld", version: "0.1.0" });
18
+ registerTools(server, client, config.writeToken !== undefined);
19
+ await server.connect(new StdioServerTransport());