@lincolnminto/zendesk-mcp-server 2.23.0 → 2.25.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 +3 -1
  2. package/dist/index.js +115 -26
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -62,7 +62,9 @@ differently.
62
62
  - A tool surface you can cap. Expose every operation as its own tool, group them
63
63
  into namespace proxies, or collapse everything into a single unified tool. You
64
64
  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)).
65
+ loads only the surface it needs (see [Tool surface](#tool-surface)). Read-only
66
+ over stdio also signs in with Zendesk's `read` scope, so Zendesk itself refuses
67
+ a write ([how](docs/configuration.md#read-only-all-the-way-to-zendesk)).
66
68
  - Two deployment shapes, same auth story. Run it on your laptop as a stdio MCP
67
69
  server, or deploy it as a private remote MCP server reached over HTTP, with one
68
70
  Zendesk session per request and each client carrying its own user's token.
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync }
4
4
  import { createServer } from "node:http";
5
5
  import { homedir, release } from "node:os";
6
6
  import open from "open";
7
- import { dirname, join } from "node:path";
7
+ import { basename, dirname, extname, isAbsolute, join } from "node:path";
8
8
  import { fileURLToPath, pathToFileURL } from "node:url";
9
9
  import { parseArgs } from "node:util";
10
10
  import * as z from "zod/v4";
@@ -20,6 +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
24
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
24
25
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
25
26
  //#region src/auth/api-token.ts
@@ -130,6 +131,7 @@ const positiveIntEnv = (name, fallback) => {
130
131
  const CHARACTER_LIMIT = positiveIntEnv("ZENDESK_CHARACTER_LIMIT", 25e3);
131
132
  const ARTICLE_RESOURCES_SCAN_MAX_PAGES = positiveIntEnv("ZENDESK_ARTICLE_RESOURCES_SCAN_MAX_PAGES", 20);
132
133
  const MAX_ATTACHMENT_BYTES = positiveIntEnv("ZENDESK_MAX_ATTACHMENT_BYTES", 5242880);
134
+ const MAX_UPLOAD_BYTES = positiveIntEnv("ZENDESK_MAX_UPLOAD_BYTES", 52428800);
133
135
  const MAX_EMBEDDED_IMAGE_COUNT = positiveIntEnv("ZENDESK_MAX_EMBEDDED_IMAGES", 10);
134
136
  const MAX_COMMENT_PAGES = positiveIntEnv("ZENDESK_MAX_COMMENT_PAGES", 10);
135
137
  const REORDER_CONFIRM_THRESHOLD = positiveIntEnv("ZENDESK_REORDER_CONFIRM_THRESHOLD", 20);
@@ -305,7 +307,7 @@ const startBrowserAuth = (config, logger = silentLogger) => {
305
307
  response_type: "code",
306
308
  client_id: oauthClientId,
307
309
  redirect_uri: redirectUri,
308
- scope: "read write",
310
+ scope: config.scope ?? "read write",
309
311
  code_challenge: codeChallenge,
310
312
  code_challenge_method: "S256"
311
313
  });
@@ -376,6 +378,12 @@ const refreshAccessToken = async (config, logger = silentLogger) => {
376
378
  return tokenData;
377
379
  };
378
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
379
387
  //#region src/utils/package-info.ts
380
388
  const FALLBACK = {
381
389
  name: "@lincolnminto/zendesk-mcp-server",
@@ -442,13 +450,16 @@ const safeName = (subdomain) => subdomain.replace(/[^a-z0-9-]/gi, "_");
442
450
  * Path to the token file for a subdomain. Each subdomain gets its **own** file
443
451
  * (`<subdomain>.json`, a single record) so concurrent processes for different
444
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.
445
456
  * `ZENDESK_TOKEN_FILE` overrides with an explicit path (a single file; use the
446
- * default layout for multi-subdomain installs).
457
+ * default layout for multi-subdomain or mixed read-only installs).
447
458
  */
448
- const resolveTokenPath = (subdomain) => {
459
+ const resolveTokenPath = (subdomain, { readOnly = false } = {}) => {
449
460
  const override = process.env["ZENDESK_TOKEN_FILE"];
450
461
  if (override) return override;
451
- return join(configDir(), `${safeName(subdomain)}.json`);
462
+ return join(configDir(), `${safeName(subdomain)}${readOnly ? ".read" : ""}.json`);
452
463
  };
453
464
  const writeFileAtomic = (path, record) => {
454
465
  const dir = dirname(path);
@@ -493,8 +504,17 @@ const createAuthRequiredError = (authorizeUrl) => Object.assign(/* @__PURE__ */
493
504
  });
494
505
  const expiryFrom = (expiresIn) => typeof expiresIn === "number" ? Date.now() + expiresIn * 1e3 : void 0;
495
506
  const createTokenStore = (config, logger = silentLogger) => {
496
- const tokenPath = resolveTokenPath(config.subdomain);
497
- 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();
498
518
  if (token) logger.debug("oauth_token_loaded_from_disk");
499
519
  let authorizeUrl;
500
520
  let starting;
@@ -518,10 +538,13 @@ const createTokenStore = (config, logger = silentLogger) => {
518
538
  oauthClientId: config.oauthClientId,
519
539
  refreshToken: current.refreshToken
520
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)}`);
521
543
  token = {
522
544
  accessToken: result.access_token,
523
545
  refreshToken: result.refresh_token ?? current.refreshToken,
524
- expiresAt: expiryFrom(result.expires_in)
546
+ expiresAt: expiryFrom(result.expires_in),
547
+ scope
525
548
  };
526
549
  probedUnknownExpiry = true;
527
550
  persist(token);
@@ -541,14 +564,21 @@ const createTokenStore = (config, logger = silentLogger) => {
541
564
  return startBrowserAuth({
542
565
  subdomain: config.subdomain,
543
566
  oauthClientId: config.oauthClientId,
544
- callbackPort: config.callbackPort
567
+ callbackPort: config.callbackPort,
568
+ scope: requestedScope(readOnly)
545
569
  }, logger).then((started) => {
546
570
  authorizeUrl = started.authorizeUrl;
547
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
+ }
548
577
  token = {
549
578
  accessToken: result.access_token,
550
579
  refreshToken: result.refresh_token,
551
- expiresAt: expiryFrom(result.expires_in)
580
+ expiresAt: expiryFrom(result.expires_in),
581
+ scope
552
582
  };
553
583
  probedUnknownExpiry = true;
554
584
  persist(token);
@@ -590,7 +620,8 @@ const createTokenStore = (config, logger = silentLogger) => {
590
620
  token = {
591
621
  accessToken: token.accessToken,
592
622
  refreshToken: token.refreshToken,
593
- expiresAt: 0
623
+ expiresAt: 0,
624
+ scope: token.scope
594
625
  };
595
626
  persist(token);
596
627
  } else {
@@ -3220,6 +3251,47 @@ const createTicketRelationTools = (ctx) => {
3220
3251
  //#endregion
3221
3252
  //#region src/tools/tickets.ts
3222
3253
  const MAX_ATTACHMENT_MB = Number.parseFloat((MAX_ATTACHMENT_BYTES / 1048576).toFixed(2));
3254
+ const CONTENT_TYPE_BY_EXTENSION = /* @__PURE__ */ new Map([
3255
+ [".png", "image/png"],
3256
+ [".jpg", "image/jpeg"],
3257
+ [".jpeg", "image/jpeg"],
3258
+ [".gif", "image/gif"],
3259
+ [".webp", "image/webp"],
3260
+ [".pdf", "application/pdf"],
3261
+ [".txt", "text/plain"],
3262
+ [".log", "text/plain"],
3263
+ [".csv", "text/csv"],
3264
+ [".json", "application/json"],
3265
+ [".xml", "application/xml"],
3266
+ [".html", "text/html"],
3267
+ [".md", "text/markdown"],
3268
+ [".sql", "application/sql"],
3269
+ [".zip", "application/zip"]
3270
+ ]);
3271
+ const contentTypeOf = (filePath) => CONTENT_TYPE_BY_EXTENSION.get(extname(filePath).toLowerCase()) ?? "application/octet-stream";
3272
+ const readLocalFile = async (filePath) => {
3273
+ if (!isAbsolute(filePath)) return { problem: "not an absolute path; pass the full path to the file" };
3274
+ try {
3275
+ const stats = await stat(filePath);
3276
+ if (!stats.isFile()) return { problem: "not a regular file" };
3277
+ if (stats.size > MAX_UPLOAD_BYTES) return { problem: `${stats.size} bytes, over the ${MAX_UPLOAD_BYTES}-byte limit per file (ZENDESK_MAX_UPLOAD_BYTES)` };
3278
+ const data = await readFile(filePath);
3279
+ return { file: {
3280
+ file_name: basename(filePath),
3281
+ data,
3282
+ content_type: contentTypeOf(filePath)
3283
+ } };
3284
+ } catch (error) {
3285
+ const code = error.code;
3286
+ return { problem: code === "ENOENT" ? "file not found" : `cannot be read (${code})` };
3287
+ }
3288
+ };
3289
+ const readLocalFiles = async (paths) => {
3290
+ const results = await Promise.all(paths.map(readLocalFile));
3291
+ const problems = results.flatMap((result, i) => "problem" in result ? [`- ${paths[i]}: ${result.problem}`] : []);
3292
+ if (problems.length > 0) throw new Error(`attachment_paths rejected; nothing was uploaded or posted:\n${problems.join("\n")}`);
3293
+ return results.flatMap((result) => "file" in result ? [result.file] : []);
3294
+ };
3223
3295
  const formatReference = (attachment) => `**${attachment.file_name}** (id ${attachment.id}, ${attachment.content_type}, ${attachment.size} bytes) — ${attachment.content_url}`;
3224
3296
  const buildEmbeddedImageBlocks = async (subdomain, token, attachment, reference) => {
3225
3297
  const { data, contentType } = await fetchZendeskBinary(subdomain, token, attachment.content_url);
@@ -3491,16 +3563,26 @@ const formatMacroPreviewDiff = (ticketId, macroId, before, result) => {
3491
3563
  return lines.join("\n");
3492
3564
  };
3493
3565
  const createTicketTools = (ctx) => {
3494
- const { subdomain, getToken } = ctx;
3566
+ const { subdomain, getToken, localFileAccess } = ctx;
3495
3567
  const attachmentSchema = z.object({
3496
3568
  file_name: z.string().min(1).describe("File name, e.g. \"app.log\" or \"screenshot.png\"."),
3497
3569
  file_base64: z.string().min(1).base64().describe("File content encoded as base64."),
3498
3570
  content_type: z.string().min(1).default("application/octet-stream").describe("MIME type, e.g. \"text/plain\", \"image/png\", \"application/pdf\".")
3499
3571
  });
3572
+ const attachmentPathsSchema = (target) => z.array(z.string().min(1).describe("Absolute path, e.g. \"/home/me/logs/app.log\".")).optional().describe(`Absolute paths of files to attach to this ${target}, read by the server from the machine it runs on (stdio only; refused over HTTP). Prefer this over attachments for any file already on disk: the call carries no base64. File name = the basename; content type inferred from the extension (unknown: application/octet-stream); at most ZENDESK_MAX_UPLOAD_BYTES per file (default 50 MiB). Every path is checked first: a missing, non-regular or oversize file fails the call with nothing uploaded or posted. Combinable with attachments, which upload first.`);
3573
+ const collectFiles = async (attachments = [], attachmentPaths = []) => {
3574
+ if (attachmentPaths.length > 0 && !localFileAccess) throw new Error("attachment_paths is not available over the HTTP transport: the paths would be read on the server host, not on your machine. Send the files with attachments (base64) instead.");
3575
+ const fromDisk = await readLocalFiles(attachmentPaths);
3576
+ return [...attachments.map((file) => ({
3577
+ file_name: file.file_name,
3578
+ data: Buffer.from(file.file_base64, "base64"),
3579
+ content_type: file.content_type
3580
+ })), ...fromDisk];
3581
+ };
3500
3582
  const uploadAttachments = async (token, files) => {
3501
3583
  let uploadToken;
3502
3584
  for (const file of files) {
3503
- const { upload } = await zendeskUpload(subdomain, token, file.file_name, Buffer.from(file.file_base64, "base64"), file.content_type, uploadToken);
3585
+ const { upload } = await zendeskUpload(subdomain, token, file.file_name, file.data, file.content_type, uploadToken);
3504
3586
  uploadToken = upload.token;
3505
3587
  }
3506
3588
  return uploadToken;
@@ -3805,11 +3887,12 @@ const createTicketTools = (ctx) => {
3805
3887
  namespace: "tickets",
3806
3888
  readOnly: false,
3807
3889
  title: "Add Private Note",
3808
- description: "Add an internal note (not visible to requester) to a ticket, optionally with file attachments (uploaded via the Zendesk Uploads API and carried on the note). The note is appended to the ticket thread; use add_public_comment instead when the reply should be visible to the requester.",
3890
+ description: "Add an internal note (not visible to requester) to a ticket, optionally with file attachments (uploaded via the Zendesk Uploads API and carried on the note). The note is appended to the ticket thread; use add_public_comment instead when the reply should be visible to the requester. Attach a file already on disk by its absolute path in attachment_paths (the server reads it, so no base64 goes in the call) rather than in attachments; if any path is unusable the call fails before anything is uploaded or posted. Returns a confirmation with the number of files attached.",
3809
3891
  inputSchema: z.object({
3810
3892
  ticket_id: z.number().int().describe("Ticket ID — the numeric id of the ticket to annotate. Obtain it from search_tickets or list_tickets."),
3811
3893
  body: z.string().min(1).describe("Note text (internal, agent-only). Plain text or HTML; not shown to the requester."),
3812
- attachments: z.array(attachmentSchema).optional().describe("Files to attach to this note (base64-encoded content).")
3894
+ attachments: z.array(attachmentSchema).optional().describe("Files to attach to this note (base64-encoded content). For a file already on disk, use attachment_paths instead."),
3895
+ attachment_paths: attachmentPathsSchema("note")
3813
3896
  }),
3814
3897
  annotations: {
3815
3898
  readOnlyHint: false,
@@ -3818,9 +3901,10 @@ const createTicketTools = (ctx) => {
3818
3901
  openWorldHint: true
3819
3902
  },
3820
3903
  handler: async (params) => {
3821
- const { ticket_id, body, attachments } = params;
3904
+ const { ticket_id, body, attachments, attachment_paths } = params;
3905
+ const files = await collectFiles(attachments, attachment_paths);
3822
3906
  const token = await getToken();
3823
- const uploads = attachments?.length ? [await uploadAttachments(token, attachments)] : void 0;
3907
+ const uploads = files.length > 0 ? [await uploadAttachments(token, files)] : void 0;
3824
3908
  await zendeskPut(subdomain, token, `/tickets/${ticket_id}`, { ticket: { comment: {
3825
3909
  body,
3826
3910
  public: false,
@@ -3828,7 +3912,7 @@ const createTicketTools = (ctx) => {
3828
3912
  } } });
3829
3913
  return { content: [{
3830
3914
  type: "text",
3831
- text: `Private note added to ticket #${ticket_id}${formatAttachmentSuffix(attachments?.length)}.`
3915
+ text: `Private note added to ticket #${ticket_id}${formatAttachmentSuffix(files.length)}.`
3832
3916
  }] };
3833
3917
  }
