airbyte_ops_mcp.mcp.zendesk_ops

MCP tools for Zendesk Support operations.

This module exposes tools for pulling Zendesk tickets (and their comments), posting internal (private, agent-only) notes, and notifying Slack reviewers after spam triage through the hosted Ops MCP server. It can also set the Ticket Complexity total score field on Solved or Closed tickets.

MCP reference

MCP primitives registered by the zendesk_ops module of the airbyte-internal-ops server: 8 tool(s), 0 prompt(s), 0 resource(s).

Tools (8)

add_zendesk_ticket_tags

Add tags to a Zendesk ticket by its numeric ID.

Tags are Zendesk's label mechanism. This reads the ticket's current tags and writes back the union (existing + supplied) via a ticket update, so the ticket's existing tags — and any tagger-backed custom fields — are preserved and never dropped. Adding a tag that is already present is a no-op.

The numeric ticket_id must already be known; this tool does not search for tickets. Credentials are read from the server environment (ZENDESK_SUBDOMAIN, ZENDESK_EMAIL, ZENDESK_API_TOKEN); this tool never accepts or logs them.

Parameters:

Name Type Required Default Description
ticket_id integer yes — The numeric Zendesk ticket ID to tag.
tags array<string> yes — Tags to add to the ticket. Appended to the ticket's existing tags (never clobbered). At least one non-empty tag is required.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "ticket_id": {
      "description": "The numeric Zendesk ticket ID to tag.",
      "type": "integer"
    },
    "tags": {
      "description": "Tags to add to the ticket. Appended to the ticket's existing tags (never clobbered). At least one non-empty tag is required.",
      "items": {
        "type": "string"
      },
      "type": "array"
    }
  },
  "required": [
    "ticket_id",
    "tags"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from the `add_zendesk_ticket_tags` tool.",
  "properties": {
    "success": {
      "description": "Whether the tags were added.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "ticket_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk ticket ID."
    },
    "tags": {
      "description": "The ticket's full tag list after the update.",
      "items": {
        "type": "string"
      },
      "type": "array"
    }
  },
  "required": [
    "success",
    "message"
  ],
  "type": "object"
}

create_zendesk_outreach_ticket

Create an idempotent ticket for the approved outreach workflow only.

This tool cannot send anything public. The first comment is always private and visible only to Zendesk agents. CCs are applied in a separate update with no comment because Zendesk does not update email CCs when an internal note is added in the same update. Re-running on an existing ticket ensures the requested CCs without posting another comment. Callers must not run concurrent calls with the same external_id; duplicates are detected after creation but not prevented.

Parameters:

Name Type Required Default Description
external_id string yes — Idempotency key beginning with outreach:.
ticket_type enum("problem", "incident") yes — Zendesk ticket type.
subject string yes — Non-empty ticket subject.
internal_note_html string yes — Non-empty first comment, posted as a private HTML note.
problem_id integer | null no null Required parent problem ticket ID for an incident.
tags array<string> no [] Ticket tags.
ticket_form_name string no "Support Outreach" Active ticket form name.
requester object | null no null Requester contact; required for incidents; not allowed for problems.
cc array<object> no [] Requester contacts to CC; incidents only; Zendesk allows at most 48.
assignee_email string | null no null Optional assignee email address.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "external_id": {
      "description": "Idempotency key beginning with `outreach:`.",
      "type": "string"
    },
    "ticket_type": {
      "description": "Zendesk ticket type.",
      "enum": [
        "problem",
        "incident"
      ],
      "type": "string"
    },
    "subject": {
      "description": "Non-empty ticket subject.",
      "type": "string"
    },
    "internal_note_html": {
      "description": "Non-empty first comment, posted as a private HTML note.",
      "type": "string"
    },
    "problem_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Required parent problem ticket ID for an incident."
    },
    "tags": {
      "default": [],
      "description": "Ticket tags.",
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "ticket_form_name": {
      "default": "Support Outreach",
      "description": "Active ticket form name.",
      "type": "string"
    },
    "requester": {
      "anyOf": [
        {
          "description": "A Zendesk outreach requester or CC contact.",
          "properties": {
            "email": {
              "description": "Contact email address.",
              "type": "string"
            },
            "name": {
              "description": "Contact name.",
              "type": "string"
            }
          },
          "required": [
            "email",
            "name"
          ],
          "type": "object"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Requester contact; required for incidents; not allowed for problems."
    },
    "cc": {
      "default": [],
      "description": "Requester contacts to CC; incidents only; Zendesk allows at most 48.",
      "items": {
        "description": "A Zendesk outreach requester or CC contact.",
        "properties": {
          "email": {
            "description": "Contact email address.",
            "type": "string"
          },
          "name": {
            "description": "Contact name.",
            "type": "string"
          }
        },
        "required": [
          "email",
          "name"
        ],
        "type": "object"
      },
      "type": "array"
    },
    "assignee_email": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Optional assignee email address."
    }
  },
  "required": [
    "external_id",
    "ticket_type",
    "subject",
    "internal_note_html"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from `create_zendesk_outreach_ticket`.",
  "properties": {
    "success": {
      "description": "Whether the ticket was found or created.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "created": {
      "description": "Whether a new ticket was created.",
      "type": "boolean"
    },
    "ticket_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk ticket ID."
    },
    "url": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Agent-facing ticket URL."
    },
    "status": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket status."
    },
    "type": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket type."
    },
    "problem_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Problem ticket ID."
    },
    "requester_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Requester user ID."
    },
    "submitter_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Submitter user ID."
    },
    "assignee_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Assignee user ID."
    },
    "organization_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Associated organization ID."
    },
    "ticket_form_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket form ID."
    },
    "email_cc_ids": {
      "anyOf": [
        {
          "items": {
            "type": "integer"
          },
          "type": "array"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk user IDs included as email CCs."
    },
    "tags": {
      "description": "Ticket tags.",
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "duplicate_ticket_ids": {
      "description": "Existing ticket IDs when an external ID has duplicates.",
      "items": {
        "type": "integer"
      },
      "type": "array"
    }
  },
  "required": [
    "success",
    "message",
    "created"
  ],
  "type": "object"
}

find_zendesk_organization_by_airbyte_org_id

Find Zendesk organizations by their airbyte_org_id custom field.

Parameters:

Name Type Required Default Description
airbyte_org_id string yes — Airbyte organization UUID stored on the Zendesk organization.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "airbyte_org_id": {
      "description": "Airbyte organization UUID stored on the Zendesk organization.",
      "type": "string"
    }
  },
  "required": [
    "airbyte_org_id"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from `find_zendesk_organization_by_airbyte_org_id`.",
  "properties": {
    "success": {
      "description": "Whether the search succeeded.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "organizations": {
      "description": "Matching Zendesk organizations.",
      "items": {
        "description": "A concise Zendesk organization search result.",
        "properties": {
          "id": {
            "description": "Zendesk organization ID.",
            "type": "integer"
          },
          "name": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Organization name."
          },
          "url": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Zendesk API organization URL."
          }
        },
        "required": [
          "id"
        ],
        "type": "object"
      },
      "type": "array"
    }
  },
  "required": [
    "success",
    "message"
  ],
  "type": "object"
}

get_zendesk_ticket

Retrieve a Zendesk Support ticket by its numeric ID.

Returns the ticket's subject, status, description, tags, and requester/ organization identifiers. Set include_comments to True to also pull the ticket's comment thread (public replies and internal notes), oldest first; only the first page (up to 100 comments) is returned.

Credentials are read from the server environment (ZENDESK_SUBDOMAIN, ZENDESK_EMAIL, ZENDESK_API_TOKEN); this tool never accepts or logs them.

Parameters:

