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

# @atxp/client

> Documentation for the @atxp/client package

## Overview

The [@atxp/client](https://www.npmjs.com/package/@atxp/client) package is used to create MCP clients with OAuth authentication and payment processing via ATXP.

<Info>
  This package depends on types and utilities from [@atxp/common](/developers/api-reference/common). All shared types like `Account`, `ClientArgs`, `AuthorizationData`, `PaymentData`, and error types are documented in the common package.
</Info>

## Installation

```bash theme={null}
npm install @atxp/client
```

## Client

#### atxpClient

```typescript theme={null}
atxpClient({
  mcpServer: string,
  account: Account,
  oauthDatabase?: SQLiteOAuthDatabase | RedisOAuthDatabase,
  onAuthorize?: (authorizationData: AuthorizationData) => Promise<void>,
  onAuthorizeFailure?: (error: AuthorizationError) => Promise<void>,
  onPayment?: (paymentData: PaymentData) => Promise<void>,
  onPaymentFailure?: (error: PaymentError) => Promise<void>,
  approvePayment?: (request: PaymentRequest) => Promise<boolean>
}): Promise<Client>
```

Creates an ATXP client that can be used to interact with [ATXP-enabled MCP servers](/tools).

**Arguments**

<ParamField body="args" type="ClientArgs" required>
  Configuration arguments for the client. See [ClientArgs](/developers/api-reference/common#clientargs) for detailed property information.

  <Expandable title="ClientArgs properties">
    <ParamField body="mcpServer" type="string" required>
      The URL of the MCP server to connect to.
    </ParamField>

    <ParamField body="account" type="Account" required>
      The account to use for authentication. See [Account](/developers/api-reference/common#account) for more details.
    </ParamField>

    <ParamField body="oauthDatabase" type="SQLiteOAuthDatabase | RedisOAuthDatabase" optional>
      The OAuth database to use for storing tokens; either a [SQLiteOAuthDatabase](/developers/api-reference/sqlite) or [RedisOAuthDatabase](/developers/api-reference/redis). If not provided, the tokens will be stored in memory.
    </ParamField>

    <ParamField body="onAuthorize" type="function" optional>
      Callback function called when a user successfully authorizes the application. This is triggered after OAuth authorization completes successfully.

      ```typescript theme={null}
      onAuthorize: async (authorizationData: AuthorizationData) => {
        console.log('User authorized:', authorizationData.userId);
        // Handle successful authorization
      }
      ```

      See [AuthorizationData](/developers/api-reference/common#authorizationdata) for callback parameter details.
    </ParamField>

    <ParamField body="onAuthorizeFailure" type="function" optional>
      Callback function called when authorization fails or is denied by the user.

      ```typescript theme={null}
      onAuthorizeFailure: async (error: AuthorizationError) => {
        console.error('Authorization failed:', error.message);
        // Handle authorization failure
      }
      ```

      See [AuthorizationError](/developers/api-reference/common#authorizationerror) for error details.
    </ParamField>

    <ParamField body="onPayment" type="function" optional>
      Callback function called when a payment is successfully processed.

      ```typescript theme={null}
      onPayment: async (paymentData: PaymentData) => {
        console.log('Payment successful:', paymentData.amount, paymentData.currency);
        // Handle successful payment
      }
      ```

      See [PaymentData](/developers/api-reference/common#paymentdata) for callback parameter details.
    </ParamField>

    <ParamField body="onPaymentFailure" type="function" optional>
      Callback function called when a payment fails or is rejected.

      ```typescript theme={null}
      onPaymentFailure: async (error: PaymentError) => {
        console.error('Payment failed:', error.message);
        // Handle payment failure
      }
      ```

      See [PaymentError](/developers/api-reference/common#paymenterror) for error details.
    </ParamField>

    <ParamField body="approvePayment" type="function" optional>
      Custom payment approval logic. If not provided, all payments are automatically approved.

      ```typescript theme={null}
      approvePayment: async (request: PaymentRequest) => {
        // Custom business logic for payment approval
        if (request.amount <= 100) {
          return true; // Auto-approve payments under $100
        }
        return await confirmLargePayment(request);
      }
      ```

      See [PaymentRequest](/developers/api-reference/common#paymentrequest) for request details.
    </ParamField>
  </Expandable>
</ParamField>

**Return**

<ResponseField name="client" type="Promise<Client>">
  Returns an object that can be used to call tools on the MCP server, handling authorization and payment.
</ResponseField>

**Callbacks**

The ATXP client provides a callback system to handle authorization and payment events throughout the application lifecycle:

<AccordionGroup>
  <Accordion title="Authorization flow">
    The authorization callbacks handle the OAuth flow:

    1. **`onAuthorize`** - Called when a user successfully completes OAuth authorization
    2. **`onAuthorizeFailure`** - Called when authorization fails or is denied

    <Tip>
      Use `onAuthorize` to store user session data, update UI state, or initialize user-specific resources. Use `onAuthorizeFailure` to show appropriate error messages and provide retry options.
    </Tip>
  </Accordion>

  <Accordion title="Payment flow">
    The payment callbacks handle the payment processing flow:

    2. **`onPayment`** - Called when a payment is successfully processed
    3. **`onPaymentFailure`** - Called when a payment fails or is rejected
  </Accordion>
</AccordionGroup>

<Note>
  Callback functions should not throw unhandled exceptions as they may interrupt the payment flow. Always wrap callback logic in try-catch blocks when necessary.
</Note>

**Example usage**

<Tabs>
  <Tab title="Without callbacks">
    An example showing how to use the ATXP client without callbacks, passing in only the required arguments.

    ```typescript theme={null}
    import { atxpClient } from '@atxp/sdk'
    import { Account } from '@atxp/common'

    const client = await atxpClient({
      mcpServer: 'https://search.mcp.atxp.ai/',
      account: new Account(atxpConnectionString),
    })
    ```
  </Tab>

  <Tab title="With callbacks">
    A complete example showing how to use the available callbacks for handling authorization and payment events:

    ```typescript theme={null}
    import { atxpClient } from '@atxp/sdk'
    import { Account } from '@atxp/common'

    // Read the ATXP connection string from the environment variables
    // Your connection string should look like https://accounts.atxp.ai?connection_token=<random_string>
    // and can be found in your ATXP account dashboard at https://accounts.atxp.ai/
    const atxpConnectionString = process.env.ATXP_CONNECTION_STRING

    const client = await atxpClient({
      mcpServer: 'https://search.mcp.atxp.ai/',
      account: new Account(atxpConnectionString),

      // Authorization callbacks
      onAuthorize: async (authorizationData) => {
        console.log('User successfully authorized:', authorizationData.userId);
        // You might want to store user session data or update UI
      },

      onAuthorizeFailure: async (error) => {
        console.error('Authorization failed:', error.message);
        // Handle failed authorization - show error message to user
      },

      // Payment callbacks
      onPayment: async (paymentData) => {
        console.log(`Payment of ${paymentData.amount} ${paymentData.currency} successful`);
        // Update user's account balance, send confirmation email, etc.
      },

      onPaymentFailure: async (error) => {
        console.error('Payment failed:', error.message);
        // Handle payment failure - show error, retry logic, etc.
      },

      // Payment approval logic
      approvePayment: async (paymentRequest) => {
        // Custom business logic for payment approval
        if (paymentRequest.amount <= 100) {
          return true; // Auto-approve payments under $100
        }

        // For larger payments, you might want to require additional confirmation
        return await confirmLargePayment(paymentRequest);
      }
    });
    ```
  </Tab>
</Tabs>

#### callTool

```typescript theme={null}
callTool({
  name: string,
  arguments: any
}): Promise<ToolResult>
```

Calls a tool on the configured MCP server.

<Tip>
  A list of ATXP-provided MCP servers can be found [here](/tools).
</Tip>

**Arguments**

<Expandable title="callTool arguments">
  <ParamField body="name" type="string" required>
    The name of the tool to call.
  </ParamField>

  <ParamField body="arguments" type="any" required>
    The arguments to pass to the tool.
  </ParamField>
</Expandable>

**Return**

Returns a `Promise<ToolResult>` typed object that contains the result of the tool call.

**Example usage**

```typescript theme={null}
import { atxpClient } from '@atxp/sdk'
import { Account } from '@atxp/common'

// Read the ATXP connection string from the environment variables
// Your connection string should look like https://accounts.atxp.ai?connection_token=<random_string>
// and can be found in your ATXP account dashboard at https://accounts.atxp.ai/
const atxpConnectionString = process.env.ATXP_CONNECTION_STRING

const client = await atxpClient({
  mcpServer: 'https://search.mcp.atxp.ai/',
  account: new Account(atxpConnectionString),
})

const query = "latest news on the US financial sector";

const result = await client.callTool({
  name: 'search_search',
  arguments: { query }
});
```

## ATXPAccount

#### ATXPAccount

```typescript theme={null}
ATXPAccount(
  connectionString: string,
  opts?: {
    fetchFn?: FetchLike,
    network?: Network
  }): ATXPAccount
```

Creates an ATXP account object that can be used to create an ATXP client.

**Arguments**

<Expandable title="ATXPAccount arguments">
  <ParamField body="connectionString" type="string" required>
    The ATXP connection string in the format: `https://accounts.atxp.ai?connection_token=<token>`. This connection string identifies the ATXP account that will be used by the client to pay for MCP server tool calls. You can find your connection string in your ATXP account dashboard at [https://accounts.atxp.ai/](https://accounts.atxp.ai/).
  </ParamField>

  <ParamField body="opts" type="object" optional>
    The options for the ATXP account.

    <Expandable title="ATXPAccount opts properties">
      <ParamField body="fetchFn" type="FetchLike" optional>
        The fetch function to use for the ATXP account.
      </ParamField>
    </Expandable>
  </ParamField>

  <ParamField body="network" type="Network" optional>
    The network to use for the ATXP account.
  </ParamField>
</Expandable>

## Account Types Moved to Separate Packages

<Note>
  **v0.9.0+ Breaking Change**: Blockchain-specific account types have been moved to dedicated packages as part of the modular architecture.

  * **`BaseAccount`** → Moved to [`@atxp/base`](/developers/api-reference/base)
  * **`SolanaAccount`** → Moved to `@atxp/solana` (install with `npm install @atxp/solana`)

  The core `@atxp/client` package now focuses on essential features with zero blockchain code (except `ATXPLocalAccount`), resulting in reduced bundle sizes and eliminated security vulnerabilities for users who don't need blockchain-specific functionality.
</Note>
