@teamnetwork-nz/sonicwall-api-mcp-server 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +5 -2
  2. package/dist/index.js +306 -312
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -4,15 +4,18 @@ A [Model Context Protocol](https://modelcontextprotocol.io/) server that provide
4
4
 
5
5
  ## Features
6
6
 
7
- - **Log analysis** — retrieve, filter, and search event logs, traffic logs, and threat/IPS events
7
+ - **Log analysis** — retrieve, filter, and search event logs and threat/IPS events
8
8
  - **Address objects & groups** — CRUD for IPv4, IPv6, FQDN, and MAC address objects and their groups
9
9
  - **Service objects & groups** — CRUD for protocol/port service definitions
10
10
  - **Access rules** — create, update, enable/disable, and delete firewall access rules (IPv4 & IPv6)
11
11
  - **NAT policies** — full CRUD for inbound/outbound NAT rules
12
12
  - **Security policies** — CRUD for zone-based security policies
13
- - **GeoIP filtering** — manage GeoIP country-block policies and assign them to access rules
13
+ - **Network discovery** — list zones, interfaces, schedules, and route policies (read-only)
14
+ - **GeoIP lookup** — identify the country/botnet classification of an IP address
14
15
  - **Config management** — view and commit (or discard) staged changes
15
16
 
17
+ > The SonicOS REST API is configuration-focused. Connection/flow ("traffic") logs and GeoIP *policy* objects are not exposed as REST endpoints and therefore have no tools.
18
+
16
19
  Supports SonicOS 6.5.x, 7.x, and 8.x with automatic version detection.
17
20
 
18
21
  ## Quick Start
package/dist/index.js CHANGED
@@ -95,29 +95,28 @@ function md5(s) {
95
95
  function sha256(s) {
96
96
  return (0, import_crypto.createHash)("sha256").update(s).digest("hex");
97
97
  }
98
- function parseDigestChallenge(header) {
99
- const params = {};
100
- for (const m of header.matchAll(/(\w+)="([^"]+)"/g)) {
101
- params[m[1]] = m[2];
102
- }
103
- for (const m of header.matchAll(/(\w+)=([^",\s]+)/g)) {
104
- if (!params[m[1]]) params[m[1]] = m[2];
98
+ function parseAuthenticateHeader(value) {
99
+ const segments = value.split(/,\s*(?=Digest\s)/i).filter((s) => /^\s*Digest\s/i.test(s)).map((s) => s.replace(/^\s*Digest\s+/i, ""));
100
+ const challenges = [];
101
+ for (const seg of segments) {
102
+ const params = {};
103
+ for (const m of seg.matchAll(/(\w+)="([^"]*)"/g)) params[m[1]] = m[2];
104
+ for (const m of seg.matchAll(/(\w+)=([^",\s]+)/g)) if (!(m[1] in params)) params[m[1]] = m[2];
105
+ if (params.realm && params.nonce) {
106
+ challenges.push({
107
+ realm: params.realm,
108
+ nonce: params.nonce,
109
+ qop: params.qop,
110
+ opaque: params.opaque,
111
+ algorithm: params.algorithm ?? "MD5"
112
+ });
113
+ }
105
114
  }
106
- return params;
115
+ return challenges;
107
116
  }
108
- function buildDigestHeader(method, uri, username, password, challenge) {
109
- const { realm, nonce, qop } = challenge;
110
- const algo = (challenge.algorithm ?? "MD5").toUpperCase();
111
- const hash = algo === "SHA-256" ? sha256 : md5;
112
- const nc = "00000001";
113
- const cnonce = Math.random().toString(36).substring(2, 10);
114
- const ha1 = hash(`${username}:${realm}:${password}`);
115
- const ha2 = hash(`${method}:${uri}`);
116
- const response = qop === "auth" ? hash(`${ha1}:${nonce}:${nc}:${cnonce}:auth:${ha2}`) : hash(`${ha1}:${nonce}:${ha2}`);
117
- let h = `Digest username="${username}", realm="${realm}", nonce="${nonce}", uri="${uri}", response="${response}"`;
118
- if (qop === "auth") h += `, qop=auth, nc=${nc}, cnonce="${cnonce}"`;
119
- if (algo !== "MD5") h += `, algorithm=${algo}`;
120
- return h;
117
+ function selectChallenge(challenges) {
118
+ if (challenges.length === 0) return null;
119
+ return challenges.find((c) => c.algorithm.toUpperCase().startsWith("SHA-256")) ?? challenges[0];
121
120
  }
122
121
  var AuthManager = class {
123
122
  constructor(username, password) {
@@ -126,16 +125,21 @@ var AuthManager = class {
126
125
  }
127
126
  username;
128
127
  password;
129
- token = null;
128
+ challenge = null;
129
+ nc = 0;
130
+ bearerToken = null;
131
+ // some firmware returns one in the body
132
+ loggedIn = false;
130
133
  lastUsed = 0;
131
134
  pending = null;
132
135
  isStale() {
133
- return !this.token || Date.now() - this.lastUsed > REAUTH_AFTER;
136
+ return !this.loggedIn || Date.now() - this.lastUsed > REAUTH_AFTER;
134
137
  }
135
- async ensureAuthenticated(baseUrl) {
138
+ /** Ensure a POST /auth session has been established (and is fresh). */
139
+ async ensureLoggedIn(baseUrl) {
136
140
  if (!this.isStale()) {
137
141
  this.lastUsed = Date.now();
138
- return this.token;
142
+ return;
139
143
  }
140
144
  if (!this.pending) {
141
145
  this.pending = this._doLogin(baseUrl).finally(() => {
@@ -143,84 +147,114 @@ var AuthManager = class {
143
147
  });
144
148
  }
145
149
  await this.pending;
146
- return this.token;
150
+ }
151
+ /**
152
+ * Authorization header for an individual request. Returns null if we have no
153
+ * cached challenge yet (the caller should send the request, capture the 401
154
+ * challenge via updateChallenge, then retry).
155
+ */
156
+ authHeader(method, uri) {
157
+ if (this.bearerToken) return `Bearer ${this.bearerToken}`;
158
+ if (this.challenge) return this._buildDigest(method, uri);
159
+ return null;
160
+ }
161
+ /** Absorb a fresh challenge from a 401 response. Returns true if usable. */
162
+ updateChallenge(wwwAuthenticate) {
163
+ if (!wwwAuthenticate) return false;
164
+ const next = selectChallenge(parseAuthenticateHeader(wwwAuthenticate));
165
+ if (!next) return false;
166
+ this.challenge = next;
167
+ this.nc = 0;
168
+ return true;
147
169
  }
148
170
  invalidate() {
149
- this.token = null;
171
+ this.loggedIn = false;
150
172
  this.lastUsed = 0;
151
173
  }
174
+ touch() {
175
+ this.lastUsed = Date.now();
176
+ }
152
177
  async logout(baseUrl) {
153
- if (!this.token) return;
178
+ if (!this.loggedIn) return;
154
179
  try {
155
180
  const headers = { "Accept": "application/json" };
156
- if (this.token !== "_cookie_session_") {
157
- headers["Authorization"] = `Bearer ${this.token}`;
158
- }
181
+ const auth = this.authHeader("DELETE", new URL(`${baseUrl}/auth`).pathname);
182
+ if (auth) headers["Authorization"] = auth;
159
183
  await fetch(`${baseUrl}/auth`, { method: "DELETE", headers });
160
184
  } catch {
161
185
  } finally {
162
- this.token = null;
186
+ this.challenge = null;
187
+ this.bearerToken = null;
188
+ this.loggedIn = false;
163
189
  this.lastUsed = 0;
164
190
  }
165
191
  }
192
+ _buildDigest(method, uri) {
193
+ const c = this.challenge;
194
+ const algo = c.algorithm.toUpperCase();
195
+ const sess = algo.endsWith("-SESS");
196
+ const hash = algo.startsWith("SHA-256") ? sha256 : md5;
197
+ this.nc += 1;
198
+ const ncHex = this.nc.toString(16).padStart(8, "0");
199
+ const cnonce = (0, import_crypto.randomBytes)(8).toString("hex");
200
+ let ha1 = hash(`${this.username}:${c.realm}:${this.password}`);
201
+ if (sess) ha1 = hash(`${ha1}:${c.nonce}:${cnonce}`);
202
+ const ha2 = hash(`${method}:${uri}`);
203
+ const response = c.qop ? hash(`${ha1}:${c.nonce}:${ncHex}:${cnonce}:${c.qop}:${ha2}`) : hash(`${ha1}:${c.nonce}:${ha2}`);
204
+ let h = `Digest username="${this.username}", realm="${c.realm}", nonce="${c.nonce}", uri="${uri}", response="${response}", algorithm=${c.algorithm}`;
205
+ if (c.qop) h += `, qop=${c.qop}, nc=${ncHex}, cnonce="${cnonce}"`;
206
+ if (c.opaque) h += `, opaque="${c.opaque}"`;
207
+ return h;
208
+ }
166
209
  async _doLogin(baseUrl) {
167
210
  const url = `${baseUrl}/auth`;
168
- const path = new URL(url).pathname;
169
- try {
170
- const challenge = await this._getDigestChallenge(url);
171
- if (challenge) {
172
- const authHeader = buildDigestHeader("POST", path, this.username, this.password, challenge);
173
- const resp2 = await fetch(url, {
174
- method: "POST",
175
- headers: {
176
- "Authorization": authHeader,
177
- "Accept": "application/json",
178
- "Content-Type": "application/json"
179
- },
180
- body: "{}"
181
- });
182
- if (resp2.status !== 401) {
183
- await this._handleLoginResponse(resp2, url);
184
- return;
185
- }
186
- }
187
- } catch (e) {
188
- if (e instanceof AuthenticationError || e instanceof SessionConflictError) throw e;
189
- }
190
- const basicCreds = Buffer.from(`${this.username}:${this.password}`).toString("base64");
191
- let resp;
211
+ const uri = new URL(url).pathname;
212
+ let challengeResp;
192
213
  try {
193
- resp = await fetch(url, {
214
+ challengeResp = await fetch(url, {
194
215
  method: "POST",
195
- headers: {
196
- "Authorization": `Basic ${basicCreds}`,
197
- "Accept": "application/json",
198
- "Content-Type": "application/json"
199
- },
216
+ headers: { "Accept": "application/json", "Content-Type": "application/json" },
200
217
  body: "{}"
201
218
  });
202
219
  } catch (e) {
203
220
  throw new AuthenticationError(`Cannot connect to ${url}: ${e.message}`);
204
221
  }
205
- await this._handleLoginResponse(resp, url);
206
- }
207
- async _getDigestChallenge(url) {
208
- let resp;
209
- try {
210
- resp = await fetch(url, {
222
+ if (challengeResp.status < 400) {
223
+ await this._handleLoginResponse(challengeResp);
224
+ return;
225
+ }
226
+ const haveChallenge = this.updateChallenge(challengeResp.headers.get("WWW-Authenticate"));
227
+ if (haveChallenge) {
228
+ const resp2 = await fetch(url, {
211
229
  method: "POST",
212
- headers: { "Accept": "application/json", "Content-Type": "application/json" },
230
+ headers: {
231
+ "Authorization": this._buildDigest("POST", uri),
232
+ "Accept": "application/json",
233
+ "Content-Type": "application/json"
234
+ },
213
235
  body: "{}"
214
236
  });
215
- } catch {
216
- return null;
237
+ if (resp2.status !== 401) {
238
+ await this._handleLoginResponse(resp2);
239
+ return;
240
+ }
241
+ throw new AuthenticationError(
242
+ "Digest authentication rejected. Verify the username/password and that the account has SonicOS API access."
243
+ );
217
244
  }
218
- if (resp.status !== 401) return null;
219
- const wwwAuth = resp.headers.get("WWW-Authenticate") ?? "";
220
- if (!wwwAuth.startsWith("Digest ")) return null;
221
- return parseDigestChallenge(wwwAuth);
245
+ const basic = Buffer.from(`${this.username}:${this.password}`).toString("base64");
246
+ const resp = await fetch(url, {
247
+ method: "POST",
248
+ headers: {
249
+ "Authorization": `Basic ${basic}`,
250
+ "Accept": "application/json",
251
+ "Content-Type": "application/json"
252
+ },
253
+ body: "{}"
254
+ });
255
+ await this._handleLoginResponse(resp);
222
256
  }
223
- async _handleLoginResponse(resp, url) {
257
+ async _handleLoginResponse(resp) {
224
258
  if (resp.status === 403) {
225
259
  throw new SessionConflictError(
226
260
  "Another admin session is currently active on this SonicWall appliance. Log out from the management UI or wait for the existing session to expire."
@@ -233,19 +267,20 @@ var AuthManager = class {
233
267
  const text = await resp.text().catch(() => "");
234
268
  throw new AuthenticationError(`Login failed with HTTP ${resp.status}: ${text.slice(0, 200)}`);
235
269
  }
236
- let token = null;
237
270
  try {
238
271
  const body = await resp.json();
239
272
  const status = body.status;
240
273
  const info = status?.info;
274
+ let token = null;
241
275
  if (Array.isArray(info) && info.length > 0) {
242
276
  token = info[0].bearer_token ?? null;
243
277
  } else if (info && typeof info === "object") {
244
278
  token = info.bearer_token ?? null;
245
279
  }
280
+ if (token) this.bearerToken = token;
246
281
  } catch {
247
282
  }
248
- this.token = token ?? "_cookie_session_";
283
+ this.loggedIn = true;
249
284
  this.lastUsed = Date.now();
250
285
  }
251
286
  };
@@ -303,6 +338,23 @@ var SonicWallClient = class {
303
338
  [`https://${host}:${port}/api/sonicos/v8`, 8],
304
339
  [`https://${host}:${port}/api/sonicos`, 7]
305
340
  ];
341
+ for (const [base, version] of candidates) {
342
+ try {
343
+ const resp = await fetch(`${base}/auth`, {
344
+ method: "POST",
345
+ headers: { "Accept": "application/json", "Content-Type": "application/json" },
346
+ body: "{}",
347
+ signal: AbortSignal.timeout(this.profile.requestTimeout * 1e3)
348
+ });
349
+ if (resp.status < 400 || resp.headers.get("WWW-Authenticate")) {
350
+ this.baseUrl = base;
351
+ this.version = version;
352
+ return;
353
+ }
354
+ } catch {
355
+ continue;
356
+ }
357
+ }
306
358
  for (const [base, version] of candidates) {
307
359
  try {
308
360
  const resp = await fetch(`${base}/system/status`, {
@@ -318,10 +370,8 @@ var SonicWallClient = class {
318
370
  continue;
319
371
  }
320
372
  }
321
- if (!this.baseUrl) {
322
- this.baseUrl = `https://${host}:${port}/api/sonicos`;
323
- this.version = 7;
324
- }
373
+ this.baseUrl = `https://${host}:${port}/api/sonicos`;
374
+ this.version = 7;
325
375
  }
326
376
  async close() {
327
377
  await this.auth.logout(this.baseUrl);
@@ -337,38 +387,37 @@ var SonicWallClient = class {
337
387
  );
338
388
  url += `?${qs}`;
339
389
  }
340
- const makeHeaders = async () => {
341
- const token = await this.auth.ensureAuthenticated(this.baseUrl);
342
- const headers2 = {
390
+ const u = new URL(url);
391
+ const target = u.pathname + u.search;
392
+ const m = method.toUpperCase();
393
+ await this.auth.ensureLoggedIn(this.baseUrl);
394
+ const buildHeaders = () => {
395
+ const headers = {
343
396
  "Accept": "application/json",
344
397
  "Content-Type": "application/json"
345
398
  };
346
- if (token && token !== "_cookie_session_") {
347
- headers2["Authorization"] = `Bearer ${token}`;
348
- }
349
- return headers2;
399
+ const auth = this.auth.authHeader(m, target);
400
+ if (auth) headers["Authorization"] = auth;
401
+ return headers;
350
402
  };
351
- let headers = await makeHeaders();
352
403
  for (let attempt = 0; attempt < 2; attempt++) {
353
- let resp;
354
- try {
355
- resp = await fetchWithRetry(url, {
356
- method,
357
- headers,
358
- body: options?.body !== void 0 ? JSON.stringify(options.body) : void 0,
359
- signal: AbortSignal.timeout(this.profile.requestTimeout * 1e3)
360
- });
361
- } catch (e) {
362
- throw e;
363
- }
404
+ const resp = await fetchWithRetry(url, {
405
+ method,
406
+ headers: buildHeaders(),
407
+ body: options?.body !== void 0 ? JSON.stringify(options.body) : void 0,
408
+ signal: AbortSignal.timeout(this.profile.requestTimeout * 1e3)
409
+ });
364
410
  if (resp.status === 401 && attempt === 0) {
365
- this.auth.invalidate();
366
- headers = await makeHeaders();
411
+ if (!this.auth.updateChallenge(resp.headers.get("WWW-Authenticate"))) {
412
+ this.auth.invalidate();
413
+ await this.auth.ensureLoggedIn(this.baseUrl);
414
+ }
367
415
  continue;
368
416
  }
369
417
  if (resp.status >= 400) {
370
418
  await this._throwApiError(resp);
371
419
  }
420
+ this.auth.touch();
372
421
  const text = await resp.text();
373
422
  return text ? JSON.parse(text) : {};
374
423
  }
@@ -485,7 +534,7 @@ function registerSystemTools(server, registry) {
485
534
  async ({ device }) => {
486
535
  try {
487
536
  const client = await registry.getClient(device);
488
- const result = await client.get("system/status");
537
+ const result = await client.get("version");
489
538
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
490
539
  } catch (e) {
491
540
  return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
@@ -1658,159 +1707,6 @@ function parseGeoLookup(ip, raw) {
1658
1707
  return parsed;
1659
1708
  }
1660
1709
  function registerGeoIpTools(server, registry) {
1661
- server.tool(
1662
- "list_geo_ip_policies",
1663
- "List all GeoIP filtering policies configured on the appliance.",
1664
- { device: import_zod9.z.string().optional() },
1665
- async ({ device }) => {
1666
- try {
1667
- const client = await registry.getClient(device);
1668
- const result = await client.get("geo-ip/policies");
1669
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1670
- } catch (e) {
1671
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1672
- }
1673
- }
1674
- );
1675
- server.tool(
1676
- "get_geo_ip_policy",
1677
- "Retrieve a GeoIP policy by name.",
1678
- { name: import_zod9.z.string(), device: import_zod9.z.string().optional() },
1679
- async ({ name, device }) => {
1680
- try {
1681
- const client = await registry.getClient(device);
1682
- const result = await client.get(`geo-ip/policies/name/${name}`);
1683
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1684
- } catch (e) {
1685
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1686
- }
1687
- }
1688
- );
1689
- server.tool(
1690
- "create_geo_ip_policy",
1691
- "Create a GeoIP filtering policy. block_countries/allow_countries: lists of ISO 3166-1 alpha-2 country codes (e.g. ['CN', 'RU', 'KP']). Changes are STAGED; call commit_config to apply.",
1692
- {
1693
- name: import_zod9.z.string(),
1694
- block_countries: import_zod9.z.array(import_zod9.z.string()).optional(),
1695
- allow_countries: import_zod9.z.array(import_zod9.z.string()).optional(),
1696
- log: import_zod9.z.boolean().optional().default(true),
1697
- device: import_zod9.z.string().optional()
1698
- },
1699
- async ({ name, block_countries, allow_countries, log, device }) => {
1700
- try {
1701
- const client = await registry.getClient(device);
1702
- const policy = { name, log };
1703
- if (block_countries && block_countries.length > 0) {
1704
- policy.block_countries = block_countries.map((c) => ({ country: c.toUpperCase() }));
1705
- }
1706
- if (allow_countries && allow_countries.length > 0) {
1707
- policy.allow_countries = allow_countries.map((c) => ({ country: c.toUpperCase() }));
1708
- }
1709
- const result = await client.post("geo-ip/policies", { geo_ip_policies: [policy] });
1710
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1711
- } catch (e) {
1712
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1713
- }
1714
- }
1715
- );
1716
- server.tool(
1717
- "update_geo_ip_policy",
1718
- "Update a GeoIP policy (GET-then-PUT). Only supplied fields are changed. Providing an empty list clears that list. Changes are STAGED; call commit_config to apply.",
1719
- {
1720
- name: import_zod9.z.string(),
1721
- block_countries: import_zod9.z.array(import_zod9.z.string()).optional(),
1722
- allow_countries: import_zod9.z.array(import_zod9.z.string()).optional(),
1723
- log: import_zod9.z.boolean().optional(),
1724
- device: import_zod9.z.string().optional()
1725
- },
1726
- async ({ name, block_countries, allow_countries, log, device }) => {
1727
- try {
1728
- const client = await registry.getClient(device);
1729
- const current = await client.get(`geo-ip/policies/name/${name}`);
1730
- const policies = current.geo_ip_policies;
1731
- const policy = policies?.[0] ?? {};
1732
- if (block_countries !== void 0) {
1733
- policy.block_countries = block_countries.map((c) => ({ country: c.toUpperCase() }));
1734
- }
1735
- if (allow_countries !== void 0) {
1736
- policy.allow_countries = allow_countries.map((c) => ({ country: c.toUpperCase() }));
1737
- }
1738
- if (log !== void 0) policy.log = log;
1739
- const result = await client.put(`geo-ip/policies/name/${name}`, { geo_ip_policies: [policy] });
1740
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1741
- } catch (e) {
1742
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1743
- }
1744
- }
1745
- );
1746
- server.tool(
1747
- "delete_geo_ip_policy",
1748
- "Delete a GeoIP policy by name. Changes are STAGED; call commit_config to apply.",
1749
- { name: import_zod9.z.string(), device: import_zod9.z.string().optional() },
1750
- async ({ name, device }) => {
1751
- try {
1752
- const client = await registry.getClient(device);
1753
- const result = await client.delete(`geo-ip/policies/name/${name}`);
1754
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1755
- } catch (e) {
1756
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1757
- }
1758
- }
1759
- );
1760
- server.tool(
1761
- "list_geo_ip_countries",
1762
- "Return all country codes and names available for GeoIP filtering.",
1763
- { device: import_zod9.z.string().optional() },
1764
- async ({ device }) => {
1765
- try {
1766
- const client = await registry.getClient(device);
1767
- const result = await client.get("geo-ip/countries");
1768
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1769
- } catch (e) {
1770
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1771
- }
1772
- }
1773
- );
1774
- server.tool(
1775
- "get_geo_ip_stats",
1776
- "Return GeoIP statistics \u2014 connection counts blocked/allowed by country.",
1777
- { device: import_zod9.z.string().optional() },
1778
- async ({ device }) => {
1779
- try {
1780
- const client = await registry.getClient(device);
1781
- const result = await client.get("geo-ip/statistics");
1782
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1783
- } catch (e) {
1784
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1785
- }
1786
- }
1787
- );
1788
- server.tool(
1789
- "assign_geo_ip_to_rule",
1790
- "Attach a GeoIP policy to an existing access rule without changing any other rule fields. Changes are STAGED; call commit_config to apply.",
1791
- {
1792
- rule_id: import_zod9.z.number(),
1793
- geo_ip_policy_name: import_zod9.z.string(),
1794
- ip_version: import_zod9.z.enum(["ipv4", "ipv6"]).optional().default("ipv4"),
1795
- device: import_zod9.z.string().optional()
1796
- },
1797
- async ({ rule_id, geo_ip_policy_name, ip_version, device }) => {
1798
- try {
1799
- const client = await registry.getClient(device);
1800
- const current = await client.get(`access-rules/${ip_version}/${rule_id}`);
1801
- const rules = current.access_rules;
1802
- const rule = rules?.[0]?.[ip_version] ?? {};
1803
- if (!rule.security_profile) rule.security_profile = {};
1804
- rule.security_profile.geo_ip_policy = { name: geo_ip_policy_name };
1805
- const result = await client.put(`access-rules/${ip_version}/${rule_id}`, {
1806
- access_rules: [{ [ip_version]: rule }]
1807
- });
1808
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1809
- } catch (e) {
1810
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1811
- }
1812
- }
1813
- );
1814
1710
  server.tool(
1815
1711
  "lookup_ip_country",
1816
1712
  "Look up the geographic location of an IP address using the appliance's built-in GeoIP database. Returns country, city, region, and botnet classification if available. Requires an active GeoIP subscription.",
@@ -1830,23 +1726,22 @@ function registerGeoIpTools(server, registry) {
1830
1726
 
1831
1727
  // src/tools/logs.ts
1832
1728
  var import_zod10 = require("zod");
1833
- function logPath(version, subpath) {
1834
- return version >= 8 ? `log/${subpath}` : `reporting/${subpath}`;
1835
- }
1836
- async function getLogsWithFallback(client, subpathV7, subpathV8, params) {
1837
- const isPrimary = client.version >= 8;
1838
- const primary = logPath(client.version, isPrimary ? subpathV8 : subpathV7);
1839
- const fallbackVersion = isPrimary ? 7 : 8;
1840
- const fallback = logPath(fallbackVersion, isPrimary ? subpathV7 : subpathV8);
1841
- try {
1842
- return await client.get(primary, params);
1843
- } catch (e) {
1844
- if (e instanceof APIError && e.status === 404) {
1845
- return await client.get(fallback, params);
1729
+ async function getLogsWithFallback(client, candidates, params) {
1730
+ let lastErr;
1731
+ for (const path of candidates) {
1732
+ try {
1733
+ return await client.get(path, params);
1734
+ } catch (e) {
1735
+ if (e instanceof APIError && (e.status === 404 || e.status === 400)) {
1736
+ lastErr = e;
1737
+ continue;
1738
+ }
1739
+ throw e;
1846
1740
  }
1847
- throw e;
1848
1741
  }
1742
+ throw lastErr;
1849
1743
  }
1744
+ var EVENT_LOG_PATHS = ["log/events", "reporting/log/events"];
1850
1745
  function registerLogTools(server, registry) {
1851
1746
  server.tool(
1852
1747
  "get_log_categories",
@@ -1855,12 +1750,15 @@ function registerLogTools(server, registry) {
1855
1750
  async ({ device }) => {
1856
1751
  try {
1857
1752
  const client = await registry.getClient(device);
1858
- const path = client.version >= 8 ? "log/categories" : "reporting/log/categories";
1859
1753
  try {
1860
- const result = await client.get(path);
1754
+ const result = await getLogsWithFallback(
1755
+ client,
1756
+ ["log/categories", "reporting/log/categories"],
1757
+ {}
1758
+ );
1861
1759
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1862
1760
  } catch (e) {
1863
- if (e instanceof APIError && e.status === 404) {
1761
+ if (e instanceof APIError && (e.status === 404 || e.status === 400)) {
1864
1762
  const fallback = {
1865
1763
  categories: [
1866
1764
  "network access",
@@ -1910,39 +1808,7 @@ function registerLogTools(server, registry) {
1910
1808
  if (end_time) params.end_time = end_time;
1911
1809
  if (source_ip) params.src_ip = source_ip;
1912
1810
  if (keyword) params.keyword = keyword;
1913
- const result = await getLogsWithFallback(client, "log", "events", params);
1914
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1915
- } catch (e) {
1916
- return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1917
- }
1918
- }
1919
- );
1920
- server.tool(
1921
- "get_traffic_logs",
1922
- "Retrieve traffic/connection logs. count: max entries. source_ip/destination_ip: filter by IP. destination_port: TCP/UDP port. protocol: e.g. 'TCP', 'UDP', 'ICMP'. action: 'allow' or 'deny'.",
1923
- {
1924
- count: import_zod10.z.number().optional().default(100),
1925
- source_ip: import_zod10.z.string().optional(),
1926
- destination_ip: import_zod10.z.string().optional(),
1927
- destination_port: import_zod10.z.number().optional(),
1928
- protocol: import_zod10.z.string().optional(),
1929
- action: import_zod10.z.enum(["allow", "deny"]).optional(),
1930
- start_time: import_zod10.z.string().optional(),
1931
- end_time: import_zod10.z.string().optional(),
1932
- device: import_zod10.z.string().optional()
1933
- },
1934
- async ({ count, source_ip, destination_ip, destination_port, protocol, action, start_time, end_time, device }) => {
1935
- try {
1936
- const client = await registry.getClient(device);
1937
- const params = { count };
1938
- if (source_ip) params.src_ip = source_ip;
1939
- if (destination_ip) params.dst_ip = destination_ip;
1940
- if (destination_port !== void 0) params.dst_port = destination_port;
1941
- if (protocol) params.protocol = protocol;
1942
- if (action) params.action = action;
1943
- if (start_time) params.start_time = start_time;
1944
- if (end_time) params.end_time = end_time;
1945
- const result = await getLogsWithFallback(client, "appflow/connections", "traffic", params);
1811
+ const result = await getLogsWithFallback(client, EVENT_LOG_PATHS, params);
1946
1812
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1947
1813
  } catch (e) {
1948
1814
  return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
@@ -1965,7 +1831,7 @@ function registerLogTools(server, registry) {
1965
1831
  const params = { count, keyword: query };
1966
1832
  if (start_time) params.start_time = start_time;
1967
1833
  if (end_time) params.end_time = end_time;
1968
- const result = await getLogsWithFallback(client, "log", "events", params);
1834
+ const result = await getLogsWithFallback(client, EVENT_LOG_PATHS, params);
1969
1835
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1970
1836
  } catch (e) {
1971
1837
  return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
@@ -1989,7 +1855,128 @@ function registerLogTools(server, registry) {
1989
1855
  if (severity) params.severity = severity;
1990
1856
  if (start_time) params.start_time = start_time;
1991
1857
  if (end_time) params.end_time = end_time;
1992
- const result = await getLogsWithFallback(client, "log", "events", params);
1858
+ const result = await getLogsWithFallback(client, EVENT_LOG_PATHS, params);
1859
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1860
+ } catch (e) {
1861
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1862
+ }
1863
+ }
1864
+ );
1865
+ }
1866
+
1867
+ // src/tools/zones.ts
1868
+ var import_zod11 = require("zod");
1869
+ function registerZoneTools(server, registry) {
1870
+ server.tool(
1871
+ "list_zones",
1872
+ "List all security zones (LAN, WAN, DMZ, etc.) with their security type and interface membership. Use this to discover valid zone names before creating access rules or security policies.",
1873
+ { device: import_zod11.z.string().optional() },
1874
+ async ({ device }) => {
1875
+ try {
1876
+ const client = await registry.getClient(device);
1877
+ const result = await client.get("zones");
1878
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1879
+ } catch (e) {
1880
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1881
+ }
1882
+ }
1883
+ );
1884
+ server.tool(
1885
+ "get_zone",
1886
+ "Retrieve a single security zone by name.",
1887
+ { name: import_zod11.z.string(), device: import_zod11.z.string().optional() },
1888
+ async ({ name, device }) => {
1889
+ try {
1890
+ const client = await registry.getClient(device);
1891
+ const result = await client.get(`zones/name/${encodeURIComponent(name)}`);
1892
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1893
+ } catch (e) {
1894
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1895
+ }
1896
+ }
1897
+ );
1898
+ }
1899
+
1900
+ // src/tools/interfaces.ts
1901
+ var import_zod12 = require("zod");
1902
+ function registerInterfaceTools(server, registry) {
1903
+ server.tool(
1904
+ "list_interfaces",
1905
+ "List IPv4 network interfaces with their IP assignment, zone, and mode (static/DHCP). Use this to discover the appliance's addressing and which interfaces belong to which zone.",
1906
+ { device: import_zod12.z.string().optional() },
1907
+ async ({ device }) => {
1908
+ try {
1909
+ const client = await registry.getClient(device);
1910
+ const result = await client.get("interfaces/ipv4");
1911
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1912
+ } catch (e) {
1913
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1914
+ }
1915
+ }
1916
+ );
1917
+ server.tool(
1918
+ "get_interface",
1919
+ 'Retrieve a single IPv4 interface by name (e.g. "X0").',
1920
+ { name: import_zod12.z.string(), device: import_zod12.z.string().optional() },
1921
+ async ({ name, device }) => {
1922
+ try {
1923
+ const client = await registry.getClient(device);
1924
+ const result = await client.get(`interfaces/ipv4/name/${encodeURIComponent(name)}`);
1925
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1926
+ } catch (e) {
1927
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1928
+ }
1929
+ }
1930
+ );
1931
+ }
1932
+
1933
+ // src/tools/schedules.ts
1934
+ var import_zod13 = require("zod");
1935
+ function registerScheduleTools(server, registry) {
1936
+ server.tool(
1937
+ "list_schedules",
1938
+ 'List schedule objects (recurring time windows like "Work Hours"). Security policies reference schedules by name to restrict when a rule is active \u2014 use this to discover valid schedule names.',
1939
+ { device: import_zod13.z.string().optional() },
1940
+ async ({ device }) => {
1941
+ try {
1942
+ const client = await registry.getClient(device);
1943
+ const result = await client.get("schedules");
1944
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1945
+ } catch (e) {
1946
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1947
+ }
1948
+ }
1949
+ );
1950
+ server.tool(
1951
+ "get_schedule",
1952
+ "Retrieve a single schedule object by name.",
1953
+ { name: import_zod13.z.string(), device: import_zod13.z.string().optional() },
1954
+ async ({ name, device }) => {
1955
+ try {
1956
+ const client = await registry.getClient(device);
1957
+ const result = await client.get(`schedules/name/${encodeURIComponent(name)}`);
1958
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1959
+ } catch (e) {
1960
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1961
+ }
1962
+ }
1963
+ );
1964
+ }
1965
+
1966
+ // src/tools/route-policies.ts
1967
+ var import_zod14 = require("zod");
1968
+ function registerRoutePolicyTools(server, registry) {
1969
+ server.tool(
1970
+ "list_route_policies",
1971
+ "List static/policy-based routes with their destination, gateway, interface, and metric. Useful for understanding how traffic is routed off the appliance.",
1972
+ {
1973
+ ip_version: import_zod14.z.enum(["ipv4", "ipv6"]).optional().default("ipv4"),
1974
+ device: import_zod14.z.string().optional()
1975
+ },
1976
+ async ({ ip_version, device }) => {
1977
+ try {
1978
+ const client = await registry.getClient(device);
1979
+ const result = await client.get(`route-policies/${ip_version}`);
1993
1980
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
1994
1981
  } catch (e) {
1995
1982
  return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
@@ -2017,7 +2004,7 @@ async function main() {
2017
2004
  const registry = new DeviceRegistry(config.profiles);
2018
2005
  const server = new import_mcp.McpServer({
2019
2006
  name: "sonicwall-mcp-server",
2020
- version: "0.4.0",
2007
+ version: "0.5.0",
2021
2008
  instructions: `SonicWall NSA MCP server \u2014 full read/write access to SonicWall firewalls via the SonicOS REST API.
2022
2009
 
2023
2010
  ## Device targeting
@@ -2032,7 +2019,6 @@ All timestamp parameters (start_time, end_time in log tools) are in the applianc
2032
2019
  ## Log querying
2033
2020
  - Call get_log_categories first to discover valid category names for get_event_logs.
2034
2021
  - get_event_logs: general system/security events. Filter by category, priority, source_ip, or keyword.
2035
- - get_traffic_logs: connection/flow logs. Filter by source_ip, destination_ip, port, protocol, or action.
2036
2022
  - get_threat_logs: IPS and AV detections. Filter by severity.
2037
2023
  - search_logs: full-text keyword search across event logs \u2014 use when you have a specific IP, hostname, or error string.
2038
2024
  - Default count is 100. Increase for broader searches, but keep it reasonable to avoid large payloads.
@@ -2043,7 +2029,11 @@ All timestamp parameters (start_time, end_time in log tools) are in the applianc
2043
2029
  - Typical workflow for a new firewall rule: list_address_objects \u2192 create_address_object_ipv4/fqdn/etc if needed \u2192 list_service_objects \u2192 create_service_object if needed \u2192 create_access_rule \u2192 commit_config.
2044
2030
  - Access rules (create_access_rule / list_access_rules) control traffic flow between zones with allow/deny/discard actions. Security policies (create_security_policy / list_security_policies) are zone-based and additionally support user and schedule filtering \u2014 use them when you need user-aware or time-restricted policies.
2045
2031
  - Always call list_access_rules, list_nat_policies, or list_security_policies before modifying, to confirm current state and avoid duplicates.
2046
- - GeoIP policies block or allow traffic by country code (ISO 3166-1 alpha-2). Use list_geo_ip_policies to see current policies, list_geo_ip_countries for all available codes, and lookup_ip_country to identify which country an IP address belongs to.
2032
+ - Rules and policies reference zones and schedules by name: use list_zones and list_schedules to discover valid names. list_interfaces shows interface IP/zone assignments and list_route_policies shows static routing \u2014 both are read-only discovery aids.
2033
+ - lookup_ip_country identifies which country an IP address belongs to (uses the appliance GeoIP database). Note: GeoIP *policy* management is not available via the SonicOS REST API.
2034
+
2035
+ ## Read-only API note
2036
+ The SonicOS REST API is configuration-focused. Connection/flow ("traffic") logs and GeoIP policy objects are not exposed as REST endpoints, so there are no tools for them.
2047
2037
 
2048
2038
  ## Concurrent sessions
2049
2039
  SonicOS allows only ONE concurrent API session per appliance. If a session error occurs, an existing admin or API session may need to be ended first.`
@@ -2058,6 +2048,10 @@ SonicOS allows only ONE concurrent API session per appliance. If a session error
2058
2048
  registerSecurityPolicyTools(server, registry);
2059
2049
  registerGeoIpTools(server, registry);
2060
2050
  registerLogTools(server, registry);
2051
+ registerZoneTools(server, registry);
2052
+ registerInterfaceTools(server, registry);
2053
+ registerScheduleTools(server, registry);
2054
+ registerRoutePolicyTools(server, registry);
2061
2055
  const transport = config.transport;
2062
2056
  if (transport === "stdio") {
2063
2057
  const t = new import_stdio.StdioServerTransport();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/sonicwall-api-mcp-server",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "MCP server for SonicWall NSA appliance API — logs, CRUD objects, rules, NAT, GeoIP",
5
5
  "keywords": [
6
6
  "mcp",