Skip to content

Start typing to search the documentation.

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("").

HeaderECDSA (EVM) agentsEd25519 agents
x-self-agent-signatureEIP-191 personal_sign of the 32 bytesEd25519 signature of the same 32 bytes
x-self-agent-timestampUnix millisecondsUnix milliseconds
x-self-agent-addressThe agent’s address (informational)Not sent
x-self-agent-keytypeNot sented25519
x-self-agent-keyNot sentThe 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:

  1. Recompute the digest from the raw body bytes and reject stale timestamps.
  2. Get the agent key: ECDSA → recover the EIP-191 signer and use zeroPad(signer, 32); Ed25519 → verify against x-self-agent-key and use that key.
  3. On the registry, require isVerifiedAgent(agentKey) and isProofFresh(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.

MemberReturns
address, agentKeyEVM 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 methodEffectDefault
.network(name) / .registry(addr) / .rpc(url)Chain to readmainnet
.requireAge(n)Minimum proven age (18 or 21). Fetches credentials automaticallyOff
.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 providerOn
.sybilLimit(n)Max active agents per human (0 = unlimited)1
.rateLimit({ perMinute?, perHour? })Per-agent sliding window, in memoryOff
.replayProtection(enabled?)Reject reused signatures. The 10,000-entry cache is per process: share replay state across instancesOn
.includeCredentials()Attach credentials to the resultOff
.maxAge(ms) / .cacheTtl(ms)Timestamp window / on-chain cache TTL5 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()

Statuserror
401Missing 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
429Rate limit exceeded (N/min) or (N/hr), with retryAfterMs
500Raw request body unavailable for signature verification
503Agent verification unavailable, try again later (the chain could not be read)

On success, req.agent holds:

FieldTypeDescription
addressstringAgent’s address (recovered, or derived from the Ed25519 key)
agentKeystringbytes32 registry key
agentIdbigintOn-chain agent ID
agentCountbigintActive agents of the same human
nullifierbigintThe human’s nullifier (rate-limit or dedupe per human)
credentialsobjectWith 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();
FunctionDoes
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 HTTP status). An expired session throws ExpiredSessionError.
  • 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}.
  • A2AClient and A2AServer implement A2A v0.3 JSON-RPC (message/send, tasks/get, tasks/cancel).

Next

Was this page helpful?