Garmy – AI-powered Python library for accessing and analyzing your Garmin health
4 months ago
19
An AI-powered Python library for Garmin Connect API designed specifically for health data analysis and AI agent integration via Model Context Protocol (MCP). Build intelligent health assistants and data analysis tools with seamless access to Garmin's comprehensive fitness metrics.
Inspired by garth - This project was heavily inspired by the excellent garth library, building upon its foundation with enhanced modularity, type safety, and AI integration capabilities.
🤖 AI-First Design: Built specifically for AI health agents and intelligent assistants
🔌 MCP Integration: Native Model Context Protocol support for seamless AI interactions
🏥 Health Analytics: Advanced data analysis capabilities for fitness and wellness insights
📊 Rich Metrics: Complete access to sleep, heart rate, stress, training readiness, and more
🗣️ Natural Language: Query health data using conversational commands
⚡ Real-time Processing: Async/await support for high-performance AI applications
🛡️ Type Safe: Full type hints and runtime validation for reliable AI workflows
🔄 Auto-Discovery: Automatic metric registration and API endpoint discovery
With MCP Support (Recommended for AI Agents)
git clone https://github.com/bes-dev/garmy.git
cd garmy
pip install -e ".[dev,mcp]"
AI Agent Example (Recommended)
fromgarmyimportAuthClient, APIClientimportasyncio# Create an AI health agentasyncdefhealth_agent():
auth_client=AuthClient()
api_client=APIClient(auth_client=auth_client)
# Login using environment variables (secure for AI agents)awaitauth_client.login_async(
email=os.getenv('GARMIN_EMAIL'),
password=os.getenv('GARMIN_PASSWORD')
)
# AI agent can now analyze multiple health metrics concurrentlysleep_task=api_client.metrics.get('sleep').get_async()
readiness_task=api_client.metrics.get('training_readiness').get_async()
hrv_task=api_client.metrics.get('hrv').get_async()
sleep_data, readiness_data, hrv_data=awaitasyncio.gather(
sleep_task, readiness_task, hrv_task
)
# AI analysis logic herehealth_score=analyze_health_trends(sleep_data, readiness_data, hrv_data)
returnhealth_score# Run AI health agenthealth_insights=asyncio.run(health_agent())
fromgarmyimportAuthClient, APIClient# Create clientsauth_client=AuthClient()
api_client=APIClient(auth_client=auth_client)
# Loginauth_client.login("[email protected]", "your_password")
# Get today's training readinessreadiness=api_client.metrics.get('training_readiness').get()
print(f"Training Readiness Score: {readiness[0].score}/100")
# Get sleep data for specific datesleep_data=api_client.metrics.get('sleep').get('2023-12-01')
print(f"Sleep Score: {sleep_data[0].overall_sleep_score}")
# Get multiple days of dataweekly_steps=api_client.metrics['steps'].list(days=7)
Garmy is specifically designed for building AI health agents and intelligent assistants through native Model Context Protocol (MCP) integration. Transform your Garmin health data into actionable insights using natural language interactions.
What Makes Garmy AI-First?
Garmy isn't just an API wrapper – it's a complete AI health agent platform that enables:
🧠 Intelligent Health Analysis: AI-powered insights into sleep patterns, training readiness, and recovery
🗣️ Natural Language Queries: Ask questions like "How was my sleep quality this week?" or "Am I ready for training today?"
📊 Predictive Analytics: Build AI models that predict optimal training times, recovery needs, and health trends
🔄 Real-time Monitoring: Create AI agents that continuously monitor health metrics and provide recommendations
🎨 Custom Health Dashboards: Generate AI-driven visualizations and reports tailored to individual health goals
📱 Multi-modal Integration: Combine Garmin data with other health sources for comprehensive AI analysis
# Install Garmy with MCP support
pip install garmy[mcp]
# Verify installation
garmy-mcp --help
Option 1: Command Line Interface
# Start MCP server for Claude Desktop (STDIO transport)
garmy-mcp serve --transport stdio
# Start HTTP server for web clients
garmy-mcp serve --transport http --port 8080
# Show server information
garmy-mcp info
# List available metrics
garmy-mcp metrics
# Test server configuration
garmy-mcp test
Option 2: Programmatic Usage
fromgarmy.mcpimportGarmyMCPServer, MCPConfig# Create and configure serverconfig=MCPConfig.for_production()
server=GarmyMCPServer(config)
# Run serverserver.run(transport="stdio") # For Claude Desktopserver.run(transport="http", port=8080) # For HTTP clients
Claude Desktop Configuration
Secure Setup (Recommended)
Add this to your Claude Desktop MCP configuration file:
⚠️ Use with: "Log into Garmin Connect with email [email] and password [password]"
Once configured, your AI health agent can interact with Garmin data using natural language. Here are examples of what your AI assistant can do:
Intelligent Health Monitoring
"Analyze my recovery patterns and tell me if I should train today"
"What's my sleep efficiency trend over the past month?"
"Create a personalized training plan based on my readiness scores"
"Identify correlations between my stress and sleep quality"
"Generate a health report with actionable insights"
Predictive Health Analytics
"Predict my optimal training windows for next week"
"What factors are affecting my sleep quality most?"
"Alert me when my recovery metrics indicate overtraining"
"Build a model to predict my daily energy levels"
Conversational Health Queries
"How am I progressing towards my fitness goals?"
"What's unusual about my health data this week?"
"Compare my current training load to last month"
"Should I adjust my sleep schedule based on my data?"
Smart Data Export & Visualization
"Create an interactive dashboard of my health metrics"
"Export my data in a format suitable for machine learning"
"Generate a health summary for my doctor"
"Build charts showing my progress over time"
MCP Configuration Options
Variable
Description
Default
GARMIN_EMAIL
Garmin Connect email
None
GARMIN_PASSWORD
Garmin Connect password
None
GARMY_MCP_DEBUG
Enable debug logging
false
GARMY_MCP_CACHE_ENABLED
Enable data caching
false
GARMY_MCP_CACHE_SIZE
Cache size limit
100
GARMY_MCP_MAX_HISTORY_DAYS
Max historical data
365
GARMY_MCP_DEFAULT_ANALYSIS_PERIOD
Default analysis period
30
fromgarmy.mcp.configimportMCPConfig# Development setupconfig=MCPConfig.for_development()
# Production setup config=MCPConfig.for_production()
# Minimal setupconfig=MCPConfig.minimal()
"Server not responding"
# Check if server is running
garmy-mcp test# Restart with debug mode
GARMY_MCP_DEBUG=true garmy-mcp serve --transport stdio
"Authentication failed"
# Verify credentialsecho$GARMIN_EMAILecho$GARMIN_PASSWORD# Test authentication
garmy-mcp test --auth
"No data available"
# Check available metrics
garmy-mcp metrics
# Verify date range
garmy-mcp test --date 2023-12-01
Enable debug logging for troubleshooting:
# Enable debug modeexport GARMY_MCP_DEBUG=true
# Run server with debug output
garmy-mcp serve --transport stdio --debug
📊 AI Health Data Analysis
Building AI Health Models
fromgarmyimportAPIClient, AuthClientimportpandasaspdimportnumpyasnpfromsklearn.ensembleimportRandomForestRegressorfromsklearn.preprocessingimportStandardScaler# Setup AI health analysis pipelineauth_client=AuthClient()
api_client=APIClient(auth_client=auth_client)
auth_client.login("email", "password")
# Gather comprehensive health data for AI modelasyncdefbuild_health_dataset(days=90):
# Collect multiple health metrics concurrentlytasks= [
api_client.metrics.get('sleep').list_async(days=days),
api_client.metrics.get('training_readiness').list_async(days=days),
api_client.metrics.get('hrv').list_async(days=days),
api_client.metrics.get('stress').list_async(days=days),
api_client.metrics.get('body_battery').list_async(days=days)
]
sleep_data, readiness_data, hrv_data, stress_data, battery_data=awaitasyncio.gather(*tasks)
# Build comprehensive health datasethealth_df=pd.DataFrame()
# ... merge and process data for AI model trainingreturnhealth_df# Train AI model to predict training readinessdeftrain_readiness_predictor(health_df):
features= ['sleep_score', 'hrv_rmssd', 'stress_avg', 'body_battery_drained']
X=health_df[features]
y=health_df['training_readiness_score']
model=RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X, y)
returnmodel# AI-powered health insightsdefgenerate_health_insights(model, current_metrics):
predicted_readiness=model.predict([current_metrics])[0]
insights= {
'readiness_prediction': predicted_readiness,
'recommendation': 'high_intensity'ifpredicted_readiness>75else'recovery',
'confidence': model.score(X_test, y_test)
}
returninsights
AI-Powered Health Monitoring
# Create an AI health monitoring agentclassHealthMonitoringAgent:
def__init__(self, api_client):
self.api_client=api_clientself.health_model=self.load_trained_model()
asyncdefdaily_health_check(self):
"""Perform daily AI-powered health analysis"""# Get today's metricstoday_data=awaitself.get_current_metrics()
# AI analysishealth_score=self.health_model.predict_health_score(today_data)
recommendations=self.generate_recommendations(health_score, today_data)
alerts=self.check_health_alerts(today_data)
return {
'health_score': health_score,
'recommendations': recommendations,
'alerts': alerts,
'insights': self.generate_insights(today_data)
}
defgenerate_recommendations(self, health_score, data):
"""AI-generated personalized health recommendations"""ifhealth_score>80:
return"Great day for high-intensity training!"elifhealth_score>60:
return"Moderate activity recommended. Focus on technique."else:
return"Prioritize recovery today. Light movement only."asyncdefweekly_health_report(self):
"""Generate comprehensive AI health report"""week_data=awaitself.api_client.metrics.get('daily_summary').list_async(days=7)
# AI trend analysistrends=self.analyze_trends(week_data)
predictions=self.predict_next_week(week_data)
returnself.format_health_report(trends, predictions)
# Usageagent=HealthMonitoringAgent(api_client)
daily_insights=awaitagent.daily_health_check()
weekly_report=awaitagent.weekly_health_report()
Check out the examples/ directory for comprehensive usage examples:
# Basic authentication example
python examples/basic_auth.py
# Sleep analysis demo
python examples/sleep_demo.py
# Training readiness analysis
python examples/training_readiness_demo.py
# Comprehensive metrics sync
python examples/metrics_sync_demo.py
# MCP server demo
python examples/mcp_integration_demo.py
Garmy's modular architecture makes it easy to add new metrics:
fromgarmy.core.configimportset_config, GarmyConfig# Create custom configurationconfig=GarmyConfig(
request_timeout=30,
retries=3,
max_workers=10,
default_user_agent="MyApp/1.0"
)
# Apply configurationset_config(config)
# Or use environment variablesimportosos.environ['GARMY_REQUEST_TIMEOUT'] ='30'os.environ['GARMY_MAX_WORKERS'] ='10'
# Install development dependencies
make install-dev
# Run all tests
make test# Run specific test modules
make test-core # Core functionality
make test-auth # Authentication
make test-metrics # Metrics
make test-mcp # MCP server# Check code quality
make lint
make quick-check
AuthClient: Handles authentication and session management
APIClient: Main interface for accessing Garmin Connect data
MetricAccessor: Provides access to specific metrics
GarmyMCPServer: MCP server for AI assistant integration
GarmyConfig: Main configuration class
MCPConfig: MCP server configuration
ConfigManager: Configuration management utilities
Each metric has its own dataclass with type-safe fields. Examples:
SleepData: Sleep tracking information
HeartRateData: Heart rate statistics
StepsData: Step count and goals
TrainingReadinessData: Training readiness scores
We welcome contributions! Please see our Contributing Guide for details.
# Clone repository
git clone https://github.com/bes-dev/garmy.git
cd garmy
# Install in development mode
make install-dev
# Run quality checks
make ci
Fork the repository
Create a feature branch: git checkout -b feature/new-feature
Make your changes
Run tests: make ci
Submit a pull request
Garmy was heavily inspired by the excellent garth library by Matin Tamizi. We're grateful for the foundational work that made this project possible. Garmy builds upon garth's concepts with:
Enhanced modularity and extensibility
Full type safety with mypy compliance
Model Context Protocol (MCP) integration for AI assistants
Comprehensive async/await support
Auto-discovery system for metrics
Modern Python architecture and testing practices
Special thanks to the garth project and its contributors for pioneering accessible Garmin Connect API access.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.