SDK API Reference
Reference for nowaikit-sdk 2.1.0, the TypeScript client for the ServiceNow REST API. This page covers client configuration, the Table API methods, the full method list, encoded queries and aggregates, batch calls, error handling, exported TypeScript types, and the subpath modules.
Client Configuration
ServiceNowClient takes a single ServiceNowConfig object that sets the instance, authentication and request behaviour.
import { ServiceNowClient } from 'nowaikit-sdk';
const sn = new ServiceNowClient({
instanceUrl: 'https://your-instance.service-now.com',
authMethod: 'oauth',
oauth: {
clientId: process.env.SERVICENOW_OAUTH_CLIENT_ID,
clientSecret: process.env.SERVICENOW_OAUTH_CLIENT_SECRET,
grantType: 'client_credentials',
},
maxRetries: 3,
retryDelayMs: 1000,
requestTimeoutMs: 30000,
hooks: {
onResponse: ({ url, status, durationMs }) => console.log(status, durationMs, url),
},
});
Constructor Options
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
instanceUrl | string | Yes | (none) | Full instance URL, e.g. https://your-instance.service-now.com |
authMethod | 'basic' | 'oauth' | Yes | (none) | How the client authenticates |
basic | { username, password } | For basic | (none) | Basic auth credentials |
oauth | object | For oauth | (none) | clientId, clientSecret, grantType, plus username/password, refreshToken or jwtAssertion depending on the grant |
authMode | 'service-account' | 'per-user' | 'impersonation' | No | 'service-account' | Whose identity each call runs under |
perUserBearerToken | string | For per-user | (none) | Access token sent as-is in per-user mode |
impersonateUserSysId | string | For impersonation | (none) | sys_id sent in the X-Sn-Impersonate header |
maxRetries | number | No | 3 | Retries for rate limits, server errors and network failures |
retryDelayMs | number | No | 1000 | Base delay between retries in ms (doubles on each attempt) |
requestTimeoutMs | number | No | 30000 | Timeout per request in ms |
hooks | RequestHooks | No | (none) | onRequest, onResponse and onRetry callbacks for logging, metrics or header changes |
onTokenRefresh | function | No | (none) | Called with { accessToken, refreshToken, expiresAt } whenever new OAuth tokens arrive |
Auth Configuration Types
// Basic auth
{ authMethod: 'basic', basic: { username: string, password: string } }
// OAuth 2.0 (grantType defaults to 'password')
{ authMethod: 'oauth', oauth: { clientId, clientSecret, grantType: 'password', username, password } }
{ authMethod: 'oauth', oauth: { clientId, clientSecret, grantType: 'client_credentials' } }
{ authMethod: 'oauth', oauth: { clientId, clientSecret, grantType: 'refresh_token', refreshToken } }
{ authMethod: 'oauth', oauth: { clientId, clientSecret, grantType: 'jwt', jwtAssertion } }
// Per-user bearer token (from your SSO or PKCE flow)
{ authMethod: 'oauth', authMode: 'per-user', perUserBearerToken: string }
Core Methods
The Table API methods work on any table: incident, change_request, cmdb_ci_server, sn_hr_core_case and so on. Table names and sys_ids are validated before the request goes out.
queryRecords(params)
Query records with an encoded query, field selection, ordering and paging. Returns { count, records }. limit defaults to 10 and is capped at 1,000. Prefix orderBy with - for descending order.
const { count, records } = await sn.queryRecords({
table: 'incident',
query: 'active=true^priority<=2',
fields: 'number,short_description,priority,assigned_to',
orderBy: '-sys_created_on',
limit: 25,
offset: 0,
});
// Every matching record, paging past the 1,000-row cap
const all = await sn.getAllRecords({ table: 'incident', query: 'active=true', fields: 'number' });
// Or stream them one at a time
for await (const rec of sn.iterateRecords({ table: 'incident', query: 'active=true' })) {
console.log(rec.number);
}
getRecord(table, sysId, fields?)
Fetch a single record by sys_id.
const incident = await sn.getRecord(
'incident',
'9d385017c611228701d22104cc95c371',
'number,short_description,state'
);
createRecord(table, data)
Insert a record and return it, including the new sys_id and number.
const incident = await sn.createRecord('incident', {
short_description: 'Email service is down',
urgency: '1',
impact: '1',
category: 'software',
});
console.log(incident.number, incident.sys_id);
updateRecord(table, sysId, data)
Update the given fields (a PATCH) and return the updated record.
await sn.updateRecord('incident', incident.sys_id as string, {
state: '2',
work_notes: 'Investigating mail relay logs',
});
deleteRecord(table, sysId)
Delete a record. Resolves with no value.
await sn.deleteRecord('incident', '9d385017c611228701d22104cc95c371');
Method reference
Every public method on ServiceNowClient. All of them return promises except iterateRecords (an async generator), withUser and getBaseUrl.
| Area | Method | Returns |
|---|---|---|
| Table API | queryRecords(params) | QueryRecordsResponse |
getAllRecords(params, pageSize?) | ServiceNowRecord[] | |
iterateRecords(params, pageSize?) | AsyncGenerator<ServiceNowRecord> | |
getRecord(table, sysId, fields?) | ServiceNowRecord | |
createRecord(table, data) | ServiceNowRecord | |
updateRecord(table, sysId, data) | ServiceNowRecord | |
deleteRecord(table, sysId) | void | |
| Schema | getTableSchema(table) | { table, columns } (field names from a sample record) |
getDictionary(table) | TableDictionary (type, label, mandatory, reference, max length) | |
| Aggregates | runAggregateQuery(table, groupBy, aggregate?, query?, opts?) | Aggregate API result |
getRecordCount(table, query?) | number | |
| Users & groups | getUser(identifier) | ServiceNowRecord (sys_id, user name or email) |
getGroup(identifier) | ServiceNowRecord (sys_id or name) | |
| CMDB | searchCmdbCi(query?, limit?) | QueryRecordsResponse |
getCmdbCi(sysId, fields?) | ServiceNowRecord | |
listRelationships(ciSysId) | { count, relationships } | |
cmdbHealthDashboard() | Health summary | |
| ITOM | listDiscoverySchedules(activeOnly?) | { count, schedules } |
listMidServers(activeOnly?) | { count, mid_servers } | |
listActiveEvents(query?, limit?) | QueryRecordsResponse | |
serviceMappingSummary(serviceSysId) | Service map summary | |
| Change | createChangeRequest(params) | ServiceNowRecord |
| Attachments | uploadAttachment(table, recordSysId, fileName, contentType, contentBase64) | Attachment record |
listAttachments(table, recordSysId) | AttachmentMeta[] | |
getAttachment(attachmentSysId) | { meta, contentBase64 } | |
deleteAttachment(attachmentSysId) | void | |
| Import sets | insertImportSetRow(stagingTable, data) | ImportSetResult |
getImportSetStatus(stagingTable, importSetSysId) | ImportSetResult | |
| Batch & scripts | batch(requests) | BatchResponseItem[] |
batchRequest(operations) | { batch_id, total, results } | |
executeScript(script, scope?) | { status, output, scope } | |
| Otto | callNowAssist(endpoint, payload) | Endpoint response |
| Instance | getInstanceStats() | InstanceStats |
getBaseUrl() | string | |
withUser({ sysId?, bearerToken? }) | A copy of the client in impersonation or per-user mode |
InstanceManager holds several named clients. It loads them from the file in SN_INSTANCES_CONFIG, the NowAIKit setup wizard's ~/.config/nowaikit/instances.json, SN_INSTANCE_<NAME>_URL environment variables, or SERVICENOW_INSTANCE_URL. Use InstanceManager.fromConfig(path), register(name, config), getClient(name?), switch(name), listNames() and listAll().
Encoded queries and aggregates
The SDK doesn't have a chained query builder. Filters are ServiceNow encoded query strings, the same ones you copy from a list view, passed to queryRecords, getAllRecords, getRecordCount or runAggregateQuery. Queries are checked before they're sent: javascript: expressions are limited to standard GlideSystem date and user functions, and queries over 4,096 characters are rejected.
// High-priority open incidents, newest first
const urgent = await sn.queryRecords({
table: 'incident',
query: 'active=true^priority<=2^ORimpact=1',
fields: 'number,short_description,priority,impact',
orderBy: '-sys_created_on',
limit: 25,
});
// Count by category
const byCategory = await sn.runAggregateQuery('incident', 'category', 'COUNT', 'active=true');
// Average reassignment count per group, only groups with more than 5 incidents
const reassign = await sn.runAggregateQuery(
'incident',
'assignment_group',
'COUNT,AVG:reassignment_count',
'active=true',
{ having: 'COUNT>5' }
);
// Just a number
const open = await sn.getRecordCount('incident', 'active=true');
runAggregateQuery parameters
| Parameter | Type | Description |
|---|---|---|
table | string | Table to aggregate |
groupBy | string | Field or comma-separated fields to group by. Pass '' for no grouping |
aggregate | string | COUNT (default), or AVG:field, SUM:field, MIN:field, MAX:field. Combine with commas, e.g. COUNT,AVG:duration |
query | string | Optional encoded query |
opts.having | string | Optional having clause, e.g. COUNT>5 |
If you want the GlideQuery-style JSON form (where, orWhere, select, aggregate) in an AI client, that's the MCP server's fluent_query tool. See the SDK & Fluent Guide.
Batch Operations
batch() sends several REST calls to ServiceNow's /api/now/v1/batch endpoint in one HTTP request. Each sub-request gets its own status code and parsed body, which makes it a good fit for dashboards and bulk updates.
// Fetch data from 3 tables in one HTTP call
const results = await sn.batch([
{ id: 'p1', method: 'GET', url: '/api/now/table/incident?sysparm_query=active=true^priority=1&sysparm_limit=10' },
{ id: 'changes', method: 'GET', url: '/api/now/table/change_request?sysparm_query=state=-1&sysparm_limit=10' },
{ id: 'open', method: 'GET', url: '/api/now/stats/incident?sysparm_count=true&sysparm_query=active=true' },
]);
for (const r of results) {
if (r.error) console.error(r.id, r.status_code, r.error);
else console.log(r.id, r.body);
}
Bulk Updates
Writes work the same way. Put the payload in body and the SDK serialises it for you.
const ids = ['<sys_id_1>', '<sys_id_2>', '<sys_id_3>'];
const results = await sn.batch(
ids.map((id) => ({
method: 'PATCH',
url: `/api/now/table/incident/${id}`,
body: { assignment_group: '<group_sys_id>', work_notes: 'Reassigned by nightly job' },
}))
);
const failed = results.filter((r) => r.status_code >= 400);
console.log(`${results.length - failed.length} updated, ${failed.length} failed`);
batchRequest(operations) is the same call with the MCP tool's shape (each operation needs an id) and returns { batch_id, total, results }. To build or read batch payloads yourself, use buildBatchPayload(requests) and parseBatchResponse(raw).
Batch Limits
| Limit | Value | Notes |
|---|---|---|
| Operations per HTTP call | 50 | batch() splits larger arrays into chunks of 50 automatically. buildBatchPayload throws above 50 |
| Empty batch | Not allowed | Throws a VALIDATION_ERROR |
| Partial failures | Per operation | Check status_code and error on each result, even when the batch call itself succeeds |
Error Handling
SDK methods throw ServiceNowError on failure. It extends Error and adds a string code and an optional details field.
import { ServiceNowError } from 'nowaikit-sdk';
try {
const incident = await sn.getRecord('incident', '00000000000000000000000000000000');
} catch (error) {
if (error instanceof ServiceNowError) {
console.error(`Code: ${error.code}`); // 'NOT_FOUND'
console.error(`Message: ${error.message}`); // ServiceNow's error message
}
}
Error Codes
| Code | HTTP Status | Description |
|---|---|---|
AUTHENTICATION_FAILED | 401 | Bad credentials, an expired token, or missing auth settings in the config |
INSUFFICIENT_PRIVILEGES | 403 | The user lacks the role or ACL access for this operation |
NOT_FOUND | 404 | The record, user or group doesn't exist |
INVALID_REQUEST | 400 | ServiceNow rejected the request |
RATE_LIMITED | 429 | Still rate limited after all retries |
VALIDATION_ERROR | (none) | Caught before sending: bad table name, sys_id or query, or an empty or oversized batch |
API_ERROR | Other | Any other HTTP error, such as a 500 |
NETWORK_ERROR | (none) | The request failed at the network level after all retries |
QUERY_FAILED, CREATE_FAILED, UPDATE_FAILED, DELETE_FAILED | (none) | An unexpected failure inside the named operation |
ATTACHMENT_*_FAILED, IMPORT_FAILED, NOW_ASSIST_ERROR | (none) | Failures in attachment, import set and Otto calls |
Retry Logic
The client retries rate limits (respecting Retry-After), server errors, timeouts and network failures with exponential backoff. It doesn't retry AUTHENTICATION_FAILED, INVALID_REQUEST or NOT_FOUND, since trying again won't help. Configure it in the constructor:
const sn = new ServiceNowClient({
instanceUrl: 'https://your-instance.service-now.com',
authMethod: 'basic',
basic: { username: '...', password: '...' },
maxRetries: 5, // Retry up to 5 times
retryDelayMs: 2000, // Start with 2s delay (doubles each retry)
requestTimeoutMs: 60000, // 60s timeout per request
hooks: {
onRetry: ({ url, attempt, delayMs, error }) => console.warn(`Retry ${attempt} in ${delayMs}ms: ${error}`),
},
});
TypeScript Types
The package ships its own declarations. Types are exported from the package root, nowaikit-sdk.
Core Types
import type {
// Client
ServiceNowConfig,
AuthMode,
OAuthGrantType,
RequestHooks,
// Records and queries
ServiceNowRecord,
ServiceNowReference,
QueryRecordsParams,
QueryRecordsResponse,
// Schema, attachments, import sets, instance
TableDictionary,
DictionaryColumn,
AttachmentMeta,
ImportSetResult,
InstanceStats,
// Batch
BatchRequestItem,
BatchResponseItem,
BatchResponse,
// OAuth
OAuthTokenResponse,
} from 'nowaikit-sdk';
import { ServiceNowError } from 'nowaikit-sdk';
Key Interfaces
interface QueryRecordsParams {
table: string;
query?: string; // Encoded query
fields?: string; // Comma-separated field list
limit?: number; // Default 10, max 1000
orderBy?: string; // Prefix with - for descending
offset?: number;
}
interface QueryRecordsResponse {
count: number;
records: ServiceNowRecord[];
}
interface ServiceNowRecord {
[key: string]: string | number | boolean | ServiceNowReference | null | undefined;
}
interface BatchRequestItem {
id?: string;
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
url: string;
headers?: Record<string, string>;
body?: unknown;
}
interface BatchResponseItem {
id?: string;
status_code: number;
headers?: Record<string, string>;
body: unknown;
error?: string;
}
class ServiceNowError extends Error {
code: string;
details?: unknown;
}
All Exported Types
| Category | Types |
|---|---|
| Client | ServiceNowConfig, AuthMode, OAuthGrantType, RequestHooks, InstanceEntry |
| Records & queries | ServiceNowRecord, ServiceNowReference, QueryRecordsParams, QueryRecordsResponse, ServiceNowApiResponse, ServiceNowApiError |
| Schema & data | DictionaryColumn, TableDictionary, AttachmentMeta, ImportSetResult, InstanceStats |
| Batch | BatchRequestItem, BatchResponseItem, BatchResponse |
| OAuth | OAuthTokenResponse |
| Parameter types | Typed parameter shapes for common operations, e.g. CreateIncidentParams, CreateChangeRequestParams, SearchCmdbCiParams, RunAggregateQueryParams, ListUsersParams, CreateStoryParams and more across ITSM, CMDB, ITOM, knowledge, catalog, approvals, SLA, reporting, ATF, scripting and agile |
| A2A | A2AClientConfig, A2AMessage, A2AAgentCard, A2ATask, A2APart |
| Streaming | SSEEvent |
| Fluent | NowConfig, FluentComponent, UxAppRoute, FluentDataBroker |
| MCP adapter | SdkToolDescriptor (from nowaikit-sdk/mcp) |
Subpath modules
These modules were added in 2.0.0, plus the MCP adapter in 2.1.0. Each has its own subpath import. Everything except nowaikit-sdk/mcp is also exported from the package root.
A2AClient
Client for the Agent-to-Agent protocol. Reads an agent's card from /.well-known/agent.json and sends JSON-RPC tasks.
import { A2AClient } from 'nowaikit-sdk/a2a';
const a2a = new A2AClient({
agentUrl: 'https://agent.example.com',
bearerToken: process.env.A2A_TOKEN, // optional
});
// Discover the agent's capabilities
const card = await a2a.discoverAgent();
// Send a task (the id is generated if you leave it out)
const task = await a2a.sendTask({
role: 'user',
parts: [{ type: 'text', text: 'Summarise open P1 incidents' }],
});
// Check on it, or cancel it
const latest = await a2a.getTask(task.id);
await a2a.cancelTask(task.id);
| Method | Returns | Description |
|---|---|---|
discoverAgent() | A2AAgentCard | Fetch the agent's name, skills and capabilities |
sendTask(message, id?) | A2ATask | Send a message as a new task (or to an existing task id) |
getTask(taskId) | A2ATask | Get the current state of a task |
cancelTask(taskId) | A2ATask | Cancel a running task |
OAuth PKCE
Functions for the OAuth authorization code flow with PKCE (S256). Your OAuth application in ServiceNow must allow the redirect URI. Once you have the tokens, pass the access token to a client in per-user mode.
import {
generateCodeVerifier,
generateCodeChallenge,
buildAuthorizationUrl,
exchangeCodeForTokens,
} from 'nowaikit-sdk/oauth-pkce';
import { ServiceNowClient } from 'nowaikit-sdk';
const instanceUrl = 'https://your-instance.service-now.com';
const clientId = 'your-client-id';
const redirectUri = 'http://localhost:3000/callback';
// 1. Create the verifier and challenge, then send the user to ServiceNow
const verifier = generateCodeVerifier();
const challenge = await generateCodeChallenge(verifier);
const authUrl = buildAuthorizationUrl(instanceUrl, clientId, redirectUri, challenge, 'useraccount');
// 2. After the redirect, swap the ?code= value for tokens
const code = new URL(callbackUrl).searchParams.get('code')!;
const tokens = await exchangeCodeForTokens(instanceUrl, clientId, redirectUri, code, verifier);
// 3. Call ServiceNow as that user
const sn = new ServiceNowClient({
instanceUrl,
authMethod: 'oauth',
authMode: 'per-user',
perUserBearerToken: tokens.access_token,
});
streamSSE
An async generator that opens a text/event-stream response with fetch and yields { event, data } objects. Pass any headers you need, such as Authorization.
import { streamSSE } from 'nowaikit-sdk/streaming';
for await (const { event, data } of streamSSE('https://agent.example.com/stream', {
headers: { Authorization: `Bearer ${token}` },
})) {
console.log(event, data);
}
SchemaCache
Caches getTableSchema results in memory so repeated lookups don't hit the instance. The TTL defaults to 5 minutes.
import { SchemaCache } from 'nowaikit-sdk/cache';
const cache = new SchemaCache(10 * 60 * 1000); // 10 minutes
const schema = await cache.getSchema(sn, 'incident'); // calls the instance
const again = await cache.getSchema(sn, 'incident'); // served from memory
cache.invalidate('incident');
cache.clear();
NowAssistClient
Wraps a ServiceNowClient to run Otto skills and manage Otto conversations. Your instance needs Otto licensed and the skills you call activated.
import { NowAssistClient } from 'nowaikit-sdk/now-assist';
const assist = new NowAssistClient(sn);
const skills = await assist.listSkills(true); // active skills only
const result = await assist.executeSkill('<skill_sys_id>', { incident_number: 'INC0010001' });
const conversation = await assist.createConversation('Password reset help');
// Take the conversation id from the createConversation response
const reply = await assist.sendMessage('<conversation_id>', 'How do I reset my password?');
| Method | Description |
|---|---|
listSkills(active?) | List Otto skills, optionally only active ones |
executeSkill(skillSysId, input) | Run a skill with the given input |
createConversation(topic?) | Start a conversation |
sendMessage(conversationId, message) | Send a message in a conversation |
createSdkTools (MCP adapter)
Added in 2.1.0. createSdkTools(client) returns plain tool descriptors (name, description, JSON Schema input, handler) for the core client operations, so any MCP host can register them without pulling in an MCP SDK.
import { createSdkTools } from 'nowaikit-sdk/mcp';
const tools = createSdkTools(sn);
// sdk_query_records, sdk_get_all_records, sdk_get_record, sdk_get_record_count,
// sdk_get_dictionary, sdk_run_aggregate, sdk_list_attachments, sdk_get_instance_stats
const tool = tools.find((t) => t.name === 'sdk_get_record_count');
const count = await tool?.handler({ table: 'incident', query: 'active=true' });
Fluent Types
Type definitions you can use when generating or checking configuration for a ServiceNow SDK (now-sdk) Fluent project. They are plain TypeScript interfaces with no runtime code.
import type {
NowConfig,
FluentComponent,
UxAppRoute,
FluentDataBroker,
} from 'nowaikit-sdk/fluent-types';
const config: NowConfig = {
name: 'Incident Workspace',
version: '1.0.0',
scope: 'x_acme_incident',
components: [{ name: 'incident-list', type: 'page' }],
routes: [{ path: '/incidents', component: 'incident-list', title: 'Incidents' }],
};
| Type | Fields |
|---|---|
NowConfig | name, version, scope, description?, components?, routes? |
FluentComponent | name, type ('page' | 'macroponent' | 'data_resource'), properties? |
UxAppRoute | path, component, title? |
FluentDataBroker | name, source, mapping? |
To scaffold, build, validate or install Fluent apps, use the MCP server's fluent_* tools, which run the ServiceNow SDK CLI for you. See the SDK & Fluent Guide.
See Also
- SDK Quickstart: Installation, first example, and authentication setup.
- SDK & Fluent Guide: The
fluent_query,batch_requestandexecute_scripttools, with real-world scenarios and SDK equivalents. - 500+ Tools Reference: Every tool the MCP server exposes.
- OAuth Setup Guide: Configure an OAuth 2.0 application in ServiceNow.
- Full Documentation: MCP setup, client configuration, examples, and everything else.



