SDK Quickstart
The NowAIKit SDK (nowaikit-sdk) is a TypeScript client for the ServiceNow REST API. It has no runtime dependencies, uses native fetch, and handles authentication, retries and OAuth token refresh for you. You call methods like queryRecords and createRecord straight from your own code, so nothing passes through a model and the SDK adds no tokens to any prompt. Version 2.0.0 added the A2A client, OAuth PKCE helpers, SSE streaming, schema caching, a Otto client and Fluent types. The current release is 2.1.0.
| Characteristic | SDK | MCP |
|---|---|---|
| Token overhead | None: calls run in your code | The AI client loads tool definitions into context (NowAIKit keeps this small with lean discovery) |
| Interface | Direct method calls | AI tool invocation |
| Language | TypeScript / JavaScript (Node.js 20+) | Any MCP-compatible AI client |
| Best for | Automation, CI/CD, backend services | Interactive AI conversations |
| Type safety | Bundled TypeScript declarations | JSON schema validation |
When to Use SDK vs MCP
Both talk to the same ServiceNow REST APIs. The MCP server gives AI clients 500+ ready-made tools. The SDK gives you the building blocks (Table API, aggregates, batch, attachments, import sets and auth) to call directly from code. The difference is who decides what to call: your code, or the model.
Use the SDK when you need:
- Automation & CI/CD scripts: Deploy changes, run health checks, or sync data as part of a pipeline. No AI layer needed.
- Token-sensitive scenarios: Nothing goes through a model, so there are no tokens to pay for.
- Backend services: Build microservices, webhooks, or scheduled jobs that interact with ServiceNow programmatically.
- Custom integrations: Connect ServiceNow to other systems (Slack bots, monitoring tools, internal dashboards) with typed method calls.
- Batch processing: Page through large tables with
getAllRecords, group calls withbatch, and let the built-in retry logic handle rate limits.
Use MCP when you need:
- Interactive AI conversations: Let Claude, GPT, or Gemini query and modify ServiceNow through natural language.
- Natural language queries: "Show me all P1 incidents from last week" translates to the right API call automatically.
- Tool chaining: AI agents that decide which tools to call based on context and chain operations together.
- Ad-hoc exploration: Investigate incidents, explore CMDB relationships, or debug issues conversationally.
Installation
Install the SDK from npm or use bun:
npm install nowaikit-sdk
bun add nowaikit-sdk
The package is ESM only and ships its TypeScript declarations, so there's no separate @types package to install. It needs Node.js 20 or later.
{
"dependencies": {
"nowaikit-sdk": "^2.1.0"
}
}
What's new in v2.1.0
Version 2.0.0 added six modules alongside the core ServiceNowClient. Each one is exported from the package root and also has its own subpath import:
| Module | Import | Description |
|---|---|---|
| A2A Client | nowaikit-sdk/a2a | A2AClient for the Agent-to-Agent protocol: discover an agent, send a task, check or cancel it |
| OAuth PKCE | nowaikit-sdk/oauth-pkce | Functions for the authorization code flow with PKCE: generateCodeVerifier, generateCodeChallenge, buildAuthorizationUrl, exchangeCodeForTokens |
| SSE Streaming | nowaikit-sdk/streaming | streamSSE, an async generator that parses text/event-stream responses into events |
| Schema Cache | nowaikit-sdk/cache | SchemaCache keeps table schema lookups in memory with a TTL (5 minutes by default) |
| Otto Client | nowaikit-sdk/now-assist | NowAssistClient: list and execute Otto skills, create conversations and send messages |
| Fluent Types | nowaikit-sdk/fluent-types | Type definitions for ServiceNow SDK (now-sdk) Fluent projects: NowConfig, FluentComponent, UxAppRoute, FluentDataBroker |
Version 2.1.0 builds out the core client: getAllRecords and iterateRecords for paging past the 1,000-row limit, getDictionary, getRecordCount, AVG/SUM/MIN/MAX in runAggregateQuery, attachments, import sets, refresh_token, client_credentials and jwt OAuth grants, request hooks, and a new nowaikit-sdk/mcp subpath whose createSdkTools turns a client into plain tool descriptors any MCP host can register.
A2A Client Quick Example
The A2A (Agent-to-Agent) client talks to any agent that speaks the A2A protocol. Read its agent card, send a task, and check the result:
import { A2AClient } from 'nowaikit-sdk/a2a';
const a2a = new A2AClient({ agentUrl: 'http://localhost:3000' });
const card = await a2a.discoverAgent();
console.log(card.name, card.skills?.map((s) => s.id));
const task = await a2a.sendTask({
role: 'user',
parts: [{ type: 'text', text: 'List active incidents' }],
});
console.log(task.status.state);
Quick Example
Connect to your ServiceNow instance and start making API calls in seconds:
import { ServiceNowClient } from 'nowaikit-sdk';
const sn = new ServiceNowClient({
instanceUrl: 'https://your-instance.service-now.com',
authMethod: 'basic',
basic: {
username: process.env.SERVICENOW_BASIC_USERNAME,
password: process.env.SERVICENOW_BASIC_PASSWORD,
},
});
// Query active P1 incidents
const { count, records } = await sn.queryRecords({
table: 'incident',
query: 'active=true^priority=1',
fields: 'number,short_description,assigned_to',
limit: 10,
});
// Create a change request
const change = await sn.createRecord('change_request', {
short_description: 'Deploy payments service to production',
type: 'normal',
});
console.log(`Found ${count} P1 incidents`);
console.log(`Created change: ${change.number}`);
Parameters and return values are typed, so your editor autocompletes options like table, query and fields. Records come back as plain objects (ServiceNowRecord), and any failure is thrown as a ServiceNowError with a code you can check.
Authentication Options
The SDK supports basic auth, OAuth 2.0 with several grant types, and per-user bearer tokens. Choose the one that fits your environment:
Basic Auth
Simplest option for development and internal tools. Pass username and password directly.
const sn = new ServiceNowClient({
instanceUrl: 'https://your-instance.service-now.com',
authMethod: 'basic',
basic: {
username: process.env.SERVICENOW_BASIC_USERNAME,
password: process.env.SERVICENOW_BASIC_PASSWORD,
},
});
OAuth 2.0
Recommended for production. The client fetches a token on the first call, caches it, and gets a new one when it expires. The grant defaults to password. This example uses client_credentials, which your OAuth application in ServiceNow has to allow.
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',
},
// Optional: called whenever new tokens arrive, so you can store them
onTokenRefresh: ({ accessToken, refreshToken, expiresAt }) => {
console.log('Token refreshed, expires at', new Date(expiresAt));
},
});
Other grants work the same way: password (also pass username and password), refresh_token (pass refreshToken) and jwt (pass a signed jwtAssertion). If a refresh token is set and fails, the client falls back once to the configured grant.
Per-user tokens (SSO and enterprise)
If your app already holds a ServiceNow access token for the signed-in user (from the PKCE helpers or your own SSO flow), use per-user mode. Every call runs as that user, so ServiceNow ACLs apply to them rather than to a shared service account. The SDK sends the token as-is and doesn't refresh it, so swap in a new one when it expires.
const sn = new ServiceNowClient({
instanceUrl: 'https://your-instance.service-now.com',
authMethod: 'oauth',
authMode: 'per-user',
perUserBearerToken: userAccessToken,
});
// Or derive a per-user copy from an existing client
const asUser = serviceClient.withUser({ bearerToken: userAccessToken });
There's also an impersonation mode: withUser({ sysId }) keeps the service account's credentials and sends the X-Sn-Impersonate header for the given user.
See the OAuth Setup Guide for step-by-step instructions on configuring OAuth in ServiceNow.
Multi-Instance
Connect to several ServiceNow instances at once. Each ServiceNowClient has its own credentials and token cache, and InstanceManager can load the instances you've already set up for NowAIKit:
import { ServiceNowClient, InstanceManager } from 'nowaikit-sdk';
// Production instance
const prod = new ServiceNowClient({
instanceUrl: 'https://your-prod-instance.service-now.com',
authMethod: 'oauth',
oauth: { clientId: '...', clientSecret: '...', grantType: 'client_credentials' },
});
// Development instance
const dev = new ServiceNowClient({
instanceUrl: 'https://your-dev-instance.service-now.com',
authMethod: 'basic',
basic: { username: '...', password: '...' },
});
// Compare active incident counts across environments
const prodCount = await prod.getRecordCount('incident', 'active=true');
const devCount = await dev.getRecordCount('incident', 'active=true');
console.log(`Prod: ${prodCount} active incidents`);
console.log(`Dev: ${devCount} active incidents`);
// Or load saved instances (instances.json or SN_INSTANCE_<NAME>_URL env vars)
const instances = new InstanceManager();
console.log(instances.listNames());
const test = instances.getClient('test');
For advanced multi-instance patterns (failover, load balancing, environment promotion), see the Full Multi-Instance Guide.
What the client covers
ServiceNowClient works at the REST API level. Every table in ServiceNow (HR cases, CSM cases, security incidents, stories and so on) is reachable through the Table API methods, and a few common areas have helpers of their own:
| Area | Methods | Description |
|---|---|---|
| Table API | queryRecords, getAllRecords, iterateRecords, getRecord, createRecord, updateRecord, deleteRecord | Read and write any table with encoded queries, field selection, ordering and paging |
| Schema | getTableSchema, getDictionary | Field names from a sample record, or the full column dictionary including inherited fields |
| Aggregates | runAggregateQuery, getRecordCount | COUNT, AVG, SUM, MIN and MAX with group-by and having, through the Aggregate API |
| Users & groups | getUser, getGroup | Look up a user (sys_id, user name or email) or a group (sys_id or name) |
| CMDB | searchCmdbCi, getCmdbCi, listRelationships, cmdbHealthDashboard | Configuration items, relationships and a health summary |
| ITOM | listDiscoverySchedules, listMidServers, listActiveEvents, serviceMappingSummary | Discovery schedules, MID servers, events and service maps |
| Change | createChangeRequest | Create a change request |
| Attachments | uploadAttachment, listAttachments, getAttachment, deleteAttachment | Upload, list, download (base64) and delete attachments |
| Import sets | insertImportSetRow, getImportSetStatus | Load rows into a staging table and run its transform map |
| Batch & scripts | batch, batchRequest, executeScript | Several REST calls in one round-trip, and server-side script execution |
| Instance | getInstanceStats, getBaseUrl, withUser | Version and build info, the base URL, and per-user copies of the client |
| Otto | callNowAssist, plus NowAssistClient | POST to a Otto endpoint, or use the skill and conversation helpers |
For ready-made, higher-level operations across ITSM, HRSD, CSM, SecOps and the rest of the platform, use the MCP server's tools. The SDK API Reference lists every method signature.
Next Steps
You are set up and ready to build. Here is where to go from here:
- SDK API Reference: Every method, configuration option, error code and exported type.
- SDK & Fluent Guide: The
fluent_query,batch_requestandexecute_scripttools, their SDK equivalents, and Fluent (now-sdk) project types. - OAuth Setup Guide: Configure OAuth 2.0 in ServiceNow for production-ready authentication.
- Multi-Instance Guide: Advanced patterns for managing dev, test, and production environments.
- 500+ Tools Reference: Every tool the MCP server exposes.
- Full Documentation: Everything else: MCP setup, client configuration, examples, and more.



