Files
Django_TasksApp/main/mcp_server/tests.py
T

570 lines
39 KiB
Python

import asyncio
import base64
import hashlib
import io
import os
import socket
import subprocess
import sys
import time
import uuid
from datetime import timedelta
from decimal import Decimal
from urllib.parse import parse_qs, urlparse
import httpx2
from PIL import Image
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import LiveServerTestCase, SimpleTestCase, override_settings
from django.utils import timezone
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.server.mcpserver.exceptions import ToolError
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
class ImageHostLoggingTests(SimpleTestCase):
def test_chatgpt_blob_account_is_allowed_without_allowing_other_blob_accounts(self):
self.assertTrue(_allowed_file_host('oaisdmntprukwest.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('other.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('not-oaisdmntprukwest.blob.core.windows.net'))
def test_rejected_file_logs_only_hostname(self):
image = ClientImageFile(download_url='https://files.example.invalid/private?signature=secret', file_id='test')
with self.assertLogs('mcp_server.server', level='WARNING') as captured:
with self.assertRaisesRegex(ToolError, 'not an allowed HTTPS file host'):
asyncio.run(_resolve_image(None, image, None, 'image'))
self.assertIn('files.example.invalid', captured.output[0])
self.assertNotIn('/private', captured.output[0])
self.assertNotIn('signature=secret', captured.output[0])
class McpHttpTests(LiveServerTestCase):
def setUp(self):
self.a = get_user_model().objects.create_user('mcp-a', password='test')
self.b = get_user_model().objects.create_user('mcp-b', password='test')
self.a_product = FoodProduct.objects.create(owner=self.a, product_name='Pasta', energy_kcal_100=Decimal('350'))
self.b_product = FoodProduct.objects.create(owner=self.b, product_name='Private rice')
self.b_entry = FoodLogEntry.objects.create(user=self.b, date=localdate_for_user(self.b), meal='lunch',
product=self.b_product, product_name_snapshot='Private rice', amount=Decimal('100'), unit='g')
location = InventoryLocation.objects.create(user=self.b, name='Private cupboard')
self.b_item = KitchenInventoryItem.objects.create(user=self.b, product=self.b_product, location=location)
_, self.secret = create_token(self.a, 'MCP test', ['food:read', 'food:write', 'inventory:read', 'inventory:write'])
_, self.b_secret = create_token(self.b, 'MCP test B', ['food:read', 'inventory:read'])
_, self.read_secret = create_token(self.a, 'MCP read', ['food:read'])
expired, self.expired_secret = create_token(self.a, 'MCP expired', ['food:read'], timezone.now() - timedelta(seconds=1))
revoked, self.revoked_secret = create_token(self.a, 'MCP revoked', ['food:read'])
revoked.revoked_at = timezone.now()
revoked.save(update_fields=['revoked_at'])
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
self.port = sock.getsockname()[1]
self.mcp_url = f'http://127.0.0.1:{self.port}/mcp'
env = {**os.environ, 'TASKNEST_API_BASE_URL': self.live_server_url + '/api/v1',
'TASKNEST_MCP_PUBLIC_URL': self.mcp_url,
'TASKNEST_OAUTH_ISSUER_URL': self.live_server_url}
self.process = subprocess.Popen([sys.executable, '-m', 'uvicorn', 'mcp_server.server:app',
'--host', '127.0.0.1', '--port', str(self.port), '--log-level', 'error'],
cwd=settings.BASE_DIR, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(50):
try:
response = httpx2.get(f'http://127.0.0.1:{self.port}/.well-known/oauth-protected-resource/mcp', timeout=1)
if response.status_code == 200:
self.assertEqual(response.json()['scopes_supported'],
['food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'])
break
except httpx2.RequestError:
pass
time.sleep(.1)
else:
self.fail('MCP server did not start.')
def tearDown(self):
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=5)
async def _client(self, secret, operation):
async with httpx2.AsyncClient(headers={'Authorization': 'Bearer ' + secret}, timeout=30) as http:
async with Client(streamable_http_client(self.mcp_url, http_client=http)) as client:
return await operation(client)
def test_nutrition_tools_discover_and_preview(self):
import hashlib
payload = {'source': {'programme': 'Body Support', 'document_name': 'sample.pdf',
'sha256': hashlib.sha256(b'sample').hexdigest()},
'ingredients': [{'row_key': 'p1-1', 'original_label': 'Broccoli vers',
'canonical_name': 'broccoli', 'quantity': '250', 'unit': 'g',
'page': 1, 'preparation': 'raw', 'category': 'vegetable'}]}
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertTrue({'nutrition_import_preview', 'nutrition_import_commit',
'nutrition_ingredients_search', 'nutrition_ingredient_correct'} <= names)
result = (await client.call_tool('nutrition_import_preview', {'payload': payload})).structured_content
self.assertEqual(result['blocking'], [])
self.assertEqual(result['ingredients'][0]['category'], 'vegetable')
self.assertFalse(result['existing_source_id'])
committed = (await client.call_tool('nutrition_import_commit', {
'payload': payload, 'confirmation': result['confirmation'], 'idempotency_key': 'nutrition-mcp-1'})).structured_content
self.assertEqual(committed['created'], 1)
repeated = (await client.call_tool('nutrition_import_commit', {
'payload': payload, 'confirmation': result['confirmation'], 'idempotency_key': 'nutrition-mcp-1'})).structured_content
self.assertTrue(repeated['idempotent'])
found = (await client.call_tool('nutrition_ingredients_search', {
'category': 'vegetable', 'programme': 'Body Support'})).structured_content
self.assertEqual(found['count'], 1)
self.assertEqual(found['results'][0]['sources'][0]['page'], 1)
corrected = (await client.call_tool('nutrition_ingredient_correct', {
'ingredient_id': found['results'][0]['id'], 'changes': {'subcategory': 'cruciferous'}})).structured_content
self.assertTrue(corrected['verified'])
asyncio.run(self._client(self.secret, check))
async def isolated(client):
found = (await client.call_tool('nutrition_ingredients_search', {'category': 'vegetable'})).structured_content
self.assertEqual(found['count'], 0)
denied = await client.call_tool('nutrition_import_preview', {'payload': payload})
self.assertTrue(denied.is_error)
asyncio.run(self._client(self.b_secret, isolated))
@override_settings(SECURE_SSL_REDIRECT=True)
def test_authentication_and_scope_boundaries(self):
async def check():
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + self.secret,
'Host': 'untrusted.example', 'Accept': 'application/json, text/event-stream'},
json={'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list'})
self.assertEqual(response.status_code, 421)
for secret in ('bad-token', self.expired_secret, self.revoked_secret):
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + secret,
'Accept': 'application/json, text/event-stream'}, json={'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list'})
self.assertEqual(response.status_code, 401)
async def read_only(client):
self.assertFalse((await client.call_tool('food_get_today')).is_error)
self.assertTrue((await client.call_tool('inventory_list')).is_error)
self.assertTrue((await client.call_tool('food_log', {'food': {
'meal': 'lunch', 'amount': '1', 'unit': 'g', 'product_name': 'No write'}})).is_error)
await self._client(self.read_secret, read_only)
asyncio.run(check())
def test_hydration_tools_and_food_logging_share_totals(self):
drink = FoodProduct.objects.create(owner=self.a, product_name='Orange juice', base_unit='ml')
async def check(client):
food = await client.call_tool('food_log', {'food': {'meal': 'lunch', 'amount': '200',
'unit': 'ml', 'product_id': str(drink.api_id)}})
self.assertFalse(food.is_error, food)
daily = (await client.call_tool('hydration_get_daily')).structured_content
self.assertEqual(daily['food_ml'], '200.000')
manual = (await client.call_tool('hydration_log', {'amount_ml': '125',
'idempotency_key': 'mcp-hydration-1'})).structured_content
self.assertEqual(manual['amount_ml'], '125')
again = (await client.call_tool('hydration_log', {'amount_ml': '125',
'idempotency_key': 'mcp-hydration-1'})).structured_content
self.assertEqual(again['id'], manual['id'])
daily = (await client.call_tool('hydration_get_daily')).structured_content
self.assertEqual(Decimal(daily['total_ml']), 325)
self.assertFalse((await client.call_tool('hydration_delete',
{'entry_id': manual['id']})).is_error)
self.assertEqual(Decimal((await client.call_tool('hydration_get_daily')).structured_content['total_ml']), 200)
asyncio.run(self._client(self.secret, check))
def test_stress_tools_support_incremental_updates(self):
_, journal_secret = create_token(self.a, 'Journal MCP test', ['journal:read', 'journal:write'])
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertTrue({'stress_create', 'stress_search', 'stress_get', 'stress_update', 'stress_delete'} <= names)
payload = {'entry': {'score': 7, 'timing': 'before_sleep', 'note': 'Work', 'tags': ['work']},
'idempotency_key': 'mcp-stress-test-1'}
created = (await client.call_tool('stress_create', payload)).structured_content
entry_id = created['id']
self.assertEqual((await client.call_tool('stress_create', payload)).structured_content['id'], entry_id)
updated = (await client.call_tool('stress_update', {'entry_id': entry_id,
'changes': {'note': 'Work and noise'}})).structured_content
self.assertEqual(updated['score'], 7)
self.assertEqual(updated['note'], 'Work and noise')
self.assertEqual((await client.call_tool('stress_get', {'entry_id': entry_id})).structured_content['note'], 'Work and noise')
self.assertEqual((await client.call_tool('stress_search', {'query': 'noise'})).structured_content['total'], 1)
self.assertFalse((await client.call_tool('stress_delete', {'entry_id': entry_id})).is_error)
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 0)
asyncio.run(self._client(journal_secret, check))
def test_dream_tools_create_and_append_without_duplicates(self):
_, journal_secret = create_token(self.a, 'Dream MCP test', ['journal:read', 'journal:write'])
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertTrue({'dream_create', 'dream_search', 'dream_get', 'dream_update', 'dream_delete'} <= names)
payload = {'entry': {'wake_up_date': '2026-10-18', 'title': 'A house',
'narrative': 'First memory.', 'tags': ['house']},
'idempotency_key': 'mcp-dream-create-1'}
created = (await client.call_tool('dream_create', payload)).structured_content
entry_id = created['id']
self.assertEqual((await client.call_tool('dream_create', payload)).structured_content['id'], entry_id)
append = {'entry_id': entry_id, 'changes': {'append_narrative': 'Second memory.'},
'idempotency_key': 'mcp-dream-append-1'}
self.assertFalse((await client.call_tool('dream_update', append)).is_error)
self.assertFalse((await client.call_tool('dream_update', append)).is_error)
entry = (await client.call_tool('dream_get', {'entry_id': entry_id})).structured_content
self.assertEqual(entry['narrative'], 'First memory.\n\nSecond memory.')
self.assertEqual((await client.call_tool('dream_search', {'tag': 'house'})).structured_content['total'], 1)
self.assertFalse((await client.call_tool('dream_delete', {'entry_id': entry_id})).is_error)
asyncio.run(self._client(journal_secret, check))
def test_inventory_update_partial_quantity_and_structured_validation(self):
product = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
package_amount=Decimal('400'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
package = KitchenInventoryItem.objects.create(user=self.a, product=product, location=location,
original_amount=Decimal('400'), remaining_amount=Decimal('400'), inventory_unit='g')
async def check(client):
changed = (await client.call_tool('inventory_update', {'item_id': str(package.api_id),
'changes': {'opened': True, 'remaining_amount': 280,
'notes': 'Used 120 g for dinner.'}})).structured_content
self.assertTrue(changed['success'])
self.assertEqual(Decimal(changed['item']['remaining_amount']), 280)
self.assertEqual(changed['item']['unit'], 'g')
stock = (await client.call_tool('inventory_get_stock',
{'product_id': str(product.api_id)})).structured_content
self.assertEqual(stock['products'][0]['totals']['g'], '280.000')
invalid = (await client.call_tool('inventory_update', {'item_id': str(package.api_id),
'changes': {'remaining_amount': 401}})).structured_content
self.assertFalse(invalid['success'])
self.assertEqual(invalid['error']['details']['field'], 'remaining_amount')
self.assertTrue((await client.call_tool('inventory_update', {'item_id': str(package.api_id),
'changes': {'remaining_amount': -1}})).is_error)
self.assertTrue((await client.call_tool('inventory_update', {'item_id': str(self.b_item.api_id),
'changes': {'notes': 'Unauthorized'}})).is_error)
unrelated = (await client.call_tool('inventory_update', {'item_id': str(package.api_id),
'changes': {'notes': 'Still in fridge'}})).structured_content
self.assertEqual(unrelated['item']['notes'], 'Still in fridge')
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_inventory_bulk_update_handles_twenty_three_rows_in_one_call(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(23)]
async def check(client):
request = {'items': [{'item_id': str(item.api_id), 'changes': {'notes': 'Audited'}} for item in items],
'dry_run': False, 'atomic': True, 'idempotency_key': 'mcp-bulk-23'}
result = (await client.call_tool('inventory_bulk_update', request)).structured_content
self.assertEqual(result['counts']['changed'], 23)
self.assertEqual(result['status'], 'success')
asyncio.run(self._client(self.secret, check))
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, notes='Audited').count(), 23)
def test_oauth_issued_pat_authenticates_mcp_with_journal_upgrade(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,
redirect_uris='http://localhost:9876/callback')
self.client.force_login(self.a)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
params = {'response_type': 'code', 'client_id': application.client_id,
'redirect_uri': 'http://localhost:9876/callback',
'scope': 'food:read food:write inventory:read inventory:write',
'state': 'mcp-oauth-test', 'code_challenge': challenge, 'code_challenge_method': 'S256',
'resource': self.mcp_url}
with override_settings(TASKNEST_MCP_PUBLIC_URL=self.mcp_url):
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'grant_journal_scopes')
form = response.context['form']
payload = {field.name: field.value() for field in form if field.field.widget.is_hidden and field.value() is not None}
payload['allow'] = 'Authorize'
payload['grant_journal_scopes'] = 'on'
payload['journal_scope_offer'] = response.context['journal_scope_offer']
with override_settings(TASKNEST_MCP_PUBLIC_URL=self.mcp_url):
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
response = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
'redirect_uri': 'http://localhost:9876/callback', 'client_id': application.client_id,
'code_verifier': verifier, 'resource': self.mcp_url}, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:200])
secret = response.json()['access_token']
self.assertEqual(set(response.json()['scope'].split()),
{'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'})
async def check(client):
self.assertFalse((await client.call_tool('food_get_today')).is_error)
self.assertFalse((await client.call_tool('inventory_list')).is_error)
dream = await client.call_tool('dream_create', {'entry': {'wake_up_date': '2026-10-18',
'title': 'User supplied', 'narrative': 'A room.'}, 'idempotency_key': 'oauth-dream-1'})
self.assertFalse(dream.is_error, dream)
dream_id = dream.structured_content['id']
self.assertEqual((await client.call_tool('dream_search', {'query': 'room'})).structured_content['total'], 1)
changed = await client.call_tool('dream_update', {'entry_id': dream_id,
'changes': {'append_narrative': 'A door.'}, 'idempotency_key': 'oauth-dream-append-1'})
self.assertFalse(changed.is_error, changed)
stress = await client.call_tool('stress_create', {'entry': {'score': 5},
'idempotency_key': 'oauth-stress-1'})
self.assertFalse(stress.is_error, stress)
self.assertEqual((await client.call_tool('stress_search')).structured_content['total'], 1)
asyncio.run(self._client(secret, check))
@override_settings(SECURE_SSL_REDIRECT=True)
def test_food_inventory_tools_and_user_isolation(self):
previous_day = localdate_for_user(self.a) - timedelta(days=1)
FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast',
product_name_snapshot='Yesterday oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
image = Image.new('RGB', (2, 2), 'red')
output = io.BytesIO()
image.save(output, format='PNG')
encoded = base64.b64encode(output.getvalue()).decode()
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertGreaterEqual(len(names), 44)
self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product',
'inventory_import_groceries', 'recipe_cook_later_add',
'recipe_cook_later_remove', 'recipe_cook_later_list'} <= names)
today = (await client.call_tool('food_get_today')).structured_content
self.assertEqual(today['meals']['lunch'], [])
yesterday = (await client.call_tool('food_get_today', {'date': previous_day.isoformat()})).structured_content
self.assertEqual(yesterday['date'], previous_day.isoformat())
self.assertEqual(yesterday['meals']['breakfast'][0]['name'], 'Yesterday oats')
self.assertEqual(yesterday['totals']['calories_kcal'], '120.000')
self.assertEqual(yesterday['goals']['fibre_goal_g'], '40.0')
self.assertIsNone(yesterday['totals']['fibre_g'])
self.assertTrue(yesterday['fibre_incomplete'])
self.assertNotIn('fibre_g', yesterday['remaining'])
self.assertTrue((await client.call_tool('food_get_today', {'date': 'yesterday'})).is_error)
products = (await client.call_tool('food_search_products', {'query': 'Pasta'})).structured_content
self.assertEqual(products['count'], 1)
self.assertEqual((await client.call_tool('food_search_products', {'query': 'Private rice'})).structured_content['count'], 0)
food = {'meal': 'dinner', 'amount': '50', 'unit': 'g', 'product_id': str(self.a_product.api_id)}
first = (await client.call_tool('food_log', {'food': food, 'idempotency_key': 'mcp-food-1'})).structured_content
self.assertEqual(first['entry']['calories_kcal'], '175.000')
again = (await client.call_tool('food_log', {'food': food, 'idempotency_key': 'mcp-food-1'})).structured_content
self.assertEqual(first['entry']['id'], again['entry']['id'])
entry_id = first['entry']['id']
updated = (await client.call_tool('food_update_entry', {'entry_id': entry_id,
'changes': {'amount': '100'}})).structured_content
self.assertEqual(updated['entry']['calories_kcal'], '350.000')
image_result = (await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_base64': encoded, 'mime_type': 'image/png', 'filename': 'meal.png',
'idempotency_key': 'mcp-image-1'})).structured_content
self.assertTrue(image_result['success'])
unsafe_file = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'http://127.0.0.1/private', 'file_id': 'test'}})
self.assertTrue(unsafe_file.is_error)
unknown_host = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'https://files.example.invalid/private?signature=secret',
'file_id': 'test'}})
self.assertTrue(unknown_host.is_error)
self.assertNotIn('files.example.invalid', str(unknown_host.content))
self.assertNotIn('signature=secret', str(unknown_host.content))
combined_food = {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Estimated meal', 'calories_kcal': '850'}
combined = (await client.call_tool('food_log_with_image', {'food': combined_food,
'image_base64': encoded, 'mime_type': 'image/png', 'idempotency_key': 'mcp-combined-1'})).structured_content
self.assertTrue(combined['attachment_added'])
partial = (await client.call_tool('food_log_with_image', {'food': combined_food,
'image_base64': 'bad!', 'mime_type': 'image/png', 'idempotency_key': 'mcp-combined-2'})).structured_content
self.assertTrue(partial['entry_created'])
self.assertFalse(partial['attachment_added'])
self.assertTrue((await client.call_tool('food_log', {'food': {'meal': 'lunch', 'amount': '0',
'unit': 'g', 'product_name': 'Invalid'}})).is_error)
self.assertTrue((await client.call_tool('food_update_entry', {'entry_id': str(self.b_entry.api_id),
'changes': {'meal': 'dinner'}})).is_error)
self.assertTrue((await client.call_tool('food_attach_image', {'entry_id': str(self.b_entry.api_id),
'image_base64': encoded, 'mime_type': 'image/png'})).is_error)
self.assertTrue((await client.call_tool('food_delete_entry', {'entry_id': str(self.b_entry.api_id)})).is_error)
self.assertTrue((await client.call_tool('food_log', {'food': {'meal': 'dinner', 'amount': '1',
'unit': 'g', 'product_id': str(self.b_product.api_id)}})).is_error)
await client.call_tool('food_delete_entry', {'entry_id': entry_id})
await client.call_tool('food_delete_entry', {'entry_id': combined['entry']['id']})
await client.call_tool('food_delete_entry', {'entry_id': partial['entry']['id']})
self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 0)
self.assertEqual((await client.call_tool('inventory_search', {'query': 'Private'})).structured_content['count'], 0)
args = {'product_id': str(self.a_product.api_id), 'quantity': 2, 'location': 'Pantry',
'idempotency_key': 'mcp-item-1'}
item = (await client.call_tool('inventory_add', args)).structured_content['item']
again = (await client.call_tool('inventory_add', args)).structured_content['item']
self.assertEqual(item['id'], again['id'])
self.assertEqual((await client.call_tool('inventory_search', {'query': 'Pasta'})).structured_content['count'], 1)
changed = (await client.call_tool('inventory_update', {'item_id': item['id'],
'changes': {'quantity': 3}})).structured_content
self.assertEqual(changed['item']['quantity'], 3)
self.assertTrue((await client.call_tool('inventory_update', {'item_id': str(self.b_item.api_id),
'changes': {'quantity': 3}})).is_error)
self.assertTrue((await client.call_tool('inventory_remove', {'item_id': str(self.b_item.api_id)})).is_error)
await client.call_tool('inventory_remove', {'item_id': item['id']})
asyncio.run(self._client(self.secret, check))
async def other(client):
self.assertEqual((await client.call_tool('food_get_today')).structured_content['meals']['lunch'][0]['name'], 'Private rice')
self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 1)
asyncio.run(self._client(self.b_secret, other))
def test_product_creation_and_grocery_batch_tools(self):
async def check(client):
lookup = (await client.call_tool('food_lookup_product', {
'query': 'Pasta', 'include_open_food_facts': False})).structured_content
self.assertEqual(lookup['matches'][0]['product_id'], str(self.a_product.api_id))
created = (await client.call_tool('food_create_product', {'product': {
'name': 'Oat milk', 'package_quantity': '1000', 'package_unit': 'ml'},
'idempotency_key': 'mcp-product-oat'})).structured_content
self.assertEqual(created['status'], 'created')
batch_args = {'items': [{'product_id': created['product_id'], 'quantity': 2, 'location': 'Fridge'}],
'idempotency_key': 'mcp-groceries-oat'}
batch = (await client.call_tool('inventory_import_groceries', batch_args)).structured_content
self.assertEqual(batch['items'][0]['status'], 'added')
again = (await client.call_tool('inventory_import_groceries', batch_args)).structured_content
self.assertEqual(again['items'][0]['inventory_item_id'], batch['items'][0]['inventory_item_id'])
self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 2)
stock = (await client.call_tool('inventory_get_stock', {'product_id': created['product_id']})).structured_content
self.assertEqual(stock['products'][0]['totals']['ml'], '2000.000')
preview = (await client.call_tool('inventory_preview_consumption', {
'product_id': created['product_id'], 'amount': '1250', 'unit': 'ml'})).structured_content
self.assertEqual([row['amount'] for row in preview['deductions']], ['1000.000', '250.000'])
used = (await client.call_tool('inventory_consume', {
'product_id': created['product_id'], 'amount': '1250', 'unit': 'ml',
'idempotency_key': 'mcp-use-oat'})).structured_content
self.assertEqual(used['amount'], '1250.000')
self.assertEqual((await client.call_tool('inventory_get_stock', {
'product_id': created['product_id']})).structured_content['products'][0]['totals']['ml'], '750.000')
undone = (await client.call_tool('inventory_undo_consumption', {
'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)
saved = await client.call_tool('recipe_cook_later_add', {'recipe_id': recipe_id})
self.assertFalse(saved.is_error, saved)
self.assertTrue(saved.structured_content['is_cook_later'])
self.assertFalse((await client.call_tool('recipe_cook_later_add',
{'recipe_id': recipe_id})).structured_content['created'])
self.assertEqual((await client.call_tool('recipe_cook_later_list', {})).structured_content['count'], 1)
self.assertTrue((await client.call_tool('recipe_get',
{'recipe_id': recipe_id})).structured_content['is_cook_later'])
self.assertTrue((await client.call_tool('recipe_cook_later_remove',
{'recipe_id': recipe_id})).structured_content['removed'])
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))