Recipes phase 5
This commit is contained in:
@@ -126,6 +126,69 @@ class HydrationSettingsUpdate(BaseModel):
|
||||
hydration_beverage_rules: dict[str, dict[str, Any]] | None = None
|
||||
|
||||
|
||||
class RecipeInput(BaseModel):
|
||||
title: str
|
||||
description: str = ''
|
||||
instructions_markdown: str = ''
|
||||
notes_markdown: str = ''
|
||||
preparation_minutes: int = Field(default=0, ge=0)
|
||||
cooking_minutes: int = Field(default=0, ge=0)
|
||||
default_servings: Decimal = Field(default=Decimal('2'), gt=0)
|
||||
yield_amount: Decimal | None = Field(default=None, gt=0)
|
||||
yield_unit: Literal['g', 'ml'] | None = None
|
||||
category: str = ''
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
status: Literal['draft', 'published'] = 'draft'
|
||||
|
||||
|
||||
class RecipeChanges(BaseModel):
|
||||
title: str | None = None
|
||||
description: str | None = None
|
||||
instructions_markdown: str | None = None
|
||||
notes_markdown: str | None = None
|
||||
preparation_minutes: int | None = Field(default=None, ge=0)
|
||||
cooking_minutes: int | None = Field(default=None, ge=0)
|
||||
default_servings: Decimal | None = Field(default=None, gt=0)
|
||||
yield_amount: Decimal | None = Field(default=None, gt=0)
|
||||
yield_unit: Literal['g', 'ml'] | None = None
|
||||
category: str | None = None
|
||||
tags: list[str] | None = None
|
||||
status: Literal['draft', 'published'] | None = None
|
||||
is_favourite: bool | None = None
|
||||
|
||||
|
||||
class RecipeIngredientInput(BaseModel):
|
||||
name: str
|
||||
quantity: Decimal = Field(gt=0)
|
||||
unit: Literal['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions']
|
||||
amount_per_unit: Decimal | None = Field(default=None, gt=0)
|
||||
amount_per_unit_unit: Literal['g', 'ml'] | None = None
|
||||
inventory_product_id: str | None = None
|
||||
nutrition_product_id: str | None = None
|
||||
preparation_note: str = ''
|
||||
is_optional: bool = False
|
||||
display_order: int = Field(default=0, ge=0)
|
||||
|
||||
|
||||
class RecipeIngredientChanges(BaseModel):
|
||||
name: str | None = None
|
||||
quantity: Decimal | None = Field(default=None, gt=0)
|
||||
unit: Literal['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions'] | None = None
|
||||
amount_per_unit: Decimal | None = Field(default=None, gt=0)
|
||||
amount_per_unit_unit: Literal['g', 'ml'] | None = None
|
||||
inventory_product_id: str | None = None
|
||||
nutrition_product_id: str | None = None
|
||||
preparation_note: str | None = None
|
||||
is_optional: bool | None = None
|
||||
display_order: int | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class RecipeAnalysisInput(BaseModel):
|
||||
servings: Decimal | None = Field(default=None, gt=0)
|
||||
include_optional: bool = False
|
||||
substitutions: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _token() -> str:
|
||||
access = get_access_token()
|
||||
if access is None:
|
||||
@@ -460,6 +523,106 @@ def create_server() -> MCPServer:
|
||||
return await api_request('PATCH', 'hydration/settings/',
|
||||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||||
|
||||
@server.tool(structured_output=True, description='Search your own recipes by title, description, or ingredient name. Returns recipe IDs and summaries; read only.')
|
||||
async def recipe_search(query: str = '', category: str = '', limit: int = 20) -> dict[str, Any]:
|
||||
return await api_request('GET', 'recipes/', params={'query': query, 'category': category, 'limit': limit})
|
||||
|
||||
@server.tool(structured_output=True, description='Read one owned recipe with Markdown instructions, ingredients, substitutions, related variations, and subrecipes. Read only.')
|
||||
async def recipe_get(recipe_id: str) -> dict[str, Any]:
|
||||
return await api_request('GET', f'recipes/{recipe_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Create an owned recipe. Add measured ingredients with recipe_ingredient_add. Reuse idempotency_key on retries.')
|
||||
async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
data = await api_request('POST', 'recipes/create/',
|
||||
payload=recipe.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||||
return {'recipe': data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Update supplied fields of one owned recipe, including Markdown and serving yield. Existing variations remain independent.')
|
||||
async def recipe_update(recipe_id: str, changes: RecipeChanges) -> dict[str, Any]:
|
||||
return await api_request('PATCH', f'recipes/{recipe_id}/',
|
||||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||||
|
||||
@server.tool(structured_output=True, description='Delete one owned recipe and its ingredients. Existing Food Diary nutrition snapshots remain unchanged. Require clear user intent.')
|
||||
async def recipe_delete(recipe_id: str) -> dict[str, Any]:
|
||||
return await api_request('DELETE', f'recipes/{recipe_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Create an independently editable copy linked as a variation of the owned recipe. Copies ingredients, substitutions, and subrecipes. Reuse idempotency_key on retries.')
|
||||
async def recipe_create_variation(recipe_id: str, title: str | None = None,
|
||||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
data = await api_request('POST', f'recipes/{recipe_id}/variations/',
|
||||
payload={'title': title} if title else {}, idempotency_key=key)
|
||||
return {'recipe': data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Add a measured ingredient to one owned recipe. Use owned food product IDs for unambiguous stock and nutrition matching.')
|
||||
async def recipe_ingredient_add(recipe_id: str, ingredient: RecipeIngredientInput,
|
||||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
data = await api_request('POST', f'recipes/{recipe_id}/ingredients/',
|
||||
payload=ingredient.model_dump(mode='json', exclude_none=True), idempotency_key=key)
|
||||
return {'ingredient': data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Correct only the supplied fields of an ingredient in an owned recipe.')
|
||||
async def recipe_ingredient_update(recipe_id: str, ingredient_id: int,
|
||||
changes: RecipeIngredientChanges) -> dict[str, Any]:
|
||||
return await api_request('PATCH', f'recipes/{recipe_id}/ingredients/{ingredient_id}/',
|
||||
payload=changes.model_dump(mode='json', exclude_unset=True))
|
||||
|
||||
@server.tool(structured_output=True, description='Remove one ingredient from an owned recipe. Require clear user intent.')
|
||||
async def recipe_ingredient_delete(recipe_id: str, ingredient_id: int) -> dict[str, Any]:
|
||||
return await api_request('DELETE', f'recipes/{recipe_id}/ingredients/{ingredient_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Attach another owned recipe as a reusable subrecipe. Cycles and cross-user references are rejected. Reuse idempotency_key on retries.')
|
||||
async def recipe_subrecipe_add(recipe_id: str, component_id: str,
|
||||
quantity: Decimal = Decimal('1'),
|
||||
unit: Literal['servings', 'g', 'ml'] = 'servings',
|
||||
note: str = '', idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
data = await api_request('POST', f'recipes/{recipe_id}/subrecipes/',
|
||||
payload={'component_id': component_id, 'quantity': str(quantity),
|
||||
'unit': unit, 'note': note}, idempotency_key=key)
|
||||
return {'subrecipe': data, 'idempotency_key': key}
|
||||
|
||||
@server.tool(structured_output=True, description='Remove one reusable subrecipe link from an owned recipe; the component recipe remains.')
|
||||
async def recipe_subrecipe_remove(recipe_id: str, subrecipe_id: int) -> dict[str, Any]:
|
||||
return await api_request('DELETE', f'recipes/{recipe_id}/subrecipes/{subrecipe_id}/')
|
||||
|
||||
@server.tool(structured_output=True, description='Check scaled ingredient availability and nutrition, with exact package deductions. Read only. If ready, returns a short-lived confirmation token for explicit inventory deduction.')
|
||||
async def recipe_check_inventory(recipe_id: str, options: RecipeAnalysisInput = None) -> dict[str, Any]:
|
||||
return await api_request('POST', f'recipes/{recipe_id}/stock/preview/',
|
||||
payload=(options or RecipeAnalysisInput()).model_dump(mode='json'))
|
||||
|
||||
@server.tool(structured_output=True, description='Deduct the exact recipe packages approved in a recent recipe_check_inventory preview. Requires the user’s explicit approval and the returned confirmation token. Replays of the same token do not double count.')
|
||||
async def recipe_deduct_inventory(recipe_id: str, confirmation: str) -> dict[str, Any]:
|
||||
return await api_request('POST', f'recipes/{recipe_id}/stock/confirm/',
|
||||
payload={'confirmation': confirmation})
|
||||
|
||||
@server.tool(structured_output=True, description='Undo a confirmed recipe inventory deduction when the affected packages have not changed since. Does not remove Food Diary entries.')
|
||||
async def recipe_undo_inventory(stock_use_id: str) -> dict[str, Any]:
|
||||
return await api_request('POST', f'recipes/stock-use/{stock_use_id}/undo/', payload={})
|
||||
|
||||
@server.tool(structured_output=True, description='Log a personally consumed portion of an owned recipe to Food Diary using a historical nutrition snapshot. This never deducts inventory. Specify prepared and consumed servings separately; reuse idempotency_key on retries.')
|
||||
async def recipe_log_meal(recipe_id: str, consumed_servings: Decimal,
|
||||
meal: Literal['breakfast', 'lunch', 'dinner', 'snacks'],
|
||||
servings: Decimal | None = None, date: str | None = None,
|
||||
time: str | None = None, include_optional: bool = False,
|
||||
substitutions: dict[str, str] | None = None,
|
||||
idempotency_key: str | None = None) -> dict[str, Any]:
|
||||
key = _key(idempotency_key)
|
||||
payload = {'consumed_servings': str(consumed_servings), 'meal': meal,
|
||||
'include_optional': include_optional,
|
||||
'substitutions': substitutions or {}}
|
||||
if servings is not None:
|
||||
payload['servings'] = str(servings)
|
||||
if date is not None:
|
||||
payload['date'] = date
|
||||
if time is not None:
|
||||
payload['time'] = time
|
||||
data = await api_request('POST', f'recipes/{recipe_id}/log/',
|
||||
payload=payload, idempotency_key=key)
|
||||
return {**data, 'idempotency_key': key}
|
||||
|
||||
return server
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ from oauth2_provider.models import Application
|
||||
from food.api import create_token
|
||||
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
|
||||
from planner.timezones import localdate_for_user
|
||||
from recipes.models import Recipe, RecipeUse
|
||||
from .server import ClientImageFile, _allowed_file_host, _resolve_image
|
||||
|
||||
|
||||
@@ -211,7 +212,7 @@ class McpHttpTests(LiveServerTestCase):
|
||||
|
||||
async def check(client):
|
||||
names = {tool.name for tool in (await client.list_tools()).tools}
|
||||
self.assertEqual(len(names), 26)
|
||||
self.assertEqual(len(names), 41)
|
||||
self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product',
|
||||
'inventory_import_groceries'} <= names)
|
||||
today = (await client.call_tool('food_get_today')).structured_content
|
||||
@@ -323,3 +324,87 @@ class McpHttpTests(LiveServerTestCase):
|
||||
'transaction_id': used['transaction_id']})).structured_content
|
||||
self.assertEqual(undone['reverses'], used['transaction_id'])
|
||||
asyncio.run(self._client(self.secret, check))
|
||||
|
||||
def test_recipe_tools_end_to_end_with_separate_stock_and_meal_actions(self):
|
||||
location = InventoryLocation.objects.create(user=self.a, name='Recipe pantry')
|
||||
package = KitchenInventoryItem.objects.create(
|
||||
user=self.a, product=self.a_product, location=location,
|
||||
original_amount=Decimal('300'), remaining_amount=Decimal('300'), inventory_unit='g')
|
||||
|
||||
async def check(client):
|
||||
created = await client.call_tool('recipe_create', {'recipe': {
|
||||
'title': 'Pasta supper', 'default_servings': '2',
|
||||
'instructions_markdown': 'Cook pasta.'}, 'idempotency_key': 'recipe-supper'})
|
||||
self.assertFalse(created.is_error, created)
|
||||
recipe_id = created.structured_content['recipe']['id']
|
||||
again = (await client.call_tool('recipe_create', {'recipe': {
|
||||
'title': 'Pasta supper', 'default_servings': '2',
|
||||
'instructions_markdown': 'Cook pasta.'}, 'idempotency_key': 'recipe-supper'})).structured_content
|
||||
self.assertEqual(again['recipe']['id'], recipe_id)
|
||||
self.assertEqual((await client.call_tool('recipe_search',
|
||||
{'query': 'Pasta supper'})).structured_content['count'], 1)
|
||||
ingredient = (await client.call_tool('recipe_ingredient_add', {'recipe_id': recipe_id,
|
||||
'ingredient': {'name': 'Pasta', 'quantity': '200', 'unit': 'g',
|
||||
'inventory_product_id': str(self.a_product.api_id),
|
||||
'nutrition_product_id': str(self.a_product.api_id)},
|
||||
'idempotency_key': 'recipe-pasta-ingredient'})).structured_content['ingredient']
|
||||
self.assertEqual(ingredient['name'], 'Pasta')
|
||||
self.assertEqual((await client.call_tool('recipe_get',
|
||||
{'recipe_id': recipe_id})).structured_content['ingredients'][0]['id'], ingredient['id'])
|
||||
self.assertFalse((await client.call_tool('recipe_ingredient_update', {
|
||||
'recipe_id': recipe_id, 'ingredient_id': ingredient['id'],
|
||||
'changes': {'quantity': '150'}})).is_error)
|
||||
variation = (await client.call_tool('recipe_create_variation', {
|
||||
'recipe_id': recipe_id, 'title': 'Spicy pasta',
|
||||
'idempotency_key': 'recipe-spicy'})).structured_content['recipe']
|
||||
self.assertEqual(variation['parent_id'], recipe_id)
|
||||
self.assertEqual(variation['ingredients'][0]['quantity'], '150.000')
|
||||
component = (await client.call_tool('recipe_create', {
|
||||
'recipe': {'title': 'Pasta topping'}, 'idempotency_key': 'recipe-topping'})).structured_content['recipe']
|
||||
attached = (await client.call_tool('recipe_subrecipe_add', {
|
||||
'recipe_id': recipe_id, 'component_id': component['id'],
|
||||
'idempotency_key': 'recipe-attach-topping'})).structured_content['subrecipe']
|
||||
self.assertEqual(attached['component_id'], component['id'])
|
||||
self.assertTrue((await client.call_tool('recipe_subrecipe_add', {
|
||||
'recipe_id': component['id'], 'component_id': recipe_id})).is_error)
|
||||
self.assertFalse((await client.call_tool('recipe_subrecipe_remove', {
|
||||
'recipe_id': recipe_id, 'subrecipe_id': attached['id']})).is_error)
|
||||
preview = (await client.call_tool('recipe_check_inventory', {
|
||||
'recipe_id': recipe_id})).structured_content
|
||||
self.assertTrue(preview['stock_ready'])
|
||||
self.assertEqual(preview['products'][0]['deductions'][0]['amount'], '150.000')
|
||||
stock = (await client.call_tool('recipe_deduct_inventory', {
|
||||
'recipe_id': recipe_id, 'confirmation': preview['confirmation']})).structured_content
|
||||
self.assertTrue(stock['created'])
|
||||
replay = (await client.call_tool('recipe_deduct_inventory', {
|
||||
'recipe_id': recipe_id, 'confirmation': preview['confirmation']})).structured_content
|
||||
self.assertFalse(replay['created'])
|
||||
logged = (await client.call_tool('recipe_log_meal', {'recipe_id': recipe_id,
|
||||
'consumed_servings': '0.5', 'servings': '2', 'meal': 'dinner',
|
||||
'idempotency_key': 'recipe-meal-supper'})).structured_content
|
||||
self.assertEqual(logged['nutrition']['calories_kcal'], '131.250')
|
||||
again = (await client.call_tool('recipe_log_meal', {'recipe_id': recipe_id,
|
||||
'consumed_servings': '0.5', 'servings': '2', 'meal': 'dinner',
|
||||
'idempotency_key': 'recipe-meal-supper'})).structured_content
|
||||
self.assertEqual(again['entry_id'], logged['entry_id'])
|
||||
self.assertFalse((await client.call_tool('recipe_update', {'recipe_id': recipe_id,
|
||||
'changes': {'title': 'Updated supper'}})).is_error)
|
||||
self.assertFalse((await client.call_tool('recipe_undo_inventory', {
|
||||
'stock_use_id': stock['stock_use_id']})).is_error)
|
||||
self.assertFalse((await client.call_tool('recipe_ingredient_delete', {
|
||||
'recipe_id': recipe_id, 'ingredient_id': ingredient['id']})).is_error)
|
||||
self.assertFalse((await client.call_tool('recipe_delete', {
|
||||
'recipe_id': component['id']})).is_error)
|
||||
self.assertFalse((await client.call_tool('recipe_delete', {
|
||||
'recipe_id': recipe_id})).is_error)
|
||||
return recipe_id, logged['entry_id']
|
||||
|
||||
recipe_id, entry_id = asyncio.run(self._client(self.secret, check))
|
||||
package.refresh_from_db()
|
||||
self.assertEqual(package.remaining_amount, Decimal('300'))
|
||||
self.assertEqual(RecipeUse.objects.count(), 1)
|
||||
self.assertEqual(FoodLogEntry.objects.get(api_id=entry_id).product_name_snapshot, 'Pasta supper')
|
||||
async def isolated(client):
|
||||
self.assertTrue((await client.call_tool('recipe_get', {'recipe_id': recipe_id})).is_error)
|
||||
self.assertTrue((await client.call_tool('recipe_check_inventory', {'recipe_id': recipe_id})).is_error)
|
||||
asyncio.run(self._client(self.b_secret, isolated))
|
||||
|
||||
Reference in New Issue
Block a user