API Reference

Core Agent API
Primary methods for agent lifecycle management and initialization.
constructor(name: string, signer: TEESigner, mode?: AgentMode)Create a new TEE-secured agent instance with specified operational mode
Example
import { UnifiedTEEAgent } from '@catgirl/agent-sdk';import { TEESigner } from '@catgirl/tee-client';const signer = new TEESigner({ mode: 'production' });await signer.connect();const agent = new UnifiedTEEAgent('MyAgent',signer,'production' // or 'development', 'test');
start(options?: NetworkOptions): Promise<void>Initialize and start the agent with network configuration
Example
await agent.start({port: 9100,bootstrapNodes: ['/ip4/192.168.1.100/tcp/9000/p2p/12D3KooW...'],announceAddresses: ['/ip4/0.0.0.0/tcp/9100']});// After start, agent has:console.log('ETH Address:', agent.ethAddress);console.log('Peer ID:', agent.peerId);console.log('Trust Score:', agent.getMyAttestation()?.trustScore);
stop(): Promise<void>Gracefully shutdown the agent and all components
Example
await agent.stop();// All connections closed, resources cleaned up
Secure Messaging API
End-to-end encrypted messaging between TEE agents with signature verification.
sendSecureMessage(ethAddress: string, content: any, messageType?: string): Promise<boolean>Send encrypted message to another agent by Ethereum address
Example
const success = await agent.sendSecureMessage('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb3',{type: 'greeting',message: 'Hello from secure TEE!'},'custom_message');
sendAttestedMessage(ethAddress: string, content: any, messageType?: string, minTrust?: number): Promise<boolean>Send message only if recipient meets minimum trust score requirement
Example
// Only send if recipient has trust score >= 70const success = await agent.sendAttestedMessage(recipientAddress,sensitiveData,'confidential',70);
sendRequest(ethAddress: string, method: string, params?: any): Promise<any>Send RPC request to another agent and await response
Example
const result = await agent.sendRequest(targetAddress,'agent.getInfo',{ includeStats: true });console.log('Remote agent info:', result);
sendNotification(ethAddress: string, method: string, params?: any): Promise<void>Send one-way notification (no response expected)
Example
await agent.sendNotification(peerAddress,'task.progress',{ taskId: 'abc123', progress: 75 });
TEE Attestation API
Hardware attestation and trust score management for secure agent verification.
getMyAttestation(): AttestationBinding | undefinedGet current agent's TEE attestation with trust score
Example
const attestation = agent.getMyAttestation();if (attestation) {console.log('Platform:', attestation.attestation_report.platform);console.log('Trust Score:', agent.getTrustScore(agent.ethAddress));console.log('Measurements:', attestation.attestation_report.measurements);}
getTrustScore(ethAddress: string): numberGet trust score (0-100) for a peer by address
Example
const trustScore = agent.getTrustScore(peerAddress);if (trustScore >= 50) {console.log('Peer is trusted for sensitive operations');}
isPeerAttested(ethAddress: string): booleanCheck if peer has valid TEE attestation
Example
if (agent.isPeerAttested(peerAddress)) {// Safe to share sensitive dataawait agent.sendSecureMessage(peerAddress, confidentialData);}
requestPeerAttestation(ethAddress: string): Promise<void>Request attestation update from a peer
Example
await agent.requestPeerAttestation(peerAddress);// Peer will respond with updated attestation
Peer Discovery API
Direct discovery protocol and P2P networking for agent-to-agent connections.
findAgentByAddress(ethAddress: string): Promise<PeerRecord | null>Discover agent by Ethereum address using Direct Discovery or broadcast
Example
const peer = await agent.findAgentByAddress('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb3');if (peer) {console.log('Found peer:', peer.peerId);console.log('Port:', peer.port);console.log('Multiaddrs:', peer.multiaddrs);}
getPeers(): PeerRecord[]Get all known peers in the network
Example
const peers = agent.getPeers();console.log(`Connected to ${peers.length} peers`);peers.forEach(peer => {console.log(`${peer.ethAddress}: ${peer.verified ? '✓' : '✗'}`);});
getAttestedPeers(): AttestedPeerRecord[]Get only peers with valid TEE attestations
Example
const trustedPeers = agent.getAttestedPeers();console.log(`${trustedPeers.length} verified TEE agents online`);// Show trust distributiontrustedPeers.forEach(peer => {console.log(`${peer.ethAddress.slice(0,8)}...: Trust ${peer.trustScore}/100`);});
dialMultiaddr(addr: string, options?: DialOptions): Promise<void>Connect directly to a peer using multiaddr
Example
await agent.dialMultiaddr('/ip4/192.168.1.100/tcp/9000/p2p/12D3KooWL8qb3L8nKPjDtQmJU8jge5Qspsn6YLSBei9MsbTjJDr8',{maxRetries: 5,timeout: 10000});
Task Execution API
Distributed task execution with quotes, pricing, and progress tracking.
requestQuote(ethAddress: string, task: TaskRequest): Promise<TaskQuote>Request price quote for task execution from another agent
Example
const quote = await agent.requestQuote(executorAddress,{type: 'compute',data: {operation: 'matrix_multiply',size: 1000}});console.log('Price:', quote.price);console.log('ETA:', quote.estimatedTime, 'seconds');
executeTask(ethAddress: string, task: TaskRequest & {taskId: string}): Promise<TaskStatus>Submit task for remote execution
Example
const status = await agent.executeTask(executorAddress,{taskId: quote.taskId,type: 'compute',data: computePayload,authorization: {maxPrice: '100 USDC',deadline: Date.now() + 300000}});console.log('Task status:', status.status);
getTaskStatus(ethAddress: string, taskId: string): Promise<TaskStatus>Check status of remote task execution
Example
const status = await agent.getTaskStatus(executorAddress,'task-abc-123');if (status.status === 'completed') {console.log('Result:', status.result);}
MCP Tool Marketplace API
Model Context Protocol tools for agent-to-agent service marketplace.
registerTool(tool: MCPToolWithPricing, executor: Function): voidOffer a tool/service to other agents with pricing
Example
agent.registerTool({name: 'image_generation',description: 'Generate images using DALL-E',inputSchema: {type: 'object',properties: {prompt: { type: 'string' },size: { type: 'string', enum: ['256x256', '512x512'] }}},pricing: [{chainId: 1,token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDCamount: '1000000', // 1 USDCdecimals: 6,symbol: 'USDC'}]},async (args) => {// Tool implementationconst image = await generateImage(args.prompt, args.size);return { url: image.url };});
queryTools(ethAddress: string): Promise<MCPToolWithPricing[]>Discover tools offered by another agent
Example
const tools = await agent.queryTools(providerAddress);tools.forEach(tool => {console.log(`Tool: ${tool.name}`);console.log(`Price: ${tool.pricing[0].amount} ${tool.pricing[0].symbol}`);});
hireTool(ethAddress: string, toolName: string, args: any, payment?: MCPPayment): Promise<any>Hire and execute a tool from another agent
Example
// Hire tool with payment authorizationconst result = await agent.hireTool(providerAddress,'image_generation',{prompt: 'A cat writing code',size: '512x512'},{vault: '0x...', // Payment vault addresschain: 1,token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',amount: '1000000',nonce: 42,signature: '0x...',recipient: providerAddress});console.log('Generated image:', result.url);
Utility API
Helper methods for agent information, capabilities, and diagnostics.
getAgentInfo(ethAddress: string): Promise<any>Get comprehensive information about another agent
Example
const info = await agent.getAgentInfo(peerAddress);console.log('Name:', info.name);console.log('Platform:', info.platform);console.log('Trust Score:', info.trustScore);console.log('Active Tasks:', info.activeTasks);console.log('Features:', info.features);
ping(ethAddress: string): Promise<number>Measure round-trip latency to another agent
Example
const latency = await agent.ping(peerAddress);console.log(`Latency: ${latency}ms`);
getCapabilities(ethAddress: string): Promise<AgentCapabilities>Query capabilities and features of another agent
Example
const caps = await agent.getCapabilities(peerAddress);console.log('Protocol:', caps.protocolVersion);console.log('Features:', caps.features);console.log('Max Task Size:', caps.limits?.maxTaskSize);
ensureConnection(ethAddress: string): Promise<boolean>Ensure active connection to peer, establishing if needed
Example
const connected = await agent.ensureConnection(peerAddress);if (connected) {// Connection established or already existsawait agent.sendSecureMessage(peerAddress, data);}
State Management API
Methods for inspecting agent state, connections, and runtime statistics.
getActiveTasks(): TaskStatus[]Get all currently executing tasks
Example
const tasks = agent.getActiveTasks();tasks.forEach(task => {console.log(`Task ${task.taskId}: ${task.status} (${task.progress}%)`);});
getConnections(): any[]Get all active network connections
Example
const connections = agent.getConnections();console.log(`Active connections: ${connections.length}`);
getMultiaddrs(): string[]Get agent's listening addresses
Example
const addrs = agent.getMultiaddrs();addrs.forEach(addr => console.log('Listening on:', addr));
getErrorStats(): anyGet error statistics and history
Example
const stats = agent.getErrorStats();console.log('Total errors:', stats.total);console.log('Critical errors:', stats.bySeverity.critical);
Agent Modes
Configuration modes that determine agent behavior and security settings.
| Setting | Development | Production | Test |
|---|---|---|---|
| Attestation Required | No | Yes | No |
| Min Trust Score | 0 | 50 | 0 |
| Mock TEE Allowed | Yes | No | Yes |
| Message Timeout | 30s | 15s | 5s |
| Task Timeout | 5m | 3m | 10s |
| Max Message Rate | 100/min | 50/min | 1000/min |
| Rate Limiting | Yes | Yes | No |
Common Types
TypeScript type definitions used throughout the API.
// Core Typesinterface PeerRecord {ethAddress: string;peerId: string;publicKey: string;multiaddrs: string[];lastSeen: number;verified: boolean;}interface AttestationBinding {attestation_report: AttestationReport;eth_address: string;peer_id: string;binding_timestamp: string;binding_signature: Hex;}interface TaskRequest {type: string;data: any;authorization?: {maxPrice?: string;deadline?: number;nonce?: string;};}interface MCPToolWithPricing {name: string;description?: string;inputSchema: object;pricing: Array<{chainId: number;token: string;amount: string;decimals: number;symbol: string;}>;}interface AgentCapabilities {methods: string[];version: string;protocolVersion: string;features: string[];limits?: {maxTaskSize?: number;maxConcurrentTasks?: number;timeout?: number;};}type AgentMode = 'development' | 'production' | 'test';type Hex = `0x${string}`;
