NowAIKit
Get started
Use cases Pricing Docs Contact Get started

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.

TypeScript
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

OptionTypeRequiredDefaultDescription
instancestringYesServiceNow instance hostname (e.g., your-instance.service-now.com)
authAuthConfigYesAuthentication configuration (see Authentication Options)
timeoutnumberNo30000Request timeout in milliseconds
retriesnumberNo3Number of automatic retries on transient failures (429, 503)
retryDelaynumberNo1000Base delay between retries in ms (exponential backoff applied)
proxystringNoHTTP proxy URL for corporate environments
debugbooleanNofalseEnable verbose request/response logging to stderr
apiVersionstringNo'now'ServiceNow REST API version namespace
maxConcurrentnumberNo10Maximum concurrent HTTP requests

Auth Configuration Types

TypeScript
// 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.

TypeScript
// 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[]
ParameterTypeDescription
active, priority, etc.anyField-value filters (AND conditions)
limitnumberMax records to return (default: 20, max: 200)
offsetnumberNumber of records to skip for pagination
fieldsstring[]Fields to include in response (reduces payload)
orderBystringSort field. Prefix with - for descending
displayValuebooleanReturn display values instead of sys_ids
encodedQuerystringRaw encoded query string for advanced filtering

kit.{module}.get(sysId)

Retrieve a single record by sys_id.

TypeScript
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.

TypeScript
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).

TypeScript
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.

TypeScript
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.

ModuleAccessAdditional Methods
Incidentkit.incidentresolve(), close(), addWorkNote(), addComment()
Problemkit.problemresolve(), addWorkNote()
Change Requestkit.changesubmitForApproval(), close(), scheduleCAB()
Taskkit.taskcomplete(), listMyTasks()
CMDB CIkit.cmdbsearch(), listRelationships(), createRelationship(), impactAnalysis(), healthDashboard()
Discoverykit.discoverylistSchedules(), listMIDServers(), runScan()
Eventkit.eventlistActive(), register(), fire()
Userkit.userlist(), addToGroup(), removeFromGroup()
Groupkit.grouplist(), addMember(), removeMember()
Catalogkit.catalogsearch(), listItems(), orderItem(), createVariable()
Knowledgekit.knowledgesearch(), listBases(), publish(), retire()
Approvalkit.approvallistMy(), listAll(), approve(), reject()
SLAkit.slagetDetails(), listActive()
HRkit.hrcreateOnboarding(), createOffboarding(), listServices(), getProfile()
CSMkit.csmclose(), listAccounts(), listContacts(), getCaseSLA()
Securitykit.securitylistVulnerabilities(), getThreatIntel(), runPlaybook(), getDashboard()
GRCkit.grclistRisks(), listControls(), listPolicies(), getAssessment()
Scriptkit.scriptlistBusinessRules(), listScriptIncludes(), listClientScripts()
UI Policykit.uiPolicylist(), listActions()
ACLkit.acllist()
Agilekit.agilelistStories(), listEpics(), listScrumTasks()
Virtual Agentkit.valistTopics(), listConversations(), listCategories()
Assetkit.assetretire(), listLicenses(), getLicenseCompliance(), trackLifecycle()
DevOpskit.devopslistPipelines(), listDeployments(), trackDeployment(), getInsights()
Flowkit.flowlist(), trigger(), getExecution(), listSubflows()
Reportkit.reportlist(), runAggregate(), trend(), export()
Notificationkit.notificationlist(), listTemplates(), listSubscriptions(), sendBroadcast()
Portalkit.portallistPages(), listWidgets(), listThemes()
UI Builderkit.uiblistPages(), listComponents(), listDataBrokers()
REST Integrationkit.restlistMessages(), listTransformMaps(), listImportSets()
System Adminkit.sysgetProperty(), setProperty(), listUpdateSets(), listScheduledJobs()
Fluent / Advancedkit.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.

TypeScript
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

MethodSignatureDescription
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.

TypeScript
// 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

TypeScript
// 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

ConstraintValue
Max operations per batch50
Supported methodsGET, POST, PATCH, DELETE
Write operations requireWRITE_ENABLED=true (or equivalent SDK config)
Partial failure handlingEach 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.

TypeScript
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

CodeHTTP StatusDescription
AUTH_FAILED401Invalid credentials or expired token
FORBIDDEN403User lacks required ACL/role for this operation
RECORD_NOT_FOUND404Record with specified sys_id does not exist
TABLE_NOT_FOUND404Specified table name does not exist on instance
VALIDATION_ERROR400Invalid field values or missing required fields
RATE_LIMITED429Too many requests; automatic retry will fire if retries > 0
INSTANCE_ERROR500Server-side error on ServiceNow instance
TIMEOUTRequest exceeded configured timeout
NETWORK_ERRORDNS 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:

TypeScript
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

TypeScript
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

TypeScript
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

CategoryTypes
ClientNowAIKitConfig, AuthConfig, BasicAuth, OAuthAuth, TokenAuth
RecordsServiceNowRecord, IncidentRecord, ProblemRecord, ChangeRequestRecord, TaskRecord, CMDBCIRecord, UserRecord, GroupRecord, CatalogItemRecord, KnowledgeArticleRecord
HRSDHRCaseRecord, HRServiceRecord, HRProfileRecord
CSMCSMCaseRecord, CSMAccountRecord, CSMContactRecord
SecOpsSecurityIncidentRecord, VulnerabilityRecord, GRCRiskRecord
DevelopmentBusinessRuleRecord, ScriptIncludeRecord, ClientScriptRecord, UIPolicyRecord, ACLRecord
QueryQueryOptions, FluentQuery, WhereClause, AggregateType, AggregateResult
BatchBatchOperation, BatchResult, BatchOperationResult
ErrorsNowAIKitError, ErrorCode
MiscFlowRecord, 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.

TypeScript
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);
MethodReturnsDescription
discoverAgent()AgentCardFetch the remote agent's capabilities and metadata
sendTask(params)TaskSend a task and wait for the complete result
sendTaskStreaming(params)AsyncIterable<TaskEvent>Send a task and receive results as an SSE stream
cancelTask(taskId)TaskCancel a running task
getTask(taskId)TaskRetrieve 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.

TypeScript
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.

TypeScript
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.

TypeScript
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.

TypeScript
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.

TypeScript
import type {
  NowConfig,
  FluentComponent,
  FluentPage,
  FluentTheme,
  FluentValidationResult,
  FluentBuildOptions,
  FluentInitOptions
} from 'nowaikit-sdk/fluent';
TypeDescription
NowConfigConfiguration object for now.config.json — instance, scope, components, pages
FluentComponentFluent component definition — name, props, slots, events, styles
FluentPagePage layout definition with component tree and route config
FluentThemeTheme tokens and CSS custom property definitions
FluentValidationResultResult from fluent_validate — errors, warnings, passed checks
FluentBuildOptionsOptions for fluent_build — output directory, minification, source maps
FluentInitOptionsOptions 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.