latest changes

This commit is contained in:
Joren de Graaf
2026-10-22 10:32:41 +02:00
parent 5799b542c8
commit 5b986134be
63 changed files with 2412 additions and 77 deletions
+70
View File
@@ -196,6 +196,25 @@ class RecipeAnalysisInput(BaseModel):
substitutions: dict[str, str] = Field(default_factory=dict)
class GroceryItemInput(BaseModel):
name: str
quantity: Decimal = Field(gt=0)
unit: Literal['pieces', 'g', 'kg', 'ml', 'L', 'packs', 'portions', 'tsp', 'tbsp'] = 'pieces'
category: str = ''
product_id: str | None = None
notes: str = ''
class GroceryItemChanges(BaseModel):
name: str | None = None
quantity: Decimal | None = Field(default=None, gt=0)
unit: Literal['pieces', 'g', 'kg', 'ml', 'L', 'packs', 'portions', 'tsp', 'tbsp'] | None = None
category: str | None = None
product_id: str | None = None
notes: str | None = None
status: Literal['needed', 'purchased'] | None = None
class StressInput(BaseModel):
score: int = Field(ge=0, le=10)
recorded_at: str | None = None
@@ -262,6 +281,12 @@ 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, return_validation=False):
headers = {'Authorization': f'Bearer {token or _token()}'}
# Django enforces HTTPS in production. This hop stays on loopback; mark it as
# the trusted internal side of the HTTPS proxy so it is not redirected to a
# TLS endpoint that the development server does not provide.
api_url = urlsplit(API_BASE)
if api_url.scheme == 'http' and api_url.hostname in {'127.0.0.1', 'localhost', '::1'}:
headers['X-Forwarded-Proto'] = 'https'
if idempotency_key:
headers['Idempotency-Key'] = idempotency_key
try:
@@ -270,6 +295,9 @@ async def api_request(method: str, path: str, *, payload=None, params=None, file
json=payload, params=params, files=files, data=form)
except (httpx2.RequestError, TimeoutError):
raise ToolError('TaskNest is unavailable. Retry with the same idempotency key if this was a creation.') from None
if 300 <= response.status_code < 400:
logger.warning('TaskNest API unexpectedly redirected an MCP request: status=%s', response.status_code)
raise ToolError('TaskNest API redirected the request. Check the internal HTTPS proxy configuration.')
if response.status_code >= 400:
if return_validation and response.status_code == 400:
return response.json()
@@ -619,6 +647,48 @@ def create_server() -> MCPServer:
return await api_request('GET', 'recipes/cook-later/',
params={'search': search, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='List your grocery items by needed, purchased, or all status. Read only.')
async def grocery_list(status: Literal['needed', 'purchased', 'all'] = 'needed', limit: int = 30,
offset: int = 0) -> dict[str, Any]:
return await api_request('GET', 'groceries/', params={'status': status, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='Search your grocery list by text, category, product, and purchase status. Read only.')
async def grocery_search(query: str = '', category: str = '', product_id: str | None = None,
status: Literal['needed', 'purchased', 'all'] = 'all', limit: int = 30,
offset: int = 0) -> dict[str, Any]:
return await api_request('GET', 'groceries/', params={'query': query, 'category': category,
'product_id': product_id or '', 'status': status, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='Add one item to your grocery list. Does not change Kitchen Inventory. Reuse the idempotency key on retries.')
async def grocery_add(item: GroceryItemInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
data = await api_request('POST', 'groceries/', payload=item.model_dump(mode='json', exclude_none=True),
idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Edit an owned grocery item, including purchase status. Purchasing never adds inventory.')
async def grocery_edit(item_id: str, changes: GroceryItemChanges) -> dict[str, Any]:
return await api_request('PATCH', f'groceries/{item_id}/',
payload=changes.model_dump(mode='json', exclude_unset=True))
@server.tool(structured_output=True, description='Delete one owned grocery item by stable UUID. Requires clear user intent.')
async def grocery_delete(item_id: str) -> dict[str, Any]:
return await api_request('DELETE', f'groceries/{item_id}/')
@server.tool(structured_output=True, description='Preview or confirm missing ingredients for an owned recipe, scaled to servings and selected substitutions. Omit confirm to preview. Set confirm true to add; uncertain matches additionally require confirm_uncertain true after review. Does not change Kitchen Inventory.')
async def grocery_add_recipe(recipe_id: str, options: RecipeAnalysisInput | None = None,
confirm: bool = False, confirm_uncertain: bool = False,
idempotency_key: str | None = None) -> dict[str, Any]:
values = (options or RecipeAnalysisInput()).model_dump(mode='json', exclude_none=True)
if not confirm:
params = {key: value for key, value in values.items() if key != 'substitutions'}
params.update({f'sub_{key}': value for key, value in values.get('substitutions', {}).items()})
return await api_request('GET', f'groceries/recipe/{recipe_id}/', params=params)
key = _key(idempotency_key)
data = await api_request('POST', f'groceries/recipe/{recipe_id}/',
payload={**values, 'confirm_uncertain': confirm_uncertain}, idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Create an owned recipe. Add measured ingredients with recipe_ingredient_add. Reuse idempotency_key on retries.')
async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
+3 -1
View File
@@ -99,6 +99,7 @@ class McpHttpTests(LiveServerTestCase):
async with Client(streamable_http_client(self.mcp_url, http_client=http)) as client:
return await operation(client)
@override_settings(SECURE_SSL_REDIRECT=True)
def test_authentication_and_scope_boundaries(self):
async def check():
async with httpx2.AsyncClient(timeout=10) as http:
@@ -293,6 +294,7 @@ class McpHttpTests(LiveServerTestCase):
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',
@@ -304,7 +306,7 @@ class McpHttpTests(LiveServerTestCase):
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertEqual(len(names), 44)
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)