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 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']) 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_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_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_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, 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', 'state': 'mcp-oauth-test', 'code_challenge': challenge, 'code_challenge_method': 'S256', 'resource': self.mcp_url} response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost') self.assertEqual(response.status_code, 200) 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' 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'] async def check(client): self.assertFalse((await client.call_tool('food_get_today')).is_error) self.assertTrue((await client.call_tool('inventory_list')).is_error) asyncio.run(self._client(secret, check)) 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.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 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) 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))