Skip to main content
Glama
ServiceNow Change Request and Incident MCP Server

ServiceNow Change Request and Incident MCP Server

by liozzazhang
README.md
# ServiceNow Change Request and Incident MCP Server

An [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) server that lets
AI assistants query ServiceNow incidents and query, summarize, create, and update
`change_request` records, plus query and create Method of Procedure (`u_mop`)
records, using natural language.

It works both as a **local single-user** server (stdio / CLI) and as a
**remote multi-user** server (HTTP) where each user's CI credentials are
passed through per request.

> **Current version: `0.1.0`** — see the [Changelog](CHANGELOG.md) for the full
> release history.

---

## Usage

### Prerequisite: get your CI client id & client secret

This server authenticates to ServiceNow on your behalf using a **CI
Account** (`client_id` + `client_secret`). Request your own pair from your
identity team first — never reuse someone else's.

Keep the `client_secret` private: put it in your local `.env` (gitignored) or in
your MCP client headers — **never** commit it or paste it into shared configs.

### A. Local (single user) — stdio / CLI / debugging

Set up the environment and credentials:

```bash
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e .
cp .env.example .env               # then edit .env
```

Put your own credentials in `.env`:

| Variable | Description |
|----------|-------------|
| `SERVICENOW_INSTANCE` | ServiceNow instance URL (required) |
| `CI_BASE_URL` | CI identity service base URL (default `https://identity.example.com`) |
| `SNOW_CI_EXCHANGE_PATH` | Scripted REST path that exchanges a CI token for a SNOW token (default `/api/x_custom/ci_token_validation`) |
| `CI_CLIENT_ID` | Your CI client id |
| `CI_CLIENT_SECRET` | Your CI client secret |

Other local auth options:

| Method | Variables |
|--------|-----------|
| Manual token | `SERVICENOW_TOKEN=Bearer eyJ...` (takes priority over auto-fetch) |
| Basic Auth | `SERVICENOW_USER` + `SERVICENOW_PASS` |
| FedRAMP | add `CI_ENV=fedramp` |

Run it:

```bash
# MCP server (stdio, for Cursor/VS Code to spawn)
MCP_TRANSPORT=stdio python -m mcp_servicenow_chg

# MCP server (HTTP transport, default)
python -m mcp_servicenow_chg

# CLI queries
python -m mcp_servicenow_chg get CHG0768536 [--verbose]
python -m mcp_servicenow_chg list "Frank Rang" --from-date 2026-03-01 --or
```

Generate a token by itself (optional). `generate-snow-token` is a console
script installed by this project, so it only exists on `PATH` once this repo's
own virtualenv is active — activating an unrelated venv gives
`command not found`. The `python -m` form is equivalent:

```bash
generate-snow-token --snow   # SNOW token (for SERVICENOW_TOKEN)
generate-snow-token          # CI token only

python -m mcp_servicenow_chg.token_cli --snow   # same, via the module
```

#### Cursor / VS Code config (stdio)

The repo ships a `.cursor/mcp.json` so Cursor spawns the server automatically.
**Do not** put URLs or credentials in the `env` block — keep them in `.env`
(gitignored), which is loaded automatically at startup.

```json
{
  "mcpServers": {
    "servicenow-chg": {
      "command": ".venv/bin/python",
      "args": ["-m", "mcp_servicenow_chg"],
      "cwd": "${workspaceFolder}",
      "env": { "MCP_TRANSPORT": "stdio" }
    }
  }
}
```

After the first setup, fully restart Cursor once so the config takes effect.

### B. Remote (multi-user) — via the MCP Market

