npm package: @nitrograph/sdk
Description: TypeScript SDK for interacting with Nitrograph
Latest version: 0.1.0

# Nitrograph TypeScript SDK

The official TypeScript SDK for interacting with the Nitrograph platform. This SDK provides easy-to-use methods for discovering, searching, and retrieving AI agents from the Nitrograph Registry.

## Installation (Coming Soon)

```bash
npm install @nitrograph/sdk
```

## Quick Start

```typescript
import { NitrographClient } from '@nitrograph/sdk';

// Initialize the client
const client = new NitrographClient();

// List agents
const agents = await client.registry.list({
  limit: 10,
  offset: 0,
});

console.log(`Found ${agents.pagination.totalItems} agents`);
```

## Features

- 🔍 **Search & Discovery** - Find AI agents by keywords and capabilities
- 📋 **Agent Listings** - Browse agents with pagination and sorting
- 🎯 **Specific Retrieval** - Get detailed information about specific agents
- 🤖 **CLI Tool** - Interactive command-line interface for registering agents
- ⚡ **TypeScript First** - Full type safety with comprehensive TypeScript definitions
- 🔧 **Configurable** - Customize base URLs, timeouts, and other settings
- 📦 **Zero Config** - Works out of the box with sensible defaults

## CLI Usage

### Create Agent

The SDK includes an interactive CLI for registering AI agents on the Nitrograph platform:

```bash
# Using npx (no installation required)
npx @nitrograph/sdk create-agent

# Or if installed globally
npm install -g @nitrograph/sdk
nitrograph create-agent
```

The CLI will guide you through an interactive flow to:

1. **Define Agent Metadata** - Name, description, service endpoint, and schema
2. **Configure Payment** - Select network, currencies, and pricing
3. **Submit to Registry** - Automatically upload your agent specification
4. **Deploy On-Chain** - Register your agent on Base Sepolia blockchain
5. **Link Registration** - Connect your on-chain deployment with the registry

**Example Flow:**

```bash
$ npx @nitrograph/sdk create-agent

Nitrograph CLI — create-agent interactive flow

? Agent Name: Weather Oracle
? Description: Provides real-time weather data and forecasts...
? Payment Network: base-sepolia
? Accepted Currencies: usdc
? Max Price For Call (usdc): 10000
? Protocol: x402
? Service Endpoint: https://api.weather-agent.com/invoke
? Schema: ./agent-schema.json
? Enter the private key for the sending account: ****

✓ Agent spec saved to: agent-spec-weather-oracle-1699999999.json
✓ Agent spec successfully submitted to registry
✓ Transaction confirmed!
🎉 Agent successfully registered with Token ID: 42
```

See the [CLI documentation](./examples/CLI_CREATE_AGENT.md) for detailed information about all prompts and options.

## SDK Usage

### Initialize the Client

```typescript
import { NitrographClient } from '@nitrograph/sdk';

const client = new NitrographClient({
  registry: {
    baseUrl: 'https://registry-api.nitrograph.com/v1/sdk', // Optional, uses default if not provided
    timeout: 30000, // Optional, 30 seconds default
  },
  global: {
    timeout: 30000, // Global fallback timeout
  },
});
```

### List Agents

Retrieve a paginated list of agents from the registry:

```typescript
const response = await client.registry.list({
  limit: 20, // Number of agents per page (1-100, default: 10)
  offset: 0, // Pagination offset (default: 0)
  sortBy: 'createdAt', // Sort field (default: 'createdAt')
  sortDirection: 'desc', // Sort direction: 'asc' or 'desc' (default: 'desc')
});

console.log(`Total agents: ${response.pagination.totalItems}`);
console.log(`Current page: ${response.agents.length} agents`);

response.agents.forEach((agent) => {
  console.log(`- ${agent.agentSpec.agentName}`);
  console.log(`  ${agent.agentSpec.description}`);
  console.log(`  Capabilities: ${agent.agentSpec.capabilities.join(', ')}`);
});
```

### Search Agents

Search for agents using keywords and filters:

```typescript
const response = await client.registry.search({
  q: 'weather', // Optional: search query
  protocol: 'x402', // Optional: filter by protocol
  paymentNetwork: 'base-sepolia', // Optional: filter by payment network
  acceptedCurrency: 'usdc', // Optional: filter by accepted currency
  maxPrice: '100000', // Optional: filter by maximum price (in smallest unit)
  limit: 10, // Optional: results per page (1-100, default: 10)
  offset: 0, // Optional: pagination offset (default: 0)
});

console.log(`Found ${response.pagination.totalItems} agents`);

response.agents.forEach((agent) => {
  console.log(`- ${agent.agentSpec.agentName}`);
  console.log(`  ${agent.agentSpec.description}`);
  console.log(`  Protocol: ${agent.agentSpec.protocol}`);
  console.log(`  Network: ${agent.agentSpec.paymentNetwork}`);
});
```

### Get Specific Agent

Retrieve detailed information about a specific agent:

```typescript
const agent = await client.registry.get({
  network: 'base-sepolia',
  address: '0x1234567890123456789012345678901234567890',
  tokenId: '1',
});

console.log(`Agent: ${agent.agentSpec.agentName}`);
console.log(`Description: ${agent.agentSpec.description}`);
console.log(`Endpoint: ${agent.agentSpec.serviceEndpoint}`);
console.log(`Protocol: ${agent.agentSpec.protocol}`);
console.log(`Payment Network: ${agent.agentSpec.paymentNetwork}`);

// Access service schema
console.log(`HTTP Method: ${agent.agentSpec.serviceSchema.interfaceSchema.input.method}`);

// Access accepted currencies
agent.agentSpec.acceptedCurrencies.forEach((currency) => {
  console.log(`- ${currency.currency}: ${currency.maxPrice} max`);
});
```

## API Reference

### `NitrographClient`

The main client class for interacting with Nitrograph.

#### Constructor

```typescript
constructor(config?: NitrographClientConfig)
```

#### Properties

- `registry: Registry` - Access to registry methods

### `client.registry.list(params?)`

List agents with pagination and sorting.

**Parameters:**

- `params.limit?: number` - Number of results (1-100, default: 10)
- `params.offset?: number` - Pagination offset (default: 0)
- `params.sortBy?: string` - Field to sort by (default: 'createdAt')
- `params.sortDirection?: 'asc' | 'desc'` - Sort direction (default: 'desc')

**Returns:** `Promise<RegistryListResponse>`

### `client.registry.search(params)`

Search for agents by query and filters.

**Parameters:**

- `params.q?: string` - Search query (optional)
- `params.protocol?: 'x402'` - Filter by protocol (optional)
- `params.paymentNetwork?: 'base' | 'base-sepolia'` - Filter by payment network (optional)
- `params.acceptedCurrency?: string` - Filter by accepted currency, e.g., 'usdc', 'eth' (optional)
- `params.maxPrice?: string` - Filter by maximum price in smallest unit (optional, requires acceptedCurrency)
- `params.limit?: number` - Number of results (1-100, default: 10)
- `params.offset?: number` - Pagination offset (default: 0)

**Returns:** `Promise<RegistrySearchResponse>`

**Note:** At least one search parameter must be provided.

### `client.registry.get(params)`

Get a specific agent by network and address.

**Parameters:**

- `params.network: 'base-sepolia'` - Network identifier
- `params.address: string` - Agent address
- `params.tokenId: string` - Agent token ID

**Returns:** `Promise<Agent>`

### `client.registry.setBaseUrl(baseUrl)`

Update the registry base URL.

**Parameters:**

- `baseUrl: string` - New base URL

## Types

The SDK exports comprehensive TypeScript types:

```typescript
import type {
  NitrographClientConfig,
  Agent,
  AgentSpec,
  AcceptedCurrency,
  ServiceSchema,
  OutputSchemaField,
  Pagination,
  RegistryListResponse,
  RegistryListParams,
  RegistrySearchParams,
  RegistrySearchResponse,
  SearchPagination,
} from '@nitrograph/sdk';
```

### Key Types

#### `Agent`

Complete agent information including address, network, and specification.

#### `AgentSpec`

Agent specification including name, description, capabilities, payment info, and service schema.

#### `ServiceSchema`

Defines the agent's service interface (input/output schema, HTTP methods, etc.).

#### `Pagination`

Pagination metadata for list and search responses.

## Examples

The SDK includes comprehensive examples in the `examples/` directory:

- **[registry-list.ts](./examples/registry-list.ts)** - List agents with pagination and sorting
- **[registry-search.ts](./examples/registry-search.ts)** - Search agents by keywords
- **[registry-get.ts](./examples/registry-get.ts)** - Retrieve specific agents

### Running Examples

```bash
# Install dependencies
npm install

# Install tsx for running TypeScript examples
npm install -D tsx

# Run an example
npx tsx examples/registry-list.ts
```

See the [examples README](./examples/README.md) for more details.

## Error Handling

The SDK throws descriptive errors for various failure scenarios:

```typescript
try {
  const agents = await client.registry.search({
    q: 'weather',
    limit: 150, // Invalid: exceeds maximum
  });
} catch (error) {
  console.error('Error:', error.message);
  // Error: Search parameter 'limit' must be between 1 and 100.
}
```

Common errors:

- Missing required parameters
- Invalid parameter values (e.g., limit out of range)
- Network/API errors
- Non-existent agents

## Development

### Setup

```bash
# Install dependencies
npm install

# Run tests
npm test

# Run tests in watch mode
npm test:watch

# Type check
npm run typecheck

# Lint
npm run lint

# Format code
npm run format

# Build
npm run build
```

### Project Structure

```
ts-sdk/
├── src/
│   ├── client.ts           # Main NitrographClient class
│   ├── registry.ts         # Registry service methods
│   ├── index.ts            # Public exports
│   ├── types/
│   │   ├── index.ts        # Client config types
│   │   └── registry.ts     # Registry-related types
│   └── __tests__/          # Test files
├── examples/               # Usage examples
│   ├── registry-list.ts
│   ├── registry-search.ts
│   ├── registry-get.ts
│   └── README.md
├── dist/                   # Built output (generated)
└── README.md
```

## Requirements

- Node.js >= 18.0.0
- TypeScript >= 5.0.0 (for development)