Name Type Required Default Description
ticket_id integer yes — The numeric Zendesk ticket ID to retrieve.
include_comments boolean no false When True, also fetch the ticket's comments (oldest first), including any attachment metadata. Only the first page (up to 100 comments) is returned. Defaults to False to keep responses small.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "ticket_id": {
      "description": "The numeric Zendesk ticket ID to retrieve.",
      "type": "integer"
    },
    "include_comments": {
      "default": false,
      "description": "When `True`, also fetch the ticket's comments (oldest first), including any attachment metadata. Only the first page (up to 100 comments) is returned. Defaults to `False` to keep responses small.",
      "type": "boolean"
    }
  },
  "required": [
    "ticket_id"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from the `get_zendesk_ticket` tool.",
  "properties": {
    "success": {
      "description": "Whether the ticket was retrieved.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "ticket_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk ticket ID."
    },
    "subject": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket subject line."
    },
    "status": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket status (e.g. `open`, `pending`, `solved`, `closed`)."
    },
    "description": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "The ticket's first comment / description text."
    },
    "priority": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket priority, if set."
    },
    "tags": {
      "description": "Ticket tags.",
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "requester_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "User ID of the ticket requester."
    },
    "type": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk ticket type."
    },
    "problem_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Associated problem ticket ID, if any."
    },
    "assignee_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "User ID of the ticket assignee."
    },
    "submitter_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "User ID of the ticket submitter."
    },
    "ticket_form_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket form ID used by the ticket."
    },
    "email_cc_ids": {
      "anyOf": [
        {
          "items": {
            "type": "integer"
          },
          "type": "array"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk user IDs included as email CCs."
    },
    "external_id": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "External idempotency identifier for the ticket."
    },
    "organization_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Organization ID associated with the ticket."
    },
    "created_at": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "ISO-8601 ticket creation timestamp."
    },
    "updated_at": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "ISO-8601 ticket last-updated timestamp."
    },
    "url": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Agent-facing Zendesk URL for the ticket."
    },
    "via_channel": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Channel the ticket came in through (e.g. `web`, `email`)."
    },
    "via_source_rel": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Source relationship (e.g. `follow_up` for follow-up tickets)."
    },
    "follow_up_source_ticket_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "For follow-up tickets, the ID of the original (closed) ticket this one follows up on. `None` when the ticket is not a follow-up."
    },
    "custom_fields": {
      "description": "Ticket custom fields (`id`/`value` pairs).",
      "items": {
        "description": "A single custom field value on a Zendesk ticket.",
        "properties": {
          "id": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Custom field ID."
          },
          "value": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              },
              {
                "type": "number"
              },
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Custom field value (may be null when unset)."
          }
        },
        "type": "object"
      },
      "type": "array"
    },
    "comments": {
      "description": "Ticket comments, oldest first. Empty unless requested.",
      "items": {
        "description": "A single comment on a Zendesk ticket.",
        "properties": {
          "id": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Comment ID."
          },
          "author_id": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Author user ID."
          },
          "public": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "`True` for public replies, `False` for internal notes."
          },
          "body": {
            "default": "",
            "description": "Plain-text comment body.",
            "type": "string"
          },
          "created_at": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "ISO-8601 timestamp when the comment was created."
          },
          "attachments": {
            "description": "Files attached to the comment (metadata only).",
            "items": {
              "description": "An attachment on a Zendesk ticket comment.",
              "properties": {
                "id": {
                  "anyOf": [
                    {
                      "type": "integer"
                    },
                    {
                      "type": "null"
                    }
                  ],
                  "default": null,
                  "description": "Attachment ID."
                },
                "file_name": {
                  "anyOf": [
                    {
                      "type": "string"
                    },
                    {
                      "type": "null"
                    }
                  ],
                  "default": null,
                  "description": "Original file name."
                },
                "content_type": {
                  "anyOf": [
                    {
                      "type": "string"
                    },
                    {
                      "type": "null"
                    }
                  ],
                  "default": null,
                  "description": "MIME content type."
                },
                "content_url": {
                  "anyOf": [
                    {
                      "type": "string"
                    },
                    {
                      "type": "null"
                    }
                  ],
                  "default": null,
                  "description": "URL to download the attachment content."
                },
                "size": {
                  "anyOf": [
                    {
                      "type": "integer"
                    },
                    {
                      "type": "null"
                    }
                  ],
                  "default": null,
                  "description": "File size in bytes."
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "type": "array"
    }
  },
  "required": [
    "success",
    "message"
  ],
  "type": "object"
}

notify_zendesk_spam_ticket

Post a spam alert to #team-support mentioning the spam reviewers.

Call this once per ticket after the triage note and tags are written. This tool does not modify the Zendesk ticket. Failures are returned, never raised, so triage can continue.

Parameters:

Name Type Required Default Description
ticket_id integer yes — The numeric Zendesk ticket ID to alert reviewers about.
reason string yes — One or two sentences on why the ticket was triaged as spam.
subject string | null no null Ticket subject, if known.
agent_session_url string | null no null URL of the Devin session that triaged the ticket.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "ticket_id": {
      "description": "The numeric Zendesk ticket ID to alert reviewers about.",
      "type": "integer"
    },
    "reason": {
      "description": "One or two sentences on why the ticket was triaged as spam.",
      "type": "string"
    },
    "subject": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Ticket subject, if known."
    },
    "agent_session_url": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "URL of the Devin session that triaged the ticket."
    }
  },
  "required": [
    "ticket_id",
    "reason"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from the `notify_zendesk_spam_ticket` tool.",
  "properties": {
    "success": {
      "description": "Whether the Slack alert was posted.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "ticket_id": {
      "description": "Zendesk ticket ID.",
      "type": "integer"
    },
    "slack_permalink": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Permalink to the posted Slack alert."
    }
  },
  "required": [
    "success",
    "message",
    "ticket_id"
  ],
  "type": "object"
}

post_zendesk_internal_comment

Post an internal (private) HTML note to a Zendesk ticket by its numeric ID.

The comment is added with public=False, so it is an internal agent note and is not visible to the ticket requester/end user. Use it to record triage findings, cross-references, or context for other agents. This server has no tool that can post a customer-visible/public reply, so it is impossible to answer the customer through the MCP server. When asked to "reply to the customer", write the proposed reply as an internal note clearly labelled as a draft for a human support agent to send, and tell the requesting human that a support agent still has to post it publicly. The note is sent as HTML (html_body), so bold text and links render as intended.

This tool only posts the note; it does not modify tags. To route/tag a ticket, call add_zendesk_ticket_tags separately.

The numeric ticket_id must already be known; this tool does not search for tickets. Credentials are read from the server environment (ZENDESK_SUBDOMAIN, ZENDESK_EMAIL, ZENDESK_API_TOKEN); this tool never accepts or logs them.

Parameters:

Name Type Required Default Description
ticket_id integer yes — The numeric Zendesk ticket ID to comment on.
html_body string yes — The internal note as an HTML fragment. Posted as a private (non-public) comment visible only to agents — NOT to the ticket requester/end user. This server cannot post a public customer reply; if asked to reply, write a clearly labelled draft for a human agent to send. Provide HTML: use <br>/<p> for line breaks, <strong> for bold, and <a href> for links. Literal <, >, and & must be HTML-escaped; Zendesk sanitizes to a limited HTML subset, so keep markup basic.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "ticket_id": {
      "description": "The numeric Zendesk ticket ID to comment on.",
      "type": "integer"
    },
    "html_body": {
      "description": "The internal note as an HTML fragment. Posted as a private (non-public) comment visible only to agents \u2014 NOT to the ticket requester/end user. This server cannot post a public customer reply; if asked to reply, write a clearly labelled draft for a human agent to send. Provide HTML: use `<br>`/`<p>` for line breaks, `<strong>` for bold, and `<a href>` for links. Literal `<`, `>`, and `&` must be HTML-escaped; Zendesk sanitizes to a limited HTML subset, so keep markup basic.",
      "type": "string"
    }
  },
  "required": [
    "ticket_id",
    "html_body"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from the `post_zendesk_internal_comment` tool.",
  "properties": {
    "success": {
      "description": "Whether the internal note was posted.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "ticket_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Zendesk ticket ID."
    },
    "comment_id": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "ID of the created comment, when Zendesk reports it."
    },
    "public": {
      "default": false,
      "description": "Always `False`: this tool can only create a private, agent-only note, never a customer-visible reply.",
      "type": "boolean"
    }
  },
  "required": [
    "success",
    "message"
  ],
  "type": "object"
}

search_zendesk_tickets

Search Zendesk tickets, with results limited to 1,000.

If query has no positive type:ticket filter, type:ticket is prepended. Negated type filters and queries that explicitly select another record type are rejected.

Parameters:

Name Type Required Default Description
query string yes — Zendesk search query; ticket searches are scoped to tickets.
sort_by enum("created_at", "updated_at") | null no null Optional ticket field to sort by.
sort_order enum("asc", "desc") no "desc" Sort direction.
limit integer no 100 Maximum number of tickets to return.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "query": {
      "description": "Zendesk search query; ticket searches are scoped to tickets.",
      "type": "string"
    },
    "sort_by": {
      "anyOf": [
        {
          "enum": [
            "created_at",
            "updated_at"
          ],
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Optional ticket field to sort by."
    },
    "sort_order": {
      "default": "desc",
      "description": "Sort direction.",
      "enum": [
        "asc",
        "desc"
      ],
      "type": "string"
    },
    "limit": {
      "default": 100,
      "description": "Maximum number of tickets to return.",
      "maximum": 1000,
      "minimum": 1,
      "type": "integer"
    }
  },
  "required": [
    "query"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from `search_zendesk_tickets`.",
  "properties": {
    "success": {
      "description": "Whether the search succeeded.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "count": {
      "description": "Number of tickets returned.",
      "type": "integer"
    },
    "tickets": {
      "description": "Matching Zendesk tickets.",
      "items": {
        "description": "A concise Zendesk ticket search result.",
        "properties": {
          "id": {
            "description": "Zendesk ticket ID.",
            "type": "integer"
          },
          "subject": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Ticket subject."
          },
          "status": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Ticket status."
          },
          "type": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Ticket type."
          },
          "requester_id": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Requester user ID."
          },
          "assignee_id": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Assignee user ID."
          },
          "organization_id": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Associated organization ID."
          },
          "tags": {
            "description": "Ticket tags.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "external_id": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "External ticket ID."
          },
          "created_at": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Ticket creation time."
          },
          "updated_at": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Ticket update time."
          },
          "url": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "default": null,
            "description": "Agent-facing ticket URL."
          }
        },
        "required": [
          "id"
        ],
        "type": "object"
      },
      "type": "array"
    }
  },
  "required": [
    "success",
    "message",
    "count"
  ],
  "type": "object"
}