When deployed, the server is published in the internal MCP Market. Users install
it from the market and connect over HTTP(S). Each user supplies **their own**
CI credentials (see [Prerequisite](#prerequisite-get-your-ci-client-id--client-secret)
above) via request headers; the server passes them through to ServiceNow per
request and **stores nothing**.

Three accepted ways to send credentials (use whichever your client supports):

| Option | Header(s) |
|--------|-----------|
| Single header (recommended) | `X-CI-CLIENT-AUTH: <client_id>:<client_secret>` |
| Two headers | `X-CI-CLIENT-ID: <client id>` and `X-CI-CLIENT-SECRET: <client secret>` |
| HTTP Basic | `Authorization: Basic base64(client_id:client_secret)` |

If multiple are present, the two discrete headers take priority, then
`X-CI-CLIENT-AUTH`, then `Authorization: Basic`.

Client config example (VS Code `settings.json` / Cursor `mcp.json`):

```json
{
  "servers": {
    "servicenow-chg": {
      "url": "https://mcp.example.com/mcp/",
      "headers": {
        "X-CI-CLIENT-AUTH": "<client_id>:<client_secret>"
      }
    }
  }
}
```

Two-header equivalent:

```json
{
  "servers": {
    "servicenow-chg": {
      "url": "https://mcp.example.com/mcp/",
      "headers": {
        "X-CI-CLIENT-ID": "<your client id>",
        "X-CI-CLIENT-SECRET": "<your client secret>"
      }
    }
  }
}
```

> Requires network access to the deployed server. Auth priority on the server is:
> request-header credentials > `SERVICENOW_TOKEN` > env CI credentials > Basic Auth.

---

## Project Structure

```
mcp-servicenow-chg/
├── src/mcp_servicenow_chg/
│   ├── __init__.py
│   ├── __main__.py      # Entry point: python -m mcp_servicenow_chg
│   ├── server.py        # MCP server + tools + auth resolution
│   ├── incidents.py     # Incident query validation and construction
│   ├── token.py         # CI -> SNOW token exchange & auto-renew (TokenHolder)
│   ├── token_cli.py     # CLI: generate-snow-token
│   ├── resources.py     # MCP resources (schema, query syntax, states)
│   └── prompts.py       # MCP prompts
├── Dockerfile           # Container image (plain HTTP; TLS terminated upstream)
├── pyproject.toml
├── .env                 # Local config (gitignored — never commit)
├── .env.example
└── README.md
```

---

## What an MCP server exposes: Tools, Resources, Prompts

MCP servers offer three kinds of capabilities to an AI client. This server uses
all three:

### 1. Tools — actions the model can execute

Tools are callable functions. The model decides when to call them and with what
arguments; each call performs a real operation (here, a ServiceNow Table API
request) and returns structured data.

| Tool | Description |
|------|-------------|
| `get_change` | Fetch a single change by number (e.g. `CHG0001234`) |
| `list_changes` | Query multiple changes with a ServiceNow encoded query |
| `list_changes_by_assignee` | List changes by assignee with filters (`from_date`, `exclude_closed`, `from_date_or_not_closed`) |
| `summarize_change` | Convert a change record into a concise text summary |
| `get_change_summary` | Fetch and summarize in one call |
| `update_change` | PATCH a change by number (`close_code`, `close_notes`, `u_post_validation_confirmation`, `state`, …) |
| `get_incident` | Fetch a single incident by number (e.g. `INC0012345`) |
| `list_incidents` | Query incidents by priority, data center, impacted business service, liable service, and UTC time range |
| `search_mops` | Search MOP records by keyword (u_name / u_title) |
| `get_mop` | Fetch a single MOP by number (e.g. MOP0001234.1) |
| `create_mop` | Create a MOP record after validating required planning fields and resolving group/creator/reviewer references |
| `verify_create_fields` | Resolve and validate all required fields before create |
| `create_change` | Create a new change — `standard`, `normal`, or `emergency` (see note below) |

> **`create_change` types & required fields:** Set `type` to `standard`
> (default), `normal`, or `emergency`. Common required fields for all types:
> `short_description`, `cmdb_ci`, `business_service`, `u_data_center`,
> `assignment_group`, `assigned_to`, `start_date` (UTC), `end_date` (UTC).
> Per type, additionally: `standard`/`normal` require `u_mop`; `emergency`
> requires `u_emergency_justification`.
>
> **Verify-first workflow:** Call `verify_create_fields` before create. It
> resolves reference fields against ServiceNow; ambiguous matches (e.g. duplicate
> CI or assignee names) return candidates for user confirmation. `create_change`
> runs verify by default (`skip_verify=true` to bypass).
>
> **Schedule (no default timezone):** Pass `schedule_timezone` (IANA or UTC offset)
> with `schedule_start_local` / `schedule_end_local`, or pass UTC `start_date` /
> `end_date` directly. The server never assumes a default timezone.
>
> **Profile (explicit opt-in):** Pass `profile` (e.g. `example_change`) only
> when the user requests a named preset; profiles are never auto-selected.
>
> Auto-handled (pass a value to override): `requested_by` is omitted when absent
> (ServiceNow fills it with the submitting user); `description` is generated from
> `short_description` when absent (standard/normal also reference the MOP);
> `state` defaults to **Scheduled (-2)** for `standard` and **New (-5)** for
> `normal`/`emergency`. The standard default state is overridable via
> `SNOW_CHG_SCHEDULED_STATE`.

`list_incidents` combines all supplied filters with AND. Priority accepts values
`1`-`5`, `P1`-`P5`, or labels such as `Critical` and `High`. Date-only time
bounds are accepted; an end date includes the full UTC day. The default time
field is `opened_at`, and callers can select `resolved_at`, `closed_at`,
`sys_created_on`, or `sys_updated_on`.

Impacted Business Service and Liable service use fuzzy `LIKE` matching by
default (`fuzzy_services=false` requests exact names). Their reference query
paths, and the data-center query path, can be overridden with the
`SNOW_INCIDENT_*_QUERY_FIELD` environment variables documented below.

### 2. Resources — read-only reference context

Resources are read-only documents the client can load into the model's context
to ground its answers (schemas, references, lookup tables). They are not
actions; they are data.

| URI | Description |
|-----|-------------|
| `servicenow://schema/change_request` | Common `change_request` fields |
| `servicenow://schema/incident` | Common incident fields and supported filters |
| `servicenow://schema/u_mop` | MOP table fields (search_mops / get_mop / create_mop) |
| `servicenow://query/syntax` | ServiceNow encoded query syntax reference |
| `servicenow://states` | State value reference (configurable via env) |

### 3. Prompts — reusable, parameterized templates

Prompts are pre-written instruction templates the user can pick from the client
UI. They expand into a ready-to-run message that typically tells the model which
tools to use.

| Prompt | Parameters | Description |
|--------|------------|-------------|
| `prompt_summarize_change` | `change_number` | Look up one change and summarize it |
| `prompt_list_assignee_changes` | `assigned_to`, `from_date?`, `exclude_closed?`, `from_date_or_not_closed?` | List changes by assignee |
| `prompt_check_change_status` | `change_numbers` (comma-separated) | Bulk-check the status of several changes |
| `prompt_create_change` | `request` | Verify fields, confirm with user, then create a change |
| `prompt_query_incidents` | `request` | Turn an incident-search request into a structured `list_incidents` call |

---

## Deployment (Container / Kubernetes)

The repo provides a `Dockerfile`: non-root, minimal image, `streamable-http`,
listening on `0.0.0.0:8000` at path `/mcp`.

**The container serves plain HTTP only.** TLS is terminated in front of it by a
reverse proxy (nginx/Caddy/Envoy) or a platform ingress (e.g. Kubernetes) — the
standard pattern for remote MCP servers. The app stays simple; cert rotation,
HTTP/2, and security hardening live in the proxy.

```bash
docker build -t mcp-servicenow-chg .
docker run -p 8000:8000 -e SERVICENOW_INSTANCE=https://your-instance.service-now.com mcp-servicenow-chg
```

Configuration notes:

- `SERVICENOW_INSTANCE` is required. Set `CI_BASE_URL` and
  `SNOW_CI_EXCHANGE_PATH` to match your identity service and the scripted REST
  API on your instance (and optionally `CI_ENV`).
- State codes default to `3` (Closed) / `4` (Canceled); override with
  `SNOW_CHG_CLOSED_STATE` / `SNOW_CHG_CANCELED_STATE` if your instance differs.
- Incident query paths default to `u_data_center.name`, `u_impacted_service.name`,
  and `business_service.name`. Override them with
  `SNOW_INCIDENT_DATA_CENTER_QUERY_FIELD`,
  `SNOW_INCIDENT_IMPACTED_SERVICE_QUERY_FIELD`, and
  `SNOW_INCIDENT_LIABLE_SERVICE_QUERY_FIELD` if your incident dictionary differs.
- **Never** bake any user credentials into the image or environment. Per-user
  credentials always arrive as request headers.

Typical topology:

```
MCP client  --HTTPS-->  reverse proxy / Kubernetes ingress  --HTTP-->  container :8000  /mcp
```

---

## Authentication & Token Call Flow

This server never stores user secrets. For each request it resolves credentials,
exchanges them for a ServiceNow token, and reuses that token until it nears
expiry.

### Per-request resolution

1. Read credentials from the request headers — `X-CI-CLIENT-ID` /
   `X-CI-CLIENT-SECRET`, or a single `X-CI-CLIENT-AUTH: client_id:client_secret`,
   or `Authorization: Basic base64(client_id:client_secret)` (deployed /
   multi-user mode) — **or** fall back to local env auth (`SERVICENOW_TOKEN`,
   then env CI credentials, then Basic Auth).
2. Look up (or create) a `TokenHolder` for those credentials in a bounded,
   in-memory LRU cache keyed by `sha256(client_id:client_secret)` — the raw
   secret is never used as a key and never logged. The cache is capped
   (LRU eviction) so memory cannot grow unbounded under many users.

### Token exchange (two steps)

`TokenHolder` obtains a ServiceNow Bearer token via CI:

```
client_id + client_secret
      │  (1) POST <CI_BASE_URL>/idb/oauth2/v1/access_token   (Basic auth, client_credentials)
      ▼
   CI access_token
      │  (2) POST <snow_instance><SNOW_CI_EXCHANGE_PATH>
      ▼
   ServiceNow access_token  ->  "Bearer <token>"  (with expires_in)
```

(For FedRAMP, `CI_ENV=fedramp` uses `CI_FEDRAMP_BASE_URL`.)

### Refresh & expiry strategy

- The SNOW token lifetime is ~1 hour (`expires_in` from the exchange).
- The token is refreshed **proactively** `REFRESH_BUFFER_SECONDS = 300` (5 min)
  before its real expiry, so a token is never used right as it expires
  mid-request.
- On a `401` from ServiceNow, the holder invalidates its token and retries the
  request **once** with a freshly fetched token.
- A manually supplied `SERVICENOW_TOKEN` is treated as static (never refreshed).

---

## Development & Debugging

Install dev extras (adds `debugpy`):

```bash
pip install -e ".[dev]"
```

HTTP + breakpoint debugging:

1. Set breakpoints in `src/mcp_servicenow_chg/server.py`.
2. Start the server (`python -m mcp_servicenow_chg`) so it listens on
   `http://127.0.0.1:8000/mcp`.
3. In Cursor: Settings → Tools & MCP → Add new MCP server → **Streamable HTTP**,
   URL `http://127.0.0.1:8000/mcp`.
4. Invoke a tool from chat; the breakpoint hits when the request arrives.

Verify the connection by asking, e.g.: *"Use get_change_summary to look up
CHG0001234."* You can also use the
[MCP Inspector](https://github.com/modelcontextprotocol/inspector) against the
stdio or HTTP endpoint.

### Example: `list_changes_by_assignee`

```python
# Frank Rang, March onward OR not closed
list_changes_by_assignee(
    assigned_to="Frank Rang",
    from_date="2026-03-01",
    from_date_or_not_closed=True,
    limit=50,
)
```

### Example: `list_incidents`

```python
list_incidents(
    priority="P1",
    data_center="DC01",
    impacted_business_service="Calling",
    liable_service="Media",
    start_time="2026-09-01",
    end_time="2026-09-02",
)
```

### Troubleshooting

| Symptom | Fix |
|---------|-----|
| Cursor doesn't detect the MCP | Fully quit and restart Cursor |
| Tools not found | Check the python path / URL in `.cursor/mcp.json` (HTTP URL must end in `/mcp`) |
| 401 / 403 errors | Tokens auto-renew; if it still fails, check your credentials / headers |
| Breakpoints not hit | Ensure the HTTP server is running and Cursor is connected to that endpoint |