Treasure Data MCP Server

by knishioka

Integrations

  • Supports loading Treasure Data API credentials from a .env file as an alternative to environment variables.

Сервер MCP данных о сокровищах

Сервер протокола контекста модели (MCP), который обеспечивает интеграцию API Treasure Data для Claude Code и Claude Desktop, позволяя управлять базами данных и выполнять функции листинга.

Начиная

# Clone the repository git clone https://github.com/yourusername/td-mcp-server.git cd td-mcp-server

Аутентификация

Клиенту требуется ключ Treasure Data API для аутентификации. Вы можете предоставить его двумя способами:

  1. Установите переменную среды TD_API_KEY :
    export TD_API_KEY="your-api-key"
  2. Передайте его непосредственно команде:
    python -m td_mcp_server --api-key="your-api-key" list-databases

Использование

Интерфейс командной строки

Пакет предоставляет простой интерфейс командной строки для выполнения стандартных операций, которые можно использовать без установки:

Список баз данных
# Show only database names (default, first 30 databases) python -m td_mcp_server.cli_api list # Show detailed database information python -m td_mcp_server.cli_api list --verbose # Get only database names in JSON format python -m td_mcp_server.cli_api list --format json # Get detailed database information in JSON format python -m td_mcp_server.cli_api list --format json --verbose # Specify a different region endpoint python -m td_mcp_server.cli_api list --endpoint api.treasuredata.co.jp # Pagination options (default: limit=30, offset=0) python -m td_mcp_server.cli_api list --limit 10 --offset 20 # Get all databases regardless of the number python -m td_mcp_server.cli_api list --all
Получить информацию о конкретной базе данных
# Get JSON output (default) python -m td_mcp_server.cli_api get my_database_name # Get table output python -m td_mcp_server.cli_api get my_database_name --format table
Список таблиц в базе данных
# Show only table names (default, first 30 tables) python -m td_mcp_server.cli_api tables my_database_name # Show detailed table information python -m td_mcp_server.cli_api tables my_database_name --verbose # Get only table names in JSON format python -m td_mcp_server.cli_api tables my_database_name --format json # Get detailed table information in JSON format python -m td_mcp_server.cli_api tables my_database_name --format json --verbose # Pagination options (default: limit=30, offset=0) python -m td_mcp_server.cli_api tables my_database_name --limit 10 --offset 20 # Get all tables regardless of the number python -m td_mcp_server.cli_api tables my_database_name --all

API-интерфейс Python

Вы также можете использовать клиент непосредственно в своем коде Python:

from td_mcp_server.api import TreasureDataClient # Initialize client with API key from environment variable client = TreasureDataClient() # Or provide API key directly client = TreasureDataClient(api_key="your-api-key") # Get databases with pagination (default: first 30 databases) databases = client.get_databases(limit=30, offset=0) for db in databases: print(f"Database: {db.name}, Tables: {db.count}") # Get all databases regardless of the number all_databases = client.get_databases(all_results=True) for db in all_databases: print(f"Database: {db.name}, Tables: {db.count}") # Get information about a specific database db = client.get_database("my_database_name") if db: print(f"Found database: {db.name}") else: print("Database not found") # Get tables in a database with pagination (default: first 30 tables) tables = client.get_tables("my_database_name", limit=30, offset=0) for table in tables: print(f"Table: {table.name}, Type: {table.type}, Count: {table.count}") # Get all tables regardless of the number all_tables = client.get_tables("my_database_name", all_results=True) for table in all_tables: print(f"Table: {table.name}, Type: {table.type}, Count: {table.count}")

Конечные точки API

По умолчанию клиент использует конечную точку региона США ( api.treasuredata.com ). Если вам нужно использовать регион Япония, укажите конечную точку:

client = TreasureDataClient(endpoint="api.treasuredata.co.jp")
python -m td_mcp_server --endpoint=api.treasuredata.co.jp list-databases

Конфигурация сервера MCP

Этот сервер реализует протокол Model Context Protocol (MCP) для предоставления Клоду доступа к функционалу API Treasure Data. Он использует библиотеку FastMCP с подходом mcp.run(transport='stdio') для стандартной коммуникации MCP.

Запуск сервера MCP

Вы можете запустить сервер MCP с помощью стандартного интерфейса командной строки MCP:

# Using MCP CLI mcp run td_mcp_server/server.py

Серверу требуется ключ API Treasure Data, который должен быть предоставлен через переменную среды TD_API_KEY :

# Using environment variable export TD_API_KEY="your-api-key" mcp run td_mcp_server/server.py # For Claude Desktop integration, you can include the API key during installation mcp install td_mcp_server/server.py -v TD_API_KEY="your-api-key" -v TD_ENDPOINT="api.treasuredata.com"

Реализация FastMCP

