#
tokens: 24300/50000 25/25 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .env.example
├── .github
│   └── ISSUE_TEMPLATE
│       ├── Bad case about the model.yml
│       ├── Bug Report for MCP.yml
│       ├── Feature request.yml
│       └── Model Inquiry.yml
├── .gitignore
├── LICENSE
├── mcp_server_config_demo.json
├── minimax_mcp
│   ├── __init__.py
│   ├── __main__.py
│   ├── client.py
│   ├── const.py
│   ├── exceptions.py
│   ├── server.py
│   └── utils.py
├── pyproject.toml
├── README-CN.md
├── README.md
├── scripts
│   ├── build.sh
│   ├── deploy.sh
│   ├── dev.sh
│   ├── setup.sh
│   └── test.sh
├── setup.py
├── tests
│   ├── conftest.py
│   └── test_utils.py
└── uv.lock
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
*.pyc
*.pyo
*.pyd
*.pyw
*.pyz
*.pywz

.env
.venv
.cursor
.cursorignore
dist/
minimax_mcp.egg-info/
.coverage
coverage.xml
```

--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------

```
MINIMAX_API_KEY=PUT_YOUR_KEY_HERE
#optional base path for output files
MINIMAX_MCP_BASE_PATH=~/Desktop 
MINIMAX_API_HOST=https://api.minimax.chat
#optional resource mode[url, local], default is url
# MINIMAX_API_RESOURCE_MODE=local
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
![export](https://github.com/MiniMax-AI/MiniMax-01/raw/main/figures/MiniMaxLogo-Light.png)

<div align="center" style="line-height: 1;">
  <a href="https://www.minimax.io" target="_blank" style="margin: 2px; color: var(--fgColor-default);">
    <img alt="Homepage" src="https://img.shields.io/badge/_Homepage-MiniMax-FF4040?style=flat-square&labelColor=2C3E50&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNDkwLjE2IDQxMS43Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjMzLjQ1LDQwLjgxYTE3LjU1LDE3LjU1LDAsMSwwLTM1LjEsMFYzMzEuNTZhNDAuODIsNDAuODIsMCwwLDEtODEuNjMsMFYxNDVhMTcuNTUsMTcuNTUsMCwxLDAtMzUuMDksMHY3OS4wNmE0MC44Miw0MC44MiwwLDAsMS04MS42MywwVjE5NS40MmExMS42MywxMS42MywwLDAsMSwyMy4yNiwwdjI4LjY2YTE3LjU1LDE3LjU1LDAsMCwwLDM1LjEsMFYxNDVBNDAuODIsNDAuODIsMCwwLDEsMTQwLDE0NVYzMzEuNTZhMTcuNTUsMTcuNTUsMCwwLDAsMzUuMSwwVjIxNy41aDBWNDAuODFhNDAuODEsNDAuODEsMCwxLDEsODEuNjIsMFYyODEuNTZhMTEuNjMsMTEuNjMsMCwxLDEtMjMuMjYsMFptMjE1LjksNjMuNEE0MC44Niw0MC44NiwwLDAsMCw0MDguNTMsMTQ1VjMwMC44NWExNy41NSwxNy41NSwwLDAsMS0zNS4wOSwwdi0yNjBhNDAuODIsNDAuODIsMCwwLDAtODEuNjMsMFYzNzAuODlhMTcuNTUsMTcuNTUsMCwwLDEtMzUuMSwwVjMzMGExMS42MywxMS42MywwLDEsMC0yMy4yNiwwdjQwLjg2YTQwLjgxLDQwLjgxLDAsMCwwLDgxLjYyLDBWNDAuODFhMTcuNTUsMTcuNTUsMCwwLDEsMzUuMSwwdjI2MGE0MC44Miw0MC44MiwwLDAsMCw4MS42MywwVjE0NWExNy41NSwxNy41NSwwLDEsMSwzNS4xLDBWMjgxLjU2YTExLjYzLDExLjYzLDAsMCwwLDIzLjI2LDBWMTQ1QTQwLjg1LDQwLjg1LDAsMCwwLDQ0OS4zNSwxMDQuMjFaIi8+PC9zdmc+&logoWidth=20" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://arxiv.org/abs/2501.08313" target="_blank" style="margin: 2px;">
    <img alt="Paper" src="https://img.shields.io/badge/📖_Paper-MiniMax--01-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
   <a href="https://chat.minimax.io/" target="_blank" style="margin: 2px;">
    <img alt="Chat" src="https://img.shields.io/badge/_MiniMax_Chat-FF4040?style=flat-square&labelColor=2C3E50&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNDkwLjE2IDQxMS43Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjMzLjQ1LDQwLjgxYTE3LjU1LDE3LjU1LDAsMSwwLTM1LjEsMFYzMzEuNTZhNDAuODIsNDAuODIsMCwwLDEtODEuNjMsMFYxNDVhMTcuNTUsMTcuNTUsMCwxLDAtMzUuMDksMHY3OS4wNmE0MC44Miw0MC44MiwwLDAsMS04MS42MywwVjE5NS40MmExMS42MywxMS42MywwLDAsMSwyMy4yNiwwdjI4LjY2YTE3LjU1LDE3LjU1LDAsMCwwLDM1LjEsMFYxNDVBNDAuODIsNDAuODIsMCwwLDEsMTQwLDE0NVYzMzEuNTZhMTcuNTUsMTcuNTUsMCwwLDAsMzUuMSwwVjIxNy41aDBWNDAuODFhNDAuODEsNDAuODEsMCwxLDEsODEuNjIsMFYyODEuNTZhMTEuNjMsMTEuNjMsMCwxLDEtMjMuMjYsMFptMjE1LjksNjMuNEE0MC44Niw0MC44NiwwLDAsMCw0MDguNTMsMTQ1VjMwMC44NWExNy41NSwxNy41NSwwLDAsMS0zNS4wOSwwdi0yNjBhNDAuODIsNDAuODIsMCwwLDAtODEuNjMsMFYzNzAuODlhMTcuNTUsMTcuNTUsMCwwLDEtMzUuMSwwVjMzMGExMS42MywxMS42MywwLDEsMC0yMy4yNiwwdjQwLjg2YTQwLjgxLDQwLjgxLDAsMCwwLDgxLjYyLDBWNDAuODFhMTcuNTUsMTcuNTUsMCwwLDEsMzUuMSwwdjI2MGE0MC44Miw0MC44MiwwLDAsMCw4MS42MywwVjE0NWExNy41NSwxNy41NSwwLDEsMSwzNS4xLDBWMjgxLjU2YTExLjYzLDExLjYzLDAsMCwwLDIzLjI2LDBWMTQ1QTQwLjg1LDQwLjg1LDAsMCwwLDQ0OS4zNSwxMDQuMjFaIi8+PC9zdmc+&logoWidth=20" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://www.minimax.io/platform" style="margin: 2px;">
    <img alt="API" src="https://img.shields.io/badge/⚡_API-Platform-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>  
</div>
<div align="center" style="line-height: 1;">
  <a href="https://huggingface.co/MiniMaxAI" target="_blank" style="margin: 2px;">
    <img alt="Hugging Face" src="https://img.shields.io/badge/🤗_Hugging_Face-MiniMax-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://github.com/MiniMax-AI/MiniMax-AI.github.io/blob/main/images/wechat-qrcode.jpeg" target="_blank" style="margin: 2px;">
    <img alt="WeChat" src="https://img.shields.io/badge/_WeChat-MiniMax-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://www.modelscope.cn/organization/MiniMax" target="_blank" style="margin: 2px;">
    <img alt="ModelScope" src="https://img.shields.io/badge/_ModelScope-MiniMax-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
</div>
<div align="center" style="line-height: 1;">
   <a href="https://github.com/MiniMax-AI/MiniMax-MCP/blob/main/LICENSE" style="margin: 2px;">
    <img alt="Code License" src="https://img.shields.io/badge/_Code_License-MIT-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
</div>

<p align="center">
  Official MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech and video/image generation APIs. This server allows MCP clients like <a href="https://www.anthropic.com/claude">Claude Desktop</a>, <a href="https://www.cursor.so">Cursor</a>, <a href="https://codeium.com/windsurf">Windsurf</a>, <a href="https://github.com/openai/openai-agents-python">OpenAI Agents</a> and others to generate speech, clone voices, generate video, generate image and more.
</p>

## Documentation
- [中文文档](README-CN.md)
- [MiniMax-MCP-JS](https://github.com/MiniMax-AI/MiniMax-MCP-JS) - Official JavaScript implementation of MiniMax MCP

## Quickstart with MCP Client
1. Get your API key from [MiniMax](https://www.minimax.io/platform/user-center/basic-information/interface-key). 
2. Install `uv` (Python package manager), install with `curl -LsSf https://astral.sh/uv/install.sh | sh` or see the `uv` [repo](https://github.com/astral-sh/uv) for additional install methods.
3. **Important**: The API host and key vary by region and must match; otherwise, you'll encounter an `Invalid API key` error.

|Region| Global  | Mainland  |
|:--|:-----|:-----|
|MINIMAX_API_KEY| go get from [MiniMax Global](https://www.minimax.io/platform/user-center/basic-information/interface-key) | go get from [MiniMax](https://platform.minimaxi.com/user-center/basic-information/interface-key) |
|MINIMAX_API_HOST| https://api.minimax.io | https://api.minimaxi.com |


### Claude Desktop
Go to `Claude > Settings > Developer > Edit Config > claude_desktop_config.json` to include the following:

```
{
  "mcpServers": {
    "MiniMax": {
      "command": "uvx",
      "args": [
        "minimax-mcp",
        "-y"
      ],
      "env": {
        "MINIMAX_API_KEY": "insert-your-api-key-here",
        "MINIMAX_MCP_BASE_PATH": "local-output-dir-path, such as /User/xxx/Desktop",
        "MINIMAX_API_HOST": "api host, https://api.minimax.io | https://api.minimaxi.com",
        "MINIMAX_API_RESOURCE_MODE": "optional, [url|local], url is default, audio/image/video are downloaded locally or provided in URL format"
      }
    }
  }
}

```
⚠️ Warning: The API key needs to match the host. If an error "API Error: invalid api key" occurs, please check your api host:
- Global Host:`https://api.minimax.io`
- Mainland Host:`https://api.minimaxi.com`

If you're using Windows, you will have to enable "Developer Mode" in Claude Desktop to use the MCP server. Click "Help" in the hamburger menu in the top left and select "Enable Developer Mode".


### Cursor
Go to `Cursor -> Preferences -> Cursor Settings -> MCP -> Add new global MCP Server` to add above config.

That's it. Your MCP client can now interact with MiniMax through these tools:

## Transport
We support two transport types: stdio and sse.
| stdio  | SSE  |
|:-----|:-----|
| Run locally | Can be deployed locally or in the cloud |
| Communication through `stdout` | Communication through `network` |
| Input: Supports processing `local files` or valid `URL` resources | Input: When deployed in the cloud, it is recommended to use `URL` for input |

## Available Tools
| tool  | description  |
|-|-|
|`text_to_audio`|Convert text to audio with a given voice|
|`list_voices`|List all voices available|
|`voice_clone`|Clone a voice using provided audio files|
|`generate_video`|Generate a video from a prompt|
|`text_to_image`|Generate a image from a prompt|
|`query_video_generation`|Query the result of video generation task|
|`music_generation`|Generate a music track from a prompt and lyrics|
|`voice_design`|Generate a voice from a prompt using preview text|

## Release Notes

### July 2, 2025

#### 🆕 What's New
- **Voice Design**: New `voice_design` tool - create custom voices from descriptive prompts with preview audio
- **Video Enhancement**: Added `MiniMax-Hailuo-02` model with ultra-clear quality and duration/resolution controls  
- **Music Generation**: Enhanced `music_generation` tool powered by `music-1.5` model

#### 📈 Enhanced Tools
- `voice_design` - Generate personalized voices from text descriptions
- `generate_video` - Now supports MiniMax-Hailuo-02 with 6s/10s duration and 768P/1080P resolution options
- `music_generation` - High-quality music creation with music-1.5 model

## FAQ
### 1. invalid api key
Please ensure your API key and API host are regionally aligned
|Region| Global  | Mainland  |
|:--|:-----|:-----|
|MINIMAX_API_KEY| go get from [MiniMax Global](https://www.minimax.io/platform/user-center/basic-information/interface-key) | go get from [MiniMax](https://platform.minimaxi.com/user-center/basic-information/interface-key) |
|MINIMAX_API_HOST| https://api.minimax.io | https://api.minimaxi.com |

### 2. spawn uvx ENOENT
Please confirm its absolute path by running this command in your terminal:
```sh
which uvx
```
Once you obtain the absolute path (e.g., /usr/local/bin/uvx), update your configuration to use that path (e.g., "command": "/usr/local/bin/uvx"). 

### 3. How to use `generate_video` in async-mode
Define completion rules before starting:
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/cursor_rule2.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>
Alternatively, these rules can be configured in your IDE settings (e.g., Cursor):
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/cursor_video_rule.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>


## Example usage

⚠️ Warning: Using these tools may incur costs.

### 1. broadcast a segment of the evening news
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_20-07-53.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>

### 2. clone a voice
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_19-45-13.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>

### 3. generate a video
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_19-58-52.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_19-59-43.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle; "/>

### 4. generate images
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/gen_image.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/gen_image1.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle; "/>

```

--------------------------------------------------------------------------------
/scripts/build.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash
rm -rf dist/ build/ *.egg-info/
uv build
```

--------------------------------------------------------------------------------
/minimax_mcp/__init__.py:
--------------------------------------------------------------------------------

```python
"""Minimax MCP Server package."""

__version__ = "0.0.17"

```

--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------

```python
from setuptools import setup, find_packages

setup(
    packages=find_packages(),
    include_package_data=True,
)

```

--------------------------------------------------------------------------------
/scripts/dev.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash
uv run fastmcp dev minimax_mcp/server.py --with python-dotenv --with fuzzywuzzy --with python-Levenshtein --with sounddevice --with soundfile --with-editable .
```

--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------

```python
import pytest
from pathlib import Path
import tempfile


@pytest.fixture
def temp_dir():
    with tempfile.TemporaryDirectory() as temp_dir:
        yield Path(temp_dir)


@pytest.fixture
def sample_audio_file(temp_dir):
    audio_file = temp_dir / "test.mp3"
    audio_file.touch()
    return audio_file


@pytest.fixture
def sample_video_file(temp_dir):
    video_file = temp_dir / "test.mp4"
    video_file.touch()
    return video_file

```

--------------------------------------------------------------------------------
/scripts/deploy.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

# Check if environment argument is provided
if [[ $# -lt 1 ]]; then
    echo "Usage: $0 [test|prod]"
    exit 1
fi

# Clean previous builds
rm -rf dist/ build/ *.egg-info/

# Build the package
uv build

if [ "$1" = "test" ]; then
    uv run twine upload --repository testpypi dist/* --verbose
elif [ "$1" = "prod" ]; then
    uv run twine upload --repository pypi dist/*
else
    echo "Please specify 'test' or 'prod' as the argument"
    exit 1
fi
```

--------------------------------------------------------------------------------
/minimax_mcp/exceptions.py:
--------------------------------------------------------------------------------

```python
"""Custom exceptions for Minimax MCP."""

class MinimaxAPIError(Exception):
    """Base exception for Minimax API errors."""
    pass

class MinimaxAuthError(MinimaxAPIError):
    """Authentication related errors."""
    pass

class MinimaxRequestError(MinimaxAPIError):
    """Request related errors."""
    pass

class MinimaxTimeoutError(MinimaxAPIError):
    """Timeout related errors."""
    pass

class MinimaxValidationError(MinimaxAPIError):
    """Validation related errors."""
    pass 

class MinimaxMcpError(MinimaxAPIError):
    pass

```

--------------------------------------------------------------------------------
/scripts/test.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

# Set default variables
COVERAGE=true
VERBOSE=false
FAIL_FAST=false

# Process command-line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --no-coverage)
      COVERAGE=false
      shift
      ;;
    --verbose|-v)
      VERBOSE=true
      shift
      ;;
    --fail-fast|-f)
      FAIL_FAST=true
      shift
      ;;
    *)
      echo "Unknown option: $1"
      echo "Usage: ./test.sh [--no-coverage] [--verbose|-v] [--fail-fast|-f]"
      exit 1
      ;;
  esac
done

# Build the command
CMD="python -m pytest"

if [ "$COVERAGE" = true ]; then
  CMD="$CMD --cov=minimax_mcp"
fi

if [ "$VERBOSE" = true ]; then
  CMD="$CMD -v"
fi

if [ "$FAIL_FAST" = true ]; then
  CMD="$CMD -x"
fi

# Run the tests
echo "Running tests with command: $CMD"
$CMD 
```

--------------------------------------------------------------------------------
/scripts/setup.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

# Ensure uv is available
if ! command -v uv &> /dev/null; then
    echo "Error: uv is not installed. Please install it first:"
    echo "pip install uv"
    exit 1
fi

# Create or update virtual environment
echo "Creating/updating virtual environment..."
uv venv .venv

# Activate virtual environment based on shell
if [[ "$SHELL" == */zsh ]]; then
    source .venv/bin/activate
elif [[ "$SHELL" == */bash ]]; then
    source .venv/bin/activate
else
    echo "Please activate the virtual environment manually:"
    echo "source .venv/bin/activate"
fi

# Install dependencies
echo "Installing dependencies with uv..."
uv pip install -e ".[dev]"

# Install pre-commit hooks
echo "Setting up pre-commit hooks..."
pre-commit install

echo "Setup complete! Virtual environment is ready." 
```

--------------------------------------------------------------------------------
/mcp_server_config_demo.json:
--------------------------------------------------------------------------------

```json
{
    "mcpServers": {
      "MiniMax": {
        "command": "uvx",
        "args": [
          "minimax-mcp"
        ],
        "env": {
          "MINIMAX_API_KEY": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTc0NTM3NjU1N30.nrmwo6orXJfyf63IqJCK4LiUXrq9r9ZELCY530Mu6sLyx_qNAVsJ3Q828Rqy6pwoQl6VFMMFaJG3kc6aIMEfVLo7xlB-4NbwMxYKhwtxyQL8g_agYqw-1aY4zr3uvgTZxafXt1dEjcuS5i9O9SuOXXofeqb0jAnb_dssaLfgHNKlKthJpjsg8G76ZULS7KCpm6GvPWR4mwIdH-i0IhBU6CVSWpBAYKVNHJ-FVN_HzN5UgGvHkDbOOggg6Ib1illYbx6zkb7_JYZ7Tek1erjvJi7IG8Keh4NHq5kcyROWBetO9W8_2if_nfO6XBhlJRECpEmYBONwroGw0nH6xNblQw",
          "MINIMAX_MCP_BASE_PATH": "~/Desktop",
          "MINIMAX_API_HOST": "https://api.minimax.chat",
          "MINIMAX_API_RESOURCE_MODE": "url"
        }
      }
    }
  }
```

--------------------------------------------------------------------------------
/minimax_mcp/const.py:
--------------------------------------------------------------------------------

```python
# speech model default values
DEFAULT_VOICE_ID = "female-shaonv"
DEFAULT_SPEECH_MODEL = "speech-02-hd"
DEFAULT_MUSIC_MODEL = "music-1.5"
DEFAULT_SPEED = 1.0
DEFAULT_VOLUME = 1.0
DEFAULT_PITCH = 0
DEFAULT_EMOTION = "happy"
DEFAULT_SAMPLE_RATE = 32000
DEFAULT_BITRATE = 128000
DEFAULT_CHANNEL = 1
DEFAULT_FORMAT = "mp3"
DEFAULT_LANGUAGE_BOOST = "auto"

# video model default values
DEFAULT_T2V_MODEL = "T2V-01"

# image model default values
DEFAULT_T2I_MODEL = "image-01"

# ENV variables
ENV_MINIMAX_API_KEY = "MINIMAX_API_KEY"
ENV_MINIMAX_API_HOST = "MINIMAX_API_HOST"
ENV_MINIMAX_MCP_BASE_PATH = "MINIMAX_MCP_BASE_PATH"
ENV_RESOURCE_MODE = "MINIMAX_API_RESOURCE_MODE"

RESOURCE_MODE_LOCAL = "local" # save resource to local file system
RESOURCE_MODE_URL = "url" # provide resource url

ENV_FASTMCP_LOG_LEVEL = "FASTMCP_LOG_LEVEL"
```

--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Feature request.yml:
--------------------------------------------------------------------------------

```yaml
name: Feature Request
description: Propose a new feature or enhancement for the project.
title: "[request]: "
labels: ["enhancement", "feature-request", "triage"]
body:
  - type: markdown
    attributes:
      value: |
        Thank you for suggesting a new feature! Please provide the following details to help us understand your proposal.

  - type: input
    id: feature-about
    attributes:
      label: Basic Information - Feature about
      description: "Please briefly describe the feature, including the type of use and the framework, e.g., support Minimax-M1 in Ollama."
      placeholder: "e.g., support Minimax-M1 in Ollama."
    validations:
      required: true 

  - type: textarea
    id: proposal
    attributes:
      label: Proposal
      description: |
        Please describe the feature you have requested and the rationale behind it.
        The following template is recommended. Feel free to modify it as you needed.
      value: |
        #### Introduction
        I would like that ...

        #### Rational
        Implementation of this feature will help the following usecase:
        - ...
        - ...

        #### Anything else
        I find ... has this feature and xxx can serve as a reference for implementation.
    validations:
      required: true 

```

--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------

```toml
[project]
name = "minimax-mcp"
version = "0.0.17"
description = "Minimax MCP Server"
authors = [
    { name = "Roy Wu", email = "[email protected]" },
]
readme = "README.md"
license = { file = "LICENSE" }
classifiers = [
    "Development Status :: 4 - Beta",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.10",
]
keywords = [
    "minimax",
    "mcp",
    "text-to-speech",
    "voice-cloning",
    "video-generation",
]
requires-python = ">=3.10"
dependencies = [
    "mcp[cli]>=1.6.0",
    "fastapi>=0.109.2",
    "uvicorn>=0.27.1",
    "python-dotenv>=1.0.1",
    "pydantic>=2.6.1",
    "httpx>=0.28.1",
    "fuzzywuzzy>=0.18.0",
    "python-Levenshtein>=0.25.0",
    "sounddevice>=0.5.1",
    "soundfile>=0.13.1",
    "requests>=2.31.0",
]

[project.scripts]
minimax-mcp = "minimax_mcp.server:main"

[project.optional-dependencies]
dev = [
    "pre-commit>=3.6.2",
    "ruff>=0.3.0",
    "fastmcp>=0.4.1",
    "pytest>=8.0.0",
    "pytest-cov>=4.1.0",
    "twine>=6.1.0",
    "build>=1.0.3",
]

[build-system]
requires = ["setuptools>=45", "wheel"]
build-backend = "setuptools.build_meta"

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = "-v --cov=minimax_mcp --cov-report=term-missing"

```

--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Model Inquiry.yml:
--------------------------------------------------------------------------------

```yaml
name: Model Inquiry
description: Ask a question about the open source models.
title: "[Inquiry]: "
labels: ["question", "triage"]
body:
  - type: markdown
    attributes:
      value: |
        Thank you for reaching out! Please provide the following details to help us understand and address your inquiry about models.

  - type: input
    attributes:
      label: Basic Information - Models Used
      description: |
        Please list the model used, e.g., MiniMax-M1, speech-02-hd, etc.
        Our models can be referred at [HuggingFace](https://huggingface.co/MiniMaxAI) or [the official site](https://www.minimax.io/platform_overview).
      placeholder: "ex: MiniMax-M1"
    validations:
      required: true
      
  - type: checkboxes
    id: problem-validation
    attributes:
      label: Is this information known and solvable?
      options:
        - label: "I have checked [Minimax documentation](https://www.minimax.io/platform_overview) and found no solution."
          required: true
        - label: "I have searched existing issues and found no duplicates."
          required: true


  - type: textarea
    id: detailed-description
    attributes:
      label: Description
      description: "Please describe your question in detail here. If available, please paste relevant screenshots directly into this box."
      placeholder: |
        - Your detailed question or issue description.
        - Relevant context or background information.
        - (Paste screenshots directly below this text)
    validations:
      required: true

```

--------------------------------------------------------------------------------
/minimax_mcp/__main__.py:
--------------------------------------------------------------------------------

```python
import os
import json
from pathlib import Path
import sys
from dotenv import load_dotenv
import argparse

load_dotenv()


def get_claude_config_path() -> Path | None:
    """Get the Claude config directory based on platform."""
    if sys.platform == "win32":
        path = Path(Path.home(), "AppData", "Roaming", "Claude")
    elif sys.platform == "darwin":
        path = Path(Path.home(), "Library", "Application Support", "Claude")
    elif sys.platform.startswith("linux"):
        path = Path(
            os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"), "Claude"
        )
    else:
        return None

    if path.exists():
        return path
    return None


def get_python_path():
    return sys.executable


def generate_config(api_key: str | None = None):
    module_dir = Path(__file__).resolve().parent
    server_path = module_dir / "server.py"
    python_path = get_python_path()

    final_api_key = api_key or os.environ.get("MINIMAX_API_KEY")
    if not final_api_key:
        print("Error: Minimax API key is required.")
        print("Please either:")
        print("  1. Pass the API key using --api-key argument, or")
        print("  2. Set the MINIMAX_API_KEY environment variable, or")
        print("  3. Add MINIMAX_API_KEY to your .env file")
        sys.exit(1)

    config = {
        "mcpServers": {
            "Minimax": {
                "command": "uvx",
                "args": [
                    "minimax-mcp",
                ],

                "env": {
                    "MINIMAX_API_KEY": final_api_key,
                    "MINIMAX_MCP_BASE_PATH": "",
                    "MINIMAX_API_HOST": "https://api.minimax.chat",
                },
            }
        }
    }

    return config


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--print",
        action="store_true",
        help="Print config to screen instead of writing to file",
    )
    parser.add_argument(
        "--api-key",
        help="Minimax API key (alternatively, set MINIMAX_API_KEY environment variable)",
    )
    parser.add_argument(
        "--config-path",
        type=Path,
        help="Custom path to Claude config directory",
    )
    args = parser.parse_args()

    config = generate_config(args.api_key)

    if args.print:
        print(json.dumps(config, indent=2))
    else:
        claude_path = args.config_path if args.config_path else get_claude_config_path()
        if claude_path is None:
            print(
                "Could not find Claude config path automatically. Please specify it using --config-path argument. The argument should be an absolute path of the claude_desktop_config.json file."
            )
            sys.exit(1)

        claude_path.mkdir(parents=True, exist_ok=True)
        print("Writing config to", claude_path / "claude_desktop_config.json")
        with open(claude_path / "claude_desktop_config.json", "w") as f:
            json.dump(config, f, indent=2)

```

--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Bug Report for MCP.yml:
--------------------------------------------------------------------------------

```yaml
name: Bug Report for MCP&API
description: Report a bug related to MCP and API tasks to help us reproduce and fix the problem.
title: "[Bug for MCP&API]: "
labels: ["bug", "triage"]
body:
  - type: markdown
    attributes:
      value: |
        Thank you for contributing to our project by reporting a bug! To help us understand and resolve the issue as quickly as possible, please provide the following details.

  - type: input
    attributes:
      label: Basic Information - Models Used
      description: |
        Please list the model used, e.g., MiniMax-M1, speech-02-hd, etc.
        Our models can be referred at [HuggingFace](https://huggingface.co/MiniMaxAI) or [the official site](https://www.minimax.io/platform_overview).
      placeholder: "ex: MiniMax-M1"
    validations:
      required: true
      
  - type: input
    id: scenario-description
    attributes:
      label: Basic Information - Scenario Description
      description: | 
        Please briefly describe the scenario, including the framework or the platform, 
      placeholder: "ex: Minimax-M1 cannot be called as MCP tools. "
    validations:
      required: false

  - type: checkboxes
    id: problem-validation
    attributes:
      label: Is this bug known and solvable?
      options:
        - label: "I have followed the GitHub READMEs for [`Minimax-MCP`](https://github.com/MiniMax-AI/MiniMax-MCP) and [`Minimax-MCP-JS`](https://github.com/MiniMax-AI/MiniMax-MCP-JS)."
          required: true
        - label: "I have checked the [official Minimax documentation](https://www.minimax.io/platform_overview) and [existing GitHub issues](https://github.com/MiniMax-AI/MiniMax-MCP/issues),but found no solution."
          required: true

  - type: textarea
    attributes:
      label: Information about environment
      description: |
        Please provide information about you environment, 
        e.g., the software versions and the information on the OS, GPUs, python packages(from pip list) if available.
      placeholder:
        "For example:
        - OS: Ubuntu 24.04
        - Python: Python 3.11
        - PyTorch: 2.6.0+cu124"
        
    validations:
      required: true

  - type: input
    id: trace-id
    attributes:
      label: Trace-ID in the request head
      description: "Please copy and paste the trace-ID of the problematic request."
    validations:
      required: true

  - type: textarea
    attributes:
      label: Description
      description: |
        Please **describe the bug** you have encountered when using the MCP tools or API, and **paste the screenshots** of the error or unexpected behaviour here.
        The following template is recommended.
        Feel free to modify as you needed.
      value: |
        #### Steps to reproduce

        This happens to Minimax_M1 and xxx.
        The bug can be reproduced with the following steps:
        1. ...
        2. ...

        The following example input & output can be used:
        ```
        system: ...
        user: ...
        ...
        ```

        #### Expected results

        The results are expected to be ...

        #### Actual behaviours

        The actual outputs are as follows: ...

        #### Error logs

        The error logs are as follows: ...

        ### The screenshots are as belows:
    validations:
      required: true

```

--------------------------------------------------------------------------------
/tests/test_utils.py:
--------------------------------------------------------------------------------

```python
import pytest
from pathlib import Path
import tempfile
from minimax_mcp.utils import (
    MinimaxMcpError,
    is_file_writeable,
    build_output_file,
    build_output_path,
    find_similar_filenames,
    try_find_similar_files,
    process_input_file,
)

def test_is_file_writeable():
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        assert is_file_writeable(temp_path) is True
        assert is_file_writeable(temp_path / "nonexistent.txt") is True


def test_make_output_file():
    tool = "test"
    text = "hello world"
    output_path = Path("/tmp")
    result = build_output_file(tool, text, output_path, "mp3")
    assert result.name.startswith("test_hello")
    assert result.suffix == ".mp3"


def test_make_output_path():
    # Test with temporary directory
    with tempfile.TemporaryDirectory() as temp_dir:
        result = build_output_path(temp_dir)
        assert result == Path(temp_dir)
        assert result.exists()
        assert result.is_dir()

    # Test with None output_directory (should use base_path)
    base_path = "/tmp/test_base"
    result = build_output_path(None, base_path, is_test=True)
    assert result == Path(base_path)
    
    # Test with relative output_directory
    base_path = "/tmp/test_base"
    result = build_output_path("subdir", base_path, is_test=True)
    assert result == Path(base_path) / "subdir"
    
    # Test with absolute output_directory (should ignore base_path)
    abs_path = "/absolute/path"
    result = build_output_path(abs_path, "/some/base/path", is_test=True)
    assert result == Path(abs_path)

    abs_path = "~/absolute/path"
    result = build_output_path(abs_path, "/some/base/path", is_test=True)
    assert result == Path(Path.home() / "absolute/path")
    
    # Test with None base_path (should use desktop)
    result = build_output_path(None, None, is_test=True)
    assert result == Path.home() / "Desktop"
    


def test_find_similar_filenames():
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        test_file = temp_path / "test_file.txt"
        similar_file = temp_path / "test_file_2.txt"
        different_file = temp_path / "different.txt"

        test_file.touch()
        similar_file.touch()
        different_file.touch()

        results = find_similar_filenames(str(test_file), temp_path)
        assert len(results) > 0
        assert any(str(similar_file) in str(r[0]) for r in results)


def test_try_find_similar_files():
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        test_file = temp_path / "test_file.mp3"
        similar_file = temp_path / "test_file_2.mp3"
        different_file = temp_path / "different.txt"

        test_file.touch()
        similar_file.touch()
        different_file.touch()

        results = try_find_similar_files(str(test_file), temp_path)
        assert len(results) > 0
        assert any(str(similar_file) in str(r) for r in results)


def test_process_input_file():
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        test_file = temp_path / "test.mp3"

        with open(test_file, "wb") as f:
            f.write(b"\xff\xfb\x90\x64\x00")

        result = process_input_file(str(test_file))
        assert result == test_file

        with pytest.raises(MinimaxMcpError):
            process_input_file(str(temp_path / "nonexistent.mp3"))

```

--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Bad case about the model.yml:
--------------------------------------------------------------------------------

```yaml
name: Bad Case Report of the model
description: Report a bug related to the model to help us reproduce and fix the problem.
title: "[BadCase about the model]: "

body:
  - type: markdown
    attributes:
      value: |
        Thank you for contributing to our project by reporting a bad case! To help us understand and resolve the issue as quickly as possible, please provide the following details.

  - type: input
    id: models-used
    attributes:
      label: Basic Information - Models Used
      description: |
        Please list the model used, e.g., MiniMax-M1, speech-02-hd, etc.
        (Note: You can refer to our models at [HuggingFace](https://huggingface.co/MiniMaxAI) or [the official site](https://www.minimax.io/platform_overview) for more details.)
      placeholder: "ex: MiniMax-M1"
    validations:
      required: true

  - type: input
    id: scenario-description
    attributes:
      label: Basic Information - Scenario Description
      description: |
        Please briefly describe the scenario, including the framework or the platform.
      placeholder: "ex: Minimax-M1 return the error related to xxx."
    validations:
      required: false

  - type: checkboxes
    id: problem-validation
    attributes:
      label: Is this badcase known and solvable?
      options:
        - label: "I have followed the [GitHub README](https://github.com/MiniMax-AI) of the model and found no duplicates in existing issues."
          required: true
        - label: "I have checked [Minimax documentation](https://www.minimax.io/platform_overview) and found no solution."
          required: true
          
  - type: textarea
    id: environment-info
    attributes:
      label: Information about environment
      description: |
        (Include software versions, OS, GPUs if applicable)
      placeholder: |
        For example:
        - OS: Ubuntu 24.04
        - Python: Python 3.11
        - PyTorch: 2.6.0+cu124
    validations:
      required: true

  - type: textarea
    id: call-execution-info # Consolidated field for call type and details
    attributes:
      label: Call & Execution Information
      description: |
        Please describe how you are interacting with the model and provide the relevant details in the box below:
        **Call Type**: (e.g., API Call, Deployment Call)
        **If API Call**: Please provide the `trace-ID` of the problematic request.
        **If Deployment Call**: Please provide the command used for deployment or inference.
      placeholder: |
        # Example for API Call:
        Call Type: API Call
        Trace-ID: abcdef1234567890

        # Example for Deployment Call:
        Call Type: Deployment Call
        Deployment Command: python run_inference.py --model my_model --config config.yaml
    validations:
      required: true

  - type: textarea
    id: description-of-bug
    attributes:
      label: Description
      description: |
        Please **describe the bad case** you have encountered and **paste the screenshots** if available.
        The following template is recommended (modify as needed):
      value: |
        ### Steps to reproduce
        The bug can be reproduced with the following steps:
        1. ...
        2. ...

        ### Expected behavior
        The results are expected to be: ...

        ### Actual behavior
        The actual outputs are as follows: ...

        ### Error logs
        The error logs are as follows:
        ```
        # Paste the related screenshots here
        ```
    validations:
      required: true

```

--------------------------------------------------------------------------------
/minimax_mcp/client.py:
--------------------------------------------------------------------------------

```python
"""Minimax API client base class."""

import requests
from typing import Any, Dict
from minimax_mcp.exceptions import MinimaxAuthError, MinimaxRequestError

class MinimaxAPIClient:
    """Base client for making requests to Minimax API."""
    
    def __init__(self, api_key: str, api_host: str):
        """Initialize the API client.
        
        Args:
            api_key: The API key for authentication
            api_host: The API host URL
        """
        self.api_key = api_key
        self.api_host = api_host
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'MM-API-Source': 'Minimax-MCP'
        })

    def _make_request(
        self, 
        method: str, 
        endpoint: str, 
        **kwargs
    ) -> Dict[str, Any]:
        """Make an HTTP request to the Minimax API.
        
        Args:
            method: HTTP method (GET, POST, etc.)
            endpoint: API endpoint path
            **kwargs: Additional arguments to pass to requests
            
        Returns:
            API response data as dictionary
            
        Raises:
            MinimaxAuthError: If authentication fails
            MinimaxRequestError: If the request fails
        """
        url = f"{self.api_host}{endpoint}"
        
        # Set Content-Type based on whether files are being uploaded
        files = kwargs.get('files')
        if not files:
            self.session.headers['Content-Type'] = 'application/json'
        else:
            # Remove Content-Type header for multipart/form-data
            # requests library will set it automatically with the correct boundary
            self.session.headers.pop('Content-Type', None)
        
        try:
            response = self.session.request(method, url, **kwargs)
            
            # Check for other HTTP errors
            response.raise_for_status()
            
            data = response.json()
            
            # Check API-specific error codes
            base_resp = data.get("base_resp", {})
            if base_resp.get("status_code") != 0:
                match base_resp.get("status_code"):
                    case 1004:
                        raise MinimaxAuthError(
                            f"API Error: {base_resp.get('status_msg')}, please check your API key and API host."
                            f"Trace-Id: {response.headers.get('Trace-Id')}"
                        )
                    case 2038:
                        raise MinimaxRequestError(
                            f"API Error: {base_resp.get('status_msg')}, should complete real-name verification on the open-platform(https://platform.minimaxi.com/user-center/basic-information)."
                            f"Trace-Id: {response.headers.get('Trace-Id')}"
                        )
                    case _:
                        raise MinimaxRequestError(
                            f"API Error: {base_resp.get('status_code')}-{base_resp.get('status_msg')} "
                            f"Trace-Id: {response.headers.get('Trace-Id')}"
                        )
                
            return data
            
        except requests.exceptions.RequestException as e:
            raise MinimaxRequestError(f"Request failed: {str(e)}")
            
    def get(self, endpoint: str, **kwargs) -> Dict[str, Any]:
        """Make a GET request."""
        return self._make_request("GET", endpoint, **kwargs)
        
    def post(self, endpoint: str, **kwargs) -> Dict[str, Any]:
        """Make a POST request."""
        return self._make_request("POST", endpoint, **kwargs) 
```

--------------------------------------------------------------------------------
/minimax_mcp/utils.py:
--------------------------------------------------------------------------------

```python
import os
from pathlib import Path
from datetime import datetime
from fuzzywuzzy import fuzz
import shutil
import subprocess
from typing import Iterator, Union
from minimax_mcp.const import *
from minimax_mcp.exceptions import MinimaxMcpError


def is_file_writeable(path: Path) -> bool:
    if path.exists():
        return os.access(path, os.W_OK)
    parent_dir = path.parent
    return os.access(parent_dir, os.W_OK)


def build_output_file(
    tool: str, text: str, output_path: Path, extension: str, full_id: bool = False
) -> Path:
    id = text if full_id else text[:10]

    output_file_name = f"{tool}_{id.replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{extension}"
    return output_path / output_file_name


def build_output_path(
    output_directory: str | None, base_path: str | None = None, is_test: bool = False
) -> Path:
    # Set default base_path to desktop if not provided
    if base_path is None:
        base_path = str(Path.home() / "Desktop")
    
    # Handle output path based on output_directory
    if output_directory is None:
        output_path = Path(os.path.expanduser(base_path))
    elif not os.path.isabs(os.path.expanduser(output_directory)):
        output_path = Path(os.path.expanduser(base_path)) / Path(output_directory)
    else:
        output_path = Path(os.path.expanduser(output_directory))

    # Safety checks and directory creation
    if is_test:
        return output_path
    if not is_file_writeable(output_path):
        raise MinimaxMcpError(f"Directory ({output_path}) is not writeable")
    output_path.mkdir(parents=True, exist_ok=True)
    return output_path


def find_similar_filenames(
    target_file: str, directory: Path, threshold: int = 70
) -> list[tuple[str, int]]:
    """
    Find files with names similar to the target file using fuzzy matching.

    Args:
        target_file (str): The reference filename to compare against
        directory (str): Directory to search in (defaults to current directory)
        threshold (int): Similarity threshold (0 to 100, where 100 is identical)

    Returns:
        list: List of similar filenames with their similarity scores
    """
    target_filename = os.path.basename(target_file)
    similar_files = []
    for root, _, files in os.walk(directory):
        for filename in files:
            if (
                filename == target_filename
                and os.path.join(root, filename) == target_file
            ):
                continue
            similarity = fuzz.token_sort_ratio(target_filename, filename)

            if similarity >= threshold:
                file_path = Path(root) / filename
                similar_files.append((file_path, similarity))

    similar_files.sort(key=lambda x: x[1], reverse=True)

    return similar_files


def try_find_similar_files(
    filename: str, directory: Path, take_n: int = 5
) -> list[Path]:
    similar_files = find_similar_filenames(filename, directory)
    if not similar_files:
        return []

    filtered_files = []

    for path, _ in similar_files[:take_n]:
        if check_audio_file(path):
            filtered_files.append(path)

    return filtered_files


def check_audio_file(path: Path) -> bool:
    audio_extensions = {
        ".wav",
        ".mp3",
        ".m4a",
        ".aac",
        ".ogg",
        ".flac",
        ".mp4",
        ".avi",
        ".mov",
        ".wmv",
    }
    return path.suffix.lower() in audio_extensions


def process_input_file(file_path: str, audio_content_check: bool = True) -> Path:
    if not os.path.isabs(file_path) and not os.environ.get(ENV_MINIMAX_MCP_BASE_PATH):
        raise MinimaxMcpError(
            "File path must be an absolute path if MINIMAX_MCP_BASE_PATH is not set"
        )
    path = Path(file_path)
    if not path.exists() and path.parent.exists():
        parent_directory = path.parent
        similar_files = try_find_similar_files(path.name, parent_directory)
        similar_files_formatted = ",".join([str(file) for file in similar_files])
        if similar_files:
            raise MinimaxMcpError(
                f"File ({path}) does not exist. Did you mean any of these files: {similar_files_formatted}?"
            )
        raise MinimaxMcpError(f"File ({path}) does not exist")
    elif not path.exists():
        raise MinimaxMcpError(f"File ({path}) does not exist")
    elif not path.is_file():
        raise MinimaxMcpError(f"File ({path}) is not a file")

    if audio_content_check and not check_audio_file(path):
        raise MinimaxMcpError(f"File ({path}) is not an audio or video file")
    return path


def is_installed(lib_name: str) -> bool:
    return shutil.which(lib_name) is not None


def play(
    audio: Union[bytes, Iterator[bytes]]
) -> None:
    if isinstance(audio, Iterator):
        audio = b"".join(audio)

    if not is_installed("ffplay"):
        message = (
            "ffplay from ffmpeg not found, necessary to play audio. "
            "mac: install it with 'brew install ffmpeg'. "
            "linux or windows: install it from https://ffmpeg.org/"
        )
        raise ValueError(message)
    
    args = ["ffplay", "-autoexit", "-", "-nodisp"]
    proc = subprocess.Popen(
        args=args,
        stdout=subprocess.PIPE,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    out, err = proc.communicate(input=audio)

    proc.poll()



```

--------------------------------------------------------------------------------
/README-CN.md:
--------------------------------------------------------------------------------

```markdown
![export](https://github.com/MiniMax-AI/MiniMax-01/raw/main/figures/MiniMaxLogo-Light.png)

<div align="center" style="line-height: 1;">
  <a href="https://www.minimax.io" target="_blank" style="margin: 2px; color: var(--fgColor-default);">
    <img alt="Homepage" src="https://img.shields.io/badge/_Homepage-MiniMax-FF4040?style=flat-square&labelColor=2C3E50&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNDkwLjE2IDQxMS43Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjMzLjQ1LDQwLjgxYTE3LjU1LDE3LjU1LDAsMSwwLTM1LjEsMFYzMzEuNTZhNDAuODIsNDAuODIsMCwwLDEtODEuNjMsMFYxNDVhMTcuNTUsMTcuNTUsMCwxLDAtMzUuMDksMHY3OS4wNmE0MC44Miw0MC44MiwwLDAsMS04MS42MywwVjE5NS40MmExMS42MywxMS42MywwLDAsMSwyMy4yNiwwdjI4LjY2YTE3LjU1LDE3LjU1LDAsMCwwLDM1LjEsMFYxNDVBNDAuODIsNDAuODIsMCwwLDEsMTQwLDE0NVYzMzEuNTZhMTcuNTUsMTcuNTUsMCwwLDAsMzUuMSwwVjIxNy41aDBWNDAuODFhNDAuODEsNDAuODEsMCwxLDEsODEuNjIsMFYyODEuNTZhMTEuNjMsMTEuNjMsMCwxLDEtMjMuMjYsMFptMjE1LjksNjMuNEE0MC44Niw0MC44NiwwLDAsMCw0MDguNTMsMTQ1VjMwMC44NWExNy41NSwxNy41NSwwLDAsMS0zNS4wOSwwdi0yNjBhNDAuODIsNDAuODIsMCwwLDAtODEuNjMsMFYzNzAuODlhMTcuNTUsMTcuNTUsMCwwLDEtMzUuMSwwVjMzMGExMS42MywxMS42MywwLDEsMC0yMy4yNiwwdjQwLjg2YTQwLjgxLDQwLjgxLDAsMCwwLDgxLjYyLDBWNDAuODFhMTcuNTUsMTcuNTUsMCwwLDEsMzUuMSwwdjI2MGE0MC44Miw0MC44MiwwLDAsMCw4MS42MywwVjE0NWExNy41NSwxNy41NSwwLDEsMSwzNS4xLDBWMjgxLjU2YTExLjYzLDExLjYzLDAsMCwwLDIzLjI2LDBWMTQ1QTQwLjg1LDQwLjg1LDAsMCwwLDQ0OS4zNSwxMDQuMjFaIi8+PC9zdmc+&logoWidth=20" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://arxiv.org/abs/2501.08313" target="_blank" style="margin: 2px;">
    <img alt="Paper" src="https://img.shields.io/badge/📖_Paper-MiniMax--01-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
   <a href="https://chat.minimax.io/" target="_blank" style="margin: 2px;">
    <img alt="Chat" src="https://img.shields.io/badge/_MiniMax_Chat-FF4040?style=flat-square&labelColor=2C3E50&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNDkwLjE2IDQxMS43Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9PC9zdHlsZT48L2RlZnM+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjMzLjQ1LDQwLjgxYTE3LjU1LDE3LjU1LDAsMSwwLTM1LjEsMFYzMzEuNTZhNDAuODIsNDAuODIsMCwwLDEtODEuNjMsMFYxNDVhMTcuNTUsMTcuNTUsMCwxLDAtMzUuMDksMHY3OS4wNmE0MC44Miw0MC44MiwwLDAsMS04MS42MywwVjE5NS40MmExMS42MywxMS42MywwLDAsMSwyMy4yNiwwdjI4LjY2YTE3LjU1LDE3LjU1LDAsMCwwLDM1LjEsMFYxNDVBNDAuODIsNDAuODIsMCwwLDEsMTQwLDE0NVYzMzEuNTZhMTcuNTUsMTcuNTUsMCwwLDAsMzUuMSwwVjIxNy41aDBWNDAuODFhNDAuODEsNDAuODEsMCwxLDEsODEuNjIsMFYyODEuNTZhMTEuNjMsMTEuNjMsMCwxLDEtMjMuMjYsMFptMjE1LjksNjMuNEE0MC44Niw0MC44NiwwLDAsMCw0MDguNTMsMTQ1VjMwMC44NWExNy41NSwxNy41NSwwLDAsMS0zNS4wOSwwdi0yNjBhNDAuODIsNDAuODIsMCwwLDAtODEuNjMsMFYzNzAuODlhMTcuNTUsMTcuNTUsMCwwLDEtMzUuMSwwVjMzMGExMS42MywxMS42MywwLDEsMC0yMy4yNiwwdjQwLjg2YTQwLjgxLDQwLjgxLDAsMCwwLDgxLjYyLDBWNDAuODFhMTcuNTUsMTcuNTUsMCwwLDEsMzUuMSwwdjI2MGE0MC44Miw0MC44MiwwLDAsMCw4MS42MywwVjE0NWExNy41NSwxNy41NSwwLDEsMSwzNS4xLDBWMjgxLjU2YTExLjYzLDExLjYzLDAsMCwwLDIzLjI2LDBWMTQ1QTQwLjg1LDQwLjg1LDAsMCwwLDQ0OS4zNSwxMDQuMjFaIi8+PC9zdmc+&logoWidth=20" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://www.minimax.io/platform" style="margin: 2px;">
    <img alt="API" src="https://img.shields.io/badge/⚡_API-Platform-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>  
</div>
<div align="center" style="line-height: 1;">
  <a href="https://huggingface.co/MiniMaxAI" target="_blank" style="margin: 2px;">
    <img alt="Hugging Face" src="https://img.shields.io/badge/🤗_Hugging_Face-MiniMax-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://github.com/MiniMax-AI/MiniMax-AI.github.io/blob/main/images/wechat-qrcode.jpeg" target="_blank" style="margin: 2px;">
    <img alt="WeChat" src="https://img.shields.io/badge/_WeChat-MiniMax-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
  <a href="https://www.modelscope.cn/organization/MiniMax" target="_blank" style="margin: 2px;">
    <img alt="ModelScope" src="https://img.shields.io/badge/_ModelScope-MiniMax-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
</div>
<div align="center" style="line-height: 1;">
   <a href="https://github.com/MiniMax-AI/MiniMax-MCP/blob/main/LICENSE" style="margin: 2px;">
    <img alt="Code License" src="https://img.shields.io/badge/_Code_License-MIT-FF4040?style=flat-square&labelColor=2C3E50" style="display: inline-block; vertical-align: middle;"/>
  </a>
</div>

<p align="center" style="line-height: 1.5; font-size: 18px; margin: 4px auto; text-decoration: underline;"><a href="README.md">English Version</a></p>

<p align="center">
  MiniMax官方模型上下文协议(MCP)服务器,支持与强大的文本转语音和视频/图像生成API交互。允许MCP客户端如<a href="https://www.anthropic.com/claude">Claude Desktop</a>、<a href="https://www.cursor.so">Cursor</a>、<a href="https://codeium.com/windsurf">Windsurf</a>、<a href="https://github.com/openai/openai-agents-python">OpenAI Agents</a>等生成语音、克隆声音、生成视频、生成图像等功能。
</p>

## Documentation
- [English Documentation](README.md)
- [MiniMax-MCP-JS](https://github.com/MiniMax-AI/MiniMax-MCP-JS) - MiniMax MCP的官方JavaScript版本

## 快速开始使用 MCP 客户端
1. 从[MiniMax国内开放平台](https://platform.minimaxi.com/user-center/basic-information/interface-key)|[MiniMax国际开放平台](https://www.minimax.io/platform/user-center/basic-information/interface-key)获取你的 API 密钥。
2. 安装`uv`(Python包管理器),使用`curl -LsSf https://astral.sh/uv/install.sh | sh`安装或查看`uv` [仓库](https://github.com/astral-sh/uv)获取其他安装方法。
3. **重要提示: API的服务器地址和密钥在不同区域有所不同**,两者需要匹配,否则会有 `invalid api key` 的错误

|地区| 国际  | 国内  |
|:--|:-----|:-----|
|MINIMAX_API_KEY| 获取密钥 [MiniMax国际版](https://www.minimax.io/platform/user-center/basic-information/interface-key) | 获取密钥 [MiniMax](https://platform.minimaxi.com/user-center/basic-information/interface-key) |
|MINIMAX_API_HOST| https://api.minimax.io | https://api.minimaxi.com |


### Claude Desktop
前往`Claude > Settings > Developer > Edit Config > claude_desktop_config.json`包含以下内容:

```
{
  "mcpServers": {
    "MiniMax": {
      "command": "uvx",
      "args": [
        "minimax-mcp"
      ],
      "env": {
        "MINIMAX_API_KEY": "填写你的API密钥",
        "MINIMAX_MCP_BASE_PATH": "本地输出目录路径,如/User/xxx/Desktop",
        "MINIMAX_API_HOST": "填写API Host, https://api.minimaxi.com 或 https://api.minimax.io",
        "MINIMAX_API_RESOURCE_MODE": "可选配置,资源生成后的提供方式, 可选项为 [url|local], 默认为 url"
      }
    }
  }
}
```


⚠️ 注意:API Key需要与Host匹配。如果出现"API Error: invalid api key"错误,请检查您的API Host:
- 国际版Host:`https://api.minimax.io`
- 国内版Host:`https://api.minimaxi.com` 

如果你使用Windows,你需要在Claude Desktop中启用"开发者模式"才能使用MCP服务器。点击左上角汉堡菜单中的"Help",然后选择"Enable Developer Mode"。


### Cursor
前往`Cursor -> Preferences -> Cursor Settings -> MCP -> Add new global MCP Server`添加上述配置。

你的MCP客户端现在可以通过Claude Desktop和Cursor等这些工具与MiniMax交互:

## Transport
我们支持两种传输方式: stdio and sse.
| stdio  | SSE  |
|:-----|:-----|
| 在本地部署运行 | 本地或云端部署均可  |
|通过 stdout 进行通信| 通过网络通信|
|输入:支持处理本地文件,或有效的URL资源| 输入: 若部署在云端,建议使用URL进行输入|

## 可用方法
| 方法  | 描述  |
|-|-|
|`text_to_audio`|使用指定音色将文本生成音频|
|`list_voices`|查询所有可用音色|
|`voice_clone`|根据指定音频文件克隆音色|
|`generate_video`|根据指定 prompt 生成视频|
|`text_to_image`|根据指定 prompt 生成图片|
|`music_generation`|根据指定 prompt 和歌词生成音乐|
|`voice_design`|根据指定 prompt 生成音色和试听文本|

## 更新日志

### 2025年7月2日

#### 🆕 新增功能
- **音色设计**: 新增 `voice_design` 工具 - 根据描述性提示词创建自定义音色并生成试听音频
- **视频生成增强**: 新增 `MiniMax-Hailuo-02` 模型,支持超清画质和时长/分辨率控制
- **音乐生成**: 采用 `music-1.5` 模型增强 `music_generation` 工具

#### 📈 功能增强
- `voice_design` - 根据文本描述生成个性化音色
- `generate_video` - 现在支持 MiniMax-Hailuo-02 模型,可选择 6s/10s 时长和 768P/1080P 分辨率
- `music_generation` - 采用 music-1.5 模型进行高质量音乐创作

## FAQ
### 1. invalid api key
请检查你获取的 API Key 和填写的 API Host 是否是同一地区的:
|地区| 国际  | 国内  |
|:--|:-----|:-----|
|MINIMAX_API_KEY| 获取密钥 [MiniMax国际版](https://www.minimax.io/platform/user-center/basic-information/interface-key) | 获取密钥 [MiniMax](https://platform.minimaxi.com/user-center/basic-information/interface-key) |
|MINIMAX_API_HOST| https://api.minimax.io | https://api.minimaxi.com

### 2. spawn uvx ENOENT
请在你的终端输入一下命令,查看uvx命令的绝对路径:
```sh
which uvx
```
如果得到如下的输出 (如:/usr/local/bin/uvx),更新mcp配置 ("command": "/usr/local/bin/uvx"). 

### 3. 如何用 `generate_video` 工具异步生成视频
在对话前设置一些规则:
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/cursor_rule2.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>
或者放到本地客户端的规则中 (以 Cursor 为例):
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/cursor_video_rule.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>


## 使用示例

⚠️ 注意:使用这些工具可能会产生费用。

### 1. 播报晚间新闻片段
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_20-07-53.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>

### 2. 克隆声音
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_19-45-13.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>

### 3. 生成视频
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_19-58-52.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/Snipaste_2025-04-09_19-59-43.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle; "/>

### 4. 生成图像
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/gen_image.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle;"/>
<img src="https://public-cdn-video-data-algeng.oss-cn-wulanchabu.aliyuncs.com/gen_image1.png?x-oss-process=image/resize,p_50/format,webp" style="display: inline-block; vertical-align: middle; "/>

```

--------------------------------------------------------------------------------
/minimax_mcp/server.py:
--------------------------------------------------------------------------------

```python
"""
MiniMax MCP Server

⚠️ IMPORTANT: This server connects to Minimax API endpoints which may involve costs.
Any tool that makes an API call is clearly marked with a cost warning. Please follow these guidelines:

1. Only use these tools when users specifically ask for them
2. For audio generation tools, be mindful that text length affects the cost
3. Voice cloning features are charged upon first use after cloning

Note: Tools without cost warnings are free to use as they only read existing data.
"""

import os
import base64
import requests
import time
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP
from mcp.types import TextContent
from minimax_mcp.utils import (
    build_output_path,
    build_output_file,
    process_input_file,
    play
)
from pathlib import Path

from minimax_mcp.const import *
from minimax_mcp.exceptions import MinimaxAPIError, MinimaxRequestError
from minimax_mcp.client import MinimaxAPIClient

load_dotenv()
api_key = os.getenv(ENV_MINIMAX_API_KEY)
base_path = os.getenv(ENV_MINIMAX_MCP_BASE_PATH) or "~/Desktop"
api_host = os.getenv(ENV_MINIMAX_API_HOST)
resource_mode = os.getenv(ENV_RESOURCE_MODE) or RESOURCE_MODE_URL
fastmcp_log_level = os.getenv(ENV_FASTMCP_LOG_LEVEL) or "WARNING"

if not api_key:
    raise ValueError("MINIMAX_API_KEY environment variable is required")
if not api_host:
    raise ValueError("MINIMAX_API_HOST environment variable is required")

mcp = FastMCP("Minimax",log_level=fastmcp_log_level)
api_client = MinimaxAPIClient(api_key, api_host)


@mcp.tool(
    description="""Convert text to audio with a given voice and save the output audio file to a given directory.
    Directory is optional, if not provided, the output file will be saved to $HOME/Desktop.
    Voice id is optional, if not provided, the default voice will be used.

    COST WARNING: This tool makes an API call to Minimax which may incur costs. Only use when explicitly requested by the user.

    Args:
        text (str): The text to convert to speech.
        voice_id (str, optional): The id of the voice to use. For example, "male-qn-qingse"/"audiobook_female_1"/"cute_boy"/"Charming_Lady"...
        model (string, optional): The model to use.
        speed (float, optional): Speed of the generated audio. Controls the speed of the generated speech. Values range from 0.5 to 2.0, with 1.0 being the default speed. 
        vol (float, optional): Volume of the generated audio. Controls the volume of the generated speech. Values range from 0 to 10, with 1 being the default volume.
        pitch (int, optional): Pitch of the generated audio. Controls the speed of the generated speech. Values range from -12 to 12, with 0 being the default speed.
        emotion (str, optional): Emotion of the generated audio. Controls the emotion of the generated speech. Values range ["happy", "sad", "angry", "fearful", "disgusted", "surprised", "neutral"], with "happy" being the default emotion.
        sample_rate (int, optional): Sample rate of the generated audio. Controls the sample rate of the generated speech. Values range [8000,16000,22050,24000,32000,44100] with 32000 being the default sample rate.
        bitrate (int, optional): Bitrate of the generated audio. Controls the bitrate of the generated speech. Values range [32000,64000,128000,256000] with 128000 being the default bitrate.
        channel (int, optional): Channel of the generated audio. Controls the channel of the generated speech. Values range [1, 2] with 1 being the default channel.
        format (str, optional): Format of the generated audio. Controls the format of the generated speech. Values range ["pcm", "mp3","flac"] with "mp3" being the default format.
        language_boost (str, optional): Language boost of the generated audio. Controls the language boost of the generated speech. Values range ['Chinese', 'Chinese,Yue', 'English', 'Arabic', 'Russian', 'Spanish', 'French', 'Portuguese', 'German', 'Turkish', 'Dutch', 'Ukrainian', 'Vietnamese', 'Indonesian', 'Japanese', 'Italian', 'Korean', 'Thai', 'Polish', 'Romanian', 'Greek', 'Czech', 'Finnish', 'Hindi', 'auto'] with "auto" being the default language boost.
        output_directory (str): The directory to save the audio to.

    Returns:
        Text content with the path to the output file and name of the voice used.
    """
)
def text_to_audio(
    text: str,
    output_directory: str = None,
    voice_id: str = DEFAULT_VOICE_ID,
    model: str = DEFAULT_SPEECH_MODEL,
    speed: float = DEFAULT_SPEED,
    vol: float = DEFAULT_VOLUME,
    pitch: int = DEFAULT_PITCH,
    emotion: str = DEFAULT_EMOTION,
    sample_rate: int = DEFAULT_SAMPLE_RATE,
    bitrate: int = DEFAULT_BITRATE,
    channel: int = DEFAULT_CHANNEL,
    format: str = DEFAULT_FORMAT,
    language_boost: str = DEFAULT_LANGUAGE_BOOST,
):
    if not text:
        raise MinimaxRequestError("Text is required.")

    payload = {
        "model": model,
        "text": text,
        "voice_setting": {
            "voice_id": voice_id,
            "speed": speed,
            "vol": vol,
            "pitch": pitch,
            "emotion": emotion
        },
        "audio_setting": {
            "sample_rate": sample_rate,
            "bitrate": bitrate,
            "format": format,
            "channel": channel
        },
        "language_boost": language_boost
    }
    if resource_mode == RESOURCE_MODE_URL:
        payload["output_format"] = "url"
    try:
        response_data = api_client.post("/v1/t2a_v2", json=payload)
        audio_data = response_data.get('data', {}).get('audio', '')
        
        if not audio_data:
            raise MinimaxRequestError(f"Failed to get audio data from response")
        if resource_mode == RESOURCE_MODE_URL:
            return TextContent(
                type="text",
                text=f"Success. Audio URL: {audio_data}"
            )
        # hex->bytes
        audio_bytes = bytes.fromhex(audio_data)

        # save audio to file
        output_path = build_output_path(output_directory, base_path)
        output_file_name = build_output_file("t2a", text, output_path, format)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_path / output_file_name, "wb") as f:
            f.write(audio_bytes)

        return TextContent(
            type="text",
            text=f"Success. File saved as: {output_path / output_file_name}. Voice used: {voice_id}",
        )
        
    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to generate audio: {str(e)}"
        )


@mcp.tool(
    description="""List all voices available.

    Args:
        voice_type (str, optional): The type of voices to list. Values range ["all", "system", "voice_cloning"], with "all" being the default.
    Returns:
        Text content with the list of voices.
    """
)
def list_voices(
    voice_type: str = "all"
):
    try:
        response_data = api_client.post("/v1/get_voice", json={'voice_type': voice_type})
        
        system_voices = response_data.get('system_voice', []) or []
        voice_cloning_voices = response_data.get('voice_cloning', []) or []
        system_voice_list = []
        voice_cloning_voice_list = []
        
        for voice in system_voices:
            system_voice_list.append(f"Name: {voice.get('voice_name')}, ID: {voice.get('voice_id')}")
        for voice in voice_cloning_voices:
            voice_cloning_voice_list.append(f"Name: {voice.get('voice_name')}, ID: {voice.get('voice_id')}")

        return TextContent(
            type="text",
            text=f"Success. System Voices: {system_voice_list}, Voice Cloning Voices: {voice_cloning_voice_list}"
        )
        
    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to list voices: {str(e)}"
        )


@mcp.tool(
    description="""Clone a voice using provided audio files. The new voice will be charged upon first use.

    COST WARNING: This tool makes an API call to Minimax which may incur costs. Only use when explicitly requested by the user.

     Args:
        voice_id (str): The id of the voice to use.
        file (str): The path to the audio file to clone or a URL to the audio file.
        text (str, optional): The text to use for the demo audio.
        is_url (bool, optional): Whether the file is a URL. Defaults to False.
        output_directory (str): The directory to save the demo audio to.
    Returns:
        Text content with the voice id of the cloned voice.
    """
)
def voice_clone(
    voice_id: str, 
    file: str,
    text: str,
    output_directory: str = None,
    is_url: bool = False
) -> TextContent:
    try:
        # step1: upload file
        if is_url:
            # download file from url
            response = requests.get(file, stream=True)
            response.raise_for_status()
            files = {'file': ('audio_file.mp3', response.raw, 'audio/mpeg')}
            data = {'purpose': 'voice_clone'}
            response_data = api_client.post("/v1/files/upload", files=files, data=data)
        else:
            # open and upload file
            if not os.path.exists(file):
                raise MinimaxRequestError(f"Local file does not exist: {file}")
            with open(file, 'rb') as f:
                files = {'file': f}
                data = {'purpose': 'voice_clone'}
                response_data = api_client.post("/v1/files/upload", files=files, data=data)
            
        file_id = response_data.get("file",{}).get("file_id")
        if not file_id:
            raise MinimaxRequestError(f"Failed to get file_id from upload response")

        # step2: clone voice
        payload = {
            "file_id": file_id,
            "voice_id": voice_id,
        }
        if text:
            payload["text"] = text
            payload["model"] = DEFAULT_SPEECH_MODEL

        response_data = api_client.post("/v1/voice_clone", json=payload)
        
        if not response_data.get("demo_audio"):
            return TextContent(
                type="text",
                text=f"Voice cloned successfully: Voice ID: {voice_id}"
            )
        if resource_mode == RESOURCE_MODE_URL:
            return TextContent(
                type="text",
                text=f"Success. Demo audio URL: {response_data.get('demo_audio')}"
            )
        # step3: download demo audio
        output_path = build_output_path(output_directory, base_path)
        output_file_name = build_output_file("voice_clone", text, output_path, "wav")
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_path / output_file_name, "wb") as f:
            f.write(requests.get(response_data.get("demo_audio")).content)

        return TextContent(
            type="text",
            text=f"Voice cloned successfully: Voice ID: {voice_id}, demo audio saved as: {output_path / output_file_name}"
        )
        
    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to clone voice: {str(e)}"
        )
    except (IOError, requests.RequestException) as e:
        return TextContent(
            type="text",
            text=f"Failed to handle files: {str(e)}"
        )


