# https://github.com/lucaperret/tidal-cli 项目说明书

生成时间：2026-05-16 11:20:21 UTC

## 目录

- [Project Overview](#page-project-overview)
- [System Architecture](#page-architecture)
- [Getting Started](#page-getting-started)
- [CLI Commands - Core Modules](#page-cli-commands)
- [CLI Commands - Search & Discovery](#page-cli-commands-search)
- [CLI Commands - Library & Playlist Management](#page-cli-commands-library)
- [CLI Commands - Playback System](#page-cli-commands-playback)
- [Authentication System](#page-authentication)
- [Data Flow & Session Management](#page-data-flow)
- [MCP Server Integration](#page-mcp-server)

<a id='page-project-overview'></a>

## Project Overview

### 相关页面

相关主题：[System Architecture](#page-architecture), [Getting Started](#page-getting-started)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
- [site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)
- [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)
- [site/app/terms/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/terms/page.tsx)
- [src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts)
</details>

# Project Overview

tidal-cli is an open-source command-line interface tool that enables programmatic interaction with the Tidal music streaming service directly from the terminal. The project provides both a traditional CLI tool and an MCP (Model Context Protocol) server integration for AI agents.

## Purpose and Scope

tidal-cli serves two primary use cases:

| Use Case | Description |
|----------|-------------|
| **CLI Tool** | Direct terminal interaction with Tidal for personal music management |
| **MCP Server** | AI agent integration for Claude Desktop and other MCP-compatible clients |

资料来源：[site/app/privacy/page.tsx:41-45]()

The tool is designed for personal use and LLM agent automation, allowing users to search tracks, manage playlists, control playback, discover new music, and interact with their music library without a web browser or desktop application.

## High-Level Architecture

```mermaid
graph TD
    A[User / AI Agent] --> B[tidal-cli]
    B --> C{Mode}
    C -->|CLI Mode| D[Local Execution]
    C -->|MCP Mode| E[Remote Server]
    D --> F[Tidal API]
    E --> F
    F --> G[Tidal Servers]
    
    D -.-> H[~/.tidal-cli/session.json]
    E -.-> I[Upstash Redis - Encrypted]
    
    style F fill:#4a90d9
    style G fill:#ff6b6b
```

资料来源：[site/app/privacy/page.tsx:41-52]()

### CLI Mode

When used as a command-line tool, tidal-cli communicates directly between your device and Tidal's API servers. No data passes through any intermediary server. Authentication tokens are stored locally on your device.

### MCP Server Mode

When used as an MCP connector (e.g., through Claude Desktop or claude.ai), authentication tokens are stored server-side in an encrypted Redis database hosted on Upstash via Vercel.

## Installation

### Prerequisites

- Node.js environment
- Tidal account

### Installation Commands

```bash
npm install -g @lucaperret/tidal-cli

# Sign in with your Tidal account
tidal-cli auth
Opening browser for Tidal authorization...
Authenticated successfully! User ID: 123456789

# Start exploring
tidal-cli search track "Teardrop"
```

资料来源：[site/app/page.tsx:101-115]()

## Core Features

### 40 Available Tools

tidal-cli provides comprehensive coverage of Tidal's functionality across multiple domains:

| Category | Capabilities |
|----------|-------------|
| **Search** | Search tracks, albums, artists, playlists, videos |
| **Playlists** | Create, rename, delete playlists; add/remove tracks and albums |
| **Playback** | Play tracks locally, get stream URLs, inspect playback quality |
| **Library** | Manage favorites, add/remove artists, albums, tracks, videos |
| **Discovery** | Find similar artists/tracks, personalized recommendations |
| **History** | View listening history, search history, recent tracks |
| **Saved** | Save-for-later functionality, sharing via public links |

资料来源：[site/app/page.tsx:17-21]()

### Discovery & History Commands

```bash
tidal-cli recommend                              # all mix categories
tidal-cli recommend --type daily                 # daily | discovery | new-release | offline
tidal-cli mix items <mix-id> --type daily        # tracks inside a specific mix
tidal-cli history tracks
tidal-cli history albums
tidal-cli history artists
tidal-cli search history                         # your recent searches
tidal-cli search history-delete <entry-id>
tidal-cli search history-clear
tidal-cli user profile
```

资料来源：[README.md:1-10]()

### Playback Commands

```bash
tidal-cli playback play <id>
tidal-cli playback play <id> --quality LOSSLESS
tidal-cli playback info <id>
tidal-cli playback url <id>
```

**Quality Options:** `LOW`, `HIGH`, `LOSSLESS`, `HI_RES`

资料来源：[README.md:29-32]()

### Save for Later & Sharing

```bash
tidal-cli saved list
tidal-cli saved add --type tracks --id <id>      # tracks | albums | artists | playlists | videos
tidal-cli saved remove --type albums --id <id>
tidal-cli share track <id>                       # creates a public share link
tidal-cli share album <id>
```

资料来源：[README.md:22-26]()

## JSON Output

All commands support structured JSON output by adding `--json` before any subcommand:

```bash
tidal-cli --json search track "Around the World"
tidal-cli --json playlist list
tidal-cli --json artist similar 8992
```

资料来源：[README.md:35-38]()

## MCP Server Integration

### AI Agent Support

tidal-cli is available as a remote MCP server for Claude Desktop and other MCP-compatible AI agents. This enables natural language control of Tidal through AI assistants.

```mermaid
graph LR
    A[User Prompt] --> B[Claude AI]
    B --> C[MCP Server]
    C --> D[tidal-cli]
    D --> E[Tidal API]
```

### Setup for Claude Desktop

1. Add the connector URL: `https://tidal-cli.lucaperret.ch/api/mcp`
2. Connect your Tidal account through OAuth
3. Begin natural language interactions

### Example AI Agent Prompts

| Prompt | Action |
|--------|--------|
| "Create a playlist with the best tracks from Daft Punk's Discovery album" | Searches, creates playlist, adds tracks |
| "Find artists similar to Massive Attack and add their top tracks to my library" | Discovers similar artists, adds to favorites |
| "What are my playlists? Add the new LCD Soundsystem album to the first one" | Lists playlists, searches album, adds tracks |
| "Play me something by Boards of Canada" | Searches, picks a track, plays it |
| "Build a 2000s indie rock playlist with The Strokes, Arctic Monkeys, and Interpol" | Multi-step: create, search, add tracks |

资料来源：[site/app/page.tsx:67-78]()

## Data Storage & Privacy

### Local Storage (CLI Mode)

Authentication tokens are stored locally at:

```
~/.tidal-cli/session.json
```

### Server Storage (MCP Mode)

For MCP server usage, authentication tokens are stored in:

- **Database:** Encrypted Redis database
- **Provider:** Upstash (via Vercel)

### Data Flow

```mermaid
graph TD
    subgraph CLI_Mode["CLI Mode"]
        A1[Local Device] --> A2[~/.tidal-cli/session.json]
        A2 --> A3[Tidal API]
    end
    
    subgraph MCP_Mode["MCP Mode"]
        B1[Claude Desktop] --> B2[tidal-cli.lucaperret.ch]
        B2 --> B3[Upstash Redis]
        B3 --> B4[Tidal API]
    end
```

## Third-Party Services

tidal-cli interacts with the following external services:

| Service | Purpose |
|---------|---------|
| **Tidal API** (openapi.tidal.com) | Music library, playlists, and catalog access |
| **Tidal Auth** (login.tidal.com, auth.tidal.com) | OAuth authentication |

资料来源：[site/app/privacy/page.tsx:75-85]()

## Legal & Licensing

- **License:** MIT License
- **Disclaimer:** tidal-cli is provided "as is" without warranty of any kind
- **Affiliation:** Not affiliated with TIDAL

资料来源：[site/app/terms/page.tsx:85-100]()

## Key Source Files

| File | Purpose |
|------|---------|
| `src/auth.ts` | Authentication handling |
| `site/app/page.tsx` | Landing page with feature documentation |
| `site/app/privacy/page.tsx` | Privacy policy and data handling |
| `site/app/terms/page.tsx` | Terms of service |
| `README.md` | Command reference and quick start |

## Summary

tidal-cli bridges the gap between the Tidal music streaming service and terminal-based workflows or AI agents. With 40 available tools covering search, playlists, playback, discovery, and library management, it provides a comprehensive command-line interface for power users and enables sophisticated automation through MCP integration. The project is fully open source, allowing users to verify its behavior and contribute improvements.

---

<a id='page-architecture'></a>

## System Architecture

### 相关页面

相关主题：[Project Overview](#page-project-overview), [Authentication System](#page-authentication), [MCP Server Integration](#page-mcp-server)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CLAUDE.md](https://github.com/lucaperret/tidal-cli/blob/main/CLAUDE.md)
- [src/index.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/index.ts)
- [src/session.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/session.ts)
- [src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts)
- [site/app/layout.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/layout.tsx)
- [site/package.json](https://github.com/lucaperret/tidal-cli/blob/main/site/package.json)
</details>

# System Architecture

## Overview

tidal-cli is an open-source command-line interface tool that enables programmatic interaction with the Tidal music streaming service. The system architecture encompasses three primary components: a CLI client for terminal-based interactions, an MCP (Model Context Protocol) server for AI agent integration, and a Next.js web application for documentation and marketing.

The architecture is designed to support direct user interactions through the CLI, automated interactions through AI agents, and provides a web presence for onboarding and documentation. All components share core authentication and Tidal API integration logic.

**资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)**

## High-Level Architecture

```mermaid
graph TD
    subgraph "Client Layer"
        CLI[tidal-cli CLI]
        MCP[MCP Server]
        WebApp[Next.js Web App]
    end

    subgraph "Integration Layer"
        AuthService[Authentication Service]
        APIClient[Tidal API Client]
    end

    subgraph "External Services"
        TidalAPI[Tidal API<br/>openapi.tidal.com]
        TidalAuth[Tidal Auth<br/>login.tidal.com<br/>auth.tidal.com]
    end

    subgraph "Data Storage"
        LocalStorage[~/.tidal-cli/session.json]
        Redis[(Redis/Upstash)]
    end

    CLI --> AuthService
    MCP --> AuthService
    AuthService --> TidalAuth
    APIClient --> TidalAPI
    CLI --> APIClient
    MCP --> APIClient
    CLI --> LocalStorage
    MCP --> Redis
    WebApp --> MCP
```

**资料来源：[src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts), [src/session.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/session.ts)**

## Component Architecture

### CLI Client

The CLI client (`src/index.ts`) is the primary interface for end users. It provides a command-based interface with subcommands for various operations.

| Command Category | Description | Example |
|-----------------|-------------|---------|
| `search` | Search artists, albums, tracks, videos, playlists | `tidal-cli search track "Teardrop"` |
| `artist` | Artist information and related content | `tidal-cli artist info 8992` |
| `album` | Album details and metadata | `tidal-cli album info <id>` |
| `track` | Track information and similar tracks | `tidal-cli track info <id>` |
| `playlist` | Playlist management | `tidal-cli playlist list` |
| `playback` | Playback control and stream URLs | `tidal-cli playback play 5756235` |
| `library` | User library management | `tidal-cli library add --track-id <id>` |
| `saved` | Save for later functionality | `tidal-cli saved list` |
| `recommend` | Recommendations and discovery | `tidal-cli recommend` |
| `history` | User listening history | `tidal-cli history tracks` |
| `user` | User profile information | `tidal-cli user profile` |

**资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)**

### MCP Server

The MCP server provides integration with AI agents, particularly Claude Desktop and claude.ai. It exposes the same functionality as the CLI through the Model Context Protocol.

```mermaid
graph LR
    A[Claude Desktop<br/>claude.ai] -->|MCP Protocol| B[tidal-cli MCP Server]
    B -->|API Requests| C[Tidal API]
    B -->|Auth Token| D[Redis/Upstash]
```

The MCP connector URL is available at `https://tidal-cli.lucaperret.ch/api/mcp` for remote server configuration.

**资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)**

### Web Application

The Next.js web application (`site/`) serves multiple purposes:

| Route | Purpose |
|-------|---------|
| `/` | Landing page with features, installation, and AI agent setup |
| `/terms` | Terms of Service documentation |
| `/privacy` | Privacy Policy documentation |
| `/api/mcp` | MCP server endpoint |
| `/og-banner` | Open Graph banner generation |
| `/banner` | Social sharing banner |

**资料来源：[site/app/layout.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/layout.tsx)**

## Authentication System

### Authentication Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant TidalAuth
    participant TidalAPI
    participant LocalStorage

    User->>CLI: tidal-cli auth
    CLI->>TidalAuth: Initiate OAuth
    TidalAuth->>User: Open browser
    User->>TidalAuth: Login credentials
    TidalAuth->>CLI: Authorization code
    CLI->>TidalAuth: Exchange for tokens
    TidalAuth->>CLI: Access token + Refresh token
    CLI->>LocalStorage: Store tokens (~/.tidal-cli/session.json)
    CLI->>TidalAPI: Authenticated requests
```

### Token Storage

The system handles token storage differently based on the deployment mode:

| Deployment Mode | Storage Location | Description |
|----------------|------------------|-------------|
| CLI (local) | `~/.tidal-cli/session.json` | Local file storage on user's device |
| MCP Server | Redis (Upstash) | Server-side encrypted storage |

**资料来源：[src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts), [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)**

### Token Refresh

The authentication system includes automatic token refresh functionality:

- Access tokens have limited validity
- Refresh tokens are used to obtain new access tokens
- The CLI automatically handles token refresh before expiration
- MCP server manages token lifecycle server-side

**资料来源：[src/session.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/session.ts)**

## Data Flow

### CLI Command Execution Flow

```mermaid
graph TD
    A[tidal-cli command] --> B[Parse arguments]
    B --> C[Load session/Authenticate]
    C --> D[Build API request]
    D --> E[Execute request to Tidal API]
    E --> F{JSON flag?}
    F -->|Yes| G[Format JSON output]
    F -->|No| H[Format human-readable output]
    G --> I[Return result]
    H --> I
```

### Search Operation Flow

```mermaid
graph LR
    A[User input] -->|search track| B[CLI]
    B --> C[Tidal API<br/>openapi.tidal.com]
    C --> D[Parse response]
    D --> E[Display results]
```

**资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)**

## External Dependencies

### Tidal API Integration

| Endpoint | Purpose | Reference |
|----------|---------|-----------|
| `openapi.tidal.com` | Music catalog API | Search, metadata, playback |
| `login.tidal.com` | Login interface | OAuth initiation |
| `auth.tidal.com` | Token exchange | OAuth flow |

**资料来源：[site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)**

### NPM Dependencies (CLI Core)

| Package | Version | Purpose |
|---------|---------|---------|
| `tidal-api` | Latest | Tidal API client |
| `commander` | Latest | CLI argument parsing |
| `open` | Latest | Browser opening for auth |

**资料来源：[src/package.json](https://github.com/lucaperret/tidal-cli/blob/main/package.json)**

### Web Application Dependencies

| Package | Purpose |
|---------|---------|
| `next` | React framework |
| `react` | UI components |
| `framer-motion` | Animations |
| `@radix-ui` | UI primitives |

**资料来源：[site/package.json](https://github.com/lucaperret/tidal-cli/blob/main/site/package.json)**

## CLI Command Structure

### Command Hierarchy

```
tidal-cli
├── auth                    # OAuth authentication
├── search                  # Search operations
│   ├── artist
│   ├── album
│   ├── track
│   ├── video
│   ├── playlist
│   ├── suggest
│   ├── editorial
│   └── history
├── artist                  # Artist operations
│   ├── info
│   ├── tracks
│   ├── albums
│   ├── similar
│   └── radio
├── album                   # Album operations
│   ├── info
│   └── barcode
├── track                   # Track operations
│   ├── info
│   ├── similar
│   ├── isrc
│   └── radio
├── playlist                # Playlist operations
│   ├── list
│   ├── create
│   ├── add-track
│   ├── add-album
│   └── remove
├── playback                # Playback operations
│   ├── play
│   ├── info
│   └── url
├── library                 # Library operations
│   ├── add
│   └── favorite-playlists
├── saved                   # Save for later
│   ├── list
│   ├── add
│   └── remove
├── recommend               # Discovery
├── history                 # Listening history
├── user                    # User profile
├── share                   # Sharing
└── --json                  # Global JSON output flag
```

**资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)**

## Quality Options

The system supports multiple audio quality settings for playback:

| Quality | Description |
|---------|-------------|
| `LOW` | Lowest quality streaming |
| `HIGH` | High quality streaming |
| `LOSSLESS` | Lossless audio (FLAC) |
| `HI_RES` | High resolution audio |

**资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)**

## Project Structure

```
tidal-cli/
├── src/
│   ├── index.ts           # CLI entry point
│   ├── auth.ts            # Authentication logic
│   ├── session.ts         # Session management
│   └── ...
├── site/
│   ├── app/
│   │   ├── page.tsx       # Landing page
│   │   ├── layout.tsx     # Root layout
│   │   ├── terms/         # Terms page
│   │   ├── privacy/       # Privacy page
│   │   ├── api/           # API routes (MCP)
│   │   └── components/    # Reusable components
│   └── package.json
├── README.md
├── CLAUDE.md              # Developer documentation
└── package.json
```

**资料来源：[CLAUDE.md](https://github.com/lucaperret/tidal-cli/blob/main/CLAUDE.md)**

## Security Considerations

### Local CLI Usage

- Authentication tokens stored in `~/.tidal-cli/session.json`
- Tokens never transmitted to external servers
- Direct communication with Tidal API

### MCP Server Usage

- Tokens stored in encrypted Redis database (Upstash)
- Server-side token management
- Encrypted communication via HTTPS

**资料来源：[site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)**

## Deployment Architecture

```mermaid
graph TD
    subgraph "Development"
        DevCLI[Local CLI]
        DevMCP[Local MCP Server]
    end

    subgraph "Production"
        ProdMCP[MCP Server<br/>Vercel]
        ProdWeb[Web App<br/>Vercel]
        Upstash[(Redis<br/>Upstash)]
    end

    subgraph "External"
        Tidal[Tidal API]
        Claude[Claude Desktop<br/>claude.ai]
    end

    DevCLI -->|OAuth| Tidal
    DevMCP -->|API| Tidal
    ProdMCP -->|Encrypted| Upstash
    ProdMCP -->|API| Tidal
    ProdWeb -->|MCP| ProdMCP
    Claude -->|MCP| ProdMCP
```

## Summary

The tidal-cli system architecture provides three distinct interfaces to the Tidal music streaming service:

1. **CLI Client**: Direct terminal access with comprehensive command coverage
2. **MCP Server**: AI agent integration for automated workflows
3. **Web Application**: Documentation, marketing, and API endpoint hosting

The architecture prioritizes security through proper token management, offers flexibility through JSON output, and maintains compatibility with modern AI agent workflows through MCP protocol support.

---

<a id='page-getting-started'></a>

## Getting Started

### 相关页面

相关主题：[Project Overview](#page-project-overview), [Authentication System](#page-authentication)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
- [site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)
</details>

# Getting Started

This guide covers everything you need to install, configure, and start using tidal-cli effectively.

## Overview

tidal-cli is an open-source command-line tool that enables interaction with your Tidal music streaming account directly from the terminal. It supports searching the catalog, managing playlists, browsing your library, and controlling playback.

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Prerequisites

Before installing tidal-cli, ensure your environment meets the following requirements:

| Requirement | Minimum Version | Description |
|-------------|-----------------|-------------|
| Node.js | >= 20 | JavaScript runtime required to execute the CLI |
| npm | Latest | Node package manager (bundled with Node.js) |
| Tidal Account | Any tier | Free, HiFi, or HiFi Plus subscription |

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## Installation

### Global npm Installation

The recommended installation method uses npm globally:

```bash
npm install -g @lucaperret/tidal-cli
```

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

### Verify Installation

After installation, verify tidal-cli is properly installed:

```bash
tidal-cli --version
```

## Initial Authentication

After installation, you must authenticate with your Tidal account:

```bash
tidal-cli auth
```

This command opens your default browser for OAuth authorization with Tidal. Once authenticated, your session tokens are stored locally.

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Usage Flow

```mermaid
graph TD
    A[Install via npm] --> B[Run tidal-cli auth]
    B --> C[Browser Opens for OAuth]
    C --> D[Tidal Login]
    D --> E[Authorize Access]
    E --> F[Tokens Stored Locally]
    F --> G[Ready to Use]
    G --> H[Search, Playlists, Playback]
```

## Quick Start Commands

After authentication, you can immediately start using tidal-cli:

### Search

```bash
tidal-cli search track "Around the World"
tidal-cli search artist "Gorillaz"
tidal-cli search album "Mezzanine"
tidal-cli search video "Stylo"
tidal-cli search playlist "Electronic"
```

### Get Information

```bash
tidal-cli artist info <id>
tidal-cli album info <id>
tidal-cli track info <id>
tidal-cli user profile
```

### Playback

```bash
tidal-cli playback play <id>
tidal-cli playback play <id> --quality LOSSLESS
tidal-cli playback info <id>
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Quality Options

When playing tracks, you can specify audio quality:

| Quality | Description |
|---------|-------------|
| `LOW` | Standard quality |
| `HIGH` | High quality |
| `LOSSLESS` | Lossless/CD quality |
| `HI_RES` | Hi-Res audio |

## JSON Output

All commands support JSON output for scripting and automation:

```bash
tidal-cli --json search track "Around the World"
tidal-cli --json playlist list
tidal-cli --json artist similar 8992
```

## Session Storage

When using tidal-cli as a CLI tool, authentication tokens are stored locally:

```
~/.tidal-cli/session.json
```

资料来源：[site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

## Next Steps

Once you're comfortable with the basics, explore these advanced features:

- **Playlists**: Create and manage playlists with `playlist create`, `playlist add-track`
- **Library**: Browse and manage your library with `library tracks`, `library favorite-artists`
- **Discovery**: Get personalized recommendations with `recommend` and explore `history tracks`
- **MCP Integration**: Connect to Claude Desktop or AI agents for automated workflows

## Troubleshooting

### Installation Issues

If npm install fails, try:
```bash
npm install -g @lucaperret/tidal-cli --registry https://registry.npmjs.org/
```

### Authentication Issues

If `tidal-cli auth` doesn't open a browser, ensure your default browser is configured correctly.

### Data Deletion

To remove all locally stored data:
```bash
rm -rf ~/.tidal-cli
```

资料来源：[site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

---

<a id='page-cli-commands'></a>

## CLI Commands - Core Modules

### 相关页面

相关主题：[CLI Commands - Search & Discovery](#page-cli-commands-search), [CLI Commands - Library & Playlist Management](#page-cli-commands-library), [CLI Commands - Playback System](#page-cli-commands-playback)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md) - CLI命令文档和用法说明
- [site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx) - 网站首页，展示CLI功能
</details>

# CLI Commands - Core Modules

## Overview

The tidal-cli project provides a comprehensive command-line interface for interacting with the Tidal music streaming service. The Core Modules encompass the essential functionality for searching, browsing, and managing music content including artists, albums, tracks, playlists, and playback control.

## Architecture Overview

```mermaid
graph TD
    A[User CLI Input] --> B[tidal-cli CLI Engine]
    B --> C[Core Modules]
    C --> D[Search Module]
    C --> E[Artist Module]
    C --> F[Album Module]
    C --> G[Track Module]
    C --> H[Playlist Module]
    C --> I[Playback Module]
    C --> J[Library Module]
    D --> K[Tidal API]
    E --> K
    F --> K
    G --> K
    H --> K
    I --> K
    J --> K
```

## Command Categories

The CLI organizes commands into functional modules as documented in the README:

| Category | Primary Module | Key Capabilities |
|----------|----------------|-------------------|
| Search | `search` | Track, album, artist, video, playlist, suggestions |
| Artists | `artist` | Info, tracks, albums, similar artists, radio |
| Albums | `album` | Info, barcode lookup |
| Tracks | `track` | Info, similar tracks, ISRC lookup, radio |
| Playlists | `playlist` | List, create, add/remove tracks, add albums |
| Playback | `playback` | Play, info, URL retrieval, quality control |
| Library | `library` | Favorites management, history tracking |
| Discovery | `recommend`, `history` | Personalized recommendations, listening history |

## Search Module

The search module provides comprehensive catalog searching capabilities.

### Supported Search Types

```bash
tidal-cli search artist "<query>"           # Artist search
tidal-cli search album "<query>"           # Album search
tidal-cli search track "<query>"           # Track search
tidal-cli search video "<query>"           # Video search
tidal-cli search playlist "<query>"        # Playlist search
tidal-cli search suggest "<query>"         # Autocomplete suggestions
tidal-cli search editorial "<query>"       # Editorial content search
```

### Search History Management

```bash
tidal-cli search history                   # View recent searches
tidal-cli search history-delete <entry-id> # Delete specific entry
tidal-cli search history-clear             # Clear all search history
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Artist Module

Provides artist information and related content discovery.

### Available Commands

| Command | Description |
|---------|-------------|
| `tidal-cli artist info <id>` | Get detailed artist information |
| `tidal-cli artist tracks <id>` | List artist's tracks |
| `tidal-cli artist albums <id>` | List artist's albums |
| `tidal-cli artist similar <id>` | Find similar artists |
| `tidal-cli artist radio <id>` | Generate artist radio stream |

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Album & Track Modules

### Album Commands

```bash
tidal-cli album info <id>        # Get album details
tidal-cli album barcode <ean>    # Lookup album by barcode/EAN
```

### Track Commands

```bash
tidal-cli track info <id>        # Get track information
tidal-cli track similar <id>     # Find similar tracks
tidal-cli track isrc <isrc>      # Lookup track by ISRC
tidal-cli track radio <id>       # Generate track radio stream
```

## Playlist Module

Full playlist management capabilities.

### Core Operations

```bash
tidal-cli playlist list                                    # List all playlists
tidal-cli playlist create --name "<playlist-name>"         # Create new playlist
tidal-cli playlist add-track --playlist-id <id> --track-id <id>  # Add single track
tidal-cli playlist add-album --playlist-id <id>            # Add entire album
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Playback Module

Handles track playback and stream URL retrieval.

### Playback Commands

```bash
tidal-cli playback play <id>                     # Play track
tidal-cli playback play <id> --quality LOSSLESS  # Play with specific quality
tidal-cli playback info <id>                    # Get playback information
tidal-cli playback url <id>                     # Get stream URL
```

### Quality Options

| Quality | Description |
|---------|-------------|
| `LOW` | Standard quality streaming |
| `HIGH` | High quality streaming |
| `LOSSLESS` | Lossless audio (FLAC) |
| `HI_RES` | Hi-Res audio quality |

## Discovery & History Module

### Recommendations

```bash
tidal-cli recommend                              # All mix categories
tidal-cli recommend --type daily                 # Daily mixes
tidal-cli recommend --type discovery              # Discovery mixes
tidal-cli recommend --type new-release           # New releases
tidal-cli recommend --type offline                # Offline mixes
tidal-cli mix items <mix-id> --type daily        # Get tracks from specific mix
```

### Listening History

```bash
tidal-cli history tracks   # View track listening history
tidal-cli history albums    # View album listening history
tidal-cli history artists   # View artist listening history
```

### User Profile

```bash
tidal-cli user profile      # Display user profile information
```

## Library Module

Manages user's personal library and saved content.

### Saved Items

```bash
tidal-cli saved list                              # List saved items
tidal-cli saved add --type <type> --id <id>       # Add item to library
tidal-cli saved remove --type <type> --id <id>    # Remove from library
```

### Supported Item Types

| Type | Description |
|------|-------------|
| `tracks` | Saved tracks |
| `albums` | Saved albums |
| `artists` | Favorite artists |
| `playlists` | Saved playlists |
| `videos` | Saved videos |

### Favorites & Sharing

```bash
tidal-cli library add --track-id <id>            # Add track to library
tidal-cli library favorite-playlists             # List favorite playlists
tidal-cli share track <id>                        # Create public share link
tidal-cli share album <id>                        # Share album link
```

## JSON Output

All commands support JSON output for programmatic use:

```bash
tidal-cli --json search track "Around the World"
tidal-cli --json playlist list
tidal-cli --json artist similar 8992
```

This enables integration with scripts and LLM agents for automation workflows.

## CLI Options

### Global Flags

| Flag | Description |
|------|-------------|
| `--json` | Output results as JSON |
| `--help` | Display command help |
| `--version` | Show CLI version |

## Integration with MCP Server

The CLI supports MCP (Model Context Protocol) integration for AI agent use:

```
https://tidal-cli.lucaperret.ch/api/mcp
```

This enables Claude Desktop and other AI assistants to control Tidal programmatically.

## Quick Start Commands

Based on the website documentation, the essential commands to get started are:

```bash
npm install -g @lucaperret/tidal-cli    # Installation
tidal-cli auth                           # OAuth authentication
tidal-cli search track "Teardrop"        # First search
tidal-cli artist info 8992               # Artist lookup (Daft Punk example)
tidal-cli playback play 5756235         # Playback
```

## Requirements

- Node.js >= 20
- Valid Tidal account (Free, HiFi, or HiFi Plus)

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

---

<a id='page-cli-commands-search'></a>

## CLI Commands - Search & Discovery

### 相关页面

相关主题：[CLI Commands - Core Modules](#page-cli-commands), [CLI Commands - Library & Playlist Management](#page-cli-commands-library)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [src/search.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/search.ts)
- [src/recommend.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/recommend.ts)
- [src/mix.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/mix.ts)
- [src/search-history.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/search-history.ts)
- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
</details>

# CLI Commands - Search & Discovery

The Search & Discovery module in tidal-cli provides comprehensive commands for exploring the Tidal music catalog, finding similar content, accessing personalized recommendations, and managing search history. This module forms the core navigation layer for users discovering music through the command-line interface.

## Overview

The Search & Discovery functionality encompasses four primary areas:

| Category | Purpose | Entry Point |
|----------|---------|-------------|
| **Catalog Search** | Query Tidal's music database by type | `tidal-cli search` |
| **Discovery** | Access personalized mixes and recommendations | `tidal-cli recommend` |
| **Listening History** | View recently played content | `tidal-cli history` |
| **Search History** | Manage personal search activity | `tidal-cli search history` |

These commands support JSON output via the `--json` flag for programmatic consumption, making tidal-cli suitable for LLM agent integration through the MCP server.

## Catalog Search

The `search` command provides type-specific queries against the Tidal API, enabling precise discovery of artists, albums, tracks, videos, playlists, editorial content, and search suggestions.

### Supported Search Types

```bash
tidal-cli search artist <query>
tidal-cli search album <query>
tidal-cli search track <query>
tidal-cli search video <query>
tidal-cli search playlist <query>
tidal-cli search suggest <query>
tidal-cli search editorial <query>
```

### Search Type Reference

| Type | Description | Use Case |
|------|-------------|----------|
| `artist` | Find artists by name | "Who is the best artist for this sound?" |
| `album` | Locate albums by title | "Find all albums by this artist" |
| `track` | Search individual songs | "Play me something similar" |
| `video` | Find music videos | "Watch the official video" |
| `playlist` | Discover user playlists | "Find playlists for parties" |
| `suggest` | Get search suggestions | Autocomplete functionality |
| `editorial` | Browse curated editorial lists | "What's trending in indie rock?" |

### JSON Output

All search commands support structured JSON output:

```bash
tidal-cli --json search track "Around the World"
tidal-cli --json artist similar 8992
```

This enables piping results to other tools or processing in automation scripts.

## Discovery & Recommendations

The discovery system provides personalized content based on user listening patterns and algorithmic recommendations.

### Mix Types

The `recommend` command accesses personalized mixes in various categories:

```bash
tidal-cli recommend                              # all mix categories
tidal-cli recommend --type daily                 # daily mix
tidal-cli recommend --type discovery             # discovery mix
tidal-cli recommend --type new-release           # new releases
tidal-cli recommend --type offline               # offline-ready tracks
```

### Mix Reference Table

| Type | Description | Refresh Frequency |
|------|-------------|-------------------|
| `daily` | Your daily personalized mix | Daily |
| `discovery` | Tracks you've never listened to but might like | Weekly |
| `new-release` | Recent releases matching your taste | Daily |
| `offline` | Tracks optimized for offline playback | Dynamic |

### Exploring Mix Content

Each mix contains tracks that can be explored individually:

```bash
tidal-cli mix items <mix-id> --type daily
```

This command retrieves all tracks within a specific mix, allowing users to add individual tracks to playlists or play them directly.

## Listening History

tidal-cli tracks your listening activity across different content types, enabling you to revisit recently played music.

### History Commands

```bash
tidal-cli history tracks
tidal-cli history albums
tidal-cli history artists
```

### History Flow Diagram

```mermaid
graph TD
    A[User plays content] --> B[Tidal API records play]
    B --> C[tidal-cli history command]
    C --> D{Content Type?}
    D -->|Tracks| E[Display recent tracks]
    D -->|Albums| F[Display recent albums]
    D -->|Artists| G[Display recent artists]
    E --> H[User can re-play or explore]
    F --> H
    G --> H
```

## Search History Management

tidal-cli maintains a local search history that allows you to quickly access previous queries and clear them when needed.

### Search History Commands

```bash
tidal-cli search history                         # display search history
tidal-cli search history-delete <entry-id>      # remove specific entry
tidal-cli search history-clear                   # clear all history
```

### Search History Data Model

| Field | Type | Description |
|-------|------|-------------|
| `entry-id` | string | Unique identifier for the search entry |
| `query` | string | The search term used |
| `timestamp` | datetime | When the search was performed |
| `result-count` | number | Number of results returned |

## User Profile Integration

The `user profile` command provides context about your Tidal account, which influences search results and recommendations:

```bash
tidal-cli user profile
```

This command returns account information including subscription tier, preferred audio quality, and personalization settings that affect recommendation quality.

## MCP Server Integration

The Search & Discovery functionality is exposed through the MCP (Model Context Protocol) server, enabling AI agents like Claude to perform music discovery tasks autonomously.

### Available MCP Tools

The MCP server exposes the following discovery-related tools:

- `search_artist` - Search for artists
- `search_track` - Search for tracks
- `search_album` - Search for albums
- `get_recommendations` - Fetch personalized recommendations
- `get_listening_history` - Retrieve play history
- `get_similar_artists` - Find similar artists

### Integration Example

```
User: "Find artists similar to Massive Attack and add their top tracks to my library"
Agent: Uses search_artist → similar_artist lookup → track lookup → library_add
```

## Architecture Overview

```mermaid
graph TD
    subgraph "CLI Layer"
        A[User Command] --> B[Command Parser]
    end
    
    subgraph "Service Layer"
        B --> C[Search Service]
        B --> D[Recommend Service]
        B --> E[History Service]
    end
    
    subgraph "API Layer"
        C --> F[Tidal Search API]
        D --> G[Tidal Personalization API]
        E --> H[Tidal User History API]
    end
    
    subgraph "Output Layer"
        F --> I[Formatted Output]
        G --> I
        H --> I
        I --> J[JSON/Terminal]
    end
```

## Best Practices

### Efficient Searching

1. **Use specific types**: Prefer `search track` over broad searches when you know what you're looking for
2. **Leverage JSON output**: Use `--json` for scripting and automation
3. **Build on history**: Review your listening history to discover patterns

### Recommendation Optimization

1. **Regular usage improves recommendations**: The system learns from your play history
2. **Explore different mix types**: Each mix type surfaces different content
3. **Use discovery mix**: The `discovery` type shows new content you haven't heard

### Search History Management

1. **Clear periodically**: Use `search history-clear` to reset if results become biased
2. **Delete specific entries**: Remove individual entries with `search history-delete <entry-id>`

## Error Handling

Common issues and resolutions:

| Issue | Cause | Solution |
|-------|-------|----------|
| No search results | Query too specific or misspelled | Try broader terms or check spelling |
| Empty history | No plays recorded yet | Start playing content through tidal-cli |
| Stale recommendations | New account or low activity | Use the service more to improve personalization |
| Rate limiting | Too many rapid requests | Add delays between commands |

## Related Commands

- [Playback Commands](playback.md) - Play discovered content
- [Library Commands](library.md) - Save and manage favorites
- [Playlist Commands](playlists.md) - Organize discovered music

## References

- Search implementation: `src/search.ts`
- Recommendations: `src/recommend.ts`
- Mix functionality: `src/mix.ts`
- Search history: `src/search-history.ts`
- Usage examples: `README.md`

---

<a id='page-cli-commands-library'></a>

## CLI Commands - Library & Playlist Management

### 相关页面

相关主题：[CLI Commands - Core Modules](#page-cli-commands), [CLI Commands - Playback System](#page-cli-commands-playback)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation page. Note: The core implementation files (`src/playlist.ts`, `src/library.ts`, `src/saved.ts`, `src/history.ts`, `src/share.ts`) were not available in the provided repository context. This page is generated based on README.md and the site landing page content.

- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md) — Primary CLI command documentation
- [site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx) — Feature overview and command examples
</details>

# CLI Commands - Library & Playlist Management

## Overview

The Library & Playlist Management commands in tidal-cli provide comprehensive tools for organizing your Tidal music library, managing playlists, tracking listening history, and sharing content. These commands enable users to interact programmatically with their personal Tidal account through a command-line interface designed for both manual use and LLM agent automation.

tidal-cli offers JSON output on every command, making it suitable for scripting and integration with other tools. The library management features allow adding or removing artists, albums, tracks, and videos from your favorites, while playlist commands support full CRUD operations including adding tracks and entire albums.

## Architecture Overview

```mermaid
graph TD
    A[User / LLM Agent] --> B[tidal-cli CLI]
    B --> C{Library & Playlist Commands}
    
    C --> D[library]
    C --> E[playlist]
    C --> F[saved]
    C --> G[history]
    C --> H[share]
    
    D --> I[Tidal API]
    E --> I
    F --> I
    G --> I
    H --> I
    
    I --> J[User Library Data]
    I --> K[Playlist Data]
    I --> L[Share Links]
```

## Library Commands

The `library` command group manages your personal Tidal library, including favorites for artists, albums, tracks, and videos.

### Available Commands

| Command | Description |
|---------|-------------|
| `library add --track-id <id>` | Add a track to your library |
| `library add --album-id <id>` | Add an album to your library |
| `library add --artist-id <id>` | Add an artist to your library |
| `library favorite-playlists` | List your favorite playlists |
| `library remove --type <type> --id <id>` | Remove an item from your library |

### Usage Examples

```bash
# Add a track to your library
tidal-cli library add --track-id 5756235

# Add an album to your library
tidal-cli library add --album-id 12345678

# Add an artist to your library
tidal-cli library add --artist-id 8992

# Remove a track from your library
tidal-cli library remove --type tracks --id 5756235

# List your favorite playlists
tidal-cli library favorite-playlists
```

### JSON Output

All library commands support JSON output for programmatic use:

```bash
tidal-cli --json library add --track-id 5756235
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Playlist Commands

The `playlist` command group provides complete playlist management capabilities including creation, modification, and deletion.

### Available Commands

| Command | Description |
|---------|-------------|
| `playlist list` | List all your playlists |
| `playlist create --name <name>` | Create a new playlist |
| `playlist add-track --playlist-id <id> --track-id <id>` | Add a track to a playlist |
| `playlist add-album --playlist-id <id>` | Add all tracks from an album |
| `playlist rename --playlist-id <id> --name <name>` | Rename a playlist |
| `playlist delete --playlist-id <id>` | Delete a playlist |
| `playlist remove-track --playlist-id <id> --track-id <id>` | Remove a track |

### Usage Examples

```bash
# List all playlists
tidal-cli playlist list

# Create a new playlist
tidal-cli playlist create --name "Late Night Electronic"

# Add a track to a playlist
tidal-cli playlist add-track --playlist-id <playlist-id> --track-id <track-id>

# Add an entire album to a playlist
tidal-cli playlist add-album --playlist-id <playlist-id>
```

### Playlist Workflow

```mermaid
graph LR
    A[Create Playlist] --> B[Get Playlist ID]
    B --> C[Add Tracks]
    C --> D[Add Albums]
    D --> E[Organize & Share]
    
    F[List Playlists] -.-> B
    G[Search Content] -.-> C
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## Save for Later Commands

The `saved` command group manages your "Save for Later" queue, allowing you to bookmark content for future listening.

### Available Commands

| Command | Description |
|---------|-------------|
| `saved list` | List all saved items |
| `saved add --type <type> --id <id>` | Add an item to saved |
| `saved remove --type <type> --id <id>` | Remove an item from saved |

### Supported Types

| Type | Description |
|------|-------------|
| `tracks` | Individual tracks |
| `albums` | Full albums |
| `artists` | Artist profiles |
| `playlists` | Other users' playlists |
| `videos` | Music videos |

### Usage Examples

```bash
# List all saved items
tidal-cli saved list

# Save a track for later
tidal-cli saved add --type tracks --id 5756235

# Save an album for later
tidal-cli saved add --type albums --id 12345678

# Remove a saved item
tidal-cli saved remove --type albums --id 12345678
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## History Commands

The `history` command group provides access to your listening history and search history.

### Listening History

| Command | Description |
|---------|-------------|
| `history tracks` | View your recently played tracks |
| `history albums` | View your recently played albums |
| `history artists` | View your recently played artists |

### Search History

| Command | Description |
|---------|-------------|
| `search history` | View your recent searches |
| `search history-delete <entry-id>` | Delete a specific search entry |
| `search history-clear` | Clear all search history |

### Usage Examples

```bash
# View your recent track history
tidal-cli history tracks

# View your recent album history
tidal-cli history albums

# View your recent artist history
tidal-cli history artists

# View search history
tidal-cli search history

# Delete a specific search entry
tidal-cli search history-delete <entry-id>

# Clear all search history
tidal-cli search history-clear
```

### User Profile

```bash
tidal-cli user profile
```

This command displays your user profile information including subscription status and account details.

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Share Commands

The `share` command group creates public share links for Tidal content.

### Available Commands

| Command | Description |
|---------|-------------|
| `share track <id>` | Create a public share link for a track |
| `share album <id>` | Create a public share link for an album |

### Usage Examples

```bash
# Share a track
tidal-cli share track 5756235

# Share an album
tidal-cli share album 12345678
```

These commands generate public URLs that can be shared with others, allowing them to access the same content on Tidal.

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Discovery & Recommendations

While not strictly library management, these commands help expand and organize your library through discovery.

### Recommendation Commands

| Command | Description |
|---------|-------------|
| `recommend` | Get all mix categories |
| `recommend --type daily` | Get daily mixes |
| `recommend --type discovery` | Get discovery mixes |
| `recommend --type new-release` | Get new release mixes |
| `recommend --type offline` | Get offline mixes |
| `mix items <mix-id> --type <type>` | Get tracks from a specific mix |

### Similar Artists & Tracks

| Command | Description |
|---------|-------------|
| `artist similar <id>` | Find similar artists |
| `track similar <id>` | Find similar tracks |
| `artist radio <id>` | Get artist radio |
| `track radio <id>` | Get track radio |

### Usage Examples

```bash
# Get all recommendation categories
tidal-cli recommend

# Get daily mixes
tidal-cli recommend --type daily

# Get tracks from a specific mix
tidal-cli mix items <mix-id> --type daily

# Find similar artists
tidal-cli artist similar 8992

# Get artist radio station
tidal-cli artist radio 8992
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## Command Reference Summary

### Library Management

| Command | Type | Key Options |
|---------|------|-------------|
| `library add` | Add | `--track-id`, `--album-id`, `--artist-id` |
| `library remove` | Remove | `--type`, `--id` |
| `library favorite-playlists` | Query | - |

### Playlist Management

| Command | Type | Key Options |
|---------|------|-------------|
| `playlist list` | Query | - |
| `playlist create` | Create | `--name` |
| `playlist add-track` | Modify | `--playlist-id`, `--track-id` |
| `playlist add-album` | Modify | `--playlist-id` |
| `playlist rename` | Modify | `--playlist-id`, `--name` |
| `playlist delete` | Delete | `--playlist-id` |

### Saved & History

| Command | Category | Key Options |
|---------|----------|-------------|
| `saved list` | Saved | - |
| `saved add` | Saved | `--type`, `--id` |
| `history tracks` | History | - |
| `search history` | History | - |

## Authentication Requirement

All Library & Playlist Management commands require authentication with your Tidal account. Run the following once to authenticate:

```bash
tidal-cli auth
```

This opens your browser for Tidal authorization. After initial authentication, all commands run non-interactively with auto-refreshing tokens.

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## Requirements

- Node.js >= 20
- A valid Tidal account (Free, HiFi, or HiFi Plus subscription)

## See Also

- [Search Commands](search-commands.md) - Finding content to add to your library
- [Playback Commands](playback-commands.md) - Playing tracks from your library
- [Artist & Album Commands](artist-album-commands.md) - Exploring the catalog

---

<a id='page-cli-commands-playback'></a>

## CLI Commands - Playback System

### 相关页面

相关主题：[CLI Commands - Core Modules](#page-cli-commands), [Authentication System](#page-authentication)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/playback.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/playback.ts)
- [src/user.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/user.ts)
- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
- [site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)
</details>

# CLI Commands - Playback System

The Playback System is a core module in tidal-cli that enables programmatic control of Tidal audio playback from the command line. It provides commands to play tracks locally, retrieve stream URLs, and inspect playback quality information. This system is designed for both direct CLI usage and LLM agent automation workflows.

## Architecture Overview

The Playback System integrates with Tidal's streaming infrastructure through the Tidal API, handling audio quality selection, stream URL generation, and local playback execution.

```mermaid
graph TD
    A["User Command<br>tidal-cli playback play <id>"] --> B["playback.ts<br>Command Handler"]
    B --> C["Tidal API<br>Audio Stream Endpoint"]
    C --> D["Stream URL<br>with Quality Parameters"]
    D --> E["Local Audio Player<br>System Default"]
    
    F["tidal-cli playback url <id>"] --> B
    G["tidal-cli playback info <id>"] --> B
    H["tidal-cli playback play <id> --quality LOSSLESS"] --> B
```

## Playback Commands

### playback play

Plays a track locally using the system's default audio player.

```bash
tidal-cli playback play <id>
tidal-cli playback play <id> --quality LOSSLESS
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `<id>` | string | Yes | Tidal track ID to play |
| `--quality` | string | No | Audio quality level |

**Supported Quality Levels:**

| Quality | Description |
|---------|-------------|
| `LOW` | Low quality audio stream |
| `HIGH` | High quality audio stream |
| `LOSSLESS` | Lossless CD-quality audio (FLAC) |
| `HI_RES` | High resolution audio |

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

### playback url

Retrieves the direct stream URL for a track without playing it. This is useful for integration with external audio players or custom playback solutions.

```bash
tidal-cli playback url <id>
```

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

### playback info

Returns detailed playback metadata for a track, including available quality options, codec information, and stream characteristics.

```bash
tidal-cli playback info <id>
```

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## JSON Output

All playback commands support structured JSON output for programmatic consumption:

```bash
tidal-cli playback play 5756235 --json
tidal-cli playback url 5756235 --json
tidal-cli playback info 5756235 --json
```

资料来源：[README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

## Integration with MCP Server

The playback system is exposed through the MCP (Model Context Protocol) connector, enabling AI agents like Claude to control Tidal playback:

```bash
https://tidal-cli.lucaperret.ch/api/mcp
```

This allows prompts such as:

> "Play me something by Boards of Canada"

The AI agent interprets the request, searches for appropriate tracks, and executes the playback command programmatically.

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## Command Structure

The playback commands follow the standard tidal-cli architecture:

```mermaid
graph LR
    A["tidal-cli"] --> B["playback"]
    B --> C["play"]
    B --> D["url"]
    B --> E["info"]
    C --> F["Track ID"]
    C --> G["--quality flag"]
```

## Typical Workflow Example

```bash
# 1. Search for a track
tidal-cli search track "Teardrop"

# 2. Get track details
tidal-cli track info 5756235

# 3. Play with default quality
tidal-cli playback play 5756235

# 4. Play with lossless quality
tidal-cli playback play 5756235 --quality LOSSLESS

# 5. Get stream URL for external player
tidal-cli playback url 5756235 --json
```

## Quality Selection

The quality parameter allows explicit control over audio streaming quality:

```bash
# Play in highest available quality
tidal-cli playback play 5756235 --quality HI_RES

# Play lossless quality
tidal-cli playback play 5756235 --quality LOSSLESS
```

If no quality is specified, tidal-cli uses a sensible default based on your Tidal subscription level.

## Error Handling

When a track ID is invalid or the track is unavailable, the CLI returns a structured error message:

```json
{
  "error": "track_not_found",
  "message": "Track with ID 5756235 not found"
}
```

## Source Files

| File | Purpose |
|------|---------|
| `src/playback.ts` | Main playback command implementation |
| `src/user.ts` | User preferences and quality settings |

## Related Commands

| Command | Description |
|---------|-------------|
| `tidal-cli search track` | Find tracks by name |
| `tidal-cli track info` | Get detailed track metadata |
| `tidal-cli track radio` | Generate a radio stream based on a track |

---

<a id='page-authentication'></a>

## Authentication System

### 相关页面

相关主题：[System Architecture](#page-architecture), [MCP Server Integration](#page-mcp-server), [Data Flow & Session Management](#page-data-flow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts)
- [src/session.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/session.ts) *(referenced in docs)*
- [site/app/mcp-lib/constants.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/constants.ts) *(referenced in docs)*
- [site/app/mcp-lib/tidal-oauth.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/tidal-oauth.ts) *(referenced in docs)*
- [site/app/mcp-lib/tools.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/tools.ts)
- [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)
- [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)
</details>

# Authentication System

## Overview

The tidal-cli project implements a dual-mode authentication system that supports both command-line interface (CLI) usage and Model Context Protocol (MCP) server integration with Claude Desktop. The authentication architecture is designed to securely handle OAuth tokens while maintaining flexibility for different deployment scenarios.

The system leverages Tidal's OAuth 2.0 flow for secure authentication, ensuring that user credentials are never stored or transmitted through tidal-cli's infrastructure. Instead, authentication tokens are exchanged between the user's browser and Tidal's auth servers, with only the resulting tokens being stored locally or server-side depending on the usage mode.

## Architecture Overview

```mermaid
graph TD
    subgraph "CLI Mode"
        A1[User] -->|tidal-cli auth| B1[Local OAuth Flow]
        B1 --> C1[Tidal Login Page]
        C1 --> D1[Callback Server :25654]
        D1 --> E1[~/.tidal-cli/session.json]
    end
    
    subgraph "MCP Server Mode"
        A2[User] -->|Connect via MCP| B2[Remote OAuth Flow]
        B2 --> C2[Tidal Login Page]
        C2 --> D2[tidal-cli.lucaperret.ch /api/mcp]
        D2 --> E2[Upstash Redis Encrypted]
    end
    
    subgraph "API Access"
        E1 --> F1[Tidal API Client]
        E2 --> F2[Tidal API Client]
    end
```

## Authentication Modes

### CLI Mode

In CLI mode, tidal-cli performs a complete OAuth 2.0 authorization code flow with PKCE (Proof Key for Code Exchange) support. The process involves:

1. Starting a local HTTP server on port 25654 to receive the OAuth callback
2. Opening the user's default browser to Tidal's authorization page
3. Waiting for the user to authenticate with their Tidal credentials
4. Exchanging the authorization code for access and refresh tokens
5. Persisting tokens to the local session file

**Token Storage Location**: `~/.tidal-cli/session.json`

**Source**: [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md) | [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

### MCP Server Mode

When used as a remote MCP connector for Claude Desktop or claude.ai, the authentication flow differs in that tokens are stored server-side rather than locally. This enables seamless authentication across multiple devices without requiring local token management.

**Token Storage Location**: Upstash Redis (encrypted, 30-day TTL)

**Source**: [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

## Authentication Flow (CLI)

```mermaid
sequenceDiagram
    participant User
    participant CLI as tidal-cli CLI
    participant Browser as User's Browser
    participant Tidal as Tidal Auth Server
    participant Callback as Local Server :25654
    
    User->>CLI: tidal-cli auth
    CLI->>CLI: Generate PKCE verifier/challenge
    CLI->>Callback: Start local server
    CLI->>Browser: Open Tidal authorization URL
    User->>Browser: Enter Tidal credentials
    Browser->>Tidal: Authorization request with PKCE
    Tidal->>Browser: Authorization code
    Browser->>Callback: Redirect with code
    Callback->>CLI: Receive authorization code
    CLI->>Tidal: Exchange code for tokens
    Tidal->>CLI: Access token + Refresh token
    CLI->>CLI: Store tokens in session.json
    CLI->>User: "Authenticated successfully!"
```

## Core Authentication Module

### src/auth.ts

The primary authentication module provides several key functions for managing the authentication lifecycle:

#### Functions

| Function | Purpose | Return Type |
|----------|--------|-------------|
| `authenticate()` | Initiates the OAuth flow with browser-based login | `Promise<void>` |
| `getApiClient()` | Returns an authenticated API client instance | `Promise<APIClient>` |
| `getCountryCode()` | Retrieves and caches the user's country code | `Promise<string>` |

#### getApiClient Implementation

```typescript
export async function getApiClient(): Promise<any> {
  await ensureInit();

  // Verify we have valid credentials
  const creds = await credentialsProvider.getCredentials();
  if (!creds.token) {
    console.error('Error: Not authenticated. Run `tidal-cli auth` first.');
    process.exit(1);
  }

  return createAPIClient(credentialsProvider);
}
```

The `getApiClient()` function serves as the central entry point for all authenticated API operations. It first ensures the authentication subsystem is initialized, then verifies that valid credentials exist before constructing and returning an API client instance.

**Source**: [src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts)

#### getCountryCode Caching

```typescript
let cachedCountryCode: string | null = null;

export async function getCountryCode(): Promise<string> {
  if (cachedCountryCode) return cachedCountryCode;

  try {
    const client = await getApiClient();
    const { data } = await client.GET('/users/{id}' as any, {
      // ... implementation
    });
    // ...
  }
}
```

The country code is retrieved from the user's profile and cached in memory to avoid repeated API calls for the same information.

**Source**: [src/auth.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/auth.ts)

## MCP Authentication Tools

### User Profile Tool

The MCP server exposes authentication-related tools for Claude integration:

```typescript
server.tool('tidal_user_profile', 'Get your Tidal user profile', {},
{ readOnlyHint: true, destructiveHint: false, openWorldHint: false, title: 'User Profile' },
async (_args, extra) => {
  const { client } = await getClientAndCountry(extractToken(extra));
  return text(await getUserProfileData(client));
});
```

**Source**: [site/app/mcp-lib/tools.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/tools.ts)

### Token Extraction

The MCP server extracts authentication tokens from incoming requests to establish authenticated sessions for Claude Desktop users. This allows the MCP server to associate API calls with the correct authenticated user.

## Data Storage Comparison

| Aspect | CLI Mode | MCP Server Mode |
|--------|----------|-----------------|
| **Storage Location** | `~/.tidal-cli/session.json` | Upstash Redis (server-side) |
| **Encryption** | File system permissions | Encrypted at rest |
| **Token TTL** | Until revoked | 30-day TTL |
| **Access** | Local only | Remote via MCP |
| **User ID Retrieval** | `creds.userId` from session | Via `tidal_user_profile` tool |

**Source**: [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

## Security Considerations

### Credential Handling

The authentication system implements several security measures:

1. **PKCE Support**: The OAuth flow uses Proof Key for Code Exchange to prevent authorization code interception attacks
2. **Local-Only Storage (CLI)**: Authentication tokens never leave the user's device in CLI mode
3. **Encrypted Storage (MCP)**: Server-side tokens are encrypted in Upstash Redis
4. **No Password Storage**: Username and password are never seen or stored by tidal-cli—authentication occurs directly with Tidal

**Source**: [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

### Data Deletion

Users can remove all locally stored authentication data by deleting the session directory:

```bash
rm -rf ~/.tidal-cli
```

For MCP mode, tokens expire automatically after 30 days and can be revoked from the user's Tidal account settings.

**Source**: [site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

## Usage Examples

### CLI Authentication

```bash
# Initiate authentication
tidal-cli auth
# Output: Opening browser for Tidal authorization...
# Output: Authenticated successfully! User ID: 123456789

# Verify authentication by querying profile
tidal-cli user profile
```

**Source**: [README.md](https://github.com/lucaperret/tidal-cli/blob/main/README.md)

### MCP Server Setup

```bash
# MCP connector URL for Claude Desktop
https://tidal-cli.lucaperret.ch/api/mcp
```

Users configure this URL in Claude Desktop's Settings → Connectors → Add custom connector.

**Source**: [site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

## Dependencies and Configuration

### Required Environment

- **Node.js**: >= 20
- **Tidal Account**: Free, HiFi, or HiFi Plus subscription

### Configuration Files

| File | Purpose | Location |
|------|---------|----------|
| `session.json` | OAuth tokens and user session | `~/.tidal-cli/` |
| `credentials` | Token provider configuration | Internal to auth module |

## Related Documentation

- [Privacy Policy](/privacy) - Detailed data handling practices
- [Terms of Service](/terms) - Usage terms and acceptable use
- [GitHub Repository](https://github.com/lucaperret/tidal-cli) - Source code and issue tracking

---

<a id='page-data-flow'></a>

## Data Flow & Session Management

### 相关页面

相关主题：[Authentication System](#page-authentication), [System Architecture](#page-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/session.ts](https://github.com/lucaperret/tidal-cli/blob/main/src/session.ts)
- [site/lib/cli/session.js](https://github.com/lucaperret/tidal-cli/blob/main/site/lib/cli/session.js)
- [site/app/mcp-lib/redis.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/redis.ts)
- [site/app/api/token/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/token/route.ts)
</details>

# Data Flow & Session Management

tidal-cli operates in two distinct modes—**CLI mode** for direct command-line interaction and **MCP mode** for integration with AI agents like Claude Desktop. Each mode implements a different session management strategy tailored to its use case.

## Architecture Overview

The system handles authentication differently depending on how users interact with tidal-cli:

| Mode | Token Storage | Location | Data Flow |
|------|--------------|----------|-----------|
| CLI | Local filesystem | `~/.tidal-cli/session.json` | Device → Tidal API (direct) |
| MCP | Encrypted Redis | Upstash (via Vercel) | Device → Vercel → Tidal API |

资料来源：[site/app/privacy/page.tsx]()

```mermaid
graph TD
    subgraph CLI_Mode["CLI Mode"]
        A1[User Device] -->|OAuth| TIDAL_AUTH[Tidal Auth<br/>login.tidal.com]
        A1 -->|API Calls| TIDAL_API[Tidal API<br/>openapi.tidal.com]
        A1 -->|session.json| LOCAL[~/.tidal-cli/]
    end
    
    subgraph MCP_Mode["MCP Mode"]
        A2[Claude Desktop<br/>claude.ai] -->|MCP Protocol| MCP_ENDPOINT[https://tidal-cli.lucaperret.ch/api/mcp]
        MCP_ENDPOINT -->|Encrypted| REDIS[Upstash Redis<br/>Vercel]
        MCP_ENDPOINT -->|API Calls| TIDAL_API2[Tidal API<br/>openapi.tidal.com]
        A2 -->|OAuth| TIDAL_AUTH2[Tidal Auth<br/>login.tidal.com]
    end
```

## CLI Mode Session Management

When using tidal-cli as a command-line tool, authentication tokens are stored locally on the user's device.

### Storage Location

```
~/.tidal-cli/session.json
```

资料来源：[site/app/privacy/page.tsx]()

### Session Data Flow

```mermaid
sequenceDiagram
    participant User as User Device
    participant CLI as tidal-cli CLI
    participant TIDAL as Tidal Auth API
    participant LOCAL as Local Storage<br/>~/.tidal-cli/

    User->>CLI: tidal-cli auth
    CLI->>TIDAL: Initiate OAuth flow
    TIDAL->>User: Open browser for login
    User->>TIDAL: Authenticate
    TIDAL-->>CLI: Authorization code
    CLI->>TIDAL: Exchange for tokens
    TIDAL-->>CLI: Access + Refresh tokens
    CLI->>LOCAL: Store in session.json
    Note over CLI,LOCAL: Tokens stored locally
```

### Data Privacy in CLI Mode

- **Direct communication**: All API calls go directly from the user's device to Tidal's servers
- **No intermediary**: No data passes through any third-party server
- **Local-only storage**: Authentication tokens remain on the local filesystem
- **User control**: Users have full control over their session data

资料来源：[site/app/privacy/page.tsx]()

## MCP Mode Session Management

When using tidal-cli as an MCP (Model Context Protocol) connector for AI agents, session management differs significantly due to the distributed nature of AI agent interactions.

### MCP Endpoint Architecture

```
https://tidal-cli.lucaperret.ch/api/mcp
```

资料来源：[site/app/page.tsx]()

### Session Data Flow

```mermaid
sequenceDiagram
    participant User as User/Claude Desktop
    participant Claude as Claude AI Agent
    participant Vercel as Vercel Edge<br/>MCP Server
    participant Redis as Upstash Redis<br/>Encrypted Storage
    participant TIDAL as Tidal API

    User->>Claude: Request music action
    Claude->>Vercel: MCP tool call
    Vercel->>Redis: Fetch/Store session
    Redis-->>Vercel: Encrypted tokens
    Vercel->>TIDAL: API request with token
    TIDAL-->>Vercel: Music data
    Vercel-->>Claude: MCP response
    Claude-->>User: Natural language response
```

### Server-Side Token Storage

| Aspect | Description |
|--------|-------------|
| Storage Provider | Upstash (Redis) |
| Hosting Platform | Vercel |
| Encryption | Encrypted at rest |
| Token Type | OAuth access + refresh tokens |

资料来源：[site/app/privacy/page.tsx]()

### MCP Configuration Steps

| Step | Action | Description |
|------|--------|-------------|
| 1 | Open Claude Desktop Settings | Settings → Connectors → Add custom connector |
| 2 | Add connector URL | `https://tidal-cli.lucaperret.ch/api/mcp` |
| 3 | Authenticate | Complete OAuth flow in browser |
| 4 | Token storage | Tokens stored in encrypted Redis |

资料来源：[site/app/page.tsx]()

## Token Lifecycle

### Token Refresh Mechanism

Both CLI and MCP modes implement automatic token refresh to maintain continuous access:

- **CLI Mode**: Token refresh handled locally by the CLI application
- **MCP Mode**: Token refresh managed server-side by the Vercel edge functions

### Available Quality Options for Playback

| Quality | Description |
|---------|-------------|
| `LOW` | Standard quality stream |
| `HIGH` | High quality stream |
| `LOSSLESS` | Lossless audio quality |
| `HI_RES` | High resolution audio |

资料来源：[README.md]()

## Data Deletion

### CLI Mode Deletion

To remove all locally stored data:

```bash
rm -rf ~/.tidal-cli
```

资料来源：[site/app/privacy/page.tsx]()

This command removes:
- `session.json` containing OAuth tokens
- Any cached session data

### MCP Mode Revocation

For MCP mode, users can revoke tidal-cli's access directly from their Tidal account settings. This invalidates the server-stored tokens.

### Additional Options

| Method | Scope | Action |
|--------|-------|--------|
| `rm -rf ~/.tidal-cli` | Local CLI data | Deletes session file |
| Tidal Account Settings | MCP server data | Revokes OAuth application |
| GitHub Issues | Support | Contact maintainer for data removal |

资料来源：[site/app/privacy/page.tsx]()

## External Service Dependencies

### Tidal Services

| Service | Endpoint | Purpose |
|---------|----------|---------|
| Tidal Auth | `login.tidal.com`, `auth.tidal.com` | OAuth authentication |
| Tidal API | `openapi.tidal.com` | Music library, playlists, catalog access |

### Third-Party Integrations

| Provider | Service | Usage |
|----------|---------|-------|
| Vercel | Edge hosting | MCP server deployment |
| Upstash | Redis database | Encrypted token storage |
| Smithery | MCP registry | MCP connector discovery |

资料来源：[site/app/privacy/page.tsx]()

## Security Considerations

### CLI Mode

- Tokens stored in user-controlled filesystem
- Direct API communication without intermediaries
- User responsible for filesystem security

### MCP Mode

- Tokens encrypted at rest in Upstash Redis
- Vercel edge infrastructure provides additional security layers
- Server-side token management reduces client-side exposure

## Summary

tidal-cli implements a dual-mode session management strategy:

1. **CLI Mode**: Local token storage with direct Tidal API communication
2. **MCP Mode**: Server-side encrypted token storage for AI agent integration

The architecture prioritizes user privacy in CLI mode while enabling seamless AI agent interactions in MCP mode. All token management includes automatic refresh capabilities, and users retain full control over data deletion through local file removal or Tidal account settings revocation.

---

<a id='page-mcp-server'></a>

## MCP Server Integration

### 相关页面

相关主题：[Authentication System](#page-authentication)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [site/app/api/mcp/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/mcp/route.ts)
- [site/app/api/authorize/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/authorize/route.ts)
- [site/app/api/callback/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/callback/route.ts)
- [site/app/api/token/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/token/route.ts)
- [site/app/mcp-lib/tools.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/tools.ts)
</details>

# MCP Server Integration

## Overview

The MCP (Model Context Protocol) Server Integration enables tidal-cli to function as a remote MCP server, allowing AI assistants like Claude to interact with Tidal music accounts through a standardized protocol. This integration provides **40 tools** for searching, playlist management, library access, recommendations, and playback control.

## Architecture

```mermaid
graph TD
    subgraph "Client Side"
        Claude[Claude Desktop / claude.ai]
    end
    
    subgraph "tidal-cli Infrastructure"
        MCP_Endpoint["https://tidal-cli.lucaperret.ch/api/mcp"]
        Auth_Endpoint["https://tidal-cli.lucaperret.ch/api/authorize"]
        Callback["https://tidal-cli.lucaperret.ch/api/callback"]
        Token_API["https://tidal-cli.lucaperret.ch/api/token"]
    end
    
    subgraph "External Services"
        Tidal_API["Tidal API<br/>openapi.tidal.com"]
        Tidal_Auth["Tidal Auth<br/>login.tidal.com"]
        Redis[(Upstash Redis<br/>Token Storage)]
    end
    
    Claude -->|"MCP Protocol"| MCP_Endpoint
    MCP_Endpoint -->|OAuth Flow| Auth_Endpoint
    Auth_Endpoint -->|"Redirect"| Tidal_Auth
    Tidal_Auth -->|"Callback"| Callback
    Callback -->|Token Exchange| Token_API
    Token_API -->|Store/Retrieve| Redis
    MCP_Endpoint -->|API Requests| Tidal_API
    
    style Redis fill:#f9f,stroke:#333,stroke-width:2px
    style Tidal_API fill:#bbf,stroke:#333,stroke-width:2px
    style Tidal_Auth fill:#bbf,stroke:#333,stroke-width:2px
```

## MCP Server Endpoint

The MCP endpoint is implemented as a Next.js route handler at `site/app/api/mcp/route.ts`. It handles the MCP protocol communication between clients and the Tidal API.

### Connection URL

```
https://tidal-cli.lucaperret.ch/api/mcp
```

### Supported Clients

| Client | URL Pattern | Status |
|--------|-------------|--------|
| Claude Desktop | `*.claude.ai` | ✅ Supported |
| Smithery | `*.smithery.ai`, `smithery.run`, `*.smithery.run` | ✅ Supported |
| Local Development | `localhost`, `127.0.0.1` | ✅ Supported |

### Allowed Redirect URIs

The server validates incoming OAuth redirect URIs against an allowlist to prevent unauthorized callback origins:

```typescript
const isAllowed =
    url.hostname.endsWith('.claude.ai') ||
    url.hostname === 'claude.ai' ||
    url.hostname.endsWith('.smithery.ai') ||
    url.hostname === 'smithery.run' ||
    url.hostname.endsWith('.smithery.run') ||
    url.hostname === 'localhost' ||
    url.hostname === '127.0.0.1';
```

资料来源：[site/app/api/authorize/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/authorize/route.ts)

## OAuth Authentication Flow

The MCP server uses OAuth Authorization Code with PKCE (Proof Key for Code Exchange) for secure authentication without exposing client secrets.

### Authentication Sequence

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant Server as tidal-cli Server
    participant Tidal as Tidal Auth
    
    Client->>Server: GET /api/authorize?redirect_uri=...
    Server->>Server: Generate PKCE (code_verifier, code_challenge)
    Server->>Server: Generate session_id
    Server->>Redis: Store OAuth session with PKCE data
    Server->>Client: Redirect to Tidal login
    Client->>Tidal: User authenticates
    Tidal->>Server: Callback with auth code
    Server->>Tidal: Exchange code for tokens
    Server->>Redis: Store encrypted tokens (30-day TTL)
    Server->>Client: Redirect to original client
```

### Session Storage

| Storage Location | Encryption | TTL |
|-----------------|------------|-----|
| Upstash Redis (Remote MCP) | AES-256 encrypted | 30 days |

> **Privacy Note**: No analytics, telemetry, or cookies are used. Tokens are encrypted at rest. 资料来源：[site/app/privacy/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/privacy/page.tsx)

## API Endpoints

### Authorization Endpoint

**Route**: `GET/POST /api/authorize`

Initiates the OAuth flow by redirecting users to Tidal's login page.

**Query Parameters**:
| Parameter | Type | Description |
|-----------|------|-------------|
| `redirect_uri` | string | Client's callback URL |
| `state` | string | CSRF protection token |
| `code_challenge` | string | PKCE code challenge |
| `code_challenge_method` | string | Must be "S256" |

**Process**:
1. Validates `redirect_uri` against allowed origins
2. Generates PKCE code verifier and challenge
3. Creates session ID for state management
4. Stores session data in Redis
5. Redirects to Tidal authorization URL

资料来源：[site/app/api/authorize/route.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/api/authorize/route.ts)

### Callback Endpoint

**Route**: `/api/callback`

Handles the OAuth callback from Tidal after user authentication.

**Process**:
1. Receives authorization code from Tidal
2. Validates state parameter against stored session
3. Exchanges code for access/refresh tokens
4. Stores tokens in Redis with session data
5. Redirects user back to MCP client

### Token Endpoint

**Route**: `POST /api/token`

Manages token operations including retrieval and refresh.

**Operations**:
| Operation | Description |
|-----------|-------------|
| Retrieve | Get stored tokens for a session |
| Refresh | Refresh expired access tokens |
| Delete | Revoke tokens and clear session |

## MCP Tools (40 Total)

The MCP server exposes 40 tools organized into functional categories. Each tool includes safety annotations for AI assistants.

资料来源：[site/app/mcp-lib/tools.ts](https://github.com/lucaperret/tidal-cli/blob/main/site/app/mcp-lib/tools.ts)

### Tool Categories

| Category | Tool Count | Examples |
|----------|------------|----------|
| Search | 6 | `tidal_search`, `tidal_search_suggest` |
| Track | 4 | `tidal_track_info`, `tidal_track_similar` |
| Album | 2 | `tidal_album_info`, `tidal_album_by_barcode` |
| Artist | 5 | `tidal_artist_info`, `tidal_artist_tracks` |
| Playlist | 8 | `tidal_playlist_list`, `tidal_playlist_add_track` |
| Library | 5 | `tidal_library_tracks`, `tidal_library_favorite_playlists` |
| History | 2 | `tidal_recently_added`, `tidal_history_tracks` |
| Playback | 3 | `tidal_playback_play`, `tidal_playback_info` |
| User | 1 | `tidal_user_profile` |
| Recommendations | 4 | `tidal_recommend`, `tidal_mix_items` |
| Saved | 2 | `tidal_saved_list`, `tidal_saved_add` |
| Sharing | 4 | `tidal_share_track`, `tidal_share_album` |

### Tool Schema Example

Tools are defined using Zod schemas with safety annotations:

```typescript
server.tool(
    'tidal_album_info',
    'Get album details including artists and cover art',
    {
        albumId: z.string().describe('Tidal album ID'),
    },
    {
        readOnlyHint: true,
        destructiveHint: false,
        openWorldHint: true,
        title: 'Album Info'
    },
    async ({ albumId }, extra) => {
        const { client, countryCode } = await getClientAndCountry(extractToken(extra));
        return text(await getAlbumInfoData(albumId, client, countryCode));
    }
);
```

### Safety Annotations

| Annotation | Type | Description |
|------------|------|-------------|
| `readOnlyHint` | boolean | Indicates if the tool only reads data |
| `destructiveHint` | boolean | Indicates if the tool modifies/deletes data |
| `openWorldHint` | boolean | Indicates if the tool interacts with external services |
| `title` | string | Human-readable title for UI display |

## Setup Instructions

### Claude Desktop

1. Open Claude Desktop settings
2. Navigate to **Connectors** → **Add custom connector**
3. Enter the connector URL:
   ```
   https://tidal-cli.lucaperret.ch/api/mcp
   ```
4. Click **Connect** and authenticate with Tidal

资料来源：[site/app/page.tsx](https://github.com/lucaperret/tidal-cli/blob/main/site/app/page.tsx)

### Smithery

Access via: [https://smithery.ai/servers/lucaperret/tidal](https://smithery.ai/servers/lucaperret/tidal)

Smithery automatically re-scans tools and prompts after deployment.

## Data Flow

```mermaid
graph LR
    subgraph "Request Flow"
        A[MCP Request] --> B{Auth Check}
        B -->|Valid Token| C[Extract Token]
        B -->|Invalid/Missing| D[OAuth Flow]
        C --> E[Get Client & Country]
        E --> F[Call Tidal API]
        F --> G[Format Response]
        G --> H[MCP Response]
    end
    
    subgraph "Tool Categories"
        I[Search Tools]
        J[Playlist Tools]
        K[Library Tools]
        L[Playback Tools]
    end
    
    F --> I
    F --> J
    F --> K
    F --> L
```

## Distribution Channels

| Channel | URL | Description |
|---------|-----|-------------|
| Direct MCP | `https://tidal-cli.lucaperret.ch/api/mcp` | Primary endpoint |
| Smithery | [smithery.ai](https://smithery.ai/servers/lucaperret/tidal) | MCP registry |
| ClawHub | [clawhub.ai](https://clawhub.ai/lucaperret/tidal-cli) | OpenClaw skill |

## Configuration Options

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `TIDAL_COUNTRY` | `US` | Fallback country code |
| `TIDAL_CLIENT_ID` | (hardcoded) | OAuth client ID |

### Session Management

- **Storage Location**: Upstash Redis (encrypted)
- **TTL**: 30 days
- **Encryption**: AES-256 at rest
- **Token Refresh**: Automatic via credentials provider

## Security Considerations

1. **PKCE Required**: All OAuth flows use Proof Key for Code Exchange
2. **Redirect Validation**: Strict allowlist for callback URIs
3. **Token Encryption**: OAuth tokens encrypted in Redis
4. **No Client Secret**: Uses public OAuth pattern
5. **State Parameter**: CSRF protection on all OAuth flows

## Comparison: CLI vs MCP

| Aspect | CLI | MCP Server |
|--------|-----|------------|
| Token Storage | `~/.tidal-cli/session.json` | Upstash Redis |
| Session Type | Local only | Server-side |
| Auth Flow | Browser-based | OAuth redirect |
| Use Case | Direct terminal | AI assistant integration |
| Platform | Node.js >= 20 | Any MCP client |

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| "redirect_uri not allowed" | Ensure client hostname matches allowed list |
| Token expired | Re-authenticate via OAuth flow |
| Tools not appearing | Refresh MCP client after deployment |

### Deployment Notes

After updating MCP tools or prompts:

1. Deploy changes to Vercel
2. Wait for auto-deploy completion
3. Smithery will automatically re-scan (if using Smithery)

资料来源：[CLAUDE.md](https://github.com/lucaperret/tidal-cli/blob/main/CLAUDE.md)

---

---

## Doramagic 踩坑日志

项目：lucaperret/tidal-cli

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。

## 1. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | host_targets=mcp_host, claude

## 2. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | README/documentation is current enough for a first validation pass.

## 3. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | last_activity_observed missing

## 4. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | no_demo; severity=medium

## 5. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | no_demo; severity=medium

## 6. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | issue_or_pr_quality=unknown

## 7. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1183583268 | https://github.com/lucaperret/tidal-cli | release_recency=unknown

<!-- canonical_name: lucaperret/tidal-cli; human_manual_source: deepwiki_human_wiki -->
