{"id":"23e6ae98-5aa5-47dc-9476-a2b59268b918","slug":"servicenow-mcp-ai","kind":"mcp","name":"servicenow-mcp-ai","summary":"ServiceNow MCP server — 67 tools over the full REST surface, with plan-and-apply write safety, capability preflight and an ACL security scan.","owner":"IvanBBaev","repoUrl":"https://github.com/IvanBBaev/servicenow-mcp-ai","license":"GPL-3.0","licenseTier":"strong-copyleft","trust":"community","stars":9,"match":null,"fewStars":false,"format":"mcp","createdAt":"2026-06-12T18:15:09.000Z","addedAt":"2026-10-14T05:13:09.614Z","logoUrl":"https://avatars.githubusercontent.com/u/126177?u=9c2146cb60dfc6905b1df0c92a4362dff168f938&v=4","linkOnly":false,"collection":null,"skillPath":null,"categories":["cloud-infra","memory-knowledge"],"tags":["ai","itsm","llm","servicenow","rest"],"runtime":"node","local":true,"cloudCapable":false,"cloudCapability":"unknown","cloudReadyOnPlatform":false,"needsApiKey":false,"reviewed":false,"syncedAt":"2026-10-25T20:13:10.371Z","sample":false,"url":"https://conduits.dev/tools/servicenow-mcp-ai","language":"JavaScript","transports":["stdio"],"install":{"npm":"servicenow-mcp-ai"},"requirements":{"env":[{"name":"SN_INSTANCE","secret":false,"required":true,"description":"ServiceNow instance host, e.g. dev12345.service-now.com."},{"name":"SN_AUTH","secret":false,"required":false,"description":"Auth mode: basic | oauth | apikey | token | none. Auto-detected from the keys present if omitted."},{"name":"SN_USER","secret":false,"required":false,"description":"Username for basic auth or the OAuth password grant."},{"name":"SN_PASSWORD","secret":true,"required":false,"description":"Password for basic auth or the OAuth password grant."},{"name":"SN_API_KEY","secret":true,"required":false,"description":"ServiceNow API key, sent as the x-sn-apikey header (apikey auth)."},{"name":"SN_TOOL_PACKAGES","secret":false,"required":false,"description":"Which tool packages to expose, e.g. core (default), all, or a comma-separated list."}],"upstreamMayCharge":false},"tools":null,"readme":"# servicenow-mcp-ai — ServiceNow MCP Server\n\n| [![npm version](https://img.shields.io/npm/v/servicenow-mcp-ai?style=flat-square&logo=npm&logoColor=white&label=npm)](https://www.npmjs.com/package/servicenow-mcp-ai) | [![npm downloads](https://img.shields.io/npm/dm/servicenow-mcp-ai?style=flat-square&logo=npm&logoColor=white&label=downloads)](https://www.npmjs.com/package/servicenow-mcp-ai) | [![node](https://img.shields.io/node/v/servicenow-mcp-ai?style=flat-square&logo=nodedotjs&logoColor=white&label=node)](https://www.npmjs.com/package/servicenow-mcp-ai) | [![tools](https://img.shields.io/badge/tools-100-blue?style=flat-square)](https://github.com/IvanBBaev/servicenow-mcp-ai#tools) | [![License: GPL-3.0](https://img.shields.io/npm/l/servicenow-mcp-ai?style=flat-square&color=blue&label=license)](LICENSE) |\n| :--: | :--: | :--: | :--: | :--: |\n| [![CI](https://img.shields.io/github/actions/workflow/status/IvanBBaev/servicenow-mcp-ai/ci.yml?branch=main&style=flat-square&logo=githubactions&logoColor=white&label=CI)](https://github.com/IvanBBaev/servicenow-mcp-ai/actions/workflows/ci.yml) | [![coverage](https://img.shields.io/codecov/c/github/IvanBBaev/servicenow-mcp-ai/main?style=flat-square&logo=codecov&logoColor=white&label=coverage)](https://codecov.io/gh/IvanBBaev/servicenow-mcp-ai) | [![last commit](https://img.shields.io/github/last-commit/IvanBBaev/servicenow-mcp-ai?style=flat-square&logo=git&logoColor=white&label=last%20commit)](https://github.com/IvanBBaev/servicenow-mcp-ai/commits/main) | [![MCP](https://img.shields.io/badge/MCP-server-orange?style=flat-square)](https://modelcontextprotocol.io) | [![Known Vulnerabilities](https://snyk.io/test/npm/servicenow-mcp-ai/badge.svg)](https://snyk.io/test/npm/servicenow-mcp-ai) |\n\n📖 **[Documentation site →](https://ivanbbaev.github.io/servicenow-mcp-ai/)**\n\nA [Model Context Protocol](https://modelcontextprotocol.io) server that lets an\nMCP client (VS Code, Claude Desktop, etc.) run commands against a **ServiceNow**\ninstance through its REST APIs — Table, Aggregate, Attachment, Import Set, Batch\nand CMDB, plus the Service Catalog, Change Management and Knowledge plugin APIs.\nCredentials are kept in a local env file and can be updated at runtime through a tool.\n\n> **Upgrading from 2.x?** 3.0 has breaking defaults (plan tokens for destructive applies,\n> protected system tables, a smaller default tool set). Run\n> `npx servicenow-mcp-ai migrate --write` once: it carries your env file and MCP client\n> config over and adds `SN_COMPAT=2`, which keeps every 2.x default you have not set.\n> See the [CHANGELOG](CHANGELOG.md) → \"Migration at a glance\" for each change.\n\n> **Upgrading from 1.x?** v2.0 makes writes **plan-by-default**: `create`/`update`/`delete`\n> and the other record-write tools return a non-mutating preview unless you pass\n> `apply: true` (or set `SN_WRITE_MODE=apply` to restore the v1 \"execute immediately\"\n> behaviour). See the [CHANGELOG](CHANGELOG.md) → 2.0.0 for the full migration note.\n\n**Contents:** [Quick demo](#quick-demo) · [Features](#features) ·\n[Requirements](#requirements) · [Setup](#setup) ·\n[Configure credentials](#configure-credentials) · [Run / debug](#run--debug) ·\n[Develop](#develop) · [Tools](#tools) · [Resources](#resources) ·\n[Prompts](#prompts) · [Project structure](#project-structure) ·\n[Security notes](#security-notes) · [Project documentation](#project-documentation) ·\n[Support](#support)\n\n_Built and maintained in my own time — if it helps, a\n[GitHub Sponsors](https://github.com/sponsors/IvanBBaev) tip keeps it going.\nFull [Support](#support) options are near the end._\n\n## Quick demo\n\nThree things the platform makes hard, one call each. Point your MCP client at an\ninstance ([Setup](#setup)) and ask:\n\n**1. \"Where is this field actually used?\"** — every script, business rule, client\nscript, UI policy/action and ACL that touches it, as JSON or a Mermaid graph. The\nIDE-grade _find usages_ ServiceNow has no button for:\n\n```jsonc\n// servicenow_where_used\n{\n  \"kind\": \"field\", // \"table\" | \"field\" | \"script\"\n  \"name\": \"u_cost_center\",\n  \"mermaid\": true, // also render a reference graph\n}\n```\n\n**2. \"What runs when I save this record?\"** — the full automation chain in\nexecution order (display → before → after → async business rules, then flows,\nworkflows and notifications), each with its condition — a logical test that runs\n**nothing**:\n\n```jsonc\n// servicenow_trace_table_event\n{\n  \"table\": \"incident\",\n  \"operation\": \"update\", // insert | update | delete | query\n}\n```\n\n**3. \"What drifted between dev and prod?\"** — a Markdown diff of tables, columns,\nscripts (matched by sys_id then name, with a unified diff of every changed script)\nand plugins between two configured profiles — plus, on request, properties, choices,\nACLs, notifications, flows, catalog items and roles — with a CI-friendly exit code\nso a pipeline can block a risky deploy:\n\n```bash\nservicenow-mcp-ai drift dev prod   # report on stdout; exit 1 on drift, 0 if clean\n```\n\nAll three are **read-only** and work against any instance — including a free PDI —\nwith the model and client of your choice.\n\n## Features\n\n- Full **Table API**: query, read, create, update and delete records on **any**\n  table, with encoded queries, field selection and pagination.\n- Extra ServiceNow APIs: **Aggregate** (Stats), **Attachment**\n  (list/upload/download/delete), **Import Set**, **Batch** (many REST calls in a\n  single request), plus table/column **metadata** (`sys_db_object`,\n  `sys_dictionary`).\n- Process & plugin APIs: **CMDB** (class-aware CI CRUD + meta, relationship\n  reads from `cmdb_rel_ci`, IRE identify-and-reconcile with an identify-only\n  plan),\n  **Service Catalog** (browse/order items), **Change Management** (typed\n  creation + conflict detection) and **Knowledge** (article search).\n  Plugin-scoped APIs report clearly when not active on the instance.\n- **Script intelligence**: read and search the instance's own code (business\n  rules, script includes, client scripts, UI policies/actions, scheduled jobs,\n  transform/REST scripts, ACLs, Service Portal widgets, UI pages/scripts/macros, processors, email/fix/\n  validation scripts, script actions, data sources, REST message functions,\n  transform maps/entries, catalog client scripts and dictionary calculations /\n  defaults) and get a table's full automation picture — all read-only over the\n  Table API. `servicenow_search_code` returns every matching line per artefact\n  (up to 20, with a line of context either side) and, like\n  `servicenow_where_used`, takes an optional application `scope`.\n  `servicenow_where_used` also finds structural references — dictionary\n  reference fields, list and form layouts, catalog variables, flow inputs and\n  reports — in a separate `structural` section.\n- **Flow tracing & code checking** (Phase 8): deterministically trace what a\n  table operation runs (`flows` package — business rules, flows, workflows and\n  notifications, in order, with a Mermaid flowchart), read Flow Designer flows\n  and run history, explain Process Automation Designer playbooks\n  (`servicenow_explain_flow` with `kind: \"playbook\"` — lanes as Mermaid\n  subgraphs, activities, triggers, variants), and lint scripts against a local rule set with an aggregate\n  code-health report (`codecheck`; `domains: true` adds the flow, Service\n  Portal and legacy-workflow analysers). Run ATF tests via the CI/CD API (`atf`,\n  opt-in, non-default — the run tools execute on the instance).\n- **Journal-based undo** (`revert`): list the local write journal and revert\n  one applied create/update/delete — with a drift check against later edits.\n- **Generic artifact reads** (`artifacts`, opt-in): list and read any\n  registered artifact type — UI policies with their actions, portal pages with\n  their layout, flows, catalog items and more — with scope and SDK-managed\n  status.\n- **Update-set awareness** (`updatesets`, opt-in): list update sets, summarise\n  one set per artefact, compare it with another profile or a snapshot — and\n  bind applied Table writes to a named update set (`update_set` /\n  `SN_UPDATE_SET`), restoring the user's current set afterwards.\n- **Operations and data health** (`ops`, opt-in): bounded \"why is it slow\"\n  reads of the system log, the scheduler queue, the outbound email queue and\n  semaphores, plus `servicenow_check_data_health` — duplicate keys, orphaned and\n  stale references for one table, from Aggregate API counts.\n- **Operations reads** (opt-in): a record's change history from `sys_audit` and\n  `sys_journal_field` (`history` — including the comments and work notes the\n  Table API reads back empty), system properties with masked secrets and a\n  journaled, revertible set (`properties`), and user / group / role lookups\n  with memberships (`directory`). ATF runs can wait for their result\n  (`wait_seconds`), and Import Set inserts report the transform run and maps.\n- **Self-documentation**: a local Markdown knowledge base (read/write/search) plus\n  deterministic Mermaid generators (ER diagrams from references, record-lifecycle\n  flowcharts from business rules) so the server builds durable, reusable context.\n- **Prompts**: ready-made workflows (incident triage, change impact analysis,\n  document a table, diagnose a slow instance, safe write, drift review, schema\n  impact, instance discovery) that orchestrate the tools; every plugin skill\n  has a prompt twin for clients without the plugin.\n- **Tool packages**: load only the tool groups you need via `SN_TOOL_PACKAGES`\n  (default profile `discovery`; `all` enables everything).\n- **Basic** or **OAuth 2.0** authentication over HTTPS; the password/token is\n  never echoed back.\n- Least-privilege controls: table allow/deny lists and a global read-only mode.\n- Resilience: per-request timeout, retry with backoff and `Retry-After`, SSRF\n  guard, and a result-size guard.\n- MCP **tool annotations** and **resources**, structured error payloads, and\n  structured logging on stderr.\n- Credentials in an env file (project, `~/.config`, or `SN_ENV_FILE`), updatable\n  at runtime via `servicenow_set_credentials`.\n\n## Requirements\n\n- Node.js 22.12+ (enforced: `engines` + a runtime guard with a clear message;\n  the project targets the version in `.nvmrc`).\n\n## Setup\n\nFrom source (for development):\n\n```bash\nnpm install\nnpm run build\n```\n\nOr run the published package directly, without cloning:\n\n```bash\nnpx servicenow-mcp-ai\n```\n\n### Install in your MCP client\n\nEvery client launches the same stdio command, `npx -y servicenow-mcp-ai` (Node.js 22.12+),\nunder the server name `servicenow`. The one-click links and snippets below carry **no\ncredentials**: keep them in the env file (`~/.config/servicenow-mcp-ai/.env`, see\n[Configure credentials](#configure-credentials)), run the one-time\n`npx servicenow-mcp-ai login` for OAuth, or ask the assistant to call\n`servicenow_set_credentials` once the server is connected. A real environment variable\nset in a client config **overrides** the env file, so only add an `env` block when you\nmean it — and never put `SN_PASSWORD` or other secrets into a client config you share\nor commit (see [SECURITY.md](SECURITY.md)).\n\n[![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_ServiceNow_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522servicenow%2522%252C%2522command%2522%253A%2522npx%2522%252C%2522args%2522%253A%255B%2522-y%2522%252C%2522servicenow-mcp-ai%2522%255D%257D)\n[![Install in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Install_ServiceNow_MCP-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522servicenow%2522%252C%2522command%2522%253A%2522npx%2522%252C%2522args%2522%253A%255B%2522-y%2522%252C%2522servicenow-mcp-ai%2522%255D%257D)\n[![Install in Cursor](https://img.shields.io/badge/Cursor-Install_ServiceNow_MCP-000000?style=flat-square&logo=cursor&logoColor=white)](https://cursor.com/en/install-mcp?name=servicenow&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsInNlcnZpY2Vub3ctbWNwLWFpIl19)\n\n| Client | One line | Config file |\n| --- | --- | --- |\n| VS Code (Copilot Chat) | Button above, or `code --add-mcp` (below) — or the **ServiceNow MCP** extension | `.vscode/mcp.json` (`servers`) |\n| VS Code Insiders | Button above, or `code-insiders --add-mcp` (below) | `.vscode/mcp.json` (`servers`) |\n| Claude Code | `claude mcp add servicenow -- npx -y servicenow-mcp-ai`, or the plugin | `.mcp.json` (`mcpServers`) |\n| Claude Desktop | — (edit the config file) | `claude_desktop_config.json` (`mcpServers`) |\n| Cursor | Button above, or the `cursor://` deeplink (below) | `~/.cursor/mcp.json` or `.cursor/mcp.json` (`mcpServers`) |\n| Windsurf | — (edit the config file) | `~/.codeium/windsurf/mcp_config.json` (`mcpServers`) |\n| Cline | — (MCP Servers → Configure MCP Servers) | `cline_mcp_settings.json` (`mcpServers`) |\n| Zed | — (edit settings) | `settings.json` (`context_servers`) |\n| JetBrains AI Assistant | — (Settings → Tools → AI Assistant → Model Context Protocol) | JSON dialog (`mcpServers`) |\n| Gemini CLI | — (edit settings) | `~/.gemini/settings.json` (`mcpServers`) |\n| Codex CLI | `codex mcp add servicenow -- npx -y servicenow-mcp-ai` | `~/.codex/config.toml` (`[mcp_servers.servicenow]`) |\n\n<details>\n<summary><strong>VS Code / VS Code Insiders</strong></summary>\n\nThe zero-config route is the **ServiceNow MCP** extension from the Marketplace\n(`code --install-extension ivanbbaev.servicenow-mcp-ai`); it registers the server in\nCopilot Chat (agent mode) automatically, no `mcp.json`. Source: [extension/](extension/).\n\nWithout the extension, add the server from a terminal (user profile):\n\n```bash\ncode --add-mcp '{\"name\":\"servicenow\",\"command\":\"npx\",\"args\":[\"-y\",\"servicenow-mcp-ai\"]}'\ncode-insiders --add-mcp '{\"name\":\"servicenow\",\"command\":\"npx\",\"args\":[\"-y\",\"servicenow-mcp-ai\"]}'\n```\n\nThe raw deeplinks behind the buttons (paste into a browser address bar):\n\n```text\nvscode:mcp/install?%7B%22name%22%3A%22servicenow%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22servicenow-mcp-ai%22%5D%7D\nvscode-insiders:mcp/install?%7B%22name%22%3A%22servicenow%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22servicenow-mcp-ai%22%5D%7D\n```\n\nOr a workspace file, `.vscode/mcp.json`:\n\n```json\n{\n  \"servers\": {\n    \"servicenow\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"servicenow-mcp-ai\"]\n    }\n  }\n}\n```\n\n</details>\n\n<details>\n<summary><strong>Claude Code</strong></summary>\n\n**Plugin** (zero-config — installs the server wired up):\n\n```bash\n/plugin marketplace add IvanBBaev/servicenow-mcp-ai\n/plugin install servicenow-mcp-ai\n```\n\nThe plugin also ships eight workflow skills, two read-only subagents and three\nhooks — see [Plugin skills](#plugin-skills).\n\n**CLI** — `--scope user` makes it available in every project; `--env` sets a\nnon-secret variable (the instance host) and leaves the secrets in the env file. A value set\nthis way wins over the env file, so drop `--env` if you switch instances with\n`servicenow_set_credentials`:\n\n```bash\nclaude mcp add servicenow --scope user --env SN_INSTANCE=your-instance.service-now.com -- npx -y servicenow-mcp-ai\n```\n\n</details>\n\n<details>\n<summary><strong>Claude Desktop</strong></summary>\n\n`claude_desktop_config.json` — macOS `~/Library/Application Support/Claude/`, Windows\n`%APPDATA%\\Claude\\` (Settings → Developer → Edit Config):\n\n```json\n{\n  \"mcpServers\": {\n    \"servicenow\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"servicenow-mcp-ai\"]\n    }\n  }\n}\n```\n\nRestart Claude Desktop after saving.\n\n</details>\n\n<details>\n<summary><strong>Cursor</strong></summary>\n\nUse the button above, or open the deeplink directly:\n\n```text\ncursor://anysphere.cursor-deeplink/mcp/install?name=servicenow&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsInNlcnZpY2Vub3ctbWNwLWFpIl19\n```\n\nOr edit `~/.cursor/mcp.json` (global) / `.cursor/mcp.json` (project) with the same\n`mcpServers` block as Claude Desktop.\n\n</details>\n\n<details>\n<summary><strong>Windsurf, Cline, JetBrains AI Assistant</strong></summary>\n\nAll three take the Claude Desktop `mcpServers` block unchanged:\n\n- **Windsurf** — `~/.codeium/windsurf/mcp_config.json` (Cascade → MCP servers → View raw\n  config), then refresh the server list.\n- **Cline** — MCP Servers icon → _Configure MCP Servers_ opens `cline_mcp_settings.json`.\n- **JetBrains AI Assistant** — Settings → Tools → AI Assistant → Model Context Protocol\n  (MCP) → Add → _As JSON_, paste the block.\n\n```json\n{\n  \"mcpServers\": {\n    \"servicenow\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"servicenow-mcp-ai\"]\n    }\n  }\n}\n```\n\n</details>\n\n<details>\n<summary><strong>Zed</strong></summary>\n\nIn Zed's `settings.json` (Zed → Settings → Open Settings):\n\n```json\n{\n  \"context_servers\": {\n    \"servicenow\": {\n      \"source\": \"custom\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"servicenow-mcp-ai\"],\n      \"env\": {}\n    }\n  }\n}\n```\n\n</details>\n\n<details>\n<summary><strong>Gemini CLI</strong></summary>\n\n`~/.gemini/settings.json` (user) or `.gemini/settings.json` (project):\n\n```json\n{\n  \"mcpServers\": {\n    \"servicenow\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"servicenow-mcp-ai\"]\n    }\n  }\n}\n```\n\nCheck it with `/mcp` inside a Gemini CLI session.\n\n</details>\n\n<details>\n<summary><strong>Codex CLI</strong></summary>\n\n```bash\ncodex mcp add servicenow --env SN_INSTANCE=your-instance.service-now.com -- npx -y servicenow-mcp-ai\n```\n\nOr `~/.codex/config.toml`:\n\n```toml\n[mcp_servers.servicenow]\ncommand = \"npx\"\nargs = [\"-y\", \"servicenow-mcp-ai\"]\n# Optional, non-secret only — secrets stay in ~/.config/servicenow-mcp-ai/.env:\n# env = { SN_INSTANCE = \"your-instance.service-now.com\" }\n```\n\n</details>\n\nPrefer a global install (`npm install -g servicenow-mcp-ai`)? Replace\n`\"command\": \"npx\", \"args\": [\"-y\", \"servicenow-mcp-ai\"]` with\n`\"command\": \"servicenow-mcp-ai\"` in any snippet. The\n[MCP Inspector](https://github.com/modelcontextprotocol/inspector) works the same way:\n`npx @modelcontextprotocol/inspector npx -y servicenow-mcp-ai`.\n\nThe one-click links are generated from `package.json` by `scripts/install-links.mjs`\n(`node scripts/install-links.mjs` prints them); `test/install-links.test.js` fails if\nthis README or the docs site drift from the generated strings.\n\n### Install via MCP bundle (.mcpb)\n\nAn [MCP bundle](https://github.com/modelcontextprotocol/mcpb) is one `.mcpb` file with the\nserver and its dependencies; Claude Desktop (or any MCPB host) installs it in one click, with\nno `npm` / `npx`. Its form asks for the connection keys (only `SN_INSTANCE` is required) and\n`SN_TOOL_PACKAGES`; secrets are marked sensitive (kept in the OS keychain). An empty field\nfalls back to the env file. Not published yet (O-22) — build it with `npm run mcpb:pack`\n(`dist/mcpb/`; `-- --validate` runs the official validator).\n\n### Docker\n\nThe repository ships a multi-stage `Dockerfile` (distroless Node 22 runtime, non-root\nuid 65532). The image contains exactly what `npm pack` publishes plus production\ndependencies, and starts the **HTTP transport** on `0.0.0.0:3000` by default. No image\nis published to a registry yet — build it locally:\n\n```bash\ndocker build -t servicenow-mcp-ai .\n\n# Secrets as files (Docker / Kubernetes secrets), mounted read-only\nmkdir -p secrets && printf '%s' 'your-password' > secrets/sn_password\nopenssl rand -hex 32 > secrets/sn_http_token\n\ndocker run --rm -p 127.0.0.1:3000:3000 \\\n  -e SN_INSTANCE=your-instance.service-now.com -e SN_USER=your.user \\\n  -e SN_PASSWORD_FILE=/run/secrets/sn_password \\\n  -e SN_HTTP_TOKEN_FILE=/run/secrets/sn_http_token \\\n  -v \"$PWD/secrets:/run/secrets:ro\" -v sn-data:/data \\\n  servicenow-mcp-ai\n```\n\n- **`SN_HTTP_TOKEN` is required for any non-loopback bind.** The image binds `0.0.0.0`\n  so the published port works; without a token (or OAuth) the server refuses to start\n  (3.0, B6). `SN_HTTP_REQUIRE_TOKEN=0` lets it start with a warning, and then every\n  client that reaches the port drives your instance with the configured credentials.\n  Clients send `Authorization: Bearer <token>`; terminate TLS in front of the container.\n- **OAuth instead of a shared token (N-17):** set `SN_HTTP_OAUTH_ISSUER` (your OIDC\n  provider) and `SN_HTTP_OAUTH_RESOURCE` (this server's public URL, e.g.\n  `https://mcp.example.com/mcp`). Clients discover the issuer from\n  `/.well-known/oauth-protected-resource` and send its JWT access tokens; the token must\n  name the resource as its audience. Optional: `SN_HTTP_OAUTH_SCOPES`,\n  `SN_HTTP_OAUTH_AUDIENCE`, `SN_HTTP_OAUTH_JWKS_URI`. For an issuer that hands out opaque\n  tokens, set `SN_HTTP_OAUTH_INTROSPECTION_URI` plus its client id and secret (RFC 7662). By\n  default the instance is still called with the configured service account.\n- **Per-user ServiceNow access (N-17 phase 2):** add `SN_HTTP_OAUTH_USER_TOKENS=true`, a\n  32-byte `SN_HTTP_OAUTH_TOKEN_KEY` (base64 or hex, e.g. `openssl rand -base64 32`) and an\n  OAuth client on the instance (`SN_OAUTH_CLIENT_ID` / `SN_OAUTH_CLIENT_SECRET`, refresh\n  tokens enabled) whose redirect URL is `/oauth/servicenow/callback` on the\n  `SN_HTTP_OAUTH_RESOURCE` origin. The first call from a user returns a link to the\n  instance's sign-in page (URL elicitation; a 2025 session gets `-32042`, a client without\n  URL elicitation and a background task get an error carrying the link). After\n  the user signs in, the server checks that the account's `sys_user` field matches the\n  token's claim (`SN_HTTP_OAUTH_USER_MATCH`, default `email=email`), keeps the refresh token\n  AES-256-GCM encrypted in `SN_HTTP_OAUTH_TOKEN_STORE`, and from then on calls the instance as\n  that user, so ServiceNow ACLs apply per user. A user drops their own links with\n  `DELETE /oauth/servicenow/link` (their bearer token; answers `{ unlinked, revoked }`); the\n  refresh tokens are also revoked on the instance, best effort. Replicas behind one\n  `SN_HTTP_OAUTH_RESOURCE` can each complete a link when they share `SN_HTTP_OAUTH_TOKEN_KEY`\n  and the store. Limit: requests authorized with `SN_HTTP_TOKEN` still use the shared\n  credential.\n- `/data` holds the docs directory (`SN_DOCS_DIR=/data/docs`) and the env file\n  (`SN_ENV_FILE=/data/.env`); mount a volume there to keep them.\n- Every `<KEY>_FILE` secret source is described in [Secrets from files](#secrets-from-files).\n- For an MCP client that spawns the container over stdio, pass `-i -e SN_TRANSPORT=stdio`\n  (`docker run --rm -i -e SN_TRANSPORT=stdio -e SN_INSTANCE=… servicenow-mcp-ai`).\n- The `HEALTHCHECK` is a TCP liveness probe. `GET /healthz` (liveness) and `GET /readyz`\n  (credentials configured) answer without the token for orchestrator probes;\n  `GET /readyz?probe=1` also calls the instance and sits behind the token, like every\n  MCP route. Set `SN_HTTP_ALLOWED_HOSTS` to the name clients use so the Host header is\n  checked on a `0.0.0.0` bind.\n- `smithery.yaml` describes the same image for [Smithery](https://smithery.ai) (stdio,\n  config keys mapped to the `SN_*` settings).\n\n### HTTP transport: sessions, probes and shutdown\n\nWith `SN_TRANSPORT=http` every MCP session (one `initialize`) gets its own server:\n\n- **Per-session state.** Enabled packages, the MCP logging level, list-changed\n  notifications, plan tokens, tasks and write caps belong to the session. Connection\n  pools, OAuth tokens and the schema cache are shared and keyed by profile + host.\n- **`servicenow_use_instance` is session-scoped over HTTP.** It switches the profile of\n  the calling session only; other sessions keep theirs and nothing is written. Pass\n  `persist: true` to also write `SN_ACTIVE_PROFILE` to the env file (journaled) — that\n  changes the default for sessions that have not switched. Over stdio the switch lasts\n  until the process exits; `persist: true` writes it there too (3.0, B12).\n- **Lifetime.** A session ends on `DELETE` or after `SN_HTTP_SESSION_TTL_SEC` idle\n  (default 30 min); a request with an ended session id gets 404 and the client\n  re-initializes. At most `SN_HTTP_MAX_SESSIONS` (64) are open at once.\n- **DNS-rebinding protection.** The `Host` header must match `SN_HTTP_ALLOWED_HOSTS`\n  (default: the loopback names on a loopback bind) and a browser `Origin` must match\n  `SN_HTTP_ALLOWED_ORIGINS` (default: loopback origins); otherwise 403.\n- **Probes.** `GET /healthz` → `200 {\"status\":\"ok\"}` while serving. `GET /readyz` →\n  200 when credentials are configured, 503 otherwise. Both answer without the token.\n  `GET /readyz?probe=1` (behind the token) also reads one `sys_user` row and returns\n  503 when the instance is unreachable; the result is cached for 5 s.\n- **Shutdown.** On SIGTERM / SIGINT the listener stops accepting connections, new\n  requests get 503, in-flight tool calls get up to 5 s to finish, then every session is\n  closed and the process exits 0.\n- **Keep-alive.** Open SSE streams get a comment every `SN_HTTP_KEEPALIVE_MS` (25 s).\n\n### Quickstart\n\nThe fastest path is three lines of Basic auth — set these (in the env file or the\nreal environment) and you are connected:\n\n```dotenv\nSN_INSTANCE=dev12345.service-now.com\nSN_USER=your.username\nSN_PASSWORD=your-password\n```\n\nEverything else is optional tuning; see the full\n[Environment variables](#environment-variables) reference for the rest.\n\n> **Past a quick try, prefer OAuth over a stored password.** For anything shared or\n> long-lived, run the one-time `npx servicenow-mcp-ai login` instead — it stores a\n> refresh token, not your password. See\n> [Configure credentials](#configure-credentials) → _OAuth 2.1_.\n\n### Verify your setup\n\nOnce the three variables are set, confirm the connection before you start:\n\n1. Run the `servicenow_test_connection` tool — it reads one `sys_user` record and\n   reports `ok`, HTTP status and latency.\n2. Run `servicenow_check_capabilities` — it previews which admin-restricted `sys_*`\n   tables the connected user can actually read.\n\nOr do both from the shell in one shot:\n\n```bash\nnpx servicenow-mcp-ai doctor   # checks credentials, reachability and capabilities\n```\n\nPrefer to be asked? `npx servicenow-mcp-ai init` prompts for the instance, the\nauth method and the credentials, writes the env file and runs `doctor` — see\n[Command-line interface](#command-line-interface).\n\n## Configure credentials\n\nCredentials live in `~/.config/servicenow-mcp-ai/.env` (or the file `SN_ENV_FILE` names):\n\n```dotenv\nSN_INSTANCE=your-instance.service-now.com\nSN_USER=your.username@example.com\nSN_PASSWORD=your-password\n```\n\n`SN_INSTANCE` accepts `dev12345`, `dev12345.service-now.com` or a full `https://` URL.\n\nYou can also set or change them at runtime by calling the\n`servicenow_set_credentials` tool — the new values are written straight back to the env file.\nMoving a configured profile to a different instance requires `user` and `password` in the same\ncall (the stored secrets are never sent to another host), and the change must be confirmed by\nthe client — clients without elicitation support are refused unless\n`SN_ALLOW_UNCONFIRMED_CREDENTIAL_CHANGE=1` is set.\n\nThe tool also sets the auth method (`auth`), the OAuth client id (`oauth_client_id`) and grant\n(`oauth_grant`). Secrets — the API key and the OAuth client secret — are never tool arguments:\nlist them in `request_secrets` and the server asks for them through an elicitation prompt, so\nthey never appear in a logged tool call, the result or the write journal. A client without\nelicitation support is refused (the opt-out above does not apply to secrets); set those keys in\nthe env file instead. The instance-change rule follows the resulting auth method: an API-key\nprofile needs a new API key, an OAuth `client_credentials` profile a new client secret, the\nOAuth `password` grant user, password and client secret, Basic / `none` user and password;\nbearer-token, `refresh_token` and `jwt_bearer` profiles cannot be moved with this tool.\n\n`servicenow_get_status` (`authWarnings`), `servicenow_list_instances` and `doctor` evaluate each\nprofile against its own auth method — an API-key profile needs no password — and report the\nmethod, the OAuth grant, the refresh-token state and the write mode, never a secret value. When\nthe refresh-token grant returns a rotated refresh token, it is written back to the env key it\nwas read from; if the env file cannot be written, the new token is kept in memory (lost on\nrestart) and a warning is logged and shown by `get_status` / `doctor`. Values the server writes\nkeep Windows paths literal (backslashes are single-quoted) and a CRLF env file stays CRLF. On\nWindows the env file inherits its folder's ACL — restrict it yourself (for example\n`icacls .env /inheritance:r /grant:r \"%USERNAME%:F\"`); the server only warns, it never runs\n`icacls`.\n\nThe env file is resolved in this order: `SN_ENV_FILE`, then\n`~/.config/servicenow-mcp-ai/.env` (XDG). A project-root `.env` is deprecated (3.0, B5):\nif one exists while neither of the two is in use, it is still read and startup warns where to move it.\nA global/`npx` install therefore writes to your user config rather than into\n`node_modules`. Real environment variables always take precedence over the file.\n\n### First run: the model configures itself\n\nAt `initialize` the server sends `instructions` built from the live configuration: the enabled\npackages and tool count, the write mode, the active profile and, when nothing is configured,\nwhat is missing and how to fix it — plus pointers to the prompts, the reference resources\nand large-result handling (paging, `format \"file\"`). Until then every instance tool fails with\n`code: \"NOT_CONFIGURED\"` and a hint naming `servicenow_set_credentials`. A first session\nwith an empty env file looks like this (abridged):\n\n```text\ninstructions  Credentials: NOT configured (missing instance, user, password). Instance tools\n              fail with code NOT_CONFIGURED until fixed. To configure: ask the user for\n              the instance and credentials, call servicenow_set_credentials, then\n              servicenow_test_connection. Never guess or echo a password.\nuser          How many open P1 incidents do we have?\nmodel         Which instance, user and password should I connect with?\nuser          dev12345, admin, ••••••\ntool call     servicenow_set_credentials { instance: \"dev12345\", user: \"admin\", password: … }\ntool result   { message: \"Credentials saved\", profile: \"default\", configured: true, password: \"***\" }\ntool call     servicenow_test_connection {}\ntool result   { ok: true, … }\ntool call     servicenow_aggregate { table: \"incident\", query: \"active=true^priority=1\" }\nmodel         There are 7 open P1 incidents.\n```\n\n`servicenow_get_status` then shows the live state: server version, uptime and transport,\n`policy.summary`, limits, redaction, the docs directory, write counters, the profile source and\n`profileDetails` (per-profile auth mode, write mode and missing keys) — never a secret value.\n\n### OAuth 2.1 (Authorization Code + PKCE) — recommended\n\nRegister an **Authorization Code** OAuth API endpoint in ServiceNow with a\nloopback redirect URL (e.g. `http://localhost:53682/callback`), set\n`SN_OAUTH_CLIENT_ID` (and `SN_OAUTH_CLIENT_SECRET` for a confidential client),\nthen run the one-time interactive login:\n\n```bash\nnpx servicenow-mcp-ai login\n```\n\nIt opens the browser, you approve, and the obtained **refresh token** is stored\nin your env file. The server then runs non-interactively (refresh_token grant) —\nno password is ever stored. PKCE (S256) is always used.\n\n> The OAuth 2.0 **password grant (ROPC) is deprecated** in OAuth 2.1 and disabled\n> on many instances; prefer `login`. `client_credentials` and `refresh_token`\n> grants remain supported for service accounts. See [.env.example](.env.example).\n\n### Supported authentication methods\n\nEvery inbound REST auth method ServiceNow offers is covered:\n\n| Method | `SN_AUTH` | Set | Notes |\n| ------ | --------- | --- | ----- |\n| Basic | `basic` | `SN_USER` / `SN_PASSWORD` | Default. |\n| OAuth 2.1 — Authorization Code + PKCE | `oauth` | `npx servicenow-mcp-ai login` | **Recommended.** Interactive, stores a refresh token. |\n| OAuth — Client Credentials | `oauth` | `SN_OAUTH_GRANT=client_credentials` | Service-to-service. |\n| OAuth — Refresh Token | `oauth` | `SN_OAUTH_GRANT=refresh_token` + `SN_OAUTH_REFRESH_TOKEN` | Set by `login`. |\n| OAuth — JWT Bearer | `oauth` | `SN_OAUTH_GRANT=jwt_bearer` + `SN_OAUTH_JWT_KEY` | RS256 assertion; no password. |\n| OAuth — Password (ROPC) | `oauth` | `SN_OAUTH_GRANT=password` | **Deprecated.** |\n| API Key | `apikey` | `SN_API_KEY` | `x-sn-apikey` header. |\n| Bearer token | `token` | `SN_BEARER_TOKEN` or `SN_TOKEN_FILE` | Pre-obtained token, used verbatim. A rejected token (401) re-reads `SN_TOKEN_FILE` once, else fails with `AUTH_EXPIRED`. |\n| Mutual TLS (client cert) | `none` (or layered) | `SN_TLS_CLIENT_CERT` / `_KEY` | Cert maps to a user; needs optional `undici`. |\n\n### Environment variables\n\nAll settings are read from the env file (`SN_ENV_FILE`, else\n`~/.config/servicenow-mcp-ai/.env`) or the real process environment, which takes\nprecedence. Only the first three are required; the rest are optional tuning knobs.\nSee [.env.example](.env.example) for a template. Every value is validated at\nstartup: an invalid one stops the server with an error that names every offending key\n(3.0, B5), or — with `SN_STRICT_SETTINGS=0` — is logged as a warning and the setting keeps\nits default.\n\n<!-- GENERATED:ENV:BEGIN (npm run docs:env) -->\n\n_These tables are generated from the settings manifest\n(`src/core/settings-manifest.ts`) — edit the manifest, then run\n`npm run docs:env`._\n\n#### Connection and authentication\n\nThe instance and its credentials. Only SN_INSTANCE is always required; the auth method is auto-detected from the keys present (API key -> bearer token -> OAuth -> Basic) unless SN_AUTH names it.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_INSTANCE` | yes | — | 1.0.0 | Instance name, host, or `https://` URL (`dev12345`, `dev12345.service-now.com`). |\n| `SN_USER` | yes | — | 1.0.0 | ServiceNow username for Basic auth. |\n| `SN_PASSWORD` | yes | — | 1.0.0 | ServiceNow password. Never logged or returned by any tool. |\n| `SN_AUTH` | no | auto | 1.1.0 | Auth method: `basic`, `oauth`, `apikey`, `token` or `none` (cert-only mTLS). Auto-detected from the keys present (API key → bearer → OAuth → Basic). |\n| `SN_API_KEY` | no | — | 1.1.0 | ServiceNow Inbound API Key, sent as the `x-sn-apikey` header (enables `apikey` mode). |\n| `SN_BEARER_TOKEN` | no | — | 1.1.0 | A pre-obtained bearer token, sent verbatim as `Authorization: Bearer …` (enables `token` mode). |\n| `SN_TOKEN_FILE` | no | — | next | File holding the bearer token (enables `token` mode; wins over `SN_BEARER_TOKEN`). Re-read once when the instance rejects the token with 401, so an external issuer can rotate it; otherwise the call fails with `AUTH_EXPIRED`. |\n| `SN_TOKEN_EXPIRES_AT` | no | — | next | ISO 8601 expiry of the bearer token. `get_status` / `doctor` warn when less than 24 h remain, when it has passed, or when it cannot be parsed. |\n| `SN_OAUTH_CLIENT_ID` | no | — | 1.1.0 | OAuth client id (its presence enables OAuth). |\n| `SN_OAUTH_CLIENT_SECRET` | no | — | 1.1.0 | OAuth client secret. |\n| `SN_OAUTH_GRANT` | no | `password` | 1.1.0 | OAuth grant: `password` (**deprecated** — ROPC), `client_credentials`, `refresh_token` or `jwt_bearer`. The `login` command sets this to `refresh_token` for you. Any other value fails every OAuth request. |\n| `SN_OAUTH_REFRESH_TOKEN` | no | — | 1.1.0 | Refresh token for the `refresh_token` grant. Obtained automatically by `npx servicenow-mcp-ai login` (Authorization Code + PKCE). |\n| `SN_OAUTH_REDIRECT_URI` | no | http://localhost:53682/callback | 1.1.0 | Loopback redirect URL for the PKCE `login` flow. Must match the redirect registered on the OAuth endpoint. |\n| `SN_OAUTH_SCOPE` | no | — | 1.1.0 | Optional OAuth scope requested during `login`. |\n| `SN_OAUTH_JWT_KEY` | no | — | 1.1.0 | PEM private key for the `jwt_bearer` grant (or `SN_OAUTH_JWT_KEY_FILE`); the public certificate is registered on the ServiceNow JWT provider. |\n| `SN_OAUTH_JWT_KEY_FILE` | no | — | 1.1.0 | Path to the PEM private key for the `jwt_bearer` grant. |\n| `SN_OAUTH_JWT_ISS` | no | client id | 1.1.0 | `iss` claim of the JWT-bearer assertion. |\n| `SN_OAUTH_JWT_SUB` | no | `SN_USER` | 1.1.0 | `sub` claim (the user) of the JWT-bearer assertion. |\n| `SN_OAUTH_JWT_AUD` | no | `https://<host>/oauth_token.do` | 1.1.0 | `aud` claim of the JWT-bearer assertion. |\n| `SN_OAUTH_JWT_KID` | no | — | 1.1.0 | `kid` header of the JWT-bearer assertion, when the provider requires one. |\n| `SN_OAUTH_JWT_EXP_SEC` | no | `300` | 1.1.0 | Lifetime of the JWT-bearer assertion in seconds. |\n| `SN_ALLOW_UNCONFIRMED_CREDENTIAL_CHANGE` | no | `false` | next | H-2: operator opt-out — lets `servicenow_set_credentials` proceed on MCP clients without elicitation support (no confirmation prompt, no live server). An explicit decline is still refused. Off by default. |\n\n#### Secrets from files\n\nContainer secrets (D-5): <KEY>_FILE=/path loads <KEY> from that file at startup (one trailing newline is trimmed). Setting both <KEY> and <KEY>_FILE is a startup error; so is an unreadable or empty file. A value loaded this way is never written back to the env file. Per profile: SN_PROFILE_<NAME>_<KEY>_FILE for the ServiceNow secrets.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_PASSWORD_FILE` | no | — | next | D-5: read `SN_PASSWORD` from this file (Docker / Kubernetes secrets). |\n| `SN_API_KEY_FILE` | no | — | next | D-5: read `SN_API_KEY` from this file (Docker / Kubernetes secrets). |\n| `SN_BEARER_TOKEN_FILE` | no | — | next | D-5: read `SN_BEARER_TOKEN` from this file (Docker / Kubernetes secrets). Read once at startup (`SN_TOKEN_FILE`, re-read on a 401, still wins). |\n| `SN_OAUTH_CLIENT_SECRET_FILE` | no | — | next | D-5: read `SN_OAUTH_CLIENT_SECRET` from this file (Docker / Kubernetes secrets). |\n| `SN_OAUTH_REFRESH_TOKEN_FILE` | no | — | next | D-5: read `SN_OAUTH_REFRESH_TOKEN` from this file (Docker / Kubernetes secrets). A rotated refresh token is then kept in memory only (update the file yourself). |\n| `SN_HTTP_TOKEN_FILE` | no | — | next | D-5: read `SN_HTTP_TOKEN` from this file (Docker / Kubernetes secrets). |\n| `SN_HTTP_OAUTH_INTROSPECTION_SECRET_FILE` | no | — | next | D-5: read `SN_HTTP_OAUTH_INTROSPECTION_SECRET` from this file (Docker / Kubernetes secrets). |\n| `SN_HTTP_OAUTH_TOKEN_KEY_FILE` | no | — | next | D-5: read `SN_HTTP_OAUTH_TOKEN_KEY` from this file (Docker / Kubernetes secrets). |\n\n#### Profiles and the env file\n\nThe bare SN_INSTANCE / SN_USER / SN_PASSWORD keys are the 'default' profile. More instances live under SN_PROFILE_<NAME>_* keys; switch with SN_ACTIVE_PROFILE or the servicenow_use_instance tool.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_PROFILE_<NAME>_*` | no | — | 1.1.0 | Named connection profiles: `SN_PROFILE_DEV_INSTANCE` / `_USER` / `_PASSWORD` define profile `dev`. The bare `SN_INSTANCE`/`SN_USER`/`SN_PASSWORD` keys are the `default` profile. The auth, policy, write-mode, `ENV`, `PROD_WRITES` and `UPDATE_SET` settings take the same prefix. Example: `SN_PROFILE_DEV_INSTANCE=dev12345.service-now.com`, `SN_PROFILE_DEV_USER=admin`, `SN_PROFILE_DEV_PASSWORD=dev-password`. |\n| `SN_ACTIVE_PROFILE` | no | `default` | 1.1.0 | Which profile tools use. Switch at runtime with `servicenow_use_instance` (written to the env file only with `persist: true`). |\n| `SN_ENV_FILE` | no | `~/.config/servicenow-mcp-ai/.env` | 1.1.0 | Explicit path to the env file to read/write. Otherwise the server uses `$XDG_CONFIG_HOME/servicenow-mcp-ai/.env` (`~/.config/…`). A project-root `.env` next to the installed package is still read when neither is in play, as a deprecated fallback (B5) with a startup warning naming where to move it. `doctor` prints the chosen file and why. |\n\n#### Network, TLS and resilience\n\nTimeouts, retries, the host allow-list, the outbound proxy, mutual TLS and the per-host queue and circuit breaker. They govern every REST client of the server. The proxy and mutual TLS need the optional undici package.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_TIMEOUT_MS` | no | `30000` | 1.1.0 | Per-request timeout in milliseconds. |\n| `SN_MAX_RETRIES` | no | `2` | 1.1.0 | Retries for transient failures (429/5xx, network errors). Non-idempotent writes are only retried on connect errors. |\n| `SN_RETRY_AFTER_MAX_MS` | no | `60000` | next | Upper bound honoured for a `Retry-After` header on 429/503; a larger value is clamped so a misbehaving upstream cannot park the client for minutes. |\n| `SN_DEADLINE_MS` | no | max(120000, 2 × `SN_TIMEOUT_MS`) | next | Total wall-clock budget for one logical request across retries, backoff, queue wait and OAuth re-auth. A retry that cannot fit into the remaining budget is not attempted — the call fails with code `DEADLINE_EXCEEDED`. |\n| `SN_ALLOWED_HOSTS` | no | — | 1.1.0 | Comma-separated allow-list of permitted hosts (for custom or sovereign-cloud domains). When set, only matching hosts are contacted. When unset, only `*.service-now.com` instances are allowed and internal/loopback hosts are blocked (SSRF guard). An entry may carry a port (`host:8443`) or be a bracketed IPv6 literal (`[2001:db8::1]`); an explicit non-443 port or an IPv6 literal in the instance value is accepted only when such an entry matches it — never under the default policy. |\n| `SN_MAX_BODY_BYTES` | no | `52428800` | next | Largest response body (bytes) read into memory; a larger declared or streamed body fails with `RESPONSE_TOO_LARGE`. Redirects are never followed — a 3xx fails with `REDIRECT_BLOCKED` naming the target host. |\n| `SN_HTTPS_PROXY` | no | — | next | Outbound HTTPS proxy URL (`http://user:pass@proxy:3128`) for all ServiceNow and OAuth traffic; needs the optional `undici` package. When unset, the ambient `HTTPS_PROXY` / `HTTP_PROXY` variables are honoured together with `NO_PROXY`; `SN_HTTPS_PROXY` itself is explicit and ignores `NO_PROXY`. Proxy credentials are never logged. |\n| `SN_USER_AGENT_SUFFIX` | no | — | next | Extra token appended to the `User-Agent` sent on every request (`servicenow-mcp-ai/<version> (node/<major>; <transport>; <client>)`), e.g. a team or ticket id for correlation in the instance's transaction log. Printable ASCII, up to 80 characters. |\n| `SN_TLS_CLIENT_CERT` | no | — | 1.1.0 | Client certificate (PEM) for **mutual TLS** (or `SN_TLS_CLIENT_CERT_FILE`). With `SN_TLS_CLIENT_KEY` it presents a client cert; ServiceNow's mutual-auth profile maps it to a user. Needs the optional `undici` package (`npm i undici`). Cert and key must be set together — only one of them is a configuration error. |\n| `SN_TLS_CLIENT_CERT_FILE` | no | — | 1.1.0 | Path to the client certificate (PEM) for mutual TLS. |\n| `SN_TLS_CLIENT_KEY` | no | — | 1.1.0 | Private key (PEM) for the client certificate (or `SN_TLS_CLIENT_KEY_FILE`). |\n| `SN_TLS_CLIENT_KEY_FILE` | no | — | 1.1.0 | Path to the private key (PEM) for the client certificate. |\n| `SN_TLS_CA` | no | — | 1.1.0 | Optional CA bundle (PEM) to trust (or `SN_TLS_CA_FILE`) — applied with or without a client certificate; needs the optional `undici` package. |\n| `SN_TLS_CA_FILE` | no | — | 1.1.0 | Path to the CA bundle (PEM) to trust. |\n| `SN_TLS_REJECT_UNAUTHORIZED` | no | `true` | 1.1.0 | `false` disables TLS certificate verification (not recommended; warned once at startup). |\n| `SN_MAX_CONCURRENT` | no | `4` | 1.1.0 | Maximum parallel HTTP requests to the instance (simple in-process semaphore). |\n| `SN_MAX_QUEUE` | no | `64` | next | Maximum requests waiting per host for a free slot beyond `SN_MAX_CONCURRENT`. Overflow fails immediately with code `BUSY` instead of piling up. Diagnostics (`servicenow_test_connection`, `doctor`) bypass the queue so they still answer while it is stalled. |\n| `SN_QUEUE_TIMEOUT_MS` | no | `SN_TIMEOUT_MS` | next | Longest a request waits for a slot before failing with code `BUSY`. Wait time is not billed to the per-attempt timeout, only to `SN_DEADLINE_MS`. |\n| `SN_BREAKER_THRESHOLD` | no | `0` (off) | next | Opt-in per-host circuit breaker: after this many consecutive failed requests (transport error, deadline, 5xx) further requests fail fast with code `CIRCUIT_OPEN` until `SN_BREAKER_RESET_MS` passes. Diagnostics are never blocked. |\n| `SN_BREAKER_RESET_MS` | no | `30000` | next | How long an open circuit breaker rejects requests before letting a trial request through; the first failure re-opens it, the first success closes it. |\n\n#### Tool packages\n\nWhich tools are registered. The admin tools (set_credentials, get_status, use_instance) are always on.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_TOOL_PACKAGES` | no | `discovery` | 1.0.0 | Comma/space-separated tool packages or profiles to enable. Profiles: `discovery` (default; `core`, the 2.x default, adds `attachment`), `all` and the presets `reader` \\\\| `developer` \\\\| `admin` (see [Presets](#presets)). Packages: `table`, `schema`, `aggregate`, `attachment`, `importset`, `batch`, `catalog`, `change`, `knowledge`, `cmdb`, `scripts`, `flows`, `codecheck`, `docs`, `instance`, `email`, `atf`, `revert`, `artifacts`, `updatesets`, `cicd`, `access`, `ops`, `history`, `properties`, `directory`, `ui`. The admin tools are always on. `atf` runs tests on the instance — enable it only on a non-production instance. `cicd` previews and commits retrieved update sets. `access` grants and revokes one non-privileged role for one user. |\n| `SN_PACKAGES_DENY` | no | — | 1.0.0 | Comma/space-separated packages to exclude even if enabled by `SN_TOOL_PACKAGES`. The only way to block plugin APIs (catalog, change, knowledge…) — the table policy does not see them. |\n| `SN_PACKAGES_READONLY` | no | — | 1.0.0 | Comma/space-separated packages whose write tools are not registered; their read tools stay. Per-package complement to the global `SN_READONLY`. |\n| `SN_CODESEARCH` | no | `false` | 1.1.0 | Opt in to the Code Search API (`sn_codesearch`) for `servicenow_search_code` (FT-7). When `true` and the plugin is active it replaces the LIKE iteration; falls back to LIKE on any failure. |\n| `SN_EXPERIMENTAL_TASKS` | no | `0` | next | M-9, **experimental**: `1` adds an optional `run_as_task:true` argument to `snapshot_instance`, `compare_instances`, `run_atf`, `check_code_health`, `document_app`, `document_instance` and `query_table` (`format:\"file\"` only). Such a call returns an MCP task handle at once (`_meta[\"io.modelcontextprotocol/related-task\"]`); the client polls `tasks/get`, reads `tasks/result` (kept 1 h, redacted) or stops it with `tasks/cancel`. Off: schemas unchanged. Built on the SDK's experimental task API. |\n| `SN_MCP_APPS` | no | `0` | next | N-50, MCP Apps (SEP-1865): `1` registers four self-contained `ui://servicenow-mcp/…` HTML views (`text/html;profile=mcp-app`: plan diff, Mermaid diagram, flow explainer, UI Builder page tree) and links the write tools with `apply`, the Mermaid generators, `explain_flow` and `explain_ui_experience` to them through `_meta.ui.resourceUri` — only for a client that advertises the `io.modelcontextprotocol/ui` extension. The views render the tool's own result (no network, strict CSP). Off: `tools/list`, resources and every result unchanged. |\n| `SN_LEGACY_TOOL_NAMES` | no | `0` | next | M-7 (B2), **deprecated bridge for one minor cycle**: every tool name renamed by the v3 naming convention is an alias of its new name — it dispatches to the new tool, accepts the old parameter names, and logs a one-time deprecation warning. Off (the default): the aliases still answer `tools/call` but are left out of `tools/list`. `1` also lists them and accepts the old parameter names on the new tool names. See the rename table in the README. |\n\n#### Access policy and write safety\n\nLeast-privilege table policy, plan-and-apply writes, destructive-write confirmation, per-session caps, prod profiles, update-set binding and the upload / email / SDK-managed-scope guards.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_TABLES_ALLOW` | no | — | 1.1.0 | Comma-separated table allowlist; when set, only these tables are reachable. |\n| `SN_TABLES_DENY` | no | — | 1.1.0 | Comma-separated table denylist; always wins over the allowlist. |\n| `SN_READONLY` | no | `false` | 1.1.0 | When truthy, refuse every create/update/delete. |\n| `SN_WRITE_MODE` | no | `plan` | 2.0.0 | `plan` (default) previews a write as a before/after diff without mutating; `apply` executes; passing `apply:true` forces a single call. |\n| `SN_COMPAT` | no | `3` | next | Upgrade bridge (owner, 2026-10-14): `2` keeps the 2.x defaults for every one of these settings left unset — `SN_PROTECTED_TABLES_WRITE=allow`, `SN_DESTRUCTIVE_CONFIRM=off`, `SN_BATCH_UNMAPPED=allow`, `SN_LEGACY_TOOL_NAMES=1` and `SN_TOOL_PACKAGES=core` (discovery plus `attachment`) — and an invalid value warns and keeps its default instead of stopping the server (`SN_STRICT_SETTINGS=0`). A setting you set yourself always wins. `servicenow-mcp-ai migrate` adds it when it converts a 2.x env file. `3` (the default) uses the 3.0 defaults. Meant for the migration, not as a permanent setting. |\n| `SN_DESTRUCTIVE_CONFIRM` | no | `token` | next | H-3: confirmation for a destructive `apply:true` (`delete_record`, `delete_attachment`, a writing `batch`, `send_email`, `order_catalog_item`, `revert_write`, `upsert_artifact`, `check_change_conflicts` with `calculate:true`) in plan mode. `token` (the 3.0 default, B4): the plan preview returns a single-use `plan_token` and the apply must pass it back with the same arguments — an apply with no token returns that preview and its token instead (nothing runs), a wrong, used or expired one is `PLAN_REQUIRED`; `elicit`: `token` plus a confirmation prompt on clients with elicitation (a decline is `CONFIRM_DECLINED`, journaled as refused). `SN_WRITE_MODE=apply` bypasses it, except on a profile marked `prod` (`SN_ENV`), which is always at least `elicit` and is confirmed in apply mode too. `off` is the explicit opt-out (the pre-3.0 behaviour). |\n| `SN_PLAN_TOKEN_TTL_SEC` | no | `600` | next | H-3: lifetime of a `plan_token` in seconds (30–86400). Tokens live only in the server process and are used up by the apply. |\n| `SN_BATCH_UNMAPPED` | no | `deny` | next | H-4: a `servicenow_batch` sub-request whose REST path no tool package owns: `deny` (the 3.0 default, B8) refuses it (so a new plugin API cannot pass `SN_PACKAGES_DENY` / `SN_PACKAGES_READONLY` inside a batch); `allow` is the opt-out and checks it against the table and read-only axes only. A nested batch is always refused. |\n| `SN_BATCH_MAX_REQUESTS` | no | `50` | next | H-4: most sub-requests one `servicenow_batch` call may carry (1–1000; 50 since 3.0), checked before anything is sent. |\n| `SN_PROTECTED_TABLES_WRITE` | no | `confirm` | next | H-11: writes to the built-in protected tables (identity, roles, ACLs, `sys_properties`, OAuth, scripts, LDAP, certificates, data sources, REST messages — `servicenow_explain_policy` lists them). `confirm` (the 3.0 default, B11) runs one only when the tool call itself passes `apply: true` — under `SN_WRITE_MODE=apply` a call without it is refused with `POLICY_DENIED` and a hint to re-run; `deny` refuses them all; `allow` is the 2.x behaviour. An exact `SN_TABLES_ALLOW` entry lifts the rule for one table. Reads are unaffected. |\n| `SN_IMPORT_SET_TABLES` | no | `u_*,imp_*` | next | H-11: patterns (`*`, `?`) the import-set staging table must match (3.0 default `u_*,imp_*`); `*` is the opt-out (any table the table policy allows). |\n| `SN_MAX_WRITES_PER_SESSION` | no | 500 per HTTP session, none on stdio | next | H-11: most applied instance writes per session (the process on stdio, one MCP session over HTTP; a batch counts its write sub-requests). Past it, writes fail with `WRITE_CAP` before any request; `get_status.writes.caps` shows the usage. Unset = 500 per HTTP session and no cap on stdio (3.0 default); `0` = no cap. |\n| `SN_MAX_DELETES_PER_SESSION` | no | `100` | next | H-11: most applied deletes per session (`WRITE_CAP`; 100 since 3.0). `0` = no cap. |\n| `SN_MAX_BATCH_WRITES` | no | `50` | next | H-11: most write (non-GET) sub-requests in one `servicenow_batch` (`WRITE_CAP`; 50 since 3.0). `0` = no cap. |\n| `SN_ENV` | no | — | next | H-11: marks the default profile `prod`, `test` or `dev` (`SN_PROFILE_<NAME>_ENV` for others). A `prod` profile stays in plan mode even when apply is configured unless `SN_PROD_WRITES` (`SN_PROFILE_<NAME>_PROD_WRITES`) is `I_UNDERSTAND`; its destructive applies are always confirmed (at least `SN_DESTRUCTIVE_CONFIRM=elicit`, also in apply mode — `CONFIRM_REQUIRED` for a client without elicitation); results carry `_meta.environment`; `use_instance` warns. `SN_PROFILE_<NAME>_WRITE_MODE` sets the write mode per profile. |\n| `SN_PROD_WRITES` | no | — | next | H-11: `I_UNDERSTAND` lets a `prod` default profile run in apply mode. |\n| `SN_UPDATE_SET` | no | — | next | S-6: update set (sys_id or exact name) that applied Table-tool writes (create / update / upsert / delete) land in; a per-call `update_set` overrides it. The plan names the set; the user's current update set is switched for the write and restored after it. Data-row tables are written unchanged. |\n| `SN_EMAIL_ALLOWED_DOMAINS` | no | — | next | Recipient domains `servicenow_send_email` may address (to/cc/bcc; a domain covers its subdomains, `*` allows any). When unset, every recipient must be the email of a user in the instance's own `sys_user` table; anything else fails with `RECIPIENT_NOT_ALLOWED`. |\n| `SN_MAX_UPLOAD_BYTES` | no | `10485760` | next | Largest decoded attachment upload, checked on the base64 length before decoding (`PAYLOAD_TOO_LARGE`). |\n| `SN_UPLOAD_MIME_ALLOW` | no | — | next | Optional allow-list of upload content types (exact, or `type/*`); others fail with `MIME_NOT_ALLOWED`. |\n| `SN_SDK_MANAGED_SCOPES` | no | — | next | P-3: comma/space-separated application scopes (namespace such as `x_acme_app`, or the `sys_scope` sys_id) you declare as managed by a ServiceNow SDK (Fluent) project. The highest source of authority for SDK-managed detection; listed in `get_status` / `check_capabilities` under `sdkManaged`. |\n| `SN_SDK_MANAGED_WRITES` | no | `warn` | next | P-22: writes into an SDK-managed scope (a record whose `sys_scope` P-3 detects as SDK-managed) from `create_record`, `update_record`, `upsert_record`, `delete_record`, `set_property`, `revert_write`, `upsert_artifact` (every record of the plan) and the Table API write sub-requests of `batch`; a create without `sys_scope` on a `sys_metadata` table is judged by the session's current application (`apps.current_app` preference; unreadable = a `sdkScopeWarning`, never a crash): `warn` previews and applies with an `sdkManaged` block naming the Fluent alternative; `deny` refuses the apply with `SDK_MANAGED_SCOPE` (the plan says `would_refuse`); `allow` skips the check. Runs after the table policy and costs nothing unless `SN_SDK_MANAGED_SCOPES` or `SN_SDK_PROJECT_DIRS` is set. |\n| `SN_SDK_PROJECT_DIRS` | no | — | next | P-3: directories (separated by commas or the platform path delimiter) scanned read-only for SDK projects: each `now.config.json` declares its `scope` / `scopeId` as SDK-managed. Bounded (depth 4, 2000 directories, 100 config files, 256 KiB per file), never follows symbolic links, skips hidden, `node_modules` and build folders, and reads nothing but `now.config.json`. |\n\n#### Results, redaction and exports\n\nResult size budgets, output shaping, redaction of record values, the write journal and CSV export safety.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_MAX_RECORDS` | no | `10000` | 1.1.0 | Hard cap on records returned by a `fetchAll` query. |\n| `SN_MAX_RESULT_CHARS` | no | `48000` | 1.1.0 | Character budget for a tool result (48,000 since O-21 (b), under Claude Code's 50,000 threshold). A larger result goes to a file while `SN_OVERSIZE_TO_FILE` is on; otherwise it is shrunk with a note naming `format:\"file\"`, and a snapshot, compare or diagram result is returned in full with a `note`. |\n| `SN_OVERSIZE_TO_FILE` | no | `true` | next | S-11 / N-61 (default on since O-21 (b)): write a `query_table` (JSON lines), snapshot, compare or diagram result over `SN_MAX_RESULT_CHARS` to a file under `SN_DOCS_DIR` (`<profile>/exports/`, `<profile>/diagrams/`) and return `{path, bytes, preview}` instead. |\n| `SN_RESULT_SIZE_HINTS` | no | `true` | next | N-65 (default on, O-21 (c)): the large readers (`document_*`, `snapshot_instance`, `compare_*`, `get_script`) carry `_meta[\"anthropic/maxResultSizeChars\"]` = `SN_MAX_RESULT_CHARS` in `tools/list`. Set `false` to drop the hints. |\n| `SN_STRUCTURED` | no | `true` | next | N-39 (default on, O-21 (d)): tools with an output shape publish `outputSchema` in `tools/list` and answer with `structuredContent` next to the JSON text. Set `false` to drop both: every result then carries its payload once, as text, and `tools/list` is smaller. |\n| `SN_INCLUDE_REF_LINKS` | no | `false` | 1.1.0 | Reference fields come back without their `link` URLs by default (token savings). Set `true` to include them. |\n| `SN_RESULT_PRETTY` | no | `false` | 1.1.0 | Tool results are compact JSON by default (pretty-printing ~doubles tokens). Set `true` for indented output. |\n| `SN_REDACT_FIELDS` | no | — | 2.0.0 | DF-5: mask these field values before records reach the model (comma/space-separated). |\n| `SN_REDACT_PII` | no | `false` | 2.0.0 | DF-5: also mask email/phone/national-id patterns inside string values. Since H-5 both redaction settings apply deeply to every tool result (success and error) and to the write journal. |\n| `SN_JOURNAL_MAX_BYTES` | no | `20971520` | next | H-5: size (bytes, default 20 MiB) at which `write-journal.jsonl` rotates to `write-journal.<ISO-time>.jsonl`; the hash chain continues across files. |\n| `SN_CSV_FORMULA_GUARD` | no | `true` | next | H-5: prefix CSV text cells that start with `=`, `+`, `-`, `@`, tab or CR with `'` so spreadsheets never evaluate them (a text `-5` exports as `'-5`). `0` opts out. |\n| `SN_CSV_BOM` | no | `true` | next | H-5: prepend a UTF-8 BOM to `format:\"csv\"` exports so Excel decodes non-ASCII text. `0` opts out. |\n\n#### Caching\n\nThe schema reads cache and the capability / plugin-API probes.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_RECORD_WATCH_INTERVAL_MS` | no | `30000` | next | N-10: poll interval of a record-watch subscription (`servicenow://profiles/<profile>/records/<table>/<sys_id>`); each poll reads `sys_updated_on` / `sys_mod_count`. Floor 30000. |\n| `SN_RECORD_WATCH_MAX_PER_SESSION` | no | `10` | next | N-10: record-watch subscriptions one client session may hold; one more is refused with `WATCH_LIMIT`. |\n| `SN_RECORD_WATCH_MAX` | no | `50` | next | N-10: record-watch subscriptions across the process (every session); one more is refused with `WATCH_LIMIT`. |\n| `SN_SCHEMA_CACHE_TTL_SEC` | no | `300` | 1.1.0 | TTL for the near-static schema reads cache (`list_tables`, `describe_table`, `get_cmdb_meta`). `0` disables caching. |\n| `SN_SCHEMA_CACHE_MAX` | no | `256` | next | Maximum entries in the schema reads cache; when full, the least-recently-used entry is evicted. Counters (`size`, `hits`, `misses`, `evictions`) appear in `get_status` under `schemaCache`. |\n| `SN_CAPABILITY_TTL_MS` | no | `600000` | next | How long a successful capability probe is cached — the `servicenow_check_capabilities` matrix and the plugin-API availability (CI/CD, Code Search, Batch…). Pass `refresh: true` to re-probe sooner. |\n| `SN_PLUGIN_NEGATIVE_TTL_MS` | no | `60000` | next | How long a failed capability probe (HTTP 401/403/404/5xx) or a missing plugin API is cached before it is tried again. Transport errors are never cached. |\n\n#### Docs store and diagrams\n\nThe local Markdown docs store (also home of the write journal — keep it out of version control) and the generated Mermaid diagrams.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_DOCS_DIR` | no | `docs/instance` | 1.0.0 | Directory the `docs` package reads/writes Markdown in. Relative paths resolve against the working directory. It also holds the per-profile write journal — add `docs/instance/` to `.gitignore` in any repository you run the server from. |\n| `SN_DOCS_MAX_FILE_BYTES` | no | `5242880` | next | Per-file size cap for the docs tools: larger writes are refused, reads return the first bytes with `truncated: true`, search skips the file. |\n| `SN_DOCS_STALE_DAYS` | no | `30` | next | `servicenow_list_docs` flags a generated document `stale` when its `sn_generated_at` is older than this many days. |\n| `SN_DOCS_SEARCH_MAX` | no | `200` | next | Most matches `servicenow_search_docs` returns; past it the result carries `truncated: true`. |\n| `SN_DIAGRAM_MAX_NODES` | no | `200` | next | Node cap for the generated Mermaid diagrams (table flow, event trace, where-used; tables in a detailed ER diagram). Nodes past it fold into one `+N more` node. |\n\n#### HTTP transport\n\nstdio (default, one local client) or Streamable HTTP for remote and agent clients. Securing the HTTP endpoint (TLS, auth, network) is the operator's job.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_TRANSPORT` | no | `stdio` | 2.0.0 | DF-6: `stdio` (default) or `http` (Streamable HTTP for remote/agent clients). |\n| `SN_PORT` | no | `3000` | 2.0.0 | DF-6: TCP port for the http transport. |\n| `SN_HTTP_HOST` | no | `127.0.0.1` | 2.0.0 | DF-6: bind address for the http transport (loopback by default). |\n| `SN_HTTP_TOKEN` | no | — | 2.0.0 | DF-6: when set, http requests must send `Authorization: Bearer <token>`. **Required** whenever `SN_HTTP_HOST` is not loopback (e.g. `0.0.0.0` in the Docker image) — without it every client that reaches the port is accepted, and a warning is logged. |\n| `SN_HTTP_OAUTH_ISSUER` | no | — | next | N-17: issuer of the OAuth 2.1 / OpenID Connect authorization server whose JWT access tokens the http transport accepts (signature checked against its JWKS; `iss`, `aud`, `exp`, `nbf` and scopes enforced). Enables RFC 9728 metadata at `/.well-known/oauth-protected-resource`. Requires `SN_HTTP_OAUTH_RESOURCE`; `SN_HTTP_TOKEN` is still accepted next to it. |\n| `SN_HTTP_OAUTH_RESOURCE` | no | — | next | N-17: this server's canonical public URI (RFC 8707 resource indicator). A token is accepted only when its `aud` names it (or an `SN_HTTP_OAUTH_AUDIENCE` value). |\n| `SN_HTTP_OAUTH_AUDIENCE` | no | — | next | N-17: extra `aud` values accepted besides `SN_HTTP_OAUTH_RESOURCE`, for an authorization server that issues its own audience identifiers. |\n| `SN_HTTP_OAUTH_JWKS_URI` | no | — | next | N-17: the issuer's JWKS URI. Unset = discovered from the issuer's OpenID Connect or RFC 8414 metadata. |\n| `SN_HTTP_OAUTH_INTROSPECTION_URI` | no | — | next | N-17: the issuer's RFC 7662 introspection endpoint. Set = opaque (non-JWT) access tokens are accepted when it answers `active` with this resource in `aud`, a `sub`, an `exp` and the required scopes; an active answer is reused for up to 60 s. Unset = JWT access tokens only. Requires `SN_HTTP_OAUTH_INTROSPECTION_CLIENT_ID` and `SN_HTTP_OAUTH_INTROSPECTION_SECRET`. |\n| `SN_HTTP_OAUTH_INTROSPECTION_CLIENT_ID` | no | — | next | N-17: this server's client id at the introspection endpoint (HTTP Basic, `client_secret_basic`). |\n| `SN_HTTP_OAUTH_INTROSPECTION_SECRET` | no | — | next | N-17: this server's client secret at the introspection endpoint. |\n| `SN_HTTP_OAUTH_SCOPES` | no | — | next | N-17: scopes every request's token must carry; published as `scopes_supported` and in the `WWW-Authenticate` challenge. A token without them gets 403 `insufficient_scope`. |\n| `SN_HTTP_OAUTH_USER_TOKENS` | no | off | next | N-17: call ServiceNow as the OAuth subject instead of the shared profile credential. Each subject links its own ServiceNow account once (Authorization Code + PKCE through a URL elicitation, callback at `/oauth/servicenow/callback` on the `SN_HTTP_OAUTH_RESOURCE` origin) with the profile's `SN_OAUTH_CLIENT_ID` / `SN_OAUTH_CLIENT_SECRET`; the refresh token is kept encrypted in `SN_HTTP_OAUTH_TOKEN_STORE`. Requires `SN_HTTP_OAUTH_ISSUER` and `SN_HTTP_OAUTH_TOKEN_KEY`. |\n| `SN_HTTP_OAUTH_USER_MATCH` | no | `email=email` | next | N-17: `<token claim>=<sys_user field>` — a linked ServiceNow account is accepted only when its `sys_user` field equals the subject's claim (case-insensitive), so nobody can link someone else's account. |\n| `SN_HTTP_OAUTH_TOKEN_KEY` | no | — | next | N-17: the AES-256-GCM key (32 bytes, base64 or hex) that encrypts the per-user refresh tokens at rest. Rotating it drops every link. |\n| `SN_HTTP_OAUTH_TOKEN_STORE` | no | `oauth-user-tokens.json` next to the env file | next | N-17: the encrypted per-user token store (written 0600, its directory 0700). |\n| `SN_HTTP_REQUIRE_TOKEN` | no | on | next | H-7 / B6: refuse to start the http transport on a non-loopback `SN_HTTP_HOST` without `SN_HTTP_TOKEN` or OAuth. Set `0` to log a warning and accept every client instead. |\n| `SN_HTTP_SESSION_TTL_SEC` | no | `1800` | next | H-7: idle TTL of an http session in seconds; an idle session is closed and its runtime disposed. `0` keeps sessions until the client sends DELETE. |\n| `SN_HTTP_MAX_SESSIONS` | no | `64` | next | H-7: cap on concurrent http sessions; a new session beyond it is refused with 503. |\n| `SN_HTTP_KEEPALIVE_MS` | no | `25000` | next | H-7: interval of the SSE keep-alive comment on an open stream (below common proxy idle timeouts). `0` disables it. |\n| `SN_HTTP_ALLOWED_HOSTS` | no | — | next | H-7: `Host` header values the http transport accepts (DNS-rebinding guard); an entry without a port matches any port. Unset = loopback names on a loopback bind, no check otherwise (warned). |\n| `SN_HTTP_ALLOWED_ORIGINS` | no | — | next | H-7: browser `Origin` values the http transport accepts (`*` = any). Unset = loopback origins only; a request without an Origin header is never refused by this check. |\n| `SN_METRICS` | no | off | next | E-5: HTTP transport only — serve Prometheus metrics at `GET /metrics`, behind `SN_HTTP_TOKEN` (disabled when no token is set). |\n\n#### Logging\n\nThe stderr log, the optional log file and the log lines mirrored to the MCP client.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_LOG_LEVEL` | no | `info` | 1.1.0 | Log verbosity on stderr: `error`, `warn`, `info`, `debug`. The legacy `LOG_LEVEL` is read when this is unset. Also read as `LOG_LEVEL`. |\n| `SN_LOG_FORMAT` | no | `json` | next | E-5: stderr log line format — `json` (one object per line) or `text` (`HH:MM:SS level message key=value`). |\n| `SN_LOG_FILE` | no | — | next | E-5: also append every log line (JSON Lines, redacted, mode 0600) to this file, with size-based rotation (`<file>.1` … `<file>.5`). Stderr keeps working. |\n| `SN_LOG_FILE_MAX_BYTES` | no | `10485760` | next | E-5: rotation threshold for `SN_LOG_FILE` (bytes). |\n| `SN_LOG_NOTIFY_RATE` | no | `20` | next | M-8: log notifications per second and client session over the MCP logging capability (burst 50, or the rate if larger). Lines over it are counted and reported in one \"N log messages suppressed\" warning per minute; stderr is never throttled. `0` = no limit. |\n| `SN_OTEL` | no | off | next | N-55: map the tool-call and HTTP `diagnostics_channel` events to OpenTelemetry spans (MCP / GenAI semantic conventions). Needs the optional peer dependency `@opentelemetry/api` and an OpenTelemetry SDK registered in the process (e.g. `node --import`); without the package one warning is logged and nothing else changes. |\n| `SN_OTEL_PROPAGATE` | no | off | next | N-55: send W3C `traceparent` / `tracestate` headers on outbound ServiceNow REST requests — the HTTP client span's context when `SN_OTEL` is on, otherwise the context the client sent in `params._meta`. Off: trace ids never leave the server. |\n\n#### Settings validation\n\nEvery setting is validated at startup. An invalid safety value is a startup error; an invalid tuning value is logged as a warning and the setting keeps its default (see `SN_STRICT_SETTINGS`).\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `SN_STRICT_SETTINGS` | no | safety settings only | next | E-4 / B5: which invalid setting values (a non-number, an unknown enum value, an out-of-range port…) stop the server with a startup error that names every offending key. Unset: only safety settings — connection, profiles, packages, policy, transport and the trust / privacy keys (`SN_ALLOWED_HOSTS`, `SN_TLS_*`, `SN_REDACT_*`, `SN_CSV_FORMULA_GUARD`); an invalid tuning value (timeouts, caps, caches, logging) logs a warning and keeps its default, as in 2.x. `1`: every invalid value is an error. `0`: none is (the default under `SN_COMPAT=2`). Unknown `SN_*` keys stay warnings. |\n\n#### Standard variables\n\nConventional variables outside the SN_ namespace that the server also honours.\n\n| Variable | Required | Default | Since | Description |\n| -------- | :------: | ------- | ----- | ----------- |\n| `HTTPS_PROXY` | no | — | next | Standard proxy for HTTPS traffic, honoured when `SN_HTTPS_PROXY` is unset (with `NO_PROXY`). Also read as `https_proxy`. |\n| `HTTP_PROXY` | no | — | next | Fallback proxy when `HTTPS_PROXY` is unset. Also read as `http_proxy`. |\n| `NO_PROXY` | no | — | next | Hosts that bypass `HTTPS_PROXY` / `HTTP_PROXY` (never `SN_HTTPS_PROXY`). Also read as `no_proxy`. |\n| `XDG_CONFIG_HOME` | no | `~/.config` | 1.1.0 | Base directory of the default env file (`$XDG_CONFIG_HOME/servicenow-mcp-ai/.env`). |\n\n<!-- GENERATED:ENV:END -->\n\n### Secrets from files\n\nEvery secret setting can be read from a file, the convention of Docker, Compose / Swarm and Kubernetes secrets: set `<KEY>_FILE` to a path and the server loads `<KEY>` from it at startup. This covers `SN_PASSWORD`, `SN_API_KEY`, `SN_BEARER_TOKEN`, `SN_OAUTH_CLIENT_SECRET`, `SN_OAUTH_REFRESH_TOKEN` and `SN_HTTP_TOKEN`, plus the per-profile forms (`SN_PROFILE_PROD_PASSWORD_FILE`, `SN_PROFILE_PROD_API_KEY_FILE`, …).\n\n- One trailing newline is trimmed, so `echo secret > file` works; other whitespace is kept.\n- Setting both `<KEY>` and `<KEY>_FILE` is a startup error that names the pair — the server never picks one silently.\n- An unreadable or empty file is a startup error that names the setting and the reason, never the content.\n- A value loaded from a file is never written back to the env file: `servicenow_set_credentials` and OAuth refresh-token rotation refuse to persist it (a rotated refresh token stays in memory with a warning) — update the file.\n- The existing file settings keep their meaning: `SN_TOKEN_FILE` (bearer token re-read on a 401), `SN_OAUTH_JWT_KEY_FILE` and the `SN_TLS_*_FILE` PEM paths are paths the server reads itself, not `<KEY>_FILE` sources.\n\n### Two-axis access policy\n\nAccess is controlled on **two independent axes**: tables and tool packages.\n\n| Axis         | Enable / deny / read-only                                | Example                                                                       |\n| ------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------- |\n| **Tables**   | `SN_TABLES_ALLOW` / `SN_TABLES_DENY` / `SN_READONLY`     | `SN_TABLES_DENY=change_request` blocks the Table API **and** (since H-4) the Change tools, which check their backing table. |\n| **Packages** | `SN_TOOL_PACKAGES` / `SN_PACKAGES_DENY` / `SN_PACKAGES_READONLY` | `SN_PACKAGES_DENY=change` removes the Change Management tools and blocks the `sn_chg_rest` plugin API, also inside a batch. |\n\nSince H-4 the plugin-backed tools (Change, Catalog, Knowledge, Email, ATF) and\nattachments (through the parent record's table) obey the table axis too; the\npackage axis still removes whole surfaces. See [Security notes](#security-notes)\nfor the full model (including how the Batch API obeys both axes).\n\n**List syntax:** table lists (`SN_TABLES_ALLOW` / `SN_TABLES_DENY`) are\ncomma-separated; package lists (`SN_TOOL_PACKAGES`, `SN_PACKAGES_DENY`,\n`SN_PACKAGES_READONLY`) accept commas **or** whitespace. Surrounding spaces are\ntrimmed in both, and table matching is case-insensitive — so\n`SN_TABLES_DENY=Change_Request, sys_user` works. Since H-11 a table entry may be\na pattern (`*` any run, `?` one character): `SN_TABLES_DENY=sys_*` blocks\n`sys_user` and leaves `incident` alone. The order is: an exact deny, an exact\nallow, a pattern deny, the protected tables (writes; since 3.0 they need the\ncall's own `apply: true` — `SN_PROTECTED_TABLES_WRITE=confirm`; `deny` refuses\nthem, `allow` lifts the rule), then the allowlist's\npatterns. Ask\n`servicenow_explain_policy({table, action})` which rule decides, or read\n`servicenow://policy`.\n\n## Run / debug\n\n- **VS Code**: open the Command Palette and start the server defined in\n  [.vscode/mcp.json](.vscode/mcp.json), then use it from Chat.\n- **MCP Inspector**: `npm run inspector`\n- **Directly**: `npm start`\n\n### Observability\n\n- **Status.** `servicenow_get_status` carries an `observability` block: per-tool\n  `{count, errors, p50, p95, totalMs}` (percentiles in ms over each tool's last 256\n  calls — memory stays bounded) plus result sizes `{bytesTotal, textBytes,\n  structuredBytes, bytesP50, bytesP95}` (UTF-8 bytes of the text blocks and of\n  `structuredContent`, the wire cost of each tool), schema-cache hits/misses, per-host retry counters,\n  queue limits and occupancy, circuit-breaker state and the last `X-RateLimit-*`\n  headers each host sent. It never calls the instance.\n- **Logs.** Logs go to stderr only (stdout is the MCP protocol). `SN_LOG_FORMAT=text`\n  switches from JSON lines to a human-readable format; `SN_LOG_FILE` also appends\n  JSON lines to a size-rotated file. Credential-named fields (`password`, `token`,\n  `authorization`, …) are masked in every sink, and the `SN_REDACT_FIELDS` /\n  `SN_REDACT_PII` rules and the secret-column masking apply on top.\n- **Tracing hooks.** Every tool call and the request loop publish on\n  [`node:diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html), so an\n  OpenTelemetry (or any) subscriber can attach without a dependency on this server.\n  Messages are built only while a channel has a subscriber:\n\n  | Channel                             | When                                           | Message fields                                                                                                        |\n  | ----------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |\n  | `servicenow-mcp:mcp.tool.call.start` | a tool call begins | `id`, `tool`, `package`, `requestId`, and `sessionId` / `traceparent` / `tracestate` when known |\n  | `servicenow-mcp:mcp.tool.call.end` | it returned a successful result | the start fields plus `profile`, `outcome` (`ok`), `ms`, `resultBytes` |\n  | `servicenow-mcp:mcp.tool.call.error` | it returned an error result or threw | the start fields plus `profile`, `outcome` (`error` / `cancelled`), `ms`, and `code` / `resultBytes` or `errorName` |\n  | `servicenow-mcp:http.request.start` | a logical request begins                       | `id`, `system`, `method`, `host`, `telemetryKey`, `url`, and `profile` / `requestId` / `sessionId` / `tool` / `callId` / `traceparent` / `tracestate` in a call |\n  | `servicenow-mcp:http.request.end`   | it resolved with an OK response                | the start fields plus `status`, `attempts`, `ms`                                                                      |\n  | `servicenow-mcp:http.request.error` | it failed                                      | the start fields plus `attempts`, `ms`, `status`, `code`, `errorName`, `errorMessage`                                 |\n  | `servicenow-mcp:http.request.retry` | an attempt is replayed (backoff, 401 re-auth) | `id`, `system`, `method`, `host`, `url`, `attempt`, `reason`, `waitMs`                                               |\n\n  `url` never includes the query string; headers, bodies and credentials are never\n  published, and `errorMessage` passes through the redaction rules.\n\n  Tool arguments and results are never published (only the result's byte count).\n  `callId` on an HTTP message is the `id` of the tool call that made it.\n  `traceparent` / `tracestate` are the W3C Trace Context the client sent in the call's\n  `params._meta`; a malformed value is dropped.\n\n- **OpenTelemetry spans.** `SN_OTEL=1` maps those channels to spans through\n  [`@opentelemetry/api`](https://www.npmjs.com/package/@opentelemetry/api), an optional\n  peer dependency (`npm install @opentelemetry/api` next to the server, plus your SDK\n  and exporter registered with `node --import`). Without the package the server logs one\n  warning and runs without spans; with `SN_OTEL` off the package is never loaded.\n  - Each tool call is a `SERVER` span named `tools/call <tool>`, a child of the client's\n    `traceparent` when it sent one. Attributes: `mcp.method.name`,\n    `gen_ai.operation.name` (`execute_tool`), `gen_ai.tool.name`, `jsonrpc.request.id`,\n    `mcp.session.id`, `network.transport`, `error.type`, plus `servicenow_mcp.package`\n    / `.profile` / `.outcome` / `.result.bytes`.\n  - Each outbound request is a `CLIENT` span named after the method, a child of its tool\n    span: `http.request.method`, `server.address`, `url.full` (no query string),\n    `http.response.status_code`, `http.request.resend_count`, `error.type`, and one\n    `retry` event per replay.\n  - The MCP and GenAI semantic conventions are still in development, so these names\n    are provisional and may follow the spec when it changes.\n  - `SN_OTEL_PROPAGATE=1` (off by default) also sends `traceparent` / `tracestate`\n    headers on requests to the ServiceNow instance: the HTTP span's context when\n    `SN_OTEL` is on, otherwise the client's context unchanged. It is opt-in because it\n    hands trace ids to the instance; the OAuth token endpoint never gets them.\n\n- **Prometheus.** With the HTTP transport, `SN_METRICS=1` and `SN_HTTP_TOKEN` set,\n  `GET /metrics` (same bearer token) serves the same figures in the Prometheus text\n  format (`servicenow_mcp_*` families, labelled by `tool` / `host` only). Without a\n  token the endpoint stays off and a warning is logged.\n\n### Command-line interface\n\nThe published `servicenow-mcp-ai` binary (run it directly, or via\n`npx servicenow-mcp-ai`) starts the MCP server when it is given no command, and\notherwise runs one of the commands below and exits. Connection settings come from\nenvironment variables / the env file (see [Environment variables](#environment-variables)).\n`servicenow-mcp-ai --help` lists everything; `--version` prints the version. An\nunknown command or option prints the usage on stderr and exits `2` — it never\nstarts the server.\n\n| Command                                         | Options                                  | What it does                                                                                                                         | Exit codes                                                  |\n| ----------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- |\n| `servicenow-mcp-ai`                             | _(none)_                                 | Starts the MCP server. The transport (`stdio` default, or `http`) is chosen by `SN_TRANSPORT`; runs until `SIGINT`/`SIGTERM`. stdout is the protocol channel. | `0` clean shutdown · `1` fatal startup error                |\n| `servicenow-mcp-ai init`                        | `--profile <name>`, `--skip-doctor`      | Interactive setup: asks for the instance, the auth method and its credentials (secrets through a hidden prompt), writes the env file, then runs `doctor`. | the `doctor` exit code · `0` with `--skip-doctor` · `2` refused / invalid answers |\n| `servicenow-mcp-ai doctor`                      | `--json`, `--ascii`, `--profile <name>`  | Health check: credentials, a live connectivity probe and the capability preflight. The first line names the env file that was used. | `0` healthy · `1` degraded or unreachable · `2` not configured |\n| `servicenow-mcp-ai login`                       | `--profile <name>`                       | One-time OAuth 2.1 Authorization Code + PKCE login: opens the browser, captures the loopback redirect, stores a refresh token.      | `0` success · `1` login failed                              |\n| `servicenow-mcp-ai drift <profileA> <profileB>` | _(none)_                                 | DF-3 CI drift gate: compares the two instances and writes a Markdown diff report.                                                  | `0` no drift · `1` drift found · `2` usage / error          |\n| `servicenow-mcp-ai support-bundle`              | `--out <file>`, `--profile <name>`       | Writes one JSON file for a bug report and prints its path on stdout.                                                               | `0` written · `1` write failed                              |\n| `servicenow-mcp-ai migrate`                     | `--write`, `--from <file>`, `--v3-defaults` | Carries 2.x settings (env file, MCP client `env` blocks) over to 3.x and prints every change; a dry run unless `--write`.         | `0` done or nothing to do · `1` refused / write failed       |\n\n**`init`** writes through the same atomic, owner-only (`0600`) env-file writer as\n`servicenow_set_credentials`, to the file `doctor` names (by default\n`~/.config/servicenow-mcp-ai/.env`). It asks, in order: the instance (`dev12345`\nor a full host; a custom domain needs `SN_ALLOWED_HOSTS`), the auth method\n(`basic` / `oauth` / `apikey` / `token`), then that method's settings — for\n`oauth` the grant (`client_credentials`, `password`, or `authorization_code`,\nwhich ends with a hint to run `login`). Secrets are never echoed or logged; the\nsummary lists key names only. With `--profile qa` the keys are written as\n`SN_PROFILE_QA_*`. An existing profile is overwritten only after a `y`. The\nanswers can be piped, one per line, which is how CI and tests drive it:\n\n```bash\nprintf 'dev12345\\nbasic\\nalice\\n%s\\n' \"$SN_PASSWORD\" | npx servicenow-mcp-ai init\n```\n\nWithout a terminal and without piped answers, `init` refuses (exit `2`) and\nwrites nothing.\n\n**`doctor`** prints plain ASCII (`[ok]` / `[x]` instead of check marks) with\n`--ascii`, when stdout is not a terminal, and on Windows outside Windows Terminal.\n`--json` prints one JSON document instead: `envFile`, `status`, `summary`,\n`checks[]` (`name`, `ok`, `detail`), `config`, `connection`, `capabilities` and\n`serverStatus` (the `servicenow_get_status` payload) — for example\n`servicenow-mcp-ai doctor --json | jq .checks`. The exit codes are the same.\n\n**`support-bundle`** collects the `doctor --json` payload, every `SN_*` setting\nwith secrets masked as `***`, `npm ls --omit=dev` (best effort), the tool\nmanifest summary (version, tool and package counts, active tools) and the last\n200 lines of `SN_LOG_FILE` when one is set. Every masked value is also scrubbed\nfrom the whole file. The default path is\n`./servicenow-mcp-ai-support-<timestamp>.json` (mode `0600`). Instance and user\nnames are **not** masked — review the file before you attach it to an issue.\n\n**`migrate`** upgrades the settings of a 2.x install. It reads the env file the\nserver resolves (or `--from <file>`) without loading it, so a file 3.x would refuse\nstill migrates, and keeps every key, value and comment except:\n\n- a project-root `.env` (deprecated, B5) or the `--from` file is copied to\n  `~/.config/servicenow-mcp-ai/.env` (or `SN_ENV_FILE`); the original stays;\n- a profile named `capabilities`, `docs`, `policy`, `profiles`, `reference`,\n  `schema` or `status` (reserved, B13) becomes `<name>_v2`, with all its\n  `SN_PROFILE_<NAME>_*` keys and `SN_ACTIVE_PROFILE`, and its docs and\n  write-journal folder `<SN_DOCS_DIR>/<name>` is renamed with it (a relative\n  `SN_DOCS_DIR` resolves against the directory you run `migrate` in; an existing\n  `<name>_v2` folder is never overwritten);\n- a value 3.x rejects at startup (B5) is commented out, so the default applies,\n  as it did in 2.x;\n- a `KEY: value` line (accepted by the 2.x parser, skipped by 3.x) becomes\n  `KEY=value`;\n- `SN_COMPAT=2` is appended unless the file sets it or `--v3-defaults` is given.\n\nSettings in an MCP client's `env` block reach the server ahead of the env file,\nso `migrate` also looks for this server in the Claude Desktop, Claude Code\n(`~/.claude.json`, `.mcp.json`), Cursor, VS Code (user and `.vscode/mcp.json`)\nand Windsurf config files, and applies the same rules to an `env` block that sets\n`SN_*` keys (an invalid value is removed). A file with comments is reported, not\nrewritten; a VS Code `envFile` is named so you can run `migrate --from` on it.\nRestart the client after a rewrite.\n\nWith `--write` each file rewritten in place is first copied to `<file>.v2.bak`\n(`0600`); an env file is `0600` too, a client file keeps its mode. Run it once\nafter the upgrade:\n\n```bash\nnpx servicenow-mcp-ai migrate          # review the plan\nnpx servicenow-mcp-ai migrate --write  # apply it\n```\n\n**`login`** operates on the active profile (`SN_ACTIVE_PROFILE`, default\n`default`) and reads, for that profile:\n\n- `SN_INSTANCE` — **required**; the target instance.\n- `SN_OAUTH_CLIENT_ID` — **required**; client id of an Authorization Code OAuth API endpoint.\n- `SN_OAUTH_CLIENT_SECRET` — optional; for a confidential client.\n- `SN_OAUTH_REDIRECT_URI` — optional; loopback URL, default `http://localhost:53682/callback`. Must match the redirect registered on the endpoint.\n- `SN_OAUTH_SCOPE` — optional; requested OAuth scope.\n\nOn success it writes `SN_AUTH=oauth`, `SN_OAUTH_GRANT=refresh_token` and\n`SN_OAUTH_REFRESH_TOKEN` back to the env file (profile-prefixed when the profile\nis not `default`). The authorization URL is printed on stderr in case the browser\ndoes not open automatically.\n\n**`drift`** takes two positional profile names; each must resolve to a configured\nprofile (`SN_PROFILE_<NAME>_*`, or the bare `SN_INSTANCE` / `SN_USER` /\n`SN_PASSWORD` keys for `default`). The Markdown report is written to **stdout**\n(capture it as a CI artifact); a one-line drift summary goes to stderr.\n\n### CI drift gate (DF-3)\n\nCompare two configured profiles and **fail a pipeline on configuration drift**:\n\n```bash\nservicenow-mcp-ai drift dev prod   # report on stdout; exit 1 on drift, 0 if clean, 2 on error\n```\n\nThe report shows each changed script as a `diff` block. The CLI compares tables,\ncolumns, scripts, plugins and apps; record sections (`sections` on\n`servicenow_compare_instances`) are opt-in, so the exit codes are unchanged.\n\n`servicenow_snapshot_instance` writes the same material to the docs folder, one\nfile per section, at most four sections at a time. An interrupted run is marked\n`partial` in `index.json`; rerun it with `resume: true` to skip every section whose\nfiles are unchanged.\n\n## Develop\n\n```bash\nnpm run check     # full gate: build, lint, format check, coverage-gated tests, tarball guard, prod audit\nnpm test          # unit tests only (node:test; needs a prior npm run build)\nnpm run lint      # ESLint (flat config + typescript-eslint)\nnpm run format    # format with Prettier\n```\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for the conventions (one commit per\ntask, tests ship with the change, generated docs).\n\n## Tools\n\nThe full reference — every parameter, the output fields, how each tool writes, and the error codes — is in [docs/tools/](docs/tools/README.md), one page per package. [docs/llms-full.txt](docs/llms-full.txt) bundles this README, SECURITY.md and that reference in one file for LLM context.\n\nEvery `inputSchema` and `outputSchema` in `tools/list` is written in JSON Schema 2020-12, the MCP default dialect, without a `$schema` field. The server supports no other dialect and never reads a schema from the client.\n\n<!-- GENERATED:TOOLS:BEGIN (npm run docs:readme) -->\n\n_This table is generated from the tool registrations — edit the tool\ndefinitions in `src/tools/`, then run `npm run docs:readme`. Every tool\nname carries the `servicenow_` prefix, left out below._\n\n| Package | Default `discovery` | Read tools | Write tools |\n| ------- | :-----------------: | ---------- | ----------- |\n| [`table`](docs/tools/table.md) | yes | `query_table`, `get_record` | `create_record`, `update_record`, `upsert_record`, `delete_record` |\n| [`schema`](docs/tools/schema.md) | yes | `list_tables`, `describe_table` | — |\n| [`aggregate`](docs/tools/aggregate.md) | yes | `aggregate` | — |\n| [`attachment`](docs/tools/attachment.md) | no | `list_attachments`, `get_attachment`, `download_attachment` | `upload_attachment`, `delete_attachment` |\n| [`importset`](docs/tools/importset.md) | no | `get_import_set_row` | `insert_import_set_row` |\n| [`batch`](docs/tools/batch.md) | no | — | `batch` |\n| [`catalog`](docs/tools/catalog.md) | no | `list_catalogs`, `list_catalog_categories`, `list_catalog_items`, `get_catalog_item` | `order_catalog_item` |\n| [`change`](docs/tools/change.md) | no | `list_changes`, `get_change` | `create_change`, `update_change`, `check_change_conflicts` |\n| [`knowledge`](docs/tools/knowledge.md) | no | `search_knowledge`, `get_knowledge_article`, `get_knowledge_highlights` | — |\n| [`cmdb`](docs/tools/cmdb.md) | no | `list_cis`, `get_ci`, `get_cmdb_meta`, `list_ci_relations` | `create_ci`, `update_ci`, `identify_reconcile` |\n| [`scripts`](docs/tools/scripts.md) | no | `list_scripts`, `get_script`, `search_code`, `describe_table_logic`, `where_used` | — |\n| [`flows`](docs/tools/flows.md) | no | `trace_table_event`, `list_flows`, `get_flow`, `get_flow_runs`, `explain_flow` | — |\n| [`codecheck`](docs/tools/codecheck.md) | no | `lint_script`, `lint_table` | `check_code_health` |\n| [`docs`](docs/tools/docs.md) | no | `list_docs`, `read_doc`, `search_docs`, `generate_er_diagram`, `generate_table_flow` | `write_doc`, `document_table`, `document_app`, `document_instance` |\n| [`instance`](docs/tools/instance.md) | no | `review_upgrade` | `snapshot_instance`, `compare_instances` |\n| [`email`](docs/tools/email.md) | no | `get_email` | `send_email` |\n| [`atf`](docs/tools/atf.md) | no | `list_atf`, `get_atf_result` | `run_atf` |\n| [`revert`](docs/tools/revert.md) | no | `list_writes` | `revert_write` |\n| [`artifacts`](docs/tools/artifacts.md) | no | `list_artifacts`, `get_artifact`, `explain_artifact`, `get_artifact_dependencies` | `upsert_artifact` |\n| [`updatesets`](docs/tools/updatesets.md) | no | `list_update_sets`, `get_update_set`, `compare_update_set` | — |\n| [`cicd`](docs/tools/cicd.md) | no | — | `commit_update_set` |\n| [`access`](docs/tools/access.md) | no | — | `change_access` |\n| [`ops`](docs/tools/ops.md) | no | `read_ops`, `check_data_health` | — |\n| [`history`](docs/tools/history.md) | no | `get_record_history`, `get_task_context` | — |\n| [`properties`](docs/tools/properties.md) | no | `get_properties` | `set_property` |\n| [`directory`](docs/tools/directory.md) | no | `lookup_directory`, `explain_access` | — |\n| [`ui`](docs/tools/ui.md) | no | `explain_portal`, `explain_ui_experience` | — |\n| [`admin`](docs/tools/admin.md) | yes | `list_instances`, `explain_policy`, `get_status`, `test_connection`, `check_capabilities`, `list_packages`, `find_tools` | `set_credentials`, `use_instance`, `enable_package`, `disable_package` |\n\n<!-- GENERATED:TOOLS:END -->\n\nAll tools carry MCP annotations (`readOnlyHint`, `destructiveHint`,\n`idempotentHint`) so clients can apply the right confirmation UX.\n\n### Tool names (v3)\n\nEvery tool is named `servicenow_<verb>_<noun>`. Parameters follow one\nvocabulary: `sys_id` is a record id, `table` is a table name (the CMDB tools\nstill accept `class_name` as a deprecated alias), `fields` is the list of\ncolumns to return, and `values` is a write payload. Version 3.0 renamed these\ntools:\n\n<!-- GENERATED:TOOL-RENAMES:BEGIN (npm run docs:readme) -->\n\n_Generated from `TOOL_RENAMES` in `src/mcp/naming.ts` — run\n`npm run docs:readme` after changing it._\n\n| v2 name                            | v3 name                                | Why                                       |\n| ---------------------------------- | -------------------------------------- | ----------------------------------------- |\n| `servicenow_artifact_dependencies` | `servicenow_get_artifact_dependencies` | No verb.                                  |\n| `servicenow_change_conflicts`      | `servicenow_check_change_conflicts`    | No verb.                                  |\n| `servicenow_code_health`           | `servicenow_check_code_health`         | No verb.                                  |\n| `servicenow_data_health`           | `servicenow_check_data_health`         | No verb; parallels check_code_health.     |\n| `servicenow_docs_list`             | `servicenow_list_docs`                 | Noun before verb.                         |\n| `servicenow_docs_read`             | `servicenow_read_doc`                  | Noun before verb.                         |\n| `servicenow_docs_search`           | `servicenow_search_docs`               | Noun before verb.                         |\n| `servicenow_docs_write`            | `servicenow_write_doc`                 | Noun before verb.                         |\n| `servicenow_knowledge_highlights`  | `servicenow_get_knowledge_highlights`  | No verb.                                  |\n| `servicenow_list_atf_suites`       | `servicenow_list_atf`                  | Merged with list_atf_tests (kind: suite). |\n| `servicenow_list_atf_tests`        | `servicenow_list_atf`                  | Merged with list_atf_suites (kind: test). |\n| `servicenow_ops_read`              | `servicenow_read_ops`                  | Noun before verb.                         |\n| `servicenow_run_atf_suite`         | `servicenow_run_atf`                   | Merged with run_atf_test (kind: suite).   |\n| `servicenow_run_atf_test`          | `servicenow_run_atf`                   | Merged with run_atf_suite (kind: test).   |\n| `servicenow_table_logic`           | `servicenow_describe_table_logic`      | No verb.                                  |\n\n<!-- GENERATED:TOOL-RENAMES:END -->\n\nA 2.x client keeps working: every old name still answers `tools/call` as a\nhidden, deprecated alias of its new tool and accepts the old parameter names,\nat no `tools/list` cost. Set `SN_LEGACY_TOOL_NAMES=1` for one minor release to\nalso list the aliases in `tools/list` and accept the old parameter names (`attachment_sys_id`, `item_sys_id`,\n`catalog_sys_id`, `test_sys_id`, `suite_sys_id`, `staging_table`, `fields` as\na write payload, `attributes`) are accepted. Each use logs one deprecation\nwarning. The tool manifest lists the renames (`toolRenames`) and each tool's\naccepted aliases.\n\nTo keep every 2.x default while you migrate, set `SN_COMPAT=2`: unset\nsettings then behave as in 2.x (protected tables writable, no plan token,\nunmapped batch rows allowed, old names listed, the `core` package set). An\nexplicit setting still wins.\n\n### Tool packages\n\nTools are grouped into packages so you can expose only what a given client needs\n(fewer tools keep the model focused). Set `SN_TOOL_PACKAGES` to a comma/space\nseparated list of profiles or package names:\n\n- `discovery` (default) — `table`, `schema`, `aggregate`, plus the always-on\n  admin tools; `servicenow_find_tools` names the package for anything else.\n  `core`, the 2.x default, is discovery plus `attachment` (B20).\n- `all` — every package below.\n- Individual packages: `table`, `schema`, `aggregate`, `attachment`,\n  `importset`, `batch`, `catalog`, `change`, `knowledge`, `cmdb`, `scripts`,\n  `flows`, `codecheck`, `docs`, `instance`, `email`, `atf`, `revert`,\n  `artifacts`, `updatesets`, `ops`, `history`, `properties`, `directory`, `ui`.\n\nThe admin tools (`servicenow_set_credentials`, `servicenow_get_status`,\n`servicenow_enable_package` and the rest of the admin package) are always\nregistered, regardless of the active packages. Unknown names are ignored.\n`servicenow_get_status` reports the resolved `enabledPackages`.\n\n```dotenv\n# Only table + batch tools (plus the always-on admin tools)\nSN_TOOL_PACKAGES=table,batch\n```\n\n#### Presets\n\nIf you would rather not curate the list yourself, three named presets cover the\ncommon roles. The admin tools are always on, so they are not listed. Each preset\nalso has a one-word alias — `SN_TOOL_PACKAGES=reader|developer|admin` — that\nexpands to the same package set.\n\n| Preset      | `SN_TOOL_PACKAGES=…`                                   | For whom                                                        |\n| ----------- | ----------------------------------------------------- | -------------------------------------------------------------- |\n| `reader`    | `table,schema,aggregate`                              | First contact, analysts, a PDI play — read and query only.     |\n| `developer` | `table,schema,aggregate,scripts,flows,codecheck,docs` | The core segment: script intelligence, flow tracing, linting, docs and diagrams. |\n| `admin`     | `all`                                                 | Everything, including the plugin and write-heavy packages.     |\n\nThe `developer` preset builds on the `reader` set; the `docs` package includes the\nMermaid diagram generators. Use the alias for brevity or spell the packages out to\nadd or drop one.\n\n#### Switching packages at runtime\n\nA client can widen or narrow its surface without a restart:\n`servicenow_list_packages` shows every package with its state for this\nsession (enabled, configured, denied, read-only, tool count), and\n`servicenow_enable_package` / `servicenow_disable_package` toggle one. The\nserver announces the change with `notifications/tools/list_changed` (and the\nprompts / resources equivalents when those change too), one per list per toggle.\nA toggle never exceeds the policy axes: a package in `SN_PACKAGES_DENY` is\nrefused (`PACKAGE_DENIED`), a package in `SN_PACKAGES_READONLY` brings only its\nread tools, and the admin tools cannot be disabled. Toggles last for the\nsession; an HTTP session that closes returns to `SN_TOOL_PACKAGES`. Nothing\nchanges unless a client calls these tools.\n\nThe server also declares `resources.subscribe`: after `servicenow_use_instance`\nor `servicenow_set_credentials` it sends `notifications/resources/list_changed`\nand, to subscribers, `notifications/resources/updated` for\n`servicenow://status`.\n\n### Upsert by key\n\n`servicenow_upsert_record({table, key, fields})` creates or updates one record\nmatched by `key`, an exact match on one or more field/value pairs (for example\n`{\"u_external_id\": \"A-17\"}`; an empty string matches an empty field). No match\ncreates a record with the key and the fields, exactly one match updates it, and\nmore than one match is refused with `AMBIGUOUS_KEY` — so is a match the user\ncannot read, since creating another would duplicate it.\n\nThe action is decided in the plan: without `apply:true` the tool returns\n`create` or `update` (with the `sys_id` and the `before` values) plus\n`apply_with: {expected_action, expected_sys_id}`. Pass those back with\n`apply:true`; if the key now resolves differently (the record appeared, went\naway or is another one) the call fails with `STALE_RECORD` and writes nothing.\nThe applied write is journaled as a create or an update, so\n`servicenow_revert_write` undoes it like a direct `create_record` /\n`update_record`.\n\n### Undo a write (journal-based revert)\n\nEvery applied write is recorded in the local, hash-chained write journal\n(`<SN_DOCS_DIR>/<profile>/write-journal.jsonl`). The opt-in `revert` package\nturns it into an undo:\n\n- `servicenow_list_writes` — the journal newest first, filtered by `profile`,\n  `table`, `since` (ISO date/time), `result` and `action`. Each row carries the\n  entry `id` and whether the line alone allows a revert (`revertible` +\n  `reason`).\n- `servicenow_revert_write` — `entry_id` → the inverse write through the Table\n  API: an **update** writes its journaled `before` values back, a **create** is\n  deleted, a **delete** is re-created from its `before` record (system fields\n  dropped, the original `sys_id` requested; the result reports\n  `sys_id_preserved`). It follows plan/apply like every write tool: without\n  `apply:true` it returns the inverse, the record's current state and the drift\n  check, and changes nothing.\n\nSafety rules:\n\n- **Drift check.** The record's `sys_mod_count` is compared with the value the\n  journaled write left (`after_mod_count`, or `before.sys_mod_count + 1`); when\n  no count is available, the written field values are compared instead. If the\n  record changed since — or nothing could be compared — the revert is refused\n  with `STALE_RECORD`; pass `force:true` to overwrite anyway (the revert's\n  journal line then records `force: true`).\n- **`NOT_REVERTIBLE`, with the reason**, when the entry is unknown, the journal\n  chain is broken, the write was not `applied`, the line has no `before` state,\n  a `before` value was redacted (`SN_REDACT_FIELDS` / `SN_REDACT_PII`), the\n  entry was already reverted, or its origin has no safe inverse: attachment\n  upload/delete, `send_email`, import set rows, catalog orders, Batch API\n  sub-requests, ATF runs, CMDB creates (IRE may have matched an existing CI) and\n  local/config entries. **A redacted value is never restored as `[redacted]`**:\n  the whole entry is refused, with no partial revert — restore those fields by\n  hand.\n- The revert is itself journaled (`reverts: <entry_id>`, `tool:\n  servicenow_revert_write`), so reverting the revert is a redo. Policy applies as\n  for a direct write: `SN_READONLY`, the table allow/deny lists and the package\n  axes of both the original package and `table`. Put `revert` in\n  `SN_PACKAGES_READONLY` to keep `list_writes` without the undo.\n\n### Update sets\n\nThe opt-in `updatesets` package reads update sets (all three tools are\nread-only and go through the table policy and redaction like every reader):\n\n- `servicenow_list_update_sets` — optional `state`, `name` fragment,\n  `application` (scope namespace, `global` or sys_id), `query`, `limit` /\n  `offset` → sets newest first, with the user's current set marked.\n- `servicenow_get_update_set` — `update_set` (sys_id or exact name) → its\n  customer updates (`sys_update_xml`) per artefact: type, target name,\n  action, table, plus counts `by_type` / `by_action`. Payloads are omitted\n  unless `include_payload: true`; they are then parsed into field values,\n  each capped at `payload_max_chars` (default 500), with secret-looking\n  fields masked.\n- `servicenow_compare_update_set` — `update_set` plus `with_profile` (read\n  live) or `with_snapshot` (a `servicenow_snapshot_instance` snapshot) → per\n  artefact `same` / `different` (differing field names only) / `missing` /\n  `not_comparable` / `not_covered` / `unknown`. Only fields in the update\n  payload are compared; audit columns are ignored.\n\nWrites: `servicenow_create_record`, `servicenow_update_record`,\n`servicenow_upsert_record` and `servicenow_delete_record` take an optional\n`update_set` (sys_id or exact name; default `SN_UPDATE_SET`). The plan\npreview names the target set; applying switches the user's `sys_update_set`\npreference (and the scope's `updateSetForScope<scope>` preference for a\nscoped set), runs the write, and restores the previous value — the result\nreports `update_set: { bound, previous, restored }` and the journal entry\nrecords `update_set`. A set that is not `in progress` is refused\n(`UPDATE_SET_NOT_IN_PROGRESS`); a data-row table (anything not extending\n`sys_metadata` and without the `update_synch` attribute) is written without\nswitching, and the plan says so. Without the argument or the setting nothing\nchanges. Other write tools (batch, catalog, change…) are not bound.\n\n### Operations and data health\n\nThe opt-in `ops` package holds two read-only tools for \"the instance is slow\"\ntriage and data quality. Every section reads its own table; an unreadable\ntable (ACL, table policy, missing table) reports `available: false` with the\nreason instead of failing the call, so a blank section never reads as healthy.\n\n- `servicenow_read_ops` — `kind`:\n  - `overview` — the counts of every section below in one call.\n  - `syslog` — entries of the last `minutes` (default 60, max 1440) at or\n    above `level` (default `warning`), optional `source` fragment: counts by\n    level, top sources and the newest rows (messages capped at 500 chars).\n  - `jobs` — the scheduler queue (`sys_trigger`) by state, the number of\n    ready jobs more than `overdue_minutes` past their next action, and the\n    `overdue` (default), `running` or `queued` jobs with their claiming node.\n  - `email_queue` — outbound `sys_email`: the send-ready backlog and its\n    oldest entry, counts by type in the window and the recent send failures.\n  - `semaphores` — `sys_semaphore` rows, newest first.\n\n  Rows are capped by `limit` (default 25, max 200).\n\n- `servicenow_check_data_health` — the data twin of `servicenow_check_code_health` for one\n  `table`, optionally scoped by `query` (no `^NQ` / `ORDERBY`): duplicate\n  groups over `key_fields` (Aggregate API grouping, count > 1, capped by\n  `limit`), and per reference field (`reference_fields`, default the first 10\n  non-system ones) the orphaned references (target row missing) and — when\n  the target has an `active` column and `stale` is not `false` — the stale\n  references (target inactive), each with the encoded query that lists the\n  rows. Field names are checked against the dictionary first. A target row\n  the user cannot read also counts as orphaned.\n\nThe `servicenow_why_is_it_slow` prompt walks through these reads and, with a\n`table`, the logic that runs on its writes.\n### Record history, properties and directory\n\nThree opt-in packages cover day-to-day operations questions. Every read goes\nthrough the table policy and redaction like every other reader.\n\n- `servicenow_get_record_history` (`history`) — `table` + `sys_id` → field\n  changes from `sys_audit` and journal entries (comments, work notes) from\n  `sys_journal_field`, merged newest first. `source` (`all` / `audit` /\n  `journal`), `fields`, `since` (`YYYY-MM-DD[ HH:MM:SS]`), `limit` (default\n  100) and `value_max_chars` (default 2000) narrow it. Audit rows that repeat\n  a journal entry are skipped. If a source cannot be read (ACL or policy), it\n  is reported under `sources` and the other one is still returned.\n- `servicenow_get_properties` (`properties`) — an exact `name` or a name\n  `prefix` → `sys_properties` rows. Password-type or secret-looking properties\n  come back as `[redacted]`, and long values are truncated.\n- `servicenow_set_property` (`properties`) — sets the value of one existing\n  property. It runs as plan/apply: the plan shows the current and the new\n  value, and apply is journaled. `servicenow_revert_write` can undo it,\n  except for secret properties, which are never journaled in clear. It honours\n  `SN_READONLY` and `SN_PACKAGES_READONLY=properties`. A missing property is\n  `PROPERTY_NOT_FOUND`; the tool never creates one.\n- `servicenow_lookup_directory` (`directory`) — `kind` (`user` / `group` /\n  `role`) plus a search `term` or a `sys_id`. With `include_details` and\n  exactly one match, the result adds:\n  - for a user, its roles and groups;\n  - for a group, its members and roles;\n  - for a role, its contained roles and the groups that grant it.\n\n  A detail table that cannot be read is listed in `details_unavailable`. Put\n  `directory` in `SN_PACKAGES_DENY` to remove the user-data surface.\n\n### Instance discovery\n\n`servicenow_document_instance` (`docs`) takes an optional `depth` that adds a\ndiscovery folder, `<SN_DOCS_DIR>/<profile>/discovery/`, next to `README.md`.\nThe tiers are cumulative:\n\n| `depth` | Files |\n| --- | --- |\n| `overview` | `overview.md` — version, counts, automation, the files written |\n| `apps` | + `apps.md` and one `tables-<scope>.md` per scope (tables and their dictionary) |\n| `artefacts` | + one `artifacts-<scope>.md` per scope |\n\nThe scopes are the named `apps`, else every non-global `sys_app` scope, up to\nthe per-run target cap (the rest are listed as skipped). `artifacts-<scope>.md`\nlists every artefact type with a **Collected / not collected and why** column:\ncollected (with a count), capped, unverified (the table is not readable here),\nno such table, unreadable for this user, package off, or no records in this\nscope. Every read goes through the same policy, redaction, capability preflight\nand write journal as the other generators. Without `depth` the tool behaves as\nbefore.\n\n### Plugin skills\n\nThe Claude Code plugin (`/plugin install servicenow-mcp-ai`) ships eight skills\nunder `skills/`. Each one only orchestrates this server's tools; none holds\ncredentials or calls ServiceNow on its own.\n\n| Skill | Use it to |\n| --- | --- |\n| `sn-discover` | Map an instance or its custom apps with `servicenow_document_instance({depth})` |\n| `sn-triage` | Investigate a failing record, flow or script (status, history, logic, logs) |\n| `sn-impact` | Assess what a change to a table, field or script would touch (where-used, table logic) |\n| `sn-drift` | Compare two instances or a saved snapshot, or review an update set |\n| `sn-safe-write` | Make a record change with plan-and-apply, the write journal and a revert path |\n| `sn-uib` | Review a UI Builder page: page map, what a change touches, data broker security, page weight |\n| `sn-upgrade` | Review upgrade readiness: unresolved skipped records, base vs customer versions, store app updates |\n| `sn-security` | Explain why a user can or cannot reach a table, record or field; review ACLs, hardening and cross-scope access |\n\nA test (`test/plugin-skills.test.js`) checks that every `servicenow_*` name in a\nskill exists in the tool manifest. The skills are not part of the npm package.\n\n#### Subagents\n\nTwo read-only subagents ship under `agents/`. Their `tools` allowlist names\nonly this server's read-only tools (`readOnlyHint`), so neither can plan,\napply, revert or switch the instance; `test/plugin-agents.test.js` enforces it.\n\n| Agent | Use it to |\n| --- | --- |\n| `sn-investigator` | Answer a question about the instance (a record, a table's automation, where something is used, a failed flow) and return a short report with its evidence instead of raw records |\n| `sn-change-reviewer` | Review a plan preview or an update set before it is applied — target records, table logic, where-used, lint, policy, history — and return a go / hold verdict |\n\nThe change reviewer has no `servicenow_check_code_health` (it writes a local\nreport); it recommends the scan when a change touches ACLs.\n\n#### Hooks\n\n`hooks/hooks.json` registers three plain Node scripts (no dependencies):\n\n| Event | Script | What it does |\n| --- | --- | --- |\n| `SessionStart` | `session-context.mjs` | Adds the active profile, its instance host, the write mode (plan / apply, read-only, a held prod profile), the tool packages and the other profile names to the session. It reads only the environment and the local env file (`SN_ENV_FILE` or `~/.config/servicenow-mcp-ai/.env`) — no network call, no credential in the output — and prints nothing when either is missing or unreadable. The server the client launches may see a different environment, so `servicenow_get_status` stays authoritative. |\n| `PreToolUse` | `require-plan-token.mjs` | Refuses a destructive `apply:true` without a `plan_token` (D-8). |\n| `PostToolUse` | `truncation-hint.mjs` | When a ServiceNow result says `truncated: true`, adds one line naming the knobs that tool has (`fields`, `offset`, `limit`, `format: \"file\"`). Silent otherwise. |\n\n#### Using the skills with other agents\n\nThe eight skills are portable [Agent Skills](https://agentskills.io): their\n`SKILL.md` frontmatter uses only `name` and `description`, and they name tools\nby their bare MCP name (`servicenow_query_table`), so any client that has this\nserver configured can run them. Copy or symlink the folders under `skills/`\ninto a directory the client scans:\n\n| Client | Project | Personal |\n| --- | --- | --- |\n| VS Code (GitHub Copilot) | `.github/skills/`, `.agents/skills/` or `.claude/skills/` | `~/.copilot/skills/`, `~/.agents/skills/` or `~/.claude/skills/` |\n| OpenAI Codex | `.agents/skills/` (in the working directory or any parent up to the repository root) | `~/.agents/skills/` |\n| Cursor | `.agents/skills/` or `.cursor/skills/` | `~/.agents/skills/` or `~/.cursor/skills/` |\n\n`.agents/skills/` works in all three. For example, from a clone of this\nrepository:\n\n```bash\nmkdir -p ~/.agents/skills\ncp -R skills/sn-* ~/.agents/skills/   # or: ln -s \"$PWD\"/skills/sn-* ~/.agents/skills/\n```\n\nIn VS Code, the extension's **ServiceNow MCP: Add Agent Skills to Workspace**\ncommand copies the eight skills into one of the project folders above (it asks\nbefore replacing a skill that is already there).\n\nThe subagents and hooks are Claude Code plugin features and do not carry over.\n\n### Service Portal tree\n\n`servicenow_explain_portal` (`ui`, opt-in) explains a Service Portal (`portal`:\n`url_suffix` or sys_id) or one page (`page`: page `id` or sys_id) as a tree.\nThe tree runs page → container → row → column → widget instance → widget. Instance\n`widget_parameters` are mapped onto the widget's `option_schema`, and each widget\nlists its dependencies, JS / CSS includes, Angular providers and templates. The\ntheme, menu, header / footer and route maps are included. Nested rows are\nfollowed to `depth` (default 3, max 6), and the layout is read for the first 5\npages. `format` is `json`, `markdown`, `mermaid` (layout tree) or `file`. A\nService Portal table that cannot be read becomes a caveat, not a failure.\n\n### UI Builder experience map\n\n`servicenow_explain_ui_experience` (`ui`, opt-in) explains a UI Builder\nexperience or workspace (`sys_id` or `path` of `sys_ux_page_registry`) as a\npage map. It reads the page properties, app config, routes, screens (with their\napplicability) and each screen's macroponent. The macroponent's composition,\ndata resources, client state and event wiring are decoded with the\n`uib-composition` decoder, and the tool lists its client scripts and its\ntransform / scriptlet data brokers, each with its `ux_data_broker` ACLs. It\nalso covers the workspace landing page, dashboards, list menus (categories,\nlists, applicability) and form action layouts. Reads are bounded, the call\nreports progress and can be cancelled. `format` is `json`, `markdown`,\n`mermaid` (page map) or `file`. Every UI Builder table and field name, and\nevery macroponent JSON shape, is unverified (U) until it is checked on a live\ninstance, so results carry `verified: false`. A table that cannot be read\nbecomes a caveat, not a failure.\n\nThe `cmdb` package also has `servicenow_list_ci_relations` (a CI's\n`cmdb_rel_ci` relationships in either direction, with the related CI's name and\nclass) and `servicenow_identify_reconcile`, which sends an IRE payload of items\nand relations. In plan mode, `servicenow_identify_reconcile` calls the\nidentify-only endpoint and shows what IRE would match; when the endpoint is\nmissing, the plan is marked `degraded`. Apply is journaled but not revertible,\nbecause IRE decides per item.\n\n`servicenow_run_atf` (a test, or a suite with `kind: \"suite\"`) takes\n`wait_seconds` (0–300). The tool polls the CI/CD progress endpoint with progress\nnotifications, and cancelling the request stops the wait. A run that is still\ngoing when the time is up returns `wait.state: \"running\"` with a `tracker`\nfor `servicenow_get_atf_result`.\n\n`servicenow_insert_import_set_row` also returns `import_set_run` (the\n`sys_import_set_run` row of the import set) and `transform_maps` (the staging\ntable's maps, the ones this row used marked `used: true`). If either follow-up\nread fails, you get `warnings` instead of an error.\n\n### Generic artifact reads\n\nThe opt-in `artifacts` package reads any type in the artifact registry (the\n`servicenow://artifact-types` resource lists them, with their tables, key\nfields and child tables):\n\n- `servicenow_list_artifacts` — `artifactType` plus optional `scope`\n  (namespace or sys_id), `active`, `query` and `limit` → summaries: sys_id,\n  name, natural key, scope, active flag, SDK-managed verdict and the type's\n  metadata. No script bodies.\n- `servicenow_get_artifact` — `artifactType` plus `sys_id` or the natural\n  `key` → the full record, its child records in registry order (a UI policy's\n  actions; a portal page's containers, rows, columns and widget instances; a\n  flow's action instances), its scope and whether that scope is SDK-managed.\n- `servicenow_explain_artifact` — same identification → a structured\n  explanation: a one-line `summary`, `when` it runs (the trigger fields that\n  are set), its non-empty `fields`, its child records as compact `items`, the\n  records it `references`, and its encoded JSON fields `decoded` (widget\n  parameters, UI Builder props and data, flow label caches). A value that\n  cannot be decoded comes back raw with `decoded: false` and a `reason` — one\n  bad field never fails the call. Long values are capped against\n  `SN_MAX_RESULT_CHARS` (a value gets at most a twentieth of it, the whole\n  explanation four fifths); `truncatedFields`, `truncated` / `preview` and\n  a child's `omitted` count say what was cut. Flow action values and UI\n  Builder compositions are read with the plain JSON decoder until their\n  dedicated decoders ship (`via: \"json\"`).\n  Some types also get an `explanation` with `lines` of prose: a state model\n  lists its states and `from -> to` transitions with their conditions, a\n  choice set or table its choices per element in sequence order, and a UI\n  policy or data policy the effect on each field when its condition holds\n  (and, with reverse-if-false, when it does not).\n- `servicenow_get_artifact_dependencies` — same identification plus `direction`\n  (`outbound` / `inbound` / `both`, default), `depth` (1–3, default 1),\n  `limit` (rows per inbound source, 1–100) and `format` (`json` or\n  `mermaid`) → a dependency graph of `nodes` and `edges` (`from` depends on\n  `to`, with `via` and `field`). Outbound edges come from registry reference\n  fields on the record and its children, decoded JSON (flow step values,\n  widget options, UI Builder data) and script text (script-include calls,\n  `GlideAjax` classes, literal `GlideRecord` tables). Inbound edges come from\n  reverse reference queries and — for a script include — script callers,\n  flow steps whose values call it and the structural pass of the where-used\n  graph. The walk visits each node once (cycles are safe), stops at 150\n  nodes (`truncated`), and turns an unreadable source into an `unavailable`\n  entry instead of an error.\n\nEvery table read obeys `SN_TABLES_ALLOW` / `SN_TABLES_DENY`; a denied child\ntable comes back as `redacted: true` instead of failing the read, and\n`SN_REDACT_FIELDS` / `SN_REDACT_PII` apply as everywhere. Types whose tables\nare not yet confirmed on a live instance carry `verified: false` and a\n`caveat`; when the instance rejects such a table the result is empty with a\n`degraded` reason instead of an error, plus `available: false` when\n`sys_db_object` shows that the table does not exist on the instance.\n\n### Artifact writes\n\n`servicenow_upsert_artifact({artifactType, key, fields, children?})` plans a\nprimary record and its child records as one unit (S-8 `create` / `update` /\n`noop` per record), then applies them parent first, each journaled with one\nshared `artifact_write` id so `servicenow_revert_write` undoes every line. The\nH-11 table policy, the P-22 SDK guard and the H-3 plan token cover every\nrecord of the plan.\n\n- **Nested children.** A child that hangs off another child names it by\n  position with `parent` (an earlier index in `children`): a portal page's\n  `sp_container` → `sp_row` → `sp_column` → `sp_instance` tree, a catalog\n  variable's `question_choice` rows, a catalog UI policy's actions. A child\n  key may be `{sys_id}`, so a `servicenow_get_artifact` result round-trips\n  unchanged. A wrong or missing `parent` is `CHILD_PARENT_INVALID`.\n- **SDK pre-flight.** Portal widgets, pages, templates, dependencies, providers,\n  headers / footers and portals, and catalog items, record producers,\n  variables, variable sets and categories are checked at plan time the way\n  the ServiceNow SDK checks them: `sp_widget.id` (across every table\n  extending it), `sp_page.id`, `sp_portal.url_suffix`, `sp_dependency` name /\n  module and `sp_ng_template.id` must be unique on the instance and within\n  the plan (`DUPLICATE_UNIQUE_FIELD`, 409); a catalog variable name must be a\n  valid identifier (`PREFLIGHT_INVALID`); a create into a scoped application\n  whose id lacks the `<scope>_` prefix gets a `SCOPE_PREFIX` warning.\n- **Flows.** A `flow` accepts only `{active}` on an existing flow — any\n  other field, a child or a create is `FLOW_ACTIVE_ONLY`. This is\n  **unverified until O-5**: that toggling `active` through the Table API\n  leaves `master_snapshot` unchanged has not been confirmed on a live\n  instance, and every flow plan carries an `UNVERIFIED` warning.\n\nThe portal and catalog write fields are unverified until O-5 (`verified:\nfalse` in the registry).\n\n### Examples\n\nQuery the 5 most recent active incidents:\n\n```jsonc\n// servicenow_query_table\n{\n  \"table\": \"incident\",\n  \"query\": \"active=true^ORDERBYDESCsys_created_on\",\n  \"fields\": [\"number\", \"short_description\", \"priority\", \"state\"],\n  \"limit\": 5,\n}\n```\n\nCreate an incident:\n\n```jsonc\n// servicenow_create_record\n{\n  \"table\": \"incident\",\n  \"values\": {\n    \"short_description\": \"Printer on 3rd floor is down\",\n    \"urgency\": \"2\",\n    \"impact\": \"2\",\n  },\n}\n```\n\nUpdate credentials at runtime:\n\n```jsonc\n// servicenow_set_credentials\n{\n  \"instance\": \"dev98765.service-now.com\",\n  \"user\": \"admin\",\n  \"password\": \"••••••\",\n}\n```\n\n## Resources\n\nRead-only metadata is also exposed as MCP resources, so clients can attach it\ndeclaratively instead of calling a tool:\n\n| URI                                     | Description                                                                                        |\n| --------------------------------------- | -------------------------------------------------------------------------------------------------- |\n| `servicenow://status`                   | Connection status, auth mode, access policy (never includes the password).                          |\n| `servicenow://capabilities`             | Capability preflight: which admin-restricted `sys_*` reads (schema, script intelligence, ACL audit) the connected user can actually achieve, plus the per-group capability matrix. |\n| `servicenow://tables`                   | List of tables from `sys_db_object`.                                                                |\n| `servicenow://schema/{table}`           | Columns of a table from `sys_dictionary` (bound to the active profile).                             |\n| `servicenow://instances`                | Configured connection profiles: name, host, user, read-only flag, credential completeness.          |\n| `servicenow://profiles/{profile}/schema/{table}` | Columns of a table read through a specific named connection profile. The v2 URI `servicenow://{profile}/schema/{table}` still works until the next minor release (deprecated). |\n| `servicenow://docs/{+path}`             | A Markdown document from the local docs store (nested paths allowed), wrapped in an untrusted-content block. |\n| `servicenow://exports/{+path}`          | A file a `format: \"file\"` result wrote (`.json`, `.jsonl`, `.csv`, `.mmd`), wrapped in an untrusted-content block. Not listed; a file delivery's `resource_link` points here when the `docs` package is off. |\n| `servicenow://artifact-types`           | Artifact types the generic artifact tools accept: table, name / key / scope fields, child tables, SDK API, verified flag (`artifacts` package). |\n| `servicenow://reference/encoded-query`  | Encoded-query reference: syntax, `javascript:` values, limits (no `^` escaping, URL length, silently ignored fields, ACL-hidden rows) and how `fetchAll` pages. |\n| `servicenow://reference/tools`          | The tool manifest as Markdown: every tool by package, read / write, and whether this session registered it under the package policy. |\n| `servicenow://reference/tools/{name}`   | One tool in full: description, annotations, the published input and output schema, an example call, package and registration state. |\n| `servicenow://profiles/{profile}/records/{table}/{sys_id}` | One record through a named profile, masked like `servicenow_get_record`. Subscribe to get `notifications/resources/updated` when it changes (polled every `SN_RECORD_WATCH_INTERVAL_MS`, floor 30 s; capped per session and per process). |\n\nResources are package-gated like tools: `status`, `capabilities` and the tool\nreference are always on; `encoded-query` and the record template come with the `table` package, `tables`/`schema` with the `schema` package, `instances`/per-profile\nschema with `instance`, and `docs` with the `docs` package. `exports` is on\nunless `docs` is denied (`SN_PACKAGES_DENY=docs`).\n\nThe three templates support completion and listing: `{table}` completes from\nthe tables already in the schema cache plus a short seed list of common\ntables, `{profile}` from the configured profiles, and `{path}` from the docs\nmanifest (`index.json`) by prefix and under the active profile's folder.\n`resources/list` shows the cached tables and the documents (generated ones\nfirst, titled from the manifest; at most 100 per template, with the docs\n`index.md` always last). Lists and completions never call the instance.\n\n## Prompts\n\nReady-made workflows are exposed as MCP prompts; they orchestrate the tools and\ninsist on reading real values from the instance. `table` and `profile`\narguments complete like the resource templates. Arguments (at most 200\ncharacters) reach the model inside an untrusted-content block, and every prompt\ntells the model to treat instance data as data, not instructions. A prompt is\nlisted only when the packages its tools live in are enabled (triage: `table`;\nchange impact: `change` or `table`; document table: `docs` and `scripts`;\nwhy is it slow: `ops`; security posture: `codecheck`; UIB page review: `ui`;\nsafe write: `table`; drift review: `instance`; schema impact: `scripts`;\ndiscover instance: `docs`; the instance overview uses admin tools only and is\nalways listed). The safe-write, drift-review, schema-impact and\ndiscover-instance prompts mirror the plugin skills `sn-safe-write`, `sn-drift`,\n`sn-impact` and `sn-discover` (triage, UIB review, upgrade review and security posture mirror\n`sn-triage`, `sn-uib`, `sn-upgrade` and `sn-security`). The list follows `servicenow_enable_package` /\n`servicenow_disable_package` live, with `notifications/prompts/list_changed`:\n\n| Prompt                              | Argument   | Purpose                                                          |\n| ----------------------------------- | ---------- | ---------------------------------------------------------------- |\n| `servicenow_incident_triage`        | `incident` | Summarize, assess priority, categorize and recommend next steps. |\n| `servicenow_change_impact_analysis` | `change`   | Affected CIs, schedule conflicts and a go/no-go call.            |\n| `servicenow_document_table`         | `table`, `profile` | Runs `servicenow_document_table`, then fills the manual Purpose block of `<profile>/tables/<table>.md`; attaches the encoded-query reference. |\n| `servicenow_why_is_it_slow`         | `symptom`, `table` (both optional) | System log, scheduler backlog, email queue and semaphores (`ops`), then the logic on a table → ranked causes. |\n| `servicenow_uib_page_review`        | `experience`, `page` (optional) | Explains the UI Builder experience (`ui`), then what a change would touch (dependencies, where-used), data broker security and page weight; steps whose package is off are skipped. |\n| `servicenow_instance_overview`      | `goal` (optional) | Capability matrix (`servicenow_check_capabilities`), status and the session's packages; the caution follows the profile's environment marker (`SN_ENV` / `SN_PROFILE_<NAME>_ENV`); an unmarked profile is treated as production. |\n| `servicenow_security_posture`      | `scope`, `profile` (both optional) | ACL scan and hardening compliance (`check_code_health`), the instance `security` document, then the cross-scope access of one app (`docs` package for the documents). |\n| `servicenow_safe_write`             | `change`, `table` (optional) | Write mode first, then read → plan → apply after approval → verify → revert path. In apply mode (`SN_WRITE_MODE=apply`) there is no preview, so the model must ask the user before every write call; a prod profile adds a caution. |\n| `servicenow_drift_review`           | `a`, `b`, `update_set` (last two optional) | Snapshot the reference profile, compare two profiles (or one with its snapshot), review an update set, then drill into differences; security-relevant drift first. |\n| `servicenow_upgrade_review`         | `upgrade` (optional) | Upgrade history, the unresolved skipped records of an upgrade, one skip's base vs customer versions, store apps with an update (`instance`), then the `upgrade` document (`docs`). |\n| `servicenow_schema_impact`          | `kind` (`table` / `field` / `script`), `name` | Where-used (structural and text), the logic and events on the table, an optional ER diagram → dependants and a risk call. |\n| `servicenow_discover_instance`      | `depth` (`overview` / `apps` / `artefacts`), `profile` (both optional) | Runs `servicenow_document_instance` at that depth, reads the result back and summarises counts, scopes and caveats. |\n\n## Project structure\n\n```\n.\n├── .env                   # credentials (git-ignored; or ~/.config/servicenow-mcp-ai/.env)\n├── .env.example           # template\n├── .github/workflows/     # CI matrix, CodeQL, npm / MCP Registry / Marketplace publishing\n├── .vscode/mcp.json       # VS Code MCP server registration\n├── bin/                   # CLI launcher (servicenow-mcp-ai.cjs, incl. the doctor command)\n├── extension/             # VS Code extension (thin wrapper that registers the server)\n├── docs/                  # GitHub Pages site\n├── scripts/               # generators + guards (README tools table, tool manifest, coverage guard)\n├── src/\n│   ├── index.ts           # bootstrap: load env, register, connect transport\n│   ├── core/              # HTTP client (auth, retry, SSRF guard), OAuth/JWT/mTLS, policy,\n│   │                      # settings, logging, config store, write journal, request\n│   │                      # context (profiles)\n│   ├── api/               # one module per REST area: table, aggregate, attachment,\n│   │                      # importset, batch, catalog, change, knowledge, cmdb, scripts,\n│   │                      # flows, codecheck, atf, email, docs, diagrams, meta, doctor,\n│   │                      # history, properties, directory, portal…\n│   ├── mcp/               # MCP surface: package registry/manifest, tool definition,\n│   │                      # resources, prompts, result envelopes, redaction, write mode\n│   │                      # (plan/apply), CSV export, stdio + HTTP transports\n│   └── tools/             # tool registrations, one file per package (28 packages)\n├── test/                  # node:test suite (406 tests): unit, mock-fetch api, MCP smoke, doc guards\n└── build/                 # compiled output (after npm run build)\n```\n\n> **Note on names:** the npm package and the GitHub repository are both\n> [`servicenow-mcp-ai`](https://github.com/IvanBBaev/servicenow-mcp-ai) (the\n> unscoped `servicenow-mcp` was already taken on npm); the local working folder\n> is `servicenow-mcp`. The difference is cosmetic and does not affect the build\n> or runtime.\n\n## Security notes\n\n- The env file is git-ignored — do not commit real credentials.\n- The env file is written **owner-only (`0600`)** — it holds a plaintext password.\n- The server uses the stdio transport and only logs to `stderr`; secrets and raw\n  encoded queries are never logged.\n- The password/token is never returned by any tool.\n- **Secret columns are always masked.** A column whose dictionary type is\n  `password`, `password2` or `glide_encrypted` (column-level encryption) comes back as `[redacted]` from\n  every record-returning tool (`query_table`, `get_record`, batch, compare,\n  exports, …) and is never stored in the write journal, whatever\n  `SN_REDACT_FIELDS` says. The types are read once per profile from\n  `sys_dictionary` and cached like other schema (`SN_SCHEMA_CACHE_TTL_SEC`);\n  when the dictionary is not readable, a list of OOTB secret column names\n  (`password`, `user_password`, `client_secret`, …) applies instead, and the\n  read goes on. This masking cannot be turned off.\n- Hosts are restricted: without `SN_ALLOWED_HOSTS`, only `*.service-now.com`\n  instances are contacted (internal/loopback blocked unless an allow-list entry\n  names the host exactly), so a mistyped host cannot silently receive\n  credentials. Redirects are never followed (`REDIRECT_BLOCKED`) and response\n  bodies are capped by `SN_MAX_BODY_BYTES`. Set `SN_ALLOWED_HOSTS` to\n  opt in a custom or sovereign-cloud domain. An explicit non-443 port or an\n  IPv6 literal in the instance value is accepted only when an allow-list entry\n  names it (`host:8443`, `[2001:db8::1]`).\n- Every request — including OAuth token requests — carries the identifying\n  `User-Agent: servicenow-mcp-ai/<version> (node/<major>; <transport>; <client>)`\n  so the instance's transaction log can attribute the traffic; extend it with\n  `SN_USER_AGENT_SUFFIX`. Proxy URLs (`SN_HTTPS_PROXY`, `HTTPS_PROXY`) are\n  honoured for every request but their credentials are never logged.\n- Prefer **OAuth 2.0** over Basic where possible (`SN_OAUTH_CLIENT_ID`).\n- Apply least privilege with `SN_TABLES_ALLOW` / `SN_TABLES_DENY` and\n  `SN_READONLY=true` for read-only deployments.\n- **Table policy does not cover plugin APIs.** `SN_TABLES_DENY=change_request`\n  blocks the Table API path, but the Change Management API (`sn_chg_rest`) can\n  still read/write changes. To restrict the plugin-backed surfaces use\n  `SN_PACKAGES_DENY` (drop the whole package) or `SN_PACKAGES_READONLY`\n  (register only its read tools). The Batch API obeys both axes too: a\n  sub-request to a denied package's path is refused, and writes to a read-only\n  package are blocked — a batch cannot be used to bypass the package policy.\n\n## Project documentation\n\n| Document | Contents |\n| -------- | -------- |\n| [ARCHITECTURE.md](project/ARCHITECTURE.md) | Layered architecture, Mermaid diagrams (modules, request lifecycle, security model, auth, packages), condensed ADRs |\n| [PRODUCT-STATE.md](project/archive/PRODUCT-STATE.md) | Current product state: API coverage map, quality status, history timeline, roadmap |\n| [ROADMAP.md](project/ROADMAP.md) | Forward plan: the shipped phases, the 2.x hardening line, the proposed 3.0 milestone, optional and deferred items |\n| [ROADMAP-V3.md](project/ROADMAP-V3.md) / [DEEP-REVIEW-2026-09.md](project/archive/DEEP-REVIEW-2026-09.md) | The proposed v3.0 execution tracker (correctness, governance, reach at scale) / the five-lens review its items are built on |\n| [GAP-ANALYSIS-2026-09.md](project/archive/GAP-ANALYSIS-2026-09.md) | The 2026-09-09 second pass over the v3.0 plan: nine narrower lenses, 67 findings each with design, acceptance criteria and tests, mapped to tracker items |\n| [INSTANCE-DOCS-ANALYSIS-2026-09.md](project/archive/INSTANCE-DOCS-ANALYSIS-2026-09.md) | The 2026-09-23 pass on instance documentation: the docs store, the Mermaid generators, the `document_table` prompt and the missing document kinds — 17 findings with design, acceptance criteria and tests, mapped to S-14 … S-16 |\n| [INSTANCE-DOCS-ANALYSIS-2026-09-25.md](project/archive/INSTANCE-DOCS-ANALYSIS-2026-09-25.md) | The 2026-09-25 second pass on instance documentation: dispositions of the first 17 findings after the docs store, artefact registry, artefact readers and security scan landed, plus 12 new findings (ID-18 … ID-29) with design, acceptance criteria and tests, mapped to S-15, S-16, M-4, M-8, S-7, E-6, E-7 |\n| [COMPETITIVE-ANALYSIS.md](project/COMPETITIVE-ANALYSIS.md) | Positioning vs the official ServiceNow MCP Server Console: comparison, where it structurally lags, the Phase 9 boost plan, and platform risks |\n| [IMPLEMENTATION-PLAN.md](project/archive/IMPLEMENTATION-PLAN.md) | Detailed specs for the upcoming phases (harness 2.0, multi-instance, flow testing) |\n| [DONE.md](project/DONE.md) / [TODO.md](project/TODO.md) | Completed work with commit refs / remaining decisions |\n| [WORKLOG.md](WORKLOG.md) / [CHANGELOG.md](CHANGELOG.md) | Detailed work journal / user-facing changelog |\n| [CONTRIBUTING.md](CONTRIBUTING.md) / [SECURITY.md](SECURITY.md) | Dev setup, gates and conventions / security model and reporting |\n\n## Support\n\nThis project is built and maintained in my own time. If it saves you or your team\ntime, please consider supporting its continued development — sponsorship directly\nfunds new tools, bug fixes and keeping pace with ServiceNow's REST surface.\n\n- **[GitHub Sponsors](https://github.com/sponsors/IvanBBaev)** — one-off or\n  recurring, with no platform fee taken out (the preferred option).\n- **[Ko-fi](https://ko-fi.com/ivanbbaev)** — quick one-off support; it also\n  accepts **PayPal**, so it's the fallback for anyone without a GitHub account.\n- **[Donate (Donatree)](https://donatr.ee/ivanbbaev/)** — a no-account donation\n  page (card, PayPal and more) for a one-off tip.\n\n[![Sponsor on GitHub](https://img.shields.io/badge/Sponsor-GitHub-ea4aaa?style=flat-square&logo=githubsponsors&logoColor=white)](https://github.com/sponsors/IvanBBaev)\n[![Support on Ko-fi](https://img.shields.io/badge/Ko--fi-Support-ff5e5b?style=flat-square&logo=kofi&logoColor=white)](https://ko-fi.com/ivanbbaev)\n[![Donate via Donatree](https://img.shields.io/badge/Donate-Donatree-22c55e?style=flat-square&logo=liberapay&logoColor=white)](https://donatr.ee/ivanbbaev/)\n\n## Trademark\n\n`servicenow-mcp-ai` is an independent, community-built project. It is **not\naffiliated with, endorsed by, or sponsored by ServiceNow, Inc.**\n\n\"ServiceNow\", the ServiceNow logo, \"Now\", and related marks are trademarks or\nregistered trademarks of ServiceNow, Inc. in the United States and other\ncountries. They are used in this project's name and documentation **only\nnominatively** — to identify the platform this software interoperates with — and\nno affiliation or endorsement is implied. All other product names and marks are\nthe property of their respective owners.\n\nCopyright (C) 2026 Ivan Baev. This project is licensed under the\n[GNU GPL v3.0 or later](LICENSE); that license covers the source code and does\nnot grant any rights to use the ServiceNow trademarks. Versions up to and\nincluding 3.0.0-beta.1 were released under the MIT License.\n"}