@mcp.tool(
    description="""Play an audio file. Supports WAV and MP3 formats. Not supports video.

     Args:
        input_file_path (str): The path to the audio file to play.
        is_url (bool, optional): Whether the audio file is a URL.
    Returns:
        Text content with the path to the audio file.
    """
)
def play_audio(input_file_path: str, is_url: bool = False) -> TextContent:
    if is_url:
        play(requests.get(input_file_path).content)
        return TextContent(type="text", text=f"Successfully played audio file: {input_file_path}")
    else:
        file_path = process_input_file(input_file_path)
        play(open(file_path, "rb").read())
        return TextContent(type="text", text=f"Successfully played audio file: {file_path}")


@mcp.tool(
    description="""Generate a video from a prompt.

    COST WARNING: This tool makes an API call to Minimax which may incur costs. Only use when explicitly requested by the user.

     Args:
        model (str, optional): The model to use. Values range ["T2V-01", "T2V-01-Director", "I2V-01", "I2V-01-Director", "I2V-01-live", "MiniMax-Hailuo-02"]. "Director" supports inserting instructions for camera movement control. "I2V" for image to video. "T2V" for text to video. "MiniMax-Hailuo-02" is the latest model with best effect, ultra-clear quality and precise response.
        prompt (str): The prompt to generate the video from. When use Director model, the prompt supports 15 Camera Movement Instructions (Enumerated Values)
            -Truck: [Truck left], [Truck right]
            -Pan: [Pan left], [Pan right]
            -Push: [Push in], [Pull out]
            -Pedestal: [Pedestal up], [Pedestal down]
            -Tilt: [Tilt up], [Tilt down]
            -Zoom: [Zoom in], [Zoom out]
            -Shake: [Shake]
            -Follow: [Tracking shot]
            -Static: [Static shot]
        first_frame_image (str): The first frame image. The model must be "I2V" Series.
        duration (int, optional): The duration of the video. The model must be "MiniMax-Hailuo-02". Values can be 6 and 10.
        resolution (str, optional): The resolution of the video. The model must be "MiniMax-Hailuo-02". Values range ["768P", "1080P"]
        output_directory (str): The directory to save the video to.
        async_mode (bool, optional): Whether to use async mode. Defaults to False. If True, the video generation task will be submitted asynchronously and the response will return a task_id. Should use `query_video_generation` tool to check the status of the task and get the result.
    Returns:
        Text content with the path to the output video file.
    """
)
def generate_video(
    model: str = DEFAULT_T2V_MODEL,
    prompt: str = "",
    first_frame_image  = None,
    duration: int = None,
    resolution: str = None,
    output_directory: str = None,
    async_mode: bool = False
):
    try:
        if not prompt:
            raise MinimaxRequestError("Prompt is required")

        # check first_frame_image
        if first_frame_image:
            if not isinstance(first_frame_image, str):
                raise MinimaxRequestError(f"First frame image must be a string, got {type(first_frame_image)}")
            if not first_frame_image.startswith(("http://", "https://", "data:")):
                # if local image, convert to dataurl
                if not os.path.exists(first_frame_image):
                    raise MinimaxRequestError(f"First frame image does not exist: {first_frame_image}")
                with open(first_frame_image, "rb") as f:
                    image_data = f.read()
                    first_frame_image = f"data:image/jpeg;base64,{base64.b64encode(image_data).decode('utf-8')}"

        # step1: submit video generation task
        payload = {
            "model": model,
            "prompt": prompt
        }
        if first_frame_image:
            payload["first_frame_image"] = first_frame_image
        if duration:
            payload["duration"] = duration
        if resolution:
            payload["resolution"] = resolution
        response_data = api_client.post("/v1/video_generation", json=payload)
        task_id = response_data.get("task_id")
        if not task_id:
            raise MinimaxRequestError("Failed to get task_id from response")

        if async_mode:
            return TextContent(
                type="text",
                text=f"Success. Video generation task submitted: Task ID: {task_id}. Please use `query_video_generation` tool to check the status of the task and get the result."
            )

        # step2: wait for video generation task to complete
        file_id = None
        max_retries = 30  # 10 minutes total (30 * 20 seconds)
        retry_interval = 20  # seconds


        # MiniMax-Hailuo-02 model has a longer processing time, so we need to wait for a longer time
        if model == "MiniMax-Hailuo-02":
            max_retries = 60

        for attempt in range(max_retries):
            status_response = api_client.get(f"/v1/query/video_generation?task_id={task_id}")
            status = status_response.get("status")
            
            if status == "Fail":
                raise MinimaxRequestError(f"Video generation failed for task_id: {task_id}")
            elif status == "Success":
                file_id = status_response.get("file_id")
                if file_id:
                    break
                raise MinimaxRequestError(f"Missing file_id in success response for task_id: {task_id}")
            
            # Still processing, wait and retry
            time.sleep(retry_interval)

        if not file_id:
            raise MinimaxRequestError(f"Failed to get file_id for task_id: {task_id}")

        # step3: fetch video result
        file_response = api_client.get(f"/v1/files/retrieve?file_id={file_id}")
        download_url = file_response.get("file", {}).get("download_url")
        
        if not download_url:
            raise MinimaxRequestError(f"Failed to get download URL for file_id: {file_id}")
        if resource_mode == RESOURCE_MODE_URL:
            return TextContent(
                type="text",
                text=f"Success. Video URL: {download_url}"
            )
        # step4: download and save video
        output_path = build_output_path(output_directory, base_path)
        output_file_name = build_output_file("video", task_id, output_path, "mp4", True)
        output_path.parent.mkdir(parents=True, exist_ok=True)

        video_response = requests.get(download_url)
        video_response.raise_for_status()
        
        with open(output_path / output_file_name, "wb") as f:
            f.write(video_response.content)

        return TextContent(
            type="text",
            text=f"Success. Video saved as: {output_path / output_file_name}"
        )

    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to generate video: {str(e)}"
        )
    except (IOError, requests.RequestException) as e:
        return TextContent(
            type="text",
            text=f"Failed to handle video file: {str(e)}"
        )
    except Exception as e:
        return TextContent(
            type="text",
            text=f"Unexpected error while generating video: {str(e)}"
        )


