Register an NHI with the TypeScript SDK
Goal: register one non-human identity (NHI) from Node/TypeScript code, with an idempotency key and a forensic-chain request_id on every call. Same end-to-end loop as the curl recipe — but typed and safe to retry.
This guide assumes you’ve completed First SDK script and have the TypeScript SDK (AtmanIDClient) vendored into your project. Pilot customers receive the SDK source today; the @atmanid/sdk npm package is planned for v2. If you haven’t set it up, start there.
Prerequisites
- An AtmanID tenant — sign in to your tenant dashboard (at your tenant’s base URL, provided with your onboarding) at least once
- An API key with the
write:nhiscope (plusread:nhito list agents andread:audit_logsto verify the audit row) — mint atSettings → API Keys → Create new key - Node.js 18+ (the SDK uses native
fetch; the example usescrypto.randomUUID) - The SDK vendored at
./vendor/atmanid-client(see First SDK script for setup)
1. Make the call
idempotency_key is required. Generate one per logical registration and reuse it on every retry of that registration — the same key within 24 hours returns the original result instead of creating a duplicate. Derive it from something stable (a job id, a manifest entry) when you need deduplication across processes, for example a job queue retrying after a worker crash.
import { randomUUID } from 'node:crypto';import { AtmanIDClient, AtmanIDError, AtmanIDClientError } from './vendor/atmanid-client';
const client = new AtmanIDClient({ apiKey: process.env.ATMANID_API_KEY!, baseUrl: process.env.ATMANID_BASE_URL, // e.g. https://your-atmanid-instance.com});
try { const result = await client.agents.register({ idempotency_key: randomUUID(), name: 'stripe-webhook-listener', type: 'External AI Tool', framework: 'node-stripe-sdk', owner_team: 'payments', owner_email: 'payments-eng@example.com', environment: 'Production', vendor: 'stripe', purpose: 'Listens for Stripe webhook events and triggers reconciliation', });
console.log('Registered:', result.agent_id); // → 'agt-v1-7a2c8d9f1234' console.log('Status: ', result.status); // → 'PENDING_REVIEW' console.log('request_id:', client.lastRequestId); // → 'req_01KQ...'} catch (err) { if (err instanceof AtmanIDClientError) { console.error(`API error ${err.status} (${err.code}): ${err.message}`); } if (err instanceof AtmanIDError) { console.error(`Forensic chain: request_id=${err.requestId}`); } throw err;}2. What the SDK gives you over raw curl
Typed bodies and results. client.agents.register() takes a typed body (required fields are enforced by the compiler) and returns a typed result, including cached: true when an idempotent replay returned the original registration.
A retry on transient failures. On a 5xx response or a network error (including the 8-second default timeout) the SDK waits briefly and retries once. It never retries 4xx responses — including 429 — so handle rate limiting yourself: wait for Retry-After, then retry with the same idempotency_key.
request_id on every call. The X-Request-Id of the most recent call is on client.lastRequestId, and every error carries it as err.requestId — the same value recorded on the corresponding audit record. In concurrent code, read it from the error rather than from lastRequestId, which reflects whichever call finished last.
Structured errors. AtmanIDClientError (4xx) exposes status, code, message, details and requestId; AtmanIDServerError (5xx) and AtmanIDNetworkError cover the rest. All of them extend AtmanIDError.
3. List your agents back
The same client lists agents you’ve registered (scope read:nhi). The managed_by filter is the GitOps blast-radius boundary — only agents registered with the same managed_by value are returned. If you’re building a GitOps workflow (declarative agent management from a YAML manifest), set managed_by when you register and filter on it when you list, so a rogue diff can’t deactivate agents owned by other workflows.
const { data, total } = await client.agents.list({ status: 'ACTIVE', managed_by: 'my-stripe-workflow', // only sees agents this workflow owns limit: 50,});console.log(`${total} active agents managed by my workflow:`);data.forEach(a => console.log(` ${a.name} (${a.id}) — env=${a.environment}`));For full GitOps semantics — diff manifest against tenant state, classify into CREATE/UPDATE/DEACTIVATE/SKIP, apply with safety guards — see GitOps NHI lifecycle.
4. Verify in the audit trail
Take the request_id you printed in step 1, navigate to Audit & Reports in the dashboard, and search by it — you’ll find exactly one AGENT_REGISTERED row with the same ID.
If you prefer to verify programmatically (scope read:audit_logs), list recent AGENT_REGISTERED events and match on request_id — the audit API filters by action type and time, not by request id:
const since = new Date(Date.now() - 60 * 60 * 1000).toISOString(); // last hourconst audit = await client.audit.list({ action_type: 'AGENT_REGISTERED', since, limit: 100 });const row = audit.data.find(e => e.request_id === 'req_01KQ...');console.log(row);// → { action_type: 'AGENT_REGISTERED', target_resource_id: 'agt-v1-...', actor_name: '...', request_id: 'req_01KQ...', ... }One ID, two tables, full forensic trail. Same pattern as the curl recipe, but the SDK captures the response header for you.
What just happened
- One
POST /api/v1/agentsregistered one agent withstatus = PENDING_REVIEW - A linked audit record was written with the same
request_id - The SDK would have retried once automatically if the first call hit a 5xx or a network error
- An identity admin can now approve the agent in
Machine Identity (NHI)to activate full policy enforcement
The PENDING_REVIEW state is intentional — see the curl recipe for the rationale on why NHIs land in a holding pen by default.
Common errors
4xx responses throw AtmanIDClientError, which exposes status, code, message, details and requestId. The most common cases:
err.status |
err.code |
What’s wrong | Fix |
|---|---|---|---|
| 401 | UNAUTHENTICATED |
Key missing, revoked, expired, or typo’d | Mint a fresh key in the dashboard |
| 403 | RBAC_DENIED |
Key lacks write:nhi, or the key owner’s role can’t manage non-human identities |
Mint a key with write:nhi selected, owned by someone with that permission |
| 400 | VALIDATION_ERROR |
Required field missing or wrong type | Check err.details for the specific field |
| 409 | AGENT_ALREADY_EXISTS / AGENT_NAME_CONFLICT |
An agent with this name already exists in your tenant |
Pick a unique name, or clear the prior registration first |
| 409 | TENANT_QUOTA_EXCEEDED / TIER_QUOTA_EXCEEDED |
Your tenant’s agent quota is reached | Deactivate unused agents or ask your administrator to raise the quota |
| 429 | RATE_LIMITED |
Hit the per-key rate limit | Not retried by the SDK — wait for Retry-After, then retry with the same idempotency_key |
The constructor also throws a plain Error if apiKey is missing or doesn’t start with atman_.
For the error envelope and the wider code list, see the API Reference.
Going further
- For the same scenario in
curl, see Register a non-human identity via curl - For mover (
PATCH /api/v1/agents/{id}) and leaver (POST /api/v1/agents/{id}/deactivate) semantics, seeclient.agents.update()andclient.agents.deactivate()in the SDK Reference — both also take a requiredidempotency_key - For GitOps multi-agent workflows with
managed_byownership, see GitOps NHI lifecycle - For pagination, retries and rate-limit handling patterns, see Common Patterns
© AtmanID · Privacy