Под капотом этот сервер использует библиотеку FastMCP , которая обеспечивает простую в использовании структуру для создания серверов MCP. Реализация:

  1. Создает экземпляр сервера FastMCP с именем «treasure-data»
  2. Использует декораторы функций ( @mcp.tool() ) для регистрации инструментов для операций с базами данных
  3. Инструменты реализованы как асинхронные функции с соответствующими аннотациями типов.
  4. Использует mcp.run(transport='stdio') для запуска сервера со стандартным вводом/выводом
  5. Автоматически обрабатывает запросы и ответы MCP с помощью библиотеки FastMCP

Реализация соответствует стандартному шаблону, рекомендованному в документации Model Context Protocol для серверов Python, что делает ее совместимой с Claude Desktop и другими клиентами MCP.

Настройка с помощью Клода Кода

Чтобы настроить этот сервер MCP для использования с Claude Code:

  1. Клонировать репозиторий
    git clone https://github.com/yourusername/td-mcp-server.git
  2. Установите свой ключ API Treasure Data как переменную среды
    export TD_API_KEY="your-api-key"
  3. Добавьте сервер MCP с помощью Claude Code CLI
    # Navigate to your project directory cd your-project-directory # Add the MCP server (use absolute path to server.py) claude mcp add td -e TD_API_KEY=${TD_API_KEY} -e TD_ENDPOINT=api.treasuredata.com -- mcp run /absolute/path/to/td-mcp-server/td_mcp_server/server.py
    Это создаст или обновит необходимую конфигурацию в файле .claude/plugins.json вашего проекта.
  4. При использовании Claude Code в проекте с этой конфигурацией вы получите доступ к следующим инструментам MCP:
    • mcp__td_list_databases : список баз данных в вашей учетной записи Treasure Data (по умолчанию только имена, добавьте verbose=True для получения полной информации, с параметрами разбиения на страницы limit , offset и all_results )
    • mcp__td_get_database : Получить информацию о конкретной базе данных
    • mcp__td_list_tables : список таблиц в определенной базе данных (по умолчанию только имена, добавьте verbose=True для получения полной информации, с параметрами разбиения на страницы limit , offset и all_results )

Настройка с помощью Claude Desktop

Чтобы настроить этот сервер MCP для использования с Claude Desktop:

  1. Клонировать репозиторий
    git clone https://github.com/yourusername/td-mcp-server.git
  2. Метод 1: Использование MCP CLI (рекомендуется)
    # Install the server with Claude Desktop using the MCP CLI mcp install /absolute/path/to/td-mcp-server/td_mcp_server/server.py -v TD_API_KEY="your-api-key" -v TD_ENDPOINT="api.treasuredata.com" # For Japan region mcp install /absolute/path/to/td-mcp-server/td_mcp_server/server.py -v TD_API_KEY="your-api-key" -v TD_ENDPOINT="api.treasuredata.co.jp"
  3. Метод 2: Использование пользовательского интерфейса Claude Desktop
    • Перейдите в Настройки > Инструменты MCP > Добавить новый инструмент.
    • Имя: API данных о сокровищах
    • Команда: mcp run /absolute/path/to/td-mcp-server/td_mcp_server/server.py
    • Переменные среды: добавьте TD_API_KEY и, при необходимости, TD_ENDPOINT
  4. Теперь вы можете использовать инструменты API Treasure Data в своих беседах Claude Desktop.

Использование инструментов MCP в Claude

После настройки вы можете использовать такие команды, как:

# Get only database names (default, first 30 databases) /mcp td_list_databases # Get full database details /mcp td_list_databases verbose=True # Pagination options (default: limit=30, offset=0) /mcp td_list_databases limit=10 offset=20 # Get all databases regardless of the number /mcp td_list_databases all_results=True
# Get information about a specific database /mcp td_get_database my_database_name
# Get only table names in a database (default, first 30 tables) /mcp td_list_tables database_name=my_database_name # Get detailed information about tables in a database /mcp td_list_tables database_name=my_database_name verbose=True # Pagination options (default: limit=30, offset=0) /mcp td_list_tables database_name=my_database_name limit=10 offset=20 # Get all tables regardless of the number /mcp td_list_tables database_name=my_database_name all_results=True

Разработка

Требования к окружающей среде

Для этого проекта требуется Python 3.11+ и следующие пакеты:

  • запросы >= 2.28.0
  • пидантический >= 2.0.0
  • mcp[cli] >= 1.8.1
  • нажмите >= 8.0.0, < 8.2.0
  • тип >= 0.9.0

Для разработки и тестирования:

  • pytest >= 7.0.0
  • pytest-mock >= 3.10.0
  • pytest-cov >= 4.0.0
  • ответы >= 0.23.0
  • черный >= 23.0.0
  • сортировка >= 5.12.0
  • mypy >= 1.0.0
  • ерш >= 0.0.270
  • предварительное обязательство >= 3.3.0

Проведение тестов

Этот проект использует pytest для модульного тестирования. Для запуска тестов:

# Create a virtual environment if you don't have one python -m venv .venv # Activate virtual environment source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install required dependencies pip install pytest pytest-mock pytest-cov responses pytest-asyncio # Run all tests python -m pytest # Run tests with coverage report python -m pytest --cov=td_mcp_server # Run tests for a specific module python -m pytest tests/unit/test_api.py # Run a specific test python -m pytest tests/unit/test_api.py::TestTreasureDataClient::test_get_databases # Run direct MCP integration tests python -m pytest tests/integration/test_direct_mcp.py ### Test Structure The tests are organized as follows: - `tests/unit/test_api.py` - Tests for the Treasure Data API client - `tests/unit/test_cli_api.py` - Tests for the CLI commands - `tests/unit/test_mcp_impl.py` - Tests for the MCP tools implementation - `tests/integration/test_direct_mcp.py` - Integration tests that directly call MCP functions in-process ### Code Formatting, Linting, and Pre-commit Hooks The project uses Ruff for code formatting and linting, with pre-commit hooks to ensure code quality: #### Using pip ```bash # Install development tools pip install ruff pre-commit mypy # Run linting with Ruff python -m ruff check td_mcp_server tests # Run linting and auto-fix with Ruff python -m ruff check --fix td_mcp_server tests # Format code with Ruff python -m ruff format td_mcp_server tests # Install pre-commit hooks (do this once) pre-commit install # Run all pre-commit hooks on all files pre-commit run --all-files
Использование УФ
# Install development dependencies uv pip install -e ".[dev]" # Run linting with Ruff uv run ruff check td_mcp_server tests # Run linting and auto-fix with Ruff uv run ruff check --fix td_mcp_server tests # Format code with Ruff uv run ruff format td_mcp_server tests # Install pre-commit hooks (do this once) uv run pre-commit install # Run all pre-commit hooks on all files uv run pre-commit run --all-files

Конфигурация хуков pre-commit находится в .pre-commit-config.yaml и включает в себя:

  • Удаление конечных пробелов
  • Обеспечение перевода строки в конце файла
  • Проверка файла YAML
  • Очистка ворса (включая сортировку импорта)
  • Форматирование ерша

Проверка типа

Вы можете запустить статическую проверку типов с помощью mypy:

# Install mypy pip install mypy # Run type checking python -m mypy td_mcp_server
-
security - not tested
F
license - not found
-
quality - not tested

remote-capable server

The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.

MCP-сервер для взаимодействия с Treasure Data API, позволяющий пользователям извлекать информацию из базы данных и проверять состояние сервера с помощью запросов на естественном языке.

  1. Начиная
    1. Аутентификация
      1. Использование
        1. Интерфейс командной строки
        2. API-интерфейс Python
      2. Конечные точки API
        1. Конфигурация сервера MCP
          1. Запуск сервера MCP
          2. Реализация FastMCP
          3. Настройка с помощью Клода Кода
          4. Настройка с помощью Claude Desktop
          5. Использование инструментов MCP в Claude
        2. Разработка
          1. Требования к окружающей среде
          2. Проведение тестов
        3. Install development tools
          1. Run linting with Ruff
            1. Run linting and auto-fix with Ruff
              1. Format code with Ruff
                1. Install pre-commit hooks (do this once)
                  1. Run all pre-commit hooks on all files
                    1. Install development dependencies
                      1. Run linting with Ruff
                        1. Run linting and auto-fix with Ruff
                          1. Format code with Ruff
                            1. Install pre-commit hooks (do this once)
                              1. Run all pre-commit hooks on all files
                                1. Install mypy
                                  1. Run type checking

                                    Related MCP Servers

                                    • A
                                      security
                                      A
                                      license
                                      A
                                      quality
                                      An MCP server implementation that integrates Claude with Salesforce, enabling natural language interactions with Salesforce data and metadata for querying, modifying, and managing objects and records.
                                      Last updated -
                                      7
                                      87
                                      15
                                      TypeScript
                                      MIT License
                                    • A
                                      security
                                      A
                                      license
                                      A
                                      quality
                                      An MCP server implementation that integrates Claude with Salesforce, enabling natural language interactions with Salesforce data and metadata for querying, modifying, and managing objects and records.
                                      Last updated -
                                      7
                                      18
                                      4
                                      TypeScript
                                      MIT License
                                      • Apple
                                      • Linux
                                    • A
                                      security
                                      F
                                      license
                                      A
                                      quality
                                      An MCP server implementation that enables interaction with the Unstructured API, providing tools to list, create, update, and manage sources, destinations, and workflows.
                                      Last updated -
                                      39
                                      26
                                      • Apple
                                    • -
                                      security
                                      F
                                      license
                                      -
                                      quality
                                      An MCP server that connects to Backlog API, providing functionality to search, retrieve, and update issues through natural language commands.
                                      Last updated -
                                      53
                                      1
                                      JavaScript
                                      • Apple

                                    View all related MCP servers

                                    ID: pk97hytjgc