food logger context tips

This commit is contained in:
Joren de Graaf
2026-10-11 15:21:10 +02:00
parent 559c51e9bb
commit 400e8254c0
51 changed files with 1988 additions and 41 deletions
+72 -5
View File
@@ -80,6 +80,32 @@ class FoodUpdate(BaseModel):
date: str | None = None
class ProductInput(BaseModel):
name: str
brand: str = ''
barcode: str | None = None
package_quantity: Decimal | None = None
package_unit: Literal['g', 'ml'] | None = None
nutrition_per_100: dict[str, Decimal | None] | None = None
source: Literal['manual'] = 'manual'
class GroceryInput(BaseModel):
product_id: str | None = None
name: str | None = None
brand: str | None = None
barcode: str | None = None
quantity: int = 1
package_quantity: Decimal | None = None
package_unit: Literal['g', 'ml'] | None = None
nutrition_per_100: dict[str, Decimal | None] | None = None
location: str = ''
category: str | None = None
notes: str = ''
opened: bool = False
best_before: str | None = None
class InventoryUpdate(BaseModel):
product_id: str | None = None
quantity: int | None = Field(default=None, ge=1)
@@ -87,6 +113,7 @@ class InventoryUpdate(BaseModel):
category: str | None = None
notes: str | None = None
opened: bool | None = None
remaining_amount: Decimal | None = Field(default=None, ge=0)
best_before: str | None = None
@@ -142,13 +169,13 @@ def _entry(entry):
return {'id': entry['id'], 'name': entry['product_name_snapshot'], 'meal': entry['meal'],
'date': entry['date'], 'amount': entry['amount'], 'unit': entry['unit'],
'calories_kcal': entry['calories_kcal'], 'carbohydrates_g': entry['carbohydrates_g'],
'protein_g': entry['protein_g'], 'fat_g': entry['fat_g'],
'protein_g': entry['protein_g'], 'fat_g': entry['fat_g'], 'fibre_g': entry['fibre_g'],
'attachments': [{'id': a['id'], 'caption': a['caption']} for a in entry.get('attachments', [])]}
def _inventory(item):
return {key: item.get(key) for key in ('id', 'product_id', 'product_name', 'brand', 'barcode',
'quantity', 'location', 'category', 'opened', 'best_before', 'notes')}
'quantity', 'location', 'category', 'opened', 'best_before', 'notes', 'remaining_amount')}
def _key(value):
@@ -232,10 +259,12 @@ def create_server() -> MCPServer:
entries = {meal: [_entry(item) for item in items] for meal, items in data['meals'].items()}
goals = data.get('goals', {})
mapping = {'calories_kcal': 'daily_calorie_goal', 'carbohydrates_g': 'carbohydrate_goal_g',
'protein_g': 'protein_goal_g', 'fat_g': 'fat_goal_g'}
'protein_g': 'protein_goal_g', 'fat_g': 'fat_goal_g', 'fibre_g': 'fibre_goal_g'}
remaining = {name: str(Decimal(goals[goal]) - Decimal(data['totals'][name]))
for name, goal in mapping.items() if goals.get(goal) is not None}
return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals, 'remaining': remaining}
for name, goal in mapping.items() if goals.get(goal) is not None and
data['totals'][name] is not None and not (name == 'fibre_g' and data.get('fibre_incomplete'))}
return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals,
'remaining': remaining, 'fibre_incomplete': data.get('fibre_incomplete', False)}
@server.tool(structured_output=True, description='Search the authenticated user’s saved TaskNest food products before logging a known food. Returns serving sizes, portions, and nutrition per 100 g/ml. Does not change data.')
async def food_search_products(query: str, limit: int = 20) -> dict[str, Any]:
@@ -245,6 +274,35 @@ def create_server() -> MCPServer:
'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100', 'portions')
return {'count': data['count'], 'products': [{k: item.get(k) for k in fields} for item in data['results']]}
@server.tool(structured_output=True, description='Find food product candidates in your saved products and optionally Open Food Facts. Read only: never saves a search result. Exact barcodes rank first; ambiguous matches are candidates for user selection. External lookup may be unavailable.')
async def food_lookup_product(query: str = '', barcode: str | None = None, brand: str = '',
package_quantity: Decimal | None = None,
package_unit: Literal['g', 'ml'] | None = None,
limit: int = 10, include_open_food_facts: bool = True) -> dict[str, Any]:
params = {'query': query, 'barcode': barcode or '', 'brand': brand, 'limit': limit,
'include_open_food_facts': str(include_open_food_facts).lower()}
if package_quantity is not None:
params['package_quantity'] = str(package_quantity)
if package_unit is not None:
params['package_unit'] = package_unit
return await api_request('GET', 'food/products/lookup/', params=params)
@server.tool(structured_output=True, description='Create a manual food product owned by the authenticated user from supplied facts. No external lookup. Missing nutrition remains unknown; possible duplicates require review. Returns a product_id when created or reused. Reuse idempotency_key on retries.')
async def food_create_product(product: ProductInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
data = await api_request('POST', 'food/products/create/',
payload=product.model_dump(mode='json', exclude_none=True), idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Save a selected Open Food Facts product by numeric barcode into your product catalogue. Changes data; uses the configured cached external import. Does not invent missing nutrition. Returns a local product_id, or a structured not-found/error response. Reuse idempotency_key on retries.')
async def food_import_product(barcode: str, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
try:
data = await api_request('POST', 'food/products/import/', payload={'barcode': barcode}, idempotency_key=key)
except ToolError as exc:
return {'status': 'failed', 'reason': str(exc), 'idempotency_key': key}
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Create one food log entry for the authenticated user. For known foods, search TaskNest products first and use product_id; do not fabricate nutrition when reliable product data exists. For a user-requested estimated meal, product_name and estimated nutrition are allowed. Uses the user’s local date unless date is supplied. Reuse idempotency_key on retries.')
async def food_log(food: FoodInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
@@ -307,6 +365,15 @@ def create_server() -> MCPServer:
item = await api_request('POST', 'kitchen/items/', payload=payload, idempotency_key=key)
return {'success': True, 'item': _inventory(item), 'idempotency_key': key}
@server.tool(structured_output=True, description='Add up to 20 groceries to your inventory in one operation. Resolves owned products, may query Open Food Facts, optionally creates manual products from supplied facts, and adds separate inventory rows. Ambiguous matches require review; each item reports success or failure. Does not interpret images. Reuse idempotency_key with the same payload on retries; changed payloads conflict.')
async def inventory_import_groceries(items: list[GroceryInput], idempotency_key: str,
create_missing_products: bool = False) -> dict[str, Any]:
key = _key(idempotency_key)
data = await api_request('POST', 'kitchen/import-groceries/', payload={
'items': [item.model_dump(mode='json', exclude_none=True) for item in items],
'create_missing_products': create_missing_products}, idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Update only the supplied fields of one inventory item belonging to the authenticated user. Changes existing data.')
async def inventory_update(item_id: str, changes: InventoryUpdate) -> dict[str, Any]:
item = await api_request('PATCH', f'kitchen/items/{item_id}/', payload=changes.model_dump(mode='json', exclude_unset=True))