@solomonneas/adguard-mcp 0.3.1 → 0.3.2
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/README.md +116 -1
- package/dist/cli.js +1214 -260
- package/dist/index.js +786 -129
- package/dist/mcp-bin.js +2018 -584
- package/dist/mcp-server.js +1994 -571
- package/openclaw.plugin.json +1 -1
- package/package.json +7 -9
package/dist/cli.js
CHANGED
|
@@ -1,202 +1,543 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
-
var __esm = (fn, res
|
|
5
|
-
|
|
6
|
-
try {
|
|
7
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
|
-
} catch (e) {
|
|
9
|
-
throw err = [e], e;
|
|
10
|
-
}
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
11
6
|
};
|
|
12
7
|
var __export = (target, all) => {
|
|
13
8
|
for (var name in all)
|
|
14
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
10
|
};
|
|
16
11
|
|
|
17
|
-
//
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
12
|
+
// node_modules/@lidless-labs/effect-operator-kit/dist/index.js
|
|
13
|
+
import { Data } from "effect";
|
|
14
|
+
import { Effect } from "effect";
|
|
15
|
+
import { Effect as Effect2 } from "effect";
|
|
16
|
+
import { Duration, Effect as Effect3, Schedule } from "effect";
|
|
17
|
+
import { Cause, Effect as Effect4, Exit } from "effect";
|
|
18
|
+
import { Cause as Cause2, Effect as Effect5 } from "effect";
|
|
19
|
+
function redactBody(text, redact2) {
|
|
20
|
+
return (redact2 ?? defaultRedact)(text);
|
|
21
|
+
}
|
|
22
|
+
function mergeHeaders(...sources) {
|
|
23
|
+
const merged = new Headers();
|
|
24
|
+
for (const source of sources) {
|
|
25
|
+
if (!source) continue;
|
|
26
|
+
const headers = new Headers(source);
|
|
27
|
+
headers.forEach((value, key) => merged.set(key, value));
|
|
28
|
+
}
|
|
29
|
+
return merged;
|
|
30
|
+
}
|
|
31
|
+
function resolveExpectedStatuses(req) {
|
|
32
|
+
return req.expectedStatuses ?? DEFAULT_SUCCESS_STATUSES;
|
|
33
|
+
}
|
|
34
|
+
function isExpectedStatus(status, expected) {
|
|
35
|
+
return expected.includes(status);
|
|
36
|
+
}
|
|
37
|
+
function resolveBodyEncoding(req) {
|
|
38
|
+
if (req.bodyEncoding !== void 0) return req.bodyEncoding;
|
|
39
|
+
return req.body !== void 0 ? "json" : "none";
|
|
40
|
+
}
|
|
41
|
+
function setContentTypeIfAbsent(headers, contentType) {
|
|
42
|
+
if (!headers.has("content-type")) {
|
|
43
|
+
headers.set("content-type", contentType);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function buildRequestBody(req, headers) {
|
|
47
|
+
const encoding = resolveBodyEncoding(req);
|
|
48
|
+
switch (encoding) {
|
|
49
|
+
case "none":
|
|
50
|
+
return void 0;
|
|
51
|
+
case "json":
|
|
52
|
+
setContentTypeIfAbsent(headers, "application/json");
|
|
53
|
+
return JSON.stringify(req.body);
|
|
54
|
+
case "text":
|
|
55
|
+
setContentTypeIfAbsent(headers, "text/plain");
|
|
56
|
+
return String(req.body);
|
|
57
|
+
case "form": {
|
|
58
|
+
setContentTypeIfAbsent(
|
|
59
|
+
headers,
|
|
60
|
+
"application/x-www-form-urlencoded"
|
|
61
|
+
);
|
|
62
|
+
const params = new URLSearchParams();
|
|
63
|
+
if (req.body && typeof req.body === "object") {
|
|
64
|
+
for (const [key, value] of Object.entries(
|
|
65
|
+
req.body
|
|
66
|
+
)) {
|
|
67
|
+
params.set(key, String(value));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return params.toString();
|
|
71
|
+
}
|
|
24
72
|
}
|
|
25
73
|
}
|
|
26
|
-
function
|
|
27
|
-
|
|
74
|
+
function mapUnexpectedStatus(req, status, bodyText, expectedStatuses, redact2) {
|
|
75
|
+
const redacted = redactBody(bodyText, redact2);
|
|
76
|
+
const mapperInput = {
|
|
77
|
+
status,
|
|
78
|
+
method: req.method,
|
|
79
|
+
path: req.path,
|
|
80
|
+
bodyText: redacted,
|
|
81
|
+
expectedStatuses
|
|
82
|
+
};
|
|
83
|
+
if (req.statusMapper) {
|
|
84
|
+
const custom = req.statusMapper(mapperInput);
|
|
85
|
+
if (custom !== null) return custom;
|
|
86
|
+
}
|
|
87
|
+
const base = {
|
|
88
|
+
method: req.method,
|
|
89
|
+
path: req.path,
|
|
90
|
+
status,
|
|
91
|
+
body: redacted
|
|
92
|
+
};
|
|
93
|
+
switch (status) {
|
|
94
|
+
case 401:
|
|
95
|
+
return new AuthError(base);
|
|
96
|
+
case 403:
|
|
97
|
+
return new ForbiddenError(base);
|
|
98
|
+
case 404:
|
|
99
|
+
return new NotFoundError(base);
|
|
100
|
+
default:
|
|
101
|
+
return new UnexpectedStatusError({
|
|
102
|
+
method: req.method,
|
|
103
|
+
path: req.path,
|
|
104
|
+
status,
|
|
105
|
+
body: redacted,
|
|
106
|
+
expected: expectedStatuses
|
|
107
|
+
});
|
|
108
|
+
}
|
|
28
109
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
"
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
110
|
+
function parseResponseBody(req, bodyText, redact2) {
|
|
111
|
+
const responseType = req.responseType ?? "json";
|
|
112
|
+
if (responseType === "none") {
|
|
113
|
+
return Effect2.succeed(void 0);
|
|
114
|
+
}
|
|
115
|
+
if (responseType === "text") {
|
|
116
|
+
return Effect2.succeed(bodyText);
|
|
117
|
+
}
|
|
118
|
+
if (bodyText.length === 0) {
|
|
119
|
+
return Effect2.succeed(void 0);
|
|
120
|
+
}
|
|
121
|
+
return Effect2.try({
|
|
122
|
+
try: () => JSON.parse(bodyText),
|
|
123
|
+
catch: (cause) => new ParseError({
|
|
124
|
+
path: req.path,
|
|
125
|
+
body: redactBody(bodyText, redact2),
|
|
126
|
+
message: "Failed to parse JSON response",
|
|
127
|
+
cause
|
|
128
|
+
})
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function fetchWithTimeout(ctx, url, init, timeoutMs, method, path) {
|
|
132
|
+
const fetchImpl = ctx.fetch ?? globalThis.fetch;
|
|
133
|
+
return Effect2.async((resume) => {
|
|
134
|
+
const controller = new AbortController();
|
|
135
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
136
|
+
const finish = (effect) => {
|
|
137
|
+
clearTimeout(timeoutId);
|
|
138
|
+
resume(effect);
|
|
40
139
|
};
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
140
|
+
void fetchImpl(url, { ...init, signal: controller.signal }).then((response) => finish(Effect2.succeed(response))).catch((cause) => {
|
|
141
|
+
if (cause instanceof Error && cause.name === "AbortError") {
|
|
142
|
+
finish(
|
|
143
|
+
Effect2.fail(new TimeoutError({ method, path, timeoutMs }))
|
|
144
|
+
);
|
|
145
|
+
return;
|
|
45
146
|
}
|
|
147
|
+
finish(
|
|
148
|
+
Effect2.fail(new TransportError({ method, path, cause }))
|
|
149
|
+
);
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function buildHeaders(ctx, req) {
|
|
154
|
+
const auth = ctx.auth;
|
|
155
|
+
if (!auth) {
|
|
156
|
+
return Effect2.succeed(mergeHeaders(ctx.defaultHeaders, req.headers));
|
|
157
|
+
}
|
|
158
|
+
return Effect2.gen(function* () {
|
|
159
|
+
let headers = mergeHeaders(ctx.defaultHeaders);
|
|
160
|
+
headers = yield* auth.apply(headers);
|
|
161
|
+
return mergeHeaders(headers, req.headers);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
function isTaggedShape(error) {
|
|
165
|
+
return error !== null && typeof error === "object" && "_tag" in error && typeof error._tag === "string";
|
|
166
|
+
}
|
|
167
|
+
function formatTaggedThin(error) {
|
|
168
|
+
switch (error._tag) {
|
|
169
|
+
case "ConfigError":
|
|
170
|
+
return error.key ? `ConfigError: ${error.key}${error.message ? `: ${error.message}` : ""}` : error.message || "ConfigError";
|
|
171
|
+
case "TimeoutError":
|
|
172
|
+
return `TimeoutError: ${error.method ?? "?"} ${error.path ?? "?"} after ${error.timeoutMs ?? "?"}ms`;
|
|
173
|
+
case "AuthError":
|
|
174
|
+
case "ForbiddenError":
|
|
175
|
+
case "NotFoundError":
|
|
176
|
+
case "UnexpectedStatusError":
|
|
177
|
+
return `${error._tag}: ${error.method ?? "?"} ${error.path ?? "?"}${error.status !== void 0 ? ` (${error.status})` : ""}`;
|
|
178
|
+
case "TransportError":
|
|
179
|
+
return `TransportError: ${error.method ?? "?"} ${error.path ?? "?"}`;
|
|
180
|
+
case "ParseError":
|
|
181
|
+
return error.message || `ParseError${error.path ? `: ${error.path}` : ""}`;
|
|
182
|
+
default:
|
|
183
|
+
return error.message || error._tag;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
var ConfigError, AuthError, ForbiddenError, NotFoundError, TimeoutError, TransportError, ParseError, UnexpectedStatusError, fromProcessEnv, isBlank, failConfig, readRaw, parseTimeoutEnv, SECRET_PATTERNS, MAX_LENGTH, redactString, defaultRedact, DEFAULT_SUCCESS_STATUSES, buildUrl, sendRequest, defaultShouldRetry, DEFAULT_POLICY_FIELDS, noRetry, exponentialRetry, buildSchedule, withRetry, ok, fail, refuseUnconfirmed, operatorErrorMessage;
|
|
187
|
+
var init_dist = __esm({
|
|
188
|
+
"node_modules/@lidless-labs/effect-operator-kit/dist/index.js"() {
|
|
189
|
+
"use strict";
|
|
190
|
+
ConfigError = class extends Data.TaggedError("ConfigError") {
|
|
46
191
|
};
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
192
|
+
AuthError = class extends Data.TaggedError("AuthError") {
|
|
193
|
+
};
|
|
194
|
+
ForbiddenError = class extends Data.TaggedError("ForbiddenError") {
|
|
195
|
+
};
|
|
196
|
+
NotFoundError = class extends Data.TaggedError("NotFoundError") {
|
|
197
|
+
};
|
|
198
|
+
TimeoutError = class extends Data.TaggedError("TimeoutError") {
|
|
199
|
+
};
|
|
200
|
+
TransportError = class extends Data.TaggedError("TransportError") {
|
|
201
|
+
};
|
|
202
|
+
ParseError = class extends Data.TaggedError("ParseError") {
|
|
203
|
+
};
|
|
204
|
+
UnexpectedStatusError = class extends Data.TaggedError("UnexpectedStatusError") {
|
|
205
|
+
};
|
|
206
|
+
fromProcessEnv = (env) => ({
|
|
207
|
+
get: (key) => (env ?? process.env)[key]
|
|
208
|
+
});
|
|
209
|
+
isBlank = (raw) => raw === void 0 || raw.trim() === "";
|
|
210
|
+
failConfig = (partial) => Effect.fail(new ConfigError(partial));
|
|
211
|
+
readRaw = (env, key) => env.get(key);
|
|
212
|
+
parseTimeoutEnv = (env, key, opts) => {
|
|
213
|
+
const raw = readRaw(env, key);
|
|
214
|
+
if (isBlank(raw)) {
|
|
215
|
+
return Effect.succeed(opts.fallbackMs);
|
|
52
216
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
217
|
+
const parsed = Number(raw.trim());
|
|
218
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
219
|
+
return failConfig({
|
|
220
|
+
key,
|
|
221
|
+
value: raw,
|
|
222
|
+
message: `${key} must be a positive timeout`
|
|
223
|
+
});
|
|
58
224
|
}
|
|
59
|
-
|
|
60
|
-
|
|
225
|
+
const unit = opts.unit ?? "s";
|
|
226
|
+
const ms = unit === "ms" ? parsed : parsed * 1e3;
|
|
227
|
+
if (opts.minMs !== void 0 && ms < opts.minMs) {
|
|
228
|
+
return failConfig({
|
|
229
|
+
key,
|
|
230
|
+
value: raw,
|
|
231
|
+
message: `${key} must be at least ${opts.minMs}ms`
|
|
232
|
+
});
|
|
61
233
|
}
|
|
62
|
-
|
|
63
|
-
return
|
|
234
|
+
if (opts.maxMs !== void 0 && ms > opts.maxMs) {
|
|
235
|
+
return failConfig({
|
|
236
|
+
key,
|
|
237
|
+
value: raw,
|
|
238
|
+
message: `${key} must be at most ${opts.maxMs}ms`
|
|
239
|
+
});
|
|
64
240
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
241
|
+
return Effect.succeed(ms);
|
|
242
|
+
};
|
|
243
|
+
SECRET_PATTERNS = [
|
|
244
|
+
/(authorization:\s*)(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
245
|
+
/\b(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
246
|
+
/(authorization:\s*)(?:token|digest|hawk|oauth|apikey)\s+\S+/gi,
|
|
247
|
+
/(x-n8n-api-key|x-auth-token|x-emby-token|x-api-key)\s*:\s*\S+/gi,
|
|
248
|
+
/(https?:\/\/)([^@\s/]+)@/gi,
|
|
249
|
+
/([?&](?:access_token|refresh_token|client_secret|id_token|x-api-key|\w+_(?:token|secret)|password|token|secret|api[_-]?key|key)=)[^&\s]+/gi,
|
|
250
|
+
/\beyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b/g
|
|
251
|
+
];
|
|
252
|
+
MAX_LENGTH = 500;
|
|
253
|
+
redactString = (message, secrets = []) => {
|
|
254
|
+
let sanitized = message;
|
|
255
|
+
for (const secret of secrets) {
|
|
256
|
+
if (secret) {
|
|
257
|
+
sanitized = sanitized.split(secret).join("[REDACTED]");
|
|
72
258
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
259
|
+
}
|
|
260
|
+
sanitized = sanitized.replace(SECRET_PATTERNS[0], "$1$2 [REDACTED]").replace(SECRET_PATTERNS[1], "$1 [REDACTED]").replace(SECRET_PATTERNS[2], "$1[REDACTED]").replace(SECRET_PATTERNS[3], "$1: [REDACTED]").replace(SECRET_PATTERNS[4], "$1[REDACTED]@").replace(SECRET_PATTERNS[5], "$1[REDACTED]").replace(SECRET_PATTERNS[6], "[REDACTED]");
|
|
261
|
+
return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}...` : sanitized;
|
|
262
|
+
};
|
|
263
|
+
defaultRedact = (value) => redactString(value);
|
|
264
|
+
DEFAULT_SUCCESS_STATUSES = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
265
|
+
buildUrl = (baseUrl, path, query) => {
|
|
266
|
+
if (path.includes("\\")) {
|
|
267
|
+
throw new TypeError("buildUrl: path must not contain backslash");
|
|
268
|
+
}
|
|
269
|
+
const url = new URL(path, baseUrl);
|
|
270
|
+
if (url.username || url.password) {
|
|
271
|
+
throw new TypeError("buildUrl: path must not contain URL userinfo");
|
|
272
|
+
}
|
|
273
|
+
if (url.origin !== baseUrl.origin) {
|
|
274
|
+
throw new TypeError(
|
|
275
|
+
`buildUrl: path "${path}" resolves to a different origin (${url.origin}) than baseUrl (${baseUrl.origin})`
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
if (query) {
|
|
279
|
+
for (const [key, value] of Object.entries(query)) {
|
|
280
|
+
if (value === null || value === void 0) continue;
|
|
281
|
+
if (Array.isArray(value)) {
|
|
282
|
+
for (const item of value) {
|
|
283
|
+
if (item === null || item === void 0) continue;
|
|
284
|
+
url.searchParams.append(key, String(item));
|
|
91
285
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (e instanceof AdGuardClientError) throw e;
|
|
95
|
-
lastErr = new AdGuardUnreachableError(e.message);
|
|
96
|
-
if (attempt === 0) await sleep(this.retryDelayMs);
|
|
286
|
+
} else {
|
|
287
|
+
url.searchParams.set(key, String(value));
|
|
97
288
|
}
|
|
98
289
|
}
|
|
99
|
-
throw lastErr ?? new AdGuardUnreachableError("unknown");
|
|
100
290
|
}
|
|
291
|
+
return url;
|
|
101
292
|
};
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
293
|
+
sendRequest = (ctx, req) => {
|
|
294
|
+
const url = buildUrl(ctx.baseUrl, req.path, req.query);
|
|
295
|
+
const timeoutMs = req.timeoutMs ?? ctx.timeoutMs;
|
|
296
|
+
const expectedStatuses = resolveExpectedStatuses(req);
|
|
297
|
+
return buildHeaders(ctx, req).pipe(
|
|
298
|
+
Effect2.flatMap((headers) => {
|
|
299
|
+
const body = buildRequestBody(req, headers);
|
|
300
|
+
const init = {
|
|
301
|
+
method: req.method,
|
|
302
|
+
headers,
|
|
303
|
+
...body !== void 0 ? { body } : {}
|
|
304
|
+
};
|
|
305
|
+
return fetchWithTimeout(
|
|
306
|
+
ctx,
|
|
307
|
+
url,
|
|
308
|
+
init,
|
|
309
|
+
timeoutMs,
|
|
310
|
+
req.method,
|
|
311
|
+
req.path
|
|
312
|
+
).pipe(
|
|
313
|
+
Effect2.flatMap(
|
|
314
|
+
(response) => Effect2.tryPromise({
|
|
315
|
+
try: () => response.text(),
|
|
316
|
+
catch: (cause) => new TransportError({
|
|
317
|
+
method: req.method,
|
|
318
|
+
path: req.path,
|
|
319
|
+
cause
|
|
320
|
+
})
|
|
321
|
+
}).pipe(
|
|
322
|
+
Effect2.flatMap((bodyText) => {
|
|
323
|
+
if (!isExpectedStatus(response.status, expectedStatuses)) {
|
|
324
|
+
return Effect2.fail(
|
|
325
|
+
mapUnexpectedStatus(
|
|
326
|
+
req,
|
|
327
|
+
response.status,
|
|
328
|
+
bodyText,
|
|
329
|
+
expectedStatuses,
|
|
330
|
+
ctx.redact
|
|
331
|
+
)
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
return parseResponseBody(req, bodyText, ctx.redact).pipe(
|
|
335
|
+
Effect2.map((parsedBody) => ({
|
|
336
|
+
status: response.status,
|
|
337
|
+
headers: response.headers,
|
|
338
|
+
bodyText,
|
|
339
|
+
body: parsedBody
|
|
340
|
+
}))
|
|
341
|
+
);
|
|
342
|
+
})
|
|
343
|
+
)
|
|
344
|
+
)
|
|
345
|
+
);
|
|
346
|
+
})
|
|
347
|
+
);
|
|
128
348
|
};
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
349
|
+
defaultShouldRetry = (error) => {
|
|
350
|
+
switch (error._tag) {
|
|
351
|
+
case "TransportError":
|
|
352
|
+
case "TimeoutError":
|
|
353
|
+
return true;
|
|
354
|
+
case "UnexpectedStatusError":
|
|
355
|
+
return error.status >= 500;
|
|
356
|
+
default:
|
|
357
|
+
return false;
|
|
133
358
|
}
|
|
134
359
|
};
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
360
|
+
DEFAULT_POLICY_FIELDS = {
|
|
361
|
+
maxAttempts: 3,
|
|
362
|
+
initialDelayMs: 100,
|
|
363
|
+
maxDelayMs: 5e3,
|
|
364
|
+
factor: 2,
|
|
365
|
+
jitter: true,
|
|
366
|
+
shouldRetry: defaultShouldRetry
|
|
367
|
+
};
|
|
368
|
+
noRetry = {
|
|
369
|
+
enabled: false,
|
|
370
|
+
...DEFAULT_POLICY_FIELDS,
|
|
371
|
+
shouldRetry: () => false
|
|
372
|
+
};
|
|
373
|
+
exponentialRetry = (opts) => ({
|
|
374
|
+
enabled: opts.enabled ?? true,
|
|
375
|
+
maxAttempts: opts.maxAttempts ?? DEFAULT_POLICY_FIELDS.maxAttempts,
|
|
376
|
+
initialDelayMs: opts.initialDelayMs ?? DEFAULT_POLICY_FIELDS.initialDelayMs,
|
|
377
|
+
maxDelayMs: opts.maxDelayMs ?? DEFAULT_POLICY_FIELDS.maxDelayMs,
|
|
378
|
+
factor: opts.factor ?? DEFAULT_POLICY_FIELDS.factor,
|
|
379
|
+
jitter: opts.jitter ?? DEFAULT_POLICY_FIELDS.jitter,
|
|
380
|
+
shouldRetry: opts.shouldRetry ?? DEFAULT_POLICY_FIELDS.shouldRetry
|
|
381
|
+
});
|
|
382
|
+
buildSchedule = (policy) => {
|
|
383
|
+
const base = Schedule.exponential(`${policy.initialDelayMs} millis`, policy.factor);
|
|
384
|
+
const withJitter = policy.jitter ? base.pipe(Schedule.jittered) : base;
|
|
385
|
+
const capped = withJitter.pipe(
|
|
386
|
+
Schedule.modifyDelay((_out, duration) => {
|
|
387
|
+
const ms = Duration.toMillis(duration);
|
|
388
|
+
return ms > policy.maxDelayMs ? `${policy.maxDelayMs} millis` : duration;
|
|
389
|
+
})
|
|
390
|
+
);
|
|
391
|
+
return capped.pipe(Schedule.whileInput((error) => policy.shouldRetry(error)));
|
|
392
|
+
};
|
|
393
|
+
withRetry = (effect, policy = noRetry) => {
|
|
394
|
+
if (!policy.enabled || policy.maxAttempts <= 1) {
|
|
395
|
+
return effect;
|
|
155
396
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
}
|
|
174
|
-
if (res.status >= 500) {
|
|
175
|
-
lastErr = new AdGuardSyncUnreachableError(`HTTP ${res.status}`);
|
|
176
|
-
if (attempt === 0) await sleep2(this.retryDelayMs);
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
const errText = await res.text();
|
|
180
|
-
let msg = errText;
|
|
181
|
-
try {
|
|
182
|
-
msg = JSON.parse(errText).message ?? errText;
|
|
183
|
-
} catch {
|
|
184
|
-
}
|
|
185
|
-
throw new AdGuardSyncClientError(res.status, msg);
|
|
186
|
-
} catch (e) {
|
|
187
|
-
if (e instanceof AdGuardSyncClientError) throw e;
|
|
188
|
-
lastErr = new AdGuardSyncUnreachableError(e.message);
|
|
189
|
-
if (attempt === 0) await sleep2(this.retryDelayMs);
|
|
397
|
+
const retries = Math.max(0, policy.maxAttempts - 1);
|
|
398
|
+
return Effect3.retry(effect, {
|
|
399
|
+
times: retries,
|
|
400
|
+
while: (error) => policy.shouldRetry(error),
|
|
401
|
+
schedule: buildSchedule(policy)
|
|
402
|
+
});
|
|
403
|
+
};
|
|
404
|
+
ok = (details) => ({
|
|
405
|
+
content: [{ type: "text", text: JSON.stringify(details, null, 2) }],
|
|
406
|
+
details
|
|
407
|
+
});
|
|
408
|
+
fail = (message, details) => {
|
|
409
|
+
const result = {
|
|
410
|
+
content: [
|
|
411
|
+
{
|
|
412
|
+
type: "text",
|
|
413
|
+
text: JSON.stringify({ error: message }, null, 2)
|
|
190
414
|
}
|
|
415
|
+
],
|
|
416
|
+
isError: true
|
|
417
|
+
};
|
|
418
|
+
if (details !== void 0) {
|
|
419
|
+
result.details = details;
|
|
420
|
+
}
|
|
421
|
+
return result;
|
|
422
|
+
};
|
|
423
|
+
refuseUnconfirmed = (operation) => fail(
|
|
424
|
+
`Refusing to ${operation} without explicit confirmation. Re-call this tool with confirm: true to proceed.`
|
|
425
|
+
);
|
|
426
|
+
operatorErrorMessage = (error) => {
|
|
427
|
+
if (isTaggedShape(error)) {
|
|
428
|
+
if (typeof error.message === "string" && error.message.length > 0 && error.message !== error._tag) {
|
|
429
|
+
return error.message;
|
|
191
430
|
}
|
|
192
|
-
|
|
431
|
+
return formatTaggedThin(error);
|
|
193
432
|
}
|
|
433
|
+
if (error instanceof Error && error.message.length > 0) {
|
|
434
|
+
return error.message;
|
|
435
|
+
}
|
|
436
|
+
return String(error);
|
|
194
437
|
};
|
|
195
438
|
}
|
|
196
439
|
});
|
|
197
440
|
|
|
441
|
+
// src/security.ts
|
|
442
|
+
import { createHash, timingSafeEqual } from "crypto";
|
|
443
|
+
function registerSecret(s) {
|
|
444
|
+
if (!s || s.length === 0) return;
|
|
445
|
+
SECRETS.add(s);
|
|
446
|
+
}
|
|
447
|
+
function maskBase64Tokens(input) {
|
|
448
|
+
return input.replace(BASE64_TOKEN, (match) => {
|
|
449
|
+
let decoded;
|
|
450
|
+
try {
|
|
451
|
+
decoded = Buffer.from(match, "base64").toString("utf8");
|
|
452
|
+
} catch {
|
|
453
|
+
return match;
|
|
454
|
+
}
|
|
455
|
+
for (const secret of SECRETS) {
|
|
456
|
+
if (decoded.includes(secret)) return "REDACTED";
|
|
457
|
+
}
|
|
458
|
+
return match;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
function redact(value) {
|
|
462
|
+
if (typeof value === "string") {
|
|
463
|
+
let out = value;
|
|
464
|
+
for (const secret of SECRETS) out = out.split(secret).join("REDACTED");
|
|
465
|
+
out = maskBase64Tokens(out);
|
|
466
|
+
return out;
|
|
467
|
+
}
|
|
468
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
469
|
+
if (value && typeof value === "object") {
|
|
470
|
+
const out = {};
|
|
471
|
+
for (const [k, v] of Object.entries(value)) out[k] = redact(v);
|
|
472
|
+
return out;
|
|
473
|
+
}
|
|
474
|
+
return value;
|
|
475
|
+
}
|
|
476
|
+
function equalSecret(a, b) {
|
|
477
|
+
return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
|
|
478
|
+
}
|
|
479
|
+
function registerHttpToken(value, configs) {
|
|
480
|
+
const token = (value ?? "").trim();
|
|
481
|
+
if (!token) throw new Error("ADGUARD_MCP_HTTP_TOKEN is required and must not be blank");
|
|
482
|
+
if (token.length < 32) throw new Error("ADGUARD_MCP_HTTP_TOKEN must be at least 32 characters (e.g. openssl rand -hex 32)");
|
|
483
|
+
const credentials = [];
|
|
484
|
+
for (const cfg of configs) {
|
|
485
|
+
const url = new URL(cfg.url);
|
|
486
|
+
for (const [username, password] of [
|
|
487
|
+
[cfg.username ?? "", cfg.password ?? ""],
|
|
488
|
+
[decodeURIComponent(url.username), decodeURIComponent(url.password)]
|
|
489
|
+
]) {
|
|
490
|
+
credentials.push(username, password);
|
|
491
|
+
if (username || password) {
|
|
492
|
+
const pair = `${username}:${password}`;
|
|
493
|
+
const encoded = Buffer.from(pair).toString("base64");
|
|
494
|
+
credentials.push(pair, encoded, `Basic ${encoded}`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (credentials.some((credential) => credential && equalSecret(token, credential))) {
|
|
499
|
+
throw new Error("ADGUARD_MCP_HTTP_TOKEN must differ from all AdGuard Home and Sync credentials");
|
|
500
|
+
}
|
|
501
|
+
registerSecret(token);
|
|
502
|
+
return token;
|
|
503
|
+
}
|
|
504
|
+
var SECRETS, BASE64_TOKEN;
|
|
505
|
+
var init_security = __esm({
|
|
506
|
+
"src/security.ts"() {
|
|
507
|
+
"use strict";
|
|
508
|
+
SECRETS = /* @__PURE__ */ new Set();
|
|
509
|
+
BASE64_TOKEN = /[A-Za-z0-9+/]{12,}={0,2}/g;
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
|
|
198
513
|
// src/config.ts
|
|
514
|
+
import { Effect as Effect6 } from "effect";
|
|
515
|
+
function presentEnvValue(env, key) {
|
|
516
|
+
const raw = env.get(key);
|
|
517
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
518
|
+
return raw;
|
|
519
|
+
}
|
|
520
|
+
function firstPresentAlias(env, keys) {
|
|
521
|
+
for (const key of keys) {
|
|
522
|
+
const value = presentEnvValue(env, key);
|
|
523
|
+
if (value !== void 0) return value;
|
|
524
|
+
}
|
|
525
|
+
return void 0;
|
|
526
|
+
}
|
|
527
|
+
function readDefaultInstance(env) {
|
|
528
|
+
const raw = env.get("ADGUARD_DEFAULT_INSTANCE");
|
|
529
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
530
|
+
return raw.toLowerCase();
|
|
531
|
+
}
|
|
532
|
+
function readRequiredInstanceField(env, key) {
|
|
533
|
+
const raw = env.get(key);
|
|
534
|
+
if (raw === void 0 || raw === "") {
|
|
535
|
+
throw new Error(`${key} is required`);
|
|
536
|
+
}
|
|
537
|
+
return raw;
|
|
538
|
+
}
|
|
199
539
|
function resolveInstances(env) {
|
|
540
|
+
const reader = fromProcessEnv(env);
|
|
200
541
|
const instances = {};
|
|
201
542
|
const candidateNames = /* @__PURE__ */ new Set();
|
|
202
543
|
const SUFFIX_RE = /^ADGUARD_([A-Z0-9_]+)_(URL|USERNAME|PASSWORD)$/;
|
|
@@ -209,9 +550,9 @@ function resolveInstances(env) {
|
|
|
209
550
|
}
|
|
210
551
|
for (const upperName of candidateNames) {
|
|
211
552
|
const name = upperName.toLowerCase();
|
|
212
|
-
const url =
|
|
213
|
-
const username =
|
|
214
|
-
const password =
|
|
553
|
+
const url = presentEnvValue(reader, `ADGUARD_${upperName}_URL`);
|
|
554
|
+
const username = presentEnvValue(reader, `ADGUARD_${upperName}_USERNAME`);
|
|
555
|
+
const password = presentEnvValue(reader, `ADGUARD_${upperName}_PASSWORD`);
|
|
215
556
|
const missing = [];
|
|
216
557
|
if (!url) missing.push("URL");
|
|
217
558
|
if (!username) missing.push("USERNAME");
|
|
@@ -219,10 +560,14 @@ function resolveInstances(env) {
|
|
|
219
560
|
if (missing.length > 0) {
|
|
220
561
|
throw new PartialInstanceConfigError(name, missing);
|
|
221
562
|
}
|
|
222
|
-
instances[name] = {
|
|
563
|
+
instances[name] = {
|
|
564
|
+
url: readRequiredInstanceField(reader, `ADGUARD_${upperName}_URL`),
|
|
565
|
+
username: readRequiredInstanceField(reader, `ADGUARD_${upperName}_USERNAME`),
|
|
566
|
+
password: readRequiredInstanceField(reader, `ADGUARD_${upperName}_PASSWORD`)
|
|
567
|
+
};
|
|
223
568
|
}
|
|
224
569
|
if (Object.keys(instances).length === 0) throw new NoInstancesError();
|
|
225
|
-
const explicitDefault =
|
|
570
|
+
const explicitDefault = readDefaultInstance(reader);
|
|
226
571
|
if (explicitDefault) {
|
|
227
572
|
if (!instances[explicitDefault]) {
|
|
228
573
|
throw new UnknownDefaultInstanceError(explicitDefault, Object.keys(instances));
|
|
@@ -233,9 +578,10 @@ function resolveInstances(env) {
|
|
|
233
578
|
return { instances, defaultInstance };
|
|
234
579
|
}
|
|
235
580
|
function resolveSyncConfig(env) {
|
|
236
|
-
const
|
|
237
|
-
const
|
|
238
|
-
const
|
|
581
|
+
const reader = fromProcessEnv(env);
|
|
582
|
+
const url = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_URL", "ADGUARD_SYNC_URL"]);
|
|
583
|
+
const username = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_USERNAME", "ADGUARD_SYNC_USERNAME"]);
|
|
584
|
+
const password = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_PASSWORD", "ADGUARD_SYNC_PASSWORD"]);
|
|
239
585
|
const missing = [];
|
|
240
586
|
if (!url && (username || password)) missing.push("URL");
|
|
241
587
|
if (username && !password) missing.push("PASSWORD");
|
|
@@ -254,10 +600,23 @@ function getSyncConfig(cfg) {
|
|
|
254
600
|
if (!cfg) throw new NoSyncServerError();
|
|
255
601
|
return cfg;
|
|
256
602
|
}
|
|
257
|
-
|
|
603
|
+
function resolveRequestTimeoutMs(env) {
|
|
604
|
+
const reader = fromProcessEnv(env);
|
|
605
|
+
return Effect6.runSync(
|
|
606
|
+
parseTimeoutEnv(reader, "ADGUARD_REQUEST_TIMEOUT_MS", {
|
|
607
|
+
fallbackMs: DEFAULT_REQUEST_TIMEOUT_MS,
|
|
608
|
+
minMs: MIN_REQUEST_TIMEOUT_MS,
|
|
609
|
+
unit: "ms"
|
|
610
|
+
})
|
|
611
|
+
);
|
|
612
|
+
}
|
|
613
|
+
var DEFAULT_REQUEST_TIMEOUT_MS, MIN_REQUEST_TIMEOUT_MS, NoInstancesError, UnknownInstanceError, PartialInstanceConfigError, UnknownDefaultInstanceError, NoSyncServerError, PartialSyncConfigError;
|
|
258
614
|
var init_config = __esm({
|
|
259
615
|
"src/config.ts"() {
|
|
260
616
|
"use strict";
|
|
617
|
+
init_dist();
|
|
618
|
+
DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
619
|
+
MIN_REQUEST_TIMEOUT_MS = 1e3;
|
|
261
620
|
NoInstancesError = class extends Error {
|
|
262
621
|
constructor() {
|
|
263
622
|
super("No AdGuard instances configured. Set ADGUARD_<NAME>_URL/USERNAME/PASSWORD for at least one instance.");
|
|
@@ -303,11 +662,367 @@ var init_config = __esm({
|
|
|
303
662
|
}
|
|
304
663
|
});
|
|
305
664
|
|
|
665
|
+
// src/adguard-client.ts
|
|
666
|
+
import { Effect as Effect7 } from "effect";
|
|
667
|
+
function toAdGuardError(error) {
|
|
668
|
+
if (error._tag === "UnexpectedStatusError") {
|
|
669
|
+
if (error.status >= 500) return new AdGuardUnreachableError(`HTTP ${error.status}`);
|
|
670
|
+
return new AdGuardClientError(error.status, extractErrorMessage(error.body));
|
|
671
|
+
}
|
|
672
|
+
if (error._tag === "TransportError") {
|
|
673
|
+
return new AdGuardUnreachableError(errorMessage(error.cause));
|
|
674
|
+
}
|
|
675
|
+
if (error._tag === "TimeoutError") return new AdGuardUnreachableError("The operation was aborted.");
|
|
676
|
+
if (error._tag === "ParseError") return new AdGuardUnreachableError(error.message);
|
|
677
|
+
return new AdGuardUnreachableError(String(error));
|
|
678
|
+
}
|
|
679
|
+
function extractErrorMessage(text) {
|
|
680
|
+
let msg = text;
|
|
681
|
+
try {
|
|
682
|
+
msg = JSON.parse(text).message ?? text;
|
|
683
|
+
} catch {
|
|
684
|
+
}
|
|
685
|
+
return redact(msg);
|
|
686
|
+
}
|
|
687
|
+
function errorMessage(error) {
|
|
688
|
+
return error instanceof Error ? error.message : String(error);
|
|
689
|
+
}
|
|
690
|
+
function identityRedact(value) {
|
|
691
|
+
return value;
|
|
692
|
+
}
|
|
693
|
+
function baseUrlForConcat(raw) {
|
|
694
|
+
return new URL(raw.replace(/\/+$/, "") + "/");
|
|
695
|
+
}
|
|
696
|
+
function pathForConcat(path) {
|
|
697
|
+
return path.replace(/^\/+/, "");
|
|
698
|
+
}
|
|
699
|
+
async function fetchWithPlainHeaders(input, init) {
|
|
700
|
+
const headers = init?.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init?.headers;
|
|
701
|
+
const signal = init?.signal;
|
|
702
|
+
const response = await fetch(input.toString(), { ...init, headers });
|
|
703
|
+
const bodyText = await new Promise((resolve, reject) => {
|
|
704
|
+
const abortError = () => Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
|
|
705
|
+
if (signal?.aborted) {
|
|
706
|
+
void response.body?.cancel().catch(() => {
|
|
707
|
+
});
|
|
708
|
+
reject(abortError());
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
const onAbort = () => {
|
|
712
|
+
void response.body?.cancel().catch(() => {
|
|
713
|
+
});
|
|
714
|
+
reject(abortError());
|
|
715
|
+
};
|
|
716
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
717
|
+
response.text().then(
|
|
718
|
+
(text) => {
|
|
719
|
+
signal?.removeEventListener("abort", onAbort);
|
|
720
|
+
resolve(text);
|
|
721
|
+
},
|
|
722
|
+
(err) => {
|
|
723
|
+
signal?.removeEventListener("abort", onAbort);
|
|
724
|
+
reject(err);
|
|
725
|
+
}
|
|
726
|
+
);
|
|
727
|
+
});
|
|
728
|
+
return new Response(bodyText, {
|
|
729
|
+
status: response.status,
|
|
730
|
+
statusText: response.statusText,
|
|
731
|
+
headers: response.headers
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
function parseSuccessBody(text) {
|
|
735
|
+
if (!text) return void 0;
|
|
736
|
+
try {
|
|
737
|
+
return JSON.parse(text);
|
|
738
|
+
} catch {
|
|
739
|
+
return text;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
var AdGuardClientError, AdGuardUnreachableError, AdGuardClient, successStatuses;
|
|
743
|
+
var init_adguard_client = __esm({
|
|
744
|
+
"src/adguard-client.ts"() {
|
|
745
|
+
"use strict";
|
|
746
|
+
init_dist();
|
|
747
|
+
init_security();
|
|
748
|
+
init_security();
|
|
749
|
+
init_config();
|
|
750
|
+
AdGuardClientError = class extends Error {
|
|
751
|
+
constructor(status, message) {
|
|
752
|
+
super(`AdGuard ${status}: ${message}`);
|
|
753
|
+
this.status = status;
|
|
754
|
+
this.name = "AdGuardClientError";
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
AdGuardUnreachableError = class extends Error {
|
|
758
|
+
constructor(cause) {
|
|
759
|
+
super(`AdGuard unreachable: ${cause}`);
|
|
760
|
+
this.name = "AdGuardUnreachableError";
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
AdGuardClient = class {
|
|
764
|
+
constructor(cfg, opts = {}) {
|
|
765
|
+
this.cfg = cfg;
|
|
766
|
+
this.authHeader = "Basic " + Buffer.from(`${cfg.username}:${cfg.password}`).toString("base64");
|
|
767
|
+
registerSecret(cfg.password);
|
|
768
|
+
registerSecret(this.authHeader);
|
|
769
|
+
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
770
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
771
|
+
this.baseUrl = baseUrlForConcat(cfg.url);
|
|
772
|
+
this.auth = {
|
|
773
|
+
apply: (headers) => {
|
|
774
|
+
headers.set("authorization", this.authHeader);
|
|
775
|
+
return Effect7.succeed(headers);
|
|
776
|
+
}
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
authHeader;
|
|
780
|
+
retryDelayMs;
|
|
781
|
+
timeoutMs;
|
|
782
|
+
baseUrl;
|
|
783
|
+
auth;
|
|
784
|
+
async get(path) {
|
|
785
|
+
return this.request("GET", path);
|
|
786
|
+
}
|
|
787
|
+
async post(path, body) {
|
|
788
|
+
return this.request("POST", path, body);
|
|
789
|
+
}
|
|
790
|
+
async put(path, body) {
|
|
791
|
+
return this.request("PUT", path, body);
|
|
792
|
+
}
|
|
793
|
+
async request(method, path, body) {
|
|
794
|
+
const reqPath = pathForConcat(path);
|
|
795
|
+
const httpEffect = (() => {
|
|
796
|
+
try {
|
|
797
|
+
return sendRequest(
|
|
798
|
+
{
|
|
799
|
+
baseUrl: this.baseUrl,
|
|
800
|
+
auth: this.auth,
|
|
801
|
+
timeoutMs: this.timeoutMs,
|
|
802
|
+
fetch: fetchWithPlainHeaders,
|
|
803
|
+
redact: identityRedact
|
|
804
|
+
},
|
|
805
|
+
{
|
|
806
|
+
method,
|
|
807
|
+
path: reqPath,
|
|
808
|
+
body,
|
|
809
|
+
responseType: "text",
|
|
810
|
+
expectedStatuses: successStatuses,
|
|
811
|
+
statusMapper: ({ status, method: method2, path: path2, bodyText, expectedStatuses }) => new UnexpectedStatusError({ status, method: method2, path: path2, body: bodyText, expected: expectedStatuses })
|
|
812
|
+
}
|
|
813
|
+
);
|
|
814
|
+
} catch (error) {
|
|
815
|
+
throw new AdGuardUnreachableError(errorMessage(error));
|
|
816
|
+
}
|
|
817
|
+
})();
|
|
818
|
+
const effect = withRetry(
|
|
819
|
+
httpEffect,
|
|
820
|
+
exponentialRetry({
|
|
821
|
+
maxAttempts: 2,
|
|
822
|
+
initialDelayMs: this.retryDelayMs,
|
|
823
|
+
maxDelayMs: this.retryDelayMs,
|
|
824
|
+
jitter: false,
|
|
825
|
+
shouldRetry: (error) => error._tag === "TransportError" || error._tag === "TimeoutError" || error._tag === "UnexpectedStatusError" && error.status >= 500
|
|
826
|
+
})
|
|
827
|
+
).pipe(
|
|
828
|
+
Effect7.map((res) => parseSuccessBody(res.bodyText)),
|
|
829
|
+
Effect7.mapError((error) => toAdGuardError(error))
|
|
830
|
+
);
|
|
831
|
+
return Effect7.runPromise(Effect7.either(effect)).then((result) => {
|
|
832
|
+
if (result._tag === "Right") return result.right;
|
|
833
|
+
throw result.left;
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
successStatuses = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
|
|
841
|
+
// src/adguard-sync-client.ts
|
|
842
|
+
import { Effect as Effect8 } from "effect";
|
|
843
|
+
function toSyncError(error) {
|
|
844
|
+
if (error._tag === "UnexpectedStatusError") {
|
|
845
|
+
if (error.status >= 500) return new AdGuardSyncUnreachableError(`HTTP ${error.status}`);
|
|
846
|
+
return new AdGuardSyncClientError(error.status, extractErrorMessage2(error.body));
|
|
847
|
+
}
|
|
848
|
+
if (error._tag === "TransportError") {
|
|
849
|
+
return new AdGuardSyncUnreachableError(errorMessage2(error.cause));
|
|
850
|
+
}
|
|
851
|
+
if (error._tag === "TimeoutError") return new AdGuardSyncUnreachableError("The operation was aborted.");
|
|
852
|
+
if (error._tag === "ParseError") return new AdGuardSyncUnreachableError(error.message);
|
|
853
|
+
return new AdGuardSyncUnreachableError(String(error));
|
|
854
|
+
}
|
|
855
|
+
function extractErrorMessage2(text) {
|
|
856
|
+
let msg = text;
|
|
857
|
+
try {
|
|
858
|
+
msg = JSON.parse(text).message ?? text;
|
|
859
|
+
} catch {
|
|
860
|
+
}
|
|
861
|
+
return redact(msg);
|
|
862
|
+
}
|
|
863
|
+
function errorMessage2(error) {
|
|
864
|
+
return error instanceof Error ? error.message : String(error);
|
|
865
|
+
}
|
|
866
|
+
function identityRedact2(value) {
|
|
867
|
+
return value;
|
|
868
|
+
}
|
|
869
|
+
function baseUrlForConcat2(raw) {
|
|
870
|
+
return new URL(raw.replace(/\/+$/, "") + "/");
|
|
871
|
+
}
|
|
872
|
+
function pathForConcat2(path) {
|
|
873
|
+
return path.replace(/^\/+/, "");
|
|
874
|
+
}
|
|
875
|
+
async function fetchWithPlainHeaders2(input, init) {
|
|
876
|
+
const headers = init?.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init?.headers;
|
|
877
|
+
const signal = init?.signal;
|
|
878
|
+
const response = await fetch(input.toString(), { ...init, headers });
|
|
879
|
+
const bodyText = await new Promise((resolve, reject) => {
|
|
880
|
+
const abortError = () => Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
|
|
881
|
+
if (signal?.aborted) {
|
|
882
|
+
void response.body?.cancel().catch(() => {
|
|
883
|
+
});
|
|
884
|
+
reject(abortError());
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
const onAbort = () => {
|
|
888
|
+
void response.body?.cancel().catch(() => {
|
|
889
|
+
});
|
|
890
|
+
reject(abortError());
|
|
891
|
+
};
|
|
892
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
893
|
+
response.text().then(
|
|
894
|
+
(text) => {
|
|
895
|
+
signal?.removeEventListener("abort", onAbort);
|
|
896
|
+
resolve(text);
|
|
897
|
+
},
|
|
898
|
+
(err) => {
|
|
899
|
+
signal?.removeEventListener("abort", onAbort);
|
|
900
|
+
reject(err);
|
|
901
|
+
}
|
|
902
|
+
);
|
|
903
|
+
});
|
|
904
|
+
return new Response(bodyText, {
|
|
905
|
+
status: response.status,
|
|
906
|
+
statusText: response.statusText,
|
|
907
|
+
headers: response.headers
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
function parseSuccessBody2(text) {
|
|
911
|
+
if (!text) return void 0;
|
|
912
|
+
try {
|
|
913
|
+
return JSON.parse(text);
|
|
914
|
+
} catch {
|
|
915
|
+
return text;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
var AdGuardSyncClientError, AdGuardSyncUnreachableError, AdGuardSyncClient, successStatuses2;
|
|
919
|
+
var init_adguard_sync_client = __esm({
|
|
920
|
+
"src/adguard-sync-client.ts"() {
|
|
921
|
+
"use strict";
|
|
922
|
+
init_dist();
|
|
923
|
+
init_security();
|
|
924
|
+
init_security();
|
|
925
|
+
init_config();
|
|
926
|
+
AdGuardSyncClientError = class extends Error {
|
|
927
|
+
constructor(status, message) {
|
|
928
|
+
super(`AdGuardHome Sync ${status}: ${message}`);
|
|
929
|
+
this.status = status;
|
|
930
|
+
this.name = "AdGuardSyncClientError";
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
AdGuardSyncUnreachableError = class extends Error {
|
|
934
|
+
constructor(cause) {
|
|
935
|
+
super(`AdGuardHome Sync unreachable: ${cause}`);
|
|
936
|
+
this.name = "AdGuardSyncUnreachableError";
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
AdGuardSyncClient = class {
|
|
940
|
+
constructor(cfg, opts = {}) {
|
|
941
|
+
this.cfg = cfg;
|
|
942
|
+
if (cfg.username && cfg.password) {
|
|
943
|
+
this.authHeader = "Basic " + Buffer.from(`${cfg.username}:${cfg.password}`).toString("base64");
|
|
944
|
+
registerSecret(cfg.password);
|
|
945
|
+
registerSecret(this.authHeader);
|
|
946
|
+
this.auth = {
|
|
947
|
+
apply: (headers) => {
|
|
948
|
+
headers.set("authorization", this.authHeader);
|
|
949
|
+
return Effect8.succeed(headers);
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
954
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
955
|
+
this.baseUrl = baseUrlForConcat2(cfg.url);
|
|
956
|
+
}
|
|
957
|
+
authHeader;
|
|
958
|
+
retryDelayMs;
|
|
959
|
+
timeoutMs;
|
|
960
|
+
baseUrl;
|
|
961
|
+
auth;
|
|
962
|
+
async get(path) {
|
|
963
|
+
return this.request("GET", path);
|
|
964
|
+
}
|
|
965
|
+
async post(path, body) {
|
|
966
|
+
return this.request("POST", path, body);
|
|
967
|
+
}
|
|
968
|
+
async head(path) {
|
|
969
|
+
await this.request("HEAD", path);
|
|
970
|
+
return { ok: true };
|
|
971
|
+
}
|
|
972
|
+
async request(method, path, body) {
|
|
973
|
+
const reqPath = pathForConcat2(path);
|
|
974
|
+
const httpEffect = (() => {
|
|
975
|
+
try {
|
|
976
|
+
return sendRequest(
|
|
977
|
+
{
|
|
978
|
+
baseUrl: this.baseUrl,
|
|
979
|
+
auth: this.auth,
|
|
980
|
+
timeoutMs: this.timeoutMs,
|
|
981
|
+
fetch: fetchWithPlainHeaders2,
|
|
982
|
+
redact: identityRedact2
|
|
983
|
+
},
|
|
984
|
+
{
|
|
985
|
+
method,
|
|
986
|
+
path: reqPath,
|
|
987
|
+
body,
|
|
988
|
+
responseType: method === "HEAD" ? "none" : "text",
|
|
989
|
+
expectedStatuses: successStatuses2,
|
|
990
|
+
statusMapper: ({ status, method: method2, path: path2, bodyText, expectedStatuses }) => new UnexpectedStatusError({ status, method: method2, path: path2, body: bodyText, expected: expectedStatuses })
|
|
991
|
+
}
|
|
992
|
+
);
|
|
993
|
+
} catch (error) {
|
|
994
|
+
throw new AdGuardSyncUnreachableError(errorMessage2(error));
|
|
995
|
+
}
|
|
996
|
+
})();
|
|
997
|
+
const effect = withRetry(
|
|
998
|
+
httpEffect,
|
|
999
|
+
exponentialRetry({
|
|
1000
|
+
maxAttempts: 2,
|
|
1001
|
+
initialDelayMs: this.retryDelayMs,
|
|
1002
|
+
maxDelayMs: this.retryDelayMs,
|
|
1003
|
+
jitter: false,
|
|
1004
|
+
shouldRetry: (error) => error._tag === "TransportError" || error._tag === "TimeoutError" || error._tag === "UnexpectedStatusError" && error.status >= 500
|
|
1005
|
+
})
|
|
1006
|
+
).pipe(
|
|
1007
|
+
Effect8.map((res) => method === "HEAD" ? void 0 : parseSuccessBody2(res.bodyText)),
|
|
1008
|
+
Effect8.mapError((error) => toSyncError(error))
|
|
1009
|
+
);
|
|
1010
|
+
return Effect8.runPromise(Effect8.either(effect)).then((result) => {
|
|
1011
|
+
if (result._tag === "Right") return result.right;
|
|
1012
|
+
throw result.left;
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
successStatuses2 = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
|
|
306
1020
|
// src/tools/_util.ts
|
|
307
1021
|
import { Type } from "@sinclair/typebox";
|
|
308
1022
|
function jsonToolResult(payload) {
|
|
1023
|
+
const kitResult = ok(payload);
|
|
309
1024
|
return {
|
|
310
|
-
content:
|
|
1025
|
+
content: kitResult.content
|
|
311
1026
|
};
|
|
312
1027
|
}
|
|
313
1028
|
function hhmmToMs(value) {
|
|
@@ -330,6 +1045,7 @@ var InstanceArg;
|
|
|
330
1045
|
var init_util = __esm({
|
|
331
1046
|
"src/tools/_util.ts"() {
|
|
332
1047
|
"use strict";
|
|
1048
|
+
init_dist();
|
|
333
1049
|
init_config();
|
|
334
1050
|
InstanceArg = Type.Optional(Type.String({
|
|
335
1051
|
description: "Named instance to target (e.g. 'primary', 'secondary'). Default: the configured default instance."
|
|
@@ -372,49 +1088,6 @@ var init_adguard_tls_status = __esm({
|
|
|
372
1088
|
}
|
|
373
1089
|
});
|
|
374
1090
|
|
|
375
|
-
// src/security.ts
|
|
376
|
-
function registerSecret(s) {
|
|
377
|
-
if (!s || s.length === 0) return;
|
|
378
|
-
SECRETS.add(s);
|
|
379
|
-
}
|
|
380
|
-
function maskBase64Tokens(input) {
|
|
381
|
-
return input.replace(BASE64_TOKEN, (match) => {
|
|
382
|
-
let decoded;
|
|
383
|
-
try {
|
|
384
|
-
decoded = Buffer.from(match, "base64").toString("utf8");
|
|
385
|
-
} catch {
|
|
386
|
-
return match;
|
|
387
|
-
}
|
|
388
|
-
for (const secret of SECRETS) {
|
|
389
|
-
if (decoded.includes(secret)) return "REDACTED";
|
|
390
|
-
}
|
|
391
|
-
return match;
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
function redact(value) {
|
|
395
|
-
if (typeof value === "string") {
|
|
396
|
-
let out = value;
|
|
397
|
-
for (const secret of SECRETS) out = out.split(secret).join("REDACTED");
|
|
398
|
-
out = maskBase64Tokens(out);
|
|
399
|
-
return out;
|
|
400
|
-
}
|
|
401
|
-
if (Array.isArray(value)) return value.map(redact);
|
|
402
|
-
if (value && typeof value === "object") {
|
|
403
|
-
const out = {};
|
|
404
|
-
for (const [k, v] of Object.entries(value)) out[k] = redact(v);
|
|
405
|
-
return out;
|
|
406
|
-
}
|
|
407
|
-
return value;
|
|
408
|
-
}
|
|
409
|
-
var SECRETS, BASE64_TOKEN;
|
|
410
|
-
var init_security = __esm({
|
|
411
|
-
"src/security.ts"() {
|
|
412
|
-
"use strict";
|
|
413
|
-
SECRETS = /* @__PURE__ */ new Set();
|
|
414
|
-
BASE64_TOKEN = /[A-Za-z0-9+/]{12,}={0,2}/g;
|
|
415
|
-
}
|
|
416
|
-
});
|
|
417
|
-
|
|
418
1091
|
// src/tools/adguard_status.ts
|
|
419
1092
|
import { Type as Type3 } from "@sinclair/typebox";
|
|
420
1093
|
function createAdguardStatusTool(getClient) {
|
|
@@ -627,16 +1300,28 @@ var init_adguard_list_blocked_services_catalog = __esm({
|
|
|
627
1300
|
});
|
|
628
1301
|
|
|
629
1302
|
// src/gates.ts
|
|
1303
|
+
function throwGateRefusal(message) {
|
|
1304
|
+
const kitResult = fail(message);
|
|
1305
|
+
let extracted = message;
|
|
1306
|
+
try {
|
|
1307
|
+
const parsed = JSON.parse(kitResult.content[0]?.text ?? "");
|
|
1308
|
+
if (typeof parsed.error === "string") extracted = parsed.error;
|
|
1309
|
+
} catch {
|
|
1310
|
+
}
|
|
1311
|
+
throw new WriteGateError(extracted);
|
|
1312
|
+
}
|
|
630
1313
|
function assertConfirmedWrite(args, toolName) {
|
|
631
1314
|
if (args.confirm !== true) {
|
|
632
|
-
|
|
1315
|
+
void refuseUnconfirmed(toolName);
|
|
1316
|
+
throwGateRefusal(
|
|
633
1317
|
`${toolName} is a write operation. Pass {"confirm": true} to proceed.`
|
|
634
1318
|
);
|
|
635
1319
|
}
|
|
636
1320
|
}
|
|
637
1321
|
function assertDestructive(args, toolName) {
|
|
638
1322
|
if (args.confirm !== true || args.destructive !== true) {
|
|
639
|
-
|
|
1323
|
+
void refuseUnconfirmed(toolName);
|
|
1324
|
+
throwGateRefusal(
|
|
640
1325
|
`${toolName} is a destructive operation. Pass {"confirm": true, "destructive": true} to proceed.`
|
|
641
1326
|
);
|
|
642
1327
|
}
|
|
@@ -645,6 +1330,7 @@ var WriteGateError;
|
|
|
645
1330
|
var init_gates = __esm({
|
|
646
1331
|
"src/gates.ts"() {
|
|
647
1332
|
"use strict";
|
|
1333
|
+
init_dist();
|
|
648
1334
|
WriteGateError = class extends Error {
|
|
649
1335
|
constructor(message) {
|
|
650
1336
|
super(message);
|
|
@@ -2179,25 +2865,25 @@ var init_tools = __esm({
|
|
|
2179
2865
|
}
|
|
2180
2866
|
});
|
|
2181
2867
|
|
|
2182
|
-
//
|
|
2183
|
-
var mcp_server_exports = {};
|
|
2184
|
-
__export(mcp_server_exports, {
|
|
2185
|
-
startServer: () => startServer
|
|
2186
|
-
});
|
|
2187
|
-
import { realpathSync } from "fs";
|
|
2188
|
-
import { pathToFileURL } from "url";
|
|
2868
|
+
// src/server.ts
|
|
2189
2869
|
import { Buffer as Buffer2 } from "buffer";
|
|
2190
2870
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2191
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
2192
2871
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2193
|
-
|
|
2194
|
-
const
|
|
2872
|
+
function mcpToolError(message) {
|
|
2873
|
+
const failed = fail(message);
|
|
2874
|
+
return {
|
|
2875
|
+
content: [{ type: "text", text: JSON.stringify({ error: message }) }],
|
|
2876
|
+
isError: failed.isError
|
|
2877
|
+
};
|
|
2878
|
+
}
|
|
2879
|
+
function createMcpServer(env = process.env) {
|
|
2880
|
+
const cfg = resolveInstances(env);
|
|
2195
2881
|
for (const inst of Object.values(cfg.instances)) {
|
|
2196
2882
|
registerSecret(inst.password);
|
|
2197
2883
|
const basicValue = "Basic " + Buffer2.from(`${inst.username}:${inst.password}`).toString("base64");
|
|
2198
2884
|
registerSecret(basicValue);
|
|
2199
2885
|
}
|
|
2200
|
-
const syncCfg = resolveSyncConfig(
|
|
2886
|
+
const syncCfg = resolveSyncConfig(env);
|
|
2201
2887
|
if (syncCfg?.password) {
|
|
2202
2888
|
registerSecret(syncCfg.password);
|
|
2203
2889
|
if (syncCfg.username) {
|
|
@@ -2205,26 +2891,282 @@ async function startServer() {
|
|
|
2205
2891
|
registerSecret(basicValue);
|
|
2206
2892
|
}
|
|
2207
2893
|
}
|
|
2208
|
-
const
|
|
2209
|
-
const
|
|
2894
|
+
const timeoutMs = resolveRequestTimeoutMs(env);
|
|
2895
|
+
const getClient = (name) => new AdGuardClient(getInstanceConfig(cfg, name), { timeoutMs });
|
|
2896
|
+
const getSyncClient = () => new AdGuardSyncClient(getSyncConfig(syncCfg), { timeoutMs });
|
|
2210
2897
|
const tools = buildAllTools(getClient, getSyncClient);
|
|
2211
2898
|
const toolMap = new Map(tools.map((t) => [t.name, t]));
|
|
2212
|
-
const server = new Server({ name: "adguard-mcp", version: "0.3.
|
|
2899
|
+
const server = new Server({ name: "adguard-mcp", version: "0.3.2" }, { capabilities: { tools: {} } });
|
|
2213
2900
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
2214
2901
|
tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
|
|
2215
2902
|
}));
|
|
2216
2903
|
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
2217
2904
|
const t = toolMap.get(req.params.name);
|
|
2218
2905
|
if (!t) {
|
|
2219
|
-
return
|
|
2906
|
+
return mcpToolError(`unknown tool: ${req.params.name}`);
|
|
2220
2907
|
}
|
|
2221
2908
|
try {
|
|
2222
2909
|
return await t.execute(req.params.name, req.params.arguments ?? {});
|
|
2223
2910
|
} catch (e) {
|
|
2224
|
-
|
|
2225
|
-
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
|
|
2911
|
+
return mcpToolError(redact(operatorErrorMessage(e)));
|
|
2226
2912
|
}
|
|
2227
2913
|
});
|
|
2914
|
+
return server;
|
|
2915
|
+
}
|
|
2916
|
+
var init_server = __esm({
|
|
2917
|
+
"src/server.ts"() {
|
|
2918
|
+
"use strict";
|
|
2919
|
+
init_dist();
|
|
2920
|
+
init_config();
|
|
2921
|
+
init_adguard_client();
|
|
2922
|
+
init_adguard_sync_client();
|
|
2923
|
+
init_security();
|
|
2924
|
+
init_tools();
|
|
2925
|
+
}
|
|
2926
|
+
});
|
|
2927
|
+
|
|
2928
|
+
// src/http.ts
|
|
2929
|
+
var http_exports = {};
|
|
2930
|
+
__export(http_exports, {
|
|
2931
|
+
createHttpServer: () => createHttpServer,
|
|
2932
|
+
startHttpServer: () => startHttpServer
|
|
2933
|
+
});
|
|
2934
|
+
import { randomUUID } from "crypto";
|
|
2935
|
+
import { createServer } from "http";
|
|
2936
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
2937
|
+
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
2938
|
+
function send(response, status, body) {
|
|
2939
|
+
if (response.headersSent || response.destroyed) return;
|
|
2940
|
+
response.writeHead(status, { "content-type": "text/plain; charset=utf-8", connection: "close" });
|
|
2941
|
+
response.end(body);
|
|
2942
|
+
}
|
|
2943
|
+
function validHost(value, boundHost) {
|
|
2944
|
+
if (!value) return false;
|
|
2945
|
+
try {
|
|
2946
|
+
const url = new URL(`http://${value}`);
|
|
2947
|
+
if (!/^(\[[a-f\d:]+\]|[a-z\d.-]+)(:\d+)?$/i.test(value)) return false;
|
|
2948
|
+
return LOOPBACK_HOSTS.has(url.hostname) || url.hostname === (boundHost.includes(":") ? `[${boundHost}]` : boundHost).toLowerCase();
|
|
2949
|
+
} catch {
|
|
2950
|
+
return false;
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
function validOrigin(value) {
|
|
2954
|
+
if (value === void 0) return true;
|
|
2955
|
+
try {
|
|
2956
|
+
const url = new URL(value);
|
|
2957
|
+
return (url.protocol === "http:" || url.protocol === "https:") && url.origin === value && LOOPBACK_HOSTS.has(url.hostname);
|
|
2958
|
+
} catch {
|
|
2959
|
+
return false;
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
async function readBody(request) {
|
|
2963
|
+
const length = request.headers["content-length"];
|
|
2964
|
+
if (length !== void 0 && (!/^\d+$/.test(length) || Number(length) > MAX_BODY_BYTES)) {
|
|
2965
|
+
throw new RequestError(413, "Request body too large");
|
|
2966
|
+
}
|
|
2967
|
+
const chunks = [];
|
|
2968
|
+
let size = 0;
|
|
2969
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
2970
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
2971
|
+
size += bytes.length;
|
|
2972
|
+
if (size > MAX_BODY_BYTES) throw new RequestError(413, "Request body too large");
|
|
2973
|
+
chunks.push(bytes);
|
|
2974
|
+
}
|
|
2975
|
+
try {
|
|
2976
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
2977
|
+
} catch {
|
|
2978
|
+
throw new RequestError(400, "Invalid JSON");
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
async function createHttpServer() {
|
|
2982
|
+
const env = { ...process.env };
|
|
2983
|
+
const rawToken = env.ADGUARD_MCP_HTTP_TOKEN;
|
|
2984
|
+
if (!rawToken?.trim()) throw new Error("ADGUARD_MCP_HTTP_TOKEN is required and must not be blank");
|
|
2985
|
+
const cfg = resolveInstances(env);
|
|
2986
|
+
const syncCfg = resolveSyncConfig(env);
|
|
2987
|
+
const token = registerHttpToken(rawToken, [...Object.values(cfg.instances), ...syncCfg ? [syncCfg] : []]);
|
|
2988
|
+
const host = env.ADGUARD_MCP_HTTP_HOST ?? "127.0.0.1";
|
|
2989
|
+
if (!host.trim() || host.includes("/") || host.includes("@")) {
|
|
2990
|
+
throw new Error("ADGUARD_MCP_HTTP_HOST must be a host name or address");
|
|
2991
|
+
}
|
|
2992
|
+
if (["0.0.0.0", "::", "[::]"].includes(host.trim())) {
|
|
2993
|
+
throw new Error("ADGUARD_MCP_HTTP_HOST must be a specific address, not a wildcard; bind the interface clients will use");
|
|
2994
|
+
}
|
|
2995
|
+
const portValue = env.ADGUARD_MCP_HTTP_PORT ?? "3111";
|
|
2996
|
+
if (!/^\d+$/.test(portValue) || Number(portValue) > 65535) {
|
|
2997
|
+
throw new Error("ADGUARD_MCP_HTTP_PORT must be an integer from 0 to 65535");
|
|
2998
|
+
}
|
|
2999
|
+
const port = Number(portValue);
|
|
3000
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
3001
|
+
const resources = /* @__PURE__ */ new Set();
|
|
3002
|
+
let closing = false;
|
|
3003
|
+
const dispose = async (session) => {
|
|
3004
|
+
resources.delete(session);
|
|
3005
|
+
if (session.transport.sessionId) sessions.delete(session.transport.sessionId);
|
|
3006
|
+
await session.server.close();
|
|
3007
|
+
};
|
|
3008
|
+
const handle = async (request, response) => {
|
|
3009
|
+
if (closing) return send(response, 503, "Service unavailable");
|
|
3010
|
+
if (!validHost(request.headers.host, host) || !validOrigin(request.headers.origin)) {
|
|
3011
|
+
return send(response, 403, "Forbidden");
|
|
3012
|
+
}
|
|
3013
|
+
if (request.method === "GET" && request.url === "/healthz") {
|
|
3014
|
+
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ status: "ok" }));
|
|
3015
|
+
return;
|
|
3016
|
+
}
|
|
3017
|
+
if (request.url !== "/mcp") return send(response, 404, "Not found");
|
|
3018
|
+
const supplied = request.headers.authorization?.match(/^Bearer (.+)$/i)?.[1] ?? "";
|
|
3019
|
+
if (!equalSecret(supplied, token)) {
|
|
3020
|
+
response.setHeader("www-authenticate", "Bearer");
|
|
3021
|
+
return send(response, 401, "Unauthorized");
|
|
3022
|
+
}
|
|
3023
|
+
if (!["GET", "POST", "DELETE"].includes(request.method ?? "")) {
|
|
3024
|
+
response.setHeader("allow", "GET, POST, DELETE");
|
|
3025
|
+
return send(response, 405, "Method not allowed");
|
|
3026
|
+
}
|
|
3027
|
+
const body = request.method === "POST" ? await readBody(request) : void 0;
|
|
3028
|
+
if (closing) return send(response, 503, "Service unavailable");
|
|
3029
|
+
const id = request.headers["mcp-session-id"];
|
|
3030
|
+
let session = typeof id === "string" ? sessions.get(id) : void 0;
|
|
3031
|
+
if (id !== void 0 && !session) return send(response, 404, "Session not found");
|
|
3032
|
+
let created = false;
|
|
3033
|
+
if (!session) {
|
|
3034
|
+
if (request.method !== "POST" || !isInitializeRequest(body)) return send(response, 400, "Initialize a session first");
|
|
3035
|
+
if (resources.size >= MAX_SESSIONS) return send(response, 503, "Service unavailable");
|
|
3036
|
+
const server = createMcpServer(env);
|
|
3037
|
+
const transport = new StreamableHTTPServerTransport({
|
|
3038
|
+
sessionIdGenerator: randomUUID,
|
|
3039
|
+
enableJsonResponse: true,
|
|
3040
|
+
onsessioninitialized: (sessionId) => {
|
|
3041
|
+
sessions.set(sessionId, entry);
|
|
3042
|
+
}
|
|
3043
|
+
});
|
|
3044
|
+
const entry = { server, transport, lastUsed: Date.now(), active: 0 };
|
|
3045
|
+
session = entry;
|
|
3046
|
+
resources.add(entry);
|
|
3047
|
+
created = true;
|
|
3048
|
+
try {
|
|
3049
|
+
await server.connect(transport);
|
|
3050
|
+
} catch (error) {
|
|
3051
|
+
await dispose(entry);
|
|
3052
|
+
throw error;
|
|
3053
|
+
}
|
|
3054
|
+
const onclose = transport.onclose;
|
|
3055
|
+
transport.onclose = () => {
|
|
3056
|
+
resources.delete(entry);
|
|
3057
|
+
if (transport.sessionId) sessions.delete(transport.sessionId);
|
|
3058
|
+
onclose?.();
|
|
3059
|
+
};
|
|
3060
|
+
}
|
|
3061
|
+
session.lastUsed = Date.now();
|
|
3062
|
+
const activeCall = request.method === "POST";
|
|
3063
|
+
if (activeCall) session.active++;
|
|
3064
|
+
try {
|
|
3065
|
+
await session.transport.handleRequest(request, response, body);
|
|
3066
|
+
} finally {
|
|
3067
|
+
if (activeCall) session.active--;
|
|
3068
|
+
session.lastUsed = Date.now();
|
|
3069
|
+
if (created && !session.transport.sessionId) await dispose(session);
|
|
3070
|
+
}
|
|
3071
|
+
};
|
|
3072
|
+
const listener = createServer((request, response) => {
|
|
3073
|
+
void handle(request, response).catch((error) => {
|
|
3074
|
+
send(
|
|
3075
|
+
response,
|
|
3076
|
+
error instanceof RequestError ? error.status : 500,
|
|
3077
|
+
error instanceof RequestError ? error.message : "Internal server error"
|
|
3078
|
+
);
|
|
3079
|
+
});
|
|
3080
|
+
});
|
|
3081
|
+
listener.requestTimeout = 3e4;
|
|
3082
|
+
listener.headersTimeout = 1e4;
|
|
3083
|
+
await new Promise((resolve, reject) => {
|
|
3084
|
+
listener.once("error", reject);
|
|
3085
|
+
listener.listen(port, host, () => {
|
|
3086
|
+
listener.off("error", reject);
|
|
3087
|
+
resolve();
|
|
3088
|
+
});
|
|
3089
|
+
});
|
|
3090
|
+
const address = listener.address();
|
|
3091
|
+
if (!address || typeof address === "string") throw new Error("HTTP listener did not bind a TCP port");
|
|
3092
|
+
const reaper = setInterval(() => {
|
|
3093
|
+
for (const session of resources) {
|
|
3094
|
+
if (session.active === 0 && Date.now() - session.lastUsed > SESSION_IDLE_MS) {
|
|
3095
|
+
void dispose(session).catch(() => void 0);
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
}, 6e4);
|
|
3099
|
+
reaper.unref();
|
|
3100
|
+
let closePromise;
|
|
3101
|
+
return {
|
|
3102
|
+
host: address.address,
|
|
3103
|
+
port: address.port,
|
|
3104
|
+
close() {
|
|
3105
|
+
closePromise ??= (async () => {
|
|
3106
|
+
closing = true;
|
|
3107
|
+
clearInterval(reaper);
|
|
3108
|
+
const stopped = new Promise((resolve, reject) => {
|
|
3109
|
+
listener.close((error) => error ? reject(error) : resolve());
|
|
3110
|
+
});
|
|
3111
|
+
const deadline = setTimeout(() => listener.closeAllConnections(), 5e3);
|
|
3112
|
+
deadline.unref();
|
|
3113
|
+
try {
|
|
3114
|
+
await Promise.allSettled([...resources].map(dispose));
|
|
3115
|
+
listener.closeIdleConnections();
|
|
3116
|
+
await stopped;
|
|
3117
|
+
} finally {
|
|
3118
|
+
clearTimeout(deadline);
|
|
3119
|
+
}
|
|
3120
|
+
})();
|
|
3121
|
+
return closePromise;
|
|
3122
|
+
}
|
|
3123
|
+
};
|
|
3124
|
+
}
|
|
3125
|
+
async function startHttpServer() {
|
|
3126
|
+
const http = await createHttpServer();
|
|
3127
|
+
const host = http.host.includes(":") ? `[${http.host}]` : http.host;
|
|
3128
|
+
console.error(`adguard-mcp HTTP listening on http://${host}:${http.port}/mcp`);
|
|
3129
|
+
const shutdown = () => {
|
|
3130
|
+
void http.close().then(() => {
|
|
3131
|
+
process.off("SIGTERM", shutdown);
|
|
3132
|
+
process.off("SIGINT", shutdown);
|
|
3133
|
+
}).catch(() => {
|
|
3134
|
+
process.exitCode = 1;
|
|
3135
|
+
});
|
|
3136
|
+
};
|
|
3137
|
+
process.on("SIGTERM", shutdown);
|
|
3138
|
+
process.on("SIGINT", shutdown);
|
|
3139
|
+
}
|
|
3140
|
+
var MAX_BODY_BYTES, MAX_SESSIONS, SESSION_IDLE_MS, LOOPBACK_HOSTS, RequestError;
|
|
3141
|
+
var init_http = __esm({
|
|
3142
|
+
"src/http.ts"() {
|
|
3143
|
+
"use strict";
|
|
3144
|
+
init_server();
|
|
3145
|
+
init_config();
|
|
3146
|
+
init_security();
|
|
3147
|
+
MAX_BODY_BYTES = 1048576;
|
|
3148
|
+
MAX_SESSIONS = 128;
|
|
3149
|
+
SESSION_IDLE_MS = 30 * 6e4;
|
|
3150
|
+
LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
3151
|
+
RequestError = class extends Error {
|
|
3152
|
+
constructor(status, message) {
|
|
3153
|
+
super(message);
|
|
3154
|
+
this.status = status;
|
|
3155
|
+
}
|
|
3156
|
+
};
|
|
3157
|
+
}
|
|
3158
|
+
});
|
|
3159
|
+
|
|
3160
|
+
// mcp-server.ts
|
|
3161
|
+
var mcp_server_exports = {};
|
|
3162
|
+
__export(mcp_server_exports, {
|
|
3163
|
+
startServer: () => startServer
|
|
3164
|
+
});
|
|
3165
|
+
import { realpathSync } from "fs";
|
|
3166
|
+
import { pathToFileURL } from "url";
|
|
3167
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3168
|
+
async function startServer() {
|
|
3169
|
+
const server = createMcpServer();
|
|
2228
3170
|
const transport = new StdioServerTransport();
|
|
2229
3171
|
const __send = transport.send.bind(transport);
|
|
2230
3172
|
transport.send = (message) => {
|
|
@@ -2243,11 +3185,8 @@ var isEntrypoint;
|
|
|
2243
3185
|
var init_mcp_server = __esm({
|
|
2244
3186
|
"mcp-server.ts"() {
|
|
2245
3187
|
"use strict";
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
init_adguard_sync_client();
|
|
2249
|
-
init_security();
|
|
2250
|
-
init_tools();
|
|
3188
|
+
init_dist();
|
|
3189
|
+
init_server();
|
|
2251
3190
|
isEntrypoint = (() => {
|
|
2252
3191
|
const arg = process.argv[1];
|
|
2253
3192
|
if (typeof arg !== "string") return false;
|
|
@@ -2258,9 +3197,9 @@ var init_mcp_server = __esm({
|
|
|
2258
3197
|
}
|
|
2259
3198
|
})();
|
|
2260
3199
|
if (isEntrypoint) {
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
console.error(`adguard-mcp fatal: ${
|
|
3200
|
+
const start = process.argv.includes("--http") ? Promise.resolve().then(() => (init_http(), http_exports)).then(({ startHttpServer: startHttpServer2 }) => startHttpServer2()) : startServer();
|
|
3201
|
+
start.catch((error) => {
|
|
3202
|
+
console.error(`adguard-mcp fatal: ${operatorErrorMessage(error)}`);
|
|
2264
3203
|
process.exit(1);
|
|
2265
3204
|
});
|
|
2266
3205
|
}
|
|
@@ -2268,13 +3207,14 @@ var init_mcp_server = __esm({
|
|
|
2268
3207
|
});
|
|
2269
3208
|
|
|
2270
3209
|
// cli.ts
|
|
3210
|
+
init_dist();
|
|
2271
3211
|
init_adguard_client();
|
|
2272
3212
|
init_adguard_sync_client();
|
|
2273
3213
|
init_config();
|
|
2274
3214
|
init_adguard_tls_status();
|
|
2275
3215
|
import { realpathSync as realpathSync2 } from "fs";
|
|
2276
3216
|
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
2277
|
-
var VERSION = "0.3.
|
|
3217
|
+
var VERSION = "0.3.2";
|
|
2278
3218
|
var UsageError = class extends Error {
|
|
2279
3219
|
};
|
|
2280
3220
|
var BLOCKED_REASONS2 = [
|
|
@@ -2318,7 +3258,7 @@ AdGuardHome Sync (read-only):
|
|
|
2318
3258
|
|
|
2319
3259
|
Other:
|
|
2320
3260
|
help Show this help
|
|
2321
|
-
mcp
|
|
3261
|
+
mcp [--http] Start the MCP server over stdio or HTTP
|
|
2322
3262
|
|
|
2323
3263
|
Global options:
|
|
2324
3264
|
--instance <name> Target a named AdGuard instance (default: configured default)
|
|
@@ -2371,8 +3311,9 @@ function parseArgs(argv) {
|
|
|
2371
3311
|
const cmd = args.shift();
|
|
2372
3312
|
if (!cmd || cmd === "help") return { kind: "help" };
|
|
2373
3313
|
if (cmd === "mcp") {
|
|
3314
|
+
const http = takeFlag(args, "--http");
|
|
2374
3315
|
ensureNoExtra(args);
|
|
2375
|
-
return { kind: "mcp" };
|
|
3316
|
+
return http ? { kind: "mcp", http: true } : { kind: "mcp" };
|
|
2376
3317
|
}
|
|
2377
3318
|
const json = takeFlag(args, "--json");
|
|
2378
3319
|
const instance = takeOption(args, "--instance");
|
|
@@ -2644,13 +3585,14 @@ async function run(argv, deps) {
|
|
|
2644
3585
|
return 0;
|
|
2645
3586
|
}
|
|
2646
3587
|
if (parsed.kind === "mcp") {
|
|
2647
|
-
await deps.startServer();
|
|
3588
|
+
if (parsed.http) await deps.startServer(true);
|
|
3589
|
+
else await deps.startServer();
|
|
2648
3590
|
return 0;
|
|
2649
3591
|
}
|
|
2650
3592
|
try {
|
|
2651
3593
|
return await dispatch(parsed, deps);
|
|
2652
3594
|
} catch (error) {
|
|
2653
|
-
deps.err(
|
|
3595
|
+
deps.err(operatorErrorMessage(error));
|
|
2654
3596
|
return 1;
|
|
2655
3597
|
}
|
|
2656
3598
|
}
|
|
@@ -2798,24 +3740,36 @@ var isEntrypoint2 = (() => {
|
|
|
2798
3740
|
})();
|
|
2799
3741
|
if (isEntrypoint2) {
|
|
2800
3742
|
const env = process.env;
|
|
2801
|
-
|
|
2802
|
-
|
|
3743
|
+
try {
|
|
3744
|
+
const timeoutMs = resolveRequestTimeoutMs(env);
|
|
3745
|
+
run(process.argv.slice(2), {
|
|
3746
|
+
out: (s) => process.stdout.write(`${s}
|
|
2803
3747
|
`),
|
|
2804
|
-
|
|
3748
|
+
err: (s) => process.stderr.write(`${s}
|
|
2805
3749
|
`),
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
3750
|
+
makeClient: (instance) => new AdGuardClient(getInstanceConfig(resolveInstances(env), instance), { timeoutMs }),
|
|
3751
|
+
makeSyncClient: () => new AdGuardSyncClient(getSyncConfig(resolveSyncConfig(env)), { timeoutMs }),
|
|
3752
|
+
startServer: async (http = false) => {
|
|
3753
|
+
if (http) {
|
|
3754
|
+
const { startHttpServer: startHttpServer2 } = await Promise.resolve().then(() => (init_http(), http_exports));
|
|
3755
|
+
await startHttpServer2();
|
|
3756
|
+
return;
|
|
3757
|
+
}
|
|
3758
|
+
const { startServer: startServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
|
|
3759
|
+
await startServer2();
|
|
3760
|
+
}
|
|
3761
|
+
}).then((code) => {
|
|
3762
|
+
process.exitCode = code;
|
|
3763
|
+
}).catch((error) => {
|
|
3764
|
+
process.stderr.write(`${operatorErrorMessage(error)}
|
|
3765
|
+
`);
|
|
3766
|
+
process.exitCode = 1;
|
|
3767
|
+
});
|
|
3768
|
+
} catch (error) {
|
|
3769
|
+
process.stderr.write(`${operatorErrorMessage(error)}
|
|
2816
3770
|
`);
|
|
2817
3771
|
process.exitCode = 1;
|
|
2818
|
-
}
|
|
3772
|
+
}
|
|
2819
3773
|
}
|
|
2820
3774
|
export {
|
|
2821
3775
|
HELP,
|