3834
3918
  },
@@ -3837,11 +3921,12 @@ const createTicketTools = (ctx) => {
3837
3921
  namespace: "tickets",
3838
3922
  readOnly: false,
3839
3923
  title: "Add Public Comment",
3840
- description: "Add a public comment (visible to requester) to a ticket, optionally with file attachments (uploaded via the Zendesk Uploads API and carried on the comment). The comment is appended to the ticket thread and emails the requester; use add_private_note instead for an internal, agent-only note.",
3924
+ description: "Add a public comment (visible to requester) to a ticket, optionally with file attachments (uploaded via the Zendesk Uploads API and carried on the comment). The comment is appended to the ticket thread and emails the requester; use add_private_note instead for an internal, agent-only note. Attach a file already on disk by its absolute path in attachment_paths (the server reads it, so no base64 goes in the call) rather than in attachments; if any path is unusable the call fails before anything is uploaded or posted. Returns a confirmation with the number of files attached.",
3841
3925
  inputSchema: z.object({
3842
3926
  ticket_id: z.number().int().describe("Ticket ID — the numeric id of the ticket to reply on. Obtain it from search_tickets or list_tickets."),
3843
3927
  body: z.string().min(1).describe("Comment text sent to the requester. Plain text or HTML; visible in the ticket."),
3844
- attachments: z.array(attachmentSchema).optional().describe("Files to attach to this comment (base64-encoded content).")
3928
+ attachments: z.array(attachmentSchema).optional().describe("Files to attach to this comment (base64-encoded content). For a file already on disk, use attachment_paths instead."),
3929
+ attachment_paths: attachmentPathsSchema("comment")
3845
3930
  }),
3846
3931
  annotations: {
3847
3932
  readOnlyHint: false,
@@ -3850,9 +3935,10 @@ const createTicketTools = (ctx) => {
3850
3935
  openWorldHint: true
3851
3936
  },
3852
3937
  handler: async (params) => {
3853
- const { ticket_id, body, attachments } = params;
3938
+ const { ticket_id, body, attachments, attachment_paths } = params;
3939
+ const files = await collectFiles(attachments, attachment_paths);
3854
3940
  const token = await getToken();
3855
- const uploads = attachments?.length ? [await uploadAttachments(token, attachments)] : void 0;
3941
+ const uploads = files.length > 0 ? [await uploadAttachments(token, files)] : void 0;
3856
3942
  await zendeskPut(subdomain, token, `/tickets/${ticket_id}`, { ticket: { comment: {
3857
3943
  body,
3858
3944
  public: true,
@@ -3860,7 +3946,7 @@ const createTicketTools = (ctx) => {
3860
3946
  } } });
3861
3947
  return { content: [{
3862
3948
  type: "text",
3863
- text: `Public comment added to ticket #${ticket_id}${formatAttachmentSuffix(attachments?.length)}.`
3949
+ text: `Public comment added to ticket #${ticket_id}${formatAttachmentSuffix(files.length)}.`
3864
3950
  }] };
3865
3951
  }
3866
3952
  },
@@ -4537,7 +4623,8 @@ const createMcpServer = (config, getToken, logger = silentLogger, onUnauthorized
4537
4623
  const server = createServerShell(config, logger);
4538
4624
  const tools = createAllTools({
4539
4625
  subdomain: config.subdomain,
4540
- getToken
4626
+ getToken,
4627
+ localFileAccess: config.transport === "stdio"
4541
4628
  });
4542
4629
  registerToolset(server, {
4543
4630
  config,
@@ -4608,7 +4695,8 @@ const createReloadableServer = (config, getToken, logger = silentLogger, onUnaut
4608
4695
  const server = createServerShell(config, logger);
4609
4696
  const ctx = {
4610
4697
  subdomain: config.subdomain,
4611
- getToken
4698
+ getToken,
4699
+ localFileAccess: config.transport === "stdio"
4612
4700
  };
4613
4701
  const params = {
4614
4702
  config,
@@ -5139,7 +5227,8 @@ const installShutdown = (options) => {
5139
5227
  const buildOAuthTokenSource = (config, logger) => createTokenStore({
5140
5228
  subdomain: config.subdomain,
5141
5229
  oauthClientId: config.oauthClientId,
5142
- callbackPort: config.callbackPort
5230
+ callbackPort: config.callbackPort,
5231
+ readOnly: config.readOnly
5143
5232
  }, logger);
5144
5233
  const buildStdioTokenSource = (config, logger) => {
5145
5234
  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.23.0",
3
+ "version": "2.25.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",