mcp-controld 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,150 @@
1
+ import { z } from "zod";
2
+ import { defineTool, nonEmptyString, readAnnotations, segment, subOrgInput, } from "./tools-shared.js";
3
+ const MAX_CSV_BYTES = 2 * 1024 * 1024;
4
+ const MAX_RULE_FOLDERS = 100;
5
+ const analyticsEndpointId = nonEmptyString.regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/, "Must be a lowercase analytics endpoint ID containing only letters, numbers, and internal hyphens.");
6
+ const rfc3339 = z.iso.datetime({ offset: true });
7
+ function isRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ function arrayField(value, field) {
11
+ if (!isRecord(value) || !Array.isArray(value[field])) {
12
+ throw new Error(`Unexpected Control D response: missing ${field} array.`);
13
+ }
14
+ return value[field];
15
+ }
16
+ function recordField(value, field) {
17
+ const fieldValue = isRecord(value) ? value[field] : undefined;
18
+ if (!isRecord(fieldValue)) {
19
+ throw new Error(`Unexpected Control D response: missing ${field} object.`);
20
+ }
21
+ return fieldValue;
22
+ }
23
+ function enabled(value) {
24
+ return isRecord(value) && (value.status === 1 || value.status === true || value.status === "1");
25
+ }
26
+ function normalizeDomain(value) {
27
+ return value.trim().toLowerCase().replace(/\.$/, "");
28
+ }
29
+ export const diagnosticsTools = [
30
+ defineTool({
31
+ name: "controld_export_dns_query_logs",
32
+ config: {
33
+ description: "Experimental: export DNS query logs as CSV. Requires Full Analytics on the device and may require an organization account.",
34
+ inputSchema: z.object({
35
+ analytics_endpoint_id: analyticsEndpointId.optional().describe("Analytics instance endpoint ID, not a hostname or URL. Omitted: auto-discovered from the account's stats_endpoint."),
36
+ start_time: rfc3339.describe("RFC 3339 start timestamp."),
37
+ end_time: rfc3339.optional().describe("Optional RFC 3339 end timestamp; omit for current logs."),
38
+ device_id: nonEmptyString.optional().describe("Optional device/resolver ID."),
39
+ ...subOrgInput,
40
+ }).strict(),
41
+ annotations: readAnnotations,
42
+ },
43
+ handler: async (client, { analytics_endpoint_id, start_time, end_time, device_id, sub_org_id, }) => {
44
+ let endpointId = analytics_endpoint_id;
45
+ if (endpointId === undefined) {
46
+ const account = await client.request("/users", {
47
+ subOrgId: sub_org_id,
48
+ });
49
+ if (typeof account.stats_endpoint !== "string" || account.stats_endpoint === "") {
50
+ throw new Error("No analytics endpoint found on the account; pass analytics_endpoint_id explicitly.");
51
+ }
52
+ endpointId = analyticsEndpointId.parse(account.stats_endpoint);
53
+ }
54
+ const url = new URL(`https://${endpointId}.analytics.controld.com/v2/activity-log/csv`);
55
+ url.searchParams.set("startTime", start_time);
56
+ if (end_time)
57
+ url.searchParams.set("endTime", end_time);
58
+ if (device_id)
59
+ url.searchParams.set("endpointId", device_id);
60
+ const { text, truncated } = await client.rawGet(url, {
61
+ subOrgId: sub_org_id,
62
+ maxBytes: MAX_CSV_BYTES,
63
+ });
64
+ return truncated
65
+ ? `${text}\n\n[TRUNCATED: response exceeded ${MAX_CSV_BYTES} bytes.]`
66
+ : text;
67
+ },
68
+ }),
69
+ defineTool({
70
+ name: "controld_explain_domain",
71
+ config: {
72
+ description: "Explain profile configuration relevant to a domain. This is a heuristic config walk, not a DNS resolution trace; Control D precedence is not formally documented.",
73
+ inputSchema: z.object({
74
+ profile_id: nonEmptyString.describe("Profile ID."),
75
+ domain: z.string().trim().min(1).describe("Domain to inspect."),
76
+ ...subOrgInput,
77
+ }).strict(),
78
+ annotations: readAnnotations,
79
+ },
80
+ handler: async (client, { profile_id, domain, sub_org_id }) => {
81
+ const profilePath = `/profiles/${segment(profile_id)}`;
82
+ const requestOptions = { subOrgId: sub_org_id };
83
+ const groups = arrayField(await client.request(`${profilePath}/groups`, requestOptions), "groups");
84
+ const selectedGroups = groups.slice(0, MAX_RULE_FOLDERS - 1);
85
+ // Live-verified: /rules/0 returns "No such group exists"; root rules are
86
+ // only served at /rules with the folder segment omitted.
87
+ const folders = [
88
+ { id: null, folder: { PK: 0, group: "Root" } },
89
+ ];
90
+ for (const folder of selectedGroups) {
91
+ if (!isRecord(folder) || (typeof folder.PK !== "string" && typeof folder.PK !== "number")) {
92
+ throw new Error("Unexpected Control D response: invalid rule folder.");
93
+ }
94
+ folders.push({ id: String(folder.PK), folder });
95
+ }
96
+ const [ruleSets, servicesValue, filtersValue, externalFiltersValue, defaultValue] = await Promise.all([
97
+ Promise.all(folders.map(({ id }) => client.request(id === null ? `${profilePath}/rules` : `${profilePath}/rules/${segment(id)}`, requestOptions))),
98
+ client.request(`${profilePath}/services`, requestOptions),
99
+ client.request(`${profilePath}/filters`, requestOptions),
100
+ client.request(`${profilePath}/filters/external`, requestOptions),
101
+ client.request(`${profilePath}/default`, requestOptions),
102
+ ]);
103
+ const inspectedDomain = normalizeDomain(domain);
104
+ const exactCustomRules = [];
105
+ const parentDomainCustomRules = [];
106
+ for (const [index, ruleSet] of ruleSets.entries()) {
107
+ const folder = folders[index].folder;
108
+ for (const rule of arrayField(ruleSet, "rules")) {
109
+ if (!isRecord(rule) || typeof rule.PK !== "string") {
110
+ throw new Error("Unexpected Control D response: invalid custom rule.");
111
+ }
112
+ const ruleDomain = normalizeDomain(rule.PK);
113
+ const wildcardBase = ruleDomain.startsWith("*.") ? ruleDomain.slice(2) : undefined;
114
+ const finding = { folder, rule };
115
+ if (ruleDomain === inspectedDomain) {
116
+ exactCustomRules.push(finding);
117
+ }
118
+ else if ((wildcardBase !== undefined && (inspectedDomain === wildcardBase || inspectedDomain.endsWith(`.${wildcardBase}`)))
119
+ || inspectedDomain.endsWith(`.${ruleDomain}`)) {
120
+ parentDomainCustomRules.push(finding);
121
+ }
122
+ }
123
+ }
124
+ const services = arrayField(servicesValue, "services");
125
+ const filters = arrayField(filtersValue, "filters");
126
+ const externalFilters = arrayField(externalFiltersValue, "filters");
127
+ const defaultRule = recordField(defaultValue, "default");
128
+ return {
129
+ domain: inspectedDomain,
130
+ scope: "Configuration walk only; this is not a DNS resolution trace.",
131
+ precedence_notice: "Findings are listed in a plausible custom-rule, service-rule, filter, default-rule order; Control D precedence is not formally documented.",
132
+ folder_walk: {
133
+ limit: MAX_RULE_FOLDERS,
134
+ discovered: groups.length + 1,
135
+ fetched: folders.length,
136
+ truncated: groups.length > selectedGroups.length,
137
+ },
138
+ findings: {
139
+ exact_custom_rules: exactCustomRules,
140
+ parent_domain_custom_rules: parentDomainCustomRules,
141
+ enabled_service_rules_not_domain_matched: services.filter((service) => isRecord(service) && enabled(service.action)),
142
+ enabled_filters_not_domain_matched: filters.filter(enabled),
143
+ enabled_external_filters_not_domain_matched: externalFilters.filter(enabled),
144
+ configured_default_rule: defaultRule,
145
+ },
146
+ catalog_notice: "Enabled services, native filters, and external filters are listed as configured; their domain catalogs were not evaluated, so no domain match is claimed for them.",
147
+ };
148
+ },
149
+ }),
150
+ ];
@@ -0,0 +1,175 @@
1
+ import { z } from "zod";
2
+ import { apiPath, defineTool, nonEmptyString, queryInput, readAnnotations, segment, subOrgInput, withQuery, } from "./tools-shared.js";
3
+ const profileSectionPaths = {
4
+ filters: "filters",
5
+ external_filters: "filters/external",
6
+ services: "services",
7
+ folders: "groups",
8
+ rules: "rules",
9
+ default_rule: "default",
10
+ };
11
+ const profileConfigInput = z.object({
12
+ profile_id: nonEmptyString,
13
+ section: z.enum([
14
+ "filters",
15
+ "external_filters",
16
+ "services",
17
+ "folders",
18
+ "rules",
19
+ "default_rule",
20
+ "all",
21
+ ]).describe("Configuration section to read, or 'all' to fetch every section in one call."),
22
+ folder_id: nonEmptyString.optional().describe("Rule folder ID. Used only when section is rules; omit or pass 0 for the root folder."),
23
+ ...subOrgInput,
24
+ }).strict();
25
+ const catalogInput = z.discriminatedUnion("catalog", [
26
+ z.object({
27
+ catalog: z.literal("services"),
28
+ category: nonEmptyString,
29
+ }).strict(),
30
+ z.object({
31
+ catalog: z.enum([
32
+ "profile_options",
33
+ "device_types",
34
+ "service_categories",
35
+ "proxies",
36
+ "analytics_levels",
37
+ "analytics_regions",
38
+ ]),
39
+ }).strict(),
40
+ ]);
41
+ export const readTools = [
42
+ defineTool({
43
+ name: "controld_list_profiles",
44
+ config: {
45
+ description: "List Control D profiles.",
46
+ inputSchema: z.object(subOrgInput).strict(),
47
+ annotations: readAnnotations,
48
+ },
49
+ handler: (client, { sub_org_id }) => client.request("/profiles", { subOrgId: sub_org_id }),
50
+ }),
51
+ defineTool({
52
+ name: "controld_get_profile_config",
53
+ config: {
54
+ description: "Get one configuration section for a Control D profile, or every section at once with section 'all'.",
55
+ inputSchema: profileConfigInput,
56
+ annotations: readAnnotations,
57
+ },
58
+ handler: async (client, { profile_id, section, folder_id, sub_org_id }) => {
59
+ const profilePath = `/profiles/${segment(profile_id)}`;
60
+ const options = { subOrgId: sub_org_id };
61
+ const read = (name, folder) => {
62
+ // Live-verified: /rules/0 404s; the root folder is addressed by omitting
63
+ // the segment entirely.
64
+ const effectiveFolder = name === "rules" && folder !== "0" ? folder : undefined;
65
+ const folderPath = effectiveFolder !== undefined ? `/${segment(effectiveFolder)}` : "";
66
+ return client.request(`${profilePath}/${profileSectionPaths[name]}${folderPath}`, options);
67
+ };
68
+ if (section !== "all")
69
+ return read(section, folder_id);
70
+ const names = Object.keys(profileSectionPaths);
71
+ const results = await Promise.all(names.map((name) => read(name, folder_id)));
72
+ return {
73
+ note: "'rules' covers the requested folder only, root by default. Use controld_explain_domain to walk every folder.",
74
+ ...Object.fromEntries(names.map((name, index) => [name, results[index]])),
75
+ };
76
+ },
77
+ }),
78
+ defineTool({
79
+ name: "controld_list_catalog",
80
+ config: {
81
+ description: "List a Control D metadata catalog.",
82
+ inputSchema: catalogInput,
83
+ annotations: readAnnotations,
84
+ },
85
+ handler: (client, input) => {
86
+ const path = input.catalog === "services"
87
+ ? `/services/categories/${segment(input.category)}`
88
+ : {
89
+ profile_options: "/profiles/options",
90
+ device_types: "/devices/types",
91
+ service_categories: "/services/categories",
92
+ proxies: "/proxies",
93
+ analytics_levels: "/analytics/levels",
94
+ analytics_regions: "/analytics/endpoints",
95
+ }[input.catalog];
96
+ return client.request(path);
97
+ },
98
+ }),
99
+ defineTool({
100
+ name: "controld_list_devices",
101
+ config: {
102
+ description: "List Control D devices.",
103
+ inputSchema: z.object(subOrgInput).strict(),
104
+ annotations: readAnnotations,
105
+ },
106
+ handler: (client, { sub_org_id }) => client.request("/devices", { subOrgId: sub_org_id }),
107
+ }),
108
+ defineTool({
109
+ name: "controld_list_known_ips",
110
+ config: {
111
+ description: "List known IP addresses for a Control D device.",
112
+ inputSchema: z.object({ device_id: nonEmptyString, ...subOrgInput }).strict(),
113
+ annotations: readAnnotations,
114
+ },
115
+ handler: (client, { device_id, sub_org_id }) => client.request(`/access?${new URLSearchParams({ device_id })}`, { subOrgId: sub_org_id }),
116
+ }),
117
+ defineTool({
118
+ name: "controld_get_account",
119
+ config: {
120
+ description: "Get the Control D account.",
121
+ inputSchema: z.object({}).strict(),
122
+ annotations: readAnnotations,
123
+ },
124
+ handler: (client) => client.request("/users"),
125
+ }),
126
+ defineTool({
127
+ name: "controld_get_billing",
128
+ config: {
129
+ description: "Get a Control D billing view.",
130
+ inputSchema: z.object({ view: z.enum(["products", "subscriptions", "payments"]) }).strict(),
131
+ annotations: readAnnotations,
132
+ },
133
+ handler: (client, { view }) => client.request(`/billing/${segment(view)}`),
134
+ }),
135
+ defineTool({
136
+ name: "controld_get_organization",
137
+ config: {
138
+ description: "Get a Control D organization view.",
139
+ inputSchema: z.object({ view: z.enum(["info", "members", "sub_organizations"]) }).strict(),
140
+ annotations: readAnnotations,
141
+ },
142
+ handler: (client, { view }) => client.request(`/organizations/${segment(view === "info" ? "organization" : view)}`),
143
+ }),
144
+ defineTool({
145
+ name: "controld_get_request_ip",
146
+ config: {
147
+ description: "Get the caller IP address and handling datacenter.",
148
+ inputSchema: z.object({}).strict(),
149
+ annotations: readAnnotations,
150
+ },
151
+ handler: (client) => client.request("/ip"),
152
+ }),
153
+ defineTool({
154
+ name: "controld_get_network_status",
155
+ config: {
156
+ description: "Get Control D network status.",
157
+ inputSchema: z.object({}).strict(),
158
+ annotations: readAnnotations,
159
+ },
160
+ handler: (client) => client.request("/network"),
161
+ }),
162
+ defineTool({
163
+ name: "controld_request_read",
164
+ config: {
165
+ description: "Escape hatch: GET any Control D API path with the read token. Use only when no typed tool covers what you need, for example the undocumented '/devices/users' and '/devices/routers'. Cannot modify anything.",
166
+ inputSchema: z.object({
167
+ path: apiPath,
168
+ query: queryInput,
169
+ ...subOrgInput,
170
+ }).strict(),
171
+ annotations: readAnnotations,
172
+ },
173
+ handler: (client, { path, query, sub_org_id }) => client.request(withQuery(path, query), { subOrgId: sub_org_id }),
174
+ }),
175
+ ];
@@ -0,0 +1,69 @@
1
+ import { z } from "zod";
2
+ import { decodeTruncated } from "./client.js";
3
+ const MAX_TEXT_BYTES = 1024 * 1024;
4
+ export function defineTool(definition) {
5
+ return {
6
+ ...definition,
7
+ handler: (client, args) => definition.handler(client, args),
8
+ };
9
+ }
10
+ export const nonEmptyString = z.string().min(1);
11
+ /**
12
+ * A path for the raw escape-hatch tools. It must be host-relative and start
13
+ * with exactly one slash: "//example.com/x" and "\\\\example.com/x" both resolve
14
+ * to another host under WHATWG URL rules, which would send the bearer token
15
+ * off-site. Whitespace and backslashes are rejected outright.
16
+ */
17
+ export const apiPath = z.string()
18
+ .regex(/^\/(?![/\\])[^\s\\#]*$/, "Path must start with a single '/', and must not contain whitespace, backslashes, or '#'.")
19
+ .describe("Control D API path starting with '/', for example '/devices/users'.");
20
+ export const queryInput = z.record(z.string().min(1), z.union([z.string(), z.number(), z.boolean()])).optional().describe("Optional query parameters.");
21
+ export function withQuery(path, query) {
22
+ if (query === undefined)
23
+ return path;
24
+ const params = new URLSearchParams();
25
+ for (const [key, value] of Object.entries(query))
26
+ params.set(key, String(value));
27
+ const search = params.toString();
28
+ return search === "" ? path : `${path}${path.includes("?") ? "&" : "?"}${search}`;
29
+ }
30
+ export function segment(value) {
31
+ const text = String(value);
32
+ if (text === "" || text === "." || text === "..") {
33
+ throw new Error("Path segments must not be empty, '.' or '..'.");
34
+ }
35
+ return encodeURIComponent(text);
36
+ }
37
+ export const subOrgInput = {
38
+ sub_org_id: z.string().min(1).optional().describe("Sub-organization ID to act on."),
39
+ };
40
+ export const readAnnotations = {
41
+ readOnlyHint: true,
42
+ destructiveHint: false,
43
+ idempotentHint: true,
44
+ openWorldHint: true,
45
+ };
46
+ export const writeAnnotations = {
47
+ readOnlyHint: false,
48
+ destructiveHint: false,
49
+ idempotentHint: false,
50
+ openWorldHint: true,
51
+ };
52
+ export const destructiveAnnotations = {
53
+ ...writeAnnotations,
54
+ destructiveHint: true,
55
+ };
56
+ export function textResult(value) {
57
+ const text = typeof value === "string" ? value : JSON.stringify(value, null, 2) ?? "null";
58
+ const bytes = Buffer.from(text);
59
+ if (bytes.length <= MAX_TEXT_BYTES) {
60
+ return { content: [{ type: "text", text }] };
61
+ }
62
+ const matchedNotice = text.match(/\n\n\[TRUNCATED:[^\r\n]*\]$/)?.[0] ?? "";
63
+ const trailingNotice = Buffer.byteLength(matchedNotice) <= 1024 ? matchedNotice : "";
64
+ const notice = `\n\n[TRUNCATED: output capped at ${MAX_TEXT_BYTES} bytes.]${trailingNotice}`;
65
+ const prefix = decodeTruncated(bytes.subarray(0, MAX_TEXT_BYTES - Buffer.byteLength(notice)));
66
+ return {
67
+ content: [{ type: "text", text: prefix + notice }],
68
+ };
69
+ }