servicenow-mcp-ai — ServiceNow MCP Server
📖 Documentation site →
A Model Context Protocol server that lets an
MCP client (VS Code, Claude Desktop, etc.) run commands against a ServiceNow
instance through its REST APIs — Table, Aggregate, Attachment, Import Set, Batch
and CMDB, plus the Service Catalog, Change Management and Knowledge plugin APIs.
Credentials are kept in a local env file and can be updated at runtime through a tool.
Upgrading from 2.x? 3.0 has breaking defaults (plan tokens for destructive applies,
protected system tables, a smaller default tool set). Run
npx servicenow-mcp-ai migrate --write once: it carries your env file and MCP client
config over and adds SN_COMPAT=2, which keeps every 2.x default you have not set.
See the CHANGELOG → "Migration at a glance" for each change.
Upgrading from 1.x? v2.0 makes writes plan-by-default: create/update/delete
and the other record-write tools return a non-mutating preview unless you pass
apply: true (or set SN_WRITE_MODE=apply to restore the v1 "execute immediately"
behaviour). See the CHANGELOG → 2.0.0 for the full migration note.
Contents: Quick demo · Features ·
Requirements · Setup ·
Configure credentials · Run / debug ·
Develop · Tools · Resources ·
Prompts · Project structure ·
Security notes · Project documentation ·
Support
Built and maintained in my own time — if it helps, a
GitHub Sponsors tip keeps it going.
Full Support options are near the end.
Quick demo
Three things the platform makes hard, one call each. Point your MCP client at an
instance (Setup) and ask:
1. "Where is this field actually used?" — every script, business rule, client
script, UI policy/action and ACL that touches it, as JSON or a Mermaid graph. The
IDE-grade find usages ServiceNow has no button for:
2. "What runs when I save this record?" — the full automation chain in
execution order (display → before → after → async business rules, then flows,
workflows and notifications), each with its condition — a logical test that runs
nothing:
3. "What drifted between dev and prod?" — a Markdown diff of tables, columns,
scripts (matched by sys_id then name, with a unified diff of every changed script)
and plugins between two configured profiles — plus, on request, properties, choices,
ACLs, notifications, flows, catalog items and roles — with a CI-friendly exit code
so a pipeline can block a risky deploy:
All three are read-only and work against any instance — including a free PDI —
with the model and client of your choice.
Features
- Full Table API: query, read, create, update and delete records on any
table, with encoded queries, field selection and pagination.
- Extra ServiceNow APIs: Aggregate (Stats), Attachment
(list/upload/download/delete), Import Set, Batch (many REST calls in a
single request), plus table/column metadata (
sys_db_object,
sys_dictionary).
- Process & plugin APIs: CMDB (class-aware CI CRUD + meta, relationship
reads from
cmdb_rel_ci, IRE identify-and-reconcile with an identify-only
plan),
Service Catalog (browse/order items), Change Management (typed
creation + conflict detection) and Knowledge (article search).
Plugin-scoped APIs report clearly when not active on the instance.
- Script intelligence: read and search the instance's own code (business
rules, script includes, client scripts, UI policies/actions, scheduled jobs,
transform/REST scripts, ACLs, Service Portal widgets, UI pages/scripts/macros, processors, email/fix/
validation scripts, script actions, data sources, REST message functions,
transform maps/entries, catalog client scripts and dictionary calculations /
defaults) and get a table's full automation picture — all read-only over the
Table API.
servicenow_search_code returns every matching line per artefact
(up to 20, with a line of context either side) and, like
servicenow_where_used, takes an optional application scope.
servicenow_where_used also finds structural references — dictionary
reference fields, list and form layouts, catalog variables, flow inputs and
reports — in a separate structural section.
- Flow tracing & code checking (Phase 8): deterministically trace what a
table operation runs (
flows package — business rules, flows, workflows and
notifications, in order, with a Mermaid flowchart), read Flow Designer flows
and run history, explain Process Automation Designer playbooks
(servicenow_explain_flow with kind: "playbook" — lanes as Mermaid
subgraphs, activities, triggers, variants), and lint scripts against a local rule set with an aggregate
code-health report (codecheck; domains: true adds the flow, Service
Portal and legacy-workflow analysers). Run ATF tests via the CI/CD API (atf,
opt-in, non-default — the run tools execute on the instance).
- Journal-based undo (
revert): list the local write journal and revert
one applied create/update/delete — with a drift check against later edits.
- Generic artifact reads (
artifacts, opt-in): list and read any
registered artifact type — UI policies with their actions, portal pages with
their layout, flows, catalog items and more — with scope and SDK-managed
status.
- Update-set awareness (
updatesets, opt-in): list update sets, summarise
one set per artefact, compare it with another profile or a snapshot — and
bind applied Table writes to a named update set (update_set /
SN_UPDATE_SET), restoring the user's current set afterwards.
- Operations and data health (
ops, opt-in): bounded "why is it slow"
reads of the system log, the scheduler queue, the outbound email queue, the
event queue and semaphores, plus servicenow_check_data_health — duplicate
keys, orphaned and stale references for one table, from Aggregate API counts.
- Operations reads (opt-in): a record's change history from
sys_audit and
sys_journal_field (history — including the comments and work notes the
Table API reads back empty), system properties with masked secrets and a
journaled, revertible set (properties), and user / group / role lookups
with memberships (directory). ATF runs can wait for their result
(wait_seconds), and Import Set inserts report the transform run and maps.
- Self-documentation: a local Markdown knowledge base (read/write/search) plus
deterministic Mermaid generators (ER diagrams from references, record-lifecycle
flowcharts from business rules) so the server builds durable, reusable context.
- Prompts: ready-made workflows (incident triage, change impact analysis,
document a table, diagnose a slow instance, safe write, drift review, schema
impact, instance discovery) that orchestrate the tools; every plugin skill
has a prompt twin for clients without the plugin.
- Tool packages: load only the tool groups you need via
SN_TOOL_PACKAGES
(default profile discovery; all enables everything).
- Basic or OAuth 2.0 authentication over HTTPS; the password/token is
never echoed back.
- Least-privilege controls: table allow/deny lists and a global read-only mode.
- Resilience: per-request timeout, retry with backoff and
Retry-After, SSRF
guard, and a result-size guard.
- MCP tool annotations and resources, structured error payloads, and
structured logging on stderr.
- Credentials in an env file (project,
~/.config, or SN_ENV_FILE), updatable
at runtime via servicenow_set_credentials.
Requirements
- Node.js 22.12+ (enforced:
engines + a runtime guard with a clear message;
the project targets the version in .nvmrc).
Setup
From source (for development):
Or run the published package directly, without cloning:
Install in your MCP client
Every client launches the same stdio command, npx -y servicenow-mcp-ai (Node.js 22.12+),
under the server name servicenow. The one-click links and snippets below carry no
credentials: keep them in the env file (~/.config/servicenow-mcp-ai/.env, see
Configure credentials), run the one-time
npx servicenow-mcp-ai login for OAuth, or ask the assistant to call
servicenow_set_credentials once the server is connected. A real environment variable
set in a client config overrides the env file, so only add an env block when you
mean it — and never put SN_PASSWORD or other secrets into a client config you share
or commit (see SECURITY.md).
[Install in VS Code]
[Install in VS Code Insiders]
[Install in Cursor]
VS Code / VS Code Insiders
The zero-config route is the ServiceNow MCP extension from the Marketplace
(code --install-extension ivanbbaev.servicenow-mcp-ai); it registers the server in
Copilot Chat (agent mode) automatically, no mcp.json. Source: extension/.
Without the extension, add the server from a terminal (user profile):
The raw deeplinks behind the buttons (paste into a browser address bar):
Or a workspace file, .vscode/mcp.json:
Claude Code
Plugin (zero-config — installs the server wired up):
The plugin also ships eight workflow skills, two read-only subagents and three
hooks — see Plugin skills.
CLI — --scope user makes it available in every project; --env sets a
non-secret variable (the instance host) and leaves the secrets in the env file. A value set
this way wins over the env file, so drop --env if you switch instances with
servicenow_set_credentials:
Claude Desktop
claude_desktop_config.json — macOS ~/Library/Application Support/Claude/, Windows
%APPDATA%\Claude\ (Settings → Developer → Edit Config):
Restart Claude Desktop after saving.
Cursor
Use the button above, or open the deeplink directly:
Or edit ~/.cursor/mcp.json (global) / .cursor/mcp.json (project) with the same
mcpServers block as Claude Desktop.
Windsurf, Cline, JetBrains AI Assistant
All three take the Claude Desktop mcpServers block unchanged:
- Windsurf —
~/.codeium/windsurf/mcp_config.json (Cascade → MCP servers → View raw
config), then refresh the server list.
- Cline — MCP Servers icon → Configure MCP Servers opens
cline_mcp_settings.json.
- JetBrains AI Assistant — Settings → Tools → AI Assistant → Model Context Protocol
(MCP) → Add → As JSON, paste the block.
Zed
In Zed's settings.json (Zed → Settings → Open Settings):
Gemini CLI
~/.gemini/settings.json (user) or .gemini/settings.json (project):
Check it with /mcp inside a Gemini CLI session.
Codex CLI
Or ~/.codex/config.toml:
Prefer a global install (npm install -g servicenow-mcp-ai)? Replace
"command": "npx", "args": ["-y", "servicenow-mcp-ai"] with
"command": "servicenow-mcp-ai" in any snippet. The
MCP Inspector works the same way:
npx @modelcontextprotocol/inspector npx -y servicenow-mcp-ai.
The one-click links are generated from package.json by scripts/install-links.mjs
(node scripts/install-links.mjs prints them); test/install-links.test.js fails if
this README or the docs site drift from the generated strings.
Install via MCP bundle (.mcpb)
An MCP bundle is one .mcpb file with the
server and its dependencies; Claude Desktop (or any MCPB host) installs it in one click, with
no npm / npx. Its form asks for the connection keys (only SN_INSTANCE is required) and
SN_TOOL_PACKAGES; secrets are marked sensitive (kept in the OS keychain). An empty field
falls back to the env file. Every GA release attaches servicenow-mcp-ai-<version>.mcpb to
its GitHub Release —
download it and open it with Claude Desktop. To build it yourself: npm run mcpb:pack
(dist/mcpb/; -- --validate runs the official validator).
Docker
The repository ships a multi-stage Dockerfile (distroless Node 22 runtime, non-root
uid 65532). The image contains exactly what npm pack publishes plus production
dependencies, and starts the HTTP transport on 0.0.0.0:3000 by default. No image
is published to a registry yet — build it locally:
SN_HTTP_TOKEN is required for any non-loopback bind. The image binds 0.0.0.0
so the published port works; without a token (or OAuth) the server refuses to start
(3.0, B6). SN_HTTP_REQUIRE_TOKEN=0 lets it start with a warning, and then every
client that reaches the port drives your instance with the configured credentials.
Clients send Authorization: Bearer <token>; terminate TLS in front of the container.
- OAuth instead of a shared token (N-17): set
SN_HTTP_OAUTH_ISSUER (your OIDC
provider) and SN_HTTP_OAUTH_RESOURCE (this server's public URL, e.g.
https://mcp.example.com/mcp). Clients discover the issuer from
/.well-known/oauth-protected-resource and send its JWT access tokens; the token must
name the resource as its audience. Optional: SN_HTTP_OAUTH_SCOPES,
SN_HTTP_OAUTH_AUDIENCE, SN_HTTP_OAUTH_JWKS_URI. For an issuer that hands out opaque
tokens, set SN_HTTP_OAUTH_INTROSPECTION_URI plus its client id and secret (RFC 7662). By
default the instance is still called with the configured service account.
- Per-user ServiceNow access (N-17 phase 2): add
SN_HTTP_OAUTH_USER_TOKENS=true, a
32-byte SN_HTTP_OAUTH_TOKEN_KEY (base64 or hex, e.g. openssl rand -base64 32) and an
OAuth client on the instance (SN_OAUTH_CLIENT_ID / SN_OAUTH_CLIENT_SECRET, refresh
tokens enabled) whose redirect URL is /oauth/servicenow/callback on the
SN_HTTP_OAUTH_RESOURCE origin. The first call from a user returns a link to the
instance's sign-in page (URL elicitation; a 2025 session gets -32042, a client without
URL elicitation and a background task get an error carrying the link). After
the user signs in, the server checks that the account's sys_user field matches the
token's claim (SN_HTTP_OAUTH_USER_MATCH, default email=email), keeps the refresh token
AES-256-GCM encrypted in SN_HTTP_OAUTH_TOKEN_STORE, and from then on calls the instance as
that user, so ServiceNow ACLs apply per user. A user drops their own links with
DELETE /oauth/servicenow/link (their bearer token; answers { unlinked, revoked }); the
refresh tokens are also revoked on the instance, best effort. Replicas behind one
SN_HTTP_OAUTH_RESOURCE can each complete a link when they share SN_HTTP_OAUTH_TOKEN_KEY
and the store. Limit: requests authorized with SN_HTTP_TOKEN still use the shared
credential.
/data holds the docs directory (SN_DOCS_DIR=/data/docs) and the env file
(SN_ENV_FILE=/data/.env); mount a volume there to keep them.
- Every
<KEY>_FILE secret source is described in Secrets from files.
- For an MCP client that spawns the container over stdio, pass
-i -e SN_TRANSPORT=stdio
(docker run --rm -i -e SN_TRANSPORT=stdio -e SN_INSTANCE=… servicenow-mcp-ai).
- The
HEALTHCHECK is a TCP liveness probe. GET /healthz (liveness) and GET /readyz
(credentials configured) answer without the token for orchestrator probes;
GET /readyz?probe=1 also calls the instance and sits behind the token, like every
MCP route. Set SN_HTTP_ALLOWED_HOSTS to the name clients use so the Host header is
checked on a 0.0.0.0 bind.
HTTP transport: sessions, probes and shutdown
With SN_TRANSPORT=http every MCP session (one initialize) gets its own server:
- Per-session state. Enabled packages, the MCP logging level, list-changed
notifications, plan tokens, tasks and write caps belong to the session. Connection
pools, OAuth tokens and the schema cache are shared and keyed by profile + host.
servicenow_use_instance is session-scoped over HTTP. It switches the profile of
the calling session only; other sessions keep theirs and nothing is written. Pass
persist: true to also write SN_ACTIVE_PROFILE to the env file (journaled) — that
changes the default for sessions that have not switched. Over stdio the switch lasts
until the process exits; persist: true writes it there too (3.0, B12).
- Lifetime. A session ends on
DELETE or after SN_HTTP_SESSION_TTL_SEC idle
(default 30 min); a request with an ended session id gets 404 and the client
re-initializes. At most SN_HTTP_MAX_SESSIONS (64) are open at once.
- DNS-rebinding protection. The
Host header must match SN_HTTP_ALLOWED_HOSTS
(default: the loopback names on a loopback bind) and a browser Origin must match
SN_HTTP_ALLOWED_ORIGINS (default: loopback origins); otherwise 403.
- Probes.
GET /healthz → 200 {"status":"ok"} while serving. GET /readyz →
200 when credentials are configured, 503 otherwise. Both answer without the token.
GET /readyz?probe=1 (behind the token) also reads one sys_user row and returns
503 when the instance is unreachable; the result is cached for 5 s.
- Shutdown. On SIGTERM / SIGINT the listener stops accepting connections, new
requests get 503, in-flight tool calls get up to 5 s to finish, then every session is
closed and the process exits 0.
- Keep-alive. Open SSE streams get a comment every
SN_HTTP_KEEPALIVE_MS (25 s).
Quickstart
The fastest path is three lines of Basic auth — set these (in the env file or the
real environment) and you are connected:
Everything else is optional tuning; see the full
Environment variables reference for the rest.
Past a quick try, prefer OAuth over a stored password. For anything shared or
long-lived, run the one-time npx servicenow-mcp-ai login instead — it stores a
refresh token, not your password. See
Configure credentials → OAuth 2.1.
Verify your setup
Once the three variables are set, confirm the connection before you start:
- Run the
servicenow_test_connection tool — it reads one sys_user record and
reports ok, HTTP status and latency.
- Run
servicenow_check_capabilities — it previews which admin-restricted sys_*
tables the connected user can actually read.
Or do both from the shell in one shot:
Prefer to be asked? npx servicenow-mcp-ai init prompts for the instance, the
auth method and the credentials, writes the env file and runs doctor — see
Command-line interface.
Configure credentials
Credentials live in ~/.config/servicenow-mcp-ai/.env (or the file SN_ENV_FILE names):
SN_INSTANCE accepts dev12345, dev12345.service-now.com or a full https:// URL.
You can also set or change them at runtime by calling the
servicenow_set_credentials tool — the new values are written straight back to the env file.
Moving a configured profile to a different instance requires user and password in the same
call (the stored secrets are never sent to another host), and the change must be confirmed by
the client — clients without elicitation support are refused unless
SN_ALLOW_UNCONFIRMED_CREDENTIAL_CHANGE=1 is set.
The tool also sets the auth method (auth), the OAuth client id (oauth_client_id) and grant
(oauth_grant). Secrets — the API key and the OAuth client secret — are never tool arguments:
list them in request_secrets and the server asks for them through an elicitation prompt, so
they never appear in a logged tool call, the result or the write journal. A client without
elicitation support is refused (the opt-out above does not apply to secrets); set those keys in
the env file instead. The instance-change rule follows the resulting auth method: an API-key
profile needs a new API key, an OAuth client_credentials profile a new client secret, the
OAuth password grant user, password and client secret, Basic / none user and password;
bearer-token, refresh_token and jwt_bearer profiles cannot be moved with this tool.
servicenow_get_status (authWarnings), servicenow_list_instances and doctor evaluate each
profile against its own auth method — an API-key profile needs no password — and report the
method, the OAuth grant, the refresh-token state and the write mode, never a secret value. When
the refresh-token grant returns a rotated refresh token, it is written back to the env key it
was read from; if the env file cannot be written, the new token is kept in memory (lost on
restart) and a warning is logged and shown by get_status / doctor. Values the server writes
keep Windows paths literal (backslashes are single-quoted) and a CRLF env file stays CRLF. On
Windows the env file inherits its folder's ACL — restrict it yourself (for example
icacls .env /inheritance:r /grant:r "%USERNAME%:F"); the server only warns, it never runs
icacls.
The env file is resolved in this order: SN_ENV_FILE, then
~/.config/servicenow-mcp-ai/.env (XDG). A project-root .env is deprecated (3.0, B5):
if one exists while neither of the two is in use, it is still read and startup warns where to move it.
A global/npx install therefore writes to your user config rather than into
node_modules. Real environment variables always take precedence over the file.
First run: the model configures itself
At initialize the server sends instructions built from the live configuration: the enabled
packages and tool count, the write mode, the active profile and, when nothing is configured,
what is missing and how to fix it — plus pointers to the prompts, the reference resources
and large-result handling (paging, format "file"). Until then every instance tool fails with
code: "NOT_CONFIGURED" and a hint naming servicenow_set_credentials. A first session
with an empty env file looks like this (abridged):
servicenow_get_status then shows the live state: server version, uptime and transport,
policy.summary, limits, redaction, the docs directory, write counters, the profile source and
profileDetails (per-profile auth mode, write mode and missing keys) — never a secret value.
OAuth 2.1 (Authorization Code + PKCE) — recommended
Register an Authorization Code OAuth API endpoint in ServiceNow with a
loopback redirect URL (e.g. http://localhost:53682/callback), set
SN_OAUTH_CLIENT_ID (and SN_OAUTH_CLIENT_SECRET for a confidential client),
then run the one-time interactive login:
It opens the browser, you approve, and the obtained refresh token is stored
in your env file. The server then runs non-interactively (refresh_token grant) —
no password is ever stored. PKCE (S256) is always used.
The OAuth 2.0 password grant (ROPC) is deprecated in OAuth 2.1 and disabled
on many instances; prefer login. client_credentials and refresh_token
grants remain supported for service accounts. See .env.example.
Supported authentication methods
Every inbound REST auth method ServiceNow offers is covered:
Environment variables
All settings are read from the env file (SN_ENV_FILE, else
~/.config/servicenow-mcp-ai/.env) or the real process environment, which takes
precedence. Only the first three are required; the rest are optional tuning knobs.
See .env.example for a template. Every value is validated at
startup: an invalid one stops the server with an error that names every offending key
(3.0, B5), or — with SN_STRICT_SETTINGS=0 — is logged as a warning and the setting keeps
its default.
These tables are generated from the settings manifest
(src/core/settings-manifest.ts) — edit the manifest, then run
npm run docs:env.
Connection and authentication
The 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.
Secrets from files
Container secrets (D-5): FILE=/path loads from that file at startup (one trailing newline is trimmed). Setting both and 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_FILE for the ServiceNow secrets.
Profiles and the env file
The bare SN_INSTANCE / SN_USER / SN_PASSWORD keys are the 'default' profile. More instances live under SN_PROFILE__* keys; switch with SN_ACTIVE_PROFILE or the servicenow_use_instance tool.
Network, TLS and resilience
Timeouts, 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.
Tool packages
Which tools are registered. The admin tools (set_credentials, get_status, use_instance) are always on.
Access policy and write safety
Least-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.
Results, redaction and exports
Result size budgets, output shaping, redaction of record values, the write journal and CSV export safety.
Caching
The schema reads cache and the capability / plugin-API probes.
Docs store and diagrams
The local Markdown docs store (also home of the write journal — keep it out of version control) and the generated Mermaid diagrams.
HTTP transport
stdio (default, one local client) or Streamable HTTP for remote and agent clients. Securing the HTTP endpoint (TLS, auth, network) is the operator's job.
Logging
The stderr log, the optional log file and the log lines mirrored to the MCP client.
Settings validation
Every 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).
Standard variables
Conventional variables outside the SN_ namespace that the server also honours.
Secrets from files
Every 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, …).
- One trailing newline is trimmed, so
echo secret > file works; other whitespace is kept.
- Setting both
<KEY> and <KEY>_FILE is a startup error that names the pair — the server never picks one silently.
- An unreadable or empty file is a startup error that names the setting and the reason, never the content.
- 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.
- 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.
Two-axis access policy
Access is controlled on two independent axes: tables and tool packages.
Since H-4 the plugin-backed tools (Change, Catalog, Knowledge, Email, ATF) and
attachments (through the parent record's table) obey the table axis too; the
package axis still removes whole surfaces. See Security notes
for the full model (including how the Batch API obeys both axes).
List syntax: table lists (SN_TABLES_ALLOW / SN_TABLES_DENY) are
comma-separated; package lists (SN_TOOL_PACKAGES, SN_PACKAGES_DENY,
SN_PACKAGES_READONLY) accept commas or whitespace. Surrounding spaces are
trimmed in both, and table matching is case-insensitive — so
SN_TABLES_DENY=Change_Request, sys_user works. Since H-11 a table entry may be
a pattern (* any run, ? one character): SN_TABLES_DENY=sys_* blocks
sys_user and leaves incident alone. The order is: an exact deny, an exact
allow, a pattern deny, the protected tables (writes; since 3.0 they need the
call's own apply: true — SN_PROTECTED_TABLES_WRITE=confirm; deny refuses
them, allow lifts the rule), then the allowlist's
patterns. Ask
servicenow_explain_policy({table, action}) which rule decides, or read
servicenow://policy.
Run / debug
- VS Code: open the Command Palette and start the server defined in
.vscode/mcp.json, then use it from Chat.
- MCP Inspector:
npm run inspector
- Directly:
npm start
Observability
-
Status. servicenow_get_status carries an observability block: per-tool
{count, errors, p50, p95, totalMs} (percentiles in ms over each tool's last 256
calls — memory stays bounded) plus result sizes {bytesTotal, textBytes, structuredBytes, bytesP50, bytesP95} (UTF-8 bytes of the text blocks and of
structuredContent, the wire cost of each tool), schema-cache hits/misses, per-host retry counters,
queue limits and occupancy, circuit-breaker state and the last X-RateLimit-*
headers each host sent. It never calls the instance.
-
Logs. Logs go to stderr only (stdout is the MCP protocol). SN_LOG_FORMAT=text
switches from JSON lines to a human-readable format; SN_LOG_FILE also appends
JSON lines to a size-rotated file. Credential-named fields (password, token,
authorization, …) are masked in every sink, and the SN_REDACT_FIELDS /
SN_REDACT_PII rules and the secret-column masking apply on top.
-
Tracing hooks. Every tool call and the request loop publish on
node:diagnostics_channel, so an
OpenTelemetry (or any) subscriber can attach without a dependency on this server.
Messages are built only while a channel has a subscriber:
url never includes the query string; headers, bodies and credentials are never
published, and errorMessage passes through the redaction rules.
Tool arguments and results are never published (only the result's byte count).
callId on an HTTP message is the id of the tool call that made it.
traceparent / tracestate are the W3C Trace Context the client sent in the call's
params._meta; a malformed value is dropped.
-
OpenTelemetry spans. SN_OTEL=1 maps those channels to spans through
@opentelemetry/api, an optional
peer dependency (npm install @opentelemetry/api next to the server, plus your SDK
and exporter registered with node --import). Without the package the server logs one
warning and runs without spans; with SN_OTEL off the package is never loaded.
- Each tool call is a
SERVER span named tools/call <tool>, a child of the client's
traceparent when it sent one. Attributes: mcp.method.name,
gen_ai.operation.name (execute_tool), gen_ai.tool.name, jsonrpc.request.id,
mcp.session.id, network.transport, error.type, plus servicenow_mcp.package
/ .profile / .outcome / .result.bytes.
- Each outbound request is a
CLIENT span named after the method, a child of its tool
span: http.request.method, server.address, url.full (no query string),
http.response.status_code, http.request.resend_count, error.type, and one
retry event per replay.
- The MCP and GenAI semantic conventions are still in development, so these names
are provisional and may follow the spec when it changes.
SN_OTEL_PROPAGATE=1 (off by default) also sends traceparent / tracestate
headers on requests to the ServiceNow instance: the HTTP span's context when
SN_OTEL is on, otherwise the client's context unchanged. It is opt-in because it
hands trace ids to the instance; the OAuth token endpoint never gets them.
-
Prometheus. With the HTTP transport, SN_METRICS=1 and SN_HTTP_TOKEN set,
GET /metrics (same bearer token) serves the same figures in the Prometheus text
format (servicenow_mcp_* families, labelled by tool / host only). Without a
token the endpoint stays off and a warning is logged.
Command-line interface
The published servicenow-mcp-ai binary (run it directly, or via
npx servicenow-mcp-ai) starts the MCP server when it is given no command, and
otherwise runs one of the commands below and exits. Connection settings come from
environment variables / the env file (see Environment variables).
servicenow-mcp-ai --help lists everything; --version prints the version. An
unknown command or option prints the usage on stderr and exits 2 — it never
starts the server.
init writes through the same atomic, owner-only (0600) env-file writer as
servicenow_set_credentials, to the file doctor names (by default
~/.config/servicenow-mcp-ai/.env). It asks, in order: the instance (dev12345
or a full host; a custom domain needs SN_ALLOWED_HOSTS), the auth method
(basic / oauth / apikey / token), then that method's settings — for
oauth the grant (client_credentials, password, or authorization_code,
which ends with a hint to run login). Secrets are never echoed or logged; the
summary lists key names only. With --profile qa the keys are written as
SN_PROFILE_QA_*. An existing profile is overwritten only after a y. The
answers can be piped, one per line, which is how CI and tests drive it:
Without a terminal and without piped answers, init refuses (exit 2) and
writes nothing.
doctor prints plain ASCII ([ok] / [x] instead of check marks) with
--ascii, when stdout is not a terminal, and on Windows outside Windows Terminal.
--json prints one JSON document instead: envFile, status, summary,
checks[] (name, ok, detail), config, connection, capabilities and
serverStatus (the servicenow_get_status payload) — for example
servicenow-mcp-ai doctor --json | jq .checks. The exit codes are the same.
support-bundle collects the doctor --json payload, every SN_* setting
with secrets masked as ***, npm ls --omit=dev (best effort), the tool
manifest summary (version, tool and package counts, active tools) and the last
200 lines of SN_LOG_FILE when one is set. Every masked value is also scrubbed
from the whole file. The default path is
./servicenow-mcp-ai-support-<timestamp>.json (mode 0600). Instance and user
names are not masked — review the file before you attach it to an issue.
migrate upgrades the settings of a 2.x install. It reads the env file the
server resolves (or --from <file>) without loading it, so a file 3.x would refuse
still migrates, and keeps every key, value and comment except:
- a project-root
.env (deprecated, B5) or the --from file is copied to
~/.config/servicenow-mcp-ai/.env (or SN_ENV_FILE); the original stays;
- a profile named
capabilities, docs, policy, profiles, reference,
schema or status (reserved, B13) becomes <name>_v2, with all its
SN_PROFILE_<NAME>_* keys and SN_ACTIVE_PROFILE, and its docs and
write-journal folder <SN_DOCS_DIR>/<name> is renamed with it (a relative
SN_DOCS_DIR resolves against the directory you run migrate in; an existing
<name>_v2 folder is never overwritten);
- a value 3.x rejects at startup (B5) is commented out, so the default applies,
as it did in 2.x;
- a
KEY: value line (accepted by the 2.x parser, skipped by 3.x) becomes
KEY=value;
SN_COMPAT=2 is appended unless the file sets it or --v3-defaults is given.
Settings in an MCP client's env block reach the server ahead of the env file,
so migrate also looks for this server in the Claude Desktop, Claude Code
(~/.claude.json, .mcp.json), Cursor, VS Code (user and .vscode/mcp.json)
and Windsurf config files, and applies the same rules to an env block that sets
SN_* keys (an invalid value is removed). A file with comments is reported, not
rewritten; a VS Code envFile is named so you can run migrate --from on it.
Restart the client after a rewrite.
With --write each file rewritten in place is first copied to <file>.v2.bak
(0600); an env file is 0600 too, a client file keeps its mode. Run it once
after the upgrade:
login operates on the active profile (SN_ACTIVE_PROFILE, default
default) and reads, for that profile:
SN_INSTANCE — required; the target instance.
SN_OAUTH_CLIENT_ID — required; client id of an Authorization Code OAuth API endpoint.
SN_OAUTH_CLIENT_SECRET — optional; for a confidential client.
SN_OAUTH_REDIRECT_URI — optional; loopback URL, default http://localhost:53682/callback. Must match the redirect registered on the endpoint.
SN_OAUTH_SCOPE — optional; requested OAuth scope.
On success it writes SN_AUTH=oauth, SN_OAUTH_GRANT=refresh_token and
SN_OAUTH_REFRESH_TOKEN back to the env file (profile-prefixed when the profile
is not default). The authorization URL is printed on stderr in case the browser
does not open automatically.
drift takes two positional profile names; each must resolve to a configured
profile (SN_PROFILE_<NAME>_*, or the bare SN_INSTANCE / SN_USER /
SN_PASSWORD keys for default). The Markdown report is written to stdout
(capture it as a CI artifact); a one-line drift summary goes to stderr.
CI drift gate (DF-3)
Compare two configured profiles and fail a pipeline on configuration drift:
The report shows each changed script as a diff block. The CLI compares tables,
columns, scripts, plugins and apps; record sections (sections on
servicenow_compare_instances) are opt-in, so the exit codes are unchanged.
servicenow_snapshot_instance writes the same material to the docs folder, one
file per section, at most four sections at a time. An interrupted run is marked
partial in index.json; rerun it with resume: true to skip every section whose
files are unchanged.
Develop
See CONTRIBUTING.md for the conventions (one commit per
task, tests ship with the change, generated docs).
Tools
The full reference — every parameter, the output fields, how each tool writes, and the error codes — is in docs/tools/, one page per package. docs/llms-full.txt bundles this README, SECURITY.md and that reference in one file for LLM context.
Every 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.
This table is generated from the tool registrations — edit the tool
definitions in src/tools/, then run npm run docs:readme. Every tool
name carries the servicenow_ prefix, left out below.
All tools carry MCP annotations (readOnlyHint, destructiveHint,
idempotentHint) so clients can apply the right confirmation UX.
Tool names (v3)
Every tool is named servicenow_<verb>_<noun>. Parameters follow one
vocabulary: sys_id is a record id, table is a table name (the CMDB tools
still accept class_name as a deprecated alias), fields is the list of
columns to return, and values is a write payload. Version 3.0 renamed these
tools:
Generated from TOOL_RENAMES in src/mcp/naming.ts — run
npm run docs:readme after changing it.
A 2.x client keeps working: every old name still answers tools/call as a
hidden, deprecated alias of its new tool and accepts the old parameter names,
at no tools/list cost. Set SN_LEGACY_TOOL_NAMES=1 for one minor release to
also list the aliases in tools/list and accept the old parameter names (attachment_sys_id, item_sys_id,
catalog_sys_id, test_sys_id, suite_sys_id, staging_table, fields as
a write payload, attributes) are accepted. Each use logs one deprecation
warning. The tool manifest lists the renames (toolRenames) and each tool's
accepted aliases.
To keep every 2.x default while you migrate, set SN_COMPAT=2: unset
settings then behave as in 2.x (protected tables writable, no plan token,
unmapped batch rows allowed, old names listed, the core package set). An
explicit setting still wins.
Tool packages
Tools are grouped into packages so you can expose only what a given client needs
(fewer tools keep the model focused). Set SN_TOOL_PACKAGES to a comma/space
separated list of profiles or package names:
discovery (default) — table, schema, aggregate, plus the always-on
admin tools; servicenow_find_tools names the package for anything else.
core, the 2.x default, is discovery plus attachment (B20).
all — every package below.
- Individual packages:
table, schema, aggregate, attachment,
importset, batch, catalog, change, knowledge, cmdb, scripts,
flows, codecheck, docs, instance, email, atf, revert,
artifacts, updatesets, ops, history, properties, directory, ui.
The admin tools (servicenow_set_credentials, servicenow_get_status,
servicenow_enable_package and the rest of the admin package) are always
registered, regardless of the active packages. Unknown names are ignored.
servicenow_get_status reports the resolved enabledPackages.
Presets
If you would rather not curate the list yourself, three named presets cover the
common roles. The admin tools are always on, so they are not listed. Each preset
also has a one-word alias — SN_TOOL_PACKAGES=reader|developer|admin — that
expands to the same package set.
The developer preset builds on the reader set; the docs package includes the
Mermaid diagram generators. Use the alias for brevity or spell the packages out to
add or drop one.
Switching packages at runtime
A client can widen or narrow its surface without a restart:
servicenow_list_packages shows every package with its state for this
session (enabled, configured, denied, read-only, tool count), and
servicenow_enable_package / servicenow_disable_package toggle one. The
server announces the change with notifications/tools/list_changed (and the
prompts / resources equivalents when those change too), one per list per toggle.
A toggle never exceeds the policy axes: a package in SN_PACKAGES_DENY is
refused (PACKAGE_DENIED), a package in SN_PACKAGES_READONLY brings only its
read tools, and the admin tools cannot be disabled. Toggles last for the
session; an HTTP session that closes returns to SN_TOOL_PACKAGES. Nothing
changes unless a client calls these tools.
The server also declares resources.subscribe: after servicenow_use_instance
or servicenow_set_credentials it sends notifications/resources/list_changed
and, to subscribers, notifications/resources/updated for
servicenow://status.
Upsert by key
servicenow_upsert_record({table, key, fields}) creates or updates one record
matched by key, an exact match on one or more field/value pairs (for example
{"u_external_id": "A-17"}; an empty string matches an empty field). No match
creates a record with the key and the fields, exactly one match updates it, and
more than one match is refused with AMBIGUOUS_KEY — so is a match the user
cannot read, since creating another would duplicate it.
The action is decided in the plan: without apply:true the tool returns
create or update (with the sys_id and the before values) plus
apply_with: {expected_action, expected_sys_id}. Pass those back with
apply:true; if the key now resolves differently (the record appeared, went
away or is another one) the call fails with STALE_RECORD and writes nothing.
The applied write is journaled as a create or an update, so
servicenow_revert_write undoes it like a direct create_record /
update_record.
Undo a write (journal-based revert)
Every applied write is recorded in the local, hash-chained write journal
(<SN_DOCS_DIR>/<profile>/write-journal.jsonl). The opt-in revert package
turns it into an undo:
servicenow_list_writes — the journal newest first, filtered by profile,
table, since (ISO date/time), result and action. Each row carries the
entry id and whether the line alone allows a revert (revertible +
reason).
servicenow_revert_write — entry_id → the inverse write through the Table
API: an update writes its journaled before values back, a create is
deleted, a delete is re-created from its before record (system fields
dropped, the original sys_id requested; the result reports
sys_id_preserved). It follows plan/apply like every write tool: without
apply:true it returns the inverse, the record's current state and the drift
check, and changes nothing.
Safety rules:
- Drift check. The record's
sys_mod_count is compared with the value the
journaled write left (after_mod_count, or before.sys_mod_count + 1); when
no count is available, the written field values are compared instead. If the
record changed since — or nothing could be compared — the revert is refused
with STALE_RECORD; pass force:true to overwrite anyway (the revert's
journal line then records force: true).
NOT_REVERTIBLE, with the reason, when the entry is unknown, the journal
chain is broken, the write was not applied, the line has no before state,
a before value was redacted (SN_REDACT_FIELDS / SN_REDACT_PII), the
entry was already reverted, or its origin has no safe inverse: attachment
upload/delete, send_email, import set rows, catalog orders, Batch API
sub-requests, ATF runs, CMDB creates (IRE may have matched an existing CI) and
local/config entries. A redacted value is never restored as [redacted]:
the whole entry is refused, with no partial revert — restore those fields by
hand.
- The revert is itself journaled (
reverts: <entry_id>, tool: servicenow_revert_write), so reverting the revert is a redo. Policy applies as
for a direct write: SN_READONLY, the table allow/deny lists and the package
axes of both the original package and table. Put revert in
SN_PACKAGES_READONLY to keep list_writes without the undo.
Update sets
The opt-in updatesets package reads update sets (all three tools are
read-only and go through the table policy and redaction like every reader):
servicenow_list_update_sets — optional state, name fragment,
application (scope namespace, global or sys_id), query, limit /
offset → sets newest first, with the user's current set marked.
servicenow_get_update_set — update_set (sys_id or exact name) → its
customer updates (sys_update_xml) per artefact: type, target name,
action, table, plus counts by_type / by_action. Payloads are omitted
unless include_payload: true; they are then parsed into field values,
each capped at payload_max_chars (default 500), with secret-looking
fields masked.
servicenow_compare_update_set — update_set plus with_profile (read
live) or with_snapshot (a servicenow_snapshot_instance snapshot) → per
artefact same / different (differing field names only) / missing /
not_comparable / not_covered / unknown. Only fields in the update
payload are compared; audit columns are ignored.
Writes: servicenow_create_record, servicenow_update_record,
servicenow_upsert_record and servicenow_delete_record take an optional
update_set (sys_id or exact name; default SN_UPDATE_SET). The plan
preview names the target set; applying switches the user's sys_update_set
preference (and the scope's updateSetForScope<scope> preference for a
scoped set), runs the write, and restores the previous value — the result
reports update_set: { bound, previous, restored } and the journal entry
records update_set. A set that is not in progress is refused
(UPDATE_SET_NOT_IN_PROGRESS); a data-row table (anything not extending
sys_metadata and without the update_synch attribute) is written without
switching, and the plan says so. Without the argument or the setting nothing
changes. Other write tools (batch, catalog, change…) are not bound.
Operations and data health
The opt-in ops package holds two read-only tools for "the instance is slow"
triage and data quality. Every section reads its own table; an unreadable
table (ACL, table policy, missing table) reports available: false with the
reason instead of failing the call, so a blank section never reads as healthy.
-
servicenow_read_ops — kind:
overview — the counts of every section below in one call.
syslog — entries of the last minutes (default 60, max 1440) at or
above level (default warning), optional source fragment: counts by
level, top sources and the newest rows (messages capped at 500 chars).
jobs — the scheduler queue (sys_trigger) by state, the number of
ready jobs more than overdue_minutes past their next action, and the
overdue (default), running or queued jobs with their claiming node.
email_queue — outbound sys_email: the send-ready backlog and its
oldest entry, counts by type in the window and the recent send failures.
events — the event queue (sysevent): the ready backlog and its oldest
entry (all-time), the events fired in the window by state and by name,
and the newest rows with their parameters (clipped). A notification is an
event processed into sys_email, so an unfired one is traced here first,
then in email_queue.
semaphores — sys_semaphore rows, newest first.
Rows are capped by limit (default 25, max 200).
-
servicenow_check_data_health — the data twin of servicenow_check_code_health for one
table, optionally scoped by query (no ^NQ / ORDERBY): duplicate
groups over key_fields (Aggregate API grouping, count > 1, capped by
limit), and per reference field (reference_fields, default the first 10
non-system ones) the orphaned references (target row missing) and — when
the target has an active column and stale is not false — the stale
references (target inactive), each with the encoded query that lists the
rows. Field names are checked against the dictionary first. A target row
the user cannot read also counts as orphaned.
The servicenow_why_is_it_slow prompt walks through these reads and, with a
table, the logic that runs on its writes; servicenow_incident_rca reads the
error log and the events around one record.
Record history, properties and directory
Three opt-in packages cover day-to-day operations questions. Every read goes
through the table policy and redaction like every other reader.
-
servicenow_get_record_history (history) — table + sys_id → field
changes from sys_audit and journal entries (comments, work notes) from
sys_journal_field, merged newest first. source (all / audit /
journal), fields, since (YYYY-MM-DD[ HH:MM:SS]), limit (default
100) and value_max_chars (default 2000) narrow it. Audit rows that repeat
a journal entry are skipped. If a source cannot be read (ACL or policy), it
is reported under sources and the other one is still returned.
-
servicenow_get_properties (properties) — an exact name or a name
prefix → sys_properties rows. Password-type or secret-looking properties
come back as [redacted], and long values are truncated.
-
servicenow_set_property (properties) — sets the value of one existing
property. It runs as plan/apply: the plan shows the current and the new
value, and apply is journaled. servicenow_revert_write can undo it,
except for secret properties, which are never journaled in clear. It honours
SN_READONLY and SN_PACKAGES_READONLY=properties. A missing property is
PROPERTY_NOT_FOUND; the tool never creates one.
-
servicenow_lookup_directory (directory) — kind (user / group /
role) plus a search term or a sys_id. With include_details and
exactly one match, the result adds:
- for a user, its roles and groups;
- for a group, its members and roles;
- for a role, its contained roles and the groups that grant it.
A detail table that cannot be read is listed in details_unavailable. Put
directory in SN_PACKAGES_DENY to remove the user-data surface.
Instance discovery
servicenow_document_instance (docs) takes an optional depth that adds a
discovery folder, <SN_DOCS_DIR>/<profile>/discovery/, next to README.md.
The tiers are cumulative:
The scopes are the named apps, else every non-global sys_app scope, up to
the per-run target cap (the rest are listed as skipped). artifacts-<scope>.md
lists every artefact type with a Collected / not collected and why column:
collected (with a count), capped, unverified (the table is not readable here),
no such table, unreadable for this user, package off, or no records in this
scope. Every read goes through the same policy, redaction, capability preflight
and write journal as the other generators. Without depth the tool behaves as
before.
Plugin skills
The Claude Code plugin (/plugin install servicenow-mcp-ai) ships eight skills
under skills/. Each one only orchestrates this server's tools; none holds
credentials or calls ServiceNow on its own.
A test (test/plugin-skills.test.js) checks that every servicenow_* name in a
skill exists in the tool manifest. The npm package carries the same skills
under build/skills/, which the server publishes over MCP (below).
Skills over MCP
With the docs package on, the server serves the eight skills through the
Skills extension
(SEP-2640, io.modelcontextprotocol/skills): skills/list returns each
skill's frontmatter and its files with a sha256 digest and byte size,
skills/get returns one skill by URI, and every file reads as a
skill://<name>/<path> resource (each SKILL.md is also in resources/list).
The extension is declared unless docs is denied; while docs is off the
catalog is empty. Whether a client loads skills this way depends on the
client — the folder copy below works everywhere.
Subagents
Two read-only subagents ship under agents/. Their tools allowlist names
only this server's read-only tools (readOnlyHint), so neither can plan,
apply, revert or switch the instance; test/plugin-agents.test.js enforces it.
The change reviewer has no servicenow_check_code_health (it writes a local
report); it recommends the scan when a change touches ACLs.
Hooks
hooks/hooks.json registers three plain Node scripts (no dependencies):
Using the skills with other agents
The eight skills are portable Agent Skills: their
SKILL.md frontmatter uses only name and description, and they name tools
by their bare MCP name (servicenow_query_table), so any client that has this
server configured can run them. The npm package carries them, and
skills install copies them into the folder an agent scans — in the current
directory, or in your home directory with --global:
A skill that is already there is kept (and named in the output) unless you
pass --force.
.agents/skills/ works in Copilot, Codex, Cursor and Gemini CLI. From a clone
of this repository you can also copy or symlink the folders under skills/
yourself:
In VS Code, the extension's ServiceNow MCP: Add Agent Skills to Workspace
command copies the eight skills into one of the project folders above (it asks
before replacing a skill that is already there).
The subagents and hooks are Claude Code plugin features and do not carry over.
Service Portal tree
servicenow_explain_portal (ui, opt-in) explains a Service Portal (portal:
url_suffix or sys_id) or one page (page: page id or sys_id) as a tree.
The tree runs page → container → row → column → widget instance → widget. Instance
widget_parameters are mapped onto the widget's option_schema, and each widget
lists its dependencies, JS / CSS includes, Angular providers and templates. The
theme, menu, header / footer and route maps are included. Nested rows are
followed to depth (default 3, max 6), and the layout is read for the first 5
pages. format is json, markdown, mermaid (layout tree) or file. A
Service Portal table that cannot be read becomes a caveat, not a failure.
UI Builder experience map
servicenow_explain_ui_experience (ui, opt-in) explains a UI Builder
experience or workspace (sys_id or path of sys_ux_page_registry) as a
page map. It reads the page properties, app config, routes, screens (with their
applicability) and each screen's macroponent. The macroponent's composition,
data resources, client state and event wiring are decoded with the
uib-composition decoder, and the tool lists its client scripts and its
transform / scriptlet data brokers, each with its ux_data_broker ACLs. It
also covers the workspace landing page, dashboards, list menus (categories,
lists, applicability) and form action layouts. Reads are bounded, the call
reports progress and can be cancelled. format is json, markdown,
mermaid (page map) or file. Every UI Builder table and field name, and
every macroponent JSON shape, is unverified (U) until it is checked on a live
instance, so results carry verified: false. A table that cannot be read
becomes a caveat, not a failure.
The cmdb package also has servicenow_list_ci_relations (a CI's
cmdb_rel_ci relationships in either direction, with the related CI's name and
class) and servicenow_identify_reconcile, which sends an IRE payload of items
and relations. In plan mode, servicenow_identify_reconcile calls the
identify-only endpoint and shows what IRE would match; when the endpoint is
missing, the plan is marked degraded. Apply is journaled but not revertible,
because IRE decides per item.
servicenow_run_atf (a test, or a suite with kind: "suite") takes
wait_seconds (0–300). The tool polls the CI/CD progress endpoint with progress
notifications, and cancelling the request stops the wait. A run that is still
going when the time is up returns wait.state: "running" with a tracker
for servicenow_get_atf_result.
servicenow_insert_import_set_row takes one row (values), several (rows,
up to 500) or a file (file_path): a .csv with a header row or a .jsonl
with one object per line, under SN_DOCS_DIR like an upload (the same path
confinement, symlink check and journal-file refusal; SN_DOCS_MAX_FILE_BYTES
is checked on the stat before the read). Several rows go through
POST /api/now/import/{table}/insertMultiple in one request; an instance
without that endpoint (404 / 405) gets one request per row, and the call stops
at the first row that fails (failed: { index, error }, sent of rows
inserted). The write journal holds one envelope line per call (row count,
columns, the file and a sha256 of the rows; its write-cap weight is the row
count) and, in the sequential mode, one line per sent row under the envelope's
batch_id. The plan preview shows row_count, columns and the first row,
never the whole file. The result also returns import_set_run (the
sys_import_set_run row of the last import set) and transform_maps (the
staging table's maps, the ones the rows used marked used: true). If either
follow-up read fails, you get warnings instead of an error.
insertMultiple keeps the values only when the staging table has an active
sys_rest_insert_multiple record with a column mapping
(sys_rest_insert_multiple_column_mapping; pick Column name when the
rows are keyed by column name). Without one the instance creates the rows and
leaves every column empty, so the result then carries a warnings entry
saying so (verified on a PDI).
Generic artifact reads
The opt-in artifacts package reads any type in the artifact registry (the
servicenow://artifact-types resource lists them, with their tables, key
fields and child tables):
servicenow_list_artifacts — artifactType plus optional scope
(namespace or sys_id), active, query and limit → summaries: sys_id,
name, natural key, scope, active flag, SDK-managed verdict and the type's
metadata. No script bodies.
servicenow_get_artifact — artifactType plus sys_id or the natural
key → the full record, its child records in registry order (a UI policy's
actions; a portal page's containers, rows, columns and widget instances; a
flow's action instances), its scope and whether that scope is SDK-managed.
servicenow_explain_artifact — same identification → a structured
explanation: a one-line summary, when it runs (the trigger fields that
are set), its non-empty fields, its child records as compact items, the
records it references, and its encoded JSON fields decoded (widget
parameters, UI Builder props and data, flow label caches). A value that
cannot be decoded comes back raw with decoded: false and a reason — one
bad field never fails the call. Long values are capped against
SN_MAX_RESULT_CHARS (a value gets at most a twentieth of it, the whole
explanation four fifths); truncatedFields, truncated / preview and
a child's omitted count say what was cut. Flow action values and UI
Builder compositions are read with the plain JSON decoder until their
dedicated decoders ship (via: "json").
Some types also get an explanation with lines of prose: a state model
lists its states and from -> to transitions with their conditions, a
choice set or table its choices per element in sequence order, and a UI
policy or data policy the effect on each field when its condition holds
(and, with reverse-if-false, when it does not).
servicenow_get_artifact_dependencies — same identification plus direction
(outbound / inbound / both, default), depth (1–3, default 1),
limit (rows per inbound source, 1–100) and format (json or
mermaid) → a dependency graph of nodes and edges (from depends on
to, with via and field). Outbound edges come from registry reference
fields on the record and its children, decoded JSON (flow step values,
widget options, UI Builder data) and script text (script-include calls,
GlideAjax classes, literal GlideRecord tables). Inbound edges come from
reverse reference queries and — for a script include — script callers,
flow steps whose values call it and the structural pass of the where-used
graph. The walk visits each node once (cycles are safe), stops at 150
nodes (truncated), and turns an unreadable source into an unavailable
entry instead of an error.
Every table read obeys SN_TABLES_ALLOW / SN_TABLES_DENY; a denied child
table comes back as redacted: true instead of failing the read, and
SN_REDACT_FIELDS / SN_REDACT_PII apply as everywhere. Types whose tables
are not yet confirmed on a live instance carry verified: false and a
caveat; when the instance rejects such a table the result is empty with a
degraded reason instead of an error, plus available: false when
sys_db_object shows that the table does not exist on the instance.
Artifact writes
servicenow_upsert_artifact({artifactType, key, fields, children?}) plans a
primary record and its child records as one unit (S-8 create / update /
noop per record), then applies them parent first, each journaled with one
shared artifact_write id so servicenow_revert_write undoes every line. The
H-11 table policy, the P-22 SDK guard and the H-3 plan token cover every
record of the plan.
- Nested children. A child that hangs off another child names it by
position with
parent (an earlier index in children): a portal page's
sp_container → sp_row → sp_column → sp_instance tree, a catalog
variable's question_choice rows, a catalog UI policy's actions. A child
key may be {sys_id}, so a servicenow_get_artifact result round-trips
unchanged. A wrong or missing parent is CHILD_PARENT_INVALID.
- SDK pre-flight. Portal widgets, pages, templates, dependencies, providers,
headers / footers and portals, and catalog items, record producers,
variables, variable sets and categories are checked at plan time the way
the ServiceNow SDK checks them:
sp_widget.id (across every table
extending it), sp_page.id, sp_portal.url_suffix, sp_dependency name /
module and sp_ng_template.id must be unique on the instance and within
the plan (DUPLICATE_UNIQUE_FIELD, 409); a catalog variable name must be a
valid identifier (PREFLIGHT_INVALID); a create into a scoped application
whose id lacks the <scope>_ prefix gets a SCOPE_PREFIX warning.
- Flows. A
flow accepts only {active} on an existing flow — any
other field, a child or a create is FLOW_ACTIVE_ONLY. This is
unverified until O-5: that toggling active through the Table API
leaves master_snapshot unchanged has not been confirmed on a live
instance, and every flow plan carries an UNVERIFIED warning.
The portal and catalog write fields are unverified until O-5 (verified: false in the registry).
Examples
Query the 5 most recent active incidents:
Create an incident:
Update credentials at runtime:
Resources
Read-only metadata is also exposed as MCP resources, so clients can attach it
declaratively instead of calling a tool:
Resources are package-gated like tools: status, capabilities and the tool
reference are always on; encoded-query and the record template come with the table package, tables/schema with the schema package, instances/per-profile
schema with instance, and docs and skill:// with the docs package. exports is on
unless docs is denied (SN_PACKAGES_DENY=docs).
The three templates support completion and listing: {table} completes from
the tables already in the schema cache plus a short seed list of common
tables, {profile} from the configured profiles, and {path} from the docs
manifest (index.json) by prefix and under the active profile's folder.
resources/list shows the cached tables and the documents (generated ones
first, titled from the manifest; at most 100 per template, with the docs
index.md always last). Lists and completions never call the instance.
Prompts
Ready-made workflows are exposed as MCP prompts; they orchestrate the tools and
insist on reading real values from the instance. table and profile
arguments complete like the resource templates. Arguments (at most 200
characters) reach the model inside an untrusted-content block, and every prompt
tells the model to treat instance data as data, not instructions. A prompt is
listed only when the packages its tools live in are enabled (triage: table;
change impact: change or table; document table: docs and scripts;
why is it slow: ops; security posture: codecheck; UIB page review: ui;
safe write: table; drift review: instance; schema impact: scripts;
discover instance: docs; the instance overview uses admin tools only and is
always listed). The safe-write, drift-review, schema-impact and
discover-instance prompts mirror the plugin skills sn-safe-write, sn-drift,
sn-impact and sn-discover (triage, UIB review, upgrade review and security posture mirror
sn-triage, sn-uib, sn-upgrade and sn-security). The list follows servicenow_enable_package /
servicenow_disable_package live, with notifications/prompts/list_changed:
Project structure
Note on names: the npm package and the GitHub repository are both
servicenow-mcp-ai (the
unscoped servicenow-mcp was already taken on npm); the local working folder
is servicenow-mcp. The difference is cosmetic and does not affect the build
or runtime.
Security notes
- The env file is git-ignored — do not commit real credentials.
- The env file is written owner-only (
0600) — it holds a plaintext password.
- The server uses the stdio transport and only logs to
stderr; secrets and raw
encoded queries are never logged.
- The password/token is never returned by any tool.
- Secret columns are always masked. A column whose dictionary type is
password, password2 or glide_encrypted (column-level encryption) comes back as [redacted] from
every record-returning tool (query_table, get_record, batch, compare,
exports, …) and is never stored in the write journal, whatever
SN_REDACT_FIELDS says. The types are read once per profile from
sys_dictionary and cached like other schema (SN_SCHEMA_CACHE_TTL_SEC);
when the dictionary is not readable, a list of OOTB secret column names
(password, user_password, client_secret, …) applies instead, and the
read goes on. This masking cannot be turned off.
- Hosts are restricted: without
SN_ALLOWED_HOSTS, only *.service-now.com
instances are contacted (internal/loopback blocked unless an allow-list entry
names the host exactly), so a mistyped host cannot silently receive
credentials. Redirects are never followed (REDIRECT_BLOCKED) and response
bodies are capped by SN_MAX_BODY_BYTES. Set SN_ALLOWED_HOSTS to
opt in a custom or sovereign-cloud domain. An explicit non-443 port or an
IPv6 literal in the instance value is accepted only when an allow-list entry
names it (host:8443, [2001:db8::1]).
- Every request — including OAuth token requests — carries the identifying
User-Agent: servicenow-mcp-ai/<version> (node/<major>; <transport>)
so the instance's transaction log can attribute the traffic; it never names
the MCP client or the user. Extend it with SN_USER_AGENT_SUFFIX. Proxy URLs (SN_HTTPS_PROXY, HTTPS_PROXY) are
honoured for every request but their credentials are never logged.
- Prefer OAuth 2.0 over Basic where possible (
SN_OAUTH_CLIENT_ID).
- Apply least privilege with
SN_TABLES_ALLOW / SN_TABLES_DENY and
SN_READONLY=true for read-only deployments.
- Table policy does not cover plugin APIs.
SN_TABLES_DENY=change_request
blocks the Table API path, but the Change Management API (sn_chg_rest) can
still read/write changes. To restrict the plugin-backed surfaces use
SN_PACKAGES_DENY (drop the whole package) or SN_PACKAGES_READONLY
(register only its read tools). The Batch API obeys both axes too: a
sub-request to a denied package's path is refused, and writes to a read-only
package are blocked — a batch cannot be used to bypass the package policy.
Project documentation
Support
This project is built and maintained in my own time. If it saves you or your team
time, please consider supporting its continued development — sponsorship directly
funds new tools, bug fixes and keeping pace with ServiceNow's REST surface.
- GitHub Sponsors — one-off or
recurring, with no platform fee taken out (the preferred option).
- Ko-fi — quick one-off support; it also
accepts PayPal, so it's the fallback for anyone without a GitHub account.
- Donate (Donatree) — a no-account donation
page (card, PayPal and more) for a one-off tip.
[Sponsor on GitHub]
[Support on Ko-fi]
[Donate via Donatree]
Trademark
servicenow-mcp-ai is an independent, community-built project. It is not
affiliated with, endorsed by, or sponsored by ServiceNow, Inc.
"ServiceNow", the ServiceNow logo, "Now", and related marks are trademarks or
registered trademarks of ServiceNow, Inc. in the United States and other
countries. They are used in this project's name and documentation only
nominatively — to identify the platform this software interoperates with — and
no affiliation or endorsement is implied. All other product names and marks are
the property of their respective owners.
Copyright (C) 2026 Ivan Baev. This project is licensed under the
GNU GPL v3.0 or later; that license covers the source code and does
not grant any rights to use the ServiceNow trademarks. Versions up to and
including 3.0.0-beta.1 were released under the MIT License.