port-scanner-mcp 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,17 +23,18 @@ Scans are bounded to 50 ports per call and 2 seconds per port. Scanning systems
23
23
  <!-- paywall -->
24
24
  ## Premium tools
25
25
 
26
- These tools need a license key:
26
+ These tools need a licence key:
27
27
 
28
28
  * `summarize_scan_results`
29
+ * `network_origin`
29
30
 
30
- Buy a key at https://mcp-marketplace.io/server/io-github-mrfentmen-port-scanner-mcp and set it in your MCP client config:
31
+ The tool bodies run on our gateway, not inside this package, so the key is what buys access. Buy one at https://buy.polar.sh/polar_cl_mrO7rS5LZxpqM7oAFFEA10i9121J240U40IIj4JRZO4 and set it in your MCP client config:
31
32
 
32
33
  ```json
33
- "env": { "MCP_LICENSE_KEY": "mcp_live_..." }
34
+ "env": { "MCP_LICENSE_KEY": "polar_..." }
34
35
  ```
35
36
 
36
- The key is checked against MCP Marketplace, cached for 24 hours, and keeps
37
- working offline once one check has succeeded. Every other tool on this server
37
+ The gateway checks the key against Polar and gives every key 1,000 free premium
38
+ calls a month before per-call billing starts. Every other tool on this server
38
39
  stays free.
39
40
  <!-- /paywall -->
package/dist/api.js CHANGED
@@ -1,55 +1,6 @@
1
- import { connect } from "node:net";
2
1
  const UA = "mrfentmen-port-scanner-mcp/1.0";
3
2
  export class PortError extends Error {
4
3
  }
5
- function check(host, port, timeoutMs) {
6
- return new Promise((resolve) => {
7
- const sock = connect({ host, port });
8
- let done = false;
9
- const finish = (open) => {
10
- if (done)
11
- return;
12
- done = true;
13
- sock.destroy();
14
- resolve(open);
15
- };
16
- sock.setTimeout(timeoutMs);
17
- sock.once("connect", () => finish(true));
18
- sock.once("timeout", () => finish(false));
19
- sock.once("error", () => finish(false));
20
- });
21
- }
22
- export async function scanHost(args) {
23
- const host = (args.host ?? "").trim();
24
- if (!host)
25
- throw new PortError("Provide a host name or IP");
26
- const timeoutMs = Math.min(Math.max(args.timeout_ms ?? 1000, 100), 2000);
27
- const ports = (args.ports ?? "80,443,22,21,25,53,8080,3306,5432,6379")
28
- .split(",").map((p) => parseInt(p.trim(), 10)).filter((p) => p >= 1 && p <= 65535).slice(0, 50);
29
- if (!ports.length)
30
- throw new PortError("Provide a valid port list");
31
- const results = [];
32
- for (const p of ports) {
33
- const open = await check(host, p, timeoutMs);
34
- results.push(`${p}: ${open ? "OPEN" : "closed"}`);
35
- }
36
- return `Scan of ${host}:\n${results.join("\n")}`;
37
- }
38
- export async function scanCommon(args) {
39
- const host = (args.host ?? "").trim();
40
- if (!host)
41
- throw new PortError("Provide a host name or IP");
42
- const common = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 993, 995, 1433, 1521, 3306, 3389, 5432, 5900, 6379, 8080, 8443, 9000, 27017];
43
- const results = [];
44
- for (const p of common) {
45
- const open = await check(host, p, 800);
46
- if (open)
47
- results.push(`${p}: OPEN`);
48
- }
49
- return results.length
50
- ? `Open ports on ${host}:\n${results.join("\n")}`
51
- : `No common ports open on ${host}`;
52
- }
53
4
  // ---- muxB tools:
54
5
  const MAX_PORTS = 4096;
55
6
  const MAX_SPEC = 20000;
@@ -141,57 +92,19 @@ export async function parsePortSpec(args) {
141
92
  out.push(` the scan_host ports field holds the full list; ${accepted.length} ports is ${Math.ceil(accepted.length / 10)} times the 50 port cap in one call`);
142
93
  return out.join("\n");
143
94
  }
