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

# Initializing AgentPayClient

> Instantiate the AgentPayClient with your Service Token, security considerations, and available configuration options.

After [installing the AgentPay SDK](./installation), the next crucial step is to initialize the `AgentPayClient` in your MCP Server application. This client object is your primary interface for interacting with AgentPay services like recording consumption and validating API keys.

## Basic Initialization

To initialize the client, you need your **Service Token** (obtained when you [registered your server](../platform/server-registration)).

```python theme={null}
from agentpay_sdk import AgentPayClient
import os

# Retrieve your Service Token
# It's highly recommended to store and access your Service Token via an environment variable.
SERVICE_TOKEN = os.getenv("AGENTPAY_SERVICE_TOKEN")

if not SERVICE_TOKEN:
    # Handle the error appropriately in your application context
    # This could be logging an error, raising an exception, or preventing startup.
    print("CRITICAL: AGENTPAY_SERVICE_TOKEN environment variable is not set. AgentPayClient cannot be initialized.")
    # For example, you might raise an exception:
    # raise EnvironmentError("AGENTPAY_SERVICE_TOKEN is not set.") 
    # Or, exit if this is a critical part of startup:
    # import sys
    # sys.exit("AgentPay Service Token missing, exiting.")
    agentpay_client = None # Or handle as per your app's error strategy
else:
    try:
        agentpay_client = AgentPayClient(service_token=SERVICE_TOKEN)
        print("AgentPayClient initialized successfully.")
        # You can now use this agentpay_client instance throughout your application,
        # e.g. by making it globally accessible as a singleton in a way that suits your web framework, like Starlette.
    except Exception as e:
        # Handle potential errors during client initialization itself (e.g., invalid token format if validated at init)
        print(f"Error initializing AgentPayClient: {e}")
        agentpay_client = None # Or handle as per your app's error strategy

# Later in your code, before making calls, you could ensure agentpay_client is not None:
# if agentpay_client:
#     # Proceed with agentpay_client.consume() or agentpay_client.validate_api_key()
# else:
#     # Handle the case where client initialization failed
```

### Key Points for Initialization:

* **Service Token Security:** Always load your Service Token from a secure source, like an environment variable or a secrets management system. **Do not hardcode it** in your source code.
* **Singleton Instance (Recommended):** Typically, you should initialize the `AgentPayClient` once when your application starts and reuse the same instance throughout the lifetime of your server process. This is more efficient than creating a new client for every request.
  * How you achieve this depends on your web framework (e.g. storing it on the application object in Starlette).
* **Error Handling:** Be prepared to handle cases where the `SERVICE_TOKEN` environment variable might not be set or if the client initialization itself fails for some reason (though typically, basic initialization is lightweight).

## Client Configuration Options

At the moment, there are no other client configuration options, since:

* **Sandboxing** is handled via [Server Registration & Management](../platform/server-registration)
* There are no custom timeout or URL settings, currently

## Next Steps

Once the `AgentPayClient` is successfully initialized, you can proceed to:

* [Extracting User API Key](./extracting-api-keys) from incoming requests.
* [Validating User API Keys](./validating-api-keys) using the `validate_api_key()` method.
* [Charging for tool usage](./charging-for-usage) using the `consume()` method.
