@lincolnminto/zendesk-mcp-server 2.24.0 → 2.26.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 +10 -3
  2. package/dist/index.js +533 -21
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -37,6 +37,11 @@ then calls the right tools on your behalf.
37
37
  - Draft and maintain knowledge-base articles. You can write a new one, or revise
38
38
  a large one a single section at a time, so the whole HTML body never has to
39
39
  round-trip through the model.
40
+ - Snapshot the account's admin configuration (triggers, automations, macros,
41
+ views, forms, fields, SLAs and more) into local JSON files, to audit,
42
+ document, diff or migrate a Zendesk setup without pulling it all through the
43
+ conversation (opt-in: start the server with an
44
+ [export directory](docs/configuration.md#zendesk_export_dir)).
40
45
 
41
46
  ## Why this server
42
47
 
@@ -62,7 +67,9 @@ differently.
62
67
  - A tool surface you can cap. Expose every operation as its own tool, group them
63
68
  into namespace proxies, or collapse everything into a single unified tool. You
64
69
  can also filter by namespace or down to read-only operations, so each context
65
- loads only the surface it needs (see [Tool surface](#tool-surface)).
70
+ loads only the surface it needs (see [Tool surface](#tool-surface)). Read-only
71
+ over stdio also signs in with Zendesk's `read` scope, so Zendesk itself refuses
72
+ a write ([how](docs/configuration.md#read-only-all-the-way-to-zendesk)).
66
73
  - Two deployment shapes, same auth story. Run it on your laptop as a stdio MCP
67
74
  server, or deploy it as a private remote MCP server reached over HTTP, with one
68
75
  Zendesk session per request and each client carrying its own user's token.
@@ -215,8 +222,8 @@ job: **[docs/http-deployment.md](docs/http-deployment.md)**.
215
222
 
216
223
  ## Tool surface
217
224
 
218
- Tools are grouped into four namespaces: **Tickets**, **Help Center**, **Users &
219
- Organizations** and **Search**. The server registers them in one of three modes,
225
+ Tools are grouped into namespaces: **Tickets**, **Help Center**, **Users &
226
+ Organizations**, **Search** and **Admin**. The server registers them in one of three modes,
220
227
  so you can trade granularity against context budget:
221
228
 
222
229
  - **`all`**: every operation as its own tool, for clients with good tool selection;
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ import remarkParse from "remark-parse";
20
20
  import remarkRehype from "remark-rehype";
21
21
  import remarkStringify from "remark-stringify";
22
22
  import { unified } from "unified";
23
- import { readFile, stat } from "node:fs/promises";
23
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
24
24
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
25
25
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
26
26
  //#region src/auth/api-token.ts
@@ -307,7 +307,7 @@ const startBrowserAuth = (config, logger = silentLogger) => {
307
307
  response_type: "code",
308
308
  client_id: oauthClientId,
309
309
  redirect_uri: redirectUri,
310
- scope: "read write",
310
+ scope: config.scope ?? "read write",
311
311
  code_challenge: codeChallenge,
312
312
  code_challenge_method: "S256"
313
313
  });
@@ -378,6 +378,12 @@ const refreshAccessToken = async (config, logger = silentLogger) => {
378
378
  return tokenData;
379
379
  };
380
380
  //#endregion
381
+ //#region src/auth/oauth-scope.ts
382
+ const requestedScope = (readOnly) => readOnly ? "read" : "read write";
383
+ const READ_ENTRY = /^(?:read|[a-z_]+:read)$/;
384
+ const WHITESPACE = /\s+/;
385
+ const isReadOnlyScope = (scope) => typeof scope === "string" && scope.trim().split(WHITESPACE).every((entry) => READ_ENTRY.test(entry));
386
+ //#endregion
381
387
  //#region src/utils/package-info.ts
382
388
  const FALLBACK = {
383
389
  name: "@lincolnminto/zendesk-mcp-server",
@@ -444,13 +450,16 @@ const safeName = (subdomain) => subdomain.replace(/[^a-z0-9-]/gi, "_");
444
450
  * Path to the token file for a subdomain. Each subdomain gets its **own** file
445
451
  * (`<subdomain>.json`, a single record) so concurrent processes for different
446
452
  * subdomains never read-modify-write a shared file — no merge, no clobber.
453
+ * A read-only server keeps its `read`-scoped token in `<subdomain>.read.json`,
454
+ * so a read-only and a read-write server on the same subdomain never overwrite
455
+ * each other's token and force a sign-in on every switch.
447
456
  * `ZENDESK_TOKEN_FILE` overrides with an explicit path (a single file; use the
448
- * default layout for multi-subdomain installs).
457
+ * default layout for multi-subdomain or mixed read-only installs).
449
458
  */
450
- const resolveTokenPath = (subdomain) => {
459
+ const resolveTokenPath = (subdomain, { readOnly = false } = {}) => {
451
460
  const override = process.env["ZENDESK_TOKEN_FILE"];
452
461
  if (override) return override;
453
- return join(configDir(), `${safeName(subdomain)}.json`);
462
+ return join(configDir(), `${safeName(subdomain)}${readOnly ? ".read" : ""}.json`);
454
463
  };
455
464
  const writeFileAtomic = (path, record) => {
456
465
  const dir = dirname(path);
@@ -495,8 +504,17 @@ const createAuthRequiredError = (authorizeUrl) => Object.assign(/* @__PURE__ */
495
504
  });
496
505
  const expiryFrom = (expiresIn) => typeof expiresIn === "number" ? Date.now() + expiresIn * 1e3 : void 0;
497
506
  const createTokenStore = (config, logger = silentLogger) => {
498
- const tokenPath = resolveTokenPath(config.subdomain);
499
- let token = loadToken(tokenPath);
507
+ const readOnly = config.readOnly ?? false;
508
+ const tokenPath = resolveTokenPath(config.subdomain, { readOnly });
509
+ const loadUsableToken = () => {
510
+ const loaded = loadToken(tokenPath);
511
+ if (loaded && readOnly && !isReadOnlyScope(loaded.scope)) {
512
+ logger.warn("oauth_token_scope_rejected");
513
+ return;
514
+ }
515
+ return loaded;
516
+ };
517
+ let token = loadUsableToken();
500
518
  if (token) logger.debug("oauth_token_loaded_from_disk");
501
519
  let authorizeUrl;
502
520
  let starting;
@@ -520,10 +538,13 @@ const createTokenStore = (config, logger = silentLogger) => {
520
538
  oauthClientId: config.oauthClientId,
521
539
  refreshToken: current.refreshToken
522
540
  }, logger);
541
+ const scope = result.scope ?? current.scope;
542
+ if (readOnly && !isReadOnlyScope(scope)) throw new Error(`Refreshed token scope is broader than read: ${String(scope)}`);
523
543
  token = {
524
544
  accessToken: result.access_token,
525
545
  refreshToken: result.refresh_token ?? current.refreshToken,
526
- expiresAt: expiryFrom(result.expires_in)
546
+ expiresAt: expiryFrom(result.expires_in),
547
+ scope
527
548
  };
528
549
  probedUnknownExpiry = true;
529
550
  persist(token);
@@ -543,14 +564,21 @@ const createTokenStore = (config, logger = silentLogger) => {
543
564
  return startBrowserAuth({
544
565
  subdomain: config.subdomain,
545
566
  oauthClientId: config.oauthClientId,
546
- callbackPort: config.callbackPort
567
+ callbackPort: config.callbackPort,
568
+ scope: requestedScope(readOnly)
547
569
  }, logger).then((started) => {
548
570
  authorizeUrl = started.authorizeUrl;
549
571
  started.tokenPromise.then((result) => {
572
+ const scope = result.scope ?? requestedScope(readOnly);
573
+ if (readOnly && !isReadOnlyScope(scope)) {
574
+ logger.error("oauth_scope_too_broad", { scope });
575
+ return;
576
+ }
550
577
  token = {
551
578
  accessToken: result.access_token,
552
579
  refreshToken: result.refresh_token,
553
- expiresAt: expiryFrom(result.expires_in)
580
+ expiresAt: expiryFrom(result.expires_in),
581
+ scope
554
582
  };
555
583
  probedUnknownExpiry = true;
556
584
  persist(token);
@@ -592,7 +620,8 @@ const createTokenStore = (config, logger = silentLogger) => {
592
620
  token = {
593
621
  accessToken: token.accessToken,
594
622
  refreshToken: token.refreshToken,
595
- expiresAt: 0
623
+ expiresAt: 0,
624
+ scope: token.scope
596
625
  };
597
626
  persist(token);
598
627
  } else {
@@ -631,9 +660,11 @@ const LogLevel = z.enum([
631
660
  const Namespace = z.enum([
632
661
  "tickets",
633
662
  "help_center",
634
- "users"
663
+ "users",
664
+ "admin"
635
665
  ]);
636
666
  const Transport = z.enum(["stdio", "http"]);
667
+ const NETWORK_PATH = /^[\\/]{2}/;
637
668
  const ConfigSchema = z.object({
638
669
  subdomain: z.string().min(1, "ZENDESK_SUBDOMAIN is required"),
639
670
  oauthClientId: z.string().min(1),
@@ -712,7 +743,14 @@ const ConfigSchema = z.object({
712
743
  * because they send no Origin header.
713
744
  */
714
745
  corsOrigins: z.array(z.string().url().transform((value) => new URL(value).origin).refine((origin) => origin !== "null", { message: "CORS origin must be an http(s) URL with a host" })).default([]),
715
- callbackPort: z.number().int().min(1).max(65535).optional()
746
+ callbackPort: z.number().int().min(1).max(65535).optional(),
747
+ /**
748
+ * Where `export_account_config` writes its snapshots; the admin namespace
749
+ * exists only when this is set. It is the operator's choice, never the
750
+ * model's: the tool takes no path, so a prompt cannot steer where files land.
751
+ * stdio only (refused at boot over HTTP, see loadConfig).
752
+ */
753
+ exportDir: z.string().refine((dir) => isAbsolute(dir) && !NETWORK_PATH.test(dir), { message: "The export directory must be an absolute local path (--export-dir / ZENDESK_EXPORT_DIR), not a relative path or a network share." }).optional()
716
754
  });
717
755
  const DIGITS_ONLY = /^\d+$/;
718
756
  const parsePort = (raw, label) => {
@@ -746,6 +784,7 @@ const CLI_OPTIONS = {
746
784
  multiple: true
747
785
  },
748
786
  "callback-port": { type: "string" },
787
+ "export-dir": { type: "string" },
749
788
  "read-only": { type: "boolean" },
750
789
  "no-topology": { type: "boolean" },
751
790
  "no-promoted-articles": { type: "boolean" },
@@ -761,7 +800,8 @@ const FIELD_BY_FLAG = /* @__PURE__ */ new Map([
761
800
  ["transport", "transport"],
762
801
  ["host", "host"],
763
802
  ["public-url", "publicUrl"],
764
- ["cors-origin", "corsOrigins"]
803
+ ["cors-origin", "corsOrigins"],
804
+ ["export-dir", "exportDir"]
765
805
  ]);
766
806
  const STANDALONE_EFFECTS = /* @__PURE__ */ new Map([
767
807
  ["read-only", { readOnly: true }],
@@ -801,6 +841,17 @@ const resolveTransportSettings = (cli) => {
801
841
  corsOrigins: [...cli.corsOrigins ?? [], ...corsFromEnv]
802
842
  };
803
843
  };
844
+ const exportAskedFor = (cli) => {
845
+ if (cli.namespaces?.includes("admin")) return "The admin namespace";
846
+ if (cli.tools?.includes("export_account_config")) return "export_account_config";
847
+ };
848
+ const resolveExportDir = (cli, transport) => {
849
+ const exportDir = cli.exportDir ?? requireNonEmptyEnv("ZENDESK_EXPORT_DIR");
850
+ const asked = exportAskedFor(cli);
851
+ if (transport === "http" && (exportDir !== void 0 || asked)) throw new Error("The account export (--export-dir / ZENDESK_EXPORT_DIR, the admin namespace) is stdio only: over HTTP the files would be written on the server host. Leave it out in HTTP mode.");
852
+ if (asked && exportDir === void 0) throw new Error(`${asked} needs an export directory: set --export-dir (or ZENDESK_EXPORT_DIR) to an absolute local path.`);
853
+ return exportDir;
854
+ };
804
855
  const loadConfig = (argv = process.argv.slice(2)) => {
805
856
  const cli = parseCliArgs(argv);
806
857
  const subdomain = cli.subdomain ?? requireNonEmptyEnv("ZENDESK_SUBDOMAIN") ?? "";
@@ -812,6 +863,7 @@ const loadConfig = (argv = process.argv.slice(2)) => {
812
863
  const hcResourceScheme = cli.hcResourceScheme ?? requireNonEmptyEnv("HC_RESOURCE_SCHEME");
813
864
  const transportSettings = resolveTransportSettings(cli);
814
865
  if (transportSettings.transport === "http" && zendeskEmail && zendeskApiToken) throw new Error("API token authentication (ZENDESK_EMAIL + ZENDESK_API_TOKEN) is not supported in HTTP mode. HTTP mode requires per-user OAuth 2.1 PKCE - unset these variables and configure your MCP client to perform the OAuth flow against Zendesk.");
866
+ const exportDir = resolveExportDir(cli, transportSettings.transport);
815
867
  return ConfigSchema.parse({
816
868
  subdomain,
817
869
  oauthClientId,
@@ -827,6 +879,7 @@ const loadConfig = (argv = process.argv.slice(2)) => {
827
879
  hcResourceScheme,
828
880
  dev: cli.dev ?? false,
829
881
  callbackPort,
882
+ exportDir,
830
883
  ...transportSettings
831
884
  });
832
885
  };
@@ -1143,11 +1196,11 @@ const HEADING_LEVELS = /* @__PURE__ */ new Set([
1143
1196
  "h2",
1144
1197
  "h3"
1145
1198
  ]);
1146
- const WHITESPACE_RUN = /\s+/;
1199
+ const WHITESPACE_RUN$1 = /\s+/;
1147
1200
  const countWords = (text) => {
1148
1201
  const trimmed = text.trim();
1149
1202
  if (!trimmed) return 0;
1150
- return trimmed.split(WHITESPACE_RUN).length;
1203
+ return trimmed.split(WHITESPACE_RUN$1).length;
1151
1204
  };
1152
1205
  const textOf = (html) => {
1153
1206
  if (!html) return "";
@@ -1864,6 +1917,453 @@ const groupByNamespace = (tools) => {
1864
1917
  return grouped;
1865
1918
  };
1866
1919
  //#endregion
1920
+ //#region src/tools/admin.ts
1921
+ const RESOURCE_KEYS = [
1922
+ "account_settings",
1923
+ "brands",
1924
+ "locales",
1925
+ "support_addresses",
1926
+ "schedules",
1927
+ "groups",
1928
+ "group_memberships",
1929
+ "custom_roles",
1930
+ "ticket_forms",
1931
+ "ticket_fields",
1932
+ "custom_statuses",
1933
+ "user_fields",
1934
+ "organization_fields",
1935
+ "triggers",
1936
+ "trigger_categories",
1937
+ "automations",
1938
+ "macros",
1939
+ "views",
1940
+ "sla_policies",
1941
+ "group_sla_policies",
1942
+ "webhooks",
1943
+ "targets",
1944
+ "dynamic_content",
1945
+ "satisfaction_reasons",
1946
+ "sharing_agreements",
1947
+ "app_installations",
1948
+ "routing_attributes",
1949
+ "custom_objects"
1950
+ ];
1951
+ /**
1952
+ * The account-configuration catalog, in export order: what an admin sets up in
1953
+ * Admin Center, not the data that flows through it (tickets, users, articles).
1954
+ * The keys are this tool's own names, so a renamed endpoint changes one row here
1955
+ * and nothing a caller depends on.
1956
+ */
1957
+ const CONFIG_RESOURCES = {
1958
+ account_settings: {
1959
+ path: "/account/settings",
1960
+ responseKey: "settings",
1961
+ single: true
1962
+ },
1963
+ brands: {
1964
+ path: "/brands",
1965
+ responseKey: "brands"
1966
+ },
1967
+ locales: {
1968
+ path: "/locales",
1969
+ responseKey: "locales"
1970
+ },
1971
+ support_addresses: {
1972
+ path: "/recipient_addresses",
1973
+ responseKey: "recipient_addresses"
1974
+ },
1975
+ schedules: {
1976
+ path: "/business_hours/schedules",
1977
+ responseKey: "schedules",
1978
+ nested: {
1979
+ attachAs: "holidays",
1980
+ idField: "id",
1981
+ path: (id) => `/business_hours/schedules/${id}/holidays`,
1982
+ responseKey: "holidays"
1983
+ }
1984
+ },
1985
+ groups: {
1986
+ path: "/groups",
1987
+ responseKey: "groups"
1988
+ },
1989
+ group_memberships: {
1990
+ path: "/group_memberships",
1991
+ responseKey: "group_memberships"
1992
+ },
1993
+ custom_roles: {
1994
+ path: "/custom_roles",
1995
+ responseKey: "custom_roles"
1996
+ },
1997
+ ticket_forms: {
1998
+ path: "/ticket_forms",
1999
+ responseKey: "ticket_forms"
2000
+ },
2001
+ ticket_fields: {
2002
+ path: "/ticket_fields",
2003
+ responseKey: "ticket_fields"
2004
+ },
2005
+ custom_statuses: {
2006
+ path: "/custom_statuses",
2007
+ responseKey: "custom_statuses"
2008
+ },
2009
+ user_fields: {
2010
+ path: "/user_fields",
2011
+ responseKey: "user_fields"
2012
+ },
2013
+ organization_fields: {
2014
+ path: "/organization_fields",
2015
+ responseKey: "organization_fields"
2016
+ },
2017
+ triggers: {
2018
+ path: "/triggers",
2019
+ responseKey: "triggers"
2020
+ },
2021
+ trigger_categories: {
2022
+ path: "/trigger_categories",
2023
+ responseKey: "trigger_categories"
2024
+ },
2025
+ automations: {
2026
+ path: "/automations",
2027
+ responseKey: "automations"
2028
+ },
2029
+ macros: {
2030
+ path: "/macros",
2031
+ responseKey: "macros"
2032
+ },
2033
+ views: {
2034
+ path: "/views",
2035
+ responseKey: "views"
2036
+ },
2037
+ sla_policies: {
2038
+ path: "/slas/policies",
2039
+ responseKey: "sla_policies"
2040
+ },
2041
+ group_sla_policies: {
2042
+ path: "/group_slas/policies",
2043
+ responseKey: "group_sla_policies"
2044
+ },
2045
+ webhooks: {
2046
+ path: "/webhooks",
2047
+ responseKey: "webhooks"
2048
+ },
2049
+ targets: {
2050
+ path: "/targets",
2051
+ responseKey: "targets"
2052
+ },
2053
+ dynamic_content: {
2054
+ path: "/dynamic_content/items",
2055
+ responseKey: "items"
2056
+ },
2057
+ satisfaction_reasons: {
2058
+ path: "/satisfaction_reasons",
2059
+ responseKey: "reasons"
2060
+ },
2061
+ sharing_agreements: {
2062
+ path: "/sharing_agreements",
2063
+ responseKey: "sharing_agreements"
2064
+ },
2065
+ app_installations: {
2066
+ path: "/apps/installations",
2067
+ responseKey: "installations"
2068
+ },
2069
+ routing_attributes: {
2070
+ path: "/routing/attributes",
2071
+ responseKey: "attributes",
2072
+ nested: {
2073
+ attachAs: "values",
2074
+ idField: "id",
2075
+ path: (id) => `/routing/attributes/${id}/values`,
2076
+ responseKey: "attribute_values"
2077
+ }
2078
+ },
2079
+ custom_objects: {
2080
+ path: "/custom_objects",
2081
+ responseKey: "custom_objects",
2082
+ nested: {
2083
+ attachAs: "fields",
2084
+ idField: "key",
2085
+ path: (key) => `/custom_objects/${key}/fields`,
2086
+ responseKey: "custom_object_fields"
2087
+ }
2088
+ }
2089
+ };
2090
+ const CURSOR_FIRST_PAGE = { "page[size]": "100" };
2091
+ /**
2092
+ * The request for the next page, or `undefined` on the last one. Zendesk pages a
2093
+ * configuration list either by offset (`next_page`) or by cursor (`meta.has_more`
2094
+ * + `links.next`); whichever the endpoint answered with is followed. The link
2095
+ * comes from the response, so it is followed only on this account's API: any
2096
+ * other target would receive the bearer token.
2097
+ */
2098
+ const nextRequest = (body, subdomain) => {
2099
+ const meta = body["meta"];
2100
+ const links = body["links"];
2101
+ const link = meta?.has_more === true && typeof links?.next === "string" ? links.next : body["next_page"];
2102
+ if (typeof link !== "string") return void 0;
2103
+ const url = new URL(link);
2104
+ const api = new URL(getBaseUrl(subdomain));
2105
+ if (url.origin !== api.origin || !url.pathname.startsWith(`${api.pathname}/`)) throw new Error(`Refusing to follow a pagination link outside this account API: ${url.origin}${url.pathname}`);
2106
+ return {
2107
+ path: url.pathname.slice(api.pathname.length),
2108
+ params: Object.fromEntries(url.searchParams)
2109
+ };
2110
+ };
2111
+ const PAGE_FRAME_KEYS = /* @__PURE__ */ new Set([
2112
+ "meta",
2113
+ "links",
2114
+ "next_page",
2115
+ "previous_page",
2116
+ "count"
2117
+ ]);
2118
+ /**
2119
+ * The resource carried by one response: its documented key, or else the one list
2120
+ * the response holds, so an endpoint whose key differs from the catalog still
2121
+ * exports instead of failing on a name.
2122
+ */
2123
+ const extractItems = (body, responseKey) => {
2124
+ if (responseKey in body) return body[responseKey];
2125
+ const lists = Object.entries(body).filter(([key, value]) => !PAGE_FRAME_KEYS.has(key) && Array.isArray(value));
2126
+ const [only] = lists;
2127
+ if (lists.length === 1 && only) return only[1];
2128
+ throw new Error(`Unexpected response shape: no "${responseKey}" list (keys: ${Object.keys(body).join(", ")})`);
2129
+ };
2130
+ /** `<subdomain>-<UTC timestamp>`, safe as a folder name on every OS. */
2131
+ const snapshotDirName = (subdomain, at) => `${subdomain.replace(/[^a-z0-9-]/gi, "_")}-${at.toISOString().replace(/[:.]/g, "-")}`;
2132
+ const listOf = (body, responseKey) => {
2133
+ const items = extractItems(body, responseKey);
2134
+ if (!Array.isArray(items)) throw new Error(`Unexpected response shape: "${responseKey}" is not a list`);
2135
+ return items;
2136
+ };
2137
+ const firstPage = async (subdomain, token, path) => {
2138
+ try {
2139
+ return await zendeskGet(subdomain, token, path, { ...CURSOR_FIRST_PAGE });
2140
+ } catch (err) {
2141
+ if (!(err instanceof ZendeskApiError && err.status === 400)) throw err;
2142
+ return zendeskGet(subdomain, token, path);
2143
+ }
2144
+ };
2145
+ const fetchList = async (subdomain, token, path, responseKey) => {
2146
+ const items = [];
2147
+ let body = await firstPage(subdomain, token, path);
2148
+ for (let pages = 1;; pages += 1) {
2149
+ items.push(...listOf(body, responseKey));
2150
+ const next = nextRequest(body, subdomain);
2151
+ if (next === void 0) return {
2152
+ items,
2153
+ truncated: false
2154
+ };
2155
+ if (pages >= 200) return {
2156
+ items,
2157
+ truncated: true
2158
+ };
2159
+ body = await zendeskGet(subdomain, token, next.path, next.params);
2160
+ }
2161
+ };
2162
+ const attachNested = async (subdomain, token, parents, nested) => {
2163
+ const result = {
2164
+ items: [],
2165
+ truncated: false,
2166
+ missing: 0
2167
+ };
2168
+ for (const parent of parents) {
2169
+ const id = parent[nested.idField];
2170
+ if (typeof id !== "string" && typeof id !== "number") {
2171
+ result.items.push(parent);
2172
+ continue;
2173
+ }
2174
+ try {
2175
+ const child = await fetchList(subdomain, token, nested.path(encodeURIComponent(String(id))), nested.responseKey);
2176
+ result.truncated ||= child.truncated;
2177
+ result.items.push({
2178
+ ...parent,
2179
+ [nested.attachAs]: child.items
2180
+ });
2181
+ } catch (err) {
2182
+ if (!(err instanceof Error) || err instanceof ZendeskApiError && err.status === 401) throw err;
2183
+ result.missing += 1;
2184
+ result.missingReason ??= `${nested.attachAs} of ${nested.idField} ${String(id)}: ${err.message}`;
2185
+ result.items.push(parent);
2186
+ }
2187
+ }
2188
+ return result;
2189
+ };
2190
+ const fetchResource = async (subdomain, token, spec) => {
2191
+ if (spec.single) {
2192
+ const body = await zendeskGet(subdomain, token, spec.path);
2193
+ return {
2194
+ data: extractItems(body, spec.responseKey),
2195
+ items: 1,
2196
+ truncated: false,
2197
+ nestedMissing: 0
2198
+ };
2199
+ }
2200
+ const list = await fetchList(subdomain, token, spec.path, spec.responseKey);
2201
+ const result = spec.nested ? await attachNested(subdomain, token, list.items, spec.nested) : {
2202
+ items: list.items,
2203
+ truncated: false,
2204
+ missing: 0
2205
+ };
2206
+ return {
2207
+ data: result.items,
2208
+ items: result.items.length,
2209
+ truncated: list.truncated || result.truncated,
2210
+ nestedMissing: result.missing,
2211
+ nestedReason: result.missingReason
2212
+ };
2213
+ };
2214
+ const zendeskErrorCode = (body) => {
2215
+ try {
2216
+ const parsed = JSON.parse(body);
2217
+ return typeof parsed.error === "string" ? parsed.error : void 0;
2218
+ } catch {
2219
+ return;
2220
+ }
2221
+ };
2222
+ const skipReason = (err) => {
2223
+ const code = zendeskErrorCode(err.body);
2224
+ const status = `${err.status}${code ? ` ${code}` : ""}`;
2225
+ return err.status === 403 ? `No access (${status}): the signed-in account cannot read it, or the plan lacks it.` : `Not available on this account (${status}): the feature is off or not on this plan, or the endpoint does not exist.`;
2226
+ };
2227
+ const tokenStillWorks = async (subdomain, token) => {
2228
+ try {
2229
+ await zendeskGet(subdomain, token, "/users/me");
2230
+ return true;
2231
+ } catch (err) {
2232
+ return !(err instanceof ZendeskApiError && err.status === 401);
2233
+ }
2234
+ };
2235
+ /**
2236
+ * Export one resource. A resource the account cannot read (403) or that is not
2237
+ * available on it (404) is skipped, and any other failure recorded, so one gap
2238
+ * never costs the rest of the export. A 401 is rethrown only when the token
2239
+ * itself is rejected, so the server's backstop can recover it.
2240
+ */
2241
+ const exportResource = async (ctx, snapshot, resource) => {
2242
+ const spec = CONFIG_RESOURCES[resource];
2243
+ const endpoint = `/api/v2${spec.path}`;
2244
+ const token = await ctx.getToken();
2245
+ try {
2246
+ const fetched = await fetchResource(ctx.subdomain, token, spec);
2247
+ const file = `${resource}.json`;
2248
+ await writeFile(join(snapshot, file), `${JSON.stringify(fetched.data, null, 2)}\n`, "utf8");
2249
+ return {
2250
+ resource,
2251
+ endpoint,
2252
+ status: "exported",
2253
+ items: fetched.items,
2254
+ file,
2255
+ truncated: fetched.truncated,
2256
+ ...fetched.nestedMissing > 0 && {
2257
+ nested_missing: fetched.nestedMissing,
2258
+ nested_missing_reason: fetched.nestedReason ?? ""
2259
+ }
2260
+ };
2261
+ } catch (err) {
2262
+ if (!(err instanceof Error)) throw err;
2263
+ if (err instanceof ZendeskApiError && err.status === 401) {
2264
+ if (!await tokenStillWorks(ctx.subdomain, token)) throw err;
2265
+ return {
2266
+ resource,
2267
+ endpoint,
2268
+ status: "failed",
2269
+ reason: "Unauthorized (401) on this endpoint, while /users/me does not reject the token."
2270
+ };
2271
+ }
2272
+ if (err instanceof ZendeskApiError && (err.status === 403 || err.status === 404)) return {
2273
+ resource,
2274
+ endpoint,
2275
+ status: "skipped",
2276
+ reason: skipReason(err)
2277
+ };
2278
+ return {
2279
+ resource,
2280
+ endpoint,
2281
+ status: "failed",
2282
+ reason: err.message
2283
+ };
2284
+ }
2285
+ };
2286
+ const REASON_CELL_MAX = 160;
2287
+ const WHITESPACE_RUN = /\s+/g;
2288
+ const PIPE = /\|/g;
2289
+ const reasonCell = (reason) => {
2290
+ const line = reason.replace(WHITESPACE_RUN, " ").replace(PIPE, "/").trim();
2291
+ return line.length > REASON_CELL_MAX ? `${line.slice(0, 159)}…` : line;
2292
+ };
2293
+ const statusCell = (entry) => {
2294
+ if (entry.status === "exported") {
2295
+ const notes = [...entry.truncated ? ["truncated"] : [], ...entry.nested_missing ? [`${entry.nested_missing} nested lists missing`] : []];
2296
+ return notes.length > 0 ? `exported (${notes.join(", ")})` : "exported";
2297
+ }
2298
+ return `${entry.status}: ${reasonCell(entry.reason)}`;
2299
+ };
2300
+ const formatSummary = (subdomain, snapshot, entries) => {
2301
+ const count = (status) => entries.filter((e) => e.status === status).length;
2302
+ const rows = entries.map((e) => `| ${e.resource} | ${statusCell(e)} | ${e.status === "exported" ? e.items : "-"} |`);
2303
+ return [
2304
+ `Exported the ${subdomain} account configuration to ${snapshot}`,
2305
+ `${count("exported")} exported, ${count("skipped")} skipped, ${count("failed")} failed. manifest.json has the per-resource details; each <resource>.json holds the raw Zendesk objects.`,
2306
+ "",
2307
+ "| Resource | Status | Items |",
2308
+ "|---|---|---|",
2309
+ ...rows
2310
+ ].join("\n");
2311
+ };
2312
+ const writeManifest = (snapshot, manifest) => writeFile(join(snapshot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
2313
+ /**
2314
+ * Opt-in: the admin namespace exists only when the operator configured an export
2315
+ * directory (`--export-dir`, stdio only). Off by default, so no existing surface
2316
+ * changes, notably a `single`-mode proxy's read-only hints.
2317
+ */
2318
+ const createAdminTools = (ctx) => ctx.exportDir ? [exportAccountConfig(ctx, ctx.exportDir)] : [];
2319
+ const exportAccountConfig = (ctx, exportDir) => ({
2320
+ name: "export_account_config",
2321
+ namespace: "admin",
2322
+ readOnly: true,
2323
+ title: "Export Zendesk Account Configuration",
2324
+ description: "Export the Zendesk account's admin configuration to local JSON files, one per resource: business rules (triggers, automations, macros, views), ticket forms, fields and statuses, SLA policies, schedules with their holidays, groups, roles, brands, webhooks, account settings and more. Use it to audit, document, diff or migrate a Zendesk setup, then read the files for the details instead of pulling them through the conversation; to look up one field id, macro, view or SLA policy during ticket work, use list_ticket_fields, list_macros, list_views or list_sla_policies instead. It only reads from Zendesk; on the machine running the server it creates a new timestamped folder in the operator's export directory and never overwrites an earlier export. Returns the folder path and a per-resource summary: items exported, or why a resource was skipped (403: no access; 404: not available on this account) or failed. Needs an admin sign-in; available only when the server was started with an export directory.",
2325
+ inputSchema: z.object({ resources: z.array(z.enum(RESOURCE_KEYS)).min(1).optional().describe("Which parts of the configuration to export, by catalog name (e.g. [\"triggers\", \"automations\", \"ticket_forms\"]). Omit to export the whole catalog, which is what an audit or a migration needs.") }),
2326
+ annotations: {
2327
+ readOnlyHint: false,
2328
+ destructiveHint: false,
2329
+ idempotentHint: false,
2330
+ openWorldHint: true
2331
+ },
2332
+ handler: async (params) => {
2333
+ const { resources } = params;
2334
+ const selected = RESOURCE_KEYS.filter((key) => resources?.includes(key) ?? true);
2335
+ await ctx.getToken();
2336
+ const exportedAt = /* @__PURE__ */ new Date();
2337
+ await mkdir(exportDir, { recursive: true });
2338
+ const snapshot = join(exportDir, snapshotDirName(ctx.subdomain, exportedAt));
2339
+ await mkdir(snapshot);
2340
+ const manifest = {
2341
+ subdomain: ctx.subdomain,
2342
+ exported_at: exportedAt.toISOString()
2343
+ };
2344
+ const entries = [];
2345
+ try {
2346
+ for (const resource of selected) entries.push(await exportResource(ctx, snapshot, resource));
2347
+ } catch (err) {
2348
+ const aborted = err instanceof Error ? err.message : String(err);
2349
+ await writeManifest(snapshot, {
2350
+ ...manifest,
2351
+ aborted,
2352
+ resources: entries
2353
+ });
2354
+ throw err;
2355
+ }
2356
+ await writeManifest(snapshot, {
2357
+ ...manifest,
2358
+ resources: entries
2359
+ });
2360
+ return { content: [{
2361
+ type: "text",
2362
+ text: formatSummary(ctx.subdomain, snapshot, entries)
2363
+ }] };
2364
+ }
2365
+ });
2366
+ //#endregion
1867
2367
  //#region src/utils/article-order.ts
1868
2368
  const hasPositionInversion = (order) => {
1869
2369
  for (let i = 0; i < order.length - 1; i += 1) {
@@ -4345,7 +4845,8 @@ const createAllTools = (ctx) => [
4345
4845
  ...createTicketRelationTools(ctx),
4346
4846
  ...createSearchTools(ctx),
4347
4847
  ...createHelpCenterTools(ctx),
4348
- ...createUserTools(ctx)
4848
+ ...createUserTools(ctx),
4849
+ ...createAdminTools(ctx)
4349
4850
  ];
4350
4851
  //#endregion
4351
4852
  //#region src/utils/validation.ts
@@ -4414,6 +4915,10 @@ const NAMESPACE_LABELS = {
4414
4915
  users: {
4415
4916
  toolName: "zendesk_users",
4416
4917
  title: "Zendesk Users"
4918
+ },
4919
+ admin: {
4920
+ toolName: "zendesk_admin",
4921
+ title: "Zendesk Admin"
4417
4922
  }
4418
4923
  };
4419
4924
  const summarizeDescription = (description) => {
@@ -4595,7 +5100,8 @@ const createMcpServer = (config, getToken, logger = silentLogger, onUnauthorized
4595
5100
  const tools = createAllTools({
4596
5101
  subdomain: config.subdomain,
4597
5102
  getToken,
4598
- localFileAccess: config.transport === "stdio"
5103
+ localFileAccess: config.transport === "stdio",
5104
+ exportDir: config.exportDir
4599
5105
  });
4600
5106
  registerToolset(server, {
4601
5107
  config,
@@ -4636,6 +5142,10 @@ const TOOL_MODULES = [
4636
5142
  {
4637
5143
  file: "users.ts",
4638
5144
  factory: "createUserTools"
5145
+ },
5146
+ {
5147
+ file: "admin.ts",
5148
+ factory: "createAdminTools"
4639
5149
  }
4640
5150
  ];
4641
5151
  /**
@@ -4667,7 +5177,8 @@ const createReloadableServer = (config, getToken, logger = silentLogger, onUnaut
4667
5177
  const ctx = {
4668
5178
  subdomain: config.subdomain,
4669
5179
  getToken,
4670
- localFileAccess: config.transport === "stdio"
5180
+ localFileAccess: config.transport === "stdio",
5181
+ exportDir: config.exportDir
4671
5182
  };
4672
5183
  const params = {
4673
5184
  config,
@@ -4708,7 +5219,7 @@ const createReloadableServer = (config, getToken, logger = silentLogger, onUnaut
4708
5219
  const registerReloadTool = (server, reload, logger = silentLogger) => {
4709
5220
  server.registerTool("reload_tools", {
4710
5221
  title: "Reload tools from source (dev)",
4711
- description: "Dev only. Re-imports the Zendesk tool modules from source and re-registers them on this live session, so tool code you just edited takes effect without restarting the server or reconnecting the client. Call it once at the end of an edit cycle, before testing your changes; the refreshed tool list is announced via tools/list_changed. Only the tool modules (tickets, search, help_center, users) are reloaded — edits to shared infrastructure (HTTP client, shared definitions, server wiring) still require a full restart. Takes no arguments and makes no Zendesk API calls.",
5222
+ description: "Dev only. Re-imports the Zendesk tool modules from source and re-registers them on this live session, so tool code you just edited takes effect without restarting the server or reconnecting the client. Call it once at the end of an edit cycle, before testing your changes; the refreshed tool list is announced via tools/list_changed. Only the tool modules (tickets, search, help_center, users, admin) are reloaded — edits to shared infrastructure (HTTP client, shared definitions, server wiring) still require a full restart. Takes no arguments and makes no Zendesk API calls.",
4712
5223
  inputSchema: z.object({}).strict(),
4713
5224
  annotations: {
4714
5225
  readOnlyHint: false,
@@ -5198,7 +5709,8 @@ const installShutdown = (options) => {
5198
5709
  const buildOAuthTokenSource = (config, logger) => createTokenStore({
5199
5710
  subdomain: config.subdomain,
5200
5711
  oauthClientId: config.oauthClientId,
5201
- callbackPort: config.callbackPort
5712
+ callbackPort: config.callbackPort,
5713
+ readOnly: config.readOnly
5202
5714
  }, logger);
5203
5715
  const buildStdioTokenSource = (config, logger) => {
5204
5716
  if (config.zendeskEmail && config.zendeskApiToken) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincolnminto/zendesk-mcp-server",
3
- "version": "2.24.0",
3
+ "version": "2.26.0",
4
4
  "mcpName": "io.github.lincolnminto/zendesk-mcp-server",
5
5
  "description": "Deep Zendesk MCP server for your AI assistant: search, draft, update and translate Help Center articles and manage Support tickets end to end — comments, triage and image attachments.",
6
6
  "type": "module",