> ## Documentation Index
> Fetch the complete documentation index at: https://docs.asgcompute.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Integration

> Integrating ASG Agent Cloud with TypeScript

# TypeScript Integration

<Note>
  An official TypeScript SDK is on the roadmap. For now, use the REST API directly with `fetch()`. The examples below show you how.
</Note>

<Tip>
  **Which endpoint?** ASG exposes two protocols:

  * **REST** (`/v1/mcp/tools/call`) — recommended for quickstart and most integrations. See [Python SDK](/sdk/python) for REST examples.
  * **JSON-RPC** (`/mcp`) — for MCP-native agent frameworks. The examples on this page use JSON-RPC since TypeScript is the primary MCP SDK language.

  Both require the same `Authorization: Bearer <api_key>` header.
</Tip>

## Quick Start

```typescript theme={null}
const ASG_ENDPOINT = 'https://agent.asgcompute.com/mcp';
const API_KEY = process.env.ASG_API_KEY!;

// Step 1: Call a tool (will return 402 with quote)
async function callTool(name: string, args: Record<string, unknown>) {
  const response = await fetch(ASG_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'tools/call',
      params: { name, arguments: args }
    })
  });

  if (response.status === 402) {
    const quote = await response.json();
    // quote.payment_instructions has pay_to, usdc_mint, network
    // Build and submit Solana USDC transfer, then retry:
    return quote;
  }

  return response.json();
}

// Step 2: Retry with payment proof
async function callToolWithPayment(
  name: string,
  args: Record<string, unknown>,
  paymentProof: string  // base64url-encoded JSON
) {
  const response = await fetch(ASG_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`,
      'X-Payment': paymentProof
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'tools/call',
      params: { name, arguments: args }
    })
  });

  return response.json();
}
```

## List Available Tools

```typescript theme={null}
async function listTools() {
  const response = await fetch(ASG_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'tools/list'
    })
  });

  const data = await response.json();
  return data.result.tools;
  // [{ name: 'inference_chat', description: '...' }, ...]
}
```

## Inference Example

```typescript theme={null}
// Get a quote for inference
const quote = await callTool('inference_chat', {
  model: 'openai/gpt-4o-mini',
  messages: [{ role: 'user', content: 'Hello!' }]
});

console.log(`Price: ${quote.quote.price_display}`);
// "Price: $0.0024"

// After paying on Solana, retry with X-Payment header
const result = await callToolWithPayment(
  'inference_chat',
  {
    model: 'openai/gpt-4o-mini',
    messages: [{ role: 'user', content: 'Hello!' }]
  },
  paymentProof
);

console.log(result.result.content);
```

## Error Handling

```typescript theme={null}
async function reliableCall(name: string, args: Record<string, unknown>, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(ASG_ENDPOINT, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
          jsonrpc: '2.0', id: 1,
          method: 'tools/call',
          params: { name, arguments: args }
        })
      });

      const data = await response.json();

      if (data.error?.code === 'QUOTE_EXPIRED') {
        continue; // Retry with fresh quote
      }
      if (data.error?.code === 'RATE_LIMITED') {
        await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
        continue;
      }

      return data;
    } catch (err) {
      if (attempt === maxRetries - 1) throw err;
    }
  }
  throw new Error('Max retries exceeded');
}
```

## Payment Proof Format

The `X-Payment` header contains a base64url-encoded JSON object:

```typescript theme={null}
const paymentProof = btoa(JSON.stringify({
  tx_signature: '5Uj3...',  // Solana transaction signature
  quote_id: 'qt_xyz789'     // Quote ID from 402 response
}));
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Examples" icon="code" href="/sdk/examples">
    More working examples
  </Card>

  <Card title="API Reference" icon="file-code" href="/api/overview">
    Complete API documentation
  </Card>
</CardGroup>