@mcp.tool(
    description="""Query the status of a video generation task.

    Args:
        task_id (str): The task ID to query. Should be the task_id returned by `generate_video` tool if `async_mode` is True.
        output_directory (str): The directory to save the video to.
    Returns:
        Text content with the status of the task.
    """
)
def query_video_generation(task_id: str, output_directory: str = None) -> TextContent:
    try:
        file_id = None
        response_data = api_client.get(f"/v1/query/video_generation?task_id={task_id}")
        status = response_data.get("status")
        if status == "Fail":
            return TextContent(
                type="text",
                text=f"Video generation FAILED for task_id: {task_id}"
            )
        elif status == "Success":
            file_id = response_data.get("file_id")
            if not file_id:
                raise MinimaxRequestError(f"Missing file_id in success response for task_id: {task_id}")
        else:
            return TextContent(
                type="text",
                text=f"Video generation task is still processing: Task ID: {task_id}"
            )
        file_response = api_client.get(f"/v1/files/retrieve?file_id={file_id}")
        download_url = file_response.get("file", {}).get("download_url")
        if not download_url:
            raise MinimaxRequestError(f"Failed to get download URL for file_id: {file_id}")
        if resource_mode == RESOURCE_MODE_URL:
            return TextContent(
                type="text",
                text=f"Success. Video URL: {download_url}"
            )
        output_path = build_output_path(output_directory, base_path)
        output_file_name = build_output_file("video", task_id, output_path, "mp4", True)
        output_path.parent.mkdir(parents=True, exist_ok=True)

        video_response = requests.get(download_url)
        video_response.raise_for_status()

        with open(output_path / output_file_name, "wb") as f:
            f.write(video_response.content)

        return TextContent(
            type="text",
            text=f"Success. Video saved as: {output_path / output_file_name}"
        )
    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to query video generation status: {str(e)}"
        )


