> ## 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/sqlite

> SQLite OAuth database implementation for persistent token storage in ATXP applications

## Overview

The [@atxp/sqlite](https://www.npmjs.com/package/@atxp/sqlite) package provides a SQLite-based OAuth database implementation for ATXP. It offers persistent OAuth token storage using SQLite, ensuring data retention across application restarts.

<Info>
  This package is designed to work seamlessly with `@atxp/client` and `@atxp/express` packages when you need persistent storage that survives application restarts. For high-scale applications, consider using [@atxp/redis](/developers/api-reference/redis) instead.
</Info>

## Installation

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

<Note>
  The `@atxp/sqlite` package includes TypeScript definitions and requires Node.js 16 or higher. It automatically installs `@atxp/common` as a dependency.
</Note>

## API Reference

### Classes

#### `SQLiteOAuthDatabase`

The main class for managing OAuth tokens in a SQLite database.

```typescript theme={null}
import { SQLiteOAuthDatabase } from '@atxp/sqlite'
```

**Constructor**

```typescript theme={null}
new SQLiteOAuthDatabase(options: SQLiteOAuthDatabaseOptions)
```

<ParamField body="options" type="SQLiteOAuthDatabaseOptions" required>
  Configuration options for the SQLite database connection.

  <Expandable title="SQLiteOAuthDatabaseOptions properties">
    <ParamField body="databasePath" type="string" required>
      Path to the SQLite database file. If the file doesn't exist, it will be created automatically.
    </ParamField>

    <ParamField body="autoCreateTables" type="boolean" default="true">
      Whether to automatically create the required database tables on initialization.
    </ParamField>

    <ParamField body="connectionTimeout" type="number" default="5000">
      Connection timeout in milliseconds.
    </ParamField>
  </Expandable>
</ParamField>

**Methods**

<ResponseField name="saveAccessToken" type="Promise<void>">
  Saves an OAuth access token in the database.

  <Expandable title="saveAccessToken arguments">
    <ParamField body="userId" type="string" required>
      Unique identifier for the user associated with the access token.
    </ParamField>

    <ParamField body="token" type="string" required>
      The OAuth access token value to store.
    </ParamField>

    <ParamField body="url" type="AccessToken" required>
      URL associated with the access token.
    </ParamField>
  </Expandable>
</ResponseField>

<ResponseField name="getAccessToken" type="Promise<AccessToken | null>">
  Retrieves an OAuth access token from the database.

  <Expandable title="getAccessToken arguments">
    <ParamField body="userId" type="string" required>
      Unique identifier for the user associated with the access token.
    </ParamField>

    <ParamField body="url" type="AccessToken" required>
      URL associated with the access token.
    </ParamField>
  </Expandable>
</ResponseField>

<ResponseField name="deleteToken" type="Promise<boolean>">
  Deletes an OAuth token from the database.

  <ParamField body="key" type="string" required>
    Unique identifier for the token to delete.
  </ParamField>
</ResponseField>

<ResponseField name="hasToken" type="Promise<boolean>">
  Checks if a token exists in the database.

  <ParamField body="key" type="string" required>
    Unique identifier for the token to check.
  </ParamField>
</ResponseField>

<ResponseField name="listTokens" type="Promise<string[]>">
  Lists all token keys stored in the database.
</ResponseField>

<ResponseField name="close" type="Promise<void>">
  Closes the database connection and releases resources.
</ResponseField>

### Interfaces

#### `SQLiteOAuthDatabaseOptions`

Configuration options for the SQLite OAuth database.

```typescript theme={null}
interface SQLiteOAuthDatabaseOptions {
  databasePath: string
  autoCreateTables?: boolean
  connectionTimeout?: number
}
```

<ResponseField name="databasePath" type="string" required>
  Path to the SQLite database file. Can be a relative or absolute path.
</ResponseField>

<ResponseField name="autoCreateTables" type="boolean" default="true">
  Whether to automatically create the required database tables on initialization.
</ResponseField>

<ResponseField name="connectionTimeout" type="number" default="5000">
  Connection timeout in milliseconds.
</ResponseField>

## Usage Examples

### Integration with ATXP Client

Use SQLite storage with the ATXP client for persistent token management:

```typescript theme={null}
import { atxpClient, ATXPAccount } from '@atxp/client'
import { SQLiteOAuthDatabase } from '@atxp/sqlite'

// Create OAuth database
const oauthDb = new SQLiteOAuthDatabase({
  databasePath: './atxp-tokens.db'
})

// Create ATXP client with custom OAuth storage
const client = await atxpClient({
  mcpServer: 'https://search.mcp.atxp.ai/',
  account: new ATXPAccount(process.env.ATXP_CONNECTION),
  oauthDatabase: oauthDb
})

// Use the client - tokens will be automatically stored in SQLite
const result = await client.callTool('search_search', {
  query: 'example query'
})
```

### Integration with ATXP Server

Use SQLite storage with the ATXP server for persistent session management:

```typescript theme={null}
import { atxpExpress, ATXPAccount } from '@atxp/express'
import { SQLiteOAuthDatabase } from '@atxp/sqlite'
import express from 'express'

// Create OAuth database
const oauthDb = new SQLiteOAuthDatabase({
  databasePath: './server-tokens.db'
})

const app = express()

// Use ATXP server with SQLite OAuth storage
app.use('/mcp', atxpExpress({
  destination: new ATXPAccount(process.env.ATXP_CONNECTION),
  payeeName: 'My MCP Server',
  oauthDatabase: oauthDb
}))

app.listen(3000, () => {
  console.log('Server running on port 3000')
})
```

## Configuration

### Database File Location

The SQLite database file can be placed anywhere on your filesystem:

```typescript theme={null}
// Relative path (creates file in current directory)
const oauthDb = new SQLiteOAuthDatabase({
  databasePath: './tokens.db'
})

// Absolute path
const oauthDb = new SQLiteOAuthDatabase({
  databasePath: '/var/lib/atxp/tokens.db'
})

// In-memory database (temporary, not persistent)
const oauthDb = new SQLiteOAuthDatabase({
  databasePath: ':memory:'
})
```

### Environment Variables

Configure the database path using environment variables:

```bash theme={null}
# .env file
ATXP_SQLITE_DB_PATH=./oauth-tokens.db
ATXP_SQLITE_CONNECTION_TIMEOUT=10000
```

```typescript theme={null}
import { SQLiteOAuthDatabase } from '@atxp/sqlite'

const oauthDb = new SQLiteOAuthDatabase({
  databasePath: process.env.ATXP_SQLITE_DB_PATH || './tokens.db',
  connectionTimeout: parseInt(process.env.ATXP_SQLITE_CONNECTION_TIMEOUT || '5000')
})
```

### Database Schema

The package automatically creates the following table structure:

```sql theme={null}
CREATE TABLE oauth_tokens (
  key TEXT PRIMARY KEY,
  token TEXT NOT NULL,
  expires_at INTEGER,
  created_at INTEGER DEFAULT (strftime('%s', 'now')),
  updated_at INTEGER DEFAULT (strftime('%s', 'now'))
)
```

<Info>
  The database schema is automatically created when `autoCreateTables` is set to `true` (default). You can disable this behavior if you want to manage the schema manually.
</Info>

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="Database file permission errors">
    If you encounter permission errors when creating or accessing the database file:

    * Ensure the directory exists and has write permissions
    * Check that the user running the application has access to the database path
    * Consider using an absolute path instead of a relative path

    ```typescript theme={null}
    // Use absolute path to avoid permission issues
    const oauthDb = new SQLiteOAuthDatabase({
      databasePath: '/var/lib/atxp/tokens.db'
    })
    ```
  </Accordion>

  <Accordion title="Connection timeout errors">
    If you're experiencing connection timeouts:

    * Increase the `connectionTimeout` value
    * Check if the database file is locked by another process
    * Ensure sufficient disk space is available

    ```typescript theme={null}
    const oauthDb = new SQLiteOAuthDatabase({
      databasePath: './tokens.db',
      connectionTimeout: 30000 // 30 seconds
    })
    ```
  </Accordion>
</AccordionGroup>

## Related Packages

<CardGroup cols={2}>
  <Card title="@atxp/client" icon="laptop" href="/developers/api-reference/client">
    Client-side integration for MCP clients with OAuth authentication.
  </Card>

  <Card title="@atxp/express" icon="server" href="/developers/api-reference/express">
    Server-side middleware for MCP servers with payment processing.
  </Card>

  <Card title="@atxp/redis" icon="database" href="/developers/api-reference/redis">
    Redis OAuth database for high-scale applications.
  </Card>

  <Card title="@atxp/common" icon="code" href="/developers/api-reference/common">
    Shared utilities and types used across ATXP packages.
  </Card>
</CardGroup>
