Skip to main content
Glama
README.md
# @onlyflows/servicenow-mcp

A governed ServiceNow MCP server: it lets an AI client read and change records on your instances, within limits you set per connection.

<!-- DEMO GIF PLACEHOLDER: add a short screen recording here (asking a question, then a denied write and a dry-run batch). Not recorded yet. -->

[![npm version](https://img.shields.io/npm/v/@onlyflows/servicenow-mcp)](https://www.npmjs.com/package/@onlyflows/servicenow-mcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

Built by [OnlyFlows](https://onlyflows.tech) · Published by [@onlyflowstech](https://github.com/onlyflowstech)

## Governed and safe for production

The server exposes 24 tools over stdio. Every call runs inside controls that
you configure and that no tool of this server can change:

- **Per-profile table and field policy.** Each profile (a named ServiceNow
  connection) has its own read and write table allowlists. Access is
  deny-by-default: a profile with no rules denies every ServiceNow call. Field
  policy decides which fields can be read or written; sensitive field names
  are refused.
- **Confirmation flag on destructive tools.** `sn_delete` and `sn_batch`
  change nothing unless the call carries `confirm: true`. The model sets that
  flag itself, so it is a guard against accidents, not an approval. A person
  approves through the client's own tool-approval prompt, and many clients let
  you "always allow" a tool. `sn_create` and `sn_update` take no confirm flag;
  keep write grants narrow.
- **Safe batching.** `sn_batch` takes a structured filter (no raw encoded
  queries), runs as a dry run by default, caps a run at 10,000 records, and
  never re-sends a batch.
- **Activity events.** Each completed tool call writes one JSON line to
  stderr with the tool, profile, instance and outcome, plus hashed owner and
  client labels. It records no table, record or fields. Delivery is
  best-effort through stderr, and events are dropped above 256 pending lines.
  Use ServiceNow's own audit history for record changes.
- **Explicit profile on every call.** There is no default or "active"
  instance. Each call names its profile, so nothing reaches an instance the
  call didn't name. Keep write grants on production profiles narrow.
- **Credentials stay out of clients.** Secrets are entered at a hidden prompt,
  verified against the instance before anything is saved, and stored
  encrypted in an owner-only `~/.servicenow-mcp` directory.

> **Limits of these controls.** They hold against the model's tool calls. A
> client that gives the model a shell or file access (Claude Code and Codex
> can) could run `servicenow-mcp-setup grant` or read
> `~/.servicenow-mcp/server.env`. The encryption key sits in the same
> owner-only folder as the encrypted profiles, so it protects against other
> users and stray copies of the files, not against your own account. Run
> production profiles from a client or account without shell access where you
> can.

Details: [Table access policy](#table-access-policy),
[Safety Features](#safety-features) and [docs/PRODUCTION-SECURITY.md](docs/PRODUCTION-SECURITY.md).

## Works with

Any MCP client that can launch a stdio server. Setup registers **Claude Code**
and **Codex** automatically; **Claude Desktop**, **Cursor**, **VS Code** and
**Windsurf** are configured with `servicenow-mcp-setup client --client <name>`
(see [Connecting a client](#connecting-a-client)). Requires Node.js 20 or newer.

## Quick start

1. **Install:** `npm install -g @onlyflows/servicenow-mcp`
2. **Set up a connection:** `servicenow-mcp-setup`. It asks for your instance
   and credential, checks them against the instance, asks which tables to
   allow, and registers Claude Code and Codex if their CLIs are installed.
   The wizard's authentication type defaults to **OAuth client credentials**,
   so you can press Enter at that prompt. You need an Application Registry
   entry on the instance first: see [OAuth 2.0](#oauth-20-recommended). Basic
   is still offered, marked legacy, because ServiceNow is
   [retiring it for REST calls](#basic-legacy-deprecated-by-servicenow).
3. **Open your client and ask.** There is no server to start; the client
   launches `servicenow-mcp` itself.

The default read grant in the wizard is **just `incident`**, and writes default
to **none**. Grant more later with `servicenow-mcp-setup grant`.

## Try asking

These work with the default read grant (profile named `dev`):

1. "On dev, list the 10 most recent open P1 incidents."
2. "On dev, how many incidents are there, grouped by priority?"
3. "On dev, which assignment groups have the most incidents?"
4. "On dev, which open incidents have no assignee, oldest first?"
5. "On dev, show incident INC0010001 and summarize where it stands."

Your client sends `profile: "dev"` with each call. Asking about other tables
(for example `change_request`) is denied until you grant them.

---

## Installation

```bash
npm install -g @onlyflows/servicenow-mcp
servicenow-mcp-setup
```

Run bare on a terminal, `servicenow-mcp-setup` walks you through the whole
thing in one command: it generates the local auth material, asks for your
instance and credential, **verifies that credential against the instance**,
asks which tables to grant, writes the profile, and registers any supported
client whose CLI is installed. The credential is entered at a hidden prompt —
never an argument, never shell history — and nothing is written to the profile
until the instance has accepted it, so a typo or a wrong password leaves
nothing behind.

```
ServiceNow MCP setup

This walks through one ServiceNow connection end to end. Nothing is
written to the profile until your credential is verified against the
instance. Press Ctrl+C at any point to stop; nothing will be saved.

Profile name [dev]: dev
ServiceNow instance (for example dev12345.service-now.com): dev12345.service-now.com
Authentication:
  1) oauth (default) - client credentials, recommended
  2) apikey - inbound API key
  3) basic - legacy, not recommended: ServiceNow is retiring it
Choice [1]: 1

OAuth client credentials need these on the instance:
  - an Application Registry entry (System OAuth > Application Registry)
    with a client ID and client secret
  - the client credentials grant enabled for it
  - an OAuth Application User: the integration user this server acts as,
    with only the roles it needs, not an administrator
Steps: README, section Authentication > OAuth 2.0.

OAuth grant type:
  1) client_credentials (default)
  2) password
Choice [1]: 1
How should the credential be stored?:
  1) encrypted (default)
  2) reference
Choice [1]: 1
OAuth client id (not a secret): <your-client-id>

Enter each secret now. Input is hidden — nothing you type from here
is displayed.
clientSecret:

Verifying against the instance...
  ok  https://dev12345.service-now.com accepted the credential.

Table access is deny-by-default: a profile with no rules denies every
tool call. Grant the narrowest set that does the job; you can add more
later with servicenow-mcp-setup grant.

Tables to allow for READS:
  1) Just incident (default)
  2) Common ITSM set (incident,change_request,problem,task,sys_user)
  3) All tables (*)
  4) Enter a custom list
  5) None
Choice [1]: 1

Tables to allow for WRITES:
  1) Just incident
  2) Common ITSM set (incident,change_request,problem,task,sys_user)
  3) All tables (*)
  4) Enter a custom list
  5) None (default)
Choice [5]: 1

Wrote profile dev.

Register this server with codex and claude-code? [Y/n]: y

ServiceNow MCP doctor

ok    node: v22.11.0
ok    server command: servicenow-mcp resolves on PATH; clients spawn it over stdio
ok    config directory: ~/.servicenow-mcp (0700)
ok    profile dev: instance: https://dev12345.service-now.com
ok    profile dev: credential: oauth clientSecret resolves from its encrypted source
ok    profile dev: table access: 1 read, 1 write, 1 target(s)

All checks passed.

Setup complete.

Profile   dev
Reads     incident
Writes    incident
Transport stdio (each client spawns its own servicenow-mcp)
Clients   codex, claude-code

Start codex or claude-code and it will launch the server itself.
There is nothing to keep running between sessions.
```

There is nothing to start. The server speaks **stdio**: each registered client
spawns its own copy of `servicenow-mcp` on demand and talks to it over that
process's stdin and stdout. Setup finishes by running the same checks `doctor`
runs, so you can re-run them any time:

```bash
servicenow-mcp-setup doctor --profile dev
```

`npx @onlyflows/servicenow-mcp@latest setup` runs the same wizard without a
global install, and `servicenow-mcp setup` is an alias for
`servicenow-mcp-setup`.

If you choose Basic and the instance answers 401, the wizard explains the
Basic Auth restriction and asks what next: `retry` with the same settings,
switch to `oauth` (it discards the Basic credential and asks the OAuth
questions, keeping the profile name and instance), or `stop`. Nothing is
saved until a credential verifies.

### Scripted setup

Pass any flag, or run without a terminal, and the wizard steps aside for the
original non-interactive behavior — so CI and provisioning scripts are
unaffected. `--non-interactive` forces it explicitly. Only the interactive
wizard defaults to OAuth. `servicenow-mcp-profile create` has no default you
should rely on: pass `--auth-type oauth` (recommended) or `--auth-type basic`.
Left out, it still creates a Basic profile, as it always has, so existing
scripts keep working, and it prints a deprecation notice only when standard
error is an interactive terminal, so output a script captures is unchanged. A
future release may require the flag.

```bash
servicenow-mcp-setup --non-interactive --clients none --json
servicenow-mcp-profile create --name dev --instance https://yourinstance.service-now.com \
  --auth-type oauth --client-id <client-id> --source reference --provider env
servicenow-mcp-setup grant --profile dev --read incident,problem --write incident
```

### The `servicenow-mcp-setup` commands

| Command | Purpose |
|---------|---------|
| `servicenow-mcp-setup` | Generate local auth material and register supported clients |
| `servicenow-mcp-setup client --client <name>` | Print copy-pasteable config for a client |
| `servicenow-mcp-setup grant --profile <name> --read <tables>` | Add table access rules to a profile |
| `servicenow-mcp-setup policy show --profile <name>` | Print the profile's effective policy as one table (tables, tools, fields, batch limits); never prints a secret |
| `servicenow-mcp-setup doctor` | Diagnose the install and print remedies |

`grant` and the wizard print a warning, and still grant, when write access
lands on a privilege-sensitive table: role, group, approval, script,
property, user or authentication tables such as `sys_user_has_role`,
`sysapproval_approver`, `sys_script` or `sp_widget`, and the MID Server queue
(`ecc_queue` and its rotation shards), whose records can run commands on MID
Server hosts.

`--force` regenerates the owner/client identifiers but deliberately preserves
`SN_PROFILE_ENCRYPTION_KEY`, which decrypts every credential envelope in
`config.json`. Add `--help` to any command for its full options.

> **The server runs as you, and the client list is the boundary.** Nothing
> listens on a port, so nothing off this machine can reach it and no web page
> can drive it. What that leaves is the registration: every MCP client
> registered here can spawn the server and use whatever ServiceNow access your
> profiles grant, as your integration account. Keep the grants narrow, and
> remove a client you no longer use with `claude mcp remove servicenow-mcp` or
> `codex mcp remove servicenow-mcp`. No ServiceNow credential is copied into a
> client's configuration file — the spawned server reads the profile and its
> encryption key from the owner-only `~/.servicenow-mcp` directory.

### Connecting a client

`servicenow-mcp-setup` registers Codex and Claude Code automatically when their
CLI is on `PATH`. For everything else:

```bash
servicenow-mcp-setup client --client claude-desktop
servicenow-mcp-setup client --client all
```

Every supported client speaks stdio natively, so each one is configured the
same way: a command to spawn.

```bash
claude mcp add servicenow-mcp -- servicenow-mcp
codex mcp add servicenow-mcp -- servicenow-mcp
```

stdio is the default transport for both CLIs, so there is no transport flag to
pass. For clients configured by file:

```json
{
  "mcpServers": {
    "servicenow-mcp": { "command": "servicenow-mcp", "args": [] }
  }
}
```

| Client | Configured by | Config location |
|--------|---------------|-----------------|
| Claude Code | `claude mcp add` or `.mcp.json` | project or `--scope user` |
| Codex | `codex mcp add` or `config.toml` | `~/.codex/config.toml` |
| Cursor | file | `~/.cursor/mcp.json` or `.cursor/mcp.json` |
| VS Code | file (`"type": "stdio"`) | `.vscode/mcp.json` or user `mcp.json` |
| Claude Desktop | file | `claude_desktop_config.json` |
| Windsurf | file | `~/.codeium/windsurf/mcp_config.json` |

No client holds a ServiceNow credential. The spawned server resolves its own
from `~/.servicenow-mcp`, which is owner-only.

Full per-client blocks are in
[V2 service and client setup](docs/CLIENT-SETUP.md#7-mcp-client-configuration).

> **`servicenow-mcp` must be on the spawning client's `PATH`.** A global npm
> install puts it there. If it is not — a project-local install, or a GUI
> client with a different `PATH` — register the absolute entrypoint instead;
> `servicenow-mcp-setup doctor` checks this and prints the exact command.

### Guided profile creation from your client

After the bootstrap, a connected MCP client can walk you through profile
creation:

```text
Add a ServiceNow MCP profile for https://yourinstance.service-now.com
```

The MCP prompt is `servicenow-mcp.add-profile`. It guides profile naming, auth
mode, and least-privilege default-deny access, and deliberately does **not**
ask you to paste passwords, API keys, bearer tokens, OAuth client secrets, or
encryption keys into chat.

### What gets installed

- `servicenow-mcp` — the MCP server itself, spawned by a client over stdio
- `servicenow-mcp-profile` — manages profile credentials out of band
- `servicenow-mcp-setup` — bootstrap, client config, grants, and diagnosis

### Manual configuration without the bootstrap

The server keeps configuration explicit. A manual run needs:

- audit identity: `MCP_OWNER_ID` and `MCP_CLIENT_ID` (optional; they label
  audit records and default to `local-owner`/`local-client`)
- one named ServiceNow profile, either in `~/.servicenow-mcp/config.json` or
  through `SN_PROFILE_NAME` + `SN_INSTANCE` + auth-specific `SN_*` variables
- per-profile table access rules; unconfigured access denies everything

The `SN_*` environment path builds a profile **only when
`~/.servicenow-mcp/config.json` does not exist**. Once you create a profile
file, `SN_ALLOWED_READ_TABLES`, `SN_ALLOWED_WRITE_TABLES`, and
`SN_TABLE_ACCESS_TARGETS` stop applying and the rules must live on the profile
(`servicenow-mcp-setup grant`). This is the most common cause of a server that
denies every call; `servicenow-mcp-setup doctor` detects it.

The server reads `~/.servicenow-mcp/server.env` itself at startup, because the
client that spawns it supplies its own environment and will not have sourced
anything. A value already present in the environment always wins over that
file, so container and CI configuration is unaffected.

For a quick environment-only run with no profile file — driving the server by
hand over a pipe, or from a client that passes environment variables — inject
protected values from your keychain or secret manager and pass only non-secret
values on the command line:

```bash
MCP_OWNER_ID=local-owner \
MCP_CLIENT_ID=local-client \
SN_PROFILE_NAME=dev \
SN_INSTANCE=https://yourinstance.service-now.com \
SN_AUTH_TYPE=oauth \
SN_CLIENT_ID=your-non-secret-client-id \
SN_ALLOWED_READ_TABLES=incident,problem,change_request \
SN_ALLOWED_WRITE_TABLES=incident,change_request \
SN_TABLE_ACCESS_TARGETS='[{"table":"incident","kind":"canonical","tools":["sn_query","sn_get","sn_create","sn_update","sn_incident_add_comment","sn_incident_add_work_note","sn_delete","sn_batch"],"closureComplete":true,"relatedTables":["incident"]},{"table":"problem","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["problem"]},{"table":"change_request","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["change_request"]}]' \
servicenow-mcp
```

Do not put `SN_PASSWORD`, OAuth client secrets, or API keys in command history.
Inject them into the server's environment from your approved secret mechanism,
or leave them in the owner-only profile file where the server can resolve them
without any client seeing them.

### Source install for development

Use source install only for development or unreleased changes:

```bash
git clone https://github.com/onlyflowstech/servicenow-mcp.git
cd servicenow-mcp
npm install
npm run build
npm start
```

For local development with a rebuild and source maps:

```bash
npm run dev
```

Container deployment applies to the dormant HTTP transport rather than a 2.0 stdio install; see [Production container deployment](docs/CONTAINER-DEPLOYMENT.md) and the [enterprise boundary](docs/ENTERPRISE-RELEASE-BOUNDARY.md#the-dormant-http-transport).

---

## Multi-Instance Profiles

Manage multiple ServiceNow instances (dev, test, prod, PDI) with named profiles. Every tool call must select one configured profile explicitly; V2 has no active-profile or default-profile fallback.

### Setup

Create profiles with the CLI rather than by hand — it captures credentials
without putting them in argv, and it writes the file with the right ownership
and mode:

```bash
servicenow-mcp-profile create --name dev  --instance https://mydev.service-now.com  --auth-type oauth --client-id <dev-client-id>  --source reference --provider env
servicenow-mcp-profile create --name prod --instance https://myprod.service-now.com --auth-type oauth --client-id <prod-client-id> --source reference --provider env

servicenow-mcp-setup grant --profile dev  --read incident,problem --write incident
servicenow-mcp-setup grant --profile prod --read incident
```

The resulting `~/.servicenow-mcp/config.json` looks like this. Note
`tableAccess`: **a profile without it denies every tool call.**

```json
{
  "version": 2,
  "profiles": {
    "dev": {
      "instance": "https://mydev.service-now.com",
      "authType": "oauth",
      "clientId": "your-dev-client-id",
      "clientSecret": { "type": "secret_ref", "provider": "env", "reference": "SN_CLIENT_SECRET_DEV" },
      "description": "Development instance",
      "tableAccess": {
        "readTables": ["incident", "problem"],
        "writeTables": ["incident"],
        "targets": [
          {
            "table": "incident",
            "kind": "canonical",
            "tools": [
              "sn_query", "sn_get", "sn_aggregate", "sn_schema", "sn_codesearch",
              "sn_create", "sn_update",
              "sn_incident_add_comment", "sn_incident_add_work_note"
            ],
            "closureComplete": true,
            "relatedTables": ["incident"]
          },
          {
            "table": "problem",
            "kind": "canonical",
            "tools": ["sn_query", "sn_get", "sn_aggregate", "sn_schema", "sn_codesearch"],
            "closureComplete": true,
            "relatedTables": ["problem"]
          }
        ]
      }
    }
  }
}
```

Have the approved supervisor, orchestrator, keychain, or secret manager provide
the values referenced by `SN_CLIENT_SECRET_DEV` and `SN_CLIENT_SECRET_PROD` in the
environment the server is spawned with, or in `~/.servicenow-mcp/server.env`,
which the server falls back to. Do not type either value into a shell command,
command argument, dotenv file, or command history.

Each `targets` entry must set the literal `closureComplete: true`, and its
`relatedTables` must include the target table itself. `relatedTables` is a
declaration that the loader checks for consistency: every related table must
be in the allowlist of each operation the target is in, or the profile is
rejected. The loader does not derive it from the instance. ServiceNow returns
inherited fields through the child table's own endpoint, so a self-only list
such as `["incident"]` is enough to read them. Declaring the immediate parent,
as `servicenow-mcp-setup` offers, is optional:
`servicenow-mcp-setup grant --profile dev --read change_request --related change_request=task`.
That adds `task` to the read allowlist, because the loader requires it, and a
later grant that gives `change_request` another operation adds `task` to that
operation's allowlist too. On its own this makes `task` addressable by no tool,
because it has no target of its own, unless such an allowlist is `*`. If
`task` has, or later gets, a target of its own, that target's tools can then
use those operations on it, so declare a table only where every tool on its
own target may use every operation the declaring target has or will have.
A grant on a base table such as `task` reaches the records of the tables that
extend it, such as `incident`, whatever `relatedTables` lists, so grant a base
table only when those records should be reachable through it. Likewise, a
view or alias returns data from every table it reads, whatever
`relatedTables` lists: declare each of those tables, so the loader requires
each to carry the same permission, and grant the view only when all of that
data should be reachable.

### Credential Options

| Format | Example | Description |
|--------|---------|-------------|
| Legacy environment reference | `"env:SN_PASSWORD_DEV"` | Read-compatible V1 form; migrated to a structured reference on the next write |
| Secret reference | `{"type":"secret_ref","provider":"env","reference":"SN_PASSWORD_DEV"}` | Provider-neutral reference resolved only for the selected request |
| Encrypted envelope | `{"type":"encrypted","version":1,...}` | AES-256-GCM value created by the protected administration CLI |

Plaintext profile secrets are rejected. Use the installed `servicenow-mcp-profile`
operator command to create, inspect, rotate, or remove profiles; it reads secrets
through a protected prompt or bounded standard input and rejects credential-bearing
command-line arguments. Encrypted sources require exactly 32 random bytes encoded
as base64 or base64url in `SN_PROFILE_ENCRYPTION_KEY`, supplied separately by the
deployment secret mechanism and never stored in the profile file. See the
[profile credential and administration guide](docs/PROFILE-CREDENTIALS.md).

The legacy `env:VAR_NAME` indirection remains readable for every secret field:
`credential`, `clientSecret`, and `apiKey`.

### Using Profiles

Pass the `profile` parameter on every tool call:

- *"query incidents on prod"* — calls `sn_query` with `profile: "prod"`
- *"get incident INC0010001 on dev"* — calls `sn_get` with `profile: "dev"`
- *"show me the dev profile endpoint"* — calls the read-only `sn_profile` diagnostic with `profile: "dev"`

Profiles are created and changed out of band by the service operator. Legacy
`default_profile` metadata is ignored and is not persisted on the next
administrative write; the MCP boundary never consults it.

### `SN_*` configuration compatibility

If no config file exists, canonical `SN_*` connection values are exposed only
through an explicit `SN_PROFILE_NAME` mapping. For example, set
`SN_PROFILE_NAME=dev` with `SN_INSTANCE`, `SN_AUTH_TYPE=oauth`, `SN_CLIENT_ID`
and `SN_CLIENT_SECRET`, then call tools with `profile: "dev"`. Without
`SN_AUTH_TYPE` the environment profile is Basic (`SN_USER` and `SN_PASSWORD`),
as it has always been; set `SN_AUTH_TYPE` explicitly. Without `SN_PROFILE_NAME`, bare connection
variables create no profile and cannot route a request. Secret values remain
runtime-only environment references and are never persisted as plaintext.

---

## Authentication

Three ServiceNow auth types are available per profile, selected with `authType`. The setup wizard and every example here use OAuth client credentials. A saved profile that has no `authType` is read as Basic, because that is what such a profile has always meant; saved profiles are never rewritten. Profile configuration is managed out of band by the service operator. This is the only authentication involved: the transport is stdio, so there is no endpoint in front of the server to protect.

> **Heads up:** ServiceNow's [inbound Basic Auth restriction program](https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB3096078) is phasing out basic auth for API requests — instances can start hard-rejecting it at any time (exemptions: Web-Service-Access-Only accounts or the `snc_basic_auth_api_access` role). **OAuth is the recommended auth type.** The server prints a startup warning for basic-auth profiles.

### OAuth 2.0 (recommended)

`client_credentials` grant (default). On the instance you need three things:

1. An **Application Registry** entry, an OAuth API endpoint for external clients (**System OAuth → Application Registry**), which gives you a client ID and a client secret.
2. The **client credentials grant enabled** for it: on current releases the system property `glide.oauth.inbound.client.credential.grant_type.enabled` must be `true`.
3. An **OAuth Application User** set on that entry: the integration user the server acts as. Give it the least roles that do the job, not an administrator.

Then create the profile with the wizard (`servicenow-mcp-setup`, press Enter at the authentication prompt) or `servicenow-mcp-profile create --auth-type oauth --client-id <client-id>`, or reference the secret via `env:` indirection:

```json
{
  "version": 2,
  "profiles": {
    "dev": {
      "instance": "https://mydev.service-now.com",
      "authType": "oauth",
      "clientId": "your-oauth-client-id",
      "clientSecret": "env:SN_CLIENT_SECRET",
      "description": "OAuth client_credentials"
    }
  }
}
```

`password` grant — set `grantType` and provide the user credentials as well:

```json
{
  "instance": "https://mydev.service-now.com",
  "authType": "oauth",
  "grantType": "password",
  "clientId": "your-oauth-client-id",
  "clientSecret": "env:SN_CLIENT_SECRET",
  "username": "integration.user",
  "credential": "env:SN_PASSWORD_DEV"
}
```

Tokens are cached until shortly before their `expires_in` expiry and refreshed automatically (including a single refresh + retry on 401). Token responses are never logged.

### API key

For instances using Inbound Authentication Profiles with API keys. The header name is configurable (default `x-sn-apikey`):

```json
{
  "instance": "https://mydev.service-now.com",
  "authType": "apikey",
  "apiKey": "env:SN_API_KEY",
  "apiKeyHeader": "x-sn-apikey"
}
```

### Basic (legacy, deprecated by ServiceNow)

Basic is no longer the wizard's default. Use it only for an instance that still accepts it.

```json
{
  "instance": "https://mydev.service-now.com",
  "username": "admin",
  "credential": "env:SN_PASSWORD_DEV"
}
```

On a 401 for a basic-auth profile, the error explains the Basic Auth restriction program (KB3096078): the role `snc_basic_auth_api_access` or a Web-Service-Access-Only account is needed, and OAuth is the recommended way to move off Basic Auth. The setup wizard gives the same explanation when it verifies the credential.

### Timeouts & retries

Every request is bounded by a timeout (default 30s; per-profile `timeoutMs` or env `SN_TIMEOUT_MS`) and retried up to twice with exponential backoff on 429/502/503/504, honoring `Retry-After`. POST requests are only retried on 429 — never after a 5xx that may have executed side effects.

ServiceNow upstream can return HTTP 429 with an empty body, while this server's own HTTP rate-limit rejections return a short JSON body plus `Retry-After`. Treat the status and `Retry-After` header as authoritative; do not benchmark or validate tool success from response latency or body shape alone. In normal ServiceNow instances, plan around the Background throttling default of roughly 120 requests per 60 seconds per identity unless the instance limit is explicitly raised.

---

## What the tools cover

The registered catalog has 24 tools (see [Tools Reference](#tools-reference)):

| Area | Tools |
|------|-------|
| Records | `sn_query`, `sn_get`, `sn_create`, `sn_update`, `sn_delete`, `sn_batch` |
| Incident journals (append-only) | `sn_incident_add_comment`, `sn_incident_add_work_note` |
| Analytics and schema | `sn_aggregate`, `sn_schema`, `sn_health` |
| CMDB and operations | `sn_relationships`, `sn_attach`, `sn_syslog`, `sn_codesearch`, `sn_discover` |
| ATF | `sn_atf_author`, `sn_atf_run`, `sn_atf_results`, `sn_atf_readiness`, `sn_atf` |
| Flow Designer (read-only) | `sn_flow_view` |
| Profiles | `sn_profile` |
| Natural language | `sn_nl` (currently policy-denied pending a typed access plan) |

Every tool requires a `profile`, and every tool is subject to the profile's
table and field policy. `sn_script` (background scripts) is not registered; see
the [Roadmap](#roadmap).

---

## Manual environment setup

The server speaks stdio and requires Node.js 20 or newer. The shortest path is
the bootstrap described under [Installation](#installation):

```bash
servicenow-mcp-setup
```

That registers your clients; each one spawns the server when it needs it.

The rest of this section is the manual environment path, for a deployment that
injects everything from a supervisor or secret manager, or for driving the
server by hand over a pipe.

Use [`.env.example`](.env.example) only as a non-secret configuration
inventory. Its protected-value assignments are intentionally empty; inject
ServiceNow secrets through a supervisor, orchestrator, keychain, or secret
manager rather than filling a repository dotenv file.

> The `SN_ALLOWED_*` and `SN_PROFILE_NAME` variables below build a profile only
> when `~/.servicenow-mcp/config.json` does **not** exist. With a profile file
> present, put the rules on the profile with `servicenow-mcp-setup grant`.

```bash
export MCP_OWNER_ID="your-owner-id"
export MCP_CLIENT_ID="your-client-id"
export SN_ALLOWED_READ_TABLES="incident,problem,change_request"
export SN_ALLOWED_WRITE_TABLES="incident,change_request"
export SN_TABLE_ACCESS_TARGETS='[{"table":"incident","kind":"canonical","tools":["sn_query","sn_get","sn_create","sn_update","sn_incident_add_comment","sn_incident_add_work_note","sn_delete","sn_batch"],"closureComplete":true,"relatedTables":["incident"]},{"table":"problem","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["problem"]},{"table":"change_request","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["change_request"]}]'
export SN_PROFILE_NAME="dev"
export SN_INSTANCE="https://yourinstance.service-now.com"
export SN_AUTH_TYPE="oauth"
export SN_CLIENT_ID="your-non-secret-oauth-client-id"
npm run build
npm start
```

Before running those non-secret commands, the approved runtime secret
mechanism must already have injected the authentication-specific ServiceNow
secret into the process. Do not enter it in this shell block.

A client connects by spawning the command; there is no URL and no header:

```json
{
  "mcpServers": {
    "servicenow-mcp": { "command": "servicenow-mcp", "args": [] }
  }
}
```

JSON-RPC messages travel on the child's stdin and stdout, one newline-delimited
message per frame. Everything else the server reports — startup warnings, and
one structured JSON-line event per completed tool call — goes to **stderr**,
which your client captures as its server log. There is no per-message size
limit imposed by the transport.

For complete official SDK and independent client examples, safe two-profile
setup, and crossed profile/result/audit checks, see
[V2 service and client setup](docs/CLIENT-SETUP.md).

### Breaking changes in 2.0

Every tool call must name a `profile`, and table access is deny-by-default.
Those two require action on every install. The transport is stdio, as it was in
`1.0.0`, so a client configured with a `command` entry keeps working.

The breaking changes from `1.0.0`, each with a before/after example, are in
[Migrating to 2.0](docs/V2-MIGRATION.md#breaking-changes-at-a-glance).

Already on 2.x? 2.2.0 changes field-policy loading and journal writes, and
can refuse to start on a configuration that loads today. Read
[Upgrading to 2.2.0](docs/V2-MIGRATION.md#upgrading-to-220) first.

### Deployment guides for the dormant HTTP transport

2.0 ships stdio only. The container image, the health and shutdown contract,
the operations runbook, and the Secure MCP Tunnel adapter all describe the
[dormant HTTP transport](docs/ENTERPRISE-RELEASE-BOUNDARY.md#the-dormant-http-transport),
which no CLI path reaches. They are kept because that transport is a planned
enterprise deployment shape, not because they apply to a 2.0 install — nothing
in this section is needed to use this server.

- [Production container deployment](docs/CONTAINER-DEPLOYMENT.md) — OCI
  artifact, non-root runtime, provenance and scanning
- [Remote operations runbook](docs/OPERATIONS-RUNBOOK.md) — health
  interpretation, telemetry, alerts, rotation, incident response
- [Private ChatGPT connectivity](docs/PRIVATE-CHATGPT-CONNECTIVITY.md) —
  outbound-only Secure MCP Tunnel adapter

---

## Tools Reference

### Core CRUD

| Tool | Description |
|------|-------------|
| `sn_query` | Query an approved table with structured filters, field selection, pagination, and sorting; bounded raw reads require an explicit policy rule. Paging runs on `has_more` and `next_offset`, which can end early if ServiceNow ACLs strip rows from a page; cross-check with `sn_aggregate` `COUNT`. A page cut to fit `max_response_bytes` keeps the same contract: see [Paging when a response is cut to size](#paging-when-a-response-is-cut-to-size) |
| `sn_get` | Get a single record by sys_id from an approved table |
| `sn_create` | Create a record on any table granted for writes, using only field-policy-approved writable fields, including the journal fields `comments` and `work_notes`; `incident` additionally requires a bounded `short_description` |
| `sn_update` | Update one record selected by exact `sys_id` on any table granted for writes, using only field-policy-approved writable fields; `comments` and `work_notes` append a journal entry |
| `sn_incident_add_comment` | Append one bounded customer-visible comment to an incident; repeated calls append again |
| `sn_incident_add_work_note` | Append one bounded internal work note to an incident; repeated calls append again |
| `sn_delete` | Delete a record on an approved write table (requires `confirm: true`) |
| `sn_batch` | Bulk update/delete using a required structured filter and dry-run safety (raw encoded selectors are prohibited; requires `confirm: true` to execute; a dry run returns the count, up to 5 sample records the profile may read, and the field names it would write). Values get the same policy as `sn_update`; execution uses the ServiceNow REST Batch API and never re-sends a batch |

### Analytics & Schema

| Tool | Description |
|------|-------------|
| `sn_aggregate` | COUNT, AVG, MIN, MAX, SUM with grouping |
| `sn_schema` | Table field definitions, types, references |
| `sn_health` | Instance version, cluster nodes, stuck jobs, key stats |

### CMDB & Operations

| Tool | Description |
|------|-------------|
| `sn_relationships` | CMDB CI graph traversal — upstream/downstream/both, configurable depth |
| `sn_attach` | List attachments, return downloads as inline base64, and upload inline base64 content; never touches a host filesystem path |
| `sn_syslog` | Query system logs with severity/source/time filters, newest first. `tail: true` starts a tail (the newest entries, oldest first, plus a `cursor`); each later call with `after_cursor` returns only the entries after it, oldest first, plus a new `cursor` ([Tailing the system log](#tailing-the-system-log)) |
| `sn_codesearch` | Search business rules, script includes, client scripts, etc., with a snippet around each match ([Code search](#code-search)). Part of the default read grant, so a plain read grant on a code table allows it |
| `sn_discover` | Discover tables, scoped apps, store apps, plugins |

#### Tailing the system log

`sn_syslog` can follow the log without re-reading it. The first call sends
`tail: true` and gets the newest `limit` entries (inside the `since` window),
oldest first, and a `cursor`. Each later call sends that cursor as
`after_cursor` and gets only the entries created after it, oldest first, and a
new `cursor`; poll no faster than every few seconds.

- **No skips, no repeats.** Many log rows share one `sys_created_on` second, so
  the cursor holds the second and the row's `sys_id`, and a call returns the
  rows after that pair. It is an opaque token: pass it back as given.
- **`has_more`.** If more than `limit` entries are waiting, the call returns
  `limit` of them with `has_more: true` and a cursor at the last one; call again
  with it. A response cut to fit the byte budget does the same, and the cursor
  always names the last entry actually returned. Tail pages carry no `total` and
  no `next_offset`, and `offset` cannot be combined with a tail.
- **Same filters on every call.** The cursor is bound to the `level`, `source`
  and `message` it was issued for. A call that changes them is refused (so is a
  malformed, oversized or altered cursor) with a fixed message that does not
  repeat the cursor. `since` applies to the first call only, but a cursor older
  than the longest `since` (525,600 minutes, one year) is refused with a fixed
  message: start a new tail. With nothing to return, the call gives the same
  position back, so keep polling with it. If the first call finds no entries in
  its window it returns no cursor; call it again.
- **Reads go straight to the instance**, never through the metadata cache, and
  use the same table and field policy as an ordinary `sn_syslog` read. A tail
  also reads `sys_id` and `sys_created_on` to place the cursor, so a field policy
  that withholds either refuses it.
- **Limits.** Order is by creation second, then `sys_id`. A row the instance
  stores late with a creation time at or before the cursor's second is not seen
  by a tail that has already moved past it.

### Testing & Automation

| Tool | Description |
|------|-------------|
| `sn_atf_author` | Create tests/suites, ordered memberships and validated typed steps |
| `sn_atf` | Legacy test/suite listing and results; execution redirects to `sn_atf_run` |
| `sn_atf_readiness` | Check plugins, properties, Cloud Runner installation and permissions |
| `sn_atf_run` | Execute a suite through Cloud Runner only, with bounded polling |
| `sn_atf_results` | Fetch results, cached history and comparisons |
| `sn_nl` | Currently fails closed until natural-language composition emits a complete typed access plan |

`sn_script` (background script execution) shipped in 1.0.0 as an unimplemented
stub and is **not published in 2.0** — it does not appear in `tools/list`. Use
`sn_query` and `sn_batch` instead. See [Roadmap](#roadmap).

### Flow Designer

| Tool | Description |
|------|-------------|
| `sn_flow_view` | Show a flow or subflow as a Mermaid diagram, an outline and a structured graph: trigger, steps, branches, loops, error handling, input values under field policy, and called subflows to depth 3. Read-only through the Table API; never calls Flow Designer's internal API. See [docs/FLOW-VIEW.md](docs/FLOW-VIEW.md) |

### Profile Management

| Tool | Description |
|------|-------------|
| `sn_profile` | Inspect non-secret metadata and the effective policy card for one explicitly named profile; profile configuration is operator-managed out of band |

---

## Environment Variables

### MCP runtime

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `MCP_OWNER_ID` | ❌ | `local-owner` | Stable non-secret owner identifier recorded in request/tool context and every audit record. A label, not a credential; it is never checked. |
| `MCP_CLIENT_ID` | ❌ | `local-client` | Stable non-secret client identifier recorded in request/tool context and every audit record. A label, not a credential; it is never checked. |

That is the whole list. There is no bind address, port, `Host`/`Origin`
allowlist, concurrency cap, connection cap, shutdown grace period, bearer
token, or rate limit, because there is no listener: a client spawns the server
and owns its lifetime.

The server reads these from its environment and falls back to
`~/.servicenow-mcp/server.env` for any it does not find there. That file is
owner-only (mode `0600`) and is where `servicenow-mcp-setup` writes the
generated identifiers and `SN_PROFILE_ENCRYPTION_KEY`. It exists because the
client that spawns the server supplies its own environment and will not have
sourced anything. A value already present in the environment always wins, so a
container or CI runner that passes configuration directly is unaffected.
`servicenow-mcp-setup doctor` reports that file's mode and contents.

### Observability

Each completed tool call emits one JSON-line event to **stderr**, which the
spawning client captures as its server log:

```json
{"schemaVersion":1,"type":"mcp_tool","observedAtMs":1737000000000,"latencyMs":42,
 "correlationId":"stdio-<session>-<invocation>","ownerIdHash":"sha256:...",
 "clientIdHash":"sha256:...","tool":"sn_query","profile":"dev",
 "instance":"https://dev00001.service-now.com","outcome":"success","reason":null,
 "errorCategory":null,"retry":null,"retryAfterSeconds":null}
```

Tool audits classify request cancellation and request-deadline expiration
separately from handler failures. Configured owner/client identifiers are
represented only by SHA-256 pseudonyms; headers, URLs/query strings, bodies,
credentials, tokens, config objects, and exception text are not event fields.
Telemetry never blocks a tool result: stderr backpressure retains at most 256
pending lines, drops excess events, and emits a
`{"type":"telemetry_dropped","count":N}` summary after the stream drains.

A correlation ID is `stdio-<session>-<invocation>`. The session half is fixed
for the life of one spawned server, so every record from one client session
groups together; the invocation half is fresh per call. Neither half is derived
from anything the caller sent.

**stdout carries the protocol and nothing else.** Every diagnostic goes to
stderr. One stray byte on stdout would desynchronize the client's JSON-RPC
parser and end the session, so there is no such thing as a harmless
`console.log` on the startup or request path; `test/stdio-entrypoint.test.ts`
spawns a real server and asserts it.

Arguments that fail a tool's schema are rejected by the MCP SDK before any
handler runs, so they return an error to the caller but produce **no audit
event** — the execution context that would issue one is never opened. Every
call that reaches a tool is audited.

### Body size and concurrency (dormant HTTP runtime only)

None of this applies to the shipped server. It describes the dormant HTTP
runtime, which no CLI path reaches — see
[the enterprise release boundary](docs/ENTERPRISE-RELEASE-BOUNDARY.md#the-dormant-http-transport)
— and binds only someone embedding this package and calling `createHttpRuntime`
directly. Over stdio there is no request-body limit and no admission ceiling.

Request body size and concurrency trade directly against each other under the
512 MiB admission ceiling:

| `maxBodyBytes` | Highest concurrency that starts | Effect |
|---|---|---|
| 1 MiB (shipped default) | 2 | 416 MiB budgeted; the intended configuration |
| 1.75 MiB | 2 | 512 MiB — exactly at the ceiling |
| **2 MiB** | **1** | **Single-flight: every tool call serializes** |
| 5.75 MiB | 1 | the last value that starts at all |
| above 5.75 MiB | none | startup fails at any concurrency |

Two failure modes are worth knowing:

- **At 2 MiB and above the server is single-flight.** Concurrency 2 no longer
  fits, so the runtime can only start at 1 and every tool call queues behind
  every other one. There is no warning and no log line — it presents as "the
  server got slow", and one large upload blocks every other tool for its
  duration. Nothing connects the cause to the effect.
- **Above 5.75 MiB the server refuses to start.** A constructor `throw`, not a
  clamp. The message names `maxConcurrentRequests` and `maxBodyBytes` but gives
  neither the ceiling, the arithmetic, nor a working value; the table above is
  the way forward.

**`maxBodyBytes` is not operator-configurable.** `src/http-entrypoint.ts`
builds the request policy with only `allowedHosts` and `allowedOrigins`, so the
limit is always 1 MiB and no environment variable changes it.

### Code search

`sn_codesearch {search_term, table?, field?, limit?, offset?}` finds records
whose script contains the text, in the business rules, script includes, UI
scripts, client scripts, scripted REST operations, ES modules and ATF step
scripts of the instance. Each row
is `{table, table_label, sys_id, name, snippet, line}`: `snippet` is about 200
characters of the script centred on the first match (`...` marks a cut) and
`line` is the line that match is on. The comparison is the instance's
case-insensitive `LIKE`; if the text holds no literal match for the term, the
snippet is the head of the script and the row has no `line`.

- **One table or all.** With `table`, one table is searched (and `field` can
  name another field of it, such as `name`). With none, every code table the
  profile may read is searched, and the tables left out are named in a warning
  (`Not searched, because this profile does not allow sn_codesearch to read
  them: sys_script, sys_ws_operation. To include one, run servicenow-mcp-setup
  grant --profile <profile> --read <table> --tools sn_codesearch.`). A table is
  left out when the table policy does not bind `sn_codesearch` to it or the field
  policy does not let the profile read its script field. The call fails only when
  none can be read, and the error says why.
- **ES modules** are `sys_module`: the script is its `content` column and a row
  is named by its `path`, because the table has no `name`. A profile reads it
  once the table policy allows it: `servicenow-mcp-setup grant --profile dev
  --read sys_module`, or a read wildcard. It is cached by default like the other
  code tables, and `fields=all` reads `content`. A default `sn_query` of it lists
  `sys_id`, `path` and `sys_updated_on`. `sys_module` is a built-in system table
  (the 24th), so a `"*"` entry in the field policy does not narrow it: a profile
  whose `"*"` entry limits `readable` and that can read `sys_module` now reads
  `content`, where it did not before. To narrow it, name it in `fieldPolicy`
  (`"sys_module": { "readable": ["sys_id", "path"] }`).
- **ATF step scripts** are searched with `table: "sys_atf_step"`. A step's script
  is not a column of the step but the value of its script input, a row of
  `sys_variable_value`. The search reads only the rows whose `document` is
  `sys_atf_step` and whose `variable` ends with `script`, a condition fixed in
  the server: no argument can widen it to another table's variables, and `field`
  is refused. Each result is the step (`sys_id` is the step's), named
  `<test name> > step <order>` where `order` is the step's own order value, and
  the steps and then their tests are read by id to say so. Three tables are read,
  so the profile needs read on `sys_variable_value`, `sys_atf_step` and
  `sys_atf_test`, each bound to `sn_codesearch`:
  `servicenow-mcp-setup grant --profile dev --read sys_variable_value,sys_atf_step,sys_atf_test`
  (or `--tools sn_codesearch` to bind only this tool: `sys_variable_value` also
  holds other tables' variable values, which that grant does not let this tool
  search). `grant --atf` binds those tables to `sn_atf_author` only, so a profile
  that has it adds this grant on top. A search with no `table` includes ATF
  step scripts when all three are held and names `sys_atf_step` in the warning
  when they are not. These tables are not in the default cache list: the reads go
  straight to the instance.
- **A page is shared among the tables.** A search of several tables takes turns:
  each table's first match (script includes first, then business rules, UI
  scripts, client scripts, scripted REST operations, ES modules), then each
  table's second,
  and so on, each table in `sys_id` order. No table crowds the others off page
  1, and the order depends only on the data, so `offset` and `next_offset` page
  through it exactly. A table with few matches leaves its share to the others.
- **Large pages degrade, they do not fail.** A script can be hundreds of
  kilobytes, so a page of them does not fit one response. A search of one table
  with `limit` 49 or less reads the scripts with the rows, in one request (and
  falls back to the two steps below if that page passes the cap). A larger page, or a search of several tables, first finds the rows without
  their scripts and then reads the scripts of the rows it returns, 50 at a time,
  narrowing a batch that is still too large. One search spends at most 12 such
  requests and 8 MiB, and only for the rows one response can hold (about 280);
  when that is spent, the remaining rows keep an empty `snippet` and a warning
  says how many (lower `limit`). A script too large to read even on its own gives
  its row an empty `snippet` and `note: "script too large to preview"`; read it
  with `sn_get`. If the rows alone pass the response cap, the
  error says the response was too large and to lower `limit` or `offset`.
- **The scripts are still field-policy readable fields.** The search reads the
  identifier, the name and the searched field of each table, each subject to the
  profile's field policy, and the sensitive-name rules apply to `field`.

### Metadata cache

Stable ServiceNow metadata reads are cached per instance and credential identity
for 24 hours by default. The default cached table patterns are
`sys_glide_object`, `sys_dictionary`, `sys_db_object`, `sys_app`, `sys_plugins`,
`sys_metadata*`, `sys_flow*`, and the six code tables `sn_codesearch`
searches: `sys_script`, `sys_script_include`, `sys_ui_script`,
`sys_script_client`, `sys_ws_operation`, and `sys_module`. A repeated code search or
`sn_query` page on those tables is served from the cache while the table's
watermark is unchanged. Set `metadataCache.ttlMs` and
`metadataCache.tables` on a file-backed profile, or `SN_METADATA_CACHE_TTL_MS`
/ `SN_METADATA_CACHE_TABLES` for the explicit environment profile; a table
list you set replaces the default list, so name the code tables in it to keep
caching them. `sn_query`, `sn_get`, and `sn_schema` accept `force_recache: true`
to refresh metadata; `sn_codesearch` has no such flag, so a change the
watermark cannot see shows there after at most one TTL. A cold `sn_get` of a
code-table record costs two requests (the watermark, then the record), and
`sn_batch` and `sn_aggregate` reads are never cached. Memory is bounded: a
response over 512 KiB is not cached, one credential scope keeps at most 32 MiB
and the whole cache 128 MiB, evicting the least recently used first. Cached
code-table entries hold full script bodies, which can contain hard-coded
credentials, in process memory (never on disk) for up to the TTL; to keep them
out, set `metadataCache.tables` or `SN_METADATA_CACHE_TABLES` to
`sys_glide_object,sys_dictionary,sys_db_object,sys_app,sys_plugins,sys_metadata*,sys_flow*`.

**Freshness is checked against the instance, in every auth mode.** Before each
fetch the cache reads a watermark in one small request: the table's row count
(`X-Total-Count`) and its newest row by `sys_updated_on`, as ServiceNow stores
it (UTC). A cache hit is served only while a new read of that watermark still
matches. Inserts and deletes change the count, and inserts and updates change
the newest row. Both sides of the comparison come from the instance, so the
session timezone, the date format, and clock skew between this host and the
instance play no part, and no user lookup is needed. Basic, OAuth (password or
client_credentials), and API-key profiles all cache the same way. The only
access it needs is the ServiceNow read permission of the user the credential
runs as, on the cached table itself; no `tableAccess` change is needed.

**The honest tradeoff:** the cache only ever saved payload bytes, never round
trips — a cache hit still costs one watermark read, and a miss costs one extra.
A tool call reads each table's watermark once, however many times it reads the
table, until the call writes. A hierarchy walk reads `sys_db_object` once for
the whole chain. An empty table caches like any other.

**Small responses are not cached.** A hit costs a round trip about the size of
a plain read, so a response under 32 KiB (serialized body) saves nothing and is
not kept. The first read of such a selector costs the watermark and the read,
as before; the server then remembers that selector as small, for one TTL, and
reads it again in a single request with no watermark. If a later read of it
comes back at 32 KiB or more, it is cached from the next read on. Large reads,
such as script bodies, are cached and checked exactly as above, and
`force_recache: true` still reads the watermark and refreshes. The memory is
per credential scope, holds at most 512 selectors (least recently used out),
and costs no cached bytes. A call that read a small selector this way reports
`miss`. On a table whose watermark is slow (`sys_dictionary` on a large
instance: about 0.5 s against a 0.1 to 0.2 s read in one measurement) even a
large read may be faster uncached; the threshold is a size, not a time. A
profile's `metadataCache.smallReadBytes` sets the threshold (0 caches every
response; at most 512 KiB).

**Seeing what the cache did.** Every successful response carries two optional
fields in `structuredContent.metadata`. `cache` says how the call's cacheable
reads were served: `hit` (all from the cache), `miss` (from ServiceNow: nothing
cached yet, the watermark moved, the entry expired, the table could not be
cached just then, or the response is small and not kept), `bypass` (a `force_recache: true` refresh), or `mixed` (the
call made several cacheable reads with different outcomes, such as an
`sn_codesearch` with no `table` over the code tables). It is absent when
the call read no cache-eligible table. `timing` is `{ total_ms, upstream_ms,
watermark_ms }` in whole milliseconds, measured wall-clock: `total_ms` is the
whole tool call; `upstream_ms` is the time during which at least one request to
ServiceNow other than a watermark read was in flight (retry waits included);
`watermark_ms` is the same for the cache's watermark reads. Overlapping
requests are counted once, not summed, so each figure is at most `total_ms`,
though the two can overlap each other and add up to more than it. A hit reports
`upstream_ms: 0` and the watermark round trip it still costs. Callers that
share a credential share cache warmth (several profiles on one credential, or
several HTTP clients on one profile), so `cache: "hit"` can reflect another
caller's earlier read made with the same credential. Both fields hold only
numbers and those four words, and appear whether or not the cache is on
(`timing` always, `cache` only when a cacheable read happened). Only the server
sets them; a tool cannot supply its own. Each tool's `outputSchema` grows by
about 320 characters for them.

If a table's watermark cannot be used, its reads go straight upstream, without
a watermark request, for a while: 15 minutes when the cause persists (an
incomplete or future-dated watermark, a 403 or 404), 30 seconds when it may not
(429, 5xx, timeouts, network), never longer than the TTL. A table whose newest
row is dated after the instance's own clock is one of these: that row would
stay the newest however many others were updated. Entries cached earlier are
kept and serve again once the table is cacheable, and `force_recache: true`
asks again at once.

**What the watermark can miss.** An update within the same second as the stored
watermark, to a row other than the newest, and a write that skips the system
fields (`autoSysFields(false)`) leave it unchanged. Such a change shows within
one TTL — up to 24 hours at the default. Lower `SN_METADATA_CACHE_TTL_MS` or
pass `force_recache: true` to see it sooner. `sn_batch` is not exposed to these
gaps: it looks up the records it will update or delete on the instance on every
run, never in the cache, even on a cached table.

**`sn_schema` results** are also kept for 5 minutes per profile, credential
identity, and effective policy, so a repeat call costs no request at all. They
are not revalidated in that window; `force_recache: true` refreshes them, and
`schemaCacheTtlMs` / `SN_SCHEMA_CACHE_TTL_MS` (up to 1 hour) changes the window.

### Paging when a response is cut to size

A read that does not fit `max_response_bytes` (or, for a result with more than
1,000 rows, the record limit) is cut by dropping whole rows from the tail, so
the rows that come back are always a prefix of the page you asked for. For the
list tools, `has_more` and `next_offset` count the rows that were dropped:

| Field | Meaning |
|-------|---------|
| `record_count` | Rows in `results`. |
| `truncated`, `dropped_records` | `sn_query` sets them when rows were dropped for size, and says how many; every list tool reports the same in `metadata.truncation`. |
| `has_more` | True when rows were dropped for size **or** rows exist past the page: rows exist that this response did not contain. A response that came back empty because its rows were too large says `has_more: true`, not "no results". |
| `next_offset` | `offset + record_count`: the first row not returned. Following it re-reads the dropped rows before anything later, so a client that only follows `next_offset` sees every row exactly once. |

When **no row fit**, there is nothing to continue after, so `next_offset` is
left out and `metadata.pagination.recovery` is
`adjust_request_and_retry_same_offset`: `has_more: true` with no `next_offset`
means the request must change (fewer `fields`, a lower `limit`, or a higher
`max_response_bytes`; `sn_get` reads one row). The `hint` says which.

This holds for `sn_query`, `sn_syslog`, `sn_schema`, `sn_relationships`,
`sn_codesearch`, `sn_discover`, `sn_attach` (list) and `sn_atf`, whose `offset`
is a row offset into the rows they return. Any other collection result that is cut to size
(for example `sn_aggregate`) reports `has_more: true` with no `next_offset`.
A page that lost no rows to size is unchanged: `has_more` and `next_offset`
come from the row after the page, and `next_offset` is `offset + limit`.

A client that follows `next_offset` should also pass the `limit` the hint names
(`continue offset=8 limit=8`): at the original `limit` each page asks
ServiceNow for that many rows and the cut drops most of them again, so the same
rows are fetched many times over.

Before this change `next_offset` after a cut page was `offset + limit`, which
skipped the dropped rows, and a cut last page reported `has_more: false` with
`record_count: 0`.

**The `sn_query` hint gives values you can use.** For example

```text
Dropped 14/22; continue offset=8 limit=8; retry offset=0 with fields="sys_id,name" or max_response_bytes=1500 (fits the next row) or max_response_bytes=31500 (fits all 22).
```

- `continue offset=8 limit=8` is `next_offset` and the number of rows that fit:
  page on with that `limit` and nothing is dropped again.
- `retry offset=0 with ...` re-reads the whole page in one response, with fewer
  fields or a larger budget. The two budgets are different numbers, and each
  says what it buys. `max_response_bytes=1500 (fits the next row)` holds one
  more row than this response did, so a retry with it returns about one more
  row; `max_response_bytes=31500 (fits all 22)` holds every row of the page.
  Both are measured from the response itself (the rows plus the envelope's own
  metadata) and rounded up. The page figure is left out when it would be more
  than the 1,000,000-byte maximum (or the `maxResponseBytes` of the raw-read
  rule that approved a raw `query`, when that is lower) and when only one row
  was dropped, since the next row is then the rest of the page. When even the
  next row would be more than that maximum, the hint says the next row exceeds
  it, names it, and offers only fields and `sn_get`. It never names a budget
  the policy would deny.
- `fields=...` appears when it helps: the table's short default list for a
  read of the defaults or of `all`, or your own list without its large fields
  (for example `script`) when you chose one. It only ever names fields your
  profile may read, and never a sensitive one. A list with nothing large in it
  gets the `limit` and the budget instead. `response_format="concise"` is
  offered to a `detailed` read.
- When no row fit, there is no `continue` clause and no `limit`: only the
  retry options and `sn_get`.

### Unrestricted field selection (`fields=all`, `response_format=detailed`)

Both resolve to the profile's readable set for the table. Where the field
policy narrows that set, they request exactly the listed fields and read no
dictionary rows; the rest of this section applies when the readable set is
every field. That wildcard selection used to drop `sysparm_fields` entirely,
so ServiceNow returned every column and a wide table could breach the 1 MiB
cumulative upstream cap and **fail the call outright**. It is now bounded to at
most **100 columns**.

The cap bounds the *upstream request*, not the response — truncating after
receipt would not help, because the bytes have already crossed the wire and
already breached the limit. Columns are resolved from `sys_dictionary`, walking
`super_class` so an extended table contributes its inherited fields. Ordering is
deterministic: the table's curated default projection first in its declared
order, then every remaining column alphabetically. Defaults lead so a capped
result stays useful; alphabetical afterwards because dictionary row order is not
stable across instances. Every failure path falls back to the table's bounded
default projection, never to dropping `sysparm_fields`.

`sn_query` reports truncation through its `hint` field. `sn_get` will carry the
same notice shortly.

Two behavior changes worth stating plainly, because they change what a caller
gets back:

- **Journal fields are now returned.** `comments` and `work_notes` are included
  in the resolved set for `fields=all` and `detailed` wherever the profile can
  read them. See
  [Journal content and field selection](#journal-content-and-field-selection).
- **Sensitive-looking field names are excluded from the resolved set entirely.**
  A name matching the sensitive-field pattern is never *requested*, rather than
  being requested and scrubbed on arrival. Under the old wildcard behavior the
  value crossed the wire and was then removed; naming it in `sysparm_fields`
  would have pulled it over deliberately, which is worse.

### Journal content and field selection

Journal content on `incident` — `comments` (customer-visible) and `work_notes`
(internal) — is readable through `fields=all`, `response_format: "detailed"`, an
explicit `fields=comments`, and `sn_schema`. **The default projection still
excludes it**, so an ordinary `sn_query` or `sn_get` does not return it.

Stated as a fact rather than a warning: journal content on real instances
routinely contains customer PII, so asking for all fields on `incident` returns
customer-visible commentary along with everything else. Operators granting
`incident` reads to an agent should know that. If that is not wanted, grant a
narrower read via the field policy rather than relying on the default
projection, since the caller chooses `fields`.

### Attachment payloads

`sn_attach` never reads from or writes to host filesystem paths. Uploads use a
safe leaf `file_name` plus `content_base64`; downloads return
`content_base64`, `file_name`, `content_type`, and `size_bytes`. Download also
requires the owning `table` and record `sys_id`, which are policy-authorized
and verified against attachment metadata before any bytes are returned.

**Size limit: 10 MiB decoded, and that is the only one.** The stdio transport
frames messages by newline with no size bound, so the tool's own limits are
what apply — 10 MiB of decoded bytes for an upload, and a separate 10 MiB raw
budget for a download. The tool's `content_base64` schema description carries
the authoritative figure.

The ~760 KiB practical ceiling documented before 2.1 came from the HTTP body
limit, which no longer applies: the client and server share a pipe, not an
envelope. Base64 still inflates a file by about a third in the message itself,
so a 10 MiB attachment is roughly a 13.3 MiB JSON frame — large, but the
transport will carry it.

Treat `sn_attach` as suitable for logs, configs, screenshots, and documents
rather than bulk transfer; a very large frame still costs memory in both the
client and the server, and ServiceNow's own UI or a dedicated integration is a
better path for bulk file movement.

### Table access policy

2.0 denies every ServiceNow table by default. Table access is selected per
profile, not from a process-wide implicit default. File-backed profiles define
`tableAccess` in `~/.servicenow-mcp/config.json`; the explicit `SN_PROFILE_NAME`
environment profile maps the `SN_ALLOWED_*` variables into that one profile only
when no profile file exists. If a profile has no table rules, it denies all.

Write the rules with the CLI rather than by hand — it validates the result with
the same loader the server uses at request time:

```bash
servicenow-mcp-setup grant --profile dev --read incident,problem --write incident
servicenow-mcp-setup grant --profile dev --read cmdb_ci --tools sn_query,sn_relationships
servicenow-mcp-setup grant --profile dev --read change_request --related change_request=task
servicenow-mcp-setup grant --profile dev --flows   # sn_flow_view's 15 tables, bound to sn_flow_view only
```

A read grant without `--tools` binds `sn_query`, `sn_get`, `sn_aggregate`,
`sn_schema` and `sn_codesearch` to each table it names. `sn_codesearch` is
authorized per code table it searches (`sys_script`, `sys_script_include`,
`sys_ui_script`, `sys_script_client`, `sys_ws_operation`, `sys_module`), so
`servicenow-mcp-setup grant --profile dev --read sys_script_include` lets that
profile search script includes. A search with no `table` searches the code tables
the profile may read and names the others in a warning; it fails only when the
profile may read none of them. On any other table the binding is inert. **A profile written before
`sn_codesearch` was a default keeps the tool list it was saved with** and is not
rewritten: re-run the same `grant --read <code table>` to add it, or pass
`--tools sn_codesearch` to add only that tool. Neither removes a tool. The
profile's field policy still decides the script field: `sn_codesearch` is
denied on a code table whose script field is not readable, exactly as `sn_query`
is for that field (in a search with no `table` that table is left out and named
in the warning instead).

A call the table policy refuses says which table and which tool were refused, and
whether the table is missing from the profile or only the tool is, and it gives
the command that lifts it: `Table access was denied by policy: "sys_script_include"
is granted to this profile, but not for sn_codesearch. To allow it, run:
servicenow-mcp-setup grant --profile <profile> --read sys_script_include --tools
sn_codesearch`. `--tools` adds to the tools a table already has, so that command
removes nothing. The message names only the table and the tool of that call,
never the rest of the profile's rules.

Allowlist entries may be exact table names or the literal `*` to allow every
table for that operation. Table names are trimmed, lowercased, deduplicated,
and must be valid ServiceNow identifiers.

> **`tableAccess` is the sole table-level authority.** There is no longer a
> built-in list of tables the server refuses unconditionally. A profile that
> grants a table gets it, subject only to ServiceNow's own per-user ACLs — so a
> grant of `sys_script`, `sys_user_role`, or a credential table is honored.
> Writing `sys_script` is server-side script execution under the integration
> account. Least privilege now lives entirely in the grant and in the roles you
> give that account; grant the narrowest set that does the job, and prefer an
> account whose ServiceNow roles cannot reach what the grant does not need.

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `SN_ALLOWED_READ_TABLES` | ❌ | deny all | Tables permitted for read operations on the explicit `SN_PROFILE_NAME` environment profile only. Use `*` to allow every readable table except `sys_audit`, `sys_journal_field`, `sys_history_line`, `sys_audit_delete`, `sys_attachment_doc` and `sys_email`, which are covered only when named (see [Field policy](#field-policy)). |
| `SN_ALLOWED_WRITE_TABLES` | ❌ | deny all | Tables permitted for create, update, incident journal append, delete, upload, and confirmed batch operations on the explicit `SN_PROFILE_NAME` environment profile only. Use `*` to allow every writable table except the same six named-only tables. Write permission never implies read permission. |
| `SN_TABLE_ACCESS_TARGETS` | Required for exact allowlisted caller-addressable tables; optional with `*` | `[]` | Trusted JSON classification with `table`, exact permitted `tools`, `kind` (`canonical`, `alias`, `view`, or `extension`), literal `closureComplete: true`, and `relatedTables`: the target itself plus any backing or parent tables the operator declares. The loader checks that every related table has the target's operation permission; it does not derive the list from the instance, and the list grants no access. A self-only list is valid for a `canonical` target; `alias`, `view` and `extension` targets must name at least one backing table, and a view or alias should declare every table it reads, because it returns data from each of them whatever the list says. With `*`, omitted target entries use the wildcard operation grant; explicit target entries can still narrow tools and check their related tables. |
| `SN_FIELD_POLICY_DEFINITIONS` | ❌ | no narrowing | Field policy for the explicit `SN_PROFILE_NAME` environment profile only, like the `SN_ALLOWED_*` variables. **If `~/.servicenow-mcp/config.json` exists, setting this variable stops startup**; give those profiles their own `fieldPolicy` instead. The value is trusted JSON, at most 65,536 characters: either a table map keyed by table name or `*`, the same shape as a profile's `fieldPolicy`, or an object holding the profile keys (`fieldPolicy`, or `readableTableFields` / `writableTableFields`), not both. Each field set is a list of exact field names or `"*"`; `["*"]` means `"*"` in that exact form only, and patterns such as `"u_*"` are rejected. A malformed value stops startup with the key named. Sensitive field names are always denied. See [Field policy](#field-policy). |
| `SN_ENCODED_QUERY_READ_POLICY` | ❌ | deny all | Trusted JSON object containing bounded `rules` for an exact `sn_query`/table pair. Each rule requires `maxLength`, `maxTerms`, readable `fields`, supported `operators`, `maxLimit`, `maxOffset`, and `maxResponseBytes`. No rule can authorize a write or another tool. |

Invalid policy configuration fails startup. A composed tool is admitted only
when every table in its access plan is allowed before the first ServiceNow
client access. A target's declared related tables must each have the same
read or write permission as the target, or the policy is rejected. Related
permission does not make a table directly caller-addressable without its own
target entry. The related tables are a declaration, not a list derived from
the instance: a grant on a base table reaches the records of the tables that
extend it whether or not they are listed, so grant a base table only when
those records should be reachable. Likewise, a view or alias returns data from
every table it reads, whatever `relatedTables` lists: declare each of those
tables, so the loader requires each to carry the same permission, and grant
the view only when all of that data should be reachable. Field policy narrows what a granted table exposes; it does not deny a table the
operator granted. Sensitive-looking field names remain excluded regardless. Build the
target catalog from approved ServiceNow metadata and treat it as trusted
startup configuration. File-backed profile example:

```json
{
  "version": 2,
  "profiles": {
    "dev": {
      "instance": "https://dev.service-now.com",
      "authType": "oauth",
      "clientId": "your-oauth-client-id",
      "clientSecret": "env:SN_CLIENT_SECRET",
      "tableAccess": {
        "readTables": ["incident", "sys_dictionary"],
        "writeTables": ["incident"],
        "targets": [
          {
            "table": "incident",
            "kind": "canonical",
            "tools": ["sn_query", "sn_get", "sn_create", "sn_update", "sn_incident_add_comment", "sn_incident_add_work_note"],
            "closureComplete": true,
            "relatedTables": ["incident"]
          }
        ]
      }
    }
  }
}
```
`sn_nl` remains denied without a complete typed side-effect plan. Legacy ATF
`run`/`run-suite` return migration guidance; use `sn_atf_run` with an explicit
`atf.execute` profile grant. Typed ATF steps use the authenticated native form
to save and verify inputs and output references without ACL changes or an
installed application. `sn_atf_author` checks each step that names a table
against the profile's grants: a `record_query`, `record_validation`,
`field_values_validation` or `open_existing_record` step needs a read grant on its
table, and an `open_new_form` or `set_field_values` step a write grant (a
named-only table must be named, for either). The conditions of the three steps
that have them may use only the operators that compare a field with a literal
(`=`, `!=`, `<`, `<=`, `>`, `>=`, `LIKE`, `NOT LIKE`, `STARTSWITH`, `ENDSWITH`,
`IN`, `NOT IN`, `ISEMPTY`, `ISNOTEMPTY`, `BETWEEN`), name plain fields the field
policy lets the profile read (no dot-walks), and may refer to an earlier step's
output only by its record id or sys_id (`record_id`, `first_record`, `sys_id`
or `user`), as may the values a `set_field_values` step sets; a refused term
refuses the whole call. The fields a `set_field_values` step sets must be
writable on its table under the profile's field policy, as for `sn_update`. `record_query` and `record_validation` also refuse
`enforce_security: false`; leave it out and it stays `true`. The impersonated
user's ACLs still apply on top of all this. Suites authored in the instance are
not checked by the server's table grants, and `atf.execute` stays opt-in. See
[ATF workflow](docs/ATF-WORKFLOW.md).

#### Field policy

Field policy is the second gate after `tableAccess`. It narrows which fields
of a granted table a profile may read, filter on, return and write; it never
denies a table the profile grants. A profile with no field policy may read and
write every field of a granted table, except that sensitive-looking names
(`password`, `token`, `secret`, `api_key` and similar) are always denied, and
the class and domain fields below must be listed before they can be written.
Fields of type `password`, `password2`, `masked` or `encrypted_text` are denied
the same way, whatever their name, and a `sys_properties` value shows only for
a known non-secret `type`. The types come from a cached `sys_dictionary` read,
so the integration user needs read access to `sys_dictionary` and
`sys_db_object`; without it the tools refuse, unless the profile sets
`"fieldTypes": { "dictionary": "not_required" }` to hide by name only (see
[Production security](docs/PRODUCTION-SECURITY.md#password-type-fields)).

State it on a profile in `~/.servicenow-mcp/config.json`, beside
`tableAccess`, in one of two forms. A profile that states both fails to load.
For the `SN_PROFILE_NAME` environment profile, `SN_FIELD_POLICY_DEFINITIONS`
supplies the same keys.

**`fieldPolicy`** maps a table name, or `"*"`, to an entry with up to three
keys:

| Key | What it limits | When the entry leaves it out |
|---|---|---|
| `readable` | Fields a call may read, return, or filter on | The `"*"` entry's `readable` where that entry applies (below); otherwise every field |
| `writable` | Fields a write may set | The `"*"` entry's `writable` where that entry applies; otherwise every field |
| `defaults` | Fields a read returns when the caller names none | A bounded projection inside `readable`: a built-in table's own projection; on other tables the `"*"` entry's `defaults`, or `sys_id` |

**`readableTableFields` / `writableTableFields`** are lists of
`{ "table": ..., "fields": ... }` entries that set `readable` and `writable`.
They have no `defaults`. A table may appear once in each list.

Every field set is a list of exact field names, or `"*"` for every field.
`["*"]` means the same as `"*"`, in that exact form only: `["*", "number"]`,
`[" * "]` and patterns such as `"u_*"` are rejected. Table and field names are
letters, digits and underscores, start with a letter, are at most 80
characters, and are compared case-insensitively. `defaults` must stay inside
`readable`. On a table with no built-in entry, an entry that lists
`readable` but no `defaults` returns that whole list by default, and an entry
that states only `defaults` also limits `readable` to those fields unless a
`"*"` entry states `readable`.

A worked example, added to a profile beside `tableAccess`:

```json
{
  "fieldPolicy": {
    "*": {
      "writable": ["short_description", "description", "state", "work_notes"]
    },
    "incident": {
      "writable": ["short_description", "description", "state", "assigned_to", "assignment_group", "work_notes"]
    },
    "u_integration_log": {
      "readable": [],
      "writable": "*"
    },
    "sys_user": {
      "readable": ["sys_id", "user_name", "name", "email"],
      "writable": []
    }
  }
}
```

On that profile, for the tables its `tableAccess` grants:

- Every ITSM table except `incident`, and every table without a built-in
  entry except `u_integration_log`, can be written only in the four fields of
  the `"*"` entry. `comments` is not listed, so no customer-visible comment
  can be posted there. The `"*"` entry states no `readable`, so reads stay
  open.
- `incident` states its own `writable`, which replaces the `"*"` list for
  `incident` only. `sn_incident_add_comment` is denied there, because
  `comments` is not listed, and `sn_incident_add_work_note` is allowed.
- `u_integration_log` is write-only. Any field except sensitive names and the
  class and domain fields can be written, and a write returns only `sys_id`.
  Reads are denied, so `sn_batch`, which reads the matching `sys_id`s first,
  cannot run there.
- `sys_user` is a system table, so the `"*"` entry does not reach it, and
  naming it is the only way to narrow it. Here it can read four fields and
  cannot be written. Other system tables, such as `sys_script`, are not
  narrowed by this policy at all.

The same policy in the list form:

```json
{
  "readableTableFields": [
    { "table": "u_integration_log", "fields": [] },
    { "table": "sys_user", "fields": ["sys_id", "user_name", "name", "email"] }
  ],
  "writableTableFields": [
    { "table": "*", "fields": ["short_description", "description", "state", "work_notes"] },
    { "table": "incident", "fields": ["short_description", "description", "state", "assigned_to", "assignment_group", "work_notes"] },
    { "table": "u_integration_log", "fields": "*" },
    { "table": "sys_user", "fields": [] }
  ]
}
```

**Which tables a `"*"` entry reaches.** Tables fall into four groups:

- **ITSM tables:** `incident`, `change_request`, `problem`, `sc_request`,
  `sc_req_item`, `sc_task`, `task`, `cmdb_ci`, `cmdb_ci_server`,
  `cmdb_ci_computer`, `kb_knowledge`.
- **Every table without a built-in entry:** `u_*` and `x_*` tables, and
  platform tables such as `change_task` and `sys_properties`.
- **The 24 system tables:** `sys_script`, `sys_script_include`,
  `sys_script_client`, `sys_ui_script`, `sys_ws_operation`, `sys_module`, `sys_user`,
  `sys_user_group`, `sys_user_grmember`, `sys_db_object`, `sys_app`,
  `sys_store_app`, `v_plugin`, `sys_atf_test`, `sys_atf_test_suite`,
  `sys_atf_test_suite_test`, `sys_atf_test_result`, `sys_atf_step`,
  `sys_element_mapping`, `sys_variable_value`, `sys_atf_test_suite_result`,
  `sys_atf_test_result_step`, `sys_atf_agent`, `syslog`.
- **The 6 named-only tables:** `sys_audit`, `sys_journal_field`,
  `sys_history_line`, `sys_audit_delete`, `sys_attachment_doc`, `sys_email`. A
  `"*"` entry reaches them once the profile names them in `tableAccess` (below).

On an ITSM table or a table without a built-in entry, named in the policy or
not, `readable` and `writable` each resolve from the table's own entry, then
the `"*"` entry, then every field. To keep one key open on such a table under
a narrowing `"*"` entry, state it on the table, such as
`"u_x": { "writable": "*" }`. The ITSM tables keep their built-in default
projections, trimmed to the effective `readable` set.

A `"*"` entry never reaches a system table, named or not: each key comes from
the table's own entry, or else covers every field. The system tables include
the script tables (`sys_script`, `sys_script_include`, `sys_script_client`,
`sys_ui_script`, `sys_ws_operation`, `sys_module`), whose records hold server- or
client-side code, and the user and group tables (`sys_user`,
`sys_user_group`, `sys_user_grmember`). Name a system table to narrow it, and
grant it in `tableAccess` only deliberately.

**Six tables are granted by name.** A `"*"` entry in `readTables` or
`writeTables` covers every other table, but not `sys_audit`, `sys_journal_field`,
`sys_history_line`, `sys_audit_delete`, `sys_attachment_doc` or `sys_email`.
Their rows hold the old and new values of other tables' fields, comments and
work notes, the history built from them, deleted records, attachment content
and email bodies. A profile reaches one only when `tableAccess` names it, for
example
`servicenow-mcp-setup grant --profile <profile> --read sys_audit --tools sn_query`.
Without that, every tool refuses it, `sn_query`, `sn_get`, `sn_aggregate`,
`sn_schema` and `sn_batch` included, and the message names the table and the
grant that allows it. A `relatedTables` list that reaches one of them under a
`"*"` grant stops the profile loading, and the message names the table and says
to grant it by name.

Once named, these tables follow the profile's field policy like an ITSM table:
a `"*"` field entry narrows them, and an entry for the table narrows or widens
them. A read that names no `fields` leaves out the value columns, which are asked
for by name: `oldvalue` and `newvalue` for `sys_audit`; `value` for
`sys_journal_field`; `old`, `new`, `old_value` and `new_value` for
`sys_history_line`; `payload` for `sys_audit_delete`; `data` for
`sys_attachment_doc`; and `body`, `body_text`, `subject`, `recipients`,
`copied`, `blind_copied`, `reply_to`, `headers` and `error_string` for
`sys_email`. `sn_attach` is unchanged: it uses the Attachment API, under the
grants for `sys_attachment` and the record's table, and never reads
`sys_attachment_doc`.

**A `"*"` write grant does not cover three ATF tables.** `sys_atf_step`,
`sys_variable_value` and `sys_element_mapping` hold the step types, input values
and pill mappings that `sn_atf_author` checks when it adds a step. Under a `"*"`
write grant they are written by `sn_atf_author` only; `sn_create`, `sn_update`, `sn_delete`, `sn_batch` and
attachment uploads reach them only when `tableAccess` names the table for write,
and the refusal names the table and the grant that allows it. Reads are
unchanged. `sys_variable_value` and `sys_element_mapping` also hold other
variables' values and mappings (catalog variables, for example), so a profile
that writes those with the generic tools needs to name them.

**Database views and extension tables are not covered by the name list.** The
six tables are matched by table name. A database view built over one of them (a
`sys_db_view` that joins any of the six) has a different name, so a `"*"` grant
reaches the view and, through it, the columns of the joined table. The same holds
for a custom table that extends one of the six. Do not grant such a view or table
unless you mean to expose those rows, and on a profile with a `"*"` grant ask
your instance administrator to review database views first; a profile with an
explicit table list never reaches a view it does not name. To have the loader
check it, declare the view as a `view` target with every table it reads in
`relatedTables`: the profile then fails to load unless it also names each of
those tables (for a named-only table, by name).

**Code tables list without their scripts.** A read of `sys_script`,
`sys_script_include`, `sys_ui_script`, `sys_script_client` or `sys_ws_operation`
that names no `fields` returns identifiers and metadata, not the script body, so
a page of them is not cut short by a few large bodies. For `sys_script_include`
that is `sys_id`, `name`, `api_name`, `active` and `sys_updated_on`; the others
keep `sys_id`, `name`, `active`, `sys_updated_on` and what identifies them
(`collection` and `when` for a business rule, `table` and `type` for a client
script, `http_method` and `relative_path` for a scripted REST operation, `global`
for a UI script). The body is one named field away, and `fields=all` and
`response_format: "detailed"` still include it:
`sn_query {table: "sys_script_include", fields: "sys_id,name,script"}`. A profile
that states its own `defaults` for one of these tables keeps them.

**Read-only profiles.** A `"*"` entry with `writable: []` does not make a
profile read-only, because it never reaches the system tables. To make a
profile read-only, grant no writes: `tableAccess.writeTables: []`, or
`SN_ALLOWED_WRITE_TABLES=''` for the environment profile.

**Class and domain fields.** `sys_class_name`, `sys_class_path`, `sys_domain`
and `sys_domain_path` move a record to another class or domain, so no
writable wildcard covers them, including the open default of a profile with
no field policy. Each is written only where it is named in the table's
`writable`, or in a `"*"` entry's `writable` on a table that entry reaches.
Listing `sys_domain` does not list `sys_domain_path`, and the reverse.
Otherwise the write is denied with:

```text
Write denied by policy: field "sys_domain" on "incident" changes the record's class or domain, so a writable wildcard never covers it. List it explicitly in fieldPolicy.incident.writable to allow this write.
```

**Record payload columns.** Some columns carry other records' content or
packaged content, so no wildcard covers them: not the open default of a
profile with no field policy, a `"*"` entry, or `"*"` on the table's own
entry. They are `payload` and `payload_diff` on `sys_update_xml`,
`sys_update_version`, `sys_update_preview_xml`, `sys_update_diff`,
`sys_sync_preview_remote`, `sys_upgrade_history_log`, `sys_metadata_link`,
`sys_metadata_delete`, `sys_audit_delete`, `sys_archive_log` and
`clone_preserved_data`; `payload` on `ecc_queue`, `data_replication_queue`,
`sys_rt_change_log`, `sys_hub_snapshot` and `sys_hub_flow_version`; `payload`
and `payload_short` on `sys_replication_queue`; `payload` and
`previous_payload` on every `cdc_queue_*` table except `cdc_queue_state_*`;
`data` on `sys_hub_snapshot_chunk`; and
`encoded_keystore` on `sn_disco_certmgmt_certificate_ca_credentials`. The
numbered rotation shards of the queue tables (`ecc_queue0003`,
`sys_replication_queue5`, ...) are covered too, each as its own table. Each
column is read only where it is named in that table's own `readable`, and
written only where it is named in its own `writable`. Until then it is
refused by name and as a filter, order, group-by, aggregate or write field,
and is left out of `fields=all`, detailed and default reads and write
echoes. A named read is denied with:

```text
Read denied by policy: field "payload" on "sys_update_xml" holds record payloads, so a readable wildcard never covers it. List it explicitly in fieldPolicy.sys_update_xml.readable to allow this read.
```

**`readable: []` and `writable: []`.** `readable: []` makes a table
write-only: writes succeed and return only `sys_id`, reads are denied, and
`sn_batch` cannot run there. `writable: []` blocks writes. To make a table
unreachable, leave it out of `tableAccess`. Every write response includes the
written record's `sys_id`; every other field, `number` included, follows the
readable set.

**Parent tables.** Field policy is evaluated against the table a call names.
If a profile may write a parent table such as `task`, a write addressed to
`task` is checked against `task`'s policy, whatever the class of the record.
When you narrow a field such as `comments` on `incident`, narrow it on every
write-granted parent table too, or do not grant writes on the parent. A
`"*"` entry covers `incident` and `task` alike. The same holds for a platform
table that stores journal entries directly, such as `sys_journal_field`: if a
profile may write it, per-table narrowing on `incident` does not reach a
write addressed to it, so either leave it out of the write grant or narrow
with a `"*"` entry, which reaches it.

**Schema metadata.** `sn_schema` describes the fields the profile can read on
the table it names. It needs `tableAccess` read on `sys_dictionary`,
`sys_db_object`, `sys_documentation` and `sys_choice`, but a field policy on
those metadata tables does not trim the labels, types, choices and help it
returns for the readable fields. The exception is `inherited_from`, the
ancestor table a field comes from: it appears only where the profile can read
`super_class` on `sys_db_object`.

**Role and group-membership tables.** Nothing built in blocks
`sys_user_role`, `sys_user_has_role`, `sys_group_has_role` or
`sys_user_grmember`. This is deliberate: profile configuration alone decides,
with `tableAccess` granting the table, field policy narrowing it, and the
integration account's ServiceNow roles bounding what is left. Grant these
tables only deliberately. `sys_user_grmember` is a system table; the other
three have no built-in entry, so a `"*"` entry reaches them.

**Validation.** Field policy is checked when profiles load, and any error
stops the server from starting. Table keys must be unique ignoring case, a
table may appear once in each list, and a field may appear once in each set.
Unknown keys are rejected, including comment keys such as `_comment`: a
`fieldPolicy` entry accepts only `defaults`, `readable` and `writable`, and a
list entry only `table` and `fields`. Every error and its message is listed in
[Field-policy load errors](docs/V2-MIGRATION.md#field-policy-load-errors).

#### Journal fields

`comments` (customer-visible) and `work_notes` (internal) are written like any
other field through `sn_create`, `sn_update` and `sn_batch`, on any table
granted for writes: `incident`, `change_request`, `problem`, `sc_task`, custom
task tables. A Table API write to a journal field appends one entry; it never
edits or removes earlier entries. Each entry is 1-8,000 characters of
non-blank text, at most 16,384 UTF-8 bytes, without control or format
characters other than newline, carriage return and tab.

Field policy decides who may write them, and with no field policy every
write-granted table accepts both. To keep a profile from posting
customer-visible comments, set `writable` to an explicit list that leaves
`comments` out: on each table, or on the `"*"` entry, and on write-granted
parent tables such as `task` (see [Field policy](#field-policy)). On
`incident` the same setting also denies `sn_incident_add_comment`, so both
routes to the field agree. Leaving the dedicated tools off a target does not
withhold journals from `sn_create`, `sn_update` or `sn_batch`.

The dedicated incident tools take exactly `profile`, incident `sys_id` and
bounded `content`, and need write access to `incident`.
`servicenow-mcp-setup grant --write incident` binds both to the incident
target unless you pass `--tools`.

Journal handling is keyed by field name. Only `comments` and `work_notes` get
the journal bounds and are never re-sent; a custom journal field gets the
generic bounds. See
[Production security boundaries](docs/PRODUCTION-SECURITY.md#journal-content).

#### Write values

A field approved by the field policy accepts:

- a string, a boolean, a safe integer, or a finite decimal such as `12.5`
  (not exponent forms such as `1e21`);
- `""` or `null` to clear the field;
- an array of scalars for a list field such as `watch_list`, sent as one
  comma-separated value, so no element may contain a comma;
- a `{"value": ..., "display_value": ..., "link": ...}` object, the shape
  reads return with display values, which is written as its `value`.

Values cannot contain control or format characters (newline, carriage return
and tab are allowed) and are bounded to 100,000 characters and 400,000 UTF-8
bytes. On `incident`,
`short_description`, `description`, `close_notes`, the reference fields
`caller_id`, `assignment_group` and `assigned_to`, and the choice fields keep
typed checks: a reference takes a 32-character `sys_id` or `""`, a choice
cannot contain `^`, `=` or `,`, and `short_description` is required on create
and cannot be cleared. Every other incident field gets the generic bounds.

#### Bulk writes

`sn_batch` sends confirmed updates and deletes through the ServiceNow REST
Batch API (`/api/now/v1/batch`), up to 50 records per request and fewer when
field values are large, so a request body stays under 4 MiB unless one
record's fields alone exceed about 3 MiB of JSON; such a record is sent one
per request. Each request gets its own 1 MiB response budget, so a run can reach the 10,000-record cap
(`limit` defaults to 200). The lookup's `sys_id`s are de-duplicated, so each
matched record is targeted once per run.

A batch request that may have reached the instance is never sent again:

- If the instance refuses a batch request outright (401, 403 or 404), nothing
  in it ran, so the run switches to one Table API call per record, for that
  batch and the rest. Batches already confirmed are not sent again.
- A rate limit (429) stops the run. The remaining records are reported as not
  sent, with the `Retry-After` hint, because serial calls would only add load.
- A record whose sub-request returns a server error (5xx or 408) is
  unconfirmed: it may have been changed, so it is reported and never retried,
  and the run continues.
- The run stops, and reports the remaining records as not sent, when a batch
  request fails or its response cannot be read or matched to the records
  sent, when every serviced record in one batch returns a server error, or
  when more than 10 records in the run are unconfirmed.

The result's `message` says how many records were unconfirmed or not sent,
and why a run stopped. Unconfirmed records count as neither processed nor
failed; records not sent count as failed.

The serial fallback follows the HTTP client's retry rules. A journal write
(`comments` or `work_notes`) is never re-sent on any path. An ordinary
`PATCH` is retried up to twice after a 502, 503, 504 or connection error, the
same rule `sn_update` follows. The fallback stops at the first record whose
outcome it cannot confirm, at a 429, and at a 401.

**Re-running a batch appends again.** A journal-only update does not change
which records the filter matches, so running the same `sn_batch` again
appends another entry to every matched record, not only to the records
reported as unconfirmed or not sent. Check the unconfirmed records and
narrow the filter to the records still to do before you re-run it.

**Practical size per call.** Each batch request must finish within the
profile's request timeout (`timeoutMs`, or `SN_TIMEOUT_MS`; 30 seconds by
default), and its duration grows with the server-side time each record's
business rules take. As a rough guide, at 50-100 ms per record a 50-record
batch takes a few seconds; at about 600 ms per record a single batch can
reach the timeout, and its records are then reported as unconfirmed and the
run stops. Over stdio the server sets no overall deadline on a call; the
dormant HTTP transport ends a call after 120 seconds by default, which at
those rates is roughly 1,200-2,400 records. For tables with heavy business
rules, use a lower `limit` and split the work across calls with narrower
filters. While the fields being set come to less than about 62 KB of JSON,
each batch holds 50 records, so journal fields alone never make a batch
smaller.

### ServiceNow profiles

> **Note:** A profile file is authoritative when present. Without one,
> `SN_PROFILE_NAME` must explicitly map the canonical connection variables to
> a named profile; there is no synthetic or default profile.

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `SN_PROFILE_NAME` | ✅* | — | Explicit name for the process-local environment profile; required before bare connection variables define any profile. |
| `SN_INSTANCE` | ✅* | — | Instance URL (e.g. `https://yourinstance.service-now.com`) |
| `SN_USER` | ✅* | — | ServiceNow username (basic auth / OAuth password grant) |
| `SN_PASSWORD` | ✅* | — | ServiceNow password (basic auth / OAuth password grant) |
| `SN_AUTH_TYPE` | ❌ | `basic` (legacy; set `oauth` explicitly) | Auth scheme: `basic`, `oauth`, or `apikey` |
| `SN_CLIENT_ID` | ❌ | — | OAuth client id (`SN_AUTH_TYPE=oauth`) |
| `SN_CLIENT_SECRET` | ❌ | — | OAuth client secret (`SN_AUTH_TYPE=oauth`) |
| `SN_GRANT_TYPE` | ❌ | `client_credentials` | OAuth grant: `client_credentials` or `password` |
| `SN_API_KEY` | ❌ | — | API key (`SN_AUTH_TYPE=apikey`) |
| `SN_API_KEY_HEADER` | ❌ | `x-sn-apikey` | Header the API key is sent in |
| `SN_TIMEOUT_MS` | ❌ | `30000` | Per-request timeout in milliseconds |
| `SN_DISPLAY_VALUE` | ❌ | `true` | Default display value mode (`true`, `false`, `all`) |
| `SN_REL_DEPTH` | ❌ | `3` | Default CMDB relationship traversal depth |

*`SN_PROFILE_NAME` and `SN_INSTANCE` are not required when using
`~/.servicenow-mcp/config.json`. Authentication-specific variables depend on
the selected auth type.

---

## Usage Examples

Once connected, your AI assistant can:

**Query incidents:**
> "On dev, show me all P1 incidents assigned to the Network team" (`profile: "dev"`)

**Create a record:**
> "On staging, create an incident for the approved VPN test" (`profile: "staging"`)

**Aggregate data:**
> "On prod, how many incidents are grouped by priority?" (`profile: "prod"`)

**Check health:**
> "Run the dev instance health check" (`profile: "dev"`)

**CMDB traversal:**
> "On prod, show upstream dependencies for email-server-01" (`profile: "prod"`)

**Schema introspection:**
> "On dev, what fields are on change_request?" (`profile: "dev"`)

**Code search:**
> "On dev, find business rules that reference GlideRecord('incident')" (`profile: "dev"`)

**ATF testing:**
> "On staging, list the approved ATF suite" (`profile: "staging"`)

**Explicit profile selection:**
> "Query incidents on dev" (the client sends `profile: "dev"` on that call)

The client must translate every example into a tool invocation containing that
exact `profile`; no prior call creates default, active, or switch-profile state.

---

## Safety Features

This server is designed for production use with multiple safety layers:

- **Delete operations** require explicit `confirm: true`
- **Batch operations** run in dry-run mode by default — shows the match count, a sample of up to 5 records and the fields it would write, without making changes (`confirm` re-runs the query and can match different records)
- **Bulk operations** require `confirm: true` to leave dry-run mode
- **Unclassified composition is denied** — `sn_nl` requires a complete typed access plan; ATF suite execution requires a separate explicit `atf.execute` grant
- **Table access is deny-by-default** with independent exact read/write allowlists; sensitive field names are denied and no configuration can grant them
- **User input is neutralized** before interpolation into encoded queries (`^` is stripped from filter values — ServiceNow's query syntax has no escape sequence)

---

## Development

Have the approved local supervisor or keychain inject the selected ServiceNow
authentication secret before starting the process. The commands below contain
non-secret configuration only; never prepend or append protected values on the
command line.

```bash
# Clone
git clone https://github.com/onlyflowstech/servicenow-mcp.git
cd servicenow-mcp

# Install & build
npm install
npm run build

# Run the server directly, speaking stdio on this terminal's pipes
MCP_OWNER_ID=local-owner \
MCP_CLIENT_ID=local-client \
SN_ALLOWED_READ_TABLES=incident,problem,change_request \
SN_ALLOWED_WRITE_TABLES=incident,change_request \
SN_TABLE_ACCESS_TARGETS='[{"table":"incident","kind":"canonical","tools":["sn_query","sn_get","sn_create","sn_update","sn_incident_add_comment","sn_incident_add_work_note","sn_delete","sn_batch"],"closureComplete":true,"relatedTables":["incident"]},{"table":"problem","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["problem"]},{"table":"change_request","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["change_request"]}]' \
SN_PROFILE_NAME=dev \
SN_INSTANCE=https://yourinstance.service-now.com \
SN_USER=your_user \
npm start

# Build and run with source maps for local development
MCP_OWNER_ID=local-owner \
MCP_CLIENT_ID=local-client \
SN_ALLOWED_READ_TABLES=incident,problem,change_request \
SN_ALLOWED_WRITE_TABLES=incident,change_request \
SN_TABLE_ACCESS_TARGETS='[{"table":"incident","kind":"canonical","tools":["sn_query","sn_get","sn_create","sn_update","sn_incident_add_comment","sn_incident_add_work_note","sn_delete","sn_batch"],"closureComplete":true,"relatedTables":["incident"]},{"table":"problem","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["problem"]},{"table":"change_request","kind":"canonical","tools":["sn_query","sn_get"],"closureComplete":true,"relatedTables":["change_request"]}]' \
SN_PROFILE_NAME=dev \
SN_INSTANCE=https://yourinstance.service-now.com \
SN_USER=your_user \
npm run dev
```

### Testing with MCP Inspector

Use the isolated, exactly locked Inspector toolchain on Node.js 22.19 or newer;
the server itself remains supported on Node.js 20. Set the non-secret
`MCP_PROFILE`, install from `tools/inspector/package-lock.json`, and run the
local-only launcher:

```bash
MCP_PROFILE=dev npm run inspector
```

(Run `npm ci --prefix tools/inspector --engine-strict --ignore-scripts` first.)

The launcher prints the exact **STDIO** command and arguments to enter in the
Inspector UI. There is no endpoint and no bearer to type. Include the explicit
profile in every call. The Inspector spawns the server itself and inherits a
scrubbed environment with every `MCP_*` and `SN_*` value removed; the server
still resolves its credential, because it reads the owner-only
`~/.servicenow-mcp/server.env` at startup rather than relying on what it was
handed. The launcher does not expose Inspector beyond loopback or create a
tunnel.

`npm run smoke` is the second client. It spawns `dist/index.js` the same way and
needs only `MCP_PROFILE`:

```bash
MCP_PROFILE=dev npm run smoke
```

See [`docs/RELEASE-VALIDATION.md`](docs/RELEASE-VALIDATION.md) for the release
gates, write confirmation, evidence, and rollback procedure.

---

## Roadmap

- [x] **stdio transport** — the client spawns the server; a Streamable HTTP runtime exists but is [dormant](docs/ENTERPRISE-RELEASE-BOUNDARY.md#the-dormant-http-transport)
- [x] **OAuth 2.0** authentication support (client_credentials + password grants, API keys)
- [ ] **sn_script** background-script execution (SNS-39) — future state, deliberately not shipped in 2.0; requires automating the `sys.scripts.do` UI endpoint with session auth
- [ ] **Streaming** for large result sets
- [ ] **Caching** for schema and relationship lookups

---

## License

MIT © [OnlyFlows](https://onlyflows.tech)

---

<p align="center">
  Built with ❤️ by <a href="https://onlyflows.tech">OnlyFlows</a> · <a href="https://github.com/onlyflowstech">@onlyflowstech</a>
</p>

TDQS

A3.6/5.0

Scored across 24 tools

Disambiguation4/5

The core CRUD set (sn_query/sn_get/sn_create/sn_update/sn_delete) is cleanly separated, and each specialty tool (sn_syslog, sn_relationships, sn_codesearch, sn_flow_view) targets a distinct artifact. The main ambiguity is sn_nl, a general natural-language interface that overlaps with sn_query, sn_aggregate, sn_schema, sn_create, sn_update, and sn_batch, and to a lesser degree sn_atf vs sn_atf_results both exposing ATF result reads — descriptions mitigate but do not eliminate this.

Naming Consistency4/5

All 24 tools use a consistent `sn_` prefix with snake_case segments, giving a predictable namespace. Minor structural deviations exist between flat verb tools (sn_query), grouped families (sn_atf_readiness / sn_atf_author / sn_atf_run / sn_atf_results alongside a bare sn_atf), and resource-scoped names (sn_incident_add_comment), but none are confusing.

Tool Count4/5

24 tools sits at the high end of the comfortable range, but ServiceNow is a genuinely broad platform (records, CMDB, ATF, flows, logs, attachments, discovery, profiles), so each tool maps to a real capability area rather than filler. A couple of niches (sn_incident_add_comment / sn_incident_add_work_note) could arguably fold into sn_update, but the surface is defensible.

Completeness4/5

Full record lifecycle is covered (query, get, create, update, delete, bulk batch, aggregates, schema), plus strong coverage of CMDB relationships, ATF authoring/running/results, code search, flow viewing, attachments, syslog, and instance health. Remaining gaps are modest: sn_attach cannot delete attachments, Flow Designer is read-only, and there is no explicit journal/history retrieval tool (only field-level comment appends).

Maintenance

ActivityActive
ResponsivenessLimited data