Skip to main content
Glama
README.md
# 🥗 ua-food-mcp

**An MCP server that gives Claude (or any MCP client) a Ukrainian food & nutrition database.**
Ask *"How many calories are in 200 g of buckwheat and a chicken breast?"* and the model
looks the foods up and does the math with real data instead of guessing.

[Українська версія нижче ↓](#-українською)

![tests](https://github.com/SaychukAndriy/ua-food-mcp/actions/workflows/tests.yml/badge.svg)
![python](https://img.shields.io/badge/python-3.10%2B-blue)
![MCP](https://img.shields.io/badge/MCP-server-8A2BE2)
![license](https://img.shields.io/badge/license-MIT-green)


## Why

LLMs are bad at nutrition facts: they invent calorie counts and add numbers wrong.
This server gives the model **548 Ukrainian foods and dishes** (borshch, varenyky, syrnyky,
buckwheat...) with calories, protein, fat and carbs per 100 g, plus tools to search them and
calculate a meal exactly. The data comes from **ApriGoal**, my diploma project: a Flutter
nutrition app with an AI assistant.

## What the model can do

| Tool | What it does | Example question |
|---|---|---|
| `search_foods` | Find foods by name, tolerant to word endings and typos | *"Що є з гречки?"* |
| `get_food` | Nutrition per 100 g for one food | *"How much protein is in cottage cheese 5%?"* |
| `calculate_meal` | Totals and macro split for a list of foods with grams | *"200 г гречки + 150 г курячої грудки"* |
| `top_foods` | Rank by a nutrient, optionally inside a category | *"Which fish has the most protein?"* |
| `list_categories` | All 18 categories with counts | *"What kinds of food do you know?"* |

It also uses the other two MCP building blocks:

- **Resource** `foods://categories`: the category list as context the client can attach.
- **Prompt** `plan_day(kcal_target, goal)`: a ready-made template that plans a day of meals and checks every meal with `calculate_meal`.

All tools are marked read-only (`readOnlyHint`), so clients know they never change anything.

## Quick start

You need [uv](https://docs.astral.sh/uv/getting-started/installation/).

```bash
git clone https://github.com/SaychukAndriy/ua-food-mcp.git
cd ua-food-mcp
uv sync
uv run pytest        # 20 tests
```

### Try it in MCP Inspector (needs Node.js)

```bash
npx @modelcontextprotocol/inspector uv run ua-food-mcp
```

Opens a web UI where you can call each tool by hand.

### Connect to Claude Desktop

Open **Settings → Developer → Edit Config** and add the server to `claude_desktop_config.json`
(use the full path to the project, and to `uv` if Claude Desktop can't find it):

```json
{
  "mcpServers": {
    "ua-food": {
      "command": "uv",
      "args": ["--directory", "C:\\path\\to\\ua-food-mcp", "run", "ua-food-mcp"]
    }
  }
}
```

Restart Claude Desktop. The tools appear under the 🔨 / connectors menu.

## How it works

```
Claude Desktop  ──(MCP over stdio, JSON-RPC)──▶  server.py  ──▶  database.py  ──▶  foods.json
   (client)                                     tools/resource/    search, scoring,
                                                prompt + schemas   portion math
```

- **`database.py`** is plain Python with no MCP code: loading, search and math. Easy to test and reuse.
  Search normalizes case and Ukrainian apostrophes (`м'ясо` = `мʼясо` = `мясо`), matches word stems
  (`гречки` → `Гречка`), and falls back to fuzzy matching (`difflib`) for typos.
- **`server.py`** is a thin MCP layer built with `MCPServer` from the official
  [Python SDK](https://github.com/modelcontextprotocol/python-sdk) (the class formerly called FastMCP).
  Type hints and Pydantic models become JSON schemas, so the model sees exactly what each tool takes and returns.
- Errors the model can recover from (an unknown food) are returned as tool errors with a hint
  ("try `search_foods`") instead of crashing.
- **`scripts/convert_dart_to_json.py`** extracts the data from ApriGoal's Dart source with a regex.

```
ua-food-mcp/
├── src/ua_food_mcp/
│   ├── server.py          # MCP tools, resource, prompt
│   ├── database.py        # search & nutrition logic (no MCP)
│   └── data/foods.json    # 548 foods, per 100 g
├── scripts/convert_dart_to_json.py
├── tests/                 # pytest: logic + end-to-end through an MCP client
└── .github/workflows/tests.yml   # CI on Ubuntu & Windows
```

## Data

548 entries in 18 categories (meat, vegetables, fruit, dishes, dairy, fish, sweets, drinks, grains...).
Values are typical averages per 100 g compiled for ApriGoal; they are fine for everyday tracking,
not for medical diets.

## Ideas for next steps

- Daily norms (BMR/TDEE) tool
- Barcode lookup via Open Food Facts
- HTTP transport to host it remotely

## License

MIT

---

## 🇺🇦 Українською

**MCP-сервер, який дає Claude (або будь-якому MCP-клієнту) українську базу продуктів з КБЖВ.**
Питаєш *«Скільки калорій у 200 г гречки й курячій грудці?»*, і модель шукає продукти в базі та
рахує на реальних даних, а не вигадує.

### Навіщо

Мовні моделі погано знають калорійність: вигадують цифри й помиляються в арифметиці. Цей сервер
дає моделі **548 українських продуктів і страв** (борщ, вареники, сирники, гречка...) з калоріями,
білками, жирами й вуглеводами на 100 г, а також інструменти для пошуку й точного підрахунку.
Дані взяті з **ApriGoal**, мого дипломного проєкту: Flutter-застосунку для харчування з ШІ-асистентом.

### Інструменти

| Інструмент | Що робить |
|---|---|
| `search_foods` | Пошук за назвою; розуміє інші закінчення слів і одруківки |
| `get_food` | КБЖВ на 100 г для одного продукту |
| `calculate_meal` | Сума КБЖВ і частка калорій з білків/жирів/вуглеводів для страви з грамами |
| `top_foods` | Рейтинг за нутрієнтом, можна в межах категорії |
| `list_categories` | 18 категорій з кількістю продуктів |

Також є **ресурс** `foods://categories` і **промпт** `plan_day`, який складає меню на день під ціль за калоріями.

### Запуск

```bash
git clone https://github.com/SaychukAndriy/ua-food-mcp.git
cd ua-food-mcp
uv sync
uv run pytest
npx @modelcontextprotocol/inspector uv run ua-food-mcp   # MCP Inspector (потрібен Node.js)
```

Для Claude Desktop: **Settings → Developer → Edit Config**, додай блок `mcpServers` з розділу
[Connect to Claude Desktop](#connect-to-claude-desktop) зі своїм шляхом до проєкту й перезапусти застосунок.

### Як влаштовано

- `database.py`: чистий Python без MCP (завантаження, пошук, підрахунок), тому його легко тестувати.
- `server.py`: тонкий MCP-шар на `MCPServer` з офіційного Python SDK. Анотації типів і Pydantic-моделі
  автоматично стають JSON-схемами, тож модель точно знає, що приймає й повертає кожен інструмент.
- `scripts/convert_dart_to_json.py`: дістає дані з Dart-коду ApriGoal регулярним виразом.
- 20 тестів на pytest, зокрема наскрізні через справжній MCP-клієнт; CI на Ubuntu та Windows.

TDQS

A3.8/5.0

Scored across 5 tools

Disambiguation4/5

Each tool has a distinct role: search returns name matches, get_food returns per-100g nutrition, list_categories enumerates categories, calculate_meal aggregates totals, and top_foods ranks by nutrient. The only mild overlap is search_foods vs get_food, both doing fuzzy name matching, but their outputs (match list vs nutrition record) clearly separate them.

Naming Consistency4/5

Four of five tools follow a clean snake_case verb_noun pattern (search_foods, get_food, list_categories, calculate_meal). top_foods breaks the pattern as a bare noun phrase, a minor deviation that is still readable and predictable.

Tool Count5/5

Five tools is well-scoped for a read-only nutrition lookup server; each operation (discover, inspect, browse, aggregate, rank) earns its place with no redundancy.

Completeness4/5

The surface covers the core lifecycle of a nutrition dataset: search, lookup, category overview, meal totals, and nutrient rankings. Minor gaps remain — no way to list foods within a category (only counts), and nutrition is limited to macros (no fiber/sugar/micronutrients or portion units beyond grams).

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues