Nutrition MCP Server
by 984fht6
README.md
# Nutrition MCP Server
š A Model Context Protocol (MCP) server for intelligent nutrition tracking with automatic macro calculation.
## Features
- **Natural Language Meal Logging**: Just say "I ate a turkey sandwich and apple" and the system automatically calculates macros
- **Automatic Macro Calculation**: Uses FoodData Central API or built-in database
- **Daily Summaries**: View your complete nutrition breakdown for any day
- **Progress Tracking**: Compare your intake against daily goals
- **Meal History**: Review your eating patterns over time
- **Simple JSON Storage**: All data stored locally in easy-to-read JSON files
## Installation
### Prerequisites
- Python 3.10 or higher
- pip (Python package manager)
### Setup Steps
1. **Clone the repository**
```bash
git clone https://github.com/984fht6/nutrition-mcp-server.git
cd nutrition-mcp-server
```
2. **Create a virtual environment** (recommended)
```bash
python -m venv venv
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate
```
3. **Install dependencies**
```bash
pip install -r requirements.txt
```
4. **Configure FoodData Central API** (optional)
For better nutrition data, get a free API key from [FoodData Central](https://fdc.nal.usda.gov/api-guide.html):
```bash
export FOODDATA_CENTRAL_API_KEY="your_api_key_here"
```
If you don't set an API key, the server will use the built-in food database.
5. **Configure your MCP client**
Add the server to your MCP client configuration (e.g., Claude Desktop):
**On macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**On Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
```json
{
"mcpServers": {
"nutrition": {
"command": "python",
"args": [
"/absolute/path/to/nutrition-mcp-server/server.py"
],
"env": {
"FOODDATA_CENTRAL_API_KEY": "your_api_key_here"
}
}
}
}
```
6. **Restart your MCP client**
## Usage
Once configured, you can use natural language to interact with the server through your MCP client:
### Logging Meals
```
I ate a grilled chicken breast with brown rice and broccoli
I had a turkey sandwich and apple for lunch
I ate 2 eggs and oatmeal for breakfast
```
### Viewing Daily Summary
```
Show me my nutrition summary for today
What did I eat yesterday?
Show my macros for 2026-03-01
```
### Checking Progress
```
How am I doing on my goals today?
Show my progress for this week
Am I meeting my protein goals?
```
### Setting Goals
```
Set my daily goals to 2000 calories, 150g protein, 200g carbs, and 60g fat
```
### Viewing History
```
Show my meal history for the past 3 days
What have I eaten this week?
```
## Available Tools
### 1. add_meal
Log a meal with automatic macro calculation.
**Parameters:**
- `description` (required): Natural language description of the meal
- `meal_type` (optional): Type of meal (breakfast, lunch, dinner, snack)
- `timestamp` (optional): ISO format timestamp (defaults to current time)
**Example:**
```json
{
"description": "grilled salmon with quinoa and asparagus",
"meal_type": "dinner"
}
```
### 2. get_daily_summary
Get macro totals for a specific day.
**Parameters:**
- `date` (optional): Date in YYYY-MM-DD format (defaults to today)
**Example:**
```json
{
"date": "2026-03-05"
}
```
### 3. get_meal_history
View recent meals.
**Parameters:**
- `days` (optional): Number of days to look back (default: 7)
- `limit` (optional): Maximum number of meals to return (default: 20)
**Example:**
```json
{
"days": 3,
"limit": 10
}
```
### 4. set_daily_goals
Set daily macro targets.
**Parameters:**
- `calories` (required): Daily calorie goal
- `protein` (required): Daily protein goal in grams
- `carbs` (required): Daily carbohydrate goal in grams
- `fat` (required): Daily fat goal in grams
**Example:**
```json
{
"calories": 2000,
"protein": 150,
"carbs": 200,
"fat": 60
}
```
### 5. get_progress
Compare actual intake vs goals.
**Parameters:**
- `date` (optional): Date in YYYY-MM-DD format (defaults to today)
**Example:**
```json
{
"date": "2026-03-05"
}
```
## Data Storage
All data is stored locally in JSON files at `~/.nutrition-mcp/`:
- `meals.json`: All logged meals with timestamps and nutrition data
- `goals.json`: Your daily macro goals
### Data Format
**meals.json:**
```json
{
"meals": [
{
"timestamp": "2026-03-05T12:30:00",
"description": "grilled chicken with rice",
"meal_type": "lunch",
"nutrition": {
"calories": 450,
"protein": 45,
"carbs": 50,
"fat": 8,
"foods": [
{
"name": "grilled chicken",
"amount": "1 serving",
"calories": 300,
"protein": 40,
"carbs": 0,
"fat": 5
}
]
}
}
]
}
```
**goals.json:**
```json
{
"calories": 2000,
"protein": 150,
"carbs": 200,
"fat": 60
}
```
## Architecture
### File Structure
```
nutrition-mcp-server/
āāā server.py # Main MCP server implementation
āāā nutrition_calculator.py # Nutrition calculation and API integration
āāā storage.py # JSON file storage management
āāā requirements.txt # Python dependencies
āāā README.md # This file
```
### Components
1. **server.py**: Implements the MCP protocol and tool handlers
2. **nutrition_calculator.py**: Handles macro calculation from natural language:
- Parses food descriptions
- Integrates with FoodData Central API
- Falls back to built-in food database
- Handles portion size estimation
3. **storage.py**: Manages persistent data storage:
- JSON file operations
- Data validation
- Query and aggregation functions
## Nutrition Database
The server includes a comprehensive built-in database with common foods:
- **Proteins**: Chicken, turkey, salmon, beef, eggs, tofu
- **Carbs**: Rice, pasta, bread, potatoes, oats, quinoa
- **Vegetables**: Broccoli, spinach, carrots, peppers, tomatoes
- **Fruits**: Apples, bananas, oranges, berries
- **Dairy**: Milk, cheese, yogurt
- **Fats**: Oils, nuts, avocado, butter
- **Common meals**: Sandwiches, pizza, burgers, salads
### Portion Sizes
The system recognizes standard portion sizes:
- Slice, piece, cup, tablespoon, teaspoon
- Ounce (oz), grams (g)
- Small, medium, large
- Serving sizes
## Error Handling
The server includes comprehensive error handling:
- Invalid date formats
- Missing required parameters
- API failures (with automatic fallback)
- Storage errors
- Unknown foods (provides estimates)
## API Integration
### FoodData Central API
The server can integrate with the USDA FoodData Central API for accurate nutrition data:
1. Sign up at [FoodData Central](https://fdc.nal.usda.gov/api-guide.html)
2. Get your API key
3. Set the environment variable: `FOODDATA_CENTRAL_API_KEY`
The API provides:
- Detailed nutrition information
- Large database of branded and generic foods
- Regular updates
### Fallback Database
If the API is unavailable or you don't have an API key, the built-in database provides reliable estimates for common foods.
## Development
### Running Tests
```bash
# Add tests here
python -m pytest tests/
```
### Logging
The server logs important events to help with debugging:
```python
import logging
logging.basicConfig(level=logging.DEBUG) # For verbose logging
```
### Extending the Food Database
To add more foods to the built-in database, edit `nutrition_calculator.py`:
```python
self.food_database = {
"your_food_name": {
"calories": 100,
"protein": 5,
"carbs": 15,
"fat": 3
},
# Values are per 100g
}
```
## Troubleshooting
### Server won't start
1. Check Python version: `python --version` (needs 3.10+)
2. Verify dependencies: `pip install -r requirements.txt`
3. Check logs for specific errors
### Nutrition calculations seem off
1. Verify API key is set correctly
2. Check food names match database entries
3. Specify portion sizes explicitly (e.g., "200g chicken" instead of "chicken")
### Data not persisting
1. Check file permissions in `~/.nutrition-mcp/`
2. Verify disk space
3. Check logs for storage errors
## Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
## License
MIT License - feel free to use this in your own projects!
## Support
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check existing issues for solutions
## Roadmap
- [ ] Add support for recipes and meal planning
- [ ] Export data to CSV
- [ ] Integration with fitness trackers
- [ ] Micronutrient tracking (vitamins, minerals)
- [ ] Custom food database entries
- [ ] Weekly/monthly reports
- [ ] Barcode scanning support
- [ ] Restaurant menu integration
## Acknowledgments
- USDA FoodData Central for nutrition data
- Model Context Protocol specification
- Claude Desktop for MCP support
---
**Built with ā¤ļø for health-conscious developers**