set_zendesk_tcm_total_score

Set only the TCM total score field on a Solved or Closed Zendesk ticket.

Other statuses are refused, a matching existing value is a no-op, and an existing different value is refused and never replaced. The tool accepts no credentials; it reads them from the server environment and never logs them.

Parameters:

Name Type Required Default Description
ticket_id integer yes — The numeric Zendesk ticket ID to score.
total integer yes — The TCM total score, an integer from 0 to 25.
run_id string yes — Required non-empty TCM scoring run ID for audit.
review_status enum("not_required", "approved", "overridden") yes — not_required for an unflagged row; approved or overridden for a flagged row Kylee reviewed. Pending flagged rows cannot be written.

Show input JSON schema

{
  "additionalProperties": false,
  "properties": {
    "ticket_id": {
      "description": "The numeric Zendesk ticket ID to score.",
      "type": "integer"
    },
    "total": {
      "description": "The TCM total score, an integer from 0 to 25.",
      "type": "integer"
    },
    "run_id": {
      "description": "Required non-empty TCM scoring run ID for audit.",
      "type": "string"
    },
    "review_status": {
      "description": "`not_required` for an unflagged row; `approved` or `overridden` for a flagged row Kylee reviewed. Pending flagged rows cannot be written.",
      "enum": [
        "not_required",
        "approved",
        "overridden"
      ],
      "type": "string"
    }
  },
  "required": [
    "ticket_id",
    "total",
    "run_id",
    "review_status"
  ],
  "type": "object"
}

Show output JSON schema

