Add MCP nutrition ingredient import and classification

This commit is contained in:
Joren de Graaf
2026-11-02 11:40:12 +01:00
parent 2f84a9f359
commit 4497771b21
9 changed files with 500 additions and 1 deletions
+19
View File
@@ -547,6 +547,25 @@ def create_server() -> MCPServer:
result['attachment_error'] = str(exc)
return result
@server.tool(structured_output=True, description='Preview 1–100 structured PDF-extracted ingredient rows. Requires source programme, filename and PDF SHA-256 plus original labels, quantities, pages, preparation and reviewable culinary categories. Read only; returns blockers and a short-lived confirmation. Unknown nutrition stays unknown.')
async def nutrition_import_preview(payload: dict[str, Any]) -> dict[str, Any]:
return await api_request('POST', 'nutrition/preview/', payload=payload)
@server.tool(structured_output=True, description='Commit exactly the previously previewed structured PDF extraction after explicit user approval. Requires the preview confirmation and an idempotency key. Writes suggestions and canonical ingredients only; never changes inventory, shopping or Food Diary.')
async def nutrition_import_commit(payload: dict[str, Any], confirmation: str, idempotency_key: str) -> dict[str, Any]:
return await api_request('POST', 'nutrition/commit/', payload={'payload': payload, 'confirmation': confirmation}, idempotency_key=idempotency_key)
@server.tool(structured_output=True, description='Search your source suggested canonical ingredients by culinary category, subcategory, programme, form, verification and actual inventory name candidates. For vegetables suggested by Body Support set category=vegetable and programme=Body Support. Stock matches are candidates only; no nutrition equivalence is inferred.')
async def nutrition_ingredients_search(category: str = '', subcategory: str = '', programme: str = '', query: str = '', form: str = '', verified: bool | None = None, inventory_status: str = '', limit: int = 20, offset: int = 0) -> dict[str, Any]:
params = {'category': category, 'subcategory': subcategory, 'programme': programme, 'query': query, 'form': form, 'inventory_status': inventory_status, 'limit': limit, 'offset': offset}
if verified is not None:
params['verified'] = str(verified).lower()
return await api_request('GET', 'nutrition/ingredients/', params=params)
@server.tool(structured_output=True, description='Manually correct the category, subcategory or aliases of one owned canonical ingredient after review. Preserves the source PDF wording and marks the classification as verified.')
async def nutrition_ingredient_correct(ingredient_id: str, changes: dict[str, Any]) -> dict[str, Any]:
return await api_request('PATCH', f'nutrition/ingredients/{ingredient_id}/', payload=changes)
@server.tool(structured_output=True, description='List a bounded page of the authenticated user’s current kitchen inventory. Does not change data.')
async def inventory_list(limit: int = 30, offset: int = 0) -> dict[str, Any]:
data = await api_request('GET', 'kitchen/items/', params={'limit': min(max(limit, 1), 100), 'offset': max(offset, 0)})
+39
View File
@@ -99,6 +99,45 @@ class McpHttpTests(LiveServerTestCase):
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():