Skip to main content
Glama
food-calorie-api

food-calorie-api

by yuanhsunliu
README.md
# Food Calorie API

A simple REST API for tracking food calorie intake with MCP (Model Context Protocol) integration for AI agent access.

## Features

- šŸŽ Create food calorie entries with name, calories, timestamp, and notes
- šŸ“Š List food entries with date filtering and pagination
- šŸ“ˆ Calculate calorie statistics (total, daily average)
- šŸ¤– MCP server integration for AI agents
- šŸ“ CSV-based storage (no database required)
- āœ… Full input validation and error handling
- šŸ“– OpenAPI v3 specification

## Installation

```bash
# Install dependencies
pip install -r requirements.txt
```

## Usage

### Starting the API Server

```bash
python3 -m food_calorie_api.app
```

The API will be available at `http://localhost:5001`

### API Endpoints

#### POST /api/foods
Create a new food entry.

**Request:**
```json
{
  "food_name": "Apple",
  "calories": 95,
  "timestamp": "2026-01-01T08:30:00Z",  // optional, defaults to current time
  "notes": "Morning snack"              // optional
}
```

**Response (201 Created):**
```json
{
  "id": 1,
  "timestamp": "2026-01-01T08:30:00Z",
  "food_name": "Apple",
  "calories": 95.0,
  "notes": "Morning snack"
}
```

**Validation Rules:**
- `food_name`: Required, 1-200 characters
- `calories`: Required, 0-10000, rounded to 1 decimal place
- `timestamp`: Optional ISO8601 UTC format, cannot be in the future
- `notes`: Optional, max 500 characters

#### GET /api/foods
List food entries with optional filters.

**Query Parameters:**
- `start_date`: Filter from this date (ISO8601)
- `end_date`: Filter to this date (ISO8601)
- `limit`: Maximum entries to return (default: 100, max: 1000)
- `offset`: Number of entries to skip (default: 0)

**Response (200 OK):**
```json
{
  "total": 250,
  "entries": [
    {
      "id": 1,
      "timestamp": "2026-01-01T08:30:00Z",
      "food_name": "Apple",
      "calories": 95.0,
      "notes": "Morning snack"
    }
  ]
}
```

#### GET /api/foods/stats
Get calorie statistics.

**Query Parameters:**
- `start_date`: Start of date range (ISO8601)
- `end_date`: End of date range (ISO8601)

**Response (200 OK):**
```json
{
  "total_calories": 5420.5,
  "average_per_day": 1806.83,
  "total_entries": 18,
  "date_range": {
    "start": "2026-01-01",
    "end": "2026-01-03"
  }
}
```

**Note:** `average_per_day` = `total_calories` / `number_of_days_in_range`. Days with no entries are included (counted as 0 calories).

### Error Response Format

All errors return a structured JSON response:

```json
{
  "error": "Human-readable error message",
  "code": "ERROR_CODE",
  "details": [
    {
      "field": "field_name",
      "message": "Specific field error"
    }
  ]
}
```

**Error Codes:**
- `INVALID_INPUT`: Validation failed
- `FUTURE_TIMESTAMP`: Timestamp cannot be in the future
- `STORAGE_ERROR`: CSV file access error
- `NOT_FOUND`: Resource not found
- `INTERNAL_ERROR`: Unexpected server error

## MCP Integration

### Starting the MCP Server

```bash
DATA_FILE=data/food_entries.csv python3 -m food_calorie_api.mcp_server
```

### MCP Configuration

Add to your MCP client configuration (e.g., `mcp_config.json`):

```json
{
  "mcpServers": {
    "food-calorie-api": {
      "command": "python3",
      "args": ["-m", "food_calorie_api.mcp_server"],
      "env": {
        "DATA_FILE": "data/food_entries.csv"
      }
    }
  }
}
```

### Available MCP Tools

#### add_food_entry
Add a new food calorie entry.

**Parameters:**
- `food_name` (string, required): Name of the food
- `calories` (number, required): Calorie value (0-10000)
- `timestamp` (string, optional): ISO8601 UTC timestamp
- `notes` (string, optional): Optional notes

**Example:**
```json
{
  "food_name": "Chicken Breast",
  "calories": 165.5,
  "notes": "Grilled, 100g"
}
```

#### list_food_entries
List food entries with optional filtering.

**Parameters:**
- `start_date` (string, optional): Filter from this date
- `end_date` (string, optional): Filter to this date
- `limit` (integer, optional): Maximum entries (default: 100)

#### get_calorie_stats
Get calorie statistics for a date range.

**Parameters:**
- `start_date` (string, optional): Start of date range
- `end_date` (string, optional): End of date range

### MCP Resources

- `food://entries`: List of all food calorie entries
- `food://stats`: Overall calorie statistics

## Examples

### Create a food entry
```bash
curl -X POST http://localhost:5001/api/foods \
  -H "Content-Type: application/json" \
  -d '{
    "food_name": "Chicken Breast",
    "calories": 165.5,
    "notes": "Grilled"
  }'
```

### List recent entries
```bash
curl http://localhost:5001/api/foods?limit=10
```

### Get today's statistics
```bash
TODAY=$(date +%Y-%m-%d)
curl "http://localhost:5001/api/foods/stats?start_date=${TODAY}&end_date=${TODAY}"
```

## Testing

Run the test suite:

```bash
python3 -m unittest tests.test_api -v
```

## Data Storage

Food entries are stored in `data/food_entries.csv` with the following format:

```csv
id,timestamp,food_name,calories,notes
1,2026-01-01T08:30:00Z,Apple,95.0,Morning snack
2,2026-01-01T12:00:00Z,"Apple, Red Delicious",95.5,"Fresh from ""market"""
```

- Uses CSV QUOTE_MINIMAL for automatic escaping
- File locking prevents concurrent write issues
- Auto-incrementing integer IDs

## Tech Stack

- **Python 3.11+**
- **Flask** - Web framework
- **flask-restful** - REST API framework
- **python-dateutil** - Date parsing
- **mcp** - Model Context Protocol

## Architecture

```
food_calorie_api/
ā”œā”€ā”€ __init__.py
ā”œā”€ā”€ app.py              # Flask application
ā”œā”€ā”€ resources.py        # API resources
ā”œā”€ā”€ storage.py          # CSV storage layer
ā”œā”€ā”€ models.py           # Data models
ā”œā”€ā”€ validators.py       # Input validation
└── mcp_server.py       # MCP integration
```

## License

MIT