144
- export async function summarizeScanResults(args) {
145
- const report = args.report ?? "";
146
- if (!report.trim())
147
- throw new Error("Paste a scan report into report to summarise");
148
- if (report.length > MAX_REPORT)
149
- throw new Error(`Keep report under ${MAX_REPORT} characters`);
150
- const counts = Object.fromEntries(STATES.map((state) => [state, 0]));
151
- const open = [];
152
- const all = [];
153
- let parsed = 0;
154
- let ignored = 0;
155
- for (const line of report.split(/\r?\n/)) {
156
- const match = /(?:^|\s)(\d{1,5})\s*[:=\-]?\s*(open|closed|filtered|timeout|refused|unreachable)\b/i.exec(line);
157
- if (!match) {
158
- if (line.trim())
159
- ignored += 1;
160
- continue;
161
- }
162
- const port = Number(match[1]);
163
- if (port < 1 || port > 65535) {
164
- ignored += 1;
165
- continue;
166
- }
167
- const state = match[2].toLowerCase();
168
- counts[state] += 1;
169
- parsed += 1;
170
- all.push(port);
171
- if (state === "open")
172
- open.push(port);
173
- }
174
- const out = [];
175
- out.push(`Scan report summary (${report.length} characters pasted)`);
176
- if (!parsed) {
177
- out.push(`${pad("Result")}no "port: state" line was recognised, ${ignored} line${ignored === 1 ? "" : "s"} ignored`);
178
- out.push("Expected lines look like \"8080: OPEN\" or \"443 closed\".");
179
- return out.join("\n");
180
- }
181
- const total = parsed;
182
- const openSorted = [...open].sort((a, b) => a - b);
183
- out.push(`${pad("Parsed")}${parsed} port lines, ${ignored} line${ignored === 1 ? "" : "s"} ignored`);
184
- out.push(`${pad("States")}${STATES.filter((state) => counts[state] > 0).map((state) => `${state} ${counts[state]}`).join(" ")}`);
185
- out.push(`${pad("Open ratio")}${((counts.open / total) * 100).toFixed(1)}% of ${total} probed ports answered`);
186
- const runs = runsOf(openSorted);
187
- out.push(`${pad("Open ports")}${openSorted.length ? formatRuns(runs, 30) : "none"}`);
188
- out.push(`${pad("Highest open")}${openSorted.length ? openSorted[openSorted.length - 1] : "not reported - no port answered"}`);
189
- out.push(`${pad("Contiguous runs")}${runs.length} run${runs.length === 1 ? "" : "s"}: ${formatRuns(runs, 12)}`);
190
- const longest = runs.reduce((max, run) => Math.max(max, run[1] - run[0] + 1), 0);
191
- const isolated = runs.filter(([from, to]) => from === to).length;
192
- out.push(`${pad("Pattern")}longest contiguous open run ${longest} port${longest === 1 ? "" : "s"}, ${isolated} isolated open port${isolated === 1 ? "" : "s"}`);
193
- const sorted = [...new Set(all)].sort((a, b) => a - b);
194
- out.push(`${pad("Coverage")}${new Set(all).size} distinct ports probed, spanning ${sorted.length ? `${sorted[0]} to ${sorted[sorted.length - 1]}` : "not reported"}`);
195
- out.push(`${pad("Reading")}${counts.open === 0 ? "nothing answered, so either the host is down or every probed port is filtered" : longest >= 3 ? "a contiguous block answered, which usually means one service listening on a range" : counts.open <= 2 ? "only one or two ports answered, which is a small attack surface" : "several scattered ports answered, worth reviewing individually"}`);
196
- return out.join("\n");
95
+ // ---- gap4a2 tools:
96
+ export async function dnsRecords(args) {
97
+ const name = args.name.trim();
98
+ if (!name || name.length > 253)
99
+ throw new PortError('Provide a DNS name up to 253 characters.');
100
+ const type = (args.type ?? 'A').toUpperCase();
101
+ if (!['A', 'AAAA', 'MX', 'NS', 'TXT', 'CNAME', 'SOA', 'PTR', 'CAA'].includes(type))
102
+ throw new PortError('Unsupported DNS record type.');
103
+ const limit = Math.max(1, Math.min(Math.trunc(args.limit ?? 10), 30));
104
+ const query = new URLSearchParams({ name, type });
105
+ const res = await fetch(`https://dns.google/resolve?${query}`, { headers: { 'User-Agent': UA, Accept: 'application/json' }, signal: AbortSignal.timeout(20000) });
106
+ if (!res.ok)
107
+ throw new PortError(`Google Public DNS returned ${res.status}`);
108
+ const d = await res.json();
109
+ return [`DNS ${type} records for ${name} | response code ${d.Status ?? 'not reported'} | authenticated data ${d.AD === true ? 'yes' : d.AD === false ? 'no' : 'not reported'}`, ...(d.Answer?.length ? d.Answer.slice(0, limit).map(r => `${(r.name ?? 'not reported').slice(0, 253)} | type ${r.type ?? 'not reported'} | TTL ${r.TTL ?? 'not reported'} seconds | ${(r.data ?? 'not reported').slice(0, 500)}`) : ['No answer records reported.'])].join('\n');
197
110
  }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Thin client for the premium gateway.
3
+ *
4
+ * The premium tools do not run in this package any more. Their bodies live on
5
+ * the gateway, which checks a Polar licence key before it does any work, so
6
+ * deleting anything here buys nothing: the answer only exists behind the gate.
7
+ *
8
+ * Set `MCP_LICENSE_KEY` to a Polar licence key. `MCP_GATEWAY_URL` overrides the
9
+ * endpoint, which is only useful for testing.
10
+ */
11
+ const DEFAULT_GATEWAY_URL = 'https://mcp-gateway.contactae2000.workers.dev/mcp';
12
+ const DEFAULT_TIMEOUT_MS = 25000;
13
+ const USER_AGENT = 'mrfentmen-mcp/1.0';
14
+ /** Raised when a premium call cannot be completed. `message` is safe to show. */
15
+ export class GatewayError extends Error {
16
+ refused;
17
+ constructor(message, refused) {
18
+ super(message);
19
+ this.refused = refused;
20
+ this.name = 'GatewayError';
21
+ }
22
+ }
23
+ export async function premiumTool(tool, args) {
24
+ const key = (process.env.MCP_LICENSE_KEY ?? '').trim();
25
+ if (!key) {
26
+ throw new GatewayError(`"${tool}" is a premium tool and no licence key is set. Set MCP_LICENSE_KEY in your MCP client config.`, true);
27
+ }
28
+ const url = (process.env.MCP_GATEWAY_URL ?? DEFAULT_GATEWAY_URL).trim();
29
+ const controller = new AbortController();
30
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
31
+ let response;
32
+ try {
33
+ response = await fetch(url, {
34
+ method: 'POST',
35
+ headers: {
36
+ 'content-type': 'application/json',
37
+ accept: 'application/json',
38
+ 'user-agent': USER_AGENT,
39
+ authorization: `Bearer ${key}`,
40
+ },
41
+ body: JSON.stringify({
42
+ jsonrpc: '2.0',
43
+ id: 1,
44
+ method: 'tools/call',
45
+ params: { name: tool, arguments: args },
46
+ }),
47
+ signal: controller.signal,
48
+ });
49
+ }
50
+ catch {
51
+ throw new GatewayError(`"${tool}" could not reach the licence gateway. Check your connection and try again.`, false);
52
+ }
53
+ finally {
54
+ clearTimeout(timer);
55
+ }
56
+ if (!response.ok) {
57
+ throw new GatewayError(`"${tool}" could not reach the licence gateway (HTTP ${response.status}).`, false);
58
+ }
59
+ let body;
60
+ try {
61
+ body = (await response.json());
62
+ }
63
+ catch {
64
+ throw new GatewayError(`"${tool}" got an unreadable answer from the licence gateway.`, false);
65
+ }
66
+ if (body.error) {
67
+ throw new GatewayError(`"${tool}" was refused by the licence gateway: ${body.error.message ?? 'unknown error'}`, false);
68
+ }
69
+ const result = body.result ?? {};
70
+ const text = (result.content ?? [])
71
+ .map((part) => part.text ?? '')
72
+ .join('\n')
73
+ .trim();
74
+ if (result.isError) {
75
+ // The gateway marks a licence refusal structurally, so a missing or rejected
76
+ // key is told apart from a tool that failed after the gate let it through.
77
+ if (result.structuredContent?.licenceRefusal) {
78
+ throw new GatewayError(text || `"${tool}" needs a valid licence key.`, true);
79
+ }
80
+ throw new GatewayError(text || `"${tool}" failed on the licence gateway.`, false);
81
+ }
82
+ if (!text)
83
+ throw new GatewayError(`"${tool}" returned no data.`, false);
84
+ return text;
85
+ }
package/dist/scan.js ADDED
@@ -0,0 +1,50 @@
1
+ import { connect } from "node:net";
2
+ import { PortError } from "./api.js";
3
+ function check(host, port, timeoutMs) {
4
+ return new Promise((resolve) => {
5
+ const sock = connect({ host, port });
6
+ let done = false;
7
+ const finish = (open) => {
8
+ if (done)
9
+ return;
10
+ done = true;
11
+ sock.destroy();
12
+ resolve(open);
13
+ };
14
+ sock.setTimeout(timeoutMs);
15
+ sock.once("connect", () => finish(true));
16
+ sock.once("timeout", () => finish(false));
17
+ sock.once("error", () => finish(false));
18
+ });
19
+ }
20
+ export async function scanHost(args) {
21
+ const host = (args.host ?? "").trim();
22
+ if (!host)
23
+ throw new PortError("Provide a host name or IP");
24
+ const timeoutMs = Math.min(Math.max(args.timeout_ms ?? 1000, 100), 2000);
25
+ const ports = (args.ports ?? "80,443,22,21,25,53,8080,3306,5432,6379")
26
+ .split(",").map((p) => parseInt(p.trim(), 10)).filter((p) => p >= 1 && p <= 65535).slice(0, 50);
27
+ if (!ports.length)
28
+ throw new PortError("Provide a valid port list");
29
+ const results = [];
30
+ for (const p of ports) {
31
+ const open = await check(host, p, timeoutMs);
32
+ results.push(`${p}: ${open ? "OPEN" : "closed"}`);
33
+ }
34
+ return `Scan of ${host}:\n${results.join("\n")}`;
35
+ }
36
+ export async function scanCommon(args) {
37
+ const host = (args.host ?? "").trim();
38
+ if (!host)
39
+ throw new PortError("Provide a host name or IP");
40
+ const common = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 993, 995, 1433, 1521, 3306, 3389, 5432, 5900, 6379, 8080, 8443, 9000, 27017];
41
+ const results = [];
42
+ for (const p of common) {
43
+ const open = await check(host, p, 800);
44
+ if (open)
45
+ results.push(`${p}: OPEN`);
46
+ }
47
+ return results.length
48
+ ? `Open ports on ${host}:\n${results.join("\n")}`
49
+ : `No common ports open on ${host}`;
50
+ }
package/dist/server.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
- import { scanCommon } from "./api.js";
4
- import { scanHost, summarizeScanResults, parsePortSpec } from "./api.js";
5
- import { premiumRequired } from "./license.js";
3
+ import { scanCommon, scanHost } from "./scan.js";
4
+ import { parsePortSpec, dnsRecords } from "./api.js";
5
+ import { premiumTool } from "./gateway.js";
6
6
  const text = (value) => ({ content: [{ type: "text", text: value }] });