@mcp.tool(
    description="""Generate a image from a prompt.

    COST WARNING: This tool makes an API call to Minimax which may incur costs. Only use when explicitly requested by the user.

     Args:
        model (str, optional): The model to use. Values range ["image-01"], with "image-01" being the default.
        prompt (str): The prompt to generate the image from.
        aspect_ratio (str, optional): The aspect ratio of the image. Values range ["1:1", "16:9","4:3", "3:2", "2:3", "3:4", "9:16", "21:9"], with "1:1" being the default.
        n (int, optional): The number of images to generate. Values range [1, 9], with 1 being the default.
        prompt_optimizer (bool, optional): Whether to optimize the prompt. Values range [True, False], with True being the default.
        output_directory (str): The directory to save the image to.
    Returns:
        Text content with the path to the output image file.
    """
)
def text_to_image(
    model: str = DEFAULT_T2I_MODEL,
    prompt: str = "",
    aspect_ratio: str = "1:1",
    n: int = 1,
    prompt_optimizer: bool = True,
    output_directory: str = None,
):
    try:
        if not prompt:
            raise MinimaxRequestError("Prompt is required")

        payload = {
            "model": model, 
            "prompt": prompt,
            "aspect_ratio": aspect_ratio,
            "n": n,
            "prompt_optimizer": prompt_optimizer
        }

        response_data = api_client.post("/v1/image_generation", json=payload)
        image_urls = response_data.get("data",{}).get("image_urls",[])
        
        if not image_urls:
            raise MinimaxRequestError("No images generated")
        if resource_mode == RESOURCE_MODE_URL:
            return TextContent(
                type="text",
                text=f"Success. Image URLs: {image_urls}"
            )
        output_path = build_output_path(output_directory, base_path)
        output_file_names = []
        
        for i, image_url in enumerate(image_urls):
            output_file_name = build_output_file("image", f"{i}_{prompt}", output_path, "jpg")
            output_path.parent.mkdir(parents=True, exist_ok=True)
            
            image_response = requests.get(image_url)
            image_response.raise_for_status()
            
            with open(output_file_name, 'wb') as f:
                f.write(image_response.content)
            output_file_names.append(output_file_name)
            
        return TextContent(
            type="text",
            text=f"Success. Images saved as: {output_file_names}"
        )
        
    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to generate images: {str(e)}"
        )
    except (IOError, requests.RequestException) as e:
        return TextContent(
            type="text",
            text=f"Failed to save images: {str(e)}"
        )

