Sponsored by Deepsite.site

Интеграция Strava API с Model Context Protocol (MCP) SDK

Created By
MCP-Mirror9 months ago
Mirror of
Content

Интеграция Strava API с Model Context Protocol (MCP) SDK

CI Codecov Python License: MIT Ruff

Интеграция для анализа тренировок и получения рекомендаций на основе данных Strava с использованием Model Context Protocol SDK.

🚀 Возможности

  • Анализ тренировок из Strava
  • Рекомендации по тренировкам
  • Автоматическое обновление токенов
  • Rate limiting для API запросов

📋 Требования

⚙️ Установка

# Клонируем репозиторий
git clone https://github.com/rbctmz/mcp-server-strava.git
cd mcp-server-strava

# Установка через uv (рекомендуется)
curl -LsSf https://astral.sh/uv/install.sh | sh
uv pip install .

# Установка в режиме разработки
uv pip install -e ".[dev]"

Установка MCP SDK

uv add "mcp[cli]"

🔧 Настройка

Настройка Strava API

  1. Перейдите на страницу настроек API
  2. Создайте приложение:
    • Application Name: MCP Strava Integration
    • Category: Training Analysis
    • Website: http://localhost
    • Authorization Callback Domain: localhost

Настройка окружения

  1. Создайте файл с переменными окружения:

    cp .env-template .env
    
  2. Получите токены доступа:

    python scripts/auth.py
    
  3. Проверьте настройку:

    mcp dev src/server.py
    curl -X GET "http://localhost:8000/activities"
    

📚 API и примеры

Ресурсы и инструменты

ТипНазваниеОписание
Ресурсstrava://activitiesСписок активностей
Ресурсstrava://activities/{id}Детали активности
Ресурсstrava://athlete/zonesТренировочные зоны
Ресурсstrava://athlete/clubsКлубы атлета
Ресурсstrava://gear/{gear_id}Информация о снаряжении
Инструментanalyze_activity(activity_id)Анализ тренировки
Инструментanalyze_training_load(activities)Анализ нагрузки
Инструментget_activity_recommendations()Рекомендации

Примеры использования

from mcp import ClientSession

# Получение активностей
async with ClientSession() as session:
    activities = await session.read_resource("strava://activities")
    activity = await session.read_resource("strava://activities/12345678")

# Анализ тренировки
result = analyze_activity(activity_id="12345678")
"""
{
    "type": "Run",
    "distance": 5000,
    "moving_time": 1800,
    "analysis": {
        "pace": 5.5,  # мин/км
        "effort": "Средняя"
    }
}
"""

# Анализ нагрузки
summary = analyze_training_load(activities)
"""
{
    "activities_count": 10,
    "total_distance": 50.5,  # км
    "total_time": 5.2,      # часы
    "heart_rate_zones": {
        "easy": 4,    # ЧСС < 120
        "medium": 4,  # ЧСС 120-150
        "hard": 2     # ЧСС > 150
    }
}
"""

# Получение тренировочных зон
async with ClientSession() as session:
    zones = await session.read_resource("strava://athlete/zones")
    """
    {
        "heart_rate": {
            "custom_zones": true,
            "zones": [
                {"min": 0, "max": 120, "name": "Z1 - Recovery"},
                {"min": 120, "max": 150, "name": "Z2 - Endurance"},
                {"min": 150, "max": 170, "name": "Z3 - Tempo"},
                {"min": 170, "max": 185, "name": "Z4 - Threshold"},
                {"min": 185, "max": -1, "name": "Z5 - Anaerobic"}
            ]
        },
        "power": {
            "zones": [
                {"min": 0, "max": 180},
                {"min": 181, "max": 250},
                {"min": 251, "max": 300},
                {"min": 301, "max": 350},
                {"min": 351, "max": -1}
            ]
        }
    }
    """

🛠 Разработка

CI/CD и безопасность

  • Coverage
  • Tests
  • Ruff

Проверки в GitHub Actions

ТипИнструментОписание
ЛинтингruffФорматирование и анализ кода
ТестыpytestUnit и интеграционные тесты
Покрытиеpytest-covОтчет о покрытии кода

Безопасность и секреты

  1. Защита токенов:

    • .env в .gitignore
    • GitHub Secrets для CI/CD
    • Rate limiting: 100 запросов/15 мин
  2. Настройка секретов:

    # В GitHub: Settings → Secrets → Actions
    STRAVA_CLIENT_ID=<client_id>
    STRAVA_CLIENT_SECRET=<client_secret>
    STRAVA_REFRESH_TOKEN=<refresh_token>
    

Contributing

  1. Форкните репозиторий

  2. Установите зависимости: uv pip install -e ".[dev]"

  3. Создайте ветку: git checkout -b feature/name

  4. Проверьте изменения:

    ruff format .
    ruff check .
    pytest --cov=src
    
  5. Создайте Pull Request

📫 Поддержка

📄 Лицензия

MIT

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
WindsurfThe new purpose-built IDE to harness magic
Playwright McpPlaywright MCP server
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
DeepChatYour AI Partner on Desktop
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
ChatWiseThe second fastest AI chatbot™
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Serper MCP ServerA Serper MCP Server
Amap Maps高德地图官方 MCP Server
Tavily Mcp
CursorThe AI Code Editor
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。