SDK API Reference
Complete reference for the NowAIKit TypeScript/JavaScript SDK. This page covers client configuration, core CRUD methods available on every module, the full module list, fluent query API, batch operations, error handling, and all exported TypeScript types.
Client Configuration
The NowAIKit constructor accepts a configuration object that controls connection, authentication, and request behavior.
import { NowAIKit } from 'nowaikit-sdk';
const kit = new NowAIKit({
instance: 'your-instance.service-now.com',
auth: {
type: 'oauth',
clientId: process.env.SN_CLIENT_ID,
clientSecret: process.env.SN_CLIENT_SECRET,
username: process.env.SN_USERNAME,
password: process.env.SN_PASSWORD
},
timeout: 30000,
retries: 3,
proxy: 'http://proxy.corp.com:8080',
debug: false
});
Constructor Options
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
instance | string | Yes | — | ServiceNow instance hostname (e.g., your-instance.service-now.com) |
auth | AuthConfig | Yes | — | Authentication configuration (see Authentication Options) |
timeout | number | No | 30000 | Request timeout in milliseconds |
retries | number | No | 3 | Number of automatic retries on transient failures (429, 503) |
retryDelay | number | No | 1000 | Base delay between retries in ms (exponential backoff applied) |
proxy | string | No | — | HTTP proxy URL for corporate environments |
debug | boolean | No | false | Enable verbose request/response logging to stderr |
apiVersion | string | No | 'now' | ServiceNow REST API version namespace |
maxConcurrent | number | No | 10 | Maximum concurrent HTTP requests |
Auth Configuration Types
// Basic Auth
{ type: 'basic', username: string, password: string }
// OAuth 2.0 (Client Credentials + Password)
{ type: 'oauth', clientId: string, clientSecret: string, username: string, password: string }
// Token-based (SSO / OIDC)
{ type: 'token', accessToken: string }
Core Methods
Every module on the kit object exposes a consistent set of CRUD methods. The patterns below work identically across kit.incident, kit.change, kit.cmdb, and all other modules.
kit.{module}.query(filters)
Query records with optional filters, field selection, sorting, and pagination.
// Query with filters
const incidents = await kit.incident.query({
active: true,
priority: 1,
limit: 25,
offset: 0,
fields: ['number', 'short_description', 'state', 'assigned_to'],
orderBy: '-sys_created_on',
displayValue: true
});
// Returns: IncidentRecord[]
| Parameter | Type | Description |
|---|---|---|
active, priority, etc. | any | Field-value filters (AND conditions) |
limit | number | Max records to return (default: 20, max: 200) |
offset | number | Number of records to skip for pagination |
fields | string[] | Fields to include in response (reduces payload) |
orderBy | string | Sort field. Prefix with - for descending |
displayValue | boolean | Return display values instead of sys_ids |
encodedQuery | string | Raw encoded query string for advanced filtering |
kit.{module}.get(sysId)
Retrieve a single record by sys_id.
const incident = await kit.incident.get('a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6');
// With field selection
const incident = await kit.incident.get('a1b2c3...d6', {
fields: ['number', 'short_description', 'state'],
displayValue: true
});
// Returns: IncidentRecord
kit.{module}.create(data)
Create a new record. Returns the created record with its sys_id and auto-generated fields.
const incident = await kit.incident.create({
short_description: 'Email server unresponsive',
description: 'Users reporting inability to send/receive emails since 09:00.',
urgency: 1,
impact: 1,
category: 'email',
assignment_group: 'IT Infrastructure'
});
console.log(incident.number); // 'INC0012345'
console.log(incident.sys_id); // 'a1b2c3d4...'
// Returns: IncidentRecord
kit.{module}.update(sysId, data)
Update an existing record. Only the specified fields are modified (PATCH semantics).
const updated = await kit.incident.update('a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6', {
state: 6, // Resolved
close_code: 'Resolved',
close_notes: 'Root cause identified and fixed. Email server restarted.'
});
// Returns: IncidentRecord (updated)
kit.{module}.delete(sysId)
Delete a record by sys_id. Returns void on success, throws on failure.
await kit.incident.delete('a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6');
// No return value — throws NowAIKitError on failure
Module Reference
All available modules accessible via the kit instance. Each module exposes the standard query, get, create, update, and delete methods, plus module-specific operations listed below.
| Module | Access | Additional Methods |
|---|---|---|
| Incident | kit.incident | resolve(), close(), addWorkNote(), addComment() |
| Problem | kit.problem | resolve(), addWorkNote() |
| Change Request | kit.change | submitForApproval(), close(), scheduleCAB() |
| Task | kit.task | complete(), listMyTasks() |
| CMDB CI | kit.cmdb | search(), listRelationships(), createRelationship(), impactAnalysis(), healthDashboard() |
| Discovery | kit.discovery | listSchedules(), listMIDServers(), runScan() |
| Event | kit.event | listActive(), register(), fire() |
| User | kit.user | list(), addToGroup(), removeFromGroup() |
| Group | kit.group | list(), addMember(), removeMember() |
| Catalog | kit.catalog | search(), listItems(), orderItem(), createVariable() |
| Knowledge | kit.knowledge | search(), listBases(), publish(), retire() |
| Approval | kit.approval | listMy(), listAll(), approve(), reject() |
| SLA | kit.sla | getDetails(), listActive() |
| HR | kit.hr | createOnboarding(), createOffboarding(), listServices(), getProfile() |
| CSM | kit.csm | close(), listAccounts(), listContacts(), getCaseSLA() |
| Security | kit.security | listVulnerabilities(), getThreatIntel(), runPlaybook(), getDashboard() |
| GRC | kit.grc | listRisks(), listControls(), listPolicies(), getAssessment() |
| Script | kit.script | listBusinessRules(), listScriptIncludes(), listClientScripts() |
| UI Policy | kit.uiPolicy | list(), listActions() |
| ACL | kit.acl | list() |
| Agile | kit.agile | listStories(), listEpics(), listScrumTasks() |
| Virtual Agent | kit.va | listTopics(), listConversations(), listCategories() |
| Asset | kit.asset | retire(), listLicenses(), getLicenseCompliance(), trackLifecycle() |
| DevOps | kit.devops | listPipelines(), listDeployments(), trackDeployment(), getInsights() |
| Flow | kit.flow | list(), trigger(), getExecution(), listSubflows() |
| Report | kit.report | list(), runAggregate(), trend(), export() |
| Notification | kit.notification | list(), listTemplates(), listSubscriptions(), sendBroadcast() |
| Portal | kit.portal | listPages(), listWidgets(), listThemes() |
| UI Builder | kit.uib | listPages(), listComponents(), listDataBrokers() |
| REST Integration | kit.rest | listMessages(), listTransformMaps(), listImportSets() |
| System Admin | kit.sys | getProperty(), setProperty(), listUpdateSets(), listScheduledJobs() |
| Fluent / Advanced | kit.fluent() | where(), orWhere(), select(), orderBy(), limit(), aggregate() |
Fluent Query API
The fluent API provides a GlideQuery-inspired chainable interface for building queries. It compiles to optimized REST calls under the hood.
const results = await kit.fluent('incident')
.where('active', true)
.where('priority', '<=', 2)
.orderByDesc('sys_created_on')
.limit(25)
.select('number', 'short_description', 'state');
// Aggregate query
const counts = await kit.fluent('incident')
.where('active', true)
.groupBy('category')
.aggregate('COUNT');
// With OR conditions
const urgent = await kit.fluent('incident')
.where('active', true)
.orWhere('priority', 1)
.orWhere('impact', 1)
.select('number', 'short_description', 'priority', 'impact')
.limit(50);
Fluent Chain Methods
| Method | Signature | Description |
|---|---|---|
where() | where(field, value) or where(field, operator, value) | Add AND filter condition |
orWhere() | orWhere(field, value) or orWhere(field, operator, value) | Add OR filter condition |
select() | select(...fields: string[]) | Specify fields to return (supports dot-walking) |
orderBy() | orderBy(field: string) | Sort ascending by field |
orderByDesc() | orderByDesc(field: string) | Sort descending by field |
limit() | limit(n: number) | Maximum records to return (max: 200) |
offset() | offset(n: number) | Skip n records for pagination |
aggregate() | aggregate(op: string, field?: string) | Run aggregate: COUNT, AVG, SUM, MIN, MAX |
groupBy() | groupBy(field: string) | Group aggregate results by field |
displayValue() | displayValue(enabled?: boolean) | Return display values instead of sys_ids |
For the complete fluent query reference with advanced examples (dot-walking, SLA queries, CMDB searches, analytics), see the Full SDK & Fluent Query Guide.
Batch Operations
Execute multiple API operations in a single HTTP request. Reduces network round-trips by 50-70% and is ideal for dashboards, reports, and bulk updates.
// Fetch data from 3 tables in one HTTP call
const results = await kit.batch([
{ id: 'incidents', method: 'GET', table: 'incident', query: { active: true, priority: 1 }, limit: 10 },
{ id: 'changes', method: 'GET', table: 'change_request', query: { state: 2 }, limit: 10 },
{ id: 'problems', method: 'GET', table: 'problem', query: { active: true }, limit: 10 }
]);
console.log(results.incidents); // IncidentRecord[]
console.log(results.changes); // ChangeRecord[]
console.log(results.problems); // ProblemRecord[]
Bulk Updates
// Close multiple incidents in one request
const closeResults = await kit.batch([
{
id: 'close_1',
method: 'PATCH',
table: 'incident',
sysId: 'a1b2c3d4...',
body: { state: 7, close_code: 'Resolved', close_notes: 'Fixed via automated remediation' }
},
{
id: 'close_2',
method: 'PATCH',
table: 'incident',
sysId: 'b2c3d4e5...',
body: { state: 7, close_code: 'Resolved', close_notes: 'Duplicate of INC0012345' }
}
]);
// Check individual operation results
for (const [id, result] of Object.entries(closeResults)) {
console.log(`${id}: ${result.success ? 'OK' : result.error}`);
}
Batch Limits
| Constraint | Value |
|---|---|
| Max operations per batch | 50 |
| Supported methods | GET, POST, PATCH, DELETE |
| Write operations require | WRITE_ENABLED=true (or equivalent SDK config) |
| Partial failure handling | Each operation returns its own status; batch does not roll back |
Error Handling
All SDK methods throw NowAIKitError on failure. The error object includes structured information for programmatic handling.
import { NowAIKit, NowAIKitError } from 'nowaikit-sdk';
try {
const incident = await kit.incident.get('invalid-sys-id');
} catch (error) {
if (error instanceof NowAIKitError) {
console.error(`Status: ${error.status}`); // 404
console.error(`Code: ${error.code}`); // 'RECORD_NOT_FOUND'
console.error(`Message: ${error.message}`); // 'Record not found in incident table'
console.error(`Instance: ${error.instance}`); // 'your-instance.service-now.com'
console.error(`RequestId: ${error.requestId}`); // ServiceNow request correlation ID
}
}
Error Codes
| Code | HTTP Status | Description |
|---|---|---|
AUTH_FAILED | 401 | Invalid credentials or expired token |
FORBIDDEN | 403 | User lacks required ACL/role for this operation |
RECORD_NOT_FOUND | 404 | Record with specified sys_id does not exist |
TABLE_NOT_FOUND | 404 | Specified table name does not exist on instance |
VALIDATION_ERROR | 400 | Invalid field values or missing required fields |
RATE_LIMITED | 429 | Too many requests; automatic retry will fire if retries > 0 |
INSTANCE_ERROR | 500 | Server-side error on ServiceNow instance |
TIMEOUT | — | Request exceeded configured timeout |
NETWORK_ERROR | — | DNS resolution, connection refused, or proxy error |
Retry Logic
The SDK automatically retries on transient errors (RATE_LIMITED and INSTANCE_ERROR) using exponential backoff. Configure retry behavior via constructor options:
const kit = new NowAIKit({
instance: 'your-instance.service-now.com',
auth: { type: 'basic', username: 'admin', password: 'pass' },
retries: 5, // Retry up to 5 times
retryDelay: 2000, // Start with 2s delay (doubles each retry)
timeout: 60000 // 60s timeout per request
});
TypeScript Types
The SDK ships with comprehensive TypeScript declarations. All types are exported from the main nowaikit package.
Core Types
import type {
// Client
NowAIKitConfig,
AuthConfig,
BasicAuth,
OAuthAuth,
TokenAuth,
// Records
ServiceNowRecord,
IncidentRecord,
ProblemRecord,
ChangeRequestRecord,
TaskRecord,
CMDBCIRecord,
UserRecord,
GroupRecord,
// Query
QueryOptions,
FluentQuery,
AggregateResult,
BatchOperation,
BatchResult,
// Errors
NowAIKitError,
ErrorCode,
} from 'nowaikit-sdk';
Key Interfaces
interface NowAIKitConfig {
instance: string;
auth: AuthConfig;
timeout?: number;
retries?: number;
retryDelay?: number;
proxy?: string;
debug?: boolean;
apiVersion?: string;
maxConcurrent?: number;
}
interface ServiceNowRecord {
sys_id: string;
sys_created_on: string;
sys_updated_on: string;
sys_created_by: string;
sys_updated_by: string;
[key: string]: unknown;
}
interface IncidentRecord extends ServiceNowRecord {
number: string;
short_description: string;
description: string;
state: number;
priority: number;
urgency: number;
impact: number;
category: string;
assigned_to: string;
assignment_group: string;
caller_id: string;
resolved_at: string;
closed_at: string;
close_code: string;
close_notes: string;
}
interface QueryOptions {
limit?: number;
offset?: number;
fields?: string[];
orderBy?: string;
displayValue?: boolean;
encodedQuery?: string;
[key: string]: unknown; // Field-value filters
}
interface NowAIKitError extends Error {
status: number;
code: ErrorCode;
instance: string;
requestId: string;
}
All Exported Types
| Category | Types |
|---|---|
| Client | NowAIKitConfig, AuthConfig, BasicAuth, OAuthAuth, TokenAuth |
| Records | ServiceNowRecord, IncidentRecord, ProblemRecord, ChangeRequestRecord, TaskRecord, CMDBCIRecord, UserRecord, GroupRecord, CatalogItemRecord, KnowledgeArticleRecord |
| HRSD | HRCaseRecord, HRServiceRecord, HRProfileRecord |
| CSM | CSMCaseRecord, CSMAccountRecord, CSMContactRecord |
| SecOps | SecurityIncidentRecord, VulnerabilityRecord, GRCRiskRecord |
| Development | BusinessRuleRecord, ScriptIncludeRecord, ClientScriptRecord, UIPolicyRecord, ACLRecord |
| Query | QueryOptions, FluentQuery, WhereClause, AggregateType, AggregateResult |
| Batch | BatchOperation, BatchResult, BatchOperationResult |
| Errors | NowAIKitError, ErrorCode |
| Misc | FlowRecord, ReportRecord, AssetRecord, ApprovalRecord, SLARecord, NotificationRecord |
| A2A (v2.0.0) | A2AClient, A2AClientOptions, AgentCard, TaskSendParams, Task, TaskEvent |
| Auth (v2.0.0) | OAuthPKCE, PKCEConfig, TokenResponse |
| Stream (v2.0.0) | streamSSE, SSEOptions, SSEEvent |
| Cache (v2.0.0) | SchemaCache, SchemaCacheOptions, TableSchema |
| Now Assist (v2.0.0) | NowAssistClient, SummaryResult, ResolutionSuggestion, ClassificationResult |
| Fluent (v2.0.0) | NowConfig, FluentComponent, FluentPage, FluentTheme, FluentValidationResult, FluentBuildOptions, FluentInitOptions |
v2.0.0 Modules
SDK v2.0.0 introduces five new modules alongside the existing core. Each is available as a sub-path import from nowaikit-sdk.
A2AClient
Agent-to-Agent protocol client for inter-agent communication. Discover remote agents, send tasks, and stream results.
import { A2AClient } from 'nowaikit-sdk/a2a';
const a2a = new A2AClient(url: string, options?: A2AClientOptions);
// Discover the agent's capabilities
const agentCard = await a2a.discoverAgent();
// Send a task and get the result
const result = await a2a.sendTask(params: TaskSendParams);
// Send a task with SSE streaming
const stream = a2a.sendTaskStreaming(params: TaskSendParams);
for await (const event of stream) {
console.log(event);
}
// Cancel a running task
await a2a.cancelTask(taskId: string);
// Get task status
const status = await a2a.getTask(taskId: string);
| Method | Returns | Description |
|---|---|---|
discoverAgent() | AgentCard | Fetch the remote agent's capabilities and metadata |
sendTask(params) | Task | Send a task and wait for the complete result |
sendTaskStreaming(params) | AsyncIterable<TaskEvent> | Send a task and receive results as an SSE stream |
cancelTask(taskId) | Task | Cancel a running task |
getTask(taskId) | Task | Retrieve the current state of a task |
OAuthPKCE
Browser-safe OAuth 2.0 authentication using PKCE (Proof Key for Code Exchange). No client secret is required — ideal for SPAs and CLI tools.
import { OAuthPKCE } from 'nowaikit-sdk/auth';
const auth = new OAuthPKCE({
instance: 'your-instance.service-now.com',
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000/callback',
scopes: ['useraccount']
});
// Generate authorization URL with PKCE challenge
const { url, codeVerifier } = await auth.getAuthorizationUrl();
// Exchange code for tokens after redirect
const tokens = await auth.exchangeCode(code, codeVerifier);
// Refresh an expired token
const refreshed = await auth.refreshToken(tokens.refresh_token);
streamSSE
Server-Sent Events streaming utility for consuming real-time responses from long-running operations.
import { streamSSE } from 'nowaikit-sdk/stream';
const stream = streamSSE(url: string, options?: SSEOptions);
for await (const event of stream) {
console.log(event.type, event.data);
}
SchemaCache
Local caching of ServiceNow table schemas with configurable TTL. Avoids redundant metadata API calls and speeds up repeated queries against the same tables.
import { SchemaCache } from 'nowaikit-sdk/cache';
const cache = new SchemaCache({ ttl: 3600000 }); // 1 hour TTL
// Get schema (fetches and caches on first call, returns cached on subsequent calls)
const schema = await cache.getSchema(kit, 'incident');
// Invalidate a specific table
cache.invalidate('incident');
// Clear all cached schemas
cache.clear();
NowAssistClient
Interact with ServiceNow Now Assist AI capabilities — generate summaries, suggest resolutions, and classify records using Now Assist models.
import { NowAssistClient } from 'nowaikit-sdk/now-assist';
const assist = new NowAssistClient(kit);
// Generate a summary for a record
const summary = await assist.summarize('incident', sysId);
// Get resolution suggestions
const suggestions = await assist.suggestResolution('incident', sysId);
// Classify a record
const classification = await assist.classify('incident', sysId);
Fluent Types (v2.0.0)
v2.0.0 exports a full set of TypeScript types for Fluent SDK components. Import them from nowaikit-sdk/fluent.
import type {
NowConfig,
FluentComponent,
FluentPage,
FluentTheme,
FluentValidationResult,
FluentBuildOptions,
FluentInitOptions
} from 'nowaikit-sdk/fluent';
| Type | Description |
|---|---|
NowConfig | Configuration object for now.config.json — instance, scope, components, pages |
FluentComponent | Fluent component definition — name, props, slots, events, styles |
FluentPage | Page layout definition with component tree and route config |
FluentTheme | Theme tokens and CSS custom property definitions |
FluentValidationResult | Result from fluent_validate — errors, warnings, passed checks |
FluentBuildOptions | Options for fluent_build — output directory, minification, source maps |
FluentInitOptions | Options for fluent_init — project template, scope, instance URL |
See Also
- SDK Quickstart — Installation, first example, and authentication setup.
- Fluent Query Guide — In-depth guide to fluent queries, batch_request, and execute_script with real-world scenarios.
- 450+ Tools Reference — Complete list of all operations available via both SDK and MCP.
- OAuth Setup Guide — Configure OAuth 2.0 application in ServiceNow.
- Full Documentation — MCP setup, client configuration, examples, and everything else.