@mcp.tool(
    description="""Create a music generation task using AI models. Generate music from prompt and lyrics.

    COST WARNING: This tool makes an API call to Minimax which may incur costs. Only use when explicitly requested by the user.

    Args:
        prompt (str): Music creation inspiration describing style, mood, scene, etc.
            Example: "Pop music, sad, suitable for rainy nights". Character range: [10, 300]
        lyrics (str): Song lyrics for music generation.
            Use newline (\\n) to separate each line of lyrics. Supports lyric structure tags [Intro][Verse][Chorus][Bridge][Outro] 
            to enhance musicality. Character range: [10, 600] (each Chinese character, punctuation, and letter counts as 1 character)
        stream (bool, optional): Whether to enable streaming mode. Defaults to False
        sample_rate (int, optional): Sample rate of generated music. Values: [16000, 24000, 32000, 44100]
        bitrate (int, optional): Bitrate of generated music. Values: [32000, 64000, 128000, 256000]
        format (str, optional): Format of generated music. Values: ["mp3", "wav", "pcm"]. Defaults to "mp3"
        output_directory (str, optional): Directory to save the generated music file
        
    Note: Currently supports generating music up to 1 minute in length.

    Returns:
        Text content with the path to the generated music file or generation status.
    """
)
def music_generation(
    prompt: str,
    lyrics: str,
    sample_rate: int = DEFAULT_SAMPLE_RATE,
    bitrate: int = DEFAULT_BITRATE,
    format: str = DEFAULT_FORMAT,
    output_directory: str = None
) -> TextContent:
        try:
            # prompt and lyrics params check
            if not prompt:
                raise MinimaxRequestError("Prompt is required.")
            if not lyrics:
                raise MinimaxRequestError("Lyrics is required.")
            
            # Build request payload
            payload = {
                "model": DEFAULT_MUSIC_MODEL,
                "prompt": prompt,
                "lyrics": lyrics,
                "audio_setting": {
                    "sample_rate": sample_rate,
                    "bitrate": bitrate,
                    "format": format
                },
            }
            if resource_mode == RESOURCE_MODE_URL:
                payload["output_format"] = "url"

            # Call music generation API
            response_data = api_client.post("/v1/music_generation", json=payload)
                    
            # Handle response
            data = response_data.get('data', {})
            audio_hex = data.get('audio', '')

            if resource_mode == RESOURCE_MODE_URL:
                return TextContent(
                    type="text",
                    text=f"Success. Music url: {audio_hex}"
                )

            output_path = build_output_path(output_directory, base_path)
            output_file_name = build_output_file("music", f"{prompt}", output_path, format)
            output_path.parent.mkdir(parents=True, exist_ok=True)

            # hex->bytes
            audio_bytes = bytes.fromhex(audio_hex)

            # save audio to file
            with open(output_path / output_file_name, "wb") as f:
                f.write(audio_bytes)

            return TextContent(
                type="text",
                text=f"Success. Music saved as: {output_path / output_file_name}"
            )
        
        except MinimaxAPIError as e:
            return TextContent(
                type="text",
                text=f"Failed to generate music: {str(e)}"
            )
        except (IOError, requests.RequestException) as e:
            return TextContent(
                type="text",
                text=f"Failed to save music: {str(e)}"
        )