{
  "description": "Response from the `set_zendesk_tcm_total_score` tool.",
  "properties": {
    "success": {
      "description": "Whether the TCM score was set.",
      "type": "boolean"
    },
    "message": {
      "description": "Human-readable status message.",
      "type": "string"
    },
    "ticket_id": {
      "description": "Zendesk ticket ID.",
      "type": "integer"
    },
    "run_id": {
      "description": "TCM scoring run ID supplied by the caller.",
      "type": "string"
    },
    "previous_value": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "description": "The score value before this operation, if one was set."
    },
    "total": {
      "anyOf": [
        {
          "type": "integer"
        },
        {
          "type": "null"
        }
      ],
      "description": "The requested TCM total score."
    },
    "changed": {
      "description": "Whether the ticket score field changed.",
      "type": "boolean"
    }
  },
  "required": [
    "success",
    "message",
    "ticket_id",
    "run_id",
    "previous_value",
    "total",
    "changed"
  ],
  "type": "object"
}

   1# Copyright (c) 2025 Airbyte, Inc., all rights reserved.
   2"""MCP tools for Zendesk Support operations.
   3
   4This module exposes tools for pulling Zendesk tickets (and their comments),
   5posting internal (private, agent-only) notes, and notifying Slack reviewers
   6after spam triage through the hosted Ops MCP server. It can also set the
   7Ticket Complexity total score field on Solved or Closed tickets.
   8
   9## MCP reference
  10
  11.. include:: ../../../docs/mcp-generated/zendesk_ops.md
  12    :start-line: 2
  13"""
  14
  15# NOTE: We intentionally do NOT use `from __future__ import annotations` here.
  16# FastMCP has issues resolving forward references when PEP 563 deferred
  17# annotations are used. See: https://github.com/jlowin/fastmcp/issues/905
  18
  19__all__: list[str] = []
  20
  21import os
  22import re
  23from typing import Annotated, Any, Literal
  24
  25import requests
  26from fastmcp import FastMCP
  27from fastmcp_extensions import mcp_tool, register_mcp_tools
  28from pydantic import BaseModel, Field
  29
  30from airbyte_ops_mcp.slack_api import SlackAPIError
  31from airbyte_ops_mcp.slack_posting import post_channel_message
  32from airbyte_ops_mcp.zendesk_api import (
  33    ENV_ZENDESK_SUBDOMAIN,
  34    ZendeskAPIError,
  35    ZendeskTcmScoreConflictError,
  36    add_internal_note,
  37    add_ticket_tags,
  38    create_ticket,
  39    find_organizations_by_airbyte_org_id,
  40    find_ticket_form_id,
  41    get_current_user,
  42    get_ticket,
  43    get_ticket_comments,
  44    list_tickets_by_external_id,
  45    search,
  46    set_ticket_email_ccs,
  47    set_ticket_tcm_total_score,
  48)
  49
  50# Private #team-support channel; the hydra bot must stay a member.
  51_SPAM_ALERT_SLACK_CHANNEL = "C02U1H7M71A"
  52_SPAM_ALERT_MENTION_IDS = (
  53    "U04QENY1EDV",
  54    "U033PU4TMHA",
  55    "U0960FC2DEG",
  56)  # Michael Moon, Kylee Soper, Vai Ignatavicius
  57_SAFE_SESSION_URL_RE = re.compile(r"^https://[^\s<>|]+$")
  58
  59
  60class ZendeskAttachment(BaseModel):
  61    """An attachment on a Zendesk ticket comment."""
  62
  63    id: int | None = Field(default=None, description="Attachment ID.")
  64    file_name: str | None = Field(default=None, description="Original file name.")
  65    content_type: str | None = Field(default=None, description="MIME content type.")
  66    content_url: str | None = Field(
  67        default=None, description="URL to download the attachment content."
  68    )
  69    size: int | None = Field(default=None, description="File size in bytes.")
  70
  71
  72class ZendeskCustomField(BaseModel):
  73    """A single custom field value on a Zendesk ticket."""
  74
  75    id: int | None = Field(default=None, description="Custom field ID.")
  76    value: str | int | float | bool | None = Field(
  77        default=None, description="Custom field value (may be null when unset)."
  78    )
  79
  80
  81class ZendeskComment(BaseModel):
  82    """A single comment on a Zendesk ticket."""
  83
  84    id: int | None = Field(default=None, description="Comment ID.")
  85    author_id: int | None = Field(default=None, description="Author user ID.")
  86    public: bool | None = Field(
  87        default=None,
  88        description="`True` for public replies, `False` for internal notes.",
  89    )
  90    body: str = Field(default="", description="Plain-text comment body.")
  91    created_at: str | None = Field(
  92        default=None,
  93        description="ISO-8601 timestamp when the comment was created.",
  94    )
  95    attachments: list[ZendeskAttachment] = Field(
  96        default_factory=list,
  97        description="Files attached to the comment (metadata only).",
  98    )
  99
 100
 101class ZendeskTicketResponse(BaseModel):
 102    """Response from the `get_zendesk_ticket` tool."""
 103
 104    success: bool = Field(description="Whether the ticket was retrieved.")
 105    message: str = Field(description="Human-readable status message.")
 106    ticket_id: int | None = Field(default=None, description="Zendesk ticket ID.")
 107    subject: str | None = Field(default=None, description="Ticket subject line.")
 108    status: str | None = Field(
 109        default=None,
 110        description="Ticket status (e.g. `open`, `pending`, `solved`, `closed`).",
 111    )
 112    description: str | None = Field(
 113        default=None,
 114        description="The ticket's first comment / description text.",
 115    )
 116    priority: str | None = Field(default=None, description="Ticket priority, if set.")
 117    tags: list[str] = Field(default_factory=list, description="Ticket tags.")
 118    requester_id: int | None = Field(
 119        default=None, description="User ID of the ticket requester."
 120    )
 121    type: str | None = Field(default=None, description="Zendesk ticket type.")
 122    problem_id: int | None = Field(
 123        default=None, description="Associated problem ticket ID, if any."
 124    )
 125    assignee_id: int | None = Field(
 126        default=None, description="User ID of the ticket assignee."
 127    )
 128    submitter_id: int | None = Field(
 129        default=None, description="User ID of the ticket submitter."
 130    )
 131    ticket_form_id: int | None = Field(
 132        default=None, description="Ticket form ID used by the ticket."
 133    )
 134    email_cc_ids: list[int] | None = Field(
 135        default=None, description="Zendesk user IDs included as email CCs."
 136    )
 137    external_id: str | None = Field(
 138        default=None, description="External idempotency identifier for the ticket."
 139    )
 140    organization_id: int | None = Field(
 141        default=None, description="Organization ID associated with the ticket."
 142    )
 143    created_at: str | None = Field(
 144        default=None, description="ISO-8601 ticket creation timestamp."
 145    )
 146    updated_at: str | None = Field(
 147        default=None, description="ISO-8601 ticket last-updated timestamp."
 148    )
 149    url: str | None = Field(
 150        default=None,
 151        description="Agent-facing Zendesk URL for the ticket.",
 152    )
 153    via_channel: str | None = Field(
 154        default=None,
 155        description="Channel the ticket came in through (e.g. `web`, `email`).",
 156    )
 157    via_source_rel: str | None = Field(
 158        default=None,
 159        description="Source relationship (e.g. `follow_up` for follow-up tickets).",
 160    )
 161    follow_up_source_ticket_id: int | None = Field(
 162        default=None,
 163        description=(
 164            "For follow-up tickets, the ID of the original (closed) ticket this "
 165            "one follows up on. `None` when the ticket is not a follow-up."
 166        ),
 167    )
 168    custom_fields: list[ZendeskCustomField] = Field(
 169        default_factory=list,
 170        description="Ticket custom fields (`id`/`value` pairs).",
 171    )
 172    comments: list[ZendeskComment] = Field(
 173        default_factory=list,
 174        description="Ticket comments, oldest first. Empty unless requested.",
 175    )
 176
 177
 178class ZendeskInternalNoteResponse(BaseModel):
 179    """Response from the `post_zendesk_internal_comment` tool."""
 180
 181    success: bool = Field(description="Whether the internal note was posted.")
 182    message: str = Field(description="Human-readable status message.")
 183    ticket_id: int | None = Field(default=None, description="Zendesk ticket ID.")
 184    comment_id: int | None = Field(
 185        default=None,
 186        description="ID of the created comment, when Zendesk reports it.",
 187    )
 188    public: bool = Field(
 189        default=False,
 190        description=(
 191            "Always `False`: this tool can only create a private, agent-only "
 192            "note, never a customer-visible reply."
 193        ),
 194    )
 195
 196
 197class ZendeskSpamAlertResponse(BaseModel):
 198    """Response from the `notify_zendesk_spam_ticket` tool."""
 199
 200    success: bool = Field(description="Whether the Slack alert was posted.")
 201    message: str = Field(description="Human-readable status message.")
 202    ticket_id: int = Field(description="Zendesk ticket ID.")
 203    slack_permalink: str | None = Field(
 204        default=None, description="Permalink to the posted Slack alert."
 205    )
 206
 207
 208class ZendeskTagsResponse(BaseModel):
 209    """Response from the `add_zendesk_ticket_tags` tool."""
 210
 211    success: bool = Field(description="Whether the tags were added.")
 212    message: str = Field(description="Human-readable status message.")
 213    ticket_id: int | None = Field(default=None, description="Zendesk ticket ID.")
 214    tags: list[str] = Field(
 215        default_factory=list,
 216        description="The ticket's full tag list after the update.",
 217    )
 218
 219
 220class ZendeskTcmScoreResponse(BaseModel):
 221    """Response from the `set_zendesk_tcm_total_score` tool."""
 222
 223    success: bool = Field(description="Whether the TCM score was set.")
 224    message: str = Field(description="Human-readable status message.")
 225    ticket_id: int = Field(description="Zendesk ticket ID.")
 226    run_id: str = Field(description="TCM scoring run ID supplied by the caller.")
 227    previous_value: int | None = Field(
 228        description="The score value before this operation, if one was set."
 229    )
 230    total: int | None = Field(description="The requested TCM total score.")
 231    changed: bool = Field(description="Whether the ticket score field changed.")
 232
 233
 234class ZendeskTicketSummary(BaseModel):
 235    """A concise Zendesk ticket search result."""
 236
 237    id: int = Field(description="Zendesk ticket ID.")
 238    subject: str | None = Field(default=None, description="Ticket subject.")
 239    status: str | None = Field(default=None, description="Ticket status.")
 240    type: str | None = Field(default=None, description="Ticket type.")
 241    requester_id: int | None = Field(default=None, description="Requester user ID.")
 242    assignee_id: int | None = Field(default=None, description="Assignee user ID.")
 243    organization_id: int | None = Field(
 244        default=None, description="Associated organization ID."
 245    )
 246    tags: list[str] = Field(default_factory=list, description="Ticket tags.")
 247    external_id: str | None = Field(default=None, description="External ticket ID.")
 248    created_at: str | None = Field(default=None, description="Ticket creation time.")
 249    updated_at: str | None = Field(default=None, description="Ticket update time.")
 250    url: str | None = Field(default=None, description="Agent-facing ticket URL.")
 251
 252
 253class ZendeskTicketSearchResponse(BaseModel):
 254    """Response from `search_zendesk_tickets`."""
 255
 256    success: bool = Field(description="Whether the search succeeded.")
 257    message: str = Field(description="Human-readable status message.")
 258    count: int = Field(description="Number of tickets returned.")
 259    tickets: list[ZendeskTicketSummary] = Field(
 260        default_factory=list, description="Matching Zendesk tickets."
 261    )
 262
 263
 264class ZendeskOrganizationSummary(BaseModel):
 265    """A concise Zendesk organization search result."""
 266
 267    id: int = Field(description="Zendesk organization ID.")
 268    name: str | None = Field(default=None, description="Organization name.")
 269    url: str | None = Field(default=None, description="Zendesk API organization URL.")
 270
 271
 272class ZendeskOrganizationSearchResponse(BaseModel):
 273    """Response from `find_zendesk_organization_by_airbyte_org_id`."""
 274
 275    success: bool = Field(description="Whether the search succeeded.")
 276    message: str = Field(description="Human-readable status message.")
 277    organizations: list[ZendeskOrganizationSummary] = Field(
 278        default_factory=list, description="Matching Zendesk organizations."
 279    )
 280
 281
 282class OutreachContact(BaseModel):
 283    """A Zendesk outreach requester or CC contact."""
 284
 285    email: str = Field(description="Contact email address.")
 286    name: str = Field(description="Contact name.")
 287
 288
 289class ZendeskOutreachTicketResponse(BaseModel):
 290    """Response from `create_zendesk_outreach_ticket`."""
 291
 292    success: bool = Field(description="Whether the ticket was found or created.")
 293    message: str = Field(description="Human-readable status message.")
 294    created: bool = Field(description="Whether a new ticket was created.")
 295    ticket_id: int | None = Field(default=None, description="Zendesk ticket ID.")
 296    url: str | None = Field(default=None, description="Agent-facing ticket URL.")
 297    status: str | None = Field(default=None, description="Ticket status.")
 298    type: str | None = Field(default=None, description="Ticket type.")
 299    problem_id: int | None = Field(default=None, description="Problem ticket ID.")
 300    requester_id: int | None = Field(default=None, description="Requester user ID.")
 301    submitter_id: int | None = Field(default=None, description="Submitter user ID.")
 302    assignee_id: int | None = Field(default=None, description="Assignee user ID.")
 303    organization_id: int | None = Field(
 304        default=None, description="Associated organization ID."
 305    )
 306    ticket_form_id: int | None = Field(default=None, description="Ticket form ID.")
 307    email_cc_ids: list[int] | None = Field(
 308        default=None, description="Zendesk user IDs included as email CCs."
 309    )
 310    tags: list[str] = Field(default_factory=list, description="Ticket tags.")
 311    duplicate_ticket_ids: list[int] = Field(
 312        default_factory=list,
 313        description="Existing ticket IDs when an external ID has duplicates.",
 314    )
 315
 316
 317def _agent_ticket_url(raw_url: str | None, ticket_id: int | None) -> str | None:
 318    """Derive the agent-facing ticket URL from the API `url` field."""
 319    if not raw_url or ticket_id is None:
 320        return None
 321    # API url looks like https://<subdomain>.zendesk.com/api/v2/tickets/123.json
 322    if "/api/v2/" not in raw_url:
 323        return None
 324    host = raw_url.split("/api/v2/", 1)[0]
 325    if not host:
 326        return None
 327    return f"{host}/agent/tickets/{ticket_id}"
 328
 329
 330def _configured_agent_ticket_url(ticket_id: int) -> str | None:
 331    """Build the agent-facing URL from the configured Zendesk subdomain."""
 332    subdomain = os.environ.get(ENV_ZENDESK_SUBDOMAIN, "").strip()
 333    if not subdomain:
 334        return None
 335    raw_url = f"https://{subdomain}.zendesk.com/api/v2/tickets/{ticket_id}.json"
 336    return _agent_ticket_url(raw_url, ticket_id)
 337
 338
 339def _escape_slack_text(value: str) -> str:
 340    """Escape user-provided text for Slack mrkdwn."""
 341    return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
 342
 343
 344def _normalize_slack_text(value: str, *, limit: int | None = None) -> str:
 345    """Collapse whitespace and optionally truncate text for a Slack alert."""
 346    normalized = re.sub(r"\s+", " ", value).strip()
 347    if limit is not None and len(normalized) > limit:
 348        normalized = f"{normalized[: limit - 3].rstrip()}..."
 349    return _escape_slack_text(normalized)
 350
 351
 352def _map_attachments(raw_comment: dict[str, Any]) -> list[ZendeskAttachment]:
 353    """Map the `attachments` array of a raw comment into typed models."""
 354    raw_attachments = raw_comment.get("attachments")
 355    if not isinstance(raw_attachments, list):
 356        return []
 357    return [
 358        ZendeskAttachment(
 359            id=a.get("id"),
 360            file_name=a.get("file_name"),
 361            content_type=a.get("content_type"),
 362            content_url=a.get("content_url"),
 363            size=a.get("size"),
 364        )
 365        for a in raw_attachments
 366        if isinstance(a, dict)
 367    ]
 368
 369
 370def _map_custom_fields(ticket: dict[str, Any]) -> list[ZendeskCustomField]:
 371    """Map the ticket's `custom_fields` array into typed models."""
 372    raw_fields = ticket.get("custom_fields")
 373    if not isinstance(raw_fields, list):
 374        return []
 375    return [
 376        ZendeskCustomField(id=f.get("id"), value=f.get("value"))
 377        for f in raw_fields
 378        if isinstance(f, dict)
 379    ]
 380
 381
 382def _as_dict(value: Any) -> dict[str, Any]:
 383    """Return `value` when it is a dict, otherwise an empty dict."""
 384    return value if isinstance(value, dict) else {}
 385
 386
 387def _follow_up_source_ticket_id(via_source: dict[str, Any]) -> int | None:
 388    """Return the original ticket ID when the ticket is a follow-up."""
 389    if via_source.get("rel") != "follow_up":
 390        return None
 391    ticket_id = _as_dict(via_source.get("from")).get("ticket_id")
 392    return ticket_id if isinstance(ticket_id, int) else None
 393
 394
 395@mcp_tool(
 396    read_only=True,
 397    idempotent=True,
 398    open_world=True,
 399)
 400def get_zendesk_ticket(
 401    ticket_id: Annotated[
 402        int,
 403        Field(description="The numeric Zendesk ticket ID to retrieve."),
 404    ],
 405    include_comments: Annotated[
 406        bool,
 407        Field(
 408            description=(
 409                "When `True`, also fetch the ticket's comments (oldest first), "
 410                "including any attachment metadata. Only the first page (up to "
 411                "100 comments) is returned. Defaults to `False` to keep "
 412                "responses small."
 413            )
 414        ),
 415    ] = False,
 416) -> ZendeskTicketResponse:
 417    """Retrieve a Zendesk Support ticket by its numeric ID.
 418
 419    Returns the ticket's subject, status, description, tags, and requester/
 420    organization identifiers. Set `include_comments` to `True` to also pull the
 421    ticket's comment thread (public replies and internal notes), oldest first;
 422    only the first page (up to 100 comments) is returned.
 423
 424    Credentials are read from the server environment (`ZENDESK_SUBDOMAIN`,
 425    `ZENDESK_EMAIL`, `ZENDESK_API_TOKEN`); this tool never accepts or logs them.
 426    """
 427    try:
 428        ticket: dict[str, Any] = get_ticket(ticket_id)
 429    except ZendeskAPIError as exc:
 430        return ZendeskTicketResponse(
 431            success=False,
 432            message=str(exc),
 433            ticket_id=ticket_id,
 434        )
 435
 436    comments: list[ZendeskComment] = []
 437    comments_note = ""
 438    if include_comments:
 439        try:
 440            raw_comments = get_ticket_comments(ticket_id)
 441            comments = [
 442                ZendeskComment(
 443                    id=c.get("id"),
 444                    author_id=c.get("author_id"),
 445                    public=c.get("public"),
 446                    body=c.get("plain_body") or c.get("body") or "",
 447                    created_at=c.get("created_at"),
 448                    attachments=_map_attachments(c),
 449                )
 450                for c in raw_comments
 451                if isinstance(c, dict)
 452            ]
 453        except ZendeskAPIError as exc:
 454            comments_note = f" (comments could not be retrieved: {exc})"
 455
 456    resolved_id = ticket.get("id", ticket_id)
 457    via = _as_dict(ticket.get("via"))
 458    via_source = _as_dict(via.get("source"))
 459    return ZendeskTicketResponse(
 460        success=True,
 461        message=f"Retrieved Zendesk ticket {resolved_id}.{comments_note}",
 462        ticket_id=resolved_id,
 463        subject=ticket.get("subject"),
 464        status=ticket.get("status"),
 465        description=ticket.get("description"),
 466        priority=ticket.get("priority"),
 467        tags=ticket.get("tags", []) or [],
 468        requester_id=ticket.get("requester_id"),
 469        type=ticket.get("type"),
 470        problem_id=ticket.get("problem_id"),
 471        assignee_id=ticket.get("assignee_id"),
 472        submitter_id=ticket.get("submitter_id"),
 473        ticket_form_id=ticket.get("ticket_form_id"),
 474        email_cc_ids=ticket.get("email_cc_ids"),
 475        external_id=ticket.get("external_id"),
 476        organization_id=ticket.get("organization_id"),
 477        created_at=ticket.get("created_at"),
 478        updated_at=ticket.get("updated_at"),
 479        url=_agent_ticket_url(ticket.get("url"), resolved_id),
 480        via_channel=via.get("channel"),
 481        via_source_rel=via_source.get("rel"),
 482        follow_up_source_ticket_id=_follow_up_source_ticket_id(via_source),
 483        custom_fields=_map_custom_fields(ticket),
 484        comments=comments,
 485    )
 486
 487
 488def _ticket_summary(ticket: dict[str, Any]) -> ZendeskTicketSummary:
 489    """Map a raw Zendesk ticket into a concise search result."""
 490    ticket_id = ticket.get("id")
 491    if not isinstance(ticket_id, int):
 492        raise ZendeskAPIError("Zendesk search result is missing a valid ticket ID.")
 493    return ZendeskTicketSummary(
 494        id=ticket_id,
 495        subject=ticket.get("subject"),
 496        status=ticket.get("status"),
 497        type=ticket.get("type"),
 498        requester_id=ticket.get("requester_id"),
 499        assignee_id=ticket.get("assignee_id"),
 500        organization_id=ticket.get("organization_id"),
 501        tags=ticket.get("tags", []) or [],
 502        external_id=ticket.get("external_id"),
 503        created_at=ticket.get("created_at"),
 504        updated_at=ticket.get("updated_at"),
 505        url=_agent_ticket_url(ticket.get("url"), ticket_id),
 506    )
 507
 508
 509def _outreach_ticket_response(
 510    ticket: dict[str, Any],
 511    *,
 512    created: bool,
 513    message: str,
 514    fallbacks: dict[str, Any] | None = None,
 515    success: bool = True,
 516    duplicate_ticket_ids: list[int] | None = None,
 517) -> ZendeskOutreachTicketResponse:
 518    """Map a raw Zendesk ticket into an outreach response."""
 519    fallbacks = fallbacks or {}
 520    ticket_id = ticket.get("id")
 521    return ZendeskOutreachTicketResponse(
 522        success=success,
 523        message=message,
 524        created=created,
 525        ticket_id=ticket_id,
 526        url=_agent_ticket_url(ticket.get("url"), ticket_id),
 527        status=ticket.get("status") or fallbacks.get("status"),
 528        type=ticket.get("type") or fallbacks.get("type"),
 529        problem_id=ticket.get("problem_id", fallbacks.get("problem_id")),
 530        requester_id=ticket.get("requester_id", fallbacks.get("requester_id")),
 531        submitter_id=ticket.get("submitter_id", fallbacks.get("submitter_id")),
 532        assignee_id=ticket.get("assignee_id"),
 533        organization_id=ticket.get("organization_id"),
 534        ticket_form_id=ticket.get("ticket_form_id", fallbacks.get("ticket_form_id")),
 535        email_cc_ids=ticket.get("email_cc_ids", fallbacks.get("email_cc_ids")),
 536        tags=ticket.get("tags", fallbacks.get("tags", [])) or [],
 537        duplicate_ticket_ids=duplicate_ticket_ids or [],
 538    )
 539
 540
 541@mcp_tool(
 542    read_only=True,
 543    idempotent=True,
 544    open_world=True,
 545)
 546def search_zendesk_tickets(
 547    query: Annotated[
 548        str,
 549        Field(
 550            description="Zendesk search query; ticket searches are scoped to tickets."
 551        ),
 552    ],
 553    sort_by: Annotated[
 554        Literal["created_at", "updated_at"] | None,
 555        Field(description="Optional ticket field to sort by."),
 556    ] = None,
 557    sort_order: Annotated[
 558        Literal["asc", "desc"],
 559        Field(description="Sort direction."),
 560    ] = "desc",
 561    limit: Annotated[
 562        int,
 563        Field(description="Maximum number of tickets to return.", ge=1, le=1000),
 564    ] = 100,
 565) -> ZendeskTicketSearchResponse:
 566    """Search Zendesk tickets, with results limited to 1,000.
 567
 568    If `query` has no positive `type:ticket` filter, `type:ticket` is prepended.
 569    Negated type filters and queries that explicitly select another record type
 570    are rejected.
 571    """
 572    if re.search(r"(^|\s)-\s*type\s*:", query, flags=re.IGNORECASE):
 573        return ZendeskTicketSearchResponse(
 574            success=False,
 575            message="Zendesk ticket search does not accept negated type filters.",
 576            count=0,
 577        )
 578    type_filters = re.findall(r"\btype\s*:\s*([^\s]+)", query, flags=re.IGNORECASE)
 579    if type_filters and any(value.casefold() != "ticket" for value in type_filters):
 580        return ZendeskTicketSearchResponse(
 581            success=False,
 582            message="Zendesk ticket search only accepts `type:ticket` queries.",
 583            count=0,
 584        )
 585    search_query = query.strip()
 586    if not type_filters:
 587        search_query = f"type:ticket {search_query}".strip()
 588
 589    try:
 590        results = search(
 591            search_query,
 592            sort_by=sort_by,
 593            sort_order=sort_order,
 594            max_results=limit,
 595        )
 596        tickets = [_ticket_summary(ticket) for ticket in results]
 597    except ZendeskAPIError as exc:
 598        return ZendeskTicketSearchResponse(
 599            success=False,
 600            message=str(exc),
 601            count=0,
 602        )
 603
 604    return ZendeskTicketSearchResponse(
 605        success=True,
 606        message=f"Found {len(tickets)} Zendesk ticket(s).",
 607        count=len(tickets),
 608        tickets=tickets,
 609    )
 610
 611
 612@mcp_tool(
 613    read_only=True,
 614    idempotent=True,
 615    open_world=True,
 616)
 617def find_zendesk_organization_by_airbyte_org_id(
 618    airbyte_org_id: Annotated[
 619        str,
 620        Field(
 621            description="Airbyte organization UUID stored on the Zendesk organization."
 622        ),
 623    ],
 624) -> ZendeskOrganizationSearchResponse:
 625    """Find Zendesk organizations by their `airbyte_org_id` custom field."""
 626    try:
 627        organizations = find_organizations_by_airbyte_org_id(airbyte_org_id)
 628    except ZendeskAPIError as exc:
 629        return ZendeskOrganizationSearchResponse(
 630            success=False,
 631            message=str(exc),
 632        )
 633
 634    mapped = [
 635        ZendeskOrganizationSummary(
 636            id=organization["id"],
 637            name=organization.get("name"),
 638            url=organization.get("url"),
 639        )
 640        for organization in organizations
 641        if isinstance(organization.get("id"), int)
 642    ]
 643    return ZendeskOrganizationSearchResponse(
 644        success=True,
 645        message=f"Found {len(mapped)} Zendesk organization(s).",
 646        organizations=mapped,
 647    )
 648
 649
 650def _outreach_tags(tags: list[str]) -> list[str]:
 651    """Trim and deduplicate tags, ensuring the `outreach` tag is present."""
 652    cleaned: list[str] = []
 653    seen: set[str] = set()
 654    has_outreach = False
 655    for raw_tag in tags:
 656        tag = raw_tag.strip()
 657        if not tag:
 658            continue
 659        normalized = tag.casefold()
 660        if normalized in seen:
 661            continue
 662        seen.add(normalized)
 663        if normalized == "outreach":
 664            cleaned.append("outreach")
 665            has_outreach = True
 666        else:
 667            cleaned.append(tag)
 668    if not has_outreach:
 669        cleaned.append("outreach")
 670    return cleaned
 671
 672
 673def _outreach_cc_contacts(
 674    cc: list[OutreachContact],
 675    requester_email: str,
 676) -> list[dict[str, str]]:
 677    """Build deduped Zendesk email CC contacts, excluding the requester."""
 678    requester_email_normalized = requester_email.strip().casefold()
 679    contacts: list[dict[str, str]] = []
 680    seen_emails: set[str] = set()
 681    for contact in cc:
 682        email = contact.email.strip()
 683        if not email:
 684            raise ZendeskAPIError("CC contact email must not be empty.")
 685        normalized_email = email.casefold()
 686        if normalized_email == requester_email_normalized:
 687            continue
 688        if normalized_email in seen_emails:
 689            continue
 690        seen_emails.add(normalized_email)
 691        contacts.append(
 692            {
 693                "user_email": email,
 694                "user_name": contact.name.strip(),
 695                "action": "put",
 696            }
 697        )
 698    if len(contacts) > 48:
 699        raise ZendeskAPIError("At most 48 unique CC contacts are allowed.")
 700    return contacts
 701
 702
 703@mcp_tool(
 704    read_only=False,
 705    idempotent=True,
 706    open_world=True,
 707)
 708def create_zendesk_outreach_ticket(
 709    external_id: Annotated[
 710        str,
 711        Field(description="Idempotency key beginning with `outreach:`."),
 712    ],
 713    ticket_type: Annotated[
 714        Literal["problem", "incident"],
 715        Field(description="Zendesk ticket type."),
 716    ],
 717    subject: Annotated[str, Field(description="Non-empty ticket subject.")],
 718    internal_note_html: Annotated[
 719        str,
 720        Field(description="Non-empty first comment, posted as a private HTML note."),
 721    ],
 722    problem_id: Annotated[
 723        int | None,
 724        Field(description="Required parent problem ticket ID for an incident."),
 725    ] = None,
 726    tags: Annotated[list[str], Field(description="Ticket tags.")] = [],  # noqa: B006
 727    ticket_form_name: Annotated[
 728        str,
 729        Field(description="Active ticket form name."),
 730    ] = "Support Outreach",
 731    requester: Annotated[
 732        OutreachContact | None,
 733        Field(
 734            description="Requester contact; required for incidents; not allowed for problems."
 735        ),
 736    ] = None,
 737    cc: Annotated[
 738        list[OutreachContact],
 739        Field(
 740            description="Requester contacts to CC; incidents only; Zendesk allows at most 48."
 741        ),
 742    ] = [],  # noqa: B006
 743    assignee_email: Annotated[
 744        str | None,
 745        Field(description="Optional assignee email address."),
 746    ] = None,
 747) -> ZendeskOutreachTicketResponse:
 748    """Create an idempotent ticket for the approved outreach workflow only.
 749
 750    This tool cannot send anything public. The first comment is always private
 751    and visible only to Zendesk agents.
 752    CCs are applied in a separate update with no comment because Zendesk does
 753    not update email CCs when an internal note is added in the same update.
 754    Re-running on an existing ticket ensures the requested CCs without posting
 755    another comment.
 756    Callers must not run concurrent calls with the same `external_id`; duplicates
 757    are detected after creation but not prevented.
 758    """
 759    try:
 760        if (
 761            not external_id.startswith("outreach:")
 762            or not external_id[len("outreach:") :].strip()
 763        ):
 764            raise ZendeskAPIError("`external_id` must begin with `outreach:`.")
 765
 766        existing = list_tickets_by_external_id(external_id)
 767        if len(existing) > 1:
 768            duplicate_ids = [
 769                ticket["id"] for ticket in existing if isinstance(ticket.get("id"), int)
 770            ]
 771            return ZendeskOutreachTicketResponse(
 772                success=False,
 773                message=(
 774                    "Multiple Zendesk tickets share this external ID: "
 775                    f"{', '.join(map(str, duplicate_ids))}."
 776                ),
 777                created=False,
 778                duplicate_ticket_ids=duplicate_ids,
 779            )
 780        if existing:
 781            ticket = existing[0]
 782            if ticket_type == "incident" and cc:
 783                if requester is None:
 784                    raise ZendeskAPIError("`requester` is required for an incident.")
 785                if not requester.email.strip():
 786                    raise ZendeskAPIError("Requester email must not be empty.")
 787                cc_contacts = _outreach_cc_contacts(cc, requester.email)
 788                if cc_contacts:
 789                    try:
 790                        ticket = set_ticket_email_ccs(ticket["id"], cc_contacts)
 791                    except ZendeskAPIError as exc:
 792                        return _outreach_ticket_response(
 793                            ticket,
 794                            created=False,
 795                            message=(
 796                                f"Failed to ensure CCs for existing Zendesk ticket "
 797                                f"{ticket.get('id')}: {exc}"
 798                            ),
 799                            success=False,
 800                        )
 801                return _outreach_ticket_response(
 802                    ticket,
 803                    created=False,
 804                    message=(
 805                        f"Found existing Zendesk ticket {ticket.get('id')}; "
 806                        f"ensured {len(cc_contacts)} CCs."
 807                    ),
 808                )
 809            return _outreach_ticket_response(
 810                ticket,
 811                created=False,
 812                message=f"Found existing Zendesk ticket {ticket.get('id')}; no ticket was created.",
 813            )
 814
 815        if ticket_type == "incident" and problem_id is None:
 816            raise ZendeskAPIError("`problem_id` is required for an incident.")
 817        if ticket_type == "problem" and problem_id is not None:
 818            raise ZendeskAPIError("`problem_id` is not allowed for a problem ticket.")
 819        if ticket_type == "incident" and requester is None:
 820            raise ZendeskAPIError("`requester` is required for an incident.")
 821        if ticket_type == "problem" and requester is not None:
 822            raise ZendeskAPIError(
 823                "`requester` is not allowed for a problem ticket; MoonBot is the requester."
 824            )
 825        if ticket_type == "problem" and cc:
 826            raise ZendeskAPIError("`cc` is not allowed for a problem ticket.")
 827        if not subject.strip():
 828            raise ZendeskAPIError("Ticket subject must not be empty.")
 829        if not internal_note_html.strip():
 830            raise ZendeskAPIError("Internal note body must not be empty.")
 831        if requester is not None and not requester.email.strip():
 832            raise ZendeskAPIError("Requester email must not be empty.")
 833        if assignee_email is not None and not assignee_email.strip():
 834            raise ZendeskAPIError("Assignee email must not be empty.")
 835
 836        current_user = get_current_user()
 837        current_user_id = current_user.get("id")
 838        if not isinstance(current_user_id, int):
 839            raise ZendeskAPIError(
 840                "Zendesk current-user response has an invalid user ID."
 841            )
 842
 843        requester_email = (
 844            requester.email.strip()
 845            if requester is not None
 846            else str(current_user.get("email") or "").strip()
 847        )
 848        cc_contacts = _outreach_cc_contacts(cc, requester_email)
 849
 850        ticket_form_id = find_ticket_form_id(ticket_form_name)
 851        ticket_payload: dict[str, Any] = {
 852            "subject": subject.strip(),
 853            "comment": {"html_body": internal_note_html.strip(), "public": False},
 854            "status": "new",
 855            "priority": "normal",
 856            "type": ticket_type,
 857            "tags": _outreach_tags(tags),
 858            "external_id": external_id,
 859            "ticket_form_id": ticket_form_id,
 860            "submitter_id": current_user_id,
 861        }
 862        if ticket_type == "incident":
 863            ticket_payload["problem_id"] = problem_id
 864        if requester is None:
 865            ticket_payload["requester_id"] = current_user_id
 866        else:
 867            ticket_payload["requester"] = {
 868                "name": requester.name.strip(),
 869                "email": requester.email.strip(),
 870            }
 871        if assignee_email is not None:
 872            ticket_payload["assignee_email"] = assignee_email.strip()
 873
 874        ticket = create_ticket(ticket_payload)
 875        try:
 876            post_create_tickets = list_tickets_by_external_id(external_id)
 877        except ZendeskAPIError as exc:
 878            post_create_tickets = None
 879            duplicate_check_error = str(exc)
 880        else:
 881            duplicate_check_error = None
 882    except ZendeskAPIError as exc:
 883        return ZendeskOutreachTicketResponse(
 884            success=False,
 885            message=str(exc),
 886            created=False,
 887        )
 888
 889    response_fallbacks: dict[str, Any] = {
 890        "status": "new",
 891        "type": ticket_type,
 892        "problem_id": problem_id,
 893        "submitter_id": current_user_id,
 894        "ticket_form_id": ticket_form_id,
 895        "email_cc_ids": [],
 896        "tags": ticket_payload["tags"],
 897    }
 898    if requester is None:
 899        response_fallbacks["requester_id"] = current_user_id
 900    if duplicate_check_error is not None:
 901        return _outreach_ticket_response(
 902            ticket,
 903            created=True,
 904            message=(
 905                f"Created ticket {ticket.get('id')} but could not check for "
 906                "duplicate tickets for this external ID: "
 907                f"{duplicate_check_error}."
 908            ),
 909            fallbacks=response_fallbacks,
 910            success=False,
 911        )
 912    if post_create_tickets is not None and len(post_create_tickets) > 1:
 913        duplicate_ids = [
 914            existing_ticket["id"]
 915            for existing_ticket in post_create_tickets
 916            if isinstance(existing_ticket.get("id"), int)
 917        ]
 918        return _outreach_ticket_response(
 919            ticket,
 920            created=True,
 921            message=(
 922                f"Created ticket {ticket.get('id')} but found duplicate tickets "
 923                f"for this external ID: {', '.join(map(str, duplicate_ids))}; "
 924                "resolve manually."
 925            ),
 926            fallbacks=response_fallbacks,
 927            success=False,
 928            duplicate_ticket_ids=duplicate_ids,
 929        )
 930    if cc_contacts:
 931        try:
 932            ticket = set_ticket_email_ccs(ticket["id"], cc_contacts)
 933        except ZendeskAPIError as exc:
 934            return _outreach_ticket_response(
 935                ticket,
 936                created=True,
 937                message=(
 938                    f"Created ticket {ticket.get('id')} but failed to add CCs: "
 939                    f"{exc}; re-run to retry."
 940                ),
 941                fallbacks=response_fallbacks,
 942                success=False,
 943            )
 944    return _outreach_ticket_response(
 945        ticket,
 946        created=True,
 947        message=f"Created private outreach ticket {ticket.get('id')}.",
 948        fallbacks=response_fallbacks,
 949    )
 950
 951
 952def _created_comment_id(audit: dict[str, Any]) -> int | None:
 953    """Return the created comment's ID from a ticket-update `audit`, if present."""
 954    events = audit.get("events")
 955    if not isinstance(events, list):
 956        return None
 957    for event in events:
 958        if not isinstance(event, dict):
 959            continue
 960        if event.get("type") == "Comment" and isinstance(event.get("id"), int):
 961            return event["id"]
 962    return None
 963
 964
 965@mcp_tool(
 966    read_only=False,
 967    idempotent=False,
 968    open_world=True,
 969)
 970def post_zendesk_internal_comment(
 971    ticket_id: Annotated[
 972        int,
 973        Field(description="The numeric Zendesk ticket ID to comment on."),
 974    ],
 975    html_body: Annotated[
 976        str,
 977        Field(
 978            description=(
 979                "The internal note as an HTML fragment. Posted as a private "
 980                "(non-public) comment visible only to agents \u2014 NOT to the "
 981                "ticket requester/end user. This server cannot post a public "
 982                "customer reply; if asked to reply, write a clearly labelled "
 983                "draft for a human agent to send. Provide HTML: use `<br>`/`<p>` for "
 984                "line breaks, `<strong>` for bold, and `<a href>` for links. "
 985                "Literal `<`, `>`, and `&` must be HTML-escaped; Zendesk "
 986                "sanitizes to a limited HTML subset, so keep markup basic."
 987            )
 988        ),
 989    ],
 990) -> ZendeskInternalNoteResponse:
 991    """Post an internal (private) HTML note to a Zendesk ticket by its numeric ID.
 992
 993    The comment is added with `public=False`, so it is an internal agent note
 994    and is **not** visible to the ticket requester/end user. Use it to record
 995    triage findings, cross-references, or context for other agents. This server
 996    has no tool that can post a customer-visible/public reply, so it is
 997    impossible to answer the customer through the MCP server. When asked to
 998    "reply to the customer", write the proposed reply as an internal note
 999    clearly labelled as a draft for a human support agent to send, and tell the
1000    requesting human that a support agent still has to post it publicly. The
1001    note is sent as HTML (`html_body`), so bold text and links render as intended.
1002
1003    This tool only posts the note; it does not modify tags. To route/tag a
1004    ticket, call `add_zendesk_ticket_tags` separately.
1005
1006    The numeric `ticket_id` must already be known; this tool does not search
1007    for tickets. Credentials are read from the server environment
1008    (`ZENDESK_SUBDOMAIN`, `ZENDESK_EMAIL`, `ZENDESK_API_TOKEN`); this tool
1009    never accepts or logs them.
1010    """
1011    try:
1012        result: dict[str, Any] = add_internal_note(ticket_id, html_body)
1013    except ZendeskAPIError as exc:
1014        return ZendeskInternalNoteResponse(
1015            success=False,
1016            message=str(exc),
1017            ticket_id=ticket_id,
1018        )
1019
1020    updated_ticket = _as_dict(result.get("ticket"))
1021    resolved_id = updated_ticket.get("id", ticket_id)
1022    comment_id = _created_comment_id(_as_dict(result.get("audit")))
1023    return ZendeskInternalNoteResponse(
1024        success=True,
1025        message=(
1026            f"Posted an internal-only note to Zendesk ticket {resolved_id}; "
1027            "it is not visible to the customer."
1028        ),
1029        ticket_id=resolved_id,
1030        comment_id=comment_id,
1031    )
1032
1033
1034@mcp_tool(
1035    read_only=False,
1036    idempotent=False,
1037    open_world=True,
1038)
1039def notify_zendesk_spam_ticket(
1040    ticket_id: Annotated[
1041        int,
1042        Field(description="The numeric Zendesk ticket ID to alert reviewers about."),
1043    ],
1044    reason: Annotated[
1045        str,
1046        Field(
1047            description="One or two sentences on why the ticket was triaged as spam."
1048        ),
1049    ],
1050    subject: Annotated[
1051        str | None,
1052        Field(default=None, description="Ticket subject, if known."),
1053    ] = None,
1054    agent_session_url: Annotated[
1055        str | None,
1056        Field(
1057            default=None,
1058            description="URL of the Devin session that triaged the ticket.",
1059        ),
1060    ] = None,
1061) -> ZendeskSpamAlertResponse:
1062    """Post a spam alert to `#team-support` mentioning the spam reviewers.
1063
1064    Call this once per ticket after the triage note and tags are written. This
1065    tool does not modify the Zendesk ticket. Failures are returned, never raised,
1066    so triage can continue.
1067    """
1068    ticket_url = _configured_agent_ticket_url(ticket_id)
1069    ticket_link = f"<{ticket_url}|#{ticket_id}>" if ticket_url else f"#{ticket_id}"
1070    subject_text = _normalize_slack_text(subject) if subject else ""
1071    subject_suffix = f": {subject_text}" if subject_text else ""
1072    mentions = " ".join(f"<@{user_id}>" for user_id in _SPAM_ALERT_MENTION_IDS)
1073    text = (
1074        f":no_entry_sign: :spam: MoonBot triaged Zendesk ticket {ticket_link}"
1075        f"{subject_suffix} as spam. {mentions}\n"
1076        f"*Reason:* {_normalize_slack_text(reason, limit=500)}"
1077    )
1078    if agent_session_url and _SAFE_SESSION_URL_RE.fullmatch(agent_session_url):
1079        text += f"\n<{_escape_slack_text(agent_session_url)}|Devin session>"
1080
1081    try:
1082        result = post_channel_message(_SPAM_ALERT_SLACK_CHANNEL, text)
1083    except (SlackAPIError, requests.RequestException) as exc:
1084        return ZendeskSpamAlertResponse(
1085            success=False,
1086            message=str(exc),
1087            ticket_id=ticket_id,
1088        )
1089
1090    return ZendeskSpamAlertResponse(
1091        success=True,
1092        message=f"Posted a Slack spam alert for Zendesk ticket {ticket_id}.",
1093        ticket_id=ticket_id,
1094        slack_permalink=result.permalink,
1095    )
1096
1097
1098@mcp_tool(
1099    read_only=False,
1100    idempotent=True,
1101    open_world=True,
1102)
1103def add_zendesk_ticket_tags(
1104    ticket_id: Annotated[
1105        int,
1106        Field(description="The numeric Zendesk ticket ID to tag."),
1107    ],
1108    tags: Annotated[
1109        list[str],
1110        Field(
1111            description=(
1112                "Tags to add to the ticket. Appended to the ticket's existing "
1113                "tags (never clobbered). At least one non-empty tag is required."
1114            )
1115        ),
1116    ],
1117) -> ZendeskTagsResponse:
1118    """Add tags to a Zendesk ticket by its numeric ID.
1119
1120    Tags are Zendesk's label mechanism. This reads the ticket's current tags
1121    and writes back the union (existing + supplied) via a ticket update, so
1122    the ticket's existing tags — and any tagger-backed custom fields — are
1123    preserved and never dropped. Adding a tag that is already present is a
1124    no-op.
1125
1126    The numeric `ticket_id` must already be known; this tool does not search
1127    for tickets. Credentials are read from the server environment
1128    (`ZENDESK_SUBDOMAIN`, `ZENDESK_EMAIL`, `ZENDESK_API_TOKEN`); this tool
1129    never accepts or logs them.
1130    """
1131    try:
1132        result_tags = add_ticket_tags(ticket_id, tags)
1133    except ZendeskAPIError as exc:
1134        return ZendeskTagsResponse(
1135            success=False,
1136            message=str(exc),
1137            ticket_id=ticket_id,
1138        )
1139
1140    return ZendeskTagsResponse(
1141        success=True,
1142        message=f"Added tags to Zendesk ticket {ticket_id}.",
1143        ticket_id=ticket_id,
1144        tags=result_tags,
1145    )
1146
1147
1148@mcp_tool(
1149    read_only=False,
1150    idempotent=True,
1151    open_world=True,
1152)
1153def set_zendesk_tcm_total_score(
1154    ticket_id: Annotated[
1155        int,
1156        Field(description="The numeric Zendesk ticket ID to score.", strict=True),
1157    ],
1158    total: Annotated[
1159        int,
1160        Field(description="The TCM total score, an integer from 0 to 25.", strict=True),
1161    ],
1162    run_id: Annotated[
1163        str,
1164        Field(description="Required non-empty TCM scoring run ID for audit."),
1165    ],
1166    review_status: Annotated[
1167        Literal["not_required", "approved", "overridden"],
1168        Field(
1169            description=(
1170                "`not_required` for an unflagged row; `approved` or `overridden` "
1171                "for a flagged row Kylee reviewed. Pending flagged rows cannot be "
1172                "written."
1173            )
1174        ),
1175    ],
1176) -> ZendeskTcmScoreResponse:
1177    """Set only the TCM total score field on a Solved or Closed Zendesk ticket.
1178
1179    Other statuses are refused, a matching existing value is a no-op, and an
1180    existing different value is refused and never replaced. The tool accepts no
1181    credentials; it reads them from the server environment and never logs them.
1182    """
1183    if not run_id.strip():
1184        return ZendeskTcmScoreResponse(
1185            success=False,
1186            message="The TCM scoring run ID must not be empty.",
1187            ticket_id=ticket_id,
1188            run_id=run_id,
1189            previous_value=None,
1190            total=total,
1191            changed=False,
1192        )
1193
1194    try:
1195        previous_value, changed = set_ticket_tcm_total_score(
1196            ticket_id,
1197            total,
1198        )
1199    except ZendeskTcmScoreConflictError as exc:
1200        return ZendeskTcmScoreResponse(
1201            success=False,
1202            message=(
1203                f"Zendesk ticket {ticket_id} already has TCM total score "
1204                f"{exc.current}; this tool never replaces an existing score."
1205            ),
1206            ticket_id=ticket_id,
1207            run_id=run_id,
1208            previous_value=exc.current,
1209            total=total,
1210            changed=False,
1211        )
1212    except ZendeskAPIError as exc:
1213        return ZendeskTcmScoreResponse(
1214            success=False,
1215            message=str(exc),
1216            ticket_id=ticket_id,
1217            run_id=run_id,
1218            previous_value=None,
1219            total=total,
1220            changed=False,
1221        )
1222
1223    action = "Updated" if changed else "Confirmed unchanged"
1224    return ZendeskTcmScoreResponse(
1225        success=True,
1226        message=(
1227            f"{action} TCM total score for Zendesk ticket {ticket_id} to {total} "
1228            f"(run {run_id}; review status: {review_status})."
1229        ),
1230        ticket_id=ticket_id,
1231        run_id=run_id,
1232        previous_value=previous_value,
1233        total=total,
1234        changed=changed,
1235    )
1236
1237
1238def register_zendesk_ops_tools(app: FastMCP) -> None:
1239    """Register zendesk_ops tools with the FastMCP app."""
1240    register_mcp_tools(app, mcp_module=__name__)