SDK integration
On this page
@selfxyz/agent-sdk (0.3.1, Node 18+) signs requests as an agent, verifies them in a service, drives registration through the REST API and ships the self-agent CLI.
npm install @selfxyz/agent-sdk
The SDK defaults to mainnet (Celo Mainnet, 42220). Pass network: 'testnet' for Celo Sepolia (11142220).
Signing scheme
The agent signs keccak256(timestamp + METHOD + pathWithQuery + keccak256(body)). METHOD is uppercase, pathWithQuery is the URL path plus query string (no host), and an empty body hashes as keccak256("").
| Header | ECDSA (EVM) agents | Ed25519 agents |
|---|---|---|
x-self-agent-signature | EIP-191 personal_sign of the 32 bytes | Ed25519 signature of the same 32 bytes |
x-self-agent-timestamp | Unix milliseconds | Unix milliseconds |
x-self-agent-address | The agent’s address (informational) | Not sent |
x-self-agent-keytype | Not sent | ed25519 |
x-self-agent-key | Not sent | The public key (0x + 64 hex) |
Verifiers reject timestamps more than 5 minutes from their clock, and reject a signature they have already seen.
To verify without the SDK:
- Recompute the digest from the raw body bytes and reject stale timestamps.
- Get the agent key: ECDSA → recover the EIP-191 signer and use
zeroPad(signer, 32); Ed25519 → verify againstx-self-agent-keyand use that key. - On the registry, require
isVerifiedAgent(agentKey)andisProofFresh(getAgentId(agentKey)).
Agent side: sign requests
import { SelfAgent } from '@selfxyz/agent-sdk';
const agent = new SelfAgent({ privateKey: process.env.AGENT_PRIVATE_KEY!, network: 'testnet' });
const res = await agent.fetch('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ q: 'test' }), // string bodies default to application/json
});
const headers = await agent.signRequest('GET', 'https://api.example.com/x'); // headers only
const info = await agent.getInfo(); // info.isVerified === info.hasHumanProof && info.isProofFresh
SelfAgent takes privateKey (or an ethers signer), network, and optional registryAddress and rpcUrl overrides.
| Member | Returns |
|---|---|
address, agentKey | EVM address; bytes32 registry key (zeroPad(address, 32)) |
fetch(url, init?) / signRequest(method, url, body?) | Signed Response / the x-self-agent-* headers |
isRegistered() | Whether a human proof was recorded (stays true after it expires) |
getInfo() | agentId, isVerified, hasHumanProof, isProofFresh, proofExpiresAt, daysUntilExpiry, isExpiringSoon, nullifier, agentCount, siblingAgentIds |
getCredentials() / getCredentialsFromApi() | ZK-attested credentials, read on-chain / through the API |
getVerificationStrength() | 0 to 100 (100 = passport) |
getAgentCard() / setAgentCard(fields) / toAgentCardDataURI() | Read / write / data URI of the agent card. setAgentCard sends a transaction and works only when the agent key owns its NFT (wallet-free agents) |
requestDeregistration({ disclosures? }) | A deregistration session for this agent |
Ed25519 agents use Ed25519Agent (new Ed25519Agent({ privateKey: '<64 hex>', network: 'testnet' })) with the same fetch, signRequest, isRegistered and getInfo. Its agentKey is the raw public key, and Ed25519Agent.deriveAddress(pubkey) gives the agent’s EVM address.
Service side: verify requests
import express from 'express';
import { SelfAgentVerifier } from '@selfxyz/agent-sdk';
const verifier = SelfAgentVerifier.create()
.network('testnet')
.requireAge(18)
.sybilLimit(0) // no cap on agents per human (the default, 1, rejects humans with several agents)
.build();
const app = express();
// The signature covers the exact body bytes: keep them as req.rawBody.
app.use(
express.json({
verify: (req, _res, buf) => {
(req as { rawBody?: Buffer }).rawBody = buf;
},
}),
);
app.post('/api/data', verifier.auth(), (req, res) => {
res.json({ agentId: req.agent!.agentId.toString() }); // req.agent: VerifiedAgent
});
Verifier options
| Builder method | Effect | Default |
|---|---|---|
.network(name) / .registry(addr) / .rpc(url) | Chain to read | mainnet |
.requireAge(n) | Minimum proven age (18 or 21). Fetches credentials automatically | Off |
.requireOFAC() | credentials.ofac[0] must be true (see OFAC) | Off |
.requireNationality(...codes) | ISO 3166-1 alpha-3 as on the passport, e.g. "USA", "GBR" | Off |
.requireSelfProvider(enabled?) | Proof must come from Self’s provider | On |
.sybilLimit(n) | Max active agents per human (0 = unlimited) | 1 |
.rateLimit({ perMinute?, perHour? }) | Per-agent sliding window, in memory | Off |
.replayProtection(enabled?) | Reject reused signatures. The 10,000-entry cache is per process: share replay state across instances | On |
.includeCredentials() | Attach credentials to the result | Off |
.maxAge(ms) / .cacheTtl(ms) | Timestamp window / on-chain cache TTL | 5 min / 1 min |
The same options work as a flat object: SelfAgentVerifier.fromConfig({ network, requireAge, requireOFAC, sybilLimit, ... }).
The verifier checks, in order: timestamp, signature, replay, on-chain isVerifiedAgent and isProofFresh, provider, sybil limit, credentials, rate limit.
OFAC credentials
credentials.ofac is a bool[3] of screening results: [passport-number match, name + date-of-birth match, name + year-of-birth match]. requireOFAC(), the MCP ofac_clear flag and the agent card’s ofacClean read ofac[0] only. Self’s Hub sets ofac[0] = false for non-passport documents (EU ID cards, Aadhaar, KYC), so OFAC-screened holders of those documents fail requireOFAC(). Check ofac[1] or ofac[2] yourself (with includeCredentials()) if you accept them.
Responses from auth()
| Status | error |
|---|---|
401 | Missing agent authentication headers, Timestamp expired or invalid, Invalid signature, Invalid Ed25519 signature, Missing agent key for Ed25519 verification, Replay detected, Agent not verified on-chain, Agent's human proof has expired, Agent was not verified by Self — proof provider mismatch, Human has N agents (max M), Agent's human does not meet minimum age (required: X, got: Y), Agent's human did not pass OFAC screening, Nationality "X" not in allowed list |
429 | Rate limit exceeded (N/min) or (N/hr), with retryAfterMs |
500 | Raw request body unavailable for signature verification |
503 | Agent verification unavailable, try again later (the chain could not be read) |
On success, req.agent holds:
| Field | Type | Description |
|---|---|---|
address | string | Agent’s address (recovered, or derived from the Ed25519 key) |
agentKey | string | bytes32 registry key |
agentId | bigint | On-chain agent ID |
agentCount | bigint | Active agents of the same human |
nullifier | bigint | The human’s nullifier (rate-limit or dedupe per human) |
credentials | object | With includeCredentials(): nationality, olderThan, ofac, … |
Without Express
Pass the raw header values, the path plus query, and the raw body string. Ed25519 requests also need keytype and agentKey:
import { SelfAgentVerifier } from '@selfxyz/agent-sdk';
const verifier = SelfAgentVerifier.create().network('testnet').sybilLimit(0).build();
async function check(
headers: Record<string, string | undefined>,
method: string,
pathWithQuery: string,
rawBody: string,
) {
const result = await verifier.verify({
signature: headers['x-self-agent-signature'] ?? '',
timestamp: headers['x-self-agent-timestamp'] ?? '',
method,
url: pathWithQuery,
body: rawBody,
keytype: headers['x-self-agent-keytype'], // 'ed25519' for Ed25519 agents
agentKey: headers['x-self-agent-key'], // required for Ed25519
});
return result.valid ? result.agentId : result.error;
}
verify() returns { valid, agentAddress, agentKey, agentId, agentCount, nullifier, error?, credentials?, proofExpiresAt?, isExpiringSoon? }. It throws when the chain can’t be read, so answer 503 in that case.
Signature-free check
verifyAgent(agentKey, { network }) returns { verified, agentId, expiresAt } or { verified: false, reason: "NOT_REGISTERED" | "NO_HUMAN_PROOF" | "PROOF_EXPIRED", reauthUrl? }.
Registration, refresh and deregistration
These helpers call the REST API and follow the rotating session token for you. The API base is the apiBase option if set, otherwise the SELF_AGENT_API_BASE environment variable, otherwise https://agent-api.self.xyz.
import { requestRegistration, requestProofRefresh } from '@selfxyz/agent-sdk';
const session = await requestRegistration({
mode: 'wallet-free',
network: 'testnet',
disclosures: { minimumAge: 18, ofac: true },
});
console.log(session.scanUrl, session.humanInstructions); // show to the human
const { agentId, agentAddress } = await session.waitForCompletion(); // { timeoutMs?, pollIntervalMs? }
const privateKey = await session.exportKey(); // EVM modes only, within 30 minutes of completion
const refresh = await requestProofRefresh({ agentId, network: 'testnet' });
const { proofExpiresAt } = await refresh.waitForCompletion();
| Function | Does |
|---|---|
requestRegistration({ mode, network, humanAddress?, ed25519Pubkey?, ed25519Signature?, disclosures? }) | Starts a registration. The session has scanUrl, deepLink, waitForCompletion(), exportKey() |
requestProofRefresh({ agentId, network }) | Renews the proof of an existing agent (same agent ID and key) |
requestDeregistration({ network, agentAddress, disclosures? }) or agent.requestDeregistration() | Starts a deregistration, with waitForCompletion() |
getAgentInfo(agentId, { network }), getAgentsForHuman(address, { network }) | API lookups (also static on SelfAgent) |
- Polling defaults to a 30-minute timeout and a 5-second interval.
exportKey()can be called again until the 30-minute window after completion ends. Store the key as a secret.- Failed calls throw
RegistrationError(with the HTTPstatus). An expired session throwsExpiredSessionError. - Modes: Registration modes.
Proof expiry
Proofs expire at min(document expiry, registration + 365 days). After that, isProofFresh is false and verifiers reject the agent with Agent's human proof has expired. getInfo() exposes proofExpiresAt (unix seconds), daysUntilExpiry and isExpiringSoon (under 30 days; also isProofExpiringSoon()). Renew in place with requestProofRefresh before expiry. Some agents can’t be refreshed: see Proof refresh.
Agent cards and A2A
generateRegistrationJSON(...)builds an ERC-8004 registration document, optionally also a valid A2A Agent Card. See Agent registration JSON.agent.setAgentCard({ name, description?, url?, skills? })stores a card on-chain (NFT owner only), and the API serves it at/api/cards/{chainId}/{agentId}.A2AClientandA2AServerimplement A2A v0.3 JSON-RPC (message/send,tasks/get,tasks/cancel).
Next
- Verifying agents in a service: step-by-step setup and tests
- CLI environment variables: CLI configuration. Full export list: the SDK README
Thanks. What went wrong?
Thanks for your feedback!