@mcp.tool(
    description="""Generate a voice based on description prompts.

    COST WARNING: This tool makes an API call to Minimax which may incur costs. Only use when explicitly requested by the user.

     Args:
        prompt (str): The prompt to generate the voice from.
        preview_text (str): The text to preview the voice.
        voice_id (str, optional): The id of the voice to use. For example, "male-qn-qingse"/"audiobook_female_1"/"cute_boy"/"Charming_Lady"...
        output_directory (str, optional): The directory to save the voice to.
    Returns:
        Text content with the path to the output voice file.
    """
)
def voice_design(
    prompt: str,
    preview_text: str,
    voice_id: str = None,
    output_directory: str = None,
):
    try:
        if not prompt:
            raise MinimaxRequestError("prompt is required")
        if not preview_text:
            raise MinimaxRequestError("preview_text is required")

       # Build request payload
        payload = {
            "prompt": prompt,
            "preview_text": preview_text
        }
        
        # Add voice_id if provided
        if voice_id:
            payload["voice_id"] = voice_id

        # Call voice design API
        response_data = api_client.post("/v1/voice_design", json=payload)

        # Get the response data
        generated_voice_id = response_data.get('voice_id', '')
        trial_audio_hex = response_data.get('trial_audio', '')
        
        if not generated_voice_id:
            raise MinimaxRequestError("No voice generated")
        if resource_mode == RESOURCE_MODE_URL:
            return TextContent(
                type="text",
                text=f"Success. Voice ID generated: {generated_voice_id}, Trial Audio: {trial_audio_hex}"
            )
        
        # hex->bytes
        audio_bytes = bytes.fromhex(trial_audio_hex)

        # save audio to file
        output_path = build_output_path(output_directory, base_path)
        output_file_name = build_output_file("voice_design", preview_text, output_path, "mp3")
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_path / output_file_name, "wb") as f:
            f.write(audio_bytes)

        return TextContent(
            type="text",
            text=f"Success. File saved as: {output_path / output_file_name}. Voice ID generated: {generated_voice_id}",
        )
        
    except MinimaxAPIError as e:
        return TextContent(
            type="text",
            text=f"Failed to design voice: {str(e)}"
        )

def main():
    print("Starting Minimax MCP server")
    """Run the Minimax MCP server"""
    mcp.run()


if __name__ == "__main__":
    main()

```