7
7
  const textError = (t) => ({ content: [{ type: "text", text: t }], isError: true });
8
8
  const READ_ONLY = { readOnlyHint: true, openWorldHint: true };
@@ -42,12 +42,10 @@ export function createServer() {
42
42
  annotations: READ_ONLY,
43
43
  }, async (args) => {
44
44
  // ---- paywall: summarize_scan_results ----
45
- const paywallMessage = await premiumRequired("summarize_scan_results");
46
- if (paywallMessage)
47
- return { content: [{ type: "text", text: paywallMessage }], isError: true };
45
+ // The body runs on the gateway, behind the licence gate.
48
46
  // ---- paywall: end ----
49
47
  try {
50
- return text(await summarizeScanResults(args));
48
+ return text(await premiumTool("mcp_port_scanner_summarize_scan_results", args));
51
49
  }
52
50
  catch (e) {
53
51
  return textError(error(e));
@@ -66,5 +64,34 @@ export function createServer() {
66
64
  return textError(error(e));
67
65
  }
68
66
  });
67
+ server.registerTool("dns_records", {
68
+ title: "DNS records",
69
+ description: "Query Google Public DNS for address, mail, nameserver and other DNS records with TTL and response status.",
70
+ inputSchema: z.object({ name: z.string().min(1).max(253).describe("DNS name, e.g. example.com."), type: z.enum(["A", "AAAA", "MX", "NS", "TXT", "CNAME", "SOA", "PTR", "CAA"]).optional(), limit: z.number().int().min(1).max(30).optional() }),
71
+ annotations: READ_ONLY,
72
+ }, async (args) => {
73
+ try {
74
+ return text(await dnsRecords(args));
75
+ }
76
+ catch (e) {
77
+ return textError(error(e));
78
+ }
79
+ });
80
+ server.registerTool("network_origin", {
81
+ title: "Network origin",
82
+ description: "Find the containing IP prefix and originating autonomous system numbers from RIPEstat routing data.",
83
+ inputSchema: z.object({ ip: z.string().min(1).max(45).describe("IPv4 or IPv6 address, e.g. 1.1.1.1.") }),
84
+ annotations: READ_ONLY,
85
+ }, async (args) => {
86
+ // ---- paywall: network_origin ----
87
+ // The body runs on the gateway, behind the licence gate.
88
+ // ---- paywall: end ----
89
+ try {
90
+ return text(await premiumTool("mcp_port_scanner_network_origin", args));
91
+ }
92
+ catch (e) {
93
+ return textError(error(e));
94
+ }
95
+ });
69
96
  return server;
