latest changes

This commit is contained in:
Joren de Graaf
2026-10-17 11:38:57 +02:00
parent 86e3afaca7
commit 76c76bc281
31 changed files with 4562 additions and 41 deletions
+8
View File
@@ -98,6 +98,14 @@ The corresponding HTTP routes are listed in `GET /api/v1/schema/`. Recipe meal d
`inventory_update` accepts an absolute `remaining_amount` for one owned package. Reductions use the same consumption service as `inventory_consume`; zero archives the package. It can update `opened` and `notes` in the same request. A rejected quantity returns `success: false` with `error.details.field` and `error.details.reason`.
### Bulk inventory housekeeping
`inventory_bulk_update` accepts 1–20 `{item_id, changes}` entries. `changes` uses the same fields and stock rules as `inventory_update`; omitted fields stay unchanged. Optional `expected_updated_at` rejects an item that changed since it was read. `dry_run` defaults to true and returns per-item before/after snapshots without saving. Set `dry_run: false` and provide an `idempotency_key` to apply. The default allows valid entries to succeed when others fail; `atomic: true` rolls back the whole batch on any failure. Duplicate IDs and oversized batches are rejected before writes.
For example, preview two location changes with `items: [{"item_id": "…", "changes": {"location": "Metalen stellingkast"}}, {"item_id": "…", "changes": {"location": "Zwarte stellingkast"}}]`. Use the returned IDs and current item timestamps for execution. To correct expiry dates, set `best_before` to `YYYY-MM-DD` (or `null` to clear it).
`inventory_bulk_delete` accepts 1–20 explicit `item_ids` and defaults to a read-only preview showing names, quantities and locations. To archive those exact rows, use `dry_run: false`, `confirm: true` and a new `idempotency_key`. It never deletes food products or consumption history. Reuse the same key and payload for retries; a changed payload with the same key is rejected. Both tools report `validated`, `changed`, `unchanged`, `failed` or `rolled_back` per item and aggregate counts. Re-read inventory before cleanup after an interrupted request.
Example tool arguments:
```json
+167 -38
View File
@@ -665,45 +665,58 @@ def inventory_change(request, identifier):
).select_related('product', 'location', 'category').first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
remaining = data.get('remaining_amount', item.remaining_amount)
if 'remaining_amount' in data and remaining is not None:
try:
remaining = _decimal(remaining, 'remaining_amount')
except ValueError as exc:
return _inventory_validation('remaining_amount', str(exc))
if item.original_amount is None or item.remaining_amount is None:
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
if remaining > item.original_amount:
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
if remaining != remaining.quantize(Decimal('.001')):
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
if remaining > item.remaining_amount:
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
if remaining < item.remaining_amount:
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
if conflicting:
return _inventory_validation(sorted(conflicting)[0],
'Change package identity or size separately from consumption.')
if data.get('opened') is False and remaining > 0:
return _inventory_validation('opened', 'A partly used package must be opened.')
from .services.inventory_consumption import StockError, consume
try:
consume(request.api_user, item.product, item.remaining_amount - remaining,
item.inventory_unit, package_id=item.api_id, source='mcp',
description=str(data.get('notes') or '')[:255])
except StockError as exc:
return _inventory_validation('remaining_amount', str(exc))
item.refresh_from_db()
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
elif 'remaining_amount' in data:
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
item, failure = _save_inventory(request, data, item)
return failure or JsonResponse(_inventory_data(item))
return _apply_inventory_update(request, item, data)
except (ValueError, ValidationError) as exc:
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
field, messages = next(iter(exc.message_dict.items()))
return _inventory_validation(field, '; '.join(messages))
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
return _inventory_exception(exc)
def _apply_inventory_update(request, item, data):
"""Shared single-item rules for PATCH and batch updates; caller owns the transaction."""
data = dict(data)
try:
remaining = data.get('remaining_amount', item.remaining_amount)
if 'remaining_amount' in data and remaining is not None:
try:
remaining = _decimal(remaining, 'remaining_amount')
except ValueError as exc:
return _inventory_validation('remaining_amount', str(exc))
if item.original_amount is None or item.remaining_amount is None:
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
if remaining > item.original_amount:
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
if remaining != remaining.quantize(Decimal('.001')):
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
if remaining > item.remaining_amount:
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
if remaining < item.remaining_amount:
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
if conflicting:
return _inventory_validation(sorted(conflicting)[0],
'Change package identity or size separately from consumption.')
if data.get('opened') is False and remaining > 0:
return _inventory_validation('opened', 'A partly used package must be opened.')
from .services.inventory_consumption import StockError, consume
try:
consume(request.api_user, item.product, item.remaining_amount - remaining,
item.inventory_unit, package_id=item.api_id, source='mcp',
description=str(data.get('notes') or '')[:255])
except StockError as exc:
return _inventory_validation('remaining_amount', str(exc))
item.refresh_from_db()
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
elif 'remaining_amount' in data:
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
item, failure = _save_inventory(request, data, item)
return failure or JsonResponse(_inventory_data(item))
except (ValueError, ValidationError) as exc:
return _inventory_exception(exc)
def _inventory_exception(exc):
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
field, messages = next(iter(exc.message_dict.items()))
return _inventory_validation(field, '; '.join(messages))
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
def _inventory_validation(field, reason):
@@ -711,6 +724,122 @@ def _inventory_validation(field, reason):
{'field': field, 'reason': reason})
def _inventory_batch_input(request, data, *, deleting=False):
rows = data.get('item_ids' if deleting else 'items')
if not isinstance(rows, list) or not 1 <= len(rows) <= 20:
raise ValueError('Provide between 1 and 20 inventory items.')
if set(data) - ({'item_ids', 'dry_run', 'atomic', 'confirm'} if deleting else {'items', 'dry_run', 'atomic'}):
raise ValueError('Unknown bulk inventory fields.')
if any(type(data.get(key, default)) is not bool for key, default in (('dry_run', False), ('atomic', False))):
raise ValueError('dry_run and atomic must be booleans.')
if deleting and type(data.get('confirm', False)) is not bool:
raise ValueError('confirm must be a boolean.')
parsed = []
for raw in rows:
if deleting:
identifier = raw
changes = None
expected = None
else:
if not isinstance(raw, dict) or set(raw) - {'item_id', 'changes', 'expected_updated_at'}:
raise ValueError('Each update needs item_id and changes.')
identifier = raw.get('item_id')
changes = raw.get('changes')
expected = raw.get('expected_updated_at')
if not isinstance(changes, dict) or not changes or set(changes) - {
'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'remaining_amount', 'best_before'}:
raise ValueError('Each update needs supported, nonempty changes.')
if expected is not None and not isinstance(expected, str):
raise ValueError('expected_updated_at must be a timestamp.')
parsed.append((_uuid(identifier), changes, expected))
if len({identifier for identifier, _, _ in parsed}) != len(parsed):
raise ValueError('Duplicate inventory item IDs are not allowed.')
return parsed
def _inventory_batch(request, parsed, *, deleting, dry_run, atomic):
results = []
with transaction.atomic():
type(request.api_user).objects.select_for_update().get(pk=request.api_user.pk)
for identifier, changes, expected in parsed:
with transaction.atomic():
item = KitchenInventoryItem.objects.select_for_update().filter(
user=request.api_user, api_id=identifier, archived_at__isnull=True,
).select_related('product', 'location', 'category').first()
if item is None:
result = {'item_id': str(identifier), 'status': 'failed', 'error': {
'code': 'inventory_item_not_found', 'message': 'Inventory item not found or unavailable.'}}
results.append(result)
continue
before = _inventory_data(item)
if expected is not None and expected != item.updated_at.isoformat():
results.append({'item_id': str(identifier), 'status': 'failed', 'before': before,
'error': {'code': 'inventory_conflict', 'message': 'Item changed since it was read.'}})
continue
if deleting:
item.archived_at = timezone.now()
item.save(update_fields=('archived_at', 'updated_at'))
after = _inventory_data(item)
failed = False
else:
response = _apply_inventory_update(request, item, changes)
failed = response.status_code >= 400
if failed:
result = {'item_id': str(identifier), 'status': 'failed', 'before': before,
'error': json.loads(response.content)['error']}
transaction.set_rollback(True)
results.append(result)
continue
after = json.loads(response.content)
meaningful = {key: value for key, value in after.items() if key != 'updated_at'} != {
key: value for key, value in before.items() if key != 'updated_at'}
results.append({'item_id': str(identifier), 'status': 'validated' if dry_run and meaningful else
'changed' if meaningful else 'unchanged', 'before': before, 'after': after})
if dry_run or not meaningful:
transaction.set_rollback(True)
failed_count = sum(row['status'] == 'failed' for row in results)
if atomic and failed_count and not dry_run:
for row in results:
if row['status'] == 'changed':
row['status'] = 'rolled_back'
transaction.set_rollback(True)
if dry_run:
transaction.set_rollback(True)
counts = {status: sum(row['status'] == status for row in results) for status in
('validated', 'changed', 'unchanged', 'failed', 'rolled_back')}
return JsonResponse({'dry_run': dry_run, 'atomic': atomic, 'items': results, 'counts': counts,
'status': 'preview' if dry_run else 'rolled_back' if atomic and failed_count else
'partial_success' if failed_count else 'success'})
@api_view('inventory:write', ('POST',))
def inventory_bulk_update(request):
if len(request.body) > 65536:
return error('batch_too_large', 'Batch payload exceeds 64 KB.', 413)
data = _json(request)
parsed = _inventory_batch_input(request, data)
dry_run = data.get('dry_run', True)
if not dry_run and not request.headers.get('Idempotency-Key'):
return error('idempotency_key_required', 'Provide an Idempotency-Key.', 400)
action = lambda: _inventory_batch(request, parsed, deleting=False, dry_run=dry_run, atomic=data.get('atomic', False))
return action() if dry_run else _idempotent(request, data, action)
@api_view('inventory:write', ('POST',))
def inventory_bulk_delete(request):
if len(request.body) > 65536:
return error('batch_too_large', 'Batch payload exceeds 64 KB.', 413)
data = _json(request)
parsed = _inventory_batch_input(request, data, deleting=True)
dry_run = data.get('dry_run', True)
if not dry_run and not data.get('confirm', False):
return error('confirmation_required', 'Preview the items and explicitly confirm deletion.', 400)
if not dry_run and not request.headers.get('Idempotency-Key'):
return error('idempotency_key_required', 'Provide an Idempotency-Key.', 400)
action = lambda: _inventory_batch(request, parsed, deleting=True, dry_run=dry_run, atomic=data.get('atomic', False))
return action() if dry_run else _idempotent(request, data, action)
@api_view('food:write', ('POST',))
def attachment_create(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).first()
+23 -1
View File
@@ -48,6 +48,17 @@ GROCERIES = {'type': 'object', 'required': ['items'], 'properties': {
'items': {'type': 'array', 'minItems': 1, 'maxItems': 20, 'items': {'type': 'object'}},
'create_missing_products': {'type': 'boolean'},
}}
BULK_INVENTORY_UPDATE = {'type': 'object', 'required': ['items'], 'properties': {
'items': {'type': 'array', 'minItems': 1, 'maxItems': 20, 'items': {'type': 'object',
'required': ['item_id', 'changes'], 'properties': {'item_id': {'type': 'string', 'format': 'uuid'},
'changes': INVENTORY, 'expected_updated_at': {'type': 'string', 'format': 'date-time'}}}},
'dry_run': {'type': 'boolean', 'default': True}, 'atomic': {'type': 'boolean', 'default': False},
}}
BULK_INVENTORY_DELETE = {'type': 'object', 'required': ['item_ids'], 'properties': {
'item_ids': {'type': 'array', 'minItems': 1, 'maxItems': 20, 'items': {'type': 'string', 'format': 'uuid'}},
'dry_run': {'type': 'boolean', 'default': True}, 'confirm': {'type': 'boolean', 'default': False},
'atomic': {'type': 'boolean', 'default': False},
}}
UPLOAD = {'type': 'object', 'required': ['image'], 'properties': {
'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'},
}}
@@ -123,6 +134,10 @@ def schema(request):
},
'/kitchen/import-groceries/': {'post': operation('Import up to 20 groceries with per-item results',
'inventory:write + food:write', GROCERIES)},
'/kitchen/bulk-update/': {'post': operation('Preview or update up to 20 inventory items; execution requires Idempotency-Key',
'inventory:write', BULK_INVENTORY_UPDATE)},
'/kitchen/bulk-delete/': {'post': operation('Preview or archive up to 20 inventory items; execution requires confirm and Idempotency-Key',
'inventory:write', BULK_INVENTORY_DELETE)},
'/kitchen/items/{id}/': {
'get': operation('Read own inventory item', 'inventory:read'),
'patch': operation('Update own inventory item', 'inventory:write', INVENTORY),
@@ -191,7 +206,8 @@ def schema(request):
'schema': {'type': 'integer', 'minimum': 1}})
if 'post' in methods:
methods['post']['responses']['201'] = methods['post']['responses'].pop('200')
for path in ('/kitchen/consumption/preview/', '/kitchen/consumption/',
for path in ('/kitchen/bulk-update/', '/kitchen/bulk-delete/',
'/kitchen/consumption/preview/', '/kitchen/consumption/',
'/kitchen/consumption/{id}/undo/', '/recipes/{id}/stock/preview/',
'/recipes/{id}/stock/confirm/', '/recipes/stock-use/{id}/undo/'):
document['paths'][path]['post']['responses']['200'] = document['paths'][path]['post']['responses'].pop('201')
@@ -215,6 +231,12 @@ def schema(request):
'name': 'Idempotency-Key', 'in': 'header', 'required': True,
'schema': {'type': 'string', 'maxLength': 128},
}]
for path in ('/kitchen/bulk-update/', '/kitchen/bulk-delete/'):
document['paths'][path]['post']['parameters'] = [{
'name': 'Idempotency-Key', 'in': 'header', 'required': False,
'description': 'Required when dry_run is false.',
'schema': {'type': 'string', 'maxLength': 128},
}]
document['paths']['/recipes/{id}/log/']['post']['parameters'] = [{
'name': 'Idempotency-Key', 'in': 'header', 'required': True,
'schema': {'type': 'string', 'maxLength': 128},
+2
View File
@@ -17,6 +17,8 @@ urlpatterns = [
path('food/attachments/<uuid:identifier>/', api.attachment_delete),
path('kitchen/items/', api.inventory_collection),
path('kitchen/import-groceries/', api.inventory_import_groceries),
path('kitchen/bulk-update/', api.inventory_bulk_update),
path('kitchen/bulk-delete/', api.inventory_bulk_delete),
path('kitchen/items/<uuid:identifier>/', api.inventory_item),
path('kitchen/stock/', api.inventory_stock),
path('kitchen/consumption/preview/', api.inventory_preview),
+92
View File
@@ -39,6 +39,98 @@ class FoodApiTests(TestCase):
data = json.dumps(data)
return getattr(self.client, method)(path, data=data, **args)
def test_bulk_inventory_update_preview_partial_atomic_and_retry(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
items = [KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
for _ in range(2)]
path = '/api/v1/kitchen/bulk-update/'
rows = [{'item_id': str(item.api_id), 'changes': {'location': ' Metal shelf ', 'best_before': '2026-11-01'}}
for item in items]
preview = self.call('post', path, {'items': rows, 'dry_run': True})
self.assertEqual(preview.status_code, 200, preview.content)
self.assertEqual(preview.json()['counts']['validated'], 2)
self.assertFalse(InventoryLocation.objects.filter(user=self.a, name='Metal shelf').exists())
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], location=location).count(), 2)
rows.append({'item_id': str(self.item_b.api_id), 'changes': {'notes': 'foreign'}})
atomic = self.call('post', path, {'items': rows, 'dry_run': False, 'atomic': True}, HTTP_IDEMPOTENCY_KEY='bulk-atomic')
self.assertEqual(atomic.json()['status'], 'rolled_back')
self.assertEqual(atomic.json()['counts']['rolled_back'], 2)
self.assertFalse(InventoryLocation.objects.filter(user=self.a, name='Metal shelf').exists())
partial_payload = {'items': rows, 'dry_run': False}
partial = self.call('post', path, partial_payload, HTTP_IDEMPOTENCY_KEY='bulk-partial')
self.assertEqual(partial.json()['counts']['changed'], 2)
self.assertEqual(partial.json()['counts']['failed'], 1)
self.assertEqual(self.call('post', path, partial_payload, HTTP_IDEMPOTENCY_KEY='bulk-partial').json(), partial.json())
self.assertEqual(self.call('post', path, {**partial_payload, 'atomic': True}, HTTP_IDEMPOTENCY_KEY='bulk-partial').status_code, 409)
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], location__name='Metal shelf').count(), 2)
self.assertEqual(KitchenInventoryItem.objects.get(pk=self.item_b.pk).notes, '')
def test_bulk_inventory_rejects_duplicates_limits_and_stale_timestamp(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
path = '/api/v1/kitchen/bulk-update/'
row = {'item_id': str(item.api_id), 'changes': {'notes': 'new'}}
self.assertEqual(self.call('post', path, {'items': [row, row], 'dry_run': False}, HTTP_IDEMPOTENCY_KEY='dup').status_code, 400)
self.assertEqual(self.call('post', path, {'items': [row] * 21, 'dry_run': False}, HTTP_IDEMPOTENCY_KEY='large').status_code, 400)
self.assertEqual(self.call('post', path, {'items': [row], 'dry_run': False}).json()['error']['code'], 'idempotency_key_required')
result = self.call('post', path, {'items': [{**row, 'expected_updated_at': '2000-01-01T00:00:00+00:00'}],
'dry_run': False}, HTTP_IDEMPOTENCY_KEY='stale')
self.assertEqual(result.json()['items'][0]['error']['code'], 'inventory_conflict')
item.refresh_from_db()
self.assertEqual(item.notes, '')
def test_bulk_inventory_accepts_twenty_updates_in_one_request(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
items = [KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
for _ in range(20)]
payload = {'items': [{'item_id': str(item.api_id), 'changes': {'notes': 'Checked'}} for item in items],
'dry_run': False}
result = self.call('post', '/api/v1/kitchen/bulk-update/', payload, HTTP_IDEMPOTENCY_KEY='twenty-items')
self.assertEqual(result.status_code, 200, result.content)
self.assertEqual(result.json()['counts']['changed'], 20)
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, notes='Checked').count(), 20)
def test_bulk_inventory_delete_preview_confirm_and_history(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
path = '/api/v1/kitchen/bulk-delete/'
payload = {'item_ids': [str(item.api_id), str(self.item_b.api_id)]}
preview = self.call('post', path, payload).json()
self.assertEqual(preview['counts']['validated'], 1)
self.assertEqual(preview['counts']['failed'], 1)
self.assertEqual(preview['items'][0]['before']['product_name'], 'Pasta')
item.refresh_from_db(); self.assertIsNone(item.archived_at)
self.assertEqual(self.call('post', path, {'item_ids': [str(item.api_id)] * 2}).status_code, 400)
self.assertEqual(self.call('post', path, {'item_ids': [str(item.api_id)] * 21}).status_code, 400)
self.assertEqual(self.call('post', path, {**payload, 'dry_run': False}, HTTP_IDEMPOTENCY_KEY='delete-no-confirm').status_code, 400)
atomic = self.call('post', path, {**payload, 'dry_run': False, 'confirm': True, 'atomic': True},
HTTP_IDEMPOTENCY_KEY='bulk-delete-atomic')
self.assertEqual(atomic.json()['status'], 'rolled_back')
item.refresh_from_db(); self.assertIsNone(item.archived_at)
run_payload = {**payload, 'dry_run': False, 'confirm': True}
run = self.call('post', path, run_payload, HTTP_IDEMPOTENCY_KEY='bulk-delete')
self.assertEqual(run.json()['counts']['changed'], 1)
self.assertEqual(self.call('post', path, run_payload, HTTP_IDEMPOTENCY_KEY='bulk-delete').json(), run.json())
item.refresh_from_db(); self.assertIsNotNone(item.archived_at)
self.assertTrue(FoodProduct.objects.filter(pk=self.product_a.pk).exists())
self.assertIsNone(KitchenInventoryItem.objects.get(pk=self.item_b.pk).archived_at)
def test_bulk_inventory_update_remaining_amount_uses_consumption_and_preview_rolls_back(self):
product = FoodProduct.objects.create(owner=self.a, product_name='Flour', package_amount=Decimal('500'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.a, product=product, location=location,
original_amount=Decimal('500'), remaining_amount=Decimal('500'), inventory_unit='g')
payload = {'items': [{'item_id': str(item.api_id), 'changes': {'remaining_amount': '400', 'opened': True}}]}
preview = self.call('post', '/api/v1/kitchen/bulk-update/', {**payload, 'dry_run': True})
self.assertEqual(preview.json()['counts']['validated'], 1)
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 0)
item.refresh_from_db(); self.assertEqual(item.remaining_amount, 500)
applied = self.call('post', '/api/v1/kitchen/bulk-update/', {**payload, 'dry_run': False},
HTTP_IDEMPOTENCY_KEY='bulk-stock-1')
self.assertEqual(applied.json()['counts']['changed'], 1)
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1)
item.refresh_from_db(); self.assertEqual(item.remaining_amount, 400)
def test_authentication_scopes_and_token_storage(self):
self.assertNotIn(self.secret, self.token.token_hash)
self.assertEqual(self.token.token_hash, hashlib.sha256(self.secret.encode()).hexdigest())
+27
View File
@@ -117,6 +117,12 @@ class InventoryUpdate(BaseModel):
best_before: str | None = None
class InventoryBulkUpdateEntry(BaseModel):
item_id: str
changes: InventoryUpdate
expected_updated_at: str | None = None
class HydrationSettingsUpdate(BaseModel):
daily_water_goal_ml: int | None = None
auto_count_food_drinks: bool | None = None
@@ -457,6 +463,27 @@ def create_server() -> MCPServer:
return {'success': False, 'error': item['error']}
return {'success': True, 'item': _inventory(item)}
@server.tool(structured_output=True, description='Preview or update up to 20 owned inventory rows. Uses inventory_update field rules. Partial success is default; atomic=true rolls back all updates if any item fails. Actual execution requires a unique idempotency_key; reuse the same key and payload on retry. Optionally supply expected_updated_at per item to reject concurrent edits.')
async def inventory_bulk_update(items: list[InventoryBulkUpdateEntry], idempotency_key: str | None = None,
dry_run: bool = True, atomic: bool = False) -> dict[str, Any]:
if not dry_run and not idempotency_key:
raise ToolError('idempotency_key_required: provide an idempotency key for updates')
data = await api_request('POST', 'kitchen/bulk-update/', payload={
'items': [{'item_id': row.item_id, 'changes': row.changes.model_dump(mode='json', exclude_unset=True),
**({'expected_updated_at': row.expected_updated_at} if row.expected_updated_at else {})}
for row in items], 'dry_run': dry_run, 'atomic': atomic}, idempotency_key=idempotency_key)
return {**data, 'idempotency_key': idempotency_key}
@server.tool(structured_output=True, description='Preview or archive up to 20 explicit owned inventory rows, without deleting products or consumption history. Dry run is default. Actual deletion requires confirm=true, a unique idempotency_key, and clear user intent. Partial success is default; atomic=true rolls back all deletions if any item fails.')
async def inventory_bulk_delete(item_ids: list[str], idempotency_key: str | None = None,
dry_run: bool = True, confirm: bool = False, atomic: bool = False) -> dict[str, Any]:
if not dry_run and (not confirm or not idempotency_key):
raise ToolError('confirmation_required: confirm=true and idempotency_key are required for deletion')
data = await api_request('POST', 'kitchen/bulk-delete/', payload={
'item_ids': item_ids, 'dry_run': dry_run, 'confirm': confirm, 'atomic': atomic},
idempotency_key=idempotency_key)
return {**data, 'idempotency_key': idempotency_key}
@server.tool(structured_output=True, description='Permanently remove one kitchen inventory item belonging to the authenticated user. This is destructive; require the user’s clear intent.')
async def inventory_remove(item_id: str) -> dict[str, Any]:
await api_request('DELETE', f'kitchen/items/{item_id}/')
+27
View File
@@ -173,6 +173,33 @@ class McpHttpTests(LiveServerTestCase):
asyncio.run(self._client(self.secret, check))
def test_inventory_bulk_update_and_delete_tools(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
items = [KitchenInventoryItem.objects.create(user=self.a, product=self.a_product, location=location)
for _ in range(2)]
ids = [str(item.api_id) for item in items]
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertIn('inventory_bulk_update', names)
self.assertIn('inventory_bulk_delete', names)
update = {'items': [{'item_id': identifier, 'changes': {'location': 'Metal shelf'}} for identifier in ids]}
preview = (await client.call_tool('inventory_bulk_update', update)).structured_content
self.assertEqual(preview['counts']['validated'], 2)
apply = {**update, 'dry_run': False, 'idempotency_key': 'mcp-bulk-update-1'}
changed = (await client.call_tool('inventory_bulk_update', apply)).structured_content
self.assertEqual(changed['counts']['changed'], 2)
self.assertEqual((await client.call_tool('inventory_bulk_update', apply)).structured_content, changed)
deletion = {'item_ids': ids}
self.assertEqual((await client.call_tool('inventory_bulk_delete', deletion)).structured_content['counts']['validated'], 2)
self.assertTrue((await client.call_tool('inventory_bulk_delete', {**deletion, 'dry_run': False})).is_error)
removed = (await client.call_tool('inventory_bulk_delete', {
**deletion, 'dry_run': False, 'confirm': True, 'idempotency_key': 'mcp-bulk-delete-1'})).structured_content
self.assertEqual(removed['counts']['changed'], 2)
asyncio.run(self._client(self.secret, check))
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], archived_at__isnull=False).count(), 2)
def test_oauth_issued_pat_authenticates_mcp(self):
application = Application.objects.create(user=self.a, name='Test ChatGPT style client',
client_type=Application.CLIENT_PUBLIC, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,