Enhancements

This commit is contained in:
Joren de Graaf
2026-10-11 20:46:55 +02:00
parent cb12c23732
commit 000ec834b0
26 changed files with 813 additions and 30 deletions
+53 -3
View File
@@ -117,6 +117,15 @@ class InventoryUpdate(BaseModel):
best_before: str | None = None
class HydrationSettingsUpdate(BaseModel):
daily_water_goal_ml: int | None = None
auto_count_food_drinks: bool | None = None
include_liquid_foods: bool | None = None
show_hydration_breakdown: bool | None = None
allow_manual_hydration_adjustments: bool | None = None
hydration_beverage_rules: dict[str, dict[str, Any]] | None = None
def _token() -> str:
access = get_access_token()
if access is None:
@@ -135,7 +144,7 @@ def _api_error(response: httpx2.Response) -> ToolError:
async def api_request(method: str, path: str, *, payload=None, params=None, files=None, form=None,
idempotency_key=None, token=None):
idempotency_key=None, token=None, return_validation=False):
headers = {'Authorization': f'Bearer {token or _token()}'}
if idempotency_key:
headers['Idempotency-Key'] = idempotency_key
@@ -146,6 +155,8 @@ async def api_request(method: str, path: str, *, payload=None, params=None, file
except (httpx2.RequestError, TimeoutError):
raise ToolError('TaskNest is unavailable. Retry with the same idempotency key if this was a creation.') from None
if response.status_code >= 400:
if return_validation and response.status_code == 400:
return response.json()
raise _api_error(response)
if response.headers.get('content-type', '').startswith('application/json'):
return response.json()
@@ -175,7 +186,8 @@ def _entry(entry):
def _inventory(item):
return {key: item.get(key) for key in ('id', 'product_id', 'product_name', 'brand', 'barcode',
'quantity', 'location', 'category', 'opened', 'best_before', 'notes', 'remaining_amount')}
'quantity', 'location', 'category', 'opened', 'best_before', 'notes',
'remaining_amount', 'original_amount', 'unit', 'status', 'archived_at')}
def _key(value):
@@ -376,7 +388,10 @@ def create_server() -> MCPServer:
@server.tool(structured_output=True, description='Update only the supplied fields of one inventory item belonging to the authenticated user. Changes existing data.')
async def inventory_update(item_id: str, changes: InventoryUpdate) -> dict[str, Any]:
item = await api_request('PATCH', f'kitchen/items/{item_id}/', payload=changes.model_dump(mode='json', exclude_unset=True))
item = await api_request('PATCH', f'kitchen/items/{item_id}/',
payload=changes.model_dump(mode='json', exclude_unset=True), return_validation=True)
if 'error' in item:
return {'success': False, 'error': item['error']}
return {'success': True, 'item': _inventory(item)}
@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.')
@@ -410,6 +425,41 @@ def create_server() -> MCPServer:
async def inventory_undo_consumption(transaction_id: str) -> dict[str, Any]:
return await api_request('POST', f'kitchen/consumption/{transaction_id}/undo/', payload={})
@server.tool(structured_output=True, description='Read combined daily hydration, separate manual and Food Diary drink contributions, the daily goal, and remaining amount. Optional date is YYYY-MM-DD in the user’s time zone.')
async def hydration_get_daily(date: str | None = None) -> dict[str, Any]:
return await api_request('GET', 'hydration/daily/', params={'date': date} if date else None)
@server.tool(structured_output=True, description='Add a standalone manual fluid entry. Food Diary drinks count automatically and need no second call. Reuse the same idempotency key on retries.')
async def hydration_log(amount_ml: Decimal, beverage_type: str = 'water',
recorded_at: str | None = None, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
payload = {'amount_ml': str(amount_ml), 'beverage_type': beverage_type}
if recorded_at is not None:
payload['recorded_at'] = recorded_at
data = await api_request('POST', 'hydration/manual/', payload=payload, idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Correct an owned standalone manual hydration entry by ID. Does not edit Food Diary contributions.')
async def hydration_update(entry_id: str, amount_ml: Decimal | None = None,
beverage_type: str | None = None, recorded_at: str | None = None) -> dict[str, Any]:
changes = {'amount_ml': str(amount_ml) if amount_ml is not None else None,
'beverage_type': beverage_type, 'recorded_at': recorded_at}
return await api_request('PATCH', f'hydration/manual/{entry_id}/',
payload={k: v for k, v in changes.items() if v is not None})
@server.tool(structured_output=True, description='Delete an owned standalone manual hydration entry. Does not affect Food Diary entries.')
async def hydration_delete(entry_id: str) -> dict[str, Any]:
return await api_request('DELETE', f'hydration/manual/{entry_id}/')
@server.tool(structured_output=True, description='Read hydration goal and automatic drink counting settings for the authenticated user.')
async def hydration_settings_get() -> dict[str, Any]:
return await api_request('GET', 'hydration/settings/')
@server.tool(structured_output=True, description='Update hydration goal, automatic Food Diary drink counting, liquid-food inclusion, widget breakdown, manual adjustment permission, or beverage-specific rules.')
async def hydration_settings_update(changes: HydrationSettingsUpdate) -> dict[str, Any]:
return await api_request('PATCH', 'hydration/settings/',
payload=changes.model_dump(mode='json', exclude_unset=True))
return server
+55 -1
View File
@@ -118,6 +118,60 @@ class McpHttpTests(LiveServerTestCase):
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,
@@ -157,7 +211,7 @@ class McpHttpTests(LiveServerTestCase):
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertEqual(len(names), 20)
self.assertEqual(len(names), 26)
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