70
97
  }
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.1",
2
+ "version": "1.0.2",
3
3
  "type": "module",
4
4
  "repository": {
5
5
  "type": "git",
package/dist/license.js DELETED
@@ -1,78 +0,0 @@
1
- // Premium tools on this server need a license key bought from MCP Marketplace.
2
- // Buyers put the key in their MCP client config as MCP_LICENSE_KEY. Every tool
3
- // that is not listed in PREMIUM keeps working without a key.
4
- const SLUG = "port-scanner-mcp";
5
- // Tools that need a key. Everything else is free.
6
- const PREMIUM = new Set([
7
- "summarize_scan_results",
8
- ]);
9
- const BUY_URL = `https://mcp-marketplace.io/server/io-github-mrfentmen-${SLUG}`;
10
- // The license check calls the marketplace's verify endpoint directly instead of
11
- // using @mcp_marketplace/license. That SDK sends no `apikey` header, so every
12
- // check it makes is rejected by Supabase before it reaches the function. The
13
- // publishable key below is public by design - it ships in mcp-marketplace.io's
14
- // own JavaScript and only ever reaches their licence check.
15
- const DEFAULT_VERIFY_URL = "https://virupvwhtkpkjsiskckg.supabase.co/functions/v1/verify-key";
16
- const PUBLISHABLE_KEY = "sb_publishable_BuqlW96Ke8C_zzJG-LQv1Q_YHi_r_4h";
17
- const OK_CACHE_MS = 60 * 60 * 1000;
18
- const BAD_CACHE_MS = 60 * 1000;
19
- const seen = new Map();
20
- const REASONS = {
21
- missing_key: "no key is set",
22
- invalid_format: "that key is not a valid MCP Marketplace key",
23
- not_found: "that key was not found",
24
- revoked: "that key has been revoked",
25
- rotated: "that key was rotated, use your new one",
26
- expired: "that key has expired, renew it",
27
- rate_limited: "there were too many checks just now, try again shortly",
28
- network_error: "the license server could not be reached",
29
- };
30
- function blocked(tool, reason) {
31
- const why = REASONS[reason] ?? `the license server answered "${reason}"`;
32
- return `"${tool}" needs a license key, but ${why}. ` +
33
- `Set MCP_LICENSE_KEY in your MCP client config. Get a key: ${BUY_URL}`;
34
- }
35
- async function verify(key) {
36
- const res = await fetch(process.env.MCP_LICENSE_VERIFY_URL || DEFAULT_VERIFY_URL, {
37
- method: "POST",
38
- headers: {
39
- apikey: PUBLISHABLE_KEY,
40
- Authorization: `Bearer ${PUBLISHABLE_KEY}`,
41
- "Content-Type": "application/json",
42
- },
43
- body: JSON.stringify({ key, slug: SLUG }),
44
- // an unusable key answers 400 with a JSON body, so read the body either way
45
- signal: AbortSignal.timeout(15000),
46
- });
47
- const data = (await res.json());
48
- if (typeof data?.valid !== "boolean")
49
- return { valid: false, reason: "unexpected_response" };
50
- return data;
51
- }
52
- /**
53
- * Returns null when the caller may run the tool, or a short message telling
54
- * them how to get a key.
55
- *
56
- * A good key is remembered for an hour, so a busy session does not hit the
57
- * license server on every call and keeps working through a brief outage.
58
- */
59
- export async function premiumRequired(tool) {
60
- if (!PREMIUM.has(tool))
61
- return null;
62
- const key = process.env.MCP_LICENSE_KEY;
63
- if (!key)
64
- return blocked(tool, "missing_key");
65
- const hit = seen.get(key);
66
- if (hit && Date.now() - hit.at < (hit.valid ? OK_CACHE_MS : BAD_CACHE_MS)) {
67
- return hit.valid ? null : blocked(tool, hit.reason ?? "invalid");
68
- }
69
- let result;
70
- try {
71
- result = await verify(key);
72
- }
73
- catch {
74
- result = { valid: false, reason: "network_error" };
75
- }
76
- seen.set(key, { ...result, at: Date.now() });
77
- return result.valid ? null : blocked(tool, result.reason ?? "invalid");
78
- }