<!-- SN-SCRIPTSYNC:SKILL instructionsSchemaVersion=39 -->
SN ScriptSync — Agent API
Full reference for the SN ScriptSync Agent API and every command except the live-form g_form bridge (see the snu-form-automation skill) and the browser debugger (see the snu-browser-debug skill).
SN ScriptSync - Agent API
The Agent API lets AI assistants drive the extension: sync files, create/update records, query ServiceNow, take screenshots, and more. Two transports are available. Prefer the HTTP transport; the file transport is kept for backward compatibility.
The browser helper tab is still required. Both transports only change the agent <-> extension hop. Anything that touches ServiceNow (record reads/writes, queries, screenshots) still round-trips through the SN Utils helper tab over WebSocket. Keep a helper tab open (run
/tokenin a browser session) or commands returnE_BROWSER_DISCONNECTED.
Transport 1: HTTP (recommended, event-driven)
When the extension is running it spins up a local HTTP server bound to 127.0.0.1, preferring the fixed port 1977 (ephemeral fallback if taken). The actual port and auth token are published to two port files — ~/.sn-scriptsync/agent-port.json (well-known, discoverable from any directory; written only while the connected browser has an active SN Utils Pro/Trial/Enterprise license) and <workspace>/.vscode/sn-agent-port.json (always written — workspace agent workflows are free):
{
"port": 1977,
"token": "4f9a...hex...",
"pid": 68861,
"apiVersion": 6,
"startedAt": 1734000000000
}
Discovering the endpoint
# Unix / macOS — global file works from any cwd; older versions only write the workspace file
PORT=$(jq -r .port ~/.sn-scriptsync/agent-port.json 2>/dev/null || jq -r .port .vscode/sn-agent-port.json)
TOKEN=$(jq -r .token ~/.sn-scriptsync/agent-port.json 2>/dev/null || jq -r .token .vscode/sn-agent-port.json)
# Windows PowerShell
$cfg = Get-Content "$HOME/.sn-scriptsync/agent-port.json" | ConvertFrom-Json
$PORT = $cfg.port
$TOKEN = $cfg.token
Required discovery algorithm (do this every session)
Port files can be stale (leftover from a crash; the workspace copy may even be synced
by iCloud/OneDrive/git from another machine), so never trust one blindly and never cache
the port/token. Each session:
- Read
port,token, andpidfrom~/.sn-scriptsync/agent-port.json, falling back to
<workspace>/.vscode/sn-agent-port.json (older versions write only the workspace file).
- Call
GET http://127.0.0.1:<port>/api/health. - Trust the endpoint only if all hold:
- the health request succeeds (HTTP 200), and
health.pidequals thepidfrom the port file (confirms the file matches the live server), andhealth.apiVersionis one you support.
- If any check fails (no file, connection refused, pid mismatch, version mismatch),
the HTTP server is not usable here — fall back to the file transport below.
- Detect available commands from
health.commands[]rather than hard-coding the list;
it changes between versions.
Health check (no auth)
curl -s http://127.0.0.1:$PORT/api/health
# → { "status": "success", "apiVersion": 6, "commands": [...], "pid": 68861 }
The extension deletes both port files when the server stops, but a crash or a sync
conflict can leave a stale file behind — which is exactly why the pid cross-check
in step 3 is mandatory before sending real commands.
Self-describing docs (no auth)
The running server serves its own documentation, so instructions can never drift from
the installed version: GET /api/instructions (connect guide + core instructions),
GET /api/skills (skill index), GET /api/skills/<name> (full skill markdown). If you
were handed only the endpoint — no workspace, no files — start there.
Sending a command
Every authenticated request is POST /api with a JSON body. Provide an X-Agent-Token header.
curl -s -X POST http://127.0.0.1:$PORT/api \
-H "Content-Type: application/json" \
-H "X-Agent-Token: $TOKEN" \
-d '{
"command": "check_connection",
"instance": "dev12345"
}'
Response:
{
"id": "http_1734000001234_a1b2c3",
"command": "check_connection",
"status": "success",
"result": { "ready": true, "appName": "Cursor" },
"timestamp": 1734000001235
}
If id is omitted, the server generates one. Errors return a JSON body with status: "error" and a structured code:
{ "status": "error", "code": "E_BROWSER_DISCONNECTED", "error": "No browser helper tab is connected." }
HTTP status codes map to codes:
| Code | HTTP | Meaning |
|------|------|---------|
| E_INVALID_PARAMS / E_INVALID_REQUEST / E_CONFIRM_REQUIRED | 400 | Malformed request, or a destructive command called without confirm:true |
| E_UNAUTHORIZED | 401 | Missing/invalid X-Agent-Token |
| E_UNKNOWN_COMMAND / E_NOT_FOUND | 404 | No such command, or the target record doesn't exist |
| E_REFERENCE_INTEGRITY | 409 | Write/delete blocked by a reference or data-integrity constraint |
| E_INSTANCE_REQUIRED / E_INSTANCE_NOT_FOUND | 422 | Instance not resolvable |
| E_VERIFY_FAILED | 422 | Standalone update_record was acknowledged but persistence could not be verified. Inspect details.reason and the saved state before retrying; the write may already have taken effect |
| E_DISCOVERY_FAILED | 422 | pull_scope could not pull any table, because the instance dictionary or the scope's record list could not be read completely. details holds the full report (skipped tables, warnings). Pull single tables with pull_records meanwhile |
| E_DISABLED | 423 | Feature disabled via settings (e.g. deletes, background scripts) |
| E_PAUSED | 423 | The user paused agent access in the ScriptSync helper tab. Stop and tell the user — do not retry until they press Resume agents there |
| E_PARTIAL_FAILURE | 207 | Batch partially succeeded — inspect per-item results |
| E_REVIEW_PENDING | 202 | The command needs human approval in the helper tab Review Queue. Tell the user to approve it in the SN Utils ScriptSync helper tab in their browser, then call get_review_result with the reviewId from details to collect the outcome |
| E_USER_REJECTED | 403 | The developer rejected the command in the Review Queue — do not retry without asking the user |
| E_COMMAND_FAILED | 500 | The command was accepted (and, when applicable, approved) but failed during execution. Inspect details.status, details.detail, and details.response; this is not a user rejection |
| E_INTERNAL | 500 | Unexpected error |
| E_ACL / E_TOKEN_EXPIRED / E_SCREENSHOT_PERMISSION | 502 | ServiceNow rejected the request, or a tab needs a one-time capture grant (click the SN Utils icon on it, then retry) |
| E_SERVER_NOT_RUNNING / E_BROWSER_DISCONNECTED | 503 | Can't reach ServiceNow |
| E_TIMEOUT | 504 | Round-trip exceeded deadline |
Resolving `E_INSTANCE_REQUIRED` (multiple instances)
When a command returns E_INSTANCE_REQUIRED, you didn't pass "instance" and
the bridge could not select a single safe target. details.knownInstances lists
remembered workspace folders; details.connectedInstances lists the subset
observed on the current helper connection. A folder is not proof of a live
session. auth_status automatically selects the target only when exactly one
known folder matches a helper-observed instance.
If the error says Multiple known workspace instances found, do not describe
those folders as active connections. If it says `Multiple helper-connected
instances found`, ask for a target (especially for a write) or use the roster
and freshness guidance below.
Use freshness as a default pick, not an exclusivity test. The extension
rewrites <instance>/_settings.json (refreshing g_ck) every time it relays for
that instance, so the **most recently modified _settings.json is the
most-recently-active session**.
The fastest path — and the one to prefer — is the one-shot list_instances
command. It's purely local (no browser round-trip, never returns
E_INSTANCE_REQUIRED) and returns the whole roster, each url, a freshest-first
ranking, and a suggested defaultInstance:
- Call
list_instances. IfdefaultInstanceis set (exactly one instance was
recently active), retry your command with "instance": defaultInstance.
- If
needsConfirmationistrue(none recent, or two-plus recent — e.g.
ven08329 + ven08331), or the operation is a write / destructive action,
confirm the target with the user instead of guessing.
- Optionally confirm the chosen instance's bridge actually responds with a cheap
get_instance_info (check recentlyActive / lastActiveAgeMs) or
query_records round-trip before committing — connected is bridge-level and
is true for every instance whenever the helper tab is up, so it doesn't
disambiguate.
If list_instances isn't available (older extension), fall back to reading the
<instance>/_settings.json mtimes yourself and applying the same rule. Once
resolved, reuse that instance for the rest of the session.
Transport: HTTP only
The legacy file-based transport ({instance_folder}/agent/requests/*.json) was removed in 4.8.0. Every agent flow uses the HTTP Agent API above; if a request file is dropped in the workspace nothing will pick it up.
Commands
`check_connection` ⚡ (CALL THIS FIRST)
Verify WebSocket server is running and browser helper tab is connected. Always call this before any other operations.
Request:
{ "id": "0", "command": "check_connection" }
Response (ready):
{
"status": "success",
"result": {
"ready": true,
"serverRunning": true,
"browserConnected": true,
"message": "Connected and ready",
"helper": { "debuggerAvailable": false, "tier": "pro", "proFeatures": true }
}
}
helper tells you which SN Utils build is connected. debuggerAvailable is true only on the SN Utils Debug edition; most users run the regular build. You don't need this to take screenshots (take_screenshot auto-routes to the best available path), but it tells you what else this session can do:
debuggerAvailable: false→ explicit debugger commands (capture_full_page, network/console capture, dialog handling) will returnE_CDP_UNAVAILABLE, and a screenshot on an ungranted tab will require the user's one-time icon click.debuggerAvailable: true+proFeatures: true→ full-page/element captures and network/console/dialog debugging are available (subject to thebrowserDebuggergate — seeget_capabilities), and screenshots never need a permission click.helper: null→ the handshake hasn't arrived yet (or the license lookup failed); retry or fall back toget_capabilitiesfor the authoritative, browser-verified view.
Response (server not running):
{
"status": "error",
"error": "WebSocket server not running. Click sn-scriptsync in VS Code status bar to start.",
"result": {
"ready": false,
"serverRunning": false,
"browserConnected": false,
"message": "WebSocket server not running"
}
}
Response (no browser):
{
"status": "error",
"error": "No browser connection. Open SN Utils helper tab via /token command in ServiceNow.",
"result": {
"ready": false,
"serverRunning": true,
"browserConnected": false,
"message": "No browser connected - open helper tab with /token"
}
}
`get_capabilities` ⚡ (preflight Pro / debugger / security gates)
Ask the connected SN Utils helper tab what it can do right now — the Agent API version, the license tier, whether the Chrome DevTools Protocol browser debugger (network/console capture, full-page screenshots, native dialog handling) is usable, which protocol capabilities the helper supports (two-phase command review, per-instance security gates), and the per-instance instanceGates snapshots. Call this once up front so you can preflight E_DISABLED instead of discovering it mid-operation, and before reaching for the snu-browser-debug skill instead of firing a CDP command and parsing the error.
Requires a connected helper tab (E_BROWSER_DISCONNECTED otherwise — run check_connection first).
Request:
{ "id": "cap_1", "command": "get_capabilities" }
Response (v8 helper with per-instance gates):
{
"status": "success",
"result": {
"apiVersion": 8,
"tier": "pro",
"proFeatures": true,
"cdp": { "available": true, "reason": null },
"capabilities": { "protocolVersion": 1, "commandReview": 1, "instanceSecurityGates": 1 },
"instanceGates": {
"https://example.service-now.com": {
"revision": 3,
"gates": {
"backgroundScripts": "approve",
"deleteRecords": "off",
"createArtifacts": "auto",
"browserDebugger": "off",
"restRequest": "auto"
}
}
}
}
}
Response (older SN Utils build — no review protocol):
{
"status": "success",
"result": {
"apiVersion": 8,
"tier": "pro",
"proFeatures": true,
"cdp": { "available": false, "reason": "E_CDP_UNAVAILABLE" },
"capabilities": { "protocolVersion": 1 },
"instanceGates": {}
}
}
tier—community|pro|trial|enterprise(license of the connected helper tab).proFeatures—truewhen the tier unlocks Pro features (e.g.code_search).cdp.available—trueonly when the debugger adapter is present (Debug edition build) and the license is Pro/Trial/Enterprise.cdp.reason— whenavailableisfalse, the code you would otherwise have hit:E_CDP_UNAVAILABLE(Community build / no debugger adapter) orE_PRO_REQUIRED(adapter present but license isn't Pro).capabilities— what the connected helper's protocol supports.commandReview: 1means high-risk commands (run_background_script,delete_record, destructiverun_ui_action,delete_application) go through the helper-tab Review Queue: expectE_REVIEW_PENDING, then collect the outcome withget_review_result. WhencommandReviewis absent the helper is an older SN Utils build: those commands run directly and are gated by thesn-scriptsync.*.enabledVS Code settings instead.instanceGates— per-instance tri-state grants keyed by instance origin, published only by helpers withinstanceSecurityGates: 1.offrefuses the command (E_DISABLED),autoruns it without review,approveroutes it through the Review Queue. A gate that is missing for an instance counts asoff(deny-wins). Checking gates up front lets you warn the user before issuing a command that will need their approval.- When a command is refused with
E_DISABLED, relay the error message to the user (it names the helper-tab gate or the VS Code setting to enable) rather than retrying.
`get_review_result` (collect a human-review outcome)
Guarded commands (background scripts, deletes, some UI actions) whose per-instance gate is set to Approve don't execute immediately: the command returns E_REVIEW_PENDING right away with a reviewId, and the actual request waits in the SN Utils helper tab Review Queue for the developer to approve or reject (5-minute window). The helper tab announces the pending review itself (sound, favicon flash, Review Queue badge).
When you receive E_REVIEW_PENDING: tell the user to approve the request in the SN Utils ScriptSync helper tab in their browser, then call this command to collect the outcome. Long-polls up to waitSeconds (default 30, max 55) per call; poll again while it keeps returning E_REVIEW_PENDING.
Request:
{ "id": "revres_1", "command": "get_review_result", "params": { "reviewId": "rev_1786...._ab12cd", "waitSeconds": 30 } }
Response (approved & executed): the original command's result, e.g. for run_background_script:
{ "status": "success", "result": { "reviewId": "rev_....", "command": "run_background_script", "output": "*** Script: ..." } }
Errors:
E_REVIEW_PENDING— still undecided; remind the user and poll again. Withdetails.running: truethe developer already approved and the command is executing now; poll again and do not re-issue it.E_USER_REJECTED— the developer rejected it; don't retry without asking.E_COMMAND_FAILED— the developer approved it, but execution failed; inspectdetails.status,details.detail, anddetails.responseinstead of treating this as a rejection.E_TIMEOUT— the 5-minute review window expired unanswered; re-issue the original command to start a new review. An approved command gets its own 5 minutes to run, counted from the approval; a timeout after the approval means the outcome is unknown, so check the instance before re-issuing.E_NOT_FOUND— unknown/expiredreviewId(results are kept ~10 minutes after the review settles). The command may already have run: check the instance before re-issuing, and never re-issue a write such assdk_deploywithout confirming it did not happen.
Prefer this two-phase flow. If you genuinely need the old blocking behavior (the original call holding open until the decision), pass
"awaitReview": truein the original command'sparams— but note most HTTP clients time out long before the 5-minute window.
`get_batch_result`
Collect the outcome of a create_records / update_records batch by its batchId: after the call returned E_TIMEOUT, after a review was approved, or after the connection dropped. Call it before retrying any row.
Requires: browser helper tab connected, in the browser profile that ran the batch. Results are kept there for 24 hours.
Request:
{ "id": "batch_1", "command": "get_batch_result", "instance": "dev12345", "params": { "batchId": "bat_lzx1y2_a1b2c3d4" } }
Response: the same shape as the batch command. While the helper is still writing, status is success with running: true and the rows answered so far; call again. Once finished, the same success or error mapping as the original call (E_PARTIAL_FAILURE with every row in details, and so on). A batch whose helper tab closed mid-run comes back with interrupted: true, and the row it was sending is unknown.
Errors:
E_INVALID_PARAMS- missing or malformedbatchIdE_NOT_FOUND- no such batch for this instance in this browser (expired, or run elsewhere)
`list_instances`
List every instance in the workspace with its URL and per-instance activity
freshness, plus a suggested default. Purely local — it reads the
*/_settings.json files directly, so it needs no browser helper tab and never
returns E_INSTANCE_REQUIRED. Use it as the first step when you don't yet know
which instance to target.
instances is sorted freshest-first (lastActiveAgeMs ascending; never-active
folders last). recentlyActive means the instance's _settings.json was
rewritten within ~10h — the extension refreshes that file (and g_ck) whenever
the helper tab relays for that instance, so it's a freshness proxy, not proof of
a live tab. defaultInstance is set only when exactly one instance is
recently active; when needsConfirmation is true (none recent, or two-plus
recent) pick with the user before any write. connected is bridge-level (the one
helper tab relays for every instance), not per-instance.
Request:
{ "id": "1", "command": "list_instances" }
Response:
{
"result": {
"instances": [
{ "name": "ven08329", "url": "https://ven08329.service-now.com", "recentlyActive": true, "lastActiveAgeMs": 425000, "hasSettings": true },
{ "name": "ven08331", "url": "https://ven08331.service-now.com", "recentlyActive": true, "lastActiveAgeMs": 980000, "hasSettings": true },
{ "name": "empakooi", "url": "https://empakooi.service-now.com", "recentlyActive": false, "lastActiveAgeMs": 10500000000, "hasSettings": true }
],
"count": 3,
"connected": true,
"defaultInstance": null,
"needsConfirmation": true
}
}
`get_instance_info`
Get instance connection info, including per-instance activity freshness.
Pass "instance" to inspect a specific candidate (useful for disambiguating
E_INSTANCE_REQUIRED). connected is bridge-level — it is true for every
instance whenever the WS server is up with the helper tab connected, because the
single helper tab relays for every instance the browser has a session for. Use
recentlyActive / lastActiveAgeMs (derived from the _settings.json mtime) to
tell which instance is the most-recently-active session.
Request:
{ "id": "2", "command": "get_instance_info", "instance": "ven08329" }
Response:
{
"result": {
"instanceName": "ven08329",
"hasSettings": true,
"connected": true,
"recentlyActive": true,
"lastActiveAgeMs": 425000
}
}
`get_sync_status`
Get current sync queue status.
Request:
{ "id": "1", "command": "get_sync_status" }
Response:
{
"result": {
"serverRunning": true,
"pendingFiles": ["/path/to/file.js"],
"pendingCount": 1,
"syncingFiles": ["/path/to/other.js"],
"syncingCount": 1,
"isPaused": false
}
}
syncingFiles were sent to the instance and wait for the helper tab's confirmation; sync_now never sends them twice. A file whose save failed stays in pendingFiles, held for the user, with the reason in the Pending Saves panel.
`sync_now` ⚡
Send eligible pending files from the VS Code workspace queue. Inspect get_sync_status first and use this only when all eligible files belong to the authorized task: it does not filter by instance or file. The standalone host does not provide this queue; use the typed record-write commands there.
synced: true means the files were sent, not that their content was verified. Wait until the intended files leave both pendingFiles and syncingFiles, then read their records with get_record and compare the changed fields. An empty queue or count: 0 does not prove your edits reached the instance.
When sn-scriptsync.agentApi.reviewWrites is enabled, the result has synced: false and blocked: true: tell the user to approve the intended files in VS Code Pending Saves (per-file ✓). Saves held for the user after Save All, auto save or refactoring cannot be flushed by an agent either. Do not bypass these holds using a direct write.
Request:
{ "id": "2", "command": "sync_now" }
Response (when files pending):
{
"result": {
"synced": true,
"message": "Synced 3 file(s) immediately",
"count": 3,
"files": ["/path/to/file1.js", "/path/to/file2.js", "/path/to/file3.js"]
}
}
Response (when no files pending):
{
"result": {
"synced": false,
"message": "No pending files to sync",
"count": 0
}
}
`get_last_error`
Get the last error that occurred. Errors are automatically written to _last_error.json in the folder of the instance that reported them, and that instance's pending Agent requests are failed when ServiceNow returns an error. Other instance folders in the workspace are untouched.
Request:
{ "id": "err", "command": "get_last_error" }
Response (when error exists):
{
"result": {
"hasError": true,
"isRecent": true,
"error": "ACL Error, try changing scope in the browser",
"time": "2024-12-07T12:30:45.123Z",
"timestamp": 1733567445123,
"details": { "message": "...", "detail": "..." },
"instance": { "name": "dev221527", "url": "https://dev221527.service-now.com" }
}
}
Response (no error):
{
"result": {
"hasError": false,
"message": "No errors recorded"
}
}
`clear_last_error`
Clear the last error file.
Request:
{ "id": "clr", "command": "clear_last_error" }
Response:
{
"result": {
"cleared": true,
"message": "Error cleared"
}
}
`update_record`
Update a single field on an existing record. Fire-and-forget (the extension sends the update through the helper tab; success is reported back asynchronously).
Use field plus content. A fields object belongs to update_record_batch; it is not accepted as a substitute for these parameters.
Requires: browser helper tab connected.
Gating: updateRecords (sn-scriptsync.updateRecords.enabled in VS Code, SNU_ALLOW_UPDATE_RECORDS in the standalone snu host, or the per-instance Update Records grant in the SN Utils helper tab) — on by default. Where nothing sets it, it follows createArtifacts: a host or instance that may not create records may not overwrite them either.
Request:
{
"id": "upd_1",
"command": "update_record",
"instance": "dev12345",
"params": {
"table": "sys_script_include",
"sys_id": "abc123def456...",
"field": "script",
"content": "gs.info('hello from the agent');"
}
}
Response (success):
{
"id": "upd_1",
"command": "update_record",
"status": "success",
"result": {
"success": true,
"message": "Update sent for sys_script_include/abc123def456...",
"table": "sys_script_include",
"sys_id": "abc123def456...",
"field": "script"
}
}
Synchronous confirmation: add "await": true to write via the Table API and read the value back. The response then includes awaited: true, the persisted value, and a warnings[] array flagging any field that came back empty (e.g. silently dropped by an ACL/read-only/business rule).
{ "id": "upd_2", "command": "update_record", "params": { "table": "sys_script_include", "sys_id": "abc...", "field": "active", "content": "false", "await": true } }
Review mode: when sn-scriptsync.agentApi.reviewWrites is on (default off), this write is not sent. It is parked in the VS Code "Pending Saves" queue and the response is { "staged": true, "reviewId": "...", "message": "..." }. The user reviews it and approves it with Sync Now (or discards it); await is ignored while staged. Treat a staged: true response as "queued for human approval", not "applied".
Standalone persistence verification: the standalone host waits for the PATCH, then separately reads the field using raw stored values and compares it to content, even when await is omitted. A match returns updated: true, awaited: true, verified: true, persisted: { "<field>": <saved value> } and an empty warnings list. Empty content remains a deliberate clear; script whitespace is significant.
A mismatch, unreadable field or failed read returns E_VERIFY_FAILED (HTTP 422) with details.writeAcknowledged: true, verified: false and a reason (value_mismatch, field_unreadable or read_failed). A failed read also includes causeCode. The write may already have taken effect: inspect the record and any ACL/business rule before retrying. Journal fields such as work_notes must be checked through the new sys_journal_field entry, not by equality against the parent record field; never repeat a journal write just because that comparison failed.
Do not verify twice: a successful verified: true result with matching persisted content already completes persistence verification. No extra get_record is needed. Only on hosts or save results without that confirmation, call get_record and compare the content before reporting it saved. A PATCH success or increased sys_mod_count alone is insufficient. Collect any pending approval before checking for the resulting change.
Errors:
E_INVALID_PARAMS- lists only missing sys_id/table/field/content parameters; empty content is a deliberate clearE_DISABLED- theupdateRecordsgate is off for this host or instanceE_BROWSER_DISCONNECTED- no helper tab availableE_INSTANCE_NOT_FOUND-_settings.jsonmissingE_VERIFY_FAILED(HTTP 422) - standalone persistence verification failed; inspectdetailsand read the saved state before deciding whether to retry
`update_record_batch`
Update multiple fields on the same record in one round-trip. Preferred for multi-file artifacts (widgets, UI pages) where you'd otherwise send many update_record calls.
Requires: browser helper tab connected.
Gating: updateRecords (sn-scriptsync.updateRecords.enabled in VS Code, SNU_ALLOW_UPDATE_RECORDS in the standalone snu host, or the per-instance Update Records grant in the SN Utils helper tab) — on by default. Where nothing sets it, it follows createArtifacts: a host or instance that may not create records may not overwrite them either.
Request:
{
"id": "upd_batch_1",
"command": "update_record_batch",
"instance": "dev12345",
"params": {
"table": "sp_widget",
"sys_id": "abc123def456...",
"fields": {
"script": "data.hello = 'world';",
"client_script": "function($scope){ /* ... */ }",
"css": ".c1 { color: red; }"
}
}
}
Response (success):
{
"id": "upd_batch_1",
"command": "update_record_batch",
"status": "success",
"result": {
"success": true,
"message": "Updated 3 field(s) on sp_widget/abc123def456...",
"table": "sp_widget",
"sys_id": "abc123def456...",
"fields": ["script", "client_script", "css"]
}
}
Synchronous confirmation: add "await": true to write via the Table API and read the values back. The response includes awaited: true, persisted, and a warnings[] array for fields that came back empty. Note: sys_scope is read-only after insert — it is stripped from the payload and reported as a warning (use create_application/create_artifact to set scope at insert time).
Review mode: when sn-scriptsync.agentApi.reviewWrites is on (default off), this write is not sent. It is parked in the VS Code "Pending Saves" queue and the response is { "staged": true, "reviewId": "...", "message": "..." }. The user approves it with Sync Now (or discards it); await is ignored while staged.
Errors:
E_INVALID_PARAMS- missing sys_id/table/fields, orfieldsobject is emptyE_DISABLED- theupdateRecordsgate is off for this host or instanceE_BROWSER_DISCONNECTED- no helper tab availableE_INSTANCE_NOT_FOUND-_settings.jsonmissing
`update_records`
Update up to 200 existing records on one table in one call. Each row is { "sys_id": "...", ...fields }. Same contract as create_records: one review for the batch, one write-history entry per record, an outcome per row, and no rollback of rows that succeeded. Use update_record_batch instead for several fields on one record.
Requires: browser helper tab connected, SN Utils 10.2.8.0 or later.
Gating: updateRecords, same as update_record (follows createArtifacts where nothing sets it).
Request:
{
"id": "urecs_1",
"command": "update_records",
"instance": "dev12345",
"params": {
"table": "incident",
"continueOnError": true,
"rows": [
{ "sys_id": "0123456789abcdef0123456789abcdef", "urgency": "2" },
{ "sys_id": "1123456789abcdef0123456789abcdef", "urgency": "2", "assignment_group": "..." }
]
}
}
Parameters: table, rows, continueOnError, dryRun and deadlineMinutes as on create_records. Each row needs a sys_id, at least one field, and may appear only once per call. There is no scope: each record is written in its own application scope (a cross-scope refusal is retried once in the record's scope, as on update_record).
sys_scope in a row is refused with E_INVALID_PARAMS (read-only after insert). This is stricter than update_record_batch, which drops the field and warns.
Response and errors: identical in shape to create_records (mode: "update"), including per-row field warnings when a written field came back empty, different or unverifiable. Collect late or lost results with get_batch_result.
`create_record`
Insert a plain data row on any table: an incident, task, sys_user, sys_user_group, cmdb_ci, catalog request — anything whose display field is not name.
Use create_artifact instead for scriptable artifacts (Script Include, Business Rule, widget): it also tracks the new record in the local workspace and its _map.json.
Gating: createArtifacts (sn-scriptsync.createArtifacts.enabled in VS Code, SNU_ALLOW_CREATE_ARTIFACTS in the standalone snu host) — the same permission as the other create_* commands, on by default.
Request:
{
"id": "crec_1",
"command": "create_record",
"params": {
"table": "incident",
"fields": { "short_description": "Printer on 3rd floor is down", "urgency": "2" }
}
}
Parameters:
table(required): target table name.fields(required): field-value dictionary, at least one entry. Use raw values (asys_idfor reference fields, the choice value for choice fields), not display labels.
Response:
{
"status": "success",
"result": {
"created": true,
"table": "incident",
"sys_id": "b1c2...",
"name": "INC0010001",
"record": { "...": "..." }
}
}
record is the inserted row as ServiceNow returned it, so the write is already verified — no follow-up get_record is needed unless you want fields the insert did not return. name is the best available display handle (number, then name, sys_name, short_description).
Errors:
E_INVALID_PARAMS— missing/invalidtable, or an emptyfieldspayload.E_DISABLED— thecreateArtifactsgate is off.E_ACL— the session may not insert on that table.E_REFERENCE_INTEGRITY— a reference field points at a record that does not exist.
Do not create records by driving the form UI (navigate + set_field + run_ui_action). Those commands exist to exercise real form behaviour (client scripts, UI policies) and to show the user something on screen. As a way to write data they are slow, silently lossy, and leave half-filled forms behind when a step fails.
`create_records`
Insert up to 200 records on one table in one call. Use it instead of looping create_record, and instead of rest_request batch calls or a GlideRecord loop in run_background_script: those reach the instance as one opaque write, while this one gets one review for the whole batch, one write-history entry per record, and an outcome for every row.
Rows that succeed are not rolled back. If row 7 fails, rows 0 to 6 stay written. Never resend the whole batch after a partial failure, or you create duplicates: retry only the rows whose outcome is not succeeded, and query the table first for rows marked unknown.
Requires: browser helper tab connected, SN Utils 10.2.8.0 or later (older helpers answer E_UNSUPPORTED_HOST).
Gating: createArtifacts, same as create_record. With an approve grant the user reviews the batch once in the helper tab (every row is on the card) and the call returns E_REVIEW_PENDING; with auto it runs at once.
Request:
{
"id": "crecs_1",
"command": "create_records",
"instance": "dev12345",
"params": {
"table": "sys_choice",
"scope": "x_acme_app",
"rows": [
{ "name": "incident", "element": "category", "label": "Network", "value": "network" },
{ "name": "incident", "element": "category", "label": "Storage", "value": "storage" }
]
}
}
Parameters:
table(required): one table per call.rows(required): array of field-value objects, at most 200 and at most 1 MB of JSON together. A row may carrysys_idto insert with that id; a row with only asys_idinserts an empty record.scope(optional): the application the rows are written in (name, sys_id orglobal), exactly as oncreate_record: it becomes the transaction scope and is never written into the rows. A row's ownsys_scope(a sys_id orglobal) is left as written, but every stated scope in one call must name the same application, or the call is refused.continueOnError(optional, defaultfalse):falsestops at the first row that fails or gets no answer;trueattempts every row. An expired session (401) always stops the batch.dryRun(optional): validate and normalize only, including that the table exists and the scope resolves. Nothing is written, nothing is staged, no review is raised. It does not predict business rules or ACLs.deadlineMinutes(optional, 1 to 30, default 10): how long the helper may run the batch. Rows not reached by then arenot_attempted.
Response (all rows written):
{
"status": "success",
"result": {
"batchId": "bat_lzx1y2_a1b2c3d4",
"table": "sys_choice",
"mode": "create",
"effectiveScope": "x_acme_app",
"running": false,
"counts": { "total": 2, "succeeded": 2, "failed": 0, "notAttempted": 0, "unknown": 0 },
"rows": [
{ "index": 0, "outcome": "succeeded", "status": 201, "sys_id": "..." },
{ "index": 1, "outcome": "succeeded", "status": 201, "sys_id": "..." }
]
}
}
Field warnings: every written row is checked against the record the instance answered with. A row whose fields did not stick keeps outcome: "succeeded" (it was written; do not create it again) and gets warnings: [{ "field", "issue" }]:
| issue | meaning |
|---|---|
| empty | a value was sent and the instance stored nothing (dropped by a business rule, field ACL or read-only field) |
| different | the instance stored another value, including a clear ("") that did not take |
| unverified | the answer does not show the field: no read access, an unknown field name, or a type the Table API does not echo (journal fields such as work_notes, passwords, encrypted fields) |
Booleans, numbers and list fields are compared by value ("1" and "true", 0 and "0", b,a and a,b match); a reference sent as a sys_id matches its stored sys_id. counts.withWarnings counts the rows with any warning. Read an empty or different field back with get_record and fix it deliberately; the cause is usually the creation path (the UI does something the Table API does not).
Row outcomes:
| outcome | meaning | retry |
|---|---|---|
| succeeded | the instance answered 2xx; sys_id included | do not retry |
| failed | the instance answered an error; status and error included | retry this row after fixing the cause |
| not_attempted | the batch stopped earlier, was rejected, or hit its deadline | safe to retry this row |
| unknown | the request was sent and no answer arrived | not safe to retry blindly: query the table first |
Overall status: all rows succeeded is success. Otherwise the call is an error whose details carry batchId, counts and every row:
- some rows succeeded:
E_PARTIAL_FAILURE - none succeeded and at least one is
unknown:E_TIMEOUT - none succeeded and at least one
failed:E_COMMAND_FAILED - nothing ran: the cause (
E_USER_REJECTED,E_DISABLED,E_INVALID_PARAMS,E_TOKEN_EXPIRED,E_UNSUPPORTED_HOST)
Long batches and lost answers: every call gets a batchId before anything runs (also on E_REVIEW_PENDING, in details). Once a batch was sent, a lost answer (your wait expired, the helper tab disconnected, the bridge stopped) is always E_TIMEOUT with details.batchId, details.cause and details.retrySafe: false: some rows may be written. Do not send the batch again. Call get_batch_result with the batchId once the helper tab is connected, then retry only what it reports as failed or not_attempted. The helper keeps every row's outcome for 24 hours, never runs one batchId twice, and refuses to start a batch at all when it cannot record its progress (E_COMMAND_FAILED, nothing written, safe to retry).
Review mode: with sn-scriptsync.agentApi.reviewWrites on, the batch is staged first as one editable rows file in Pending Saves ({ "staged": true, "batchId": ... }). The user can edit or drop rows; Sync Now validates the edited rows again and only then raises the helper review (when the grant is approve) or runs them. The file stays in Pending Saves, with the user's edits, until the batch has run; after a run, rows that failed or were not attempted go back as a new batch.
Errors:
E_INVALID_PARAMS- invalid or nonexistent table, rows, scope, a row without fields, or limits exceeded (the message names the row index)E_DISABLED-createArtifactsis off for this host or instanceE_UNSUPPORTED_HOST- the helper tab predates multi-record writesE_PARTIAL_FAILURE/E_COMMAND_FAILED/E_TIMEOUT- see above (E_TIMEOUTwithretrySafe: false: collect withget_batch_result, never resend)
`create_artifact` ⚡ (RECOMMENDED FOR AI AGENTS)
Create a new artifact directly via payload. This is the preferred method for AI agents - no file creation needed, executes immediately (not queued).
⚠️ IMPORTANT: Transaction Scope Required
The extension automatically includes ?sysparm_transaction_scope=<SCOPE_SYS_ID> in the API request to ensure the artifact is created in the correct scope context.
Request:
{
"id": "11",
"command": "create_artifact",
"params": {
"table": "sys_script_include",
"scope": "global",
"fields": {
"name": "MyNewUtils",
"script": "var MyNewUtils = Class.create();\nMyNewUtils.prototype = {\n initialize: function() {},\n type: 'MyNewUtils'\n};",
"active": "true",
"access": "public"
}
}
}
Parameters:
table(required): The ServiceNow table (e.g.,sys_script_include,sys_script)scope(required): Scope name - always specify explicitly (e.g.,global,x_myapp)fields(required): Object containing field:value pairsname(required): The artifact name- Other fields depend on the table (script, active, etc.)
Response:
{
"status": "success",
"result": {
"sys_id": "abc123def456789012345678901234",
"name": "MyNewUtils",
"table": "sys_script_include",
"scope": "global"
}
}
Synchronous confirmation: add "await": true to read the new record back after creation. The response then includes awaited: true, the persisted field values, and a warnings[] array flagging any requested field that came back empty (e.g. silently dropped).
Benefits over file-based creation:
- ✅ Executes immediately (not queued with debounce)
- ✅ Can set multiple fields in one request
- ✅ Can set reference fields directly (e.g.,
web_service_definitionfor REST API operations) - ✅ No need to create files first
- ✅ Automatically updates
_map.json
Example: Creating a Business Rule with table reference:
{
"id": "12",
"command": "create_artifact",
"params": {
"table": "sys_script",
"scope": "global",
"fields": {
"name": "My Business Rule",
"collection": "incident", // ✅ Include table reference in payload
"script": "// Business Rule script",
"when": "before", // ✅ Include when in payload
"action_insert": "true", // ✅ Include action in payload
"active": "true" // ✅ Include active in payload
}
}
}
⚠️ NOTE: All configuration fields (collection, when, action_insert, active) are included in the single payload. These are STRING/BOOLEAN values, not code.
Do NOT create files for configuration fields:
- ❌
MyBR.collection.js- this is just the string "incident" - ❌
MyBR.when.js- this is just the string "before" - ❌
MyBR.active.js- this is just the boolean true
Only the script content (actual code) goes in a file:
- ✅
MyBR.script.js- contains the business rule code
If an artifact has multiple code fields, create multiple files:
- ✅
MyUIPage.html- contains markup - ✅
MyUIPage.client_script.js- contains client-side code - ✅
MyUIPage.processing_script.js- contains server-side code
Example: Creating a REST API Operation with parent reference:
{
"id": "13",
"command": "create_artifact",
"params": {
"table": "sys_ws_operation",
"scope": "x_myapp",
"fields": {
"name": "getUsers",
"web_service_definition": "abc123def456",
"http_method": "GET",
"operation_script": "(function process(request, response) {\n response.setBody({message: 'Hello'});\n})(request, response);",
"active": "true"
}
}
}
⚠️ Large / multi-field payloads (widgets etc.): A widget's four big code fields (template, css, script, client_script) are escaping-hell to pass inline on a shell command line (curl -d '...'). Don't hand-build the JSON string — write the request body to a file and send it with curl -d @body.json (build the file with JSON.stringify so newlines/quotes are encoded correctly), or use the file transport. This applies to any multiline or large field value.
Review mode: when sn-scriptsync.agentApi.reviewWrites is on (default off), the record is not created. The request is parked in the VS Code "Pending Saves" queue and the response is { "staged": true, "reviewId": "...", "message": "..." }. The user approves it with Sync Now (which then creates the record and updates _map.json) or discards it; await is ignored while staged. Treat a staged: true response as "queued for human approval", not "created" — the sys_id is only assigned on approval.
Errors:
E_DISABLED— artifact creation is off (sn-scriptsync.createArtifacts.enabled). This setting defaults totrue, so creation works out of the box; it only fails here if the user explicitly turned it off. Checkget_capabilities→gates.createArtifactsto preflight.E_INVALID_PARAMS— missingtable, missingfields, or missingfields.name.
⚠️ fields.name is required for every table. For a data table whose display field isn't name (e.g. a custom table whose display column is title), don't fight this command — seed rows with rest_request instead: POST /api/now/table/<table> with the row in body (requires sn-scriptsync.restRequest.enabled). create_artifact is for metadata/code artifacts; rest_request POST is the blessed path for plain data rows.
`delete_record` ⚠️ (DESTRUCTIVE — guarded)
Delete a record by table + sys_id, or bulk-delete by query. Disabled by default. Enable sn-scriptsync.deleteRecords.enabled in VS Code settings to allow it. Both hosts (VS Code and the standalone snu bridge) implement the single and the bulk form.
Single delete:
{
"id": "del_1",
"command": "delete_record",
"params": { "table": "incident", "sys_id": "abc123def456..." }
}
The display value (name/number/short_description) is read back first and echoed so you can confirm what was removed.
Bulk delete (query-based): requires confirm: true AND a positive integer limit.
{
"id": "del_2",
"command": "delete_record",
"params": { "table": "incident", "query": "active=false^sys_created_on<javascript:gs.daysAgo(365)", "limit": 50, "confirm": true }
}
Preview without deleting: add "dryRun": true to return the matches that would be deleted. A dry run only reads, so it is never held for review; the delete permission must still be granted.
Parameters:
table(required).sys_id— single-record mode.query— bulk mode (encoded query). Mutually exclusive withsys_id.confirm(bulk, required): must betrue.limit(bulk, required): positive integer cap on how many records are deleted.dryRun(optional): preview only, never deletes.
Response (single):
{ "status": "success", "result": { "deleted": true, "table": "incident", "sys_id": "abc...", "display": "INC0010001" } }
Response (bulk): an outcome per record. deleted is true only when every match was removed; when some fail the command answers E_PARTIAL_FAILURE with the same results list in details.
{ "status": "success", "result": { "deleted": true, "table": "incident", "count": 2, "deletedCount": 2,
"results": [ { "sys_id": "abc...", "display": "INC0010001", "deleted": true }, { "sys_id": "def...", "display": "INC0010002", "deleted": true } ] } }
Errors:
E_DISABLED—sn-scriptsync.deleteRecords.enabledis off.E_CONFIRM_REQUIRED— bulk delete withoutconfirm:true+limit.E_NOT_FOUND— single sys_id does not exist.E_REFERENCE_INTEGRITY— blocked by a referencing record (HTTP 409).E_PARTIAL_FAILURE— some records in a bulk delete failed (seedetails.results).
`create_application`
Create a scoped application (sys_app). The scope is set at insert time — it is read-only afterwards, so this is the correct way to establish a new scope. The resolved scope name → sys_id is recorded in scopes.json so later create_artifact / add_column calls can target it.
Request:
{
"id": "app_1",
"command": "create_application",
"params": { "name": "My Cool App", "prefix": "acme", "short_description": "Demo app" }
}
Parameters:
name(required): Friendly application name.scope(optional): Explicit scope (e.g.x_acme_mycoolapp). If omitted, derived asx_<prefix>_<slug(name)>.prefix(required whenscopeomitted): Vendor/company code used to derive the scope.short_description(optional),version(optional, default1.0.0).
Response:
{ "status": "success", "result": { "created": true, "name": "My Cool App", "scope": "x_acme_my_cool_app", "sys_id": "..." } }
Errors:
E_DISABLED—sn-scriptsync.createArtifacts.enabledis off.E_INVALID_PARAMS— neitherscopenorprefixprovided.
`create_table`
Create a custom table by inserting a sys_db_object record. ServiceNow auto-creates the physical table and its base sys_* fields (sys_id, sys_created_on, sys_updated_on, etc.). Pair it with add_column for your own fields, and set the display column via add_column display: true. This mirrors the create_application / add_column ergonomics so you don't have to drive create_artifact against sys_db_object by hand.
Request:
{
"id": "tbl_1",
"command": "create_table",
"params": { "name": "project", "label": "Project", "scope": "x_acme_myapp", "extends": "task" }
}
Parameters:
name(required): Table name. When a non-globalscopeis given and the name isn't already prefixed, it is prefixed for you as<scope>_<name>(e.g.x_acme_myapp_project). An already-prefixedx_...name is left as-is.label(optional): Human label (defaults to a title-casedname).scope(optional): Scope name; when known (inscopes.json) the table is created withsysparm_transaction_scopeset so it lands in the right app. Omit (orglobal) for a global table.extends/super_class(optional): Parent table to extend (e.g.task). Omit for a standalone table.
Response:
{ "status": "success", "result": { "created": true, "name": "x_acme_myapp_project", "label": "Project", "sys_id": "...", "scope": "x_acme_myapp" } }
Typical table-build flow:
create_table→ get the prefixednameback.add_columnfor each field (setdisplay: trueon the one you want as the display value, plusmandatory/choices/ etc. inline).- Seed data rows with
rest_requestPOST /api/now/table/<name>(display field need not bename).
Errors:
E_DISABLED—sn-scriptsync.createArtifacts.enabledis off (defaults totrue). Preflight withget_capabilities→gates.createArtifacts.E_INVALID_PARAMS— missingname.
`add_column`
Add a column to a table by creating a sys_dictionary entry (keyed by table.element). Use this instead of create_artifact for dictionary entries — it avoids the _map.json name collision where every column would share name = <table>.
Request:
{
"id": "col_1",
"command": "add_column",
"params": { "table": "x_acme_myapp_widget", "element": "priority", "type": "integer", "label": "Priority", "display": true, "mandatory": true, "scope": "x_acme_myapp" }
}
Parameters:
table(required): Table to add the column to.element(required): Column name (theelement).type(optional, defaultstring): Internal type, e.g.string,integer,boolean,glide_date_time,reference,choice.label(optional): Column label (defaults to a title-casedelement).max_length(optional): For string columns.reference(optional): Referenced table whentypeisreference.display(optional, boolean): Make this the table's display column — no separateupdate_recordneeded.mandatory(optional, boolean): Mark the column mandatory.read_only(optional, boolean): Mark the column read-only.default(optional): Default value for the column.reference_qual(optional): Reference qualifier (forreferencecolumns).choice(optional): Dropdown mode —0none,1dropdown with--None--,3dropdown without--None--.choices(optional, array): Create the choice list values in the same call. Each entry is either a plain string (used for both label and value) or{ "label": "...", "value": "...", "sequence": 0 }. Supplyingchoicesdefaultschoiceto1unless you set it explicitly.scope(optional): Scope name; when known (inscopes.json) the column (and its choices) are created withsysparm_transaction_scopeset so they land in the right app.
Example with attributes + choices:
{
"id": "col_2",
"command": "add_column",
"params": {
"table": "x_acme_myapp_project",
"element": "stage",
"type": "choice",
"label": "Stage",
"display": true,
"mandatory": true,
"default": "planning",
"choices": [
{ "label": "Planning", "value": "planning" },
{ "label": "In Progress", "value": "in_progress" },
"Done"
]
}
}
Response:
{ "status": "success", "result": { "created": true, "table": "x_acme_myapp_widget", "element": "priority", "type": "integer", "label": "Priority", "sys_id": "...", "choices": ["planning", "in_progress", "Done"] } }
choices is present in the response only when you passed a choices array; it lists the values that were created.
Errors:
E_DISABLED—sn-scriptsync.createArtifacts.enabledis off.E_INVALID_PARAMS— missing table/element.
`delete_application` ⚠️ (DESTRUCTIVE — cascade)
Delete a scoped application: its scoped metadata (records whose sys_scope is the app) and the sys_app record itself, via a guarded background script. Irreversible. Requires confirm: true and both sn-scriptsync.deleteRecords.enabled and sn-scriptsync.backgroundScripts.enabled.
Request:
{
"id": "delapp_1",
"command": "delete_application",
"params": { "scope": "x_acme_myapp", "confirm": true }
}
Parameters:
sys_id— thesys_appsys_id (32-char hex), orscope— the scope name (e.g.x_acme_myapp).confirm(required): must betrue.
Response:
{ "status": "success", "result": { "deleted": true, "name": "My App", "scope": "x_acme_myapp", "childRecordsDeleted": 37 } }
Errors:
E_DISABLED— delete and/or background-script settings are off.E_CONFIRM_REQUIRED—confirm:truenot provided.E_NOT_FOUND— no application matchedsys_id/scope.E_INVALID_PARAMS— neithersys_idnorscope, or malformed values.
Best-effort cascade: it sweeps
sys_metadatafor the app's scope then deletessys_app. Some artifact types may need a manual follow-up; verify in the instance afterwards.
`sdk_deploy` (Pro/Trial)
Build, pack and install a ServiceNow SDK (NOW SDK / Fluent) app with the user's browser session, with no separate now-sdk auth login. It runs the project's own now-sdk build and now-sdk pack, then the SN Utils helper tab asks the user to confirm in a modal, installs the package and activates the app's flows. The call waits for that confirmation (up to 15 minutes), so tell the user to confirm in the helper tab. Needs the createArtifacts permission.
Request:
{
"id": "deploy_1",
"command": "sdk_deploy",
"instance": "dev12345",
"params": { "projectPath": "my-fluent-app" }
}
Parameters:
projectPath(optional): the project folder (the one withnow.config.json), relative to the workspace root or absolute, and inside the workspace. Omit it when the workspace holds one NOW SDK project.force(optional): deploy even when the app changed on the instance since the last deploy or pull. Only after the user agreed.
Without instance, the app's linked instance (the one it was last deployed to or pulled from) is used.
Response:
{ "status": "success", "result": {
"success": true, "installed": true, "partial": false,
"app": { "name": "My App", "scope": "x_1234_my_app", "version": "1.0.0" },
"rollbackUrl": "https://dev12345.service-now.com/sys_rollback_context.do?sys_id=...",
"flowActivation": { "ok": true, "total": 1, "succeeded": 1, "failed": 0 },
"durationMs": 8200
} }
installed: true, partial: true: the app installed, but some flows or actions did not activate. Report which, and suggest opening them in Flow Designer.
Errors:
E_INSTANCE_CHANGED: the deploy would overwrite changes made on the instance since the last deploy or pull.details.changeslists each record with thefieldsit would overwrite and, when a pull cannot bring the change in, areason(for example "compiled from your server source"). Ask the user whether to pull first (sdk_pull), copy the unpullable changes into the source, or overwrite (force: true).details.instanceOnlylists records that exist only on the instance; a deploy leaves them.E_CONFIRM_REQUIREDwithdetails.checkFailed: the check for changes on the instance could not run (for example an expired session), so nothing was deployed. Retry, or ask the user before deploying withforce: true, which installs without the check. The result'sinstanceCheckedsays whether a deploy was checked.E_USER_REJECTED: the user cancelled in the helper tab. Do not retry on your own.E_PRO_REQUIRED: the connected SN Utils is the Community tier.E_PAUSED: the user paused agents in the helper tab.E_UNSUPPORTED_HOST: the connected SN Utils is too old to deploy apps.E_INVALID_PARAMS: no project found, several projects and noprojectPath, a path outside the workspace, the SDK not installed in the project (npm install), an SDK version outside 4.1 to 4.x, or an app type ScriptSync does not deploy (configuration project, Store app, global scope). Tell the user to usenow-sdk installfor those.E_COMMAND_FAILED: build or install failed, or the instance refused the app (installed from the Store, or its scope is used by another app).detailscarriestrackerUrl(the install's execution tracker) andreason(the cause the instance logged, e.g. a scope that does not match the instance's vendor prefix).E_TIMEOUT: no result in time. The install may still have finished: check the app on the instance before deploying again.
The result also carries instance, baselineRecorded (the state used for the next change check) and, after a forced deploy, overwritten.
now-sdk dependenciesand the other SDK commands still use the SDK's own login.
`sdk_pull` (Pro/Trial)
Pull changes made on the instance into a ServiceNow SDK (NOW SDK / Fluent) project, with the user's browser session and the project's own now-sdk (no separate now-sdk auth login). SN Utils downloads the app package, the SDK converts it into Fluent in a temporary copy of the project, and the differing files are copied into the project. Without instance, the app's linked instance (the one it was last deployed to or pulled from) is used.
Request:
{
"id": "pull_1",
"command": "sdk_pull",
"instance": "dev12345",
"params": { "projectPath": "my-fluent-app" }
}
Parameters:
projectPath(optional): the project folder (the one withnow.config.json), relative to the workspace root or absolute, and inside the workspace. Omit it when the workspace holds one NOW SDK project.dryRun(optional): only list what would change.force(optional): apply even when the project is not in git or an affected file has uncommitted edits. Only after the user agreed.
Response:
{ "status": "success", "result": {
"app": { "name": "My App", "scope": "x_1234_my_app", "version": "1.0.0" },
"instance": "dev12345",
"changes": [{ "path": "src/server/script-includes/util.js", "status": "modified" }],
"applied": ["src/server/script-includes/util.js"],
"upToDate": false
} }
- Review the applied files with
git diff; undo withgit checkout -- <file>. firstPull: true: the first pull also writes out defaults and IDs the ServiceNow SDK keeps in the source. Mention it so the user is not surprised by the extra lines.notOnInstance: files that are not in the instance package. They are never deleted; tell the user.notPulled: instance changes the SDK cannot write back to the source, with areason(generated UI pages, server modules, module glue scripts, build assets,@fluent-disable-sync). Tell the user to copy them into the source by hand; the next deploy would otherwise overwrite them.
Errors:
E_CONFIRM_REQUIRED: the project is not in git, or an affected file has uncommitted edits (details.uncommitted). Ask the user to commit first, or whether to passforce: true.E_PRO_REQUIRED,E_PAUSED,E_UNSUPPORTED_HOST: as forsdk_deploy.E_INVALID_PARAMS: no project found, a path outside the workspace, the SDK not installed, an SDK version outside 4.1 to 4.x, or an app type ScriptSync does not handle.E_COMMAND_FAILED: the download or the conversion failed; the message says why (for example, the app is not installed on the instance).
`get_record`
Fetch a single record by table + sys_id. Cheaper and simpler than query_records when you already know the sys_id (e.g. to confirm a write).
Request:
{
"id": "get_1",
"command": "get_record",
"params": {
"table": "incident",
"sys_id": "abc123def456...",
"fields": "number,short_description,state,priority"
}
}
Parameters:
table(required): The ServiceNow table.sys_id(required): The record sys_id.fields(optional): Comma-separatedsysparm_fieldslist. Omit for all fields.
Response:
{
"status": "success",
"result": {
"table": "incident",
"sys_id": "abc123def456...",
"record": { "number": "INC0010001", "short_description": "...", "state": "2" }
}
}
Errors:
E_NOT_FOUND— no record with that sys_id.E_INVALID_PARAMS— missing table/sys_id.
`get_table_metadata`
Fetch the columns of a table, including the ones it inherits, with type, reference target, mandatory and read-only flags.
Request:
{ "id": "8", "command": "get_table_metadata", "params": { "table": "sys_script_include", "choices": false } }
Parameters:
table(required): table name.choices(optional, defaultfalse): include{ value, label }choices per choice field. Without it a choice field only carrieschoiceCount.
Response (VS Code host): columns is the instance's form metadata keyed by column name, as before. fields is the same list normalized:
{
"result": {
"columns": { "name": { "label": "Name", "type": "string", "mandatory": false, "max_length": 100 } },
"fields": [
{ "name": "name", "label": "Name", "internalType": "string", "type": "string", "mandatory": false, "readOnly": false, "maxLength": 100 },
{ "name": "sys_scope", "label": "Application", "internalType": "reference", "type": "reference", "reference": "sys_scope", "mandatory": false, "readOnly": false, "maxLength": 32 }
]
}
}
Response (standalone bridge, snu schema): an array of the same normalized columns. Each keeps the API documentation keys name, label, internalType and exampleValue.
- A key that is missing means unknown, not false: the instance did not report it.
exampleValueis a generated sample from the REST API documentation, the same on every instance. It is never record data. Usequery_recordsfor real values.
`check_name_exists_remote`
Check if an artifact exists in ServiceNow (queries the actual instance, not just local files).
Request:
{ "id": "9", "command": "check_name_exists_remote", "params": { "table": "sys_script_include", "name": "MyUtils" } }
Response:
{
"result": {
"exists": true,
"sysId": "abc123def456",
"record": { "name": "MyUtils", "sys_scope": "global" }
}
}
`pull_records` (alias: `pull_artifacts`)
Pull records from ServiceNow and store their code fields into canonical local workspace files (<instance>/<scope>/<table>/<name>.<field>.<ext> or <table>/<name>/<field>.<ext> for folder-record tables) with automatic _map.json registration.
Key Advantage: Agents call this command over HTTP (port 1977) and never compete for the WebSocket client; the existing SN Utils helper tab remains connected and is required to fulfill the request via the authenticated session.
Request:
{
"id": "pull_1",
"command": "pull_records",
"params": {
"table": "sys_script_include",
"query": "nameSTARTSWITHincident^active=true",
"limit": 10,
"openFiles": false
}
}
Parameters:
table(required, string): ServiceNow table name (e.g.sys_script_include,sys_script,sp_widget). Must be alphanumeric/underscores.query(optional, string): ServiceNow encoded query string.sys_id(optional, string): Single 32-character hex sys_id (or'global'). Combined withqueryusing^(AND).sys_ids(optional, string[]): Array of 32-character hex sys_ids. Combined withqueryusing^(AND).fields(optional, string[] | string): Custom code fields to pull. If omitted, fields and file extensions are automatically discovered from table metadata (e.g.scriptforsys_script,template/client_script/css/scriptforsp_widget).limit(optional, integer): Max records to pull (1to500, default:50). Values outside this range returnE_INVALID_PARAMS.openFiles(optional, boolean): Whether to open each written file in active VS Code editor tabs (default:falseto avoid tab spam).
Response:
{
"status": "success",
"result": {
"table": "sys_script_include",
"matchedRecords": 2,
"pulledRecords": 2,
"filesWritten": 2,
"skippedEmpty": 0,
"warnings": [],
"records": [
{
"sys_id": "9659b9900a0a0b340079eb7c8a410eb8",
"name": "IncidentUtils",
"scope": "global",
"files": [
{
"field": "script",
"path": "dev12345/global/sys_script_include/IncidentUtils.script.js",
"bytes": 1420,
"action": "updated"
}
]
}
]
}
}
Behavior & Rules:
_map.jsontracking: Maintains<instance>/<scope>/<table>/_map.json. If a record was previously pulled, its existing mapped name is preserved. Name collisions receive a"-XXXX"sys_id suffix.- Folder record tables: Tables in
FOLDERRECORDTABLES(such assp_widget,sp_header_footer,sys_ui_page) are stored in subfolders (sp_widget/<name>/template.html,client_script.js,css.scss,script.js). - Empty remote fields: If a remote field has no content and a local file already exists, the local file is cleared (action:
cleared) to prevent stale code. If no local file exists, it is skipped (action:skipped_empty). - Self-write protection: Every written file is marked as a self-write to prevent the file watcher from triggering an unnecessary sync-back loop to ServiceNow.
Errors:
E_INVALID_PARAMS— invalid table name, invalid sys_id format, orlimitout of range[1, 500].E_BROWSER_DISCONNECTED— the SN Utils helper tab is not connected.E_PAUSED— agent commands are paused in the SN Utils helper tab.E_COMMAND_FAILED— ServiceNow Table API query failed.
`pull_scope`
Pull every scriptable artifact of one application scope into canonical local workspace files (<instance>/<scope>/<table>/<name>.<field>.<ext>, or <table>/<name>/<field>.<ext> for folder-record tables) with _map.json registration, so an agent can work from local files instead of fetching artifacts one by one. This is the Agent API counterpart of the VS Code Load Scope button.
The command first lists which artifact tables the application actually uses, then walks each table that sn-scriptsync knows how to write to disk, paging past the Table API limits. Tables without code fields (properties, roles, ACL rows without scripts, ...) are reported under skippedTables and not written.
Request:
{
"id": "pull_scope_1",
"command": "pull_scope",
"params": { "scope": "x_acme_app" }
}
Parameters:
scope(required, string): Application scope name (x_acme_app) or thesys_scopesys_id.globalis refused: pull global artifacts withpull_recordsand a query instead.tables(optional, string[]): Restrict the pull to these tables. Tables that hold no records in the scope are reported inwarnings.limit(optional, integer): Maximum records per table,1to10000(default2000). A table that hits the limit is markedtruncated.includeRecords(optional, boolean): Return the per-record file list inside each table entry (defaultfalse, keeps the response small for large applications).
Response:
{
"result": {
"scope": { "name": "x_acme_app", "sys_id": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" },
"folder": "dev221527/x_acme_app",
"tables": [
{ "table": "sys_script", "matchedRecords": 12, "pulledRecords": 12, "filesWritten": 12, "skippedEmpty": 0, "truncated": false },
{ "table": "sys_script_include", "matchedRecords": 140, "pulledRecords": 140, "filesWritten": 140, "skippedEmpty": 0, "truncated": false }
],
"totals": { "tables": 2, "records": 152, "filesWritten": 152, "skippedEmpty": 0 },
"skippedTables": [ { "table": "sys_properties", "records": 4, "reason": "no_scriptable_fields" } ],
"warnings": [],
"complete": true,
"outcome": "complete"
}
}
outcome says what the pull achieved. Check it, not only the HTTP status:
complete— every table with script fields was pulled and verified.partial— files were written, but something was skipped (reason: "dictionary_unavailable"), could not be verified, or hitlimit.noteandwarningssay which. Re-run, or pull the named tables withpull_records.empty— the scope has no records in tables with script fields, established from a complete record list. Nothing to do.- Discovery failure is an error, not an outcome:
E_DISCOVERY_FAILED(HTTP 422, CLI exit 1) when no table could be pulled because the instance dictionary could not be read, or because the list of the scope's records was incomplete, so emptiness could not be established.detailsholds the full report above, including every skipped table and warning. Pull single tables withpull_recordsmeanwhile.
When the instance dictionary cannot be read for a table, known tables fall back to the field definitions bundled with sn-scriptsync and snu, with a warning; a table is only reported as no_scriptable_fields when its dictionary was read completely.
Existing local files for the same records are refreshed in place and keep their file names through _map.json; a remote field that is now empty clears the local file. Run it again at any time to re-sync the whole application.
`analyze_artifact_type`
Read-only. Samples existing artifacts of one type on the instance and compares them into a type profile: what records make up one artifact of this type, how often each appears, what the platform creates for you, what the creation path changes, and what the scan could and could not see. Use it before building a composite artifact you have not built on this instance in this project, then build with create_records and ask the user about everything labeled choice.
When to use it, and when not: it costs many reads and returns a large result.
- Use before creating a new table or catalog item on an instance where you have not built one in this project, and as a diagnostic when a create succeeded but the result does not behave (a role cannot see the new table, an item does not show its variables).
- Do not use for a single record, an edit to an existing artifact, or a type you already have a fresh profile for.
Supported types in this version: table (root sys_db_object) and catalog_item (root sc_cat_item). UI Builder pages are not profiled by this command.
Requires: browser helper tab connected. No permission gate: every request is a GET through the helper tab, as the connected user. The profile is written to the local workspace (<instance>/_profiles/), never to the instance.
Request:
{ "id": "prof_1", "command": "analyze_artifact_type", "instance": "dev12345", "params": { "type": "table", "scope": "x_acme_app" } }
Parameters:
type(required):tableorcatalog_item.roots(optional): up to 30 sys_ids to analyze instead of a sample.query(optional): extra encoded query to narrow the sample (no^NQ, nojavascript:).scope(optional): only samples from this application scope.sample(optional, 1 to 30, default 12): how many samples. Tables created by thesystemuser (machine-made, for example CMDB query builder results) are excluded and counted unlessincludeGenerated: true.detail(optional): classify the records around each sampled root (slower; best withroots).refresh(optional): analyze again even when a saved profile is still fresh.save: falseskips writing the file.
Reading the profile:
satellites[]: one entry per related table, each with three separate facets:observed:{ samples, of, perSample: { min, max } }, recurrence only;generated:yes/no/unknown, from recorded experiments only, withpath(for example "UI table form only") andevidence;required: the same,unknownunless an experiment or documentation says otherwise.label:platform(generated on every creation path tested: do not create it),convention(in every sample, not shown to be required: build it unless told otherwise and say that you did),choice(varies between samples: ask the user),not_observed,unknown(fewer than 3 samples or the probe could not be read).creationPaths[]: findings about how the artifact must be created, with evidence. For tables: the UI table form creates the role and four record ACLs; an API insert andcreate_tabledo not, so build them deliberately. For catalog items: settingsc_catalogsandcategorycreates their link rows; policy actions loseui_policyandcatalog_variablethrough the Table API.applicationAccess(tables): what other scopes may do with the table. A new scoped table lets other scopes, Global included, only read it.flows[](catalog items): each sampled fulfillment flow with its distinct subflows (followed up to 3 levels;usescounts repeated calls;cycleslists only subflows that call one of their own ancestors), and whether it asks for approval or sends notifications. An order waits for any approval before fulfillment tasks appear.sampleReports[]: per sample, satellite counts, root fields andprovenance(originwith aconfidenceand the rawsignals; inferred, not confirmed history). Withdetail,members[]andembeddedRefs[]:owned_by_reference: the record points at the root through its own container field.shared: other configuration uses it (a variable set linked by two or more items, a role guarding other tables).inherits_shared: belongs to a shared container (a variable of a shared set).no_other_use_found: nothing else found within the scan; not confirmed ownership.external: outside the artifact (a catalog, a category).dataReferences: rows such as order answers that reference the record; reported, never used to classify.coverage: probes run and their status (ok,restricted,error), embedded patterns searched, reference fields scanned, limits, unresolved embedded references, and the access note (everything is filtered by the connected user's ACLs; unreadable rows are invisible, not reported missing).freshness: the fingerprint used for reuse and its limitation. A saved profile is reused when type, scope, instance, analyzer version and the fingerprint match (reused: true).deferred[]: what this version does not do (UI Builder pages, non-admin CRUD verification for tables, general flow profiling).
Errors:
E_INVALID_PARAMS- unsupported type, bad roots, query, scope or sample.E_BROWSER_DISCONNECTED- no helper tab available.
`query_records` ⚡
Execute an arbitrary encoded query against any ServiceNow table. Use this to fetch data, check conditions, or explore records.
Request:
{
"id": "q1",
"command": "query_records",
"params": {
"table": "incident",
"query": "priority=1^active=true",
"fields": "number,short_description,priority,state,sys_created_on",
"limit": 5,
"orderBy": "ORDERBYDESCsys_created_on"
}
}
Parameters:
table(required): The ServiceNow table to queryquery(optional): Encoded query string (e.g.,priority=1^active=true)fields(optional): Comma-separated field names (default:sys_id,number,short_description,sys_created_on)limit(optional): Max records to return (default: 10)orderBy(optional): Order clause (e.g.,ORDERBYDESCsys_created_on)validate(optional, defaulttrue):falseruns the query without checking its field paths.referenceLinks(optional, defaulttrue):falsereturns each reference as its sys_id instead of a{ link, value }object, roughly halving reference-heavy results. To read a referenced value, dot-walk infieldsinstead (target_scope.scope).
Keep results small: always pass fields and limit. The defaults are four fields and 10 rows, and the result says when they applied.
Field paths are checked before the query runs. ServiceNow silently ignores a condition on a field that does not exist and returns unfiltered rows, so every path in query, fields (when you pass it) and orderBy is checked hop by hop against the table schema, including dot-walks and the field inside ORDERBY, DYNAMIC, OR/NQ branches. Values are not judged: javascript:gs.beginningOfToday() is fine once its field exists. Keyword search (123TEXTQUERY321) is supported. A related-list block (RLQUERY<table>.<field>,…^…^ENDRLQUERY) is checked against its own table; one without ENDRLQUERY is refused. A ref_<table> cast passes only when <table> really extends the reference target (checked in sys_db_object).
E_INVALID_QUERY— a path does not exist (e.g.question.cat_itemonquestion_choice:questionhas nocat_item; usequestion.ref_item_option_new.cat_item), or a non-reference field is dot-walked.details.problemslists each one with the failinghopandtable. The query was not run: fix the path.E_QUERY_UNVERIFIABLE— a path could not be checked (the table's columns could not be read, or an operator was not recognised). The query was not run. Passvalidate: falseonly when you are sure the query is right, for example a field your session cannot see the definition of.
Response:
{
"status": "success",
"result": {
"table": "incident",
"count": 3,
"records": [
{
"sys_id": "abc123",
"number": "INC0010001",
"short_description": "Server down",
"priority": "1",
"state": "2",
"sys_created_on": "2024-12-07 10:30:00"
},
...
]
}
}
What the result left out: besides table, count and records, the result carries limit, more (true when more records match than were returned), total (the instance's own count, when it reports one), defaultFields / defaultLimit (true when the defaults applied) and a note in words. With more: true, raise limit or narrow the query; never treat the first page as everything.
Common Query Examples:
| Use Case | Query |
|----------|-------|
| Get single record by sys_id | sys_id=abc123def456... |
| Active P1 incidents | priority=1^active=true |
| Recent changes | ORDERBYDESCsys_created_on |
| My assigned tasks | assigned_to=javascript:gs.getUserID()^active=true |
| Open problems | state!=7^state!=8 |
| Items in scope | sys_scope.scope=x_myapp |
| Name contains | nameLIKEutils |
| Created today | sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday() |
Encoded Query Operators:
=equals!=not equalsLIKEcontainsNOT LIKEdoes not contain (the space is required)STARTSWITHstarts withENDSWITHends with>greater than<less than>=greater or equal<=less or equalINin list (comma-separated)NOT INnot in list (comma-separated; the space is required)ISEMPTYis emptyISNOTEMPTYis not empty^AND^OROR^NQnew query (OR group)
`get_parent_options`
Get available parent records for reference fields. Use this to find existing REST API services, tables, etc.
Request:
{
"id": "10",
"command": "get_parent_options",
"params": {
"table": "sys_ws_definition",
"scope": "x_myapp",
"nameField": "name",
"limit": 50
}
}
Parameters:
table(required): The parent table to query (e.g.,sys_ws_definitionfor REST API services)scope(optional): Filter by scope namenameField(optional): Field to use as display name (default:name)limit(optional): Max records to return (default: 50)
Response:
{
"result": {
"table": "sys_ws_definition",
"count": 3,
"options": [
{ "sys_id": "abc123", "name": "My REST API", "scope": "x_myapp" },
{ "sys_id": "def456", "name": "Another API", "scope": "global" },
{ "sys_id": "ghi789", "name": "Third API", "scope": "x_myapp" }
]
}
}
Common use cases:
| Creating | Query table | To get |
|----------|-------------|--------|
| REST API Operation | sys_ws_definition | Available REST API services |
| Business Rule | sys_db_object | Available tables |
| UI Action | sys_db_object | Available tables |
| Client Script | sys_db_object | Available tables |
`code_search` ⚡ (Pro feature)
Run the SN Utils GraphQL field-index code search across ServiceNow script tables and return structured matches. This is the same engine as the SN Utils code search page — far better than a plain query_records LIKE at finding where a term actually lives in scripts (script includes, business rules, UI actions, client scripts, fix scripts, etc.). Use it to discover existing code before writing new artifacts.
Requires: an active SN Utils Pro / Trial / Enterprise license in the connected browser helper tab. Without it the command returns E_DISABLED.
Request:
{
"id": "cs_1",
"command": "code_search",
"instance": "dev12345",
"params": {
"term": "sn_appclient dev mode",
"activeOnly": false,
"limit": 50
}
}
Parameters:
term(required): Search term. Supports the sametable:/ field filters as the code search page (e.g.table:sys_script_include setPreference). Minimum 2 characters.activeOnly(optional, defaultfalse): Only match active records.limit(optional, default50): Max records per table.compact(optional, defaultfalse): Return only{ table, label, count, names }per table instead of every hit with its matching lines. Search compact first: full results for a common term run to hundreds of kilobytes. Then read the records you need withget_record.tables(optional, string or string[]): Exact table names as a comma-separated string or an array, for example"sys_script_include,sys_script"or["sys_script_include", "sys_script"]. Empty values leave the search scope unrestricted. Inlinetable:filters intermfurther narrow this selection; unknown names produce no matches. Applying this parameter requires an updated SN Utils browser extension; with an older helper, usetable:<name>interm.
Response:
{
"status": "success",
"result": {
"term": "sn_appclient dev mode",
"stats": { "tables": 3, "records": 7, "matches": 12, "searchedTables": ["sys_script_include", "sys_script", "sys_ui_action"] },
"words": ["sn_appclient", "dev", "mode"],
"results": [
{
"tableName": "sys_script_include",
"tableLabel": "Script Include",
"rowCount": 2,
"hits": [
{
"sysId": "abc123...",
"name": "AppClientUtils",
"sysClassName": "sys_script_include",
"active": true,
"matches": [
{
"field": "script",
"fieldLabel": "Script",
"matchingWords": ["dev", "mode"],
"context": "...if (current.dev_mode) { ... }...",
"lineMatches": [
{ "lineNumber": 42, "content": " var devMode = gs.getProperty('sn_appclient.dev_mode');", "isMatch": true }
]
}
],
"missingWords": null,
"parentRef": null
}
]
}
]
}
}
Response shape:
result.stats—tables,records,matches(total field matches), andsearchedTables(the tables actually queried).result.words— the tokenized search terms the engine looked for.result.results[]— one entry per matching table:tableName,tableLabel,rowCount,hits[].- Each hit:
sysId,name,sysClassName(real class of the record),active(true/false/null),matches[],missingWords(terms not found in this record, ornull), andparentRef({ table, sysId, label }when the value lives on a parent record, e.g. a variable value — elsenull). - Each match:
field,fieldLabel,matchingWords(which terms hit this field),context(a short excerpt), andlineMatches[]for line-level rendering —{ lineNumber, content, isMatch }(each match line plus a little surrounding context;isMatchflags the line(s) that actually contain a term).
Notes:
- Matches are excerpts —
contextplus a handful oflineMatches, not full field bodies. To get the complete script of a specific hit, follow up withget_record(using the hit'stableName+sysId). - The first search after the helper tab opens may take longer while the field index builds; later searches reuse the cached per-instance index.
- Inline scripts in flows are not searched: Flow Designer stores a flow's action inputs compressed. Script steps in custom actions are searched.
Errors:
E_DISABLED— no SN Utils Pro/Trial/Enterprise license in the connected browser.E_INVALID_PARAMS— missing/shortterm.E_BROWSER_DISCONNECTED— no helper tab connected.
`rest_request` (guarded generic passthrough)
Make an arbitrary ServiceNow REST call through the connected browser session (reuses its authentication). The escape hatch for anything the typed commands don't cover.
Gating:
GET— always allowed.POST/PUT/PATCH— requiresn-scriptsync.restRequest.enabled(VS Code) orSNU_ALLOW_REST_REQUEST=1(standalonesnuhost).DELETE— requiressn-scriptsync.deleteRecords.enabled(VS Code) orSNU_ALLOW_DELETE_RECORDS=1(standalonesnuhost).POST /api/now/v1/batch(the Batch API) is gated by the requests inside itsrest_requestsarray, not by the outerPOST: a batch holding aDELETEsub-request, or whose body cannot be read, needs the delete permission as well as the REST write permission and goes through the Review Queue with its sub-requests listed on the card. A batch of reads and writes needs the REST write permission only. For bulk deletes preferdelete_recordwithquery+limit: one review, an outcome per record.
Both hosts implement this command. Over MCP it is also reachable as the snu_rest_request tool, and a plain record insert has a dedicated wrapper, snu_create_record, that returns the inserted record instead of a raw HTTP envelope.
Request:
{
"id": "rest_1",
"command": "rest_request",
"params": {
"endpoint": "/api/now/table/incident",
"method": "GET",
"queryParams": { "sysparm_limit": "1", "sysparm_query": "active=true" }
}
}
Parameters:
endpoint(required): Instance-relative path beginning with/(e.g./api/now/table/incident).method(optional, defaultGET): one ofGET,POST,PUT,PATCH,DELETE.body(optional): JSON body for write methods.queryParams(optional): Object of query-string parameters.
Response:
{ "status": "success", "result": { "status": 200, "data": { "result": [ { "...": "..." } ] } } }
Errors:
E_DISABLED— the method is gated off by settings.E_INVALID_PARAMS— missing/invalid endpoint or method.E_NOT_FOUND/E_REFERENCE_INTEGRITY/E_ACL— mapped from the HTTP response.
`run_background_script` ⚠️ (guarded — runs server-side code)
Execute a server-side background script (/sys.scripts.do) on the instance and return its captured output. Runs as the connected browser user, in the global scope. Disabled by default — enable sn-scriptsync.backgroundScripts.enabled.
Request:
{
"id": "bg_1",
"command": "run_background_script",
"params": { "script": "gs.print('Active incidents: ' + new GlideAggregate('incident').getRowCount());" }
}
Parameters:
script(required): The server-side script to run. Usegs.print(...)to emit output you want back.
Response:
{ "status": "success", "result": {
"executed": true,
"output": "[0:00:00.1] Script completed … <PRE>*** Script: Active incidents: 42<BR/>[CacheFlushLog] …</PRE>",
"stdout": "Active incidents: 42",
"warnings": [], "errors": [], "logLines": ["[CacheFlushLog] …"],
"executionId": "47eea1d697485f14c3e2fc90f053af06",
"status": "completed"
} }
outputis the raw page text, unchanged. Readstdoutfor yourgs.printlines;errorsholds evaluator errors (status: "failed"),logLinesthe platform's own log noise.executionIdis thesys_script_execution_historyrecord of the run.
Errors:
E_DISABLED—sn-scriptsync.backgroundScripts.enabledis off, or the instance gate is set to Off in the helper tab.E_REVIEW_PENDING— the instance gate is set to Approve: the script is waiting in the helper tab Review Queue. Tell the user to approve it in the SN Utils ScriptSync helper tab in their browser, then collect the output withget_review_result.E_USER_REJECTED— the developer rejected the script in the Review Queue; don't retry without asking.E_UNAUTHORIZED— the instance refused the session before running the script (session lost, or the user can't run background scripts). Only when the reply proves the script never ran is the token refreshed and the script run once more; otherwise nothing is replayed.E_TIMEOUT/E_BROWSER_DISCONNECTED— the wait ended, not necessarily the script: it may still be running or may have finished. Never run a mutating script again after these. Check its effect first (query the records it changes).E_INVALID_PARAMS— missingscript.
The pragmatic escape hatch for bulk data fixes that the typed commands don't cover. Output is whatever
/sys.scripts.doreturns (thegs.printlines plus the server's evaluation log).
`list_tables`
List available table folders in the instance.
Request:
{ "id": "3", "command": "list_tables" }
Response:
{
"result": {
"tables": ["sys_script_include", "sys_script", "sp_widget"]
}
}
`list_artifacts`
List artifacts in a specific table.
Request:
{ "id": "4", "command": "list_artifacts", "params": { "table": "sys_script_include" } }
Response:
{
"result": {
"artifacts": ["global/MyUtils.script.js", "global/HelperFunctions.script.js"]
}
}
`check_name_exists`
Check if an artifact name already exists (checks local _map.json files only, not ServiceNow).
Request:
{ "id": "5", "command": "check_name_exists", "params": { "table": "sys_script_include", "name": "MyUtils" } }
Response:
{
"result": {
"exists": true,
"sysId": "abc123def456"
}
}
`get_file_structure`
Get the expected file naming convention.
Request:
{ "id": "6", "command": "get_file_structure" }
Response:
{
"result": {
"pattern": "{instance}/{scope}/{table}/{name}.{field}.{ext}",
"example": "myinstance/global/sys_script_include/MyUtils.script.js",
"fields": {
"sys_script_include": ["script"],
"sys_script": ["script"],
"sp_widget": ["script", "css", "client_script", "link", "template"]
}
}
}
`validate_path`
Validate a proposed file path before creating it.
Request:
{ "id": "7", "command": "validate_path", "params": { "path": "myinstance/global/sys_script_include/NewUtil.script.js" } }
Response:
{
"result": {
"valid": true,
"parsed": {
"instance": "myinstance",
"scope": "global",
"table": "sys_script_include",
"file": "NewUtil.script.js"
}
}
}
`open_in_browser`
Open an artifact in the browser. For widgets, opens the preview page; for other artifacts, opens the form view.
Request (with sys_id):
{
"id": "3",
"command": "open_in_browser",
"params": {
"table": "sp_widget",
"sys_id": "abc123def456"
}
}
Request (with name - looks up sys_id from _map.json):
{
"id": "3",
"command": "open_in_browser",
"params": {
"table": "sp_widget",
"name": "MyWidget",
"scope": "global"
}
}
Response:
{
"result": {
"opened": true,
"url": "https://instance.service-now.com/$sp.do?id=sp-preview&sys_id=abc123def456",
"table": "sp_widget",
"sys_id": "abc123def456"
}
}
URL patterns by table:
| Table | URL Pattern |
|-------|-------------|
| sp_widget | /$sp.do?id=sp-preview&sys_id={sys_id} (Widget Preview) |
| sp_page | /sp?id={name} (Portal Page) |
| Other tables | /{table}.do?sys_id={sys_id} (Standard Form) |
`get_served_url`
Resolve the URL an artifact is actually served at — without opening a tab. UI pages render at <instance>/<name>.do, Service Portal pages at /sp?id=..., widgets in the preview harness — not at their record form. Handy before navigate_and_screenshot or for sharing a link.
Handles the scoped prefix automatically. A UI page named todo_app in scope x_acme_app is stored with the unprefixed name todo_app, but ServiceNow serves it at /x_acme_app_todo_app.do. This command reads the record's scope (sys_scope.scope) and prepends it (guarding against double-prefixing if the name already carries the scope), so you get /x_acme_app_todo_app.do — not the 404-prone /todo_app.do.
Request:
{ "id": "url_1", "command": "get_served_url", "params": { "table": "sys_ui_page", "name": "my_page" } }
Parameters:
table(required).sys_id— orname(+ optionalscope) to resolve the sys_id from the local_map.json.
Response:
{ "status": "success", "result": { "url": "https://dev.service-now.com/x_acme_app_my_page.do", "table": "sys_ui_page", "name": "my_page" } }
Errors:
E_INVALID_PARAMS— neithersys_idnornameprovided.
`refresh_preview`
Refresh browser tabs showing the artifact preview. Useful after updating a widget to see changes immediately.
Request:
{
"id": "4",
"command": "refresh_preview",
"params": {
"table": "sp_widget",
"sys_id": "abc123def456"
}
}
Request (with name):
{
"id": "4",
"command": "refresh_preview",
"params": {
"table": "sp_widget",
"name": "MyWidget",
"scope": "global"
}
}
Response:
{
"result": {
"refreshed": true,
"sys_id": "abc123def456",
"testUrls": [
"https://instance.service-now.com/$sp.do?id=sp-preview&sys_id=abc123def456*",
"https://instance.service-now.com/sp?id=mywidget*"
],
"message": "Refresh command sent for sp_widget"
}
}
Note: This refreshes ALL browser tabs matching the widget's preview URLs, plus the active tab if it's on the same instance.
`take_screenshot` ⚡ (Remote - Async)
Take a screenshot of a ServiceNow page. The browser picks the best capture path it actually has — no capability juggling needed on your side:
- activeTab (tab already granted): captures directly, as always.
- Chrome debugger: when the grant is missing and the connected build supports it (Debug edition + Pro +
sn-scriptsync.browserDebugger.enabled), the browser captures via the debugger instead — no user action, just a brief flash of Chrome's debugger banner. The result carries"capturedVia": "debugger". - Ask the user: only when neither path works does
E_SCREENSHOT_PERMISSIONsurface — the user must click the SN Utils extension icon on the target tab, and a retry is built in (see below).
Permission notes (regular build — most users):
- First screenshot: user must click the SN Utils extension icon on the target tab to grant permission
- Subsequent screenshots: reuse the same tab without re-approval (when possible)
Request:
{
"id": "14",
"command": "take_screenshot",
"params": {
"url": "https://instance.service-now.com/sp?id=my_widget"
}
}
Parameters:
url(required if no tabId): The full URL to capturetabId(optional): Specific browser tab ID to capture (alternative to url)fileName(optional): Custom filename (defaults toscreenshot_TIMESTAMP.png)exactUrl(optional): Whentrue, do not reuse the last-captured tab — target the giventabId/urlstrictly. Use when you must capture a precise page. (navigate_and_screenshotsets this automatically.)focus(optional, defaultfalse): Leave the captured tab in front afterwards. The capture has to bring the tab forward for a moment; by default it then switches back to the tab the user had open.
Response (success):
{
"id": "14",
"command": "take_screenshot",
"status": "success",
"timestamp": 1733779200000,
"result": {
"saved": true,
"filePath": "/workspace/screenshots/screenshot_2024-12-09T14-00-00.png",
"fileName": "screenshot_2024-12-09T14-00-00.png",
"url": "https://instance.service-now.com/sp?id=my_widget",
"tabTitle": "My Widget - ServiceNow",
"capturedVia": "activeTab"
}
}
capturedVia is "activeTab" or "debugger" — which path actually produced the image.
Response (permission needed):
{
"id": "14",
"command": "take_screenshot",
"status": "error",
"code": "E_SCREENSHOT_PERMISSION",
"error": "Screenshot requires permission. Click the SN Utils extension icon on the tab you want to capture, then retry."
}
The extension auto-retries once (~10s) after a permission error before surfacing E_SCREENSHOT_PERMISSION, giving the user time to click the extension icon — so a "slow" screenshot call usually means the grant flow is in progress, not a hang. The retry stays pinned to the tab selected by the first attempt so a ServiceNow redirect cannot open duplicate tabs.
Use cases:
- Capture widget preview for visual verification
- Document UI state during development
- Debug visual issues
Behavior:
- Screenshots are saved to
{workspace}/screenshots/folder - The browser extension must be connected
- Tab reuse: Requests prefer an open tab on the same ServiceNow instance; retries stay pinned to the selected tab, and later screenshots reuse the last captured tab when possible
- If no matching tab is found, a new tab will be opened
Handling permission errors:
If E_SCREENSHOT_PERMISSION surfaces, the debugger route was already tried or isn't available — inform the user they need to click the SN Utils extension icon, then retry the screenshot command. (If the error's details say cdpFallbackAvailable: true, the build could do debugger captures but the user hasn't enabled sn-scriptsync.browserDebugger.enabled — you can mention that as an alternative.)
`navigate_and_screenshot`
Open/activate a URL, wait for it to finish loading, settle briefly, then screenshot that exact tab — collapsing the activate → sleep → screenshot dance into one call. The PNG is saved under screenshots/.
Request:
{
"id": "nss_1",
"command": "navigate_and_screenshot",
"params": { "url": "https://dev.service-now.com/incident.do?sys_id=-1", "settleMs": 1500 }
}
Parameters:
url(required): URL to open/activate (opens a tab if none matches).settleMs(optional, default1500): Extra wait after load before capture.fileName(optional): Output filename underscreenshots/.reload(optional): Force a reload of an already-open tab.
Response:
{ "status": "success", "result": { "saved": true, "filePath": ".../screenshots/screenshot_....png", "tabId": 42, "url": "https://dev.service-now.com/incident.do?sys_id=-1", "tabTitle": "Incident | ServiceNow", "navigated": true } }
Verify url/tabTitle match the page you intended — cheaper than rendering the image.
Errors:
E_SCREENSHOT_PERMISSION— the browser could not capture the tab. Navigation has already happened at that point, so the target page is on screen; the same capture routing and recovery astake_screenshotapplies (debugger path when available, then a ~10s icon-click retry window).E_INVALID_PARAMS— missingurl.
`run_slash_command` ⚡ (Remote - Async)
Execute SN Utils slash commands on a ServiceNow tab. Particularly useful for debugging forms with /tn (show technical names).
⚠️ IMPORTANT: Only use DOCUMENTED slash commands!
Documented commands include:
/tn- Toggle technical names on forms/bg- Open background scripts/token- Refresh the session for an explicitly targeted instance when auto-run; manual use opens the helper tab for connection/sn- Search navigator/xml- Show XML of current record/rnd- Fill empty mandatory form fields with test data;/rnd -afills all empty editable fields. Requires admin or impersonation. UI16 and Service Portal are Free; Configurable Workspace requires SN Utils Pro (including an active trial). Leaves the form unsaved.- See SN Utils documentation for full list
❌ Do NOT use non-existent commands like /click, /select, etc.
Request:
{
"id": "14",
"command": "run_slash_command",
"params": {
"command": "/tn",
"url": "https://*.service-now.com/*",
"autoRun": true
}
}
Parameters:
command(required): The slash command to run (e.g.,/tn,/bg,tn- leading slash is optional)url(optional): URL pattern to find the tab (default:https://*.service-now.com/*). Automatic/tokenneeds a specifictabIdor an exact instance URL, optionally ending in/*; it has no wildcard default.tabId(optional): Specific browser tab ID to targetautoRun(optional): Auto-execute the command (default:true)focus(optional, defaultfalse): Bring the tab to the front. Tabs an agent drives stay in the background so the user can keep working; settruewhen the user asks to see the page.
Response (success):
{
"id": "14",
"command": "run_slash_command",
"status": "success",
"timestamp": 1733779200000,
"result": {
"executed": true,
"status": "completed",
"summary": { "status": "completed", "state": "enabled", "enabled": true, "total": 8, "visible": 8 },
"slashCommand": "/tn",
"tabId": 12345,
"autoRun": true
}
}
Response (error):
{
"id": "14",
"command": "run_slash_command",
"status": "error",
"error": "No ServiceNow tab found matching: https://*.service-now.com/*"
}
Completion status:
result.status is dispatched, completed, cancelled, or error. executed is retained for compatibility and only confirms delivery. Always inspect the status before deciding what to do next.
dispatched: delivered to the page, with no completion confirmation. This includesautoRun: false, commands without result reporting, custom overrides of/rnd,/tn,/bgor/xml, and older helpers without a reported outcome.completed: the reported action finished. The meaning is specific to the command; opening a tab does not mean its content has loaded or a script has run.cancelled: the action stopped, for example because the active Workspace record changed during/rnd.error: the action failed./rndcan include partial results and a reason insummary. Delivery, navigation and token-refresh failures use the standard Agent API error response withdetails.status: "error".
Additional built-in results (updated SN Utils and ScriptSync required):
| Command | result.summary |
| --- | --- |
| /tn | state: enabled, disabled, mixed, or unavailable; enabled: true, false, or null for mixed/unavailable; total and visible: technical-name element counts across reachable frames. Waits for Workspace toggling to finish. These are element counts, not field counts or viewport visibility. |
| /bg, /xml | url and tabId of the tab the helper created. result.tabId remains the source tab. The new tab stays in the background unless focus: true. /xml resolves the current active form and requires a saved record. |
| /token | refreshed: true and origin identifying the refreshed instance. No token or credentials are included in the summary. Existing session-refresh permission checks still apply. |
Random-fill completion (/rnd):
With an updated SN Utils extension, autoRun: true waits for the built-in /rnd to finish, including dependent fields and retries. The ScriptSync Agent API returns result.summary:
Workspace filling requires SN Utils Pro, Enterprise or an active Pro trial. UI16 and Service Portal remain available on Free. Without the required entitlement, a Workspace request returns the standard Agent API error E_PRO_REQUIRED with details.status: "error", before writing any fields. The stripped Community build does not include Workspace filling. This gate is identical for manual use and agent requests; do not retry a blocked fill through another command or script.
{
"status": "completed",
"ui": "workspace",
"table": "incident",
"sysId": "0123456789abcdef0123456789abcdef",
"mode": "mandatory",
"total": 4,
"filled": 3,
"skipped": 1,
"pending": 0,
"revalidated": 3
}
- Always inspect
summary.status:completed,cancelled(active Workspace form changed), orerror(for example, no form or insufficient access). Cancellation and errors includereasonand any partial counts. - Workspace uses the active record tab at execution time. If that form changes during a fill, pending writes stop and the summary is
cancelled; run again only when the intended form is active. filledandskippedcount unique fields by their last fill attempt; retries do not inflate these counts.pendingcounts targets not attempted, andtotal = filled + skipped + pending.revalidatedcounts retry attempts across fields.uiisworkspace,classic(UI16), orportal.tableandsysIdidentify the original form and may be null when unavailable.modeismandatory,all(including-all), orxss(-xss).- The summary contains no field values. Use
get_form_statewhen you need current values. The command does not save or submit the form. - Commands without completion reporting,
autoRun: false, older helpers without reported outcomes, and custom overrides of/rndreturndispatchedand may omitsummary. Do not interpretexecuted: truealone as proof that fields were filled. - A page timeout returns
E_TIMEOUT. The fill may still be running; inspect the form before deciding whether to retry.
Why /tn matters:
When debugging form issues, you need to know the actual field names (not just labels). The /tn command toggles the display of technical field names on any ServiceNow form.
Before /tn:
Short Description: [Server is down]
Priority: [1 - Critical]
Assignment Group: [Network Support]
After /tn:
short_description: [Server is down]
priority: [1 - Critical]
assignment_group: [Network Support]
Recommended debugging workflow:
1. User reports form issue: "The priority field won't save"
2. AI activates the form tab and runs /tn:
{ "command": "run_slash_command", "params": {
"command": "/tn",
"url": "https://*.service-now.com/*incident*"
}}
3. AI takes a screenshot to see the technical field names:
{ "command": "take_screenshot", "params": {
"url": "https://*.service-now.com/*incident*"
}}
4. Now AI knows the exact field name (e.g., "priority")
to investigate in Business Rules, Client Scripts, etc.
`activate_tab` ⚡ (Remote - Async)
Find and activate a browser tab by URL pattern. Useful for navigating to specific ServiceNow pages or ensuring a tab is ready before taking screenshots.
Request:
{
"id": "14",
"command": "activate_tab",
"params": {
"url": "https://*.service-now.com/nav_to.do*",
"reload": true,
"waitForLoad": true,
"openIfNotFound": false
}
}
Parameters:
url(required): URL pattern to match (supports wildcards like*)reload(optional): Whether to reload the tab after activating (default:false)waitForLoad(optional): Wait for page load to complete before responding (default:false)openIfNotFound(optional): Open a new tab with the URL if no matching tab exists (default:false)
Response (success):
{
"id": "14",
"command": "activate_tab",
"status": "success",
"timestamp": 1733779200000,
"result": {
"activated": true,
"tabId": 12345,
"url": "https://instance.service-now.com/nav_to.do?uri=incident.do?sys_id=abc123",
"title": "Incident | ServiceNow",
"opened": false,
"reloaded": true
}
}
Response (tab not found):
{
"id": "14",
"command": "activate_tab",
"status": "error",
"error": "No tab found matching: https://*.service-now.com/nav_to.do*"
}
Use cases:
- Activate a ServiceNow tab before taking a screenshot
- Reload a page to see updated changes
- Navigate to a specific record form
- Ensure a widget preview tab is ready
URL Pattern Examples:
| Pattern | Matches |
|---------|---------|
| https://*.service-now.com/* | Any ServiceNow page |
| https://myinstance.service-now.com/sp?id=my_widget* | Specific widget page |
| https://*.service-now.com/nav_to.do* | Any classic UI page |
| https://*.service-now.com/$sp.do?id=sp-preview* | Widget preview pages |
Workflow: Activate tab → Take screenshot:
1. Activate tab with reload to ensure fresh content
{ "command": "activate_tab", "params": {
"url": "https://*.service-now.com/sp?id=my_widget*",
"reload": true,
"waitForLoad": true
}}
2. Take screenshot (tab is already active and ready)
{ "command": "take_screenshot", "params": {
"url": "https://instance.service-now.com/sp?id=my_widget"
}}
`switch_context` ⚡ (Remote - Async)
Switch ServiceNow context: update set, application scope, or domain. This uses the ServiceNow UI Concourse Picker API to change the active context in the browser session.
Request:
{
"id": "15",
"command": "switch_context",
"params": {
"switchType": "updateset",
"value": "abc123def456789012345678901234",
"reloadTab": true,
"tabUrl": "https://*.service-now.com/*"
}
}
Parameters:
switchType(required): Type of context to switch. Must be one of:updateset- Switch the current update setapplication(orapp) - Switch the application scopedomain- Switch the domain (for domain-separated instances)value(required): The sys_id of the target update set, application, or domainreloadTab(optional): Whether to reload a ServiceNow tab after switching (default:true)tabUrl(optional): URL pattern to find the tab to reload (default:https://*.service-now.com/*)
Response (success):
{
"id": "15",
"command": "switch_context",
"status": "success",
"timestamp": 1733779200000,
"result": {
"success": true,
"switchType": "updateset",
"value": "abc123def456789012345678901234",
"reloaded": true
}
}
Response (error):
{
"id": "15",
"command": "switch_context",
"status": "error",
"error": "Invalid switchType. Must be one of: updateset, application, domain"
}
Use cases:
- Switch to a specific update set before creating artifacts
- Change application scope to deploy code to the correct app
- Switch domain context in domain-separated instances
Finding the sys_id:
Before switching context, you may need to query for the sys_id:
1. Find update set sys_id:
{ "command": "query_records", "params": {
"table": "sys_update_set",
"query": "name=My Update Set^state=in progress",
"fields": "sys_id,name,state"
}}
2. Find application sys_id:
{ "command": "query_records", "params": {
"table": "sys_scope",
"query": "scope=x_myapp",
"fields": "sys_id,scope,name"
}}
3. Find domain sys_id:
{ "command": "query_records", "params": {
"table": "domain",
"query": "name=My Domain",
"fields": "sys_id,name"
}}
Examples:
Switch to a specific update set:
{
"id": "sw1",
"command": "switch_context",
"params": {
"switchType": "updateset",
"value": "abc123def456..."
}
}
Switch application scope (e.g., before creating artifacts):
{
"id": "sw2",
"command": "switch_context",
"params": {
"switchType": "application",
"value": "xyz789ghi012..."
}
}
Switch domain:
{
"id": "sw3",
"command": "switch_context",
"params": {
"switchType": "domain",
"value": "dom456jkl789..."
}
}
Workflow: Find update set → Switch → Create artifact:
1. Query for update set
{ "command": "query_records", "params": {
"table": "sys_update_set",
"query": "nameLIKEMyFeature^state=in progress",
"fields": "sys_id,name"
}}
2. Switch to the update set (using sys_id from response)
{ "command": "switch_context", "params": {
"switchType": "updateset",
"value": "<sys_id from step 1>"
}}
3. Create artifact (now goes into correct update set)
{ "command": "create_artifact", "params": {
"table": "sys_script_include",
"scope": "global",
"fields": { "name": "MyNewUtils", "script": "..." }
}}
`upload_attachment` ⚡ (Remote - Async)
Upload a file (image, document, etc.) as an attachment to any ServiceNow record.
Gating: createArtifacts (sn-scriptsync.createArtifacts.enabled in VS Code, SNU_ALLOW_CREATE_ARTIFACTS in the standalone snu host, or the per-instance grant in the SN Utils helper tab) — on by default. An upload inserts a sys_attachment row, so it carries the same permission as the other create_* commands and returns E_DISABLED when that permission is off.
Request (using filePath - recommended):
{
"id": "15",
"command": "upload_attachment",
"params": {
"table": "incident",
"sys_id": "abc123def456789012345678901234",
"filePath": "screenshots/screenshot_2024-12-09.png"
}
}
Request (using imageData - base64):
{
"id": "15",
"command": "upload_attachment",
"params": {
"table": "incident",
"sys_id": "abc123def456789012345678901234",
"fileName": "screenshot_2024-12-09.png",
"imageData": "iVBORw0KGgoAAAANSUhEUgAA...",
"contentType": "image/png"
}
}
Parameters:
table(required): The ServiceNow table the record belongs to (e.g.,incident,sp_widget,kb_knowledge)sys_id(required): The sys_id of the record to attach the file tofilePath(optional): Path to the file to upload. Can be absolute or relative to instance folder. If provided,fileNameandcontentTypeare auto-detected from the file.fileName(required if no filePath): Name for the attachment file. Auto-detected fromfilePathif not provided.imageData(required if no filePath): Base64-encoded file content. Auto-read fromfilePathif not provided.contentType(optional): MIME type. Auto-detected from file extension if not provided (default:image/png)
Response (success):
{
"id": "15",
"command": "upload_attachment",
"status": "success",
"timestamp": 1733779200000,
"result": {
"uploaded": true,
"fileName": "screenshot_2024-12-09.png",
"table": "incident",
"recordSysId": "abc123def456789012345678901234",
"attachment": {
"sys_id": "xyz789...",
"size_bytes": "45678",
"content_type": "image/png"
}
}
}
Response (error):
{
"id": "15",
"command": "upload_attachment",
"status": "error",
"error": "HTTP 403: Access denied"
}
Use cases:
- Attach screenshots to incidents or tasks
- Upload documentation images to knowledge articles
- Attach design assets to widgets or UI pages
- Add evidence/proof to change requests
Combining with take_screenshot:
A powerful workflow is to take a screenshot and then upload it as an attachment:
1. Take screenshot of a widget/page
{ "command": "take_screenshot", "params": { "url": "..." } }
Response includes: "filePath": "/workspace/screenshots/screenshot_2024-12-09_143022.png"
2. Upload as attachment using the ABSOLUTE filePath from the response
{ "command": "upload_attachment", "params": {
"table": "incident",
"sys_id": "...",
"filePath": "/workspace/screenshots/screenshot_2024-12-09_143022.png"
}}
⚠️ IMPORTANT: File Path Resolution
The upload_attachment command resolves relative paths from the instance folder, not the workspace root.
- Screenshots are saved to
{workspace}/screenshots/(workspace root) - Instance folder is
{workspace}/{instance}/(e.g.,empakooi/)
Always use ABSOLUTE paths for files outside the instance folder:
// ❌ WRONG - relative path will look in instance folder
{ "filePath": "screenshots/screenshot.png" }
// Resolves to: /workspace/empakooi/screenshots/screenshot.png (NOT FOUND)
// ✅ CORRECT - use absolute path from take_screenshot response
{ "filePath": "/Users/me/workspace/screenshots/screenshot.png" }
// Finds the actual file
Best practice: Copy the filePath value directly from the take_screenshot response.
Note: Using filePath eliminates the need to manually read and base64-encode files. The extension handles this automatically.
Supported content types (auto-detected from file extension):
| Extension | contentType |
|-----------|-------------|
| .png | image/png |
| .jpg, .jpeg | image/jpeg |
| .gif | image/gif |
| .webp | image/webp |
| .svg | image/svg+xml |
| .pdf | application/pdf |
| .txt | text/plain |
| .json | application/json |
| .xml | application/xml |
| .html | text/html |
| .css | text/css |
| .js | application/javascript |
| .zip | application/zip |
| .doc | application/msword |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| .xls | application/vnd.ms-excel |
| .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| Other | application/octet-stream |
`download_attachment` (bytes to a file, never to you)
Download one attachment (sys_attachment sys_id) to a file in the workspace. The result carries the file path, size, content type and sha256, never the bytes, so a binary file never lands in your context. Process the file locally (resize, convert, inspect) and send it back with upload_attachment using relativePath or filePath from the result.
Needs a current SN Utils helper tab (capabilities.attachmentDownload in get_capabilities); an older one answers E_UNSUPPORTED_HELPER. A read: no permission gate.
Request:
{ "id": "dl_1", "command": "download_attachment", "params": { "sys_id": "68cf699a97485f14c3e2fc90f053af5d" } }
Parameters:
sys_id(required): thesys_attachmentrecord.filePath(optional): where to write it. Relative paths resolve under the instance folder; absolute paths must stay inside the workspace. Default:<instance>/attachments/<sys_id>/<file name>.overwrite(optional, defaultfalse): replace an existing file. Without it an existing file is never touched (E_FILE_EXISTS).maxBytes(optional, default and maximum 50 MB): refuse larger attachments.
Response:
{ "status": "success", "result": {
"downloaded": true, "sys_id": "68cf699a97485f14c3e2fc90f053af5d",
"filePath": "/workspace/dev1/attachments/68cf699a97485f14c3e2fc90f053af5d/lineup.png",
"relativePath": "attachments/68cf699a97485f14c3e2fc90f053af5d/lineup.png",
"fileName": "lineup.png", "sizeBytes": 1748088, "contentType": "image/png",
"sha256": "…", "sourceTable": "sc_cat_item", "sourceSysId": "73da21de97085f14c3e2fc90f053aff3"
} }
The file is written to a temporary file first and published atomically only after its size and sha256 match what the helper read, so a file at filePath is always complete.
Errors:
E_UNSUPPORTED_HELPER— update SN Utils and reopen the ScriptSync helper tab. Do not fall back to base64 throughrun_background_scriptorrest_request.E_TOO_LARGE— larger thanmaxBytes.E_FILE_EXISTS— the target exists; pick another path or passoverwrite: true.E_ATOMIC_PUBLISH_UNSUPPORTED— the volume cannot publish without overwriting; choose another folder.E_TRANSFER_MISMATCH— the received bytes did not match; nothing was written. Retrying is safe (a read).E_SECURITY— the path leaves the workspace or goes through a symbolic link.E_NOT_FOUND— no such attachment.
`delete_attachment` ⚠️ (DESTRUCTIVE — guarded)
Delete one attachment through the Attachment API, which removes the sys_attachment row and its stored content. Prefer it over delete_record on sys_attachment.
Gating: the deleteRecords permission, like delete_record, including the helper-tab Review Queue when the instance gate is Approve (E_REVIEW_PENDING, then get_review_result). In snu, pass confirm: true (or --confirm).
Request:
{ "id": "dat_1", "command": "delete_attachment", "params": { "sys_id": "68cf699a97485f14c3e2fc90f053af5d" } }
Parameters:
sys_id(required): thesys_attachmentrecord.dryRun(optional): only read and return the attachment; not reviewed.
Response:
{ "status": "success", "result": { "deleted": true, "sys_id": "68cf…", "fileName": "lineup.png", "table": "sc_cat_item", "tableSysId": "73da…", "sizeBytes": 1748088 } }
Errors: E_NOT_FOUND (nothing deleted), E_DISABLED, E_REVIEW_PENDING, E_USER_REJECTED.