@solomonneas/adguard-mcp 0.2.0 → 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.
@@ -0,0 +1,3215 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
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
+ }
72
+ }
73
+ }
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
+ }
109
+ }
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);
139
+ };
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;
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") {
191
+ };
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);
216
+ }
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
+ });
224
+ }
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
+ });
233
+ }
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
+ });
240
+ }
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]");
258
+ }
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));
285
+ }
286
+ } else {
287
+ url.searchParams.set(key, String(value));
288
+ }
289
+ }
290
+ }
291
+ return url;
292
+ };
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
+ );
348
+ };
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;
358
+ }
359
+ };
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;
396
+ }
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)
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;
430
+ }
431
+ return formatTaggedThin(error);
432
+ }
433
+ if (error instanceof Error && error.message.length > 0) {
434
+ return error.message;
435
+ }
436
+ return String(error);
437
+ };
438
+ }
439
+ });
440
+
441
+ // src/config.ts
442
+ import { Effect as Effect6 } from "effect";
443
+ function presentEnvValue(env, key) {
444
+ const raw = env.get(key);
445
+ if (raw === void 0 || raw === "") return void 0;
446
+ return raw;
447
+ }
448
+ function firstPresentAlias(env, keys) {
449
+ for (const key of keys) {
450
+ const value = presentEnvValue(env, key);
451
+ if (value !== void 0) return value;
452
+ }
453
+ return void 0;
454
+ }
455
+ function readDefaultInstance(env) {
456
+ const raw = env.get("ADGUARD_DEFAULT_INSTANCE");
457
+ if (raw === void 0 || raw === "") return void 0;
458
+ return raw.toLowerCase();
459
+ }
460
+ function readRequiredInstanceField(env, key) {
461
+ const raw = env.get(key);
462
+ if (raw === void 0 || raw === "") {
463
+ throw new Error(`${key} is required`);
464
+ }
465
+ return raw;
466
+ }
467
+ function resolveInstances(env) {
468
+ const reader = fromProcessEnv(env);
469
+ const instances = {};
470
+ const candidateNames = /* @__PURE__ */ new Set();
471
+ const SUFFIX_RE = /^ADGUARD_([A-Z0-9_]+)_(URL|USERNAME|PASSWORD)$/;
472
+ for (const key of Object.keys(env)) {
473
+ const m = SUFFIX_RE.exec(key);
474
+ if (!m) continue;
475
+ if (m[1] === "SYNC") continue;
476
+ if (env[key] === void 0 || env[key] === "") continue;
477
+ candidateNames.add(m[1]);
478
+ }
479
+ for (const upperName of candidateNames) {
480
+ const name = upperName.toLowerCase();
481
+ const url = presentEnvValue(reader, `ADGUARD_${upperName}_URL`);
482
+ const username = presentEnvValue(reader, `ADGUARD_${upperName}_USERNAME`);
483
+ const password = presentEnvValue(reader, `ADGUARD_${upperName}_PASSWORD`);
484
+ const missing = [];
485
+ if (!url) missing.push("URL");
486
+ if (!username) missing.push("USERNAME");
487
+ if (!password) missing.push("PASSWORD");
488
+ if (missing.length > 0) {
489
+ throw new PartialInstanceConfigError(name, missing);
490
+ }
491
+ instances[name] = {
492
+ url: readRequiredInstanceField(reader, `ADGUARD_${upperName}_URL`),
493
+ username: readRequiredInstanceField(reader, `ADGUARD_${upperName}_USERNAME`),
494
+ password: readRequiredInstanceField(reader, `ADGUARD_${upperName}_PASSWORD`)
495
+ };
496
+ }
497
+ if (Object.keys(instances).length === 0) throw new NoInstancesError();
498
+ const explicitDefault = readDefaultInstance(reader);
499
+ if (explicitDefault) {
500
+ if (!instances[explicitDefault]) {
501
+ throw new UnknownDefaultInstanceError(explicitDefault, Object.keys(instances));
502
+ }
503
+ return { instances, defaultInstance: explicitDefault };
504
+ }
505
+ const defaultInstance = instances.primary ? "primary" : Object.keys(instances).sort()[0];
506
+ return { instances, defaultInstance };
507
+ }
508
+ function resolveSyncConfig(env) {
509
+ const reader = fromProcessEnv(env);
510
+ const url = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_URL", "ADGUARD_SYNC_URL"]);
511
+ const username = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_USERNAME", "ADGUARD_SYNC_USERNAME"]);
512
+ const password = firstPresentAlias(reader, ["ADGUARDHOME_SYNC_PASSWORD", "ADGUARD_SYNC_PASSWORD"]);
513
+ const missing = [];
514
+ if (!url && (username || password)) missing.push("URL");
515
+ if (username && !password) missing.push("PASSWORD");
516
+ if (password && !username) missing.push("USERNAME");
517
+ if (missing.length > 0) throw new PartialSyncConfigError(missing);
518
+ if (!url) return void 0;
519
+ return username && password ? { url, username, password } : { url };
520
+ }
521
+ function getInstanceConfig(cfg, name) {
522
+ const resolved = (name ?? cfg.defaultInstance).toLowerCase();
523
+ const inst = cfg.instances[resolved];
524
+ if (!inst) throw new UnknownInstanceError(resolved, Object.keys(cfg.instances));
525
+ return inst;
526
+ }
527
+ function getSyncConfig(cfg) {
528
+ if (!cfg) throw new NoSyncServerError();
529
+ return cfg;
530
+ }
531
+ function resolveRequestTimeoutMs(env) {
532
+ const reader = fromProcessEnv(env);
533
+ return Effect6.runSync(
534
+ parseTimeoutEnv(reader, "ADGUARD_REQUEST_TIMEOUT_MS", {
535
+ fallbackMs: DEFAULT_REQUEST_TIMEOUT_MS,
536
+ minMs: MIN_REQUEST_TIMEOUT_MS,
537
+ unit: "ms"
538
+ })
539
+ );
540
+ }
541
+ var DEFAULT_REQUEST_TIMEOUT_MS, MIN_REQUEST_TIMEOUT_MS, NoInstancesError, UnknownInstanceError, PartialInstanceConfigError, UnknownDefaultInstanceError, NoSyncServerError, PartialSyncConfigError;
542
+ var init_config = __esm({
543
+ "src/config.ts"() {
544
+ "use strict";
545
+ init_dist();
546
+ DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
547
+ MIN_REQUEST_TIMEOUT_MS = 1e3;
548
+ NoInstancesError = class extends Error {
549
+ constructor() {
550
+ super("No AdGuard instances configured. Set ADGUARD_<NAME>_URL/USERNAME/PASSWORD for at least one instance.");
551
+ this.name = "NoInstancesError";
552
+ }
553
+ };
554
+ UnknownInstanceError = class extends Error {
555
+ constructor(name, known) {
556
+ super(`Unknown AdGuard instance: ${name}. Known: ${known.join(", ") || "(none)"}.`);
557
+ this.name = "UnknownInstanceError";
558
+ }
559
+ };
560
+ PartialInstanceConfigError = class extends Error {
561
+ constructor(name, missing) {
562
+ super(
563
+ `Partial AdGuard instance config for '${name}': missing ${missing.join(", ")}. Set ADGUARD_${name.toUpperCase()}_URL, ADGUARD_${name.toUpperCase()}_USERNAME, and ADGUARD_${name.toUpperCase()}_PASSWORD together, or unset all three.`
564
+ );
565
+ this.name = "PartialInstanceConfigError";
566
+ }
567
+ };
568
+ UnknownDefaultInstanceError = class extends Error {
569
+ constructor(name, known) {
570
+ super(
571
+ `ADGUARD_DEFAULT_INSTANCE is set to '${name}', but no such instance is configured. Known: ${known.join(", ") || "(none)"}.`
572
+ );
573
+ this.name = "UnknownDefaultInstanceError";
574
+ }
575
+ };
576
+ NoSyncServerError = class extends Error {
577
+ constructor() {
578
+ super("No AdGuardHome Sync server configured. Set ADGUARDHOME_SYNC_URL or ADGUARD_SYNC_URL, and optionally matching USERNAME/PASSWORD.");
579
+ this.name = "NoSyncServerError";
580
+ }
581
+ };
582
+ PartialSyncConfigError = class extends Error {
583
+ constructor(missing) {
584
+ super(
585
+ `Partial AdGuardHome Sync config: missing ${missing.join(", ")}. Set ADGUARDHOME_SYNC_URL or ADGUARD_SYNC_URL, and set USERNAME/PASSWORD together when the Sync API uses auth.`
586
+ );
587
+ this.name = "PartialSyncConfigError";
588
+ }
589
+ };
590
+ }
591
+ });
592
+
593
+ // src/security.ts
594
+ import { createHash, timingSafeEqual } from "crypto";
595
+ function registerSecret(s) {
596
+ if (!s || s.length === 0) return;
597
+ SECRETS.add(s);
598
+ }
599
+ function maskBase64Tokens(input) {
600
+ return input.replace(BASE64_TOKEN, (match) => {
601
+ let decoded;
602
+ try {
603
+ decoded = Buffer.from(match, "base64").toString("utf8");
604
+ } catch {
605
+ return match;
606
+ }
607
+ for (const secret of SECRETS) {
608
+ if (decoded.includes(secret)) return "REDACTED";
609
+ }
610
+ return match;
611
+ });
612
+ }
613
+ function redact(value) {
614
+ if (typeof value === "string") {
615
+ let out = value;
616
+ for (const secret of SECRETS) out = out.split(secret).join("REDACTED");
617
+ out = maskBase64Tokens(out);
618
+ return out;
619
+ }
620
+ if (Array.isArray(value)) return value.map(redact);
621
+ if (value && typeof value === "object") {
622
+ const out = {};
623
+ for (const [k, v] of Object.entries(value)) out[k] = redact(v);
624
+ return out;
625
+ }
626
+ return value;
627
+ }
628
+ function equalSecret(a, b) {
629
+ return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
630
+ }
631
+ function registerHttpToken(value, configs) {
632
+ const token = (value ?? "").trim();
633
+ if (!token) throw new Error("ADGUARD_MCP_HTTP_TOKEN is required and must not be blank");
634
+ if (token.length < 32) throw new Error("ADGUARD_MCP_HTTP_TOKEN must be at least 32 characters (e.g. openssl rand -hex 32)");
635
+ const credentials = [];
636
+ for (const cfg of configs) {
637
+ const url = new URL(cfg.url);
638
+ for (const [username, password] of [
639
+ [cfg.username ?? "", cfg.password ?? ""],
640
+ [decodeURIComponent(url.username), decodeURIComponent(url.password)]
641
+ ]) {
642
+ credentials.push(username, password);
643
+ if (username || password) {
644
+ const pair = `${username}:${password}`;
645
+ const encoded = Buffer.from(pair).toString("base64");
646
+ credentials.push(pair, encoded, `Basic ${encoded}`);
647
+ }
648
+ }
649
+ }
650
+ if (credentials.some((credential) => credential && equalSecret(token, credential))) {
651
+ throw new Error("ADGUARD_MCP_HTTP_TOKEN must differ from all AdGuard Home and Sync credentials");
652
+ }
653
+ registerSecret(token);
654
+ return token;
655
+ }
656
+ var SECRETS, BASE64_TOKEN;
657
+ var init_security = __esm({
658
+ "src/security.ts"() {
659
+ "use strict";
660
+ SECRETS = /* @__PURE__ */ new Set();
661
+ BASE64_TOKEN = /[A-Za-z0-9+/]{12,}={0,2}/g;
662
+ }
663
+ });
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
+
1020
+ // src/tools/_util.ts
1021
+ import { Type } from "@sinclair/typebox";
1022
+ function jsonToolResult(payload) {
1023
+ const kitResult = ok(payload);
1024
+ return {
1025
+ content: kitResult.content
1026
+ };
1027
+ }
1028
+ function hhmmToMs(value) {
1029
+ if (typeof value === "number") {
1030
+ if (!Number.isFinite(value)) throw new Error(`schedule time must be HH:MM or milliseconds, got: ${String(value)}`);
1031
+ return value;
1032
+ }
1033
+ if (typeof value !== "string") {
1034
+ throw new Error(`schedule time must be HH:MM string or milliseconds number, got: ${typeof value}`);
1035
+ }
1036
+ const m = /^(\d{1,2}):(\d{2})$/.exec(value);
1037
+ if (!m) throw new Error(`schedule time must be HH:MM or milliseconds, got: ${value}`);
1038
+ const h = Number(m[1]);
1039
+ const mm = Number(m[2]);
1040
+ if (mm > 59) throw new Error(`invalid HH:MM (minutes > 59): ${value}`);
1041
+ if (h > 24 || h === 24 && mm > 0) throw new Error(`invalid HH:MM (max 24:00): ${value}`);
1042
+ return (h * 60 + mm) * 60 * 1e3;
1043
+ }
1044
+ var InstanceArg;
1045
+ var init_util = __esm({
1046
+ "src/tools/_util.ts"() {
1047
+ "use strict";
1048
+ init_dist();
1049
+ init_config();
1050
+ InstanceArg = Type.Optional(Type.String({
1051
+ description: "Named instance to target (e.g. 'primary', 'secondary'). Default: the configured default instance."
1052
+ }));
1053
+ }
1054
+ });
1055
+
1056
+ // src/tools/adguard_status.ts
1057
+ import { Type as Type2 } from "@sinclair/typebox";
1058
+ function createAdguardStatusTool(getClient) {
1059
+ return {
1060
+ name: "adguard_status",
1061
+ label: "adguard: status",
1062
+ description: "Get the AdGuard Home server status (version, protection-enabled state, DNS port, running flag) via GET /control/status.",
1063
+ parameters: Schema,
1064
+ execute: async (_id, raw) => {
1065
+ const args = raw;
1066
+ const client = getClient(args.instance);
1067
+ const status = await client.get("/control/status");
1068
+ return jsonToolResult(status);
1069
+ }
1070
+ };
1071
+ }
1072
+ var Schema;
1073
+ var init_adguard_status = __esm({
1074
+ "src/tools/adguard_status.ts"() {
1075
+ "use strict";
1076
+ init_util();
1077
+ Schema = Type2.Object({ instance: InstanceArg }, { additionalProperties: false });
1078
+ }
1079
+ });
1080
+
1081
+ // src/tools/adguard_stats.ts
1082
+ import { Type as Type3 } from "@sinclair/typebox";
1083
+ function createAdguardStatsTool(getClient) {
1084
+ return {
1085
+ name: "adguard_stats",
1086
+ label: "adguard: stats",
1087
+ description: "Get 24h DNS query statistics (totals, blocked %, top blocked domains, top clients) via GET /control/stats.",
1088
+ parameters: Schema2,
1089
+ execute: async (_id, raw) => {
1090
+ const args = raw;
1091
+ const client = getClient(args.instance);
1092
+ const stats = await client.get("/control/stats");
1093
+ return jsonToolResult(stats);
1094
+ }
1095
+ };
1096
+ }
1097
+ var Schema2;
1098
+ var init_adguard_stats = __esm({
1099
+ "src/tools/adguard_stats.ts"() {
1100
+ "use strict";
1101
+ init_util();
1102
+ Schema2 = Type3.Object({ instance: InstanceArg }, { additionalProperties: false });
1103
+ }
1104
+ });
1105
+
1106
+ // src/tools/adguard_query_log.ts
1107
+ import { Type as Type4 } from "@sinclair/typebox";
1108
+ function createAdguardQueryLogTool(getClient) {
1109
+ return {
1110
+ name: "adguard_query_log",
1111
+ label: "adguard: query log",
1112
+ description: "Read recent DNS queries via GET /control/querylog. Filter by client, domain, blocked-only, or specific FilteringReason values. client + domain are combined into AGH's single `search` param when both passed.",
1113
+ parameters: Schema3,
1114
+ execute: async (_id, raw) => {
1115
+ const args = raw;
1116
+ const params = new URLSearchParams();
1117
+ params.set("limit", String(args.limit ?? 50));
1118
+ const reasons = args.reasons && args.reasons.length > 0 ? args.reasons : args.blocked_only ? BLOCKED_REASONS : [];
1119
+ for (const reason of reasons) params.append("reason", reason);
1120
+ const searchTerms = [];
1121
+ if (args.client) searchTerms.push(args.client);
1122
+ if (args.domain) searchTerms.push(args.domain);
1123
+ if (searchTerms.length > 0) params.set("search", searchTerms.join(" "));
1124
+ const client = getClient(args.instance);
1125
+ const log = await client.get(`/control/querylog?${params.toString()}`);
1126
+ return jsonToolResult(log);
1127
+ }
1128
+ };
1129
+ }
1130
+ var Schema3, BLOCKED_REASONS;
1131
+ var init_adguard_query_log = __esm({
1132
+ "src/tools/adguard_query_log.ts"() {
1133
+ "use strict";
1134
+ init_util();
1135
+ Schema3 = Type4.Object({
1136
+ instance: InstanceArg,
1137
+ limit: Type4.Optional(Type4.Integer({ minimum: 1, maximum: 500, description: "Max entries to return. Default 50." })),
1138
+ client: Type4.Optional(Type4.String({ description: "Filter by client IP or hostname. AGH's querylog supports a single free-text `search` parameter; client/domain are combined (space-joined) when both passed." })),
1139
+ domain: Type4.Optional(Type4.String({ description: "Filter by domain. AGH's querylog supports a single free-text `search` parameter; client/domain are combined (space-joined) when both passed." })),
1140
+ blocked_only: Type4.Optional(Type4.Boolean({ description: "When true, only return blocked queries using AGH's modern `reason` filter." })),
1141
+ reasons: Type4.Optional(Type4.Array(Type4.Union([
1142
+ Type4.Literal("NotFilteredNotFound"),
1143
+ Type4.Literal("NotFilteredWhiteList"),
1144
+ Type4.Literal("NotFilteredError"),
1145
+ Type4.Literal("FilteredBlackList"),
1146
+ Type4.Literal("FilteredSafeBrowsing"),
1147
+ Type4.Literal("FilteredParental"),
1148
+ Type4.Literal("FilteredInvalid"),
1149
+ Type4.Literal("FilteredSafeSearch"),
1150
+ Type4.Literal("FilteredBlockedService"),
1151
+ Type4.Literal("Rewrite"),
1152
+ Type4.Literal("RewriteEtcHosts"),
1153
+ Type4.Literal("RewriteRule")
1154
+ ]), { description: "Filter by one or more AGH FilteringReason values. Takes precedence over blocked_only." }))
1155
+ }, { additionalProperties: false });
1156
+ BLOCKED_REASONS = [
1157
+ "FilteredBlackList",
1158
+ "FilteredSafeBrowsing",
1159
+ "FilteredParental",
1160
+ "FilteredInvalid",
1161
+ "FilteredSafeSearch",
1162
+ "FilteredBlockedService"
1163
+ ];
1164
+ }
1165
+ });
1166
+
1167
+ // src/tools/adguard_list_filter_lists.ts
1168
+ import { Type as Type5 } from "@sinclair/typebox";
1169
+ function createAdguardListFilterListsTool(getClient) {
1170
+ return {
1171
+ name: "adguard_list_filter_lists",
1172
+ label: "adguard: list filter lists",
1173
+ description: "List subscribed filter lists with enabled state and rule counts via GET /control/filtering/status.",
1174
+ parameters: Schema4,
1175
+ execute: async (_id, raw) => {
1176
+ const args = raw;
1177
+ const client = getClient(args.instance);
1178
+ const status = await client.get("/control/filtering/status");
1179
+ return jsonToolResult(status);
1180
+ }
1181
+ };
1182
+ }
1183
+ var Schema4;
1184
+ var init_adguard_list_filter_lists = __esm({
1185
+ "src/tools/adguard_list_filter_lists.ts"() {
1186
+ "use strict";
1187
+ init_util();
1188
+ Schema4 = Type5.Object({ instance: InstanceArg }, { additionalProperties: false });
1189
+ }
1190
+ });
1191
+
1192
+ // src/tools/adguard_list_user_rules.ts
1193
+ import { Type as Type6 } from "@sinclair/typebox";
1194
+ function createAdguardListUserRulesTool(getClient) {
1195
+ return {
1196
+ name: "adguard_list_user_rules",
1197
+ label: "adguard: list user rules",
1198
+ description: "List the custom user-rules block (lines like '@@||t.co^' or '||badsite.com^') via GET /control/filtering/status, returning just the rules array.",
1199
+ parameters: Schema5,
1200
+ execute: async (_id, raw) => {
1201
+ const args = raw;
1202
+ const client = getClient(args.instance);
1203
+ const status = await client.get("/control/filtering/status");
1204
+ return jsonToolResult({ rules: status.user_rules ?? [] });
1205
+ }
1206
+ };
1207
+ }
1208
+ var Schema5;
1209
+ var init_adguard_list_user_rules = __esm({
1210
+ "src/tools/adguard_list_user_rules.ts"() {
1211
+ "use strict";
1212
+ init_util();
1213
+ Schema5 = Type6.Object({ instance: InstanceArg }, { additionalProperties: false });
1214
+ }
1215
+ });
1216
+
1217
+ // src/tools/adguard_list_clients.ts
1218
+ import { Type as Type7 } from "@sinclair/typebox";
1219
+ function createAdguardListClientsTool(getClient) {
1220
+ return {
1221
+ name: "adguard_list_clients",
1222
+ label: "adguard: list clients",
1223
+ description: "List configured clients with their per-client blocked services and tags via GET /control/clients.",
1224
+ parameters: Schema6,
1225
+ execute: async (_id, raw) => {
1226
+ const args = raw;
1227
+ const client = getClient(args.instance);
1228
+ const out = await client.get("/control/clients");
1229
+ return jsonToolResult(out);
1230
+ }
1231
+ };
1232
+ }
1233
+ var Schema6;
1234
+ var init_adguard_list_clients = __esm({
1235
+ "src/tools/adguard_list_clients.ts"() {
1236
+ "use strict";
1237
+ init_util();
1238
+ Schema6 = Type7.Object({ instance: InstanceArg }, { additionalProperties: false });
1239
+ }
1240
+ });
1241
+
1242
+ // src/tools/adguard_list_blocked_services_catalog.ts
1243
+ import { Type as Type8 } from "@sinclair/typebox";
1244
+ function createAdguardListBlockedServicesCatalogTool(getClient) {
1245
+ return {
1246
+ name: "adguard_list_blocked_services_catalog",
1247
+ label: "adguard: blocked services catalog",
1248
+ description: "List the services AdGuard Home can block per-client (youtube, tiktok, instagram, etc) via GET /control/blocked_services/all.",
1249
+ parameters: Schema7,
1250
+ execute: async (_id, raw) => {
1251
+ const args = raw;
1252
+ const client = getClient(args.instance);
1253
+ const catalog = await client.get("/control/blocked_services/all");
1254
+ return jsonToolResult(catalog);
1255
+ }
1256
+ };
1257
+ }
1258
+ var Schema7;
1259
+ var init_adguard_list_blocked_services_catalog = __esm({
1260
+ "src/tools/adguard_list_blocked_services_catalog.ts"() {
1261
+ "use strict";
1262
+ init_util();
1263
+ Schema7 = Type8.Object({ instance: InstanceArg }, { additionalProperties: false });
1264
+ }
1265
+ });
1266
+
1267
+ // src/gates.ts
1268
+ function throwGateRefusal(message) {
1269
+ const kitResult = fail(message);
1270
+ let extracted = message;
1271
+ try {
1272
+ const parsed = JSON.parse(kitResult.content[0]?.text ?? "");
1273
+ if (typeof parsed.error === "string") extracted = parsed.error;
1274
+ } catch {
1275
+ }
1276
+ throw new WriteGateError(extracted);
1277
+ }
1278
+ function assertConfirmedWrite(args, toolName) {
1279
+ if (args.confirm !== true) {
1280
+ void refuseUnconfirmed(toolName);
1281
+ throwGateRefusal(
1282
+ `${toolName} is a write operation. Pass {"confirm": true} to proceed.`
1283
+ );
1284
+ }
1285
+ }
1286
+ function assertDestructive(args, toolName) {
1287
+ if (args.confirm !== true || args.destructive !== true) {
1288
+ void refuseUnconfirmed(toolName);
1289
+ throwGateRefusal(
1290
+ `${toolName} is a destructive operation. Pass {"confirm": true, "destructive": true} to proceed.`
1291
+ );
1292
+ }
1293
+ }
1294
+ var WriteGateError;
1295
+ var init_gates = __esm({
1296
+ "src/gates.ts"() {
1297
+ "use strict";
1298
+ init_dist();
1299
+ WriteGateError = class extends Error {
1300
+ constructor(message) {
1301
+ super(message);
1302
+ this.name = "WriteGateError";
1303
+ }
1304
+ };
1305
+ }
1306
+ });
1307
+
1308
+ // src/tools/adguard_add_user_rule.ts
1309
+ import { Type as Type9 } from "@sinclair/typebox";
1310
+ function createAdguardAddUserRuleTool(getClient) {
1311
+ return {
1312
+ name: NAME,
1313
+ label: "adguard: add user rule",
1314
+ description: "Append a custom rule to the AdGuard user-rules block. Tier-2 write; requires confirm:true.",
1315
+ parameters: Schema8,
1316
+ execute: async (_id, raw) => {
1317
+ assertConfirmedWrite(raw, NAME);
1318
+ const args = raw;
1319
+ const client = getClient(args.instance);
1320
+ const status = await client.get("/control/filtering/status");
1321
+ const existing = status.user_rules ?? [];
1322
+ if (existing.includes(args.rule)) {
1323
+ return jsonToolResult({ added: null, already_present: true, rules_count: existing.length });
1324
+ }
1325
+ const next = [...existing, args.rule];
1326
+ await client.post("/control/filtering/set_rules", { rules: next });
1327
+ return jsonToolResult({ added: args.rule, already_present: false, rules_count: next.length });
1328
+ }
1329
+ };
1330
+ }
1331
+ var Schema8, NAME;
1332
+ var init_adguard_add_user_rule = __esm({
1333
+ "src/tools/adguard_add_user_rule.ts"() {
1334
+ "use strict";
1335
+ init_util();
1336
+ init_gates();
1337
+ Schema8 = Type9.Object({
1338
+ instance: InstanceArg,
1339
+ rule: Type9.String({ description: "AdGuard rule line, e.g. '@@||t.co^' or '||badsite.com^'." }),
1340
+ confirm: Type9.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
1341
+ }, { additionalProperties: false });
1342
+ NAME = "adguard_add_user_rule";
1343
+ }
1344
+ });
1345
+
1346
+ // src/tools/adguard_remove_user_rule.ts
1347
+ import { Type as Type10 } from "@sinclair/typebox";
1348
+ function createAdguardRemoveUserRuleTool(getClient) {
1349
+ return {
1350
+ name: NAME2,
1351
+ label: "adguard: remove user rule",
1352
+ description: "Remove an exact-match rule from the AdGuard user-rules block. Tier-2 write; requires confirm:true.",
1353
+ parameters: Schema9,
1354
+ execute: async (_id, raw) => {
1355
+ assertConfirmedWrite(raw, NAME2);
1356
+ const args = raw;
1357
+ const client = getClient(args.instance);
1358
+ const status = await client.get("/control/filtering/status");
1359
+ const existing = status.user_rules ?? [];
1360
+ if (!existing.includes(args.rule)) {
1361
+ return jsonToolResult({ removed: null, not_found: true, rules_count: existing.length });
1362
+ }
1363
+ const next = existing.filter((r) => r !== args.rule);
1364
+ await client.post("/control/filtering/set_rules", { rules: next });
1365
+ return jsonToolResult({ removed: args.rule, not_found: false, rules_count: next.length });
1366
+ }
1367
+ };
1368
+ }
1369
+ var Schema9, NAME2;
1370
+ var init_adguard_remove_user_rule = __esm({
1371
+ "src/tools/adguard_remove_user_rule.ts"() {
1372
+ "use strict";
1373
+ init_util();
1374
+ init_gates();
1375
+ Schema9 = Type10.Object({
1376
+ instance: InstanceArg,
1377
+ rule: Type10.String({ description: "Exact-match rule line to remove from user_rules." }),
1378
+ confirm: Type10.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
1379
+ }, { additionalProperties: false });
1380
+ NAME2 = "adguard_remove_user_rule";
1381
+ }
1382
+ });
1383
+
1384
+ // src/tools/adguard_add_filter_list.ts
1385
+ import { Type as Type11 } from "@sinclair/typebox";
1386
+ function createAdguardAddFilterListTool(getClient) {
1387
+ return {
1388
+ name: NAME3,
1389
+ label: "adguard: add filter list",
1390
+ description: "Subscribe to a new filter list URL via POST /control/filtering/add_url. Tier-2 write; requires confirm:true.",
1391
+ parameters: Schema10,
1392
+ execute: async (_id, raw) => {
1393
+ assertConfirmedWrite(raw, NAME3);
1394
+ const args = raw;
1395
+ const client = getClient(args.instance);
1396
+ await client.post("/control/filtering/add_url", { name: args.name, url: args.url, whitelist: args.whitelist ?? false });
1397
+ return jsonToolResult({ added: { name: args.name, url: args.url } });
1398
+ }
1399
+ };
1400
+ }
1401
+ var Schema10, NAME3;
1402
+ var init_adguard_add_filter_list = __esm({
1403
+ "src/tools/adguard_add_filter_list.ts"() {
1404
+ "use strict";
1405
+ init_util();
1406
+ init_gates();
1407
+ Schema10 = Type11.Object({
1408
+ instance: InstanceArg,
1409
+ name: Type11.String({ description: "Display name for the list." }),
1410
+ url: Type11.String({ description: "URL of the filter list to subscribe." }),
1411
+ whitelist: Type11.Optional(Type11.Boolean({ description: "When true, treat as an allowlist (default false)." })),
1412
+ confirm: Type11.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
1413
+ }, { additionalProperties: false });
1414
+ NAME3 = "adguard_add_filter_list";
1415
+ }
1416
+ });
1417
+
1418
+ // src/tools/adguard_remove_filter_list.ts
1419
+ import { Type as Type12 } from "@sinclair/typebox";
1420
+ function createAdguardRemoveFilterListTool(getClient) {
1421
+ return {
1422
+ name: NAME4,
1423
+ label: "adguard: remove filter list",
1424
+ description: "Unsubscribe a filter list by URL via POST /control/filtering/remove_url. Tier-2 write; requires confirm:true.",
1425
+ parameters: Schema11,
1426
+ execute: async (_id, raw) => {
1427
+ assertConfirmedWrite(raw, NAME4);
1428
+ const args = raw;
1429
+ const client = getClient(args.instance);
1430
+ await client.post("/control/filtering/remove_url", { url: args.url, whitelist: args.whitelist ?? false });
1431
+ return jsonToolResult({ removed: args.url });
1432
+ }
1433
+ };
1434
+ }
1435
+ var Schema11, NAME4;
1436
+ var init_adguard_remove_filter_list = __esm({
1437
+ "src/tools/adguard_remove_filter_list.ts"() {
1438
+ "use strict";
1439
+ init_util();
1440
+ init_gates();
1441
+ Schema11 = Type12.Object({
1442
+ instance: InstanceArg,
1443
+ url: Type12.String({ description: "URL of the filter list to unsubscribe." }),
1444
+ whitelist: Type12.Optional(Type12.Boolean({ description: "When true, target the allowlist set (default false)." })),
1445
+ confirm: Type12.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
1446
+ }, { additionalProperties: false });
1447
+ NAME4 = "adguard_remove_filter_list";
1448
+ }
1449
+ });
1450
+
1451
+ // src/tools/adguard_toggle_filter_list.ts
1452
+ import { Type as Type13 } from "@sinclair/typebox";
1453
+ function createAdguardToggleFilterListTool(getClient) {
1454
+ return {
1455
+ name: NAME5,
1456
+ label: "adguard: toggle filter list",
1457
+ description: "Enable or disable a subscribed filter list by URL via POST /control/filtering/set_url. Tier-2 write; requires confirm:true.",
1458
+ parameters: Schema12,
1459
+ execute: async (_id, raw) => {
1460
+ assertConfirmedWrite(raw, NAME5);
1461
+ const args = raw;
1462
+ const client = getClient(args.instance);
1463
+ await client.post("/control/filtering/set_url", { url: args.url, whitelist: args.whitelist ?? false, data: { enabled: args.enabled } });
1464
+ return jsonToolResult({ url: args.url, enabled: args.enabled });
1465
+ }
1466
+ };
1467
+ }
1468
+ var Schema12, NAME5;
1469
+ var init_adguard_toggle_filter_list = __esm({
1470
+ "src/tools/adguard_toggle_filter_list.ts"() {
1471
+ "use strict";
1472
+ init_util();
1473
+ init_gates();
1474
+ Schema12 = Type13.Object({
1475
+ instance: InstanceArg,
1476
+ url: Type13.String({ description: "URL of the filter list to enable/disable." }),
1477
+ enabled: Type13.Boolean({ description: "Target enabled state." }),
1478
+ whitelist: Type13.Optional(Type13.Boolean({ description: "When true, target the allowlist set (default false)." })),
1479
+ confirm: Type13.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
1480
+ }, { additionalProperties: false });
1481
+ NAME5 = "adguard_toggle_filter_list";
1482
+ }
1483
+ });
1484
+
1485
+ // src/tools/adguard_set_client_blocked_services.ts
1486
+ import { Type as Type14 } from "@sinclair/typebox";
1487
+ function createAdguardSetClientBlockedServicesTool(getClient) {
1488
+ return {
1489
+ name: NAME6,
1490
+ label: "adguard: set client blocked services",
1491
+ description: "Set the per-client blocked-services list for a named client via POST /control/clients/update. Tier-2 write; requires confirm:true.",
1492
+ parameters: Schema13,
1493
+ execute: async (_id, raw) => {
1494
+ assertConfirmedWrite(raw, NAME6);
1495
+ const args = raw;
1496
+ const client = getClient(args.instance);
1497
+ const clients = await client.get("/control/clients");
1498
+ const existing = (clients.clients ?? []).find((c) => c.name === args.name);
1499
+ if (!existing) return jsonToolResult({ client: args.name, not_found: true });
1500
+ const updated = { ...existing, blocked_services: args.services };
1501
+ await client.post("/control/clients/update", { name: args.name, data: updated });
1502
+ return jsonToolResult({ client: args.name, not_found: false, blocked_services: args.services });
1503
+ }
1504
+ };
1505
+ }
1506
+ var Schema13, NAME6;
1507
+ var init_adguard_set_client_blocked_services = __esm({
1508
+ "src/tools/adguard_set_client_blocked_services.ts"() {
1509
+ "use strict";
1510
+ init_util();
1511
+ init_gates();
1512
+ Schema13 = Type14.Object({
1513
+ instance: InstanceArg,
1514
+ name: Type14.String({ description: "Client name as configured in AdGuard." }),
1515
+ services: Type14.Array(Type14.String(), { description: "Service ids to block (e.g. ['youtube','tiktok']). Empty array clears." }),
1516
+ confirm: Type14.Boolean({ description: "Must be true to write. Tier-2 safe-write gate." })
1517
+ }, { additionalProperties: false });
1518
+ NAME6 = "adguard_set_client_blocked_services";
1519
+ }
1520
+ });
1521
+
1522
+ // src/tools/adguard_replace_user_rules.ts
1523
+ import { Type as Type15 } from "@sinclair/typebox";
1524
+ function createAdguardReplaceUserRulesTool(getClient) {
1525
+ return {
1526
+ name: NAME7,
1527
+ label: "adguard: replace user rules",
1528
+ description: "Overwrite the entire user-rules block via POST /control/filtering/set_rules. Destroys any rule not in the new set. Tier-3 destructive; requires confirm:true and destructive:true.",
1529
+ parameters: Schema14,
1530
+ execute: async (_id, raw) => {
1531
+ assertDestructive(raw, NAME7);
1532
+ const args = raw;
1533
+ const client = getClient(args.instance);
1534
+ await client.post("/control/filtering/set_rules", { rules: args.rules });
1535
+ return jsonToolResult({ rules_count: args.rules.length });
1536
+ }
1537
+ };
1538
+ }
1539
+ var Schema14, NAME7;
1540
+ var init_adguard_replace_user_rules = __esm({
1541
+ "src/tools/adguard_replace_user_rules.ts"() {
1542
+ "use strict";
1543
+ init_util();
1544
+ init_gates();
1545
+ Schema14 = Type15.Object({
1546
+ instance: InstanceArg,
1547
+ rules: Type15.Array(Type15.String(), { description: "Complete replacement set of user rules. Overwrites the existing block." }),
1548
+ confirm: Type15.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
1549
+ destructive: Type15.Boolean({ description: "Must be true. Tier-3 destructive gate (overwrites existing rules)." })
1550
+ }, { additionalProperties: false });
1551
+ NAME7 = "adguard_replace_user_rules";
1552
+ }
1553
+ });
1554
+
1555
+ // src/tools/adguard_toggle_protection.ts
1556
+ import { Type as Type16 } from "@sinclair/typebox";
1557
+ function createAdguardToggleProtectionTool(getClient) {
1558
+ return {
1559
+ name: NAME8,
1560
+ label: "adguard: toggle protection",
1561
+ description: "Enable or disable global AdGuard filtering via POST /control/protection. Tier-3 destructive (disabling stops ALL blocking); requires confirm:true and destructive:true.",
1562
+ parameters: Schema15,
1563
+ execute: async (_id, raw) => {
1564
+ assertDestructive(raw, NAME8);
1565
+ const args = raw;
1566
+ const client = getClient(args.instance);
1567
+ await client.post("/control/protection", { enabled: args.enabled });
1568
+ return jsonToolResult({ enabled: args.enabled });
1569
+ }
1570
+ };
1571
+ }
1572
+ var Schema15, NAME8;
1573
+ var init_adguard_toggle_protection = __esm({
1574
+ "src/tools/adguard_toggle_protection.ts"() {
1575
+ "use strict";
1576
+ init_util();
1577
+ init_gates();
1578
+ Schema15 = Type16.Object({
1579
+ instance: InstanceArg,
1580
+ enabled: Type16.Boolean({ description: "Target global filtering state (false disables ALL blocking on this instance)." }),
1581
+ confirm: Type16.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
1582
+ destructive: Type16.Boolean({ description: "Must be true. Tier-3 destructive gate (toggling off removes all blocking)." })
1583
+ }, { additionalProperties: false });
1584
+ NAME8 = "adguard_toggle_protection";
1585
+ }
1586
+ });
1587
+
1588
+ // src/tools/adguard_check_host.ts
1589
+ import { Type as Type17 } from "@sinclair/typebox";
1590
+ function createAdguardCheckHostTool(getClient) {
1591
+ return {
1592
+ name: NAME9,
1593
+ label: "adguard: check host",
1594
+ description: "Test what AGH would do with a hostname via GET /control/filtering/check_host. Returns the filter decision, matched rules, CNAME chain, and IPs.",
1595
+ parameters: Schema16,
1596
+ execute: async (_id, raw) => {
1597
+ const args = raw;
1598
+ const client = getClient(args.instance);
1599
+ const params = new URLSearchParams({ name: args.host });
1600
+ if (args.client) params.set("client", args.client);
1601
+ if (args.qtype) params.set("qtype", args.qtype);
1602
+ const result = await client.get(`/control/filtering/check_host?${params.toString()}`);
1603
+ return jsonToolResult(result);
1604
+ }
1605
+ };
1606
+ }
1607
+ var Schema16, NAME9;
1608
+ var init_adguard_check_host = __esm({
1609
+ "src/tools/adguard_check_host.ts"() {
1610
+ "use strict";
1611
+ init_util();
1612
+ Schema16 = Type17.Object({
1613
+ instance: InstanceArg,
1614
+ host: Type17.String({ description: "Hostname to test (e.g. 'youtube.com'). The lookup runs through AGH's filter pipeline as if the client queried it." }),
1615
+ client: Type17.Optional(Type17.String({ description: "Optional client IP/ClientID/name to simulate the lookup against (per-client rules differ)." })),
1616
+ qtype: Type17.Optional(Type17.String({ description: "DNS query type (A, AAAA, HTTPS, MX...). Default: server-side default (A)." }))
1617
+ }, { additionalProperties: false });
1618
+ NAME9 = "adguard_check_host";
1619
+ }
1620
+ });
1621
+
1622
+ // src/tools/adguard_get_blocked_services.ts
1623
+ import { Type as Type18 } from "@sinclair/typebox";
1624
+ function createAdguardGetBlockedServicesTool(getClient) {
1625
+ return {
1626
+ name: NAME10,
1627
+ label: "adguard: get blocked services",
1628
+ description: "Get the GLOBAL blocked-services list and weekly schedule via GET /control/blocked_services/get. Schedule day ranges are milliseconds-from-midnight.",
1629
+ parameters: Schema17,
1630
+ execute: async (_id, raw) => {
1631
+ const args = raw;
1632
+ const client = getClient(args.instance);
1633
+ const result = await client.get("/control/blocked_services/get");
1634
+ return jsonToolResult(result);
1635
+ }
1636
+ };
1637
+ }
1638
+ var Schema17, NAME10;
1639
+ var init_adguard_get_blocked_services = __esm({
1640
+ "src/tools/adguard_get_blocked_services.ts"() {
1641
+ "use strict";
1642
+ init_util();
1643
+ Schema17 = Type18.Object({ instance: InstanceArg }, { additionalProperties: false });
1644
+ NAME10 = "adguard_get_blocked_services";
1645
+ }
1646
+ });
1647
+
1648
+ // src/tools/adguard_get_dns_config.ts
1649
+ import { Type as Type19 } from "@sinclair/typebox";
1650
+ function createAdguardGetDnsConfigTool(getClient) {
1651
+ return {
1652
+ name: NAME11,
1653
+ label: "adguard: get DNS config",
1654
+ description: "Get the DNS server config via GET /control/dns_info (upstreams, bootstrap, cache, parallel resolution, blocking mode, etc).",
1655
+ parameters: Schema18,
1656
+ execute: async (_id, raw) => {
1657
+ const args = raw;
1658
+ const client = getClient(args.instance);
1659
+ const result = await client.get("/control/dns_info");
1660
+ return jsonToolResult(result);
1661
+ }
1662
+ };
1663
+ }
1664
+ var Schema18, NAME11;
1665
+ var init_adguard_get_dns_config = __esm({
1666
+ "src/tools/adguard_get_dns_config.ts"() {
1667
+ "use strict";
1668
+ init_util();
1669
+ Schema18 = Type19.Object({ instance: InstanceArg }, { additionalProperties: false });
1670
+ NAME11 = "adguard_get_dns_config";
1671
+ }
1672
+ });
1673
+
1674
+ // src/tools/adguard_get_safesearch_settings.ts
1675
+ import { Type as Type20 } from "@sinclair/typebox";
1676
+ function createAdguardGetSafesearchSettingsTool(getClient) {
1677
+ return {
1678
+ name: NAME12,
1679
+ label: "adguard: get safesearch settings",
1680
+ description: "Get SafeSearch enabled state + per-engine flags via GET /control/safesearch/status.",
1681
+ parameters: Schema19,
1682
+ execute: async (_id, raw) => {
1683
+ const args = raw;
1684
+ const client = getClient(args.instance);
1685
+ const result = await client.get("/control/safesearch/status");
1686
+ return jsonToolResult(result);
1687
+ }
1688
+ };
1689
+ }
1690
+ var Schema19, NAME12;
1691
+ var init_adguard_get_safesearch_settings = __esm({
1692
+ "src/tools/adguard_get_safesearch_settings.ts"() {
1693
+ "use strict";
1694
+ init_util();
1695
+ Schema19 = Type20.Object({ instance: InstanceArg }, { additionalProperties: false });
1696
+ NAME12 = "adguard_get_safesearch_settings";
1697
+ }
1698
+ });
1699
+
1700
+ // src/tools/adguard_refresh_filter_lists.ts
1701
+ import { Type as Type21 } from "@sinclair/typebox";
1702
+ function createAdguardRefreshFilterListsTool(getClient) {
1703
+ return {
1704
+ name: NAME13,
1705
+ label: "adguard: refresh filter lists",
1706
+ description: "Force refresh subscribed filter lists immediately via POST /control/filtering/refresh. Returns the number of lists updated. Tier-2 write; requires confirm:true.",
1707
+ parameters: Schema20,
1708
+ execute: async (_id, raw) => {
1709
+ assertConfirmedWrite(raw, NAME13);
1710
+ const args = raw;
1711
+ const client = getClient(args.instance);
1712
+ const result = await client.post("/control/filtering/refresh", { whitelist: args.whitelist === true });
1713
+ return jsonToolResult(result);
1714
+ }
1715
+ };
1716
+ }
1717
+ var Schema20, NAME13;
1718
+ var init_adguard_refresh_filter_lists = __esm({
1719
+ "src/tools/adguard_refresh_filter_lists.ts"() {
1720
+ "use strict";
1721
+ init_util();
1722
+ init_gates();
1723
+ Schema20 = Type21.Object({
1724
+ instance: InstanceArg,
1725
+ whitelist: Type21.Optional(Type21.Boolean({ description: "Refresh allowlist lists instead of blocklist lists. Default: false (refresh blocklists)." })),
1726
+ confirm: Type21.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
1727
+ }, { additionalProperties: false });
1728
+ NAME13 = "adguard_refresh_filter_lists";
1729
+ }
1730
+ });
1731
+
1732
+ // src/tools/adguard_add_client.ts
1733
+ import { Type as Type22 } from "@sinclair/typebox";
1734
+ function createAdguardAddClientTool(getClient) {
1735
+ return {
1736
+ name: NAME14,
1737
+ label: "adguard: add client",
1738
+ description: "Register a new named client via POST /control/clients/add. Tier-2 write; requires confirm:true.",
1739
+ parameters: Schema21,
1740
+ execute: async (_id, raw) => {
1741
+ assertConfirmedWrite(raw, NAME14);
1742
+ const body = {};
1743
+ for (const k of CLIENT_BODY_FIELDS) {
1744
+ if (raw[k] !== void 0) body[k] = raw[k];
1745
+ }
1746
+ const client = getClient(raw.instance);
1747
+ await client.post("/control/clients/add", body);
1748
+ return jsonToolResult({ added: true, name: body.name });
1749
+ }
1750
+ };
1751
+ }
1752
+ var SafeSearchSchema, Schema21, NAME14, CLIENT_BODY_FIELDS;
1753
+ var init_adguard_add_client = __esm({
1754
+ "src/tools/adguard_add_client.ts"() {
1755
+ "use strict";
1756
+ init_util();
1757
+ init_gates();
1758
+ SafeSearchSchema = Type22.Optional(Type22.Object({
1759
+ enabled: Type22.Optional(Type22.Boolean()),
1760
+ bing: Type22.Optional(Type22.Boolean()),
1761
+ duckduckgo: Type22.Optional(Type22.Boolean()),
1762
+ ecosia: Type22.Optional(Type22.Boolean()),
1763
+ google: Type22.Optional(Type22.Boolean()),
1764
+ pixabay: Type22.Optional(Type22.Boolean()),
1765
+ yandex: Type22.Optional(Type22.Boolean()),
1766
+ youtube: Type22.Optional(Type22.Boolean())
1767
+ }, { additionalProperties: false }));
1768
+ Schema21 = Type22.Object({
1769
+ instance: InstanceArg,
1770
+ name: Type22.String({ description: "Client display name (must be unique on this instance)." }),
1771
+ ids: Type22.Array(Type22.String(), { minItems: 1, description: "Identifier(s) for this client: IP, MAC, ClientID, or CIDR. At least one required." }),
1772
+ use_global_settings: Type22.Optional(Type22.Boolean()),
1773
+ filtering_enabled: Type22.Optional(Type22.Boolean()),
1774
+ safebrowsing_enabled: Type22.Optional(Type22.Boolean()),
1775
+ parental_enabled: Type22.Optional(Type22.Boolean()),
1776
+ safe_search: SafeSearchSchema,
1777
+ use_global_blocked_services: Type22.Optional(Type22.Boolean()),
1778
+ blocked_services: Type22.Optional(Type22.Array(Type22.String())),
1779
+ blocked_services_schedule: Type22.Optional(Type22.Object({}, { additionalProperties: true })),
1780
+ upstreams: Type22.Optional(Type22.Array(Type22.String())),
1781
+ tags: Type22.Optional(Type22.Array(Type22.String())),
1782
+ ignore_querylog: Type22.Optional(Type22.Boolean()),
1783
+ ignore_statistics: Type22.Optional(Type22.Boolean()),
1784
+ upstreams_cache_enabled: Type22.Optional(Type22.Boolean()),
1785
+ upstreams_cache_size: Type22.Optional(Type22.Number()),
1786
+ confirm: Type22.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
1787
+ }, { additionalProperties: false });
1788
+ NAME14 = "adguard_add_client";
1789
+ CLIENT_BODY_FIELDS = [
1790
+ "name",
1791
+ "ids",
1792
+ "use_global_settings",
1793
+ "filtering_enabled",
1794
+ "safebrowsing_enabled",
1795
+ "parental_enabled",
1796
+ "safe_search",
1797
+ "use_global_blocked_services",
1798
+ "blocked_services",
1799
+ "blocked_services_schedule",
1800
+ "upstreams",
1801
+ "tags",
1802
+ "ignore_querylog",
1803
+ "ignore_statistics",
1804
+ "upstreams_cache_enabled",
1805
+ "upstreams_cache_size"
1806
+ ];
1807
+ }
1808
+ });
1809
+
1810
+ // src/tools/adguard_update_client.ts
1811
+ import { Type as Type23 } from "@sinclair/typebox";
1812
+ function createAdguardUpdateClientTool(getClient) {
1813
+ return {
1814
+ name: NAME15,
1815
+ label: "adguard: update client",
1816
+ description: "Update an existing named client via POST /control/clients/update. Body is nested {name, data} where data replaces the full client record. Tier-2 write; requires confirm:true.",
1817
+ parameters: Schema22,
1818
+ execute: async (_id, raw) => {
1819
+ assertConfirmedWrite(raw, NAME15);
1820
+ const args = raw;
1821
+ const client = getClient(args.instance);
1822
+ await client.post("/control/clients/update", { name: args.name, data: args.data });
1823
+ return jsonToolResult({ updated: true, name: args.name });
1824
+ }
1825
+ };
1826
+ }
1827
+ var Schema22, NAME15;
1828
+ var init_adguard_update_client = __esm({
1829
+ "src/tools/adguard_update_client.ts"() {
1830
+ "use strict";
1831
+ init_util();
1832
+ init_gates();
1833
+ Schema22 = Type23.Object({
1834
+ instance: InstanceArg,
1835
+ name: Type23.String({ description: "Current name of the client to update (used to find the existing record)." }),
1836
+ data: Type23.Object({}, { additionalProperties: true, description: "Full new Client object (AGH replaces the record; this is NOT a partial merge). Include name (new), ids, and any per-client settings to preserve." }),
1837
+ confirm: Type23.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
1838
+ }, { additionalProperties: false });
1839
+ NAME15 = "adguard_update_client";
1840
+ }
1841
+ });
1842
+
1843
+ // src/tools/adguard_set_blocked_services.ts
1844
+ import { Type as Type24 } from "@sinclair/typebox";
1845
+ function normalizeSchedule(schedule) {
1846
+ if (!schedule) return void 0;
1847
+ const out = {};
1848
+ for (const [key, value] of Object.entries(schedule)) {
1849
+ if (key === "time_zone") {
1850
+ out[key] = value;
1851
+ continue;
1852
+ }
1853
+ if (value && typeof value === "object" && "start" in value && "end" in value) {
1854
+ const range = value;
1855
+ out[key] = { start: hhmmToMs(range.start), end: hhmmToMs(range.end) };
1856
+ } else {
1857
+ out[key] = value;
1858
+ }
1859
+ }
1860
+ return out;
1861
+ }
1862
+ function createAdguardSetBlockedServicesTool(getClient) {
1863
+ return {
1864
+ name: NAME16,
1865
+ label: "adguard: set blocked services",
1866
+ description: "Set the GLOBAL blocked-services list and optional weekly schedule via PUT /control/blocked_services/update. Accepts HH:MM strings or milliseconds for schedule times. Tier-2 write; requires confirm:true.",
1867
+ parameters: Schema23,
1868
+ execute: async (_id, raw) => {
1869
+ assertConfirmedWrite(raw, NAME16);
1870
+ const args = raw;
1871
+ const client = getClient(args.instance);
1872
+ const body = { ids: args.ids };
1873
+ const normalized = normalizeSchedule(args.schedule);
1874
+ if (normalized) body.schedule = normalized;
1875
+ await client.put("/control/blocked_services/update", body);
1876
+ return jsonToolResult({ set: true, count: args.ids.length });
1877
+ }
1878
+ };
1879
+ }
1880
+ var DayRange, ScheduleSchema, Schema23, NAME16;
1881
+ var init_adguard_set_blocked_services = __esm({
1882
+ "src/tools/adguard_set_blocked_services.ts"() {
1883
+ "use strict";
1884
+ init_util();
1885
+ init_gates();
1886
+ DayRange = Type24.Object({
1887
+ start: Type24.Union([Type24.Number(), Type24.String()], { description: "Milliseconds from midnight (0-86400000) or HH:MM string." }),
1888
+ end: Type24.Union([Type24.Number(), Type24.String()], { description: "Milliseconds from midnight (0-86400000) or HH:MM string." })
1889
+ }, { additionalProperties: false });
1890
+ ScheduleSchema = Type24.Optional(Type24.Object({
1891
+ time_zone: Type24.Optional(Type24.String()),
1892
+ sun: Type24.Optional(DayRange),
1893
+ mon: Type24.Optional(DayRange),
1894
+ tue: Type24.Optional(DayRange),
1895
+ wed: Type24.Optional(DayRange),
1896
+ thu: Type24.Optional(DayRange),
1897
+ fri: Type24.Optional(DayRange),
1898
+ sat: Type24.Optional(DayRange)
1899
+ }, { additionalProperties: false }));
1900
+ Schema23 = Type24.Object({
1901
+ instance: InstanceArg,
1902
+ ids: Type24.Array(Type24.String(), { description: "Service IDs from the catalog (youtube, instagram, tiktok, ...). Empty array clears global blocks." }),
1903
+ schedule: ScheduleSchema,
1904
+ confirm: Type24.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
1905
+ }, { additionalProperties: false });
1906
+ NAME16 = "adguard_set_blocked_services";
1907
+ }
1908
+ });
1909
+
1910
+ // src/tools/adguard_toggle_safesearch.ts
1911
+ import { Type as Type25 } from "@sinclair/typebox";
1912
+ function createAdguardToggleSafesearchTool(getClient) {
1913
+ return {
1914
+ name: NAME17,
1915
+ label: "adguard: toggle safesearch",
1916
+ description: "Enable or disable SafeSearch globally via PUT /control/safesearch/settings. Per-engine flags optional (default to all engines when enabling). Tier-2 write; requires confirm:true.",
1917
+ parameters: Schema24,
1918
+ execute: async (_id, raw) => {
1919
+ assertConfirmedWrite(raw, NAME17);
1920
+ const args = raw;
1921
+ const enabled = args.enabled;
1922
+ const engines = ["bing", "duckduckgo", "ecosia", "google", "pixabay", "yandex", "youtube"];
1923
+ const body = { enabled };
1924
+ for (const e of engines) {
1925
+ if (!enabled) body[e] = false;
1926
+ else if (args[e] !== void 0) body[e] = args[e];
1927
+ else body[e] = true;
1928
+ }
1929
+ const client = getClient(args.instance);
1930
+ await client.put("/control/safesearch/settings", body);
1931
+ return jsonToolResult({ set: true, enabled });
1932
+ }
1933
+ };
1934
+ }
1935
+ var Schema24, NAME17;
1936
+ var init_adguard_toggle_safesearch = __esm({
1937
+ "src/tools/adguard_toggle_safesearch.ts"() {
1938
+ "use strict";
1939
+ init_util();
1940
+ init_gates();
1941
+ Schema24 = Type25.Object({
1942
+ instance: InstanceArg,
1943
+ enabled: Type25.Boolean({ description: "Target SafeSearch state globally." }),
1944
+ bing: Type25.Optional(Type25.Boolean()),
1945
+ duckduckgo: Type25.Optional(Type25.Boolean()),
1946
+ ecosia: Type25.Optional(Type25.Boolean()),
1947
+ google: Type25.Optional(Type25.Boolean()),
1948
+ pixabay: Type25.Optional(Type25.Boolean()),
1949
+ yandex: Type25.Optional(Type25.Boolean()),
1950
+ youtube: Type25.Optional(Type25.Boolean()),
1951
+ confirm: Type25.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
1952
+ }, { additionalProperties: false });
1953
+ NAME17 = "adguard_toggle_safesearch";
1954
+ }
1955
+ });
1956
+
1957
+ // src/tools/adguard_toggle_safebrowsing.ts
1958
+ import { Type as Type26 } from "@sinclair/typebox";
1959
+ function createAdguardToggleSafebrowsingTool(getClient) {
1960
+ return {
1961
+ name: NAME18,
1962
+ label: "adguard: toggle safebrowsing",
1963
+ description: "Enable or disable AGH SafeBrowsing via POST /control/safebrowsing/enable or /disable. Tier-2 write; requires confirm:true.",
1964
+ parameters: Schema25,
1965
+ execute: async (_id, raw) => {
1966
+ assertConfirmedWrite(raw, NAME18);
1967
+ const args = raw;
1968
+ const client = getClient(args.instance);
1969
+ const path = args.enabled ? "/control/safebrowsing/enable" : "/control/safebrowsing/disable";
1970
+ await client.post(path, void 0);
1971
+ return jsonToolResult({ set: true, enabled: args.enabled });
1972
+ }
1973
+ };
1974
+ }
1975
+ var Schema25, NAME18;
1976
+ var init_adguard_toggle_safebrowsing = __esm({
1977
+ "src/tools/adguard_toggle_safebrowsing.ts"() {
1978
+ "use strict";
1979
+ init_util();
1980
+ init_gates();
1981
+ Schema25 = Type26.Object({
1982
+ instance: InstanceArg,
1983
+ enabled: Type26.Boolean({ description: "Target SafeBrowsing state." }),
1984
+ confirm: Type26.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
1985
+ }, { additionalProperties: false });
1986
+ NAME18 = "adguard_toggle_safebrowsing";
1987
+ }
1988
+ });
1989
+
1990
+ // src/tools/adguard_delete_client.ts
1991
+ import { Type as Type27 } from "@sinclair/typebox";
1992
+ function createAdguardDeleteClientTool(getClient) {
1993
+ return {
1994
+ name: NAME19,
1995
+ label: "adguard: delete client",
1996
+ description: "Remove a configured named client via POST /control/clients/delete. Tier-3 destructive; per-client rules and per-client filtering settings are lost. Requires confirm:true and destructive:true.",
1997
+ parameters: Schema26,
1998
+ execute: async (_id, raw) => {
1999
+ assertDestructive(raw, NAME19);
2000
+ const args = raw;
2001
+ const client = getClient(args.instance);
2002
+ await client.post("/control/clients/delete", { name: args.name });
2003
+ return jsonToolResult({ deleted: true, name: args.name });
2004
+ }
2005
+ };
2006
+ }
2007
+ var Schema26, NAME19;
2008
+ var init_adguard_delete_client = __esm({
2009
+ "src/tools/adguard_delete_client.ts"() {
2010
+ "use strict";
2011
+ init_util();
2012
+ init_gates();
2013
+ Schema26 = Type27.Object({
2014
+ instance: InstanceArg,
2015
+ name: Type27.String({ description: "Name of the configured client to remove." }),
2016
+ confirm: Type27.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
2017
+ destructive: Type27.Boolean({ description: "Must be true. Tier-3 destructive gate (deleting a client drops per-client rules and stats)." })
2018
+ }, { additionalProperties: false });
2019
+ NAME19 = "adguard_delete_client";
2020
+ }
2021
+ });
2022
+
2023
+ // src/tools/adguard_clear_query_log.ts
2024
+ import { Type as Type28 } from "@sinclair/typebox";
2025
+ function createAdguardClearQueryLogTool(getClient) {
2026
+ return {
2027
+ name: NAME20,
2028
+ label: "adguard: clear query log",
2029
+ description: "Wipe the AGH DNS query log via POST /control/querylog_clear (underscore endpoint). Tier-3 destructive; requires confirm:true and destructive:true.",
2030
+ parameters: Schema27,
2031
+ execute: async (_id, raw) => {
2032
+ assertDestructive(raw, NAME20);
2033
+ const args = raw;
2034
+ const client = getClient(args.instance);
2035
+ await client.post("/control/querylog_clear", void 0);
2036
+ return jsonToolResult({ cleared: true });
2037
+ }
2038
+ };
2039
+ }
2040
+ var Schema27, NAME20;
2041
+ var init_adguard_clear_query_log = __esm({
2042
+ "src/tools/adguard_clear_query_log.ts"() {
2043
+ "use strict";
2044
+ init_util();
2045
+ init_gates();
2046
+ Schema27 = Type28.Object({
2047
+ instance: InstanceArg,
2048
+ confirm: Type28.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
2049
+ destructive: Type28.Boolean({ description: "Must be true. Tier-3 destructive gate (the query log is gone after this)." })
2050
+ }, { additionalProperties: false });
2051
+ NAME20 = "adguard_clear_query_log";
2052
+ }
2053
+ });
2054
+
2055
+ // src/tools/adguard_reset_stats.ts
2056
+ import { Type as Type29 } from "@sinclair/typebox";
2057
+ function createAdguardResetStatsTool(getClient) {
2058
+ return {
2059
+ name: NAME21,
2060
+ label: "adguard: reset stats",
2061
+ description: "Zero out the AGH stats window via POST /control/stats_reset (underscore endpoint). Tier-3 destructive; requires confirm:true and destructive:true.",
2062
+ parameters: Schema28,
2063
+ execute: async (_id, raw) => {
2064
+ assertDestructive(raw, NAME21);
2065
+ const args = raw;
2066
+ const client = getClient(args.instance);
2067
+ await client.post("/control/stats_reset", void 0);
2068
+ return jsonToolResult({ reset: true });
2069
+ }
2070
+ };
2071
+ }
2072
+ var Schema28, NAME21;
2073
+ var init_adguard_reset_stats = __esm({
2074
+ "src/tools/adguard_reset_stats.ts"() {
2075
+ "use strict";
2076
+ init_util();
2077
+ init_gates();
2078
+ Schema28 = Type29.Object({
2079
+ instance: InstanceArg,
2080
+ confirm: Type29.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
2081
+ destructive: Type29.Boolean({ description: "Must be true. Tier-3 destructive gate (stats history is zeroed)." })
2082
+ }, { additionalProperties: false });
2083
+ NAME21 = "adguard_reset_stats";
2084
+ }
2085
+ });
2086
+
2087
+ // src/tools/adguard_list_rewrites.ts
2088
+ import { Type as Type30 } from "@sinclair/typebox";
2089
+ function createAdguardListRewritesTool(getClient) {
2090
+ return {
2091
+ name: NAME22,
2092
+ label: "adguard: list rewrites",
2093
+ description: "List DNS rewrite rules via GET /control/rewrite/list.",
2094
+ parameters: Schema29,
2095
+ execute: async (_id, raw) => {
2096
+ const args = raw;
2097
+ const client = getClient(args.instance);
2098
+ const rewrites = await client.get("/control/rewrite/list");
2099
+ return jsonToolResult(rewrites);
2100
+ }
2101
+ };
2102
+ }
2103
+ var Schema29, NAME22;
2104
+ var init_adguard_list_rewrites = __esm({
2105
+ "src/tools/adguard_list_rewrites.ts"() {
2106
+ "use strict";
2107
+ init_util();
2108
+ Schema29 = Type30.Object({ instance: InstanceArg }, { additionalProperties: false });
2109
+ NAME22 = "adguard_list_rewrites";
2110
+ }
2111
+ });
2112
+
2113
+ // src/tools/adguard_add_rewrite.ts
2114
+ import { Type as Type31 } from "@sinclair/typebox";
2115
+ function createAdguardAddRewriteTool(getClient) {
2116
+ return {
2117
+ name: NAME23,
2118
+ label: "adguard: add rewrite",
2119
+ description: "Add a DNS rewrite rule via POST /control/rewrite/add. Tier-2 write; requires confirm:true.",
2120
+ parameters: Schema30,
2121
+ execute: async (_id, raw) => {
2122
+ assertConfirmedWrite(raw, NAME23);
2123
+ const args = raw;
2124
+ const body = { domain: args.domain, answer: args.answer };
2125
+ if (args.enabled !== void 0) body.enabled = args.enabled;
2126
+ const client = getClient(args.instance);
2127
+ await client.post("/control/rewrite/add", body);
2128
+ return jsonToolResult({ added: true, domain: args.domain, answer: args.answer });
2129
+ }
2130
+ };
2131
+ }
2132
+ var Schema30, NAME23;
2133
+ var init_adguard_add_rewrite = __esm({
2134
+ "src/tools/adguard_add_rewrite.ts"() {
2135
+ "use strict";
2136
+ init_util();
2137
+ init_gates();
2138
+ Schema30 = Type31.Object({
2139
+ instance: InstanceArg,
2140
+ domain: Type31.String({ description: "Domain name to rewrite, e.g. router.home.arpa." }),
2141
+ answer: Type31.String({ description: "A, AAAA, or CNAME answer value." }),
2142
+ enabled: Type31.Optional(Type31.Boolean({ description: "Whether the rewrite is enabled. Defaults to AGH's default true when omitted." })),
2143
+ confirm: Type31.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2144
+ }, { additionalProperties: false });
2145
+ NAME23 = "adguard_add_rewrite";
2146
+ }
2147
+ });
2148
+
2149
+ // src/tools/adguard_update_rewrite.ts
2150
+ import { Type as Type32 } from "@sinclair/typebox";
2151
+ function createAdguardUpdateRewriteTool(getClient) {
2152
+ return {
2153
+ name: NAME24,
2154
+ label: "adguard: update rewrite",
2155
+ description: "Update a DNS rewrite rule via PUT /control/rewrite/update with {target, update}. Tier-2 write; requires confirm:true.",
2156
+ parameters: Schema31,
2157
+ execute: async (_id, raw) => {
2158
+ assertConfirmedWrite(raw, NAME24);
2159
+ const args = raw;
2160
+ const client = getClient(args.instance);
2161
+ await client.put("/control/rewrite/update", { target: args.target, update: args.update });
2162
+ return jsonToolResult({ updated: true, target: args.target, update: args.update });
2163
+ }
2164
+ };
2165
+ }
2166
+ var RewriteEntrySchema, Schema31, NAME24;
2167
+ var init_adguard_update_rewrite = __esm({
2168
+ "src/tools/adguard_update_rewrite.ts"() {
2169
+ "use strict";
2170
+ init_util();
2171
+ init_gates();
2172
+ RewriteEntrySchema = Type32.Object({
2173
+ domain: Type32.String({ description: "Domain name." }),
2174
+ answer: Type32.String({ description: "A, AAAA, or CNAME answer value." }),
2175
+ enabled: Type32.Optional(Type32.Boolean({ description: "Whether this rewrite is enabled." }))
2176
+ }, { additionalProperties: false });
2177
+ Schema31 = Type32.Object({
2178
+ instance: InstanceArg,
2179
+ target: RewriteEntrySchema,
2180
+ update: RewriteEntrySchema,
2181
+ confirm: Type32.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2182
+ }, { additionalProperties: false });
2183
+ NAME24 = "adguard_update_rewrite";
2184
+ }
2185
+ });
2186
+
2187
+ // src/tools/adguard_delete_rewrite.ts
2188
+ import { Type as Type33 } from "@sinclair/typebox";
2189
+ function createAdguardDeleteRewriteTool(getClient) {
2190
+ return {
2191
+ name: NAME25,
2192
+ label: "adguard: delete rewrite",
2193
+ description: "Delete a DNS rewrite rule via POST /control/rewrite/delete. Tier-2 write; requires confirm:true.",
2194
+ parameters: Schema32,
2195
+ execute: async (_id, raw) => {
2196
+ assertConfirmedWrite(raw, NAME25);
2197
+ const args = raw;
2198
+ const body = { domain: args.domain, answer: args.answer };
2199
+ if (args.enabled !== void 0) body.enabled = args.enabled;
2200
+ const client = getClient(args.instance);
2201
+ await client.post("/control/rewrite/delete", body);
2202
+ return jsonToolResult({ deleted: true, domain: args.domain, answer: args.answer });
2203
+ }
2204
+ };
2205
+ }
2206
+ var Schema32, NAME25;
2207
+ var init_adguard_delete_rewrite = __esm({
2208
+ "src/tools/adguard_delete_rewrite.ts"() {
2209
+ "use strict";
2210
+ init_util();
2211
+ init_gates();
2212
+ Schema32 = Type33.Object({
2213
+ instance: InstanceArg,
2214
+ domain: Type33.String({ description: "Domain name of the rewrite to delete." }),
2215
+ answer: Type33.String({ description: "Answer value of the rewrite to delete." }),
2216
+ enabled: Type33.Optional(Type33.Boolean({ description: "Enabled state, when needed to identify the exact rewrite." })),
2217
+ confirm: Type33.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2218
+ }, { additionalProperties: false });
2219
+ NAME25 = "adguard_delete_rewrite";
2220
+ }
2221
+ });
2222
+
2223
+ // src/tools/adguard_get_rewrite_settings.ts
2224
+ import { Type as Type34 } from "@sinclair/typebox";
2225
+ function createAdguardGetRewriteSettingsTool(getClient) {
2226
+ return {
2227
+ name: NAME26,
2228
+ label: "adguard: get rewrite settings",
2229
+ description: "Get DNS rewrite enabled state via GET /control/rewrite/settings.",
2230
+ parameters: Schema33,
2231
+ execute: async (_id, raw) => {
2232
+ const args = raw;
2233
+ const client = getClient(args.instance);
2234
+ const settings = await client.get("/control/rewrite/settings");
2235
+ return jsonToolResult(settings);
2236
+ }
2237
+ };
2238
+ }
2239
+ var Schema33, NAME26;
2240
+ var init_adguard_get_rewrite_settings = __esm({
2241
+ "src/tools/adguard_get_rewrite_settings.ts"() {
2242
+ "use strict";
2243
+ init_util();
2244
+ Schema33 = Type34.Object({ instance: InstanceArg }, { additionalProperties: false });
2245
+ NAME26 = "adguard_get_rewrite_settings";
2246
+ }
2247
+ });
2248
+
2249
+ // src/tools/adguard_toggle_rewrites.ts
2250
+ import { Type as Type35 } from "@sinclair/typebox";
2251
+ function createAdguardToggleRewritesTool(getClient) {
2252
+ return {
2253
+ name: NAME27,
2254
+ label: "adguard: toggle rewrites",
2255
+ description: "Enable or disable DNS rewrites via PUT /control/rewrite/settings/update. Tier-2 write; requires confirm:true.",
2256
+ parameters: Schema34,
2257
+ execute: async (_id, raw) => {
2258
+ assertConfirmedWrite(raw, NAME27);
2259
+ const args = raw;
2260
+ const client = getClient(args.instance);
2261
+ await client.put("/control/rewrite/settings/update", { enabled: args.enabled });
2262
+ return jsonToolResult({ updated: true, enabled: args.enabled });
2263
+ }
2264
+ };
2265
+ }
2266
+ var Schema34, NAME27;
2267
+ var init_adguard_toggle_rewrites = __esm({
2268
+ "src/tools/adguard_toggle_rewrites.ts"() {
2269
+ "use strict";
2270
+ init_util();
2271
+ init_gates();
2272
+ Schema34 = Type35.Object({
2273
+ instance: InstanceArg,
2274
+ enabled: Type35.Boolean({ description: "Target DNS rewrite enabled state." }),
2275
+ confirm: Type35.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2276
+ }, { additionalProperties: false });
2277
+ NAME27 = "adguard_toggle_rewrites";
2278
+ }
2279
+ });
2280
+
2281
+ // src/tools/adguard_get_access_list.ts
2282
+ import { Type as Type36 } from "@sinclair/typebox";
2283
+ function createAdguardGetAccessListTool(getClient) {
2284
+ return {
2285
+ name: NAME28,
2286
+ label: "adguard: get access list",
2287
+ description: "Get allowed clients, disallowed clients, and blocked hosts via GET /control/access/list.",
2288
+ parameters: Schema35,
2289
+ execute: async (_id, raw) => {
2290
+ const args = raw;
2291
+ const client = getClient(args.instance);
2292
+ const list = await client.get("/control/access/list");
2293
+ return jsonToolResult(list);
2294
+ }
2295
+ };
2296
+ }
2297
+ var Schema35, NAME28;
2298
+ var init_adguard_get_access_list = __esm({
2299
+ "src/tools/adguard_get_access_list.ts"() {
2300
+ "use strict";
2301
+ init_util();
2302
+ Schema35 = Type36.Object({ instance: InstanceArg }, { additionalProperties: false });
2303
+ NAME28 = "adguard_get_access_list";
2304
+ }
2305
+ });
2306
+
2307
+ // src/tools/adguard_set_access_list.ts
2308
+ import { Type as Type37 } from "@sinclair/typebox";
2309
+ function createAdguardSetAccessListTool(getClient) {
2310
+ return {
2311
+ name: NAME29,
2312
+ label: "adguard: set access list",
2313
+ description: "Replace allowed clients, disallowed clients, and blocked hosts via POST /control/access/set. Tier-2 write; requires confirm:true.",
2314
+ parameters: Schema36,
2315
+ execute: async (_id, raw) => {
2316
+ assertConfirmedWrite(raw, NAME29);
2317
+ const args = raw;
2318
+ const body = {
2319
+ allowed_clients: args.allowed_clients,
2320
+ disallowed_clients: args.disallowed_clients,
2321
+ blocked_hosts: args.blocked_hosts
2322
+ };
2323
+ const client = getClient(args.instance);
2324
+ await client.post("/control/access/set", body);
2325
+ return jsonToolResult({ updated: true, ...body });
2326
+ }
2327
+ };
2328
+ }
2329
+ var Schema36, NAME29;
2330
+ var init_adguard_set_access_list = __esm({
2331
+ "src/tools/adguard_set_access_list.ts"() {
2332
+ "use strict";
2333
+ init_util();
2334
+ init_gates();
2335
+ Schema36 = Type37.Object({
2336
+ instance: InstanceArg,
2337
+ allowed_clients: Type37.Array(Type37.String(), { description: "Allowlist of clients: IP addresses, CIDRs, or ClientIDs. Empty array disables the allowlist." }),
2338
+ disallowed_clients: Type37.Array(Type37.String(), { description: "Blocklist of clients: IP addresses, CIDRs, or ClientIDs." }),
2339
+ blocked_hosts: Type37.Array(Type37.String(), { description: "Blocklist of hostnames." }),
2340
+ confirm: Type37.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2341
+ }, { additionalProperties: false });
2342
+ NAME29 = "adguard_set_access_list";
2343
+ }
2344
+ });
2345
+
2346
+ // src/tools/adguard_get_querylog_config.ts
2347
+ import { Type as Type38 } from "@sinclair/typebox";
2348
+ function createAdguardGetQuerylogConfigTool(getClient) {
2349
+ return {
2350
+ name: NAME30,
2351
+ label: "adguard: get query log config",
2352
+ description: "Get query log settings via GET /control/querylog/config.",
2353
+ parameters: Schema37,
2354
+ execute: async (_id, raw) => {
2355
+ const args = raw;
2356
+ const client = getClient(args.instance);
2357
+ const config = await client.get("/control/querylog/config");
2358
+ return jsonToolResult(config);
2359
+ }
2360
+ };
2361
+ }
2362
+ var Schema37, NAME30;
2363
+ var init_adguard_get_querylog_config = __esm({
2364
+ "src/tools/adguard_get_querylog_config.ts"() {
2365
+ "use strict";
2366
+ init_util();
2367
+ Schema37 = Type38.Object({ instance: InstanceArg }, { additionalProperties: false });
2368
+ NAME30 = "adguard_get_querylog_config";
2369
+ }
2370
+ });
2371
+
2372
+ // src/tools/adguard_update_querylog_config.ts
2373
+ import { Type as Type39 } from "@sinclair/typebox";
2374
+ function createAdguardUpdateQuerylogConfigTool(getClient) {
2375
+ return {
2376
+ name: NAME31,
2377
+ label: "adguard: update query log config",
2378
+ description: "Update query log settings via PUT /control/querylog/config/update. Pass the AGH config fields inside `config`. Tier-2 write; requires confirm:true.",
2379
+ parameters: Schema38,
2380
+ execute: async (_id, raw) => {
2381
+ assertConfirmedWrite(raw, NAME31);
2382
+ const args = raw;
2383
+ const client = getClient(args.instance);
2384
+ await client.put("/control/querylog/config/update", args.config);
2385
+ return jsonToolResult({ updated: true, config: args.config });
2386
+ }
2387
+ };
2388
+ }
2389
+ var Schema38, NAME31;
2390
+ var init_adguard_update_querylog_config = __esm({
2391
+ "src/tools/adguard_update_querylog_config.ts"() {
2392
+ "use strict";
2393
+ init_util();
2394
+ init_gates();
2395
+ Schema38 = Type39.Object({
2396
+ instance: InstanceArg,
2397
+ config: Type39.Object({}, { additionalProperties: true, description: "Query log config body for PUT /control/querylog/config/update." }),
2398
+ confirm: Type39.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2399
+ }, { additionalProperties: false });
2400
+ NAME31 = "adguard_update_querylog_config";
2401
+ }
2402
+ });
2403
+
2404
+ // src/tools/adguard_get_stats_config.ts
2405
+ import { Type as Type40 } from "@sinclair/typebox";
2406
+ function createAdguardGetStatsConfigTool(getClient) {
2407
+ return {
2408
+ name: NAME32,
2409
+ label: "adguard: get stats config",
2410
+ description: "Get statistics settings via GET /control/stats/config.",
2411
+ parameters: Schema39,
2412
+ execute: async (_id, raw) => {
2413
+ const args = raw;
2414
+ const client = getClient(args.instance);
2415
+ const config = await client.get("/control/stats/config");
2416
+ return jsonToolResult(config);
2417
+ }
2418
+ };
2419
+ }
2420
+ var Schema39, NAME32;
2421
+ var init_adguard_get_stats_config = __esm({
2422
+ "src/tools/adguard_get_stats_config.ts"() {
2423
+ "use strict";
2424
+ init_util();
2425
+ Schema39 = Type40.Object({ instance: InstanceArg }, { additionalProperties: false });
2426
+ NAME32 = "adguard_get_stats_config";
2427
+ }
2428
+ });
2429
+
2430
+ // src/tools/adguard_update_stats_config.ts
2431
+ import { Type as Type41 } from "@sinclair/typebox";
2432
+ function createAdguardUpdateStatsConfigTool(getClient) {
2433
+ return {
2434
+ name: NAME33,
2435
+ label: "adguard: update stats config",
2436
+ description: "Update statistics settings via PUT /control/stats/config/update. Pass the AGH config fields inside `config`. Tier-2 write; requires confirm:true.",
2437
+ parameters: Schema40,
2438
+ execute: async (_id, raw) => {
2439
+ assertConfirmedWrite(raw, NAME33);
2440
+ const args = raw;
2441
+ const client = getClient(args.instance);
2442
+ await client.put("/control/stats/config/update", args.config);
2443
+ return jsonToolResult({ updated: true, config: args.config });
2444
+ }
2445
+ };
2446
+ }
2447
+ var Schema40, NAME33;
2448
+ var init_adguard_update_stats_config = __esm({
2449
+ "src/tools/adguard_update_stats_config.ts"() {
2450
+ "use strict";
2451
+ init_util();
2452
+ init_gates();
2453
+ Schema40 = Type41.Object({
2454
+ instance: InstanceArg,
2455
+ config: Type41.Object({}, { additionalProperties: true, description: "Stats config body for PUT /control/stats/config/update." }),
2456
+ confirm: Type41.Boolean({ description: "Must be true. Tier-2 safe-write gate." })
2457
+ }, { additionalProperties: false });
2458
+ NAME33 = "adguard_update_stats_config";
2459
+ }
2460
+ });
2461
+
2462
+ // src/tools/adguard_dhcp_status.ts
2463
+ import { Type as Type42 } from "@sinclair/typebox";
2464
+ function createAdguardDhcpStatusTool(getClient) {
2465
+ return {
2466
+ name: NAME34,
2467
+ label: "adguard: dhcp status",
2468
+ description: "Get DHCP server settings, leases, and status via GET /control/dhcp/status.",
2469
+ parameters: Schema41,
2470
+ execute: async (_id, raw) => {
2471
+ const args = raw;
2472
+ const client = getClient(args.instance);
2473
+ const status = await client.get("/control/dhcp/status");
2474
+ return jsonToolResult(status);
2475
+ }
2476
+ };
2477
+ }
2478
+ var Schema41, NAME34;
2479
+ var init_adguard_dhcp_status = __esm({
2480
+ "src/tools/adguard_dhcp_status.ts"() {
2481
+ "use strict";
2482
+ init_util();
2483
+ Schema41 = Type42.Object({ instance: InstanceArg }, { additionalProperties: false });
2484
+ NAME34 = "adguard_dhcp_status";
2485
+ }
2486
+ });
2487
+
2488
+ // src/tools/adguard_dhcp_interfaces.ts
2489
+ import { Type as Type43 } from "@sinclair/typebox";
2490
+ function createAdguardDhcpInterfacesTool(getClient) {
2491
+ return {
2492
+ name: NAME35,
2493
+ label: "adguard: dhcp interfaces",
2494
+ description: "List network interfaces available to the DHCP server via GET /control/dhcp/interfaces.",
2495
+ parameters: Schema42,
2496
+ execute: async (_id, raw) => {
2497
+ const args = raw;
2498
+ const client = getClient(args.instance);
2499
+ const interfaces = await client.get("/control/dhcp/interfaces");
2500
+ return jsonToolResult(interfaces);
2501
+ }
2502
+ };
2503
+ }
2504
+ var Schema42, NAME35;
2505
+ var init_adguard_dhcp_interfaces = __esm({
2506
+ "src/tools/adguard_dhcp_interfaces.ts"() {
2507
+ "use strict";
2508
+ init_util();
2509
+ Schema42 = Type43.Object({ instance: InstanceArg }, { additionalProperties: false });
2510
+ NAME35 = "adguard_dhcp_interfaces";
2511
+ }
2512
+ });
2513
+
2514
+ // src/tools/adguard_tls_status.ts
2515
+ import { Type as Type44 } from "@sinclair/typebox";
2516
+ function createAdguardTlsStatusTool(getClient) {
2517
+ return {
2518
+ name: NAME36,
2519
+ label: "adguard: tls status",
2520
+ description: "Get TLS configuration and validation status via GET /control/tls/status. Private key values are redacted from tool output.",
2521
+ parameters: Schema43,
2522
+ execute: async (_id, raw) => {
2523
+ const args = raw;
2524
+ const client = getClient(args.instance);
2525
+ const status = await client.get("/control/tls/status");
2526
+ return jsonToolResult(redactTlsSecrets(status));
2527
+ }
2528
+ };
2529
+ }
2530
+ function redactTlsSecrets(value) {
2531
+ if (Array.isArray(value)) return value.map(redactTlsSecrets);
2532
+ if (!value || typeof value !== "object") return value;
2533
+ const out = {};
2534
+ for (const [key, entry] of Object.entries(value)) {
2535
+ out[key] = key === "private_key" ? "[REDACTED]" : redactTlsSecrets(entry);
2536
+ }
2537
+ return out;
2538
+ }
2539
+ var Schema43, NAME36;
2540
+ var init_adguard_tls_status = __esm({
2541
+ "src/tools/adguard_tls_status.ts"() {
2542
+ "use strict";
2543
+ init_util();
2544
+ Schema43 = Type44.Object({ instance: InstanceArg }, { additionalProperties: false });
2545
+ NAME36 = "adguard_tls_status";
2546
+ }
2547
+ });
2548
+
2549
+ // src/tools/adguard_validate_tls_config.ts
2550
+ import { Type as Type45 } from "@sinclair/typebox";
2551
+ function createAdguardValidateTlsConfigTool(getClient) {
2552
+ return {
2553
+ name: NAME37,
2554
+ label: "adguard: validate tls config",
2555
+ description: "Validate a TLS config via POST /control/tls/validate without applying it. Tier-2 gated because the request can carry certificate/key material; private key values are redacted from tool output.",
2556
+ parameters: Schema44,
2557
+ execute: async (_id, raw) => {
2558
+ assertConfirmedWrite(raw, NAME37);
2559
+ const args = raw;
2560
+ const client = getClient(args.instance);
2561
+ const result = await client.post("/control/tls/validate", args.config);
2562
+ return jsonToolResult(redactTlsSecrets(result));
2563
+ }
2564
+ };
2565
+ }
2566
+ var Schema44, NAME37;
2567
+ var init_adguard_validate_tls_config = __esm({
2568
+ "src/tools/adguard_validate_tls_config.ts"() {
2569
+ "use strict";
2570
+ init_util();
2571
+ init_gates();
2572
+ init_adguard_tls_status();
2573
+ Schema44 = Type45.Object({
2574
+ instance: InstanceArg,
2575
+ config: Type45.Object({}, { additionalProperties: true, description: "TLS config body for POST /control/tls/validate. May include certificate_chain/private_key or file paths." }),
2576
+ confirm: Type45.Boolean({ description: "Must be true. Tier-2 gate because TLS validation may include sensitive key material." })
2577
+ }, { additionalProperties: false });
2578
+ NAME37 = "adguard_validate_tls_config";
2579
+ }
2580
+ });
2581
+
2582
+ // src/tools/adguard_test_upstream_dns.ts
2583
+ import { Type as Type46 } from "@sinclair/typebox";
2584
+ function createAdguardTestUpstreamDnsTool(getClient) {
2585
+ return {
2586
+ name: NAME38,
2587
+ label: "adguard: test upstream dns",
2588
+ description: "Test upstream DNS server configuration via POST /control/test_upstream_dns. Tier-2 gated because it causes the AGH server to probe the provided upstreams.",
2589
+ parameters: Schema45,
2590
+ execute: async (_id, raw) => {
2591
+ assertConfirmedWrite(raw, NAME38);
2592
+ const args = raw;
2593
+ const body = {
2594
+ bootstrap_dns: args.bootstrap_dns,
2595
+ upstream_dns: args.upstream_dns
2596
+ };
2597
+ if (args.fallback_dns !== void 0) body.fallback_dns = args.fallback_dns;
2598
+ if (args.private_upstream !== void 0) body.private_upstream = args.private_upstream;
2599
+ const client = getClient(args.instance);
2600
+ const result = await client.post("/control/test_upstream_dns", body);
2601
+ return jsonToolResult(result);
2602
+ }
2603
+ };
2604
+ }
2605
+ var Schema45, NAME38;
2606
+ var init_adguard_test_upstream_dns = __esm({
2607
+ "src/tools/adguard_test_upstream_dns.ts"() {
2608
+ "use strict";
2609
+ init_util();
2610
+ init_gates();
2611
+ Schema45 = Type46.Object({
2612
+ instance: InstanceArg,
2613
+ bootstrap_dns: Type46.Array(Type46.String(), { description: "Bootstrap DNS servers, port optional." }),
2614
+ upstream_dns: Type46.Array(Type46.String(), { description: "Upstream DNS servers to test, port optional." }),
2615
+ fallback_dns: Type46.Optional(Type46.Array(Type46.String(), { description: "Fallback DNS servers to test, port optional." })),
2616
+ private_upstream: Type46.Optional(Type46.Array(Type46.String(), { description: "Local PTR resolvers to test, port optional." })),
2617
+ confirm: Type46.Boolean({ description: "Must be true. Tier-2 gate because the AGH server will probe the provided upstreams." })
2618
+ }, { additionalProperties: false });
2619
+ NAME38 = "adguard_test_upstream_dns";
2620
+ }
2621
+ });
2622
+
2623
+ // src/tools/adguard_sync_status.ts
2624
+ import { Type as Type47 } from "@sinclair/typebox";
2625
+ function createAdguardSyncStatusTool(getSyncClient) {
2626
+ return {
2627
+ name: "adguard_sync_status",
2628
+ label: "adguard sync: status",
2629
+ description: "Get AdGuardHome Sync origin/replica status via GET /api/v1/status.",
2630
+ parameters: Schema46,
2631
+ execute: async (_id, _raw) => {
2632
+ const client = getSyncClient();
2633
+ const status = await client.get("/api/v1/status");
2634
+ return jsonToolResult(status);
2635
+ }
2636
+ };
2637
+ }
2638
+ var Schema46;
2639
+ var init_adguard_sync_status = __esm({
2640
+ "src/tools/adguard_sync_status.ts"() {
2641
+ "use strict";
2642
+ init_util();
2643
+ Schema46 = Type47.Object({}, { additionalProperties: false });
2644
+ }
2645
+ });
2646
+
2647
+ // src/tools/adguard_sync_health.ts
2648
+ import { Type as Type48 } from "@sinclair/typebox";
2649
+ function createAdguardSyncHealthTool(getSyncClient) {
2650
+ return {
2651
+ name: "adguard_sync_health",
2652
+ label: "adguard sync: health",
2653
+ description: "Check AdGuardHome Sync health via HEAD /healthz. The endpoint is unauthenticated upstream and returns 2xx only when origin and replicas are healthy.",
2654
+ parameters: Schema47,
2655
+ execute: async (_id, _raw) => {
2656
+ const client = getSyncClient();
2657
+ const health = await client.head("/healthz");
2658
+ return jsonToolResult(health);
2659
+ }
2660
+ };
2661
+ }
2662
+ var Schema47;
2663
+ var init_adguard_sync_health = __esm({
2664
+ "src/tools/adguard_sync_health.ts"() {
2665
+ "use strict";
2666
+ init_util();
2667
+ Schema47 = Type48.Object({}, { additionalProperties: false });
2668
+ }
2669
+ });
2670
+
2671
+ // src/tools/adguard_sync_logs.ts
2672
+ import { Type as Type49 } from "@sinclair/typebox";
2673
+ function createAdguardSyncLogsTool(getSyncClient) {
2674
+ return {
2675
+ name: "adguard_sync_logs",
2676
+ label: "adguard sync: logs",
2677
+ description: "Read AdGuardHome Sync in-memory logs via GET /api/v1/logs.",
2678
+ parameters: Schema48,
2679
+ execute: async (_id, _raw) => {
2680
+ const client = getSyncClient();
2681
+ const logs = await client.get("/api/v1/logs");
2682
+ return jsonToolResult({ logs });
2683
+ }
2684
+ };
2685
+ }
2686
+ var Schema48;
2687
+ var init_adguard_sync_logs = __esm({
2688
+ "src/tools/adguard_sync_logs.ts"() {
2689
+ "use strict";
2690
+ init_util();
2691
+ Schema48 = Type49.Object({}, { additionalProperties: false });
2692
+ }
2693
+ });
2694
+
2695
+ // src/tools/adguard_sync_run.ts
2696
+ import { Type as Type50 } from "@sinclair/typebox";
2697
+ function createAdguardSyncRunTool(getSyncClient) {
2698
+ return {
2699
+ name: NAME39,
2700
+ label: "adguard sync: run",
2701
+ description: "Trigger AdGuardHome Sync immediately via POST /api/v1/sync. Tier-2 write; requires confirm:true.",
2702
+ parameters: Schema49,
2703
+ execute: async (_id, raw) => {
2704
+ assertConfirmedWrite(raw, NAME39);
2705
+ const client = getSyncClient();
2706
+ await client.post("/api/v1/sync");
2707
+ return jsonToolResult({ started: true });
2708
+ }
2709
+ };
2710
+ }
2711
+ var Schema49, NAME39;
2712
+ var init_adguard_sync_run = __esm({
2713
+ "src/tools/adguard_sync_run.ts"() {
2714
+ "use strict";
2715
+ init_util();
2716
+ init_gates();
2717
+ Schema49 = Type50.Object({
2718
+ confirm: Type50.Boolean({ description: "Must be true. Tier-2 safe-write gate. Starts a sync from origin to replicas." })
2719
+ }, { additionalProperties: false });
2720
+ NAME39 = "adguard_sync_run";
2721
+ }
2722
+ });
2723
+
2724
+ // src/tools/adguard_sync_clear_logs.ts
2725
+ import { Type as Type51 } from "@sinclair/typebox";
2726
+ function createAdguardSyncClearLogsTool(getSyncClient) {
2727
+ return {
2728
+ name: NAME40,
2729
+ label: "adguard sync: clear logs",
2730
+ description: "Clear AdGuardHome Sync in-memory logs via POST /api/v1/clear-logs. Tier-3 destructive; requires confirm:true and destructive:true.",
2731
+ parameters: Schema50,
2732
+ execute: async (_id, raw) => {
2733
+ assertDestructive(raw, NAME40);
2734
+ const client = getSyncClient();
2735
+ await client.post("/api/v1/clear-logs");
2736
+ return jsonToolResult({ cleared: true });
2737
+ }
2738
+ };
2739
+ }
2740
+ var Schema50, NAME40;
2741
+ var init_adguard_sync_clear_logs = __esm({
2742
+ "src/tools/adguard_sync_clear_logs.ts"() {
2743
+ "use strict";
2744
+ init_util();
2745
+ init_gates();
2746
+ Schema50 = Type51.Object({
2747
+ confirm: Type51.Boolean({ description: "Must be true. Tier-3 destructive gate." }),
2748
+ destructive: Type51.Boolean({ description: "Must be true. Tier-3 destructive gate. Clears AdGuardHome Sync logs." })
2749
+ }, { additionalProperties: false });
2750
+ NAME40 = "adguard_sync_clear_logs";
2751
+ }
2752
+ });
2753
+
2754
+ // src/tools/index.ts
2755
+ function buildAllTools(getClient, getSyncClient) {
2756
+ return [
2757
+ // Tier 1: reads
2758
+ createAdguardStatusTool(getClient),
2759
+ createAdguardStatsTool(getClient),
2760
+ createAdguardQueryLogTool(getClient),
2761
+ createAdguardListFilterListsTool(getClient),
2762
+ createAdguardListUserRulesTool(getClient),
2763
+ createAdguardListClientsTool(getClient),
2764
+ createAdguardListBlockedServicesCatalogTool(getClient),
2765
+ createAdguardCheckHostTool(getClient),
2766
+ createAdguardGetBlockedServicesTool(getClient),
2767
+ createAdguardGetDnsConfigTool(getClient),
2768
+ createAdguardGetSafesearchSettingsTool(getClient),
2769
+ createAdguardListRewritesTool(getClient),
2770
+ createAdguardGetRewriteSettingsTool(getClient),
2771
+ createAdguardGetAccessListTool(getClient),
2772
+ createAdguardGetQuerylogConfigTool(getClient),
2773
+ createAdguardGetStatsConfigTool(getClient),
2774
+ createAdguardDhcpStatusTool(getClient),
2775
+ createAdguardDhcpInterfacesTool(getClient),
2776
+ createAdguardTlsStatusTool(getClient),
2777
+ createAdguardSyncStatusTool(getSyncClient),
2778
+ createAdguardSyncHealthTool(getSyncClient),
2779
+ createAdguardSyncLogsTool(getSyncClient),
2780
+ // Tier 2: safe writes (confirm: true)
2781
+ createAdguardAddUserRuleTool(getClient),
2782
+ createAdguardRemoveUserRuleTool(getClient),
2783
+ createAdguardAddFilterListTool(getClient),
2784
+ createAdguardRemoveFilterListTool(getClient),
2785
+ createAdguardToggleFilterListTool(getClient),
2786
+ createAdguardSetClientBlockedServicesTool(getClient),
2787
+ createAdguardRefreshFilterListsTool(getClient),
2788
+ createAdguardAddClientTool(getClient),
2789
+ createAdguardUpdateClientTool(getClient),
2790
+ createAdguardSetBlockedServicesTool(getClient),
2791
+ createAdguardToggleSafesearchTool(getClient),
2792
+ createAdguardToggleSafebrowsingTool(getClient),
2793
+ createAdguardAddRewriteTool(getClient),
2794
+ createAdguardUpdateRewriteTool(getClient),
2795
+ createAdguardDeleteRewriteTool(getClient),
2796
+ createAdguardToggleRewritesTool(getClient),
2797
+ createAdguardSetAccessListTool(getClient),
2798
+ createAdguardUpdateQuerylogConfigTool(getClient),
2799
+ createAdguardUpdateStatsConfigTool(getClient),
2800
+ createAdguardValidateTlsConfigTool(getClient),
2801
+ createAdguardTestUpstreamDnsTool(getClient),
2802
+ createAdguardSyncRunTool(getSyncClient),
2803
+ // Tier 3: destructive (confirm: true + destructive: true)
2804
+ createAdguardReplaceUserRulesTool(getClient),
2805
+ createAdguardToggleProtectionTool(getClient),
2806
+ createAdguardDeleteClientTool(getClient),
2807
+ createAdguardClearQueryLogTool(getClient),
2808
+ createAdguardResetStatsTool(getClient),
2809
+ createAdguardSyncClearLogsTool(getSyncClient)
2810
+ ];
2811
+ }
2812
+ var init_tools = __esm({
2813
+ "src/tools/index.ts"() {
2814
+ "use strict";
2815
+ init_adguard_status();
2816
+ init_adguard_stats();
2817
+ init_adguard_query_log();
2818
+ init_adguard_list_filter_lists();
2819
+ init_adguard_list_user_rules();
2820
+ init_adguard_list_clients();
2821
+ init_adguard_list_blocked_services_catalog();
2822
+ init_adguard_add_user_rule();
2823
+ init_adguard_remove_user_rule();
2824
+ init_adguard_add_filter_list();
2825
+ init_adguard_remove_filter_list();
2826
+ init_adguard_toggle_filter_list();
2827
+ init_adguard_set_client_blocked_services();
2828
+ init_adguard_replace_user_rules();
2829
+ init_adguard_toggle_protection();
2830
+ init_adguard_check_host();
2831
+ init_adguard_get_blocked_services();
2832
+ init_adguard_get_dns_config();
2833
+ init_adguard_get_safesearch_settings();
2834
+ init_adguard_refresh_filter_lists();
2835
+ init_adguard_add_client();
2836
+ init_adguard_update_client();
2837
+ init_adguard_set_blocked_services();
2838
+ init_adguard_toggle_safesearch();
2839
+ init_adguard_toggle_safebrowsing();
2840
+ init_adguard_delete_client();
2841
+ init_adguard_clear_query_log();
2842
+ init_adguard_reset_stats();
2843
+ init_adguard_list_rewrites();
2844
+ init_adguard_add_rewrite();
2845
+ init_adguard_update_rewrite();
2846
+ init_adguard_delete_rewrite();
2847
+ init_adguard_get_rewrite_settings();
2848
+ init_adguard_toggle_rewrites();
2849
+ init_adguard_get_access_list();
2850
+ init_adguard_set_access_list();
2851
+ init_adguard_get_querylog_config();
2852
+ init_adguard_update_querylog_config();
2853
+ init_adguard_get_stats_config();
2854
+ init_adguard_update_stats_config();
2855
+ init_adguard_dhcp_status();
2856
+ init_adguard_dhcp_interfaces();
2857
+ init_adguard_tls_status();
2858
+ init_adguard_validate_tls_config();
2859
+ init_adguard_test_upstream_dns();
2860
+ init_adguard_sync_status();
2861
+ init_adguard_sync_health();
2862
+ init_adguard_sync_logs();
2863
+ init_adguard_sync_run();
2864
+ init_adguard_sync_clear_logs();
2865
+ }
2866
+ });
2867
+
2868
+ // src/server.ts
2869
+ import { Buffer as Buffer2 } from "buffer";
2870
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2871
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
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);
2881
+ for (const inst of Object.values(cfg.instances)) {
2882
+ registerSecret(inst.password);
2883
+ const basicValue = "Basic " + Buffer2.from(`${inst.username}:${inst.password}`).toString("base64");
2884
+ registerSecret(basicValue);
2885
+ }
2886
+ const syncCfg = resolveSyncConfig(env);
2887
+ if (syncCfg?.password) {
2888
+ registerSecret(syncCfg.password);
2889
+ if (syncCfg.username) {
2890
+ const basicValue = "Basic " + Buffer2.from(`${syncCfg.username}:${syncCfg.password}`).toString("base64");
2891
+ registerSecret(basicValue);
2892
+ }
2893
+ }
2894
+ const timeoutMs = resolveRequestTimeoutMs(env);
2895
+ const getClient = (name) => new AdGuardClient(getInstanceConfig(cfg, name), { timeoutMs });
2896
+ const getSyncClient = () => new AdGuardSyncClient(getSyncConfig(syncCfg), { timeoutMs });
2897
+ const tools = buildAllTools(getClient, getSyncClient);
2898
+ const toolMap = new Map(tools.map((t) => [t.name, t]));
2899
+ const server = new Server({ name: "adguard-mcp", version: "0.3.2" }, { capabilities: { tools: {} } });
2900
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
2901
+ tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
2902
+ }));
2903
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
2904
+ const t = toolMap.get(req.params.name);
2905
+ if (!t) {
2906
+ return mcpToolError(`unknown tool: ${req.params.name}`);
2907
+ }
2908
+ try {
2909
+ return await t.execute(req.params.name, req.params.arguments ?? {});
2910
+ } catch (e) {
2911
+ return mcpToolError(redact(operatorErrorMessage(e)));
2912
+ }
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();
3170
+ const transport = new StdioServerTransport();
3171
+ const __send = transport.send.bind(transport);
3172
+ transport.send = (message) => {
3173
+ const listed = message?.result?.tools;
3174
+ if (Array.isArray(listed)) {
3175
+ for (const t of listed) {
3176
+ if (t?.inputSchema) delete t.inputSchema.$schema;
3177
+ if (t?.outputSchema) delete t.outputSchema.$schema;
3178
+ }
3179
+ }
3180
+ return __send(message);
3181
+ };
3182
+ await server.connect(transport);
3183
+ }
3184
+ var isEntrypoint;
3185
+ var init_mcp_server = __esm({
3186
+ "mcp-server.ts"() {
3187
+ "use strict";
3188
+ init_dist();
3189
+ init_server();
3190
+ isEntrypoint = (() => {
3191
+ const arg = process.argv[1];
3192
+ if (typeof arg !== "string") return false;
3193
+ try {
3194
+ return import.meta.url === pathToFileURL(realpathSync(arg)).href;
3195
+ } catch {
3196
+ return false;
3197
+ }
3198
+ })();
3199
+ if (isEntrypoint) {
3200
+ const start2 = process.argv.includes("--http") ? Promise.resolve().then(() => (init_http(), http_exports)).then(({ startHttpServer: startHttpServer2 }) => startHttpServer2()) : startServer();
3201
+ start2.catch((error) => {
3202
+ console.error(`adguard-mcp fatal: ${operatorErrorMessage(error)}`);
3203
+ process.exit(1);
3204
+ });
3205
+ }
3206
+ }
3207
+ });
3208
+
3209
+ // mcp-bin.ts
3210
+ var start = process.argv.includes("--http") ? Promise.resolve().then(() => (init_http(), http_exports)).then(({ startHttpServer: startHttpServer2 }) => startHttpServer2()) : Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports)).then(({ startServer: startServer2 }) => startServer2());
3211
+ start.catch((error) => {
3212
+ const msg = error instanceof Error ? error.message : String(error);
3213
+ console.error(`adguard-mcp fatal: ${msg}`);
3214
+ process.exit(1);
3215
+ });